Skip to content

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.

fix(ultrawiki): stop a bypassed model switch from bricking the embed lane

Ruben Lütkebd891d143232
diff --git a/jarvis/ui/web/ultrawiki_routes.py b/jarvis/ui/web/ultrawiki_routes.py
index 1fbb5b8ee8..53b53d29b1 100644
--- a/jarvis/ui/web/ultrawiki_routes.py
+++ b/jarvis/ui/web/ultrawiki_routes.py
@@ -1042,6 +1042,34 @@ async def activate_mode(body: ActivateBody, request: Request) -> dict[str, Any]:
enabled_persisted, enabled_error = _persist_enabled(True)
_apply_live(request, {}, enabled=True)
+
+ # Activation can CHANGE the embedding model (the wizard asks for it, and
+ # the Normal/Ultra switch re-sends the configured provider), so this route
+ # owes the store the same registration PUT /settings performs. Without it
+ # the config named one model while the store stayed pinned to another,
+ # every vector was rejected, and the embed lane failed 100 % of its work
+ # in silence — the 2026-07-28 forensic. `reconcile_space` is idempotent
+ # and a no-op when the model already matches, so the ordinary "switch
+ # Ultra back on" path costs two primary-key reads.
+ space_rebuild = ""
+ try:
+ store = await _store_of(service)
+ verdict = await store.reconcile_space(
+ _effective_embedding_model(_uw_cfg(request), values)
+ )
+ if verdict == "started":
+ space_rebuild = "started"
+ elif verdict == "rebuilding":
+ space_rebuild = "running"
+ except Exception: # noqa: BLE001 — activation succeeded; the pipeline retries
+ # `_reconcile_embedding_space` asks again on every pass, so a failure
+ # here delays the rebuild by one pass instead of losing it.
+ log.warning(
+ "UltraWiki: could not reconcile the embedding space during "
+ "activation; the pipeline reconciles on its next pass",
+ exc_info=True,
+ )
+
# The pipeline only starts while the mode is on, so it is started here —
# after the flip, never before it.
await service.ensure_started()
@@ -1049,6 +1077,7 @@ async def activate_mode(body: ActivateBody, request: Request) -> dict[str, Any]:
response: dict[str, Any] = {
"ok": True,
"enabled": True,
+ "embedding_space_rebuild": space_rebuild,
"persisted": slots_persisted and enabled_persisted,
**result,
"next_steps": (
diff --git a/jarvis/ultrawiki/pipeline.py b/jarvis/ultrawiki/pipeline.py
index 17f2ed3ef9..75361a11ea 100644
--- a/jarvis/ultrawiki/pipeline.py
+++ b/jarvis/ultrawiki/pipeline.py
@@ -461,6 +461,42 @@ class PipelineWorker:
log.debug("UltraWiki: rebuild probe failed", exc_info=True)
return False
+ async def _reconcile_embedding_space(self, model: str) -> None:
+ """Keep the store's vector space in step with the configured model.
+
+ The switch is registered by whoever changes the setting — but only ONE
+ of the paths that can change it ever did (the settings route). The
+ activation route behind the Normal/Ultra switch, a voice-driven config
+ change, a hand-edited ``jarvis.toml`` and a config restored from
+ another machine all wrote the new model and left the store pinned to
+ the old one. The result was silent and total: every vector rejected,
+ every item charged a retry, the whole corpus on its way to the
+ dead-letter state, and a surface that still said "still filling up".
+
+ Asking the store once per pass — with the model this pass will really
+ use, after the slot resolved it — makes the guarantee independent of
+ which door the user walked through. Never raises: an unreconcilable
+ store still gets its honest per-item failure below.
+ """
+ reconcile = getattr(self._store, "reconcile_space", None)
+ if reconcile is None: # an older embedded store, or a test fake
+ return
+ try:
+ verdict = str(await reconcile(model) or "")
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001 — reconciliation never kills the lane
+ log.debug("UltraWiki: embedding-space reconciliation failed", exc_info=True)
+ return
+ if verdict == "started":
+ log.warning(
+ "UltraWiki: the configured embedding model %r did not match the "
+ "stored vector space — a background rebuild was registered. "
+ "Semantic search keeps answering from the current vectors until "
+ "it completes.",
+ model,
+ )
+
async def _promote_pass(self) -> None:
"""Swap in a finished embedding rebuild (see
``UltraStore.promote_pending_space``).
@@ -490,6 +526,20 @@ class PipelineWorker:
return self._now_fn() if self._now_fn is not None else None
async def _retry(self, item: dict[str, Any], stage: str, exc: BaseException) -> None:
+ from jarvis.ultrawiki.store import ( # noqa: PLC0415 — lazy (AP-26)
+ EmbeddingSpaceMismatch,
+ )
+
+ if isinstance(exc, EmbeddingSpaceMismatch):
+ # A configuration fault, not a poisoned item. Charging it here cost
+ # the item an attempt, and five attempts dead-letter it: a single
+ # mis-registered model switch was quietly converting the entire
+ # corpus into `failed` at 32 items a pass, one innocent item at a
+ # time, while the surface reported a healthy backlog. The lane
+ # pauses instead and the backlog waits, intact, for the space to
+ # agree again (`_reconcile_embedding_space`).
+ self._note_stage_pause(stage, str(exc), key="embed-space-mismatch")
+ return
log.warning(
"UltraWiki %s stage failed for item %s (%s): %s",
stage,
@@ -856,6 +906,7 @@ class PipelineWorker:
# A stable dedup key, because the sentence carries a countdown.
self._note_stage_pause("embed", cooldown, key="embed-cooldown")
return 0
+ await self._reconcile_embedding_space(model)
self._clear_stage_pause("embed")
items = await self._store.claim_batch(
ItemState.EMBEDDED, limit=EMBED_BATCH, now=self._claim_now()
diff --git a/jarvis/ultrawiki/store.py b/jarvis/ultrawiki/store.py
index 160c0025a5..0e57a682e6 100644
--- a/jarvis/ultrawiki/store.py
+++ b/jarvis/ultrawiki/store.py
@@ -128,6 +128,19 @@ class UltraStoreError(RuntimeError):
"""Raised for store-contract violations (e.g. embedding-dim mismatch)."""
+class EmbeddingSpaceMismatch(UltraStoreError):
+ """A vector was offered for a space this store neither serves nor builds.
+
+ Its own type because the CALLER's correct response differs from every
+ other store error: this is a CONFIGURATION fault, not a poisoned item.
+ Charging it as a per-item retry (the generic handler) burns five attempts
+ on innocent content and then dead-letters it, so a single mis-registered
+ model switch quietly destroys the corpus item by item while the surface
+ still reads "still filling up" (forensic 2026-07-28). Callers pause the
+ stage instead and leave the backlog exactly where it is.
+ """
+
+
def sanitize_conn_error(exc: BaseException, conn_str: str = "") -> str:
"""``"TypeName: message"`` with every credential scrubbed out.
@@ -582,6 +595,7 @@ class UltraStore(IdentityMixin, EventMixin):
await run_migrations(conn, directory=_MIGRATIONS_DIR)
await self._apply_column_migrations(conn)
await self._adopt_running_reembed(conn)
+ await self._repair_unclaimable_reembed(conn)
self._conn = conn
@staticmethod
@@ -649,6 +663,38 @@ class UltraStore(IdentityMixin, EventMixin):
flagged,
)
+ @staticmethod
+ async def _repair_unclaimable_reembed(conn: aiosqlite.Connection) -> None:
+ """Enforce the invariant every rebuild depends on: a FLAGGED item must
+ be CLAIMABLE.
+
+ ``_reembed_remaining`` counts ``reembed_pending = 1``; ``claim_batch``
+ only ever selects the PREDECESSOR state of the stage it feeds. An item
+ that is flagged while sitting in ``embedded``/``distilled`` therefore
+ satisfies neither: the counter waits for it forever and no worker can
+ ever reach it. The promotion never fires, and because the distill stage
+ stands aside for a running rebuild (``reembed-priority``), summaries
+ stop too — permanently, from a handful of rows.
+
+ ``begin_reembed`` demotes correctly; ``_adopt_running_reembed`` did not,
+ which is how nine such rows stranded a 4 712-item rebuild at 4 703 (the
+ 2026-07-28 forensic). Rather than trust every future writer of the flag
+ to remember, the invariant is restored on open: cheap (the partial
+ index ``idx_uw_items_reembed_pending`` answers it), idempotent, and a
+ no-op in the overwhelmingly common case of no rebuild at all.
+ """
+ await conn.execute(
+ "UPDATE uw_items SET state = ?, updated_at = ?"
+ " WHERE reembed_pending = 1 AND deleted_at IS NULL"
+ " AND state IN (?, ?)",
+ (
+ ItemState.KEYWORD_INDEXED.value,
+ _iso_utc(),
+ ItemState.EMBEDDED.value,
+ ItemState.DISTILLED.value,
+ ),
+ )
+
async def close(self) -> None:
async with self._lock:
for reader in self._read_conns:
@@ -1699,7 +1745,7 @@ class UltraStore(IdentityMixin, EventMixin):
)
await self.begin_reembed(model, dim=dim)
return False
- raise UltraStoreError(
+ raise EmbeddingSpaceMismatch(
"embedding space mismatch: the store is pinned to "
f"model={pinned_model!r} dim={pinned_dim} but got "
f"model={model!r} dim={dim}. Changing the embedding model goes "
@@ -2137,6 +2183,46 @@ class UltraStore(IdentityMixin, EventMixin):
)
return True
+ async def reconcile_space(self, model: str) -> str:
+ """Make the store agree with the model the pipeline is about to use.
+
+ **Why this exists (forensic 2026-07-28).** Registering a model switch
+ used to live in exactly ONE caller — the settings route. Every other
+ way the same value can legitimately change wrote the config and left
+ the store pinned to the previous model: the activation route behind
+ the Normal/Ultra switch, a voice-driven config change, a hand-edited
+ ``jarvis.toml``, a config carried over from another machine. The store
+ then rejected every vector the configured provider produced, the embed
+ lane failed 100 % of its work for days, and the surface still read
+ "still filling up" — because nothing on the failing side ever compared
+ the two values. A rule enforced in one caller is not enforced.
+
+ So the reconciliation happens HERE, next to the pins it protects, and
+ the pipeline calls it with the model it actually resolved. Cheap by
+ design (two primary-key reads in the steady state) because it runs on
+ every pass.
+
+ Returns ``"active"`` (the model serves live search), ``"rebuilding"``
+ (a rebuild into it is already under way), ``"started"`` (this call
+ registered the switch) or ``"unknown"`` (no model to check).
+ """
+ model = str(model or "").strip()
+ if not model:
+ return "unknown"
+ pinned_model, _pinned_dim = await self._pinned_space()
+ # No pin yet: the first vector of an empty store defines the space.
+ if pinned_model is None or pinned_model == model:
+ return "active"
+ pending_model, _pending_dim = await self._pending_space()
+ if pending_model == model:
+ return "rebuilding"
+ # The configured model belongs to NEITHER space. This is the exact
+ # state that used to brick the lane. `begin_reembed` is the sanctioned
+ # switch: live vectors and the ANN index keep answering search
+ # untouched while the new space is built alongside them.
+ started = await self.begin_reembed(model)
+ return "started" if started else "active"
+
async def reembed_is_running(self) -> bool:
"""Is a model switch rebuilding the vector space right now?
@@ -2922,6 +3008,7 @@ class PostgresStore(IdentityMixin, EventMixin):
for statement in self.ddl_statements():
await conn.execute(statement)
await self._adopt_running_reembed(conn)
+ await self._repair_unclaimable_reembed(conn)
self._conn = conn
@staticmethod
@@ -2957,6 +3044,21 @@ class PostgresStore(IdentityMixin, EventMixin):
flagged,
)
+ @staticmethod
+ async def _repair_unclaimable_reembed(conn: Any) -> None:
+ """Postgres twin of :meth:`UltraStore._repair_unclaimable_reembed`."""
+ await conn.execute(
+ "UPDATE uw_items SET state = %s, updated_at = %s"
+ " WHERE reembed_pending = 1 AND deleted_at IS NULL"
+ " AND state IN (%s, %s)",
+ (
+ ItemState.KEYWORD_INDEXED.value,
+ _iso_utc(),
+ ItemState.EMBEDDED.value,
+ ItemState.DISTILLED.value,
+ ),
+ )
+
async def close(self) -> None:
async with self._lock:
if self._conn is not None:
@@ -3718,7 +3820,7 @@ class PostgresStore(IdentityMixin, EventMixin):
)
await self.begin_reembed(model, dim=dim)
return False
- raise UltraStoreError(
+ raise EmbeddingSpaceMismatch(
"embedding space mismatch: the store is pinned to "
f"model={pinned_model!r} dim={pinned_dim} but got "
f"model={model!r} dim={dim}. Changing the embedding model goes "
@@ -4027,6 +4129,20 @@ class PostgresStore(IdentityMixin, EventMixin):
)
return True
+ async def reconcile_space(self, model: str) -> str:
+ """Postgres twin of :meth:`UltraStore.reconcile_space`."""
+ model = str(model or "").strip()
+ if not model:
+ return "unknown"
+ pinned_model, _pinned_dim = await self._pinned_space()
+ if pinned_model is None or pinned_model == model:
+ return "active"
+ pending_model, _pending_dim = await self._pending_space()
+ if pending_model == model:
+ return "rebuilding"
+ started = await self.begin_reembed(model)
+ return "started" if started else "active"
+
async def reembed_is_running(self) -> bool:
"""Postgres twin of :meth:`UltraStore.reembed_is_running`."""
return await self.get_meta(META_PENDING_EMBED_MODEL) is not None
@@ -4391,6 +4507,7 @@ __all__ = [
"META_PENDING_EMBED_DIM",
"META_PENDING_EMBED_MODEL",
"PG_CONNECT_TIMEOUT_S",
+ "EmbeddingSpaceMismatch",
"PostgresStore",
"UltraStore",
"UltraStoreError",
diff --git a/tests/unit/ultrawiki/test_pipeline.py b/tests/unit/ultrawiki/test_pipeline.py
index e9e84cddf1..c725f2669a 100644
--- a/tests/unit/ultrawiki/test_pipeline.py
+++ b/tests/unit/ultrawiki/test_pipeline.py
@@ -20,7 +20,7 @@ from typing import Any
import pytest
from jarvis.ultrawiki.pipeline import EMBED_BATCH, MAX_EMBED_CHARS, PipelineWorker
-from jarvis.ultrawiki.store import UltraStore
+from jarvis.ultrawiki.store import MAX_ATTEMPTS, EmbeddingSpaceMismatch, UltraStore
from jarvis.ultrawiki.types import ConsentState, ItemState, RawItem
VECTOR = [0.1, 0.2, 0.3]
@@ -218,6 +218,96 @@ async def test_not_ready_backend_claims_no_embed_work(store):
assert backend.embed_calls == []
+# ---------------------------------------------------------------------------
+# A vector-space pin the config has outgrown (forensic 2026-07-28)
+# ---------------------------------------------------------------------------
+
+
+async def test_a_stale_vector_space_pin_is_reconciled_not_dead_lettered(store):
+ """Changing the embedding model outside PUT /settings must still work.
+
+ The maintainer switched the model with the Normal/Ultra switch — a real,
+ visible UI act. That route wrote the config and never registered the switch
+ with the store, so every vector the new provider produced was rejected. The
+ lane failed 100 % of its work for a day, and because the rejection was
+ charged as a per-item retry, the corpus was five attempts away from
+ dead-lettering itself item by item while the screen said "still filling up".
+
+ The worker now reconciles with the model it actually resolved, so the
+ rebuild starts on the next pass no matter who changed the setting.
+ """
+ await store.upsert_items("src1", [make_item(1)])
+ cfg = make_cfg()
+ backend = FakeEmbeddingBackend()
+ worker = PipelineWorker(
+ store,
+ cfg,
+ embedding_backend_factory=lambda: backend,
+ distill_fn=distill_never,
+ distill_ready_fn=DISTILL_READY,
+ )
+ await worker.run_once()
+ assert (await store.counts()).embedded == 1 # pin is now "fake-model"
+
+ # The switch, exactly as a bypassing route leaves it: config says one
+ # model, the store is still pinned to the other.
+ cfg.ultrawiki.embedding_model = "other-model"
+ await store.upsert_items("src1", [make_item(2)])
+
+ for _ in range(MAX_ATTEMPTS + 1):
+ await worker.run_once()
+
+ # Not one item was charged an attempt, let alone dead-lettered.
+ counts = await store.counts()
+ assert counts.failed == 0
+ item = await store.get_item_by_external_id("src1", "ext-0002")
+ assert item is not None
+ assert item["attempt_count"] == 0
+
+ # And the lane is moving again: the switch was registered as a background
+ # rebuild, with the live vectors still serving search until it completes.
+ assert (await store.reembed_status())["model"] == "other-model"
+ assert item["state"] == ItemState.EMBEDDED.value
+
+
+async def test_a_space_mismatch_pauses_the_lane_and_charges_no_attempt(store):
+ """The second half of the same defect, isolated.
+
+ Reconciliation cannot close every gap — a provider may answer with a model
+ id nobody configured. Whatever the cause, a vector-space mismatch is a
+ CONFIGURATION fault: it says nothing about the item that happened to be in
+ the batch, so charging it an attempt (and dead-lettering it on the fifth)
+ destroys innocent content to report a settings problem.
+ """
+ await store.upsert_items("src1", [make_item(1)])
+
+ async def refuse(*args: Any, **kwargs: Any) -> None:
+ raise EmbeddingSpaceMismatch("embedding space mismatch: pinned to model-a")
+
+ async def already_fine(model: str) -> str:
+ return "active" # reconciliation sees nothing to do
+
+ store.store_embedding = refuse # type: ignore[method-assign]
+ store.reconcile_space = already_fine # type: ignore[method-assign]
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=FakeEmbeddingBackend,
+ distill_fn=distill_never,
+ distill_ready_fn=DISTILL_READY,
+ )
+
+ for _ in range(MAX_ATTEMPTS + 1):
+ await worker.run_once()
+
+ item = await store.get_item_by_external_id("src1", "ext-0001")
+ assert item is not None
+ # The backlog waits, intact, exactly where it was.
+ assert item["state"] == ItemState.KEYWORD_INDEXED.value
+ assert item["attempt_count"] == 0
+ assert (await store.counts()).failed == 0
+
+
# ---------------------------------------------------------------------------
# Poisoned distill item — retries into failed while others pass
# ---------------------------------------------------------------------------
diff --git a/tests/unit/ultrawiki/test_store.py b/tests/unit/ultrawiki/test_store.py
index cbaa846076..b48ebe31b3 100644
--- a/tests/unit/ultrawiki/test_store.py
+++ b/tests/unit/ultrawiki/test_store.py
@@ -496,6 +496,94 @@ async def test_existing_database_migrates_to_the_shadow_space_key(tmp_path):
await migrated.close()
+async def test_reconcile_space_registers_a_switch_no_caller_announced(store):
+ """The forensic of 2026-07-28, as a contract.
+
+ Registering a model switch lived in ONE caller (PUT /settings). Every other
+ legitimate way the setting changes — the activation route behind the
+ Normal/Ultra switch, a voice-driven config change, a hand-edited
+ jarvis.toml, a config carried over from another machine — wrote the new
+ model and left the store pinned to the old one. The store then rejected
+ every vector the configured provider produced: the embed lane failed 100 %
+ of its work for days while the surface still read "still filling up".
+
+ A rule enforced in one caller is not enforced. `reconcile_space` is what
+ the pipeline asks on every pass, so the guarantee no longer depends on
+ which door the user walked through.
+ """
+ await add_source(store)
+ _item, doc = await _seed_embedded_item(store, 0)
+ await store.store_embedding(doc, model="model-a", dim=4, vector=[1, 0, 0, 0])
+
+ # The live model needs nothing and must stay cheap — this runs every pass.
+ assert await store.reconcile_space("model-a") == "active"
+ assert await store.reembed_status() == {}
+ # An empty model name is "the slot has not resolved one yet", never a
+ # reason to tear down a vector space.
+ assert await store.reconcile_space(" ") == "unknown"
+ assert await store.reembed_status() == {}
+
+ # A model belonging to NEITHER space is exactly the bricked state. It is
+ # registered as a background rebuild, not left to fail per item.
+ assert await store.reconcile_space("model-b") == "started"
+ assert (await store.reembed_status())["model"] == "model-b"
+ # The live space is untouched: search keeps answering while it rebuilds.
+ assert await store.get_meta(META_EMBED_MODEL) == "model-a"
+
+ # Idempotent: the next pass finds the rebuild already running and must not
+ # restart it (that would discard every vector produced so far).
+ assert await store.reconcile_space("model-b") == "rebuilding"
+ assert (await store.reembed_status())["model"] == "model-b"
+
+ # And the point of the whole exercise: the vector the provider produces is
+ # now accepted instead of raising.
+ await store.store_embedding(doc, model="model-b", dim=3, vector=[1, 0, 0])
+
+
+async def test_a_flagged_reembed_item_is_never_left_unclaimable(tmp_path):
+ """A flagged item that no worker can claim stalls the rebuild forever.
+
+ ``_reembed_remaining`` counts ``reembed_pending = 1``; ``claim_batch`` only
+ selects the PREDECESSOR state of the stage it feeds. An item flagged while
+ sitting in ``embedded`` satisfies neither — the counter waits for it and no
+ worker can reach it. On the maintainer's store nine such rows stranded a
+ 4 712-item rebuild at 4 703, which also kept the distill stage standing
+ aside for a rebuild that could never finish: summaries stopped permanently.
+ """
+ path = tmp_path / "ultrawiki.db"
+ store = UltraStore(path)
+ try:
+ await add_source(store)
+ item_id, doc_id = await _seed_embedded_item(store, 0)
+ await store.store_embedding(doc_id, model="model-a", dim=4, vector=[1, 0, 0, 0])
+ await store.mark_stage_done(item_id, ItemState.EMBEDDED)
+ assert await store.begin_reembed("model-b") is True
+
+ # Reproduce the damage the adopt path caused: flag the item WITHOUT
+ # demoting it (begin_reembed demotes; _adopt_running_reembed did not).
+ conn = await store._ensure_open()
+ await conn.execute(
+ "UPDATE uw_items SET state = ?, reembed_pending = 1 WHERE id = ?",
+ (ItemState.EMBEDDED.value, item_id),
+ )
+
+ # The deadlock: counted as outstanding, unreachable by any worker.
+ assert (await store.reembed_status())["remaining"] == 1
+ assert await store.claim_batch(ItemState.EMBEDDED) == []
+ finally:
+ await store.close()
+
+ reopened = UltraStore(path)
+ try:
+ claimed = await reopened.claim_batch(ItemState.EMBEDDED)
+ assert [row["id"] for row in claimed] == [item_id]
+ # Still owed to the rebuild — the repair restores reachability, it does
+ # not silently declare the work done.
+ assert (await reopened.reembed_status())["remaining"] == 1
+ finally:
+ await reopened.close()
+
+
async def test_switching_back_mid_rebuild_costs_nothing(store):
"""The reversibility half: an abandoned rebuild must not have damaged the
live space, so changing your mind is free rather than a second full run."""