File size: 24,398 Bytes
7ffaec7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
"""recompute_entry02.py: recomputes entry 02's class and every number in its results table offline, from the released
files alone.

No GPU, no simulator, no network: Python 3 and NumPy. It reads, under results/entry-02/:
  gpu/*.json                       every evaluation block of the repaired attempt (H, Z, identity, transport, M0 on banks
                                   4000 and 1000, the three S selections, S on bank 1000, the fallback with its snapshots)
  gpu/SHA256SUMS.txt               the hashes those blocks had on the GPU machine
  inputs/identity_reference.json   the bound step-0a record the identity arm must reproduce (and the step-0a GPU cost)
  gait_search.json                 the CPU gait screen (walkability, first reference)
  fallback_snapshot_checks.jsonl   the append-only counter checks the fallback wrote as it ran
  admission_ledger.jsonl           the cumulative GPU ledger of both attempts and the rehearsal
  launch_evidence.txt              the job log lines (the final ledger the wrapper printed)
  stage0.json                      the repaired attempt's own record, cross-checked against everything above
  incomplete-first-attempt/        the first attempt's record and ledger (history: its class only, never its numbers)
  repair/entry2-stage0-r1-import.jsonl   the ledger imported into the repaired attempt
and does three things:
  1. rebuilds the decision record from the evaluation blocks (identity and transport compared episode by episode,
     returns and action hashes; S chosen; every counter check recomputed from the frozen snapshot rule) and checks it
     equals the record stage0.json carries;
  2. applies the registered rule (entry2_stage0_run.decide, which calls entry2_stage0_logic.stage0) to the rebuilt record,
     and separately recomputes the consequence rule, T, the walkability bar, the fallback selection and the means with
     code written here from the design text;
  3. recomputes the GPU cost from the ledger and the step-0a record.
The code checks (slot map, non-mutation, receiver XML hash) and the pilot timings need the simulator or the GPU; they are
taken as recorded and named as such in the output. Exits 1 on any disagreement.

Usage (from the package root or from scripts/):
    python3 scripts/recompute_entry02.py [path/to/results/entry-02]
"""
import calendar
import hashlib
import json
import math
import os
import re
import sys
import time

import numpy as np

import entry2_receiver as RX
import entry2_stage0_logic as L
import entry2_stage0_run as RUN

HERE = os.path.dirname(os.path.abspath(__file__))
DEFAULT_ENTRY_DIR = os.path.join(HERE, "..", "results", "entry-02")
AGREEMENT_TOLERANCE = 1e-9
SECONDS_PER_HOUR = 3600.0
ISO_UTC = "%Y-%m-%dT%H:%M:%SZ"
FALLBACK_STEPS = L.FALLBACK_SNAPSHOT_STEPS
PILOT_LAST_STEP = RUN.PILOT_STEPS
GPU_BLOCKS = {   # name: (bank, number of episodes)
    "H": (L.BANK_CONSEQUENCE, L.EPISODES), "Z": (L.BANK_CONSEQUENCE, L.EPISODES),
    "identity": (L.BANK_CONSEQUENCE, L.EPISODES), "transport": (L.BANK_CONSEQUENCE, L.EPISODES),
    "M0_4000": (L.BANK_NOISE, L.EPISODES), "M0_1000": (L.BANK_STAGE1, L.EPISODES), "S_1000": (L.BANK_STAGE1, L.EPISODES),
    **{f"S_selection_{e}": (L.BANK_S_SELECTION, L.EPISODES) for e in L.S_CANDIDATES},
}
FINAL_LEDGER_LINE = re.compile(r"admission ledger after stage 0 [^:]*: (\{.*\})")


class Inconsistent(ValueError):
    """Released files that contradict each other."""


def load_json(path):
    with open(path) as f:
        return json.load(f)


def read_text(path):
    with open(path) as f:
        return f.read()


def sha256_file(path):
    with open(path, "rb") as f:
        return hashlib.sha256(f.read()).hexdigest()


def load_entry(entry_dir):
    """Every released file the recomputation reads, by role."""
    gpu = os.path.join(entry_dir, "gpu")
    first = os.path.join(entry_dir, "incomplete-first-attempt")
    return {
        "dir": entry_dir,
        "record": load_json(os.path.join(entry_dir, "stage0.json")),
        "gpu": {n: load_json(os.path.join(gpu, f"{n}.json")) for n in list(GPU_BLOCKS) + ["fallback"]},
        "gpu_sums": read_text(os.path.join(gpu, "SHA256SUMS.txt")),
        "identity_reference": load_json(os.path.join(entry_dir, "inputs", "identity_reference.json")),
        "gait": load_json(os.path.join(entry_dir, "gait_search.json")),
        "fallback_checks": [json.loads(x) for x in read_text(os.path.join(entry_dir, "fallback_snapshot_checks.jsonl"))
                            .splitlines() if x.strip()],
        "ledger_text": read_text(os.path.join(entry_dir, "admission_ledger.jsonl")),
        "launch_evidence": read_text(os.path.join(entry_dir, "launch_evidence.txt")),
        "first_record": load_json(os.path.join(first, "stage0.json")),
        "first_ledger_text": read_text(os.path.join(first, "admission_ledger.jsonl")),
        "import_ledger_text": read_text(os.path.join(entry_dir, "repair", "entry2-stage0-r1-import.jsonl")),
    }


def utc_seconds(stamp):
    return calendar.timegm(time.strptime(stamp, ISO_UTC))


# ---------------------------------------------------------------------------------------------------------------------
# 1. The evaluation blocks and the rebuilt decision record.
def check_gpu_hashes(entry_dir, sums_text):
    """Every gpu/*.json against the SHA256SUMS.txt written on the GPU machine (the blocks are released byte-identical)."""
    bad = []
    for line in sums_text.splitlines():
        if not line.strip():
            continue
        digest, name = line.split()
        if sha256_file(os.path.join(entry_dir, "gpu", name)) != digest:
            bad.append(name)
    return bad


def check_block(name, block, bank, n):
    """Bank, episode ids, seeds, decisions and finiteness of one evaluation block, and its stored means."""
    eps = block["per_episode"]
    if block.get("bank") != bank or [e["episode"] for e in eps] != list(range(n)):
        raise Inconsistent(f"{name}: bank {block.get('bank')} episodes {[e['episode'] for e in eps]}, expected bank {bank} "
                           f"episodes 0 to {n - 1}")
    for e in eps:
        if e["seed"] != L.bank_seed(bank, e["episode"]) or e["decisions"] != L.DECISIONS:
            raise Inconsistent(f"{name} episode {e['episode']}: seed {e['seed']} decisions {e['decisions']}")
        if not (math.isfinite(e["return"]) and math.isfinite(e["ud"]) and RUN.is_actions_sha256(e["actions_sha256"])):
            raise Inconsistent(f"{name} episode {e['episode']}: nonfinite value or missing action hash")
    for key, field in (("mean_return", "return"), ("mean_ud", "ud")):
        if abs(float(np.mean([e[field] for e in eps])) - block[key]) > AGREEMENT_TOLERANCE:
            raise Inconsistent(f"{name}: stored {key} {block[key]} is not the mean of its episodes")


def fallback_evaluations(fb):
    """The fallback's snapshot blocks (bank 5000, eps 0 to 4) and its final block (bank 6000, eps 0 to 9)."""
    ev = fb["evaluations"]
    for step in FALLBACK_STEPS:
        check_block(f"fallback snapshot {step}", ev[f"snapshot_{step}"], L.BANK_REF_SELECTION, L.FALLBACK_SELECTION_EPISODES)
        scores = [e["ud"] for e in ev[f"snapshot_{step}"]["per_episode"]]
        if scores != fb["scores"][str(step)]:
            raise Inconsistent(f"fallback snapshot {step}: stored selection scores are not its episodes' UD")
    final = [k for k in ev if not k.startswith("snapshot_")]
    if len(final) != 1:
        raise Inconsistent(f"fallback: expected one final evaluation block, found {final}")
    check_block("fallback final", ev[final[0]], L.BANK_REF_EVALUATION, L.EPISODES)
    return {s: [e["ud"] for e in ev[f"snapshot_{s}"]["per_episode"]] for s in FALLBACK_STEPS}, \
        [e["ud"] for e in ev[final[0]]["per_episode"]]


def fallback_checks_from_log(lines):
    """The append-only check log, each check recomputed from the frozen snapshot rule (not read from its 'matches')."""
    out = {}
    for x in lines:
        step = int(x["step"])
        if step in out:
            raise Inconsistent(f"fallback check log has step {step} twice")
        out[step] = RUN.counters_match_snapshot(step, x["check"]["observed"])
    return out


def pilots_recomputed(record):
    """Each pilot's counters against the frozen rule at its last step (the timings are taken as recorded)."""
    pilots = json.loads(json.dumps(record["pilot_detail"]))
    for arm in L.PILOT_ARMS:
        p = pilots[arm]
        if p["steps"] != PILOT_LAST_STEP:
            raise Inconsistent(f"pilot {arm} ran to step {p['steps']}, not {PILOT_LAST_STEP}")
        p["snapshot"] = RUN.counters_match_snapshot(p["steps"], p["counters"])
    return pilots


def rebuild_record(files):
    """The decision record, rebuilt from the released evaluation blocks; code checks taken as recorded."""
    gpu, record = files["gpu"], files["record"]
    for name, (bank, n) in GPU_BLOCKS.items():
        check_block(name, gpu[name], bank, n)
    ref = files["identity_reference"]
    ref_eps = {int(i): {"return": e["return"], "actions_sha256": e["actions_sha256"]} for i, e in ref["episodes"].items()}
    for i, e in ref["episodes"].items():
        if e["seed"] != L.bank_seed(ref["bank"], int(i)) or e["decisions"] != L.DECISIONS:
            raise Inconsistent(f"identity reference episode {i}: seed {e['seed']} decisions {e['decisions']}")
    identity = RUN.exact_match(RUN.episodes_by_index(gpu["identity"]), ref_eps)
    transport = RUN.exact_match(RUN.episodes_by_index(gpu["transport"]), RUN.episodes_by_index(gpu["Z"]))
    scores, final_ud = fallback_evaluations(gpu["fallback"])
    log_checks = fallback_checks_from_log(files["fallback_checks"])
    stored_checks = {int(k): v for k, v in gpu["fallback"]["snapshot_checks"].items()}
    if log_checks != stored_checks:
        raise Inconsistent("the fallback's append-only check log and fallback.json's snapshot_checks differ")
    best_step = RUN.fallback_best(scores)
    if best_step != gpu["fallback"]["best_step"]:
        raise Inconsistent(f"fallback selection recomputes to step {best_step}, fallback.json says {gpu['fallback']['best_step']}")
    pilots = pilots_recomputed(record)
    ev = {n: gpu[n] for n in GPU_BLOCKS}
    selection = {e: [x["return"] for x in gpu[f"S_selection_{e}"]["per_episode"]] for e in L.S_CANDIDATES}
    s_chosen = L.choose_s(selection)
    rebuilt = RUN.assemble_record(
        record["record"]["code_checks"], identity["reproduces"], transport["reproduces"], ev, s_chosen, pilots,
        {"eval_ud": files["gait"]["eval_ud"]}, {"eval_ud": final_ud},
        schedule=RUN.schedule_checks(pilots, True, log_checks), fallback_executed=True)
    return {"record": rebuilt, "identity": identity, "transport": transport, "fallback_scores": scores,
            "fallback_best_step": best_step, "pilots": pilots}


# ---------------------------------------------------------------------------------------------------------------------
# 2. The rule, from the design text (written here, not imported), beside the registered decide().
def bootstrap_interval(h, z, draws, seed):
    """95% percentile interval of mean(H_i - Z_i): the 10 episode pairs resampled with replacement, one draw call."""
    d = np.asarray(h, dtype=float) - np.asarray(z, dtype=float)
    idx = np.random.default_rng(seed).integers(0, d.size, size=(draws, d.size))
    lo, hi = np.percentile(d[idx].mean(axis=1), [2.5, 97.5])
    return float(lo), float(hi)


def t_operational(m0_a, m0_b, draws, seed, floor):
    """max(floor, 95th percentile of |mean1 - mean2|), two independent resamples of 10 from M0's 20 pooled returns."""
    pool = np.concatenate([np.asarray(m0_a, dtype=float), np.asarray(m0_b, dtype=float)])
    idx = np.random.default_rng(seed).integers(0, pool.size, size=(draws, 2, 10))
    m = pool[idx].mean(axis=2)
    q = float(np.percentile(np.abs(m[:, 0] - m[:, 1]), 95.0))
    return max(floor, q), q


def independent_reading(rebuilt, scores):
    """The numbers and the class, from the design's text: CONSEQUENTIAL iff mean Z <= 0.5 x mean H and the interval's
    lower end > 0; walkability passes iff a reference's bank-6000 mean UD >= 0.25 x mean UD(H)."""
    r = rebuilt
    mean_h, mean_z = float(np.mean(r["H_ud"])), float(np.mean(r["Z_ud"]))
    lo, hi = bootstrap_interval(r["H_ud"], r["Z_ud"], 10_000, 20261016)
    T, q95 = t_operational(r["M0_returns_3000"], r["M0_returns_4000"], 10_000, 20261017, 50.0)
    walk_bar = 0.25 * mean_h
    cpu_mean = float(np.mean(r["walk_cpu"]["eval_ud"]))
    fb_means = {s: float(np.mean(v)) for s, v in scores.items()}
    best = max(sorted(fb_means), key=lambda s: (fb_means[s], s))   # ties go to the later snapshot
    fb_mean = float(np.mean(r["walk_fallback"]["eval_ud"]))
    s_means = {e: float(np.mean(v)) for e, v in r["S_selection"].items()}
    s_chosen = max(L.S_CANDIDATES, key=lambda e: (s_means[e], -L.S_CANDIDATES.index(e)))
    walkable = cpu_mean >= walk_bar or fb_mean >= walk_bar
    consequential = mean_z <= 0.5 * mean_h and lo > 0
    if not (r["identity"] and r["transport"] and all(r["code_checks"].values()) and mean_h >= 12.5):
        outcome = "INVALID"
    elif not walkable:
        outcome = "REJECTED"
    elif not consequential:
        outcome = "NOT CONSEQUENTIAL"
    else:
        outcome = "PASS"
    return {"mean_H": mean_h, "mean_Z": mean_z, "Z_over_H": mean_z / mean_h, "half_H": 0.5 * mean_h,
            "consequence_ci_m": [lo, hi], "mean_H_minus_Z": float(np.mean(np.subtract(r["H_ud"], r["Z_ud"]))),
            "Z_condition": mean_z <= 0.5 * mean_h, "interval_condition": lo > 0, "T": T, "T_q95": q95,
            "S_chosen": s_chosen, "S_selection_means": s_means, "mean_M0_1000": float(np.mean(r["M0_returns_1000"])),
            "mean_S_1000": float(np.mean(r["S_returns_1000"])), "walk_bar_m": walk_bar, "walk_cpu_mean": cpu_mean,
            "fallback_selection_means": fb_means, "fallback_best_step": best, "walk_fallback_mean": fb_mean,
            "outcome": outcome}


# ---------------------------------------------------------------------------------------------------------------------
# 3. Cost.
def cost(files):
    """GPU hours charged across both attempts: step 0a (from the identity record's own start and finish) plus every
    gpu_attempt line of the final ledger; CPU wall time beside it, uncharged."""
    ref = files["identity_reference"]
    step0a_s = float(utc_seconds(ref["finished"]) - utc_seconds(ref["started"]))
    ledger = RUN.read_ledger(files["ledger_text"])
    first = RUN.read_ledger(files["first_ledger_text"])
    imported = RUN.read_ledger(files["import_ledger_text"])
    if ledger[:len(imported)] != imported or imported[:len(first)] != first:
        raise Inconsistent("the final ledger does not start with the imported ledger, or that with the first attempt's")
    gpu = [e for e in ledger if e["kind"] == RUN.LEDGER_GPU]
    if [e["gpu_dir"] for e in gpu] != ["gpu", "fallback-rehearsal", "fallback-rehearsal-launch-overhead", "gpu"]:
        raise Inconsistent(f"unexpected GPU ledger lines {[e['gpu_dir'] for e in gpu]}")
    final = RUN.admission_ledger(step0a_s, ledger, budget_h=L.ADMISSION_BUDGET_H)
    printed = [json.loads(m.group(1)) for m in FINAL_LEDGER_LINE.finditer(files["launch_evidence"])]
    return {"step0a_s": step0a_s, "first_attempt_s": gpu[0]["gpu_occupancy_s"],
            "rehearsal_s": gpu[1]["gpu_occupancy_s"], "rehearsal_overhead_s": gpu[2]["gpu_occupancy_s"],
            "repaired_attempt_s": gpu[3]["gpu_occupancy_s"],
            "charged_s": step0a_s + sum(e["gpu_occupancy_s"] for e in gpu), "charged_h": final["charged_gpu_h"],
            "remaining_h": final["remaining_h"], "budget_h": final["budget_h"],
            "cpu_uncharged_s": sum(e["wall_s"] for e in ledger if e["kind"] == RUN.LEDGER_CPU),
            "printed_final_charged_h": [p["charged_gpu_h"] for p in printed],
            "runner_pre_exit_charged_h": files["record"]["admission_ledger_at_finish"]["charged_gpu_h"],
            "repaired_wall_h": (utc_seconds(files["record"]["finished"]) - utc_seconds(files["record"]["started"]))
            / SECONDS_PER_HOUR}


# ---------------------------------------------------------------------------------------------------------------------
def recompute(files):
    """Everything entry 02 reports. Raises Inconsistent where released files contradict each other."""
    bad = check_gpu_hashes(files["dir"], files["gpu_sums"])
    if bad:
        raise Inconsistent(f"gpu blocks differ from SHA256SUMS.txt: {bad}")
    rb = rebuild_record(files)
    registered = RUN.decide(rb["record"])
    first = RUN.decide(files["first_record"]["record"])
    rec = files["record"]
    g = rec["receiver"]
    return {"rebuilt": rb, "registered": registered, "independent": independent_reading(rb["record"], rb["fallback_scores"]),
            "cost": cost(files), "first_attempt": {"outcome": first["outcome"], "reason": first["reason"]},
            "g_hash_ok": RX.g_sha256(g["g"]) == g["g_sha256"] == RX.g_sha256() and g["g"] == RX.G_PINNED,
            "non_mutation_after": rec["non_mutation_after"],
            "fingerprints_equal": rec["grown_fingerprint_before"] == rec["grown_fingerprint_after"],
            "checkpoint_unchanged": rec["checkpoint_sha256"] == rec["checkpoint_sha256_after"],
            "refusals": rec["refusals"], "stopped": rec["stopped"]}


def disagreements(table, record):
    """Every place the recomputed entry differs from what stage0.json and the first attempt's record say."""
    found = []

    def close(name, a, b):
        if a is None or b is None:   # an early INVALID or INCOMPLETE stops the registered rule before this number
            if a is not b:
                found.append(f"{name}: recomputed {a!r}, recorded {b!r}")
        elif abs(float(a) - float(b)) > AGREEMENT_TOLERANCE:
            found.append(f"{name}: recomputed {a!r}, recorded {b!r}")

    def same(name, a, b):
        if a != b:
            found.append(f"{name}: recomputed {a!r}, recorded {b!r}")

    s0, reg, ind = record["stage0"], table["registered"], table["independent"]
    same("rebuilt decision record", table["rebuilt"]["record"], record["record"])
    same("outcome (registered decide)", reg["outcome"], s0["outcome"])
    same("reason (registered decide)", reg["reason"], s0["reason"])
    same("outcome (independent reading)", ind["outcome"], s0["outcome"])
    for k in ("mean_H", "mean_Z", "T", "T_q95", "mean_M0_1000", "mean_S_1000", "walk_bar_m", "walk_cpu_mean",
              "walk_fallback_mean"):
        close(f"{k} (registered)", reg.get(k), s0.get(k))
        close(f"{k} (independent)", ind[k], s0.get(k))
    for i in (0, 1):
        close(f"interval end {i} (registered)", (reg.get("consequence_ci_m") or [None, None])[i], s0["consequence_ci_m"][i])
        close(f"interval end {i} (independent)", ind["consequence_ci_m"][i], s0["consequence_ci_m"][i])
    same("S chosen", ind["S_chosen"], s0["S_chosen"])
    same("fallback best step", ind["fallback_best_step"], record["fallback_detail"]["best_step"])
    same("identity check", {k: table["rebuilt"]["identity"][k] for k in record["identity_check"]}, record["identity_check"])
    same("transport check", {k: table["rebuilt"]["transport"][k] for k in record["transport_check"]},
         record["transport_check"])
    same("first attempt class", table["first_attempt"]["outcome"], "INCOMPLETE")
    for flag in ("g_hash_ok", "non_mutation_after", "fingerprints_equal", "checkpoint_unchanged"):
        same(flag, table[flag], True)
    same("refusals", table["refusals"], [])
    same("stopped", table["stopped"], None)
    c = table["cost"]
    close("step 0a seconds", c["step0a_s"], record["identity_record"]["step0a_gpu_s"])
    # The wrapper's final line appears twice in launch_evidence.txt (the job journal and the wrapper's own log).
    same("final ledger printed by the wrapper", sorted({round(x, 9) for x in c["printed_final_charged_h"]}),
         [round(c["charged_h"], 9)])
    return found


def render(table):
    reg, ind, c, rb = table["registered"], table["independent"], table["cost"], table["rebuilt"]
    h = lambda s: s / SECONDS_PER_HOUR
    lines = [
        "Entry 02, recomputed offline from the released files",
        f"  identity arm vs bound step-0a record     reproduces {rb['identity']['reproduces']}, "
        f"{rb['identity']['compared']} episodes, max |return diff| {rb['identity']['max_abs_return_diff']}, "
        f"action-hash mismatches {rb['identity']['action_hash_mismatch_episodes']}",
        f"  transport (P then P inverse) vs Z        reproduces {rb['transport']['reproduces']}, "
        f"{rb['transport']['compared']} episodes, max |return diff| {rb['transport']['max_abs_return_diff']}, "
        f"action-hash mismatches {rb['transport']['action_hash_mismatch_episodes']}",
        f"  H, healthy walker, mean upright distance {ind['mean_H']:.6f} m (positive check needs >= 12.5 m)",
        f"  Z, unadapted model on R, mean UD         {ind['mean_Z']:.6f} m ({ind['Z_over_H']:.6f} x H)",
        f"  consequence rule: mean Z <= 0.5 x mean H {ind['half_H']:.6f} m: {ind['Z_condition']}",
        f"  paired mean(H - Z)                       {ind['mean_H_minus_Z']:.6f} m",
        f"  95% paired bootstrap interval            [{ind['consequence_ci_m'][0]:.6f}, {ind['consequence_ci_m'][1]:.6f}] m;"
        f" lower end > 0: {ind['interval_condition']}",
        f"  walkability bar 0.25 x mean H            {ind['walk_bar_m']:.6f} m",
        f"  CPU gait reference, bank 6000 mean       {ind['walk_cpu_mean']:.6f} m (passes {ind['walk_cpu_mean'] >= ind['walk_bar_m']})",
        "  fallback selection, bank 5000 means      " + ", ".join(
            f"{s}: {m:.6f}" for s, m in sorted(ind["fallback_selection_means"].items())) + f" -> step {ind['fallback_best_step']}",
        f"  fallback reference, bank 6000 mean       {ind['walk_fallback_mean']:.6f} m (passes {ind['walk_fallback_mean'] >= ind['walk_bar_m']})",
        f"  T (stage-1 screen, return points)        {ind['T']:.6f} (95th percentile {ind['T_q95']:.6f})",
        "  S selection, bank 2000 mean returns      " + ", ".join(f"{e} {m:.3f}" for e, m in ind["S_selection_means"].items())
        + f" -> {ind['S_chosen']}",
        f"  M0 and S on bank 1000, mean return       {ind['mean_M0_1000']:.4f}, {ind['mean_S_1000']:.4f}",
        f"  code checks (taken as recorded)          {table['rebuilt']['record']['code_checks']}",
        f"  G permutation hash recomputes            {table['g_hash_ok']}; model and checkpoint unchanged after the run "
        f"{table['fingerprints_equal'] and table['checkpoint_unchanged'] and table['non_mutation_after']}",
        f"  registered class (decide)                {reg['outcome']}: {reg['reason']}",
        f"  independent reading                      {ind['outcome']}",
        f"  first attempt (history, class only)      {table['first_attempt']['outcome']}: {table['first_attempt']['reason']}",
        "  GPU cost, charged hours",
        f"    step 0a (bound identity record)        {h(c['step0a_s']):.6f}",
        f"    first attempt (INCOMPLETE)             {h(c['first_attempt_s']):.6f}",
        f"    GPU rehearsal of the repair            {h(c['rehearsal_s']):.6f} (+ launch overhead {h(c['rehearsal_overhead_s']):.6f})",
        f"    repaired attempt                       {h(c['repaired_attempt_s']):.6f} (record start to finish {c['repaired_wall_h']:.6f} h)",
        f"    total charged                          {c['charged_h']:.6f} of {c['budget_h']:.1f}; unused {c['remaining_h']:.6f}",
        f"    CPU gait searches, not charged          {c['cpu_uncharged_s']:.4f} s",
        f"    wrapper's final ledger line            {c['printed_final_charged_h']}; runner's pre-exit snapshot "
        f"{c['runner_pre_exit_charged_h']:.6f} ({(c['charged_h'] - c['runner_pre_exit_charged_h']) * SECONDS_PER_HOUR:.3f} s earlier)",
    ]
    return "\n".join(lines)


def main(argv):
    entry_dir = argv[1] if len(argv) > 1 else DEFAULT_ENTRY_DIR
    files = load_entry(entry_dir)
    table = recompute(files)
    print(render(table))
    found = disagreements(table, files["record"])
    if found:
        print("DISAGREES with stage0.json:\n  " + "\n  ".join(found))
        return 1
    print("AGREES with stage0.json on every recomputed value")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))