Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions openviking/storage/vectordb/index/local_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -1178,7 +1178,7 @@ def aggregate(
logger.debug(f"aggregate extra_json: {extra_json}")
except Exception as e:
logger.error(f"Aggregation operation failed: {e}")
return {}
raise

# Parse extra_json to get aggregation results
agg_data = {}
Expand All @@ -1188,10 +1188,15 @@ def aggregate(
logger.debug(f"aggregate parsed agg_data: {agg_data}")
except json.JSONDecodeError as e:
logger.error(f"Failed to parse aggregation results: {e}")
return {}
raise
else:
logger.warning("Aggregation results not available: extra_json is empty")
return {}
# The engine served the request but produced no aggregation
# payload. Surface the failure instead of an empty result, which
# callers cannot tell apart from a legitimate zero count.
raise RuntimeError(
"Aggregation results not available: engine returned no "
"aggregation payload (extra_json is empty)"
)

return agg_data

Expand Down
12 changes: 10 additions & 2 deletions src/index/detail/scalar/bitmap_holder/bitmap_field_group.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -449,9 +449,17 @@ BitmapPtr FieldBitmapGroupSet::make_field_copy(const std::string& field,
const std::string key) {
auto itr = field_bitmap_groups_map_.find(field);
if (itr == field_bitmap_groups_map_.end()) {
return nullptr;
// A filter referencing a field (or a scalar value) that was never
// inserted matches nothing: return an empty bitmap so callers get an
// explicit zero instead of a null bitmap that search treats as an
// engine failure. Same semantics as the multi-key variant above.
return std::make_shared<Bitmap>();
}
auto bitmap = itr->second->get_bitmap_copy(key);
if (bitmap == nullptr) {
return std::make_shared<Bitmap>();
}
return itr->second->get_bitmap_copy(key);
return bitmap;
}

BitmapPtr FieldBitmapGroupSet::make_path_field_copy(
Expand Down
5 changes: 4 additions & 1 deletion src/index/index_engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ IndexEngine::IndexEngine(const std::string& path_or_json, bool normalize_vector)

SearchResult IndexEngine::search(const SearchRequest& req) {
SearchResult result;
impl_->search(req, result);
const int ret = impl_->search(req, result);
if (ret != 0) {
throw std::runtime_error("Failed to search the native index");
}
result.result_num = result.labels.size();
return result;
}
Expand Down
187 changes: 187 additions & 0 deletions tests/vectordb/test_local_aggregate_missing_value.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0

"""Regression tests for issue #5877.

On the local vector backend, a count whose filter references a scalar value
that was never inserted used to travel the engine error path (null filter
bitmap -> failed search -> empty ``extra_json``) and was rendered by the
Python layers as a legitimate zero, alongside an
"Aggregation results not available: extra_json is empty" warning. These tests
pin the contract:

* a filter on a value that was never inserted is a valid no-match query and
must produce an explicit ``_total: 0`` without any warning;
* an engine-side aggregation failure must raise instead of being laundered
into an empty aggregation result.
"""

import json
import logging
import uuid

import pytest

import openviking.storage.vectordb.engine as engine
from openviking.storage.vectordb.collection.local_collection import (
get_or_create_local_collection,
)

_WARNING_TEXT = "Aggregation results not available: extra_json is empty"


class _ExtraJsonWarningCapture(logging.Handler):
def __init__(self):
super().__init__(level=logging.WARNING)
self.messages = []

def emit(self, record):
if _WARNING_TEXT in record.getMessage():
self.messages.append(record.getMessage())

@property
def triggered(self):
return bool(self.messages)


@pytest.fixture()
def warning_capture():
capture = _ExtraJsonWarningCapture()
# local_index logs through openviking_cli's default_logger ("openviking").
loggers = [logging.getLogger("openviking"), logging.getLogger()]
for target in loggers:
target.addHandler(capture)
yield capture
for target in loggers:
target.removeHandler(capture)


def _build_collection(path):
meta = {
"CollectionName": "issue_5877_regression",
"Fields": [
{"FieldName": "id", "FieldType": "int64", "IsPrimaryKey": True},
{"FieldName": "vector", "FieldType": "vector", "Dim": 4},
{"FieldName": "category", "FieldType": "string"},
],
}
collection = get_or_create_local_collection(meta_data=meta, path=str(path / str(uuid.uuid4())))
collection.upsert_data(
[
{"id": 1, "vector": [0.1, 0.1, 0.1, 0.1], "category": "success"},
{"id": 2, "vector": [0.2, 0.2, 0.2, 0.2], "category": "success"},
{"id": 3, "vector": [0.3, 0.3, 0.3, 0.3], "category": "failure"},
]
)
collection.create_index(
"idx",
{
"IndexName": "idx",
"VectorIndex": {"IndexType": "flat", "Distance": "ip"},
"ScalarIndex": ["category"],
},
)
return collection


def _count(collection, filters):
return collection.aggregate_data("idx", op="count", filters=filters).agg


def _must(value):
return {"op": "must", "field": "category", "conds": [value]}


def test_count_unfiltered_returns_total(tmp_path, warning_capture):
collection = _build_collection(tmp_path)
try:
assert _count(collection, None) == {"_total": 3}
finally:
collection.close()
assert not warning_capture.triggered


def test_count_inserted_value_returns_exact_matches(tmp_path, warning_capture):
collection = _build_collection(tmp_path)
try:
assert _count(collection, _must("success")) == {"_total": 2}
assert _count(collection, _must("failure")) == {"_total": 1}
finally:
collection.close()
assert not warning_capture.triggered


def test_count_never_inserted_value_is_explicit_zero_without_warning(tmp_path, warning_capture):
"""A filter on a scalar value that was never inserted matches nothing.

It must behave like any other no-match query (explicit zero) and must not
take the engine error path that used to emit the "extra_json is empty"
warning (#5877).
"""
collection = _build_collection(tmp_path)
try:
assert _count(collection, _must("absent")) == {"_total": 0}
finally:
collection.close()
assert not warning_capture.triggered


def test_count_empty_intersection_is_zero_without_warning(tmp_path, warning_capture):
"""Control: a genuine empty intersection already returned an explicit zero."""
collection = _build_collection(tmp_path)
try:
filters = {
"op": "and",
"conds": [_must("success"), _must("failure")],
}
assert _count(collection, filters) == {"_total": 0}
finally:
collection.close()
assert not warning_capture.triggered


def test_aggregate_raises_when_engine_serves_no_payload(tmp_path):
"""An aggregation without an engine payload must surface as an exception.

Before #5877 the missing payload was swallowed into ``{}`` (after a
warning), which callers cannot distinguish from a legitimate zero.
"""
collection = _build_collection(tmp_path)
try:
index = collection._Collection__collection.indexes.get("idx")
# An empty DSL: the engine serves the request but has neither sorter
# nor counter to run, so it returns no aggregation payload.
with pytest.raises(RuntimeError, match="extra_json is empty"):
index.aggregate({})
finally:
collection.close()


def test_native_index_engine_search_raises_on_bad_dsl(tmp_path):
"""Native regression: IndexEngine::search propagates parse failures."""
collection = _build_collection(tmp_path)
try:
index = collection._Collection__collection.indexes.get("idx")
native = index.engine_proxy.index_engine
request = engine.SearchRequest()
request.topk = 1
request.dsl = '{"sorter": not-parseable'
with pytest.raises(RuntimeError):
native.search(request)
finally:
collection.close()


def test_native_index_engine_search_count_on_missing_value(tmp_path):
"""Native regression: never-inserted value yields an explicit zero."""
collection = _build_collection(tmp_path)
try:
index = collection._Collection__collection.indexes.get("idx")
native = index.engine_proxy.index_engine
request = engine.SearchRequest()
request.topk = 1
request.dsl = json.dumps({"sorter": {"op": "count"}, "filter": _must("absent")})
result = native.search(request)
assert json.loads(result.extra_json) == {"__total_count__": 0}
finally:
collection.close()