File size: 51,747 Bytes
808ecc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
#!/usr/bin/env python
"""Task 1 as a learning problem: policies learned from a log of one setting per forum, scored on the full grid.

WHY. Task 1 grades an estimate of a GIVEN policy's value. The next question is how good a policy can be learned from
a LOG of one setting per interaction. Every setting of the core was run on every interaction, so a learned policy's
value on held-out seeds is computed from the grid rather than estimated, which no ordinary log allows.

PROTOCOL, per repetition, under Task 1's two loggers (code/ds4_ope_bandit.py):
  fit seeds    10, used only to build the tilted logger, exactly as Task 1 builds it; no learner sees them
  train seeds  20, the log: for each (context, seed) ONE arm drawn from mu(. | c), with its reward and its
               exact propensity, and nothing else
  test seeds   20, held out: a learned policy's value is the mean over (context, test seed) of the reward of
               the arm it picks there, computed from the full grid
LEARNERS, each from the train log alone; each picks one arm per context unless it says pooled:
  uniform       every arm equally; no learning, the floor a learner has to clear
  pooled-IPS    the one arm with the highest importance-weighted value over all contexts
  pooled-DM     the one arm with the highest observed mean reward over all contexts: the best FIXED setting a
                log supports, the comparator a per-context learner has to beat
  context-IPS   per context, the arm with the highest importance-weighted value
  context-DM    per context, the arm with the highest observed mean reward; where the context never logged
                an arm, that arm's mean over every context, then the log's overall mean
  context-DR    per context, the doubly robust value, with each arm's mean over every context as the model
  lever-model   ridge regression of the reward on the context, the arm's three levers, their squares and
                every pairwise product, fit on the log, then the best predicted arm per context
REFERENCES, which see more than the log, printed as ceilings and never as learners:
  full-information  per context, the best arm on the train seeds' FULL grid: what this many seeds allows
  pooled-full-information  the one arm best over all contexts on the train seeds' FULL grid
  test-oracle       per context, the best arm on the test seeds themselves, in-sample and optimistic
REPORTED on the graded composite r_util + r_safe + |r_fid|, on r_total and on the all-objectives sum: each policy's
mean test value with a bootstrap interval for that mean over repetitions, its gain over uniform, its regret against
the full-information reference, and how often it beats pooled-IPS. This is the table of learners the paper prints for
Task 1 as a learning problem.

THE CONSERVATIVE LEARNER, behind --conservative and nowhere else. Without the option the program writes
core/policy_baselines.json and nothing else.
  LCB-lever@k   per context, the setting with the largest lower bound on the lever model's prediction: the
                prediction minus k times its pairs-bootstrap standard error (100 refits on the logged interactions
                resampled with replacement, from a stream of its own), and minus infinity for a setting the log
                never played in that context, so it never picks a setting the log never tried there
  LCB-DM@k      the same rule on the direct method's cell mean, minus k times sigma_a over the root of the cell's
                logged count; sigma_a is the setting's within-cell residual deviation pooled over contexts. A
                bootstrap of a cell holding one logged interaction has no spread, so this error is analytic
  k = 1 is the learner the paper reports; 0, 0.5 and 2 are a sensitivity curve. Loggers: uniform, and Task 1's holed
  logger (evaluate.py --holed 5: 5 settings per context never played, seed 142), on the same seed splits and uniform
  draws as run(); and the periphery's recorded logger, where no full grid exists and the readout is the chosen
  setting's mean on a held-out half of the cells. The holes are checked against core/ope_positivity.json, which
  `python evaluate.py --root . --holed 5` writes, and the uniform logger's values against core/policy_baselines.json,
  which the first command below writes.

SHIPPED IN THE RELEASE as code/ds4_policy_baselines.py. It reads <root>/core/trace.parquet (and, with --conservative,
<root>/periphery/trace.parquet) and imports only code/ds4_ope_bandit.py beside it.

    python code/ds4_policy_baselines.py --selftest
    python code/ds4_policy_baselines.py --root .                    # core/policy_baselines.json
    python evaluate.py --root . --holed 5                           # core/ope_positivity.json, for the next one
    python code/ds4_policy_baselines.py --root . --conservative     # the conservative learner, core and periphery
"""
import argparse
import json
import sys
from pathlib import Path

import numpy as np
import pandas as pd

sys.path.insert(0, str(Path(__file__).resolve().parent))
from ds4_ope_bandit import load_grid  # noqa: E402  the one grid loader both tasks read

REWARDS = ("r_util+r_safe+abs:r_fid", "r_total", "r_util+r_safe+abs:r_fid+r_fair+r_read")
GRADED = REWARDS[0]
LEARNERS = ("uniform", "pooled-IPS", "pooled-DM", "context-IPS", "context-DM", "context-DR", "lever-model")
REFERENCES = ("full-information", "pooled-full-information", "test-oracle")
POOLED_ADDED = ("pooled-DM", "pooled-full-information")
LEVERS = ("a_arditi_alpha", "a_delta_scale", "a_rank")
# --conservative only. The periphery varies seven levers; the core crosses three.
PERI_LEVERS = ("a_delta_scale", "a_clamp", "a_rank", "a_temperature", "a_mc_dropout", "a_cfg_scale", "a_arditi_alpha")
NONCONS = ("pooled-IPS", "pooled-DM", "context-IPS", "context-DM", "context-DR", "lever-model")
KAPPA = 1.0                       # the penalty weight the paper reports
KAPPAS = (0.0, 0.5, 1.0, 2.0)     # the sensitivity curve, never ruled on
MARGIN = 0.010                    # the non-inferiority margin under the uniform logger
SE_BOOT = 100                     # pairs-bootstrap refits behind LCB-lever's standard error
HOLES_PER_CONTEXT = 5             # Task 1's positivity logger, evaluate.py --holed 5


def arm_features(df, arms, levers=LEVERS):
    lev = df.groupby("config_idx")[list(levers)].first()
    miss = [a for a in arms if a not in lev.index]
    if miss:
        raise SystemExit(f"[policy] FATAL: no lever values for arms {miss}")
    A = lev.loc[list(arms), list(levers)].astype(float).values
    return (A - A.mean(axis=0)) / (A.std(axis=0) + 1e-12)


def context_features(ctxs):
    C = np.array([[float(x) for x in c.split("|")] for c in ctxs])
    return (C - C.mean(axis=0)) / (C.std(axis=0) + 1e-12)


def design(cf, af, ci, ai):
    """Features of (context, arm) pairs: intercept, context, levers, squares and every pairwise product."""
    c, a = cf[ci], af[ai]
    cols = [np.ones(len(ci))] + [c[:, j] for j in range(c.shape[1])] + [a[:, j] for j in range(a.shape[1])]
    cols += [a[:, j] ** 2 for j in range(a.shape[1])]
    cols += [a[:, j] * a[:, k] for j in range(a.shape[1]) for k in range(j + 1, a.shape[1])]
    cols += [c[:, j] * a[:, k] for j in range(c.shape[1]) for k in range(a.shape[1])]
    return np.column_stack(cols)


def ridge(X, y, lam):
    P = np.eye(X.shape[1]) * lam
    P[0, 0] = 0.0
    return np.linalg.solve(X.T @ X + P, X.T @ y)


def logger_mu(q, kind, beta):
    """Task 1's two loggers, built the same way (ds4_ope_bandit.one_rep)."""
    n_ctx, n_arm = q.shape
    if kind == "uniform":
        return np.full((n_ctx, n_arm), 1.0 / n_arm)
    z = (q - q.mean(axis=1, keepdims=True)) / (q.std(axis=1, keepdims=True) + 1e-12)
    e = np.exp(beta * z)
    return e / e.sum(axis=1, keepdims=True)


def value(G, pol):
    """Mean reward over (context, seed) of the arm `pol` picks in each context."""
    idx = np.broadcast_to(np.asarray(pol)[:, None, None], (G.shape[0], G.shape[1], 1))
    return float(np.take_along_axis(G, idx, axis=2).mean())


def one_rep(grids, cf, af, rng, n_fit, n_train, logger, beta, lam, cons=None):
    first = next(iter(grids.values()))
    n_ctx, n_seed, n_arm = first.shape
    perm = rng.permutation(n_seed)
    fit, tr, te = perm[:n_fit], perm[n_fit:n_fit + n_train], perm[n_fit + n_train:]
    base = grids["r_total"] if "r_total" in grids else first
    if logger == "holed":       # --conservative only; the default path never reaches it
        mu = holed_mu(cons["holes"])
    else:
        mu = logger_mu(base[:, fit, :].mean(axis=1), logger, beta)
    cum = np.cumsum(mu, axis=1)
    u = rng.random_sample((n_ctx, len(tr)))
    A = np.minimum((u[:, :, None] > cum[:, None, :]).sum(axis=2), n_arm - 1)   # the logged arm, (c, s)
    P = np.take_along_axis(mu, A, axis=1)                                      # its exact propensity
    if cons is not None:
        check_logged_propensity(P)
    cidx = np.repeat(np.arange(n_ctx)[:, None], len(tr), axis=1)
    allc, alla = np.repeat(np.arange(n_ctx), n_arm), np.tile(np.arange(n_arm), n_ctx)
    X = design(cf, af, cidx.ravel(), A.ravel())
    Xall = design(cf, af, allc, alla)
    out = {}
    for rw, G in grids.items():
        R = np.take_along_axis(G[:, tr, :], A[:, :, None], axis=2)[:, :, 0]    # the logged rewards only
        Gte = G[:, te, :]
        ips = np.zeros((n_ctx, n_arm))
        np.add.at(ips, (cidx, A), R / P)
        ips /= len(tr)
        cnt, sm = np.zeros((n_ctx, n_arm)), np.zeros((n_ctx, n_arm))
        np.add.at(cnt, (cidx, A), 1.0)
        np.add.at(sm, (cidx, A), R)
        gmean = float(R.mean())
        arm_cnt, arm_sm = cnt.sum(axis=0), sm.sum(axis=0)
        arm_mean = np.where(arm_cnt > 0, arm_sm / np.maximum(arm_cnt, 1.0), gmean)
        dm = np.where(cnt > 0, sm / np.maximum(cnt, 1.0), arm_mean[None, :])
        resid = np.zeros((n_ctx, n_arm))
        np.add.at(resid, (cidx, A), (R - arm_mean[A]) / P)
        dr = arm_mean[None, :] + resid / len(tr)
        pred = (Xall @ ridge(X, R.ravel(), lam)).reshape(n_ctx, n_arm)
        pols = {"pooled-IPS": np.full(n_ctx, int(np.argmax(ips.mean(axis=0)))),
                "pooled-DM": np.full(n_ctx, int(np.argmax(arm_mean))),
                "pooled-full-information": np.full(n_ctx, int(np.argmax(G[:, tr, :].mean(axis=(0, 1))))),
                "context-IPS": ips.argmax(axis=1), "context-DM": dm.argmax(axis=1),
                "context-DR": dr.argmax(axis=1), "lever-model": pred.argmax(axis=1),
                "full-information": G[:, tr, :].mean(axis=1).argmax(axis=1),
                "test-oracle": Gte.mean(axis=1).argmax(axis=1)}
        if cons is not None:
            pols.update(lcb_policies(cnt, cidx.ravel(), A.ravel(), R.ravel(), X, Xall, pred, lam, n_ctx, n_arm,
                                     cons["kappas"], cons["B"], cons["rng"], cons.get("support", True)))
        vals = {k: value(Gte, p) for k, p in pols.items()}
        vals["uniform"] = float(Gte.mean())
        agree = {k: float((p == pols["full-information"]).mean()) for k, p in pols.items()}
        out[rw] = {"value": vals, "agree": agree,
                   "mu_ratio": float(mu.max() / (mu[mu > 0].min() if logger == "holed" else mu.min()))}
        if cons is not None:
            rows = np.arange(n_ctx)
            out[rw]["unsupported"] = {k: float((cnt[rows, p] == 0).mean()) for k, p in pols.items()}
            if cons["holes"] is not None and logger == "holed":
                out[rw]["in_hole"] = {k: float(cons["holes"][rows, p].mean()) for k, p in pols.items()}
    return out


def _boot(x, rng, B=2000):
    x = np.asarray(x, float)
    m = x[rng.randint(0, len(x), size=(B, len(x)))].mean(axis=1)
    return [float(np.percentile(m, 2.5)), float(np.percentile(m, 97.5))]


def run(grids, cf, af, reps, n_fit, n_train, beta, lam, seed=142):
    res = {}
    rngb = np.random.RandomState(seed + 7)
    # separate streams: rngp for the paired comparison with the pooled direct method, rngq for the two pooled policies
    rngp = np.random.RandomState(seed + 11)
    rngq = np.random.RandomState(seed + 13)
    for logger in ("uniform", "tilted"):
        rng = np.random.RandomState(seed)
        acc, ratios = {}, []
        for _ in range(reps):
            for rw, v in one_rep(grids, cf, af, rng, n_fit, n_train, logger, beta, lam).items():
                ratios.append(v["mu_ratio"])
                a = acc.setdefault(rw, {"value": {}, "agree": {}})
                for k, x in v["value"].items():
                    a["value"].setdefault(k, []).append(x)
                for k, x in v["agree"].items():
                    a["agree"].setdefault(k, []).append(x)
        L = {"mu_max_over_min": float(np.median(ratios)), "rewards": {}}
        for rw, a in acc.items():
            V = {k: np.array(v) for k, v in a["value"].items()}
            rec = {}
            # every policy but the two pooled ones draws its intervals from rngb in this order; those two draw from rngq
            for k in [k for k in LEARNERS + REFERENCES if k not in POOLED_ADDED] + list(POOLED_ADDED):
                x = V[k]
                rb = rngq if k in POOLED_ADDED else rngb
                rec[k] = {"value": float(x.mean()), "ci95_of_mean": _boot(x, rb),
                          "gain_over_uniform": float((x - V["uniform"]).mean()),
                          "gain_ci95": _boot(x - V["uniform"], rb),
                          "regret_vs_full_information": float((V["full-information"] - x).mean()),
                          "regret_ci95": _boot(V["full-information"] - x, rb),
                          "share_beats_pooled_ips": float(np.mean(x > V["pooled-IPS"])),
                          "gain_over_pooled_dm": float((x - V["pooled-DM"]).mean()),
                          "gain_over_pooled_dm_ci95": _boot(x - V["pooled-DM"], rngp),
                          "agree_full_information": (float(np.mean(a["agree"][k])) if k in a["agree"]
                                                     else None)}
            L["rewards"][rw] = rec
        res[logger] = L
    return res


def check_split(n_seeds, n_fit, n_train):
    if n_seeds < n_fit + n_train + 4:
        raise SystemExit(f"[policy] FATAL: {n_seeds} seeds cannot hold {n_fit} fit, {n_train} train and at "
                         f"least 4 test seeds.")


def table(res, rw):
    lines = []
    for logger, L in res.items():
        lines.append(f"[policy] {rw}, {logger} logger (median largest over smallest propensity "
                     f"{L['mu_max_over_min']:.1f}):")
        for k in LEARNERS + REFERENCES:
            r = L["rewards"][rw][k]
            lines.append(f"   {k:<17} value {r['value']:.4f}  gain over uniform {r['gain_over_uniform']:+.4f} "
                         f"[{r['gain_ci95'][0]:+.4f}, {r['gain_ci95'][1]:+.4f}]  regret "
                         f"{r['regret_vs_full_information']:+.4f}  beats pooled-IPS "
                         f"{100 * r['share_beats_pooled_ips']:.0f}%")
    return "\n".join(lines)


# ------------------------------------------------------------------- the conservative learner (--conservative)
def holes_like_task1(n_ctx, n_arm, k=HOLES_PER_CONTEXT, seed=142):
    """Task 1's positivity holes, drawn exactly as ds4_ope_bandit.py main() draws them for --holed k."""
    hr = np.random.RandomState(seed)
    holes = np.zeros((n_ctx, n_arm), bool)
    for c in range(n_ctx):
        holes[c, hr.choice(n_arm, k, replace=False)] = True
    return holes


def holed_mu(holes):
    """Uniform over each context's settings except its holes, which the logger never plays."""
    mu = np.where(holes, 0.0, 1.0)
    return mu / mu.sum(axis=1, keepdims=True)


def check_logged_propensity(P):
    if np.any(P <= 0):
        raise ValueError("a logged arm has propensity zero: the logger played an arm it never plays")


def lcb_policies(cnt, ci, ai, r, X, Xall, pred, lam, n_ctx, n_arm, kappas, B, rngse, support=True):
    """LCB-lever@k and LCB-DM@k from one log. `support=False` is a planted defect for the selftest only."""
    sm, ssq = np.zeros((n_ctx, n_arm)), np.zeros((n_ctx, n_arm))
    np.add.at(sm, (ci, ai), r)
    mean = np.where(cnt > 0, sm / np.maximum(cnt, 1.0), 0.0)
    np.add.at(ssq, (ci, ai), (r - mean[ci, ai]) ** 2)
    df_a, ss_a = np.clip(cnt - 1.0, 0.0, None).sum(axis=0), ssq.sum(axis=0)
    s2_all = float(ss_a.sum() / df_a.sum()) if df_a.sum() > 0 else float(np.var(r))
    s2_a = np.where(df_a >= 2, ss_a / np.maximum(df_a, 1.0), s2_all)
    se_dm = np.sqrt(s2_a)[None, :] / np.sqrt(np.maximum(cnt, 1.0))
    n = len(r)
    boots = np.empty((B, n_ctx * n_arm))
    for b in range(B):
        idx = rngse.randint(0, n, size=n)
        boots[b] = Xall @ ridge(X[idx], r[idx], lam)
    se_lev = boots.std(axis=0, ddof=1).reshape(n_ctx, n_arm)
    hole = (cnt == 0) if support else np.zeros((n_ctx, n_arm), bool)
    pols = {}
    for k in kappas:
        pols[f"LCB-lever@{k:g}"] = np.where(hole, -np.inf, pred - k * se_lev).argmax(axis=1)
        pols[f"LCB-DM@{k:g}"] = np.where(hole, -np.inf, mean - k * se_dm).argmax(axis=1)
    return pols


def cons_names(kappas):
    return [f"LCB-lever@{k:g}" for k in kappas] + [f"LCB-DM@{k:g}" for k in kappas]


def summarize(acc, kappas, rngb, comparators):
    """Per learner: mean value with its interval over repetitions and its gain over uniform; per conservative
    learner: the paired difference against every comparator, with its interval and the share it wins."""
    out = {}
    for rw, a in acc.items():
        V = {k: np.array(v) for k, v in a["value"].items()}
        rec = {"learners": {}, "paired": {}}
        for k in sorted(V):
            x = V[k]
            rec["learners"][k] = {"value": float(x.mean()), "ci95_of_mean": _boot(x, rngb), "n_reps": int(len(x))}
            if "uniform" in V and k != "uniform":
                rec["learners"][k]["gain_over_uniform"] = float((x - V["uniform"]).mean())
                rec["learners"][k]["gain_ci95"] = _boot(x - V["uniform"], rngb)
            for extra in ("unsupported", "in_hole", "design_hole", "scored_share"):
                if k in a.get(extra, {}):
                    rec["learners"][k][extra] = float(np.mean(a[extra][k]))
        for c in cons_names(kappas):
            for k in comparators:
                if k not in V or k == c:
                    continue
                d = V[c] - V[k]
                rec["paired"].setdefault(c, {})[k] = {"mean": float(d.mean()), "ci95": _boot(d, rngb),
                                                      "share_cons_wins": float(np.mean(d > 0)),
                                                      "share_tied": float(np.mean(d == 0)), "n_reps": int(len(d))}
        if "paired_diag" in a:
            rec["paired_per_context_diagnostic"] = {}
            for (c, k), v in sorted(a["paired_diag"].items()):
                d = np.array([x for x in v if np.isfinite(x)])
                rec["paired_per_context_diagnostic"].setdefault(c, {})[k] = (
                    {"mean": float(d.mean()), "ci95": _boot(d, rngb), "n_reps": int(len(d))} if len(d) else None)
        out[rw] = rec
    return out


def run_conservative(grids, cf, af, reps, n_fit, n_train, beta, lam, holes, kappas=KAPPAS, B=SE_BOOT,
                     loggers=("uniform", "holed"), seed=142, support=True):
    """The core: every learner, the conservative ones included, on run()'s own seed splits and uniform draws."""
    res = {}
    rngb = np.random.RandomState(seed + 19)
    for logger in loggers:
        rng = np.random.RandomState(seed)                       # the same stream run() starts each logger with
        cons = {"holes": holes, "kappas": kappas, "B": B, "support": support,
                "rng": np.random.RandomState(seed + 17)}        # the bootstrap's own stream
        acc, ratios = {}, []
        for _ in range(reps):
            for rw, v in one_rep(grids, cf, af, rng, n_fit, n_train, logger, beta, lam, cons=cons).items():
                ratios.append(v["mu_ratio"])
                a = acc.setdefault(rw, {"value": {}, "unsupported": {}, "in_hole": {}})
                for key in ("value", "unsupported", "in_hole"):
                    for k, x in v.get(key, {}).items():
                        a[key].setdefault(k, []).append(x)
        res[logger] = {"mu_max_over_min": float(np.median(ratios)),
                       "rewards": summarize(acc, kappas, rngb, NONCONS + ("uniform",) + REFERENCES)}
    return res


def load_log(df, rewards, levers=PERI_LEVERS):
    """A log with holes: (context, arm) index per cell, each reward, the recorded propensity, the arm levers."""
    df = df.assign(_ctx=df["s_pool_imbalance"].astype(str) + "|" + df["s_bad_actor_frac"].astype(str))
    need = sorted({c[4:] if c.startswith("abs:") else c for rw in rewards for c in rw.split("+")})
    miss = [c for c in need + ["mu_logging"] + list(levers) if c not in df.columns]
    if miss:
        raise SystemExit(f"[policy] FATAL: the log has no {miss} column")
    # A cell without one of the summed objectives has no reward on that sum. It is dropped from EVERY reward's log
    # (one periphery cell has no r_safe, because every post in it was removed), and named.
    sums = {rw: sum((np.abs(df[c[4:]].astype(float).values) if c.startswith("abs:") else df[c].astype(float).values)
                    for c in rw.split("+")) for rw in rewards}
    keep = np.all([np.isfinite(v) for v in sums.values()], axis=0)
    dropped = df.loc[~keep, "cell_id"].astype(str).tolist() if "cell_id" in df.columns else [int(i) for i in
                                                                                             np.flatnonzero(~keep)]
    df = df[keep]
    ctxs, arms = sorted(df["_ctx"].unique()), sorted(df["config_idx"].unique())
    ci = df["_ctx"].map({c: i for i, c in enumerate(ctxs)}).values
    ai = df["config_idx"].map({a: i for i, a in enumerate(arms)}).values
    mu = df["mu_logging"].astype(float).values
    if not np.all(np.isfinite(mu)) or np.any(mu <= 0):
        raise SystemExit("[policy] FATAL: a logged cell has no positive recorded propensity")
    R = {rw: v[keep] for rw, v in sums.items()}
    return {"ci": ci, "ai": ai, "mu": mu, "R": R, "ctxs": ctxs, "arms": arms, "dropped": dropped,
            "cf": context_features(ctxs), "af": arm_features(df, arms, levers)}


def periphery_split(ci, ai, n_ctx, n_arm, rng):
    """Held-out half: within each setting, alternate over its cells in a random order of contexts and cells, so
    every setting has cells in both halves and every pair with two or more cells has one in each."""
    pair_key, cell_key = rng.random_sample(n_ctx * n_arm), rng.random_sample(len(ci))
    off = rng.randint(0, 2, size=n_arm)
    order = np.lexsort((cell_key, pair_key[ci * n_arm + ai], ai))
    a_sorted = ai[order]
    starts = np.r_[0, np.flatnonzero(np.diff(a_sorted)) + 1]
    rank = np.arange(len(order)) - np.repeat(starts, np.diff(np.r_[starts, len(order)]))
    test = np.zeros(len(ci), bool)
    test[order] = ((rank + off[a_sorted]) % 2) == 1
    return test


def periphery_policies(ci, ai, r, mu, cf, af, n_ctx, n_arm, lam, kappas, B, rngse, support=True):
    """Task 1's learners from a log with holes and an uneven recorded propensity, and the conservative ones."""
    n_c = np.bincount(ci, minlength=n_ctx).astype(float)
    cnt, sm = np.zeros((n_ctx, n_arm)), np.zeros((n_ctx, n_arm))
    np.add.at(cnt, (ci, ai), 1.0)
    np.add.at(sm, (ci, ai), r)
    gmean = float(r.mean())
    arm_cnt, arm_sm = cnt.sum(axis=0), sm.sum(axis=0)
    arm_mean = np.where(arm_cnt > 0, arm_sm / np.maximum(arm_cnt, 1.0), gmean)
    dm = np.where(cnt > 0, sm / np.maximum(cnt, 1.0), arm_mean[None, :])
    ips, resid = np.zeros((n_ctx, n_arm)), np.zeros((n_ctx, n_arm))
    np.add.at(ips, (ci, ai), r / mu)
    ips /= n_c[:, None]
    np.add.at(resid, (ci, ai), (r - arm_mean[ai]) / mu)
    dr = arm_mean[None, :] + resid / n_c[:, None]
    allc, alla = np.repeat(np.arange(n_ctx), n_arm), np.tile(np.arange(n_arm), n_ctx)
    X, Xall = design(cf, af, ci, ai), design(cf, af, allc, alla)
    pred = (Xall @ ridge(X, r, lam)).reshape(n_ctx, n_arm)
    pols = {"pooled-IPS": np.full(n_ctx, int(np.argmax(ips.mean(axis=0)))),
            "pooled-DM": np.full(n_ctx, int(np.argmax(arm_mean))),
            "context-IPS": ips.argmax(axis=1), "context-DM": dm.argmax(axis=1),
            "context-DR": dr.argmax(axis=1), "lever-model": pred.argmax(axis=1)}
    pols.update(lcb_policies(cnt, ci, ai, r, X, Xall, pred, lam, n_ctx, n_arm, kappas, B, rngse, support))
    return pols, cnt


def run_periphery(log, reps, lam, kappas=KAPPAS, B=SE_BOOT, seed=142, support=True):
    """The periphery under its recorded logger. No full grid exists, so a policy's value is the held-out half's
    mean graded reward of the setting it picks in each context, pooled over every context that logged that
    setting, averaged over the 12 contexts; the per-context held-out mean is a diagnostic with its scored share."""
    ci, ai, mu = log["ci"], log["ai"], log["mu"]
    n_ctx, n_arm = len(log["ctxs"]), len(log["arms"])
    total = np.zeros((n_ctx, n_arm))
    np.add.at(total, (ci, ai), 1.0)
    rng, rngse, rngb = np.random.RandomState(seed), np.random.RandomState(seed + 17), np.random.RandomState(seed + 19)
    rows = np.arange(n_ctx)
    acc = {}
    for _ in range(reps):
        test = periphery_split(ci, ai, n_ctx, n_arm, rng)
        tr = ~test
        for rw, r in log["R"].items():
            pols, cnt = periphery_policies(ci[tr], ai[tr], r[tr], mu[tr], log["cf"], log["af"], n_ctx, n_arm, lam,
                                           kappas, B, rngse, support)
            tc_a = np.bincount(ai[test], minlength=n_arm)
            arm_te = np.where(tc_a > 0, np.bincount(ai[test], weights=r[test], minlength=n_arm)
                              / np.maximum(tc_a, 1), np.nan)
            if not np.all(np.isfinite(arm_te)):
                raise SystemExit("[policy] FATAL: a periphery setting has no held-out cell")
            tcnt, tsm = np.zeros((n_ctx, n_arm)), np.zeros((n_ctx, n_arm))
            np.add.at(tcnt, (ci[test], ai[test]), 1.0)
            np.add.at(tsm, (ci[test], ai[test]), r[test])
            pair_te = np.where(tcnt > 0, tsm / np.maximum(tcnt, 1.0), np.nan)
            a = acc.setdefault(rw, {"value": {}, "unsupported": {}, "design_hole": {}, "scored_share": {},
                                    "paired_diag": {}})
            for k, p in pols.items():
                a["value"].setdefault(k, []).append(float(arm_te[p].mean()))
                a["unsupported"].setdefault(k, []).append(float((cnt[rows, p] == 0).mean()))
                a["design_hole"].setdefault(k, []).append(float((total[rows, p] == 0).mean()))
                a["scored_share"].setdefault(k, []).append(float(np.isfinite(pair_te[rows, p]).mean()))
            a["value"].setdefault("uniform", []).append(float(arm_te.mean()))
            a["value"].setdefault("logger", []).append(float(r[test].mean()))
            for c in cons_names(kappas):
                for k in NONCONS:
                    d = pair_te[rows, pols[c]] - pair_te[rows, pols[k]]
                    a["paired_diag"].setdefault((c, k), []).append(float(np.nanmean(d)) if np.isfinite(d).any()
                                                                   else np.nan)
    return {"rewards": summarize(acc, kappas, rngb, NONCONS + ("uniform", "logger"))}


def read_conservative_rule(core, peri, kappa=KAPPA, margin=MARGIN, graded=GRADED):
    """The decision lines K1 to K4, each HOLDS or DOES NOT HOLD. `core` maps logger -> run_conservative's record
    and `peri` is run_periphery's (either may be None in a selftest)."""
    c_lev, c_dm = f"LCB-lever@{kappa:g}", f"LCB-DM@{kappa:g}"
    lines = {}

    def pd_(res, cname, k):
        return res["rewards"][graded]["paired"][cname][k]

    def verdict(ok):
        return "HOLDS" if ok else "DOES NOT HOLD"
    if core is not None:
        for name, cname, base in (("K1", c_lev, "lever-model"), ("K2", c_dm, "context-DM")):
            h, u = pd_(core["holed"], cname, base), pd_(core["uniform"], cname, base)
            ok_h, ok_u = h["ci95"][0] > 0, u["ci95"][0] > -margin
            lines[name] = {"learner": cname, "against": base, "holed": h, "uniform": u, "margin": margin,
                           "holed_half": verdict(ok_h), "uniform_half": verdict(ok_u), "reads": verdict(ok_h and ok_u),
                           "holed_wholly_below_zero": bool(h["ci95"][1] < 0)}
        each = {k: pd_(core["holed"], c_lev, k) for k in NONCONS}
        lines["K3"] = {"learner": c_lev, "against_each": each,
                       "reads": verdict(all(v["ci95"][0] > 0 for v in each.values()))}
    if peri is not None:
        for name, cname, base in (("K4", c_lev, "lever-model"), ("K4b", c_dm, "context-DM")):
            p = pd_(peri, cname, base)
            lines[name] = {"learner": cname, "against": base, "periphery": p, "reads": verdict(p["ci95"][0] > 0)}
    return lines


def conservative_table(res, rw, title):
    lines = [f"[conservative] {title}, {rw}"]
    L = res["rewards"][rw]
    for k, r in L["learners"].items():
        extra = "".join(f"  {e} {r[e]:.3f}" for e in ("unsupported", "in_hole", "design_hole", "scored_share") if e in r)
        lines.append(f"   {k:<20} value {r['value']:.4f} [{r['ci95_of_mean'][0]:.4f}, {r['ci95_of_mean'][1]:.4f}]"
                     + (f"  gain {r['gain_over_uniform']:+.4f}" if "gain_over_uniform" in r else "") + extra)
    for c, d in L["paired"].items():
        if not c.endswith(f"@{KAPPA:g}"):
            continue
        for k, v in d.items():
            if k in NONCONS:
                lines.append(f"   {c} - {k:<12} {v['mean']:+.4f} [{v['ci95'][0]:+.4f}, {v['ci95'][1]:+.4f}]  "
                             f"wins {100 * v['share_cons_wins']:.0f}%  ties {100 * v['share_tied']:.0f}%")
    return "\n".join(lines)


# ---------------------------------------------------------------------------------------------- selftest
def _trace(n_ctx=6, n_seed=50, n_arm=8, signal=True, seed=3, hole=False, drop_col=None):
    rng = np.random.RandomState(seed)
    rows = []
    for c in range(n_ctx):
        best = 2 if c < n_ctx // 2 else 5
        for s in range(n_seed):
            for a in range(n_arm):
                r = 0.5 + (0.3 if (signal and a == best) else 0.0) + rng.normal(0, 0.05)
                rows.append({"s_pool_imbalance": float(c // 2), "s_bad_actor_frac": 0.05 * (c % 2 + 1),
                             "seed": s, "config_idx": a, "mu_logging": 1.0 / n_arm, "r_util": r,
                             "r_safe": 0.0, "r_fid": 0.0, "r_fair": 0.0, "r_read": 0.0, "r_total": r,
                             "a_arditi_alpha": 0.25 * (a % 4), "a_delta_scale": 1.0 + 3.0 * (a // 4),
                             "a_rank": 8.0 + 16.0 * (a % 2)})
    df = pd.DataFrame(rows)
    if hole:
        df = df.iloc[1:]
    if drop_col:
        df = df.drop(columns=[drop_col])
    return df


def _fit(df, reps=30):
    grids, ctxs, seeds, arms, _ = load_grid(df, REWARDS)
    check_split(len(seeds), 10, 20)
    return run(grids, context_features(ctxs), arm_features(df, arms), reps, 10, 20, 0.6, 1.0)


def selftest():
    ok = True

    def case(label, good, detail=""):
        nonlocal ok
        ok = ok and bool(good)
        print(f"  {label} -> {'OK' if good else 'FAIL'} {detail}", flush=True)

    def refused(fn):
        try:
            fn()
            return False
        except SystemExit:
            return True

    res = _fit(_trace())
    for logger in ("uniform", "tilted"):
        r = res[logger]["rewards"][GRADED]
        good = (r["full-information"]["agree_full_information"] == 1.0
                and r["full-information"]["regret_vs_full_information"] == 0.0
                and r["context-DM"]["gain_ci95"][0] > 0.1
                and r["context-DR"]["gain_ci95"][0] > 0.1
                and r["test-oracle"]["value"] >= r["full-information"]["value"] - 1e-9)
        case(f"PLANTED-PASS   a planted best arm per context is learned from the {logger} log; the "
             f"reference regrets nothing", good,
             f"DM gain {r['context-DM']['gain_over_uniform']:+.3f}, DR gain "
             f"{r['context-DR']['gain_over_uniform']:+.3f}")
    # Pure noise: a learner that saw nothing of the test seeds gains nothing in expectation, and 60 repetitions
    # put the standard error of a mean gain near 0.0006, so +0.005 is far outside chance. The in-sample test
    # oracle gains about 0.016 on the same noise, which is why it is a ceiling and never a learner.
    res0 = _fit(_trace(signal=False), reps=60)
    r0 = res0["uniform"]["rewards"][GRADED]
    gains = {k: r0[k]["gain_over_uniform"] for k in LEARNERS if k != "uniform"}
    no_gain = all(g < 0.005 for g in gains.values())
    case("PLANTED-FAIL 1 on pure noise no learner gains over uniform (nothing leaks from the test seeds), "
         "while the in-sample test oracle does", no_gain and r0["test-oracle"]["gain_over_uniform"] > 0.005,
         f"learner gains {[round(g, 4) for g in gains.values()]}, oracle "
         f"{r0['test-oracle']['gain_over_uniform']:+.4f}")
    case("PLANTED-FAIL 2 a grid with a hole is refused", refused(lambda: _fit(_trace(hole=True), reps=2)))
    case("PLANTED-FAIL 3 a trace without the readability objective is refused",
         refused(lambda: _fit(_trace(drop_col="r_read"), reps=2)))
    case("PLANTED-FAIL 4 too few seeds for a fit, train and test split is refused",
         refused(lambda: _fit(_trace(n_seed=30), reps=2)))
    ok = selftest_conservative(case, refused) and ok
    print("\n  SELFTEST PASSED" if ok else "\n  SELFTEST FAILED", flush=True)
    return 0 if ok else 1


def assert_supported(*recs):
    """The conservative learner never picks a setting the log never played in that context, anywhere."""
    for rec in recs:
        for rw, L in rec["rewards"].items():
            for k, r in L["learners"].items():
                if k.startswith("LCB-") and r.get("unsupported", 0.0) != 0.0:
                    raise SystemExit(f"[policy] FATAL: {k} picked a setting the log never played ({rw}, share "
                                     f"{r['unsupported']:.4f})")


def _grid_df(mean_fn, sd_fn, n_ctx=6, n_seed=50, n_arm=8, seed=11):
    """A full grid with one varying lever (the arm index as the steering strength) and the reward in r_util."""
    rng = np.random.RandomState(seed)
    rows = []
    for c in range(n_ctx):
        for s in range(n_seed):
            for a in range(n_arm):
                r = mean_fn(c, a) + rng.normal(0, sd_fn(a))
                rows.append({"s_pool_imbalance": float(c // 2), "s_bad_actor_frac": 0.05 * (c % 2 + 1), "seed": s,
                             "config_idx": a, "mu_logging": 1.0 / n_arm, "r_util": r, "r_safe": 0.0, "r_fid": 0.0,
                             "r_fair": 0.0, "r_read": 0.0, "r_total": r, "a_arditi_alpha": float(a),
                             "a_delta_scale": 1.0, "a_rank": 8.0})
    return pd.DataFrame(rows)


def _cons_fit(df, holes, reps, loggers, support=True):
    grids, ctxs, seeds, arms, _ = load_grid(df, REWARDS)
    return run_conservative(grids, context_features(ctxs), arm_features(df, arms), reps, 10, 20, 0.6, 1.0, holes,
                            kappas=(0.0, KAPPA), B=30, loggers=loggers, support=support)


def _periphery_df(seed=13, n_ctx=6, n_arm=20):
    """A log with holes and uneven support: settings 0-9 hold 6 cells per context and are good; settings 10-19
    hold one cell in half the contexts; setting 15 holds one cell per context, a low mean and a high variance."""
    rng = np.random.RandomState(seed)
    rows = []
    for c in range(n_ctx):
        for a in range(n_arm):
            if a < 10:
                n, m, sd = 6, 0.55 + 0.01 * a, 0.05
            elif a == 15:
                n, m, sd = 1, 0.0, 1.0
            else:
                n, m, sd = (1 if c < n_ctx // 2 else 0), 0.5, 0.05
            for j in range(n):
                r = m + rng.normal(0, sd)
                rows.append({"s_pool_imbalance": float(c // 2), "s_bad_actor_frac": 0.05 * (c % 2 + 1),
                             "seed": 7000 + 7 * j, "config_idx": a, "r_util": r, "r_safe": 0.0, "r_fid": 0.0,
                             "r_fair": 0.0, "r_read": 0.0, "r_total": r, "a_delta_scale": 1.0 + a % 4,
                             "a_clamp": 0.02 * (1 + a % 3), "a_rank": 8.0 * (1 + a % 2),
                             "a_temperature": 0.3 + 0.2 * (a % 5), "a_mc_dropout": 0.1 * (a % 3),
                             "a_cfg_scale": 1.0 + 0.5 * (a % 2), "a_arditi_alpha": 0.25 * (a % 5)})
    df = pd.DataFrame(rows)
    df["_c"] = df["s_pool_imbalance"].astype(str) + "|" + df["s_bad_actor_frac"].astype(str)
    df["mu_logging"] = df.groupby(["_c", "config_idx"])["r_util"].transform("size") / df.groupby("_c")["r_util"].transform("size")
    return df.drop(columns=["_c"])


def selftest_conservative(case, refused):
    """The --conservative path: planted logs where pessimism must help, must not, and planted defects."""
    ok = True

    def c2(label, good, detail=""):
        nonlocal ok
        ok = ok and bool(good)
        case(label, good, detail)
    c1 = f"LCB-lever@{KAPPA:g}"
    cd = f"LCB-DM@{KAPPA:g}"
    one_hole = np.zeros((6, 8), bool)
    one_hole[:, 7] = True
    # PLANTED-PASS 1: the reward rises with the lever up to setting 6 and falls off a cliff at setting 7, which the
    # log never plays. The lever model extrapolates the rise into the hole; the conservative learner cannot.
    cliff = _grid_df(lambda c, a: 0.0 if a == 7 else 0.5 + 0.05 * a, lambda a: 0.02)
    r1 = _cons_fit(cliff, one_hole, 20, ("holed",))
    L1 = r1["holed"]["rewards"][GRADED]
    d1 = L1["paired"][c1]["lever-model"]
    c2("PLANTED-PASS C1 an unlogged setting the lever model extrapolates to a high value is a cliff: the lever model "
       "picks it, LCB-lever never does and is worth more",
       L1["learners"]["lever-model"]["in_hole"] > 0.9 and L1["learners"][c1]["in_hole"] == 0.0
       and L1["learners"][c1]["unsupported"] == 0.0 and d1["ci95"][0] > 0.3,
       f"lever-model in a hole {L1['learners']['lever-model']['in_hole']:.2f}, {c1} - lever-model {d1['mean']:+.3f} "
       f"[{d1['ci95'][0]:+.3f}, {d1['ci95'][1]:+.3f}]")
    # PLANTED-FAIL C1: the same log with the support restriction removed is caught by the invariant check.
    r1b = _cons_fit(cliff, one_hole, 5, ("holed",), support=False)
    c2("PLANTED-FAIL C1 with the support restriction removed (a planted defect) the learner picks an unlogged "
       "setting and the check refuses it", refused(lambda: assert_supported(r1b["holed"])))
    # PLANTED-PASS C2: one setting has a low mean and a high variance and is logged two or three times per context.
    # The direct method picks it whenever a draw runs high; the analytic standard error penalizes it.
    hv_means = (0.5, 0.55, 0.6, 0.4, 0.62, 0.65, 0.68, 0.7)
    hv = _grid_df(lambda c, a: hv_means[a], lambda a: 1.0 if a == 3 else 0.05, seed=12)
    r2 = _cons_fit(hv, None, 30, ("uniform",))
    d2 = r2["uniform"]["rewards"][GRADED]["paired"][cd]["context-DM"]
    c2("PLANTED-PASS C2 a high-variance setting with a low mean: context-DM picks it on lucky draws, LCB-DM is worth "
       "more", d2["ci95"][0] > 0, f"{cd} - context-DM {d2['mean']:+.3f} [{d2['ci95'][0]:+.3f}, {d2['ci95'][1]:+.3f}]")
    # PLANTED-FAIL C2: a smooth surface whose best setting is the hole. The lever model extrapolates correctly and
    # the conservative learner loses, so the rule must read DOES NOT HOLD.
    peak = _grid_df(lambda c, a: 1.0 - 0.05 * (a - 7) ** 2, lambda a: 0.02, seed=14)
    r3 = _cons_fit(peak, one_hole, 20, ("uniform", "holed"))
    k1 = read_conservative_rule(r3, None)["K1"]
    c2("PLANTED-FAIL C2 the best setting is a hole the lever model reaches correctly: LCB-lever loses and K1 reads "
       "DOES NOT HOLD", k1["reads"] == "DOES NOT HOLD" and k1["holed_half"] == "DOES NOT HOLD"
       and k1["holed"]["ci95"][1] < 0, f"holed {k1['holed']['mean']:+.3f} [{k1['holed']['ci95'][0]:+.3f}, "
       f"{k1['holed']['ci95'][1]:+.3f}]")
    # THE RULE READER on planted intervals: both halves pass; the uniform half breaches the margin; the holed
    # interval spans zero.
    def fake(h_ci, u_ci):
        def rec(ci):
            row = {"mean": 0.0, "ci95": ci, "share_cons_wins": 0.5, "share_tied": 0.0, "n_reps": 1}
            paired = {c: {k: dict(row) for k in NONCONS} for c in (c1, cd)}
            return {"rewards": {GRADED: {"paired": paired}}}
        return {"holed": rec(h_ci), "uniform": rec(u_ci)}
    got = [read_conservative_rule(fake(h, u), None)["K1"]["reads"]
           for h, u in (([0.01, 0.03], [-0.009, 0.002]), ([0.01, 0.03], [-0.011, 0.002]), ([-0.001, 0.03], [0.0, 0.01]))]
    c2("PLANTED rule reader: K1 HOLDS only when the holed interval is above zero and the uniform interval's lower end "
       "is above minus the margin", got == ["HOLDS", "DOES NOT HOLD", "DOES NOT HOLD"], str(got))
    # PLANTED-FAIL C3: a holed log that records a play at propensity zero is refused.
    c2("PLANTED-FAIL C3 a logged play at propensity zero is refused, a positive one is not",
       _raises_value_error(np.array([[0.05, 0.0]])) and not _raises_value_error(np.array([[0.05, 0.1]])))
    # PLANTED-PASS C3: the periphery path, a log with holes and uneven support whose one-cell high-variance setting
    # the direct method picks on lucky draws.
    plog = load_log(_periphery_df(), REWARDS)
    rp = run_periphery(plog, 40, 1.0, kappas=(0.0, KAPPA), B=20)
    Lp = rp["rewards"][GRADED]
    dp = Lp["paired"][cd]["context-DM"]
    sup = all(Lp["learners"][k]["unsupported"] == 0.0 and Lp["learners"][k]["design_hole"] == 0.0
              for k in Lp["learners"] if k.startswith("LCB-"))
    c2("PLANTED-PASS C3 periphery path: LCB-DM beats context-DM on held-out cells and no conservative pick is "
       "unsupported or in an empty pair", dp["ci95"][0] > 0 and sup,
       f"{cd} - context-DM {dp['mean']:+.3f} [{dp['ci95'][0]:+.3f}, {dp['ci95'][1]:+.3f}]; supported {sup}")
    # PLANTED-FAIL C4: a cell missing one summed objective is dropped from every reward's log and named.
    pdf = _periphery_df()
    pdf.loc[0, "r_safe"] = np.nan
    plog2 = load_log(pdf, REWARDS)
    c2("PLANTED-FAIL C4 a cell missing one objective is dropped from every reward's log and named",
       len(plog2["dropped"]) == 1 and len(plog2["ci"]) == len(pdf) - 1
       and all(len(v) == len(pdf) - 1 and np.all(np.isfinite(v)) for v in plog2["R"].values()))
    return ok


def _raises_value_error(P):
    try:
        check_logged_propensity(P)
        return False
    except ValueError:
        return True


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--root", default=".",
                    help="the corpus root, the directory holding core/ and periphery/; in the release that is the "
                         "release directory itself")
    ap.add_argument("--reps", type=int, default=200)
    ap.add_argument("--n_fit", type=int, default=10)
    ap.add_argument("--n_train", type=int, default=20)
    ap.add_argument("--beta", type=float, default=0.6)
    ap.add_argument("--lam", type=float, default=1.0)
    ap.add_argument("--out", default="", help="where to write policy_baselines.json (default: core/ under --out_dir)")
    ap.add_argument("--out_dir", default="",
                    help="the folder the outputs are written under, in core/ and periphery/ (default: --root)")
    ap.add_argument("--positivity", default="",
                    help="with --conservative: Task 1's positivity output, whose holes the holed logger must match "
                         "(default: core/ope_positivity.json under --root)")
    ap.add_argument("--selftest", action="store_true")
    ap.add_argument("--conservative", action="store_true",
                    help="the conservative learner: writes core/policy_conservative.json, "
                         "periphery/policy_conservative_periphery.json and conservative_readout.json under --out_dir, "
                         "and never policy_baselines.json")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    if a.conservative:
        return conservative_main(a)
    trace = Path(a.root) / "core" / "trace.parquet"
    try:
        if not trace.is_file():
            raise SystemExit(f"[policy] FATAL: no trace at {trace}")
        df = pd.read_parquet(trace)
        grids, ctxs, seeds, arms, _ = load_grid(df, REWARDS)
        check_split(len(seeds), a.n_fit, a.n_train)
        cf, af = context_features(ctxs), arm_features(df, arms)
    except SystemExit as e:
        print(f"[policy] REFUSED: {e}")
        return 2
    res = run(grids, cf, af, a.reps, a.n_fit, a.n_train, a.beta, a.lam)
    out = {"protocol": "the policy-learning challenge from the log: a per-context playbook learned from one "
                       "arm per interaction, its value computed on held-out seeds from the full grid",
           "trace": str(trace), "n_contexts": len(ctxs), "n_seeds": len(seeds), "n_arms": len(arms),
           "reps": a.reps, "n_fit": a.n_fit, "n_train": a.n_train,
           "n_test": len(seeds) - a.n_fit - a.n_train, "beta": a.beta, "ridge_lambda": a.lam,
           "graded": GRADED, "learners": list(LEARNERS), "references": list(REFERENCES), "loggers": res}
    path = Path(a.out) if a.out else Path(a.out_dir or a.root) / "core" / "policy_baselines.json"
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(out, indent=1))
    for rw in REWARDS:
        print(table(res, rw))
    print(f"[policy] wrote {path}")
    return 0


def conservative_main(a):
    root = Path(a.root)
    dest = Path(a.out_dir or a.root)
    try:
        trace = root / "core" / "trace.parquet"
        df = pd.read_parquet(trace)
        grids, ctxs, seeds, arms, _ = load_grid(df, REWARDS)
        check_split(len(seeds), a.n_fit, a.n_train)
        cf, af = context_features(ctxs), arm_features(df, arms)
        holes = holes_like_task1(len(ctxs), len(arms))
        have = sorted((ctxs[c], int(arms[k])) for c, k in zip(*np.where(holes)))
        pos = Path(a.positivity) if a.positivity else root / "core" / "ope_positivity.json"
        if not pos.is_file():
            raise SystemExit(f"no {pos} to check the holes against; run `python evaluate.py --root . --holed 5` first")
        want = sorted((str(c), int(k)) for c, k in json.loads(pos.read_text())["holes"]["pairs"])
        if want != have:
            raise SystemExit("the holes differ from the ones Task 1's positivity test used")
        print(f"[conservative] holed logger: {len(have)} of {holes.size} pairs never logged, identical to "
              f"{pos.name}'s {len(want)}")
        ptrace = root / "periphery" / "trace.parquet"
        log = load_log(pd.read_parquet(ptrace), REWARDS)
        n_pairs = len(log["ctxs"]) * len(log["arms"])
        logged = len(set(zip(log["ci"].tolist(), log["ai"].tolist())))
        print(f"[conservative] periphery: {len(log['ci'])} cells, {len(log['arms'])} settings, {len(log['ctxs'])} "
              f"contexts, {n_pairs - logged} of {n_pairs} pairs never logged; dropped for a missing objective: "
              f"{log['dropped']}")
    except SystemExit as e:
        print(f"[policy] REFUSED: {e}")
        return 2
    core = run_conservative(grids, cf, af, a.reps, a.n_fit, a.n_train, a.beta, a.lam, holes)
    stored = Path(a.out) if a.out else dest / "core" / "policy_baselines.json"
    if stored.is_file():
        S = json.loads(stored.read_text())["loggers"]["uniform"]["rewards"]
        worst = max(abs(core["uniform"]["rewards"][rw]["learners"][k]["value"] - S[rw][k]["value"])
                    for rw in REWARDS for k in LEARNERS + REFERENCES)
        print(f"[conservative] uniform logger, every Task 1 learner and reference against {stored.name}: largest "
              f"difference in value {worst:.3e}")
        if worst > 1e-12:
            print("[policy] REFUSED: the uniform logger's splits are not the ones policy_baselines.json used")
            return 2
    peri = run_periphery(log, a.reps, a.lam)
    try:
        assert_supported(core["uniform"], core["holed"], peri)
    except SystemExit as e:
        print(f"[policy] REFUSED: {e}")
        return 2
    lines = read_conservative_rule(core, peri)
    common = {"graded": GRADED,
              "kappa_filed": KAPPA, "kappas": list(KAPPAS), "margin": MARGIN, "se_bootstrap_refits": SE_BOOT,
              "reps": a.reps, "learners": list(LEARNERS), "references": list(REFERENCES),
              "conservative": cons_names(KAPPAS)}
    for sub in ("core", "periphery"):
        (dest / sub).mkdir(parents=True, exist_ok=True)
    (dest / "core" / "policy_conservative.json").write_text(json.dumps(dict(common, **{
        "protocol": "Task 1's policy-learning protocol (10 fit, 20 train, 20 test seeds per repetition, seed 142, the "
                    "splits and uniform draws of policy_baselines.json) under the uniform logger and Task 1's holed "
                    "logger, with the conservative learners added; value = mean graded reward of the chosen setting "
                    "over the 12 contexts and 20 test seeds, from the full grid, holes included",
        "trace": str(trace), "n_fit": a.n_fit, "n_train": a.n_train, "n_test": len(seeds) - a.n_fit - a.n_train,
        "holes": {"per_context": HOLES_PER_CONTEXT, "seed": 142, "pairs": [list(x) for x in have]},
        "loggers": core}), indent=1))
    (dest / "periphery" / "policy_conservative_periphery.json").write_text(json.dumps(dict(common, **{
        "protocol": "the periphery under its recorded logger: per repetition (seed 142) the cells split in two halves, "
                    "alternating within each setting over a random order of contexts and cells; learners see the "
                    "training half; value = mean over the 12 contexts of the held-out half's mean graded reward of the "
                    "chosen setting, pooled over the contexts that logged it; the per-context held-out mean is a "
                    "diagnostic with its scored share",
        "trace": str(ptrace), "levers": list(PERI_LEVERS), "n_cells": int(len(log["ci"])),
        "n_settings": len(log["arms"]), "n_contexts": len(log["ctxs"]), "pairs_never_logged": int(n_pairs - logged),
        "dropped_cells_missing_objective": log["dropped"],
        "result": peri}), indent=1))
    (dest / "conservative_readout.json").write_text(json.dumps(dict(common, lines=lines), indent=1))
    for rw in REWARDS:
        for logger in ("uniform", "holed"):
            print(conservative_table(core[logger], rw, f"core, {logger} logger"))
        print(conservative_table(peri, rw, "periphery, recorded logger"))
    for name, ln in lines.items():
        print(f"[conservative] {name} {ln['learner']}: {ln['reads']}")
        for half in ("holed", "uniform", "periphery"):
            if half in ln:
                v = ln[half]
                print(f"      {half}: {ln['learner']} - {ln['against']} {v['mean']:+.4f} "
                      f"[{v['ci95'][0]:+.4f}, {v['ci95'][1]:+.4f}] over {v['n_reps']} repetitions")
        for k, v in ln.get("against_each", {}).items():
            print(f"      holed: {ln['learner']} - {k} {v['mean']:+.4f} [{v['ci95'][0]:+.4f}, {v['ci95'][1]:+.4f}]")
    print(f"[conservative] wrote {dest / 'core' / 'policy_conservative.json'}, "
          f"{dest / 'periphery' / 'policy_conservative_periphery.json'}, {dest / 'conservative_readout.json'}")
    return 0


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