Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(ultrawiki): cache query embeddings in-process
Ruben Lütkea97fa6f9b698
diff --git a/jarvis/ultrawiki/search.py b/jarvis/ultrawiki/search.pyindex 98f527624f..4514109fba 100644--- a/jarvis/ultrawiki/search.py+++ b/jarvis/ultrawiki/search.py@@ -351,6 +351,36 @@ def _configured_model(ultrawiki: Any, provider: str, defaults: dict[str, str]) -return model or defaults.get(provider, "")+#: In-process LRU of query-text embeddings, keyed by (provider, model,+#: whitespace-normalized lowercased query). Embedding the query is usually the+#: only network round trip on the read path, and the SAME query text is+#: embedded repeatedly — the context injector and the search tool both run it+#: within one turn, and users re-ask questions. In-memory only, deliberately:+#: persisting query texts (or vectors keyed by them) to disk would write a+#: trace of what the user asked their memory, which the log-privacy rule above+#: exists to prevent.+_QUERY_VECTOR_CACHE: dict[tuple[str, str, str], list[float]] = {}+_QUERY_VECTOR_CACHE_MAX = 256+++def _query_cache_key(provider: str, model: str, query: str) -> tuple[str, str, str]:+ return (provider, model, " ".join(query.split()).lower())+++def _cached_query_vector(key: tuple[str, str, str]) -> list[float] | None:+ vector = _QUERY_VECTOR_CACHE.get(key)+ if vector is not None:+ # Refresh LRU position (dicts iterate in insertion order).+ _QUERY_VECTOR_CACHE[key] = _QUERY_VECTOR_CACHE.pop(key)+ return vector+++def _remember_query_vector(key: tuple[str, str, str], vector: list[float]) -> None:+ _QUERY_VECTOR_CACHE[key] = vector+ while len(_QUERY_VECTOR_CACHE) > _QUERY_VECTOR_CACHE_MAX:+ del _QUERY_VECTOR_CACHE[next(iter(_QUERY_VECTOR_CACHE))]++async def _vector_leg(store: Any,cfg: Any,@@ -386,25 +416,32 @@ async def _vector_leg(log.warning("vector leg skipped: unknown embedding provider %r", provider)return []model = _configured_model(ultrawiki, provider, DEFAULT_MODELS)- try:- vectors = await _timed(- "vector_embed_ms", factory(cfg).embed([query], model=model), sink- )- except EmbeddingError as exc:- log.info("vector leg skipped: %s", exc)- return []- except Exception: # noqa: BLE001 — degrade to keyword-only, never fail the search- log.warning(- "vector leg skipped: query embedding raised unexpectedly",- exc_info=True,- )- return []- if not vectors or not vectors[0]:- log.info("vector leg skipped: %s returned no query vector", provider)- return []+ cache_key = _query_cache_key(provider, model, query)+ query_vector = _cached_query_vector(cache_key)+ if query_vector is None:+ try:+ vectors = await _timed(+ "vector_embed_ms", factory(cfg).embed([query], model=model), sink+ )+ except EmbeddingError as exc:+ log.info("vector leg skipped: %s", exc)+ return []+ except Exception: # noqa: BLE001 — degrade to keyword-only, never fail the search+ log.warning(+ "vector leg skipped: query embedding raised unexpectedly",+ exc_info=True,+ )+ return []+ if not vectors or not vectors[0]:+ log.info("vector leg skipped: %s returned no query vector", provider)+ return []+ query_vector = list(vectors[0])+ _remember_query_vector(cache_key, query_vector)+ else:+ log.debug("query vector served from the in-process cache")results, reason = await _timed("vector_ann_ms",- store.vector_search(vectors[0], k=LEG_POOL, area_id=area_id),+ store.vector_search(query_vector, k=LEG_POOL, area_id=area_id),sink,)if reason:diff --git a/tests/unit/ultrawiki/conftest.py b/tests/unit/ultrawiki/conftest.pynew file mode 100644index 0000000000..ac8977ae4c--- /dev/null+++ b/tests/unit/ultrawiki/conftest.py@@ -0,0 +1,17 @@+"""Shared fixtures for the UltraWiki unit tests."""++from __future__ import annotations++import pytest++import jarvis.ultrawiki.search as search_mod++[email protected](autouse=True)+def _fresh_query_vector_cache():+ """The query-embedding LRU is process-global; a vector cached by one test+ must never satisfy (or mask) another test's embedding path — that would+ make the suite order-dependent."""+ search_mod._QUERY_VECTOR_CACHE.clear()+ yield+ search_mod._QUERY_VECTOR_CACHE.clear()diff --git a/tests/unit/ultrawiki/test_search.py b/tests/unit/ultrawiki/test_search.pyindex 66252757ce..e4a2ae6e25 100644--- a/tests/unit/ultrawiki/test_search.py+++ b/tests/unit/ultrawiki/test_search.py@@ -956,3 +956,78 @@ async def test_fast_search_stays_quiet_at_info_level(store, caplog):await hybrid_search(store, make_cfg(), "alpha")assert not any("hybrid search took" in rec.message for rec in caplog.records)+++# ---------------------------------------------------------------------------+# Query-embedding cache+# ---------------------------------------------------------------------------+++async def test_repeated_query_embeds_only_once(store, monkeypatch):+ """The injector and the search tool run the SAME query within one turn;+ the second run must not pay the embedding round trip again."""+ await add_source(store)+ await store.upsert_items("src1", [raw_item("a", body="alpha content")])+ await index_all_keyword(store)+ fake = FakeEmbedding()+ register_fake_embedding(monkeypatch, fake)+ cfg = make_cfg(embedding_provider="fake", embedding_model=EMBED_MODEL)++ await hybrid_search(store, cfg, "alpha content")+ await hybrid_search(store, cfg, " Alpha CONTENT ") # same after normalizing++ assert len(fake.calls) == 1+++async def test_cache_is_scoped_by_model_and_query(store, monkeypatch):+ await add_source(store)+ await store.upsert_items("src1", [raw_item("a", body="alpha content")])+ await index_all_keyword(store)+ fake = FakeEmbedding()+ register_fake_embedding(monkeypatch, fake)++ await hybrid_search(+ store, make_cfg(embedding_provider="fake", embedding_model="model-a"), "alpha"+ )+ await hybrid_search(+ store, make_cfg(embedding_provider="fake", embedding_model="model-b"), "alpha"+ )+ await hybrid_search(+ store, make_cfg(embedding_provider="fake", embedding_model="model-a"), "beta"+ )++ assert len(fake.calls) == 3 # no cross-model or cross-query reuse+++async def test_failed_embeddings_are_never_cached(store, monkeypatch):+ await add_source(store)+ await store.upsert_items("src1", [raw_item("a", body="alpha content")])+ await index_all_keyword(store)+ fake = FakeEmbedding(error=EmbeddingError("fake: HTTP 500"))+ register_fake_embedding(monkeypatch, fake)+ cfg = make_cfg(embedding_provider="fake", embedding_model=EMBED_MODEL)++ await hybrid_search(store, cfg, "alpha")+ await hybrid_search(store, cfg, "alpha")++ assert len(fake.calls) == 2 # a failure is retried, not remembered+++async def test_cache_eviction_keeps_the_size_bounded(store, monkeypatch):+ import jarvis.ultrawiki.search as search_mod++ await add_source(store)+ await store.upsert_items("src1", [raw_item("a", body="alpha content")])+ await index_all_keyword(store)+ fake = FakeEmbedding()+ register_fake_embedding(monkeypatch, fake)+ monkeypatch.setattr(search_mod, "_QUERY_VECTOR_CACHE_MAX", 2)+ cfg = make_cfg(embedding_provider="fake", embedding_model=EMBED_MODEL)++ for query in ("one", "two", "three"):+ await hybrid_search(store, cfg, query)++ assert len(search_mod._QUERY_VECTOR_CACHE) == 2+ # "one" was evicted (oldest); asking again re-embeds.+ await hybrid_search(store, cfg, "one")+ assert len(fake.calls) == 4