Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

perf(cuvs): optimize filters, rebuilds, concurrency, and memory (#3092)

Yuanqing ZHAO7e6a0515f98e
diff --git a/.github/workflows/_build.yml b/.github/workflows/_build.yml
index d80b9962a..071c95160 100644
--- a/.github/workflows/_build.yml
+++ b/.github/workflows/_build.yml
@@ -327,6 +327,8 @@ jobs:
required_filter_symbols = (
"_index_engine_set_filter_layout",
"_index_engine_evaluate_filter",
+ "_index_engine_evaluate_filter_cached",
+ "_index_engine_search_with_filter_token",
)
missing_filter_symbols = [
symbol for symbol in required_filter_symbols if not hasattr(backend, symbol)
@@ -337,7 +339,11 @@ jobs:
f"{', '.join(missing_filter_symbols)}"
)
- required_filter_methods = ("set_filter_layout", "evaluate_filter")
+ required_filter_methods = (
+ "set_filter_layout",
+ "evaluate_filter",
+ "search_with_filter_token",
+ )
missing_filter_methods = [
method for method in required_filter_methods if not hasattr(engine.IndexEngine, method)
]
diff --git a/benchmark/cuvs/PRELIMINARY_RESULTS.md b/benchmark/cuvs/PRELIMINARY_RESULTS.md
index 0373ca011..d935fa102 100644
--- a/benchmark/cuvs/PRELIMINARY_RESULTS.md
+++ b/benchmark/cuvs/PRELIMINARY_RESULTS.md
@@ -26,19 +26,28 @@ GPU. It does not mean CAGRA. CAGRA is the approximate GPU index and uses
results. Each public-dataset process times all 10,000 queries after ten
warm-up batches.
-The index-only harness uses float32 for both native and cuVS exact search. The
-collection and service sections intentionally preserve normal application
-behavior instead: native keeps its default per-vector-scale int8 index and
-cuVS keeps a float32 GPU shadow. Opting into cuVS does not rewrite the native
-index. Those later sections are therefore not equal-dtype or equal-memory
-comparisons and report native Recall@K against cuVS brute-force.
+For the measurements in this document, the index-only harness used float32 for
+both native and cuVS exact search. The collection and service runs intentionally
+preserved normal application behavior instead: native kept its default
+per-vector-scale int8 index, while cuVS was configured with `dtype=float32`.
+The current integration also supports an explicitly selected float16 device
+dataset/query; its host record shadow retains prepared Python floating-point
+values, and only the device dataset and query are cast to the configured dtype
+when each is created. Opting into cuVS does not rewrite the native index. The
+recorded collection and service results are therefore not equal-dtype or
+equal-memory comparisons and report native Recall@K against cuVS brute-force.
## GPU memory footprint
-The current cuVS shadow stores float32 vectors. The brute-force payload is
-therefore `N * dimension * 4` bytes. CAGRA also retains a uint32 neighbor graph
-of approximately `N * graph_degree * 4` bytes and may require an intermediate
-graph during build. A cached filter bitset adds approximately `N / 8` bytes.
+All cuVS measurements reported here used a float32 device dataset, so their
+brute-force payload was `N * dimension * 4` bytes. In the current integration,
+that device payload follows the configured `dtype`: float32 uses 4 bytes and
+float16 uses 2 bytes per component. The host shadow retains prepared Python
+floating-point values regardless of the device dtype; only the device dataset
+and query are cast to that dtype when each is created. CAGRA also retains a
+uint32 neighbor graph of approximately `N * graph_degree * 4` bytes and may
+require an intermediate graph during build. A cached filter bitset adds
+approximately `N / 8` bytes.
The harness records `cudaMemGetInfo` immediately before and after index build.
The following retained-build deltas are medians from five clean processes:
@@ -56,10 +65,10 @@ These are not peak-VRAM measurements. Allocator state, CAGRA build parameters,
query batch size, and concurrent GPU use can add transient memory. The deltas
also exclude the approximately 327 MiB CUDA runtime/context baseline observed
before build in these processes. The opt-in memory-aware auto mode initializes
-that runtime first, then estimates the float32 payload, CAGRA retained and
-intermediate graphs, and filter cache; multiplies the result by a 2.0 default
-safety factor; and preserves 1 GiB of free memory. Insufficient budget keeps
-the native path for that query and allows a later retry.
+that runtime first, then estimates the configured-dtype device payload, CAGRA
+retained and intermediate graphs, and filter cache; multiplies the result by a
+2.0 default safety factor; and preserves 1 GiB of free memory. Insufficient
+budget keeps the native path for that query and allows a later retry.
## Batch size 1
@@ -195,12 +204,12 @@ runs.
- Mutations: upsert 1, 100, 1,000, and 10,000 records; delete 100 records;
close and reopen the persistent collection
-This comparison deliberately uses the normal collection defaults. The native
-flat index uses its default int8 quantization, while cuVS brute-force retains
-float32 vectors. Consequently, the native path is not the float exact baseline
-from the index microbenchmark. Its Recall@10 against cuVS GPU brute-force was
-0.982 without a filter and 0.978--0.994 with filters. This is both a quality
-and memory semantic that the integration must make explicit.
+This comparison deliberately used the normal collection defaults. The native
+flat index used its default int8 quantization, while these cuVS brute-force runs
+used `dtype=float32`. Consequently, the native path was not the float exact
+baseline from the index microbenchmark. Its Recall@10 against cuVS GPU
+brute-force was 0.982 without a filter and 0.978--0.994 with filters. This is
+both a quality and memory semantic that the integration must make explicit.
### Initial uncached-filter result
@@ -294,11 +303,11 @@ work is avoided after its cuVS bitset is cached. The 1% URI case remains on GPU
because repeatedly rebuilding its native path bitmap was slower than cached
cuVS search; only the 0.1% URI case crosses the more conservative path threshold.
-These auto-mode rows can execute over either the native int8 representation or
-the cuVS float32 representation. They are latency-routing results, not an
-equal-dtype comparison; applications requiring one fixed numerical
-representation should select an explicit backend or disable the native-routing
-thresholds.
+These auto-mode rows could execute over either the native int8 representation
+or the cuVS device representation, which was configured as float32 for these
+runs. They are latency-routing results, not an equal-dtype comparison;
+applications requiring one fixed numerical representation should select an
+explicit backend or disable the native-routing thresholds.
### Dirty-index selective-first follow-up
@@ -378,9 +387,9 @@ authentication, embedding, reranking, and LLM work are still excluded.
Results aggregate five independent clean processes on H20. Values written with
`+/-` include median absolute deviation; the compact paired-latency tables show
-process medians where dispersion is omitted. The native collection continues
-to use its default int8 vector quantization, while cuVS brute-force retains
-float32 vectors.
+process medians where dispersion is omitted. In these runs, the native
+collection used its default int8 vector quantization and cuVS brute-force was
+configured with `dtype=float32`.
### Cached tenant filter
@@ -454,9 +463,10 @@ the same rebuild delay amortized across more requests released together.
imply better performance.
3. CAGRA can improve batched capacity around Recall@10=0.96, but this benefit
requires batching that the current OpenViking integration does not expose.
-4. Collection-level unfiltered lookup retains an approximately 9.0x warm-p50
- benefit at 100K x 768D, but native int8 versus cuVS float32 is not an
- equal-memory or equal-quality comparison.
+4. Collection-level unfiltered lookup retained an approximately 9.0x warm-p50
+ benefit at 100K x 768D in these runs, but native int8 versus the configured
+ cuVS float32 device representation is not an equal-memory or equal-quality
+ comparison.
5. Caching prepared filter bitsets improves repeated-filter cuVS p50 by
98--111x. Repeated 10% filters now favor cuVS, while native remains
1.9--3.0x faster at 1% and 0.1% selectivity. A new filter still pays a
diff --git a/benchmark/cuvs/README.md b/benchmark/cuvs/README.md
index 333bf4159..75117ec98 100644
--- a/benchmark/cuvs/README.md
+++ b/benchmark/cuvs/README.md
@@ -77,17 +77,39 @@ measuring cold storage reads.
- `native` is OpenViking's C++ flat index and is exact within its configured
representation.
- `cuvs_brute_force` is GPU exact search over its retained representation.
+- `cuvs_brute_force_fp16` uses the same exact algorithm after casting dataset
+ and queries to float16; report Recall@K against float32.
- `cuvs_cagra` is approximate; the result reports Recall@K against an exact
backend from the same run.
+- `cuvs_cagra_fp16` combines CAGRA approximation with float16 storage/query
+ casts and must be compared on both recall and retained VRAM.
+
+The harness rejects any FP16 or CAGRA-only run that has neither supplied
+ground truth nor an exact `native`/`cuvs_brute_force` backend. A missing recall
+value is displayed as `N/A`; it is never treated as perfect recall.
+
+Run the dtype frontier in one clean process with:
+
+```bash
+python benchmark/cuvs/run_index_benchmark.py \
+ --backends cuvs_brute_force,cuvs_brute_force_fp16,cuvs_cagra,cuvs_cagra_fp16 \
+ --vector-count 100000 \
+ --dimension 768 \
+ --query-count 1000 \
+ --k 10
+```
The index-only harness constructs the native index without an explicit
`Quant`, so both native and cuVS brute-force use float32 there. The collection
and async service harnesses deliberately retain normal application behavior:
the native CPU index uses its default per-vector-scale int8 quantization while
-the cuVS GPU shadow uses float32. Enabling cuVS does not mutate the native
-index metadata. Collection/service results are therefore application-path
-comparisons, not equal-dtype or equal-memory comparisons, and must be reported
-with Recall@K and the dtype caveat.
+the cuVS device dataset and queries use the configured dtype (float32 by
+default, or explicitly selected float16). The host record shadow retains
+prepared Python floating-point values; only the device dataset and queries are
+cast to the configured dtype when each is created. `dtype` does not rewrite the
+host shadow or the native index metadata. Collection/service results are
+therefore application-path comparisons, not equal-dtype or equal-memory
+comparisons, and must be reported with Recall@K and the dtype caveat.
The native measurement uses the current OpenViking single-query call path; it
is not a claim about the maximum throughput of a separately tuned,
@@ -249,6 +271,12 @@ python benchmark/cuvs/run_service_concurrency_benchmark.py \
--data-root /data/openviking-cuvs
```
+Add `--backends auto_cuvs_background` to isolate the optional coalescing
+background-rebuild path. The harness waits for a warm GPU snapshot before each
+mutation, then measures the immediate read burst while the dirty auto-cuVS
+index routes queries to native search. Rebuild waiting is kept outside the
+reported request wall time; the JSON records that wait separately.
+
The normal tenant scope means every public service-facade query includes an
`account_id` filter. The benchmark reports p50/p95/p99, QPS, errors, and the
post-mutation burst separately. A later end-to-end server benchmark should add
diff --git a/benchmark/cuvs/run_index_benchmark.py b/benchmark/cuvs/run_index_benchmark.py
index 0ad0623fe..d7a622787 100644
--- a/benchmark/cuvs/run_index_benchmark.py
+++ b/benchmark/cuvs/run_index_benchmark.py
@@ -39,7 +39,12 @@ from openviking.storage.vectordb.meta.index_meta import create_index_meta # noq
from openviking.storage.vectordb.store.data import DeltaRecord # noqa: E402
EXACT_BACKENDS = {"native", "cuvs_brute_force"}
-SUPPORTED_BACKENDS = (*sorted(EXACT_BACKENDS), "cuvs_cagra")
+SUPPORTED_BACKENDS = (
+ *sorted(EXACT_BACKENDS),
+ "cuvs_brute_force_fp16",
+ "cuvs_cagra",
+ "cuvs_cagra_fp16",
+)
def utc_now() -> str:
@@ -394,6 +399,7 @@ class Backend(Protocol):
class NativeFlatBackend:
name = "native"
+ dtype = "unknown"
def __init__(self, dimension: int, metric: str, ingest_batch_size: int):
self.dimension = dimension
@@ -425,6 +431,7 @@ class NativeFlatBackend:
},
)
config = index_meta.get_build_index_dict()
+ self.dtype = str(config["VectorIndex"].get("Quant", "float")).lower()
config["VectorIndex"]["ElementCount"] = 0
config["VectorIndex"]["MaxElementCount"] = int(dataset.shape[0])
self.index = LocalIndex(json.dumps(config), index_meta)
@@ -469,6 +476,7 @@ class CuVSBackend:
metric: str,
build_params: dict[str, Any],
search_params: dict[str, Any],
+ dtype: str = "float32",
):
import cupy as cp
from cuvs.neighbors import brute_force, cagra
@@ -482,6 +490,8 @@ class CuVSBackend:
self.metric = "inner_product" if metric == "cosine" else "sqeuclidean"
self.build_params = dict(build_params)
self.search_params = dict(search_params)
+ self.dtype = dtype
+ self.device_dtype = cp.float16 if dtype == "float16" else cp.float32
self.dataset = None
self.index = None
self.name = f"cuvs_{algorithm}"
@@ -490,7 +500,7 @@ class CuVSBackend:
self.search_params = dict(search_params)
def build(self, dataset: np.ndarray) -> None:
- self.dataset = self.cp.asarray(dataset, dtype=self.cp.float32)
+ self.dataset = self.cp.asarray(dataset, dtype=self.device_dtype)
if self.algorithm == "brute_force":
self.index = self.brute_force.build(self.dataset, metric=self.metric)
else:
@@ -501,7 +511,7 @@ class CuVSBackend:
def search(self, queries: np.ndarray, k: int) -> tuple[np.ndarray, np.ndarray]:
if self.index is None:
raise RuntimeError("cuVS index has not been built")
- device_queries = self.cp.asarray(queries, dtype=self.cp.float32)
+ device_queries = self.cp.asarray(queries, dtype=self.device_dtype)
if self.algorithm == "brute_force":
distances, neighbors = self.brute_force.search(self.index, device_queries, k)
else:
@@ -701,6 +711,8 @@ def make_backend(name: str, args: argparse.Namespace) -> Backend:
return NativeFlatBackend(args.dimension, args.metric, args.native_ingest_batch_size)
if name == "cuvs_brute_force":
return CuVSBackend("brute_force", args.metric, {}, {})
+ if name == "cuvs_brute_force_fp16":
+ return CuVSBackend("brute_force", args.metric, {}, {}, dtype="float16")
if name == "cuvs_cagra":
return CuVSBackend(
"cagra",
@@ -708,6 +720,14 @@ def make_backend(name: str, args: argparse.Namespace) -> Backend:
args.cagra_build_params,
args.cagra_search_params,
)
+ if name == "cuvs_cagra_fp16":
+ return CuVSBackend(
+ "cagra",
+ args.metric,
+ args.cagra_build_params,
+ args.cagra_search_params,
+ dtype="float16",
+ )
raise ValueError(f"Unsupported backend: {name}")
@@ -719,6 +739,8 @@ def print_summary(results: Sequence[dict[str, Any]]) -> None:
for result in results:
search = result["search"]
label = result["backend"]
+ recall_at_k_value = result.get("recall_at_k")
+ recall_text = f"{float(recall_at_k_value):.4f}" if recall_at_k_value is not None else "N/A"
if result.get("cagra_search_params"):
itopk_size = result["cagra_search_params"].get("itopk_size")
search_width = result["cagra_search_params"].get("search_width", "auto")
@@ -730,7 +752,7 @@ def print_summary(results: Sequence[dict[str, Any]]) -> None:
f"{search['per_query_latency_ms']['p50']:>7.3f} "
f"{search['per_query_latency_ms']['p95']:>7.3f} "
f"{search['qps']:>8.1f} "
- f"{result.get('recall_at_k', 1.0):>7.4f}"
+ f"{recall_text:>7}"
)
@@ -839,6 +861,26 @@ def validate_args(parser: argparse.ArgumentParser, args: argparse.Namespace) ->
return backends
+def validate_reference_requirement(
+ parser: argparse.ArgumentParser,
+ backends: Sequence[str],
+ *,
+ has_supplied_ground_truth: bool,
+) -> None:
+ """Require an exact reference for every lossy or approximate backend."""
+
+ reference_required_backends = [name for name in backends if name not in EXACT_BACKENDS]
+ if (
+ reference_required_backends
+ and not has_supplied_ground_truth
+ and not set(backends).intersection(EXACT_BACKENDS)
+ ):
+ parser.error(
+ f"{', '.join(reference_required_backends)} requires native/cuvs_brute_force "
+ "or a full ann-benchmarks dataset with supplied ground truth"
+ )
+
+
def main() -> None:
parser = build_parser()
args = parser.parse_args()
@@ -886,15 +928,11 @@ def main() -> None:
)
reference_neighbors = supplied_ground_truth[:, : args.k]
reference_backend = "ann-benchmarks_ground_truth"
- if (
- "cuvs_cagra" in backends
- and reference_neighbors is None
- and not set(backends).intersection(EXACT_BACKENDS)
- ):
- parser.error(
- "CAGRA requires native/cuvs_brute_force or a full ann-benchmarks dataset "
- "with supplied ground truth"
- )
+ validate_reference_requirement(
+ parser,
+ backends,
+ has_supplied_ground_truth=reference_neighbors is not None,
+ )
cagra_variants = cagra_search_variants(args)
variant_keys = [json.dumps(value, sort_keys=True) for value in cagra_variants]
@@ -960,7 +998,7 @@ def main() -> None:
rss_after = current_rss_bytes()
gpu_after = backend.gpu_memory_used_bytes()
- search_variants = cagra_variants if backend_name == "cuvs_cagra" else [None]
+ search_variants = cagra_variants if backend_name.startswith("cuvs_cagra") else [None]
for variant_index, search_params in enumerate(search_variants):
if search_params is not None:
if not isinstance(backend, CuVSBackend):
@@ -982,6 +1020,7 @@ def main() -> None:
)
result = {
"backend": backend_name,
+ "dtype": getattr(backend, "dtype", "unknown"),
"build_seconds": build_seconds,
"build_shared_across_variants": len(search_variants) > 1,
"search_variant_index": variant_index,
diff --git a/benchmark/cuvs/run_service_concurrency_benchmark.py b/benchmark/cuvs/run_service_concurrency_benchmark.py
index 947e18673..c05bc4d6b 100644
--- a/benchmark/cuvs/run_service_concurrency_benchmark.py
+++ b/benchmark/cuvs/run_service_concurrency_benchmark.py
@@ -41,7 +41,7 @@ from openviking_cli.utils.config.vectordb_config import ( # noqa: E402
VectorDBBackendConfig,
)
-SUPPORTED_BACKENDS = ("native", "cuvs_brute_force")
+SUPPORTED_BACKENDS = ("native", "cuvs_brute_force", "auto_cuvs_background")
ACCOUNT_ID = "benchmark"
@@ -76,6 +76,7 @@ def make_config(
collection_name: str,
dimension: int,
filter_cache_size: int,
+ auto_rebuild_debounce_ms: int,
) -> VectorDBBackendConfig:
common = {
"name": collection_name,
@@ -97,9 +98,34 @@ def make_config(
),
**common,
)
+ if backend == "auto_cuvs_background":
+ return VectorDBBackendConfig(
+ backend="local",
+ cuvs=CuVSConfig(
+ algorithm="brute_force",
+ auto_enable=True,
+ auto_background_rebuild=True,
+ auto_rebuild_debounce_ms=auto_rebuild_debounce_ms,
+ filter_cache_size=filter_cache_size,
+ ),
+ **common,
+ )
raise ValueError(f"Unsupported backend: {backend}")
+async def wait_for_background_rebuild(manager: VikingVectorIndexBackend, timeout: float) -> float:
+ index = manager._shared_adapter.get_collection().get_index("default")
+ wait = getattr(index, "wait_for_background_rebuild", None)
+ if wait is None:
+ raise RuntimeError("auto background benchmark could not access the local index worker")
+ started = time.perf_counter()
+ completed = await asyncio.to_thread(wait, timeout)
+ elapsed = time.perf_counter() - started
+ if not completed:
+ raise RuntimeError(f"auto background rebuild did not complete within {timeout}s")
+ return elapsed
+
+
def concurrent_summary(
latencies_ms: Sequence[float],
*,
@@ -312,9 +338,16 @@ async def run_post_mutation_scenario(
*,
concurrency_levels: Sequence[int],
k: int,
+ wait_for_background: bool,
+ background_timeout: float,
) -> dict[str, Any]:
results = []
for matrix_index, concurrency in enumerate(concurrency_levels):
+ background_wait_seconds = 0.0
+ if wait_for_background:
+ background_wait_seconds = await wait_for_background_rebuild(
+ manager, background_timeout
+ )
row_index = matrix_index % dataset.shape[0]
record = make_record(row_index, queries[matrix_index % len(queries)].tolist())
write_started = time.perf_counter()
@@ -333,6 +366,7 @@ async def run_post_mutation_scenario(
)
result["concurrency"] = concurrency
result["write_ms"] = write_ms
+ result["pre_write_background_wait_seconds"] = background_wait_seconds
results.append(result)
return {
"name": "post_mutation_burst",
@@ -349,6 +383,8 @@ async def run_backend(
run_root: Path,
ingest_batch_size: int,
filter_cache_size: int,
+ auto_rebuild_debounce_ms: int,
+ background_timeout: float,
concurrency_levels: Sequence[int],
cached_request_count: int,
unique_request_count: int,
@@ -361,6 +397,7 @@ async def run_backend(
collection_name=collection_name,
dimension=dataset.shape[1],
filter_cache_size=filter_cache_size,
+ auto_rebuild_debounce_ms=auto_rebuild_debounce_ms,
)
manager = VikingVectorIndexBackend(config)
ctx = RequestContext(user=UserIdentifier(ACCOUNT_ID, "user"), role=Role.USER)
@@ -378,6 +415,13 @@ async def run_backend(
f"Collection count mismatch for {backend}: {record_count} != {dataset.shape[0]}"
)
+ initial_background_wait_seconds = 0.0
+ background_enabled = backend == "auto_cuvs_background"
+ if background_enabled:
+ initial_background_wait_seconds = await wait_for_background_rebuild(
+ manager, background_timeout
+ )
+
scenarios = [
await run_cached_scenario(
manager,
@@ -415,12 +459,15 @@ async def run_backend(
queries,
concurrency_levels=concurrency_levels,
k=k,
+ wait_for_background=background_enabled,
+ background_timeout=background_timeout,
),
]
return {
"backend": backend,
"ingest": ingest,
"record_count": record_count,
+ "initial_background_wait_seconds": initial_background_wait_seconds,
"scenarios": scenarios,
}
finally:
@@ -457,6 +504,8 @@ def build_parser() -> argparse.ArgumentParser:
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--ingest-batch-size", type=int, default=256)
parser.add_argument("--filter-cache-size", type=int, default=16)
+ parser.add_argument("--auto-rebuild-debounce-ms", type=int, default=500)
+ parser.add_argument("--background-timeout", type=float, default=120.0)
parser.add_argument(
"--concurrency",
type=lambda value: parse_positive_int_list(value, "--concurrency"),
@@ -486,6 +535,10 @@ def validate_args(parser: argparse.ArgumentParser, args: argparse.Namespace) ->
parser.error("--k cannot exceed --vector-count")
if args.filter_cache_size < 0:
parser.error("--filter-cache-size cannot be negative")
+ if args.auto_rebuild_debounce_ms < 0:
+ parser.error("--auto-rebuild-debounce-ms cannot be negative")
+ if args.background_timeout <= 0:
+ parser.error("--background-timeout must be positive")
backends = [item.strip() for item in args.backends.split(",") if item.strip()]
if not backends:
parser.error("--backends cannot be empty")
@@ -525,6 +578,8 @@ async def async_main(args: argparse.Namespace, backends: Sequence[str]) -> dict[
run_root=run_root,
ingest_batch_size=args.ingest_batch_size,
filter_cache_size=args.filter_cache_size,
+ auto_rebuild_debounce_ms=args.auto_rebuild_debounce_ms,
+ background_timeout=args.background_timeout,
concurrency_levels=args.concurrency,
cached_request_count=args.cached_request_count,
unique_request_count=args.unique_request_count,
@@ -548,6 +603,8 @@ async def async_main(args: argparse.Namespace, backends: Sequence[str]) -> dict[
"k": args.k,
"ingest_batch_size": args.ingest_batch_size,
"filter_cache_size": args.filter_cache_size,
+ "auto_rebuild_debounce_ms": args.auto_rebuild_debounce_ms,
+ "background_timeout": args.background_timeout,
"concurrency": args.concurrency,
"cached_request_count": args.cached_request_count,
"unique_request_count": args.unique_request_count,
diff --git a/benchmark/cuvs/summarize_index_runs.py b/benchmark/cuvs/summarize_index_runs.py
index e8cc280c9..7d5499bcc 100644
--- a/benchmark/cuvs/summarize_index_runs.py
+++ b/benchmark/cuvs/summarize_index_runs.py
@@ -38,7 +38,13 @@ METRIC_PATHS = {
"gpu_used_delta_bytes": ("gpu_used_delta_bytes",),
}
-BACKEND_ORDER = {"native": 0, "cuvs_brute_force": 1, "cuvs_cagra": 2}
+BACKEND_ORDER = {
+ "native": 0,
+ "cuvs_brute_force": 1,
+ "cuvs_brute_force_fp16": 2,
+ "cuvs_cagra": 3,
+ "cuvs_cagra_fp16": 4,
+}
def canonical(value: Any) -> str:
diff --git a/docker/cuvs-dev/Dockerfile b/docker/cuvs-dev/Dockerfile
index 533901f68..bd43b658c 100644
--- a/docker/cuvs-dev/Dockerfile
+++ b/docker/cuvs-dev/Dockerfile
@@ -24,6 +24,7 @@ RUN --mount=type=cache,target=/root/.cache/pip \
"${CUPY_PACKAGE}" \
"apscheduler>=3.11,<4" \
"h5py>=3.12,<4" \
+ "httpx>=0.25,<1" \
"pydantic>=2,<3" \
"pytest>=8,<9" \
"pytest-asyncio>=0.24,<2" \
diff --git a/docker/cuvs-dev/README.md b/docker/cuvs-dev/README.md
index 9c61a61ac..51b1e4d2d 100644
--- a/docker/cuvs-dev/README.md
+++ b/docker/cuvs-dev/README.md
@@ -2,9 +2,9 @@
This lightweight image contains cuVS, CuPy, the OpenViking local VectorDB
native engine, and the minimal Python dependencies needed by the cuVS smoke
-and integration tests. It deliberately excludes the server, bot, Web UI, and
-unrelated ingestion dependencies. It does not encode any cluster-specific
-configuration.
+and vector benchmark harnesses. It deliberately excludes the full server,
+bot, Web UI, and unrelated ingestion dependencies. It does not encode any
+cluster-specific configuration.
Build it from the repository root:
@@ -41,6 +41,9 @@ docker run --rm --gpus all openviking-cuvs:dev \
python /opt/openviking-cuvs/cuvs_smoke.py --algorithm cagra
```
+Append `--dtype float16` to either smoke command to exercise the opt-in
+lower-precision dataset and query path.
+
For Python-only iteration, mount a worktree and point
`OPENVIKING_SOURCE_DIR` at it. The entrypoint copies the prebuilt native
engine into the mounted tree before running the command:
diff --git a/docs/design/openviking-cuvs-benchmark-plan.md b/docs/design/openviking-cuvs-benchmark-plan.md
index 5f125f447..09d0c0029 100644
--- a/docs/design/openviking-cuvs-benchmark-plan.md
+++ b/docs/design/openviking-cuvs-benchmark-plan.md
@@ -25,7 +25,7 @@ cuVS 官方建议从 build time、search quality 和 search performance 三个
| 名称 | OpenViking 配置 | 作用 |
| --- | --- | --- |
| Native exact | `backend=local`, `IndexType=flat` | CPU flat 基线;精确性相对于其实际存储表示定义 |
-| cuVS exact | `backend=cuvs`, `algorithm=brute_force` | GPU 在其 float32 表示上的精确检索 |
+| cuVS exact | `backend=cuvs`, `algorithm=brute_force` | GPU 在配置的 device dtype(默认 float32,可显式选择 float16)表示上的精确检索 |
| cuVS ANN | `backend=cuvs`, `algorithm=cagra` | 在固定 Recall@K 下比较 ANN 性能 |
可以使用 `cuvs-bench` 的 HNSWlib 或其他算法作为算法级参考,但不能把它们当作
@@ -34,17 +34,22 @@ OpenViking 端到端基线,因为它们没有经过相同的过滤、label map
### Dtype 与非侵入性原则
cuVS 是 opt-in dense-search sidecar,不修改默认 backend,也不改变 native CPU
-索引的默认 `int8` 量化。当前 cuVS GPU shadow 使用 `float32`。因此:
-
-- L1 index-only harness 显式形成 float32 CPU / float32 GPU 对比,用于隔离 kernel;
-- L2/L3 保留真实应用默认,即 native int8 / cuVS float32,并同时报告 Recall@K;
+索引的默认 `int8` 量化。cuVS host shadow 保存预处理后的 Python 浮点值;仅在创建
+device dataset 和 query 时将它们 cast 为配置的 `dtype`,默认是 float32,也可以
+显式选择 float16。因此:
+
+- L1 index-only harness 在隔离 kernel 时显式锁定 float32 CPU / float32 GPU;评估低精度
+ frontier 时另跑配置为 float16 的 cuVS,并相对于 exact reference 报告 Recall@K;
+- L2/L3 保留真实应用行为,即 native int8 / cuVS 配置的 device dtype,并同时报告实际
+ dtype、Recall@K 和内存占用;
- L2/L3 不能表述为等 dtype、等内存或完全相同数值语义的比较;
- native fallback 始终继续使用原有 int8 CPU index,启用 cuVS 不触发迁移或重写。
-低精度 GPU 路线分开评估:先增加 cuVS float16 dataset/query,与 float32 ground
-truth 比较 Recall@K、延迟和显存;随后再评估 CAGRA int8 或 VPQ。native 的逐向量
-scale int8 不能直接映射到 cuVS brute-force,若要求数值兼容,需要自定义 int8
-distance/top-k 或候选召回后按 scale rerank,不能用简单 cast 代替。
+低精度 GPU 路线作为显式配置分开评估:使用 `dtype=float16` 将 cuVS dataset/query
+cast 为 float16,并与 float32 exact ground truth 比较 Recall@K、延迟和显存;随后再
+评估 CAGRA int8 或 VPQ。native 的逐向量 scale int8 不能直接映射到 cuVS
+brute-force,若要求数值兼容,需要自定义 int8 distance/top-k 或候选召回后按 scale
+rerank,不能用简单 cast 代替。
## 与 agent-memory benchmark 的关系
diff --git a/docs/design/openviking-cuvs-integration-plan.md b/docs/design/openviking-cuvs-integration-plan.md
index d82c673d3..50c6c1a44 100644
--- a/docs/design/openviking-cuvs-integration-plan.md
+++ b/docs/design/openviking-cuvs-integration-plan.md
@@ -49,7 +49,7 @@
| 过滤 | native bitmap 投影为 cuVS row bitset | 复用既有 DSL 和 scalar/path index,不重复实现语义 |
| 持久化 | 不持久化 cuVS index | 避免绑定 GPU、CUDA/cuVS 版本和序列化兼容性 |
| 默认 CPU dtype | 保持现有 per-vector-scale int8 | cuVS opt-in 不能改变未启用用户的行为 |
-| GPU dtype | 当前使用 float32 shadow | 先建立正确性和性能基线;低精度作为独立能力评估 |
+| GPU dtype | device dataset/query 默认 float32,可显式配置 float16 | host shadow 保存预处理后的 Python 浮点值;仅 device dataset/query 在创建时 cast 为配置 dtype;低精度按独立能力报告 Recall@K 和显存 |
## 4. 总体架构
@@ -119,7 +119,7 @@ sequenceDiagram
Note over G: 下一次 GPU 查询同步重建 index
```
-`LocalIndex` 使用跨后端重入锁覆盖 native mutation 和 cuVS shadow mutation,避免查询获得新 native bitmap 却使用旧 GPU row layout。当前 mutation 后不增量修改 CAGRA,而是标脏并在下一次 dense 查询全量重建。
+`LocalIndex` 使用跨后端读写锁覆盖 native mutation 和 cuVS shadow mutation,避免查询获得新 native bitmap 却使用旧 GPU row layout。warmed query 持有共享读锁并发搜索,mutation 和同步 rebuild 持有写锁。当前 mutation 后不增量修改 CAGRA,而是标脏并在下一次 dense 查询全量重建。
### 5.2 Dense query
@@ -129,17 +129,20 @@ flowchart TD
Pure -->|否| N[Native search]
Pure -->|是| Ready{cuVS 已配置且可用?}
Ready -->|否| N
- Ready -->|是| Dirty{GPU index dirty?}
+ Ready -->|是| Preflight{auto filtered query?}
+ Preflight -->|是| Bitmap[native bitmap + eligible count<br/>共享读并行 preflight]
+ Bitmap --> Route{候选数低于<br/>native 阈值?}
+ Route -->|是| N
+ Route -->|否| Dirty{GPU index dirty?}
+ Preflight -->|否| Dirty
Dirty -->|是| Admit{auto 显存预算允许?}
Admit -->|否| N
Admit -->|是| Build[批量构建 GPU index<br/>注册 label layout]
Dirty -->|否| Filter
Build --> Filter{存在 filter?}
Filter -->|否| GPU[cuVS top-k]
- Filter -->|是| Bitmap[native scalar/path bitmap<br/>投影为 cuVS row bitset]
- Bitmap --> Route{auto 模式且候选数<br/>低于 native 阈值?}
- Route -->|是| N
- Route -->|否| GPU
+ Filter -->|是| DeviceBitmap[native bitmap<br/>投影为 cuVS row bitset]
+ DeviceBitmap --> GPU
GPU --> Map[row id → label → record]
```
@@ -153,8 +156,13 @@ flowchart TD
2. native engine 将每个 cuVS row 预映射到 native logical offset;
3. 查询时 native filter parser 与 scalar/path index 计算原生 bitmap;
4. `evaluate_filter(dsl)` 按已注册 layout 投影,返回 packed `uint32` words 和 eligible count;
-5. cuVS 将 words 复制到 device,并通过 `filters.from_bitset()` 构造 prefilter;
-6. 相同 filter 复用 device bitset;mutation 同时使 layout 和 cache 失效。
+5. 宽过滤把 preflight words 直接交给 cuVS,通过 `filters.from_bitset()` 构造 prefilter,不重复计算 native bitmap;
+6. 窄过滤由 native engine 返回一个有界、短生命周期的 bitmap token,CPU recall 直接复用;token miss 时安全回退到普通 search;
+7. 相同 filter 复用 device bitset;mutation 同时使 layout、device cache 和 native token 失效。
+
+auto 模式会在进入 cuVS search 前完成候选数 preflight。native engine 对
+`evaluate_filter` 使用共享读锁,因此不同的首次过滤条件可以并行计算;layout 注册和
+mutation 使用写锁。cuVS shadow 的 generation 校验会丢弃跨 mutation 得到的旧路由结果。
该 bridge 继承 native 对以下能力的处理:
@@ -207,14 +215,17 @@ auto 模式包含两层决策:
URI/path 使用更低阈值,是因为宽路径需要 native Trie traversal 和 subtree bitmap union;这个成本会先于 GPU search 发生。阈值设为 `0` 可关闭对应 native 路由。阈值是当前测量得到的默认值,不是跨硬件、维度和 workload 的常数。
-native fallback 在跨后端 GPU 锁外执行,以保留 native engine 原有的共享读并发。
+候选数 preflight 和 native fallback 使用跨后端共享读锁,既保留 native engine
+原有的读并发,也避免与 mutation 交错;相同 filter 的路由决策由 LRU 直接复用。
## 7. Dtype 与数值语义
### 7.1 当前边界
- native collection 默认保持 per-vector-scale int8;
-- cuVS host/device shadow 当前为 float32;
+- cuVS host shadow 保存预处理后的 Python 浮点值,不随 `dtype` 改写;
+- 仅 cuVS device dataset/query 在创建时 cast 为配置的 `dtype`,默认是 float32,
+ 可显式配置为 float16;
- 启用 cuVS 不迁移、不重写 native index metadata;
- native fallback 始终使用原有 CPU representation;
- auto 模式可能按 query 在两种 representation 间路由。
@@ -222,7 +233,7 @@ native fallback 在跨后端 GPU 锁外执行,以保留 native engine 原有
因此:
- index-only exact benchmark 可显式使用 FP32 CPU / FP32 GPU 隔离 kernel;
-- collection/service benchmark 必须说明是 native int8 / cuVS float32;
+- collection/service benchmark 必须说明是 native int8 / cuVS 配置的 float32 或 float16;
- 结果必须同时报告 Recall@K、显存和 host memory,不能声称 equal-dtype 或 equal-memory;
- 要求固定 numerical representation 的应用应选择显式 backend,或关闭 native 候选路由。
@@ -239,7 +250,8 @@ native fallback 在跨后端 GPU 锁外执行,以保留 native engine 原有
当前保守估算包含:
-- float32 vector payload:`N * dimension * 4`;
+- device vector payload 跟随配置的 dtype:float32 为 `N * dimension * 4`,
+ float16 为 `N * dimension * 2`;
- CAGRA retained graph:约 `N * graph_degree * 4`;
- CAGRA build intermediate graph:约 `N * intermediate_graph_degree * 4`;
- device filter cache:每个 bitset 约 `N / 8`;
@@ -260,6 +272,8 @@ native fallback 在跨后端 GPU 锁外执行,以保留 native engine 原有
"distance_metric": "cosine",
"cuvs": {
"algorithm": "brute_force",
+ "dtype": "float32",
+ "max_concurrent_gpu_searches": 1,
"fallback_to_native": true
}
}
@@ -306,7 +320,9 @@ native fallback 在跨后端 GPU 锁外执行,以保留 native engine 原有
"auto_memory_safety_factor": 2.0,
"auto_filter_native_threshold": 2000,
"auto_path_filter_native_threshold": 200,
- "filter_cache_size": 16
+ "filter_cache_size": 16,
+ "auto_background_rebuild": true,
+ "auto_rebuild_debounce_ms": 500
}
}
}
@@ -318,6 +334,8 @@ native fallback 在跨后端 GPU 锁外执行,以保留 native engine 原有
| 配置 | 默认值 | 说明 |
| --- | --- | --- |
| `algorithm` | `brute_force` | `brute_force` exact 或 `cagra` ANN |
+| `dtype` | `float32` | GPU dataset/query dtype;可显式设为 `float16`,不改变 native CPU dtype |
+| `max_concurrent_gpu_searches` | `1` | 单 index 同时进入 GPU search 的上限;host preflight/filter 仍可并行 |
| `build_params` | `{}` | 传给 CAGRA `IndexParams` |
| `search_params` | `{}` | 传给 CAGRA `SearchParams` |
| `fallback_to_native` | `true` | sparse/hybrid 等非 cuVS dense top-k 能力使用 native |
@@ -327,6 +345,8 @@ native fallback 在跨后端 GPU 锁外执行,以保留 native engine 原有
| `auto_filter_native_threshold` | `2000` | auto 普通过滤 native 路由阈值 |
| `auto_path_filter_native_threshold` | `200` | auto URI/path native 路由阈值 |
| `filter_cache_size` | `16` | device bitset 或 native 路由决策的 LRU 大小 |
+| `auto_background_rebuild` | `false` | auto 模式合并 mutation 并在后台构建新 snapshot;dirty 期间查询走 native |
+| `auto_rebuild_debounce_ms` | `500` | 后台 rebuild 前用于合并连续 mutation 的静默窗口 |
依赖安装方式和 CUDA 12/13 wheel 选择见中英文用户指南,不在本计划中复制易过期的版本命令。
@@ -335,8 +355,12 @@ native fallback 在跨后端 GPU 锁外执行,以保留 native engine 原有
### 10.1 当前保证
- 顺序 upsert/delete 返回后,下一次 GPU dense query 会先重建,提供 read-after-write;
-- native mutation、cuVS shadow mutation、layout 注册和 GPU search 由跨后端锁协调;
-- GPU search 在单个 index 内当前串行化;
+- native mutation 与 cuVS shadow mutation 由跨后端读写锁协调;filter layout 和 bitmap
+ preflight 由 native engine 读写锁及 cuVS generation 校验保证一致性;
+- GPU index、dataset ownership、label mapping 和 generation 组成 immutable snapshot;
+- warmed GPU search 使用不同的 cuVS resources/CUDA stream 并发执行,只短暂串行访问 host cache;
+- mutation 不会破坏已被查询持有的 snapshot;同步 rebuild 仍由写锁合并为一次;
+- 同一 GPU 上不同 collection 的 admission/build 由进程级 coordinator 串行,避免并发超卖显存;
- native fallback 不持有 GPU 锁,可以继续并发读取;
- Store 是最终事实来源,重启后派生状态会重新收敛。
@@ -362,11 +386,11 @@ native fallback 在跨后端 GPU 锁外执行,以保留 native engine 原有
| --- | --- | --- |
| 每次 mutation 后整体重建 | 写后首查和 build 为 O(N) | base + delta、阈值重建、后台 build、原子切换 |
| host shadow 保存完整 dense vectors | Store/native/GPU 之外增加 host memory | 连续 buffer、共享内存、减少 Python object |
-| 单 index GPU lock | 并发请求转化为排队延迟 | immutable GPU snapshot、CUDA streams、micro-batching |
+| 高并发小 query | 单 query 无法充分占用 GPU | 动态 batching 或显式 query batching |
| Python/CuPy 数据面 | 对象构造、复制和同步有固定开销 | 先 profiling,再决定是否下沉 C++ cuVS C API |
| 重启后 lazy rebuild | 大 collection 的首次查询延迟高 | 后台预热、版本化派生 cache |
| native dense 与 GPU shadow 并存 | CPU 内存和写放大 | 覆盖率和回退策略稳定后再评估裁剪 |
-| CPU int8 / GPU float32 | 数值和内存语义不同 | 明确报告 dtype、Recall@K 和两侧 memory |
+| CPU int8 / GPU float32 或 float16 | 数值和内存语义不同 | 明确报告 dtype、Recall@K 和两侧 memory |
| auto admission 是估算 | 实际 peak 随 allocator 和 workload 波动 | telemetry、校准 safety factor、OOM fallback |
| 路由阈值来自当前 workload | 不能直接泛化 | 按规模、维度、filter type 做自适应或离线调参 |
@@ -397,16 +421,16 @@ native fallback 在跨后端 GPU 锁外执行,以保留 native engine 原有
优先级顺序:
-1. 将可搜索 GPU index 变成 immutable snapshot;
-2. build 新 snapshot 时继续服务旧 snapshot;
-3. 完成后原子交换,并延迟回收旧资源;
-4. 合并连续 mutation,避免每次写后重复重建;
-5. 评估 CUDA streams、persistent query buffers 和 micro-batching;
-6. 补充 build queue、fallback reason、eligible count、VRAM 和 latency telemetry。
+1. 已将可搜索 GPU index 变成 immutable snapshot;
+2. 已保证 in-flight query 在 rebuild 期间安全持有旧 snapshot;后台 build 期间的新请求路由仍待实现;
+3. 已实现完成后原子交换,并延迟到最后一个持有者退出再回收旧资源;
+4. 已实现可选的连续 mutation 合并与后台 rebuild;默认关闭以保留现有 auto 行为;
+5. 已实现每线程 cuVS resources/CUDA stream;persistent query buffers 和 micro-batching 待评估;
+6. 已补充 build queue、fallback reason、eligible count 和分阶段 latency telemetry;VRAM 指标待统一管理器。
### Phase 3:容量与低精度
-- float16 brute-force 的 recall/latency/VRAM;
+- 已实现显式 float16 brute-force/CAGRA 路径;recall/latency/VRAM 矩阵待补齐;
- CAGRA int8 或 VPQ frontier;
- 大 collection 的 host shadow 内存优化;
- 根据 benchmark 决定 CAGRA 启用规模和参数策略。
@@ -451,6 +475,7 @@ native fallback 在跨后端 GPU 锁外执行,以保留 native engine 原有
- 目标 VectorDB 单元/集成测试通过;
- stable-ABI loader 测试通过;
- standalone C++ engine bitmap projection 测试通过;
+- native bitmap token 复用、mutation 失效及旧 ABI fallback 测试通过;
- brute-force/CAGRA GPU smoke 覆盖组合过滤、update、delete 和 rebuild;
- Python lint、C++ syntax 和 diff check 通过;
- 提交前扫描 staged/committed diff,不允许包含凭据、私钥或非公开环境标识。
diff --git a/docs/en/guides/07-operation-telemetry.md b/docs/en/guides/07-operation-telemetry.md
index 3180fa482..f71ecfb15 100644
--- a/docs/en/guides/07-operation-telemetry.md
+++ b/docs/en/guides/07-operation-telemetry.md
@@ -176,6 +176,33 @@ Only fields that are actually produced by an operation are returned. Missing gro
| `summary.vector.scanned` | Number of vectors scanned by the backend |
| `summary.vector.scan_reason` | Text description of the scan strategy or reason |
+When cuVS is configured, `summary.vector.cuvs` aggregates routing and timing
+information across every dense search in the operation. The aggregation is
+independent of concurrent-query completion order. It never includes the query
+vector, filter values, or URI contents, and unknown dimension values are
+coalesced into the bounded `other` bucket.
+
+| Field | Meaning |
+| --- | --- |
+| `summary.vector.cuvs.searches` | Number of dense searches represented by this aggregate |
+| `summary.vector.cuvs.algorithms.<algorithm>` | Search count by cuVS algorithm, such as `brute_force` or `cagra` |
+| `summary.vector.cuvs.dtypes.<dtype>` | Search count by GPU dataset/query dtype, `float32` or `float16` |
+| `summary.vector.cuvs.max_concurrent_gpu_searches` | Maximum configured per-index in-flight GPU search limit observed |
+| `summary.vector.cuvs.auto_mode_searches` | Number of searches with automatic CPU/GPU routing enabled |
+| `summary.vector.cuvs.routes.<reason>` | Search count by route, such as `cuvs`, `native_filter_threshold`, `native_rebuild_pending`, or `native_memory_budget` |
+| `summary.vector.cuvs.filter_kinds.<kind>` | Search count by low-cardinality filter class: `none`, `scalar`, or `path` |
+| `summary.vector.cuvs.filter_cache_hits` | Number of searches that reused a prepared or preflight filter |
+| `summary.vector.cuvs.native_filter_reuses` | Number of native recalls that reused the preflight bitmap |
+| `summary.vector.cuvs.builds` | Number of searches that performed a GPU index build |
+| `summary.vector.cuvs.eligible_count_max` | Maximum candidate count observed after native filtering |
+| `summary.vector.cuvs.records_generation_max` | Maximum record generation observed |
+| `summary.vector.cuvs.index_size_max` | Maximum cuVS host-snapshot size observed |
+| `summary.vector.cuvs.memory.estimated_peak_bytes_max` | Maximum estimated peak bytes used for auto-build admission |
+| `summary.vector.cuvs.memory.free_bytes_min` | Minimum free device bytes observed inside the per-GPU admission coordinator |
+| `summary.vector.cuvs.memory.usable_bytes_min` | Minimum free bytes observed after applying the configured reserve |
+| `summary.vector.cuvs.timings_ms.<stage>.sum` | Sum across searches for `total`, `preflight`, `queue`, `build`, `filter_prepare`, `gpu_search`, or `native_search` |
+| `summary.vector.cuvs.timings_ms.<stage>.max` | Maximum single-search time for the same stage |
+
### `summary.resource`
This group appears on resource ingestion operations such as `resources.add_resource`.
diff --git a/docs/en/guides/16-cuvs.md b/docs/en/guides/16-cuvs.md
index 5fbca6ace..984cd8ed1 100644
--- a/docs/en/guides/16-cuvs.md
+++ b/docs/en/guides/16-cuvs.md
@@ -25,6 +25,8 @@ Start with exact brute-force search:
"distance_metric": "cosine",
"cuvs": {
"algorithm": "brute_force",
+ "dtype": "float32",
+ "max_concurrent_gpu_searches": 1,
"fallback_to_native": true,
"filter_cache_size": 16
}
@@ -51,7 +53,9 @@ idle GPU memory without changing the default behavior for other installations:
"auto_memory_reserve_mb": 1024,
"auto_memory_safety_factor": 2.0,
"auto_filter_native_threshold": 2000,
- "auto_path_filter_native_threshold": 200
+ "auto_path_filter_native_threshold": 200,
+ "auto_background_rebuild": true,
+ "auto_rebuild_debounce_ms": 500
}
}
}
@@ -59,14 +63,19 @@ idle GPU memory without changing the default behavior for other installations:
```
Before each lazy build or rebuild, auto mode reads free device memory and
-estimates the float32 vector payload, CAGRA graph and intermediate graph when
-applicable, and the configured filter-bitset cache. It multiplies those known
-allocations by `auto_memory_safety_factor` and then preserves
-`auto_memory_reserve_mb`. If the estimate does not fit, or cuVS/GPU discovery
+estimates the device vector payload for the configured `dtype`, the CAGRA graph
+and intermediate graph when applicable, and the configured filter-bitset
+cache. It multiplies those known allocations by
+`auto_memory_safety_factor` and then preserves `auto_memory_reserve_mb`. If the
+estimate does not fit, or cuVS/GPU discovery
is unavailable, that query uses the unchanged native index. The cuVS index
remains dirty so a later query can retry after GPU memory becomes available.
An allocation failure after admission also falls back to native. Explicit
`backend: "cuvs"` retains fail-fast behavior and does not use this gate.
+Build and admission are coordinated per GPU across local collections, so two
+concurrent builds cannot both pass the same stale free-memory observation.
+Builds on different devices remain independent; warmed searches are not
+serialized by this coordinator.
Auto mode also uses the eligible count returned by the native scalar index for
latency-aware filtered-query routing. Filters with at most
`auto_filter_native_threshold` candidates use native vector recall; path
@@ -76,10 +85,21 @@ bitmap construction can dominate wider subtrees. The defaults are 2,000 and
that route. These crossover values are hardware- and workload-dependent.
Explicit `backend: "cuvs"` continues to use cuVS for supported dense queries.
+`auto_background_rebuild` is disabled by default. When enabled, consecutive
+mutations are coalesced for `auto_rebuild_debounce_ms`, and a worker builds the
+new immutable GPU snapshot without holding the cross-backend mutation lock.
+The 500 ms default avoids rebuilding most intermediate batches during normal
+ingestion; use a larger value for bulk loads with longer gaps between batches.
+Queries use the current native index while the snapshot is dirty, so GPU build
+time does not become request queue time. The worker installs the new label
+layout and GPU snapshot atomically only if its record generation is still
+current; otherwise it discards that build and rebuilds the newest generation.
+
## GPU memory footprint
-The current GPU shadow is float32, so brute-force's dominant retained payload
-is `N * dimension * 4` bytes. CAGRA additionally retains approximately
+With the default `dtype: "float32"`, brute-force's dominant retained device
+payload is `N * dimension * 4` bytes. Opt-in `dtype: "float16"` reduces that
+device payload to `N * dimension * 2` bytes. CAGRA additionally retains approximately
`N * graph_degree * 4` bytes for the graph and can require an intermediate
`N * intermediate_graph_degree * 4` bytes while building. Each cached filter
bitset costs approximately `ceil(N / 32) * 4` bytes.
@@ -109,35 +129,54 @@ rather than admitting from the vector payload alone.
Enabling cuVS does not change OpenViking's default backend or rewrite the
native CPU index. The normal collection metadata remains
`VectorIndex.Quant=int8`, so native fallback searches keep the existing
-per-vector-scale int8 quantization. In parallel, the current cuVS runtime keeps
-its GPU shadow in float32 because the cuVS Python brute-force API accepts
-float32/float16 rather than OpenViking's scaled int8 record format.
+per-vector-scale int8 quantization. In parallel, the cuVS device dataset and
+queries use the configured `dtype`: float32 by default, or float16 when
+explicitly selected. The host record shadow retains prepared Python
+floating-point values; only the device dataset and queries are cast to the
+configured dtype when each is created. The cuVS Python brute-force API accepts
+those two device representations rather than OpenViking's scaled int8 record
+format.
The two dense paths therefore do not have equal memory or numerical semantics:
native results are exact within the quantized CPU representation, while cuVS
-brute-force is exact over the retained float32 vectors. Small score or neighbor
-ordering differences are expected. Benchmarks must report the two data types
-and include Recall@K instead of presenting the comparison as equal-dtype or
-equal-memory. This separation is intentional for the initial opt-in
+brute-force is exact over its retained float32 or float16 device
+representation. Small score or neighbor ordering differences are expected.
+Benchmarks must report the two data types and include Recall@K instead of
+presenting the comparison as equal-dtype or equal-memory. This separation is
+intentional for the initial opt-in
integration and leaves existing CPU behavior unchanged. In auto mode, the
filter candidate thresholds can select either representation per query, so
applications that require one fixed numerical representation should use an
explicit backend or disable the native-routing thresholds.
-Lower-precision GPU storage is a follow-up rather than an implicit cast. The
-first candidate is configurable float16 for both the cuVS dataset and queries,
-with Recall@K measured against float32. Native-compatible int8 requires a
-separate design because OpenViking uses a per-vector scale, while cuVS
-brute-force does not accept that scaled-int8 representation. CAGRA int8 or PQ
-compression must likewise be evaluated as approximate modes with an explicit
-recall/latency/memory frontier.
-
-The integration rebuilds the GPU index lazily after an upsert or delete. On
-each rebuild it registers the cuVS label order with the native engine once.
+Lower-precision GPU storage is explicit rather than an implicit cast. Setting
+`dtype: "float16"` casts both the cuVS dataset and every query to float16 for
+brute-force or CAGRA; mixed query/index dtypes are not used. This is a storage
+cast, not per-vector quantization, and must be reported with Recall@K against
+the default float32 path. Native-compatible int8 still requires a separate
+design because OpenViking uses a per-vector scale that cuVS brute-force does
+not accept directly. CAGRA int8 or PQ compression must likewise be evaluated
+as approximate modes with an explicit recall/latency/memory frontier.
+
+The integration uses immutable GPU snapshots. Warmed searches use per-thread
+cuVS resources/CUDA streams, while mutation and snapshot commit use a
+cross-backend writer lock. Host-side filter and snapshot work can proceed in
+parallel, but `max_concurrent_gpu_searches` defaults to 1 because concurrent
+single-query brute-force kernels can contend for memory bandwidth and reduce
+throughput. Increase it only after measuring the target GPU and workload. By
+default, the first query after an upsert or delete rebuilds synchronously;
+optional background rebuild changes dirty queries to native fallback until the
+new snapshot is ready. On each rebuild it registers the cuVS label order with
+the native engine once.
The first use of a scalar or URI filter then reuses OpenViking's native
scalar/path index and projects its bitmap into cuVS row order; it does not scan
all host-side records in Python. `filter_cache_size` retains the resulting
-device bitsets and routing decisions and invalidates them on mutation.
+device bitsets and routing decisions and invalidates them on mutation. In auto
+mode, candidate-count preflight runs before the cuVS search path.
+Different unseen filters can use the native engine's shared-read path in
+parallel, while cached native routing decisions go directly to the native
+index. A record-generation check prevents a result computed across a mutation
+from entering the route cache.
Sparse/hybrid queries fall back to OpenViking's native local index when
`fallback_to_native` is enabled. The canonical vectors remain in the local
store and repopulate cuVS after restart.
@@ -148,4 +187,5 @@ Python interop path, even when the host provides a CUDA driver but no toolkit.
After installation, run `python examples/cuvs_smoke.py` for an exact
GPU-backed write and filtered-search check, or
`python examples/cuvs_smoke.py --algorithm cagra` to exercise the graph index.
+Add `--dtype float16` to either command to validate the lower-precision path.
Neither command requires an embedding or VLM service.
diff --git a/docs/zh/guides/07-operation-telemetry.md b/docs/zh/guides/07-operation-telemetry.md
index d6ad74c63..9633d6a95 100644
--- a/docs/zh/guides/07-operation-telemetry.md
+++ b/docs/zh/guides/07-operation-telemetry.md
@@ -176,6 +176,31 @@ summary 顶层这 3 个基础字段总会存在:
| `summary.vector.scanned` | 底层实际扫描的向量数量 |
| `summary.vector.scan_reason` | 本次扫描策略或扫描原因说明 |
+配置 cuVS 后,`summary.vector.cuvs` 会聚合本次 operation 内所有 dense search 的
+CPU/GPU 路由和分阶段耗时;并发 query 的完成顺序不会改变结果。其中不会包含
+查询向量、filter 值或 URI 内容,未知的维度值会统一归入有界的 `other` bucket。
+
+| 字段 | 含义 |
+| --- | --- |
+| `summary.vector.cuvs.searches` | 本次聚合包含的 dense search 数量 |
+| `summary.vector.cuvs.algorithms.<algorithm>` | 按 cuVS 算法统计的 search 数,例如 `brute_force` 或 `cagra` |
+| `summary.vector.cuvs.dtypes.<dtype>` | 按 GPU dataset/query dtype 统计的 search 数:`float32` 或 `float16` |
+| `summary.vector.cuvs.max_concurrent_gpu_searches` | 观测到的单 index in-flight GPU search 配置上限最大值 |
+| `summary.vector.cuvs.auto_mode_searches` | 启用自动 CPU/GPU 路由的 search 数量 |
+| `summary.vector.cuvs.routes.<reason>` | 按路由原因统计的 search 数,例如 `cuvs`、`native_filter_threshold`、`native_rebuild_pending` 或 `native_memory_budget` |
+| `summary.vector.cuvs.filter_kinds.<kind>` | 按低基数 filter 类型统计的 search 数:`none`、`scalar` 或 `path` |
+| `summary.vector.cuvs.filter_cache_hits` | 复用 prepared/preflight filter 的 search 数量 |
+| `summary.vector.cuvs.native_filter_reuses` | native recall 复用 preflight bitmap 的次数 |
+| `summary.vector.cuvs.builds` | 执行 GPU index build 的 search 数量 |
+| `summary.vector.cuvs.eligible_count_max` | native filter 后观测到的最大候选数 |
+| `summary.vector.cuvs.records_generation_max` | 观测到的最大 record generation |
+| `summary.vector.cuvs.index_size_max` | 观测到的最大 cuVS host snapshot 行数 |
+| `summary.vector.cuvs.memory.estimated_peak_bytes_max` | auto build 准入使用的最大峰值显存估算 |
+| `summary.vector.cuvs.memory.free_bytes_min` | 单 GPU 准入协调器内观测到的最小空闲显存 |
+| `summary.vector.cuvs.memory.usable_bytes_min` | 扣除配置 reserve 后观测到的最小可用显存 |
+| `summary.vector.cuvs.timings_ms.<stage>.sum` | `total`、`preflight`、`queue`、`build`、`filter_prepare`、`gpu_search` 或 `native_search` 阶段跨 search 的耗时总和 |
+| `summary.vector.cuvs.timings_ms.<stage>.max` | 同一阶段单次 search 的最大耗时 |
+
### `summary.resource`
这个分组常见于 `resources.add_resource` 这类资源导入操作。
diff --git a/docs/zh/guides/16-cuvs.md b/docs/zh/guides/16-cuvs.md
index feadfa74f..c62f9ec7f 100644
--- a/docs/zh/guides/16-cuvs.md
+++ b/docs/zh/guides/16-cuvs.md
@@ -39,6 +39,8 @@ headers;即使宿主机已有 CUDA driver、但没有完整 toolkit,也建
"distance_metric": "cosine",
"cuvs": {
"algorithm": "brute_force",
+ "dtype": "float32",
+ "max_concurrent_gpu_searches": 1,
"fallback_to_native": true,
"filter_cache_size": 16
}
@@ -87,21 +89,28 @@ headers;即使宿主机已有 CUDA driver、但没有完整 toolkit,也建
"auto_memory_reserve_mb": 1024,
"auto_memory_safety_factor": 2.0,
"auto_filter_native_threshold": 2000,
- "auto_path_filter_native_threshold": 200
+ "auto_path_filter_native_threshold": 200,
+ "auto_background_rebuild": true,
+ "auto_rebuild_debounce_ms": 500
}
}
}
}
```
-每次 lazy build/rebuild 前,auto 模式会读取当前空闲显存,并估算 float32 vector
-payload、CAGRA graph/intermediate graph(如适用)和 filter-bitset cache,再乘以
-`auto_memory_safety_factor`,同时保留 `auto_memory_reserve_mb`。如果预算不足,
+每次 lazy build/rebuild 前,auto 模式会读取当前空闲显存,并根据配置的 `dtype`
+估算 device vector payload、CAGRA graph/intermediate graph(如适用)和
+filter-bitset cache,再乘以 `auto_memory_safety_factor`,同时保留
+`auto_memory_reserve_mb`。如果预算不足,
或者 cuVS/GPU 不可用,本次查询继续使用未改变的 native index;cuVS index 保持
dirty,后续查询会在显存释放后重新尝试。通过 admission 后若仍遇到 GPU allocation
failure,也会回退 native。显式配置 `backend: "cuvs"` 时仍保持 fail-fast,不经过
这层自动判断。
+同一进程内的 local collection 会按 GPU 协调 build 和 admission,避免两个并发
+build 都基于同一份过期 free-memory 观测通过准入。不同 GPU 彼此独立,warmed
+search 也不会被这个协调器串行化。
+
auto 模式还会使用 native scalar index 返回的候选数做 filtered query 延迟路由:
候选数不超过 `auto_filter_native_threshold` 时使用 native vector recall;路径过滤
采用更低的 `auto_path_filter_native_threshold`,因为宽 URI 子树的 Trie 遍历和
@@ -109,10 +118,18 @@ bitmap union 本身可能占主要开销。默认阈值分别为 2,000 和 200
对应路由。阈值与硬件、维度和工作负载有关。显式 `backend: "cuvs"` 对支持的
dense query 仍固定使用 cuVS。
+`auto_background_rebuild` 默认关闭。开启后,连续 mutation 会按
+`auto_rebuild_debounce_ms` 合并,worker 在不持有跨后端 mutation 锁的情况下构建
+新的 immutable GPU snapshot。默认 500 ms 用于避免普通 ingest 的中间 batch
+反复触发构建;batch 间隔更长的 bulk load 应配置更大的值。snapshot dirty 期间查询直接使用当前 native index,
+不会把 GPU build 时间转化成请求排队时间。worker 只在 record generation 仍匹配时
+原子提交 label layout 和 GPU snapshot;过期 build 会被丢弃,并只重建最新一代。
+
## GPU 显存占用
-当前 GPU shadow 是 float32,因此 brute-force 的主要常驻 payload 为
-`N * dimension * 4` bytes。CAGRA 还需要约 `N * graph_degree * 4` bytes
+使用默认的 `dtype: "float32"` 时,brute-force 的主要常驻 device payload 为
+`N * dimension * 4` bytes。显式设置 `dtype: "float16"` 后,device payload
+降为 `N * dimension * 2` bytes。CAGRA 还需要约 `N * graph_degree * 4` bytes
保存 graph,构建期间可能需要 `N * intermediate_graph_degree * 4` bytes 的
intermediate graph。每个缓存 filter bitset 约占 `ceil(N / 32) * 4` bytes。
@@ -140,23 +157,32 @@ cuVS 版本、CAGRA 参数、query batch 和并行 GPU workload 都可能进一
启用 cuVS 不会改变 OpenViking 的默认后端,也不会重写原生 CPU 索引。正常的
collection metadata 仍为 `VectorIndex.Quant=int8`,因此 native fallback
-继续使用现有的、带逐向量 scale 的 int8 量化。与此同时,当前 cuVS runtime
-在 GPU 上保留 float32 shadow,因为 cuVS Python brute-force API 支持
-float32/float16,但不能直接表示 OpenViking 的 scaled-int8 record 格式。
+继续使用现有的、带逐向量 scale 的 int8 量化。与此同时,cuVS device dataset
+和 query 使用配置的 `dtype`:默认是 float32,也可以显式选择 float16。host
+record shadow 保存预处理后的 Python 浮点值;仅在创建 device dataset 和 query
+时将它们 cast 为配置的 dtype。cuVS Python brute-force API 支持这两种 device
+表示,但不能直接表示 OpenViking 的 scaled-int8 record 格式。
所以两条 dense search 路径不是等内存、等数值语义的比较:native 是在 CPU
-量化表示上的精确检索,cuVS brute-force 是在保留的 float32 向量上的精确检索,
-两者可能出现少量 score 或 neighbor ordering 差异。Benchmark 必须同时报告
-两边的数据类型和 Recall@K,不能将结果描述为 equal-dtype 或 equal-memory。
+量化表示上的精确检索,cuVS brute-force 是在保留的 float32 或 float16 device
+表示上的精确检索,两者可能出现少量 score 或 neighbor ordering 差异。
+Benchmark 必须同时报告两边的数据类型和 Recall@K,不能将结果描述为
+equal-dtype 或 equal-memory。
这是首版 opt-in 集成的有意边界,现有 CPU 行为保持不变。auto 模式会根据 filter
候选阈值在两种表示之间选择;要求固定数值表示的应用应使用显式 backend,或将
native 路由阈值设为 0。
-GPU 低精度存储作为后续显式能力实现,不做隐式 cast。第一步可以让 cuVS dataset
-与 query 可配置为 float16,并以 float32 为 ground truth 测 Recall@K。与 native
-兼容的 int8 需要单独设计,因为 OpenViking 使用逐向量 scale,而 cuVS
-brute-force 不能直接接收这种 scaled-int8 表示。CAGRA int8 或 PQ compression
-也应作为近似模式,单独报告 recall/latency/memory frontier。
+GPU 低精度存储是显式能力,不做隐式 cast。设置 `dtype: "float16"` 会把 cuVS
+dataset 和每个 query 同时 cast 为 float16,brute-force 与 CAGRA 都不使用混合
+query/index dtype。这是存储 cast,不是逐向量量化,必须以默认 float32 为 ground
+truth 报告 Recall@K。与 native 兼容的 int8 仍需单独设计,因为 OpenViking 使用
+逐向量 scale,而 cuVS brute-force 不能直接接收这种 scaled-int8 表示。CAGRA
+int8 或 PQ compression 也应作为近似模式,单独报告 recall/latency/memory frontier。
+
+集成使用 immutable GPU snapshot 和每线程 cuVS resource/CUDA stream。host 侧
+filter 与 snapshot 工作可以并行,但 `max_concurrent_gpu_searches` 默认是 1:
+单 query brute-force 通常受显存带宽限制,并发 kernel 可能互相争抢带宽、反而降低
+吞吐。只有在目标 GPU 与真实 workload 上测得收益后,才建议显式调大该值。
## 最小功能验证
@@ -167,6 +193,9 @@ python examples/cuvs_smoke.py
# 验证 CAGRA 图索引
python examples/cuvs_smoke.py --algorithm cagra
+
+# 验证显式 float16 路径
+python examples/cuvs_smoke.py --dtype float16
```
核心调用方式如下:
@@ -223,7 +252,8 @@ collection.close()
- cuVS 只接管 pure dense search;sparse/hybrid query 在 `fallback_to_native=true` 时走原生本地索引。
- local 集成通过 native scalar/path index 生成 prefilter,因此继承原生 DSL、`date_time`、`geo_point` 和 path depth 的过滤语义,而不是在 Python 重复实现。
- 每次 GPU rebuild 会向 native engine 注册一次 cuVS label 顺序。新过滤条件直接复用 native scalar/path index 的 bitmap,再投影为 cuVS row bitset,不再用 Python 扫描所有 host-side records。
-- `filter_cache_size` 会保留最近使用的 GPU bitset 或 native 路由决策,并在数据更新时失效。
-- 每次 upsert/delete 后会在下一次查询时重建 GPU 索引。这保证了首版更新语义正确,但不适合写密集负载。
+- `filter_cache_size` 会保留最近使用的 GPU bitset 或 native 路由决策,并在数据更新时失效;auto 模式在进入 cuVS search 前预判候选数,不同的首次过滤条件可通过 native engine 的共享读路径并行计算,命中已缓存的 native 路由时则直接进入 native index。generation 校验会阻止跨 mutation 计算出的旧结果写入路由缓存。
+- GPU index 使用 immutable snapshot;warmed search 通过不同的 cuVS resources/CUDA stream 并发执行,mutation 和 snapshot commit 使用跨后端写锁。
+- 默认情况下,每次 upsert/delete 后仍由下一次查询同步重建;开启 `auto_background_rebuild` 后,dirty 期间查询走 native,连续写被合并为后台重建。
- cuVS 索引不作为权威持久化数据;进程重启时会从 OpenViking 本地 store 重建,因此不受 cuVS 跨版本序列化格式变化影响。
- `brute_force` 适合功能对齐和 ground truth;CAGRA 的 graph/search 参数需要在后续结合召回率、QPS、延迟和显存进行调优。
diff --git a/examples/cuvs_smoke.py b/examples/cuvs_smoke.py
index 362b6f89b..f8ff0144c 100644
--- a/examples/cuvs_smoke.py
+++ b/examples/cuvs_smoke.py
@@ -1,13 +1,14 @@
"""Minimal GPU smoke test for OpenViking's cuVS dense-search backend."""
import argparse
+from concurrent.futures import ThreadPoolExecutor
from openviking.storage.vectordb.collection.local_collection import (
get_or_create_local_collection,
)
-def main(algorithm: str) -> None:
+def main(algorithm: str, dtype: str) -> None:
collection = get_or_create_local_collection(
meta_data={
"CollectionName": "cuvs_smoke",
@@ -22,6 +23,7 @@ def main(algorithm: str) -> None:
"dense_search": {
"backend": "cuvs",
"algorithm": algorithm,
+ "dtype": dtype,
"fallback_to_native": True,
"build_params": (
{"graph_degree": 16, "intermediate_graph_degree": 32}
@@ -89,6 +91,23 @@ def main(algorithm: str) -> None:
ids = [item.id for item in result.data]
assert ids == ["a", "b"], ids
+ with ThreadPoolExecutor(max_workers=4) as executor:
+ concurrent_results = list(
+ executor.map(
+ lambda _index: collection.search_by_vector(
+ "default",
+ dense_vector=[1, 0, 0, 0],
+ limit=2,
+ filters=demo_filter,
+ ),
+ range(4),
+ )
+ )
+ assert all(
+ [item.id for item in concurrent_result.data] == ["a", "b"]
+ for concurrent_result in concurrent_results
+ )
+
collection.update_data(
[
{
@@ -108,7 +127,12 @@ def main(algorithm: str) -> None:
)
ids_after_mutation = [item.id for item in result.data]
assert ids_after_mutation == ["b"], ids_after_mutation
- print(f"cuVS {algorithm} smoke test passed:", ids, "->", ids_after_mutation)
+ print(
+ f"cuVS {algorithm}/{dtype} smoke test passed:",
+ ids,
+ "->",
+ ids_after_mutation,
+ )
finally:
collection.close()
@@ -120,5 +144,10 @@ if __name__ == "__main__":
choices=("brute_force", "cagra"),
default="brute_force",
)
+ parser.add_argument(
+ "--dtype",
+ choices=("float32", "float16"),
+ default="float32",
+ )
args = parser.parse_args()
- main(args.algorithm)
+ main(args.algorithm, args.dtype)
diff --git a/openviking/storage/vectordb/collection/local_collection.py b/openviking/storage/vectordb/collection/local_collection.py
index 64940177b..49bcd27e9 100644
--- a/openviking/storage/vectordb/collection/local_collection.py
+++ b/openviking/storage/vectordb/collection/local_collection.py
@@ -979,6 +979,7 @@ class PersistCollection(LocalCollection):
# This ensures the index's base version starts at 0, allowing it to ingest
# all data from the delta log (CandidateData) regardless of when that data was created.
# If we used the default (current time), the index would ignore older data in the log.
+ # Keep the dense worker stopped until the native snapshot has replayed those deltas.
index = PersistentIndex(
name=index_name,
path=self.index_dir,
@@ -986,6 +987,7 @@ class PersistCollection(LocalCollection):
cands_list=recovery_candidates,
initial_timestamp=0,
dense_search_config=self.dense_search_config,
+ defer_dense_rebuild_start=True,
)
newest_version = index.get_newest_version()
if not self.store_mgr:
@@ -1045,6 +1047,7 @@ class PersistCollection(LocalCollection):
operation="delete",
)
logger.info("Index '%s': replay complete (%d records)", index_name, _processed)
+ index._start_dense_rebuild_worker()
self.indexes.set(index_name, index)
def _replay_recovery_records(
diff --git a/openviking/storage/vectordb/engine/_python_api.py b/openviking/storage/vectordb/engine/_python_api.py
index d24f95097..427944ab7 100644
--- a/openviking/storage/vectordb/engine/_python_api.py
+++ b/openviking/storage/vectordb/engine/_python_api.py
@@ -348,22 +348,25 @@ class SearchResult:
class FilterResult:
- __slots__ = ("eligible_count", "bitset_words")
+ __slots__ = ("eligible_count", "bitset_words", "native_filter_token")
def __init__(
self,
*,
eligible_count: int = 0,
bitset_words: list[int] | None = None,
+ native_filter_token: int = 0,
):
self.eligible_count = eligible_count
self.bitset_words = bitset_words or []
+ self.native_filter_token = native_filter_token
@classmethod
def from_backend(cls, payload: dict[str, Any]) -> "FilterResult":
return cls(
eligible_count=int(payload.get("eligible_count", 0)),
bitset_words=[int(word) for word in payload.get("bitset_words", [])],
+ native_filter_token=int(payload.get("native_filter_token", 0)),
)
@@ -459,13 +462,31 @@ def build_abi3_exports(backend: Any) -> dict[str, Any]:
def search(self, req: SearchRequest) -> SearchResult:
return SearchResult.from_backend(self._backend._index_engine_search(self._handle, req))
+ def search_with_filter_token(
+ self, req: SearchRequest, filter_token: int
+ ) -> SearchResult | None:
+ search_with_token = getattr(
+ self._backend, "_index_engine_search_with_filter_token", None
+ )
+ if search_with_token is None:
+ return None
+ payload = search_with_token(self._handle, req, filter_token)
+ return None if payload is None else SearchResult.from_backend(payload)
+
def set_filter_layout(self, ordered_labels: list[int]) -> int:
return int(self._backend._index_engine_set_filter_layout(self._handle, ordered_labels))
- def evaluate_filter(self, dsl: str) -> FilterResult:
- return FilterResult.from_backend(
- self._backend._index_engine_evaluate_filter(self._handle, dsl)
- )
+ def evaluate_filter(self, dsl: str, max_cached_candidates: int = 0) -> FilterResult:
+ evaluate_cached = getattr(self._backend, "_index_engine_evaluate_filter_cached", None)
+ if max_cached_candidates > 0 and evaluate_cached is not None:
+ payload = evaluate_cached(
+ self._handle,
+ dsl,
+ max_cached_candidates,
+ )
+ else:
+ payload = self._backend._index_engine_evaluate_filter(self._handle, dsl)
+ return FilterResult.from_backend(payload)
def dump(self, path: str) -> int:
return int(self._backend._index_engine_dump(self._handle, path))
diff --git a/openviking/storage/vectordb/index/cuvs_index.py b/openviking/storage/vectordb/index/cuvs_index.py
index 14bea8817..db98a9778 100644
--- a/openviking/storage/vectordb/index/cuvs_index.py
+++ b/openviking/storage/vectordb/index/cuvs_index.py
@@ -21,14 +21,23 @@ import logging
import math
import re
import threading
+import time
+import traceback
from collections import OrderedDict
+from contextlib import nullcontext
from dataclasses import dataclass
-from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple
+from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union
from openviking.storage.vectordb.store.data import CandidateData, DeltaRecord
logger = logging.getLogger(__name__)
+NativeFilterEvaluation = Union[
+ Tuple[Sequence[int], int],
+ Tuple[Sequence[int], int, int],
+]
+NativeFilterResolver = Callable[[Mapping[str, Any]], NativeFilterEvaluation]
+
class CuVSUnavailableError(RuntimeError):
"""Raised when the configured cuVS runtime cannot be used."""
@@ -57,6 +66,60 @@ class CuVSMemoryEstimate:
estimated_peak_bytes: int
+@dataclass
+class CuVSSearchTelemetry:
+ """Low-cardinality timings and route metadata for one dense query."""
+
+ algorithm: str
+ auto_mode: bool
+ dtype: str = "float32"
+ max_concurrent_gpu_searches: int = 1
+ route_reason: str = "pending"
+ filter_kind: str = "none"
+ filter_cache_hit: bool = False
+ native_filter_reused: bool = False
+ build_performed: bool = False
+ eligible_count: Optional[int] = None
+ records_generation: int = 0
+ index_size: int = 0
+ memory_estimated_peak_bytes: Optional[int] = None
+ memory_free_bytes: Optional[int] = None
+ memory_usable_bytes: Optional[int] = None
+ total_ms: float = 0.0
+ preflight_ms: float = 0.0
+ queue_ms: float = 0.0
+ build_ms: float = 0.0
+ filter_prepare_ms: float = 0.0
+ gpu_search_ms: float = 0.0
+ native_search_ms: float = 0.0
+
+ def as_dict(self) -> Dict[str, Any]:
+ return {
+ "algorithm": self.algorithm,
+ "auto_mode": self.auto_mode,
+ "dtype": self.dtype,
+ "max_concurrent_gpu_searches": self.max_concurrent_gpu_searches,
+ "route_reason": self.route_reason,
+ "filter_kind": self.filter_kind,
+ "filter_cache_hit": self.filter_cache_hit,
+ "native_filter_reused": self.native_filter_reused,
+ "build_performed": self.build_performed,
+ "eligible_count": self.eligible_count,
+ "records_generation": self.records_generation,
+ "index_size": self.index_size,
+ "memory_estimated_peak_bytes": self.memory_estimated_peak_bytes,
+ "memory_free_bytes": self.memory_free_bytes,
+ "memory_usable_bytes": self.memory_usable_bytes,
+ "total_ms": round(self.total_ms, 3),
+ "preflight_ms": round(self.preflight_ms, 3),
+ "queue_ms": round(self.queue_ms, 3),
+ "build_ms": round(self.build_ms, 3),
+ "filter_prepare_ms": round(self.filter_prepare_ms, 3),
+ "gpu_search_ms": round(self.gpu_search_ms, 3),
+ "native_search_ms": round(self.native_search_ms, 3),
+ }
+
+
def estimate_cuvs_memory(
*,
vector_count: int,
@@ -65,13 +128,14 @@ def estimate_cuvs_memory(
build_params: Mapping[str, Any],
filter_cache_size: int,
safety_factor: float,
+ dtype: str = "float32",
) -> CuVSMemoryEstimate:
"""Estimate peak VRAM without changing the explicit cuVS backend behavior.
- The estimate accounts for the float32 dataset, retained and intermediate
- CAGRA graphs, and the configured number of cached filter bitsets. cuVS and
- allocator workspaces vary by release and build algorithm, so the configured
- safety factor intentionally covers the remaining uncertainty.
+ The estimate accounts for the configured device-dataset dtype, retained and
+ intermediate CAGRA graphs, and the configured number of cached filter bitsets.
+ cuVS and allocator workspaces vary by release and build algorithm, so the
+ configured safety factor intentionally covers the remaining uncertainty.
"""
vector_count = max(0, int(vector_count))
@@ -80,7 +144,9 @@ def estimate_cuvs_memory(
if safety_factor < 1.0:
raise ValueError("cuVS auto memory safety factor must be at least 1.0")
- vector_bytes = vector_count * dimension * 4
+ if dtype not in {"float32", "float16"}:
+ raise ValueError(f"Unsupported cuVS memory-estimate dtype: {dtype!r}")
+ vector_bytes = vector_count * dimension * (2 if dtype == "float16" else 4)
graph_bytes = 0
build_graph_bytes = 0
if algorithm == "cagra":
@@ -102,6 +168,26 @@ def estimate_cuvs_memory(
)
+class _CuVSMemoryCoordinator:
+ """Serialize admission and builds per GPU across local collections."""
+
+ def __init__(self):
+ self._lock = threading.Lock()
+ self._device_locks: Dict[int, threading.Lock] = {}
+
+ def build_lock(self, runtime: Any) -> threading.Lock:
+ device_id = int(getattr(runtime, "device_id", 0))
+ with self._lock:
+ lock = self._device_locks.get(device_id)
+ if lock is None:
+ lock = threading.Lock()
+ self._device_locks[device_id] = lock
+ return lock
+
+
+_CUVS_MEMORY_COORDINATOR = _CuVSMemoryCoordinator()
+
+
def _normalize(vector: Sequence[float]) -> List[float]:
norm = math.sqrt(sum(float(value) * float(value) for value in vector))
if norm == 0:
@@ -278,12 +364,15 @@ class _CuVSRuntime:
metric: str,
build_params: Mapping[str, Any],
search_params: Mapping[str, Any],
+ dtype: str,
):
try:
import cupy as cp
+ from cuvs.common import Resources
from cuvs.neighbors import brute_force, cagra, filters
device_count = cp.cuda.runtime.getDeviceCount()
+ device_id = cp.cuda.runtime.getDevice()
except Exception as exc:
raise CuVSUnavailableError(
"cuVS backend requires Python 3.11+, a CUDA-capable NVIDIA GPU, and the "
@@ -296,22 +385,50 @@ class _CuVSRuntime:
self.brute_force = brute_force
self.cagra = cagra
self.filters = filters
+ self.Resources = Resources
+ self.device_id = int(device_id)
+ self.dtype = dtype
+ self.device_dtype = cp.float16 if dtype == "float16" else cp.float32
self.algorithm = algorithm
self.metric = metric
self.build_params = dict(build_params)
self.search_params = dict(search_params)
- self.dataset = None
+ # Resources are borrowed per admitted search rather than retained by
+ # worker thread. This keeps their lifetime on device_id and bounds the
+ # registry even when callers churn short-lived host threads.
+ self._resource_condition = threading.Condition(threading.Lock())
+ self._available_resources: List[Any] = []
+ self._owned_resources: List[Any] = []
+ self._resource_limit = 1
+ self._resources_closed = False
+ self._use_explicit_resources = False
+
+ def set_max_concurrent_searches(self, value: int) -> None:
+ limit = max(1, int(value))
+ with self._resource_condition:
+ self._resource_limit = limit
+ self._use_explicit_resources = limit > 1
+ self._resource_condition.notify_all()
+
+ def device_scope(self):
+ """Activate the device captured when this runtime was constructed."""
+
+ return self.cp.cuda.Device(self.device_id)
def memory_info(self) -> Tuple[int, int]:
- free_bytes, total_bytes = self.cp.cuda.runtime.memGetInfo()
- return int(free_bytes), int(total_bytes)
+ # CUDA's current device is thread-local. Searches and background
+ # rebuilds can run on threads other than the one which constructed the
+ # runtime, so every CUDA entry point must restore the captured device.
+ with self.device_scope():
+ free_bytes, total_bytes = self.cp.cuda.runtime.memGetInfo()
+ return int(free_bytes), int(total_bytes)
def release_index(self) -> None:
- self.dataset = None
- try:
- self.cp.get_default_memory_pool().free_all_blocks()
- except Exception:
- logger.debug("Could not release unused CuPy memory-pool blocks", exc_info=True)
+ with self.device_scope():
+ try:
+ self.cp.get_default_memory_pool().free_all_blocks()
+ except Exception:
+ logger.debug("Could not release unused CuPy memory-pool blocks", exc_info=True)
def is_out_of_memory(self, exc: Exception) -> bool:
out_of_memory_type = getattr(self.cp.cuda.memory, "OutOfMemoryError", ())
@@ -323,63 +440,159 @@ class _CuVSRuntime:
)
def build(self, dataset: Sequence[Sequence[float]]):
- self.dataset = self.cp.asarray(dataset, dtype=self.cp.float32)
- if self.algorithm == "brute_force":
- return self.brute_force.build(self.dataset, metric=self.metric)
- params = self.cagra.IndexParams(metric=self.metric, **self.build_params)
- return self.cagra.build(params, self.dataset)
+ with self.device_scope():
+ device_dataset = None
+ index = None
+ try:
+ device_dataset = self.cp.asarray(dataset, dtype=self.device_dtype)
+ if self.algorithm == "brute_force":
+ index = self.brute_force.build(device_dataset, metric=self.metric)
+ return _CuVSRuntimeIndex(index=index, dataset=device_dataset)
+ params = self.cagra.IndexParams(metric=self.metric, **self.build_params)
+ index = self.cagra.build(params, device_dataset)
+ return _CuVSRuntimeIndex(index=index, dataset=device_dataset)
+ except Exception as exc:
+ # These can be the last Python references after a partial build.
+ # Drop them before Device.__exit__ restores the caller's device.
+ index = None
+ device_dataset = None
+ # Python/Cython exception frames can retain CUDA arguments even
+ # after the locals above are cleared. Preserve stack locations
+ # while releasing frame locals under the captured device.
+ traceback.clear_frames(exc.__traceback__)
+ raise
+
+ def _acquire_resources(self):
+ with self.device_scope():
+ with self._resource_condition:
+ while not self._resources_closed:
+ if self._available_resources:
+ return self._available_resources.pop()
+ if len(self._owned_resources) < self._resource_limit:
+ resources = self.Resources()
+ self._owned_resources.append(resources)
+ return resources
+ self._resource_condition.wait()
+ raise RuntimeError("cuVS runtime is closed")
+
+ def _return_resources(self, resources: Any, *, reusable: bool) -> None:
+ with self._resource_condition:
+ owned_index = next(
+ (index for index, owned in enumerate(self._owned_resources) if owned is resources),
+ None,
+ )
+ if owned_index is None:
+ return
+ if reusable and not self._resources_closed:
+ self._available_resources.append(resources)
+ else:
+ self._owned_resources.pop(owned_index)
+ self._resource_condition.notify()
def _prefilter(self, mask: Sequence[bool]):
- return self.filters.from_bitset(self.prepare_filter(mask))
+ with self.device_scope():
+ return self.filters.from_bitset(self.prepare_filter(mask))
def prepare_filter(self, mask: Sequence[bool]):
"""Pack a host mask once and retain its device allocation for reuse."""
- word_count = (len(mask) + 31) // 32
- words = [0] * word_count
- for index, included in enumerate(mask):
- if included:
- words[index // 32] |= 1 << (index % 32)
- return self.cp.asarray(words, dtype=self.cp.uint32)
+ with self.device_scope():
+ word_count = (len(mask) + 31) // 32
+ words = [0] * word_count
+ for index, included in enumerate(mask):
+ if included:
+ words[index // 32] |= 1 << (index % 32)
+ return self.cp.asarray(words, dtype=self.cp.uint32)
def prepare_filter_words(self, words: Sequence[int]):
"""Copy an already packed native filter bitmap to the device."""
- return self.cp.asarray(words, dtype=self.cp.uint32)
+ with self.device_scope():
+ return self.cp.asarray(words, dtype=self.cp.uint32)
def search(
self,
- index: Any,
+ runtime_index: "_CuVSRuntimeIndex",
query: Sequence[float],
limit: int,
mask: Optional[Any],
) -> Tuple[List[int], List[float]]:
- queries = self.cp.asarray([query], dtype=self.cp.float32)
- if mask is None:
+ with self.device_scope():
+ queries = None
prefilter = None
- elif isinstance(mask, self.cp.ndarray) and mask.dtype == self.cp.uint32:
- prefilter = self.filters.from_bitset(mask)
- else:
- prefilter = self._prefilter(mask)
- if self.algorithm == "brute_force":
- distances, neighbors = self.brute_force.search(
- index, queries, limit, prefilter=prefilter
- )
- else:
- search_params = dict(self.search_params)
- configured_itopk = int(search_params.get("itopk_size", 64))
- minimum_itopk = ((limit + 31) // 32) * 32
- search_params["itopk_size"] = max(configured_itopk, minimum_itopk)
- params = self.cagra.SearchParams(**search_params)
- distances, neighbors = self.cagra.search(
- params, index, queries, limit, filter=prefilter
- )
- host_neighbors = self.cp.asnumpy(neighbors)[0].tolist()
- host_distances = self.cp.asnumpy(distances)[0].tolist()
- return [int(item) for item in host_neighbors], [float(item) for item in host_distances]
+ distances = None
+ neighbors = None
+ resources = None
+ resource_kwargs = None
+ resource_reusable = False
+ try:
+ index = runtime_index.index
+ resources = self._acquire_resources() if self._use_explicit_resources else None
+ resource_kwargs = {"resources": resources} if resources is not None else {}
+ queries = self.cp.asarray([query], dtype=self.device_dtype)
+ if mask is None:
+ prefilter = None
+ elif isinstance(mask, self.cp.ndarray) and mask.dtype == self.cp.uint32:
+ prefilter = self.filters.from_bitset(mask)
+ else:
+ prefilter = self._prefilter(mask)
+ if self.algorithm == "brute_force":
+ distances, neighbors = self.brute_force.search(
+ index,
+ queries,
+ limit,
+ prefilter=prefilter,
+ **resource_kwargs,
+ )
+ else:
+ search_params = dict(self.search_params)
+ configured_itopk = int(search_params.get("itopk_size", 64))
+ minimum_itopk = ((limit + 31) // 32) * 32
+ search_params["itopk_size"] = max(configured_itopk, minimum_itopk)
+ params = self.cagra.SearchParams(**search_params)
+ distances, neighbors = self.cagra.search(
+ params,
+ index,
+ queries,
+ limit,
+ filter=prefilter,
+ **resource_kwargs,
+ )
+ if resources is not None:
+ resources.sync()
+ resource_reusable = True
+ host_neighbors = self.cp.asnumpy(neighbors)[0].tolist()
+ host_distances = self.cp.asnumpy(distances)[0].tolist()
+ return [int(item) for item in host_neighbors], [
+ float(item) for item in host_distances
+ ]
+ except Exception as exc:
+ traceback.clear_frames(exc.__traceback__)
+ raise
+ finally:
+ # Search temporaries otherwise outlive Device.__exit__ as frame
+ # locals and may free allocations on the worker's prior device.
+ queries = None
+ prefilter = None
+ distances = None
+ neighbors = None
+ try:
+ if resources is not None:
+ self._return_resources(resources, reusable=resource_reusable)
+ finally:
+ resource_kwargs = None
+ resources = None
def close(self) -> None:
- self.release_index()
+ with self.device_scope():
+ with self._resource_condition:
+ self._resources_closed = True
+ self._available_resources.clear()
+ owned_resources = self._owned_resources
+ self._owned_resources = []
+ self._resource_condition.notify_all()
+ owned_resources.clear()
+ self.release_index()
@dataclass(frozen=True)
@@ -388,12 +601,34 @@ class _Record:
fields: Mapping[str, Any]
+@dataclass(frozen=True)
+class _CuVSRuntimeIndex:
+ index: Any
+ dataset: Any
+
+
+@dataclass(frozen=True)
+class _CuVSIndexSnapshot:
+ runtime_index: Any
+ labels: Tuple[int, ...]
+ generation: int
+
+
+@dataclass
+class _CuVSBuildCandidate:
+ runtime_index: Any
+ labels: Tuple[int, ...]
+ generation: int
+ consumed: bool = False
+
+
@dataclass(frozen=True)
class _CachedFilter:
prepared: Any
eligible_count: int
route_native: bool = False
native_threshold: int = 0
+ native_filter_token: int = 0
@dataclass(frozen=True)
@@ -402,6 +637,7 @@ class _ResolvedNativeFilter:
eligible_count: int
route_native: bool
native_threshold: int
+ native_filter_token: int = 0
class CuVSDenseIndex:
@@ -433,11 +669,19 @@ class CuVSDenseIndex:
)
if self.distance not in {"ip", "l2"}:
raise ValueError(f"Unsupported OpenViking distance for cuVS: {self.distance!r}")
+ self.dtype = str(config.get("dtype", "float32")).lower()
+ if self.dtype not in {"float32", "float16"}:
+ raise ValueError(
+ f"Unsupported cuVS dtype {self.dtype!r}; choose 'float32' or 'float16'"
+ )
self.fallback_to_native = bool(config.get("fallback_to_native", True))
self.filter_cache_size = int(config.get("filter_cache_size", 16))
if self.filter_cache_size < 0:
raise ValueError("cuVS filter_cache_size cannot be negative")
+ self.max_concurrent_gpu_searches = int(config.get("max_concurrent_gpu_searches", 1))
+ if self.max_concurrent_gpu_searches < 1:
+ raise ValueError("cuVS max_concurrent_gpu_searches must be at least 1")
self.auto_memory_reserve_bytes = (
int(config.get("auto_memory_reserve_mb", 1024)) * 1024 * 1024
)
@@ -470,13 +714,23 @@ class CuVSDenseIndex:
self._metric,
build_params,
search_params,
+ self.dtype,
)
+ set_max_concurrent_searches = getattr(self._runtime, "set_max_concurrent_searches", None)
+ if set_max_concurrent_searches is not None:
+ set_max_concurrent_searches(self.max_concurrent_gpu_searches)
self._records: Dict[int, _Record] = {}
- self._labels: List[int] = []
- self._index: Any = None
+ self._snapshot: Optional[_CuVSIndexSnapshot] = None
self._dirty = True
self._filter_cache: OrderedDict[str, _CachedFilter] = OrderedDict()
+ self._preflight_filter_cache: OrderedDict[str, _ResolvedNativeFilter] = OrderedDict()
self._lock = threading.RLock()
+ self._idle_condition = threading.Condition(self._lock)
+ self._active_searches = 0
+ self._gpu_search_gate = threading.BoundedSemaphore(self.max_concurrent_gpu_searches)
+ self._filter_layout_lock = threading.Lock()
+ self._records_generation = 0
+ self._filter_layout_generation = -1
logger.info(
"Initialized cuVS dense index: algorithm=%s metric=%s dimension=%d",
self.algorithm,
@@ -484,11 +738,20 @@ class CuVSDenseIndex:
self.dimension,
)
+ def _runtime_device_scope(self):
+ device_scope = getattr(self._runtime, "device_scope", None)
+ return device_scope() if callable(device_scope) else nullcontext()
+
@property
def size(self) -> int:
with self._lock:
return len(self._records)
+ @property
+ def needs_rebuild(self) -> bool:
+ with self._lock:
+ return self._dirty
+
def _prepare_vector(self, vector: Sequence[float]) -> Tuple[float, ...]:
if len(vector) != self.dimension:
raise ValueError(
@@ -542,8 +805,11 @@ class CuVSDenseIndex:
self._invalidate()
def _invalidate(self) -> None:
+ self._records_generation += 1
self._dirty = True
- self._filter_cache.clear()
+ with self._runtime_device_scope():
+ self._filter_cache.clear()
+ self._preflight_filter_cache.clear()
@staticmethod
def _filter_cache_key(filters: Mapping[str, Any]) -> Optional[str]:
@@ -563,21 +829,151 @@ class CuVSDenseIndex:
def _cache_filter(self, cache_key: Optional[str], cached: _CachedFilter) -> None:
if cache_key is None or self.filter_cache_size <= 0:
return
- self._filter_cache[cache_key] = cached
- while len(self._filter_cache) > self.filter_cache_size:
- self._filter_cache.popitem(last=False)
+ self._preflight_filter_cache.pop(cache_key, None)
+ with self._runtime_device_scope():
+ self._filter_cache[cache_key] = cached
+ while len(self._filter_cache) > self.filter_cache_size:
+ self._filter_cache.popitem(last=False)
- def _resolve_native_filter(
+ def _get_preflight_filter(self, cache_key: Optional[str]) -> Optional[_ResolvedNativeFilter]:
+ if cache_key is None:
+ return None
+ cached = self._preflight_filter_cache.pop(cache_key, None)
+ if cached is not None:
+ self._preflight_filter_cache[cache_key] = cached
+ return cached
+
+ def _cache_preflight_filter(
self,
- filters: Mapping[str, Any],
- native_filter_resolver: Callable[[Mapping[str, Any]], Tuple[Sequence[int], int]],
- ) -> _ResolvedNativeFilter:
- words, eligible_count = native_filter_resolver(filters)
- native_threshold = (
+ cache_key: Optional[str],
+ resolved: _ResolvedNativeFilter,
+ ) -> None:
+ if cache_key is None:
+ return
+ self._preflight_filter_cache[cache_key] = resolved
+ capacity = max(1, self.filter_cache_size)
+ while len(self._preflight_filter_cache) > capacity:
+ self._preflight_filter_cache.popitem(last=False)
+
+ def native_filter_threshold(self, filters: Mapping[str, Any]) -> int:
+ return (
self.auto_path_filter_native_threshold
if _filter_uses_field_type(filters, self.field_types, "path")
else self.auto_filter_native_threshold
)
+
+ def native_filter_token(self, filters: Mapping[str, Any]) -> int:
+ cache_key = self._filter_cache_key(filters)
+ with self._lock:
+ cached = self._get_cached_filter(cache_key)
+ if cached is None or not cached.route_native:
+ return 0
+ return cached.native_filter_token
+
+ def _ensure_native_filter_layout(
+ self,
+ native_filter_layout_registrar: Callable[[Sequence[int]], None],
+ ) -> Optional[int]:
+ with self._filter_layout_lock:
+ with self._lock:
+ generation = self._records_generation
+ if self._filter_layout_generation == generation:
+ return generation
+ ordered_labels = list(self._records)
+
+ native_filter_layout_registrar(ordered_labels)
+
+ with self._lock:
+ if self._records_generation != generation:
+ return None
+ self._filter_layout_generation = generation
+ return generation
+
+ def preflight_native_count(
+ self,
+ filters: Mapping[str, Any],
+ native_filter_resolver: NativeFilterResolver,
+ native_filter_layout_registrar: Callable[[Sequence[int]], None],
+ telemetry: Optional[CuVSSearchTelemetry] = None,
+ ) -> Optional[int]:
+ """Return the native-route candidate count, or None for the cuVS path."""
+
+ started = time.perf_counter()
+ try:
+ if not self.auto_memory or not filters:
+ return None
+ cache_key = self._filter_cache_key(filters)
+ with self._lock:
+ if telemetry is not None:
+ telemetry.filter_kind = (
+ "path"
+ if _filter_uses_field_type(filters, self.field_types, "path")
+ else "scalar"
+ )
+ telemetry.records_generation = self._records_generation
+ telemetry.index_size = len(self._records)
+ cached = self._get_cached_filter(cache_key)
+ if cached is not None:
+ if telemetry is not None:
+ telemetry.filter_cache_hit = True
+ telemetry.eligible_count = cached.eligible_count
+ return cached.eligible_count if cached.route_native else None
+ native_threshold = self.native_filter_threshold(filters)
+ if native_threshold <= 0:
+ return None
+ preflight_cached = self._get_preflight_filter(cache_key)
+ if preflight_cached is not None:
+ if telemetry is not None:
+ telemetry.filter_cache_hit = True
+ telemetry.eligible_count = preflight_cached.eligible_count
+ return (
+ preflight_cached.eligible_count if preflight_cached.route_native else None
+ )
+
+ generation = self._ensure_native_filter_layout(native_filter_layout_registrar)
+ if generation is None:
+ return None
+ resolved = self._resolve_native_filter(filters, native_filter_resolver)
+ if telemetry is not None:
+ telemetry.eligible_count = resolved.eligible_count
+
+ with self._lock:
+ if self._records_generation != generation:
+ return None
+ cached = self._get_cached_filter(cache_key)
+ if cached is not None:
+ if telemetry is not None:
+ telemetry.filter_cache_hit = True
+ telemetry.eligible_count = cached.eligible_count
+ return cached.eligible_count if cached.route_native else None
+ if not resolved.route_native and resolved.eligible_count != 0:
+ self._cache_preflight_filter(cache_key, resolved)
+ return None
+ cached = _CachedFilter(
+ prepared=None,
+ eligible_count=resolved.eligible_count,
+ route_native=resolved.route_native,
+ native_threshold=resolved.native_threshold,
+ native_filter_token=resolved.native_filter_token,
+ )
+ self._cache_filter(cache_key, cached)
+ return cached.eligible_count if cached.route_native else None
+ finally:
+ if telemetry is not None:
+ telemetry.preflight_ms += (time.perf_counter() - started) * 1000.0
+
+ def _resolve_native_filter(
+ self,
+ filters: Mapping[str, Any],
+ native_filter_resolver: NativeFilterResolver,
+ ) -> _ResolvedNativeFilter:
+ evaluation = native_filter_resolver(filters)
+ if len(evaluation) == 2:
+ words, eligible_count = evaluation
+ native_filter_token = 0
+ else:
+ words, eligible_count, native_filter_token = evaluation
+ native_threshold = self.native_filter_threshold(filters)
route_native = (
self.auto_memory and native_threshold > 0 and eligible_count <= native_threshold
)
@@ -586,14 +982,14 @@ class CuVSDenseIndex:
eligible_count=int(eligible_count),
route_native=route_native,
native_threshold=native_threshold,
+ native_filter_token=int(native_filter_token),
)
def _prepare_filter(
self,
filters: Mapping[str, Any],
- native_filter_resolver: Optional[
- Callable[[Mapping[str, Any]], Tuple[Sequence[int], int]]
- ] = None,
+ labels: Sequence[int],
+ native_filter_resolver: Optional[NativeFilterResolver] = None,
resolved_native_filter: Optional[_ResolvedNativeFilter] = None,
) -> _CachedFilter:
cache_key = self._filter_cache_key(filters)
@@ -608,7 +1004,7 @@ class CuVSDenseIndex:
eligible_count = resolved.eligible_count
native_threshold = resolved.native_threshold
route_native = resolved.route_native
- if route_native:
+ if route_native or eligible_count == 0:
prepared = None
else:
prepare_filter_words = getattr(self._runtime, "prepare_filter_words", None)
@@ -617,16 +1013,21 @@ class CuVSDenseIndex:
else:
prepared = tuple(
bool(resolved.bitset_words[row // 32] & (1 << (row % 32)))
- for row in range(len(self._labels))
+ for row in range(len(labels))
)
else:
mask = [
matches_filter(self._records[label].fields, filters, self.field_types)
- for label in self._labels
+ for label in labels
]
- prepare_filter = getattr(self._runtime, "prepare_filter", None)
- prepared = prepare_filter(mask) if prepare_filter is not None else tuple(mask)
eligible_count = sum(mask)
+ prepare_filter = getattr(self._runtime, "prepare_filter", None)
+ if eligible_count == 0:
+ prepared = None
+ elif prepare_filter is not None:
+ prepared = prepare_filter(mask)
+ else:
+ prepared = tuple(mask)
route_native = False
native_threshold = 0
cached = _CachedFilter(
@@ -634,85 +1035,213 @@ class CuVSDenseIndex:
eligible_count=eligible_count,
route_native=route_native,
native_threshold=native_threshold,
+ native_filter_token=(
+ resolved_native_filter.native_filter_token
+ if resolved_native_filter is not None
+ else 0
+ ),
)
self._cache_filter(cache_key, cached)
return cached
- def _rebuild_if_needed(
+ def prepare_rebuild(
+ self,
+ telemetry: Optional[CuVSSearchTelemetry] = None,
+ ) -> Optional[_CuVSBuildCandidate]:
+ with self._lock:
+ if not self._dirty:
+ return None
+ labels = tuple(self._records)
+ generation = self._records_generation
+ dataset = [self._records[label].vector for label in labels]
+ can_release_unused = self._active_searches == 0
+ if can_release_unused:
+ with self._runtime_device_scope():
+ self._snapshot = None
+
+ build_started = time.perf_counter()
+ try:
+ if not labels:
+ return _CuVSBuildCandidate(
+ runtime_index=None,
+ labels=labels,
+ generation=generation,
+ )
+ with _CUVS_MEMORY_COORDINATOR.build_lock(self._runtime):
+ if self.auto_memory:
+ release_index = getattr(self._runtime, "release_index", None)
+ if release_index is not None and can_release_unused:
+ release_index()
+ estimate = estimate_cuvs_memory(
+ vector_count=len(labels),
+ dimension=self.dimension,
+ algorithm=self.algorithm,
+ build_params=self._build_params,
+ filter_cache_size=self.filter_cache_size,
+ safety_factor=self.auto_memory_safety_factor,
+ dtype=self.dtype,
+ )
+ if telemetry is not None:
+ telemetry.memory_estimated_peak_bytes = estimate.estimated_peak_bytes
+ try:
+ free_bytes, total_bytes = self._runtime.memory_info()
+ except Exception as exc:
+ raise CuVSMemoryBudgetError(
+ "cuVS auto mode could not read free GPU memory"
+ ) from exc
+ usable_bytes = max(0, free_bytes - self.auto_memory_reserve_bytes)
+ if telemetry is not None:
+ telemetry.memory_free_bytes = free_bytes
+ telemetry.memory_usable_bytes = usable_bytes
+ if estimate.estimated_peak_bytes > usable_bytes:
+ raise CuVSMemoryBudgetError(
+ "cuVS auto mode kept native search because the estimated GPU peak "
+ f"({estimate.estimated_peak_bytes} bytes) exceeds the usable free "
+ f"memory ({usable_bytes} of {total_bytes} bytes after reserve)"
+ )
+ try:
+ if telemetry is not None:
+ telemetry.build_performed = True
+ runtime_index = self._runtime.build(dataset)
+ except Exception as exc:
+ is_out_of_memory = getattr(self._runtime, "is_out_of_memory", None)
+ if self.auto_memory and is_out_of_memory is not None and is_out_of_memory(exc):
+ release_index = getattr(self._runtime, "release_index", None)
+ if release_index is not None and can_release_unused:
+ release_index()
+ raise CuVSMemoryBudgetError(
+ "cuVS auto mode fell back to native search after a GPU "
+ "allocation failure"
+ ) from exc
+ raise
+ return _CuVSBuildCandidate(
+ runtime_index=runtime_index,
+ labels=labels,
+ generation=generation,
+ )
+ finally:
+ if telemetry is not None:
+ telemetry.build_ms += (time.perf_counter() - build_started) * 1000.0
+
+ def commit_rebuild(
self,
+ candidate: _CuVSBuildCandidate,
native_filter_layout_registrar: Optional[Callable[[Sequence[int]], None]] = None,
- *,
- filter_layout_is_current: bool = False,
- ) -> None:
- if not self._dirty:
- return
- self._labels = list(self._records)
- if not self._labels:
- self._index = None
+ ) -> bool:
+ with self._lock:
+ with self._runtime_device_scope():
+ if candidate.consumed:
+ raise RuntimeError("cuVS rebuild candidate has already been consumed")
+ if self._records_generation != candidate.generation:
+ candidate.consumed = True
+ candidate.runtime_index = None
+ return False
+ if (
+ native_filter_layout_registrar is not None
+ and self._filter_layout_generation != candidate.generation
+ ):
+ try:
+ native_filter_layout_registrar(candidate.labels)
+ except Exception:
+ candidate.consumed = True
+ candidate.runtime_index = None
+ raise
+ self._filter_layout_generation = candidate.generation
+ runtime_index = candidate.runtime_index
+ candidate.consumed = True
+ candidate.runtime_index = None
+ self._snapshot = (
+ _CuVSIndexSnapshot(
+ runtime_index=runtime_index,
+ labels=candidate.labels,
+ generation=candidate.generation,
+ )
+ if runtime_index is not None
+ else None
+ )
self._dirty = False
- return
- if self.auto_memory:
- self._index = None
- release_index = getattr(self._runtime, "release_index", None)
- if release_index is not None:
- release_index()
- estimate = estimate_cuvs_memory(
- vector_count=len(self._labels),
- dimension=self.dimension,
- algorithm=self.algorithm,
- build_params=self._build_params,
- filter_cache_size=self.filter_cache_size,
- safety_factor=self.auto_memory_safety_factor,
+ logger.info(
+ "Built cuVS %s index with %d vectors",
+ self.algorithm,
+ len(candidate.labels),
)
- try:
- free_bytes, total_bytes = self._runtime.memory_info()
- except Exception as exc:
- raise CuVSMemoryBudgetError(
- "cuVS auto mode could not read free GPU memory"
- ) from exc
- usable_bytes = max(0, free_bytes - self.auto_memory_reserve_bytes)
- if estimate.estimated_peak_bytes > usable_bytes:
- raise CuVSMemoryBudgetError(
- "cuVS auto mode kept native search because the estimated GPU peak "
- f"({estimate.estimated_peak_bytes} bytes) exceeds the usable free "
- f"memory ({usable_bytes} of {total_bytes} bytes after reserve)"
- )
- dataset = [self._records[label].vector for label in self._labels]
- self._index = None
- try:
- self._index = self._runtime.build(dataset)
- except Exception as exc:
- is_out_of_memory = getattr(self._runtime, "is_out_of_memory", None)
- if self.auto_memory and is_out_of_memory is not None and is_out_of_memory(exc):
- release_index = getattr(self._runtime, "release_index", None)
- if release_index is not None:
- release_index()
- raise CuVSMemoryBudgetError(
- "cuVS auto mode fell back to native search after a GPU allocation failure"
- ) from exc
- raise
- if native_filter_layout_registrar is not None and not filter_layout_is_current:
- native_filter_layout_registrar(self._labels)
- self._dirty = False
- logger.info("Built cuVS %s index with %d vectors", self.algorithm, len(self._labels))
+ return True
+
+ def discard_rebuild(self, candidate: _CuVSBuildCandidate) -> None:
+ """Release an uncommitted GPU build candidate on the runtime device."""
+
+ with self._lock:
+ with self._runtime_device_scope():
+ if candidate.consumed:
+ return
+ candidate.consumed = True
+ candidate.runtime_index = None
+
+ def _rebuild_if_needed(
+ self,
+ native_filter_layout_registrar: Optional[Callable[[Sequence[int]], None]] = None,
+ telemetry: Optional[CuVSSearchTelemetry] = None,
+ ) -> None:
+ while self.needs_rebuild:
+ candidate = self.prepare_rebuild(telemetry)
+ if candidate is None:
+ return
+ if self.commit_rebuild(candidate, native_filter_layout_registrar):
+ return
def search(
self,
query_vector: Sequence[float],
limit: int,
filters: Optional[Mapping[str, Any]],
- native_filter_resolver: Optional[
- Callable[[Mapping[str, Any]], Tuple[Sequence[int], int]]
- ] = None,
+ native_filter_resolver: Optional[NativeFilterResolver] = None,
native_filter_layout_registrar: Optional[Callable[[Sequence[int]], None]] = None,
+ telemetry: Optional[CuVSSearchTelemetry] = None,
) -> Tuple[List[int], List[float]]:
if limit <= 0:
return [], []
+ queue_started = time.perf_counter()
+ self._gpu_search_gate.acquire()
+ if telemetry is not None:
+ telemetry.queue_ms += (time.perf_counter() - queue_started) * 1000.0
+ try:
+ return self._search_admitted(
+ query_vector,
+ limit,
+ filters,
+ native_filter_resolver,
+ native_filter_layout_registrar,
+ telemetry,
+ )
+ finally:
+ self._gpu_search_gate.release()
+
+ def _search_admitted(
+ self,
+ query_vector: Sequence[float],
+ limit: int,
+ filters: Optional[Mapping[str, Any]],
+ native_filter_resolver: Optional[NativeFilterResolver] = None,
+ native_filter_layout_registrar: Optional[Callable[[Sequence[int]], None]] = None,
+ telemetry: Optional[CuVSSearchTelemetry] = None,
+ ) -> Tuple[List[int], List[float]]:
query = self._prepare_vector(query_vector)
+ if self.auto_memory and native_filter_layout_registrar is not None:
+ self._ensure_native_filter_layout(native_filter_layout_registrar)
with self._lock:
+ if telemetry is not None:
+ telemetry.filter_kind = (
+ "path"
+ if filters and _filter_uses_field_type(filters, self.field_types, "path")
+ else "scalar"
+ if filters
+ else "none"
+ )
+ telemetry.records_generation = self._records_generation
+ telemetry.index_size = len(self._records)
cached_filter: Optional[_CachedFilter] = None
resolved_native_filter: Optional[_ResolvedNativeFilter] = None
- filter_layout_is_current = False
+ filter_layout_is_current = self._filter_layout_generation == self._records_generation
# Auto mode decides whether a selective filter should remain native
# before paying GPU admission or rebuild costs. A dirty native
@@ -721,13 +1250,26 @@ class CuVSDenseIndex:
if filters and self.auto_memory and native_filter_resolver is not None:
cache_key = self._filter_cache_key(filters)
cached_filter = self._get_cached_filter(cache_key)
+ if cached_filter is not None and telemetry is not None:
+ telemetry.filter_cache_hit = True
+ telemetry.eligible_count = cached_filter.eligible_count
if cached_filter is None:
- if self._dirty and native_filter_layout_registrar is not None:
- native_filter_layout_registrar(list(self._records))
- filter_layout_is_current = True
- resolved_native_filter = self._resolve_native_filter(
- filters, native_filter_resolver
- )
+ resolved_native_filter = self._get_preflight_filter(cache_key)
+ if resolved_native_filter is not None and telemetry is not None:
+ telemetry.filter_cache_hit = True
+ telemetry.eligible_count = resolved_native_filter.eligible_count
+ if resolved_native_filter is None:
+ if (
+ self._dirty
+ and native_filter_layout_registrar is not None
+ and not filter_layout_is_current
+ ):
+ native_filter_layout_registrar(list(self._records))
+ filter_layout_is_current = True
+ self._filter_layout_generation = self._records_generation
+ resolved_native_filter = self._resolve_native_filter(
+ filters, native_filter_resolver
+ )
if (
resolved_native_filter.route_native
or resolved_native_filter.eligible_count == 0
@@ -737,6 +1279,7 @@ class CuVSDenseIndex:
eligible_count=resolved_native_filter.eligible_count,
route_native=resolved_native_filter.route_native,
native_threshold=resolved_native_filter.native_threshold,
+ native_filter_token=resolved_native_filter.native_filter_token,
)
self._cache_filter(cache_key, cached_filter)
@@ -752,18 +1295,28 @@ class CuVSDenseIndex:
self._rebuild_if_needed(
native_filter_layout_registrar,
- filter_layout_is_current=filter_layout_is_current,
+ telemetry=telemetry,
)
- if self._index is None:
+ snapshot = self._snapshot
+ if snapshot is None:
return [], []
mask: Optional[Any] = None
if filters:
+ filter_started = time.perf_counter()
+ if cached_filter is None:
+ cached_filter = self._get_cached_filter(self._filter_cache_key(filters))
+ if cached_filter is not None and telemetry is not None:
+ telemetry.filter_cache_hit = True
cached_filter = cached_filter or self._prepare_filter(
filters,
+ snapshot.labels,
native_filter_resolver,
resolved_native_filter,
)
+ if telemetry is not None:
+ telemetry.filter_prepare_ms += (time.perf_counter() - filter_started) * 1000.0
+ telemetry.eligible_count = cached_filter.eligible_count
mask = cached_filter.prepared
eligible_count = cached_filter.eligible_count
if eligible_count == 0:
@@ -776,21 +1329,52 @@ class CuVSDenseIndex:
)
result_limit = min(limit, eligible_count)
else:
- result_limit = min(limit, len(self._labels))
+ result_limit = min(limit, len(snapshot.labels))
+ self._active_searches += 1
- offsets, distances = self._runtime.search(self._index, query, result_limit, mask)
- labels: List[int] = []
- scores: List[float] = []
+ labels: List[int] = []
+ scores: List[float] = []
+ try:
+ gpu_started = time.perf_counter()
+ try:
+ offsets, distances = self._runtime.search(
+ snapshot.runtime_index,
+ query,
+ result_limit,
+ mask,
+ )
+ finally:
+ if telemetry is not None:
+ telemetry.gpu_search_ms += (time.perf_counter() - gpu_started) * 1000.0
for offset, distance in zip(offsets, distances, strict=True):
- if offset < 0 or offset >= len(self._labels):
+ if offset < 0 or offset >= len(snapshot.labels):
continue
- labels.append(self._labels[offset])
+ labels.append(snapshot.labels[offset])
scores.append(1.0 - distance if self.distance == "l2" else distance)
- return labels, scores
+ finally:
+ try:
+ # A concurrent rebuild can remove the index/cache's owning
+ # references while this search still holds its immutable snapshot
+ # and prepared filter. Release those last local references before
+ # advertising the search as idle or restoring another CUDA device.
+ with self._runtime_device_scope():
+ mask = None
+ cached_filter = None
+ resolved_native_filter = None
+ snapshot = None
+ finally:
+ with self._lock:
+ self._active_searches -= 1
+ if self._active_searches == 0:
+ self._idle_condition.notify_all()
+ return labels, scores
def close(self) -> None:
with self._lock:
- self._index = None
- self._labels = []
- self._filter_cache.clear()
- self._runtime.close()
+ while self._active_searches:
+ self._idle_condition.wait()
+ with self._runtime_device_scope():
+ self._snapshot = None
+ self._filter_cache.clear()
+ self._preflight_filter_cache.clear()
+ self._runtime.close()
diff --git a/openviking/storage/vectordb/index/local_index.py b/openviking/storage/vectordb/index/local_index.py
index 7804f136f..f5e443d03 100644
--- a/openviking/storage/vectordb/index/local_index.py
+++ b/openviking/storage/vectordb/index/local_index.py
@@ -1,19 +1,22 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
import json
+import logging
import math
import os
import shutil
import threading
import time
+from contextlib import contextmanager
from pathlib import Path
-from typing import Any, Dict, List, Optional, Tuple, Union
+from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
import openviking.storage.vectordb.engine as engine
from openviking.storage.vectordb.index.cuvs_index import (
CuVSDenseIndex,
CuVSMemoryBudgetError,
CuVSNativeRouteError,
+ CuVSSearchTelemetry,
CuVSUnavailableError,
UnsupportedCuVSFilterError,
)
@@ -52,6 +55,51 @@ def normalize_vector(vector: List[float]) -> List[float]:
return [x / norm for x in vector]
+class _ReadWriteLock:
+ """Writer-preferring lock for atomic mutation and concurrent warmed reads."""
+
+ def __init__(self):
+ self._condition = threading.Condition(threading.Lock())
+ self._readers = 0
+ self._writer = False
+ self._waiting_writers = 0
+
+ @contextmanager
+ def read(self) -> Iterator[None]:
+ with self._condition:
+ while self._writer or self._waiting_writers:
+ self._condition.wait()
+ self._readers += 1
+ try:
+ yield
+ finally:
+ with self._condition:
+ self._readers -= 1
+ if self._readers == 0:
+ self._condition.notify_all()
+
+ @contextmanager
+ def write(self) -> Iterator[None]:
+ with self._condition:
+ self._waiting_writers += 1
+ try:
+ while self._writer or self._readers:
+ self._condition.wait()
+ self._writer = True
+ finally:
+ self._waiting_writers -= 1
+ try:
+ yield
+ finally:
+ with self._condition:
+ self._writer = False
+ self._condition.notify_all()
+
+
+class _CuVSBackgroundRebuildPending(Exception):
+ """Internal signal used to route a dirty background index to native search."""
+
+
class IndexEngineProxy:
"""Proxy wrapper for the underlying index engine with vector normalization support.
@@ -112,6 +160,24 @@ class IndexEngineProxy:
scores = search_result.scores
return labels, scores
+ def search_with_filter_token(
+ self,
+ query_vector: List[float],
+ limit: int,
+ filter_token: int,
+ ) -> Optional[Tuple[List[int], List[float]]]:
+ """Reuse a native scalar bitmap when the engine still owns its token."""
+
+ if not self.index_engine or filter_token <= 0:
+ return None
+ req = engine.SearchRequest()
+ req.query = normalize_vector(query_vector) if self.normalize_vector_flag else query_vector
+ req.topk = limit
+ search_result = self.index_engine.search_with_filter_token(req, filter_token)
+ if search_result is None:
+ return None
+ return search_result.labels, search_result.scores
+
def add_data(self, cands_list: List[CandidateData]):
if not self.index_engine:
raise RuntimeError("Index engine not initialized")
@@ -195,13 +261,20 @@ class IndexEngineProxy:
if result != 0:
raise RuntimeError("Failed to register native scalar filter layout")
- def evaluate_filter(self, filters: Dict[str, Any]) -> Tuple[List[int], int]:
+ def evaluate_filter(
+ self,
+ filters: Dict[str, Any],
+ max_cached_candidates: int = 0,
+ ) -> Tuple[List[int], int, int]:
"""Evaluate a native scalar filter in the registered dense-index row order."""
if not self.index_engine:
raise RuntimeError("Index engine not initialized")
- result = self.index_engine.evaluate_filter(json.dumps(filters))
- return result.bitset_words, result.eligible_count
+ result = self.index_engine.evaluate_filter(
+ json.dumps(filters),
+ max_cached_candidates=max_cached_candidates,
+ )
+ return result.bitset_words, result.eligible_count, result.native_filter_token
def drop(self):
"""Release the index engine resources.
@@ -235,12 +308,17 @@ class LocalIndex(IIndex):
meta: Any,
dense_search_config: Optional[Dict[str, Any]] = None,
initial_candidates: Optional[List[CandidateData]] = None,
+ defer_dense_rebuild_start: bool = False,
):
"""Initialize a local index instance.
Args:
index_path_or_json (str): Path to index files or JSON configuration
meta: Index metadata object containing configuration
+ dense_search_config: Optional dense-search backend configuration.
+ initial_candidates: Records used to initialize the dense-search shadow state.
+ defer_dense_rebuild_start: Delay the background rebuild worker until the
+ caller has finished initializing the native index.
"""
# Get the vector normalization flag from meta
normalize_vector_flag = meta.inner_meta.get("VectorIndex", {}).get("NormalizeVector", False)
@@ -250,8 +328,19 @@ class LocalIndex(IIndex):
self.meta = meta
self.field_type_converter = DataProcessor(self.meta.collection_meta.fields_dict)
self.dense_search: Optional[CuVSDenseIndex] = None
- self._dense_search_lock = threading.RLock()
+ self._dense_search_lock = _ReadWriteLock()
self._auto_cuvs = False
+ self._auto_background_rebuild = False
+ self._dense_rebuild_debounce_seconds = 0.0
+ self._dense_rebuild_event = threading.Event()
+ self._dense_rebuild_completed = threading.Event()
+ self._dense_rebuild_stop = threading.Event()
+ self._dense_rebuild_state_lock = threading.Lock()
+ self._dense_rebuild_generation = 0
+ self._dense_rebuild_debounce_deadline = 0.0
+ self._dense_rebuild_failure: Optional[Tuple[type[Exception], str]] = None
+ self._dense_rebuild_memory_blocked = False
+ self._dense_rebuild_thread: Optional[threading.Thread] = None
dense_search_config = dict(dense_search_config or {})
dense_search_backend = dense_search_config.get("backend")
if dense_search_backend in {"cuvs", "auto_cuvs"}:
@@ -271,11 +360,19 @@ class LocalIndex(IIndex):
auto_memory=self._auto_cuvs,
)
self.dense_search.add_candidates(initial_candidates or [])
+ self._auto_background_rebuild = self._auto_cuvs and bool(
+ dense_search_config.get("auto_background_rebuild", False)
+ )
+ self._dense_rebuild_debounce_seconds = (
+ max(0, int(dense_search_config.get("auto_rebuild_debounce_ms", 500))) / 1000.0
+ )
except CuVSUnavailableError:
if not self._auto_cuvs:
raise
logger.info("cuVS auto mode unavailable; keeping native dense search")
self.dense_search = None
+ if not defer_dense_rebuild_start:
+ self._start_dense_rebuild_worker()
def update(
self,
@@ -296,22 +393,182 @@ class LocalIndex(IIndex):
def upsert_data(self, delta_list: List[DeltaRecord]):
if self.dense_search:
- with self._dense_search_lock:
+ with self._dense_search_lock.write():
if self.engine_proxy:
self.engine_proxy.upsert_data(self._convert_delta_list_for_index(delta_list))
self.dense_search.upsert(delta_list)
+ self._schedule_dense_rebuild()
elif self.engine_proxy:
self.engine_proxy.upsert_data(self._convert_delta_list_for_index(delta_list))
def delete_data(self, delta_list: List[DeltaRecord]):
if self.dense_search:
- with self._dense_search_lock:
+ with self._dense_search_lock.write():
if self.engine_proxy:
self.engine_proxy.delete_data(self._convert_delta_list_for_index(delta_list))
self.dense_search.delete(delta_list)
+ self._schedule_dense_rebuild()
elif self.engine_proxy:
self.engine_proxy.delete_data(self._convert_delta_list_for_index(delta_list))
+ def _schedule_dense_rebuild(self) -> None:
+ if not self._auto_background_rebuild or self.dense_search is None:
+ return
+ with self._dense_rebuild_state_lock:
+ self._dense_rebuild_generation += 1
+ self._dense_rebuild_debounce_deadline = (
+ time.monotonic() + self._dense_rebuild_debounce_seconds
+ )
+ self._dense_rebuild_failure = None
+ self._dense_rebuild_memory_blocked = False
+ self._dense_rebuild_completed.clear()
+ self._dense_rebuild_event.set()
+
+ def _start_dense_rebuild_worker(self) -> None:
+ """Start the worker once native and dense initial state are aligned."""
+
+ if (
+ not self._auto_background_rebuild
+ or self.dense_search is None
+ or self._dense_rebuild_thread is not None
+ or self._dense_rebuild_stop.is_set()
+ ):
+ return
+ self._dense_rebuild_thread = threading.Thread(
+ target=self._dense_rebuild_loop,
+ name="openviking-cuvs-rebuild",
+ daemon=True,
+ )
+ self._dense_rebuild_thread.start()
+ self._schedule_dense_rebuild()
+
+ def _wake_dense_rebuild_worker(self) -> None:
+ """Wake the worker without extending the mutation debounce window."""
+
+ if not self._auto_background_rebuild or self.dense_search is None:
+ return
+ with self._dense_rebuild_state_lock:
+ self._dense_rebuild_memory_blocked = False
+ self._dense_rebuild_completed.clear()
+ self._dense_rebuild_event.set()
+
+ def _retry_memory_blocked_rebuild(self) -> bool:
+ """Let the first later query retry an expected memory-budget fallback."""
+
+ if not self._auto_background_rebuild or self.dense_search is None:
+ return False
+ with self._dense_rebuild_state_lock:
+ if not self._dense_rebuild_memory_blocked:
+ return False
+ self._dense_rebuild_memory_blocked = False
+ self._dense_rebuild_completed.clear()
+ self._dense_rebuild_event.set()
+ return True
+
+ def _raise_dense_rebuild_failure(self) -> None:
+ with self._dense_rebuild_state_lock:
+ failure = self._dense_rebuild_failure
+ if failure is not None:
+ error_type, message = failure
+ try:
+ error = error_type(message)
+ except Exception:
+ error = RuntimeError(f"{error_type.__name__}: {message}")
+ raise error
+
+ def _dense_rebuild_loop(self) -> None:
+ while True:
+ self._dense_rebuild_event.wait()
+ if self._dense_rebuild_stop.is_set():
+ return
+ self._dense_rebuild_event.clear()
+
+ while self._dense_rebuild_debounce_seconds > 0:
+ with self._dense_rebuild_state_lock:
+ remaining = self._dense_rebuild_debounce_deadline - time.monotonic()
+ if remaining <= 0:
+ break
+ changed = self._dense_rebuild_event.wait(timeout=remaining)
+ if not changed:
+ break
+ self._dense_rebuild_event.clear()
+ if self._dense_rebuild_stop.is_set():
+ return
+
+ with self._dense_rebuild_state_lock:
+ rebuild_generation = self._dense_rebuild_generation
+ try:
+ committed = self._run_background_rebuild()
+ except CuVSMemoryBudgetError as exc:
+ with self._dense_rebuild_state_lock:
+ if self._dense_rebuild_generation == rebuild_generation:
+ self._dense_rebuild_failure = None
+ self._dense_rebuild_memory_blocked = True
+ logger.debug("cuVS background rebuild kept native search: %s", exc)
+ except Exception as exc:
+ with self._dense_rebuild_state_lock:
+ if self._dense_rebuild_generation == rebuild_generation:
+ self._dense_rebuild_failure = (type(exc), str(exc))
+ self._dense_rebuild_memory_blocked = False
+ logger.warning("cuVS background rebuild failed", exc_info=True)
+ else:
+ if committed:
+ with self._dense_rebuild_state_lock:
+ if self._dense_rebuild_generation == rebuild_generation:
+ self._dense_rebuild_failure = None
+ self._dense_rebuild_memory_blocked = False
+ finally:
+ self._dense_rebuild_completed.set()
+
+ def _run_background_rebuild(self) -> bool:
+ dense_search = self.dense_search
+ if dense_search is None or self.engine_proxy is None:
+ return False
+ candidate = dense_search.prepare_rebuild()
+ if candidate is None:
+ return not dense_search.needs_rebuild
+ if self._dense_rebuild_stop.is_set():
+ dense_search.discard_rebuild(candidate)
+ return False
+ with self._dense_search_lock.write():
+ if (
+ self.dense_search is not dense_search
+ or self.engine_proxy is None
+ or self._dense_rebuild_stop.is_set()
+ ):
+ dense_search.discard_rebuild(candidate)
+ return False
+ committed = dense_search.commit_rebuild(
+ candidate,
+ self.engine_proxy.set_filter_layout,
+ )
+ if not committed:
+ self._wake_dense_rebuild_worker()
+ return committed
+
+ def _stop_dense_rebuild_worker(self) -> None:
+ thread = self._dense_rebuild_thread
+ if thread is None:
+ return
+ self._dense_rebuild_stop.set()
+ self._dense_rebuild_event.set()
+ thread.join()
+ self._dense_rebuild_thread = None
+
+ def wait_for_background_rebuild(self, timeout: float = 5.0) -> bool:
+ if not self._auto_background_rebuild:
+ return False
+ deadline = time.monotonic() + max(0.0, timeout)
+ while self.dense_search is not None and self.dense_search.needs_rebuild:
+ self._raise_dense_rebuild_failure()
+ if not self._retry_memory_blocked_rebuild():
+ self._wake_dense_rebuild_worker()
+ remaining = deadline - time.monotonic()
+ if remaining <= 0 or not self._dense_rebuild_completed.wait(remaining):
+ return False
+ self._raise_dense_rebuild_failure()
+ return self.dense_search is not None
+
def search(
self,
query_vector: Optional[List[float]],
@@ -332,36 +589,259 @@ class LocalIndex(IIndex):
if self.field_type_converter and filters is not None:
filters = self.field_type_converter.convert_filter_for_index(filters)
- if self.dense_search and query_vector:
- with self._dense_search_lock:
+ cuvs_telemetry: Optional[CuVSSearchTelemetry] = None
+ telemetry_started = 0.0
+ native_filter_token = 0
+ if self.dense_search and query_vector and self._cuvs_telemetry_enabled():
+ cuvs_telemetry = CuVSSearchTelemetry(
+ algorithm=self.dense_search.algorithm,
+ auto_mode=self._auto_cuvs,
+ dtype=self.dense_search.dtype,
+ max_concurrent_gpu_searches=(self.dense_search.max_concurrent_gpu_searches),
+ )
+ telemetry_started = time.perf_counter()
+
+ try:
+ if self.dense_search and query_vector:
if not sparse_raw_terms and not sparse_values:
+ background_rebuild_pending = (
+ self._auto_background_rebuild and self.dense_search.needs_rebuild
+ )
+ if background_rebuild_pending:
+ self._raise_dense_rebuild_failure()
+ self._retry_memory_blocked_rebuild()
+ if cuvs_telemetry is not None:
+ cuvs_telemetry.route_reason = "native_rebuild_pending"
+ return self._search_native(
+ query_vector,
+ limit,
+ filters,
+ sparse_raw_terms,
+ sparse_values,
+ 0,
+ cuvs_telemetry,
+ )
+ if self._auto_cuvs and filters:
+ queue_started = time.perf_counter()
+ with self._dense_search_lock.read():
+ if cuvs_telemetry is not None:
+ cuvs_telemetry.queue_ms += (
+ time.perf_counter() - queue_started
+ ) * 1000.0
+ native_count = self.dense_search.preflight_native_count(
+ filters,
+ self._evaluate_cuvs_filter,
+ self.engine_proxy.set_filter_layout,
+ telemetry=cuvs_telemetry,
+ )
+ if native_count == 0:
+ if cuvs_telemetry is not None:
+ cuvs_telemetry.route_reason = "empty_filter"
+ return [], []
+ if native_count is not None:
+ if cuvs_telemetry is not None:
+ cuvs_telemetry.route_reason = "native_filter_threshold"
+ native_filter_token = self.dense_search.native_filter_token(
+ filters
+ )
+ logger.debug(
+ "cuVS auto mode selected native filtered search "
+ "(%d candidates)",
+ native_count,
+ )
+ return self._search_native(
+ query_vector,
+ limit,
+ filters,
+ sparse_raw_terms,
+ sparse_values,
+ native_filter_token,
+ cuvs_telemetry,
+ )
try:
- return self.dense_search.search(
+ result = self._search_cuvs(
query_vector,
limit,
filters,
- self.engine_proxy.evaluate_filter,
- self.engine_proxy.set_filter_layout,
+ cuvs_telemetry,
)
+ if cuvs_telemetry is not None:
+ cuvs_telemetry.route_reason = "cuvs"
+ return result
except CuVSMemoryBudgetError as exc:
+ if cuvs_telemetry is not None:
+ cuvs_telemetry.route_reason = "native_memory_budget"
if not self._auto_cuvs:
raise
logger.debug("cuVS auto mode kept native dense search: %s", exc)
+ except _CuVSBackgroundRebuildPending:
+ if cuvs_telemetry is not None:
+ cuvs_telemetry.route_reason = "native_rebuild_pending"
except CuVSNativeRouteError as exc:
+ if cuvs_telemetry is not None:
+ cuvs_telemetry.route_reason = "native_filter_threshold"
+ native_filter_token = self.dense_search.native_filter_token(filters)
logger.debug("cuVS auto mode selected native dense search: %s", exc)
except UnsupportedCuVSFilterError as exc:
+ if cuvs_telemetry is not None:
+ cuvs_telemetry.route_reason = "native_unsupported_filter"
if not self.dense_search.fallback_to_native:
raise
logger.debug("Falling back to native dense search: %s", exc)
elif not self.dense_search.fallback_to_native:
+ if cuvs_telemetry is not None:
+ cuvs_telemetry.route_reason = "unsupported_sparse_hybrid"
raise ValueError(
"cuVS dense search does not support OpenViking sparse/hybrid queries"
)
+ else:
+ if cuvs_telemetry is not None:
+ cuvs_telemetry.route_reason = "native_sparse_hybrid"
+
+ return self._search_native(
+ query_vector,
+ limit,
+ filters,
+ sparse_raw_terms,
+ sparse_values,
+ native_filter_token,
+ cuvs_telemetry,
+ )
+ except Exception:
+ if cuvs_telemetry is not None and cuvs_telemetry.route_reason == "pending":
+ cuvs_telemetry.route_reason = "cuvs_error"
+ raise
+ finally:
+ if cuvs_telemetry is not None:
+ cuvs_telemetry.total_ms += (time.perf_counter() - telemetry_started) * 1000.0
+ self._record_cuvs_telemetry(cuvs_telemetry)
+ return [], []
+ def _search_cuvs(
+ self,
+ query_vector: List[float],
+ limit: int,
+ filters: Dict[str, Any],
+ telemetry: Optional[CuVSSearchTelemetry],
+ ) -> Tuple[List[int], List[float]]:
+ if self.dense_search is None or self.engine_proxy is None:
+ raise RuntimeError("cuVS search requires an initialized index")
+ if self._auto_background_rebuild:
+ queue_started = time.perf_counter()
+ with self._dense_search_lock.read():
+ if telemetry is not None:
+ telemetry.queue_ms += (time.perf_counter() - queue_started) * 1000.0
+ if self.dense_search.needs_rebuild:
+ self._raise_dense_rebuild_failure()
+ self._retry_memory_blocked_rebuild()
+ raise _CuVSBackgroundRebuildPending
+ return self.dense_search.search(
+ query_vector,
+ limit,
+ filters,
+ self._evaluate_cuvs_filter,
+ self.engine_proxy.set_filter_layout,
+ telemetry=telemetry,
+ )
+ while True:
+ queue_started = time.perf_counter()
+ with self._dense_search_lock.read():
+ if telemetry is not None:
+ telemetry.queue_ms += (time.perf_counter() - queue_started) * 1000.0
+ if not self.dense_search.needs_rebuild:
+ return self.dense_search.search(
+ query_vector,
+ limit,
+ filters,
+ self._evaluate_cuvs_filter,
+ self.engine_proxy.set_filter_layout,
+ telemetry=telemetry,
+ )
+
+ queue_started = time.perf_counter()
+ with self._dense_search_lock.write():
+ if telemetry is not None:
+ telemetry.queue_ms += (time.perf_counter() - queue_started) * 1000.0
+ if self.dense_search.needs_rebuild:
+ return self.dense_search.search(
+ query_vector,
+ limit,
+ filters,
+ self._evaluate_cuvs_filter,
+ self.engine_proxy.set_filter_layout,
+ telemetry=telemetry,
+ )
+
+ def _search_native(
+ self,
+ query_vector: List[float],
+ limit: int,
+ filters: Dict[str, Any],
+ sparse_raw_terms: List[str],
+ sparse_values: List[float],
+ native_filter_token: int,
+ telemetry: Optional[CuVSSearchTelemetry],
+ ) -> Tuple[List[int], List[float]]:
+ if self.engine_proxy is None:
+ return [], []
+ native_started = time.perf_counter()
+ try:
+ if native_filter_token:
+ token_result = self.engine_proxy.search_with_filter_token(
+ query_vector,
+ limit,
+ native_filter_token,
+ )
+ if token_result is not None:
+ if telemetry is not None:
+ telemetry.native_filter_reused = True
+ return token_result
return self.engine_proxy.search(
- query_vector, limit, filters, sparse_raw_terms, sparse_values
+ query_vector,
+ limit,
+ filters,
+ sparse_raw_terms,
+ sparse_values,
)
- return [], []
+ finally:
+ if telemetry is not None:
+ telemetry.native_search_ms += (time.perf_counter() - native_started) * 1000.0
+ if telemetry.route_reason == "pending":
+ telemetry.route_reason = "native_fallback"
+
+ def _evaluate_cuvs_filter(self, filters: Dict[str, Any]) -> Tuple[List[int], int, int]:
+ if self.dense_search is None or self.engine_proxy is None:
+ raise RuntimeError("cuVS filter evaluation requires an initialized index")
+ return self.engine_proxy.evaluate_filter(
+ filters,
+ max_cached_candidates=self.dense_search.native_filter_threshold(filters),
+ )
+
+ @staticmethod
+ def _cuvs_telemetry_enabled() -> bool:
+ if logger.isEnabledFor(logging.DEBUG):
+ return True
+ try:
+ from openviking.telemetry import get_current_telemetry
+
+ return bool(get_current_telemetry().enabled)
+ except Exception:
+ return False
+
+ @staticmethod
+ def _record_cuvs_telemetry(telemetry: CuVSSearchTelemetry) -> None:
+ payload = telemetry.as_dict()
+ if logger.isEnabledFor(logging.DEBUG):
+ logger.debug("cuVS search telemetry: %s", json.dumps(payload, sort_keys=True))
+ try:
+ from openviking.telemetry import get_current_telemetry
+
+ operation_telemetry = get_current_telemetry()
+ if not operation_telemetry.enabled:
+ return
+ operation_telemetry.record_cuvs_search(payload)
+ except Exception:
+ logger.debug("Failed to record cuVS search telemetry", exc_info=True)
def aggregate(
self,
@@ -405,15 +885,19 @@ class LocalIndex(IIndex):
return agg_data
def close(self):
+ self._stop_dense_rebuild_worker()
if self.dense_search:
- self.dense_search.close()
- self.dense_search = None
+ with self._dense_search_lock.write():
+ self.dense_search.close()
+ self.dense_search = None
return None
def drop(self):
+ self._stop_dense_rebuild_worker()
if self.dense_search:
- self.dense_search.close()
- self.dense_search = None
+ with self._dense_search_lock.write():
+ self.dense_search.close()
+ self.dense_search = None
if self.engine_proxy:
self.engine_proxy.drop()
self.meta = None
@@ -539,8 +1023,12 @@ class VolatileIndex(LocalIndex):
meta,
dense_search_config=dense_search_config,
initial_candidates=cands_list,
+ defer_dense_rebuild_start=True,
)
self.engine_proxy.add_data(self._convert_candidate_list_for_index(cands_list))
+ # Native add_data() invalidates its filter layout, so publish the first
+ # dense snapshot only after the native records are present.
+ self._start_dense_rebuild_worker()
def need_rebuild(self) -> bool:
"""Determine if rebuild is needed.
@@ -606,6 +1094,7 @@ class PersistentIndex(LocalIndex):
force_rebuild: bool = False,
initial_timestamp: Optional[int] = None,
dense_search_config: Optional[Dict[str, Any]] = None,
+ defer_dense_rebuild_start: bool = False,
):
"""Initialize a persistent index with versioning support.
@@ -621,6 +1110,9 @@ class PersistentIndex(LocalIndex):
Defaults to False.
initial_timestamp (Optional[int]): Timestamp to use if creating a new index
from scratch. If None, uses current time. Useful for recovery scenarios.
+ dense_search_config: Optional dense-search backend configuration.
+ defer_dense_rebuild_start: Delay the background rebuild worker until
+ collection-level recovery has replayed all pending deltas.
Process:
1. Create directory structure if not exists
@@ -655,8 +1147,10 @@ class PersistentIndex(LocalIndex):
meta,
dense_search_config=dense_search_config,
initial_candidates=cands_list,
+ defer_dense_rebuild_start=True,
)
- # Remove scheduling logic, unified scheduling by collection layer
+ if not defer_dense_rebuild_start:
+ self._start_dense_rebuild_worker()
def _create_new_index(
self,
@@ -703,6 +1197,8 @@ class PersistentIndex(LocalIndex):
This ensures data durability and proper resource cleanup.
After close(), the index cannot be used for further operations.
"""
+ self._stop_dense_rebuild_worker()
+
# 1. Persist latest data first
self.persist()
diff --git a/openviking/telemetry/operation.py b/openviking/telemetry/operation.py
index 95fee9d0a..c8aa649df 100644
--- a/openviking/telemetry/operation.py
+++ b/openviking/telemetry/operation.py
@@ -4,6 +4,7 @@
from __future__ import annotations
+import math
import time
from collections import defaultdict
from contextlib import contextmanager
@@ -12,6 +13,31 @@ from threading import Lock
from typing import Any, Dict, Iterator, Optional
from uuid import uuid4
+_CUVS_TIMING_FIELDS = (
+ "total_ms",
+ "preflight_ms",
+ "queue_ms",
+ "build_ms",
+ "filter_prepare_ms",
+ "gpu_search_ms",
+ "native_search_ms",
+)
+_CUVS_ROUTE_BUCKETS = {
+ "cuvs",
+ "cuvs_error",
+ "empty_filter",
+ "native_fallback",
+ "native_filter_threshold",
+ "native_memory_budget",
+ "native_rebuild_pending",
+ "native_sparse_hybrid",
+ "native_unsupported_filter",
+ "unsupported_sparse_hybrid",
+}
+_CUVS_FILTER_BUCKETS = {"none", "scalar", "path"}
+_CUVS_ALGORITHM_BUCKETS = {"brute_force", "cagra"}
+_CUVS_DTYPE_BUCKETS = {"float32", "float16"}
+
@dataclass
class TelemetrySnapshot:
@@ -41,6 +67,11 @@ class TelemetrySummaryBuilder:
"""Build normalized summary metrics from collector data."""
_PRUNED = object()
+ _PRESERVED_ZERO_METRIC_PATHS = {
+ ("vector", "cuvs", "memory", "estimated_peak_bytes_max"),
+ ("vector", "cuvs", "memory", "free_bytes_min"),
+ ("vector", "cuvs", "memory", "usable_bytes_min"),
+ }
_MEMORY_EXTRACT_STAGE_KEYS = {
"prepare_inputs_ms": "memory.extract.stage.prepare_inputs.duration_ms",
@@ -75,7 +106,7 @@ class TelemetrySummaryBuilder:
return default
try:
return int(value)
- except (TypeError, ValueError):
+ except (TypeError, ValueError, OverflowError):
return default
@staticmethod
@@ -83,9 +114,12 @@ class TelemetrySummaryBuilder:
if value is None:
return default
try:
- return round(float(value), 3)
- except (TypeError, ValueError):
+ normalized = float(value)
+ except (TypeError, ValueError, OverflowError):
return default
+ if not math.isfinite(normalized):
+ return default
+ return round(normalized, 3)
@staticmethod
def _bool(value: Any, default: bool = False) -> bool:
@@ -104,11 +138,11 @@ class TelemetrySummaryBuilder:
return default
@classmethod
- def _prune_zero_metrics(cls, value: Any) -> Any:
+ def _prune_zero_metrics(cls, value: Any, path: tuple[str, ...] = ()) -> Any:
if isinstance(value, dict):
pruned: Dict[str, Any] = {}
for key, child in value.items():
- pruned_child = cls._prune_zero_metrics(child)
+ pruned_child = cls._prune_zero_metrics(child, (*path, key))
if pruned_child is cls._PRUNED:
continue
pruned[key] = pruned_child
@@ -117,7 +151,11 @@ class TelemetrySummaryBuilder:
if isinstance(value, bool):
return value
- if isinstance(value, (int, float)) and value == 0:
+ if (
+ isinstance(value, (int, float))
+ and value == 0
+ and path not in cls._PRESERVED_ZERO_METRIC_PATHS
+ ):
return cls._PRUNED
return value
@@ -131,6 +169,30 @@ class TelemetrySummaryBuilder:
key.startswith(needle) for key in gauges
)
+ @classmethod
+ def _counter_breakdown(cls, prefix: str, counters: Dict[str, float]) -> Dict[str, int]:
+ needle = f"{prefix}."
+ return {
+ key[len(needle) :]: cls._i(value, 0)
+ for key, value in sorted(counters.items())
+ if key.startswith(needle) and cls._i(value, 0) > 0
+ }
+
+ @classmethod
+ def _cuvs_timing_summary(
+ cls, counters: Dict[str, float], gauges: Dict[str, Any]
+ ) -> Dict[str, Dict[str, float]]:
+ result: Dict[str, Dict[str, float]] = {}
+ for field in _CUVS_TIMING_FIELDS:
+ public_name = field.removesuffix("_ms")
+ total_us = cls._i(counters.get(f"vector.cuvs.timings.{field}.sum_us"), 0)
+ maximum_us = cls._i(gauges.get(f"vector.cuvs.timings.{field}.max_us"), 0)
+ total = cls._f(total_us / 1000.0, 0.0)
+ maximum = cls._f(maximum_us / 1000.0, 0.0)
+ if total or maximum:
+ result[public_name] = {"sum": total, "max": maximum}
+ return result
+
@classmethod
def _build_stage_token_summary(cls, counters: Dict[str, float]) -> Dict[str, Dict[str, Any]]:
"""Build a low-cardinality stage -> source -> token breakdown from counter keys."""
@@ -226,6 +288,42 @@ class TelemetrySummaryBuilder:
"scanned": vectors_scanned,
"scan_reason": gauges.get("vector.scan_reason", ""),
}
+ if cls._has_metric_prefix("vector.cuvs", counters, gauges):
+ cuvs_memory = {
+ public_name: cls._i(gauges[metric_key], 0)
+ for public_name, metric_key in (
+ (
+ "estimated_peak_bytes_max",
+ "vector.cuvs.memory_estimated_peak_bytes.max",
+ ),
+ ("free_bytes_min", "vector.cuvs.memory_free_bytes.min"),
+ ("usable_bytes_min", "vector.cuvs.memory_usable_bytes.min"),
+ )
+ if metric_key in gauges
+ }
+ summary["vector"]["cuvs"] = {
+ "searches": cls._i(counters.get("vector.cuvs.searches"), 0),
+ "algorithms": cls._counter_breakdown("vector.cuvs.algorithms", counters),
+ "dtypes": cls._counter_breakdown("vector.cuvs.dtypes", counters),
+ "max_concurrent_gpu_searches": cls._i(
+ gauges.get("vector.cuvs.max_concurrent_gpu_searches"), 1
+ ),
+ "auto_mode_searches": cls._i(counters.get("vector.cuvs.auto_mode_searches"), 0),
+ "routes": cls._counter_breakdown("vector.cuvs.routes", counters),
+ "filter_kinds": cls._counter_breakdown("vector.cuvs.filter_kinds", counters),
+ "filter_cache_hits": cls._i(counters.get("vector.cuvs.filter_cache_hits"), 0),
+ "native_filter_reuses": cls._i(
+ counters.get("vector.cuvs.native_filter_reuses"), 0
+ ),
+ "builds": cls._i(counters.get("vector.cuvs.builds"), 0),
+ "eligible_count_max": cls._i(gauges.get("vector.cuvs.eligible_count.max"), 0),
+ "records_generation_max": cls._i(
+ gauges.get("vector.cuvs.records_generation.max"), 0
+ ),
+ "index_size_max": cls._i(gauges.get("vector.cuvs.index_size.max"), 0),
+ "memory": cuvs_memory,
+ "timings_ms": cls._cuvs_timing_summary(counters, gauges),
+ }
if cls._has_metric_prefix("semantic_nodes", counters, gauges):
summary["semantic_nodes"] = {
@@ -321,7 +419,7 @@ class TelemetrySummaryBuilder:
):
if key not in summary:
continue
- pruned_value = cls._prune_zero_metrics(summary[key])
+ pruned_value = cls._prune_zero_metrics(summary[key], (key,))
if pruned_value is cls._PRUNED:
summary.pop(key, None)
else:
@@ -367,6 +465,95 @@ class OperationTelemetry:
def set_value(self, key: str, value: Any) -> None:
self.set(key, value)
+ @staticmethod
+ def _metric_bucket(value: Any, allowed: set[str]) -> str:
+ normalized = str(value or "").strip().lower()
+ return normalized if normalized in allowed else "other"
+
+ @staticmethod
+ def _duration_us(value: Any) -> int:
+ """Normalize a duration to integer microseconds for deterministic addition."""
+
+ try:
+ duration_ms = float(value)
+ except (TypeError, ValueError, OverflowError):
+ return 0
+ if not math.isfinite(duration_ms) or duration_ms <= 0:
+ return 0
+ duration_us = duration_ms * 1000.0
+ if not math.isfinite(duration_us):
+ return 0
+ return max(int(round(duration_us)), 0)
+
+ def record_cuvs_search(self, metrics: Dict[str, Any]) -> None:
+ """Aggregate one dense-search sample with order-independent operations."""
+
+ if not self.enabled:
+ return
+ route = self._metric_bucket(metrics.get("route_reason"), _CUVS_ROUTE_BUCKETS)
+ filter_kind = self._metric_bucket(metrics.get("filter_kind"), _CUVS_FILTER_BUCKETS)
+ algorithm = self._metric_bucket(metrics.get("algorithm"), _CUVS_ALGORITHM_BUCKETS)
+ dtype = self._metric_bucket(metrics.get("dtype"), _CUVS_DTYPE_BUCKETS)
+
+ with self._lock:
+ self._counters["vector.cuvs.searches"] += 1
+ self._counters[f"vector.cuvs.routes.{route}"] += 1
+ self._counters[f"vector.cuvs.filter_kinds.{filter_kind}"] += 1
+ self._counters[f"vector.cuvs.algorithms.{algorithm}"] += 1
+ self._counters[f"vector.cuvs.dtypes.{dtype}"] += 1
+ if TelemetrySummaryBuilder._bool(metrics.get("auto_mode"), False):
+ self._counters["vector.cuvs.auto_mode_searches"] += 1
+ if TelemetrySummaryBuilder._bool(metrics.get("filter_cache_hit"), False):
+ self._counters["vector.cuvs.filter_cache_hits"] += 1
+ if TelemetrySummaryBuilder._bool(metrics.get("native_filter_reused"), False):
+ self._counters["vector.cuvs.native_filter_reuses"] += 1
+ if TelemetrySummaryBuilder._bool(metrics.get("build_performed"), False):
+ self._counters["vector.cuvs.builds"] += 1
+
+ concurrency = max(
+ TelemetrySummaryBuilder._i(metrics.get("max_concurrent_gpu_searches"), 1), 1
+ )
+ self._gauges["vector.cuvs.max_concurrent_gpu_searches"] = max(
+ TelemetrySummaryBuilder._i(
+ self._gauges.get("vector.cuvs.max_concurrent_gpu_searches"), 1
+ ),
+ concurrency,
+ )
+ for field in ("eligible_count", "records_generation", "index_size"):
+ raw_value = metrics.get(field)
+ if raw_value is None:
+ continue
+ value = max(TelemetrySummaryBuilder._i(raw_value, 0), 0)
+ key = f"vector.cuvs.{field}.max"
+ self._gauges[key] = max(TelemetrySummaryBuilder._i(self._gauges.get(key), 0), value)
+
+ peak_raw = metrics.get("memory_estimated_peak_bytes")
+ peak = TelemetrySummaryBuilder._i(peak_raw, -1)
+ if peak_raw is not None and peak >= 0:
+ key = "vector.cuvs.memory_estimated_peak_bytes.max"
+ self._gauges[key] = max(TelemetrySummaryBuilder._i(self._gauges.get(key), 0), peak)
+ for field in ("memory_free_bytes", "memory_usable_bytes"):
+ raw_value = metrics.get(field)
+ value = TelemetrySummaryBuilder._i(raw_value, -1)
+ if raw_value is None or value < 0:
+ continue
+ key = f"vector.cuvs.{field}.min"
+ existing = self._gauges.get(key)
+ self._gauges[key] = (
+ value if existing is None else min(TelemetrySummaryBuilder._i(existing), value)
+ )
+
+ for field in _CUVS_TIMING_FIELDS:
+ value_us = self._duration_us(metrics.get(field))
+ sum_key = f"vector.cuvs.timings.{field}.sum_us"
+ max_key = f"vector.cuvs.timings.{field}.max_us"
+ self._counters[sum_key] = (
+ TelemetrySummaryBuilder._i(self._counters.get(sum_key), 0) + value_us
+ )
+ self._gauges[max_key] = max(
+ TelemetrySummaryBuilder._i(self._gauges.get(max_key), 0), value_us
+ )
+
def add_duration(self, key: str, duration_ms: float) -> None:
if not self.enabled:
return
diff --git a/openviking_cli/utils/config/vectordb_config.py b/openviking_cli/utils/config/vectordb_config.py
index 36d97e441..b6b4905c4 100644
--- a/openviking_cli/utils/config/vectordb_config.py
+++ b/openviking_cli/utils/config/vectordb_config.py
@@ -79,6 +79,13 @@ class QdrantConfig(BaseModel):
class CuVSConfig(BaseModel):
"""Configuration for GPU dense-vector search through NVIDIA cuVS."""
+ dtype: Literal["float32", "float16"] = Field(
+ default="float32",
+ description=(
+ "GPU dataset and query dtype. float16 is an opt-in direct cast and "
+ "must be benchmarked for recall; it does not change native CPU quantization."
+ ),
+ )
algorithm: Literal["brute_force", "cagra"] = Field(
default="brute_force",
description=(
@@ -147,6 +154,29 @@ class CuVSConfig(BaseModel):
"Set to zero to disable caching."
),
)
+ max_concurrent_gpu_searches: int = Field(
+ default=1,
+ ge=1,
+ description=(
+ "Maximum in-flight cuVS GPU search calls per index. Host-side filter and "
+ "snapshot work remains concurrent; increase only after hardware-specific tuning."
+ ),
+ )
+ auto_background_rebuild: bool = Field(
+ default=False,
+ description=(
+ "Build dirty auto-cuVS snapshots in a coalescing background worker. "
+ "Queries use the native index until the new GPU snapshot is committed."
+ ),
+ )
+ auto_rebuild_debounce_ms: int = Field(
+ default=500,
+ ge=0,
+ description=(
+ "Quiet period used to coalesce consecutive mutations before an auto-cuVS "
+ "background rebuild."
+ ),
+ )
model_config = {"extra": "forbid"}
diff --git a/src/abi3_engine_backend.cpp b/src/abi3_engine_backend.cpp
index 9dd76e635..6ae2ac906 100644
--- a/src/abi3_engine_backend.cpp
+++ b/src/abi3_engine_backend.cpp
@@ -1159,17 +1159,23 @@ PyObject* build_filter_result(const vdb::FilterResult& result) {
PyObject* eligible_count =
PyLong_FromUnsignedLongLong(result.eligible_count);
PyObject* bitset_words = uint32_vector_to_py(result.bitset_words);
- if (eligible_count == nullptr || bitset_words == nullptr) {
+ PyObject* native_filter_token =
+ PyLong_FromUnsignedLongLong(result.native_filter_token);
+ if (eligible_count == nullptr || bitset_words == nullptr ||
+ native_filter_token == nullptr) {
Py_XDECREF(eligible_count);
Py_XDECREF(bitset_words);
+ Py_XDECREF(native_filter_token);
Py_DECREF(payload);
return nullptr;
}
PyDict_SetItemString(payload, "eligible_count", eligible_count);
PyDict_SetItemString(payload, "bitset_words", bitset_words);
+ PyDict_SetItemString(payload, "native_filter_token", native_filter_token);
Py_DECREF(eligible_count);
Py_DECREF(bitset_words);
+ Py_DECREF(native_filter_token);
return payload;
}
@@ -1314,6 +1320,40 @@ PyObject* py_index_engine_search(PyObject*, PyObject* args) {
}
}
+PyObject* py_index_engine_search_with_filter_token(PyObject*, PyObject* args) {
+ PyObject* capsule = nullptr;
+ PyObject* request_obj = nullptr;
+ unsigned long long filter_token = 0;
+ if (!PyArg_ParseTuple(args, "OOK", &capsule, &request_obj,
+ &filter_token)) {
+ return nullptr;
+ }
+
+ auto* engine = capsule_to_ptr<vdb::IndexEngine>(capsule, kIndexCapsuleName);
+ if (engine == nullptr) {
+ return nullptr;
+ }
+
+ vdb::SearchRequest request;
+ if (!parse_search_request(request_obj, &request)) {
+ return nullptr;
+ }
+
+ try {
+ const auto result = call_without_gil([&]() {
+ return engine->search_with_filter_token(
+ request, static_cast<uint64_t>(filter_token));
+ });
+ if (!result.has_value()) {
+ Py_RETURN_NONE;
+ }
+ return build_search_result(*result);
+ } catch (const std::exception& exc) {
+ raise_runtime_error(exc.what());
+ return nullptr;
+ }
+}
+
PyObject* py_index_engine_set_filter_layout(PyObject*, PyObject* args) {
PyObject* capsule = nullptr;
PyObject* labels_obj = nullptr;
@@ -1363,6 +1403,32 @@ PyObject* py_index_engine_evaluate_filter(PyObject*, PyObject* args) {
}
}
+PyObject* py_index_engine_evaluate_filter_cached(PyObject*, PyObject* args) {
+ PyObject* capsule = nullptr;
+ const char* dsl = nullptr;
+ unsigned long long max_cached_candidates = 0;
+ if (!PyArg_ParseTuple(args, "OsK", &capsule, &dsl,
+ &max_cached_candidates)) {
+ return nullptr;
+ }
+
+ auto* engine = capsule_to_ptr<vdb::IndexEngine>(capsule, kIndexCapsuleName);
+ if (engine == nullptr) {
+ return nullptr;
+ }
+
+ try {
+ const vdb::FilterResult result = call_without_gil([&]() {
+ return engine->evaluate_filter(
+ dsl, static_cast<uint64_t>(max_cached_candidates));
+ });
+ return build_filter_result(result);
+ } catch (const std::exception& exc) {
+ raise_runtime_error(exc.what());
+ return nullptr;
+ }
+}
+
PyObject* py_index_engine_dump(PyObject*, PyObject* args) {
PyObject* capsule = nullptr;
const char* path = nullptr;
@@ -1649,10 +1715,16 @@ PyMethodDef kModuleMethods[] = {
"Delete data from the index engine."},
{"_index_engine_search", py_index_engine_search, METH_VARARGS,
"Search the index engine."},
+ {"_index_engine_search_with_filter_token",
+ py_index_engine_search_with_filter_token, METH_VARARGS,
+ "Search using a retained native scalar filter bitmap."},
{"_index_engine_set_filter_layout", py_index_engine_set_filter_layout,
METH_VARARGS, "Register an external label order for scalar filters."},
{"_index_engine_evaluate_filter", py_index_engine_evaluate_filter,
METH_VARARGS, "Evaluate a scalar filter in an external label order."},
+ {"_index_engine_evaluate_filter_cached",
+ py_index_engine_evaluate_filter_cached, METH_VARARGS,
+ "Evaluate and optionally retain a native scalar filter bitmap."},
{"_index_engine_dump", py_index_engine_dump, METH_VARARGS,
"Dump index state to disk."},
{"_index_engine_get_state", py_index_engine_get_state, METH_VARARGS,
diff --git a/src/index/common_structs.h b/src/index/common_structs.h
index bba5334c4..c32578456 100644
--- a/src/index/common_structs.h
+++ b/src/index/common_structs.h
@@ -45,6 +45,7 @@ struct SearchResult {
struct FilterResult {
uint64_t eligible_count = 0;
std::vector<uint32_t> bitset_words;
+ uint64_t native_filter_token = 0;
};
struct StateResult {
diff --git a/src/index/detail/index_manager_impl.cpp b/src/index/detail/index_manager_impl.cpp
index 4bb991a11..f00c25981 100644
--- a/src/index/detail/index_manager_impl.cpp
+++ b/src/index/detail/index_manager_impl.cpp
@@ -18,6 +18,7 @@ namespace vectordb {
const std::string kMetaFile = "manager_meta.json";
const std::string kVectorIndexDir = "vector_index";
const std::string kScalarIndexDir = "scalar_index";
+constexpr size_t kFilterTokenCacheCapacity = 32;
IndexManagerImpl::IndexManagerImpl(const std::string& path_or_json) {
int ret = 0;
@@ -204,6 +205,31 @@ int IndexManagerImpl::search(const SearchRequest& req, SearchResult& result) {
return ret;
}
+int IndexManagerImpl::search_with_filter_token(const SearchRequest& req,
+ uint64_t filter_token,
+ SearchResult& result,
+ bool& token_found) {
+ token_found = false;
+ if (filter_token == 0 || req.query.empty()) {
+ return 0;
+ }
+
+ std::shared_lock<std::shared_mutex> lock(rw_mutex_);
+ BitmapPtr bitmap;
+ {
+ std::lock_guard<std::mutex> token_lock(filter_token_mutex_);
+ const auto it = filter_token_cache_.find(filter_token);
+ if (it == filter_token_cache_.end()) {
+ return 0;
+ }
+ bitmap = it->second;
+ }
+
+ token_found = true;
+ SearchContext ctx;
+ return perform_vector_recall(req, ctx, bitmap, result);
+}
+
int IndexManagerImpl::set_filter_layout(
const std::vector<uint64_t>& ordered_labels) {
std::unique_lock<std::shared_mutex> lock(rw_mutex_);
@@ -219,6 +245,7 @@ int IndexManagerImpl::set_filter_layout(
}
int IndexManagerImpl::evaluate_filter(const std::string& dsl,
+ uint64_t max_cached_candidates,
FilterResult& result) {
SearchContext ctx;
if (int ret = parse_dsl_query(dsl, ctx); ret != 0) {
@@ -250,9 +277,34 @@ int IndexManagerImpl::evaluate_filter(const std::string& dsl,
static_cast<uint32_t>(1U << (row % 32));
++result.eligible_count;
}
+ if (bitmap && result.eligible_count > 0 &&
+ result.eligible_count <= max_cached_candidates) {
+ result.native_filter_token = cache_filter_bitmap_(bitmap);
+ }
return 0;
}
+uint64_t IndexManagerImpl::cache_filter_bitmap_(const BitmapPtr& bitmap) {
+ std::lock_guard<std::mutex> lock(filter_token_mutex_);
+ uint64_t token = next_filter_token_++;
+ if (token == 0) {
+ token = next_filter_token_++;
+ }
+ filter_token_cache_[token] = bitmap;
+ filter_token_order_.push_back(token);
+ while (filter_token_order_.size() > kFilterTokenCacheCapacity) {
+ filter_token_cache_.erase(filter_token_order_.front());
+ filter_token_order_.pop_front();
+ }
+ return token;
+}
+
+void IndexManagerImpl::clear_filter_token_cache_() {
+ std::lock_guard<std::mutex> lock(filter_token_mutex_);
+ filter_token_cache_.clear();
+ filter_token_order_.clear();
+}
+
BitmapPtr IndexManagerImpl::calculate_filter_bitmap(const SearchContext& ctx,
const std::string& dsl) {
auto bitmap = ctx.filter_op->calc_bitmap(scalar_index_->get_field_sets(),
@@ -364,6 +416,7 @@ int IndexManagerImpl::add_data(const std::vector<AddDataRequest>& data_list) {
}
if (has_update) {
filter_layout_offsets_.clear();
+ clear_filter_token_cache_();
auto duration = std::chrono::system_clock::now().time_since_epoch();
manager_meta_->update_timestamp =
std::chrono::duration_cast<std::chrono::nanoseconds>(duration).count();
@@ -407,6 +460,7 @@ int IndexManagerImpl::delete_data(
}
if (has_update) {
filter_layout_offsets_.clear();
+ clear_filter_token_cache_();
auto duration = std::chrono::system_clock::now().time_since_epoch();
manager_meta_->update_timestamp =
std::chrono::duration_cast<std::chrono::nanoseconds>(duration).count();
diff --git a/src/index/detail/index_manager_impl.h b/src/index/detail/index_manager_impl.h
index b288100c2..a510dc486 100644
--- a/src/index/detail/index_manager_impl.h
+++ b/src/index/detail/index_manager_impl.h
@@ -11,9 +11,12 @@
#include "index/detail/scalar/bitmap_holder/bitmap.h"
#include <shared_mutex>
+#include <deque>
#include <filesystem>
#include <memory>
+#include <mutex>
#include <stdio.h>
+#include <unordered_map>
namespace vectordb {
@@ -29,10 +32,16 @@ class IndexManagerImpl : public IndexManager {
int search(const SearchRequest& req, SearchResult& result) override;
+ int search_with_filter_token(const SearchRequest& req,
+ uint64_t filter_token,
+ SearchResult& result,
+ bool& token_found) override;
+
int set_filter_layout(
const std::vector<uint64_t>& ordered_labels) override;
int evaluate_filter(const std::string& dsl,
+ uint64_t max_cached_candidates,
FilterResult& result) override;
int add_data(const std::vector<AddDataRequest>& data_list) override;
@@ -60,12 +69,20 @@ class IndexManagerImpl : public IndexManager {
void register_label_offset_converter_();
+ uint64_t cache_filter_bitmap_(const BitmapPtr& bitmap);
+
+ void clear_filter_token_cache_();
+
private:
std::shared_mutex rw_mutex_;
std::shared_ptr<ManagerMeta> manager_meta_;
std::shared_ptr<ScalarIndex> scalar_index_;
std::shared_ptr<VectorIndexAdapter> vector_index_;
std::vector<uint32_t> filter_layout_offsets_;
+ std::mutex filter_token_mutex_;
+ uint64_t next_filter_token_ = 1;
+ std::deque<uint64_t> filter_token_order_;
+ std::unordered_map<uint64_t, BitmapPtr> filter_token_cache_;
};
} // namespace vectordb
diff --git a/src/index/index_engine.cpp b/src/index/index_engine.cpp
index a26e190c4..da9924566 100644
--- a/src/index/index_engine.cpp
+++ b/src/index/index_engine.cpp
@@ -18,14 +18,32 @@ SearchResult IndexEngine::search(const SearchRequest& req) {
return result;
}
+std::optional<SearchResult> IndexEngine::search_with_filter_token(
+ const SearchRequest& req, uint64_t filter_token) {
+ SearchResult result;
+ bool token_found = false;
+ const int ret =
+ impl_->search_with_filter_token(req, filter_token, result, token_found);
+ if (ret != 0) {
+ throw std::runtime_error("Failed to search with native filter token");
+ }
+ if (!token_found) {
+ return std::nullopt;
+ }
+ result.result_num = result.labels.size();
+ return result;
+}
+
int IndexEngine::set_filter_layout(
const std::vector<uint64_t>& ordered_labels) {
return impl_->set_filter_layout(ordered_labels);
}
-FilterResult IndexEngine::evaluate_filter(const std::string& dsl) {
+FilterResult IndexEngine::evaluate_filter(
+ const std::string& dsl, uint64_t max_cached_candidates) {
FilterResult result;
- const int ret = impl_->evaluate_filter(dsl, result);
+ const int ret =
+ impl_->evaluate_filter(dsl, max_cached_candidates, result);
if (ret != 0) {
throw std::runtime_error("Failed to evaluate native scalar filter");
}
diff --git a/src/index/index_engine.h b/src/index/index_engine.h
index 45a654fc6..cea8004fd 100644
--- a/src/index/index_engine.h
+++ b/src/index/index_engine.h
@@ -5,6 +5,7 @@
#include <string>
#include <vector>
#include <memory>
+#include <optional>
#include "index/common_structs.h"
#include "index/index_manager.h"
@@ -24,9 +25,13 @@ class IndexEngine {
SearchResult search(const SearchRequest& req);
+ std::optional<SearchResult> search_with_filter_token(
+ const SearchRequest& req, uint64_t filter_token);
+
int set_filter_layout(const std::vector<uint64_t>& ordered_labels);
- FilterResult evaluate_filter(const std::string& dsl);
+ FilterResult evaluate_filter(const std::string& dsl,
+ uint64_t max_cached_candidates = 0);
int64_t dump(const std::string& dir);
diff --git a/src/index/index_manager.h b/src/index/index_manager.h
index 20a61cc2b..420112bd9 100644
--- a/src/index/index_manager.h
+++ b/src/index/index_manager.h
@@ -14,10 +14,16 @@ class IndexManager {
virtual int search(const SearchRequest& req, SearchResult& result) = 0;
+ virtual int search_with_filter_token(const SearchRequest& req,
+ uint64_t filter_token,
+ SearchResult& result,
+ bool& token_found) = 0;
+
virtual int set_filter_layout(
const std::vector<uint64_t>& ordered_labels) = 0;
virtual int evaluate_filter(const std::string& dsl,
+ uint64_t max_cached_candidates,
FilterResult& result) = 0;
virtual int add_data(const std::vector<AddDataRequest>& data_list) = 0;
diff --git a/tests/benchmark/test_cuvs_index_benchmark.py b/tests/benchmark/test_cuvs_index_benchmark.py
index ced860a84..4c448635a 100644
--- a/tests/benchmark/test_cuvs_index_benchmark.py
+++ b/tests/benchmark/test_cuvs_index_benchmark.py
@@ -107,6 +107,94 @@ def test_cagra_itopk_sweep_preserves_shared_search_params():
]
+def test_validate_args_accepts_float16_backend_variants():
+ parser = benchmark.build_parser()
+ args = parser.parse_args(
+ ["--backends", "cuvs_brute_force,cuvs_brute_force_fp16,cuvs_cagra_fp16"]
+ )
+
+ assert benchmark.validate_args(parser, args) == [
+ "cuvs_brute_force",
+ "cuvs_brute_force_fp16",
+ "cuvs_cagra_fp16",
+ ]
+
+
+ "backends",
+ [
+ ["cuvs_brute_force_fp16"],
+ ["cuvs_cagra"],
+ ["cuvs_cagra_fp16"],
+ ["cuvs_brute_force_fp16", "cuvs_cagra"],
+ ],
+)
+def test_lossy_or_approximate_backend_requires_exact_reference(backends):
+ parser = benchmark.build_parser()
+
+ with pytest.raises(SystemExit) as exc_info:
+ benchmark.validate_reference_requirement(
+ parser,
+ backends,
+ has_supplied_ground_truth=False,
+ )
+ assert exc_info.value.code == 2
+
+
+ "backends",
+ [
+ ["native"],
+ ["cuvs_brute_force"],
+ ["native", "cuvs_brute_force"],
+ ["native", "cuvs_cagra"],
+ ["cuvs_brute_force", "cuvs_brute_force_fp16"],
+ ],
+)
+def test_reference_validation_accepts_exact_backend_combinations(backends):
+ parser = benchmark.build_parser()
+
+ benchmark.validate_reference_requirement(
+ parser,
+ backends,
+ has_supplied_ground_truth=False,
+ )
+
+
+ "backend",
+ ["cuvs_brute_force_fp16", "cuvs_cagra", "cuvs_cagra_fp16"],
+)
+def test_reference_validation_accepts_supplied_ground_truth(backend):
+ parser = benchmark.build_parser()
+
+ benchmark.validate_reference_requirement(
+ parser,
+ [backend],
+ has_supplied_ground_truth=True,
+ )
+
+
+def test_print_summary_does_not_invent_missing_recall(capsys):
+ benchmark.print_summary(
+ [
+ {
+ "backend": "cuvs_brute_force_fp16",
+ "build_seconds": 1.0,
+ "first_search_per_query_ms": 2.0,
+ "search": {
+ "per_query_latency_ms": {"p50": 3.0, "p95": 4.0},
+ "qps": 5.0,
+ },
+ }
+ ]
+ )
+
+ output = capsys.readouterr().out
+ assert "N/A" in output
+ assert "1.0000" not in output
+
+
def test_cagra_itopk_and_search_width_sweeps_form_cartesian_product():
parser = benchmark.build_parser()
args = parser.parse_args(
diff --git a/tests/benchmark/test_cuvs_index_summary.py b/tests/benchmark/test_cuvs_index_summary.py
index 834d4c41a..71d05feb3 100644
--- a/tests/benchmark/test_cuvs_index_summary.py
+++ b/tests/benchmark/test_cuvs_index_summary.py
@@ -82,7 +82,9 @@ def test_summarize_files_reports_process_median_and_mad(tmp_path):
def test_variant_sort_key_orders_backends_and_numeric_itopk():
keys = [
("cuvs_cagra", summary_module.canonical({"itopk_size": 2048})),
+ ("cuvs_cagra_fp16", summary_module.canonical({"itopk_size": 512})),
("cuvs_brute_force", summary_module.canonical(None)),
+ ("cuvs_brute_force_fp16", summary_module.canonical(None)),
("cuvs_cagra", summary_module.canonical({"itopk_size": 512})),
("native", summary_module.canonical(None)),
]
@@ -90,8 +92,10 @@ def test_variant_sort_key_orders_backends_and_numeric_itopk():
assert sorted(keys, key=summary_module.variant_sort_key) == [
("native", "null"),
("cuvs_brute_force", "null"),
+ ("cuvs_brute_force_fp16", "null"),
("cuvs_cagra", '{"itopk_size":512}'),
("cuvs_cagra", '{"itopk_size":2048}'),
+ ("cuvs_cagra_fp16", '{"itopk_size":512}'),
]
diff --git a/tests/benchmark/test_cuvs_service_concurrency_benchmark.py b/tests/benchmark/test_cuvs_service_concurrency_benchmark.py
index ac7d80d43..f8887da9c 100644
--- a/tests/benchmark/test_cuvs_service_concurrency_benchmark.py
+++ b/tests/benchmark/test_cuvs_service_concurrency_benchmark.py
@@ -38,6 +38,29 @@ def test_service_record_contains_tenant_and_filter_fields():
}
+def test_auto_background_backend_enables_coalescing_rebuild(tmp_path):
+ config = benchmark.make_config(
+ "auto_cuvs_background",
+ project_path=tmp_path,
+ collection_name="background",
+ dimension=128,
+ filter_cache_size=16,
+ auto_rebuild_debounce_ms=25,
+ )
+
+ assert config.backend == "local"
+ assert config.cuvs.auto_enable is True
+ assert config.cuvs.auto_background_rebuild is True
+ assert config.cuvs.auto_rebuild_debounce_ms == 25
+
+
+def test_validate_args_accepts_auto_background_backend():
+ parser = benchmark.build_parser()
+ args = parser.parse_args(["--backends", "auto_cuvs_background"])
+
+ assert benchmark.validate_args(parser, args) == ["auto_cuvs_background"]
+
+
@pytest.mark.asyncio
async def test_run_request_set_reports_concurrent_successes():
class FakeManager:
diff --git a/tests/engine/test_index_engine.cpp b/tests/engine/test_index_engine.cpp
index c839ef9c3..330b74723 100644
--- a/tests/engine/test_index_engine.cpp
+++ b/tests/engine/test_index_engine.cpp
@@ -96,10 +96,11 @@ void test_basic_workflow() {
SPDLOG_ERROR("Filter layout registration failed");
exit(1);
}
- FilterResult filter_res = engine.evaluate_filter(
- R"({"op":"must","field":"uri","conds":["/docs"],"para":"-d=-1"})");
+ const std::string uri_filter =
+ R"({"op":"must","field":"uri","conds":["/docs"],"para":"-d=-1"})";
+ FilterResult filter_res = engine.evaluate_filter(uri_filter);
if (filter_res.eligible_count != 1 || filter_res.bitset_words.size() != 1 ||
- filter_res.bitset_words[0] != 4U) {
+ filter_res.bitset_words[0] != 4U || filter_res.native_filter_token != 0) {
SPDLOG_ERROR(
"Filter projection failed: count={}, words={}, first_word={}",
filter_res.eligible_count, filter_res.bitset_words.size(),
@@ -107,6 +108,19 @@ void test_basic_workflow() {
exit(1);
}
+ FilterResult cached_filter_res = engine.evaluate_filter(uri_filter, 10);
+ if (cached_filter_res.native_filter_token == 0) {
+ SPDLOG_ERROR("Native filter token was not retained");
+ exit(1);
+ }
+ auto token_search_res = engine.search_with_filter_token(
+ search_req, cached_filter_res.native_filter_token);
+ if (!token_search_res || token_search_res->result_num != 1 ||
+ token_search_res->labels[0] != 1001) {
+ SPDLOG_ERROR("Search with native filter token failed");
+ exit(1);
+ }
+
// 4. Delete Data
std::vector<DeleteDataRequest> del_reqs(1);
del_reqs[0].label = 1001;
@@ -118,6 +132,12 @@ void test_basic_workflow() {
SPDLOG_ERROR("Delete data failed");
exit(1);
}
+ auto stale_token_result = engine.search_with_filter_token(
+ search_req, cached_filter_res.native_filter_token);
+ if (stale_token_result.has_value()) {
+ SPDLOG_ERROR("Native filter token survived a mutation");
+ exit(1);
+ }
// 5. Search again to verify deletion
res = engine.search(search_req);
diff --git a/tests/misc/test_vectordb_engine_loader.py b/tests/misc/test_vectordb_engine_loader.py
index 2b4123cab..7885254d5 100644
--- a/tests/misc/test_vectordb_engine_loader.py
+++ b/tests/misc/test_vectordb_engine_loader.py
@@ -246,6 +246,15 @@ def test_engine_loader_wraps_abi3_backend_with_python_api(monkeypatch):
"extra_json": '{"ok":true}',
}
),
+ _index_engine_search_with_filter_token=lambda handle, req, token: (
+ calls.append(("search_with_filter_token", handle, req, token))
+ or {
+ "result_num": 1,
+ "labels": [101],
+ "scores": [0.9],
+ "extra_json": "",
+ }
+ ),
_index_engine_set_filter_layout=lambda handle, labels: (
calls.append(("set_filter_layout", handle, labels)) or 0
),
@@ -253,6 +262,14 @@ def test_engine_loader_wraps_abi3_backend_with_python_api(monkeypatch):
calls.append(("evaluate_filter", handle, dsl))
or {"eligible_count": 1, "bitset_words": [4]}
),
+ _index_engine_evaluate_filter_cached=lambda handle, dsl, max_candidates: (
+ calls.append(("evaluate_filter_cached", handle, dsl, max_candidates))
+ or {
+ "eligible_count": 1,
+ "bitset_words": [4],
+ "native_filter_token": 17,
+ }
+ ),
_index_engine_dump=lambda handle, path: calls.append(("dump", handle, path)) or 11,
_index_engine_get_state=lambda handle: (
calls.append(("get_state", handle)) or {"update_timestamp": 123, "element_count": 7}
@@ -322,6 +339,21 @@ def test_engine_loader_wraps_abi3_backend_with_python_api(monkeypatch):
filter_result = index.evaluate_filter('{"op":"must"}')
assert filter_result.eligible_count == 1
assert filter_result.bitset_words == [4]
+ assert filter_result.native_filter_token == 0
+
+ cached_filter_result = index.evaluate_filter('{"op":"must"}', max_cached_candidates=10)
+ assert cached_filter_result.native_filter_token == 17
+ token_search_result = index.search_with_filter_token(search_req, 17)
+ assert token_search_result is not None
+ assert token_search_result.labels == [101]
+
+ # A source checkout paired with an older native module keeps the original
+ # evaluate + search path instead of failing during a rolling upgrade.
+ del backend._index_engine_evaluate_filter_cached
+ del backend._index_engine_search_with_filter_token
+ fallback_filter_result = index.evaluate_filter('{"op":"must"}', max_cached_candidates=10)
+ assert fallback_filter_result.native_filter_token == 0
+ assert index.search_with_filter_token(search_req, 17) is None
state = index.get_state()
assert state.update_timestamp == 123
diff --git a/tests/test_telemetry_runtime.py b/tests/test_telemetry_runtime.py
index 52c5aa507..5ae9e8bda 100644
--- a/tests/test_telemetry_runtime.py
+++ b/tests/test_telemetry_runtime.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import asyncio
import json
+from concurrent.futures import ThreadPoolExecutor
from types import SimpleNamespace
import pytest
@@ -249,6 +250,233 @@ def test_telemetry_summary_uses_simplified_internal_metric_keys():
assert result["memory"] == {"extracted": 6}
+def test_telemetry_summary_includes_cuvs_route_and_stage_timings():
+ telemetry = MemoryOperationTelemetry(operation="search.find", enabled=True)
+ telemetry.record_cuvs_search(
+ {
+ "algorithm": "brute_force",
+ "dtype": "float16",
+ "max_concurrent_gpu_searches": 2,
+ "auto_mode": True,
+ "route_reason": "native_filter_threshold",
+ "filter_kind": "path",
+ "filter_cache_hit": True,
+ "native_filter_reused": True,
+ "build_performed": False,
+ "eligible_count": 12,
+ "records_generation": 3,
+ "index_size": 1000,
+ "memory_estimated_peak_bytes": 4096,
+ "memory_free_bytes": 8192,
+ "memory_usable_bytes": 6144,
+ "total_ms": 1.25,
+ "preflight_ms": 0.4,
+ "native_search_ms": 0.7,
+ }
+ )
+
+ cuvs = telemetry.finish().summary["vector"]["cuvs"]
+
+ assert cuvs == {
+ "searches": 1,
+ "algorithms": {"brute_force": 1},
+ "dtypes": {"float16": 1},
+ "max_concurrent_gpu_searches": 2,
+ "auto_mode_searches": 1,
+ "routes": {"native_filter_threshold": 1},
+ "filter_kinds": {"path": 1},
+ "filter_cache_hits": 1,
+ "native_filter_reuses": 1,
+ "eligible_count_max": 12,
+ "records_generation_max": 3,
+ "index_size_max": 1000,
+ "memory": {
+ "estimated_peak_bytes_max": 4096,
+ "free_bytes_min": 8192,
+ "usable_bytes_min": 6144,
+ },
+ "timings_ms": {
+ "total": {"sum": 1.25, "max": 1.25},
+ "preflight": {"sum": 0.4, "max": 0.4},
+ "native_search": {"sum": 0.7, "max": 0.7},
+ },
+ }
+
+
+def test_cuvs_telemetry_aggregation_is_completion_order_independent():
+ samples = [
+ {
+ "algorithm": "brute_force",
+ "dtype": "float32",
+ "max_concurrent_gpu_searches": 1,
+ "auto_mode": False,
+ "route_reason": "cuvs",
+ "filter_kind": "none",
+ "build_performed": True,
+ "records_generation": 2,
+ "index_size": 100,
+ "memory_estimated_peak_bytes": 4000,
+ "memory_free_bytes": 8000,
+ "memory_usable_bytes": 7000,
+ "total_ms": 12,
+ "queue_ms": 2,
+ "build_ms": 5,
+ "gpu_search_ms": 5,
+ },
+ {
+ "algorithm": "brute_force",
+ "dtype": "float32",
+ "max_concurrent_gpu_searches": 2,
+ "auto_mode": True,
+ "route_reason": "native_filter_threshold",
+ "filter_kind": "path",
+ "filter_cache_hit": True,
+ "native_filter_reused": True,
+ "eligible_count": 3,
+ "records_generation": 2,
+ "index_size": 100,
+ "memory_free_bytes": 6000,
+ "memory_usable_bytes": 5000,
+ "total_ms": 3,
+ "preflight_ms": 1,
+ "native_search_ms": 2,
+ },
+ ]
+
+ def aggregate(order):
+ telemetry = MemoryOperationTelemetry(operation="search.find", enabled=True)
+ for index in order:
+ telemetry.record_cuvs_search(samples[index])
+ return telemetry.finish().summary["vector"]["cuvs"]
+
+ forward = aggregate([0, 1])
+ reverse = aggregate([1, 0])
+
+ assert forward == reverse
+ assert forward["routes"] == {"cuvs": 1, "native_filter_threshold": 1}
+ assert forward["builds"] == 1
+ assert forward["memory"]["free_bytes_min"] == 6000
+ assert forward["timings_ms"]["total"] == {"sum": 15.0, "max": 12.0}
+
+
+def test_cuvs_telemetry_timing_sum_is_strictly_order_independent():
+ # A large first value makes ordinary floating-point associativity loss observable.
+ durations_ms = [10_000_000_000_000.0, 0.001, 0.001]
+
+ def aggregate(order):
+ telemetry = MemoryOperationTelemetry(operation="search.find", enabled=True)
+ for index in order:
+ telemetry.record_cuvs_search(
+ {
+ "algorithm": "brute_force",
+ "dtype": "float32",
+ "route_reason": "cuvs",
+ "filter_kind": "none",
+ "total_ms": durations_ms[index],
+ }
+ )
+ return telemetry.finish().summary["vector"]["cuvs"]["timings_ms"]["total"]
+
+ forward = aggregate([0, 1, 2])
+ reverse = aggregate([2, 1, 0])
+
+ assert (
+ forward
+ == reverse
+ == {
+ "sum": 10_000_000_000_000.002,
+ "max": 10_000_000_000_000.0,
+ }
+ )
+
+
+def test_cuvs_telemetry_aggregation_is_thread_safe():
+ telemetry = MemoryOperationTelemetry(operation="search.find", enabled=True)
+ samples = [
+ {
+ "algorithm": "brute_force",
+ "dtype": "float32",
+ "route_reason": "cuvs",
+ "filter_kind": "none",
+ "memory_free_bytes": 8000,
+ "total_ms": 0.001,
+ "gpu_search_ms": 0.001,
+ },
+ {
+ "algorithm": "cagra",
+ "dtype": "float16",
+ "route_reason": "native_filter_threshold",
+ "filter_kind": "path",
+ "memory_free_bytes": 6000,
+ "total_ms": 0.002,
+ "native_search_ms": 0.002,
+ },
+ ] * 100
+
+ with ThreadPoolExecutor(max_workers=8) as executor:
+ list(executor.map(telemetry.record_cuvs_search, samples))
+
+ cuvs = telemetry.finish().summary["vector"]["cuvs"]
+
+ assert cuvs["searches"] == 200
+ assert cuvs["algorithms"] == {"brute_force": 100, "cagra": 100}
+ assert cuvs["dtypes"] == {"float16": 100, "float32": 100}
+ assert cuvs["routes"] == {"cuvs": 100, "native_filter_threshold": 100}
+ assert cuvs["filter_kinds"] == {"none": 100, "path": 100}
+ assert cuvs["memory"]["free_bytes_min"] == 6000
+ assert cuvs["timings_ms"]["total"] == {"sum": 0.3, "max": 0.002}
+
+
+def test_cuvs_telemetry_bounds_dimensions_and_prunes_unobserved_values():
+ telemetry = MemoryOperationTelemetry(operation="search.find", enabled=True)
+ telemetry.record_cuvs_search(
+ {
+ "algorithm": "tenant-specific-algorithm",
+ "dtype": "tenant-specific-dtype",
+ "route_reason": "tenant/1234",
+ "filter_kind": "tenant-specific-filter",
+ "auto_mode": "false",
+ "filter_cache_hit": "false",
+ "native_filter_reused": "false",
+ "build_performed": "false",
+ "eligible_count": None,
+ "memory_estimated_peak_bytes": float("inf"),
+ "total_ms": float("nan"),
+ "gpu_search_ms": -1,
+ }
+ )
+
+ cuvs = telemetry.finish().summary["vector"]["cuvs"]
+
+ assert cuvs == {
+ "searches": 1,
+ "algorithms": {"other": 1},
+ "dtypes": {"other": 1},
+ "max_concurrent_gpu_searches": 1,
+ "routes": {"other": 1},
+ "filter_kinds": {"other": 1},
+ }
+
+
+def test_cuvs_telemetry_distinguishes_zero_memory_from_unobserved_memory():
+ telemetry = MemoryOperationTelemetry(operation="search.find", enabled=True)
+ telemetry.record_cuvs_search(
+ {
+ "algorithm": "brute_force",
+ "dtype": "float32",
+ "route_reason": "native_memory_budget",
+ "filter_kind": "none",
+ "memory_free_bytes": 0,
+ "memory_usable_bytes": 0,
+ }
+ )
+
+ cuvs = telemetry.finish().summary["vector"]["cuvs"]
+
+ assert cuvs["memory"] == {"free_bytes_min": 0, "usable_bytes_min": 0}
+ assert "estimated_peak_bytes_max" not in cuvs["memory"]
+
+
def test_init_tracer_forwards_headers_to_grpc_exporter(monkeypatch):
captured = {}
diff --git a/tests/vectordb/test_cuvs_collection.py b/tests/vectordb/test_cuvs_collection.py
index 983a9f6b1..505832b9d 100644
--- a/tests/vectordb/test_cuvs_collection.py
+++ b/tests/vectordb/test_cuvs_collection.py
@@ -1,10 +1,25 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
+import multiprocessing
+import threading
+import traceback
+from concurrent.futures import ThreadPoolExecutor
+
+import pytest
+
from openviking.storage.vectordb.collection.local_collection import (
+ PersistCollection,
get_or_create_local_collection,
)
from openviking.storage.vectordb.index import cuvs_index
+from openviking.storage.vectordb.index.local_index import (
+ IndexEngineProxy,
+ LocalIndex,
+ PersistentIndex,
+)
+from openviking.telemetry.backends.memory import MemoryOperationTelemetry
+from openviking.telemetry.context import bind_telemetry
class FakeCuVSRuntime:
@@ -63,10 +78,23 @@ def patch_cuvs_runtime(monkeypatch):
monkeypatch.setattr(
cuvs_index,
"_CuVSRuntime",
- lambda algorithm, metric, build_params, search_params: FakeCuVSRuntime(metric),
+ lambda algorithm, metric, build_params, search_params, dtype: FakeCuVSRuntime(metric),
)
+def _delete_without_persisting_index(path, ready, hold):
+ """Write a deletion delta, then wait to be terminated without closing."""
+
+ try:
+ collection = get_or_create_local_collection(path=path)
+ collection.delete_data(["deleted"])
+ ready.send(("ok", ""))
+ hold.wait()
+ except BaseException:
+ ready.send(("error", traceback.format_exc()))
+ raise
+
+
def test_local_collection_routes_dense_search_to_cuvs(monkeypatch):
patch_cuvs_runtime(monkeypatch)
collection = get_or_create_local_collection(
@@ -184,6 +212,124 @@ def test_local_collection_routes_dense_search_to_cuvs(monkeypatch):
collection.close()
+def test_local_collection_records_cuvs_route_telemetry(monkeypatch):
+ patch_cuvs_runtime(monkeypatch)
+ collection = get_or_create_local_collection(
+ meta_data={
+ "CollectionName": "cuvs_telemetry",
+ "Fields": [
+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
+ {"FieldName": "vector", "FieldType": "vector", "Dim": 4},
+ ],
+ },
+ config={"dense_search": {"backend": "cuvs", "algorithm": "brute_force"}},
+ )
+ try:
+ collection.create_index(
+ "default",
+ {
+ "IndexName": "default",
+ "VectorIndex": {"IndexType": "flat", "Distance": "cosine"},
+ },
+ )
+ collection.upsert_data([{"id": "first", "vector": [1.0, 0.0, 0.0, 0.0]}])
+ telemetry = MemoryOperationTelemetry(operation="search.find", enabled=True)
+
+ with bind_telemetry(telemetry):
+ result = collection.search_by_vector(
+ "default", dense_vector=[1.0, 0.0, 0.0, 0.0], limit=1
+ )
+
+ assert [item.id for item in result.data] == ["first"]
+ cuvs = telemetry.finish().summary["vector"]["cuvs"]
+ assert cuvs["searches"] == 1
+ assert cuvs["algorithms"] == {"brute_force": 1}
+ assert cuvs["dtypes"] == {"float32": 1}
+ assert cuvs["max_concurrent_gpu_searches"] == 1
+ assert cuvs["routes"] == {"cuvs": 1}
+ assert cuvs["filter_kinds"] == {"none": 1}
+ assert cuvs["builds"] == 1
+ assert cuvs["index_size_max"] == 1
+ finally:
+ collection.close()
+
+
+def test_local_collection_allows_concurrent_warmed_cuvs_searches(monkeypatch):
+ class ConcurrentFakeCuVSRuntime(FakeCuVSRuntime):
+ def __init__(self, metric):
+ super().__init__(metric)
+ self.barrier = threading.Barrier(1)
+ self.active_lock = threading.Lock()
+ self.active = 0
+ self.peak_active = 0
+
+ def search(self, index, query, limit, mask):
+ with self.active_lock:
+ self.active += 1
+ self.peak_active = max(self.peak_active, self.active)
+ try:
+ self.barrier.wait(timeout=5)
+ return super().search(index, query, limit, mask)
+ finally:
+ with self.active_lock:
+ self.active -= 1
+
+ runtime = ConcurrentFakeCuVSRuntime("inner_product")
+ monkeypatch.setattr(
+ cuvs_index,
+ "_CuVSRuntime",
+ lambda _algorithm, _metric, _build_params, _search_params, _dtype: runtime,
+ )
+ collection = get_or_create_local_collection(
+ meta_data={
+ "CollectionName": "cuvs_concurrent_search",
+ "Fields": [
+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
+ {"FieldName": "vector", "FieldType": "vector", "Dim": 4},
+ ],
+ },
+ config={
+ "dense_search": {
+ "backend": "cuvs",
+ "algorithm": "brute_force",
+ "max_concurrent_gpu_searches": 4,
+ }
+ },
+ )
+ try:
+ collection.create_index(
+ "default",
+ {
+ "IndexName": "default",
+ "VectorIndex": {"IndexType": "flat", "Distance": "cosine"},
+ },
+ )
+ collection.upsert_data([{"id": "first", "vector": [1.0, 0.0, 0.0, 0.0]}])
+ assert (
+ collection.search_by_vector("default", dense_vector=[1.0, 0.0, 0.0, 0.0], limit=1)
+ .data[0]
+ .id
+ == "first"
+ )
+ runtime.barrier = threading.Barrier(4)
+
+ with ThreadPoolExecutor(max_workers=4) as executor:
+ futures = [
+ executor.submit(
+ collection.search_by_vector,
+ "default",
+ dense_vector=[1.0, 0.0, 0.0, 0.0],
+ limit=1,
+ )
+ for _ in range(4)
+ ]
+ assert [future.result(timeout=5).data[0].id for future in futures] == ["first"] * 4
+
+ assert runtime.peak_active == 4
+ finally:
+ collection.close()
+
+
def test_persistent_collection_rehydrates_cuvs_from_local_store(monkeypatch, tmp_path):
patch_cuvs_runtime(monkeypatch)
path = str(tmp_path / "cuvs-persistent")
@@ -219,10 +365,160 @@ def test_persistent_collection_rehydrates_cuvs_from_local_store(monkeypatch, tmp
reopened.close()
+def test_persistent_cuvs_rebuild_waits_for_deletion_replay(monkeypatch, tmp_path):
+ path = str(tmp_path / "persistent-cuvs-recovery")
+ collection = get_or_create_local_collection(
+ meta_data={
+ "CollectionName": "persistent_cuvs_recovery",
+ "Fields": [
+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
+ {"FieldName": "vector", "FieldType": "vector", "Dim": 4},
+ {"FieldName": "kind", "FieldType": "string"},
+ ],
+ },
+ path=path,
+ )
+ collection.create_index(
+ "default",
+ {
+ "IndexName": "default",
+ "VectorIndex": {"IndexType": "flat", "Distance": "cosine"},
+ "ScalarIndex": ["kind"],
+ },
+ )
+ collection.upsert_data(
+ [
+ {
+ "id": "deleted",
+ "vector": [1.0, 0.0, 0.0, 0.0],
+ "kind": "deleted",
+ },
+ {
+ "id": "survivor",
+ "vector": [0.0, 1.0, 0.0, 0.0],
+ "kind": "survivor",
+ },
+ ]
+ )
+ collection.close()
+
+ # Commit only the store deletion. Terminating the process leaves the native
+ # snapshot stale, so recovery has exactly one deletion to replay.
+ ctx = multiprocessing.get_context("spawn")
+ ready_parent, ready_child = ctx.Pipe(duplex=False)
+ hold = ctx.Event()
+ process = ctx.Process(
+ target=_delete_without_persisting_index,
+ args=(path, ready_child, hold),
+ )
+ process.start()
+ ready_child.close()
+ try:
+ assert ready_parent.poll(20), "deletion worker did not finish"
+ status, detail = ready_parent.recv()
+ assert status == "ok", detail
+ finally:
+ ready_parent.close()
+ if process.is_alive():
+ process.terminate()
+ process.join(10)
+ assert not process.is_alive()
+
+ runtime = MemoryAwareFakeCuVSRuntime("inner_product", free_memory_bytes=1 << 30)
+ monkeypatch.setattr(
+ cuvs_index,
+ "_CuVSRuntime",
+ lambda _algorithm, _metric, _build_params, _search_params, _dtype: runtime,
+ )
+
+ replay_completed = threading.Event()
+ layout_registered = threading.Event()
+ layouts_before_replay = []
+ replay_operations = []
+ original_init = PersistentIndex.__init__
+ original_replay = PersistCollection._replay_recovery_records
+ original_set_filter_layout = IndexEngineProxy.set_filter_layout
+
+ def synchronize_constructor(self, *args, **kwargs):
+ original_init(self, *args, **kwargs)
+ # The old lifecycle starts the worker during construction. Waiting here
+ # forces its stale layout to commit before recovery can replay deletion.
+ if self._dense_rebuild_thread is not None:
+ assert layout_registered.wait(timeout=5)
+
+ def observe_replay(self, *, index_name, index, records, operation):
+ replay_operations.append((operation, len(records)))
+ result = original_replay(
+ self,
+ index_name=index_name,
+ index=index,
+ records=records,
+ operation=operation,
+ )
+ replay_completed.set()
+ return result
+
+ def observe_filter_layout(self, ordered_labels):
+ result = original_set_filter_layout(self, ordered_labels)
+ if not replay_completed.is_set():
+ layouts_before_replay.append(tuple(ordered_labels))
+ layout_registered.set()
+ return result
+
+ monkeypatch.setattr(PersistentIndex, "__init__", synchronize_constructor)
+ monkeypatch.setattr(PersistCollection, "_replay_recovery_records", observe_replay)
+ monkeypatch.setattr(IndexEngineProxy, "set_filter_layout", observe_filter_layout)
+
+ reopened = get_or_create_local_collection(
+ path=path,
+ config={
+ "dense_search": {
+ "backend": "auto_cuvs",
+ "algorithm": "brute_force",
+ "filter_cache_size": 0,
+ "auto_memory_reserve_mb": 0,
+ "auto_memory_safety_factor": 1.0,
+ "auto_background_rebuild": True,
+ "auto_rebuild_debounce_ms": 0,
+ }
+ },
+ )
+ try:
+ assert replay_operations == [("delete", 1)]
+ assert replay_completed.is_set()
+ index = reopened.get_index("default")
+ assert index is not None
+ assert index.wait_for_background_rebuild(timeout=5)
+ assert layout_registered.wait(timeout=5)
+ assert layouts_before_replay == []
+ assert runtime.build_count == 1
+
+ unfiltered = reopened.search_by_vector(
+ "default", dense_vector=[0.0, 1.0, 0.0, 0.0], limit=2
+ )
+ filtered = reopened.search_by_vector(
+ "default",
+ dense_vector=[0.0, 1.0, 0.0, 0.0],
+ limit=2,
+ filters={"op": "must", "field": "kind", "conds": ["survivor"]},
+ )
+ deleted = reopened.search_by_vector(
+ "default",
+ dense_vector=[1.0, 0.0, 0.0, 0.0],
+ limit=2,
+ filters={"op": "must", "field": "kind", "conds": ["deleted"]},
+ )
+ assert [item.id for item in unfiltered.data] == ["survivor"]
+ assert [item.id for item in filtered.data] == ["survivor"]
+ assert deleted.data == []
+ finally:
+ reopened.close()
+
+
def test_auto_cuvs_falls_back_then_retries_when_memory_is_available(monkeypatch):
runtimes = []
- def make_runtime(_algorithm, metric, _build_params, _search_params):
+ def make_runtime(_algorithm, metric, _build_params, _search_params, _dtype):
runtime = MemoryAwareFakeCuVSRuntime(metric, free_memory_bytes=31)
runtimes.append(runtime)
return runtime
@@ -293,15 +589,523 @@ def test_auto_cuvs_falls_back_then_retries_when_memory_is_available(monkeypatch)
collection.close()
+def test_auto_cuvs_background_rebuild_warms_gpu_before_query(monkeypatch):
+ runtime = MemoryAwareFakeCuVSRuntime("inner_product", free_memory_bytes=64)
+ monkeypatch.setattr(
+ cuvs_index,
+ "_CuVSRuntime",
+ lambda _algorithm, _metric, _build_params, _search_params, _dtype: runtime,
+ )
+ collection = get_or_create_local_collection(
+ meta_data={
+ "CollectionName": "auto_cuvs_background",
+ "Fields": [
+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
+ {"FieldName": "vector", "FieldType": "vector", "Dim": 4},
+ ],
+ },
+ config={
+ "dense_search": {
+ "backend": "auto_cuvs",
+ "algorithm": "brute_force",
+ "filter_cache_size": 0,
+ "auto_memory_reserve_mb": 0,
+ "auto_memory_safety_factor": 1.0,
+ "auto_background_rebuild": True,
+ "auto_rebuild_debounce_ms": 0,
+ }
+ },
+ )
+ try:
+ index = collection.create_index(
+ "default",
+ {
+ "IndexName": "default",
+ "VectorIndex": {"IndexType": "flat", "Distance": "cosine"},
+ },
+ )
+ collection.upsert_data(
+ [
+ {"id": "first", "vector": [1.0, 0.0, 0.0, 0.0]},
+ {"id": "second", "vector": [0.0, 1.0, 0.0, 0.0]},
+ ]
+ )
+
+ assert index.wait_for_background_rebuild(timeout=5)
+ assert runtime.build_count == 1
+ result = collection.search_by_vector("default", dense_vector=[1.0, 0.0, 0.0, 0.0], limit=1)
+ assert [item.id for item in result.data] == ["first"]
+ assert runtime.search_count == 1
+ finally:
+ collection.close()
+
+
+def test_auto_cuvs_initial_rebuild_waits_for_native_data(monkeypatch):
+ runtime = MemoryAwareFakeCuVSRuntime("inner_product", free_memory_bytes=1 << 30)
+ monkeypatch.setattr(
+ cuvs_index,
+ "_CuVSRuntime",
+ lambda _algorithm, _metric, _build_params, _search_params, _dtype: runtime,
+ )
+
+ native_add_done = threading.Event()
+ layout_registered = threading.Event()
+ original_add_data = IndexEngineProxy.add_data
+ original_set_filter_layout = IndexEngineProxy.set_filter_layout
+ original_schedule = LocalIndex._schedule_dense_rebuild
+
+ def observe_native_add(self, candidates):
+ result = original_add_data(self, candidates)
+ native_add_done.set()
+ return result
+
+ def observe_filter_layout(self, ordered_labels):
+ result = original_set_filter_layout(self, ordered_labels)
+ layout_registered.set()
+ return result
+
+ def wait_for_early_rebuild(self):
+ original_schedule(self)
+ # Force the buggy pre-add schedule to wait until its worker publishes
+ # the stale layout; the fixed lifecycle never enters this branch.
+ if not native_add_done.is_set():
+ assert layout_registered.wait(timeout=5)
+
+ monkeypatch.setattr(IndexEngineProxy, "add_data", observe_native_add)
+ monkeypatch.setattr(IndexEngineProxy, "set_filter_layout", observe_filter_layout)
+ monkeypatch.setattr(LocalIndex, "_schedule_dense_rebuild", wait_for_early_rebuild)
+
+ collection = get_or_create_local_collection(
+ meta_data={
+ "CollectionName": "auto_cuvs_initial_rebuild",
+ "Fields": [
+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
+ {"FieldName": "vector", "FieldType": "vector", "Dim": 4},
+ {"FieldName": "kind", "FieldType": "string"},
+ ],
+ },
+ config={
+ "dense_search": {
+ "backend": "auto_cuvs",
+ "algorithm": "brute_force",
+ "auto_memory_reserve_mb": 0,
+ "auto_memory_safety_factor": 1.0,
+ "auto_background_rebuild": True,
+ "auto_rebuild_debounce_ms": 0,
+ }
+ },
+ )
+ try:
+ collection.upsert_data([{"id": "first", "vector": [1.0, 0.0, 0.0, 0.0], "kind": "x"}])
+ index = collection.create_index(
+ "default",
+ {
+ "IndexName": "default",
+ "VectorIndex": {"IndexType": "flat", "Distance": "cosine"},
+ "ScalarIndex": ["kind"],
+ },
+ )
+
+ assert index.wait_for_background_rebuild(timeout=5)
+ assert runtime.build_count == 1
+ unfiltered = collection.search_by_vector(
+ "default", dense_vector=[1.0, 0.0, 0.0, 0.0], limit=1
+ )
+ filtered = collection.search_by_vector(
+ "default",
+ dense_vector=[1.0, 0.0, 0.0, 0.0],
+ limit=1,
+ filters={"op": "must", "field": "kind", "conds": ["x"]},
+ )
+ assert [item.id for item in unfiltered.data] == ["first"]
+ assert [item.id for item in filtered.data] == ["first"]
+ finally:
+ collection.close()
+
+
+def test_auto_cuvs_background_rebuild_coalesces_mutations_and_routes_native(
+ monkeypatch,
+):
+ class BlockingBuildRuntime(MemoryAwareFakeCuVSRuntime):
+ def __init__(self):
+ super().__init__("inner_product", free_memory_bytes=1 << 20)
+ self.build_started = threading.Event()
+ self.resume_build = threading.Event()
+
+ def build(self, dataset):
+ self.build_started.set()
+ assert self.resume_build.wait(timeout=5)
+ return super().build(dataset)
+
+ runtime = BlockingBuildRuntime()
+ monkeypatch.setattr(
+ cuvs_index,
+ "_CuVSRuntime",
+ lambda _algorithm, _metric, _build_params, _search_params, _dtype: runtime,
+ )
+ collection = get_or_create_local_collection(
+ meta_data={
+ "CollectionName": "auto_cuvs_coalesced_rebuild",
+ "Fields": [
+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
+ {"FieldName": "vector", "FieldType": "vector", "Dim": 4},
+ ],
+ },
+ config={
+ "dense_search": {
+ "backend": "auto_cuvs",
+ "algorithm": "brute_force",
+ "filter_cache_size": 0,
+ "auto_memory_reserve_mb": 0,
+ "auto_memory_safety_factor": 1.0,
+ "auto_background_rebuild": True,
+ "auto_rebuild_debounce_ms": 0,
+ }
+ },
+ )
+ try:
+ index = collection.create_index(
+ "default",
+ {
+ "IndexName": "default",
+ "VectorIndex": {"IndexType": "flat", "Distance": "cosine"},
+ },
+ )
+ collection.upsert_data([{"id": "first", "vector": [1.0, 0.0, 0.0, 0.0]}])
+ assert runtime.build_started.wait(timeout=5)
+
+ # The build does not hold the cross-backend lock. Queries remain
+ # correct through native search and writes coalesce into one follow-up.
+ result = collection.search_by_vector("default", dense_vector=[1.0, 0.0, 0.0, 0.0], limit=1)
+ assert [item.id for item in result.data] == ["first"]
+ assert runtime.search_count == 0
+ collection.update_data([{"id": "first", "vector": [0.0, 1.0, 0.0, 0.0]}])
+ collection.update_data([{"id": "first", "vector": [0.0, 0.0, 1.0, 0.0]}])
+
+ runtime.resume_build.set()
+ assert index.wait_for_background_rebuild(timeout=5)
+ assert runtime.build_count == 2
+ finally:
+ runtime.resume_build.set()
+ collection.close()
+
+
+def test_auto_cuvs_background_debounce_is_not_extended_by_dirty_reads(monkeypatch):
+ class BuildStartedRuntime(MemoryAwareFakeCuVSRuntime):
+ def __init__(self):
+ super().__init__("inner_product", free_memory_bytes=1 << 20)
+ self.build_started = threading.Event()
+
+ def build(self, dataset):
+ self.build_started.set()
+ return super().build(dataset)
+
+ runtime = BuildStartedRuntime()
+ monkeypatch.setattr(
+ cuvs_index,
+ "_CuVSRuntime",
+ lambda _algorithm, _metric, _build_params, _search_params, _dtype: runtime,
+ )
+ collection = get_or_create_local_collection(
+ meta_data={
+ "CollectionName": "auto_cuvs_read_safe_debounce",
+ "Fields": [
+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
+ {"FieldName": "vector", "FieldType": "vector", "Dim": 4},
+ ],
+ },
+ config={
+ "dense_search": {
+ "backend": "auto_cuvs",
+ "algorithm": "brute_force",
+ "filter_cache_size": 0,
+ "auto_memory_reserve_mb": 0,
+ "auto_memory_safety_factor": 1.0,
+ "auto_background_rebuild": True,
+ "auto_rebuild_debounce_ms": 200,
+ }
+ },
+ )
+ stop_reads = threading.Event()
+ reader_started = threading.Event()
+
+ try:
+ index = collection.create_index(
+ "default",
+ {
+ "IndexName": "default",
+ "VectorIndex": {"IndexType": "flat", "Distance": "cosine"},
+ },
+ )
+ assert index.wait_for_background_rebuild(timeout=5)
+
+ def keep_reading():
+ reader_started.set()
+ while not stop_reads.wait(0.005):
+ collection.search_by_vector(
+ "default",
+ dense_vector=[1.0, 0.0, 0.0, 0.0],
+ limit=1,
+ )
+
+ reader = threading.Thread(target=keep_reading)
+ reader.start()
+ assert reader_started.wait(timeout=1)
+ collection.upsert_data([{"id": "first", "vector": [1.0, 0.0, 0.0, 0.0]}])
+
+ # Reads continue throughout the non-zero trailing-edge mutation debounce.
+ # They must not keep pushing its deadline out indefinitely.
+ assert runtime.build_started.wait(timeout=1)
+ assert reader.is_alive()
+ assert index.wait_for_background_rebuild(timeout=5)
+ assert runtime.build_count == 1
+ finally:
+ stop_reads.set()
+ if "reader" in locals():
+ reader.join(timeout=5)
+ collection.close()
+
+
+def test_auto_cuvs_clean_to_dirty_race_never_rebuilds_on_query_thread(monkeypatch):
+ class RaceBuildRuntime(MemoryAwareFakeCuVSRuntime):
+ def __init__(self):
+ super().__init__("inner_product", free_memory_bytes=1 << 20)
+ self.build_attempts = 0
+ self.block_build = False
+ self.build_started = threading.Event()
+ self.resume_build = threading.Event()
+
+ def build(self, dataset):
+ self.build_attempts += 1
+ if self.block_build:
+ self.build_started.set()
+ assert self.resume_build.wait(timeout=5)
+ return super().build(dataset)
+
+ runtime = RaceBuildRuntime()
+ monkeypatch.setattr(
+ cuvs_index,
+ "_CuVSRuntime",
+ lambda _algorithm, _metric, _build_params, _search_params, _dtype: runtime,
+ )
+ collection = get_or_create_local_collection(
+ meta_data={
+ "CollectionName": "auto_cuvs_clean_dirty_race",
+ "Fields": [
+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
+ {"FieldName": "vector", "FieldType": "vector", "Dim": 4},
+ ],
+ },
+ config={
+ "dense_search": {
+ "backend": "auto_cuvs",
+ "algorithm": "brute_force",
+ "filter_cache_size": 0,
+ "auto_memory_reserve_mb": 0,
+ "auto_memory_safety_factor": 1.0,
+ "auto_background_rebuild": True,
+ "auto_rebuild_debounce_ms": 0,
+ }
+ },
+ )
+ try:
+ index = collection.create_index(
+ "default",
+ {
+ "IndexName": "default",
+ "VectorIndex": {"IndexType": "flat", "Distance": "cosine"},
+ },
+ )
+ collection.upsert_data([{"id": "first", "vector": [1.0, 0.0, 0.0, 0.0]}])
+ assert index.wait_for_background_rebuild(timeout=5)
+ assert runtime.build_attempts == 1
+
+ original_search_cuvs = index._search_cuvs
+ mutation_injected = threading.Event()
+ runtime.block_build = True
+
+ def inject_mutation_after_clean_check(*args, **kwargs):
+ if not mutation_injected.is_set():
+ mutation_injected.set()
+ collection.update_data([{"id": "first", "vector": [0.0, 1.0, 0.0, 0.0]}])
+ assert runtime.build_started.wait(timeout=5)
+ return original_search_cuvs(*args, **kwargs)
+
+ monkeypatch.setattr(index, "_search_cuvs", inject_mutation_after_clean_check)
+ executor = ThreadPoolExecutor(max_workers=1)
+ try:
+ future = executor.submit(
+ collection.search_by_vector,
+ "default",
+ dense_vector=[0.0, 1.0, 0.0, 0.0],
+ limit=1,
+ )
+ # The request routes to the current native index even while the sole
+ # rebuild for this generation is blocked in the background worker.
+ assert [item.id for item in future.result(timeout=1).data] == ["first"]
+ finally:
+ runtime.resume_build.set()
+ executor.shutdown(wait=True)
+
+ assert runtime.build_attempts == 2
+ assert index.wait_for_background_rebuild(timeout=5)
+ assert runtime.build_attempts == 2
+ finally:
+ runtime.resume_build.set()
+ collection.close()
+
+
+def test_auto_cuvs_background_failure_surfaces_to_wait_and_query(monkeypatch):
+ class FailingBuildRuntime(MemoryAwareFakeCuVSRuntime):
+ def __init__(self):
+ super().__init__("inner_product", free_memory_bytes=1 << 20)
+ self.fail_build = True
+
+ def build(self, dataset):
+ if self.fail_build:
+ raise RuntimeError("injected background build failure")
+ return super().build(dataset)
+
+ runtime = FailingBuildRuntime()
+ monkeypatch.setattr(
+ cuvs_index,
+ "_CuVSRuntime",
+ lambda _algorithm, _metric, _build_params, _search_params, _dtype: runtime,
+ )
+ collection = get_or_create_local_collection(
+ meta_data={
+ "CollectionName": "auto_cuvs_background_failure",
+ "Fields": [
+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
+ {"FieldName": "vector", "FieldType": "vector", "Dim": 4},
+ ],
+ },
+ config={
+ "dense_search": {
+ "backend": "auto_cuvs",
+ "algorithm": "brute_force",
+ "filter_cache_size": 0,
+ "auto_memory_reserve_mb": 0,
+ "auto_memory_safety_factor": 1.0,
+ "auto_background_rebuild": True,
+ "auto_rebuild_debounce_ms": 0,
+ }
+ },
+ )
+ try:
+ index = collection.create_index(
+ "default",
+ {
+ "IndexName": "default",
+ "VectorIndex": {"IndexType": "flat", "Distance": "cosine"},
+ },
+ )
+ collection.upsert_data([{"id": "first", "vector": [1.0, 0.0, 0.0, 0.0]}])
+
+ with pytest.raises(RuntimeError, match="injected background build failure"):
+ index.wait_for_background_rebuild(timeout=5)
+ with pytest.raises(RuntimeError, match="injected background build failure"):
+ collection.search_by_vector(
+ "default",
+ dense_vector=[1.0, 0.0, 0.0, 0.0],
+ limit=1,
+ )
+
+ # A later mutation is a new rebuild generation and clears the stale
+ # failure, allowing a transient runtime problem to recover.
+ runtime.fail_build = False
+ collection.update_data([{"id": "first", "vector": [0.0, 1.0, 0.0, 0.0]}])
+ assert index.wait_for_background_rebuild(timeout=5)
+ assert (
+ collection.search_by_vector(
+ "default",
+ dense_vector=[0.0, 1.0, 0.0, 0.0],
+ limit=1,
+ )
+ .data[0]
+ .id
+ == "first"
+ )
+ finally:
+ collection.close()
+
+
+def test_auto_cuvs_background_memory_fallback_retries_on_later_query(monkeypatch):
+ runtime = MemoryAwareFakeCuVSRuntime("inner_product", free_memory_bytes=31)
+ monkeypatch.setattr(
+ cuvs_index,
+ "_CuVSRuntime",
+ lambda _algorithm, _metric, _build_params, _search_params, _dtype: runtime,
+ )
+ collection = get_or_create_local_collection(
+ meta_data={
+ "CollectionName": "auto_cuvs_background_memory_retry",
+ "Fields": [
+ {"FieldName": "id", "FieldType": "string", "IsPrimaryKey": True},
+ {"FieldName": "vector", "FieldType": "vector", "Dim": 4},
+ ],
+ },
+ config={
+ "dense_search": {
+ "backend": "auto_cuvs",
+ "algorithm": "brute_force",
+ "filter_cache_size": 0,
+ "auto_memory_reserve_mb": 0,
+ "auto_memory_safety_factor": 1.0,
+ "auto_background_rebuild": True,
+ "auto_rebuild_debounce_ms": 0,
+ }
+ },
+ )
+ try:
+ index = collection.create_index(
+ "default",
+ {
+ "IndexName": "default",
+ "VectorIndex": {"IndexType": "flat", "Distance": "cosine"},
+ },
+ )
+ collection.upsert_data(
+ [
+ {"id": "first", "vector": [1.0, 0.0, 0.0, 0.0]},
+ {"id": "second", "vector": [0.0, 1.0, 0.0, 0.0]},
+ ]
+ )
+ assert index._dense_rebuild_completed.wait(timeout=5)
+ assert index.dense_search.needs_rebuild
+ assert runtime.build_count == 0
+
+ runtime.free_memory_bytes = 32
+ result = collection.search_by_vector("default", dense_vector=[1.0, 0.0, 0.0, 0.0], limit=1)
+ assert [item.id for item in result.data] == ["first"]
+ assert index.wait_for_background_rebuild(timeout=5)
+ assert runtime.build_count == 1
+
+ result = collection.search_by_vector("default", dense_vector=[1.0, 0.0, 0.0, 0.0], limit=1)
+ assert [item.id for item in result.data] == ["first"]
+ assert runtime.search_count == 1
+ finally:
+ collection.close()
+
+
def test_auto_cuvs_selective_first_query_skips_gpu_build(monkeypatch):
runtimes = []
+ dense_search_calls = 0
- def make_runtime(_algorithm, metric, _build_params, _search_params):
- runtime = MemoryAwareFakeCuVSRuntime(metric, free_memory_bytes=32)
+ original_search = cuvs_index.CuVSDenseIndex.search
+
+ def tracked_search(self, *args, **kwargs):
+ nonlocal dense_search_calls
+ dense_search_calls += 1
+ return original_search(self, *args, **kwargs)
+
+ def make_runtime(_algorithm, metric, _build_params, _search_params, _dtype):
+ runtime = MemoryAwareFakeCuVSRuntime(metric, free_memory_bytes=64)
runtimes.append(runtime)
return runtime
monkeypatch.setattr(cuvs_index, "_CuVSRuntime", make_runtime)
+ monkeypatch.setattr(cuvs_index.CuVSDenseIndex, "search", tracked_search)
collection = get_or_create_local_collection(
meta_data={
"CollectionName": "auto_cuvs_selective_first",
@@ -315,7 +1119,7 @@ def test_auto_cuvs_selective_first_query_skips_gpu_build(monkeypatch):
"dense_search": {
"backend": "auto_cuvs",
"algorithm": "brute_force",
- "filter_cache_size": 0,
+ "filter_cache_size": 1,
"auto_memory_reserve_mb": 0,
"auto_memory_safety_factor": 1.0,
"auto_filter_native_threshold": 1,
@@ -346,6 +1150,22 @@ def test_auto_cuvs_selective_first_query_skips_gpu_build(monkeypatch):
]
)
+ telemetry = MemoryOperationTelemetry(operation="search.find", enabled=True)
+ with bind_telemetry(telemetry):
+ result = collection.search_by_vector(
+ "default",
+ dense_vector=[1.0, 0.0, 0.0, 0.0],
+ limit=1,
+ filters={"op": "must", "field": "account_id", "conds": ["a"]},
+ )
+ assert [item.id for item in result.data] == ["first"]
+ cuvs = telemetry.finish().summary["vector"]["cuvs"]
+ assert cuvs["routes"] == {"native_filter_threshold": 1}
+ assert cuvs["native_filter_reuses"] == 1
+ assert dense_search_calls == 0
+ assert runtimes[0].build_count == 0
+ assert runtimes[0].search_count == 0
+
result = collection.search_by_vector(
"default",
dense_vector=[1.0, 0.0, 0.0, 0.0],
@@ -353,11 +1173,11 @@ def test_auto_cuvs_selective_first_query_skips_gpu_build(monkeypatch):
filters={"op": "must", "field": "account_id", "conds": ["a"]},
)
assert [item.id for item in result.data] == ["first"]
- assert runtimes[0].build_count == 0
- assert runtimes[0].search_count == 0
+ assert dense_search_calls == 0
result = collection.search_by_vector("default", dense_vector=[1.0, 0.0, 0.0, 0.0], limit=1)
assert [item.id for item in result.data] == ["first"]
+ assert dense_search_calls == 1
assert runtimes[0].build_count == 1
assert runtimes[0].search_count == 1
finally:
diff --git a/tests/vectordb/test_cuvs_config.py b/tests/vectordb/test_cuvs_config.py
index fbc10b095..71b15a19d 100644
--- a/tests/vectordb/test_cuvs_config.py
+++ b/tests/vectordb/test_cuvs_config.py
@@ -12,13 +12,20 @@ from openviking_cli.utils.config.vectordb_config import CuVSConfig, VectorDBBack
def test_cuvs_filter_cache_defaults_and_disable_value():
+ assert CuVSConfig().dtype == "float32"
+ assert CuVSConfig(dtype="float16").dtype == "float16"
+ assert CuVSConfig().max_concurrent_gpu_searches == 1
assert CuVSConfig().filter_cache_size == 16
assert CuVSConfig(filter_cache_size=0).filter_cache_size == 0
def test_cuvs_filter_cache_rejects_negative_size():
+ with pytest.raises(ValidationError, match="dtype"):
+ CuVSConfig(dtype="int8")
with pytest.raises(ValidationError, match="filter_cache_size"):
CuVSConfig(filter_cache_size=-1)
+ with pytest.raises(ValidationError, match="max_concurrent_gpu_searches"):
+ CuVSConfig(max_concurrent_gpu_searches=0)
def test_cuvs_auto_mode_is_opt_in_and_validates_memory_guardrails():
@@ -28,6 +35,8 @@ def test_cuvs_auto_mode_is_opt_in_and_validates_memory_guardrails():
assert config.auto_memory_safety_factor == 2.0
assert config.auto_filter_native_threshold == 2000
assert config.auto_path_filter_native_threshold == 200
+ assert config.auto_background_rebuild is False
+ assert config.auto_rebuild_debounce_ms == 500
with pytest.raises(ValidationError, match="auto_memory_reserve_mb"):
CuVSConfig(auto_memory_reserve_mb=-1)
@@ -37,6 +46,8 @@ def test_cuvs_auto_mode_is_opt_in_and_validates_memory_guardrails():
CuVSConfig(auto_filter_native_threshold=-1)
with pytest.raises(ValidationError, match="auto_path_filter_native_threshold"):
CuVSConfig(auto_path_filter_native_threshold=-1)
+ with pytest.raises(ValidationError, match="auto_rebuild_debounce_ms"):
+ CuVSConfig(auto_rebuild_debounce_ms=-1)
def test_local_adapter_only_passes_auto_cuvs_config_when_enabled():
diff --git a/tests/vectordb/test_cuvs_index.py b/tests/vectordb/test_cuvs_index.py
index 0aa7dacfb..0cf878639 100644
--- a/tests/vectordb/test_cuvs_index.py
+++ b/tests/vectordb/test_cuvs_index.py
@@ -1,14 +1,20 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
+import threading
+import time
+from concurrent.futures import ThreadPoolExecutor
+
import pytest
from openviking.storage.vectordb.index.cuvs_index import (
CuVSDenseIndex,
CuVSMemoryBudgetError,
CuVSNativeRouteError,
+ CuVSSearchTelemetry,
CuVSUnavailableError,
UnsupportedCuVSFilterError,
+ _CuVSRuntime,
estimate_cuvs_memory,
matches_filter,
)
@@ -70,6 +76,274 @@ class FakeCuVSRuntime:
self.closed = True
+def test_cuvs_runtime_uses_captured_device_from_worker_thread():
+ """Every CUDA call must select the device captured by the runtime."""
+
+ class DeviceSpy:
+ def __init__(self, expected_device):
+ self.expected_device = expected_device
+ self.local = threading.local()
+ self.lock = threading.Lock()
+ self.operations = []
+ self.releases = []
+ self.temporary_releases = []
+ self.track_temporaries = False
+ self.temporary_count = 0
+ self.resource_count = 0
+ self.fail_build = False
+ self.fail_search = False
+
+ def set_current(self, device_id):
+ self.local.current = device_id
+
+ def current(self):
+ return getattr(self.local, "current", None)
+
+ def require_captured_device(self, operation):
+ assert self.current() == self.expected_device, operation
+ with self.lock:
+ self.operations.append(operation)
+
+ def device(self, device_id):
+ spy = self
+
+ class DeviceContext:
+ def __enter__(self):
+ self.previous = spy.current()
+ spy.set_current(device_id)
+ return self
+
+ def __exit__(self, _exc_type, _exc, _traceback):
+ spy.set_current(self.previous)
+
+ return DeviceContext()
+
+ spy = DeviceSpy(expected_device=3)
+
+ class FakeArray:
+ def __init__(self, values, dtype, release_name=None):
+ self.values = values
+ self.dtype = dtype
+ self.release_name = release_name
+
+ def __getitem__(self, offset):
+ value = self.values[offset]
+
+ class HostRow(list):
+ def tolist(self):
+ return list(self)
+
+ return HostRow(value) if isinstance(value, list) else value
+
+ def __del__(self):
+ if self.release_name is not None:
+ spy.temporary_releases.append((self.release_name, spy.current()))
+
+ class FakeRuntimeAPI:
+ @staticmethod
+ def memGetInfo():
+ spy.require_captured_device("memory_info")
+ return 100, 200
+
+ class FakeMemory:
+ class OutOfMemoryError(Exception):
+ pass
+
+ class FakeCuda:
+ runtime = FakeRuntimeAPI()
+ memory = FakeMemory()
+
+ @staticmethod
+ def Device(device_id):
+ return spy.device(device_id)
+
+ class FakeMemoryPool:
+ @staticmethod
+ def free_all_blocks():
+ spy.require_captured_device("release_index")
+
+ class FakeCuPy:
+ float16 = "float16"
+ float32 = "float32"
+ uint32 = "uint32"
+ ndarray = FakeArray
+ cuda = FakeCuda()
+
+ @staticmethod
+ def asarray(values, dtype):
+ spy.require_captured_device("asarray")
+ release_name = None
+ if spy.track_temporaries:
+ spy.temporary_count += 1
+ release_name = f"array-{spy.temporary_count}"
+ return FakeArray(values, dtype, release_name)
+
+ @staticmethod
+ def asnumpy(values):
+ spy.require_captured_device("asnumpy")
+ return values
+
+ @staticmethod
+ def get_default_memory_pool():
+ spy.require_captured_device("memory_pool")
+ return FakeMemoryPool()
+
+ class FakeResources:
+ def __init__(self):
+ spy.require_captured_device("resources_create")
+ spy.resource_count += 1
+ self.name = f"resources-{spy.resource_count}"
+ self.device_id = spy.current()
+
+ def sync(self):
+ spy.require_captured_device("resources_sync")
+ assert spy.current() == self.device_id
+
+ def __del__(self):
+ spy.releases.append((self.name, spy.current()))
+
+ class FakeBruteForce:
+ @staticmethod
+ def build(_dataset, metric):
+ spy.require_captured_device("build")
+ assert metric == "inner_product"
+ if spy.fail_build:
+ raise RuntimeError("injected build failure")
+ return object()
+
+ @staticmethod
+ def search(_index, _queries, limit, prefilter, resources):
+ spy.require_captured_device("search")
+ assert limit == 1
+ assert prefilter is not None
+ assert resources.device_id == spy.expected_device
+ if spy.fail_search:
+ raise RuntimeError("injected search failure")
+ return FakeArray([[0.25]], "float32", "distances"), FakeArray(
+ [[0]], "int64", "neighbors"
+ )
+
+ class FakeFilters:
+ @staticmethod
+ def from_bitset(bitset):
+ spy.require_captured_device("filter")
+ return bitset
+
+ runtime = _CuVSRuntime.__new__(_CuVSRuntime)
+ runtime.cp = FakeCuPy()
+ runtime.brute_force = FakeBruteForce()
+ runtime.cagra = object()
+ runtime.filters = FakeFilters()
+ runtime.Resources = FakeResources
+ runtime.device_id = spy.expected_device
+ runtime.dtype = "float32"
+ runtime.device_dtype = FakeCuPy.float32
+ runtime.algorithm = "brute_force"
+ runtime.metric = "inner_product"
+ runtime.build_params = {}
+ runtime.search_params = {}
+ runtime._resource_condition = threading.Condition(threading.Lock())
+ runtime._available_resources = []
+ runtime._owned_resources = []
+ runtime._resource_limit = 1
+ runtime._resources_closed = False
+ runtime._use_explicit_resources = False
+ runtime.set_max_concurrent_searches(2)
+ constructing_thread = threading.get_ident()
+
+ def use_runtime_from_worker():
+ assert threading.get_ident() != constructing_thread
+ spy.set_current(9)
+
+ assert runtime.memory_info() == (100, 200)
+ assert spy.current() == 9
+ runtime_index = runtime.build([[1.0, 0.0]])
+ assert spy.current() == 9
+ runtime.prepare_filter([True])
+ runtime.prepare_filter_words([1])
+ runtime._prefilter([True])
+ assert spy.current() == 9
+ spy.track_temporaries = True
+ assert runtime.search(runtime_index, [1.0, 0.0], 1, [True]) == ([0], [0.25])
+ spy.track_temporaries = False
+ assert {name for name, _device in spy.temporary_releases} == {
+ "array-1",
+ "array-2",
+ "distances",
+ "neighbors",
+ }
+ assert all(device == 3 for _name, device in spy.temporary_releases)
+ assert spy.current() == 9
+ spy.fail_build = True
+ spy.track_temporaries = True
+ with pytest.raises(RuntimeError, match="injected build failure"):
+ runtime.build([[0.0, 1.0]])
+ spy.fail_build = False
+ spy.track_temporaries = False
+ assert ("array-3", 3) in spy.temporary_releases
+ assert spy.current() == 9
+ spy.fail_search = True
+ spy.track_temporaries = True
+ with pytest.raises(RuntimeError, match="injected search failure"):
+ runtime.search(runtime_index, [0.0, 1.0], 1, [True])
+ spy.fail_search = False
+ spy.track_temporaries = False
+ assert ("array-4", 3) in spy.temporary_releases
+ assert ("array-5", 3) in spy.temporary_releases
+ assert spy.current() == 9
+ assert spy.releases == [("resources-1", 3)]
+ assert runtime.search(runtime_index, [1.0, 0.0], 1, [True]) == ([0], [0.25])
+ runtime.release_index()
+ assert spy.current() == 9
+ return runtime_index
+
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ runtime_index = executor.submit(use_runtime_from_worker).result(timeout=5)
+
+ churn_errors = []
+
+ def search_from_short_lived_thread():
+ try:
+ spy.set_current(9)
+ assert runtime.search(runtime_index, [1.0, 0.0], 1, [True]) == ([0], [0.25])
+ assert spy.current() == 9
+ except BaseException as exc:
+ churn_errors.append(exc)
+
+ for _ in range(8):
+ thread = threading.Thread(target=search_from_short_lived_thread)
+ thread.start()
+ thread.join(timeout=5)
+ assert not thread.is_alive()
+
+ assert churn_errors == []
+ assert spy.resource_count == 2
+ assert len(runtime._owned_resources) <= 2
+ assert len(runtime._available_resources) == 1
+
+ # A failed search discarded the first resource under device 3. The bounded
+ # pool reused the replacement across short-lived threads and retains it
+ # until close can also destroy it on the captured device.
+ assert spy.releases == [("resources-1", 3)]
+ spy.set_current(9)
+ runtime.close()
+ assert spy.current() == 9
+ assert spy.releases == [("resources-1", 3), ("resources-2", 3)]
+
+ assert {
+ "memory_info",
+ "memory_pool",
+ "release_index",
+ "asarray",
+ "build",
+ "resources_create",
+ "resources_sync",
+ "filter",
+ "search",
+ "asnumpy",
+ } <= set(spy.operations)
+
+
def candidate(label, vector, **fields):
import json
@@ -82,6 +356,215 @@ def delta(label, vector, **fields):
return DeltaRecord(label=label, vector=vector, fields=json.dumps(fields))
+def test_cuvs_rebuild_objects_are_released_on_the_captured_device():
+ class DeviceOwned:
+ def __init__(self, runtime, name):
+ self.runtime = runtime
+ self.name = name
+
+ def __del__(self):
+ self.runtime.released.append((self.name, self.runtime.current_device))
+
+ class LifecycleRuntime:
+ def __init__(self):
+ self.current_device = 9
+ self.build_count = 0
+ self.released = []
+ self.closed = False
+
+ def device_scope(self):
+ runtime = self
+
+ class DeviceContext:
+ def __enter__(self):
+ self.previous = runtime.current_device
+ runtime.current_device = 3
+
+ def __exit__(self, _exc_type, _exc, _traceback):
+ runtime.current_device = self.previous
+
+ return DeviceContext()
+
+ def build(self, _dataset):
+ self.build_count += 1
+ return DeviceOwned(self, f"build-{self.build_count}")
+
+ def close(self):
+ assert self.current_device == 3
+ self.closed = True
+
+ runtime = LifecycleRuntime()
+ index = CuVSDenseIndex(
+ dimension=2,
+ distance="ip",
+ normalize_vectors=False,
+ field_types={},
+ config={},
+ runtime=runtime,
+ )
+ index.add_candidates([candidate(1, [1.0, 0.0])])
+
+ first = index.prepare_rebuild()
+ assert first is not None and index.commit_rebuild(first)
+
+ # Preparing a replacement drops the unused snapshot in the device scope.
+ index.upsert([delta(2, [0.0, 1.0])])
+ stale = index.prepare_rebuild()
+ assert stale is not None
+ assert ("build-1", 3) in runtime.released
+
+ # A mutation makes the candidate stale; rejecting it releases its GPU data
+ # on the captured device rather than whichever device this thread inherited.
+ index.upsert([delta(3, [1.0, 1.0])])
+ assert index.commit_rebuild(stale) is False
+ assert ("build-2", 3) in runtime.released
+
+ abandoned = index.prepare_rebuild()
+ assert abandoned is not None
+ index.discard_rebuild(abandoned)
+ assert ("build-3", 3) in runtime.released
+
+ final = index.prepare_rebuild()
+ assert final is not None and index.commit_rebuild(final)
+ index.close()
+ assert runtime.closed is True
+ assert ("build-4", 3) in runtime.released
+ assert runtime.current_device == 9
+
+
+def test_inflight_snapshot_is_released_on_captured_device_after_replacement():
+ class DeviceOwned:
+ def __init__(self, runtime, name):
+ self.runtime = runtime
+ self.name = name
+
+ def __del__(self):
+ self.runtime.released.append((self.name, self.runtime.current_device()))
+
+ class ConcurrentLifecycleRuntime:
+ def __init__(self):
+ self.local = threading.local()
+ self.build_count = 0
+ self.released = []
+ self.search_started = threading.Event()
+ self.resume_search = threading.Event()
+
+ def set_current_device(self, device_id):
+ self.local.current_device = device_id
+
+ def current_device(self):
+ return getattr(self.local, "current_device", None)
+
+ def device_scope(self):
+ runtime = self
+
+ class DeviceContext:
+ def __enter__(self):
+ self.previous = runtime.current_device()
+ runtime.set_current_device(3)
+
+ def __exit__(self, _exc_type, _exc, _traceback):
+ runtime.set_current_device(self.previous)
+
+ return DeviceContext()
+
+ def build(self, _dataset):
+ self.build_count += 1
+ return DeviceOwned(self, f"build-{self.build_count}")
+
+ def search(self, _index, _query, _limit, _mask):
+ self.search_started.set()
+ assert self.resume_search.wait(timeout=5)
+ return [0], [1.0]
+
+ def close(self):
+ assert self.current_device() == 3
+
+ runtime = ConcurrentLifecycleRuntime()
+ runtime.set_current_device(9)
+ index = CuVSDenseIndex(
+ dimension=2,
+ distance="ip",
+ normalize_vectors=False,
+ field_types={},
+ config={"max_concurrent_gpu_searches": 2},
+ runtime=runtime,
+ )
+ index.add_candidates([candidate(1, [1.0, 0.0])])
+ first = index.prepare_rebuild()
+ assert first is not None and index.commit_rebuild(first)
+
+ def search_from_other_device():
+ runtime.set_current_device(9)
+ result = index.search([1.0, 0.0], 1, None)
+ assert runtime.current_device() == 9
+ return result
+
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ inflight = executor.submit(search_from_other_device)
+ assert runtime.search_started.wait(timeout=5)
+ index.upsert([delta(2, [0.0, 1.0])])
+ replacement = index.prepare_rebuild()
+ assert replacement is not None and index.commit_rebuild(replacement)
+ assert runtime.released == []
+ runtime.resume_search.set()
+ assert inflight.result(timeout=5)[0] == [1]
+
+ assert ("build-1", 3) in runtime.released
+ index.close()
+ assert ("build-2", 3) in runtime.released
+ assert runtime.current_device() == 9
+
+
+def test_cuvs_rebuild_candidate_cannot_be_committed_twice():
+ runtime = FakeCuVSRuntime()
+ index = CuVSDenseIndex(
+ dimension=2,
+ distance="ip",
+ normalize_vectors=False,
+ field_types={},
+ config={},
+ runtime=runtime,
+ )
+ index.add_candidates([candidate(1, [1.0, 0.0])])
+ rebuild = index.prepare_rebuild()
+ assert rebuild is not None and index.commit_rebuild(rebuild)
+
+ with pytest.raises(RuntimeError, match="already been consumed"):
+ index.commit_rebuild(rebuild)
+
+ assert index.needs_rebuild is False
+ assert index.search([1.0, 0.0], 1, None)[0] == [1]
+
+
+def test_cuvs_registrar_failure_consumes_candidate_without_marking_clean():
+ runtime = FakeCuVSRuntime()
+ index = CuVSDenseIndex(
+ dimension=2,
+ distance="ip",
+ normalize_vectors=False,
+ field_types={},
+ config={},
+ runtime=runtime,
+ )
+ index.add_candidates([candidate(1, [1.0, 0.0])])
+ rebuild = index.prepare_rebuild()
+ assert rebuild is not None
+
+ def fail_registration(_labels):
+ raise RuntimeError("injected registrar failure")
+
+ with pytest.raises(RuntimeError, match="injected registrar failure"):
+ index.commit_rebuild(rebuild, fail_registration)
+ assert index.needs_rebuild is True
+ with pytest.raises(RuntimeError, match="already been consumed"):
+ index.commit_rebuild(rebuild)
+
+ replacement = index.prepare_rebuild()
+ assert replacement is not None and index.commit_rebuild(replacement)
+ assert index.search([1.0, 0.0], 1, None)[0] == [1]
+
+
def test_cuvs_dense_search_handles_filter_upsert_delete_and_lazy_rebuild():
runtime = FakeCuVSRuntime()
index = CuVSDenseIndex(
@@ -126,6 +609,256 @@ def test_cuvs_dense_search_handles_filter_upsert_delete_and_lazy_rebuild():
assert runtime.build_count == 3
+def test_empty_filter_does_not_allocate_a_device_bitset():
+ class SearchCountingRuntime(FakeCuVSRuntime):
+ def __init__(self):
+ super().__init__()
+ self.search_count = 0
+
+ def search(self, index, query, limit, mask):
+ self.search_count += 1
+ return super().search(index, query, limit, mask)
+
+ runtime = SearchCountingRuntime()
+ index = CuVSDenseIndex(
+ dimension=2,
+ distance="ip",
+ normalize_vectors=False,
+ field_types={"tenant": "string"},
+ config={"filter_cache_size": 0},
+ runtime=runtime,
+ )
+ index.add_candidates([candidate(1, [1.0, 0.0], tenant="a")])
+
+ assert index.search(
+ [1.0, 0.0],
+ 1,
+ {"op": "must", "field": "tenant", "conds": ["missing"]},
+ ) == ([], [])
+ assert runtime.prepare_filter_count == 0
+ assert runtime.search_count == 0
+
+
+def test_cuvs_search_telemetry_records_build_filter_cache_and_search():
+ runtime = FakeCuVSRuntime()
+ index = CuVSDenseIndex(
+ dimension=2,
+ distance="ip",
+ normalize_vectors=False,
+ field_types={"account_id": "string"},
+ config={"algorithm": "brute_force"},
+ runtime=runtime,
+ )
+ index.add_candidates(
+ [
+ candidate(1, [1.0, 0.0], account_id="a"),
+ candidate(2, [0.0, 1.0], account_id="b"),
+ ]
+ )
+ filter_a = {"op": "must", "field": "account_id", "conds": ["a"]}
+
+ first = CuVSSearchTelemetry(algorithm="brute_force", auto_mode=False)
+ assert index.search([1.0, 0.0], 1, filter_a, telemetry=first)[0] == [1]
+ assert first.build_performed is True
+ assert first.filter_kind == "scalar"
+ assert first.filter_cache_hit is False
+ assert first.eligible_count == 1
+ assert first.index_size == 2
+ assert first.build_ms >= 0
+ assert first.filter_prepare_ms >= 0
+ assert first.gpu_search_ms >= 0
+
+ second = CuVSSearchTelemetry(algorithm="brute_force", auto_mode=False)
+ assert index.search([1.0, 0.0], 1, filter_a, telemetry=second)[0] == [1]
+ assert second.build_performed is False
+ assert second.filter_cache_hit is True
+ assert second.eligible_count == 1
+
+
+def test_warmed_cuvs_searches_run_concurrently():
+ class ConcurrentRuntime(FakeCuVSRuntime):
+ def __init__(self):
+ super().__init__()
+ self.barrier = threading.Barrier(4)
+ self.active_lock = threading.Lock()
+ self.active = 0
+ self.peak_active = 0
+
+ def search(self, index, query, limit, mask):
+ with self.active_lock:
+ self.active += 1
+ self.peak_active = max(self.peak_active, self.active)
+ try:
+ self.barrier.wait(timeout=5)
+ return super().search(index, query, limit, mask)
+ finally:
+ with self.active_lock:
+ self.active -= 1
+
+ runtime = ConcurrentRuntime()
+ index = CuVSDenseIndex(
+ dimension=2,
+ distance="ip",
+ normalize_vectors=False,
+ field_types={},
+ config={"max_concurrent_gpu_searches": 4},
+ runtime=runtime,
+ )
+ index.add_candidates([candidate(1, [1.0, 0.0])])
+ # Build without entering the barrier.
+ runtime.barrier = threading.Barrier(1)
+ assert index.search([1.0, 0.0], 1, None)[0] == [1]
+ runtime.barrier = threading.Barrier(4)
+
+ with ThreadPoolExecutor(max_workers=4) as executor:
+ futures = [executor.submit(index.search, [1.0, 0.0], 1, None) for _ in range(4)]
+ assert [future.result(timeout=5)[0] for future in futures] == [[1]] * 4
+
+ assert runtime.peak_active == 4
+
+
+def test_cuvs_gpu_search_gate_serializes_kernels_by_default():
+ class SerialRuntime(FakeCuVSRuntime):
+ def __init__(self):
+ super().__init__()
+ self.active_lock = threading.Lock()
+ self.active = 0
+ self.peak_active = 0
+
+ def search(self, index, query, limit, mask):
+ with self.active_lock:
+ self.active += 1
+ self.peak_active = max(self.peak_active, self.active)
+ try:
+ time.sleep(0.01)
+ return super().search(index, query, limit, mask)
+ finally:
+ with self.active_lock:
+ self.active -= 1
+
+ runtime = SerialRuntime()
+ index = CuVSDenseIndex(
+ dimension=2,
+ distance="ip",
+ normalize_vectors=False,
+ field_types={},
+ config={},
+ runtime=runtime,
+ )
+ index.add_candidates([candidate(1, [1.0, 0.0])])
+ assert index.search([1.0, 0.0], 1, None)[0] == [1]
+
+ telemetry = [CuVSSearchTelemetry(algorithm="brute_force", auto_mode=False) for _ in range(4)]
+ with ThreadPoolExecutor(max_workers=4) as executor:
+ futures = [
+ executor.submit(index.search, [1.0, 0.0], 1, None, None, None, item)
+ for item in telemetry
+ ]
+ assert [future.result(timeout=5)[0] for future in futures] == [[1]] * 4
+
+ assert runtime.peak_active == 1
+ assert max(item.queue_ms for item in telemetry) > 0
+
+
+def test_inflight_search_keeps_immutable_snapshot_during_rebuild():
+ class BlockingRuntime(FakeCuVSRuntime):
+ def __init__(self):
+ super().__init__()
+ self.block_next = False
+ self.search_started = threading.Event()
+ self.resume_search = threading.Event()
+
+ def search(self, index, query, limit, mask):
+ if self.block_next:
+ self.block_next = False
+ self.search_started.set()
+ assert self.resume_search.wait(timeout=5)
+ return super().search(index, query, limit, mask)
+
+ runtime = BlockingRuntime()
+ index = CuVSDenseIndex(
+ dimension=2,
+ distance="ip",
+ normalize_vectors=False,
+ field_types={},
+ config={"max_concurrent_gpu_searches": 2},
+ runtime=runtime,
+ )
+ index.add_candidates([candidate(1, [1.0, 0.0])])
+ assert index.search([1.0, 0.0], 1, None)[0] == [1]
+
+ runtime.block_next = True
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ inflight = executor.submit(index.search, [1.0, 0.0], 1, None)
+ assert runtime.search_started.wait(timeout=5)
+ index.upsert([delta(2, [2.0, 0.0])])
+ assert index.search([1.0, 0.0], 1, None)[0] == [2]
+ runtime.resume_search.set()
+ assert inflight.result(timeout=5)[0] == [1]
+
+ assert runtime.build_count == 2
+
+
+def test_auto_memory_coordinator_serializes_builds_on_same_device():
+ class CoordinatedRuntime(FakeCuVSRuntime):
+ def __init__(self):
+ super().__init__()
+ self.device_id = 7
+ self.first_build_started = threading.Event()
+ self.resume_first_build = threading.Event()
+ self.build_lock = threading.Lock()
+ self.build_attempts = 0
+ self.active_builds = 0
+ self.peak_active_builds = 0
+
+ def build(self, dataset):
+ with self.build_lock:
+ self.build_attempts += 1
+ attempt = self.build_attempts
+ self.active_builds += 1
+ self.peak_active_builds = max(self.peak_active_builds, self.active_builds)
+ try:
+ if attempt == 1:
+ self.first_build_started.set()
+ assert self.resume_first_build.wait(timeout=5)
+ return super().build(dataset)
+ finally:
+ with self.build_lock:
+ self.active_builds -= 1
+
+ runtime = CoordinatedRuntime()
+
+ def make_index(label):
+ index = CuVSDenseIndex(
+ dimension=2,
+ distance="ip",
+ normalize_vectors=False,
+ field_types={},
+ config={
+ "filter_cache_size": 0,
+ "auto_memory_reserve_mb": 0,
+ "auto_memory_safety_factor": 1.0,
+ },
+ runtime=runtime,
+ auto_memory=True,
+ )
+ index.add_candidates([candidate(label, [1.0, 0.0])])
+ return index
+
+ first = make_index(1)
+ second = make_index(2)
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ first_future = executor.submit(first.search, [1.0, 0.0], 1, None)
+ assert runtime.first_build_started.wait(timeout=5)
+ second_future = executor.submit(second.search, [1.0, 0.0], 1, None)
+ runtime.resume_first_build.set()
+ assert first_future.result(timeout=5)[0] == [1]
+ assert second_future.result(timeout=5)[0] == [2]
+
+ assert runtime.build_attempts == 2
+ assert runtime.peak_active_builds == 1
+
+
def test_cuvs_l2_scores_match_openviking_score_convention():
runtime = FakeCuVSRuntime(metric="sqeuclidean")
index = CuVSDenseIndex(
@@ -164,6 +897,29 @@ def test_cuvs_memory_estimate_accounts_for_fp32_graphs_and_filter_cache():
+ estimate.filter_cache_bytes
)
+ fp16 = estimate_cuvs_memory(
+ vector_count=1_000_000,
+ dimension=768,
+ algorithm="brute_force",
+ build_params={},
+ filter_cache_size=0,
+ safety_factor=1.0,
+ dtype="float16",
+ )
+ assert fp16.vector_bytes == 1_000_000 * 768 * 2
+
+
+def test_cuvs_rejects_unsupported_gpu_dtype():
+ with pytest.raises(ValueError, match="dtype"):
+ CuVSDenseIndex(
+ dimension=2,
+ distance="ip",
+ normalize_vectors=False,
+ field_types={},
+ config={"dtype": "int8"},
+ runtime=FakeCuVSRuntime(),
+ )
+
def test_auto_cuvs_retries_after_gpu_memory_becomes_available():
runtime = FakeCuVSRuntime()
@@ -184,14 +940,21 @@ def test_auto_cuvs_retries_after_gpu_memory_becomes_available():
)
index.add_candidates([candidate(1, [1.0, 0.0]), candidate(2, [0.0, 1.0])])
+ rejected = CuVSSearchTelemetry(algorithm="brute_force", auto_mode=True)
with pytest.raises(CuVSMemoryBudgetError, match="estimated GPU peak"):
- index.search([1.0, 0.0], 1, None)
+ index.search([1.0, 0.0], 1, None, telemetry=rejected)
assert runtime.build_count == 0
+ assert rejected.memory_estimated_peak_bytes == 16
+ assert rejected.memory_free_bytes == 15
+ assert rejected.memory_usable_bytes == 15
runtime.free_memory_bytes = 16
- assert index.search([1.0, 0.0], 1, None)[0] == [1]
+ admitted = CuVSSearchTelemetry(algorithm="brute_force", auto_mode=True)
+ assert index.search([1.0, 0.0], 1, None, telemetry=admitted)[0] == [1]
assert runtime.build_count == 1
assert runtime.release_count == 2
+ assert admitted.memory_estimated_peak_bytes == 16
+ assert admitted.memory_free_bytes == 16
def test_auto_cuvs_converts_gpu_allocation_failure_to_native_fallback_signal():
@@ -332,6 +1095,115 @@ def test_auto_mode_caches_native_route_for_selective_filter():
assert runtime.prepare_filter_count == 0
+def test_auto_mode_preflights_different_filters_concurrently():
+ runtime = FakeCuVSRuntime()
+ index = CuVSDenseIndex(
+ dimension=2,
+ distance="ip",
+ normalize_vectors=False,
+ field_types={"account_id": "string"},
+ config={
+ "auto_filter_native_threshold": 1,
+ "auto_memory_reserve_mb": 0,
+ "auto_memory_safety_factor": 1.0,
+ },
+ runtime=runtime,
+ auto_memory=True,
+ )
+ index.add_candidates(
+ [
+ candidate(10, [1.0, 0.0], account_id="a"),
+ candidate(20, [0.0, 1.0], account_id="b"),
+ ]
+ )
+ barrier = threading.Barrier(4)
+ active_lock = threading.Lock()
+ active = 0
+ peak_active = 0
+ registered_layouts = []
+
+ def register(ordered_labels):
+ registered_layouts.append(list(ordered_labels))
+
+ def resolve(_filters):
+ nonlocal active, peak_active
+ with active_lock:
+ active += 1
+ peak_active = max(peak_active, active)
+ barrier.wait(timeout=5)
+ with active_lock:
+ active -= 1
+ return [0b01], 1
+
+ filters = [
+ {"op": "must", "field": "account_id", "conds": [value]} for value in ("a", "b", "c", "d")
+ ]
+ with ThreadPoolExecutor(max_workers=4) as executor:
+ futures = [
+ executor.submit(index.preflight_native_count, item, resolve, register)
+ for item in filters
+ ]
+ routes = [future.result(timeout=5) for future in futures]
+
+ assert routes == [1] * 4
+ assert peak_active == 4
+ assert registered_layouts == [[10, 20]]
+
+
+def test_auto_mode_does_not_cache_preflight_across_record_change():
+ runtime = FakeCuVSRuntime()
+ index = CuVSDenseIndex(
+ dimension=2,
+ distance="ip",
+ normalize_vectors=False,
+ field_types={"account_id": "string"},
+ config={
+ "auto_filter_native_threshold": 1,
+ "auto_memory_reserve_mb": 0,
+ "auto_memory_safety_factor": 1.0,
+ },
+ runtime=runtime,
+ auto_memory=True,
+ )
+ index.add_candidates([candidate(10, [1.0, 0.0], account_id="a")])
+ filter_a = {"op": "must", "field": "account_id", "conds": ["a"]}
+ resolver_started = threading.Event()
+ resume_resolver = threading.Event()
+
+ def resolve(_filters):
+ resolver_started.set()
+ assert resume_resolver.wait(timeout=5)
+ return [0b1], 1
+
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(
+ index.preflight_native_count,
+ filter_a,
+ resolve,
+ lambda _labels: None,
+ )
+ assert resolver_started.wait(timeout=5)
+ index.add_candidates([candidate(20, [0.0, 1.0], account_id="b")])
+ resume_resolver.set()
+ assert future.result(timeout=5) is None
+
+ cache_miss_observed = threading.Event()
+
+ def resolve_after_change(_filters):
+ cache_miss_observed.set()
+ return [0b11], 2
+
+ assert (
+ index.preflight_native_count(
+ filter_a,
+ resolve_after_change,
+ lambda _labels: None,
+ )
+ is None
+ )
+ assert cache_miss_observed.is_set()
+
+
def test_auto_mode_selective_filter_skips_rebuild_after_mutation():
runtime = FakeCuVSRuntime()
index = CuVSDenseIndex(
@@ -435,10 +1307,19 @@ def test_auto_mode_wide_filter_reuses_preflight_bitmap_after_build():
resolve_count += 1
return [0b11], 2
+ filter_a = {"op": "must", "field": "account_id", "conds": ["a"]}
+ assert (
+ index.preflight_native_count(
+ filter_a,
+ resolve,
+ lambda _labels: None,
+ )
+ is None
+ )
labels, _ = index.search(
[1.0, 0.0],
2,
- {"op": "must", "field": "account_id", "conds": ["a"]},
+ filter_a,
resolve,
lambda _labels: None,
)
@@ -447,6 +1328,31 @@ def test_auto_mode_wide_filter_reuses_preflight_bitmap_after_build():
assert runtime.build_count == 1
+def test_auto_mode_retains_native_filter_token_for_selective_route():
+ runtime = FakeCuVSRuntime()
+ index = CuVSDenseIndex(
+ dimension=2,
+ distance="ip",
+ normalize_vectors=False,
+ field_types={"account_id": "string"},
+ config={"auto_filter_native_threshold": 1},
+ runtime=runtime,
+ auto_memory=True,
+ )
+ index.add_candidates([candidate(10, [1.0, 0.0], account_id="a")])
+ filter_a = {"op": "must", "field": "account_id", "conds": ["a"]}
+
+ assert (
+ index.preflight_native_count(
+ filter_a,
+ lambda _filters: ([0b1], 1, 17),
+ lambda _labels: None,
+ )
+ == 1
+ )
+ assert index.native_filter_token(filter_a) == 17
+
+
def test_auto_mode_uses_lower_native_threshold_for_path_filters():
runtime = FakeCuVSRuntime()
index = CuVSDenseIndex(