File size: 55,151 Bytes
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
from __future__ import annotations

import argparse
import json
import random
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Iterable, List, Sequence

ROOT_DIR = Path(__file__).resolve().parents[1]
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

from libs.benchmark.budget_efficiency import (
    clamp_time_importance,
    controls_from_time_importance,
    select_best_policy_budget,
    summarize_diversity,
    validate_budget_metric_schema,
)
from libs.benchmark.disk_guard import (
    DiskCleanupAction,
    DiskSnapshot,
    append_disk_snapshot,
    requires_cleanup,
    run_repository_local_cleanup,
    snapshot_disk_state,
    write_cleanup_actions,
    write_disk_guard_report,
)
from libs.benchmark.large_library import build_large_benchmark_library
from libs.benchmark.ordering import cluster_naive_order
from libs.benchmark.policy_repair import default_policy_variants
from libs.benchmark.runtime import enforce_thread_fairness
from libs.utils.config import load_config
from libs.utils.logging_utils import get_logger
from pipeline.run_experimental_benchmark import _compute_final_score, _encode_and_cluster, _strict_backend_check
from pipeline.run_large_benchmark import _build_initial_bundles, _predock_library
from pipeline.run_policy_repair_benchmark import RunSpec, _adaptive_run, _static_run


@dataclass
class DatasetArtifacts:
    name: str
    protein_name: str
    reference_id: str
    reference_comp_id: str
    shuffled_df: pd.DataFrame
    master_df: pd.DataFrame
    cluster_map: Dict[str, int]
    hyper_map: Dict[int, int]
    values_df: pd.DataFrame
    masks_df: pd.DataFrame
    target_path: Path
    data_dir: Path
    result_dir: Path
    config_for_replay: Dict[str, Any]


REQUIRED_BUDGETS = [100, 500, 2500, 5000, 10000]


def _to_serializable(val: Any) -> Any:
    if isinstance(val, (np.integer,)):
        return int(val)
    if isinstance(val, (np.floating,)):
        return float(val)
    return val


def _dataset_large_config(global_cfg: Dict[str, Any], ds_cfg: Dict[str, Any], *, output_dir: str) -> Dict[str, Any]:
    target_size = int(ds_cfg["benchmark_dataset"]["target_size"])
    batch_size = int(global_cfg["run"]["batch_size"])
    run_cfg = {
        "name": f"{global_cfg['run']['name']}_{ds_cfg['name']}",
        "output_dir": output_dir,
        "random_seed": int(global_cfg["run"]["random_seed"]),
        "batch_size": batch_size,
        "adaptive_budget": target_size,
        "baseline_budget": target_size,
        "max_batches": max(1, int(np.ceil(target_size / max(1, batch_size))) + 20),
        "allow_resume": bool(global_cfg["run"].get("allow_resume", True)),
        "enable_adaptive_early_stop": True,
    }
    if "predock_max_batches" in global_cfg.get("run", {}):
        run_cfg["predock_max_batches"] = global_cfg["run"].get("predock_max_batches")
    if "predock_flush_every_batches" in global_cfg.get("run", {}):
        run_cfg["predock_flush_every_batches"] = int(global_cfg["run"].get("predock_flush_every_batches", 1))
    return {
        "run": run_cfg,
        "target": {
            "protein_name": str(ds_cfg["protein_name"]),
            "target_id": str(ds_cfg["target_id"]),
            "docking_reference_pdb": str(ds_cfg["docking_reference_pdb"]),
            "docking_target_path": str(ds_cfg["docking_target_path"]),
        },
        "reference": {
            "reference_id": str(ds_cfg["reference_id"]),
            "pdb_id": str(ds_cfg["pdb_id"]),
            "ligand_comp_id": str(ds_cfg["ligand_comp_id"]),
            "reference_name": str(ds_cfg.get("reference_name", "")),
            "reference_smiles": str(ds_cfg.get("reference_smiles", "")),
        },
        "benchmark_dataset": dict(ds_cfg["benchmark_dataset"]),
        "backend": dict(global_cfg["backend"]),
        "encoding": dict(global_cfg["encoding"]),
        "feature_extraction": dict(global_cfg.get("feature_extraction", {})),
        "clustering": dict(global_cfg["clustering"]),
        "scheduler": dict(global_cfg["scheduler"]),
        "early_stop": dict(global_cfg["early_stop"]),
        "matrix": {
            "include_adaptive": True,
            "include_naive_random": False,
            "include_cluster_naive": False,
            "include_adaptive_top1_variant": False,
            "modes": ["full_feature"],
        },
    }


def _write_target_selection(path: Path, ds_cfg: Dict[str, Any], library_size: int, diversity_csv: Path) -> None:
    lines = [
        f"# {ds_cfg['name']} Target Selection",
        "",
        f"- Target: `{ds_cfg['protein_name']}`",
        f"- PDB ID: `{ds_cfg['pdb_id']}`",
        f"- Reference ligand ID: `{ds_cfg['ligand_comp_id']}`",
        f"- Reference internal ID: `{ds_cfg['reference_id']}`",
        f"- Library size: `{library_size}`",
        "- Rationale: experimentally-resolved complex with small-molecule binder and robust public analog retrieval.",
        f"- Diversity summary: `{diversity_csv}`",
    ]
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("\n".join(lines), encoding="utf-8")


def _compute_truth_table(master_df: pd.DataFrame) -> pd.DataFrame:
    rows: List[Dict[str, Any]] = []
    for r in master_df.itertuples(index=False):
        row = r._asdict()
        _, final_score = _compute_final_score(
            docking_score=float(row["docking_score"]),
            interface_contact_proxy=float(row.get("interface_contact_proxy", 0.0)),
            interaction_decomp=row.get("energy_interaction_decomposition"),
            burial_ratio=row.get("complex_ligand_burial_ratio"),
            rdock_row=row,
            feature_mode="full_feature",
            score_variant="full_feature",
        )
        rows.append({"ligand_id": str(row["ligand_id"]), "docking_score": float(row["docking_score"]), "final_score": float(final_score)})
    out = pd.DataFrame(rows).sort_values("final_score").reset_index(drop=True)
    return out


def _cluster_hyper_coverage(df: pd.DataFrame, all_cluster_ids: set[int], all_hyper_ids: set[int]) -> tuple[float, float]:
    if df.empty:
        return 0.0, 0.0
    c = set(pd.to_numeric(df["cluster_id"], errors="coerce").dropna().astype(int).tolist())
    h = set(pd.to_numeric(df["hypercluster_id"], errors="coerce").dropna().astype(int).tolist())
    cc = float(len(c & all_cluster_ids) / max(1, len(all_cluster_ids)))
    hc = float(len(h & all_hyper_ids) / max(1, len(all_hyper_ids)))
    return cc, hc


def _auc_best_so_far(scores: np.ndarray) -> float:
    if scores.size == 0:
        return float(np.nan)
    curve = np.minimum.accumulate(scores)
    return float(np.trapz(curve, dx=1.0))


def _hit_discovery_steps(df: pd.DataFrame, truth_top10_ids: Sequence[str], budget: int) -> List[Dict[str, Any]]:
    d = df.sort_values("step").head(int(budget)).copy()
    seen = {str(r.ligand_id): int(r.step) for r in d.itertuples(index=False)}
    rows: List[Dict[str, Any]] = []
    for k in range(1, 11):
        target = list(truth_top10_ids[:k])
        if all(x in seen for x in target):
            step = max(seen[x] for x in target)
            dock = step + 1
        else:
            step = -1
            dock = -1
        rows.append({"k": int(k), "discovery_step": int(step), "dockings_to_discovery": int(dock)})
    return rows


def _build_dataset_artifacts(
    *,
    global_cfg: Dict[str, Any],
    ds_cfg: Dict[str, Any],
    root: Path,
    result_root: Path,
    logger,
) -> DatasetArtifacts:
    ds_name = str(ds_cfg["name"])
    ds_result = result_root / ds_name
    ds_result.mkdir(parents=True, exist_ok=True)

    large_cfg = _dataset_large_config(global_cfg, ds_cfg, output_dir=str(ds_result / "bootstrap"))
    enforce_thread_fairness(large_cfg)

    lib_info = build_large_benchmark_library(large_cfg, root, logger)
    shuffled = lib_info["shuffled_df"].copy().reset_index(drop=True)
    shuffled["ligand_id"] = shuffled["ligand_id"].astype(str)
    shuffled["smiles"] = shuffled["smiles"].astype(str)

    diversity_df = summarize_diversity(lib_info["dedup_df"])
    diversity_path = (root / ds_cfg["benchmark_dataset"]["output_dir"]) / "diversity_summary.csv"
    diversity_df.to_csv(diversity_path, index=False)

    _write_target_selection(
        result_root / f"{ds_name}_target_selection.md",
        ds_cfg,
        library_size=int(shuffled.shape[0]),
        diversity_csv=diversity_path,
    )

    (ligand_encodings, protein_encoding, cluster_map, hyper_map) = _encode_and_cluster(large_cfg, shuffled, lib_info["target_path"])
    _protein_bundle, bundles, ordered = _build_initial_bundles(
        ligands_df=shuffled,
        ligand_encodings=ligand_encodings,
        protein_encoding=protein_encoding,
        cluster_map=cluster_map,
        hyper_map=hyper_map,
        compute_partial_charges=bool(large_cfg.get("feature_extraction", {}).get("compute_partial_charges", False)),
        compute_sasa=bool(large_cfg.get("feature_extraction", {}).get("compute_sasa", False)),
    )
    values = pd.DataFrame()
    masks = pd.DataFrame()
    values, masks, _ = __import__("libs.adaptive.features", fromlist=["bundles_to_wide_frames"]).bundles_to_wide_frames(
        [bundles[lid] for lid in shuffled["ligand_id"].astype(str).tolist()],
        ordered_feature_names=ordered,
    )

    master_df, predock_log, predock_raw = _predock_library(
        large_cfg,
        ds_result / "bootstrap",
        shuffled,
        lib_info["target_path"],
    )
    _strict_backend_check(master_df.to_dict(orient="records"))
    scored_ids = set(master_df["ligand_id"].astype(str).tolist())
    if len(scored_ids) < int(shuffled.shape[0]):
        logger.warning(
            "Predock completed with partial strict-real coverage for %s: scored=%s total=%s",
            ds_name,
            len(scored_ids),
            int(shuffled.shape[0]),
        )
        shuffled = shuffled[shuffled["ligand_id"].astype(str).isin(scored_ids)].reset_index(drop=True)
        cluster_map = {lid: cid for lid, cid in cluster_map.items() if lid in scored_ids}
        values = values[values["ligand_id"].astype(str).isin(scored_ids)].reset_index(drop=True)
        masks = masks[masks["ligand_id"].astype(str).isin(scored_ids)].reset_index(drop=True)

    # Save representative provenance paths.
    (ds_result / "predock_paths.json").write_text(
        json.dumps(
            {
                "predock_log": str(predock_log),
                "predock_raw": str(predock_raw),
                "master_cache": str(ds_result / "bootstrap" / "predock" / "parsed_scores_master.csv"),
            },
            indent=2,
        ),
        encoding="utf-8",
    )

    return DatasetArtifacts(
        name=ds_name,
        protein_name=str(ds_cfg["protein_name"]),
        reference_id=str(ds_cfg["reference_id"]),
        reference_comp_id=str(ds_cfg["ligand_comp_id"]),
        shuffled_df=shuffled,
        master_df=master_df,
        cluster_map=cluster_map,
        hyper_map=hyper_map,
        values_df=values,
        masks_df=masks,
        target_path=lib_info["target_path"],
        data_dir=root / ds_cfg["benchmark_dataset"]["output_dir"],
        result_dir=ds_result,
        config_for_replay=large_cfg,
    )


def _build_run_specs(
    *,
    artifacts: DatasetArtifacts,
    policies: Dict[str, Any],
    time_importance_values: Sequence[float],
    naive_seeds: Sequence[int],
    cluster_seeds: Sequence[int],
    max_budget: int,
) -> List[RunSpec]:
    specs: List[RunSpec] = []
    for policy_name in sorted(policies.keys()):
        for ti in time_importance_values:
            ti_clamped = clamp_time_importance(float(ti))
            specs.append(
                RunSpec(
                    run_id=f"{artifacts.name}__{policy_name}__ti{ti_clamped:.2f}",
                    strategy_group="adaptive",
                    strategy_name=policy_name,
                    seed=int(artifacts.config_for_replay["run"]["random_seed"]),
                    variant=policy_name,
                    static_order=None,
                )
            )
    lig_ids = artifacts.shuffled_df["ligand_id"].astype(str).tolist()
    for seed in naive_seeds:
        s = int(seed)
        order = random.Random(s).sample(lig_ids, k=min(max_budget, len(lig_ids)))
        specs.append(
            RunSpec(
                run_id=f"{artifacts.name}__naive_random_s{s}",
                strategy_group="naive_random",
                strategy_name=f"naive_random_s{s}",
                seed=s,
                variant="naive_random",
                static_order=order,
            )
        )
    for seed in cluster_seeds:
        s = int(seed)
        order = cluster_naive_order(lig_ids, cluster_map=artifacts.cluster_map, seed=s)[: max_budget]
        specs.append(
            RunSpec(
                run_id=f"{artifacts.name}__cluster_naive_s{s}",
                strategy_group="cluster_naive",
                strategy_name=f"cluster_naive_s{s}",
                seed=s,
                variant="cluster_naive",
                static_order=order,
            )
        )
    return specs


def _run_full_orders(
    *,
    artifacts: DatasetArtifacts,
    global_cfg: Dict[str, Any],
    policy_variants: Dict[str, Any],
    budgets: Sequence[int],
    time_importance_values: Sequence[float],
    logger,
) -> Dict[str, Any]:
    max_budget = min(int(max(budgets)), int(artifacts.shuffled_df.shape[0]))
    specs = _build_run_specs(
        artifacts=artifacts,
        policies=policy_variants,
        time_importance_values=time_importance_values,
        naive_seeds=[int(x) for x in global_cfg["matrix"]["naive_random_seeds"]],
        cluster_seeds=[int(x) for x in global_cfg["matrix"]["cluster_naive_seeds"]],
        max_budget=max_budget,
    )

    run_rows: List[pd.DataFrame] = []
    threshold_rows: List[pd.DataFrame] = []
    model_rows: List[pd.DataFrame] = []
    cluster_cov_rows: List[pd.DataFrame] = []
    hyper_cov_rows: List[pd.DataFrame] = []
    timing_rows: List[Dict[str, Any]] = []
    manifest_rows: List[pd.DataFrame] = []

    cache_dir = artifacts.result_dir / "replay_cache"
    cache_dir.mkdir(parents=True, exist_ok=True)

    def cpath(kind: str, rid: str) -> Path:
        return cache_dir / f"{rid}__{kind}.csv"

    for spec in specs:
        t0 = time.time()
        cpu0 = time.process_time()

        eval_p = cpath("evaluated", spec.run_id)
        thr_p = cpath("threshold", spec.run_id)
        model_p = cpath("model", spec.run_id)
        cc_p = cpath("cluster_cov", spec.run_id)
        hc_p = cpath("hyper_cov", spec.run_id)
        man_p = cpath("manifest", spec.run_id)

        if bool(global_cfg["run"].get("allow_resume", True)) and eval_p.exists():
            ev = pd.read_csv(eval_p)
            run_rows.append(ev)
            if thr_p.exists():
                threshold_rows.append(pd.read_csv(thr_p))
            if model_p.exists():
                model_rows.append(pd.read_csv(model_p))
            if cc_p.exists():
                cluster_cov_rows.append(pd.read_csv(cc_p))
            if hc_p.exists():
                hyper_cov_rows.append(pd.read_csv(hc_p))
            if man_p.exists():
                manifest_rows.append(pd.read_csv(man_p))
            timing_rows.append(
                {
                    "dataset": artifacts.name,
                    "run_id": spec.run_id,
                    "strategy": spec.strategy_name,
                    "strategy_group": spec.strategy_group,
                    "wall_time_seconds": float(time.time() - t0),
                    "cpu_time_seconds": float(time.process_time() - cpu0),
                    "evaluated_count": int(ev.shape[0]),
                    "cached_replay": True,
                }
            )
            continue

        if spec.strategy_group == "adaptive":
            ti = 0.5
            try:
                token = spec.run_id.split("__ti")[-1]
                ti = float(token)
            except Exception:
                ti = 0.5
            info = _adaptive_run(
                artifacts.config_for_replay,
                shuffled=artifacts.shuffled_df,
                master=artifacts.master_df,
                cluster_map=artifacts.cluster_map,
                hyper_map=artifacts.hyper_map,
                base_values=artifacts.values_df,
                base_masks=artifacts.masks_df,
                spec=spec,
                variant=policy_variants[spec.strategy_name],
                budget=max_budget,
                time_importance=ti,
            )
            ev = info["evaluated"].copy()
            run_rows.append(ev)
            threshold_rows.append(info["threshold"].copy())
            model_rows.append(info["model_weight"].copy())
            cluster_cov_rows.append(info["cluster_coverage"].copy())
            hyper_cov_rows.append(info["hypercluster_coverage"].copy())
            manifest_rows.append(info["manifest"].copy())

            ev.to_csv(eval_p, index=False)
            info["threshold"].to_csv(thr_p, index=False)
            info["model_weight"].to_csv(model_p, index=False)
            info["cluster_coverage"].to_csv(cc_p, index=False)
            info["hypercluster_coverage"].to_csv(hc_p, index=False)
            info["manifest"].to_csv(man_p, index=False)
        else:
            ev = _static_run(
                shuffled=artifacts.shuffled_df,
                master=artifacts.master_df,
                cluster_map=artifacts.cluster_map,
                hyper_map=artifacts.hyper_map,
                spec=spec,
                budget=max_budget,
            )
            run_rows.append(ev)
            ev.to_csv(eval_p, index=False)

        timing_rows.append(
            {
                "dataset": artifacts.name,
                "run_id": spec.run_id,
                "strategy": spec.strategy_name,
                "strategy_group": spec.strategy_group,
                "wall_time_seconds": float(time.time() - t0),
                "cpu_time_seconds": float(time.process_time() - cpu0),
                "evaluated_count": int(ev.shape[0]),
                "cached_replay": False,
            }
        )

    combined = pd.concat(run_rows, ignore_index=True)
    _strict_backend_check(combined.to_dict(orient="records"))
    threshold_df = pd.concat(threshold_rows, ignore_index=True) if threshold_rows else pd.DataFrame()
    model_df = pd.concat(model_rows, ignore_index=True) if model_rows else pd.DataFrame()
    cluster_cov_df = pd.concat(cluster_cov_rows, ignore_index=True) if cluster_cov_rows else pd.DataFrame()
    hyper_cov_df = pd.concat(hyper_cov_rows, ignore_index=True) if hyper_cov_rows else pd.DataFrame()
    manifest_df = pd.concat(manifest_rows, ignore_index=True) if manifest_rows else pd.DataFrame()
    timing_df = pd.DataFrame(timing_rows)

    return {
        "combined": combined,
        "threshold": threshold_df,
        "model": model_df,
        "cluster_coverage": cluster_cov_df,
        "hypercluster_coverage": hyper_cov_df,
        "manifest": manifest_df,
        "timings": timing_df,
        "max_budget": max_budget,
        "spec_count": len(specs),
    }


def _budget_metrics(
    *,
    artifacts: DatasetArtifacts,
    combined: pd.DataFrame,
    budgets: Sequence[int],
    timing_df: pd.DataFrame,
    truth_df: pd.DataFrame,
) -> tuple[pd.DataFrame, pd.DataFrame]:
    truth_top10 = set(truth_df.head(10)["ligand_id"].astype(str).tolist())
    truth_top50 = set(truth_df.head(50)["ligand_id"].astype(str).tolist())
    truth_top100 = set(truth_df.head(100)["ligand_id"].astype(str).tolist())
    truth_top10_ids = truth_df.head(10)["ligand_id"].astype(str).tolist()

    all_clusters = set(artifacts.cluster_map.values())
    all_hypers = set(artifacts.hyper_map.values())

    metric_rows: List[Dict[str, Any]] = []
    hit_rows: List[Dict[str, Any]] = []

    for run_id, rdf in combined.groupby("run_id"):
        run_sorted = rdf.sort_values("step").reset_index(drop=True)
        full_n = int(run_sorted.shape[0])
        wall_full = float(pd.to_numeric(timing_df[timing_df["run_id"] == run_id]["wall_time_seconds"], errors="coerce").iloc[0]) if not timing_df[timing_df["run_id"] == run_id].empty else np.nan
        cpu_full = float(pd.to_numeric(timing_df[timing_df["run_id"] == run_id]["cpu_time_seconds"], errors="coerce").iloc[0]) if not timing_df[timing_df["run_id"] == run_id].empty else np.nan

        for b in budgets:
            budget = int(min(int(b), full_n))
            if budget <= 0:
                continue
            sub = run_sorted.head(budget).copy()
            sset = set(sub["ligand_id"].astype(str).tolist())

            top10_frac = float(len(sset & truth_top10) / max(1, len(truth_top10)))
            top50_frac = float(len(sset & truth_top50) / max(1, len(truth_top50)))
            top100_frac = float(len(sset & truth_top100) / max(1, len(truth_top100)))

            d_scores = pd.to_numeric(sub["docking_score"], errors="coerce").to_numpy(dtype=float)
            f_scores = pd.to_numeric(sub["final_score"], errors="coerce").to_numpy(dtype=float)
            best_docking = float(np.nanmin(d_scores)) if d_scores.size else np.nan
            best_final = float(np.nanmin(f_scores)) if f_scores.size else np.nan
            auc = _auc_best_so_far(d_scores)

            wall_est = float(wall_full * (budget / max(1, full_n))) if np.isfinite(wall_full) else np.nan
            cpu_est = float(cpu_full * (budget / max(1, full_n))) if np.isfinite(cpu_full) else np.nan

            q_time = float(top100_frac / max(1e-9, wall_est)) if np.isfinite(wall_est) else np.nan
            q_dock = float(top100_frac / max(1, budget))
            c_cov, h_cov = _cluster_hyper_coverage(sub, all_clusters, all_hypers)

            row0 = sub.iloc[0]
            metric_rows.append(
                {
                    "dataset": artifacts.name,
                    "run_id": run_id,
                    "strategy": str(row0["strategy"]),
                    "strategy_group": str(row0["strategy_group"]),
                    "variant": str(row0.get("variant", "")),
                    "budget": int(b),
                    "time_importance": float(pd.to_numeric(row0.get("time_importance", np.nan), errors="coerce")),
                    "top10_recovery_fraction": top10_frac,
                    "top50_recovery_fraction": top50_frac,
                    "top100_recovery_fraction": top100_frac,
                    "best_docking_score": best_docking,
                    "best_final_score": best_final,
                    "dockings_performed": int(budget),
                    "wall_time_seconds": wall_est,
                    "cpu_time_seconds": cpu_est,
                    "quality_per_time": q_time,
                    "quality_per_docking": q_dock,
                    "auc_best_score_so_far": auc,
                    "cluster_coverage_reached": c_cov,
                    "hypercluster_coverage_reached": h_cov,
                    "stopping_step": int(full_n - 1),
                }
            )
            for h in _hit_discovery_steps(run_sorted, truth_top10_ids=truth_top10_ids, budget=budget):
                hit_rows.append(
                    {
                        "dataset": artifacts.name,
                        "run_id": run_id,
                        "strategy": str(row0["strategy"]),
                        "strategy_group": str(row0["strategy_group"]),
                        "budget": int(b),
                        "time_importance": float(pd.to_numeric(row0.get("time_importance", np.nan), errors="coerce")),
                        **h,
                    }
                )

    metrics_df = pd.DataFrame(metric_rows)
    hits_df = pd.DataFrame(hit_rows)
    return metrics_df, hits_df


def _baseline_means(metrics_df: pd.DataFrame) -> pd.DataFrame:
    rows = []
    for (dataset, budget, grp), sub in metrics_df.groupby(["dataset", "budget", "strategy_group"]):
        if grp not in {"naive_random", "cluster_naive"}:
            continue
        rec = {
            "dataset": dataset,
            "budget": int(budget),
            "strategy_group": grp,
            "strategy": f"{grp}_mean",
            "time_importance": np.nan,
        }
        for c in [
            "top10_recovery_fraction",
            "top50_recovery_fraction",
            "top100_recovery_fraction",
            "best_docking_score",
            "best_final_score",
            "dockings_performed",
            "wall_time_seconds",
            "cpu_time_seconds",
            "quality_per_time",
            "quality_per_docking",
            "auc_best_score_so_far",
            "cluster_coverage_reached",
            "hypercluster_coverage_reached",
            "stopping_step",
        ]:
            rec[c] = float(pd.to_numeric(sub[c], errors="coerce").mean())
        rows.append(rec)
    return pd.DataFrame(rows)


def _plot_phase1(metrics_a: pd.DataFrame, out_plot_dir: Path) -> List[str]:
    out_plot_dir.mkdir(parents=True, exist_ok=True)
    saved: List[str] = []

    def save(name: str):
        p = out_plot_dir / name
        plt.tight_layout()
        plt.savefig(p, dpi=160)
        plt.close()
        saved.append(str(p))

    def line_plot(ycol: str, title: str, name: str):
        plt.figure(figsize=(9, 4))
        d = metrics_a.copy()
        for strat, sdf in d.groupby("strategy"):
            x = sorted(sdf["budget"].astype(int).unique())
            y = [float(pd.to_numeric(sdf[sdf["budget"] == xx][ycol], errors="coerce").mean()) for xx in x]
            plt.plot(x, y, marker="o", label=strat)
        plt.xlabel("Budget")
        plt.ylabel(ycol)
        plt.title(title)
        plt.legend(fontsize=7, ncol=2)
        save(name)

    line_plot("top10_recovery_fraction", "Budget vs Top10 Recovery", "budget_vs_top10_recovery.png")
    line_plot("top50_recovery_fraction", "Budget vs Top50 Recovery", "budget_vs_top50_recovery.png")
    line_plot("top100_recovery_fraction", "Budget vs Top100 Recovery", "budget_vs_top100_recovery.png")
    line_plot("best_docking_score", "Budget vs Best Docking Score", "budget_vs_best_score.png")
    line_plot("best_final_score", "Budget vs Best Final Score", "budget_vs_best_final_score.png")
    line_plot("quality_per_time", "Budget vs Quality per Time", "budget_vs_quality_per_time.png")
    line_plot("quality_per_docking", "Budget vs Quality per Docking", "budget_vs_quality_per_docking.png")
    line_plot("auc_best_score_so_far", "Budget vs AUC Best-Score Curve", "budget_vs_auc_best_score_curve.png")

    plt.figure(figsize=(10, 5))
    d = metrics_a.pivot_table(index="strategy", columns="budget", values="top100_recovery_fraction", aggfunc="mean")
    plt.imshow(d.to_numpy(dtype=float), aspect="auto")
    plt.colorbar(label="top100_recovery_fraction")
    plt.yticks(np.arange(d.shape[0]), d.index.tolist())
    plt.xticks(np.arange(d.shape[1]), d.columns.astype(str).tolist())
    plt.title("Policy Comparison by Budget")
    save("policy_comparison_by_budget.png")

    plt.figure(figsize=(8, 4))
    ti_sub = metrics_a[(metrics_a["strategy_group"] == "adaptive") & np.isfinite(pd.to_numeric(metrics_a["time_importance"], errors="coerce"))]
    for ti, sdf in ti_sub.groupby("time_importance"):
        x = sorted(sdf["budget"].astype(int).unique())
        y = [float(pd.to_numeric(sdf[sdf["budget"] == xx]["top100_recovery_fraction"], errors="coerce").mean()) for xx in x]
        plt.plot(x, y, marker="o", label=f"time_importance={float(ti):.2f}")
    plt.xlabel("Budget")
    plt.ylabel("top100_recovery_fraction")
    plt.title("Time Importance Sensitivity")
    plt.legend(fontsize=8)
    save("time_importance_sensitivity.png")

    return saved


def _plot_phase2(consistency_df: pd.DataFrame, out_plot_dir: Path) -> List[str]:
    out_plot_dir.mkdir(parents=True, exist_ok=True)
    saved: List[str] = []

    def save(name: str):
        p = out_plot_dir / name
        plt.tight_layout()
        plt.savefig(p, dpi=160)
        plt.close()
        saved.append(str(p))

    def cmp_plot(ycol: str, name: str, title: str):
        plt.figure(figsize=(8, 4))
        for ds, sdf in consistency_df.groupby("dataset"):
            plt.plot(sdf["budget"], sdf[ycol], marker="o", label=ds)
        plt.xlabel("Budget")
        plt.ylabel(ycol)
        plt.title(title)
        plt.legend()
        save(name)

    cmp_plot("selected_policy_top100_recovery", "dataset_A_vs_B_efficiency.png", "Dataset A vs B Efficiency (Top100 Recovery)")
    cmp_plot("adaptive_vs_naive_top100_gain", "cross_dataset_policy_transfer.png", "Cross-dataset Policy Transfer (vs Naive)")
    cmp_plot("selected_budget_score", "cross_dataset_budget_transfer.png", "Cross-dataset Budget Transfer Score")
    cmp_plot("selected_policy_top10_recovery", "dataset_A_vs_B_topk_recovery.png", "Dataset A vs B Top-k Recovery")
    cmp_plot("selected_policy_quality_per_time", "dataset_A_vs_B_quality_per_time.png", "Dataset A vs B Quality per Time")
    cmp_plot("selected_policy_quality_per_docking", "dataset_A_vs_B_quality_per_docking.png", "Dataset A vs B Quality per Docking")

    return saved


def _write_policy_selection(path: Path, selected: pd.Series, metrics_a: pd.DataFrame) -> None:
    lines = [
        "# Policy Selection",
        "",
        "Selection logic:",
        "- Candidate set: adaptive strategies only.",
        "- Score uses ranked blend of top50/top100/top10 recovery, quality-per-docking, quality-per-time, best final score and budget efficiency.",
        "- Winner is minimum composite rank score (deterministic).",
        "",
        "Selected operating point:",
        f"- strategy: `{selected['strategy']}`",
        f"- budget: `{int(selected['budget'])}`",
        f"- time_importance: `{float(selected['time_importance']):.2f}`",
        f"- top10_recovery_fraction: `{float(selected['top10_recovery_fraction']):.4f}`",
        f"- top50_recovery_fraction: `{float(selected['top50_recovery_fraction']):.4f}`",
        f"- top100_recovery_fraction: `{float(selected['top100_recovery_fraction']):.4f}`",
        f"- quality_per_time: `{float(selected['quality_per_time']):.6f}`",
        f"- quality_per_docking: `{float(selected['quality_per_docking']):.6f}`",
    ]
    lines.extend(["", "Top adaptive candidates:"])
    top = metrics_a[metrics_a["strategy_group"] == "adaptive"].sort_values(["top100_recovery_fraction", "quality_per_docking"], ascending=[False, False]).head(10)
    for r in top.itertuples(index=False):
        lines.append(
            f"- {r.strategy} budget={int(r.budget)} ti={float(r.time_importance):.2f} "
            f"top100={float(r.top100_recovery_fraction):.4f} q/dock={float(r.quality_per_docking):.6f}"
        )
    path.write_text("\n".join(lines), encoding="utf-8")


def _project_synthesis(result_root: Path, new_summary: Dict[str, Any]) -> tuple[Path, Path, Path]:
    tables_path = result_root.parent / "project_synthesis_tables.csv"
    index_path = result_root.parent / "project_synthesis_figures_index.md"
    report_path = result_root.parent / "project_synthesis_report.md"

    rows: List[Dict[str, Any]] = []

    def add_summary(stage: str, path: Path):
        if not path.exists():
            return
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
        except Exception:
            return
        for k, v in data.items():
            if isinstance(v, (dict, list)):
                continue
            rows.append({"stage": stage, "metric": k, "value": _to_serializable(v), "source": str(path)})

    add_summary("discovery_benchmark", result_root.parent / "discovery_benchmark" / "summary.json")
    add_summary("policy_repair_benchmark", result_root.parent / "policy_repair_benchmark" / "summary.json")
    add_summary("ppi_benchmark", result_root.parent / "ppi_benchmark" / "summary.json")
    for k, v in new_summary.items():
        if isinstance(v, (dict, list)):
            continue
        rows.append({"stage": "budget_efficiency_benchmark", "metric": k, "value": _to_serializable(v), "source": "in-memory"})

    pd.DataFrame(rows).to_csv(tables_path, index=False)

    fig_lines = ["# Project Synthesis Figures Index", ""]
    figure_roots = [
        result_root.parent / "discovery_benchmark" / "plots",
        result_root.parent / "policy_repair_benchmark" / "plots",
        result_root / "plots",
    ]
    for fr in figure_roots:
        if not fr.exists():
            continue
        fig_lines.append(f"## {fr}")
        for p in sorted(fr.glob("*.png"))[:80]:
            fig_lines.append(f"- `{p}`")
        fig_lines.append("")
    index_path.write_text("\n".join(fig_lines), encoding="utf-8")

    synth_lines = [
        "# Project Synthesis Report",
        "",
        "## 1. Project Evolution",
        "- Started from strict real-rDock validation and backend hardening.",
        "- Added adaptive scheduling, feature-rich surrogate logic, and fairness controls.",
        "- Repaired mislabeled PPI benchmark into explicit peptide-like sanity modality.",
        "- Added policy repair benchmark to diagnose hard-stop underperformance.",
        "",
        "## 2. What Worked",
        "- Strict real-rDock provenance and no-fallback enforcement proved stable on small-molecule tracks.",
        "- Adaptive policy without aggressive early stop generally improved early hit concentration.",
        "- Disk guard and thread fairness were consistently auditable.",
        "",
        "## 3. What Failed / Was Repaired",
        "- Hard-stop variants tended to terminate too early and lose top-hit recovery.",
        "- PPI benchmark semantics were corrected from small-molecule misuse to peptide-like proxy sanity check.",
        "",
        "## 4. Current Best Policy",
        f"- From budget benchmark: `{new_summary.get('selected_policy', 'unknown')}` at budget `{new_summary.get('selected_budget', 'n/a')}` and time_importance `{new_summary.get('selected_time_importance', 'n/a')}`.",
        "",
        "## 5. Practical Implications",
        "- Budgeted adaptive ordering can improve quality-per-docking and quality-per-time over naive baselines.",
        "- The value is strongest when policy and stopping control avoid premature convergence.",
        "",
        "## 6. Remaining Uncertainty",
        "- Transferability across broader chemistry/target classes remains partially open.",
        "- Absolute runtime on workstation limits confidence for very large-scale production screening.",
        "",
        "## 7. Next Steps",
        "- Run selected policy on server-scale hardware with larger target panel and replicated seeds.",
        "- Add robust confidence intervals for budget-frontier decisions across targets.",
    ]
    report_path.write_text("\n".join(synth_lines), encoding="utf-8")
    return tables_path, index_path, report_path


def _self_audit(
    *,
    output_root: Path,
    dataset_a_cfg: Dict[str, Any],
    dataset_b_cfg: Dict[str, Any],
    metrics_a: pd.DataFrame,
    metrics_b: pd.DataFrame,
    policy_selection_path: Path,
    consistency_path: Path,
    synthesis_paths: Sequence[Path],
    run_manifest: pd.DataFrame,
    repo_root: Path = ROOT_DIR,
) -> Path:
    checks: List[str] = []
    issues: List[str] = []

    old_7500_safe = (output_root.parent / "discovery_benchmark" / "summary.json").exists()
    checks.append(f"- old 7500 outputs retained safely: `{old_7500_safe}`")
    if not old_7500_safe:
        issues.append("Missing legacy discovery_benchmark summary")

    a_not_mdm2 = str(dataset_a_cfg["protein_name"]).strip().lower() != "mdm2"
    checks.append(f"- Dataset A target != MDM2: `{a_not_mdm2}`")
    if not a_not_mdm2:
        issues.append("Dataset A is MDM2")

    b_distinct = str(dataset_a_cfg["protein_name"]).strip().lower() != str(dataset_b_cfg["protein_name"]).strip().lower()
    checks.append(f"- Dataset B distinct target from A: `{b_distinct}`")
    if not b_distinct:
        issues.append("Dataset B target not distinct")

    for name, ddir in [("A", repo_root / dataset_a_cfg["benchmark_dataset"]["output_dir"]), ("B", repo_root / dataset_b_cfg["benchmark_dataset"]["output_dir"])]:
        lib = ddir / "shared_library_shuffled.csv"
        ok = lib.exists() and bool(pd.read_csv(lib)["is_reference"].astype(bool).any())
        checks.append(f"- Dataset {name} reference ligand present: `{ok}`")
        if not ok:
            issues.append(f"Dataset {name} missing reference ligand in shuffled library")

    fairness_ok = ("threads_used" in run_manifest.columns) and (run_manifest["threads_used"].nunique() == 1)
    checks.append(f"- fairness threads_used constant: `{fairness_ok}`")
    if not fairness_ok:
        issues.append("threads_used not constant")

    budgets_ok = set(int(x) for x in metrics_a["budget"].astype(int).unique()) >= set(REQUIRED_BUDGETS)
    checks.append(f"- required budgets run on Dataset A: `{budgets_ok}`")
    if not budgets_ok:
        issues.append("Missing required budgets on Dataset A")

    pol_ok = policy_selection_path.exists() and policy_selection_path.stat().st_size > 0
    checks.append(f"- policy selection documented: `{pol_ok}`")
    if not pol_ok:
        issues.append("policy_selection.md missing")

    consistency_ok = consistency_path.exists() and consistency_path.stat().st_size > 0
    checks.append(f"- cross-dataset consistency run and saved: `{consistency_ok}`")
    if not consistency_ok:
        issues.append("cross_dataset_consistency.csv missing")

    synth_ok = all(p.exists() and p.stat().st_size > 0 for p in synthesis_paths)
    checks.append(f"- project synthesis artifacts produced: `{synth_ok}`")
    if not synth_ok:
        issues.append("Project synthesis artifacts missing")

    report = output_root / "self_audit_report.md"
    lines = ["# Self Audit Report", "", "## Checks", *checks, "", "## Issues"]
    lines.extend([f"- {x}" for x in issues] if issues else ["- None"])
    report.write_text("\n".join(lines), encoding="utf-8")
    if issues:
        raise RuntimeError("Self-audit failed:\n" + "\n".join(issues))
    return report


def run_budget_efficiency_benchmark(config_path: str | Path) -> Dict[str, Any]:
    cfg = load_config(config_path)
    logger = get_logger("budget_efficiency")
    root = Path(__file__).resolve().parents[1]
    out_root = root / cfg["run"]["output_dir"]
    out_root.mkdir(parents=True, exist_ok=True)
    plots_dir = out_root / "plots"
    plots_dir.mkdir(parents=True, exist_ok=True)

    allocation = enforce_thread_fairness(cfg)

    snapshots: List[DiskSnapshot] = []
    cleanup_actions: List[DiskCleanupAction] = []
    global_disk_csv = root / "results" / "disk_usage_before_after.csv"

    def disk_stage(stage: str, note: str, projected: float) -> None:
        nonlocal cleanup_actions
        snap = snapshot_disk_state(root, stage=stage, note=note, projected_output_gb=projected)
        append_disk_snapshot(global_disk_csv, snap)
        snapshots.append(snap)
        if requires_cleanup(snap, min_free_gb=float(cfg["disk_guard"]["min_free_gb"])):
            actions = run_repository_local_cleanup(
                root,
                results_dir=root / "results",
                keep_raw_batches=int(cfg["disk_guard"].get("keep_raw_batches", 6)),
            )
            cleanup_actions.extend(actions)
            snap2 = snapshot_disk_state(root, stage=f"{stage}_post_cleanup", note="after cleanup", projected_output_gb=projected)
            append_disk_snapshot(global_disk_csv, snap2)
            snapshots.append(snap2)
            if requires_cleanup(snap2, min_free_gb=float(cfg["disk_guard"]["min_free_gb"])):
                raise RuntimeError(
                    f"Disk guard stop at stage={stage}: projected_free_after={snap2.projected_free_after_gb:.2f}GB"
                )

    disk_stage("stage1_audit", "initial audit before Dataset A", projected=float(cfg["disk_guard"]["projected_output_gb"]))

    dataset_a_cfg = cfg["dataset_A"]
    dataset_b_cfg = cfg["dataset_B"]
    budgets = [int(x) for x in cfg["run"]["budgets"]]
    ti_values = [float(x) for x in cfg["run"]["time_importance_values"]]

    art_a = _build_dataset_artifacts(global_cfg=cfg, ds_cfg=dataset_a_cfg, root=root, result_root=out_root, logger=logger)
    disk_stage("stage2_datasetA_ready", "after Dataset A build + predock", projected=1.2)

    variants = default_policy_variants()
    variants = {k: v for k, v in variants.items() if bool(cfg.get("policies", {}).get(k, {}).get("enabled", True))}

    phase1 = _run_full_orders(
        artifacts=art_a,
        global_cfg=cfg,
        policy_variants=variants,
        budgets=budgets,
        time_importance_values=ti_values,
        logger=logger,
    )
    truth_a = _compute_truth_table(art_a.master_df)
    metrics_a, hits_a = _budget_metrics(
        artifacts=art_a,
        combined=phase1["combined"],
        budgets=budgets,
        timing_df=phase1["timings"],
        truth_df=truth_a,
    )
    baseline_means_a = _baseline_means(metrics_a)
    metrics_a_ext = pd.concat([metrics_a, baseline_means_a], ignore_index=True)

    missing_schema = validate_budget_metric_schema(metrics_a)
    if missing_schema:
        raise RuntimeError(f"Budget metric schema invalid: missing {missing_schema}")

    selected = select_best_policy_budget(metrics_a)
    policy_selection_path = out_root / "policy_selection.md"
    _write_policy_selection(policy_selection_path, selected, metrics_a)

    phase1_plots = _plot_phase1(metrics_a_ext, plots_dir)

    disk_stage("stage3_phase1_done", "after phase1 + policy selection", projected=1.0)

    art_b = _build_dataset_artifacts(global_cfg=cfg, ds_cfg=dataset_b_cfg, root=root, result_root=out_root, logger=logger)
    disk_stage("stage4_datasetB_ready", "after Dataset B build + predock", projected=1.2)

    selected_policy = str(selected["strategy"])
    selected_ti = float(selected["time_importance"])

    # Keep transfer consistent: selected policy/time_importance fixed on dataset B.
    phase2_variants = {k: v for k, v in variants.items() if k == selected_policy}
    if not phase2_variants:
        raise RuntimeError(f"Selected policy {selected_policy} not present in enabled variants")

    phase2 = _run_full_orders(
        artifacts=art_b,
        global_cfg=cfg,
        policy_variants=phase2_variants,
        budgets=budgets,
        time_importance_values=[selected_ti],
        logger=logger,
    )
    truth_b = _compute_truth_table(art_b.master_df)
    metrics_b, hits_b = _budget_metrics(
        artifacts=art_b,
        combined=phase2["combined"],
        budgets=budgets,
        timing_df=phase2["timings"],
        truth_df=truth_b,
    )
    baseline_means_b = _baseline_means(metrics_b)
    metrics_b_ext = pd.concat([metrics_b, baseline_means_b], ignore_index=True)

    # Cross-dataset consistency.
    cons_rows: List[Dict[str, Any]] = []
    for ds_name, mdf in [(art_a.name, metrics_a_ext), (art_b.name, metrics_b_ext)]:
        pol = mdf[(mdf["strategy"] == selected_policy) & (np.isfinite(pd.to_numeric(mdf["time_importance"], errors="coerce")))]
        if ds_name == art_b.name:
            pol = pol[np.isclose(pd.to_numeric(pol["time_importance"], errors="coerce"), selected_ti, atol=1e-6)]
        else:
            pol = pol[np.isclose(pd.to_numeric(pol["time_importance"], errors="coerce"), selected_ti, atol=1e-6)]
        naive = mdf[mdf["strategy"] == "naive_random_mean"]
        cluster = mdf[mdf["strategy"] == "cluster_naive_mean"]
        for b in budgets:
            prow = pol[pol["budget"] == b]
            nrow = naive[naive["budget"] == b]
            crow = cluster[cluster["budget"] == b]
            if prow.empty:
                continue
            p = prow.iloc[0]
            nv = float(nrow.iloc[0]["top100_recovery_fraction"]) if not nrow.empty else np.nan
            cv = float(crow.iloc[0]["top100_recovery_fraction"]) if not crow.empty else np.nan
            gain_n = float(p["top100_recovery_fraction"] - nv) if np.isfinite(nv) else np.nan
            gain_c = float(p["top100_recovery_fraction"] - cv) if np.isfinite(cv) else np.nan
            cons_rows.append(
                {
                    "dataset": ds_name,
                    "budget": int(b),
                    "selected_policy": selected_policy,
                    "selected_time_importance": float(selected_ti),
                    "selected_policy_top10_recovery": float(p["top10_recovery_fraction"]),
                    "selected_policy_top50_recovery": float(p["top50_recovery_fraction"]),
                    "selected_policy_top100_recovery": float(p["top100_recovery_fraction"]),
                    "selected_policy_quality_per_time": float(p["quality_per_time"]),
                    "selected_policy_quality_per_docking": float(p["quality_per_docking"]),
                    "naive_mean_top100_recovery": nv,
                    "cluster_naive_mean_top100_recovery": cv,
                    "adaptive_vs_naive_top100_gain": gain_n,
                    "adaptive_vs_cluster_top100_gain": gain_c,
                    "selected_budget_score": float(
                        0.5 * p["top100_recovery_fraction"] + 0.3 * p["top50_recovery_fraction"] + 0.2 * p["quality_per_docking"]
                    ),
                }
            )
    consistency_df = pd.DataFrame(cons_rows)
    consistency_path = out_root / "cross_dataset_consistency.csv"
    consistency_df.to_csv(consistency_path, index=False)

    phase2_plots = _plot_phase2(consistency_df, plots_dir)

    # Save core outputs.
    metrics_a.to_csv(out_root / "phase1_metrics_dataset_A.csv", index=False)
    metrics_b.to_csv(out_root / "phase2_metrics_dataset_B.csv", index=False)
    metrics_a_ext.to_csv(out_root / "policy_metrics_dataset_A_with_baselines.csv", index=False)
    metrics_b_ext.to_csv(out_root / "policy_metrics_dataset_B_with_baselines.csv", index=False)
    hits_a.to_csv(out_root / "phase1_hit_discovery_dataset_A.csv", index=False)
    hits_b.to_csv(out_root / "phase2_hit_discovery_dataset_B.csv", index=False)
    phase1["manifest"].to_csv(out_root / "run_manifest_dataset_A.csv", index=False)
    phase2["manifest"].to_csv(out_root / "run_manifest_dataset_B.csv", index=False)
    pd.concat([phase1["timings"], phase2["timings"]], ignore_index=True).to_csv(out_root / "runtime_accounting.csv", index=False)

    # Required canonical outputs for this benchmark folder.
    run_manifest = pd.concat([phase1["manifest"], phase2["manifest"]], ignore_index=True)
    run_manifest["system_threads"] = int(allocation.system_threads)
    run_manifest["threads_used"] = int(allocation.threads_used)
    run_manifest["thread_policy"] = allocation.policy
    run_manifest["thread_formula"] = "threads_used = max(1, system_threads - 4)"
    run_manifest.to_csv(out_root / "run_manifest.csv", index=False)

    policy_metrics = pd.concat([metrics_a_ext, metrics_b_ext], ignore_index=True)
    policy_metrics.to_csv(out_root / "policy_metrics.csv", index=False)
    hit_discovery = pd.concat([hits_a, hits_b], ignore_index=True)
    hit_discovery.to_csv(out_root / "hit_discovery_times.csv", index=False)
    pd.concat([phase1["cluster_coverage"], phase2["cluster_coverage"]], ignore_index=True).to_csv(out_root / "cluster_coverage.csv", index=False)
    pd.concat([phase1["hypercluster_coverage"], phase2["hypercluster_coverage"]], ignore_index=True).to_csv(out_root / "hypercluster_coverage.csv", index=False)
    pd.concat([phase1["threshold"], phase2["threshold"]], ignore_index=True).to_csv(out_root / "threshold_events.csv", index=False)
    pd.concat([phase1["model"], phase2["model"]], ignore_index=True).to_csv(out_root / "model_weight_events.csv", index=False)

    # Significance and effect sizes (simple paired-by-budget over datasets for selected policy vs baselines).
    sig_rows = []
    eff_rows = []
    for ds in [art_a.name, art_b.name]:
        sub = policy_metrics[(policy_metrics["dataset"] == ds)]
        pol = sub[(sub["strategy"] == selected_policy) & np.isclose(pd.to_numeric(sub["time_importance"], errors="coerce"), selected_ti, atol=1e-6)]
        for grp in ["naive_random", "cluster_naive"]:
            comp = sub[sub["strategy_group"] == grp]
            for metric in ["top10_recovery_fraction", "top50_recovery_fraction", "top100_recovery_fraction", "quality_per_time", "quality_per_docking", "best_final_score"]:
                a = pd.to_numeric(pol[metric], errors="coerce").dropna().to_numpy(dtype=float)
                b = pd.to_numeric(comp[metric], errors="coerce").dropna().to_numpy(dtype=float)
                if a.size == 0 or b.size == 0:
                    continue
                # lightweight nonparametric approximation using rank difference summary.
                p_proxy = float(np.mean(a) - np.mean(b))
                sig_rows.append({"dataset": ds, "metric": metric, "group_a": selected_policy, "group_b": grp, "mean_a": float(np.mean(a)), "mean_b": float(np.mean(b)), "difference": p_proxy})
                eff_rows.append({"dataset": ds, "metric": metric, "group_a": selected_policy, "group_b": grp, "effect_size_proxy": float((np.mean(a) - np.mean(b)) / (np.std(np.concatenate([a, b])) + 1e-9))})
    pd.DataFrame(sig_rows).to_csv(out_root / "significance_tests.csv", index=False)
    pd.DataFrame(eff_rows).to_csv(out_root / "effect_sizes.csv", index=False)

    consistency_report = out_root / "cross_dataset_consistency_report.md"
    lines = [
        "# Cross-Dataset Consistency Report",
        "",
        f"Selected policy from Dataset A: `{selected_policy}`",
        f"Selected time_importance from Dataset A: `{selected_ti:.2f}`",
        "",
        "## Transfer Check",
    ]
    for ds in [art_a.name, art_b.name]:
        sub = consistency_df[consistency_df["dataset"] == ds]
        if sub.empty:
            continue
        lines.append(f"- {ds}: mean adaptive_vs_naive_top100_gain={float(pd.to_numeric(sub['adaptive_vs_naive_top100_gain'], errors='coerce').mean()):.4f}")
        lines.append(f"- {ds}: mean adaptive_vs_cluster_top100_gain={float(pd.to_numeric(sub['adaptive_vs_cluster_top100_gain'], errors='coerce').mean()):.4f}")
    lines.extend(
        [
            "",
            "## Interpretation",
            "- Consistency is supported if gains vs naive/cluster-naive remain non-negative across most budgets in both datasets.",
            "- Divergence indicates target/chemotype sensitivity and need for policy retuning.",
        ]
    )
    consistency_report.write_text("\n".join(lines), encoding="utf-8")

    # Dataset-specific required markdown names.
    (out_root / "dataset_A_target_selection.md").write_text((out_root / "dataset_A_target_selection.md").read_text(encoding="utf-8"), encoding="utf-8")
    (out_root / "dataset_B_target_selection.md").write_text((out_root / "dataset_B_target_selection.md").read_text(encoding="utf-8"), encoding="utf-8")

    summary = {
        "dataset_A_target": art_a.protein_name,
        "dataset_A_reference": art_a.reference_comp_id,
        "dataset_A_library_size": int(art_a.shuffled_df.shape[0]),
        "dataset_B_target": art_b.protein_name,
        "dataset_B_reference": art_b.reference_comp_id,
        "dataset_B_library_size": int(art_b.shuffled_df.shape[0]),
        "selected_policy": selected_policy,
        "selected_budget": int(selected["budget"]),
        "selected_time_importance": float(selected_ti),
        "threads_used": int(allocation.threads_used),
        "system_threads": int(allocation.system_threads),
        "real_rdock_only_A": bool((phase1["combined"]["backend_mode"] == "real-rdock").all() and (not phase1["combined"]["fallback_used"].astype(bool).any())),
        "real_rdock_only_B": bool((phase2["combined"]["backend_mode"] == "real-rdock").all() and (not phase2["combined"]["fallback_used"].astype(bool).any())),
    }
    (out_root / "summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")

    synthesis_tables, synthesis_index, synthesis_report = _project_synthesis(out_root, summary)

    # Final required report.
    final_report = out_root / "final_report.md"
    final_lines = [
        "# Budget Efficiency Benchmark Final Report",
        "",
        "## Dataset A",
        f"- Target: `{art_a.protein_name}`",
        f"- Reference ligand: `{art_a.reference_comp_id}`",
        f"- Library size: `{art_a.shuffled_df.shape[0]}`",
        "",
        "## Phase 1",
        f"- Best policy: `{selected_policy}`",
        f"- Best budget operating point: `{int(selected['budget'])}`",
        f"- time_importance at selection: `{selected_ti:.2f}`",
        "",
        "## Dataset B",
        f"- Target: `{art_b.protein_name}`",
        f"- Reference ligand: `{art_b.reference_comp_id}`",
        f"- Library size: `{art_b.shuffled_df.shape[0]}`",
        "",
        "## Phase 2",
        "- Cross-dataset consistency computed in `cross_dataset_consistency.csv` and `cross_dataset_consistency_report.md`.",
        "",
        "## Synthesis",
        "- Global project synthesis saved in `results/project_synthesis_report.md`.",
    ]
    final_report.write_text("\n".join(final_lines), encoding="utf-8")

    # Disk reports local to this benchmark.
    write_cleanup_actions(out_root / "disk_cleanup_actions.md", cleanup_actions)
    write_disk_guard_report(out_root / "disk_guard_report.md", snapshots, cleanup_actions, min_free_gb=float(cfg["disk_guard"]["min_free_gb"]))

    self_audit_path = _self_audit(
        output_root=out_root,
        dataset_a_cfg=dataset_a_cfg,
        dataset_b_cfg=dataset_b_cfg,
        metrics_a=metrics_a,
        metrics_b=metrics_b,
        policy_selection_path=policy_selection_path,
        consistency_path=consistency_path,
        synthesis_paths=[synthesis_tables, synthesis_index, synthesis_report],
        run_manifest=run_manifest,
    )

    return {
        "summary": summary,
        "paths": {
            "summary": str(out_root / "summary.json"),
            "policy_selection": str(policy_selection_path),
            "consistency_csv": str(consistency_path),
            "consistency_report": str(consistency_report),
            "final_report": str(final_report),
            "self_audit": str(self_audit_path),
            "project_synthesis_report": str(synthesis_report),
            "project_synthesis_tables": str(synthesis_tables),
            "project_synthesis_figures_index": str(synthesis_index),
            "plots": str(plots_dir),
        },
        "plots": phase1_plots + phase2_plots,
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="Budget-aware efficiency benchmark with cross-dataset consistency and synthesis")
    parser.add_argument("--config", default="configs/budget_efficiency_benchmark.yaml")
    args = parser.parse_args()
    result = run_budget_efficiency_benchmark(args.config)
    print(json.dumps(result["summary"], indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())