File size: 54,659 Bytes
8c74f19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
#!/usr/bin/env python3
"""Experimental direct pooled graph builder, kept separate from compact_v1.

This program is a deliberately independent prototype for the MedusaGraph
materialized docking poses.  It keeps the *meaning* of an enhanced graph
unchanged, but changes how it is built and stored:

* protein/native PDB parsing and the protein--protein distance matrix are
  cached once per protein--ligand system;
* a pose builds only protein--ligand and ligand--ligand distances;
* topology features use an exact sparse formulation instead of the legacy
  dense ``adj @ adj`` calculation;
* graphs are packed directly into bounded pooled tensor shards.  There are no
  per-pose ``.pt`` checkpoints and no legacy monolithic graph list.

The output deliberately remains readable by ``CompactGraphDataset`` as
``gnncp_compact_v1``.  A shard is one *storage* space with pointer tensors;
individual protein--ligand poses remain disconnected graphs.  The prototype
never invents geometric edges between unrelated systems.

It never writes to the input directory, to any existing output directory, or
to the older v1 staging directories.
"""

from __future__ import annotations

import argparse
import concurrent.futures
import gc
import json
import os
import re
import sys
import time
import traceback
from collections import Counter, OrderedDict
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Sequence

import numpy as np
import torch
from scipy import sparse
from scipy.spatial.distance import cdist
from torch_geometric.data import Data


# The experiment owns its builder and output format decisions, but imports the
# established feature definitions/read-only PDB helpers so a parity comparison
# is meaningful.  No source file in system_split_code is modified.
_THIS_DIR = Path(__file__).resolve().parent
if str(_THIS_DIR) not in sys.path:
    sys.path.insert(0, str(_THIS_DIR))
# When this file is executed as a script, the automatic sidecar exporter
# imports ``build_pooled_v2`` for the deterministic raw-pose discovery
# helpers.  Alias the already-running module so it never executes a second
# copy merely because this entrypoint is named ``__main__``.
if __name__ == "__main__":
    sys.modules.setdefault("build_pooled_v2", sys.modules[__name__])
_SYSTEM_SPLIT_CODE = _THIS_DIR.parent / "system_split_code"
if str(_SYSTEM_SPLIT_CODE) not in sys.path:
    sys.path.insert(0, str(_SYSTEM_SPLIT_CODE))

from build_graph_unified_enhanced import (  # noqa: E402
    AA3,
    AA3_2IDX,
    AA_DIM,
    ATOMIC_MASS,
    ELECTRONEGATIVITY,
    ELEMENT2IDX,
    ELEMENTS,
    _get_element,
    _one_hot,
    build_graph_enhanced,
    compute_chemical_features,
    compute_protein_specific_features,
    find_docking_poses,
    load_pdb_clean_models,
)
from compact_graph_dataset import CompactGraphDataset  # noqa: E402


FORMAT_NAME = "gnncp_compact_v1"
SCHEMA_VERSION = 1
STATIC_COLUMNS = tuple(range(0, 34)) + tuple(range(61, 71))
DYNAMIC_COLUMNS = tuple(range(34, 61)) + tuple(range(71, 82))
DOCKING_METHODS = ("protenix", "diffdock", "autodock_vina", "medusagraph")


@dataclass(frozen=True)
class PoseSpec:
    source_graph_index: int
    system_id: str
    protein: Path
    ligand_native: Path
    ligand_pred: Path


@dataclass(frozen=True)
class SystemSpec:
    ordinal: int
    system_id: str
    protein: Path
    ligand_native: Path
    poses: tuple[PoseSpec, ...]


@dataclass(frozen=True)
class BuildConfig:
    data_dir: Path
    output_dir: Path
    method: str
    cutoff: float
    target_shard_mib: int
    system_workers: int
    max_systems: int | None
    max_poses_per_system: int | None
    include_systems: tuple[str, ...]
    on_error: str
    verify_reference: bool
    verify_reference_systems: int
    verify_reference_poses: int
    reader_smoke_graphs: int


@dataclass
class SystemContext:
    """The invariant part of a source protein--ligand system."""

    system: SystemSpec
    coords_protein: np.ndarray
    coords_native_ligand: np.ndarray
    protein_static: np.ndarray
    protein_elements: List[str]
    protein_center: np.ndarray
    pp_dist: np.ndarray

    @property
    def n_protein(self) -> int:
        return int(self.coords_protein.shape[0])

    @property
    def n_ligand(self) -> int:
        return int(self.coords_native_ligand.shape[0])


def _natural_key(value: str) -> tuple[Any, ...]:
    return tuple(
        int(part) if part.isdigit() else part.casefold()
        for part in re.split(r"(\d+)", value)
    )


def _timestamp() -> str:
    return datetime.now(timezone.utc).isoformat()


def _atomic_json(path: Path, payload: Mapping[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(path.name + ".tmp")
    with temporary.open("w", encoding="utf-8") as handle:
        json.dump(payload, handle, ensure_ascii=False, indent=2)
        handle.write("\n")
        handle.flush()
        os.fsync(handle.fileno())
    os.replace(temporary, path)


def _atomic_torch_save(payload: Any, path: Path) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(path.name + ".tmp")
    torch.save(payload, temporary)
    os.replace(temporary, path)


def _relative_or_absolute(path: Path, root: Path) -> str:
    try:
        return str(path.resolve().relative_to(root.resolve()))
    except ValueError:
        return str(path.resolve())


def parse_args(argv: Sequence[str] | None = None) -> BuildConfig:
    parser = argparse.ArgumentParser(
        description=(
            "Build an independent cached/sparse pooled-v2 experiment from "
            "materialized docking poses."
        )
    )
    parser.add_argument("--data-dir", required=True, type=Path)
    parser.add_argument("--output-dir", required=True, type=Path)
    parser.add_argument("--method", required=True, choices=DOCKING_METHODS)
    parser.add_argument("--cutoff", type=float, default=6.0)
    parser.add_argument(
        "--target-shard-mib",
        type=int,
        default=512,
        help="Bounded pooled storage size; systems are never split across a record.",
    )
    parser.add_argument(
        "--system-workers",
        type=int,
        default=1,
        help="Independent source-system workers; use one numerical thread per worker.",
    )
    parser.add_argument("--max-systems", type=int, default=None)
    parser.add_argument("--max-poses-per-system", type=int, default=None)
    parser.add_argument(
        "--system-id",
        action="append",
        default=[],
        dest="include_systems",
        help="Repeatable exact source system ID filter.",
    )
    parser.add_argument(
        "--on-error",
        choices=("abort", "skip-system"),
        default="skip-system",
        help="A failed pose skips only its source system in this experiment.",
    )
    parser.add_argument(
        "--verify-reference",
        action="store_true",
        help="Build selected poses with the old builder too and require parity.",
    )
    parser.add_argument(
        "--verify-reference-systems",
        type=int,
        default=1,
        help="Number of selected systems to reference-check when --verify-reference is set.",
    )
    parser.add_argument(
        "--verify-reference-poses",
        type=int,
        default=1,
        help="Number of leading poses per checked system to reference-check.",
    )
    parser.add_argument(
        "--reader-smoke-graphs",
        type=int,
        default=2,
        help="How many reconstructed graphs to inspect after writing the compact shard(s).",
    )
    args = parser.parse_args(argv)
    return BuildConfig(
        data_dir=args.data_dir.expanduser().resolve(),
        output_dir=args.output_dir.expanduser().resolve(),
        method=args.method,
        cutoff=float(args.cutoff),
        target_shard_mib=int(args.target_shard_mib),
        system_workers=int(args.system_workers),
        max_systems=args.max_systems,
        max_poses_per_system=args.max_poses_per_system,
        include_systems=tuple(args.include_systems),
        on_error=args.on_error,
        verify_reference=bool(args.verify_reference),
        verify_reference_systems=int(args.verify_reference_systems),
        verify_reference_poses=int(args.verify_reference_poses),
        reader_smoke_graphs=int(args.reader_smoke_graphs),
    )


def validate_config(config: BuildConfig) -> None:
    if not config.data_dir.is_dir():
        raise FileNotFoundError(f"data directory not found: {config.data_dir}")
    if config.output_dir.exists():
        raise FileExistsError(
            f"refusing to overwrite an existing output directory: {config.output_dir}"
        )
    if config.output_dir == config.data_dir:
        raise ValueError("output directory must differ from the input data directory")
    if config.cutoff <= 0:
        raise ValueError("--cutoff must be positive")
    if config.target_shard_mib <= 0:
        raise ValueError("--target-shard-mib must be positive")
    if config.system_workers <= 0:
        raise ValueError("--system-workers must be positive")
    if config.max_systems is not None and config.max_systems <= 0:
        raise ValueError("--max-systems must be positive")
    if config.max_poses_per_system is not None and config.max_poses_per_system <= 0:
        raise ValueError("--max-poses-per-system must be positive")
    if config.verify_reference_systems <= 0:
        raise ValueError("--verify-reference-systems must be positive")
    if config.verify_reference_poses <= 0:
        raise ValueError("--verify-reference-poses must be positive")
    if config.reader_smoke_graphs < 0:
        raise ValueError("--reader-smoke-graphs cannot be negative")


def discover_systems(config: BuildConfig) -> List[SystemSpec]:
    """Discover the same deterministic source ordering as the direct v1 builder."""
    raw_poses = find_docking_poses(str(config.data_dir), config.method)
    grouped: MutableMapping[str, List[Mapping[str, str]]] = OrderedDict()
    for pose in sorted(
        raw_poses,
        key=lambda item: (
            _natural_key(str(item["pdb_id"])),
            _natural_key(str(Path(item["ligand_pred"]))),
        ),
    ):
        grouped.setdefault(str(pose["pdb_id"]), []).append(pose)

    requested = set(config.include_systems)
    if requested:
        missing = requested.difference(grouped)
        if missing:
            first_available = ", ".join(list(grouped)[:10])
            raise ValueError(
                f"requested system IDs were not discovered: {sorted(missing)}; "
                f"first available IDs: {first_available}"
            )
        grouped = OrderedDict((key, poses) for key, poses in grouped.items() if key in requested)

    selected = list(grouped.items())
    if config.max_systems is not None:
        selected = selected[: config.max_systems]
    if not selected:
        raise ValueError("no docking systems matched the selection")

    systems: List[SystemSpec] = []
    source_graph_index = 0
    for ordinal, (system_id, raw_system_poses) in enumerate(selected):
        unique_by_path: Dict[Path, Mapping[str, str]] = {}
        for pose in raw_system_poses:
            unique_by_path[Path(pose["ligand_pred"]).resolve()] = pose
        ordered = [
            unique_by_path[path]
            for path in sorted(unique_by_path, key=lambda value: _natural_key(str(value)))
        ]
        if config.max_poses_per_system is not None:
            ordered = ordered[: config.max_poses_per_system]
        if not ordered:
            continue

        proteins = {Path(pose["protein"]).resolve() for pose in ordered}
        natives = {Path(pose["ligand_native"]).resolve() for pose in ordered}
        if len(proteins) != 1 or len(natives) != 1:
            raise ValueError(
                f"{system_id}: discovered multiple protein/native files in one source system"
            )
        protein = next(iter(proteins))
        ligand_native = next(iter(natives))
        poses: List[PoseSpec] = []
        for pose in ordered:
            ligand_pred = Path(pose["ligand_pred"]).resolve()
            if ligand_pred.suffix.lower() != ".pdb":
                raise ValueError(
                    f"{system_id}: only PDB poses are supported by this experiment: {ligand_pred}"
                )
            poses.append(
                PoseSpec(
                    source_graph_index=source_graph_index,
                    system_id=system_id,
                    protein=protein,
                    ligand_native=ligand_native,
                    ligand_pred=ligand_pred,
                )
            )
            source_graph_index += 1
        systems.append(
            SystemSpec(
                ordinal=ordinal,
                system_id=system_id,
                protein=protein,
                ligand_native=ligand_native,
                poses=tuple(poses),
            )
        )
    if not systems:
        raise ValueError("no PDB poses remained after filtering")
    return systems


def _static_features(atoms: Any, protein: bool) -> tuple[np.ndarray, List[str]]:
    """Return the 44 pose-static columns for one atom block.

    The original functions are used for chemistry and protein-specific fields;
    all of those features are node-local, so computing protein and ligand
    blocks separately preserves their values exactly.
    """
    atom_list = list(atoms)
    if not atom_list:
        raise ValueError("a graph atom block is empty after hydrogen filtering")
    elements = [_get_element(atom) for atom in atom_list]
    atom_type_oh = np.stack(
        [_one_hot(ELEMENT2IDX.get(element, ELEMENT2IDX["Other"]), len(ELEMENTS))
         for element in elements]
    )
    if protein:
        res_type_oh = np.stack(
            [_one_hot(AA3_2IDX.get(atom.resname.strip().upper(), len(AA3)), AA_DIM)
             for atom in atom_list]
        )
    else:
        ligand_residue = _one_hot(len(AA3), AA_DIM)
        res_type_oh = np.repeat(ligand_residue.reshape(1, -1), len(atom_list), axis=0)
    is_protein = np.full((len(atom_list), 1), 1.0 if protein else 0.0, dtype=np.float32)
    is_ligand = 1.0 - is_protein
    chemical = compute_chemical_features(atom_list, elements)
    protein_specific = compute_protein_specific_features(atom_list, is_protein)
    static = np.concatenate(
        [atom_type_oh, res_type_oh, is_protein, is_ligand, chemical, protein_specific],
        axis=1,
    ).astype(np.float32)
    if static.shape[1] != len(STATIC_COLUMNS):
        raise AssertionError(f"expected 44 static columns, got {static.shape}")
    return static, elements


def prepare_system_context(system: SystemSpec) -> SystemContext:
    """Read invariant PDBs only once and cache the P--P distance matrix."""
    protein_universe = load_pdb_clean_models(str(system.protein))
    native_universe = load_pdb_clean_models(str(system.ligand_native))
    protein_atoms = protein_universe.select_atoms("not name H*")
    native_atoms = native_universe.select_atoms("not name H*")
    coords_protein = protein_atoms.positions.astype(np.float32)
    coords_native_ligand = native_atoms.positions.astype(np.float32)
    if coords_protein.shape[0] == 0 or coords_native_ligand.shape[0] == 0:
        raise ValueError(f"{system.system_id}: empty protein or native ligand after H filtering")
    protein_static, protein_elements = _static_features(protein_atoms, protein=True)
    return SystemContext(
        system=system,
        coords_protein=coords_protein,
        coords_native_ligand=coords_native_ligand,
        protein_static=protein_static,
        protein_elements=protein_elements,
        protein_center=coords_protein.mean(axis=0, keepdims=True),
        pp_dist=cdist(coords_protein, coords_protein),
    )


def _distance_matrix_for_pose(
    context: SystemContext,
    coords_ligand: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
    """Assemble one full legacy-equivalent distance matrix without redoing P--P."""
    n_protein = context.n_protein
    n_ligand = int(coords_ligand.shape[0])
    protein_ligand = cdist(context.coords_protein, coords_ligand)
    ligand_ligand = cdist(coords_ligand, coords_ligand)
    total = n_protein + n_ligand
    distance = np.empty((total, total), dtype=np.float64)
    distance[:n_protein, :n_protein] = context.pp_dist
    distance[:n_protein, n_protein:] = protein_ligand
    distance[n_protein:, :n_protein] = protein_ligand.T
    distance[n_protein:, n_protein:] = ligand_ligand
    coords_all = np.vstack([context.coords_protein, coords_ligand])
    return coords_all, distance


def local_geometry_from_distance(
    coords: np.ndarray,
    distance: np.ndarray,
    radii: Sequence[float] = (3.0, 5.0, 8.0),
) -> np.ndarray:
    """Legacy local geometry feature code, fed a precomputed distance matrix."""
    n_nodes = coords.shape[0]
    feature_blocks = []
    for radius in radii:
        mask = (distance <= radius) & (distance > 0)
        n_neighbors = mask.sum(axis=1).astype(np.float32)
        anisotropy = np.zeros(n_nodes, dtype=np.float32)
        centroid_distance = np.zeros(n_nodes, dtype=np.float32)
        for index in range(n_nodes):
            neighbor_index = np.where(mask[index])[0]
            if len(neighbor_index) < 3:
                continue
            neighbor_coords = coords[neighbor_index] - coords[index]
            centroid = neighbor_coords.mean(axis=0)
            centroid_distance[index] = np.linalg.norm(centroid)
            covariance = np.cov(neighbor_coords.T)
            try:
                eigenvalues = np.linalg.eigvalsh(covariance)
                eigenvalues = np.sort(eigenvalues)[::-1]
                anisotropy[index] = (
                    (eigenvalues[0] - eigenvalues[-1]) / (eigenvalues.sum() + 1e-8)
                )
            except Exception:
                # Match the established feature builder's deliberately tolerant
                # handling of a numerically degenerate local neighborhood.
                pass
        feature_blocks.extend(
            [
                n_neighbors.reshape(-1, 1),
                anisotropy.reshape(-1, 1),
                centroid_distance.reshape(-1, 1),
            ]
        )
    return np.concatenate(feature_blocks, axis=1)


def distance_statistics_from_distance(
    distance: np.ndarray,
    n_protein: int,
) -> np.ndarray:
    """Legacy 14 distance statistics, reusing the one assembled matrix."""
    to_protein = distance[:, :n_protein]
    to_ligand = distance[:, n_protein:]
    protein_stats = [
        to_protein.min(axis=1, keepdims=True),
        to_protein.mean(axis=1, keepdims=True),
        to_protein.std(axis=1, keepdims=True),
        np.percentile(to_protein, 25, axis=1, keepdims=True),
        np.percentile(to_protein, 75, axis=1, keepdims=True),
    ]
    ligand_stats = [
        to_ligand.min(axis=1, keepdims=True),
        to_ligand.mean(axis=1, keepdims=True),
        to_ligand.std(axis=1, keepdims=True),
        np.percentile(to_ligand, 25, axis=1, keepdims=True),
        np.percentile(to_ligand, 75, axis=1, keepdims=True),
    ]
    shells = []
    for lower, upper in ((0, 3), (3, 5), (5, 8), (8, 12)):
        shells.append(((distance > lower) & (distance <= upper)).sum(axis=1, keepdims=True).astype(np.float32))
    return np.concatenate([*protein_stats, *ligand_stats, *shells], axis=1)


def sparse_topology_from_distance(distance: np.ndarray, cutoff: float) -> np.ndarray:
    """Exact sparse substitute for legacy ``compute_topology_features``.

    ``A @ A`` in the old NumPy bool implementation asks whether a two-hop path
    exists.  Here an int32 CSR product preserves the same nonzero structure,
    while also supplies the multiplicities needed for the clustering
    coefficient.  This avoids the old dense N-by-N matrix multiplication.
    """
    adjacency = (distance <= cutoff) & (distance > 0)
    graph = sparse.csr_matrix(adjacency, dtype=np.int32)
    degree_count = np.diff(graph.indptr).astype(np.int64, copy=False)
    degree = degree_count.astype(np.float32)

    two_hop = graph @ graph
    two_hop.setdiag(0)
    two_hop.eliminate_zeros()
    second_degree = np.diff(two_hop.indptr).astype(np.float32)

    # For node i, sum_j A[i,j] * (A^2)[i,j] / 2 is precisely the number of
    # undirected edges in the induced graph of i's neighbors.
    twice_triangles = np.asarray(two_hop.multiply(graph).sum(axis=1)).reshape(-1)
    clustering = np.zeros(adjacency.shape[0], dtype=np.float32)
    valid = degree_count >= 2
    k = degree_count[valid]
    clustering[valid] = (
        (twice_triangles[valid] / 2.0) / (k * (k - 1) / 2.0)
    ).astype(np.float32)

    return np.stack(
        [
            degree / (degree.max() + 1e-8),
            clustering,
            second_degree / (second_degree.max() + 1e-8),
        ],
        axis=1,
    )


def interface_from_distance(distance: np.ndarray, n_protein: int, cutoff: float = 5.0) -> np.ndarray:
    cross = distance[:n_protein, n_protein:]
    protein_minimum = cross.min(axis=1)
    ligand_minimum = cross.min(axis=0)
    n_nodes = distance.shape[0]
    is_interface = np.zeros((n_nodes, 1), dtype=np.float32)
    interface_distance = np.zeros((n_nodes, 1), dtype=np.float32)
    is_interface[:n_protein, 0] = (protein_minimum <= cutoff).astype(np.float32)
    is_interface[n_protein:, 0] = (ligand_minimum <= cutoff).astype(np.float32)
    interface_distance[:n_protein, 0] = protein_minimum
    interface_distance[n_protein:, 0] = ligand_minimum
    interface_distance = np.clip(interface_distance / 10.0, 0, 1)
    return np.concatenate([is_interface, interface_distance], axis=1)


def local_environment_from_distance(
    distance: np.ndarray,
    elements: Sequence[str],
    cutoff: float = 5.0,
) -> np.ndarray:
    """Legacy local environment feature code, fed a precomputed matrix."""
    n_nodes = distance.shape[0]
    mask = (distance <= cutoff) & (distance > 0)
    element_index = {"C": 0, "N": 1, "O": 2, "S": 3}
    composition = np.zeros((n_nodes, 4), dtype=np.float32)
    electronegativity = np.zeros((n_nodes, 1), dtype=np.float32)
    mass = np.zeros((n_nodes, 1), dtype=np.float32)
    for index in range(n_nodes):
        neighbors = np.where(mask[index])[0]
        if len(neighbors) == 0:
            continue
        for neighbor in neighbors:
            element = elements[neighbor]
            if element in element_index:
                composition[index, element_index[element]] += 1
            electronegativity[index] += ELECTRONEGATIVITY.get(element, 2.5)
            mass[index] += ATOMIC_MASS.get(element, 12.0)
        count = len(neighbors)
        composition[index] /= count
        electronegativity[index] /= count
        mass[index] /= count
    electronegativity = (electronegativity - 2.5) / 1.5
    mass = np.log1p(mass) / 5.0
    return np.concatenate([composition, electronegativity, mass], axis=1)


def build_pose_graph(context: SystemContext, pose: PoseSpec, cutoff: float) -> Data:
    """Build one graph while reusing invariant system context."""
    ligand_universe = load_pdb_clean_models(str(pose.ligand_pred))
    ligand_atoms = ligand_universe.select_atoms("not name H*")
    coords_ligand = ligand_atoms.positions.astype(np.float32)
    if coords_ligand.shape[0] != context.n_ligand:
        raise ValueError(
            f"{pose.system_id}: ligand atom count mismatch: "
            f"pred={coords_ligand.shape[0]}, native={context.n_ligand}"
        )

    ligand_static, ligand_elements = _static_features(ligand_atoms, protein=False)
    static = np.concatenate([context.protein_static, ligand_static], axis=0)
    elements = [*context.protein_elements, *ligand_elements]
    coords_all, distance = _distance_matrix_for_pose(context, coords_ligand)
    n_protein = context.n_protein
    n_nodes = coords_all.shape[0]

    ligand_center = coords_ligand.mean(axis=0, keepdims=True)
    distance_protein_center = np.linalg.norm(
        coords_all - context.protein_center, axis=1, keepdims=True
    ) / 50.0
    distance_ligand_center = np.linalg.norm(
        coords_all - ligand_center, axis=1, keepdims=True
    ) / 30.0
    minimum_protein = distance[:, :n_protein].min(axis=1, keepdims=True) / 20.0
    minimum_ligand = distance[:, n_protein:].min(axis=1, keepdims=True) / 20.0
    local_geometry = local_geometry_from_distance(coords_all, distance)
    distance_statistics = distance_statistics_from_distance(distance, n_protein) / 20.0
    topology = sparse_topology_from_distance(distance, cutoff=cutoff)
    interface = interface_from_distance(distance, n_protein)
    local_environment = local_environment_from_distance(distance, elements)

    x = np.empty((n_nodes, 82), dtype=np.float32)
    x[:, :34] = static[:, :34]
    x[:, 34:38] = np.concatenate(
        [distance_protein_center, distance_ligand_center, minimum_protein, minimum_ligand],
        axis=1,
    )
    x[:, 38:47] = local_geometry
    x[:, 47:61] = distance_statistics
    x[:, 61:71] = static[:, 34:44]
    x[:, 71:74] = topology
    x[:, 74:76] = interface
    x[:, 76:82] = local_environment

    errors = np.concatenate(
        [
            np.zeros(n_protein, dtype=np.float32),
            np.linalg.norm(coords_ligand - context.coords_native_ligand, axis=1).astype(np.float32),
        ]
    )
    coordinates_native = np.vstack([context.coords_protein, context.coords_native_ligand])
    is_protein = np.zeros((n_nodes, 1), dtype=np.float32)
    is_protein[:n_protein] = 1.0

    edge_mask = (distance <= cutoff) & (~np.eye(n_nodes, dtype=bool))
    src, dst = np.where(edge_mask)
    edge_index = np.vstack([src, dst]).astype(np.int64)
    edge_distance = distance[src, dst]
    edge_attr = np.stack(
        [
            edge_distance / cutoff,
            np.exp(-edge_distance / 3.0),
            (src < n_protein).astype(np.float32),
            (dst < n_protein).astype(np.float32),
        ],
        axis=1,
    ).astype(np.float32)
    return Data(
        x=torch.from_numpy(x),
        edge_index=torch.from_numpy(edge_index),
        edge_attr=torch.from_numpy(edge_attr),
        pos=torch.from_numpy(coords_all),
        is_protein=torch.from_numpy(is_protein),
        y_true=torch.from_numpy(errors).unsqueeze(-1),
        y_pred=torch.from_numpy(coords_all),
        y_grt=torch.from_numpy(coordinates_native),
        num_nodes=n_nodes,
    )


def _upper_edges(graph: Data) -> torch.Tensor:
    mask = graph.edge_index[0] < graph.edge_index[1]
    return graph.edge_index[:, mask].to(dtype=torch.int32).contiguous()


def _tensor_bytes(tensor: torch.Tensor) -> int:
    return tensor.numel() * tensor.element_size()


def _make_records(
    system: SystemSpec,
    graphs: Sequence[Data],
    data_root: Path,
) -> List[Dict[str, Any]]:
    """Compact a source system without hash-based grouping or pose files."""
    if len(graphs) != len(system.poses):
        raise ValueError(f"{system.system_id}: graph/pose count changed during construction")

    static_index = torch.tensor(STATIC_COLUMNS, dtype=torch.int64)
    dynamic_index = torch.tensor(DYNAMIC_COLUMNS, dtype=torch.int64)
    groups: List[List[int]] = []
    static_references: List[torch.Tensor] = []
    for graph_index, graph in enumerate(graphs):
        static = graph.x.index_select(1, static_index).contiguous()
        for group_index, reference in enumerate(static_references):
            if torch.equal(static, reference):
                groups[group_index].append(graph_index)
                break
        else:
            static_references.append(static)
            groups.append([graph_index])

    records: List[Dict[str, Any]] = []
    for group_index, graph_indices in enumerate(groups):
        reference = graphs[graph_indices[0]]
        n_nodes = int(reference.x.shape[0])
        n_protein = int((reference.is_protein.reshape(-1) > 0.5).sum().item())
        n_ligand = n_nodes - n_protein
        if n_protein <= 0 or n_ligand <= 0:
            raise ValueError(f"{system.system_id}: invalid protein/ligand node partition")
        x_static = reference.x.index_select(1, static_index).contiguous().clone()
        protein_pos = reference.pos[:n_protein].contiguous().clone()
        native_ligand_pos = reference.y_grt[n_protein:].contiguous().clone()
        reference_upper = _upper_edges(reference)
        pp_mask = (reference_upper[0] < n_protein) & (reference_upper[1] < n_protein)
        pp_edge_upper = reference_upper[:, pp_mask].contiguous().clone()

        dynamic_parts: List[torch.Tensor] = []
        ligand_positions: List[torch.Tensor] = []
        nonpp_parts: List[torch.Tensor] = []
        nonpp_counts: List[int] = []
        source_graph_indices: List[int] = []
        source_pose_paths: List[str] = []
        for graph_index in graph_indices:
            graph = graphs[graph_index]
            if int(graph.x.shape[0]) != n_nodes:
                raise ValueError(f"{system.system_id}: pose node count changed within a static group")
            dynamic_parts.append(graph.x.index_select(1, dynamic_index).contiguous())
            ligand_positions.append(graph.pos[n_protein:].contiguous())
            upper = _upper_edges(graph)
            nonpp = upper[:, ~((upper[0] < n_protein) & (upper[1] < n_protein))].contiguous()
            nonpp_parts.append(nonpp)
            nonpp_counts.append(int(nonpp.shape[1]))
            source_graph_indices.append(system.poses[graph_index].source_graph_index)
            source_pose_paths.append(
                _relative_or_absolute(system.poses[graph_index].ligand_pred, data_root)
            )

        storage_id = (
            system.system_id
            if len(groups) == 1
            else f"{system.system_id}__static_variant_{group_index:02d}"
        )
        record: Dict[str, Any] = {
            "_system_id": storage_id,
            "_source_label": system.system_id,
            "_source_system_id": system.system_id,
            "_source_label_counts": {system.system_id: len(graph_indices)},
            # This v2 experiment intentionally does not make SHA hashes part of
            # progress or grouping.  Static equality above is enough here.
            "_native_hash": "not-computed-v2",
            "_shared_hash": "not-computed-v2",
            "_n_nodes": n_nodes,
            "_n_protein": n_protein,
            "_n_ligand": n_ligand,
            "_n_poses": len(graph_indices),
            "x_static": x_static,
            "protein_pos": protein_pos,
            "native_ligand_pos": native_ligand_pos,
            "x_dynamic": torch.cat(dynamic_parts, dim=0),
            "ligand_pos": torch.cat(ligand_positions, dim=0),
            "pp_edge_upper": pp_edge_upper,
            "nonpp_edge_upper": torch.cat(nonpp_parts, dim=1),
            "nonpp_edge_counts": torch.tensor(nonpp_counts, dtype=torch.int64),
            "source_graph_index": torch.tensor(source_graph_indices, dtype=torch.int64),
            "_source_pose_paths": source_pose_paths,
        }
        record["_tensor_bytes"] = sum(
            _tensor_bytes(value) for value in record.values() if isinstance(value, torch.Tensor)
        )
        records.append(record)
    return records


def _compare_reference(actual: Data, reference: Data, system_id: str, pose_path: Path) -> Dict[str, Any]:
    """Require strong, human-readable parity with the established builder."""
    result: Dict[str, Any] = {
        "system_id": system_id,
        "pose": str(pose_path),
        "passed": True,
        "max_abs": {},
    }
    exact_names = ("edge_index", "pos", "is_protein", "y_true", "y_pred", "y_grt")
    for name in exact_names:
        if not torch.equal(getattr(actual, name), getattr(reference, name)):
            raise AssertionError(f"{system_id} {pose_path.name}: {name} differs from reference")
    for name in ("x", "edge_attr"):
        current = getattr(actual, name)
        expected = getattr(reference, name)
        if current.shape != expected.shape:
            raise AssertionError(
                f"{system_id} {pose_path.name}: {name} shape {tuple(current.shape)} != {tuple(expected.shape)}"
            )
        max_abs = float((current - expected).abs().max().item()) if current.numel() else 0.0
        result["max_abs"][name] = max_abs
        if not torch.allclose(current, expected, rtol=1e-6, atol=1e-6):
            raise AssertionError(
                f"{system_id} {pose_path.name}: {name} differs from reference; max_abs={max_abs}"
            )
    return result


def _build_one_system(
    system: SystemSpec,
    config: BuildConfig,
    verify_reference: bool,
) -> Dict[str, Any]:
    """Top-level worker target: build a system entirely in memory, then return records."""
    started = time.perf_counter()
    try:
        context_start = time.perf_counter()
        context = prepare_system_context(system)
        context_seconds = time.perf_counter() - context_start
        graph_seconds = 0.0
        graphs: List[Data] = []
        parity: List[Dict[str, Any]] = []
        for local_index, pose in enumerate(system.poses):
            pose_start = time.perf_counter()
            graph = build_pose_graph(context, pose, config.cutoff)
            graph_seconds += time.perf_counter() - pose_start
            if verify_reference and local_index < config.verify_reference_poses:
                reference = build_graph_enhanced(
                    protein_pdb=str(pose.protein),
                    ligand_pred_pdb=str(pose.ligand_pred),
                    ligand_native_pdb=str(pose.ligand_native),
                    cutoff=config.cutoff,
                    use_enhanced_features=True,
                )
                parity.append(_compare_reference(graph, reference, system.system_id, pose.ligand_pred))
                del reference
            graphs.append(graph)
        records = _make_records(system, graphs, config.data_dir)
        node_count = int(graphs[0].num_nodes)
        return {
            "ok": True,
            "ordinal": system.ordinal,
            "system_id": system.system_id,
            "records": records,
            "parity": parity,
            "stats": {
                "system_id": system.system_id,
                "ordinal": system.ordinal,
                "n_poses": len(system.poses),
                "n_nodes_per_pose": node_count,
                "n_records": len(records),
                "context_seconds": context_seconds,
                "pose_build_seconds": graph_seconds,
                "total_seconds": time.perf_counter() - started,
            },
        }
    except Exception as error:
        return {
            "ok": False,
            "ordinal": system.ordinal,
            "system_id": system.system_id,
            "error_type": type(error).__name__,
            "error": str(error),
            "traceback": traceback.format_exc(),
            "n_poses": len(system.poses),
            "total_seconds": time.perf_counter() - started,
        }


def _cumulative_ptr(lengths: Iterable[int]) -> torch.Tensor:
    values = [0]
    for length in lengths:
        values.append(values[-1] + int(length))
    return torch.tensor(values, dtype=torch.int64)


def pack_pooled_shard(records: Sequence[Mapping[str, Any]]) -> Dict[str, torch.Tensor]:
    """A local copy of the reader-compatible pooled tensor layout."""
    if not records:
        raise ValueError("cannot pack an empty shard")
    n_poses = [int(record["_n_poses"]) for record in records]
    n_nodes = [int(record["_n_nodes"]) for record in records]
    n_protein = [int(record["_n_protein"]) for record in records]
    n_ligand = [int(record["_n_ligand"]) for record in records]
    pose_node_lengths: List[int] = []
    pose_ligand_lengths: List[int] = []
    for poses, nodes, ligand in zip(n_poses, n_nodes, n_ligand):
        pose_node_lengths.extend([nodes] * poses)
        pose_ligand_lengths.extend([ligand] * poses)
    cat = lambda key, dim=0: torch.cat([record[key] for record in records], dim=dim)
    return {
        "schema_version": torch.tensor([SCHEMA_VERSION], dtype=torch.int32),
        "system_graph_ptr": _cumulative_ptr(n_poses),
        "pose_system": torch.repeat_interleave(
            torch.arange(len(records), dtype=torch.int32),
            torch.tensor(n_poses, dtype=torch.int64),
        ),
        "source_graph_index": cat("source_graph_index"),
        "system_node_ptr": _cumulative_ptr(n_nodes),
        "n_protein": torch.tensor(n_protein, dtype=torch.int32),
        "x_static": cat("x_static"),
        "protein_ptr": _cumulative_ptr(n_protein),
        "protein_pos": cat("protein_pos"),
        "native_ligand_ptr": _cumulative_ptr(n_ligand),
        "native_ligand_pos": cat("native_ligand_pos"),
        "pose_node_ptr": _cumulative_ptr(pose_node_lengths),
        "x_dynamic": cat("x_dynamic"),
        "pose_ligand_ptr": _cumulative_ptr(pose_ligand_lengths),
        "ligand_pos": cat("ligand_pos"),
        "pp_edge_ptr": _cumulative_ptr(record["pp_edge_upper"].shape[1] for record in records),
        "pp_edge_upper": cat("pp_edge_upper", dim=1),
        "nonpp_edge_ptr": _cumulative_ptr(
            int(count) for record in records for count in record["nonpp_edge_counts"].tolist()
        ),
        "nonpp_edge_upper": cat("nonpp_edge_upper", dim=1),
    }


def _record_manifest_entry(record: Mapping[str, Any]) -> Dict[str, Any]:
    return {
        "system_id": record["_system_id"],
        "source_label": record["_source_label"],
        "source_system_id": record["_source_system_id"],
        "source_label_counts": record["_source_label_counts"],
        "native_hash": record["_native_hash"],
        "shared_hash": record["_shared_hash"],
        "num_graphs": record["_n_poses"],
        "num_nodes": record["_n_nodes"],
        "num_protein_nodes": record["_n_protein"],
        "num_ligand_nodes": record["_n_ligand"],
        "source_graph_indices": record["source_graph_index"].tolist(),
        "source_pose_paths": record["_source_pose_paths"],
    }


class _ShardWriter:
    def __init__(self, stage_dir: Path, target_bytes: int) -> None:
        self.stage_dir = stage_dir
        self.target_bytes = target_bytes
        self.pending: List[Dict[str, Any]] = []
        self.pending_bytes = 0
        self.shards: List[Dict[str, Any]] = []
        self.graph_locations: Dict[int, List[int]] = {}
        self.compact_bytes = 0

    def add_records(self, records: Sequence[Dict[str, Any]]) -> None:
        for record in records:
            record_bytes = int(record["_tensor_bytes"])
            if self.pending and self.pending_bytes + record_bytes > self.target_bytes:
                self.flush()
            self.pending.append(record)
            self.pending_bytes += record_bytes

    def flush(self) -> None:
        if not self.pending:
            return
        shard_index = len(self.shards)
        relative_path = f"shards/shard_{shard_index:05d}.pt"
        shard_path = self.stage_dir / relative_path
        packed = pack_pooled_shard(self.pending)
        _atomic_torch_save(packed, shard_path)
        size_bytes = int(shard_path.stat().st_size)
        local_pose = 0
        for record in self.pending:
            for offset, source_graph_index in enumerate(record["source_graph_index"].tolist()):
                source_graph_index = int(source_graph_index)
                if source_graph_index in self.graph_locations:
                    raise RuntimeError(f"duplicate source_graph_index {source_graph_index}")
                self.graph_locations[source_graph_index] = [shard_index, local_pose + offset]
            local_pose += int(record["_n_poses"])
        self.shards.append(
            {
                "path": relative_path,
                "num_graphs": int(packed["pose_system"].numel()),
                "num_systems": len(self.pending),
                "num_source_systems": len(
                    {str(record["_source_system_id"]) for record in self.pending}
                ),
                "size_bytes": size_bytes,
                "systems": [_record_manifest_entry(record) for record in self.pending],
            }
        )
        self.compact_bytes += size_bytes
        self.pending = []
        self.pending_bytes = 0
        del packed
        gc.collect()


def _reader_smoke(stage_dir: Path, n_graphs: int, requested: int) -> Dict[str, Any]:
    if requested == 0:
        return {"requested": 0, "checked": []}
    dataset = CompactGraphDataset(stage_dir, strict=True)
    if len(dataset) != n_graphs:
        raise AssertionError(f"reader length {len(dataset)} != manifest graph count {n_graphs}")
    candidates = np.linspace(0, max(0, n_graphs - 1), min(requested, n_graphs), dtype=int)
    checked = []
    for index in sorted(set(int(value) for value in candidates)):
        graph = dataset[index]
        if graph.x.shape[1] != 82 or graph.edge_attr.shape[1] != 4:
            raise AssertionError(f"reader smoke graph {index} has wrong feature widths")
        checked.append(
            {
                "dataset_index": index,
                "n_nodes": int(graph.num_nodes),
                "n_edges": int(graph.edge_index.shape[1]),
            }
        )
    return {"requested": requested, "checked": checked}


def _source_index_payload(
    systems: Sequence[SystemSpec],
    graph_locations: Mapping[int, Sequence[int]],
    errors: Sequence[Mapping[str, Any]],
) -> Dict[str, Any]:
    source_to_system = {
        pose.source_graph_index: system.system_id
        for system in systems
        for pose in system.poses
    }
    source_indices = sorted(graph_locations)
    graph_to_system = [source_to_system[index] for index in source_indices]
    counts = Counter(graph_to_system)
    return {
        "graph_to_system": graph_to_system,
        "source_graph_indices": source_indices,
        "n_graphs": len(graph_to_system),
        "n_systems": len(counts),
        "systems": sorted(counts, key=_natural_key),
        "system_counts": dict(sorted(counts.items(), key=lambda item: _natural_key(item[0]))),
        "skipped_source_systems": [str(error["system_id"]) for error in errors],
        "note": (
            "Original source system IDs are retained. Poses within a source system "
            "may be separated only when their 44 static columns differ exactly."
        ),
    }


def _consume_outcome(
    outcome: Mapping[str, Any],
    config: BuildConfig,
    writer: _ShardWriter,
    stats: List[Dict[str, Any]],
    parity: List[Dict[str, Any]],
    errors: List[Dict[str, Any]],
) -> None:
    if not outcome["ok"]:
        error = {
            key: outcome[key]
            for key in ("ordinal", "system_id", "error_type", "error", "traceback", "n_poses", "total_seconds")
        }
        errors.append(error)
        print(
            f"[skip] {error['system_id']}: {error['error_type']}: {error['error']}",
            file=sys.stderr,
            flush=True,
        )
        if config.on_error == "abort" or config.verify_reference:
            raise RuntimeError(
                f"{error['system_id']} failed: {error['error_type']}: {error['error']}"
            )
        return
    writer.add_records(outcome["records"])
    stats.append(dict(outcome["stats"]))
    parity.extend(outcome["parity"])
    details = outcome["stats"]
    print(
        f"[done] {details['ordinal'] + 1}: {details['system_id']} "
        f"{details['n_poses']} poses, {details['n_nodes_per_pose']} nodes/pose, "
        f"{details['total_seconds']:.2f}s",
        flush=True,
    )


def _build_and_write(
    systems: Sequence[SystemSpec],
    config: BuildConfig,
    stage_dir: Path,
) -> tuple[_ShardWriter, List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]:
    writer = _ShardWriter(stage_dir, config.target_shard_mib * 1024 * 1024)
    stats: List[Dict[str, Any]] = []
    parity: List[Dict[str, Any]] = []
    errors: List[Dict[str, Any]] = []
    verify_ordinals = set(range(min(config.verify_reference_systems, len(systems))))

    if config.system_workers == 1:
        for system in systems:
            outcome = _build_one_system(
                system,
                config,
                config.verify_reference and system.ordinal in verify_ordinals,
            )
            _consume_outcome(outcome, config, writer, stats, parity, errors)
    else:
        # At most one completed record per worker can wait in the parent.  This
        # retains direct final-shard writes while still exploiting the new CPU
        # allowance for independent source systems.
        with concurrent.futures.ProcessPoolExecutor(max_workers=config.system_workers) as executor:
            next_submit = 0
            next_commit = 0
            in_flight: Dict[concurrent.futures.Future[Dict[str, Any]], int] = {}
            completed: Dict[int, Dict[str, Any]] = {}

            def submit_one(index: int) -> None:
                system = systems[index]
                future = executor.submit(
                    _build_one_system,
                    system,
                    config,
                    config.verify_reference and system.ordinal in verify_ordinals,
                )
                in_flight[future] = index

            while next_submit < len(systems) and len(in_flight) < config.system_workers:
                submit_one(next_submit)
                next_submit += 1

            while in_flight:
                done, _ = concurrent.futures.wait(
                    in_flight,
                    return_when=concurrent.futures.FIRST_COMPLETED,
                )
                for future in done:
                    index = in_flight.pop(future)
                    try:
                        completed[index] = future.result()
                    except BaseException as error:
                        completed[index] = {
                            "ok": False,
                            "ordinal": systems[index].ordinal,
                            "system_id": systems[index].system_id,
                            "error_type": type(error).__name__,
                            "error": str(error),
                            "traceback": traceback.format_exc(),
                            "n_poses": len(systems[index].poses),
                            "total_seconds": 0.0,
                        }
                    if next_submit < len(systems):
                        submit_one(next_submit)
                        next_submit += 1
                while next_commit in completed:
                    outcome = completed.pop(next_commit)
                    _consume_outcome(outcome, config, writer, stats, parity, errors)
                    next_commit += 1
    writer.flush()
    return writer, stats, parity, errors


def _manifest(
    config: BuildConfig,
    systems: Sequence[SystemSpec],
    writer: _ShardWriter,
    stats: Sequence[Mapping[str, Any]],
    errors: Sequence[Mapping[str, Any]],
) -> Dict[str, Any]:
    source_indices = sorted(writer.graph_locations)
    source_to_system = {
        pose.source_graph_index: system.system_id
        for system in systems
        for pose in system.poses
    }
    graph_to_system = [source_to_system[index] for index in source_indices]
    successful_sources = sorted(set(graph_to_system), key=_natural_key)
    return {
        "format": FORMAT_NAME,
        "schema_version": SCHEMA_VERSION,
        "status": "complete",
        "created_utc": _timestamp(),
        "method": config.method,
        "cutoff": config.cutoff,
        "source": {
            "data_dir": str(config.data_dir),
            "mode": "direct_cached_sparse_from_docking_poses",
            "discovered_source_systems": len(systems),
            "discovered_poses": sum(len(system.poses) for system in systems),
            "successful_source_systems": len(successful_sources),
            "skipped_source_systems": len(errors),
            "source_index": "source_index.json",
            "system_index": "system_index.json",
            "graph_index": "graph_index.jsonl",
            "graph_index_manifest": "graph_index_manifest.json",
        },
        "features": {
            "full_dimension": 82,
            "dtype": "float32",
            "static_dimension": len(STATIC_COLUMNS),
            "static_columns": list(STATIC_COLUMNS),
            "dynamic_dimension": len(DYNAMIC_COLUMNS),
            "dynamic_columns": list(DYNAMIC_COLUMNS),
        },
        "edges": {
            "index_dtype_on_disk": "int32",
            "stored_direction": "upper_triangle_src_lt_dst",
            "protein_protein_scope": "once_per_storage_group",
            "non_protein_protein_scope": "once_per_pose",
            "edge_attr": "derived_by_CompactGraphDataset_from_float32_coordinates",
        },
        "pooling": {
            "storage_scope": "one bounded tensor pool per shard",
            "node_and_edge_storage": "concatenated tensors with explicit ptr arrays",
            "cross_system_edges": False,
            "graph_semantics": (
                "Each pose remains a disconnected protein-ligand graph; pointers, "
                "not geometric edges, separate systems and poses."
            ),
        },
        "v2_experiment": {
            "implementation": "compact_v2_pooled/build_pooled_v2.py",
            "protein_and_native_parse_cached_once_per_system": True,
            "protein_protein_distance_cached_once_per_system": True,
            "temporary_per_pose_graph_files": False,
            "topology": "exact scipy CSR A@A formulation of legacy topology features",
            "storage_grouping": "direct torch.equal of 44 static columns; no SHA grouping/freeze",
            "target_shard_mib": config.target_shard_mib,
            "system_workers": config.system_workers,
        },
        "n_graphs": len(source_indices),
        "n_systems": sum(int(shard["num_systems"]) for shard in writer.shards),
        "n_source_systems": len(successful_sources),
        "n_shards": len(writer.shards),
        "graph_map": [writer.graph_locations[index] for index in source_indices],
        "shards": writer.shards,
        "size": {"compact_shard_bytes": writer.compact_bytes},
        "build_summary": {
            "successful_system_stats": list(stats),
            "skipped_systems": list(errors),
        },
    }


def run(config: BuildConfig) -> Dict[str, Any]:
    validate_config(config)
    systems = discover_systems(config)
    stage_dir = config.output_dir.with_name(
        f".{config.output_dir.name}.v2building.{os.getpid()}"
    )
    if stage_dir.exists():
        raise FileExistsError(f"refusing to reuse an experiment staging directory: {stage_dir}")
    stage_dir.mkdir(parents=True)
    (stage_dir / "shards").mkdir()
    started = time.perf_counter()
    print(f"data:       {config.data_dir}", flush=True)
    print(f"output:     {config.output_dir}", flush=True)
    print(f"staging:    {stage_dir}", flush=True)
    print(f"systems:    {len(systems)}", flush=True)
    print(f"poses:      {sum(len(system.poses) for system in systems)}", flush=True)
    print(f"workers:    {config.system_workers}", flush=True)
    print(f"reference:  {config.verify_reference}", flush=True)
    try:
        writer, stats, parity, errors = _build_and_write(systems, config, stage_dir)
        if not writer.shards:
            raise RuntimeError("no source systems completed successfully")
        source_index = _source_index_payload(systems, writer.graph_locations, errors)
        _atomic_json(stage_dir / "source_index.json", source_index)
        _atomic_json(stage_dir / "system_index.json", source_index)
        manifest = _manifest(config, systems, writer, stats, errors)
        _atomic_json(stage_dir / "manifest.json", manifest)
        # The compact tensor layout is intentionally pointer-based and does
        # not duplicate raw PDB paths per tensor row.  Emit an additive,
        # one-row-per-graph provenance map while the exact selected source
        # SystemSpecs are still available.  The helper refuses all overwrite;
        # the stage directory is unique and will be atomically renamed only
        # after this mapping, reader smoke test, and build report succeed.
        from export_graph_index import write_sidecars

        graph_index_result = write_sidecars(
            stage_dir,
            config.data_dir,
            dataset_root_label=".",
        )
        reader_smoke = _reader_smoke(stage_dir, manifest["n_graphs"], config.reader_smoke_graphs)
        elapsed = time.perf_counter() - started
        report = {
            "status": "complete",
            "created_utc": _timestamp(),
            "elapsed_seconds": elapsed,
            "manifest": "manifest.json",
            "graph_index": "graph_index.jsonl",
            "graph_index_manifest": "graph_index_manifest.json",
            "reader_smoke": reader_smoke,
            "reference_parity": parity,
            "totals": {
                "selected_source_systems": len(systems),
                "successful_source_systems": manifest["n_source_systems"],
                "skipped_source_systems": len(errors),
                "graphs": manifest["n_graphs"],
                "storage_groups": manifest["n_systems"],
                "shards": manifest["n_shards"],
                "compact_shard_bytes": writer.compact_bytes,
                "graph_index_rows": graph_index_result["rows"],
                "sum_context_seconds": sum(float(item["context_seconds"]) for item in stats),
                "sum_pose_build_seconds": sum(float(item["pose_build_seconds"]) for item in stats),
            },
            "systems": stats,
            "errors": errors,
        }
        _atomic_json(stage_dir / "build_report.json", report)
        os.replace(stage_dir, config.output_dir)
        print(
            f"complete: {config.output_dir} ({manifest['n_graphs']} graphs, "
            f"{manifest['n_source_systems']} source systems, {manifest['n_shards']} shards, "
            f"{elapsed:.1f}s)",
            flush=True,
        )
        return manifest
    except BaseException:
        # Keep an isolated, uniquely named staging directory for debugging;
        # never repurpose it or touch v1 staging/output paths.
        print(f"v2 experiment stopped; isolated staging retained: {stage_dir}", file=sys.stderr, flush=True)
        raise


def main(argv: Sequence[str] | None = None) -> int:
    run(parse_args(argv))
    return 0


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