Skip to content

Commit a3270b9

Browse files
committed
P-037 A18-0: the eight-row decomposition script
One script over exactly the eight B1 UNEXPLAINED rows, from the frozen population and the unchanged B1 instrument: - L_actual and G come from own-guarded-report on the facts as emitted; - L_canonical is the same production MOS with the row's one legacy op rewritten to the honest forward; - each row gets a deterministic reason (CONSUMES_PARAM_FOLD / ARGUMENT_SHAPE_LOSS) and an executable witness; the shape-loss witness re-extracts the frozen source with the value-preserving wrapper removed on that one line. 158 counted lines (cap 200). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KmiyfrkaG9sJruTcshM2oq
1 parent ccde27c commit a3270b9

1 file changed

Lines changed: 189 additions & 0 deletions

File tree

‎scripts/p037_a18_decompose.py‎

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
#!/usr/bin/env python3
2+
"""P-037 A18-0: the three-way decomposition of the eight B1 UNEXPLAINED rows.
3+
4+
Contract: docs/notes/p037-a18-legacy-decomposition.md (pre-registered in
5+
ccde27c). For exactly the eight rows committed in B1's evidence, from the
6+
frozen population and the unchanged B1 instrument:
7+
8+
L_actual the production MOS (own-bridge) on the facts as emitted
9+
G the guarded shadow on the same facts
10+
L_canonical the same production MOS with the row's one legacy op at the
11+
forwarding call's line rewritten to the honest forward
12+
13+
Each row gets one deterministic normalization reason (CONSUMES_PARAM_FOLD or
14+
ARGUMENT_SHAPE_LOSS, never a P-037 class) and that reason's executable
15+
witness.
16+
17+
Run: python scripts/p037_a18_decompose.py --out docs/evidence/p037-a18/eight-rows.json
18+
"""
19+
from __future__ import annotations
20+
21+
import argparse
22+
import copy
23+
import json
24+
import re
25+
import subprocess
26+
import sys
27+
import tempfile
28+
from pathlib import Path
29+
from typing import Any
30+
31+
ROOT = Path(__file__).resolve().parent.parent
32+
sys.path.insert(0, str(ROOT / "scripts"))
33+
34+
import p037_b1_shadow as b1 # noqa: E402
35+
36+
EVIDENCE = ROOT / "docs/evidence/p037-b1/shadow-run.json"
37+
38+
39+
def report(facts: Any) -> Any:
40+
run = subprocess.run([str(b1.REPORT_BIN)], input=json.dumps(facts).encode(),
41+
capture_output=True, check=True)
42+
return json.loads(run.stdout)
43+
44+
45+
def coord(rep: Any, method: str, key: str, value: int) -> Any:
46+
rows = [s for s in rep["summary"] if s["method"] == method and s[key] == value]
47+
return rows[0] if len(rows) == 1 else None
48+
49+
50+
def op_sites(body: list[Any]) -> list[tuple[list[Any], int]]:
51+
"""Every op as (containing list, position), pre-order."""
52+
out = []
53+
for i, op in enumerate(body):
54+
out.append((body, i))
55+
for k in ("then", "else", "body"):
56+
out += op_sites(op.get(k) or [])
57+
return out
58+
59+
60+
def names(op: Any, p: str) -> bool:
61+
return p in (op.get("var"), op.get("src"), op.get("result")) or p in (op.get("args") or [])
62+
63+
64+
def locate(facts: Any, row: Any) -> tuple[Any, Any, list[tuple[list[Any], int]]]:
65+
"""The row's function, its one forwarding sidecar call, and the legacy ops on
66+
the parameter at that call's statement line."""
67+
fn = next(f for f in facts["functions"] if f["name"] == row["method"])
68+
calls = [c for c in (fn.get("guarded_facts") or {}).get("calls", [])
69+
if any(a["kind"] == "param" and a.get("source_param") == row["ordinal"]
70+
for a in c["args"])]
71+
call = calls[0] if len(calls) == 1 else None
72+
line = call["statement_line"] if call else None
73+
ops = [(lst, i) for lst, i in op_sites(fn["body"])
74+
if lst[i].get("line") == line and names(lst[i], row["param"])]
75+
return fn, call, ops
76+
77+
78+
def decompose(facts: Any, rep: Any, row: Any) -> dict[str, Any]:
79+
_, call, ops = locate(facts, row)
80+
if call is None or len(ops) != 1:
81+
return {"reason": None, "why": "no single forwarding call / legacy op"}
82+
kind = ops[0][0][ops[0][1]]["op"]
83+
slot = next(a["param"] for a in call["args"]
84+
if a["kind"] == "param" and a.get("source_param") == row["ordinal"])
85+
callee = coord(rep, call["callee"], "ordinal", slot)
86+
if callee is None:
87+
return {"reason": None, "why": "callee coordinate not in the B1 report"}
88+
reason = ("CONSUMES_PARAM_FOLD" if kind == "release" and callee["legacy"] != "must" else
89+
"ARGUMENT_SHAPE_LOSS" if kind == "use" and callee["legacy"] != "no" else None)
90+
canon = copy.deepcopy(facts)
91+
lst, i = locate(canon, row)[2][0]
92+
lst[i] = {"op": "call", "callee": call["callee"], "sig": call["sig"],
93+
"args": ["_"] * callee["index"] + [row["param"]], "line": call["statement_line"]}
94+
after = coord(report(canon), row["method"], "index", row["index"])
95+
return {"reason": reason, "legacy_op": kind, "callee": call["callee"],
96+
"callee_actual": callee["legacy"], "line": call["statement_line"],
97+
"canonical": after["legacy"], "guarded_after_rewrite": after["guarded"],
98+
"canonical_class": after["class"]}
99+
100+
101+
UNWRAP = [(re.compile(r"\(\s*[\w.]+\s*\)\s*(?=\w)"), ""), (re.compile(r"(\w)!(?!=)"), r"\1")]
102+
103+
104+
def shape_probe(tree: Path, files: list[str], row: Any, line: int, work: Path) -> dict[str, Any]:
105+
"""ARGUMENT_SHAPE_LOSS witness: the frozen source with the value-preserving
106+
wrapper removed on that one line re-extracts to a fold (`release`)."""
107+
src = next(tree / f for f in files if row["method"].split(".")[0] in (tree / f).read_text())
108+
text = src.read_text()
109+
lines = text.split("\n")
110+
old = lines[line - 1]
111+
for pat, rep_ in UNWRAP:
112+
lines[line - 1] = pat.sub(rep_, lines[line - 1])
113+
src.write_text("\n".join(lines))
114+
try:
115+
facts, rep, _ = b1.run_document(tree, files, work)
116+
finally:
117+
src.write_text(text)
118+
ops = locate(facts, row)[2]
119+
return {"line_before": old.strip(), "line_after": lines[line - 1].strip(),
120+
"op_after": ops[0][0][ops[0][1]]["op"] if len(ops) == 1 else None,
121+
"actual_after": coord(rep, row["method"], "index", row["index"])["legacy"]}
122+
123+
124+
def witnessed(d: dict[str, Any], row: dict[str, Any]) -> bool:
125+
moved = d["canonical"] != row["actual"]
126+
if d["reason"] == "CONSUMES_PARAM_FOLD":
127+
return moved and bool(d["callee_actual"] != "must")
128+
if d["reason"] == "ARGUMENT_SHAPE_LOSS":
129+
probe = d.get("probe") or {}
130+
return moved and probe.get("op_after") == "release" and probe["line_after"] != \
131+
probe["line_before"]
132+
return False
133+
134+
135+
def main(argv: list[str]) -> int:
136+
ap = argparse.ArgumentParser(description=__doc__,
137+
formatter_class=argparse.RawDescriptionHelpFormatter)
138+
ap.add_argument("--out", required=True)
139+
args = ap.parse_args(argv)
140+
commit = b1.frozen(b1.POPULATION_COMMIT)
141+
if b1.git("status", "--porcelain", "--untracked-files=no").strip():
142+
print("REFUSED: the instrument tree is dirty; commit it first")
143+
return 2
144+
b1_rows = [u for u in json.loads(EVIDENCE.read_text())["unexplained"]
145+
if u["level"] == "summary"]
146+
rows: list[dict[str, Any]] = []
147+
with tempfile.TemporaryDirectory(prefix="p037-a18-") as td:
148+
tree, work = Path(td) / "tree", Path(td)
149+
tree.mkdir()
150+
archive = subprocess.run(["git", "archive", commit], cwd=ROOT, capture_output=True,
151+
check=True).stdout
152+
subprocess.run(["tar", "-x", "-C", str(tree)], input=archive, check=True)
153+
docs = {name: files for _, name, files in b1.documents(tree, commit)}
154+
for u in b1_rows:
155+
facts, rep, _ = b1.run_document(tree, docs[u["doc"]], work)
156+
now = coord(rep, u["method"], "index", u["index"])
157+
row = {"doc": u["doc"], "method": u["method"], "index": u["index"],
158+
"ordinal": u["ordinal"], "param": u["param"], "actual": now["legacy"],
159+
"guarded": now["guarded"],
160+
"void": now["legacy"] != u["legacy"] or now["guarded"] != u["guarded"]}
161+
d = decompose(facts, rep, row)
162+
if d["reason"] == "ARGUMENT_SHAPE_LOSS":
163+
d["probe"] = shape_probe(tree, docs[u["doc"]], row, d["line"], work)
164+
row.update(d)
165+
row["witness"] = witnessed(d, row)
166+
rows.append(row)
167+
ok = [r for r in rows if not r["void"] and r["reason"] and r["witness"]
168+
and r["guarded"] == r["canonical"] == r["guarded_after_rewrite"]]
169+
kill = [r for r in rows if r["guarded"] != r.get("canonical")]
170+
verdict = ("VOID — instrument drift" if any(r["void"] for r in rows) else
171+
"FAIL — A18 DECOMPOSITION REFUTED" if kill or len(ok) != 8 or len(rows) != 8
172+
else "PASS — A18 8-ROW DECOMPOSITION HOLDS")
173+
out = {"schema": "p037-a18-eight-rows/1", "population_commit": commit,
174+
"instrument_commit": b1.git("rev-parse", "HEAD").strip(), "rows_checked": len(rows),
175+
"g_equals_canonical": sum(r["guarded"] == r.get("canonical") for r in rows),
176+
"deterministic_reason": sum(bool(r["reason"]) for r in rows),
177+
"witnessed": sum(r["witness"] for r in rows), "rows": rows, "result": verdict}
178+
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
179+
Path(args.out).write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8")
180+
for r in rows:
181+
print(f" {r['doc']} {r['method']}: L_actual={r['actual']} L_canonical="
182+
f"{r.get('canonical')} G={r['guarded']} reason={r['reason']} "
183+
f"witness={r['witness']}")
184+
print(f"RESULT: {verdict}")
185+
return 0 if verdict.startswith("PASS") else 1
186+
187+
188+
if __name__ == "__main__":
189+
sys.exit(main(sys.argv[1:]))

0 commit comments

Comments
 (0)