File size: 50,681 Bytes
8c4f971
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Generate fixed spatial hotspots using existing static and dynamic ANN datasets."""

from __future__ import annotations

import argparse
import copy
import hashlib
import json
import math
import os
from pathlib import Path

import numpy as np

from spatial_common import (digest_json, file_identity, matrix, read_json, safe_child,
                            seeded_rng, sha256, write_json, write_matrix, write_u32)
from spatial_groundtruth import write_checkpoint_groundtruth
from spatial_partition import prepare_partition, prepare_query_bank


class Dataset:
    def __init__(self, config, static_root, update_root, partition_root, threads=16, chunk_rows=250000):
        self.config = config
        self.source = config["source"]
        self.static = Path(static_root)
        self.update = Path(update_root)
        self.partition = Path(partition_root)
        self.partition_info = read_json(self.partition / "partition.json")
        self.base = matrix(self.static / self.source["base"], self.source["dtype"])
        self.queries = matrix(self.static / self.source["queries"], self.source.get("query_dtype", self.source["dtype"]))
        self.n, self.dim = self.base.shape
        self.initial_count = int(self.source["initial_count"])
        if self.n != self.source["base_count"] or not 0 < self.initial_count < self.n:
            raise ValueError("Invalid base/initial source counts")
        if self.partition_info["source_rows"] != self.n or self.partition_info["query_rows"] != len(self.queries):
            raise ValueError("Partition source/query row count mismatch")
        if self.partition_info["parameters"] != config["partition"]:
            raise ValueError("Partition parameters differ from requested configuration")
        for key, path in (("base", self.static / self.source["base"]), ("queries", self.static / self.source["queries"])):
            identity = file_identity(path)
            expected = self.partition_info["source"][key]
            if (identity["bytes"], identity["sample_sha256"]) != (expected["bytes"], expected["sample_sha256"]):
                raise ValueError(f"Partition was generated from different {key}")
        signature_inputs = {"parameters": config["partition"], "source": self.partition_info["source"],
                            "dtype": self.source["dtype"]}
        if self.source.get("query_dtype", self.source["dtype"]) != self.source["dtype"]:
            signature_inputs["query_dtype"] = self.source["query_dtype"]
        if digest_json(signature_inputs) != self.partition_info["signature"]:
            raise ValueError("Partition dtype semantics/signature mismatch")
        for name, expected in self.partition_info["files"].items():
            path = safe_child(self.partition, name)
            if path.stat().st_size != expected["bytes"] or sha256(path) != expected["sha256"]:
                raise ValueError(f"Corrupted partition file: {name}")
        self.assignments = np.memmap(self.partition / "assignments.u32", dtype="<u4", mode="r")
        self.query_assignments = np.memmap(self.partition / "query_assignments.u32", dtype="<u4", mode="r")
        self.order = np.memmap(self.update / self.source["update_order"], dtype="<u4", mode="r")
        self.clusters = int(config["partition"]["clusters"])
        if len(self.assignments) != self.n or len(self.order) != self.n or len(self.query_assignments) != len(self.queries):
            raise ValueError("Assignment or update permutation length mismatch")
        seen = np.zeros(self.n, dtype=bool)
        # Check the entire permutation, including duplicates inside each block.
        for offset in range(0, self.n, 1000000):
            ids = self.order[offset:offset + 1000000]
            if np.any(ids >= self.n) or seen[ids].any() or len(np.unique(ids)) != len(ids):
                raise ValueError("update_order is not a permutation of original source IDs")
            seen[ids] = True
        if not seen.all():
            raise ValueError("update_order omits source IDs")
        self.initial_live = np.zeros(self.n, dtype=bool)
        self.initial_live[self.order[:self.initial_count]] = True
        self.inverse_order = np.empty(self.n, dtype="<u4")
        for offset in range(0, self.n, 1000000):
            self.inverse_order[self.order[offset:offset + 1000000]] = np.arange(offset, min(offset + 1000000, self.n), dtype="<u4")
        self.insert_vectors = matrix(self.update / self.source["insert_vectors"], self.source["dtype"])
        if self.insert_vectors.shape != self.base.shape:
            raise ValueError("Shared insert-vector matrix shape mismatch")
        if self.source.get("insert_vector_order", "permuted") not in ("permuted", "source"):
            raise ValueError("insert_vector_order must be permuted or source")
        self.source_identities = {
            "base": self.partition_info["source"]["base"],
            "queries": self.partition_info["source"]["queries"],
            "groundtruth": file_identity(self.static / self.source["groundtruth"]),
            "update_order": file_identity(self.update / self.source["update_order"]),
            "insert_vectors": file_identity(self.update / self.source["insert_vectors"]),
        }
        self.query_bank_name = "original"
        self._root_dataset = self
        self._query_bank_views = {"original": self}
        self._query_threads, self._query_chunk_rows = threads, chunk_rows
        original = {"queries": self.source["queries"], "groundtruth": self.source["groundtruth"],
                    "query_dtype": self.source.get("query_dtype", self.source["dtype"])}
        self.query_bank_specs = {"original": original, **config.get("query_banks", {})}
        for name, bank in self.query_bank_specs.items():
            if not isinstance(name, str) or Path(name).name != name or name in ("", ".", ".."):
                raise ValueError("Query bank names must be simple directory names")
            if not isinstance(bank, dict) or not all(key in bank for key in ("queries", "groundtruth")):
                raise ValueError(f"Query bank {name!r} requires queries and groundtruth")
            for key in ("queries", "groundtruth"):
                if (not isinstance(bank[key], str) or not bank[key] or
                        Path(bank[key]).is_absolute() or ".." in Path(bank[key]).parts):
                    raise ValueError("Query bank paths must be relative to the static source root")
        declared_original = self.query_bank_specs["original"]
        if any(declared_original.get(key, original[key]) != original[key] for key in original):
            raise ValueError("Original query bank must match the source paths/dtype used by the fixed partition")
        self.query_bank_info = self._query_bank_identity(
            "query_assignments.u32", "partition.json", self.partition_info["signature"],
            self.partition_info["files"]["query_assignments.u32"]["sha256"])

    def _query_bank_identity(self, assignment_path, metadata_path, signature, assignment_hash):
        prefix = f"partitions/{self.partition.name}/"
        return {"name": self.query_bank_name, "queries": self.source["queries"],
                "groundtruth": self.source["groundtruth"],
                "query_dtype": self.source.get("query_dtype", self.source["dtype"]),
                "row_count": len(self.queries), "dimension": self.dim,
                "source_identities": {key: self.source_identities[key] for key in ("queries", "groundtruth")},
                "assignment": {"path": prefix + assignment_path, "metadata": prefix + metadata_path,
                               "signature": signature, "sha256": assignment_hash}}

    def for_profile(self, profile):
        """Return a bank-specific view sharing all base, permutation, and live arrays."""
        name = profile.get("query_bank", "original")
        root = self._root_dataset
        if name not in root.query_bank_specs:
            raise ValueError(f"Unknown query bank: {name!r}")
        if name in root._query_bank_views:
            return root._query_bank_views[name]
        bank = root.query_bank_specs[name]
        view = copy.copy(root)
        view.query_bank_name = name
        view.source = {**root.source, "queries": bank["queries"], "groundtruth": bank["groundtruth"],
                       "query_dtype": bank.get("query_dtype", root.source.get("query_dtype", root.source["dtype"]))}
        # Input packages may compose immutable source files through symlinks.
        # Their declared paths were checked lexically; generated artifacts still
        # use safe_child's resolved-path confinement.
        query_path = root.static / bank["queries"]
        gt_path = root.static / bank["groundtruth"]
        view.queries = matrix(query_path, view.source["query_dtype"])
        source_gt = matrix(gt_path, "uint32", allow_distances=True)
        if view.queries.shape[1] != root.dim or len(source_gt) != len(view.queries):
            raise ValueError(f"Query bank {name!r} has mismatched query/GT rows or vector dimensions")
        manifest = prepare_query_bank(root.partition, name, query_path, view.source["query_dtype"],
                                      root._query_threads, root._query_chunk_rows)
        relative = f"query_banks/{name}/"
        view.query_assignments = np.memmap(root.partition / relative / "query_assignments.u32", dtype="<u4", mode="r")
        if (len(view.query_assignments) != len(view.queries) or
                np.any(view.query_assignments >= root.clusters)):
            raise ValueError(f"Invalid query bank assignments: {name}")
        if not np.array_equal(np.bincount(view.query_assignments, minlength=root.clusters), manifest["query_counts"]):
            raise ValueError(f"Query bank assignment counts disagree with sidecar: {name}")
        view.source_identities = {**root.source_identities, "queries": file_identity(query_path),
                                  "groundtruth": file_identity(gt_path)}
        view.query_bank_info = view._query_bank_identity(
            relative + "query_assignments.u32", relative + "query_bank.json", manifest["signature"],
            manifest["files"]["query_assignments.u32"]["sha256"])
        root._query_bank_views[name] = view
        return view

    def explicit_query_bank(self, profile=None):
        return "query_banks" in self.config or (profile is not None and "query_bank" in profile)

    def live(self, state):
        if state == "static-100m":
            return np.ones(self.n, dtype=bool)
        if state == "initial-80m":
            return self.initial_live.copy()
        raise ValueError(f"Unsupported initial state: {state}")

    def vector_refs(self, source_ids):
        if self.source.get("insert_vector_order", "permuted") == "source":
            return np.asarray(source_ids, dtype="<u4")
        return self.inverse_order[source_ids]


def select_hotspot(dataset):
    # The hotspot definition retains the original bank's statistics and identity.
    dataset = dataset._root_dataset
    parameters = dataset.config["hotspot"]
    centroids = matrix(dataset.partition / "centroids.fbin")
    counts = np.asarray(dataset.partition_info["counts"], dtype=np.int64)
    if len(counts) != dataset.clusters or counts.sum() != dataset.n:
        raise ValueError("Invalid partition counts")
    if "clusters" in parameters:
        selected = [int(c) for c in parameters["clusters"]]
        if not selected or len(set(selected)) != len(selected) or min(selected) < 0 or max(selected) >= len(counts):
            raise ValueError("Invalid explicit hotspot cluster IDs")
        root = selected[0]
    else:
        mass = float(parameters["target_mass"])
        if not 0 < mass < 1:
            raise ValueError("Hotspot target_mass must be between 0 and 1")
        rng = seeded_rng(int(parameters["seed"]), "hotspot-root")
        root = int(rng.choice(np.flatnonzero(counts)))
        distances = np.sum((centroids.astype(np.float64) - centroids[root]) ** 2, axis=1)
        nearest = np.lexsort((np.arange(len(counts)), distances))
        selected, total = [], 0
        for label in nearest:
            if not counts[label]:
                continue
            selected.append(int(label))
            total += int(counts[label])
            if total >= math.ceil(mass * dataset.n):
                break
    flags = np.zeros(dataset.clusters, dtype=bool)
    flags[selected] = True
    if np.any(dataset.assignments >= dataset.clusters) or np.any(dataset.query_assignments >= dataset.clusters):
        raise ValueError("Invalid cluster assignment")
    hot = flags[dataset.assignments]
    query_hot = flags[dataset.query_assignments]
    actual_counts = np.bincount(dataset.assignments, minlength=dataset.clusters)
    if not np.array_equal(actual_counts, counts):
        raise ValueError("Partition counts disagree with actual assignments")
    info = {
        "scope": "one fixed hotspot for the entire run, shared by all CNs",
        "root_cluster": root, "clusters": selected,
        "target_mass": parameters.get("target_mass"),
        "actual_mass": float(hot.mean()), "source_vectors": int(hot.sum()),
        "initial_live_vectors": int(np.count_nonzero(hot & dataset.initial_live)),
        "fresh_vectors": int(np.count_nonzero(hot & ~dataset.initial_live)),
        "query_vectors": int(query_hot.sum()),
    }
    return info, hot, query_hot


def quota(count, fraction):
    if fraction is None:
        return None
    if not 0 <= float(fraction) <= 1:
        raise ValueError("Hot operation fraction must be in [0,1]")
    return int(math.floor(count * float(fraction) + 0.5))


def profile_plan(dataset, profile, hotspot, hot, query_hot):
    dataset = dataset.for_profile(profile)
    query_hot = np.isin(dataset.query_assignments, hotspot["clusters"])
    kind = profile["kind"]
    if kind not in ("query", "insert", "delete", "mixed"):
        raise ValueError(f"Unknown profile kind: {kind}")
    for key in ("inserts", "deletes", "queries", "query_rows"):
        if int(profile[key]) != profile[key] or profile[key] < 0:
            raise ValueError(f"Invalid {key}")
    if not profile["query_rows"] or not profile["queries"]:
        raise ValueError("Query count and stored query rows must be positive")
    inserts, deletes = profile["inserts"], profile["deletes"]
    if ((kind == "query" and (inserts or deletes)) or
            (kind == "insert" and (not inserts or deletes)) or
            (kind == "delete" and (inserts or not deletes)) or
            (kind == "mixed" and (not inserts or inserts != deletes))):
        raise ValueError("Profile kind and operation counts disagree")
    if inserts and profile["initial_state"] != "initial-80m":
        raise ValueError("Fresh inserts require the initial update snapshot")
    live = dataset.live(profile["initial_state"])
    capacities = {}
    for name, count, eligible in (("insert", inserts, ~live), ("delete", deletes, live), ("query", profile["query_rows"], None)):
        mask = query_hot if name == "query" else hot
        total = len(mask) if eligible is None else int(eligible.sum())
        hot_count = int(mask.sum()) if eligible is None else int(np.count_nonzero(mask & eligible))
        required = quota(count, profile.get(f"{name}_hot_fraction"))
        if name != "query":
            if count > total or (required is not None and (required > hot_count or count - required > total - hot_count)):
                raise ValueError(f"{profile['id']}: insufficient {name} pool; no spill or ID reuse is permitted")
        elif required is not None and ((required and not hot_count) or (count - required and total == hot_count)):
            raise ValueError("Requested query region has no official queries")
        capacities[name] = {"eligible": total, "hot_eligible": hot_count, "cold_eligible": total - hot_count,
                            "requested": count, "hot_quota": required}
    batch_size = int(profile.get("batch_size", 0))
    if batch_size != profile.get("batch_size", 0):
        raise ValueError("batch_size must be an integer")
    if kind != "query" and (batch_size < 1 or max(inserts, deletes) % batch_size):
        raise ValueError("Updates must consist of complete, equal-size batches")
    if kind == "mixed" and profile["queries"] != 36 * inserts:
        raise ValueError("v1 mixed profiles use the existing 36:1:1 concurrent ratio")
    result = {"profile": profile, "hotspot": hotspot, "capacities": capacities,
              "batch_count": max(inserts, deletes) // batch_size if batch_size else 0,
              "initial_live_count": int(live.sum()), "final_live_count": int(live.sum()) + inserts - deletes}
    if dataset.explicit_query_bank(profile):
        result["query_bank"] = dataset.query_bank_info
    return result


def sample_ids(eligible, hot, count, fraction, rng):
    if not count:
        return np.empty(0, dtype="<u4")
    hot_count = quota(count, fraction)
    if hot_count is None:
        pool = np.flatnonzero(eligible).astype("<u4")
        return rng.choice(pool, count, replace=False).astype("<u4")
    pieces = []
    for mask, requested in ((hot, hot_count), (~hot, count - hot_count)):
        if requested:
            pool = np.flatnonzero(eligible & mask).astype("<u4")
            if requested > len(pool):
                raise ValueError("Insufficient eligible pool")
            pieces.append(rng.choice(pool, requested, replace=False))
    selected = np.concatenate(pieces).astype("<u4")
    rng.shuffle(selected)
    return selected


def ordered_ids(dataset, profile, name):
    """Uniform IDs taken in update_order (P) instead of random sampling.

    insert: P[initial_count + k]; delete from static-100m: P[initial_count + k];
    delete from initial-80m: P[k]. Smaller runs are prefixes of the same stream and
    match the legacy insert-20 / delete-20 / mixed-replace-100 traces.
    """
    count = profile[name + "s"]
    if not count:
        return np.empty(0, dtype="<u4")
    if profile.get(f"{name}_hot_fraction") is not None:
        raise ValueError("id_order=update_order applies only to uniform streams")
    start = 0 if (name == "delete" and profile["initial_state"] == "initial-80m") else dataset.initial_count
    end = start + count
    if (name == "delete" and profile["initial_state"] == "initial-80m" and end > dataset.initial_count) or end > dataset.n:
        raise ValueError(f"{profile['id']}: update_order slice exceeds the eligible pool")
    return np.asarray(dataset.order[start:end], dtype="<u4")


def stream_ids(dataset, profile, name, eligible, hot, stream):
    if profile.get("id_order") == "update_order":
        return ordered_ids(dataset, profile, name)
    if profile.get("id_order", "sampled") != "sampled":
        raise ValueError("id_order must be sampled or update_order")
    return sample_ids(eligible, hot, profile[name + "s"], profile.get(f"{name}_hot_fraction"),
                      seeded_rng(dataset.config["sampling_seed"], f"{name}:" + stream))


def sample_queries(dataset, profile, query_hot):
    dataset = dataset.for_profile(profile)
    rows = profile["query_rows"]
    fraction = profile.get("query_hot_fraction")
    stream = f"queries:{fraction}:{rows}"
    if dataset.query_bank_name != "original":
        stream += f":bank:{dataset.query_bank_name}"
    rng = seeded_rng(dataset.config["sampling_seed"], stream)
    hot_count = quota(rows, fraction)
    if hot_count is None:
        # Exact repetitions preserve the familiar Original10K x50 control.
        if rows % len(dataset.queries) == 0:
            refs = np.tile(np.arange(len(dataset.queries), dtype="<u4"), rows // len(dataset.queries))
        else:
            refs = rng.integers(len(dataset.queries), size=rows, dtype="<u4")
    else:
        pieces = [rng.choice(np.flatnonzero(mask), count, replace=True)
                  for mask, count in ((query_hot, hot_count), (~query_hot, rows - hot_count)) if count]
        refs = np.concatenate(pieces).astype("<u4")
    rng.shuffle(refs)
    return refs


def canonical_gt(dataset, live, cache_root, threads):
    identity = {"live_sha256": hashlib.sha256(live).hexdigest(),
                "inputs": dataset.source_identities, "k": dataset.config["top_k"],
                "metric": dataset.source["metric"], "base_dtype": dataset.source["dtype"],
                "query_dtype": dataset.source.get("query_dtype", dataset.source["dtype"])}
    if dataset.explicit_query_bank() or dataset.query_bank_name != "original":
        identity["query_bank"] = dataset.query_bank_info
    key = digest_json(identity)
    path = Path(cache_root) / f"{key}.bin"
    metadata = path.with_suffix(".json")
    if path.exists() and metadata.exists():
        stats = read_json(metadata)
        if sha256(path) != stats["sha256"]:
            raise ValueError(f"Corrupt cached canonical GT: {path}")
        return path, stats
    stats = write_checkpoint_groundtruth(
        source_groundtruth_path=dataset.static / dataset.source["groundtruth"],
        query_path=dataset.static / dataset.source["queries"],
        base_path=dataset.static / dataset.source["base"], output_path=path,
        live_mask=live, k=dataset.config["top_k"], metric=dataset.source["metric"],
        base_dtype=dataset.source["dtype"], query_dtype=dataset.source.get("query_dtype", dataset.source["dtype"]),
        threads=threads,
    )
    stats["path"] = path.name
    if "query_bank" in identity:
        stats["query_bank"] = dataset.query_bank_info
    stats["sha256"] = sha256(path)
    write_json(metadata, stats)
    return path, stats


def gather_gt(canonical_path, query_refs, output):
    source = matrix(canonical_path, "uint32", allow_distances=True)
    write_matrix(output, source[query_refs], "<u4")


def descriptor(filename, offset, count):
    return {"encoding": "u32_slice", "path": f"../../../streams/{filename}",
            "offset_items": offset, "count": count}


def profile_spec(dataset, profile, hotspot):
    dataset = dataset.for_profile(profile)
    result = {"schema": "spatial-workload-instance.v1", "profile": profile,
              "hotspot": hotspot, "partition_signature": dataset.partition_info["signature"],
              "sampling_seed": dataset.config["sampling_seed"], "source": dataset.source,
              "source_identities": dataset.source_identities, "top_k": dataset.config["top_k"]}
    if dataset.explicit_query_bank(profile):
        result["query_bank"] = dataset.query_bank_info
    return result


def generate_profile(dataset, plan, hot, query_hot, output_root, threads=16):
    profile = plan["profile"]
    dataset = dataset.for_profile(profile)
    query_hot = np.isin(dataset.query_assignments, plan["hotspot"]["clusters"])
    root = Path(output_root) / "workloads" / profile["id"]
    root.mkdir(parents=True, exist_ok=True)
    spec = profile_spec(dataset, profile, plan["hotspot"])
    if (root / "spec.json").exists() and read_json(root / "spec.json") != spec:
        raise ValueError(f"Existing instance {root} uses a different spec; choose a new output/catalog")
    write_json(root / "validation.json", {"status": "generating", "profile": profile["id"]})
    write_json(root / "spec.json", spec)
    write_json(root / "plan.json", plan)
    live = dataset.live(profile["initial_state"])
    stream = profile.get("update_stream", profile["id"])
    insert_ids = stream_ids(dataset, profile, "insert", ~live, hot, stream)
    delete_ids = stream_ids(dataset, profile, "delete", live, hot, stream)
    query_refs = sample_queries(dataset, profile, query_hot)
    write_u32(root / "queries/query_refs.u32", query_refs)
    suffix = {"float32": "fbin", "uint8": "u8bin", "int8": "i8bin"}[dataset.source.get("query_dtype", dataset.source["dtype"])]
    query_rel = f"queries/queries.{suffix}"
    write_matrix(root / query_rel, dataset.queries[query_refs])
    for filename, values in (("insert_ids.u32", insert_ids), ("insert_refs.u32", dataset.vector_refs(insert_ids)), ("delete_ids.u32", delete_ids)):
        if len(values):
            write_u32(root / "streams" / filename, values)
    cache = Path(output_root) / "cache/groundtruth"
    initial_gt, initial_stats = canonical_gt(dataset, live, cache, threads)
    gather_gt(initial_gt, query_refs, root / "groundtruth/initial.bin")
    checkpoints = [{"batch_index": 0, "canonical": str(initial_gt.relative_to(output_root)), "stats": initial_stats}]
    batch_count = plan["batch_count"]
    trace_id = profile["id"]
    trace_root = root / "traces" / trace_id
    for b in range(1, batch_count + 1):
        offset = (b - 1) * profile["batch_size"]
        size = profile["batch_size"]
        operations = []
        if profile["deletes"]:
            ids = delete_ids[offset:offset + size]
            live[ids] = False
            operations.append({"type": "delete", "count": size,
                               "external_ids": descriptor("delete_ids.u32", offset, size)})
        if profile["inserts"]:
            ids = insert_ids[offset:offset + size]
            live[ids] = True
            operations.append({"type": "insert", "count": size,
                               "external_ids": descriptor("insert_ids.u32", offset, size),
                               "vector_refs": descriptor("insert_refs.u32", offset, size)})
        canonical, stats = canonical_gt(dataset, live, cache, threads)
        checkpoint_rel = f"groundtruth/checkpoint_{b:04d}.bin"
        gather_gt(canonical, query_refs, trace_root / checkpoint_rel)
        write_json(trace_root / f"batches/batch_{b:04d}.json", {
            "schema": "batch-update-eval-batch.v1", "dataset": dataset.config["dataset"],
            "trace_id": trace_id, "batch_index": b, "operations": operations,
            "checkpoint": {"index": b, "live_count": int(live.sum()), "groundtruth": checkpoint_rel},
        })
        checkpoints.append({"batch_index": b, "canonical": str(canonical.relative_to(output_root)), "stats": stats})
    state = {"state_id": profile["initial_state"], "live_count": plan["initial_live_count"],
             "groundtruth": "groundtruth/initial.bin"}
    workload = {
        "schema": "batch-update-eval-workload.v1", "checkpoint_contract": "exact-update-counts.v1",
        "dataset": dataset.config["dataset"], "package": profile["id"],
        "base_count": dataset.n, "initial_count": dataset.initial_count,
        "batch_size": profile.get("batch_size", 0),
        "initial" if profile["initial_state"] == "initial-80m" else "static_initial": state,
        "insert_vector_source": {"path": dataset.source["insert_vectors"], "row_count": dataset.n,
                                  "dtype": dataset.source["dtype"], "dim": dataset.dim,
                                  "format": Path(dataset.source["insert_vectors"]).suffix.lstrip(".")},
        "traces": [],
    }
    if batch_count:
        write_json(trace_root / "trace.json", {
            "schema": "batch-update-eval-trace.v1", "dataset": dataset.config["dataset"],
            "trace_id": trace_id, "initial_state": profile["initial_state"],
            "initial_live_count": plan["initial_live_count"], "batch_count": batch_count,
            "batch_size": profile["batch_size"], "groundtruth": {"top_k": dataset.config["top_k"],
                "checkpoint_pattern": "groundtruth/checkpoint_%04d.bin", "source": "actual live source IDs; exact top-k"},
        })
        workload["traces"].append({"id": trace_id, "initial_state": profile["initial_state"],
                                   "batch_count": batch_count, "batches": f"traces/{trace_id}/batches",
                                   "groundtruth": f"traces/{trace_id}/groundtruth"})
    write_json(root / "workload.json", workload)
    bindings = {"kind": profile["kind"], "initial_state": profile["initial_state"],
                "query_path": query_rel, "query_source_count": len(query_refs),
                "query_logical_count": profile["queries"], "initial_groundtruth": "groundtruth/initial.bin",
                "workload_root": ".", "trace_id": trace_id, "batch_count": batch_count,
                "source_segment_update_count": profile.get("batch_size", 0),
                "operation_counts": {"query": profile["queries"], "insert": profile["inserts"], "delete": profile["deletes"]}}
    if profile["kind"] == "mixed":
        bindings["skip_final_merge_delete"] = False
    info = {"schema": "spatial-workload-profile.v1", "id": profile["id"],
            "spec_sha256": digest_json(spec), "runner_bindings": bindings,
            "groundtruth_checkpoints": checkpoints, "control": profile.get("control"),
            "query_execution": "cyclic for mixed; stored row numbers are runtime query IDs",
            "query_role": "foreground" if profile["kind"] in ("query", "mixed") else "recall checkpoints",
            "sampling": {"queries": "with replacement (uniform controls use balanced cycles when divisible)",
                         "updates": ("update_order prefix: insert P[initial+k], delete P[initial+k] from static "
                                     "or P[k] from initial" if profile.get("id_order") == "update_order" else
                                     "without replacement over the entire run; delete only initially live IDs")}}
    if dataset.explicit_query_bank(profile):
        info["query_bank"] = dataset.query_bank_info
        bindings["query_bank"] = dataset.query_bank_name
    write_json(root / "profile.json", info)
    return root


def read_selected_rows_sequentially(values, row_ids, label, block_rows=200000):
    """Gather selected rows while reading file slabs in monotonically increasing order.

    Explicit slab copies trade extra sequential bytes for avoiding hundreds of
    thousands of random page faults on large, disk-backed source matrices.
    """
    row_ids = np.asarray(row_ids)
    order = np.argsort(row_ids)
    sorted_ids = row_ids[order]
    result = np.empty((len(row_ids), values.shape[1]), dtype=values.dtype)
    blocks = np.unique(sorted_ids // block_rows)
    for ordinal, block in enumerate(blocks):
        start = int(block) * block_rows
        stop = min(start + block_rows, len(values))
        left, right = np.searchsorted(sorted_ids, [start, stop])
        slab = np.array(values[start:stop], copy=True)
        result[order[left:right]] = slab[sorted_ids[left:right] - start]
        if ordinal == 0 or (ordinal + 1) % 50 == 0 or ordinal + 1 == len(blocks):
            print(f"Verify {label}: read {ordinal + 1}/{len(blocks)} slabs, selected {right:,}/{len(row_ids):,} rows", flush=True)
    return result


_VERIFIED_INSERT_PAYLOADS = set()


def validate_profile(dataset, profile_root, hot, query_hot, output_root, verify_vectors=True):
    """Validate generated bytes against source vectors and the actual evolving live set."""
    root, output_root = Path(profile_root), Path(output_root)
    write_json(root / "validation.json", {"status": "checking"})
    spec = read_json(root / "spec.json")
    info = read_json(root / "profile.json")
    profile = spec["profile"]
    dataset = dataset.for_profile(profile)
    if info["spec_sha256"] != digest_json(spec):
        raise ValueError("Profile/spec digest mismatch")
    if spec["source_identities"] != dataset.source_identities:
        raise ValueError("Generated profile source identities differ from the supplied dataset")
    current_hotspot, _, _ = select_hotspot(dataset)
    query_hot = np.isin(dataset.query_assignments, current_hotspot["clusters"])
    if spec["hotspot"] != current_hotspot or spec["partition_signature"] != dataset.partition_info["signature"]:
        raise ValueError("Generated profile uses a different hotspot/partition")
    if spec != profile_spec(dataset, profile, current_hotspot):
        raise ValueError("Generated profile spec/query bank differs from the supplied configuration")
    if dataset.explicit_query_bank(profile) and (
            info.get("query_bank") != dataset.query_bank_info or
            info["runner_bindings"].get("query_bank") != dataset.query_bank_name):
        raise ValueError("Generated profile query bank binding mismatch")
    plan = profile_plan(dataset, profile, current_hotspot, hot, query_hot)
    if read_json(root / "plan.json") != plan:
        raise ValueError("Generated plan differs from independently checked capacities")
    bindings = info["runner_bindings"]
    expected_counts = {"query": profile["queries"], "insert": profile["inserts"], "delete": profile["deletes"]}
    if bindings["operation_counts"] != expected_counts or bindings["batch_count"] != plan["batch_count"]:
        raise ValueError("Runner operation counts differ from the generated spec")
    live = dataset.live(profile["initial_state"])
    streams = {}
    for name, count in (("insert", profile["inserts"]), ("delete", profile["deletes"])):
        path = root / f"streams/{name}_ids.u32"
        ids = np.fromfile(path, dtype="<u4") if count else np.empty(0, dtype="<u4")
        if len(ids) != count or np.any(ids >= dataset.n) or len(np.unique(ids)) != len(ids):
            raise ValueError(f"Invalid or repeated {name} source IDs")
        if (name == "insert" and live[ids].any()) or (name == "delete" and not live[ids].all()):
            raise ValueError(f"Illegal {name} lifecycle")
        expected_hot = quota(count, profile.get(f"{name}_hot_fraction"))
        if expected_hot is not None and int(hot[ids].sum()) != expected_hot:
            raise ValueError(f"Incorrect {name} hotspot quota")
        if profile.get("id_order") == "update_order" and not np.array_equal(ids, ordered_ids(dataset, profile, name)):
            raise ValueError(f"{name} IDs do not follow update_order")
        streams[name] = ids
    if len(streams["insert"]):
        refs = np.fromfile(root / "streams/insert_refs.u32", dtype="<u4")
        if not np.array_equal(refs, dataset.vector_refs(streams["insert"])):
            raise ValueError("Insert vector refs do not correspond to external source IDs")
        stream_key = (hashlib.sha256(streams["insert"].tobytes()).hexdigest(),
                      json.dumps(dataset.source_identities["insert_vectors"], sort_keys=True),
                      json.dumps(dataset.source_identities["base"], sort_keys=True))
        if verify_vectors and stream_key not in _VERIFIED_INSERT_PAYLOADS:
            expected_vectors = read_selected_rows_sequentially(dataset.base, streams["insert"], "original vectors")
            actual_vectors = read_selected_rows_sequentially(dataset.insert_vectors, refs, "insert vectors")
            if not np.array_equal(actual_vectors, expected_vectors):
                raise ValueError("Shared insertion vector payload differs from original source vectors")
            del actual_vectors, expected_vectors
            # Profiles sharing an update stream (other query bank / query distribution) reuse this check.
            _VERIFIED_INSERT_PAYLOADS.add(stream_key)
    query_refs = np.fromfile(root / "queries/query_refs.u32", dtype="<u4")
    if len(query_refs) != profile["query_rows"] or np.any(query_refs >= len(dataset.queries)):
        raise ValueError("Invalid query references")
    expected_hot = quota(len(query_refs), profile.get("query_hot_fraction"))
    if expected_hot is not None and int(query_hot[query_refs].sum()) != expected_hot:
        raise ValueError("Incorrect query hotspot quota")
    runtime_queries = matrix(safe_child(root, bindings["query_path"]), dataset.source.get("query_dtype", dataset.source["dtype"]))
    if runtime_queries.shape != (len(query_refs), dataset.dim):
        raise ValueError("Runtime query matrix shape mismatch")
    for offset in range(0, len(query_refs), 10000):
        if not np.array_equal(runtime_queries[offset:offset + 10000], dataset.queries[query_refs[offset:offset + 10000]]):
            raise ValueError("Runtime queries do not match query_refs")
    source_gt = matrix(dataset.static / dataset.source["groundtruth"], "uint32", allow_distances=True)
    if len(source_gt) != len(dataset.queries):
        raise ValueError("Source query bank/groundtruth row count mismatch")
    k = dataset.config["top_k"]
    trace_root = root / "traces" / profile["id"]
    checkpoint_results = []
    for b in range(plan["batch_count"] + 1):
        if b:
            batch = read_json(trace_root / f"batches/batch_{b:04d}.json")
            size = profile["batch_size"]
            offset = (b - 1) * size
            expected_ops = []
            for name in ("delete", "insert"):
                if len(streams[name]):
                    op = {"type": name, "count": size,
                          "external_ids": descriptor(f"{name}_ids.u32", offset, size)}
                    if name == "insert":
                        op["vector_refs"] = descriptor("insert_refs.u32", offset, size)
                    expected_ops.append(op)
                    live[streams[name][offset:offset + size]] = name == "insert"
            if batch["operations"] != expected_ops or batch["checkpoint"]["live_count"] != int(live.sum()):
                raise ValueError("Batch descriptors/checkpoint live count disagree with selected streams")
            runtime_gt = matrix(safe_child(trace_root, batch["checkpoint"]["groundtruth"]), "uint32")
        else:
            runtime_gt = matrix(safe_child(root, bindings["initial_groundtruth"]), "uint32")
        if runtime_gt.shape != (len(query_refs), k):
            raise ValueError("Runtime GT shape does not match query rows/top-k")
        expected = np.empty((len(dataset.queries), k), dtype="<u4")
        insufficient = []
        for q, row in enumerate(source_gt):
            survivors = row[live[row]]
            if len(survivors) >= k:
                expected[q] = survivors[:k]
            else:
                insufficient.append(q)
        if insufficient:
            # Recompute exhausted prefixes, never trust a previous invalid/padded GT.
            temporary = output_root / "cache/validation-fallback.bin"
            write_checkpoint_groundtruth(
                source_groundtruth_path=dataset.static / dataset.source["groundtruth"],
                query_path=dataset.static / dataset.source["queries"],
                base_path=dataset.static / dataset.source["base"], output_path=temporary,
                live_mask=live, k=k, metric=dataset.source["metric"],
                base_dtype=dataset.source["dtype"], query_dtype=dataset.source.get("query_dtype", dataset.source["dtype"]),
            )
            expected = matrix(temporary, "uint32")
        for offset in range(0, len(query_refs), 10000):
            if not np.array_equal(runtime_gt[offset:offset + 10000], expected[query_refs[offset:offset + 10000]]):
                raise ValueError(f"Checkpoint {b} GT is wrong for its live set or query order")
        checkpoint_results.append({"batch_index": b, "live_count": int(live.sum()),
                                   "queries_verified": len(query_refs), "exact_fallback_queries": len(insufficient)})
    result = {
        "schema": "spatial-workload-validation.v1", "status": "passed", "profile": profile["id"],
        "checks": {"id_lifecycle": True, "vector_refs": True, "insert_payloads": verify_vectors,
                   "query_payloads": True, "hot_quotas": True, "exact_groundtruth": True},
        "hotspot": current_hotspot, "checkpoints": checkpoint_results,
        "operations": {},
        "query_count_scope": "stored query rows; logical runtime executions can include a partial cycle",
        "logical_query_count": profile["queries"],
    }
    if dataset.explicit_query_bank(profile):
        result["query_bank"] = dataset.query_bank_info
    for name, ids in (("insert", streams["insert"]), ("delete", streams["delete"]), ("query", query_refs)):
        assignments = dataset.query_assignments if name == "query" else dataset.assignments
        mask = query_hot if name == "query" else hot
        result["operations"][name] = {
            "count": len(ids), "unique": len(np.unique(ids)),
            "hot_count": int(mask[ids].sum()),
            "hot_fraction": float(mask[ids].mean()) if len(ids) else None,
            "cluster_counts": np.bincount(assignments[ids], minlength=dataset.clusters).tolist(),
        }
    write_json(root / "validation.json", result)
    return result


def seal_catalog(output_root, catalog):
    """Seal portable generated files; runtime configs/logs stay outside this tree."""
    root = Path(output_root)
    write_json(root / "catalog.json", catalog)
    names = sorted(path for path in root.rglob("*") if path.is_file()
                   and path.name != "checksums.sha256" and not path.name.endswith((".tmp", ".log")))
    lines = [f"{sha256(path)}  {path.relative_to(root).as_posix()}" for path in names]
    (root / "checksums.sha256").write_text("\n".join(lines) + "\n")
    return len(names)


def retained_catalog_profiles(output_root, config, dataset, hotspot, catalog_context,
                              selected_ids, hot, query_hot):
    """Keep completed instances when a CLI call selects only part of a catalog."""
    output_root = Path(output_root)
    config_path = output_root / "generation-spec.json"
    if config_path.exists() and read_json(config_path) != config:
        raise ValueError("Existing catalog uses a different full config; choose a new output/catalog")
    catalog_path = output_root / "catalog.json"
    if catalog_path.exists():
        if not config_path.exists():
            raise ValueError("Existing catalog has no full generation spec; choose a new output/catalog")
        previous = read_json(catalog_path)
        if any(previous.get(key) != value for key, value in catalog_context.items()):
            raise ValueError("Existing catalog source/partition/hotspot differs; choose a new output/catalog")
    sealed = {}
    checksum_path = output_root / "checksums.sha256"
    if checksum_path.exists() and len(selected_ids) < len(config["profiles"]):
        for line in checksum_path.read_text().splitlines():
            value, separator, name = line.partition("  ")
            if (not separator or len(value) != 64 or
                    any(c not in "0123456789abcdef" for c in value) or name in sealed):
                raise ValueError("Invalid previous catalog checksum manifest")
            safe_child(output_root, name)
            sealed[name] = value
    results = {}
    for profile in config["profiles"]:
        # Selected profiles will be regenerated/revalidated by this invocation.
        if profile["id"] in selected_ids:
            continue
        root = output_root / "workloads" / profile["id"]
        if not all((root / name).is_file() for name in ("spec.json", "profile.json", "validation.json")):
            continue
        expected_spec = profile_spec(dataset, profile, hotspot)
        info, validation = read_json(root / "profile.json"), read_json(root / "validation.json")
        if (read_json(root / "spec.json") != expected_spec or
                info.get("spec_sha256") != digest_json(expected_spec) or
                info.get("id") != profile["id"] or
                validation.get("status") != "passed" or validation.get("profile") != profile["id"]):
            continue
        prefix = f"workloads/{profile['id']}/"
        expected_files = {name: value for name, value in sealed.items() if name.startswith(prefix)}
        if expected_files:
            actual_files = {str(path.relative_to(output_root)) for path in root.rglob("*")
                            if path.is_file() and path.name != "checksums.sha256"
                            and not path.name.endswith((".tmp", ".log"))}
            if actual_files != set(expected_files):
                raise ValueError(f"Retained profile file inventory differs from its seal: {profile['id']}")
            for name, expected in expected_files.items():
                path = safe_child(root, name[len(prefix):])
                if sha256(path) != expected:
                    raise ValueError(f"Retained profile checksum mismatch: {name}; validate or regenerate it explicitly")
        else:
            # An interrupted run may have completed this profile before sealing.
            # A passed marker alone does not establish integrity of its payloads.
            print(f"Revalidating unsealed retained profile: {profile['id']}", flush=True)
            validate_profile(dataset, root, hot, query_hot, output_root)
        results[profile["id"]] = {"id": profile["id"], "kind": profile["kind"],
                                  "path": str((root / "profile.json").relative_to(output_root)),
                                  "validation": "passed", "control": profile.get("control")}
    return results


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("command", choices=("partition", "plan", "generate", "validate"))
    parser.add_argument("--config", type=Path, required=True)
    parser.add_argument("--static-root", type=Path, required=True)
    parser.add_argument("--update-root", type=Path)
    parser.add_argument("--output", type=Path, required=True, help="Catalog root outside the Git repository")
    parser.add_argument("--partition-id", default="k128-seed42")
    parser.add_argument("--threads", type=int, default=16)
    parser.add_argument("--chunk-rows", type=int, default=250000)
    parser.add_argument("--profile", action="append", help="Select named profiles; default all")
    args = parser.parse_args()
    config = read_json(args.config)
    if config.get("schema") != "spatial-workload-spec.v1":
        raise ValueError("Unsupported spatial workload configuration schema")
    partition_root = safe_child(args.output / "partitions", args.partition_id)
    if args.command == "partition":
        prepare_partition(config, args.static_root, partition_root, args.threads, args.chunk_rows)
        return
    if args.update_root is None:
        parser.error("--update-root is required for plan/generate/validate")
    print("Checking source mappings and partition metadata", flush=True)
    dataset = Dataset(config, args.static_root, args.update_root, partition_root,
                      threads=args.threads, chunk_rows=args.chunk_rows)
    hotspot, hot, query_hot = select_hotspot(dataset)
    print(f"Fixed hotspot: {hotspot}", flush=True)
    profiles = config["profiles"]
    ids = [p["id"] for p in profiles]
    if len(ids) != len(set(ids)) or any(Path(i).name != i or i in (".", "..") for i in ids):
        raise ValueError("Profile IDs must be unique simple directory names")
    catalog_context = {"schema": "spatial-workload-catalog.v1", "dataset": config["dataset"],
                       "partition": str((partition_root / "partition.json").relative_to(args.output)),
                       "hotspot": hotspot, "source": config["source"],
                       "source_identities": dataset.source_identities}
    if "query_banks" in config:
        catalog_context["query_banks"] = {
            name: dataset.for_profile({"query_bank": name}).query_bank_info
            for name in dataset.query_bank_specs}
    if args.profile:
        if set(args.profile) - set(ids):
            raise ValueError("Unknown profile requested")
        profiles = [p for p in profiles if p["id"] in args.profile]
    selected_ids = set(ids) if args.command == "plan" else {p["id"] for p in profiles}
    results = retained_catalog_profiles(args.output, config, dataset, hotspot, catalog_context,
                                        selected_ids, hot, query_hot)
    plans = [profile_plan(dataset, p, hotspot, hot, query_hot) for p in profiles]
    retained_plans = {}
    plan_context = {"schema": "spatial-workload-plan.v1", "hotspot": hotspot,
                    "source_identities": dataset.source_identities,
                    "partition_signature": dataset.partition_info["signature"]}
    if "query_banks" in catalog_context:
        plan_context["query_banks"] = catalog_context["query_banks"]
    previous_plan_path = args.output / "plan.json"
    if previous_plan_path.exists():
        previous_plan = read_json(previous_plan_path)
        configured = {profile["id"]: profile for profile in config["profiles"]}
        matching_context = all(previous_plan.get(key) == value for key, value in plan_context.items())
        if previous_plan.get("hotspot") == hotspot:
            for plan in previous_plan.get("profiles", []):
                profile = plan.get("profile", {})
                if (profile == configured.get(profile.get("id")) and
                        (matching_context or profile.get("id") in results)):
                    retained_plans[profile["id"]] = plan
    retained_plans.update({plan["profile"]["id"]: plan for plan in plans})
    # Pin the complete configuration before work so interrupted partial runs can resume.
    write_json(args.output / "generation-spec.json", config)
    write_json(args.output / "plan.json", {**plan_context,
                                          "profiles": [retained_plans[i] for i in ids if i in retained_plans]})
    if args.command == "plan":
        print(f"Validated capacity for {len(plans)} profiles", flush=True)
        return
    for plan in plans:
        profile = plan["profile"]
        print(f"{args.command}: {profile['id']}", flush=True)
        root = args.output / "workloads" / profile["id"]
        if args.command == "generate":
            root = generate_profile(dataset, plan, hot, query_hot, args.output, args.threads)
        result = validate_profile(dataset, root, hot, query_hot, args.output)
        results[profile["id"]] = {"id": profile["id"], "kind": profile["kind"],
                                  "path": str((root / "profile.json").relative_to(args.output)),
                                  "validation": result["status"], "control": profile.get("control")}
        print(f"Validated {profile['id']}: {result['operations']['query']['unique']} distinct queries", flush=True)
    catalog = {**catalog_context, "profiles": [results[i] for i in ids if i in results],
               "limitations": ["Spatial input concentration does not guarantee graph-access conflicts.",
                               "Queries can repeat; report unique query counts and workload-weighted recall.",
                               "All profiles reuse existing shared HNSW/PQ artifacts; clustering only controls sampling."]}
    count = seal_catalog(args.output, catalog)
    print(f"Sealed {count} files in {args.output}", flush=True)


if __name__ == "__main__":
    main()