File size: 33,855 Bytes
c6a8401
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
#!/usr/bin/env python3
"""gen_q#275 -- beta patterns under the CORRECTED coin-terminated chain, PAIRED.

Every success number comes from the shipped table loader `verdict_table.cells(task)` (mug/threading
success criteria, canonical region, policy-family regex from POL, epoch filter, and the arm key that
carries CH<cap> so a chain cell can never pool with a fold cell).  `verdict_table.CELL_FILES` gives the
files behind each key; we re-read those files ONLY to recover per-episode indices (for pairing), the
flow-step stratum, and the chain accounting block.  There is NO hand-rolled glob+regex over eval JSONs
producing any published number -- three earlier false beta effects came from exactly that.

Pre-registration: status/BETA_PATTERNS_DONE, 2026-09-23 05:30Z (written before any contrast was run).
Output: status/beta_patterns.json  (+ a printed report)
"""
import json, math, os, re, sys, random, zlib
from collections import defaultdict
from pathlib import Path

ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
sys.path.insert(0, str(ROOT / "scripts"))
import verdict_table as VT

GAMMA = 0.99
# RUN 24 ADOPTION (2026-09-24, pre-registered status/BETA_PATTERNS_DONE 07:55Z): the hop
# expectation is now taken at the CELL'S OWN gamma by DEFAULT.  Run 23b measured, on one
# corpus with both rules built back to back, that this keeps 376 of 2136 units that the
# gamma-0.99 expectation had been discarding as BROKEN -- all 376 off-gamma-tagged, and not
# one of the 1584 gamma-0.99 units affected.  Q275_HOP_GAMMA_FIX=0 restores the retired rule
# (status/beta_patterns.ruleoff.json is that table, kept permanently).
HOP_GAMMA_FIX = os.environ.get("Q275_HOP_GAMMA_FIX", "1") != "0"
# GAMMA IN THE CELL IDENTITY (run 24c, 2026-09-24 08:25Z).  The retired hop rule excluded every
# off-gamma cell, so no key in this study had to carry gamma.  The run-24 fix keeps 380 of them --
# and then `stratum()` below, and the `(model, pseed, eseed)` key of six consumers, map an
# off-gamma cell onto the SAME slot as the gamma-0.99 cell of record and OVERWRITE it (the run-17
# lost-update class, re-introduced by the fix).  gamma is part of what the estimator IS, exactly as
# `plan_flow_steps` is, so it belongs in the key.  OFF BY DEFAULT: with the flag unset every key is
# byte-identical to the published one, and the KEY-A/KEY-B question the owner has not answered is
# untouched -- this is additive to whichever of those is in force.
# RUN 25 (2026-09-24, pre-registered 09:15Z): ON BY DEFAULT.  Run 24 measured that with the hop
# rule fixed and gamma absent from the key, 176 of 286 primary-arm keys mix gamma and 104 have an
# off-gamma row displacing the gamma-0.99 row of record (mean |dsucc| 0.055, max 0.260) -- so the
# default must carry gamma.  Q275_GAMMA_IN_KEY=0 restores the pre-run key.
GAMMA_IN_KEY = os.environ.get("Q275_GAMMA_IN_KEY", "1") == "1"
# GAMMA SCOPE (run 24d, 2026-09-24 08:35Z).  #275 asks what beta does AT THE FLAGSHIP DISCOUNT; the
# corpus also holds cells run at gamma 0.95/0.98/0.995 from #273's gamma sweep.  The retired hop rule
# excluded those cells as "broken" -- the right population for the wrong reason.  With the rule fixed
# they come back, and they must not enter the table of record by accident: gamma sets the horizon
# (E[total frames] = gamma/(1-gamma) = 49 / 99 / 199 at 0.98 / 0.99 / 0.995), so pooling them across
# gamma breaks #275's trap 2 whether or not the key collides.  This flag states the scope EXPLICITLY
# and leaves the excluded rows in `hop_accounting` carrying their reason, so the count is auditable.
# Unset = no filter (the pre-run behaviour).
# RUN 25 (2026-09-24, pre-registered 09:15Z): DEFAULTS TO 0.99, the flagship discount #275 asks
# about.  A scope that lives in one runner's environment is one forgotten `export` away from the
# pooled build run 24 measured to be wrong.  Q275_GAMMA_SCOPE= (empty) restores the unfiltered
# behaviour; the excluded rows stay in `hop_accounting` carrying their reason, so the count is
# auditable either way.
GAMMA_SCOPE = os.environ.get("Q275_GAMMA_SCOPE", "0.99")
GAMMA_SCOPE_V = float(GAMMA_SCOPE) if GAMMA_SCOPE else None
CAPPED_FRAC_MAX = 1e-2       # pre-registered exclusion 1
HOPS_REL_ERR_MAX = 0.05      # pre-registered exclusion 2
MIN_COMMON_EPISODES = 40     # pre-registered exclusion 4
NBOOT = 10000

TASKS = ["square_sub_20100", "square_expert_play", "two_piece_expert_suboptimal",
         "two_piece_expert_play", "two_piece_expert_play_tipping",
         "mug_expert_suboptimal", "threading_expert_play"]

# The recipe half of the loader's arm key for an RSM chain arm, e.g.
#   "Mb@best b0.9 CH73 N128 P16 prob"
RECIPE = re.compile(r"^(?P<model>[A-Za-z0-9_]+)@(?P<ck>\S+) b(?P<beta>[0-9.]+) CH(?P<cap>\d+) "
                    r"N(?P<n>\d+) P(?P<part>\d+) (?P<score>\w+)(?P<rest>.*)$")


def expected_hops(beta, gamma=GAMMA):
    """E[taken hops] = p/(1-p) with p = (gamma-beta)/(gamma(1-beta)), which simplifies to
       E[hops] = (gamma - beta) / (beta * (1 - gamma)).
    NOTE (this stream, 2026-09-23): gen_q#275's body states "Expected hops is p/(1-p) =
    (1-beta)/(1-gamma)".  The right-hand equality is FALSE except at beta = gamma/(2-gamma)
    (= 0.90 exactly at gamma = 0.99, which is why it looked right on the flagship beta).
    At beta = 0.95 the two read 4.211 vs 5, at 0.98 they read 1.020 vs 2.  The scorer is right:
    `chain_hops.E_hops_expected` is p/(1-p) and `L_star_tab_discounts` is the other quantity,
    (1-beta)/(1-gamma), which is the FOLD's tabular-equivalent depth, not a hop count.
    The horizon identity itself is unaffected: mean composed frame offset is
    (beta/(1-beta)) * (1 + p/(1-p)) = 99 frames at every beta, gamma = 0.99."""
    return (gamma - beta) / (beta * (1.0 - gamma))


def tabular_L_star(beta, gamma=GAMMA):
    """The fold's tabular-equivalent depth (1-beta)/(1-gamma); NOT the chain's hop count."""
    return (1.0 - beta) / (1.0 - gamma)


def mean_frame_offset(beta, gamma=GAMMA):
    """The quantity that is matched by construction across beta: (beta/(1-beta)) * (1 + p/(1-p))."""
    return (beta / (1.0 - beta)) * (1.0 + expected_hops(beta, gamma))


def p_cont(beta, gamma=GAMMA):
    return (gamma - beta) / (gamma * (1.0 - beta))


def gamma_from_p(beta, pc):
    """invert p = (gamma-beta)/(gamma(1-beta))  =>  gamma = beta / (1 - p(1-beta)).

    `pc` must be the STORED per-cell `chain_hops.p_cont` written by the scorer, NOT this module's
    analytic p_cont(beta) -- inverting the analytic form returns GAMMA for every row by algebra
    (gen_q#273 run 38; that identity is what made this stream's run-23a census circular).
    """
    if pc is None or not (0.0 <= pc < 1.0):
        return None
    den = 1.0 - pc * (1.0 - beta)
    return (beta / den) if den > 0 else None


def gamma_key(row_or_unit):
    """the gamma component of a cell key: () when the flag is off, so keys cannot move by accident."""
    if not GAMMA_IN_KEY:
        return ()
    g = row_or_unit.get("gamma_cell")
    if g is None:
        acc = row_or_unit.get("acc")
        if acc is not None:
            g = gamma_from_p(row_or_unit["beta"], agg(acc, "p_cont"))
    return (round(g, 4) if g is not None else "unknown",)


def load_units():
    """-> list of unit dicts, one per (task, arm-stratum, pseed, eseed, beta) cell."""
    units, skipped = [], defaultdict(int)
    for task in TASKS:
        try:
            cs = VT.cells(task)
        except AssertionError as e:
            print(f"[{task}] loader assertion: {e}", file=sys.stderr); continue
        files = dict(VT.CELL_FILES)          # cells() clears it each call, so snapshot now
        for key, succ in cs.items():
            (head, recipe), pol, pseed, eseed = key
            if not head.startswith("rsm:"):
                continue
            m = RECIPE.match(recipe)
            if not m:
                skipped["not-a-chain-arm"] += 1      # fold arms (L<depth>) and controls
                continue
            g = m.groupdict()
            # SPLIT THE CELL BY FLOW STEPS (this stream, 2026-09-23 07:50Z).  `verdict_table`'s arm key
            # carries the beta, the chain cap, the candidate count, the particle count and the read-out --
            # but NOT `plan_flow_steps`.  #273's flow sweep therefore lands flow-4, flow-8 and flow-16
            # eval files in ONE cell key, and this loader used to AVERAGE them: measured here, all 54
            # threading beta-0.95 units came back with mixed flow (the `F-1` rows in the hop table).
            # A flow step changes what a successor SAMPLE IS, so that is a pooled arm of three different
            # estimators, and #275 pre-registered flow as a confound to be STRATIFIED, not averaged.  The
            # cell is therefore split per flow value here; when a key has one flow value (every task but
            # threading today) this is byte-identical to the old behaviour.  The underlying arm-key gap is
            # reported to #273 rather than patched in verdict_table, which this stream does not own.
            byflow = defaultdict(list)
            for f in files.get(key, []):
                try:
                    _j = json.load(open(f))
                except Exception:
                    continue
                _o = _j.get("planner_overrides") or {}
                # Use the EFFECTIVE flow steps the cell recorded (planner.scorer.flow_steps), with the
                # requested override only as a fallback -- the SAME precedence verdict_table's ` F<n>`
                # arm-key suffix uses.  If the two disagreed, my split and the loader's key would name
                # different partitions and a stratum could silently hold two estimators again.
                _fs = ((_j.get("planner") or {}).get("scorer") or {}).get("flow_steps")
                if _fs is None:
                    _fs = _o.get("plan_flow_steps") or 8
                byflow[int(_fs)].append((f, _j))
            for flow_val, group in sorted(byflow.items()):
                ep, conflicts, acc = {}, 0, []
                for f, jj in group:
                    for e in (jj.get("episodes") or []):
                        i_ep = e.get("episode")
                        if i_ep is None:
                            continue
                        s_ok = bool(e.get("success"))
                        if i_ep in ep and ep[i_ep] != s_ok:
                            conflicts += 1
                        ep[i_ep] = s_ok
                    sc = (jj.get("planner") or {}).get("scorer") or {}
                    ch = sc.get("chain_hops") or {}
                    pt = jj.get("planner_time") or {}
                    acc.append(dict(
                        file=os.path.relpath(f, ROOT), n_ep=len(jj.get("episodes") or []),
                        hops_mean=ch.get("hops_mean"), hops_median=ch.get("hops_median"),
                        hops_p90=ch.get("hops_p90"), capped_frac=ch.get("capped_frac"),
                        cap_binding=ch.get("cap_binding"), hops_rel_err=ch.get("hops_rel_err"),
                        decisions=ch.get("decisions"), E_hops_expected=ch.get("E_hops_expected"),
                        p_cont=ch.get("p_cont"), cap=ch.get("cap"),
                        ties=pt.get("ties_at_max_mean"), ties_exact=pt.get("prob_ties_at_max_exact_mean"),
                        distinct=pt.get("prob_distinct_mean"),
                        gap=pt.get("gap_chosen_minus_mean"), sat=pt.get("frac_saturated_mean")))
                if not ep:
                    skipped["no-episodes"] += 1; continue
                beta = float(g["beta"])
                # STRIP THE ` F<n>` TOKEN OUT OF `extra` (this stream, 2026-09-23 08:55Z).  When #273
                # applied my flow-steps fix to verdict_table's arm key at 08:15Z, that suffix started
                # landing in this regex's `rest` group, i.e. in `extra` -- which q275_flow.py uses as
                # part of the "everything except flow" stratum key.  The flow strata therefore became
                # singletons and the pre-registered flow confound check went from 18 contrasts to ZERO,
                # printing "not yet measurable" with rc=0: the check disappeared without an error, the
                # same failure mode as the RSM_EXTRA_EPOCHS trap.  Flow already has its own field, so it
                # must not also sit in `extra`.  The assert is the positively-signed cross-check that the
                # loader's key and my split name the SAME partition (lesson from #273's lost-update: a
                # fix that changes nothing looks exactly like a fix that is not there).
                _rest = g["rest"].strip()
                _mF = re.search(r"\bF(\d+)\b", _rest)
                if _mF:
                    assert int(_mF.group(1)) == flow_val, (
                        f"flow mismatch: arm key says F{_mF.group(1)}, cell records flow_steps="
                        f"{flow_val} for {task} {recipe} p{pseed}e{eseed}")
                    _rest = re.sub(r"\s*\bF\d+\b", "", _rest).strip()
                _extra = _rest
                units.append(dict(
                    task=task, model=g["model"], ck=g["ck"], head=head, pol=pol,
                    pseed=int(pseed), eseed=int(eseed), beta=beta, cap=int(g["cap"]),
                    particles=int(g["part"]), score=g["score"], extra=_extra,
                    flow=flow_val, flow_split=(len(byflow) > 1),
                    ep=ep, n=len(ep), succ_rate=sum(ep.values()) / len(ep),
                    conflicts=conflicts, acc=acc, files=[a["file"] for a in acc]))
            if len(byflow) > 1:
                skipped[f"{task}:cells-split-by-flow"] += 1
        # report what the loader dropped, so an empty task is never silent
        skipped[f"{task}:units"] += sum(1 for u in units if u["task"] == task)
    # HARD GUARD (2026-09-23 07:40Z, this stream).  The line above only COUNTED an empty task, and a
    # count printed in a dict on line 1 of a 160-line report is not a guard: running this script
    # without RSM_EXTRA_EPOCHS=500 drops every threading cell (its proposer is pinned at policy epoch
    # 500) and the study's one significant beta effect vanished in silence, rc=0.  A task that is in
    # TASKS and yields nothing is a loader/environment fault, not a result, so it stops the run.
    empty = [t for t in TASKS if not any(u["task"] == t for u in units)]
    if empty:
        print(f"### FATAL: {len(empty)} task(s) yielded 0 chain units: {', '.join(empty)}\n"
              f"###        RSM_EXTRA_EPOCHS={os.environ.get('RSM_EXTRA_EPOCHS','')!r} "
              f"(threading needs 500).  Refusing to write a table with a task missing.",
              file=sys.stderr)
        sys.exit(3)
    return units, dict(skipped)


def agg(acc, k):
    v = [a[k] for a in acc if a.get(k) is not None]
    return (sum(v) / len(v)) if v else None


def qc(u):
    """pre-registered exclusions 1 and 2 -> (ok, reasons)"""
    bad = []
    cf, he = agg(u["acc"], "capped_frac"), agg(u["acc"], "hops_rel_err")
    if cf is None or he is None:
        bad.append("no chain accounting block")
    else:
        if cf > CAPPED_FRAC_MAX: bad.append(f"capped_frac={cf:.3g}>{CAPPED_FRAC_MAX}")
        if he > HOPS_REL_ERR_MAX: bad.append(f"hops_rel_err={he:.3g}>{HOPS_REL_ERR_MAX}")
    hm = agg(u["acc"], "hops_mean")
    # THE EXPECTATION MUST BE AT THE CELL'S OWN GAMMA (this stream, run 23, 2026-09-24 07:05Z,
    # after gen_q#273 run 37 `status/q273/run37/offgamma.txt`).  This line scored EVERY cell against
    # expected_hops(beta, GAMMA=0.99), but 372 cells in the corpus ran at gamma 0.98 / 0.995, where
    # E[N] is a different number entirely (beta 0.95: 1.579 at g0.98, 4.211 at g0.99, 9.474 at
    # g0.995).  Scored at 0.99 they are 372/372 over the 5% bar and were excluded as if BROKEN; they
    # are sound.  The cell's own gamma is recoverable from the STORED p_cont with no new field:
    #   p = (gamma-beta)/(gamma(1-beta))  =>  gamma = beta / (1 - p(1-beta)).
    # OFF BY DEFAULT.  Q275_HOP_GAMMA_FIX=1 turns it on; with it unset this function is semantically
    # identical to the version that produced every published number, so nothing moves until the
    # measurement in scripts/q275_gammafix.py says it should.
    if hm is not None:
        g_cell = GAMMA
        if HOP_GAMMA_FIX:
            g_cell = gamma_from_p(u["beta"], agg(u["acc"], "p_cont")) or GAMMA
        E = expected_hops(u["beta"], g_cell)
        # PRE-REGISTERED EXCLUSION 2b, THE DEGENERATE RULE (run 24, 07:55Z; it answers gen_q#273 run
        # 38 caveat 5, which they raised AGAINST their own proposed fix).  When beta >= gamma the
        # chain has p = 0 and E[N] = 0: a RELATIVE error bar cannot test such a cell at all, so a
        # bare `E > 0` guard would turn the old false exclusion into an UNCHECKED INCLUSION.  Such a
        # cell is excluded EXPLICITLY and with its own reason string.  Expected population: the 74
        # `G0p9` units at beta = gamma = 0.90, which the cap rule already excludes at
        # capped_frac = 1.0, so the kept count must not move -- only the reason gains a term.
        if GAMMA_SCOPE_V is not None and abs(g_cell - GAMMA_SCOPE_V) > 5e-4:
            bad.append(f"out of scope: gamma_cell={g_cell:.4g} != {GAMMA_SCOPE_V:g} "
                       f"(table of record is the flagship discount; this cell belongs to the gamma sweep)")
        if E <= 0:
            bad.append(f"degenerate beta={u['beta']:.3g}>=gamma_cell={g_cell:.4g} (E[N]=0, untestable)")
        elif abs(hm / E - 1.0) > HOPS_REL_ERR_MAX:
            bad.append(f"hops_mean={hm:.3g} vs E={E:.3g}"
                       + ("" if g_cell == GAMMA else f" (gamma={g_cell:.4g})"))
    return (not bad), bad


# REPRODUCIBILITY DEFECT, found by run 24d's diff and fixed here (2026-09-24 08:45Z).  The paired
# bootstrap below was seeded `hash((st, bA, bB)) & 0xffff`.  Python randomises `hash()` of anything
# containing a str once per PROCESS unless PYTHONHASHSEED is set, and it is set nowhere in this repo
# (`grep -n PYTHONHASHSEED scripts/*.sh` -> nothing).  So EVERY paired CI this study has published was
# drawn with a per-process-random seed and is not reproducible across builds; measured jitter on
# identical data is up to 0.0044 absolute (run 24d: 53 of 63 contrast CI endpoints moved between two
# builds whose point estimates, McNemar p's, Holm p's, n_cells and argmax were all bit-identical).
# crc32 of the repr is a stable 32-bit hash, so the same stratum and beta pair now always draw the
# same resamples.  Q275_LEGACY_SEED=1 restores the randomised seed for the control that measures the
# defect.  Point estimates and p's never depended on this; only the CI endpoints can move, once.
LEGACY_SEED = os.environ.get("Q275_LEGACY_SEED", "") == "1"


def ci_seed(key):
    if LEGACY_SEED:
        return hash(key) & 0xffff
    return zlib.crc32(repr(key).encode()) & 0xffff


def boot_ci(d, nboot=NBOOT, seed=0):
    """paired bootstrap over CLUSTERS (the pre-registered primary test)"""
    if not d: return (None, None, None)
    rng = random.Random(seed); n = len(d); mean = sum(d) / n
    if n < 2: return (mean, None, None)
    bs = []
    for _ in range(nboot):
        s = [d[rng.randrange(n)] for _ in range(n)]
        bs.append(sum(s) / n)
    bs.sort()
    return mean, bs[int(0.025 * nboot)], bs[min(nboot - 1, int(0.975 * nboot))]


def mcnemar_exact(b, c):
    """two-sided exact binomial on the discordant pairs"""
    n = b + c
    if n == 0: return 1.0
    k = min(b, c)
    # `2.0 ** n` OVERFLOWS for n > 1023 discordant pairs (run 24c: the gamma-keyed build's pooled
    # across-task contrast reached n = 1034 and the whole table build died with OverflowError).
    # Integer/integer true division is exact and cannot overflow for a ratio <= 1, and for every
    # n <= 1023 it returns the identical double, so no published number can move.
    p = sum(math.comb(n, i) for i in range(0, k + 1)) / (1 << n)
    return min(1.0, 2.0 * p)


def holm(pvals):
    idx = sorted(range(len(pvals)), key=lambda i: pvals[i])
    out = [None] * len(pvals); run = 0.0
    for r, i in enumerate(idx):
        adj = max(run, min(1.0, (len(pvals) - r) * pvals[i])); run = adj; out[i] = adj
    return out


def main():
    units, skipped = load_units()
    print(f"# units loaded: {len(units)}   loader notes: {skipped}")

    # QC first, before any beta contrast is formed
    for u in units:
        u["ok"], u["qc"] = qc(u)
    flagged = [u for u in units if not u["ok"]]
    units_ok = [u for u in units if u["ok"]]
    print(f"# QC: {len(units_ok)} kept, {len(flagged)} excluded")
    for u in flagged[:20]:
        print(f"#   EXCLUDED {u['task']} {u['model']} b{u['beta']} P{u['particles']}/{u['score']}"
              f"/F{u['flow']} p{u['pseed']}e{u['eseed']}: {'; '.join(u['qc'])}")

    # strata: everything except beta and the (pseed, eseed) pairing key
    def stratum(u):
        return (u["task"], u["model"], u["ck"], u["head"], u["pol"], u["particles"], u["score"],
                u["flow"], u["extra"]) + gamma_key(u)

    by = defaultdict(dict)                      # stratum -> (pseed,eseed) -> beta -> unit
    for u in units_ok:
        by[stratum(u)].setdefault((u["pseed"], u["eseed"]), {})[u["beta"]] = u

    results, hop_rows = [], []
    for u in units:
        a = u["acc"]
        hop_rows.append(dict(
            task=u["task"], model=u["model"], beta=u["beta"], cap=u["cap"],
            particles=u["particles"], score=u["score"], flow=u["flow"],
            # THE DECLARED CELL IDENTITY, carried into the hop table (this stream, 2026-09-24 02:58Z,
            # pre-registered).  PURELY ADDITIVE: no existing consumer reads these four and no key
            # changes here.  They already exist on the unit and are already part of stratum(), which
            # is what the `paired` table keys on; the hop table simply dropped them, and that omission
            # is why q275_headline.py/q275_oracle.py could key a cell as (model, pseed, eseed) -- a
            # key COARSER than the identity the section declares -- and silently overwrite cells
            # instead of creating them (run 17, status/q275_keycoll.json: 17 collisions in P16/prob/F8,
            # all 17 with different success, up to 0.300 absolute apart).  Carrying the fields does not
            # fix that; it makes the two readings measurable from disk without a regex over filenames.
            ck=u["ck"], head=u["head"], pol=u["pol"], extra=u["extra"],
            pseed=u["pseed"], eseed=u["eseed"], kept=u["ok"], qc=u["qc"],
            # `E_hops` / `p_cont` are and always were THIS MODULE'S ANALYTIC CONSTANTS OF BETA at
            # GAMMA = 0.99, not measurements; every consumer of them is reading beta (run 23, and
            # gen_q#273 run 38 point 1).  Run 24 surfaces the scorer's OWN stored values beside
            # them -- names added, nothing renamed or removed, so the two readings are separable
            # from disk without a regex over filenames and no downstream reader changes meaning.
            E_hops=expected_hops(u["beta"]), p_cont=p_cont(u["beta"]),
            p_cont_stored=agg(a, "p_cont"), E_hops_stored=agg(a, "E_hops_expected"),
            gamma_cell=gamma_from_p(u["beta"], agg(a, "p_cont")),
            L_star_tab=tabular_L_star(u["beta"]), frames_mean=mean_frame_offset(u["beta"]),
            hops_mean=agg(a, "hops_mean"), hops_median=agg(a, "hops_median"),
            hops_p90=agg(a, "hops_p90"), capped_frac=agg(a, "capped_frac"),
            hops_rel_err=agg(a, "hops_rel_err"), decisions=agg(a, "decisions"),
            ties=agg(a, "ties"), ties_exact=agg(a, "ties_exact"), distinct=agg(a, "distinct"),
            gap=agg(a, "gap"), sat=agg(a, "sat"),
            n_ep=u["n"], succ=u["succ_rate"], files=u["files"]))

    for st, cells in sorted(by.items()):
        betas = sorted({b for c in cells.values() for b in c})
        for i in range(len(betas)):
            for jx in range(i + 1, len(betas)):
                bA, bB = betas[i], betas[jx]     # paired difference = A - B (A the SMALLER beta)
                d, nb, nc, nep, drops = [], 0, 0, 0, []
                for pe, c in sorted(cells.items()):
                    if bA not in c or bB not in c: continue
                    uA, uB = c[bA], c[bB]
                    common = sorted(set(uA["ep"]) & set(uB["ep"]))
                    if len(common) < MIN_COMMON_EPISODES:
                        drops.append(f"p{pe[0]}e{pe[1]}:{len(common)} common"); continue
                    dd = sum(int(uA["ep"][k]) - int(uB["ep"][k]) for k in common) / len(common)
                    d.append(dd); nep += len(common)
                    nb += sum(1 for k in common if uA["ep"][k] and not uB["ep"][k])
                    nc += sum(1 for k in common if uB["ep"][k] and not uA["ep"][k])
                if not d: continue
                mean, lo, hi = boot_ci(d, seed=ci_seed((st, bA, bB)))
                p = mcnemar_exact(nb, nc)
                # tie-artefact guard: the read-out tie count is the competing explanation
                tA = [agg(c[bA]["acc"], "ties_exact") for c in cells.values() if bA in c]
                tB = [agg(c[bB]["acc"], "ties_exact") for c in cells.values() if bB in c]
                tA = [x for x in tA if x is not None]; tB = [x for x in tB if x is not None]
                results.append(dict(
                    task=st[0], model=st[1], ck=st[2], pol=st[4], particles=st[5], score=st[6],
                    flow=st[7], extra=st[8], beta_lo=bA, beta_hi=bB, n_cells=len(d),
                    n_episodes=nep, mean_paired_d=mean, ci_lo=lo, ci_hi=hi,
                    per_cell_d=d, mcnemar_b=nb, mcnemar_c=nc, mcnemar_p=p,
                    ties_exact_lo=(sum(tA) / len(tA) if tA else None),
                    ties_exact_hi=(sum(tB) / len(tB) if tB else None),
                    dropped_cells=drops))

    # Holm across the PRIMARY family: the default arm (P16 prob, flow 8), one test per (task, pair)
    prim = [r for r in results if r["particles"] == 16 and r["score"] == "prob" and r["flow"] == 8
            and not r["extra"] and not r["model"].startswith("TDF")]
    if prim:
        adj = holm([r["mcnemar_p"] for r in prim])
        for r, a in zip(prim, adj): r["mcnemar_p_holm"] = a

    out = dict(generated_utc=__import__("datetime").datetime.utcnow().isoformat() + "Z",
               prereg="status/BETA_PATTERNS_DONE 2026-09-23 05:30Z",
               loader="scripts/verdict_table.py::cells", gamma=GAMMA,
               exclusions=dict(capped_frac_max=CAPPED_FRAC_MAX, hops_rel_err_max=HOPS_REL_ERR_MAX,
                               min_common_episodes=MIN_COMMON_EPISODES,
                               hop_gamma_fix=bool(HOP_GAMMA_FIX),
                               gamma_in_key=bool(GAMMA_IN_KEY), gamma_scope=GAMMA_SCOPE or None,
                               ci_seed=("legacy hash() -- NOT reproducible" if LEGACY_SEED
                                        else "crc32(repr(key)) -- reproducible")),
               n_units=len(units), n_units_kept=len(units_ok),
               hop_accounting=hop_rows, paired=results)
    print(f"# wrote status/beta_patterns.json  ({len(results)} paired contrasts, "
          f"{len(hop_rows)} accounting rows)")

    print("\n## PAIRED BETA CONTRASTS (primary arm: P16 prob, flow 8, flagship successor)")
    print(f"{'task':30s} {'arm':16s} {'pair':14s} {'cells':>5s} {'eps':>5s} "
          f"{'mean d':>8s} {'95% CI':>18s} {'b/c':>10s} {'p':>8s} {'p_holm':>8s}")
    for r in sorted(prim, key=lambda r: (r["task"], r["beta_lo"], r["beta_hi"])):
        ci = f"[{r['ci_lo']:+.3f},{r['ci_hi']:+.3f}]" if r["ci_lo"] is not None else "n/a"
        arm = "P%d %s" % (r["particles"], r["score"])
        pair = "%.2f-%.2f" % (r["beta_lo"], r["beta_hi"])
        bc = "%d/%d" % (r["mcnemar_b"], r["mcnemar_c"])
        ph = r.get("mcnemar_p_holm")
        ph = float("nan") if ph is None else ph
        print(f"{r['task']:30s} {arm:16s} {pair:14s} "
              f"{r['n_cells']:5d} {r['n_episodes']:5d} {r['mean_paired_d']:+8.4f} {ci:>18s} "
              f"{bc:>10s} {r['mcnemar_p']:8.4f} {ph:8.4f}")

    # ---- POOLED across tasks (the headline, unadjusted) and the H1 particle-stratification ----
    print("\n## POOLED ACROSS TASKS -- flagship successor, default arm (P16 prob, flow 8)")
    pooled = []
    print(f"  (primary family: {len(prim)} contrasts, pairs "
          f"{sorted({(r['beta_lo'], r['beta_hi']) for r in prim})})")
    for pair in sorted({(r["beta_lo"], r["beta_hi"]) for r in prim}):
        cellsd = [x for r in prim if (r["beta_lo"], r["beta_hi"]) == pair for x in r["per_cell_d"]]
        taskd = [r["mean_paired_d"] for r in prim if (r["beta_lo"], r["beta_hi"]) == pair]
        m1, l1, h1 = boot_ci(cellsd, seed=11)
        m2, l2, h2 = boot_ci(taskd, seed=12)
        nan = float("nan")
        m1, l1, h1 = (nan if m1 is None else m1), (nan if l1 is None else l1), (nan if h1 is None else h1)
        m2, l2, h2 = (nan if m2 is None else m2), (nan if l2 is None else l2), (nan if h2 is None else h2)
        nb = sum(r["mcnemar_b"] for r in prim if (r["beta_lo"], r["beta_hi"]) == pair)
        nc = sum(r["mcnemar_c"] for r in prim if (r["beta_lo"], r["beta_hi"]) == pair)
        print(f"  beta {pair[0]:.2f} vs {pair[1]:.2f}: cluster-over-CELLS n={len(cellsd):3d} "
              f"d={m1:+.4f} [{l1:+.4f},{h1:+.4f}] | cluster-over-TASKS n={len(taskd)} "
              f"d={m2:+.4f} [{l2:+.4f},{h2:+.4f}] | McNemar b/c={nb}/{nc} p={mcnemar_exact(nb, nc):.4f}")
        pooled.append(dict(beta_lo=pair[0], beta_hi=pair[1], n_cells=len(cellsd),
                           d_cells=m1, ci_cells=[l1, h1], n_tasks=len(taskd), d_tasks=m2,
                           ci_tasks=[l2, h2], mcnemar_b=nb, mcnemar_c=nc,
                           mcnemar_p=mcnemar_exact(nb, nc)))
    out["pooled"] = pooled

    print("\n## H1 CONFOUND -- does the beta effect shrink as particles rise?  (per task, per read-out)")
    print(f"  {'task':30s} {'score':6s} {'pair':11s} {'P16 d (n)':>18s} {'P64 d (n)':>18s}  ratio")
    h1rows = []
    for t in sorted({r["task"] for r in results}):
        for sc in ("prob", "logit"):
            for pair in sorted({(r["beta_lo"], r["beta_hi"]) for r in results}):
                g = {r["particles"]: r for r in results
                     if r["task"] == t and r["score"] == sc and r["flow"] == 8 and not r["extra"]
                     and not r["model"].startswith("TDF")
                     and (r["beta_lo"], r["beta_hi"]) == pair}
                if 16 not in g or 64 not in g: continue
                a, b = g[16], g[64]
                ratio = (abs(b["mean_paired_d"]) / abs(a["mean_paired_d"])
                         if abs(a["mean_paired_d"]) > 1e-9 else float("nan"))
                print(f"  {t:30s} {sc:6s} {pair[0]:.2f}-{pair[1]:.2f} "
                      f"{a['mean_paired_d']:+12.4f} ({a['n_cells']:2d}) "
                      f"{b['mean_paired_d']:+12.4f} ({b['n_cells']:2d})  {ratio:.2f}")
                h1rows.append(dict(task=t, score=sc, beta_lo=pair[0], beta_hi=pair[1],
                                   d_P16=a["mean_paired_d"], n_P16=a["n_cells"],
                                   d_P64=b["mean_paired_d"], n_P64=b["n_cells"], ratio=ratio))
    out["h1_particles"] = h1rows

    print("\n## PER-TASK SUCCESS BY BETA (flagship successor, default arm) -- the figure's rows")
    fig = []
    for t in sorted({u["task"] for u in units_ok}):
        for b in sorted({u["beta"] for u in units_ok if u["task"] == t}):
            us = [u for u in units_ok if u["task"] == t and u["beta"] == b and u["particles"] == 16
                  and u["score"] == "prob" and u["flow"] == 8 and not u["extra"]
                  and not u["model"].startswith("TDF")]
            if not us: continue
            rates = [u["succ_rate"] for u in us]
            mn = sum(rates) / len(rates)
            sd = (sum((x - mn) ** 2 for x in rates) / (len(rates) - 1)) ** 0.5 if len(rates) > 1 else 0.0
            sem = sd / (len(rates) ** 0.5) if rates else 0.0
            print(f"  {t:30s} b{b:.2f}  n_cells={len(us):2d}  succ={mn:.4f} +/- {1.96*sem:.4f} (95% SEM over cells)")
            fig.append(dict(task=t, beta=b, n_cells=len(us), succ=mn, sem=sem, ci95=1.96 * sem,
                            per_cell=rates))
    out["figure_rows"] = fig
    _dst = os.environ.get("Q275_OUT") or str(ROOT / "status/beta_patterns.json")
    __import__("pathlib").Path(_dst).write_text(json.dumps(out, indent=1))
    print(f"# output path: {_dst}  (Q275_HOP_GAMMA_FIX={int(HOP_GAMMA_FIX)})")

    print("\n## HOP ACCOUNTING  (mean taken hops must equal p/(1-p) = (gamma-beta)/(beta(1-gamma)))")
    seen = set()
    for h in sorted(hop_rows, key=lambda h: (h["task"], h["beta"], h["particles"], h["score"])):
        k = (h["task"], h["model"], h["beta"], h["particles"], h["score"], h["flow"])
        if k in seen: continue
        seen.add(k)
        rows = [x for x in hop_rows if (x["task"], x["model"], x["beta"], x["particles"],
                                        x["score"], x["flow"]) == k]
        def m(f):
            v = [x[f] for x in rows if x[f] is not None]
            return sum(v) / len(v) if v else float("nan")
        print(f"{h['task']:30s} {h['model']:10s} b{h['beta']:.2f} cap{h['cap']:3d} "
              f"P{h['particles']:<3d}{h['score']:5s} F{h['flow']:<3d} n={len(rows):2d}  "
              f"E[hops]={h['E_hops']:6.3f} hops_mean={m('hops_mean'):7.3f} "
              f"frames={h['frames_mean']:6.2f} "
              f"relerr={m('hops_rel_err'):7.4f} capped={m('capped_frac'):9.2e} "
              f"ties={m('ties'):7.2f} tiesX={m('ties_exact'):7.2f} distinct={m('distinct'):7.2f} "
              f"succ={m('succ'):5.3f}")


if __name__ == "__main__":
    main()