Files
rune/scripts/gen_graph_projection_truth.py
T
Nick 2c97b6859f feat(graph_projection): literal-100% residue — dichotomy wave
Port the three audit-unmatched fns name-preserving into the Rust crate:
_now (strftime/gmtime UTC law over civil_from_days, injectable epoch
seam pin_epoch_secs + gp_pin_epoch FFI, i64::MIN un-pin sentinel),
_model_to_dicts (assembly + .get defaults; hasattr/getattr probes stay
facade-side), write_all (mkdir + 3 artifacts + path map with an
in-crate py_dumps_sorted emitter: json.dumps indent=1 sort_keys=True
byte law — ensure_ascii, lowercase hex, astral surrogate pairs).
DEFECTS FOUND+FIXED (write_all byte parity exposed them): kernel
project_json dropped generated_at entirely; project_dot label fallback
ignored the split(':',1)[-1] law; project_mermaid numbered ids in
entity order instead of sorted(set) with dedup, missed the label
quote-escape, and used the full-id fallback. Facade: gp_loader honors
RUNE_GP_CORE=python (rig-pin-gap law) + new fns with configured
argtypes/restype (restype default truncated pointers). Truth: 4
shared-harness cases (freeze_truth --verify OK) + 9 kernel-seam cases
(_now epochs incl. 0/-1, attr-branch m2d, write_all placeholder paths
+ verbatim bytes, clock pinned per row); regen x2 byte-identical.
Battery 12/12 incl. truth replays; clippy -D warnings + fmt clean;
live parity failures=0 (sample + empty + 60-model seeded fuzz, byte
level); pytest 4/4 both pins; ruff clean. graph_projection 3/6
PARTIAL -> 6/6 FULL (audit instrument regenerated).
2026-10-15 09:39:57 +01:00

161 lines
6.7 KiB
Python

#!/usr/bin/env python3
"""gen_graph_projection_truth.py — freeze the graph_projection oracle truth
(dichotomy literal-100% residue wave).
TWO frozen artifacts (both replayed by src/rust/graph_projection/src/
truth_battery.rs):
1. frozen_gp_truth.json — SHARED-HARNESS freeze form (freeze_truth.py):
the JSON-safe rows only. The oracle's `_model_to_dicts` dict-branch
(model without a .doc attribute) is directly callable from JSON args,
so those rows ride the shared harness and stay `freeze_truth.py
--verify` clean.
2. frozen_gp_gap_truth.json — doc-envelope kernel-seam rows (recall_uplift
precedent): the clock (`_now`, epoch-argument law), the attr-branch of
`_model_to_dicts` (needs a live object with .doc/.project_id), and
`write_all` (file IO; out_dir frozen as the GP_TRUTH_OUT placeholder —
the battery substitutes its tempdir). Clock is PINNED per row (epoch),
so every expected byte is wall-clock-free.
Generator law: RUNE_GP_CORE=python pinned (oracle runs the pure-Python
floor), inputs deep-copied, regen byte-identical (no timestamps in the
frozen files).
"""
import copy
import json
import os
import sys
import tempfile
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
sys.path.insert(0, str(ROOT / "scripts"))
os.environ["RUNE_GP_CORE"] = "python"
from freeze_truth import freeze # noqa: E402 shared harness
from rune import graph_projection as gp # noqa: E402
PLACEHOLDER = "GP_TRUTH_OUT"
class _Model:
"""Attr-branch model: .doc + .project_id, like StructuralModel."""
def __init__(self, doc, project_id):
self.doc = doc
self.project_id = project_id
def sample_doc():
"""Deterministic doc with the byte-law traps: unicode name, embedded
quotes, duplicate ids (set-collapse law), root belongs_to edge (skip
law), ghost edge (membership guard), ext filtering."""
return {
"entities": [
{"id": "domain:cøré", "kind": "domain", "maturity": "LIVE_PROVEN",
"identities": {"name": 'Cøré "Q" ünïcode'},
"ext": {"source": "measured", "zzz": "dropped"}},
{"id": "component:alpha", "kind": "component",
"ext": {"bounded_adapter": "cli"}},
{"id": "component:alpha", "kind": "component",
"identities": {"name": "dup"}},
],
"relationships": [
{"type": "belongs_to", "from": "component:alpha",
"to": "domain:cøré", "authority": "spine", "status": "root"},
{"type": "depends_on", "from": "component:alpha",
"to": "domain:cøré", "status": "CURRENT"},
{"type": "depends_on", "from": "ghost", "to": "domain:cøré"},
],
}
def main() -> None:
# ── 1. shared-harness rows: the dict-branch of _model_to_dicts ────
shared = freeze("rune.graph_projection", [
("_model_to_dicts", ({"entities": [1, 2], "relationships": [],
"extra": "ignored"},), {}),
("_model_to_dicts", ({"relationships": [{"type": "x"}]},), {}),
("_model_to_dicts", ({},), {}),
("_model_to_dicts", ({"entities": [], "relationships": [],
"project_id": "key-not-attr"},), {}),
])
# dict-branch law: getattr(dict, "project_id", "") is "" even when the
# KEY exists — the fourth row pins exactly that.
assert shared[3]["expected"]["project_id"] == "", shared[3]["expected"]
out = ROOT / "src/rust/graph_projection/frozen_gp_truth.json"
out.write_text(json.dumps(shared, indent=2, ensure_ascii=False) + "\n")
print(f"shared-harness truth: {len(shared)} cases -> {out}")
# ── 2. kernel-seam gap rows ────────────────────────────────────────
gap: list = []
# _now: pure function of the epoch (clock-as-argument law)
for epoch in (0, -1, 951782400, 1760483570, 4102444800):
expected = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(epoch))
assert gp._now() != expected or True # noqa: B011 — sanity only
gap.append({"fn": "_now", "args": {"epoch": epoch},
"expected": expected})
# _model_to_dicts attr-branch: live object, asserted oracle-side
for doc, pid in ((sample_doc(), "proj-x"),
({"entities": [], "relationships": []}, "")):
model = _Model(doc, pid)
got = gp._model_to_dicts(model)
assert got == {"entities": doc.get("entities", []),
"relationships": doc.get("relationships", []),
"project_id": pid}
gap.append({"fn": "_model_to_dicts",
"args": {"doc": copy.deepcopy(doc), "project_id": pid},
"expected": copy.deepcopy(got)})
# write_all: oracle floor into a scratch dir, clock pinned per row;
# paths frozen with the placeholder, file bytes verbatim
orig_now = gp._now
try:
for epoch, doc, pid in ((951782400, sample_doc(), "proj-x"),
(0, {"entities": [], "relationships": []}, "")):
fixed = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(epoch))
gp._now = lambda: fixed
with tempfile.TemporaryDirectory(prefix="gp-truth-") as td:
model = _Model(doc, pid)
got = gp.write_all(model, td)
assert got["json"] == os.path.join(td, "structural_graph.json")
files = {}
for key, name in (("json", "structural_graph.json"),
("dot", "structural_graph.dot"),
("mermaid", "structural_graph.mmd")):
files[name] = Path(got[key]).read_text()
expected = {k: v.replace(td, PLACEHOLDER) for k, v in got.items()}
gap.append({
"fn": "write_all",
"args": {"model": copy.deepcopy(gp._model_to_dicts(model)),
"out_dir": PLACEHOLDER, "epoch": epoch},
"expected": {**expected, "files": files},
})
finally:
gp._now = orig_now
doc = {
"module": "graph_projection",
"pin": "RUNE_GP_CORE=python",
"placeholder": PLACEHOLDER,
"laws": {
"now": "expected = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(epoch))",
"write_all": "paths carry the placeholder; files are verbatim bytes; clock pinned by epoch",
},
"cases": gap,
}
out2 = ROOT / "src/rust/graph_projection/frozen_gp_gap_truth.json"
out2.write_text(json.dumps(doc, indent=2, ensure_ascii=False) + "\n")
print(f"kernel-seam truth: {len(gap)} cases -> {out2}")
if __name__ == "__main__":
main()