Files
ai-agent/scripts/ab/parse-ab.py
gabrielvidalandClaude Opus 5.5 ae6cdcef16 feat(ab): parse-ab --rename — prove a step is only a planned rename
renames.py restates a rename the parser output is meant to go through
(tools-v45: the neutral tool names of parser v45), with no product import,
so a slip in the product's table is a diff rather than an expectation.
`parse-ab.py --base REF --rename NAME` applies it to the base side before
hashing and still demands a zero diff. byTool / byToolSub costs are
compared apart: exactly, except where the rename merges or moves cells
(the new parser sums the same terms in another order), there to a
relative 1e-9 — counted in the report.

Checked both ways: without --rename every file differs; a wrong entry in
the transform (Read → reed) shows on the files with a Read card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 18:14:01 +01:00

262 lines
12 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""A/B the transcript parser: a base git ref against the working tree.
Both trees parse the same real transcripts (read in place, never copied into
the repo), each in its own subprocesses, ``parse_conversation(p, full=False)``
and ``full=True``; the canonical JSON (sorted keys) must be identical. There is
no stored baseline: the two sides run back to back with one environment, so
the price book, the OpenRouter catalogue snapshot and the timezone cancel out.
scripts/ab/parse-ab.py --base HEAD # the default corpus
scripts/ab/parse-ab.py --base main --max-files 300 # a quick seeded sample
scripts/ab/parse-ab.py --chunked # incremental == one-shot
scripts/ab/parse-ab.py --base HEAD --chunked # both
scripts/ab/parse-ab.py --base main --rename tools-v45 # only the planned rename
``--rename NAME`` proves a step is *only* a rename: the base side's summaries
go through ``renames.TRANSFORMS[NAME]`` (the rename restated, no product code)
before they are compared, and the diff must still be zero. The byTool /
byToolSub costs are compared apart: exactly, except where the rename merges
or moves cells (the new parser adds the same terms in another order) — there
to float rounding (relative 1e-9).
``--chunked`` checks the working tree alone: every file is fed through
``conversations.feed_lines`` in chunks cut at seeded random byte offsets (most
of them mid-line), ``summary()`` is called after every chunk, and the last
summary must equal the one-shot ``parse_conversation`` — the byte-offset
contract the indexer and the detail route live on.
Exit codes: 0 = identical, 1 = a difference, 2 = usage / setup error.
"""
import argparse
import json
import math
import pathlib
import sys
import time
HERE = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import _common as ab # noqa: E402
import renames # noqa: E402
WORKER = HERE / "_parse_worker.py"
REL_TOL = ABS_TOL = 1e-9
def _costs_match(ra: dict, rb: dict, mode: str) -> tuple[bool, int]:
"""(equal, how many costs only matched to rounding) for one mode of a
--rename row pair: same cost paths, each value identical — or, at a path
the transform re-summed, within REL_TOL."""
ca, cb = ra.get(mode + "Costs") or {}, rb.get(mode + "Costs") or {}
if set(ca) != set(cb):
return False, 0
approx, rounded = set(ra.get(mode + "Approx") or ()), 0
for k, va in ca.items():
vb = cb[k]
if va == vb:
continue
if (k in approx and isinstance(va, (int, float)) and isinstance(vb, (int, float))
and math.isclose(va, vb, rel_tol=REL_TOL, abs_tol=ABS_TOL)):
rounded += 1
continue
return False, 0
return True, rounded
def _rows(paths: list[pathlib.Path]) -> dict[str, dict]:
out = {}
for p in paths:
for line in p.read_text(encoding="utf-8").splitlines():
row = json.loads(line)
out[row["path"]] = row
return out
def _stable(f: dict, *rows: dict) -> bool:
want = [f["size"], f["mtime_ns"]]
return all(r.get("before") == want and r.get("after") == want for r in rows)
def _run_side(tree: pathlib.Path, mode: str, parts: list[list[dict]], work: pathlib.Path,
tag: str, env: dict, jobs: int, extra: list[str]) -> dict[str, dict]:
cmds, outs = [], []
for i, part in enumerate(parts):
lst = work / f"{tag}-{i}.list.json"
lst.write_text(json.dumps(part))
out = work / f"{tag}-{i}.out.jsonl"
outs.append(out)
cmds.append(([sys.executable, str(WORKER), "--tree", str(tree), "--mode", mode,
"--list", str(lst), "--out", str(out), *extra], env, None))
t0 = time.time()
ab.run_pool(cmds, jobs)
print(f" {tag}: {time.time() - t0:.0f}s", file=sys.stderr)
return _rows(outs)
def ab_diff(args, files: list[dict], work: pathlib.Path, env: dict) -> int:
base, sha = ab.materialise(args.base, work / "base")
print(f"base: {args.base} ({sha[:8]}) new: working tree {ab.REPO}"
+ (f" rename: {args.rename} applied to the base" if args.rename else ""))
parts = ab.shards(files, args.jobs)
extra_a = ["--transform", args.rename, "--split-costs"] if args.rename else []
extra_b = ["--split-costs"] if args.rename else []
t0 = time.time()
a = _run_side(base, "digest", parts, work, "base", env, args.jobs, extra_a)
b = _run_side(ab.REPO, "digest", parts, work, "new", env, args.jobs, extra_b)
differing, unstable, compared, rounded_files, rounded = [], 0, 0, 0, 0
for f in files:
ra, rb = a.get(f["path"]), b.get(f["path"])
if not ra or not rb or not _stable(f, ra, rb):
unstable += 1
continue
compared += 1
modes, file_rounded = [], 0
for m in ("short", "full"):
ok = ra[m] == rb[m]
if ok and args.rename:
ok, n = _costs_match(ra, rb, m)
file_rounded += n
if not ok:
modes.append(m)
if modes:
differing.append((f, modes))
elif file_rounded:
rounded_files += 1
rounded += file_rounded
print(f"parse A/B: {compared} file(s) compared × 2 modes, "
f"{len(differing)} differing, {unstable} skipped (changed during the run) "
f"— {time.time() - t0:.0f}s")
if args.rename:
print(f" re-summed costs equal to rounding only: {rounded} in {rounded_files} file(s) "
f"(relative {REL_TOL:g}); every other value identical")
if not differing:
print("OK: the parser output is identical"
+ (f" once the {args.rename} rename is applied to the base" if args.rename else ""))
return 0
by_cat: dict[str, int] = {}
for f, _ in differing:
by_cat[f["cat"]] = by_cat.get(f["cat"], 0) + 1
print("differing by category: " + ", ".join(f"{c} {n}" for c, n in sorted(by_cat.items())))
shown = differing[:args.show]
lst = work / "dump.list.json"
lst.write_text(json.dumps([f for f, _ in shown]))
ab.run_pool([([sys.executable, str(WORKER), "--tree", str(tree), "--mode", "dump",
"--list", str(lst), "--out", str(work / f"dump-{tag}"),
*(["--transform", args.rename] if args.rename and tag == "base" else [])],
env, None)
for tag, tree in (("base", base), ("new", ab.REPO))], args.jobs)
tally: dict[str, int] = {}
for i, (f, modes) in enumerate(shown):
print(f"\n✗ {f['path']} [{f['cat']}]")
for m in modes:
ja = json.loads((work / "dump-base" / f"{i}.{m}.json").read_text(encoding="utf-8"))
jb = json.loads((work / "dump-new" / f"{i}.{m}.json").read_text(encoding="utf-8"))
paths = ab.diff_paths(ja, jb, limit=args.paths)
print(f" full={m == 'full'}: {len(paths)}{'+' if len(paths) >= args.paths else ''} path(s)")
for line in paths:
print(f" {line}")
for g in {ab.generic_path(x) for x in paths}:
tally[g] = tally.get(g, 0) + 1
if not paths and args.rename:
print(" (only costs differ, beyond rounding or at a path the "
"rename does not re-sum — compare the byTool / byToolSub costs)")
elif not paths:
print(" (digests differed but a re-parse is identical: the "
"output is not deterministic for this file)")
if len(differing) > len(shown):
print(f"\n… and {len(differing) - len(shown)} more differing file(s) (--show N)")
print(f"\nfields differing in the {len(shown)} file(s) detailed (file × mode):")
for g, n in sorted(tally.items(), key=lambda kv: (-kv[1], kv[0]))[:30]:
print(f" {n:>4} × {g}")
return 1
def chunked(args, files: list[dict], work: pathlib.Path, env: dict) -> int:
parts = ab.shards(files, args.jobs)
extra = ["--chunks", str(args.chunks), "--seed", str(args.seed)]
if args.tmp_dir:
extra += ["--tmp-dir", args.tmp_dir]
t0 = time.time()
rows = _run_side(ab.REPO, "chunked", parts, work, "chunked", env, args.jobs, extra)
bad, impure, unstable, checked, cuts = [], [], 0, 0, 0
for f in files:
r = rows.get(f["path"])
if not r or not _stable(f, r):
unstable += 1
continue
checked += 1
cuts += r.get("cuts", 0)
res = [(m, r.get(m) or {"equal": False, "error": r.get("error", "no result")})
for m in ("short", "full")]
if any(not x["equal"] for _, x in res):
bad.append((f, r, res))
if any(x.get("pure") is False and x.get("equal") for _, x in res):
impure.append(f)
print(f"chunked: {checked} file(s) × 2 modes, {cuts} chunk(s) fed, "
f"{len(bad)} where chunked ≠ one-shot, {len(impure)} where summary() "
f"is not pure, {unstable} skipped (changed during the run) "
f"— {time.time() - t0:.0f}s")
for f in impure[:args.show]:
print(f"\n✗ summary() called twice gave two results: {f['path']}")
for f, r, res in bad[:args.show]:
print(f"\n✗ {f['path']} [{f['cat']}] size {f['size']}, "
f"ends with newline: {r.get('endsWithNewline')}")
for m, x in res:
if x["equal"]:
continue
print(f" full={m == 'full'}: fed up to byte {x.get('offset')}"
+ (f" — {x['error']}" if x.get("error") else ""))
for line in x.get("paths", []):
print(f" {line} (one-shot → chunked)")
if len(bad) > args.show:
print(f"\n… and {len(bad) - args.show} more file(s) (--show N)")
if not bad and not impure:
print("OK: chunked feed_lines == one-shot parse_conversation")
return 0
return 1
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--base", metavar="REF", help="git ref to compare the working tree with")
ap.add_argument("--rename", choices=sorted(renames.TRANSFORMS),
help="with --base: apply this planned rename to the base output first")
ap.add_argument("--chunked", action="store_true",
help="check incremental feed_lines == one-shot (working tree)")
ab.add_corpus_args(ap)
ap.add_argument("--jobs", type=int, default=2,
help="parser processes at a time (default 2 — the lab is small)")
ap.add_argument("--chunks", type=int, default=8,
help="--chunked: random cuts per file (default 8)")
ap.add_argument("--show", type=int, default=10,
help="differing files to detail (default 10)")
ap.add_argument("--paths", type=int, default=20,
help="JSON paths shown per differing file (default 20)")
ap.add_argument("--tmp-dir", help="--chunked: where the growing prefix is "
"written (default: the system temp dir)")
ap.add_argument("--keep", action="store_true", help="keep the scratch dir")
args = ap.parse_args()
if not args.base and not args.chunked:
ap.error("give --base REF and/or --chunked")
if args.rename and not args.base:
ap.error("--rename needs --base")
files = ab.corpus_from_args(args)
print(ab.corpus_report(files))
rc = 0
with ab.workdir(args.keep) as work:
env = ab.frozen_env(work)
if args.base:
rc = max(rc, ab_diff(args, files, work, env))
if args.chunked:
rc = max(rc, chunked(args, files, work, env))
return rc
if __name__ == "__main__":
sys.exit(main())