cluster_review.py¶
scripts/cluster_review.py
THE POST-RELEASE REVIEW'S FIRST THREE STEPS, as a command rather than as a habit.
cell_shape
tuple[float, int, int, int, int] cluster_review.cell_shape(Path adir, str stem)
One cell's score, answer length, call count and failed weight.
Called by rank, test_a_missing_meta_yields_unknown_and_not_zero, test_failed_weight_de_duplicates_by_mark_text
Calls none
Source · 27 lines
def cell_shape(adir: Path, stem: str) -> tuple[float, int, int, int, int]:
"""FAILED WEIGHT IS DE-DUPLICATED BY MARK TEXT, because replicates repeat every decision and
summing them counts one mark three times. A mark that any replicate HIT is counted as hit —
the pessimistic direction would make a flaky judge look like a capability gap.
`-1` IS RETURNED FOR AN ABSENT MEASUREMENT, never 0, for the reason the vocabulary states
about `tool_calls`: unknown must not be counted as none.
@brief Read one cell's shape from its sidecars.
@return The tuple.
@version 1
"""
grade = json.loads((adir / f"{stem}.grade.json").read_text("utf-8"))
by_mark: dict[str, bool] = {}
for d in grade.get("decisions", []):
by_mark[d["mark"]] = by_mark.get(d["mark"], False) or bool(d.get("hit"))
weights = {d["mark"]: d.get("weight", 1) for d in grade.get("decisions", [])}
failed = sum(w for m, w in weights.items() if not by_mark.get(m))
md = adir / f"{stem}.md"
meta = adir / f"{stem}.meta.json"
chars = len(md.read_text("utf-8")) if md.exists() else -1
calls = -1
if meta.exists():
calls = json.loads(meta.read_text("utf-8")).get("tool_calls", -1)
return grade["score"] * 100, chars, calls, failed, sum(weights.values())
Activity · 13 steps
Flows
main
int cluster_review.main(list[str] argv)
Dispatch a subcommand.
Source · 13 lines
def main(argv: list[str]) -> int:
"""@brief Route `rank` / `trace`.
@return The subcommand's status, or 1 on a usage error.
@version 1
"""
if len(argv) >= 2 and argv[0] == "rank":
return rank(Path(argv[1]))
if len(argv) >= 4 and argv[0] == "trace":
return trace(Path(argv[1]), argv[2], argv[3])
print(__doc__)
return 1
Activity · 6 steps
Flows
rank
int cluster_review.rank(Path run)
Rank every cluster by the primary arm's gap against baseline.
Called by main, test_a_run_with_nothing_to_pair_refuses, test_an_unpaired_cluster_is_named_rather_than_ranked, test_the_ranking_is_by_gap_and_not_by_raw_score
Calls cell_shape, targets_of
Source · 72 lines
def rank(run: Path) -> int:
"""STEP 1 OF THE PROCEDURE, with the paired shape beside it. See the module docstring for why
the pairing is the point rather than a decoration.
A cluster with no baseline arm is SKIPPED AND NAMED, not ranked against nothing: a gap needs
both halves, and ranking a one-armed cluster at its raw score is the "cluster every arm fails"
error the step exists to avoid.
@brief Print the gap-ranked cluster table.
@return 0, or 2 when no cluster could be paired.
@version 1
"""
shapes: dict[tuple[str, str, str], list[tuple[float, int, int, int, int]]] = defaultdict(list)
for target in targets_of(run):
adir = run / target / "answers"
for grade in sorted(adir.glob("*.grade.json")):
stem = grade.name[: -len(".grade.json")]
m = CELL.match(stem)
if not m:
continue
q, _model, arm, _rep = m.groups()
shapes[(target, q, arm)].append(cell_shape(adir, stem))
rows = []
unpaired = []
for (target, q, arm), vals in shapes.items():
if arm != PRIMARY_ARM:
continue
base = shapes.get((target, q, "baseline"))
if not base:
unpaired.append(f"{target} {q}")
continue
mean = lambda vs, i: statistics.mean(v[i] for v in vs) # noqa: E731
rows.append(
(
mean(vals, 0) - mean(base, 0),
target,
q,
mean(vals, 0),
mean(base, 0),
mean(vals, 2),
mean(base, 2),
mean(vals, 1),
mean(base, 1),
mean(vals, 3),
mean(vals, 4),
)
)
if not rows:
print(f"no cluster in {run} has both {PRIMARY_ARM} and baseline cells")
return 2
rows.sort()
print(f"run: {run} primary arm: {PRIMARY_ARM} clusters: {len(rows)}\n")
print(
f"{'gap':>7} {'cluster':<14} {'score':>12} {'tool calls':>12} "
f"{'answer chars':>14} {'failed wt':>10}"
)
print(f"{'':>7} {'':<14} {'idx':>5}{'base':>7} {'idx':>5}{'base':>7} {'idx':>6}{'base':>8}")
for gap, target, q, io, b0, ic, bc, ich, bch, fw, tw in rows:
print(
f"{gap:+7.2f} {target + ' ' + q:<14} {io:5.1f}{b0:7.1f} "
f"{ic:5.1f}{bc:7.1f} {ich:6.0f}{bch:8.0f} {fw:4.0f}/{tw:<5.0f}"
)
## NAMED, NOT SUMMARISED. A cluster left out of a ranking is a cluster the review did not
## cover, and "25 clusters ranked" beside a silent omission is the flattering reading.
if unpaired:
print(f"\nunpaired (no baseline arm, NOT ranked): {len(unpaired)}")
for name in unpaired:
print(f" {name}")
return 0
Activity · 35 steps
Flows
targets_of
list[str] cluster_review.targets_of(Path run)
Every target directory of a run that holds answers.
Source · 8 lines
def targets_of(run: Path) -> list[str]:
"""@brief List a run's answer-bearing targets.
@return The target names.
@version 1
"""
return sorted(p.name for p in run.iterdir() if (p / "answers").is_dir())
Activity · 1 steps
Flows
trace
int cluster_review.trace(Path run, str target, str question)
Print one cluster's call-and-reply trace, per replicate.
Source · 42 lines
def trace(run: Path, target: str, question: str) -> int:
"""STEP 3 OF THE PROCEDURE. Paired by `tool_use` id through `selector_waste._blocks`, so a
transcript that repeats a row shows one call — the inflation that put 157 in a draft where
`selector_waste.py` counts 92.
THE REPLY IS SIZED AND FLAGGED RATHER THAN PRINTED WHOLE. A single cell's replies run to 54 KB
and the thing a reviewer needs first is the SHAPE: which calls came back empty, and how big the
one before the agent stopped was. Reading a specific reply in full is then a one-line jq away,
and the trace names the transcript so it can be.
@brief Trace one cluster's calls and replies.
@return 0, or 2 when no transcript resolves.
@version 1
"""
adir = run / target / "answers"
raws = sorted(adir.glob(f"{question}_*{PRIMARY_ARM}*.raw.json"))
if not raws:
print(f"no {PRIMARY_ARM} cells for {target} {question} in {run}")
return 2
resolved = 0
for raw in raws:
session = json.loads(raw.read_text("utf-8")).get("session_id")
hits = sorted(PROJECTS.glob(f"*/{session}.jsonl")) if session else []
stem = raw.name[: -len(".raw.json")]
if not hits:
## A CULLED TRANSCRIPT IS NAMED. It is the artefact a published run does not carry,
## so its absence is the expected failure here and must not read as a quiet cell.
print(f"\n=== {stem}: NO TRANSCRIPT (session {session})")
continue
resolved += 1
uses, results = _blocks(hits[0])
print(f"\n=== {stem} calls={len(uses)} transcript={hits[0].name}")
for call_id, block in uses.items():
name = str(block.get("name") or "").replace("mcp__clew__", "")
args = json.dumps(block.get("input") or {})
reply = results.get(call_id, "")
miss = '"found": false' in reply or '"found":false' in reply
print(f" CALL {name}({args[:150]})")
print(f" REPLY {len(reply):>7} bytes {'MISS' if miss else 'hit'}")
return 0 if resolved else 2