File size: 28,388 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
#!/usr/bin/env python3
"""Create and validate a one-row-per-graph provenance sidecar for pooled-v2.

The compact tensor format is deliberately optimized for training and therefore
does not put PDB provenance in every tensor row.  This program writes an
*additive* ``graph_index.jsonl`` sidecar, ordered exactly like
``CompactGraphDataset``.  Each row is the durable join key between a training
sample, a baseline-prediction row, the corresponding raw PDB files and its
pooled shard position.

It is intentionally non-destructive:

* it only reads the compact dataset and materialized source PDBs;
* it refuses to overwrite either output sidecar; and
* ``--check-only`` never writes anything.

No content hashes are used.  The identity is explicit and human-auditable:
``dataset_index``, ``source_system_id``, ``raw_pose_ordinal`` and the three
PDB paths.
"""

from __future__ import annotations

import argparse
import json
import os
import sys
from collections import Counter, defaultdict
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Iterable, List, Mapping, Sequence, Tuple

import torch


THIS_DIR = Path(__file__).resolve().parent
if str(THIS_DIR) not in sys.path:
    sys.path.insert(0, str(THIS_DIR))

import build_pooled_v2 as v2  # noqa: E402


INDEX_FORMAT = "gnncp_graph_index_v1"
INDEX_SCHEMA_VERSION = 1
DEFAULT_INDEX_NAME = "graph_index.jsonl"
DEFAULT_MANIFEST_NAME = "graph_index_manifest.json"


@dataclass(frozen=True)
class Arguments:
    dataset_root: Path
    data_dir: Path
    index_path: Path
    index_manifest_path: Path
    check_only: bool


def _read_json(path: Path) -> Dict[str, Any]:
    with path.open("r", encoding="utf-8") as handle:
        value = json.load(handle)
    if not isinstance(value, dict):
        raise TypeError(f"expected a JSON object in {path}")
    return value


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


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 _resolve_declared_path(value: str, data_dir: Path) -> Path:
    path = Path(value).expanduser()
    return path.resolve() if path.is_absolute() else (data_dir / path).resolve()


def _pointer_bounds(pointer: torch.Tensor, index: int, name: str) -> tuple[int, int]:
    if pointer.ndim != 1 or not 0 <= index + 1 < int(pointer.numel()):
        raise AssertionError(f"invalid {name} lookup at {index}")
    begin = int(pointer[index].item())
    end = int(pointer[index + 1].item())
    if begin < 0 or end < begin:
        raise AssertionError(f"invalid {name}[{index}] = [{begin}, {end})")
    return begin, end


def _load_shards(root: Path, manifest: Mapping[str, Any]) -> List[Mapping[str, torch.Tensor]]:
    shards: List[Mapping[str, torch.Tensor]] = []
    for shard_index, entry in enumerate(manifest["shards"]):
        if not isinstance(entry, Mapping):
            raise TypeError(f"manifest shard {shard_index} is not an object")
        path = root / str(entry["path"])
        if not path.is_file():
            raise FileNotFoundError(path)
        payload = torch.load(path, map_location="cpu", mmap=True, weights_only=True)
        if not isinstance(payload, Mapping):
            raise TypeError(f"shard {path} is not a tensor mapping")
        shards.append(payload)
    return shards


def _selected_raw_systems(
    data_dir: Path,
    method: str,
    source_ids: Iterable[str],
) -> List[v2.SystemSpec]:
    """Rediscover all raw poses for exactly the source systems in this output.

    We intentionally filter by explicit source IDs rather than replaying an
    assumed ``--max-systems`` selection.  ``selected_raw_system_ordinal`` is
    therefore explicitly local to this output selection; the stable identity
    across runs is the source-system ID plus raw pose ordinal/path.  This also
    works for a future run made with ``--system-id`` and for outputs that
    skipped a source system.
    """
    unique_ids = tuple(sorted({str(value) for value in source_ids}, key=v2._natural_key))
    if not unique_ids:
        raise AssertionError("the dataset has no source system IDs")
    config = v2.BuildConfig(
        data_dir=data_dir,
        output_dir=Path("/tmp/unused_graph_index_output"),
        method=method,
        cutoff=6.0,
        target_shard_mib=1,
        system_workers=1,
        max_systems=None,
        max_poses_per_system=None,
        include_systems=unique_ids,
        on_error="abort",
        verify_reference=False,
        verify_reference_systems=1,
        verify_reference_poses=1,
        reader_smoke_graphs=0,
    )
    systems = v2.discover_systems(config)
    found = {system.system_id for system in systems}
    missing = set(unique_ids).difference(found)
    if missing:
        raise AssertionError(f"raw source systems missing: {sorted(missing)[:10]}")
    return systems


def _source_ids_from_manifest(manifest: Mapping[str, Any]) -> set[str]:
    result: set[str] = set()
    for shard in manifest["shards"]:
        for record in shard["systems"]:
            result.add(str(record["source_system_id"]))
    for item in manifest.get("build_summary", {}).get("skipped_systems", []):
        if isinstance(item, Mapping) and "system_id" in item:
            result.add(str(item["system_id"]))
    return result


def _raw_pose_lookup(
    systems: Sequence[v2.SystemSpec],
) -> tuple[Dict[tuple[str, Path], tuple[v2.SystemSpec, int, v2.PoseSpec]], Dict[str, int]]:
    """Map source-system/path to a stable raw pose ordinal and PDB triplet."""
    lookup: Dict[tuple[str, Path], tuple[v2.SystemSpec, int, v2.PoseSpec]] = {}
    system_ordinals: Dict[str, int] = {}
    for selected_ordinal, system in enumerate(systems):
        if system.system_id in system_ordinals:
            raise AssertionError(f"duplicate raw source system ID: {system.system_id}")
        system_ordinals[system.system_id] = selected_ordinal
        for raw_pose_ordinal, pose in enumerate(system.poses):
            key = (system.system_id, pose.ligand_pred.resolve())
            if key in lookup:
                raise AssertionError(f"duplicate raw predicted pose path: {key}")
            lookup[key] = (system, raw_pose_ordinal, pose)
    return lookup, system_ordinals


def _manifest_pose_records(
    manifest: Mapping[str, Any],
    data_dir: Path,
) -> Dict[int, Dict[str, Any]]:
    """Validate manifest storage records and flatten their per-pose metadata."""
    flattened: Dict[int, Dict[str, Any]] = {}
    for shard_index, shard in enumerate(manifest["shards"]):
        records = shard["systems"]
        for storage_system_index, record in enumerate(records):
            sources = [int(value) for value in record["source_graph_indices"]]
            paths = [str(value) for value in record["source_pose_paths"]]
            if len(sources) != len(paths) or len(sources) != int(record["num_graphs"]):
                raise AssertionError(
                    f"shard {shard_index} storage group {storage_system_index}: "
                    "source indices, paths and graph count differ"
                )
            for storage_pose_ordinal, (source, path_text) in enumerate(zip(sources, paths)):
                if source in flattened:
                    raise AssertionError(f"source_graph_index appears in two manifest records: {source}")
                predicted_path = _resolve_declared_path(path_text, data_dir)
                flattened[source] = {
                    "shard_index": shard_index,
                    "local_storage_system_index": storage_system_index,
                    "storage_pose_ordinal": storage_pose_ordinal,
                    "storage_system_id": str(record["system_id"]),
                    "source_system_id": str(record["source_system_id"]),
                    "predicted_ligand_path": predicted_path,
                    "declared_predicted_ligand_path": path_text,
                }
    return flattened


def _source_locations_from_tensors(
    manifest: Mapping[str, Any],
    shards: Sequence[Mapping[str, torch.Tensor]],
) -> Dict[int, tuple[int, int, int]]:
    """Read the authoritative source -> pooled-location relationship."""
    locations: Dict[int, tuple[int, int, int]] = {}
    for shard_index, (entry, shard) in enumerate(zip(manifest["shards"], shards)):
        source_tensor = shard.get("source_graph_index")
        pose_system = shard.get("pose_system")
        if source_tensor is None or pose_system is None:
            raise AssertionError(f"shard {shard_index} lacks source_graph_index or pose_system")
        if source_tensor.ndim != 1 or pose_system.ndim != 1 or source_tensor.numel() != pose_system.numel():
            raise AssertionError(f"shard {shard_index} has inconsistent pose tensors")
        if int(entry["num_graphs"]) != int(source_tensor.numel()):
            raise AssertionError(f"shard {shard_index} manifest graph count differs from tensor")
        if int(entry["num_systems"]) != int(shard["system_graph_ptr"].numel()) - 1:
            raise AssertionError(f"shard {shard_index} manifest storage count differs from pointer")
        for local_pose, (source_value, storage_value) in enumerate(
            zip(source_tensor.tolist(), pose_system.tolist())
        ):
            source = int(source_value)
            storage_system = int(storage_value)
            if source in locations:
                raise AssertionError(f"source_graph_index appears in two tensor positions: {source}")
            if not 0 <= storage_system < int(entry["num_systems"]):
                raise AssertionError(
                    f"shard {shard_index} local pose {local_pose}: invalid storage system {storage_system}"
                )
            begin, end = _pointer_bounds(shard["system_graph_ptr"], storage_system, "system_graph_ptr")
            if not begin <= local_pose < end:
                raise AssertionError(
                    f"shard {shard_index} local pose {local_pose}: pose_system violates pointer"
                )
            locations[source] = (shard_index, local_pose, storage_system)
    return locations


def _run_pose_ordinals(rows: Sequence[Mapping[str, Any]]) -> Dict[int, int]:
    """Rank output poses within each source system by run-local source index."""
    by_system: Dict[str, List[int]] = defaultdict(list)
    for row in rows:
        by_system[str(row["source_system_id"])].append(int(row["source_graph_index"]))
    result: Dict[int, int] = {}
    for source_system_id, sources in by_system.items():
        if len(sources) != len(set(sources)):
            raise AssertionError(f"duplicate source graph index within {source_system_id}")
        for ordinal, source in enumerate(sorted(sources)):
            result[source] = ordinal
    return result


def build_rows(
    dataset_root: Path,
    data_dir: Path,
    manifest: Mapping[str, Any],
    source_index: Mapping[str, Any],
) -> tuple[List[Dict[str, Any]], Dict[str, int]]:
    """Build ordered graph-index rows and prove every compact pointer agrees."""
    if manifest.get("format") != v2.FORMAT_NAME or int(manifest.get("schema_version", -1)) != 1:
        raise AssertionError("only gnncp_compact_v1 schema 1 pooled-v2 outputs are supported")
    if manifest.get("status") != "complete":
        raise AssertionError("refusing to index a dataset whose manifest is not complete")
    if not data_dir.is_dir():
        raise FileNotFoundError(data_dir)
    if not isinstance(manifest.get("shards"), list) or not manifest["shards"]:
        raise AssertionError("manifest has no shards")

    dataset_sources = [int(value) for value in source_index["source_graph_indices"]]
    dataset_systems = [str(value) for value in source_index["graph_to_system"]]
    n_graphs = int(manifest["n_graphs"])
    if len(dataset_sources) != n_graphs or len(dataset_systems) != n_graphs:
        raise AssertionError("source_index count differs from manifest n_graphs")
    if len(dataset_sources) != len(set(dataset_sources)):
        raise AssertionError("source_index contains duplicate source_graph_index values")
    if int(source_index.get("n_graphs", n_graphs)) != n_graphs:
        raise AssertionError("source_index n_graphs differs from manifest")
    graph_map = manifest.get("graph_map")
    if not isinstance(graph_map, list) or len(graph_map) != n_graphs:
        raise AssertionError("manifest graph_map is absent or has the wrong length")

    source_ids = _source_ids_from_manifest(manifest)
    source_ids.update(dataset_systems)
    raw_systems = _selected_raw_systems(data_dir, str(manifest["method"]), source_ids)
    raw_lookup, raw_system_ordinals = _raw_pose_lookup(raw_systems)
    manifest_records = _manifest_pose_records(manifest, data_dir)
    shards = _load_shards(dataset_root, manifest)
    tensor_locations = _source_locations_from_tensors(manifest, shards)

    if set(manifest_records) != set(tensor_locations):
        mismatch = sorted(set(manifest_records).symmetric_difference(tensor_locations))[:10]
        raise AssertionError(f"manifest/tensor source_graph_index sets differ: {mismatch}")
    if set(dataset_sources) != set(tensor_locations):
        mismatch = sorted(set(dataset_sources).symmetric_difference(tensor_locations))[:10]
        raise AssertionError(f"source_index/tensor source_graph_index sets differ: {mismatch}")

    provisional: List[Dict[str, Any]] = []
    for dataset_index, (source, source_system_id) in enumerate(zip(dataset_sources, dataset_systems)):
        shard_index, local_pose_index, local_storage_system_index = tensor_locations[source]
        declared = manifest_records[source]
        expected_map = [shard_index, local_pose_index]
        actual_map = [int(value) for value in graph_map[dataset_index]]
        if actual_map != expected_map:
            raise AssertionError(
                f"dataset_index {dataset_index}: graph_map={actual_map} != tensor location={expected_map}"
            )
        if declared["shard_index"] != shard_index or declared["local_storage_system_index"] != local_storage_system_index:
            raise AssertionError(
                f"source_graph_index {source}: manifest record does not match tensor storage group"
            )
        if declared["source_system_id"] != source_system_id:
            raise AssertionError(
                f"dataset_index {dataset_index}: source_index system {source_system_id} "
                f"!= manifest system {declared['source_system_id']}"
            )
        raw_key = (source_system_id, declared["predicted_ligand_path"])
        if raw_key not in raw_lookup:
            raise AssertionError(
                f"dataset_index {dataset_index}: declared predicted PDB does not match a raw pose: "
                f"{source_system_id} / {declared['predicted_ligand_path']}"
            )
        raw_system, raw_pose_ordinal, raw_pose = raw_lookup[raw_key]
        if not raw_pose.protein.is_file() or not raw_pose.ligand_native.is_file() or not raw_pose.ligand_pred.is_file():
            raise FileNotFoundError(f"raw PDB missing for source_graph_index {source}")
        storage_begin, _ = _pointer_bounds(
            shards[shard_index]["system_graph_ptr"], local_storage_system_index, "system_graph_ptr"
        )
        provisional.append(
            {
                "dataset_index": dataset_index,
                "source_graph_index": source,
                "source_system_id": source_system_id,
                "selected_raw_system_ordinal": raw_system_ordinals[source_system_id],
                "raw_pose_ordinal": raw_pose_ordinal,
                "shard_index": shard_index,
                "local_pose_index": local_pose_index,
                "local_storage_system_index": local_storage_system_index,
                "storage_pose_ordinal": local_pose_index - storage_begin,
                "storage_system_id": declared["storage_system_id"],
                "protein_path": _relative_or_absolute(raw_pose.protein, data_dir),
                "native_ligand_path": _relative_or_absolute(raw_pose.ligand_native, data_dir),
                "predicted_ligand_path": _relative_or_absolute(raw_pose.ligand_pred, data_dir),
            }
        )

    run_ordinals = _run_pose_ordinals(provisional)
    rows: List[Dict[str, Any]] = []
    for row in provisional:
        copied = dict(row)
        copied["run_pose_ordinal"] = run_ordinals[int(copied["source_graph_index"])]
        rows.append(copied)

    identity = {
        (str(row["source_system_id"]), int(row["raw_pose_ordinal"]), str(row["predicted_ligand_path"]))
        for row in rows
    }
    locations = {(int(row["shard_index"]), int(row["local_pose_index"])) for row in rows}
    if len(identity) != len(rows):
        raise AssertionError("raw system/pose/path identity is not one-to-one")
    if len(locations) != len(rows):
        raise AssertionError("pooled shard/local pose location is not one-to-one")
    if [int(row["dataset_index"]) for row in rows] != list(range(n_graphs)):
        raise AssertionError("dataset indices are not the contiguous reader order")

    checks = {
        "dataset_graphs": len(rows),
        "source_graph_indices_unique": len(set(dataset_sources)),
        "raw_identity_unique": len(identity),
        "shard_local_locations_unique": len(locations),
        "raw_source_systems_matched": len({str(row["source_system_id"]) for row in rows}),
        "shards_checked": len(shards),
        "storage_groups_checked": sum(int(entry["num_systems"]) for entry in manifest["shards"]),
        "raw_pdb_triplets_exists": len(rows),
    }
    return rows, checks


def _jsonl_bytes(rows: Sequence[Mapping[str, Any]]) -> bytes:
    return b"".join(
        (json.dumps(row, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8")
        for row in rows
    )


def _write_new_bytes(path: Path, payload: bytes) -> None:
    """Atomically create a new file without ever replacing an existing one."""
    if path.exists():
        raise FileExistsError(f"refusing to overwrite existing sidecar: {path}")
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(f".{path.name}.tmp.{os.getpid()}")
    try:
        with temporary.open("xb") as handle:
            handle.write(payload)
            handle.flush()
            os.fsync(handle.fileno())
        # link(2) creates the destination only if it is absent.  Unlike
        # os.replace, this cannot overwrite a concurrently-created sidecar.
        os.link(temporary, path)
    except BaseException:
        temporary.unlink(missing_ok=True)
        raise
    temporary.unlink(missing_ok=True)


def _read_jsonl(path: Path) -> List[Dict[str, Any]]:
    rows: List[Dict[str, Any]] = []
    with path.open("r", encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, start=1):
            if not line.strip():
                raise AssertionError(f"blank row in graph index at line {line_number}")
            value = json.loads(line)
            if not isinstance(value, dict):
                raise AssertionError(f"non-object row in graph index at line {line_number}")
            rows.append(value)
    return rows


def _sidecar_manifest(
    dataset_root: Path,
    data_dir: Path,
    dataset_manifest: Mapping[str, Any],
    index_path: Path,
    rows: Sequence[Mapping[str, Any]],
    checks: Mapping[str, int],
    *,
    dataset_root_label: str | None = None,
) -> Dict[str, Any]:
    return {
        "format": INDEX_FORMAT,
        "schema_version": INDEX_SCHEMA_VERSION,
        "status": "complete",
        "created_utc": _timestamp(),
        # A builder may generate this sidecar in an isolated staging directory
        # just before an atomic stage -> final rename.  ``.`` keeps the map
        # portable and never leaks that transient staging path.
        "dataset_root": dataset_root_label if dataset_root_label is not None else str(dataset_root),
        "dataset_root_semantics": "relative to this sidecar's containing directory when set to '.'",
        "data_dir": str(data_dir),
        "dataset": {
            "format": dataset_manifest["format"],
            "schema_version": int(dataset_manifest["schema_version"]),
            "method": str(dataset_manifest["method"]),
            "cutoff": float(dataset_manifest["cutoff"]),
            "manifest": "manifest.json",
            "source_index": "source_index.json",
        },
        "graph_index": index_path.name,
        "n_graphs": len(rows),
        "ordering": {
            "row_order": "row N is exactly CompactGraphDataset(dataset_root)[N]",
            "dataset_index": "0-based CompactGraphDataset index; primary training/prediction join key for this dataset root",
            "source_graph_index": "0-based builder-run-local source pose index; keep it for audit, do not treat it as a cross-run global ID",
            "selected_raw_system_ordinal": "0-based natural source-system order within the source systems represented by this output; not a cross-run global ID",
            "raw_pose_ordinal": "0-based natural pose order within source_system_id across all raw poses present under data_dir",
            "run_pose_ordinal": "0-based rank within the successful build output for source_system_id, ordered by source_graph_index",
            "paths": "relative to data_dir when possible; otherwise absolute",
        },
        "row_columns": [
            "dataset_index",
            "source_graph_index",
            "source_system_id",
            "selected_raw_system_ordinal",
            "raw_pose_ordinal",
            "run_pose_ordinal",
            "shard_index",
            "local_pose_index",
            "local_storage_system_index",
            "storage_pose_ordinal",
            "storage_system_id",
            "protein_path",
            "native_ligand_path",
            "predicted_ligand_path",
        ],
        "validation": dict(checks),
        "training_contract": (
            "Emit dataset_index with every model prediction.  When predictions are "
            "merged across runs, retain source_system_id, raw_pose_ordinal and "
            "predicted_ligand_path as provenance columns."
        ),
    }


def write_sidecars(
    dataset_root: Path,
    data_dir: Path,
    *,
    index_name: str = DEFAULT_INDEX_NAME,
    index_manifest_name: str = DEFAULT_MANIFEST_NAME,
    dataset_root_label: str | None = None,
) -> Dict[str, Any]:
    """Create both new provenance sidecars, refusing every overwrite.

    This is also the builder-facing API.  ``dataset_root`` may be an isolated
    staging directory, while ``dataset_root_label='.'`` produces a portable
    final-sidecar manifest after the builder atomically renames the directory.
    """
    if Path(index_name).name != index_name or Path(index_manifest_name).name != index_manifest_name:
        raise ValueError("sidecar file names must be simple names inside dataset_root")
    index_path = dataset_root / index_name
    index_manifest_path = dataset_root / index_manifest_name
    if index_path.exists() or index_manifest_path.exists():
        present = [str(path) for path in (index_path, index_manifest_path) if path.exists()]
        raise FileExistsError(f"refusing to overwrite existing sidecar(s): {present}")
    dataset_manifest = _read_json(dataset_root / "manifest.json")
    source_index = _read_json(dataset_root / "source_index.json")
    rows, checks = build_rows(dataset_root, data_dir, dataset_manifest, source_index)
    sidecar_manifest = _sidecar_manifest(
        dataset_root,
        data_dir,
        dataset_manifest,
        index_path,
        rows,
        checks,
        dataset_root_label=dataset_root_label,
    )
    _write_new_bytes(index_path, _jsonl_bytes(rows))
    try:
        _write_new_bytes(
            index_manifest_path,
            (json.dumps(sidecar_manifest, ensure_ascii=False, indent=2) + "\n").encode("utf-8"),
        )
    except BaseException:
        # Do not remove a successfully-created immutable index: removal would
        # be destructive.  Report the remaining file clearly instead.
        raise RuntimeError(
            f"graph index was created at {index_path}, but its companion "
            f"manifest was not created; preserve it and resolve manually"
        ) from None
    return {"status": "created", "rows": len(rows), "checks": checks}


def parse_args(argv: Sequence[str] | None = None) -> Arguments:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--dataset-root", required=True, type=Path)
    parser.add_argument(
        "--data-dir",
        type=Path,
        default=None,
        help="Raw materialized docking root; defaults to manifest.source.data_dir.",
    )
    parser.add_argument("--index-name", default=DEFAULT_INDEX_NAME)
    parser.add_argument("--index-manifest-name", default=DEFAULT_MANIFEST_NAME)
    parser.add_argument(
        "--check-only",
        action="store_true",
        help="Validate an existing sidecar against compact tensors and raw PDB paths without writing.",
    )
    raw = parser.parse_args(argv)
    dataset_root = raw.dataset_root.expanduser().resolve()
    if not dataset_root.is_dir():
        raise FileNotFoundError(dataset_root)
    if Path(raw.index_name).name != raw.index_name or Path(raw.index_manifest_name).name != raw.index_manifest_name:
        raise ValueError("index file names must be simple file names inside --dataset-root")
    dataset_manifest = _read_json(dataset_root / "manifest.json")
    data_dir_value = raw.data_dir if raw.data_dir is not None else dataset_manifest.get("source", {}).get("data_dir")
    if not data_dir_value:
        raise ValueError("--data-dir is required because manifest.source.data_dir is absent")
    return Arguments(
        dataset_root=dataset_root,
        data_dir=Path(data_dir_value).expanduser().resolve(),
        index_path=dataset_root / raw.index_name,
        index_manifest_path=dataset_root / raw.index_manifest_name,
        check_only=bool(raw.check_only),
    )


def run(arguments: Arguments) -> Dict[str, Any]:
    if arguments.check_only:
        dataset_manifest = _read_json(arguments.dataset_root / "manifest.json")
        source_index = _read_json(arguments.dataset_root / "source_index.json")
        rows, checks = build_rows(
            arguments.dataset_root, arguments.data_dir, dataset_manifest, source_index
        )
        if not arguments.index_path.is_file() or not arguments.index_manifest_path.is_file():
            raise FileNotFoundError("--check-only requires both graph index sidecar files")
        existing_rows = _read_jsonl(arguments.index_path)
        if existing_rows != rows:
            raise AssertionError("existing graph_index.jsonl differs from reconstructed provenance mapping")
        existing_manifest = _read_json(arguments.index_manifest_path)
        if existing_manifest.get("format") != INDEX_FORMAT or int(existing_manifest.get("schema_version", -1)) != INDEX_SCHEMA_VERSION:
            raise AssertionError("existing graph index manifest has an unsupported schema")
        if int(existing_manifest.get("n_graphs", -1)) != len(rows):
            raise AssertionError("existing graph index manifest graph count differs")
        print(
            f"checked: {arguments.index_path} ({len(rows)} rows; "
            f"{checks['raw_identity_unique']} unique raw identities)",
            flush=True,
        )
        return {"status": "checked", "rows": len(rows), "checks": checks}

    # Rebuild once through the write API so the non-overwrite policy is shared
    # by standalone export and automatic builder integration.
    result = write_sidecars(
        arguments.dataset_root,
        arguments.data_dir,
        index_name=arguments.index_path.name,
        index_manifest_name=arguments.index_manifest_path.name,
    )
    print(
        f"created: {arguments.index_path} ({result['rows']} rows; "
        f"{result['checks']['raw_identity_unique']} unique raw identities)",
        flush=True,
    )
    return result


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


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