Skip to content

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

fix(embedding): cache query embeddings per request to stop the context face re-embedding the same text (#4794)

Nick James2cdf64c7a6d1
diff --git a/openviking/models/embedder/base.py b/openviking/models/embedder/base.py
index 9f2e79496..e6b735e63 100644
--- a/openviking/models/embedder/base.py
+++ b/openviking/models/embedder/base.py
@@ -1,6 +1,7 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
import asyncio
+import contextvars
import logging
import random
import time
@@ -27,6 +28,26 @@ from openviking_cli.utils import get_logger
T = TypeVar("T")
logger = get_logger(__name__)
+# Request-scoped cache for query embeddings. A request handler installs the
+# scope once by setting a fresh dict; every task spawned inside that request
+# (the context assembler fans finds out via asyncio.gather) then shares the
+# same dict object by reference, so repeated embeddings of the same query text
+# within one request are served from the first in-flight embed.
+# The dedup relies on the synchronous check-create-store block below running on
+# a single event loop; if an embed path ever moves into a thread pool, that
+# invariant breaks and the cache would need a lock.
+query_embed_cache_var: contextvars.ContextVar[Optional[Dict[Any, "asyncio.Task"]]] = (
+ contextvars.ContextVar("ov_query_embed_cache", default=None)
+)
+
+
+def _query_cache_key(embedder: "EmbedderBase", embedding_input: "EmbeddingInput") -> tuple:
+ """Stable cache key for a prepared embedding input and its embedder."""
+ if isinstance(embedding_input, str):
+ return (embedder.model_name, embedding_input)
+ return (embedder.model_name, repr(embedding_input))
+
+
# A multimodal embedding input is a list of content parts, e.g.
# [{"type": "text", "text": "..."}, {"type": "image_url", "image_url": {"url": "..."}}]
EmbeddingInput = Union[str, List[Dict[str, Any]]]
@@ -90,10 +111,44 @@ async def embed_compat(
stage = "embed_query" if is_query else "embed_resource"
embedding_input = embedder.prepare_embedding_input(content)
+ if is_query:
+ cached = await _embed_from_request_cache(embedder, embedding_input, stage)
+ if cached is not None:
+ return cached
with bind_telemetry_stage(stage):
return await embedder.embed_async(embedding_input, is_query=is_query)
+async def _embed_from_request_cache(
+ embedder: "EmbedderBase", embedding_input: "EmbeddingInput", stage: str
+) -> Optional["EmbedResult"]:
+ """Serve a query embed from the request-scoped cache, deduplicating in-flight embeds.
+
+ Returns None when the request scope is not installed, so the caller falls back
+ to the plain embed path.
+ """
+ from openviking.telemetry import bind_telemetry_stage
+
+ cache = query_embed_cache_var.get()
+ if cache is None:
+ return None
+ key = _query_cache_key(embedder, embedding_input)
+ pending = cache.get(key)
+ if pending is None:
+ # Create the task synchronously and store it before the first await:
+ # sibling tasks of the same request then see this entry and await the
+ # same in-flight embed instead of starting their own.
+ with bind_telemetry_stage(stage):
+ pending = asyncio.create_task(embedder.embed_async(embedding_input, is_query=True))
+ cache[key] = pending
+ try:
+ return await pending
+ except Exception:
+ # A failed embed must not poison the rest of the request.
+ cache.pop(key, None)
+ raise
+
+
def truncate_and_normalize(embedding: List[float], dimension: Optional[int]) -> List[float]:
"""Truncate and L2 normalize embedding vector
diff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.py
index 309e050ba..22ca0c492 100644
--- a/openviking/server/routers/search.py
+++ b/openviking/server/routers/search.py
@@ -12,6 +12,7 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator
from openviking.core.path_variables import resolve_path_variables
from openviking.core.uri_validation import validate_request_viking_uri
+from openviking.models.embedder.base import query_embed_cache_var
from openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundError
from openviking.retrieve.context_assembler import (
CATEGORY_KEYS,
@@ -430,6 +431,10 @@ async def search(
_ctx: RequestContext = Depends(get_request_context),
):
"""Semantic search with optional session context."""
+ # Install the request-scoped query embedding cache before any search work
+ # spawns tasks: every find fanned out below shares this dict and reuses the
+ # first embed of a given query text.
+ query_embed_cache_var.set({})
service = get_service()
actual_limit = _resolve_search_limit(request.limit, request.node_limit)
effective_filter = _resolve_search_filter(
diff --git a/tests/models/test_query_embedding_cache.py b/tests/models/test_query_embedding_cache.py
new file mode 100644
index 000000000..4d9459000
--- /dev/null
+++ b/tests/models/test_query_embedding_cache.py
@@ -0,0 +1,110 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+from __future__ import annotations
+
+import asyncio
+from typing import List
+
+from openviking.models.embedder.base import (
+ EmbedResult,
+ EmbedderBase,
+ embed_compat,
+ query_embed_cache_var,
+)
+
+
+class CountingEmbedder(EmbedderBase):
+ """Fake embedder that records every async embed and can be told to fail."""
+
+ def __init__(self, model_name: str = "fake-model"):
+ super().__init__(model_name)
+ self.calls: List[str] = []
+ self.fail_next = 0
+
+ def embed(self, content, is_query: bool = False) -> EmbedResult:
+ self.calls.append(str(content))
+ return EmbedResult(dense_vector=[1.0])
+
+ async def embed_async(self, content, is_query: bool = False) -> EmbedResult:
+ self.calls.append(str(content))
+ await asyncio.sleep(0)
+ if self.fail_next > 0:
+ self.fail_next -= 1
+ raise RuntimeError("embed failed")
+ return EmbedResult(dense_vector=[1.0])
+
+
+async def test_embed_compat_reuses_same_query_text_within_request():
+ embedder = CountingEmbedder()
+ query_embed_cache_var.set({})
+
+ first = await embed_compat(embedder, "hello", is_query=True)
+ second = await embed_compat(embedder, "hello", is_query=True)
+
+ assert first.dense_vector == second.dense_vector == [1.0]
+ assert embedder.calls == ["hello"]
+
+
+async def test_embed_compat_caches_distinct_texts_separately():
+ embedder = CountingEmbedder()
+ query_embed_cache_var.set({})
+
+ await embed_compat(embedder, "alpha", is_query=True)
+ await embed_compat(embedder, "beta", is_query=True)
+
+ assert embedder.calls == ["alpha", "beta"]
+
+
+async def test_embed_compat_dedupes_concurrent_same_text():
+ # Mirrors gather.py: all finds for one request run as sibling tasks that
+ # copy the request context, so the cache dict must be shared by reference
+ # and the first find's in-flight embed is awaited by every sibling.
+ embedder = CountingEmbedder()
+ query_embed_cache_var.set({})
+
+ async def one():
+ return await embed_compat(embedder, "shared", is_query=True)
+
+ results = await asyncio.gather(*(one() for _ in range(5)))
+
+ assert len(results) == 5
+ assert all(r.dense_vector == [1.0] for r in results)
+ assert embedder.calls == ["shared"]
+
+
+async def test_embed_compat_never_caches_resource_embeds():
+ embedder = CountingEmbedder()
+ query_embed_cache_var.set({})
+
+ await embed_compat(embedder, "hello", is_query=False)
+ await embed_compat(embedder, "hello", is_query=False)
+
+ assert embedder.calls == ["hello", "hello"]
+
+
+async def test_embed_compat_does_not_cache_outside_request_scope():
+ # Without the request scope installed (no handler set), behavior must stay
+ # exactly as today: every embed goes through.
+ embedder = CountingEmbedder()
+
+ await embed_compat(embedder, "hello", is_query=True)
+ await embed_compat(embedder, "hello", is_query=True)
+
+ assert embedder.calls == ["hello", "hello"]
+
+
+async def test_embed_compat_retries_after_a_failed_embed():
+ embedder = CountingEmbedder()
+ embedder.fail_next = 1
+ query_embed_cache_var.set({})
+
+ failed = False
+ try:
+ await embed_compat(embedder, "hello", is_query=True)
+ except RuntimeError:
+ failed = True
+ assert failed
+
+ result = await embed_compat(embedder, "hello", is_query=True)
+ assert result.dense_vector == [1.0]
+ assert embedder.calls == ["hello", "hello"]