Skip to content

Commit 3efdd24

Browse files
committed
P-037 B1: the proof-boundary checker learns the guarded shadow
--check (every run): - F9 refined: `.fin().collapse()` reads a finalized summary and is allowed; a raw `.collapse()` or any direct `lower(` in a kernel-importing file still fails (G5). F8 already covers own-guarded (G4). - G3 reuse guard: own-guarded may not define the kernel's types or algebra. - G11: own-guarded code may not read dispatch; A14 is a condition only. - N1 mirror of the dag.rs guard over every rust/ Cargo.toml: only own-guarded names p037-kernel, only own-shadow names own-guarded (G1/G2). --b1-gate (the B1 evidence gate, needs history back to 0e2c01a): the N2 zero-cut path set (G12) and the §F hard caps, counted as added lines with no blanks and no comment lines. Today: own-guarded 894/900, total 1390/2500 before this commit. --mutants now also kills G6-G10 and G11 on a temporary copy of rust/: each is a real code mutation that its named acceptance test must turn red, and the kernel's apply-without-fin mutant is run against own-guarded's K7 witness (G8). All killed locally. --selftest demonstrates every new static falsifier and the gate's rules. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KmiyfrkaG9sJruTcshM2oq
1 parent 8504ad4 commit 3efdd24

2 files changed

Lines changed: 215 additions & 9 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,9 @@ jobs:
108108
# P-037 B0 (docs/notes/p037-phase-b-proof-boundary.md): F5, the
109109
# finalize-before-apply controls must go red when apply/lower stop
110110
# finalizing (temp copy of the crate), and the #368 witness must hold.
111-
- name: proof-boundary kernel mutants (B0 F5 / F7)
111+
# P-037 B1 (docs/notes/p037-phase-b1-shadow.md §C): the same run kills
112+
# the own-guarded mutants G6-G11 on a temporary copy of rust/.
113+
- name: proof-boundary mutants (B0 F5 / F7, B1 G6-G11)
112114
run: python3 ../../scripts/p037_proof_boundary.py --mutants
113115
- name: install Kani (pinned) and its toolchain bundle
114116
run: |

‎scripts/p037_proof_boundary.py‎

Lines changed: 212 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@
2020
--check audit the tree; RESULT: PASS | FAIL (exit 0 | 1)
2121
--selftest the cheap falsifiers F1-F4 and F6-F10 as in-memory mutants
2222
--mutants F5 (and the #368 witness) as real `cargo test` runs on a
23-
temporary copy of the kernel crate; needs cargo
23+
temporary copy of the kernel crate, then B1's G6-G11 on a
24+
copy of rust/ (docs/notes/p037-phase-b1-shadow.md); needs cargo
25+
--b1-gate B1's N2 zero-cut path set and §F hard caps against B1_BASE
2426
2527
Stdlib only. A new generic verification framework is out of budget by rule.
2628
"""
@@ -29,6 +31,7 @@
2931
import argparse
3032
import copy
3133
import json
34+
import os
3235
import re
3336
import shutil
3437
import subprocess
@@ -90,7 +93,32 @@
9093
SKIP_DIRS = {"target", "bin", "obj", "node_modules", "__pycache__", ".git"}
9194
SCHEDULE_API = re.compile(r"\b(solve_with|elect_with|lfp_chaotic)\s*\(")
9295
KERNEL_IMPORT = re.compile(r"\bp037_kernel\b")
93-
DIRECT_LOWER = re.compile(r"\.collapse\s*\(\s*\)|\blower\s*\(")
96+
# `.fin().collapse()` reads a FINALIZED summary (B1's summary report); a raw
97+
# `.collapse()` or any direct `lower(` bypasses `apply` (F9 / G5).
98+
DIRECT_LOWER = re.compile(r"(?<!\.fin\(\))\.collapse\s*\(\s*\)|\blower\s*\(")
99+
100+
# B1 (docs/notes/p037-phase-b1-shadow.md): the guarded shadow read.
101+
B1_BASE = "0e2c01a"
102+
GUARDED_SRC = "rust/crates/own-guarded/src/"
103+
REUSE = re.compile(
104+
r"\bfn\s+(join|leq|fin|collapse|swap|read|contribute|import|apply|lower|shape_of)\b"
105+
r"|\b(enum|struct|type|trait)\s+(Transfer|Cells|Election|GuardBinding|Shape|Transform|"
106+
r"Mask|Selection|Lowered|Lattice)\b")
107+
DISPATCH = re.compile(r"\b(virtual|override|interface)\b|(?<!static_)dispatch(?!_conditional)")
108+
ZERO_CUT = ("ownlang/", "spec/", "scripts/own-check.sh", *(
109+
f"rust/crates/{c}/src/" for c in ("own-bridge", "own-cli", "own-ir", "own-lowered",
110+
"own-analysis", "own-cfg", "own-syntax",
111+
"own-diagnostics")))
112+
# §F hard caps, counted lines (no blanks, no comment lines) added since B1_BASE.
113+
CAPS: list[tuple[str, tuple[str, ...], int]] = [
114+
("own-guarded non-test Rust", (GUARDED_SRC,), 900),
115+
("own-shadow B1 additions", ("rust/crates/own-shadow/",), 200),
116+
("extractor A14 side report (C#)", ("frontend/roslyn/OwnSharp.Extractor/",), 150),
117+
("everything B1 hand-writes", ("rust/crates/own-guarded/", "rust/crates/own-shadow/",
118+
"rust/crates/own-diagnostics/tests/dag.rs",
119+
"frontend/roslyn/OwnSharp.Extractor/", "scripts/p037_",
120+
"tests/test_p037_"), 2500),
121+
]
94122

95123

96124
@dataclass
@@ -103,6 +131,7 @@ class Tree:
103131
ci_runs_harness: dict[str, bool] # the loop actually calls cargo kani
104132
lib: str
105133
production: dict[str, str] # repo-relative path -> text
134+
manifests: dict[str, str] = field(default_factory=dict) # rust/**/Cargo.toml
106135
root: Path = ROOT
107136

108137

@@ -196,6 +225,9 @@ def load_tree() -> Tree:
196225
ci_runs_harness=runs,
197226
lib=LIB.read_text(encoding="utf-8"),
198227
production=production_texts(),
228+
manifests={f.relative_to(ROOT).as_posix(): f.read_text(encoding="utf-8")
229+
for f in (ROOT / "rust").rglob("Cargo.toml")
230+
if not SKIP_DIRS & set(f.relative_to(ROOT).parts)},
199231
)
200232

201233

@@ -398,9 +430,78 @@ def audit(tree: Tree) -> Report:
398430
r.err(f"F8 {rel}: production calls the schedule-taking {mm.group(1)} (#368)")
399431
if DIRECT_LOWER.search(text):
400432
r.err(f"F9 {rel}: imports the kernel and lowers/collapses cells outside `apply`")
433+
audit_b1(tree, r)
401434
return r
402435

403436

437+
def audit_b1(tree: Tree, r: Report) -> None:
438+
"""B1's static guards: reuse (G3), dispatch (G11), kernel edges (G1/G2)."""
439+
guarded = {k: v for k, v in tree.production.items() if k.startswith(GUARDED_SRC)}
440+
if not guarded:
441+
r.err(f"B1 no sources under {GUARDED_SRC}")
442+
for rel, text in sorted(guarded.items()):
443+
code = re.sub(r"//[^\n]*", "", text)
444+
for mm in REUSE.finditer(code):
445+
r.err(f"G3 {rel}: defines kernel algebra {mm.group(0)!r} instead of reusing it")
446+
if DISPATCH.search(code):
447+
r.err(f"G11 {rel}: reads dispatch; A14 is a condition, never acted on")
448+
for rel, text in sorted(tree.manifests.items()):
449+
crate = rel.split("/")[-2]
450+
for dep, owner in (("p037-kernel", "own-guarded"), ("own-guarded", "own-shadow")):
451+
if crate != owner and re.search(rf"^\s*{dep}\s*=", text, re.M):
452+
r.err(f"N1 {rel}: names {dep}; only {owner} may")
453+
454+
455+
def _git(*args: str) -> str:
456+
return subprocess.run(["git", *args], cwd=ROOT, capture_output=True, text=True,
457+
check=True).stdout
458+
459+
460+
def zero_cut(changed: list[str]) -> list[str]:
461+
"""N2 / G12: B1 touches no production source path."""
462+
return [f"N2 {p}: B1 must not change it" for p in changed if p.startswith(ZERO_CUT)]
463+
464+
465+
def counted(lines: list[str], rel: str) -> int:
466+
mark = "#" if rel.endswith(".py") else "//"
467+
return sum(1 for ln in lines if ln.strip() and not ln.strip().startswith(mark))
468+
469+
470+
def added(rel: str) -> list[str]:
471+
"""The lines `rel` gained since B1_BASE (all of it when it is new)."""
472+
diff = _git("diff", "-U0", B1_BASE, "--", rel)
473+
if diff:
474+
return [ln[1:] for ln in diff.splitlines() if ln.startswith("+") and
475+
not ln.startswith("+++")]
476+
tracked = _git("ls-files", "--", rel).strip()
477+
known = subprocess.run(["git", "cat-file", "-e", f"{B1_BASE}:{rel}"], cwd=ROOT,
478+
capture_output=True, check=False).returncode == 0
479+
return [] if tracked and known else (ROOT / rel).read_text(encoding="utf-8").splitlines()
480+
481+
482+
def caps(sizes: dict[str, int]) -> list[str]:
483+
"""§F: every cap holds; reaching one unfinished is a STOP."""
484+
out = []
485+
for label, prefixes, cap in CAPS:
486+
n = sum(v for k, v in sizes.items() if k.startswith(prefixes))
487+
print(f" {label}: {n} / {cap}")
488+
if n > cap:
489+
out.append(f"CAP {label}: {n} > {cap}")
490+
return out
491+
492+
493+
def b1_gate() -> int:
494+
changed = sorted(set(_git("diff", "--name-only", B1_BASE).split()) |
495+
set(_git("ls-files", "--others", "--exclude-standard").split()))
496+
code = [p for p in changed if p.endswith((".rs", ".py", ".cs")) and
497+
any(p.startswith(pre) for _, pres, _ in CAPS for pre in pres)]
498+
problems = zero_cut(changed) + caps({p: counted(added(p), p) for p in code})
499+
for e in problems:
500+
print(f" ERROR {e}")
501+
print("RESULT: FAIL — B1 BLOCKED" if problems else "RESULT: PASS — B1 GATE (N2 paths, §F caps)")
502+
return 1 if problems else 0
503+
504+
404505
# ---------------------------------------------------------------------------
405506
# modes
406507
# ---------------------------------------------------------------------------
@@ -501,6 +602,50 @@ def expect(label: str, tree: Tree, needle: str) -> None:
501602
"rust/crates/own-bridge/src/guarded.rs",
502603
"use p037_kernel::{lower, Cells};\nfn f(c: Cells) { lower(c.collapse()); }")),
503604
"F9")
605+
ok = not audit(_mutant(base, lambda t: t.production.__setitem__(
606+
"rust/crates/own-guarded/src/x.rs",
607+
"use p037_kernel::Cells;\nfn f(c: Cells) -> T { c.fin().collapse() }"))).errors
608+
print(f"{'ok ' if ok else 'MISS'} F9' a finalized summary read stays green")
609+
fails += not ok
610+
expect("G5 own-guarded collapses a raw cell",
611+
_mutant(base, lambda t: t.production.__setitem__(
612+
"rust/crates/own-guarded/src/x.rs",
613+
"use p037_kernel::Cells;\nfn f(c: Cells) -> T { c.collapse() }")), "F9")
614+
expect("G4 own-guarded takes a schedule",
615+
_mutant(base, lambda t: t.production.__setitem__(
616+
"rust/crates/own-guarded/src/x.rs",
617+
"use p037_kernel::elect_with;\nfn f() { elect_with(&s, &[1, 0]); }")), "F8")
618+
expect("G3 own-guarded defines its own join",
619+
_mutant(base, lambda t: t.production.__setitem__(
620+
"rust/crates/own-guarded/src/x.rs",
621+
"use p037_kernel::Cells;\nfn join(a: T, b: T) -> T { a }")), "G3")
622+
expect("G11 own-guarded acts on dispatch",
623+
_mutant(base, lambda t: t.production.__setitem__(
624+
"rust/crates/own-guarded/src/x.rs", "fn f(c: &Call) { if c.dispatch == 1 {} }")),
625+
"G11")
626+
expect("G1 own-bridge names own-guarded",
627+
_mutant(base, lambda t: t.manifests.__setitem__(
628+
"rust/crates/own-bridge/Cargo.toml",
629+
t.manifests["rust/crates/own-bridge/Cargo.toml"] +
630+
'\nown-guarded = { path = "../own-guarded" }\n')), "N1")
631+
expect("G2 a second crate names p037-kernel",
632+
_mutant(base, lambda t: t.manifests.__setitem__(
633+
"rust/crates/own-cli/Cargo.toml",
634+
t.manifests["rust/crates/own-cli/Cargo.toml"] +
635+
'\n[dev-dependencies]\np037-kernel = { path = "x" }\n')), "N1")
636+
for label, hit in (
637+
("G12 an own-bridge source change sneaks in",
638+
zero_cut(["rust/crates/own-bridge/src/lower.rs"])),
639+
("G12' an own-cli source change sneaks in",
640+
zero_cut(["rust/crates/own-cli/src/main.rs"])),
641+
("§F a cap reached unfinished is a STOP",
642+
caps({"rust/crates/own-guarded/src/lib.rs": 901}))):
643+
print(f"{'ok ' if hit else 'MISS'} {label}")
644+
fails += not hit
645+
ok = not zero_cut(["rust/crates/own-guarded/src/lib.rs", "rust/Cargo.lock",
646+
"rust/crates/own-diagnostics/tests/dag.rs"])
647+
print(f"{'ok ' if ok else 'MISS'} G12' B1's own paths stay green")
648+
fails += not ok
504649
well_formed_user = next(n for n, h in sorted(base.source.items())
505650
if re.search(r"\bany_system\s*\(", h))
506651
expect(f"F10 {well_formed_user} stops declaring WF",
@@ -534,6 +679,65 @@ def expect(label: str, tree: Tree, needle: str) -> None:
534679
]
535680

536681

682+
# B1: each falsifier of docs/notes/p037-phase-b1-shadow.md §C that is a code
683+
# mutation, as (label, repo-relative file, old, new, own-guarded test filter).
684+
# Run on a temporary copy of rust/ + the kernel; the named test must PANIC.
685+
GUARDED_MUTANTS = [
686+
("G6 the A15 join places what it cannot", "rust/crates/own-guarded/src/facts.rs",
687+
"w.check_calls()?;", "let _ = w.check_calls();", "a15_"),
688+
("G7 an unresolvable forward is read as nothing", "rust/crates/own-guarded/src/facts.rs",
689+
"fwds.push((n, callee_coord(fns, c, slot)));",
690+
"fwds.extend(callee_coord(fns, c, slot).ok().map(|t| (n, Ok(t))));", "record_absence"),
691+
("G8 the K7 witness: apply skips fin", "formal/p037-kernel/src/lib.rs",
692+
"let c = solved.fin();", "let c = solved;", "k7_"),
693+
("G9 a raw cell crosses an SCC", "rust/crates/own-guarded/src/solve.rs",
694+
"callee.fin()", "callee", "a13_"),
695+
("G10 the sidecar is no longer read", "rust/crates/own-guarded/src/facts.rs",
696+
'f.extra.get("guarded_facts")', "None::<&Value>", "n4_"),
697+
("G11 the report drops static_dispatch_conditional", "rust/crates/own-guarded/src/lib.rs",
698+
'"static_dispatch_conditional": true,', "", "a14_"),
699+
]
700+
701+
702+
def _killed(run: subprocess.CompletedProcess[str], test: str) -> tuple[bool, list[str]]:
703+
"""Killed = a test matching `test` PANICKED; a compile error is not a kill."""
704+
out = run.stdout + run.stderr
705+
died = sorted(set(re.findall(r"^---- (\S+) stdout ----$", out, re.M)))
706+
red = run.returncode != 0 and "test result: FAILED" in out and any(
707+
d.split("::")[-1].startswith(test) for d in died)
708+
return red, died
709+
710+
711+
def guarded_mutants(cargo: str) -> int:
712+
fails = 0
713+
with tempfile.TemporaryDirectory(prefix="p037-b1-") as tmp:
714+
work = Path(tmp)
715+
for top in ("rust", "formal/p037-kernel"):
716+
shutil.copytree(ROOT / top, work / top, ignore=shutil.ignore_patterns("target"))
717+
env = {**os.environ, "CARGO_TARGET_DIR": str(work / "target")}
718+
test = [cargo, "test", "-q", "-p", "own-guarded", "--test", "acceptance"]
719+
base = subprocess.run(test, cwd=work / "rust", capture_output=True, text=True,
720+
check=False, env=env)
721+
ok = base.returncode == 0
722+
print(f"{'ok ' if ok else 'MISS'} B1 the own-guarded acceptance controls pass unmutated")
723+
fails += not ok
724+
for label, rel, old, new, flt in GUARDED_MUTANTS:
725+
f = work / rel
726+
pristine = f.read_text(encoding="utf-8")
727+
if pristine.count(old) != 1:
728+
print(f"MISS {label}: the mutation site {old!r} is not unique")
729+
fails += 1
730+
continue
731+
f.write_text(pristine.replace(old, new), encoding="utf-8")
732+
run = subprocess.run([*test, flt], cwd=work / "rust", capture_output=True,
733+
text=True, check=False, env=env)
734+
f.write_text(pristine, encoding="utf-8")
735+
red, died = _killed(run, flt)
736+
print(f"{'ok ' if red else 'MISS'} {label}: killed by {', '.join(died) or 'nothing'}")
737+
fails += not red
738+
return fails
739+
740+
537741
def mutants() -> int:
538742
cargo = shutil.which("cargo")
539743
if cargo is None:
@@ -564,15 +768,12 @@ def mutants() -> int:
564768
run = subprocess.run(
565769
[cargo, "test", "--release", test],
566770
cwd=crate, capture_output=True, text=True, check=False)
567-
# killed = a matching test PANICKED; a compile error is not a kill
568-
out = run.stdout + run.stderr
569-
died = sorted(set(re.findall(r"^---- (\S+) stdout ----$", out, re.M)))
570-
red = run.returncode != 0 and "test result: FAILED" in out and any(
571-
d.split("::")[-1].startswith(test) for d in died)
771+
red, died = _killed(run, test)
572772
print(f"{'ok ' if red else 'MISS'} {label}: killed by {', '.join(died) or 'nothing'}")
573773
fails += not red
574774
lib.write_text(pristine, encoding="utf-8")
575-
print(f"RESULT: {'every kernel mutant is killed' if not fails else f'{fails} miss(es)'}")
775+
fails += guarded_mutants(cargo)
776+
print(f"RESULT: {'every kernel and B1 mutant is killed' if not fails else f'{fails} miss(es)'}")
576777
return 1 if fails else 0
577778

578779

@@ -583,7 +784,10 @@ def main(argv: list[str]) -> int:
583784
g.add_argument("--check", action="store_true")
584785
g.add_argument("--selftest", action="store_true")
585786
g.add_argument("--mutants", action="store_true")
787+
g.add_argument("--b1-gate", action="store_true")
586788
args = ap.parse_args(argv)
789+
if args.b1_gate:
790+
return b1_gate()
587791
if args.selftest:
588792
return selftest()
589793
if args.mutants:

0 commit comments

Comments
 (0)