The question

You run LLM benchmarks. A colleague proposes adding “think step by step” to the prompt for a cheap hosted model, and quotes the large gains that chain-of-thought (CoT) prompting produced on grade-school arithmetic a few years ago. Before you change the prompt for every downstream evaluation, two questions have to be answered on your model: does the step-by-step instruction raise exact-match on GSM8K, and does any such gain survive on items the model cannot have seen? GSM8K has been public for years, so a score on it may partly be a memory test. This study asks both, on one dated snapshot, qwen-flash-2025-07-28, queried at temperature 0 with its thinking mode off.

What was decided, and how it was registered

Two registered tracks, each a set of pre-declared measurement cells rather than a search (no cell was ever “kept” against an incumbent):

Each track declared that its headline would need a sealed confirmation cell and a replication before it could be called confirmed. How far the records got is shown in the evidence block of section 5, not restated here.

What the study found, before the method

Scope of every sentence on this page: one model snapshot, two registered prompt wordings, one query date. Nothing here says anything about another model, a thinking-mode configuration or another prompt.

The method taught

The method is a paired item comparison with an honest unit of uncertainty, plus a fresh-twin probe for contamination. Both are cheap, and both are easy to get subtly wrong.

Two arms, one scorer, every call pinned

Each item is sent twice to the same model at temperature 0, once under a direct instruction and once under a cot instruction. A fixed scorer extracts the integer the reply commits to (the number after the last Answer: marker, else the last number in the reply) and scores 1 if it equals the gold answer, else 0. The prompts, decoding parameters and scorer live in a library file the experiment cannot edit, so a cell chooses which items to measure and never how they are asked or graded. Every request and response goes through a call ledger that pins the exact request, the response, the model id actually served, and the token usage; the study therefore re-verifies offline.

The paired gain, and why pairing matters

With c_i, r_i \in \{0,1\} the exact-match of item i under the CoT and direct arms, the gain is the mean of the per-item differences, which depends only on the discordant items (those where exactly one arm is right):

\hat\Delta=\frac1n\sum_{i}(c_i-r_i)=\frac{n_{10}-n_{01}}{n},\qquad \operatorname{SE}(\hat\Delta)=\sqrt{\frac{p_{10}+p_{01}-\Delta^{2}}{n}}

Here n_{10} counts items only CoT answered correctly and n_{01} items only the direct arm did. Items both arms get right (or both get wrong) add nothing. That is why a pair of arms at 0.95 and 0.96 can be compared far more sharply than two marginal means, and also why, near a ceiling, the whole comparison rests on a handful of items. McNemar’s exact test asks whether the discordant items split like a fair coin:

p_{\text{McNemar}}=\min\!\Big(1,\;2\sum_{j=0}^{\min(n_{10},n_{01})}\binom{D}{j}\,2^{-D}\Big),\qquad D=n_{10}+n_{01}

It assumes the discordant items are independent. That holds for the public GSM8K items. It fails on the twin blocks, where four twins share one template’s wording and structure.

The cluster bootstrap: the template is the unit

On a twin block the study resamples whole templates, not rows, with a ratio estimator so that unequal cluster sizes stay correct:

\hat\Delta^{*b}=\frac{\sum_{t\in S_b}\sum_{k}(c_{tk}-r_{tk})}{\sum_{t\in S_b}m_t},\qquad S_b=\text{templates drawn with replacement}

The same four-twin block therefore carries the information of far fewer than 200 independent items (the design effect 1+(m-1)\rho_d with m twins per template and intra-template correlation \rho_d). On twins, the cluster interval is the inference; McNemar’s p is shown only to be told it overstates the evidence.

The contamination probe: originals against fresh twins

GSM8K is presumed contaminated. A twin is the same question text with new numbers, generated from a template by a procedure that regenerates the original byte-for-byte and whose answers an exact solver validates. If the model had memorized an original’s answer, its score on the original should exceed its score on the twins of that template. With o_t the CoT score on template t’s original and \bar y_t its twins’ mean score:

G=\frac1T\sum_{t}\bigl(o_t-\bar y_t\bigr)

The comparison is paired by template, so a hard template counts against both sides of its own difference and the template mix cannot create a gap. Two honest limits come with the design. First, a twin is a fresh string, not a fresh kind of problem, so the probe sees instance memorization only. Second, a gap cannot exceed one minus the twins’ score, so a model scoring near the ceiling leaves almost no room for the probe to find anything. The same headroom logic caps the gain:

\Delta\le 1-p_r

Registering rules, and what a point-estimate rule can decide

The registered predictions read the printed point estimate, not the interval. A rule at a threshold the truth sits exactly on is a coin flip, and a rule can be satisfied while its interval still reaches past the bound. The study keeps those two things apart: the notary adjudicates the rule as written, and the interval is the evidence for what the data can and cannot exclude.

The data story

Shape

The source is the bundled GSM8K test file, verified by hash before preparation. The study uses four blocks of an index that the contract names, so no evaluator invents its own partition:

BlockSplitWhat it is
originaltrainthe 50 GSM8K test items the templates were written from
gsm8kdevelopment300 further public items (the anchor sample)
twin_devdevelopment4 twins per template, generator seed A (200 items)
twin_sealedtest, sealed4 twins per template, a second generator seed (200 items), opened once per track

The unit of independence on a twin block is the template, so the effective sample for the contamination track is the 50 templates, not the 200 twins.

The gotchas that travelled into the findings

The go/no-go call

The mechanized near-duplicate check failed by design: a twin shares a 13-gram with its own template’s original and twins, which is exactly what a twin is. The auditor showed that every hit is own-template and none touches another template or any public item. Under the protocol any mechanized FAIL is a blocker, so the card stayed at no-go until the lead recorded a gate override with that reasoning, the actor, and the index hash. That override is on the record, not a clean pass, and the findings carry it as a caveat. The audit itself made no model call.

The experiment journey

Both tracks are registered: every row of the ledger is a pre-declared cell that was either measured or crashed. There is no incumbent and no keep, so the “frontier” for each track is simply its cells in the order they ran. Development cells and sealed confirmation cells are labelled separately below; the table that follows is generated from the ledger.

Tracks: cot_gain — em_gain (higher is better) · contamination — em_gap (lower is better)

ExpTrackKindMetricStatusDescription
E0001cot_gaindevelopmentNAcrashanchor: CoT vs direct on the 300-item public GSM8K sample; process exit code 1
E0002cot_gaindevelopment0.01measuredanchor: CoT vs direct on the 300-item public GSM8K sample, rerun after E0001's rate-limit crash; registered cell measured
E0003contaminationdevelopment0.02measuredcontamination: CoT on 50 template originals vs 200 development twins (template-paired); registered cell measured
E0004cot_gaindevelopment-0.025measuredcot_gain on development twin block A (CoT vs direct); registered cell measured
E0005cot_gainfinal_test0measuredsealed confirmation: CoT vs direct on twin block C; registered cell measured
E0006contaminationfinal_test0.01measuredsealed confirmation: CoT originals vs twin block C; registered cell measured

Track cot_gain: three development cells and one sealed cell

E0001 crashed. The first anchor run hit an HTTP rate-limit response after almost all of its calls had been made and pinned. That is an infrastructure fault (eight concurrent workers on an account shared with another study), not a bad idea, so the lead lowered the worker count and re-ran. E0002 answered all but one of its requests from E0001’s pinned shard and made one new call: this is how the public anchor was measured. Its paired gain was +0.01 with interval [-0.01, 0.03], against a registered rule value of 0.10 (P2 refuted), and its direct score of 0.95 was far above the 0.55 to 0.85 range the card had expected (P1 refuted).

Gain and its 95% interval for each cot_gain cell, with the registered 0.10 rule value as a dashed line; the crashed first run is a rug mark.
Track cot_gain, development cells (dots) and the sealed twin cell (star), each with its 95% interval, against the registered rule value of 0.10 (dashed) and zero (solid). The first anchor run crashed and carries no value. Every interval lies far below the registered gain and spans zero or sits near it. Close

E0004 repeated the paired comparison on 200 development twins and found the direct arm ahead by 0.025 (cluster interval [-0.065, 0.005]); P4 refuted. The experimenter’s decision lines were written before the next cell ran. The sealed cell E0005 was opened once, after a mandatory offline dry run that spent nothing: the gain was 0.000 with interval [-0.055, 0.045] (P5 refuted).

Grouped bars of items where only CoT was right and items where only direct was right, for public items, development twins and sealed twins.
Cells E0002 (public, 300 items), E0004 (development twins) and E0005 (sealed twins) on the cot_gain track: the items where exactly one arm answered correctly, bars zero-based, concordant counts beneath each pair. A near-zero gain is a handful of disagreements that fall in both directions; the twin cells are template-clustered, so McNemar’s p overstates them. Close

Track contamination: one development cell and one sealed cell

E0003 compared CoT on the 50 originals with their 200 development twins, template by template: gap 0.02, interval over templates [-0.015, 0.06] (P3 supported by its point-estimate rule, with an upper end above the 0.05 bound). The sealed cell E0006 gave a gap of 0.01, interval [-0.04, 0.065] (P6 supported by the same rule). The two sealed cells share ledger entries. E0006 made no new model call: it re-scored the 50 original answers E0003 had recorded and the 200 sealed CoT twin answers E0005 had recorded. Their agreement is by construction, so the sealed contamination cell is a second scoring of answers already in the ledger, not a second query of the model.

Gap and its 95% interval for the two contamination cells, with the 0.05 rule value dashed.
Track contamination, the development cell E0003 (dot) and the sealed cell E0006 (star), each with its 95% template-bootstrap interval, against the registered rule value of 0.05 (dashed) and zero (solid). Both point estimates sit below the bound, but both interval upper ends reach past it, so a 5-point gap is not excluded. Close

Replications, and the replay that is not one

Two salted re-queries re-asked the model: one of the public anchor (E0002) and one of the development contamination cell (E0003). Each re-query reproduced within its pre-registered tolerance (0.03 and 0.05), and each moved: the anchor gain went from +0.01 to -0.0067, and the gap’s sign flipped from 0.02 to -0.025 (a shift of 0.045). That is what temperature 0 on a hosted model looks like. An offline replay of E0002 also ran. It reproduced with a difference of 0, because it re-scored the same recorded answers. A replay is never a replication: it audits parsing, scoring and aggregation, and says nothing about the model.

The decision lines

Every refuted prediction received a dated decision line in the lab notebook before the next cell ran. Two decisions shaped everything after them. When the experimenter saw, from E0001’s pinned shard and before any score existed, that the direct arm did not comply with its instruction, the lead declined to change the prompt, so the instrument would not adapt to observed outputs. And after the first referee round the synthesist added two post-hoc controls and a family-wise interval check, labelled as such; they appear in the next section.

Findings & insights

The records below are copied by the builder from the claims lock and the study state; the prose after them cites them and never restates a total.

claims
18 locked in claims.lock
by strength
confirmed 6 · exploratory 12
by class
empirical-description 8 · mechanism-interpretation 3 · procedural-verdict 1 · research-discipline 6
errata
2 of 18 claims tagged · 2 erratum record(s) in the lock
locked at
84ca15a69233 · klein 2.2.0
label
confirmed
referee
PASS-WITH-NOTES — klein-referee (Claude Code subagent, model: claude-opus-5-5) · independent of the experimenter: yes

The verdicts

Grouped bars of exact-match for the direct and CoT arms on public items, the 50 originals, development twins and sealed twins; all bars are near 1.
Exact-match per arm and item block (public items and development and sealed twins under both arms; the 50 originals under CoT only), bars zero-based, from the per-item tables of E0002, E0003, E0004 and E0005. Both arms sit at the ceiling on every block, which is why a gain of the registered size was arithmetically out of reach. Close

The surprise: the “direct” arm is a terse chain of thought

[C5] The registered number-only instruction was not followed: only 4 of 300 public replies were a bare number, the direct arm’s median output was 112.5 tokens against 243 for CoT, and CoT wrote only 1.85 times the direct arm’s mean output tokens on public items (1.92 on sealed twins). What was compared is CoT against a terse CoT, not CoT against answering without written steps. The method card named this failure mode in advance; its quantitative form, CoT writing at least twenty times as many tokens, was the most informative prior that missed.

Overlaid step histograms of output tokens per call for the direct arm and the CoT arm.
Output tokens per call for every unique recorded call of the study (direct arm and CoT arm, all blocks, from the pinned call-ledger shards), vertical lines at the medians. The direct arm’s replies are shorter but nowhere near number-sized: it writes its working anyway. Close

Why the gain is hard to see: the ceiling

[C6, re-scoped by erratum E1] Both arms score between 0.95 and 0.985 in every cell, so the largest gain the public cell could have shown is one minus the direct score, 0.05. The gain was measured, with a tight interval; what the ceiling removed is headroom, and a gain as large as 0.10 was unreachable given the observed direct scores. Whether a compliant direct arm would reopen that headroom is an untested hypothesis, not a finding.

What the contamination probe saw, template by template

Histograms of the per-template gap for the development and the sealed contamination cells; most templates sit at zero.
Per-template gap (the original’s score minus the mean of its four twins) for the 50 templates, development cell E0003 and sealed cell E0006, counts zero-based. Almost every template shows no gap, so the mean gap is carried by a few templates; a single original is worth 0.02 of em_gap. Close

[C7, exploratory] The sign of a gap this small is set by serving noise on 50 originals: in the E0003 re-query three originals went from right to wrong and one from wrong to right, moving the originals’ score from 0.98 to 0.94. [C8, exploratory, unresolved beyond “noise”] The development-twin reversal (direct ahead by 0.025) did not survive on the sealed twins, where the arms tied, and the discordant twins sit in a few templates, which the cluster interval absorbs and McNemar does not.

Controls added after the first referee round (post-hoc, exploratory)

The headline results are nulls, so the record has to show that the scorer and interval code would have seen a gain if one existed. Neither control was registered; both were computed offline from the committed ledger and tables, with no model call.

Forest plot per cot_gain cell: the observed gain with its interval, a planted 0.05 gain and a planted 0.10 gain, each with its interval.
Post-hoc controls on the three cot_gain cells (public items, development twins, sealed twins): the observed gain with its 95% interval (dot) beside one seeded planted gain of 0.05 (square) and of 0.10 (diamond), x-axis spanning zero. Each plant is one seeded draw per block, not a power estimate; it shows the interval code responds to a planted shift, not that the scorer would credit a real CoT advantage at the reply level. Close

What the two controls do not do: neither plants an effect at the reply level, so neither can show that the scorer would credit a real CoT advantage that extraction might mangle. That part rests on the instrument check (the re-scored exact-match equals the notarized value in every cell and arm) and on the offline replay.

Multiple comparisons

[C18, post-hoc] With 4 comparisons in the cot_gain family and 2 in the contamination family, Bonferroni-level intervals (levels 0.9875 and 0.975) still exclude the registered 0.10 for every gain cell (upper ends 0.0367 public, 0.01 development twins, 0.055 sealed twins) and still fail to exclude 0.05 for either gap (upper ends 0.065 and 0.075). The families were drawn by the synthesist after the fact; the next test study should fix the family and guard at consultation.

What changes in practice

Caveats that limit every conclusion

Prompting and evaluation-harness advice

The change. A step-by-step instruction in place of a number-only instruction, scored by a fixed integer-extraction rule. The model and date. qwen-flash-2025-07-28, a hosted snapshot, queried 2026-11-03 at temperature 0, thinking off, 1024-token cap. The item set and its status. Public GSM8K (presumed contaminated) and procedurally generated twins. The paired effect. Indistinguishable from zero on every block. The cost. Roughly twice the output tokens; no price pinned. What this does not say. Nothing about another model, another snapshot or a thinking-mode configuration.

The executed source, in three layers

The harness has three layers, and keeping them apart is the first piece of advice. The instrument (prompts, decoding parameters, scorer) is library code outside the mutable surface, written before any prediction was registered and then left alone. The measurement machinery (the lanes, the intervals, the table writer) is also outside the surface. The cell, analyze.py, is the only mutable file, and it only chooses which items to measure and how to summarize them.

The instrument. Everything that decides what the model is asked and what counts as correct is in one short file:

lib/prompts.py · executed by E0002 (development, track cot_gain) at commit 90198c83e848 · sha256 518484438478…
"""The FIXED instrument: two prompt arms, the decoding parameters, the scorer.

Library code, outside `entrypoint.mutable`: a cell chooses WHICH items to
measure, never how they are asked or how answers are graded. Changing anything
here changes the instrument for every registered prediction at once, so it is
written before the predictions are registered and then left alone.

The two arms differ in the instruction only:

* ``direct`` — "Answer with the final number only." — the model must do the
  arithmetic without writing it down;
* ``cot``    — "Solve the problem step by step, then give the final number after
  'Answer:'." — chain-of-thought (Wei et al. 2022).

Decoding is greedy (``temperature: 0``) with the provider's thinking mode OFF, so
the only reasoning a CoT response contains is the reasoning it prints.

The scorer: the number after the LAST ``Answer:`` / ``####`` marker; failing that,
the last number in the response. Thousands commas and an all-zero decimal tail
(``18.0``, ``45.00``) are normalized; anything else with a fractional part is not
an integer and scores 0. The comparison is integer equality with the gold.
"""

from __future__ import annotations

import re

#: The two arms. ``{question}`` is the item text, verbatim.
ARMS: dict[str, str] = {
    "direct": "Answer with the final number only.\n\nQuestion: {question}\nAnswer:",
    "cot": (
        "Solve the problem step by step, then give the final number after 'Answer:'."
        "\n\nQuestion: {question}"
    ),
}

#: Decoding parameters, identical for both arms. ``enable_thinking`` is the
#: DashScope (OpenAI-compatible) switch for Qwen's hidden reasoning mode.
PARAMS: dict[str, object] = {"temperature": 0.0, "max_tokens": 1024, "enable_thinking": False}


def messages(arm: str, question: str) -> list[dict[str, str]]:
    """The single-turn chat for one item under one arm."""
    if arm not in ARMS:
        raise ValueError(f"unknown arm {arm!r}; choose one of {sorted(ARMS)}")
    return [{"role": "user", "content": ARMS[arm].format(question=question)}]


# --------------------------------------------------------------------------
# The scorer
# --------------------------------------------------------------------------

#: An answer marker: "Answer:" / "answer =" (any case) or GSM8K's "####".
_MARKER = re.compile(r"answer\s*[:=]|####", re.IGNORECASE)

#: A number: optional sign, thousands groups or plain digits, optional decimals.
#: Not preceded by a digit or a point (so "10-3" yields 10 and 3, never -3), and a
#: comma group only counts when exactly three digits follow it ("1,2345" is 1 and 2345).
_NUMBER = re.compile(r"(?<![\d.])-?(?:\d{1,3}(?:,\d{3})+(?!\d)|\d+)(?:\.\d+)?")


def _to_int(token: str) -> int | None:
    """``"1,210"`` -> 1210, ``"18.00"`` -> 18, ``"2.5"`` -> None (not an integer)."""
    text = token.replace(",", "")
    whole, _, fraction = text.partition(".")
    if fraction and fraction.strip("0"):
        return None
    return int(whole)


def extract(response: str | None) -> int | None:
    """The integer a response commits to, or None when it commits to none."""
    text = response or ""
    markers = list(_MARKER.finditer(text))
    if markers:
        after = _NUMBER.search(text, markers[-1].end())
        if after:
            return _to_int(after.group())
    numbers = _NUMBER.findall(text)
    return _to_int(numbers[-1]) if numbers else None


def exact_match(response: str | None, answer: int | str) -> int:
    """1 when the extracted integer equals the gold answer, else 0."""
    got = extract(response)
    return int(got is not None and got == int(str(answer).replace(",", "").strip()))

Two things in it deserve a second look. The scorer falls back to the last number in the reply when there is no Answer: marker. That is a sensible rule for chain-of-thought, and it is also exactly why a direct arm that ignores its instruction is scored without any warning: it silently becomes a different arm. The only way this study saw it was by auditing the replies, not the scores. And the decoding parameters travel as a single dictionary, identical for both arms:

PARAMS = {"temperature": 0.0, "max_tokens": 1024, "enable_thinking": False}

The cap matters: a handful of CoT replies were cut at the token limit, so truncation can account for a few of the “direct-only” discordant items, and the study reports how many.

The measurement machinery. Intervals are percentile bootstraps with a fixed replicate count and seed; on twins the resampling unit is the template:

lib/measure.py · executed by E0002 (development, track cot_gain) at commit 90198c83e848 · sha256 62da1c55fc07…
"""The measurement machinery every cell of study 20 composes — NOT the mutable surface.

* **The index and the lanes.** :func:`read_index` reads the split index the
  CONTRACT names (``data.split.index`` under ``data.prepared_path``);
  item ids come only from ``kleinlib.data.load_items()``, which prints the
  ``split_fingerprint:`` line and honours the sealed dry run. A lane is a
  ``block`` of the index, intersected with the partition ``load_items`` handed
  back — so a cell can narrow what it was given, never widen it.
* **The intervals.** Percentile bootstrap, ``N_BOOT`` replicates, fixed
  ``BOOT_SEED``, ``CI_LEVEL``: a paired item bootstrap on independent GSM8K
  items, a paired CLUSTER bootstrap (whole templates resampled) on twin blocks,
  whose four instances of one template are not independent.
* **The table writer.** Fixed column order, ``%.6f`` floats, LF endings, no
  index; built but NOT written under ``KLEIN_SMOKE=1`` or a sealed dry run
  (either would leave an untracked file that blocks the next ``run-one``).
"""

from __future__ import annotations

import os
from collections.abc import Iterable, Mapping, Sequence
from pathlib import Path
from typing import Any

import numpy as np
import pandas as pd

from kleinlib.contract import load_contract
from kleinlib.data import index_path
from kleinlib.metrology import item_bootstrap, paired_bootstrap

#: Bootstrap replicates, seed and interval level — declared once, for every cell.
N_BOOT: int = 10_000
BOOT_SEED: int = 20261103
CI_LEVEL: float = 0.95

#: Blocks of the index (prepare.py writes exactly these).
BLOCK_ORIGINAL = "original"  # train: the 50 template-source GSM8K items
BLOCK_GSM8K = "gsm8k"  # development: 300 further GSM8K test items
BLOCK_TWIN_DEV = "twin_dev"  # development: twins, seed 20261104
BLOCK_TWIN_SEALED = "twin_sealed"  # test: twins, seed 20261105 — SEALED
TWIN_BLOCKS: tuple[str, ...] = (BLOCK_TWIN_DEV, BLOCK_TWIN_SEALED)

#: Under KLEIN_SMOKE=1 a cell looks at this many items / templates only.
SMOKE_ITEMS: int = 8
SMOKE_TEMPLATES: int = 3


def study_dir() -> Path:
    """This study's directory — the parent of `lib/`."""
    return Path(__file__).resolve().parent.parent


def smoke() -> bool:
    return os.environ.get("KLEIN_SMOKE") == "1"


def sealed_dry_run() -> bool:
    """True inside `klein run-one --final-test --dry-run` (served development data)."""
    return (
        os.environ.get("KLEIN_EVALUATION_KIND") == "final_test"
        and os.environ.get("KLEIN_SEALED_DRYRUN") == "1"
    )


def evaluation_kind() -> str:
    """``development`` or ``final_test`` — set by `klein run-one`, never chosen here."""
    return os.environ.get("KLEIN_EVALUATION_KIND") or "development"


def read_index() -> pd.DataFrame:
    """The split index (`data/prepared/index.csv`), indexed by item id, all text.

    ``answer`` is parsed to int; ``template`` is ``""`` for GSM8K-only items.
    """
    path = index_path(study_dir(), load_contract(study_dir()))
    if path is None or not path.is_file():
        raise FileNotFoundError(f"no split index at {path} — run prepare.py first")
    frame = pd.read_csv(path, dtype=str, keep_default_na=False)
    frame["answer"] = frame["answer"].astype(int)
    return frame.set_index("id", drop=True)


def lane(index: pd.DataFrame, ids: Sequence[str], blocks: Iterable[str]) -> list[str]:
    """The ids of ``ids`` (a partition from ``load_items``) whose block is in ``blocks``."""
    wanted = set(blocks)
    return [item for item in ids if index.at[item, "block"] in wanted]


def twin_lane(index: pd.DataFrame, eval_ids: Sequence[str]) -> tuple[list[str], str]:
    """The twin block of the evaluation partition, and its name.

    twin_dev on development and on a sealed DRY RUN (which is served the
    development partition); twin_sealed on the one real sealed run, whose
    partition must then hold nothing else.
    """
    ids = lane(index, eval_ids, TWIN_BLOCKS)
    names = sorted({index.at[item, "block"] for item in ids})
    if len(names) != 1:
        raise RuntimeError(f"expected exactly one twin block in the evaluation partition, got {names}")
    if evaluation_kind() == "final_test" and not sealed_dry_run():
        if names != [BLOCK_TWIN_SEALED] or len(ids) != len(eval_ids):
            raise RuntimeError("the sealed partition must be exactly the twin_sealed block")
    return ids, names[0]


# --------------------------------------------------------------------------
# Intervals
# --------------------------------------------------------------------------


def _percentile_interval(values: Sequence[float]) -> tuple[float, float]:
    tail = (1.0 - CI_LEVEL) / 2.0
    low, high = np.quantile(np.asarray(values, dtype=float), [tail, 1.0 - tail])
    return float(low), float(high)


def paired_difference_ci(
    a: Sequence[float], b: Sequence[float], clusters: Sequence[str] | None = None
) -> tuple[float, float]:
    """Percentile CI of ``mean(a) - mean(b)`` on the same rows, in the same order.

    ``clusters=None`` resamples rows (``metrology.paired_bootstrap``: one index
    vector drawn per replicate and applied to both series). With ``clusters``
    whole clusters are resampled (``metrology.item_bootstrap`` with ``groups=``
    on the per-row differences, a ratio estimator, so unequal cluster sizes are
    handled): the paired cluster bootstrap a twin block needs.
    """
    left = np.asarray(a, dtype=float)
    right = np.asarray(b, dtype=float)
    if clusters is None:
        estimate = paired_bootstrap(left, right, n_boot=N_BOOT, seed=BOOT_SEED)
    else:
        estimate = item_bootstrap(left - right, n_boot=N_BOOT, seed=BOOT_SEED, groups=list(clusters))
    return _percentile_interval(estimate.values)


# --------------------------------------------------------------------------
# The deterministic table writer
# --------------------------------------------------------------------------


def table_text(columns: Sequence[str], rows: Iterable[Mapping[str, Any]]) -> str:
    """The exact bytes of a pinned table: fixed columns, ``%.6f``, tab-separated, LF."""
    frame = pd.DataFrame(list(rows), columns=list(columns))
    return frame.to_csv(index=False, sep="\t", float_format="%.6f", lineterminator="\n")


def write_table(
    relative_path: str, columns: Sequence[str], rows: Iterable[Mapping[str, Any]]
) -> str | None:
    """Write a pinned ``artifact:`` table; return its study-relative path, or None.

    The text is always BUILT, so a formatting bug surfaces in the smoke check. It
    is WRITTEN only on a real run: under ``KLEIN_SMOKE=1`` nothing may be
    written, and a sealed dry run that left an untracked table behind would make
    the real sealed run refuse its dirty tree.
    """
    text = table_text(columns, rows)
    if smoke() or sealed_dry_run():
        return None
    path = study_dir() / relative_path
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8", newline="")
    return Path(relative_path).as_posix()

The public cell, as run (E0002). The cell below is the exact analyze.py the notary committed before the anchor ran. Read run_cot_gain: one ledger-backed call per item per arm, the scorer applied to the recorded replies, the paired table written, then the paired interval and McNemar’s exact test. Everything the model returned goes through CallLedger, so the call is pinned and a re-run answers from the shard.

analyze.py · executed by E0002 (development, track cot_gain) at commit 90198c83e848 · sha256 417acf82e572…
"""One measurement cell of study 20 (the mutable surface).

`klein run-one --track <track>` sets ``KLEIN_TRACK``; the cell measures that
track's estimand on the partition the contract hands it. ``CELL`` chooses the
LANE only — the instrument (prompts, decoding, scorer: `lib/prompts.py`), the
intervals and the table writer (`lib/measure.py`) are fixed outside this file.

* ``cot_gain`` — exact-match gain of the ``cot`` arm over the ``direct`` arm,
  paired on the same items. Development lane: ``CELL["block"]`` — ``gsm8k`` (P1,
  P2) or ``twin_dev`` (P4). A sealed run (``KLEIN_EVALUATION_KIND=final_test``)
  ignores ``CELL`` and measures the twin block ``load_items()`` hands back:
  twin_sealed (P5), or twin_dev on the sealed dry run. Interval: paired item
  bootstrap on GSM8K items, paired cluster bootstrap (whole templates) on twins.
* ``contamination`` — CoT arm only. Per template: the original item's score
  minus the mean over its twins in the evaluated twin block (twin_dev on
  development, P3; twin_sealed when sealed, P6). Primary ``em_gap`` = mean of
  those per-template gaps; interval: bootstrap over templates. ``CELL`` is
  ignored.

Every model call goes through ``CallLedger.from_contract`` (pinned under
`calls/`); a sealed dry run is answered from the ledger only (offline), so the
rehearsal spends nothing and leaves no new shard behind.
"""

from __future__ import annotations

import os
import time

import numpy as np
from lib import measure
from lib.prompts import PARAMS, exact_match, messages

from kleinlib.calls import CallLedger
from kleinlib.data import load_items
from kleinlib.eval import evaluate_estimate
from kleinlib.metrology import mcnemar_exact

SMOKE = measure.smoke()
EXPERIMENT_ID = os.environ.get("KLEIN_EXPERIMENT_ID") or ("SMOKE" if SMOKE else None)
TRACK = os.environ.get("KLEIN_TRACK")
TRACKS = ("cot_gain", "contamination")

# The lane of this cell (cot_gain, development only): "gsm8k" (P1, P2) | "twin_dev" (P4).
CELL = {"block": "gsm8k"}


def _summary(ledger: CallLedger) -> dict[str, float]:
    """Call accounting as ``calls_*`` keys (machine keys: replication ignores them)."""
    return {
        key if key.startswith("calls_") else f"calls_{key}": value
        for key, value in ledger.summary().items()
    }


def _ask(ledger: CallLedger, arm: str, questions: list[str]) -> list[str]:
    return ledger.chat_many([messages(arm, q) for q in questions], **PARAMS)


def run_cot_gain(t0: float, eval_ids: list[str], index) -> None:
    if measure.evaluation_kind() == "final_test":
        ids, block = measure.twin_lane(index, eval_ids)
    else:
        block = CELL["block"]
        if block not in (measure.BLOCK_GSM8K, measure.BLOCK_TWIN_DEV):
            raise SystemExit(f"CELL['block'] must be 'gsm8k' or 'twin_dev', got {block!r}")
        ids = measure.lane(index, eval_ids, [block])
    if SMOKE:
        ids = ids[: measure.SMOKE_ITEMS]
    if len(ids) < 2:
        raise RuntimeError(f"lane {block!r} holds {len(ids)} items")
    items = index.loc[ids]
    twins = block in measure.TWIN_BLOCKS
    print(f"cell: track=cot_gain block={block} items={len(ids)} arms=direct,cot "
          f"interval={'cluster bootstrap over templates' if twins else 'paired item bootstrap'}")

    offline = True if measure.sealed_dry_run() else None
    with CallLedger.from_contract(".", smoke_response="Answer: 0", offline=offline) as ledger:
        questions = items["question"].tolist()
        direct = _ask(ledger, "direct", questions)
        cot = _ask(ledger, "cot", questions)
        answers = items["answer"].tolist()
        score_direct = np.array([exact_match(r, a) for r, a in zip(direct, answers, strict=True)])
        score_cot = np.array([exact_match(r, a) for r, a in zip(cot, answers, strict=True)])

        table = measure.write_table(
            f"tables/cot_gain_{EXPERIMENT_ID}.tsv",
            ["item_id", "block", "template", "answer", "score_direct", "score_cot"],
            (
                {"item_id": item_id, "block": row["block"], "template": row["template"],
                 "answer": int(row["answer"]), "score_direct": int(d), "score_cot": int(c)}
                for (item_id, row), d, c in zip(items.iterrows(), score_direct, score_cot, strict=True)
            ),
        )
        if table:
            print(f"artifact: {table}")

        em_direct = float(score_direct.mean())
        em_cot = float(score_cot.mean())
        gain = em_cot - em_direct
        clusters = items["template"].tolist() if twins else None
        ci_low, ci_high = measure.paired_difference_ci(score_cot, score_direct, clusters)
        test = mcnemar_exact(score_cot, score_direct)
        evaluate_estimate(
            gain, ci_low, ci_high, len(ids),
            exp_id=EXPERIMENT_ID, metric_name="em_gain", metric_goal="higher",
            extra={
                "em_direct": round(em_direct, 6),
                "em_cot": round(em_cot, 6),
                "n_items": len(ids),
                "n_clusters": len(set(clusters)) if clusters else len(ids),
                "mcnemar_p": test["p_value"],
                "discordant_cot_only": int(test["n10"]),
                "discordant_direct_only": int(test["n01"]),
                **_summary(ledger),
            },
            study_dir=None if SMOKE else ".",
            t0=t0,
        )


def run_contamination(t0: float, fit_ids: list[str], eval_ids: list[str], index) -> None:
    twin_ids, block = measure.twin_lane(index, eval_ids)
    original_ids = measure.lane(index, fit_ids, [measure.BLOCK_ORIGINAL])
    originals = index.loc[original_ids]
    templates = originals["template"].tolist()  # template order = selection order
    if SMOKE:
        templates = templates[: measure.SMOKE_TEMPLATES]
    originals = originals[originals["template"].isin(templates)]
    twin_items = index.loc[twin_ids]
    twin_items = twin_items[twin_items["template"].isin(templates)]
    if sorted(set(twin_items["template"])) != sorted(templates) or len(originals) != len(templates):
        raise RuntimeError("every template needs exactly one original and at least one twin")
    print(f"cell: track=contamination block={block} templates={len(templates)} "
          f"twins={len(twin_items)} arm=cot interval=bootstrap over templates")

    offline = True if measure.sealed_dry_run() else None
    with CallLedger.from_contract(".", smoke_response="Answer: 0", offline=offline) as ledger:
        responses = _ask(ledger, "cot", originals["question"].tolist() + twin_items["question"].tolist())
        n_orig = len(originals)
        orig_scores = dict(zip(
            originals["template"],
            (exact_match(r, a) for r, a in zip(responses[:n_orig], originals["answer"], strict=True)),
            strict=True,
        ))
        twin_scores = [exact_match(r, a) for r, a in zip(responses[n_orig:], twin_items["answer"], strict=True)]
        by_template: dict[str, list[int]] = {t: [] for t in templates}
        for template, score in zip(twin_items["template"], twin_scores, strict=True):
            by_template[template].append(score)

        rows = [
            {"template": t, "source_id": originals.index[originals["template"] == t][0],
             "score_original": int(orig_scores[t]),
             "twin_mean": float(np.mean(by_template[t])), "twin_n": len(by_template[t])}
            for t in templates
        ]
        table = measure.write_table(
            f"tables/contamination_{EXPERIMENT_ID}.tsv",
            ["template", "source_id", "score_original", "twin_mean", "twin_n"],
            rows,
        )
        if table:
            print(f"artifact: {table}")

        score_original = np.array([row["score_original"] for row in rows], dtype=float)
        twin_mean = np.array([row["twin_mean"] for row in rows], dtype=float)
        em_original = float(score_original.mean())
        em_twins = float(twin_mean.mean())  # template-weighted, so em_gap = em_original - em_twins
        gap = float(np.mean(score_original - twin_mean))
        ci_low, ci_high = measure.paired_difference_ci(score_original, twin_mean)
        evaluate_estimate(
            gap, ci_low, ci_high, len(templates),
            exp_id=EXPERIMENT_ID, metric_name="em_gap", metric_goal="lower",
            extra={
                "em_original": round(em_original, 6),
                "em_twins": round(em_twins, 6),
                "n_templates": len(templates),
                "n_twin_items": len(twin_items),
                **_summary(ledger),
            },
            study_dir=None if SMOKE else ".",
            t0=t0,
        )


def main() -> None:
    if EXPERIMENT_ID is None:
        raise SystemExit("run through `klein run-one` (or KLEIN_SMOKE=1 for a shape check)")
    if TRACK not in TRACKS:
        raise SystemExit(f"KLEIN_TRACK must be one of {TRACKS}, got {TRACK!r}")
    t0 = time.time()
    fit_ids, eval_ids = load_items()  # prints split_fingerprint (and sealed_dryrun when rehearsing)
    index = measure.read_index()
    if TRACK == "cot_gain":
        run_cot_gain(t0, eval_ids, index)
    else:
        run_contamination(t0, fit_ids, eval_ids, index)


if __name__ == "__main__":
    main()

The sealed gain cell (E0005). The same file at the commit of the sealed run. In a sealed run the cell ignores its lane setting and measures whatever twin block the contract hands back, so the sealed access could not be spent on the wrong block:

analyze.py · executed by E0005 (final_test, track cot_gain) at commit 30051467ba04 · sha256 370e6ba9bf07…
"""One measurement cell of study 20 (the mutable surface).

`klein run-one --track <track>` sets ``KLEIN_TRACK``; the cell measures that
track's estimand on the partition the contract hands it. ``CELL`` chooses the
LANE only — the instrument (prompts, decoding, scorer: `lib/prompts.py`), the
intervals and the table writer (`lib/measure.py`) are fixed outside this file.

* ``cot_gain`` — exact-match gain of the ``cot`` arm over the ``direct`` arm,
  paired on the same items. Development lane: ``CELL["block"]`` — ``gsm8k`` (P1,
  P2) or ``twin_dev`` (P4). A sealed run (``KLEIN_EVALUATION_KIND=final_test``)
  ignores ``CELL`` and measures the twin block ``load_items()`` hands back:
  twin_sealed (P5), or twin_dev on the sealed dry run. Interval: paired item
  bootstrap on GSM8K items, paired cluster bootstrap (whole templates) on twins.
* ``contamination`` — CoT arm only. Per template: the original item's score
  minus the mean over its twins in the evaluated twin block (twin_dev on
  development, P3; twin_sealed when sealed, P6). Primary ``em_gap`` = mean of
  those per-template gaps; interval: bootstrap over templates. ``CELL`` is
  ignored.

Every model call goes through ``CallLedger.from_contract`` (pinned under
`calls/`); a sealed dry run is answered from the ledger only (offline), so the
rehearsal spends nothing and leaves no new shard behind.
"""

from __future__ import annotations

import os
import time

import numpy as np
from lib import measure
from lib.prompts import PARAMS, exact_match, messages

from kleinlib.calls import CallLedger
from kleinlib.data import load_items
from kleinlib.eval import evaluate_estimate
from kleinlib.metrology import mcnemar_exact

SMOKE = measure.smoke()
EXPERIMENT_ID = os.environ.get("KLEIN_EXPERIMENT_ID") or ("SMOKE" if SMOKE else None)
TRACK = os.environ.get("KLEIN_TRACK")
TRACKS = ("cot_gain", "contamination")

# The lane of this cell (cot_gain, development only): "gsm8k" (P1, P2) | "twin_dev" (P4).
CELL = {"block": "twin_dev"}


def _summary(ledger: CallLedger) -> dict[str, float]:
    """Call accounting as ``calls_*`` keys (machine keys: replication ignores them)."""
    return {
        key if key.startswith("calls_") else f"calls_{key}": value
        for key, value in ledger.summary().items()
    }


def _ask(ledger: CallLedger, arm: str, questions: list[str]) -> list[str]:
    return ledger.chat_many([messages(arm, q) for q in questions], **PARAMS)


def run_cot_gain(t0: float, eval_ids: list[str], index) -> None:
    if measure.evaluation_kind() == "final_test":
        ids, block = measure.twin_lane(index, eval_ids)
    else:
        block = CELL["block"]
        if block not in (measure.BLOCK_GSM8K, measure.BLOCK_TWIN_DEV):
            raise SystemExit(f"CELL['block'] must be 'gsm8k' or 'twin_dev', got {block!r}")
        ids = measure.lane(index, eval_ids, [block])
    if SMOKE:
        ids = ids[: measure.SMOKE_ITEMS]
    if len(ids) < 2:
        raise RuntimeError(f"lane {block!r} holds {len(ids)} items")
    items = index.loc[ids]
    twins = block in measure.TWIN_BLOCKS
    print(f"cell: track=cot_gain block={block} items={len(ids)} arms=direct,cot "
          f"interval={'cluster bootstrap over templates' if twins else 'paired item bootstrap'}")

    offline = True if measure.sealed_dry_run() else None
    with CallLedger.from_contract(".", smoke_response="Answer: 0", offline=offline) as ledger:
        questions = items["question"].tolist()
        direct = _ask(ledger, "direct", questions)
        cot = _ask(ledger, "cot", questions)
        answers = items["answer"].tolist()
        score_direct = np.array([exact_match(r, a) for r, a in zip(direct, answers, strict=True)])
        score_cot = np.array([exact_match(r, a) for r, a in zip(cot, answers, strict=True)])

        table = measure.write_table(
            f"tables/cot_gain_{EXPERIMENT_ID}.tsv",
            ["item_id", "block", "template", "answer", "score_direct", "score_cot"],
            (
                {"item_id": item_id, "block": row["block"], "template": row["template"],
                 "answer": int(row["answer"]), "score_direct": int(d), "score_cot": int(c)}
                for (item_id, row), d, c in zip(items.iterrows(), score_direct, score_cot, strict=True)
            ),
        )
        if table:
            print(f"artifact: {table}")

        em_direct = float(score_direct.mean())
        em_cot = float(score_cot.mean())
        gain = em_cot - em_direct
        clusters = items["template"].tolist() if twins else None
        ci_low, ci_high = measure.paired_difference_ci(score_cot, score_direct, clusters)
        test = mcnemar_exact(score_cot, score_direct)
        evaluate_estimate(
            gain, ci_low, ci_high, len(ids),
            exp_id=EXPERIMENT_ID, metric_name="em_gain", metric_goal="higher",
            extra={
                "em_direct": round(em_direct, 6),
                "em_cot": round(em_cot, 6),
                "n_items": len(ids),
                "n_clusters": len(set(clusters)) if clusters else len(ids),
                "mcnemar_p": test["p_value"],
                "discordant_cot_only": int(test["n10"]),
                "discordant_direct_only": int(test["n01"]),
                **_summary(ledger),
            },
            study_dir=None if SMOKE else ".",
            t0=t0,
        )


def run_contamination(t0: float, fit_ids: list[str], eval_ids: list[str], index) -> None:
    twin_ids, block = measure.twin_lane(index, eval_ids)
    original_ids = measure.lane(index, fit_ids, [measure.BLOCK_ORIGINAL])
    originals = index.loc[original_ids]
    templates = originals["template"].tolist()  # template order = selection order
    if SMOKE:
        templates = templates[: measure.SMOKE_TEMPLATES]
    originals = originals[originals["template"].isin(templates)]
    twin_items = index.loc[twin_ids]
    twin_items = twin_items[twin_items["template"].isin(templates)]
    if sorted(set(twin_items["template"])) != sorted(templates) or len(originals) != len(templates):
        raise RuntimeError("every template needs exactly one original and at least one twin")
    print(f"cell: track=contamination block={block} templates={len(templates)} "
          f"twins={len(twin_items)} arm=cot interval=bootstrap over templates")

    offline = True if measure.sealed_dry_run() else None
    with CallLedger.from_contract(".", smoke_response="Answer: 0", offline=offline) as ledger:
        responses = _ask(ledger, "cot", originals["question"].tolist() + twin_items["question"].tolist())
        n_orig = len(originals)
        orig_scores = dict(zip(
            originals["template"],
            (exact_match(r, a) for r, a in zip(responses[:n_orig], originals["answer"], strict=True)),
            strict=True,
        ))
        twin_scores = [exact_match(r, a) for r, a in zip(responses[n_orig:], twin_items["answer"], strict=True)]
        by_template: dict[str, list[int]] = {t: [] for t in templates}
        for template, score in zip(twin_items["template"], twin_scores, strict=True):
            by_template[template].append(score)

        rows = [
            {"template": t, "source_id": originals.index[originals["template"] == t][0],
             "score_original": int(orig_scores[t]),
             "twin_mean": float(np.mean(by_template[t])), "twin_n": len(by_template[t])}
            for t in templates
        ]
        table = measure.write_table(
            f"tables/contamination_{EXPERIMENT_ID}.tsv",
            ["template", "source_id", "score_original", "twin_mean", "twin_n"],
            rows,
        )
        if table:
            print(f"artifact: {table}")

        score_original = np.array([row["score_original"] for row in rows], dtype=float)
        twin_mean = np.array([row["twin_mean"] for row in rows], dtype=float)
        em_original = float(score_original.mean())
        em_twins = float(twin_mean.mean())  # template-weighted, so em_gap = em_original - em_twins
        gap = float(np.mean(score_original - twin_mean))
        ci_low, ci_high = measure.paired_difference_ci(score_original, twin_mean)
        evaluate_estimate(
            gap, ci_low, ci_high, len(templates),
            exp_id=EXPERIMENT_ID, metric_name="em_gap", metric_goal="lower",
            extra={
                "em_original": round(em_original, 6),
                "em_twins": round(em_twins, 6),
                "n_templates": len(templates),
                "n_twin_items": len(twin_items),
                **_summary(ledger),
            },
            study_dir=None if SMOKE else ".",
            t0=t0,
        )


def main() -> None:
    if EXPERIMENT_ID is None:
        raise SystemExit("run through `klein run-one` (or KLEIN_SMOKE=1 for a shape check)")
    if TRACK not in TRACKS:
        raise SystemExit(f"KLEIN_TRACK must be one of {TRACKS}, got {TRACK!r}")
    t0 = time.time()
    fit_ids, eval_ids = load_items()  # prints split_fingerprint (and sealed_dryrun when rehearsing)
    index = measure.read_index()
    if TRACK == "cot_gain":
        run_cot_gain(t0, eval_ids, index)
    else:
        run_contamination(t0, fit_ids, eval_ids, index)


if __name__ == "__main__":
    main()

The contamination cell (E0006). The same file again, executed on the contamination track. Note that every call in it is a ledger hit: the CoT answers for the 50 originals and the 200 sealed twins were recorded by E0003 and E0005, which is why this sealed cell and the sealed gain cell are one query of the model scored two ways.

analyze.py · executed by E0006 (final_test, track contamination) at commit e793d3fb32a9 · sha256 370e6ba9bf07…
"""One measurement cell of study 20 (the mutable surface).

`klein run-one --track <track>` sets ``KLEIN_TRACK``; the cell measures that
track's estimand on the partition the contract hands it. ``CELL`` chooses the
LANE only — the instrument (prompts, decoding, scorer: `lib/prompts.py`), the
intervals and the table writer (`lib/measure.py`) are fixed outside this file.

* ``cot_gain`` — exact-match gain of the ``cot`` arm over the ``direct`` arm,
  paired on the same items. Development lane: ``CELL["block"]`` — ``gsm8k`` (P1,
  P2) or ``twin_dev`` (P4). A sealed run (``KLEIN_EVALUATION_KIND=final_test``)
  ignores ``CELL`` and measures the twin block ``load_items()`` hands back:
  twin_sealed (P5), or twin_dev on the sealed dry run. Interval: paired item
  bootstrap on GSM8K items, paired cluster bootstrap (whole templates) on twins.
* ``contamination`` — CoT arm only. Per template: the original item's score
  minus the mean over its twins in the evaluated twin block (twin_dev on
  development, P3; twin_sealed when sealed, P6). Primary ``em_gap`` = mean of
  those per-template gaps; interval: bootstrap over templates. ``CELL`` is
  ignored.

Every model call goes through ``CallLedger.from_contract`` (pinned under
`calls/`); a sealed dry run is answered from the ledger only (offline), so the
rehearsal spends nothing and leaves no new shard behind.
"""

from __future__ import annotations

import os
import time

import numpy as np
from lib import measure
from lib.prompts import PARAMS, exact_match, messages

from kleinlib.calls import CallLedger
from kleinlib.data import load_items
from kleinlib.eval import evaluate_estimate
from kleinlib.metrology import mcnemar_exact

SMOKE = measure.smoke()
EXPERIMENT_ID = os.environ.get("KLEIN_EXPERIMENT_ID") or ("SMOKE" if SMOKE else None)
TRACK = os.environ.get("KLEIN_TRACK")
TRACKS = ("cot_gain", "contamination")

# The lane of this cell (cot_gain, development only): "gsm8k" (P1, P2) | "twin_dev" (P4).
CELL = {"block": "twin_dev"}


def _summary(ledger: CallLedger) -> dict[str, float]:
    """Call accounting as ``calls_*`` keys (machine keys: replication ignores them)."""
    return {
        key if key.startswith("calls_") else f"calls_{key}": value
        for key, value in ledger.summary().items()
    }


def _ask(ledger: CallLedger, arm: str, questions: list[str]) -> list[str]:
    return ledger.chat_many([messages(arm, q) for q in questions], **PARAMS)


def run_cot_gain(t0: float, eval_ids: list[str], index) -> None:
    if measure.evaluation_kind() == "final_test":
        ids, block = measure.twin_lane(index, eval_ids)
    else:
        block = CELL["block"]
        if block not in (measure.BLOCK_GSM8K, measure.BLOCK_TWIN_DEV):
            raise SystemExit(f"CELL['block'] must be 'gsm8k' or 'twin_dev', got {block!r}")
        ids = measure.lane(index, eval_ids, [block])
    if SMOKE:
        ids = ids[: measure.SMOKE_ITEMS]
    if len(ids) < 2:
        raise RuntimeError(f"lane {block!r} holds {len(ids)} items")
    items = index.loc[ids]
    twins = block in measure.TWIN_BLOCKS
    print(f"cell: track=cot_gain block={block} items={len(ids)} arms=direct,cot "
          f"interval={'cluster bootstrap over templates' if twins else 'paired item bootstrap'}")

    offline = True if measure.sealed_dry_run() else None
    with CallLedger.from_contract(".", smoke_response="Answer: 0", offline=offline) as ledger:
        questions = items["question"].tolist()
        direct = _ask(ledger, "direct", questions)
        cot = _ask(ledger, "cot", questions)
        answers = items["answer"].tolist()
        score_direct = np.array([exact_match(r, a) for r, a in zip(direct, answers, strict=True)])
        score_cot = np.array([exact_match(r, a) for r, a in zip(cot, answers, strict=True)])

        table = measure.write_table(
            f"tables/cot_gain_{EXPERIMENT_ID}.tsv",
            ["item_id", "block", "template", "answer", "score_direct", "score_cot"],
            (
                {"item_id": item_id, "block": row["block"], "template": row["template"],
                 "answer": int(row["answer"]), "score_direct": int(d), "score_cot": int(c)}
                for (item_id, row), d, c in zip(items.iterrows(), score_direct, score_cot, strict=True)
            ),
        )
        if table:
            print(f"artifact: {table}")

        em_direct = float(score_direct.mean())
        em_cot = float(score_cot.mean())
        gain = em_cot - em_direct
        clusters = items["template"].tolist() if twins else None
        ci_low, ci_high = measure.paired_difference_ci(score_cot, score_direct, clusters)
        test = mcnemar_exact(score_cot, score_direct)
        evaluate_estimate(
            gain, ci_low, ci_high, len(ids),
            exp_id=EXPERIMENT_ID, metric_name="em_gain", metric_goal="higher",
            extra={
                "em_direct": round(em_direct, 6),
                "em_cot": round(em_cot, 6),
                "n_items": len(ids),
                "n_clusters": len(set(clusters)) if clusters else len(ids),
                "mcnemar_p": test["p_value"],
                "discordant_cot_only": int(test["n10"]),
                "discordant_direct_only": int(test["n01"]),
                **_summary(ledger),
            },
            study_dir=None if SMOKE else ".",
            t0=t0,
        )


def run_contamination(t0: float, fit_ids: list[str], eval_ids: list[str], index) -> None:
    twin_ids, block = measure.twin_lane(index, eval_ids)
    original_ids = measure.lane(index, fit_ids, [measure.BLOCK_ORIGINAL])
    originals = index.loc[original_ids]
    templates = originals["template"].tolist()  # template order = selection order
    if SMOKE:
        templates = templates[: measure.SMOKE_TEMPLATES]
    originals = originals[originals["template"].isin(templates)]
    twin_items = index.loc[twin_ids]
    twin_items = twin_items[twin_items["template"].isin(templates)]
    if sorted(set(twin_items["template"])) != sorted(templates) or len(originals) != len(templates):
        raise RuntimeError("every template needs exactly one original and at least one twin")
    print(f"cell: track=contamination block={block} templates={len(templates)} "
          f"twins={len(twin_items)} arm=cot interval=bootstrap over templates")

    offline = True if measure.sealed_dry_run() else None
    with CallLedger.from_contract(".", smoke_response="Answer: 0", offline=offline) as ledger:
        responses = _ask(ledger, "cot", originals["question"].tolist() + twin_items["question"].tolist())
        n_orig = len(originals)
        orig_scores = dict(zip(
            originals["template"],
            (exact_match(r, a) for r, a in zip(responses[:n_orig], originals["answer"], strict=True)),
            strict=True,
        ))
        twin_scores = [exact_match(r, a) for r, a in zip(responses[n_orig:], twin_items["answer"], strict=True)]
        by_template: dict[str, list[int]] = {t: [] for t in templates}
        for template, score in zip(twin_items["template"], twin_scores, strict=True):
            by_template[template].append(score)

        rows = [
            {"template": t, "source_id": originals.index[originals["template"] == t][0],
             "score_original": int(orig_scores[t]),
             "twin_mean": float(np.mean(by_template[t])), "twin_n": len(by_template[t])}
            for t in templates
        ]
        table = measure.write_table(
            f"tables/contamination_{EXPERIMENT_ID}.tsv",
            ["template", "source_id", "score_original", "twin_mean", "twin_n"],
            rows,
        )
        if table:
            print(f"artifact: {table}")

        score_original = np.array([row["score_original"] for row in rows], dtype=float)
        twin_mean = np.array([row["twin_mean"] for row in rows], dtype=float)
        em_original = float(score_original.mean())
        em_twins = float(twin_mean.mean())  # template-weighted, so em_gap = em_original - em_twins
        gap = float(np.mean(score_original - twin_mean))
        ci_low, ci_high = measure.paired_difference_ci(score_original, twin_mean)
        evaluate_estimate(
            gap, ci_low, ci_high, len(templates),
            exp_id=EXPERIMENT_ID, metric_name="em_gap", metric_goal="lower",
            extra={
                "em_original": round(em_original, 6),
                "em_twins": round(em_twins, 6),
                "n_templates": len(templates),
                "n_twin_items": len(twin_items),
                **_summary(ledger),
            },
            study_dir=None if SMOKE else ".",
            t0=t0,
        )


def main() -> None:
    if EXPERIMENT_ID is None:
        raise SystemExit("run through `klein run-one` (or KLEIN_SMOKE=1 for a shape check)")
    if TRACK not in TRACKS:
        raise SystemExit(f"KLEIN_TRACK must be one of {TRACKS}, got {TRACK!r}")
    t0 = time.time()
    fit_ids, eval_ids = load_items()  # prints split_fingerprint (and sealed_dryrun when rehearsing)
    index = measure.read_index()
    if TRACK == "cot_gain":
        run_cot_gain(t0, eval_ids, index)
    else:
        run_contamination(t0, fit_ids, eval_ids, index)


if __name__ == "__main__":
    main()

No verifier is declared for this study: the scorer is a deterministic rule, not an LLM judge, so there is no separate checker whose hash was fixed at the method gate. That is a limit, not an omission to hide.

Eight lessons, each with the run that paid for it

  1. Audit the direct arm’s compliance from the ledger before reading any gain [C9]. The share of bare-number replies and output tokens per item, against the CoT arm. Here, 4 of 300 replies were bare; the direct arm’s median output was 112.5 tokens against 243. (E0002.)

  2. Check the headroom before you register a gain threshold [C10]. A gain cannot exceed one minus the direct score; at a direct score of 0.95 a registered gain of 0.10 could not be reached. Measure the direct score first, from a pilot or from items off the ceiling. (E0002.)

  3. Size a template-paired contamination probe to the gap it must resolve [C11]. Fifty templates gave interval widths of 0.075 and 0.105, so a gap of 0.05 could be neither detected nor excluded. Roughly four times the templates halves the interval. (E0003, E0006.)

  4. Treat cells that share ledger entries as one measurement [C12]. The ledger’s de-duplication makes a study cheap and replayable; it also couples the cells, and the findings must say which. (E0006.)

  5. Never count a replay as a replication [C13]. The offline replay reproduced with a difference of 0 because it re-scored the same recorded answers; the salted re-query changed 9 of 600 item-arm scores and moved the gain by 0.0167.

  6. On twin blocks, report the cluster bootstrap over templates, not McNemar’s test [C14]. Four twins of one template are not independent; McNemar’s p of 0.125 on the development twins overstates the evidence.

  7. Expect a sign flip when the effect is below the serving noise. Temperature 0 on a hosted model is not determinism. One flipped original is worth 0.02 of em_gap on 50 templates, so a handful of flips reverses a gap this small.

  8. Rate limits are a harness fault, not a result. The first anchor run crashed on an HTTP rate-limit after almost all calls were pinned; the pinned shard made the re-run nearly free. Lower the worker count on a shared account and let the ledger’s cache do the rest.

Pitfalls and war stories

Next steps & references

What to try next

  1. Make the direct arm direct, then re-measure the gain. A new study with an enforced bare-number arm (a token cap of a few tokens, or a response-format constraint) and compliance itself as a registered prediction, on the same public items and twin blocks. It is the cheapest test of whether the ceiling belongs to the instrument or to the model.
  2. Move off the ceiling. Repeat the paired comparison on items where the direct arm scores well below 0.95 (longer chains, harder re-instantiations) so that a registered gain of 0.10 is reachable.
  3. Power the contamination probe. Roughly four times the templates, with magnitude-matched twins, and the direct arm also run on the originals. Register the gap rule on the interval’s upper end, not the point estimate.
  4. Measure serving noise as the floor. At least three salted re-queries of one cell, recorded as fit noise. This study’s minimum deltas are pre-registered replication tolerances, not measured floors.

References

Every entry below is marked verified in the study’s method card (each resolved at its source and matched on title); none is unverified.