Files
ai-agent/scripts/ab/_parse_worker.py
gabrielvidalandClaude Opus 5.5 13a7a42089 feat(ab): mirror-replay --parse — a format change proven by the hub's parse
The converters' A/B was byte for byte; step 1c changes the format, so
--base REF --parse parses both trees' output with the working tree's
backend instead: the base's old-format output rewritten to v1 with no fix
must parse exactly like itself, the working tree's v1 output like the base
rewritten with every fix (up to `native`, the harness's own tool name), and
fed in chunks like in one go. _parse_worker.py --mode v1 runs the rewrite,
_common.json_paths lists every differing path. test_mirror_replay.py reads
the fixtures' v1 output (groups of events by key).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 11:13:42 +01:00

226 lines
9.3 KiB
Python
Executable File

#!/usr/bin/env python3
"""parse-ab's helper: parse a list of transcripts with ONE tree's parser.
Run by parse-ab.py, once per tree (base ref, working tree), never by hand:
_parse_worker.py --tree <dir with backend/> --mode digest|dump|chunked
--list files.json --out result
``digest`` one JSON line per file with the sha256 of the canonical summary,
``full=False`` and ``full=True`` (the summaries themselves are not
kept: the corpus is several GB).
``dump`` the canonical summaries themselves, one file per input, for the
few files whose digests differed.
``chunked`` the incremental contract: ``feed_lines`` over growing prefixes cut
at seeded random byte offsets must end on the one-shot summary.
``v1`` rewrite each file to v1 (``conversations/parse/rewrite_v1.py``):
the list's ``out`` paths get the v1 lines, ``fixes`` the fixes
applied (``mirror-replay.py --parse`` normalises the old format
with it).
``--transform NAME`` (base side of ``parse-ab.py --rename``): each summary
goes through ``renames.TRANSFORMS[NAME]`` first. ``--split-costs`` (both
sides then): the byTool / byToolSub costs leave the hashed summary and ride
in the row by JSON path (``shortCosts`` / ``fullCosts``, plus the transform's
``shortApprox`` / ``fullApprox`` paths), so the driver can compare re-summed
costs to float rounding and everything else exactly.
The transcripts are read in place. ``chunked`` writes each file's growing
prefix to a temp file that is deleted before the next one.
"""
import argparse
import hashlib
import json
import os
import pathlib
import random
import sys
import tempfile
import traceback
HERE = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from _common import canonical, diff_paths # noqa: E402 (no product code in it)
import renames # noqa: E402 (no product code either)
def _stat(p: pathlib.Path):
try:
st = p.stat()
return [st.st_size, st.st_mtime_ns]
except OSError:
return None
def _parse(conversations, p: pathlib.Path, full: bool):
"""(summary, None) or (None, "ExcType: message") — a crash is a result
too: both sides must crash alike."""
try:
return conversations.parse_conversation(p, full=full), None
except Exception as e: # noqa: BLE001
tb = traceback.extract_tb(e.__traceback__)[-1]
return None, f"{type(e).__name__}: {e} @ {pathlib.Path(tb.filename).name}:{tb.name}"
def _sha(text: str) -> str:
return hashlib.sha256(text.encode("utf-8", "replace")).hexdigest()
def run_digest(conversations, files, out, transform=None, split=False):
for f in files:
p = pathlib.Path(f["path"])
row = {"path": f["path"], "before": _stat(p)}
for name, full in (("short", False), ("full", True)):
s, err = _parse(conversations, p, full)
if err:
row[name] = "EXC " + err
continue
if transform is not None:
s, approx = transform(s)
row[name + "Approx"] = sorted(approx)
if split:
s, row[name + "Costs"] = renames.split_costs(s)
row[name] = _sha(canonical(s))
row["after"] = _stat(p)
out.write(json.dumps(row) + "\n")
out.flush()
def run_dump(conversations, files, out_dir: pathlib.Path, transform=None):
out_dir.mkdir(parents=True, exist_ok=True)
for i, f in enumerate(files):
p = pathlib.Path(f["path"])
for name, full in (("short", False), ("full", True)):
s, err = _parse(conversations, p, full)
if not err and transform is not None:
s, _ = transform(s)
(out_dir / f"{i}.{name}.json").write_text(
canonical({"__exception__": err} if err else s), encoding="utf-8")
def run_v1(files, out):
from conversations.parse import rewrite_v1
for f in files:
p = pathlib.Path(f["path"])
lines = p.read_text(encoding="utf-8", errors="ignore").splitlines()
recs = []
for ln in lines:
try:
recs.append(json.loads(ln))
except ValueError:
pass
harness = f.get("harness") or rewrite_v1.detect_harness(recs)
row = {"path": f["path"], "harness": harness}
if harness is not None:
v1 = rewrite_v1.to_v1(lines, harness, tuple(f.get("fixes") or ()))
pathlib.Path(f["out"]).write_text("\n".join(v1) + "\n", encoding="utf-8")
out.write(json.dumps(row) + "\n")
def cut_points(path: str, size: int, chunks: int, seed: int) -> list[int]:
"""Seeded random byte offsets in (0, size), then ``size`` — most land in
the middle of a line."""
rng = random.Random(f"{seed}:{path}:{size}")
cuts = {rng.randrange(1, size) for _ in range(chunks)} if size > 1 else set()
return sorted(cuts) + [size]
def run_chunked(conversations, files, out, chunks: int, seed: int, tmp_dir: str | None):
for f in files:
p = pathlib.Path(f["path"])
row = {"path": f["path"], "before": _stat(p), "size": f["size"]}
try:
data = p.read_bytes()
except OSError as e:
row["error"] = f"read: {e}"
out.write(json.dumps(row) + "\n")
continue
# The state carries the transcript's own path (the project label falls
# back to it); only feed_lines reads the growing temp copy. A file that
# changed meanwhile is dropped by the driver (before/after stat).
fd, tmp_name = tempfile.mkstemp(prefix="ab-chunk-", suffix=".jsonl", dir=tmp_dir)
tmp = pathlib.Path(tmp_name)
try:
cuts = cut_points(f["path"], len(data), chunks, seed)
row["cuts"] = len(cuts)
row["endsWithNewline"] = data.endswith(b"\n")
for name, full in (("short", False), ("full", True)):
try:
with open(tmp, "wb"):
pass
state = conversations.ParserState(p, full=full)
offset, prev, last = 0, 0, None
with open(tmp, "ab") as grow:
for cut in cuts:
grow.write(data[prev:cut])
grow.flush()
prev = cut
new_off = conversations.feed_lines(state, tmp, offset)
if new_off is None:
raise RuntimeError("feed_lines returned None")
if not offset <= new_off <= cut:
raise RuntimeError(
f"feed_lines offset {new_off} outside [{offset}, {cut}]")
offset = new_off
last = state.summary()
again = state.summary() # summary() must be a pure snapshot
ref = conversations.parse_conversation(p, full=full)
a, b, c = canonical(ref), canonical(last), canonical(again)
row[name] = {
"equal": a == b, "pure": b == c, "offset": offset,
"paths": [] if a == b else diff_paths(
json.loads(a), json.loads(b), limit=8),
}
except Exception as e: # noqa: BLE001
row[name] = {"equal": False, "pure": False,
"error": f"{type(e).__name__}: {e}", "paths": []}
finally:
os.close(fd)
tmp.unlink(missing_ok=True)
row["after"] = _stat(p)
out.write(json.dumps(row) + "\n")
out.flush()
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--tree", required=True, type=pathlib.Path)
ap.add_argument("--mode", required=True, choices=("digest", "dump", "chunked", "v1"))
ap.add_argument("--list", required=True, type=pathlib.Path)
ap.add_argument("--out", required=True, type=pathlib.Path)
ap.add_argument("--chunks", type=int, default=8)
ap.add_argument("--seed", type=int, default=1)
ap.add_argument("--tmp-dir", default=None)
ap.add_argument("--transform", choices=sorted(renames.TRANSFORMS))
ap.add_argument("--split-costs", action="store_true")
args = ap.parse_args()
transform = renames.TRANSFORMS[args.transform] if args.transform else None
backend = args.tree / "backend"
if not (backend / "conversations").is_dir():
print(f"error: no backend/conversations under {args.tree}", file=sys.stderr)
return 2
sys.path.insert(0, str(backend))
import conversations # noqa: E402 (this tree's parser)
assert pathlib.Path(conversations.__file__).resolve().is_relative_to(
backend.resolve()), conversations.__file__
files = json.loads(args.list.read_text())
if args.mode == "dump":
run_dump(conversations, files, args.out, transform)
return 0
with open(args.out, "w", encoding="utf-8") as out:
if args.mode == "digest":
run_digest(conversations, files, out, transform, args.split_costs)
elif args.mode == "v1":
run_v1(files, out)
else:
run_chunked(conversations, files, out, args.chunks, args.seed, args.tmp_dir)
return 0
if __name__ == "__main__":
sys.exit(main())