diff --git a/seaweed-block/.github/model-code-trace.md b/seaweed-block/.github/model-code-trace.md new file mode 100644 index 0000000000..2c2cb0db81 --- /dev/null +++ b/seaweed-block/.github/model-code-trace.md @@ -0,0 +1,23 @@ +# Model citations for mapped files + +The spec-trace workflow reads `model-code-trace.tsv` and the validator from +the target branch. A PR cannot replace its own mapping or checker. + +Each non-comment line has two tab-separated columns: an exact repository +path and `Module.Action`. Repeat a path to list alternative actions that +cover it. Paths are case-sensitive; directories and glob patterns are not +expanded. Missing, empty or malformed mappings refuse the check. + +For every changed mapped path, including deletions, the PR's `Model:` line +must contain a listed action or `NONE (pure function of Module)` for that +module. Separate multiple citations with semicolons, for example: + +```text +Model: Snapshot.Begin; Lease.Renew; NONE (pure function of Codec) +``` + +Unmapped paths keep the existing spec-trace policy. The pure-function +declaration is a review claim; CI checks its module, not its truth. + +This branch is a trial. Populate the canonical mapping and run the complete +shell self-test on Linux before enabling it by merging the workflow. diff --git a/seaweed-block/.github/model-code-trace.tsv b/seaweed-block/.github/model-code-trace.tsv new file mode 100644 index 0000000000..57cee6e920 --- /dev/null +++ b/seaweed-block/.github/model-code-trace.tsv @@ -0,0 +1,2 @@ +# Exact repository-relative pathModule.Action; repeat a path for alternatives. +# DRAFT: canonical model-to-code mapping must be populated before this gate lands. diff --git a/seaweed-block/.github/pull_request_template.md b/seaweed-block/.github/pull_request_template.md index 25ad685875..6ea6d32104 100644 --- a/seaweed-block/.github/pull_request_template.md +++ b/seaweed-block/.github/pull_request_template.md @@ -1,6 +1,6 @@ Feature: Machine/INV: / -Model: +Model: Red-first: Simplest: @@ -23,4 +23,8 @@ DOCS may still change contract text (docs/design/invariants.md): the reviewer is NONE needs a reason of at least 10 characters. Simplest is required when the PR changes non-test Go under core/ or cmd/. + +Mapped files in .github/model-code-trace.tsv require a listed Module.Action +or NONE (pure function of Module). Separate citations for multiple modules +with semicolons. Unmapped files retain the existing Model trace policy. --> diff --git a/seaweed-block/.github/scripts/model-trace-check-test.py b/seaweed-block/.github/scripts/model-trace-check-test.py new file mode 100644 index 0000000000..3e89b30770 --- /dev/null +++ b/seaweed-block/.github/scripts/model-trace-check-test.py @@ -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() diff --git a/seaweed-block/.github/scripts/model-trace-check.py b/seaweed-block/.github/scripts/model-trace-check.py new file mode 100644 index 0000000000..cec3ecc1a4 --- /dev/null +++ b/seaweed-block/.github/scripts/model-trace-check.py @@ -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 PATHModule.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()) diff --git a/seaweed-block/.github/scripts/spec-trace-check-test.sh b/seaweed-block/.github/scripts/spec-trace-check-test.sh index 0bfc8cac99..c5de3487b2 100644 --- a/seaweed-block/.github/scripts/spec-trace-check-test.sh +++ b/seaweed-block/.github/scripts/spec-trace-check-test.sh @@ -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 " 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 diff --git a/seaweed-block/.github/scripts/spec-trace-check.sh b/seaweed-block/.github/scripts/spec-trace-check.sh index 0ff8bf9756..89fe207e5d 100644 --- a/seaweed-block/.github/scripts/spec-trace-check.sh +++ b/seaweed-block/.github/scripts/spec-trace-check.sh @@ -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 diff --git a/seaweed-block/.github/workflows/spec-trace.yml b/seaweed-block/.github/workflows/spec-trace.yml index 7bd9bdaa40..e7537aa621 100644 --- a/seaweed-block/.github/workflows/spec-trace.yml +++ b/seaweed-block/.github/workflows/spec-trace.yml @@ -47,6 +47,7 @@ jobs: run: | set -euo pipefail bash .github/scripts/spec-trace-check-test.sh + python3 -B .github/scripts/model-trace-check-test.py git fetch --no-tags origin "+refs/pull/${PR}/head:refs/remotes/pr/head" printf '%s' "$BODY" >body.txt bash .github/scripts/post-merge-review-changed.sh "$BASE" "$HEAD" >changed.bin @@ -60,7 +61,8 @@ jobs: git show "$HEAD:$p" >"blobs/new/$p" 2>/dev/null || rm -f "blobs/new/$p" done mkdir -p blobs - bash .github/scripts/spec-trace-check.sh body.txt blobs