#!/usr/bin/env python3 """Checkpoint GT of an extra query bank for the existing mixed-replace-100 trace. The trace keeps 80M vectors live for 100 rounds. Rounds 21-100 re-insert base rows 0-80M under new labels (100M+), so liveness is tracked per *vector row* (source ID) and the output maps each surviving row to its current label. The batch descriptors in the update package are replayed as written (u32_slice / u32_cyclic_slice / range encodings), so this tool never re-derives the trace. For each checkpoint the bank's static top-100 GT (source IDs over the full 100M base) is filtered through the live rows; the first 10 survivors are the exact live top-10. Queries with fewer than 10 survivors are re-computed by an exhaustive float64 scan of the live rows (``spatial_groundtruth._exact_fallback``) and counted in the manifest. ``--check-bank`` repeats the filter for the bank that already has checkpoint GT (the official queries) and requires byte equality wherever that GT exists. """ from __future__ import annotations import argparse import hashlib import json import struct import sys import time from pathlib import Path import numpy as np sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "spatial-workload-prep/scripts")) from spatial_groundtruth import _exact_fallback # noqa: E402 DT = {"float32": " np.ndarray: enc = desc["encoding"] if enc == "range": return np.arange(desc["begin"], desc["begin"] + desc["count"], dtype=np.int64) if Path(desc["path"]).name != "update_order.u32": raise ValueError(f"unexpected id source {desc['path']}") off, n = desc["offset_items"], desc["count"] if enc == "u32_slice": return np.asarray(order[off:off + n], dtype=np.int64) if enc == "u32_cyclic_slice": idx = (np.arange(off, off + n, dtype=np.int64)) % desc["wrap_at_items"] return np.asarray(order[idx], dtype=np.int64) raise ValueError(f"unknown encoding {enc}") def filtered(owner: np.ndarray, gt: np.ndarray, chunk: int = 50000): rows = gt.shape[0] out = np.empty((rows, K), dtype="= 0 counts = active.sum(axis=1) min_surv = min(min_surv, int(counts.min())) keep = active & (np.cumsum(active, axis=1) <= K) ok = counts >= K out[a:b][ok] = own[ok][keep[ok]].reshape(-1, K) missing.extend((np.flatnonzero(~ok) + a).tolist()) return out, missing, min_surv def write_gt(path: Path, ids: np.ndarray) -> str: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(".tmp") with tmp.open("wb") as handle: handle.write(struct.pack(" None: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--update-root", type=Path, required=True) ap.add_argument("--base", type=Path, required=True, help="static 100M base in source-ID order") ap.add_argument("--dtype", choices=DT, required=True) ap.add_argument("--queries", type=Path, required=True) ap.add_argument("--source-gt", type=Path, required=True, help="bank top-100 over the static base") ap.add_argument("--out-dir", type=Path, required=True) ap.add_argument("--check-gt", type=Path) ap.add_argument("--trace", default="mixed-replace-100") args = ap.parse_args() root = args.update_root trace_root = root / "traces" / args.trace trace = json.loads((trace_root / "trace.json").read_text()) order = np.fromfile(root / "update_order.u32", dtype=" live label owner[order[:initial]] = order[:initial] bank = gt_ids(args.source_gt) queries = mat(args.queries, DT[args.dtype]) base = mat(args.base, DT[args.dtype]) check = gt_ids(args.check_gt) if args.check_gt else None if base.shape[0] != n or queries.shape[0] != bank.shape[0]: raise ValueError("base/query/GT shapes disagree") label_to_row = {} # labels >= n map to re-inserted rows manifest = {"schema": "mixed-replace-extra-bank-gt.v1", "trace": args.trace, "top_k": K, "queries": args.queries.name, "source_groundtruth": args.source_gt.name, "method": "replay batch descriptors; owner[source row] = live label; filter static top-100 " "by live rows; exhaustive float64 fallback when < 10 survive", "checkpoints": []} started = time.monotonic() for i in range(0, trace["batch_count"] + 1): if i: batch = json.loads((trace_root / f"batches/batch_{i:04d}.json").read_text()) for op in batch["operations"]: labels = ids_of(op["external_ids"], root, order) if op["type"] == "delete": rows = np.array([label_to_row.get(int(x), int(x)) for x in labels]) if (labels >= n).any() else labels if (owner[rows] != labels).any(): raise ValueError(f"batch {i}: deleting labels that are not live") owner[rows] = -1 elif op["type"] == "insert": refs = ids_of(op["vector_refs"], root, order) # base_permuted rows rows = np.asarray(order[refs], dtype=np.int64) # -> source rows if (owner[rows] >= 0).any(): raise ValueError(f"batch {i}: inserting a row that is already live") owner[rows] = labels if (labels >= n).any(): label_to_row.update(zip(labels[labels >= n].tolist(), rows[labels >= n].tolist())) else: raise ValueError(op["type"]) live_count = int((owner >= 0).sum()) if live_count != batch["checkpoint"]["live_count"]: raise ValueError(f"batch {i}: live count {live_count} != {batch['checkpoint']['live_count']}") name = "initial.bin" if i == 0 else f"checkpoint_{i:04d}.bin" out, missing, min_surv = filtered(owner, bank) if missing: src = _exact_fallback(base, np.asarray(queries[missing], dtype=np.float64), owner >= 0, None, k=K, metric="l2", block_rows=1_000_000, query_batch_size=32, progress=None) out[missing] = owner[src.astype(np.int64)] sha = write_gt(args.out_dir / name, out) entry = {"checkpoint": i, "path": name, "sha256": sha, "live_count": int((owner >= 0).sum()), "fallback_queries": len(missing), "min_static_survivors": min_surv} if check is not None and i: ref_path = trace_root / f"groundtruth/checkpoint_{i:04d}.bin" if ref_path.exists(): ref, ref_missing, _ = filtered(owner, check) stored = gt_ids(ref_path) same = not ref_missing and np.array_equal(ref, stored) entry["official_recompute_equal"] = bool(same) if not same: raise ValueError(f"checkpoint {i}: replay disagrees with the existing official GT") manifest["checkpoints"].append(entry) print(f"checkpoint {i}: fallback {len(missing)}, min survivors {min_surv}, " f"{time.monotonic() - started:.0f}s", flush=True) manifest["seconds"] = round(time.monotonic() - started, 1) (args.out_dir / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") if __name__ == "__main__": main()