ci: require mapped model actions in spec traces

This commit is contained in:
pingqiu committed 2026-11-25 15:48:26 -08:00
1 parent 6ed99b411b
commit aedd3002bd
8 files changed
+204 -32

No files matched your search

+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env python3
import importlib.util
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
SCRIPT = Path(__file__).with_name("model-trace-check.py")
spec = importlib.util.spec_from_file_location("model_trace", SCRIPT)
checker = importlib.util.module_from_spec(spec)
spec.loader.exec_module(checker)
class ModelTraceTests(unittest.TestCase):
mapping = {"core/a.go": {"Kernel.Begin", "Kernel.Commit"}, "core/b.go": {"Lease.Renew"}}
def test_each_mapped_file_needs_its_own_citation(self):
problems = checker.check("Kernel.Begin", ["core/a.go", "core/b.go"], self.mapping)
self.assertEqual(len(problems), 1)
self.assertIn("core/b.go", problems[0])
self.assertEqual(checker.check("Kernel.Begin; Lease.Renew", list(self.mapping), self.mapping), [])
def test_mapped_file_refuses_free_text_wrong_actions_and_lookalikes(self):
for model in ("exhausted", "Kernel.Unknown", "Other.Begin", "Kernel.BeginExtra",
"docs/Kernel.Begin", "example: Kernel.Begin", "NONE: no state changes",
"NONE (pure function of Other)", "NONE (pure function of Kernel) extra"):
with self.subTest(model=model):
self.assertEqual(len(checker.check(model, ["core/a.go"], self.mapping)), 1)
def test_pure_function_exception_is_module_specific(self):
self.assertEqual(checker.check("NONE (pure function of Kernel)", ["core/a.go"], self.mapping), [])
self.assertEqual(len(checker.check("NONE (pure function of Kernel)", ["core/b.go"], self.mapping)), 1)
def test_unmapped_files_keep_existing_policy(self):
self.assertEqual(checker.check("existing prose", ["docs/a.md", "core/a.go.bak"], self.mapping), [])
def test_cli_checks_nul_paths_and_model_citations(self):
with tempfile.TemporaryDirectory() as tmp:
mapping = Path(tmp) / "map.tsv"
mapping.write_text("# exact paths\ncore/a.go\tKernel.Begin\n", encoding="utf-8")
def run(model, paths):
return subprocess.run([sys.executable, str(SCRIPT), str(mapping), model],
input=paths, capture_output=True).returncode
self.assertEqual(run("Kernel.Begin", b"core/a.go\0"), 0)
self.assertEqual(run("unstructured prose", b"core/a.go\0"), 1)
self.assertEqual(run("Kernel.Begin", b"core/a.go"), 2)
self.assertEqual(run("Kernel.Begin", b"\0"), 2)
def test_mapping_refuses_missing_empty_and_malformed_data(self):
with tempfile.TemporaryDirectory() as tmp:
mapping = Path(tmp) / "map.tsv"
with self.assertRaises(OSError):
checker.read_mapping(mapping)
for content in ("# not populated\n", "core/a.go Kernel.Begin\n",
"../core/a.go\tKernel.Begin\n", "core//a.go\tKernel.Begin\n",
"core/a.go\tKernel\n", "core/a.go\tKernel.Begin extra\n"):
with self.subTest(content=content):
mapping.write_text(content, encoding="utf-8")
with self.assertRaises(ValueError):
checker.read_mapping(mapping)
if __name__ == "__main__":
unittest.main()
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Check Model citations against a base-owned, exact-path TSV mapping."""
import re
import sys
from pathlib import Path, PurePosixPath
IDENT = r"[A-Za-z_][A-Za-z0-9_]*"
ACTION = re.compile(rf"{IDENT}\.{IDENT}")
PURE = re.compile(rf"NONE \(pure function of ({IDENT})\)")
def read_mapping(path):
mapping = {}
for number, line in enumerate(Path(path).read_text(encoding="utf-8").splitlines(), 1):
if not line.strip() or line.startswith("#"):
continue
columns = line.split("\t")
if len(columns) != 2:
raise ValueError(f"mapping line {number}: expected PATH<TAB>Module.Action")
file, action = columns
parts = PurePosixPath(file).parts
if (not file or file.startswith("/") or "\\" in file or ":" in file
or any(part in (".", "..") for part in file.split("/"))
or str(PurePosixPath(file)) != file or not parts):
raise ValueError(f"mapping line {number}: expected a repository-relative exact path")
if not ACTION.fullmatch(action):
raise ValueError(f"mapping line {number}: invalid Module.Action")
mapping.setdefault(file, set()).add(action)
if not mapping:
raise ValueError("model mapping is empty; populate it before enabling this gate")
return mapping
def check(model, paths, mapping):
# A list permits one citation for each mapped file in a multi-module PR.
# Full matches prevent prose, quoted examples, or a prefixed NONE excuse
# from accidentally satisfying a mapped-file obligation.
citations = {part.strip() for part in model.split(";")}
actions = {part for part in citations if ACTION.fullmatch(part)}
pure = {match.group(1) for part in citations if (match := PURE.fullmatch(part))}
problems = []
for file in sorted(set(paths)):
expected = mapping.get(file)
if expected and not (actions & expected or any(a.split(".")[0] in pure for a in expected)):
names = "; ".join(sorted(expected))
problems.append(f"{file}: Model must cite {names} or NONE (pure function of its module)")
return problems
def main():
if len(sys.argv) != 3:
print("usage: model-trace-check.py MAPPING MODEL < nul-separated-paths", file=sys.stderr)
return 2
try:
mapping = read_mapping(sys.argv[1])
raw = sys.stdin.buffer.read()
if raw and not raw.endswith(b"\0"):
raise ValueError("unterminated changed path")
paths = [p.decode("utf-8") for p in raw.split(b"\0")[:-1]]
if any(not p for p in paths):
raise ValueError("empty changed path")
problems = check(sys.argv[2], paths, mapping)
except (OSError, UnicodeError, ValueError) as error:
print(f"spec-trace: {error}", file=sys.stderr)
return 2
for problem in problems:
print(f"spec-trace: {problem}")
return int(bool(problems))
if __name__ == "__main__":
sys.exit(main())
+22 -29
View File
@@ -124,35 +124,28 @@ expect_kind 0 "CI: workflow" CI - - M .github/workflows/w.yml
expect_kind 1 "CI: scripts/ is shipped" CI - - A scripts/install.sh
expect_kind 1 "DOCS next to another kind" "DOCS FIX INV-X-001" - - M docs/a.md
[[ $fail == 0 ]] && echo "spec-trace self-test: ok"
exit $fail
import (
"C"
)
' "${P}// #include <b.h>" DOCS - - M core/x/s.go
expect_kind 1 "DOCS: a model under docs/spec" DOCS - - M docs/spec/X.tla
expect_kind 1 "DOCS: a non-docs, non-Go file" DOCS - - M deploy/x.env
expect_kind 0 "TEST: tests and testdata" TEST - - M core/x/s_test.go A core/x/testdata/in.bin
expect_kind 1 "TEST: production Go" TEST - - M core/x/s.go
expect_kind 0 "CI: workflow" CI - - M .github/workflows/w.yml
expect_kind 1 "CI: scripts/ is shipped" CI - - A scripts/install.sh
expect_kind 1 "DOCS next to another kind" "DOCS FIX INV-X-001" - - M docs/a.md
[[ $fail == 0 ]] && echo "spec-trace self-test: ok"
exit $fail
import (
"C"
)
' M core/x/s.go
expect_kind 1 "DOCS: a model under docs/spec" DOCS - - M docs/spec/X.tla
expect_kind 1 "DOCS: a non-docs, non-Go file" DOCS - - M deploy/x.env
expect_kind 0 "TEST: tests and testdata" TEST - - M core/x/s_test.go A core/x/testdata/in.bin
expect_kind 1 "TEST: production Go" TEST - - M core/x/s.go
expect_kind 0 "CI: workflow" CI - - M .github/workflows/w.yml
expect_kind 1 "CI: scripts/ is shipped" CI - - A scripts/install.sh
expect_kind 1 "DOCS next to another kind" "DOCS FIX INV-X-001" - - M docs/a.md
# The workflow supplies its base-owned map as the third argument.
expect_map() {
local want=$1 name=$2 model=$3 got=0
shift 3
printf '%s\n%s\n' "${ok/Model: docs\/spec\/MaintenanceOwner.tla, exhausted/Model: $model}" "$simplest" >"$tmp/body"
if (($#)); then printf '%s\0' "$@"; fi |
bash "$check" "$tmp/body" "" "$tmp/map.tsv" >/dev/null 2>&1 || got=$?
if [[ $got != "$want" ]]; then
echo "FAIL $name: exit $got, want $want"
fail=1
fi
}
printf 'core/x/s.go\tKernel.Begin\ncore/y/s.go\tLease.Renew\n' >"$tmp/map.tsv"
expect_map 0 "mapped action" "Kernel.Begin" M core/x/s.go
expect_map 0 "mapped pure function" "NONE (pure function of Kernel)" M core/x/s.go
expect_map 0 "all mapped modules cited" "Kernel.Begin; Lease.Renew" M core/x/s.go M core/y/s.go
expect_map 1 "mapped file rejects old prose" "docs/spec/Kernel.tla, exhausted" M core/x/s.go
expect_map 1 "deleted mapped file still needs model" "NONE: deletion has no new code" D core/x/s.go
expect_map 1 "one citation cannot cover another module" "Kernel.Begin" M core/x/s.go M core/y/s.go
expect_map 0 "unmapped file keeps old policy" "docs/spec/Kernel.tla, exhausted" M core/z/s.go
printf '# no canonical rows yet\n' >"$tmp/map.tsv"
expect_map 2 "empty map is not silently disabled" "Kernel.Begin" M core/x/s.go
[[ $fail == 0 ]] && echo "spec-trace self-test: ok"
exit $fail
+12 -1
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
# Usage: spec-trace-check.sh BODY_FILE [BLOBS] < changes
# Usage: spec-trace-check.sh BODY_FILE [BLOBS] [MODEL_MAP] < changes
#
# Checks the spec trace in a PR description. changes are NUL-separated
# STATUS, PATH pairs (post-merge-review-changed.sh).
@@ -25,6 +25,7 @@ set -euo pipefail
body_file=${1:?usage: spec-trace-check.sh BODY_FILE [BLOBS] < changes}
blobs=${2-}
model_map=${3-}
here=$(cd "$(dirname "$0")" && pwd)
[[ -f $body_file ]] || { echo "spec-trace: body file $body_file missing" >&2; exit 2; }
body=$(tr -d '\r' <"$body_file")
@@ -99,6 +100,16 @@ while IFS= read -r -d '' status; do
done
# A record cut off before its NUL is malformed, not skipped.
[[ -z ${status-} ]] || { echo "spec-trace: malformed change list: unterminated record" >&2; exit 2; }
if [[ -n $model_map ]]; then
model_status=0
{ if ((${#paths[@]})); then printf '%s\0' "${paths[@]}"; fi; } |
"${PYTHON:-python3}" -B "$here/model-trace-check.py" "$model_map" "$(value Model:)" || model_status=$?
case $model_status in
0) ;;
1) bad=1 ;;
*) exit "$model_status" ;;
esac
fi
if ((core)); then
s=$(value Simplest:)
if ((${#s} < 20)) || [[ $s == '<'* ]]; then