#!/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 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="= 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="= 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="= 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=" len(pool): raise ValueError("Insufficient eligible pool") pieces.append(rng.choice(pool, requested, replace=False)) selected = np.concatenate(pieces).astype("= 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") streams[name] = ids if len(streams["insert"]): refs = np.fromfile(root / "streams/insert_refs.u32", dtype="= 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="= 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()