Skip to content

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

fix(search): reject empty queries (#1695)

Qin Haojie1bba108b1464
diff --git a/openviking/service/search_service.py b/openviking/service/search_service.py
index af2562dcf..36379b5fc 100644
--- a/openviking/service/search_service.py
+++ b/openviking/service/search_service.py
@@ -10,7 +10,7 @@ from typing import TYPE_CHECKING, Any, Dict, Optional
from openviking.server.identity import RequestContext
from openviking.storage.viking_fs import VikingFS
-from openviking_cli.exceptions import NotInitializedError
+from openviking_cli.exceptions import InvalidArgumentError, NotInitializedError
from openviking_cli.utils import get_logger
if TYPE_CHECKING:
@@ -19,6 +19,11 @@ if TYPE_CHECKING:
logger = get_logger(__name__)
+def _ensure_non_empty_query(query: str) -> None:
+ if not query.strip():
+ raise InvalidArgumentError("Search query must not be empty.")
+
+
class SearchService:
"""Semantic search service."""
@@ -58,6 +63,7 @@ class SearchService:
Returns:
FindResult
"""
+ _ensure_non_empty_query(query)
viking_fs = self._ensure_initialized()
session_info = None
@@ -96,6 +102,7 @@ class SearchService:
Returns:
FindResult
"""
+ _ensure_non_empty_query(query)
viking_fs = self._ensure_initialized()
result = await viking_fs.find(
query=query,
diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.py
index a0f5f966d..e8454443d 100644
--- a/openviking/storage/viking_fs.py
+++ b/openviking/storage/viking_fs.py
@@ -54,6 +54,11 @@ if TYPE_CHECKING:
logger = get_logger(__name__)
+def _ensure_non_empty_search_query(query: str) -> None:
+ if not query.strip():
+ raise InvalidArgumentError("Search query must not be empty.")
+
+
def _is_directory_not_empty_error(message: str) -> bool:
"""Check if an error message indicates a directory not empty error.
@@ -1013,6 +1018,7 @@ class VikingFS:
Returns:
FindResult
"""
+ _ensure_non_empty_search_query(query)
telemetry = get_current_telemetry()
from openviking.retrieve.hierarchical_retriever import HierarchicalRetriever
from openviking_cli.retrieve import (
@@ -1105,6 +1111,7 @@ class VikingFS:
Returns:
FindResult
"""
+ _ensure_non_empty_search_query(query)
telemetry = get_current_telemetry()
from openviking.retrieve.hierarchical_retriever import HierarchicalRetriever
from openviking.retrieve.intent_analyzer import IntentAnalyzer
diff --git a/tests/server/test_api_search.py b/tests/server/test_api_search.py
index 80453252c..abca6ec4d 100644
--- a/tests/server/test_api_search.py
+++ b/tests/server/test_api_search.py
@@ -11,7 +11,9 @@ import pytest
from openviking.models.embedder.base import EmbedResult
from openviking.server.auth import get_request_context
from openviking.server.identity import RequestContext, Role
+from openviking.storage.viking_fs import VikingFS
from openviking.utils.time_utils import parse_iso_datetime
+from openviking_cli.exceptions import InvalidArgumentError
from openviking_cli.session.user_id import UserIdentifier
@@ -93,6 +95,61 @@ async def test_find_no_results(client: httpx.AsyncClient):
assert resp.json()["status"] == "ok"
[email protected]("query", ["", " \t\n"])
+async def test_find_rejects_empty_query(client: httpx.AsyncClient, service, query: str):
+ class RaisingEmbedder:
+ def embed(self, text: str, is_query: bool = False) -> EmbedResult:
+ raise AssertionError("empty query should not be embedded")
+
+ async def embed_async(self, text: str, is_query: bool = False) -> EmbedResult:
+ raise AssertionError("empty query should not be embedded")
+
+ service.viking_fs.query_embedder = RaisingEmbedder()
+
+ resp = await client.post(
+ "/api/v1/search/find",
+ json={"query": query},
+ )
+
+ assert resp.status_code == 400
+ body = resp.json()
+ assert body["status"] == "error"
+ assert body["error"]["code"] == "INVALID_ARGUMENT"
+ assert "must not be empty" in body["error"]["message"]
+
+
[email protected]("query", ["", " \t\n"])
+async def test_search_rejects_empty_query(client: httpx.AsyncClient, service, query: str):
+ class RaisingEmbedder:
+ def embed(self, text: str, is_query: bool = False) -> EmbedResult:
+ raise AssertionError("empty query should not be embedded")
+
+ async def embed_async(self, text: str, is_query: bool = False) -> EmbedResult:
+ raise AssertionError("empty query should not be embedded")
+
+ service.viking_fs.query_embedder = RaisingEmbedder()
+
+ resp = await client.post(
+ "/api/v1/search/search",
+ json={"query": query},
+ )
+
+ assert resp.status_code == 400
+ body = resp.json()
+ assert body["status"] == "error"
+ assert body["error"]["code"] == "INVALID_ARGUMENT"
+ assert "must not be empty" in body["error"]["message"]
+
+
[email protected]("method_name", ["find", "search"])
+async def test_vikingfs_rejects_empty_query_before_initialization(method_name: str):
+ viking_fs = VikingFS.__new__(VikingFS)
+ method = getattr(viking_fs, method_name)
+
+ with pytest.raises(InvalidArgumentError, match="must not be empty"):
+ await method(query=" ")
+
+
async def test_find_with_since_compiles_time_range(client: httpx.AsyncClient, service, monkeypatch):
captured = {}