Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix: require all retrieval tags in search (#3097)
Jiahui Zhou5390bd5e5479
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rsindex 01345281a..634ea908b 100644--- a/crates/ov_cli/src/main.rs+++ b/crates/ov_cli/src/main.rs@@ -643,7 +643,7 @@ enum Commands {help_heading = "Common options")]context_type: Option<Vec<String>>,- /// Only include results matching any of these explicit tags+ /// Only include results matching all of these explicit tags#[arg(long = "tags", value_delimiter = ',')]tags: Option<Vec<String>>,},@@ -711,7 +711,7 @@ enum Commands {help_heading = "Advanced options")]context_type: Option<Vec<String>>,- /// Only include results matching any of these explicit tags+ /// Only include results matching all of these explicit tags#[arg(long = "tags", value_delimiter = ',')]tags: Option<Vec<String>>,},diff --git a/docs/en/api/06-retrieval.md b/docs/en/api/06-retrieval.mdindex 6d01551b7..5a1b6364d 100644--- a/docs/en/api/06-retrieval.md+++ b/docs/en/api/06-retrieval.md@@ -58,6 +58,7 @@ The `find()` method performs pure vector similarity search for simple query scen| image_url | str | No | None | Image query as a `data:image/...;base64,...`, `http(s)://`, or `viking://` URI. Requires a multimodal embedding model || target_uri | str \| List[str] | No | "" | Limit search to specific URI prefix || context_type | str \| List[str] | No | None | Limit results to one or more `ContextType` values: `memory`, `resource`, or `skill` |+| tags | List[str] | No | None | Explicit retrieval tags in strict `k=v` form. Multiple tags are combined with AND; a result must contain every requested tag || node_limit | int | No | None | Maximum number of results || score_threshold | float | No | None | Minimum relevance score threshold || filter | Dict | No | None | Metadata filter |@@ -161,6 +162,20 @@ curl -X POST http://localhost:1933/api/v1/search/find \}'```+**Search by Explicit Retrieval Tags**++```bash+curl -X POST http://localhost:1933/api/v1/search/find \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "query": "rollback runbook",+ "tags": ["env=prod", "team=search"]+ }'+```++Tags must use strict `k=v` strings. When multiple tags are provided, `find()` requires all of them; the example above only returns contexts whose explicit retrieval tags contain both `env=prod` and `team=search`.+**Python SDK**```python@@ -190,6 +205,12 @@ typed_results = client.find(# Search by local image, bytes, data URI, HTTP URL, or viking:// URIimage_results = client.find(image="/path/to/photo.png")+# Search by explicit retrieval tags. Multiple tags are AND-ed.+tagged_results = client.find(+ "rollback runbook",+ tags=["env=prod", "team=search"],+)+# Iterate through resultsfor ctx in results.resources:print(f"URI: {ctx.uri}")@@ -372,6 +393,7 @@ The `search()` method adds session context understanding and intent analysis cap| session | Session | No | None | Session for context-aware search (SDK) || session_id | str | No | None | Session ID for context-aware search (HTTP) || context_type | str \| List[str] | No | None | Limit results to one or more `ContextType` values: `memory`, `resource`, or `skill` |+| tags | List[str] | No | None | Explicit retrieval tags in strict `k=v` form. Multiple tags are combined with AND; a result must contain every requested tag || node_limit | int | No | None | Maximum number of results || score_threshold | float | No | None | Minimum relevance score threshold || filter | Dict | No | None | Metadata filter |@@ -382,7 +404,7 @@ The `search()` method adds session context understanding and intent analysis cap| include_provenance | bool | No | False | Include provenance/query-plan details in serialized result || telemetry | bool \| object | No | False | Attach telemetry data to response |-`search()` uses the same target resolution rules as `find()`, including the peer collection filter selected by `X-OpenViking-Actor-Peer` or SDK `actor_peer_id`. When `image_url` is provided, `search()` uses direct image retrieval and skips session query planning.+`search()` uses the same target resolution and explicit tag filtering rules as `find()`, including the peer collection filter selected by `X-OpenViking-Actor-Peer` or SDK `actor_peer_id`. When `image_url` is provided, `search()` uses direct image retrieval and skips session query planning.#### 3. Usage Examplesdiff --git a/docs/zh/api/06-retrieval.md b/docs/zh/api/06-retrieval.mdindex f81aa6b58..ef036d821 100644--- a/docs/zh/api/06-retrieval.md+++ b/docs/zh/api/06-retrieval.md@@ -58,6 +58,7 @@ OpenViking 提供多种检索方法,包括简单的向量相似度搜索、带| image_url | str | 否 | None | 图片查询,支持 `data:image/...;base64,...`、`http(s)://` 或 `viking://` URI;需要 multimodal embedding 模型 || target_uri | str \| List[str] | 否 | "" | 限制搜索范围到指定的 URI 前缀 || context_type | str \| List[str] | 否 | None | 限定一个或多个 `ContextType` 取值:`memory`、`resource` 或 `skill` |+| tags | List[str] | 否 | None | 显式检索标签,必须是严格的 `k=v` 格式。多个 tags 之间是 AND 关系,结果必须同时包含所有请求的标签 || limit | int | 否 | 10 | 最大返回结果数 || node_limit | int | 否 | None | 可选 HTTP 别名;如果提供,会覆盖 limit || score_threshold | float | 否 | None | 最低相关性分数阈值 |@@ -162,6 +163,20 @@ curl -X POST http://localhost:1933/api/v1/search/find \}'```+**按显式检索标签搜索**++```bash+curl -X POST http://localhost:1933/api/v1/search/find \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "query": "rollback runbook",+ "tags": ["env=prod", "team=search"]+ }'+```++Tags 必须使用严格的 `k=v` 字符串。传入多个 tags 时,`find()` 会要求全部命中;上面的例子只返回显式检索标签同时包含 `env=prod` 和 `team=search` 的上下文。+**Python SDK**```python@@ -191,6 +206,12 @@ typed_results = client.find(# 按本地图片、bytes、data URI、HTTP URL 或 viking:// URI 搜索image_results = client.find(image="/path/to/photo.png")+# 按显式检索标签搜索。多个 tags 之间是 AND 关系。+tagged_results = client.find(+ "rollback runbook",+ tags=["env=prod", "team=search"],+)+# 遍历结果for ctx in results.resources:print(f"URI: {ctx.uri}")@@ -373,6 +394,7 @@ openviking find "红色海报风格" --image ./poster.png --uri "viking://resour| session | Session | 否 | None | 用于上下文感知搜索的会话(SDK)|| session_id | str | 否 | None | 用于上下文感知搜索的会话 ID(HTTP)|| context_type | str \| List[str] | 否 | None | 限定一个或多个 `ContextType` 取值:`memory`、`resource` 或 `skill` |+| tags | List[str] | 否 | None | 显式检索标签,必须是严格的 `k=v` 格式。多个 tags 之间是 AND 关系,结果必须同时包含所有请求的标签 || limit | int | 否 | 10 | 最大返回结果数 || node_limit | int | 否 | None | 可选 HTTP 别名;如果提供,会覆盖 limit || score_threshold | float | 否 | None | 最低相关性分数阈值 |@@ -384,7 +406,7 @@ openviking find "红色海报风格" --image ./poster.png --uri "viking://resour| include_provenance | bool | 否 | False | 在序列化结果中附带 provenance / query-plan 细节 || telemetry | bool \| object | 否 | False | 在响应中附带遥测数据 |-`search()` 使用和 `find()` 相同的目标解析规则,包括由 `X-OpenViking-Actor-Peer` 或 SDK `actor_peer_id` 选择的 peer 集合过滤。提供 `image_url` 时,`search()` 会直接执行图片检索并跳过会话 query planning。+`search()` 使用和 `find()` 相同的目标解析和显式标签过滤规则,包括由 `X-OpenViking-Actor-Peer` 或 SDK `actor_peer_id` 选择的 peer 集合过滤。提供 `image_url` 时,`search()` 会直接执行图片检索并跳过会话 query planning。#### 3. 使用示例diff --git a/openviking/client/local.py b/openviking/client/local.pyindex deb531314..bcccbed61 100644--- a/openviking/client/local.py+++ b/openviking/client/local.py@@ -26,7 +26,7 @@ from openviking.telemetry.execution import ()from openviking.utils.image_search import normalize_client_image_inputfrom openviking.utils.search_filters import SearchContextTypeInput, merge_search_filter-from openviking.utils.tags import normalize_search_tags+from openviking.utils.tags import build_search_tags_filterfrom openviking_cli.client.base import BaseClientfrom openviking_cli.exceptions import InvalidArgumentError, NotFoundErrorfrom openviking_cli.session.user_id import UserIdentifier@@ -61,11 +61,12 @@ def _resolve_search_filter(until=until,time_field=time_field,)- normalized_tags = normalize_search_tags(tags)- if not normalized_tags:+ tag_filter = build_search_tags_filter(tags)+ if not tag_filter:return merged- tag_filter = {"op": "must", "field": "search_tags", "conds": normalized_tags}if merged:+ if tag_filter.get("op") == "and" and isinstance(tag_filter.get("conds"), list):+ return {"op": "and", "conds": [merged, *tag_filter["conds"]]}return {"op": "and", "conds": [merged, tag_filter]}return tag_filterdiff --git a/openviking/integrations/langchain/retrievers.py b/openviking/integrations/langchain/retrievers.pyindex e38009cc6..fcab9ab09 100644--- a/openviking/integrations/langchain/retrievers.py+++ b/openviking/integrations/langchain/retrievers.py@@ -89,6 +89,7 @@ class OpenVikingRetriever(BaseRetriever):limit=self.limit,score_threshold=self.score_threshold,filter=self.filter,+ tags=self.tags,)documents: list[Document] = []for context_type, item in iter_result_items(result, self.context_types):diff --git a/openviking/integrations/langchain/testing.py b/openviking/integrations/langchain/testing.pyindex 6d437b253..2f1f2599f 100644--- a/openviking/integrations/langchain/testing.py+++ b/openviking/integrations/langchain/testing.py@@ -44,6 +44,7 @@ class InMemoryOpenVikingClient:limit: int = 10,score_threshold: float | None = None,filter: dict[str, Any] | None = None,+ tags: list[str] | None = None,**_: Any,) -> dict[str, Any]:self.find_calls.append(@@ -53,6 +54,7 @@ class InMemoryOpenVikingClient:"limit": limit,"score_threshold": score_threshold,"filter": filter,+ "tags": tags,})return self._search(query, target_uri, limit, score_threshold)@@ -65,6 +67,7 @@ class InMemoryOpenVikingClient:limit: int = 10,score_threshold: float | None = None,filter: dict[str, Any] | None = None,+ tags: list[str] | None = None,**_: Any,) -> dict[str, Any]:self.search_calls.append(@@ -75,6 +78,7 @@ class InMemoryOpenVikingClient:"limit": limit,"score_threshold": score_threshold,"filter": filter,+ "tags": tags,})session_text = " ".join(diff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.pyindex 17db948fa..d302b8a2b 100644--- a/openviking/server/routers/search.py+++ b/openviking/server/routers/search.py@@ -29,7 +29,7 @@ from openviking.utils.search_filters import (_resolve_levels,merge_search_filter,)-from openviking.utils.tags import normalize_search_tags+from openviking.utils.tags import build_search_tags_filterfrom openviking_cli.exceptions import InvalidArgumentError, NotFoundError@@ -70,15 +70,12 @@ def _resolve_search_filter(until=until,time_field=time_field,)- normalized_tags = normalize_search_tags(tags)- if not normalized_tags:+ tag_filter = build_search_tags_filter(tags)+ if not tag_filter:return merged- tag_filter: Dict[str, Any] = {- "op": "must",- "field": "search_tags",- "conds": normalized_tags,- }if merged:+ if tag_filter.get("op") == "and" and isinstance(tag_filter.get("conds"), list):+ return {"op": "and", "conds": [merged, *tag_filter["conds"]]}return {"op": "and", "conds": [merged, tag_filter]}return tag_filterexcept ValueError as exc:diff --git a/openviking/utils/tags.py b/openviking/utils/tags.pyindex ae882bb0c..89c7e5309 100644--- a/openviking/utils/tags.py+++ b/openviking/utils/tags.py@@ -5,7 +5,7 @@from __future__ import annotationsfrom collections import OrderedDict-from typing import Iterable+from typing import Any, Iterablefrom openviking_cli.exceptions import InvalidArgumentError@@ -44,6 +44,25 @@ def normalize_search_tags(tags: Iterable[str] | None) -> list[str]:return normalized+def build_search_tags_filter(tags: Iterable[str] | None) -> dict[str, Any] | None:+ """Build a metadata filter that requires every explicit search tag."""+ normalized_tags = normalize_search_tags(tags)+ if not normalized_tags:+ return None++ tag_filters = [+ {+ "op": "must",+ "field": "search_tags",+ "conds": [tag],+ }+ for tag in normalized_tags+ ]+ if len(tag_filters) == 1:+ return tag_filters[0]+ return {"op": "and", "conds": tag_filters}++def merge_search_tags(existing: Iterable[str] | None, incoming: Iterable[str] | None) -> list[str]:"""Merge normalized search tags by key, replacing old values with incoming ones."""ordered: OrderedDict[str, str] = OrderedDict()diff --git a/tests/server/test_api_search.py b/tests/server/test_api_search.pyindex 7506e9f97..281b5f058 100644--- a/tests/server/test_api_search.py+++ b/tests/server/test_api_search.py@@ -78,32 +78,38 @@ async def test_find_with_target_uri(client_with_resource):assert resp.json()["status"] == "ok"-async def test_find_with_target_uri_and_tags_after_set_tags(client_with_resource):- client, uri = client_with_resource+async def test_find_with_target_uri_and_tags_passes_target_and_filter(+ client: httpx.AsyncClient, service, monkeypatch+):+ captured = {}- set_tags_resp = await client.post(- "/api/v1/fs/attrs/set_tags",- json={"uri": uri, "tags": ["team=search"]},- )- assert set_tags_resp.status_code == 200- assert set_tags_resp.json()["status"] == "ok"+ async def fake_find(*, target_uri=None, filter=None, **kwargs):+ captured["target_uri"] = target_uri+ captured["filter"] = filter+ return {"items": []}- untagged_resp = await client.post(- "/api/v1/search/find",- json={"query": "sample", "target_uri": uri, "limit": 10},- )- assert untagged_resp.status_code == 200- assert untagged_resp.json()["status"] == "ok"- untagged_total = untagged_resp.json()["result"]["total"]- assert untagged_total > 0+ monkeypatch.setattr(service.search, "find", fake_find)- tagged_resp = await client.post(+ resp = await client.post("/api/v1/search/find",- json={"query": "sample", "target_uri": uri, "tags": ["team=search"], "limit": 10},+ json={+ "query": "sample",+ "target_uri": "viking://resources/sample",+ "tags": ["team=search", "env=prod"],+ "limit": 10,+ },)- assert tagged_resp.status_code == 200- assert tagged_resp.json()["status"] == "ok"- assert tagged_resp.json()["result"]["total"] > 0++ assert resp.status_code == 200+ assert resp.json()["status"] == "ok"+ assert captured["target_uri"] == "viking://resources/sample"+ assert captured["filter"] == {+ "op": "and",+ "conds": [+ {"op": "must", "field": "search_tags", "conds": ["team=search"]},+ {"op": "must", "field": "search_tags", "conds": ["env=prod"]},+ ],+ }async def test_find_with_level_passes_to_service(client: httpx.AsyncClient, service, monkeypatch):@@ -563,7 +569,7 @@ async def test_find_combines_tags_with_existing_filter(json={"query": "sample","filter": {"op": "must", "field": "kind", "conds": ["email"]},- "tags": ["Env=Prod", " env=prod "],+ "tags": ["Env=Prod", " env=prod ", "team=Search"],},)@@ -574,6 +580,7 @@ async def test_find_combines_tags_with_existing_filter("conds": [{"op": "must", "field": "kind", "conds": ["email"]},{"op": "must", "field": "search_tags", "conds": ["env=prod"]},+ {"op": "must", "field": "search_tags", "conds": ["team=search"]},],}@@ -620,15 +627,17 @@ async def test_search_compiles_tags_only_filter(client: httpx.AsyncClient, serviresp = await client.post("/api/v1/search/search",- json={"query": "sample", "tags": ["Team=Search"]},+ json={"query": "sample", "tags": ["Team=Search", "env=prod"]},)assert resp.status_code == 200assert resp.json()["status"] == "ok"assert captured["filter"] == {- "op": "must",- "field": "search_tags",- "conds": ["team=search"],+ "op": "and",+ "conds": [+ {"op": "must", "field": "search_tags", "conds": ["team=search"]},+ {"op": "must", "field": "search_tags", "conds": ["env=prod"]},+ ],}diff --git a/tests/unit/test_langchain_integration.py b/tests/unit/test_langchain_integration.pyindex bb4d2aab6..939f36d48 100644--- a/tests/unit/test_langchain_integration.py+++ b/tests/unit/test_langchain_integration.py@@ -98,6 +98,21 @@ def test_retriever_keeps_peer_id_out_of_retrieval():assert "peer_id" not in client.find_calls[-1]+def test_retriever_passes_tags_to_retrieval():+ client = InMemoryOpenVikingClient(+ {"viking://resources/runbooks/release.md": "Release notes mention LangChain."}+ )+ retriever = OpenVikingRetriever(+ client=client,+ target_uri="viking://resources",+ tags=["env=prod", "team=search"],+ )++ retriever.invoke("LangChain")++ assert client.find_calls[-1]["tags"] == ["env=prod", "team=search"]++def test_create_openviking_tools_exposes_common_viking_primitives():client = InMemoryOpenVikingClient({"viking://user/memories/profile.md": "The user likes LangGraph agents."}diff --git a/tests/unit/test_search_tags_filter.py b/tests/unit/test_search_tags_filter.pynew file mode 100644index 000000000..fbddfe297--- /dev/null+++ b/tests/unit/test_search_tags_filter.py@@ -0,0 +1,84 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++from openviking.client.local import _resolve_search_filter as _resolve_local_search_filter+from openviking.server.routers.search import _resolve_search_filter+from openviking.utils.tags import build_search_tags_filter+++def test_search_tags_filter_keeps_single_tag_as_single_must():+ assert build_search_tags_filter(["Team=Search"]) == {+ "op": "must",+ "field": "search_tags",+ "conds": ["team=search"],+ }+++def test_search_tags_filter_dedupes_before_building_and_filter():+ assert build_search_tags_filter(["Env=Prod", " env=prod ", "team=Search"]) == {+ "op": "and",+ "conds": [+ {"op": "must", "field": "search_tags", "conds": ["env=prod"]},+ {"op": "must", "field": "search_tags", "conds": ["team=search"]},+ ],+ }+++def test_find_tags_filter_requires_all_tags():+ result = _resolve_search_filter(+ request_filter=None,+ context_type=None,+ since=None,+ until=None,+ time_field=None,+ tags=["Env=Prod", "team=Search"],+ )++ assert result == {+ "op": "and",+ "conds": [+ {"op": "must", "field": "search_tags", "conds": ["env=prod"]},+ {"op": "must", "field": "search_tags", "conds": ["team=search"]},+ ],+ }+++def test_find_tags_filter_ands_all_tags_with_existing_filter():+ existing_filter = {"op": "must", "field": "kind", "conds": ["email"]}++ result = _resolve_search_filter(+ request_filter=existing_filter,+ context_type=None,+ since=None,+ until=None,+ time_field=None,+ tags=["env=prod", "team=search"],+ )++ assert result == {+ "op": "and",+ "conds": [+ existing_filter,+ {"op": "must", "field": "search_tags", "conds": ["env=prod"]},+ {"op": "must", "field": "search_tags", "conds": ["team=search"]},+ ],+ }+++def test_local_client_tags_filter_requires_all_tags():+ result = _resolve_local_search_filter(+ filter=None,+ context_type=None,+ since=None,+ until=None,+ time_field=None,+ tags=["env=prod", "team=search"],+ )++ assert result == {+ "op": "and",+ "conds": [+ {"op": "must", "field": "search_tags", "conds": ["env=prod"]},+ {"op": "must", "field": "search_tags", "conds": ["team=search"]},+ ],+ }