idacy's picture
TRACE artifact: framework, corpus, instrumented case, provider case, evaluators, figures
2955ecc verified
Raw
History Blame Contribute Delete
14.5 kB
"""CLI entry for regenerating the 24-family synthetic sweep.
cd corpus
PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=. python3 -m generator.run \
--base-seed 20260609 --out reproduced_sweep \
[--family NAME ...] [--dry-run] [--persist-all] [--max-per-family N]
Order of operations: anchors gate (abort on drift) -> fixed-cell probe suite
(abort on failure) -> per-family generation with per-instance validation gates
(schema gate aborts; stage-invariant violations are flagged + surfaced, never
dropped) -> per-family summary.json -> top-level run_summary.json.
--max-per-family N evaluates an evenly strided subset of each family while
preserving the true instance_index, and therefore the per-instance seed, of
every kept instance.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
import numpy as np
# Paths are resolved against the repository root, so the generator imports the
# evaluator and validation assets shipped alongside it. The AAAI supplement
# ships the same modules with a "framework/" segment inserted here.
REPO_ROOT = Path(__file__).resolve().parents[2]
SRC = REPO_ROOT / "src"
if str(SRC) not in sys.path:
sys.path.insert(0, str(SRC))
from datacenter_verification.observable_algorithm import ALGORITHM_VERSION, THRESHOLDS, evaluate_site # noqa: E402
from . import GENERATOR_VERSION, anchors, families, metrics, schema, selfcheck # noqa: E402
from .seeding import DEFAULT_BASE_SEED, RNG_NAME # noqa: E402
ALGORITHM_PATH = SRC / "datacenter_verification" / "observable_algorithm.py"
def parse_args(argv=None):
parser = argparse.ArgumentParser(prog="python -m generator.run", description=__doc__)
parser.add_argument("--base-seed", type=int, default=DEFAULT_BASE_SEED)
parser.add_argument("--out", type=Path, default=None,
help="output dir relative to the supplement root unless absolute "
"(default reproduced_sweep_<UTCdate>_NN); "
"must resolve inside the supplement")
parser.add_argument("--family", action="append", default=None,
help="family short key (P1) or dotted name; repeatable; default all")
parser.add_argument("--dry-run", action="store_true",
help="one instance per family + full self-checks; nothing written")
parser.add_argument("--persist-all", action="store_true",
help="dump every site object for the selected families")
parser.add_argument("--max-per-family", type=int, default=None,
help="smoke-run extension: evaluate an evenly strided subset")
return parser.parse_args(argv)
def resolve_out(args) -> Path:
if args.out is None:
date = datetime.now(timezone.utc).strftime("%Y%m%d")
base = REPO_ROOT / "corpus"
nn = 1
while (base / f"reproduced_sweep_{date}_{nn:02d}").exists():
nn += 1
out = base / f"reproduced_sweep_{date}_{nn:02d}"
else:
out = args.out if args.out.is_absolute() else REPO_ROOT / args.out
out = out.resolve()
try:
out.relative_to(REPO_ROOT.resolve())
except ValueError:
raise SystemExit(f"REFUSED: --out {out} resolves outside {REPO_ROOT}")
return out
def select_families(names):
if not names:
return list(families.FAMILIES)
selected = []
for name in names:
if name not in families.FAMILY_BY_KEY:
raise SystemExit(f"unknown family {name!r}; known: "
f"{[f.short for f in families.FAMILIES]}")
fam = families.FAMILY_BY_KEY[name]
if fam not in selected:
selected.append(fam)
return selected
def make_sidecar(inst, result, base_seed: int, invariant_errors: list) -> dict:
stages = result["stage_outputs"]
observed = result["final_route"]
record = {
"family": inst.family,
"instance_index": inst.instance_index,
"seed": inst.seed,
"base_seed": base_seed,
"parameters": inst.params,
"expected_route": (inst.expected_route_set[0]
if len(inst.expected_route_set) == 1 else None),
"expected_route_set": inst.expected_route_set,
"observed_route": observed,
"observed_A": stages["A_capacity_gate"]["label"],
"observed_B": stages["B_training_candidate_detection"]["labels"],
"observed_C": stages["C_discrepancy_and_explanation_review"]["labels"],
"observed_warning_height": stages["final_claim_routing"]["warning_height"],
"match": observed in inst.expected_route_set,
}
if invariant_errors:
record["invariant_violation"] = True
record["invariant_errors"] = invariant_errors
return record
def algorithm_sha256() -> str:
return hashlib.sha256(ALGORITHM_PATH.read_bytes()).hexdigest()
def chosen_indices(total: int, max_n) -> set:
if max_n is None or max_n >= total:
return set(range(total))
return {int(round(v)) for v in np.linspace(0, total - 1, max_n)}
def run_family(meta, base_seed: int, out_dir, persist_all: bool, max_n) -> dict:
fam_dir = out_dir / meta.name
fam_dir.mkdir(parents=True, exist_ok=True)
(fam_dir / "seed").write_text(f"{base_seed}\n", encoding="utf-8")
keep = chosen_indices(meta.instances, max_n)
records, sample_sites, all_sites = [], [], []
t_gen = t_eval = 0.0
t0 = time.perf_counter()
evaluated = 0
routes_path = fam_dir / "raw_routes.jsonl"
with routes_path.open("w", encoding="utf-8") as routes:
gen_start = time.perf_counter()
for inst in meta.generate(base_seed):
t_gen += time.perf_counter() - gen_start
if inst.instance_index in keep:
schema_errors = selfcheck.schema_gate(inst.site)
if schema_errors:
raise SystemExit("SCHEMA GATE FAILED (generator bug):\n"
+ "\n".join(schema_errors))
consistency = selfcheck.consistency_errors(inst.site)
if consistency:
raise SystemExit("RAW/NORMALIZED CONSISTENCY FAILED (generator bug):\n"
+ "\n".join(consistency))
completeness = selfcheck.coverage_completeness_errors(inst)
if completeness:
raise SystemExit("COVERAGE COMPLETENESS FAILED (generator bug):\n"
+ "\n".join(completeness))
e0 = time.perf_counter()
result = evaluate_site(inst.site)
t_eval += time.perf_counter() - e0
evaluated += 1
invariant_errors = selfcheck.stage_invariant_gate(inst.site, result)
record = make_sidecar(inst, result, base_seed, invariant_errors)
routes.write(json.dumps(record, sort_keys=True) + "\n")
records.append(record)
if len(sample_sites) < 20:
sample_sites.append(inst.site)
if persist_all:
all_sites.append(inst.site)
gen_start = time.perf_counter()
summary = metrics.family_summary(meta, records)
summary["evaluated_instances"] = evaluated
summary["designed_instances"] = meta.instances
(fam_dir / "summary.json").write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n",
encoding="utf-8")
(fam_dir / "sites_sample.json").write_text(
json.dumps({"metadata": {"family": meta.name, "base_seed": base_seed,
"sample_size": len(sample_sites)},
"sites": sample_sites}, indent=2, sort_keys=True) + "\n",
encoding="utf-8")
fam_config = {
"family": meta.name, "short": meta.short, "group": meta.group,
"description": meta.description, "param_points": meta.param_points,
"seeds_per_point": meta.seeds_per_point, "designed_instances": meta.instances,
"evaluated_instances": evaluated, "base_seed": base_seed,
"seed_range": {"first_instance_seed": records[0]["seed"] if records else None,
"last_instance_seed": records[-1]["seed"] if records else None},
"headline_metric": meta.headline, "risk_knobs": meta.risk_knobs,
}
(fam_dir / "config.json").write_text(json.dumps(fam_config, indent=2, sort_keys=True) + "\n",
encoding="utf-8")
if persist_all:
with (fam_dir / "sites_all.jsonl").open("w", encoding="utf-8") as handle:
for site in all_sites:
handle.write(json.dumps(site, sort_keys=True) + "\n")
summary["_timing"] = {"generation_s": t_gen, "evaluation_s": t_eval,
"total_s": time.perf_counter() - t0}
return summary
def dry_run(selected, base_seed: int, anchors_status, probe_status) -> dict:
report = {"mode": "dry_run", "base_seed": base_seed, "anchors_gate": anchors_status,
"self_check_probes": {"passed": probe_status["passed"],
"failed": probe_status["failed"]},
"families": {}}
ok = probe_status["status"] == "pass"
for meta in selected:
inst = next(meta.generate(base_seed))
errors = (selfcheck.schema_gate(inst.site)
+ selfcheck.consistency_errors(inst.site)
+ selfcheck.coverage_completeness_errors(inst))
result = evaluate_site(inst.site)
invariants = selfcheck.stage_invariant_gate(inst.site, result)
det = selfcheck.determinism_check(base_seed, meta)
entry = {
"designed_instances": meta.instances,
"first_instance_seed": inst.seed,
"observed_route": result["final_route"],
"expected_route_set": inst.expected_route_set,
"match": result["final_route"] in inst.expected_route_set,
"gate_errors": errors,
"invariant_errors": invariants,
"deterministic": det["deterministic"],
"generation_hash": det["hash"],
}
if errors or not det["deterministic"]:
ok = False
report["families"][meta.name] = entry
report["total_designed_instances"] = sum(m.instances for m in selected)
report["status"] = "pass" if ok else "FAIL"
return report
def main(argv=None) -> None:
args = parse_args(argv)
selected = select_families(args.family)
anchors_status = anchors.run_anchors() # raises AnchorDriftError on drift
probe_status = selfcheck.run_probe_suite()
if probe_status["status"] != "pass" and not args.dry_run:
raise SystemExit("SELF-CHECK PROBES FAILED; aborting sweep:\n"
+ "\n".join(probe_status["failures"]))
if args.dry_run:
report = dry_run(selected, args.base_seed, anchors_status, probe_status)
if probe_status["failures"]:
report["probe_failures"] = probe_status["failures"]
print(json.dumps(report, indent=2, sort_keys=True))
if report["status"] != "pass":
raise SystemExit(1)
return
out_dir = resolve_out(args)
out_dir.mkdir(parents=True, exist_ok=True)
run_id = out_dir.name
t_start = time.perf_counter()
config = {
"run_id": run_id,
"base_seed": args.base_seed,
"rng": RNG_NAME,
"algorithm_version": ALGORITHM_VERSION,
"algorithm_source_sha256": algorithm_sha256(),
"generator_version": GENERATOR_VERSION,
"families": {meta.name: {"short": meta.short, "param_points": meta.param_points,
"seeds_per_point": meta.seeds_per_point,
"instances": meta.instances,
"description": meta.description}
for meta in selected},
"coverage_profiles": {"good": dict(schema.GOOD_COVERAGE)},
"thresholds_snapshot": dict(THRESHOLDS),
"created_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"total_instances": sum(meta.instances for meta in selected),
"full_design_total_instances": families.TOTAL_INSTANCES,
"max_per_family": args.max_per_family,
}
(out_dir / "config.json").write_text(json.dumps(config, indent=2, sort_keys=True) + "\n",
encoding="utf-8")
summaries = []
for meta in selected:
summary = run_family(meta, args.base_seed, out_dir, args.persist_all,
args.max_per_family)
timing = summary.pop("_timing")
print(json.dumps({"family": meta.name,
"evaluated": summary["evaluated_instances"],
"match_rate": summary["match_rate"]["rate"],
"headline": summary["headline"],
"invariant_violations": summary["invariant_violations"],
"seconds": round(timing["total_s"], 3)}))
summary["timing"] = timing
summaries.append(summary)
total_s = time.perf_counter() - t_start
evaluated = sum(s["evaluated_instances"] for s in summaries)
timing = {
"wall_clock_s": total_s,
"evaluated_instances": evaluated,
"seconds_per_instance": total_s / evaluated if evaluated else None,
"extrapolated_full_sweep_s": (total_s / evaluated * families.TOTAL_INSTANCES
if evaluated else None),
}
top = metrics.run_summary(summaries, timing, anchors_status,
{"passed": probe_status["passed"],
"failed": probe_status["failed"]})
(out_dir / "run_summary.json").write_text(json.dumps(top, indent=2, sort_keys=True) + "\n",
encoding="utf-8")
print(json.dumps({"run_id": run_id, "out": str(out_dir),
"evaluated_instances": evaluated,
"wall_clock_s": round(total_s, 2),
"extrapolated_full_sweep_s":
round(timing["extrapolated_full_sweep_s"], 2)
if timing["extrapolated_full_sweep_s"] else None}))
if __name__ == "__main__":
main()