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.

feat(ultrawiki): keep semantic search alive while a model switch rebuilds

Ruben Lütke055f8f5b68ec
diff --git a/UltraWiki/04-configuration-and-ui.md b/UltraWiki/04-configuration-and-ui.md
index 9e20050bee..2801f93cfc 100644
--- a/UltraWiki/04-configuration-and-ui.md
+++ b/UltraWiki/04-configuration-and-ui.md
@@ -12,7 +12,7 @@ local and one cloud option**:
| Slot | Local option | Cloud option | Switch cost |
|---|---|---|---|
| **Storage** | SQLite file (created automatically under the data dir) | PostgreSQL connection string — any host the user has (own server, Supabase, Neon, RDS, …) | export/import migration, guided |
-| **Embedding model** | multilingual local model via Ollama (bge-m3 class; one-time download) | any configured embedding-capable provider key (e.g. Gemini Embedding, OpenAI, Voyage, Mistral) | **full re-embed** — deliberate, wizard-guarded (D-3) |
+| **Embedding model** | multilingual local model via Ollama (bge-m3 class; one-time download) | any configured embedding-capable provider key (e.g. Gemini Embedding, OpenAI, Voyage, Mistral) | **background rebuild** — deliberate, confirmed; search stays up throughout (D-3) |
| **Distillation model** | local model via Ollama | any configured chat-capable provider key | none (applies to new work; re-enrichment optional) |
| **Rerank (optional)** | local cross-encoder | rerank-capable provider | none |
diff --git a/UltraWiki/README.md b/UltraWiki/README.md
index df9afed5ed..d2c79d4f65 100644
--- a/UltraWiki/README.md
+++ b/UltraWiki/README.md
@@ -56,7 +56,7 @@ D-5). The switch is **role-based, never destructive** (D-9):
|---|---|
| D-1 | Design written from scratch; earlier cleared design docs are not a basis. |
| D-2 | **Bring-your-own everything.** Jarvis bundles and provisions no database and no service. A dedicated UltraWiki settings section (modeled on the API-Keys section) lets the user pick storage, models, and sources — always with at least one local AND one cloud option per slot. |
-| D-3 | The embedding model is a **one-time deliberate choice in the activation wizard** (switching later triggers an explicit, cost-estimated re-embed). |
+| D-3 | The embedding model is a **deliberate choice in the activation wizard**. Switching later triggers an explicit, confirmed rebuild — the new vector space is built in the BACKGROUND alongside the live one, so semantic search never goes dark and switching back before it completes costs nothing. Only the model defines the space: the same model behind a different provider needs no rebuild at all. |
| D-4 | Source scope is "the whole life": local files (Obsidian, Jarvis conversations, folders), export-file imports (WhatsApp, takeouts), OAuth APIs (Google mail/calendar/drive, GitHub), and a **generic bridge that turns every connected Jarvis plugin/CLI into a data source**. |
| D-5 | UI is an **either-or mode switch** inside the Wiki section; the active mode replaces the other completely. |
| D-6 | The distillation model (the LLM that summarizes raw content before storage) is chosen in the same activation wizard — local or cloud, one conscious privacy decision. |
@@ -78,6 +78,7 @@ D-5). The switch is **role-based, never destructive** (D-9):
| [`05-identity-areas-privacy.md`](05-identity-areas-privacy.md) | Entity resolution, the confirmation queue, areas, privacy and deletion |
| [`06-roadmap.md`](06-roadmap.md) | Build phases with hard gates |
| [`07-visual-projection.md`](07-visual-projection.md) | The readable face: topic/moment pages, the entity graph, and the generated Obsidian vault |
+| [`08-universal-ingestion.md`](08-universal-ingestion.md) | Taking in everything from every platform worldwide: one extractor, media enrichment, the platform export guide, the generic custom source |
## Prior art
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.test.tsx
index 16966663bc..bcd0f6c722 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.test.tsx
@@ -352,6 +352,40 @@ describe("SlotsPanel", () => {
expect(dialog.textContent).toContain("412");
});
+ it("shows the background rebuild instead of looking idle", async () => {
+ // A model switch rebuilds the vector space WITHOUT taking search down, so
+ // the panel would otherwise sit fully green for hours with no sign that
+ // anything is happening.
+ installFetchMock();
+ renderWithClient(
+ <SlotsPanel
+ status={{
+ ...STATUS,
+ reembed: {
+ model: "voyage-3.5",
+ active_model: "bge-m3",
+ done: 120,
+ total: 400,
+ },
+ }}
+ onChanged={() => {}}
+ />,
+ );
+ const banner = await screen.findByTestId("ultrawiki-reembed-progress");
+ expect(banner.textContent).toContain("120");
+ expect(banner.textContent).toContain("400");
+ expect(
+ within(banner).getByRole("progressbar").getAttribute("aria-valuenow"),
+ ).toBe("30");
+ });
+
+ it("stays out of the way when no rebuild is running", async () => {
+ installFetchMock();
+ renderWithClient(<SlotsPanel status={STATUS} onChanged={() => {}} />);
+ await screen.findByTestId("ultrawiki-slots-panel");
+ expect(screen.queryByTestId("ultrawiki-reembed-progress")).toBeNull();
+ });
+
it("offers the guided Supabase sign-in instead of a raw URI box", async () => {
renderWithClient(<SlotsPanel status={STATUS} onChanged={() => {}} />);
const connect = await screen.findByTestId("ultrawiki-supabase-connect");
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.tsx
index e9e4848590..33e86afb95 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.tsx
@@ -161,6 +161,8 @@ export function SlotsPanel({
{t("ultrawiki.slots.title")}
</h3>
+ <ReembedProgress status={status} />
+
<StorageSection {...shared} />
<EmbeddingSection {...shared} />
<DistillSection {...shared} />
@@ -703,6 +705,47 @@ function ReembedDialog({
);
}
+/**
+ * The background rebuild after an embedding-model switch.
+ *
+ * It is deliberately calm rather than a warning: search is NOT degraded while
+ * this runs — the old vector space keeps answering until the new one is
+ * complete. Without the line, though, the panel would look idle for hours
+ * after a switch, which is how "did my change do anything?" starts.
+ */
+function ReembedProgress({ status }: { status: UltraWikiStatus }): JSX.Element | null {
+ const t = useT();
+ const reembed = status.reembed;
+ if (!reembed?.model) return null;
+ const total = Number(reembed.total ?? 0);
+ const done = Math.min(Number(reembed.done ?? 0), total);
+ const percent = total > 0 ? Math.round((done / total) * 100) : 0;
+ return (
+ <div
+ className="rounded-md border border-border bg-muted/40 px-4 py-3"
+ data-testid="ultrawiki-reembed-progress"
+ >
+ <p className="text-sm text-muted-foreground">
+ {t("ultrawiki.slots.reembed_progress")
+ .replace("{0}", String(done))
+ .replace("{1}", String(total))}
+ </p>
+ <div
+ className="mt-2 h-1.5 overflow-hidden rounded-full bg-border"
+ role="progressbar"
+ aria-valuenow={percent}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ >
+ <div
+ className="h-full rounded-full bg-primary transition-all"
+ style={{ width: `${percent}%` }}
+ />
+ </div>
+ </div>
+ );
+}
+
/** Per-slot real-call Test button + result chip (the API-Keys test idiom). */
function SlotTestControl({ slot }: { slot: UltraWikiSlotName }): JSX.Element {
const t = useT();
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 2a146f760a..ba35acfe58 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -3018,10 +3018,11 @@
"applying": "Wird übernommen…",
"applied": "Slot-Einstellungen übernommen.",
"apply_failed": "Konnte nicht übernommen werden: {0}",
- "reembed_started": "Das Neu-Einbetten läuft im Hintergrund — die Stichwortsuche funktioniert währenddessen weiter.",
- "reembed_title": "Alles neu einbetten?",
- "reembed_body": "Ein Wechsel von Embedding-Anbieter oder -Modell wechselt den Vektorraum: {0} bereits eingebettete Elemente werden verworfen und im Hintergrund neu eingebettet. Die Stichwortsuche funktioniert währenddessen weiter.",
- "reembed_confirm": "{0} Elemente neu einbetten",
+ "reembed_started": "Der neue Suchindex wird im Hintergrund aufgebaut — die Suche nutzt so lange den aktuellen weiter.",
+ "reembed_title": "Suchindex neu aufbauen?",
+ "reembed_body": "Jedes Modell legt Bedeutung in seinem eigenen Koordinatensystem ab. Die {0} eingebetteten Elemente müssen deshalb mit dem neuen Modell neu vermessen werden — alte und neue Werte sind nicht vergleichbar. Der Aufbau läuft im Hintergrund, die Suche antwortet so lange aus dem aktuellen Index weiter. Es wird nichts gelöscht, du kannst jederzeit zurückwechseln.",
+ "reembed_confirm": "{0} Elemente neu aufbauen",
+ "reembed_progress": "Neuer Suchindex im Aufbau: {0} von {1} Textabschnitten. Die Suche ist davon nicht betroffen.",
"test": "Testen",
"testing": "Teste…",
"test_ok": "OK",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 13380fa457..c478d70144 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -3004,10 +3004,11 @@
"applying": "Applying…",
"applied": "Slot settings applied.",
"apply_failed": "Could not apply: {0}",
- "reembed_started": "Re-embedding runs in the background — keyword search keeps working meanwhile.",
- "reembed_title": "Re-embed everything?",
- "reembed_body": "Changing the embedding provider or model switches vector spaces: {0} already-embedded items will be dropped and re-embedded in the background. Keyword search keeps working meanwhile.",
- "reembed_confirm": "Re-embed {0} items",
+ "reembed_started": "The new index is being built in the background — search keeps using the current one until it is ready.",
+ "reembed_title": "Rebuild the search index?",
+ "reembed_body": "Every model stores meaning in its own coordinate system, so the {0} embedded items have to be measured again with the new one — old and new values cannot be compared. The rebuild runs in the background, and search keeps answering from the current index until the new one is complete. Nothing is deleted meanwhile, so you can switch back at any time.",
+ "reembed_confirm": "Rebuild {0} items",
+ "reembed_progress": "Building the new search index: {0} of {1} passages. Search is unaffected.",
"test": "Test",
"testing": "Testing…",
"test_ok": "OK",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index ad956ea9c2..02f9882c98 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -3003,10 +3003,11 @@
"applying": "Aplicando…",
"applied": "Ajustes de ranuras aplicados.",
"apply_failed": "No se pudo aplicar: {0}",
- "reembed_started": "La re-incrustación se ejecuta en segundo plano — la búsqueda por palabras clave sigue funcionando mientras tanto.",
- "reembed_title": "¿Volver a incrustar todo?",
- "reembed_body": "Cambiar el proveedor o el modelo de embeddings cambia el espacio vectorial: {0} elementos ya incrustados se descartarán y se volverán a incrustar en segundo plano. La búsqueda por palabras clave sigue funcionando mientras tanto.",
- "reembed_confirm": "Volver a incrustar {0} elementos",
+ "reembed_started": "El nuevo índice se construye en segundo plano — la búsqueda sigue usando el actual hasta que esté listo.",
+ "reembed_title": "¿Reconstruir el índice de búsqueda?",
+ "reembed_body": "Cada modelo guarda el significado en su propio sistema de coordenadas, así que los {0} elementos incrustados deben medirse de nuevo con el nuevo modelo — los valores antiguos y nuevos no son comparables. La reconstrucción se ejecuta en segundo plano y la búsqueda sigue respondiendo desde el índice actual hasta que el nuevo esté completo. Mientras tanto no se borra nada, así que puedes volver atrás en cualquier momento.",
+ "reembed_confirm": "Reconstruir {0} elementos",
+ "reembed_progress": "Construyendo el nuevo índice de búsqueda: {0} de {1} fragmentos. La búsqueda no se ve afectada.",
"test": "Probar",
"testing": "Probando…",
"test_ok": "OK",
diff --git a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
index 8dab99580c..81912d08e7 100644
--- a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
@@ -398,6 +398,19 @@ export interface UltraWikiStatus {
storage?: UltraWikiStorageSlot;
};
counts: Partial<UltraWikiCounts>;
+ /**
+ * Mirrors jarvis/ultrawiki/store.py::reembed_status — present only while an
+ * embedding-model switch rebuilds the vector space in the background.
+ * Search answers from the OLD space throughout, so without this the UI would
+ * show an idle, fully-green knowledge base during the whole rebuild.
+ * `done`/`total` count passages, not items.
+ */
+ reembed?: {
+ model?: string;
+ active_model?: string;
+ done?: number;
+ total?: number;
+ };
progress?: UltraWikiProgress;
pipeline: UltraWikiPipeline;
sources: UltraWikiSource[];
diff --git a/jarvis/ui/web/ultrawiki_routes.py b/jarvis/ui/web/ultrawiki_routes.py
index 00c7334c80..baa69112df 100644
--- a/jarvis/ui/web/ultrawiki_routes.py
+++ b/jarvis/ui/web/ultrawiki_routes.py
@@ -260,6 +260,7 @@ async def get_status(request: Request) -> dict[str, Any]:
"db_backend": configured_backend,
"backend_in_use": "",
"slots": {},
+ "reembed": {},
"counts": {},
# Same shape as a live answer, so no client has to special-case a
# booting backend into zeros of its own invention.
@@ -298,6 +299,10 @@ async def get_status(request: Request) -> dict[str, Any]:
"db_backend": str(backend.get("configured") or configured_backend),
"backend_in_use": str(backend.get("in_use") or ""),
"slots": slots,
+ # Empty unless an embedding-model switch is rebuilding the vector space
+ # right now. Search keeps answering from the old space meanwhile, so
+ # without this a client would show a green, idle knowledge base.
+ "reembed": data.get("reembed", {}),
"counts": data.get("counts", {}),
"progress": data.get("progress") or build_progress(data.get("counts")),
"pipeline": data.get("pipeline", {}),
@@ -1038,6 +1043,28 @@ class UpdateSettingsBody(BaseModel):
confirm_reembed: bool = False
+def _effective_embedding_model(uw: Any, changes: dict[str, str]) -> str:
+ """The model name the embed stage will actually send after *changes*.
+
+ The vector space is defined by the MODEL, not by who hosts it, and an empty
+ model field means "this provider's default". Both matter for the re-embed
+ question: resolving it here is what lets a pure provider switch that keeps
+ the model skip the rebuild entirely.
+ """
+ model = changes.get("embedding_model")
+ if model is None:
+ model = str(getattr(uw, "embedding_model", "") or "")
+ model = model.strip()
+ if model:
+ return model
+ provider = changes.get("embedding_provider")
+ if provider is None:
+ provider = str(getattr(uw, "embedding_provider", "") or "")
+ from jarvis.ultrawiki import embeddings as embeddings_mod # noqa: PLC0415
+
+ return embeddings_mod.DEFAULT_MODELS.get(provider.strip(), "")
+
+
@router.put(
"/settings",
summary="Change UltraWiki slot settings",
@@ -1111,21 +1138,31 @@ async def update_settings(body: UpdateSettingsBody, request: Request) -> dict[st
key in changes for key in ("embedding_provider", "embedding_model")
)
vector_items = 0
+ target_model = ""
if embedding_change:
+ from jarvis.ultrawiki.store import META_EMBED_MODEL # noqa: PLC0415
+
store = await _store_of(service)
- counts = await store.counts()
- vector_items = int(counts.embedded) + int(counts.distilled)
+ target_model = _effective_embedding_model(uw, changes)
+ pinned_model = await store.get_meta(META_EMBED_MODEL)
+ # Same model behind a different provider is the SAME vector space —
+ # nothing to rebuild, so nothing to confirm either.
+ if pinned_model and target_model and pinned_model != target_model:
+ counts = await store.counts()
+ vector_items = int(counts.embedded) + int(counts.distilled)
if vector_items and not body.confirm_reembed:
raise HTTPException(
status_code=409,
detail={
"message": (
"changing the embedding provider or model switches "
- f"vector spaces: the {vector_items} already-embedded "
- "items must be re-embedded from scratch. Repeat the "
- "request with confirm_reembed=true to drop the "
- "existing vectors and re-embed in the background — "
- "keyword search keeps working meanwhile."
+ f"vector spaces, so the {vector_items} embedded items "
+ "have to be embedded again with the new model — "
+ "vectors of two models cannot be compared. Repeat the "
+ "request with confirm_reembed=true to start that "
+ "rebuild in the background. Semantic search keeps "
+ "answering from the current vectors the whole time; "
+ "the new space is swapped in only once it is complete."
),
"vector_items": vector_items,
},
@@ -1135,13 +1172,12 @@ async def update_settings(body: UpdateSettingsBody, request: Request) -> dict[st
persisted, persist_error = _persist_slots(applied)
_apply_live(request, applied)
reembed_started = False
- if embedding_change:
+ if embedding_change and target_model:
store = await _store_of(service)
- # Drops uw_vec + uw_embeddings, clears the model/dim pin, and resets
- # embedded/distilled items to keyword_indexed — the running pipeline
- # re-embeds them in the background with the new slot.
- await store.reset_vectors()
- reembed_started = vector_items > 0
+ # Builds the new space ALONGSIDE the live one: the current vectors and
+ # the ANN index stay untouched and keep serving search until the
+ # pipeline has re-embedded everything (store.promote_pending_space).
+ reembed_started = await store.begin_reembed(target_model)
response: dict[str, Any] = {
"ok": True,
"changed": sorted(applied),
diff --git a/jarvis/ultrawiki/migrations/0002_embedding_shadow_space.sql b/jarvis/ultrawiki/migrations/0002_embedding_shadow_space.sql
new file mode 100644
index 0000000000..7ea0a13aa5
--- /dev/null
+++ b/jarvis/ultrawiki/migrations/0002_embedding_shadow_space.sql
@@ -0,0 +1,41 @@
+-- Two embedding spaces may coexist, so switching the model no longer blinds
+-- semantic search.
+--
+-- Why: `uw_embeddings` was keyed by `document_id` alone, so exactly ONE vector
+-- per document could exist and therefore exactly one embedding space per
+-- store. Changing the embedding provider or model consequently had to DELETE
+-- every stored vector before the first replacement was computed — semantic
+-- search went dark for the whole re-embed, minutes to hours on a real corpus,
+-- and switching back cost the same again. The rebuild itself is unavoidable
+-- (vectors of two models are not comparable), but the blackout is not.
+--
+-- Widening the key to (document_id, model, dim) lets the NEW space be built
+-- alongside the live one; the `uw_vec` ANN index stays derived from the ACTIVE
+-- space only and is rebuilt at the moment of promotion. A cancelled switch
+-- simply drops the half-built shadow rows and leaves the live space untouched.
+
+BEGIN;
+
+CREATE TABLE uw_embeddings_new (
+ document_id INTEGER NOT NULL
+ REFERENCES uw_documents(id) ON DELETE CASCADE,
+ model TEXT NOT NULL,
+ dim INTEGER NOT NULL,
+ vector BLOB NOT NULL,
+ created_at TEXT NOT NULL,
+ PRIMARY KEY (document_id, model, dim)
+);
+
+INSERT INTO uw_embeddings_new
+ (document_id, model, dim, vector, created_at)
+SELECT document_id, model, dim, vector, created_at FROM uw_embeddings;
+
+DROP TABLE uw_embeddings;
+
+ALTER TABLE uw_embeddings_new RENAME TO uw_embeddings;
+
+-- The promotion and progress queries both filter by space.
+CREATE INDEX IF NOT EXISTS idx_uw_embeddings_space
+ ON uw_embeddings(model, dim);
+
+COMMIT;
diff --git a/jarvis/ultrawiki/migrations/README.md b/jarvis/ultrawiki/migrations/README.md
index cadb374dd9..4dceb8a4f1 100644
--- a/jarvis/ultrawiki/migrations/README.md
+++ b/jarvis/ultrawiki/migrations/README.md
@@ -24,6 +24,9 @@ The contract:
from the same point.
- Files that do not match `NNNN_<slug>.sql` are ignored (this README included).
-No migration files exist yet — the base schema is current. The Postgres
-backend applies its DDL idempotently from `PostgresStore.ddl_statements()` and
-receives its own version tracking when its first migration ships.
+Shipped so far: `0001` (multi-chunk documents), `0002` (the shadow embedding
+space — widening the `uw_embeddings` key so a model switch can build the new
+vector space alongside the live one). The Postgres backend applies its DDL
+idempotently from `PostgresStore.ddl_statements()`, including the in-place
+key widening that mirrors `0002`; it receives its own version tracking when a
+change ships that idempotent DDL cannot express.
diff --git a/jarvis/ultrawiki/schema.sql b/jarvis/ultrawiki/schema.sql
index a69bcee832..81861b2b1d 100644
--- a/jarvis/ultrawiki/schema.sql
+++ b/jarvis/ultrawiki/schema.sql
@@ -131,19 +131,28 @@ CREATE TABLE IF NOT EXISTS uw_documents (
CREATE INDEX IF NOT EXISTS idx_uw_documents_item ON uw_documents(item_id);
-- Embedding vectors, stored provider-neutral as little-endian float32 BLOBs
--- keyed by document. The sqlite-vec vec0 index (uw_vec) is DERIVED from this
--- table by store.py once the extension loads and the dimension is pinned —
--- so a host without the extension still accumulates vectors and gains
--- semantic search the moment the extension becomes available, without
--- re-embedding anything.
+-- keyed by document AND embedding space. The sqlite-vec vec0 index (uw_vec) is
+-- DERIVED from this table by store.py once the extension loads and the
+-- dimension is pinned — so a host without the extension still accumulates
+-- vectors and gains semantic search the moment the extension becomes
+-- available, without re-embedding anything.
+--
+-- The (model, dim) part of the key is what lets a model switch build the new
+-- space ALONGSIDE the live one (uw_meta: embed_model/embed_dim pin the active
+-- space, pending_embed_model/pending_embed_dim the one being built). Semantic
+-- search keeps answering from the active space until the shadow is complete
+-- and store.py promotes it. Steady state holds exactly one space.
CREATE TABLE IF NOT EXISTS uw_embeddings (
- document_id INTEGER PRIMARY KEY
+ document_id INTEGER NOT NULL
REFERENCES uw_documents(id) ON DELETE CASCADE,
model TEXT NOT NULL,
dim INTEGER NOT NULL,
vector BLOB NOT NULL,
- created_at TEXT NOT NULL
+ created_at TEXT NOT NULL,
+ PRIMARY KEY (document_id, model, dim)
);
+CREATE INDEX IF NOT EXISTS idx_uw_embeddings_space
+ ON uw_embeddings(model, dim);
-- Distillation results cached on (content_hash, prompt_version, model):
-- identical input is never paid for twice, and crash re-runs converge
diff --git a/jarvis/ultrawiki/service.py b/jarvis/ultrawiki/service.py
index 9a2864e833..34f9be753c 100644
--- a/jarvis/ultrawiki/service.py
+++ b/jarvis/ultrawiki/service.py
@@ -587,6 +587,7 @@ class UltraWikiService:
counts = PipelineCounts()
sources: list[dict[str, Any]] = []
vector: dict[str, Any] = {"ready": False, "reason": "store not started"}
+ reembed: dict[str, Any] = {}
if started:
try:
counts = await self._store.counts()
@@ -601,6 +602,16 @@ class UltraWikiService:
vector = {"ready": bool(vec_ok), "reason": vec_reason}
except Exception as exc: # noqa: BLE001 — status never raises
vector = {"ready": False, "reason": f"vector probe failed ({exc})"}
+ # A model switch rebuilds the vector space in the background while
+ # search keeps answering from the old one. Without this the UI
+ # would show a fully-green knowledge base and no hint that half the
+ # corpus is still being re-embedded.
+ status_fn = getattr(self._store, "reembed_status", None)
+ if status_fn is not None:
+ try:
+ reembed = dict(await status_fn())
+ except Exception as exc: # noqa: BLE001 — status never raises
+ self._note_degradation(f"re-embed status query failed ({exc})")
pipeline_running = (
self._pipeline_task is not None and not self._pipeline_task.done()
)
@@ -647,6 +658,9 @@ class UltraWikiService:
},
"slots": slots,
"vector": vector,
+ # Empty unless an embedding-model switch is rebuilding right now:
+ # {model, active_model, done, total} over DOCUMENTS.
+ "reembed": reembed,
"counts": counts_payload,
"progress": progress,
"pipeline": {
diff --git a/jarvis/ultrawiki/store.py b/jarvis/ultrawiki/store.py
index b642b09e21..a0db765c71 100644
--- a/jarvis/ultrawiki/store.py
+++ b/jarvis/ultrawiki/store.py
@@ -72,10 +72,19 @@ MAX_ATTEMPTS = 5
BACKOFF_BASE_S = 60
BACKOFF_CAP_S = 6 * 3600
-#: ``uw_meta`` keys pinning the embedding space (semi-permanent, D-3).
+#: ``uw_meta`` keys pinning the ACTIVE embedding space — the one the derived
+#: ``uw_vec`` index holds and every search answers from (D-3).
META_EMBED_MODEL = "embed_model"
META_EMBED_DIM = "embed_dim"
+#: ``uw_meta`` keys naming the space currently being built in the background
+#: after a model switch. Vectors accumulate under it while searches keep using
+#: the active space; :meth:`UltraStore.promote_pending_space` swaps them once
+#: the shadow covers everything the live space covers. The dimension is unknown
+#: until the provider answers, so ``PENDING_DIM`` appears with the first vector.
+META_PENDING_EMBED_MODEL = "pending_embed_model"
+META_PENDING_EMBED_DIM = "pending_embed_dim"
+
_SNIPPET_CHARS = 240
_IN_CHUNK = 400
@@ -355,6 +364,34 @@ def _item_filter_sql(
return (f" WHERE {' AND '.join(clauses)}" if clauses else ""), params
+def _documents_unchanged(
+ rows: Sequence[Any], chunks: Sequence[Any], content_hash: str
+) -> bool:
+ """True when the stored rows ALREADY are the passage set *chunks* describes.
+
+ Why this matters far beyond saving two writes: ``uw_embeddings`` cascades on
+ ``uw_documents``. A delete-and-reinsert therefore destroys every vector the
+ item owns — including the ones of the ACTIVE embedding space, which the
+ shadow rebuild after a model switch depends on keeping. Chunking is
+ deterministic, so a re-embed of unchanged content produces byte-identical
+ passages; recognizing that keeps the document ids (and their live vectors)
+ stable across re-runs.
+ """
+ chunk_list = list(chunks)
+ if len(rows) != len(chunk_list):
+ return False
+ by_index = {int(row["chunk_index"]): row for row in rows}
+ for chunk in chunk_list:
+ row = by_index.get(int(getattr(chunk, "index", 0)))
+ if row is None:
+ return False
+ if str(row["text_norm"]) != str(getattr(chunk, "text", "")):
+ return False
+ if str(row["content_hash"] or "") != str(content_hash or ""):
+ return False
+ return True
+
+
def _counts_from_pairs(pairs: Iterable[tuple[str, int]]) -> PipelineCounts:
by_state = {state.value: 0 for state in ItemState}
for state_value, count in pairs:
@@ -1418,16 +1455,23 @@ class UltraStore:
an item with half its passages, and a re-run is idempotent.
Returns the new document ids in passage order, so the caller can pair
- each with its vector.
+ each with its vector. When the stored passages are already identical
+ (a re-embed of unchanged content), the existing rows are KEPT and their
+ ids returned — see :func:`_documents_unchanged` for why that is load
+ bearing rather than an optimization.
"""
kind = DocType(doc_type).value
now = _iso_utc()
async with self._txn() as conn:
old_rows = await self._fetchall(
conn,
- "SELECT id FROM uw_documents WHERE item_id = ? AND doc_type = ?",
+ "SELECT id, chunk_index, text_norm, content_hash FROM uw_documents"
+ " WHERE item_id = ? AND doc_type = ?",
(item_id, kind),
)
+ if _documents_unchanged(old_rows, chunks, content_hash):
+ by_index = {int(row["chunk_index"]): int(row["id"]) for row in old_rows}
+ return [by_index[int(getattr(c, "index", 0))] for c in chunks]
old_ids = [row["id"] for row in old_rows]
if old_ids and self._vec_state is not None and self._vec_state[0]:
for chunk in _chunks(old_ids):
@@ -1469,6 +1513,61 @@ class UltraStore:
dim_raw = await self.get_meta(META_EMBED_DIM)
return model, int(dim_raw) if dim_raw else None
+ async def _pending_space(self) -> tuple[str | None, int | None]:
+ model = await self.get_meta(META_PENDING_EMBED_MODEL)
+ dim_raw = await self.get_meta(META_PENDING_EMBED_DIM)
+ return model, int(dim_raw) if dim_raw else None
+
+ async def _writes_to_active_space(self, model: str, dim: int) -> bool:
+ """Decide which space a vector of ``(model, dim)`` belongs to.
+
+ ``True`` means the ACTIVE space — the one ``uw_vec`` mirrors and every
+ search answers from. ``False`` means the shadow space of a running
+ rebuild. A pair matching neither raises: that is the D-3 guard, so
+ nothing mixes incompatible vector spaces by accident. A deliberate
+ change goes through :meth:`begin_reembed`.
+ """
+ pinned_model, pinned_dim = await self._pinned_space()
+ if pinned_model is None or pinned_dim is None:
+ await self.set_meta(META_EMBED_MODEL, model)
+ await self.set_meta(META_EMBED_DIM, str(dim))
+ return True
+ if pinned_model == model and pinned_dim == dim:
+ return True
+ pending_model, pending_dim = await self._pending_space()
+ if pending_model is not None and pending_model == model:
+ if pending_dim is None:
+ # First vector of the rebuild: the provider just told us the
+ # width of the new space.
+ await self.set_meta(META_PENDING_EMBED_DIM, str(dim))
+ elif pending_dim != dim:
+ raise UltraStoreError(
+ f"embedding dimension mismatch: the rebuild of {model!r} "
+ f"started at dim={pending_dim} but got dim={dim}"
+ )
+ return False
+ if pinned_model == model:
+ # Same model NAME, different width — a genuinely different model
+ # behind a familiar name (switching provider onto a same-named
+ # model). It IS a new vector space, so rebuild into it rather than
+ # reject every vector until the corpus dead-letters.
+ log.warning(
+ "UltraWiki: model %r now answers with dim=%d instead of %d — "
+ "rebuilding the vector space in the background",
+ model,
+ dim,
+ pinned_dim,
+ )
+ await self.begin_reembed(model, dim=dim)
+ return False
+ raise UltraStoreError(
+ "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 "
+ "through begin_reembed() (rebuilds the corpus in the background "
+ "while search keeps using the current vectors)."
+ )
+
async def store_embedding(
self,
document_id: int,
@@ -1479,27 +1578,21 @@ class UltraStore:
) -> None:
"""Store one vector (little-endian float32 BLOB) for a document.
- The first embedding pins ``embed_model``/``embed_dim`` in
- ``uw_meta`` (semi-permanent, D-3); later writes with a different
- model or dimension are rejected with a clear error — changing the
- embedding space goes through :meth:`reset_vectors`.
+ The first embedding pins ``embed_model``/``embed_dim`` in ``uw_meta``
+ (D-3). While a model switch is rebuilding, vectors of the new model
+ land in the shadow space instead and are deliberately kept OUT of
+ ``uw_vec``: the ANN index mirrors the active space alone, so searches
+ keep answering correctly until :meth:`promote_pending_space` swaps
+ them.
"""
if len(vector) != dim:
raise UltraStoreError(
f"vector has {len(vector)} components but dim={dim} was declared"
)
- pinned_model, pinned_dim = await self._pinned_space()
- if pinned_model is None or pinned_dim is None:
- await self.set_meta(META_EMBED_MODEL, model)
- await self.set_meta(META_EMBED_DIM, str(dim))
- elif pinned_model != model or pinned_dim != dim:
- raise UltraStoreError(
- "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 "
- "requires reset_vectors() (re-embeds the corpus)."
- )
- vec_ok, _ = await self._ensure_vec(dim)
+ active = await self._writes_to_active_space(model, dim)
+ vec_ok = False
+ if active:
+ vec_ok, _ = await self._ensure_vec(dim)
blob = pack_vector(vector)
now = _iso_utc()
async with self._txn() as conn:
@@ -1567,6 +1660,11 @@ class UltraStore:
self._vec_dim = dim
return self._vec_state
self._vec_ext_loaded = True
+ # The index mirrors the ACTIVE space alone. A shadow rebuild's vectors
+ # answer a different geometry and cover only part of the corpus, so
+ # letting them in would corrupt every search until promotion.
+ active_model, _ = await self._pinned_space()
+ space = (active_model or "", int(dim))
async with self._lock:
# Recreate the index when the pinned dimension changed.
existing = await self._fetchone(
@@ -1587,12 +1685,16 @@ class UltraStore:
# backfill vectors the index does not hold yet.
await conn.execute(
"DELETE FROM uw_vec WHERE rowid NOT IN"
- " (SELECT document_id FROM uw_embeddings)"
+ " (SELECT document_id FROM uw_embeddings"
+ " WHERE model = ? AND dim = ?)",
+ space,
)
missing = await self._fetchall(
conn,
"SELECT document_id, vector FROM uw_embeddings"
- " WHERE document_id NOT IN (SELECT rowid FROM uw_vec)",
+ " WHERE model = ? AND dim = ?"
+ " AND document_id NOT IN (SELECT rowid FROM uw_vec)",
+ space,
)
if missing:
# One batch, not one round trip per row: the first search
@@ -1638,11 +1740,15 @@ class UltraStore:
return await self._ensure_vec(None)
async def reset_vectors(self) -> None:
- """The embedding-model-change path: wipe the vector index and every
- stored embedding, clear the ``embed_model``/``embed_dim`` pin, and
- reset ``embedded``/``distilled`` items to ``keyword_indexed`` so the
- pipeline re-embeds (re-distillation rides the distill cache).
- Derived documents keep their text; only vectors are discarded.
+ """Hard reset: wipe the vector index and EVERY stored embedding of
+ every space, clear both pins, and reset ``embedded``/``distilled``
+ items to ``keyword_indexed`` so the pipeline re-embeds
+ (re-distillation rides the distill cache). Derived documents keep
+ their text; only vectors are discarded.
+
+ This blinds semantic search until the corpus is rebuilt, so it is the
+ recovery path, not the model-switch path — a switch uses
+ :meth:`begin_reembed`, which keeps the current vectors answering.
"""
vec_droppable = self._vec_ext_loaded # vec0 DDL needs the extension
async with self._txn() as conn:
@@ -1650,8 +1756,13 @@ class UltraStore:
await conn.execute("DROP TABLE IF EXISTS uw_vec")
await conn.execute("DELETE FROM uw_embeddings")
await conn.execute(
- "DELETE FROM uw_meta WHERE key IN (?, ?)",
- (META_EMBED_MODEL, META_EMBED_DIM),
+ "DELETE FROM uw_meta WHERE key IN (?, ?, ?, ?)",
+ (
+ META_EMBED_MODEL,
+ META_EMBED_DIM,
+ META_PENDING_EMBED_MODEL,
+ META_PENDING_EMBED_DIM,
+ ),
)
await conn.execute(
"UPDATE uw_items SET state = ?, updated_at = ? WHERE state IN (?, ?)",
@@ -1665,6 +1776,202 @@ class UltraStore:
self._vec_state = None
self._vec_dim = None
+ async def begin_reembed(self, model: str, *, dim: int | None = None) -> bool:
+ """Start rebuilding the corpus in *model*'s vector space, in the
+ background, WITHOUT taking semantic search down.
+
+ *dim* is normally unknown until the provider answers and stays ``None``;
+ pass it when the width is already known and distinguishes the target
+ space from the live one (same model name, different geometry).
+
+ The live vectors, the ``uw_vec`` index and every search stay untouched;
+ new vectors accumulate in the shadow space until
+ :meth:`promote_pending_space` finds it complete and swaps it in. An
+ abandoned rebuild costs nothing but the shadow rows, which the next
+ call drops.
+
+ Returns ``True`` when a rebuild actually started. ``False`` means there
+ is nothing to rebuild: either the corpus already sits in that space (a
+ provider change that keeps the model — same geometry, no work) or
+ nothing has been embedded yet, in which case the pipeline's normal
+ backlog already produces the new space.
+ """
+ pinned_model, pinned_dim = await self._pinned_space()
+ same_space = pinned_model == model and (dim is None or pinned_dim == dim)
+ if pinned_model is None or pinned_dim is None or same_space:
+ # Switching back to the live model mid-rebuild lands here too: the
+ # shadow becomes garbage and the live space was never touched.
+ await self.abort_reembed()
+ return False
+ now = _iso_utc()
+ async with self._txn() as conn:
+ # A superseded rebuild leaves half-built rows behind. Everything
+ # outside the ACTIVE space is exactly that.
+ await conn.execute(
+ "DELETE FROM uw_embeddings WHERE model != ? OR dim != ?",
+ (pinned_model, pinned_dim),
+ )
+ await conn.execute(
+ "INSERT OR REPLACE INTO uw_meta (key, value) VALUES (?, ?)",
+ (META_PENDING_EMBED_MODEL, model),
+ )
+ # The width is normally the provider's answer, not ours — see
+ # _writes_to_active_space.
+ if dim is None:
+ await conn.execute(
+ "DELETE FROM uw_meta WHERE key = ?", (META_PENDING_EMBED_DIM,)
+ )
+ else:
+ await conn.execute(
+ "INSERT OR REPLACE INTO uw_meta (key, value) VALUES (?, ?)",
+ (META_PENDING_EMBED_DIM, str(int(dim))),
+ )
+ await conn.execute(
+ "UPDATE uw_items SET state = ?, updated_at = ? WHERE state IN (?, ?)",
+ (
+ ItemState.KEYWORD_INDEXED.value,
+ now,
+ ItemState.EMBEDDED.value,
+ ItemState.DISTILLED.value,
+ ),
+ )
+ return True
+
+ async def abort_reembed(self) -> bool:
+ """Discard a running rebuild and keep the live space. ``True`` when
+ one was actually running. Items already re-embedded stay where the
+ pipeline left them — their live vectors were never removed."""
+ pending_model, _ = await self._pending_space()
+ pinned_model, pinned_dim = await self._pinned_space()
+ if pending_model is None:
+ return False
+ async with self._txn() as conn:
+ if pinned_model is not None and pinned_dim is not None:
+ await conn.execute(
+ "DELETE FROM uw_embeddings WHERE model != ? OR dim != ?",
+ (pinned_model, pinned_dim),
+ )
+ await conn.execute(
+ "DELETE FROM uw_meta WHERE key IN (?, ?)",
+ (META_PENDING_EMBED_MODEL, META_PENDING_EMBED_DIM),
+ )
+ return True
+
+ async def _shadow_gap(
+ self,
+ conn: aiosqlite.Connection,
+ active: tuple[str, int],
+ pending: tuple[str, int],
+ ) -> int:
+ """How many documents the live space covers and the shadow does not.
+
+ Documents of dead-lettered or tombstoned items are excluded: they will
+ never be re-embedded, and counting them would stall the promotion
+ forever behind a handful of permanently failing items.
+ """
+ row = await self._fetchone(
+ conn,
+ "SELECT count(*) AS n FROM uw_embeddings a"
+ " JOIN uw_documents d ON d.id = a.document_id"
+ " JOIN uw_items i ON i.id = d.item_id"
+ " WHERE a.model = ? AND a.dim = ?"
+ " AND i.deleted_at IS NULL AND i.state != ?"
+ " AND NOT EXISTS (SELECT 1 FROM uw_embeddings p"
+ " WHERE p.document_id = a.document_id"
+ " AND p.model = ? AND p.dim = ?)",
+ (*active, ItemState.FAILED.value, *pending),
+ )
+ return 0 if row is None else int(row["n"])
+
+ async def promote_pending_space(self) -> bool:
+ """Swap a completed shadow space in; a no-op otherwise.
+
+ The pipeline calls this after every pass, so the common case (nothing
+ pending) must stay cheap — it costs one ``uw_meta`` read.
+ """
+ pending_model, pending_dim = await self._pending_space()
+ if pending_model is None or pending_dim is None:
+ return False # no rebuild, or not one vector produced yet
+ active_model, active_dim = await self._pinned_space()
+ if active_model is None or active_dim is None:
+ return False
+ conn = await self._ensure_open()
+ gap = await self._shadow_gap(
+ conn, (active_model, active_dim), (pending_model, pending_dim)
+ )
+ if gap:
+ return False
+ vec_droppable = self._vec_ext_loaded
+ async with self._txn() as txn:
+ await txn.execute(
+ "DELETE FROM uw_embeddings WHERE model = ? AND dim = ?",
+ (active_model, active_dim),
+ )
+ await txn.execute(
+ "INSERT OR REPLACE INTO uw_meta (key, value) VALUES (?, ?)",
+ (META_EMBED_MODEL, pending_model),
+ )
+ await txn.execute(
+ "INSERT OR REPLACE INTO uw_meta (key, value) VALUES (?, ?)",
+ (META_EMBED_DIM, str(pending_dim)),
+ )
+ await txn.execute(
+ "DELETE FROM uw_meta WHERE key IN (?, ?)",
+ (META_PENDING_EMBED_MODEL, META_PENDING_EMBED_DIM),
+ )
+ if vec_droppable:
+ # The index is derived, so rebuilding it is a local copy, not
+ # a re-embed: _ensure_vec backfills it from the new space.
+ await txn.execute("DROP TABLE IF EXISTS uw_vec")
+ self._vec_state = None
+ self._vec_dim = None
+ await self._ensure_vec(pending_dim)
+ log.info(
+ "UltraWiki embedding space promoted: %s (dim=%d) replaces %s",
+ pending_model,
+ pending_dim,
+ active_model,
+ )
+ return True
+
+ async def reembed_status(self) -> dict[str, Any]:
+ """Honest progress of a running rebuild, for the settings surface.
+
+ ``{}`` when none is running. ``done``/``total`` count DOCUMENTS (the
+ passages actually embedded), so the number moves smoothly rather than
+ jumping per item.
+ """
+ pending_model, pending_dim = await self._pending_space()
+ if pending_model is None:
+ return {}
+ active_model, active_dim = await self._pinned_space()
+ if active_model is None or active_dim is None:
+ return {"model": pending_model, "done": 0, "total": 0}
+ conn = await self._ensure_open()
+ row = await self._fetchone(
+ conn,
+ "SELECT count(*) AS n FROM uw_embeddings a"
+ " JOIN uw_documents d ON d.id = a.document_id"
+ " JOIN uw_items i ON i.id = d.item_id"
+ " WHERE a.model = ? AND a.dim = ?"
+ " AND i.deleted_at IS NULL AND i.state != ?",
+ (active_model, active_dim, ItemState.FAILED.value),
+ )
+ total = 0 if row is None else int(row["n"])
+ gap = (
+ total
+ if pending_dim is None
+ else await self._shadow_gap(
+ conn, (active_model, active_dim), (pending_model, pending_dim)
+ )
+ )
+ return {
+ "model": pending_model,
+ "done": max(0, total - gap),
+ "total": total,
+ "active_model": active_model,
+ }
+
# -- search legs (SQL only, fusion lives in the read path) --------------
async def keyword_search(
@@ -2192,10 +2499,26 @@ class PostgresStore:
"CREATE INDEX IF NOT EXISTS idx_uw_documents_item"
" ON uw_documents(item_id)",
"CREATE TABLE IF NOT EXISTS uw_embeddings ("
- " document_id BIGINT PRIMARY KEY"
+ " document_id BIGINT NOT NULL"
" REFERENCES uw_documents(id) ON DELETE CASCADE,"
" model TEXT NOT NULL, dim INTEGER NOT NULL,"
- " vector BYTEA NOT NULL, created_at TEXT NOT NULL)",
+ " vector BYTEA NOT NULL, created_at TEXT NOT NULL,"
+ " PRIMARY KEY (document_id, model, dim))",
+ # Databases created before the shadow-space key: widen the primary
+ # key in place so a model switch can build the new space alongside
+ # the live one (SQLite does the same via migration 0002).
+ "DO $$ BEGIN"
+ " IF EXISTS (SELECT 1 FROM pg_constraint"
+ " WHERE conrelid = to_regclass('uw_embeddings')"
+ " AND contype = 'p'"
+ " AND array_length(conkey, 1) = 1) THEN"
+ " ALTER TABLE uw_embeddings DROP CONSTRAINT uw_embeddings_pkey;"
+ " ALTER TABLE uw_embeddings"
+ " ADD PRIMARY KEY (document_id, model, dim);"
+ " END IF;"
+ "END $$",
+ "CREATE INDEX IF NOT EXISTS idx_uw_embeddings_space"
+ " ON uw_embeddings(model, dim)",
"CREATE TABLE IF NOT EXISTS uw_distill_cache ("
" content_hash TEXT NOT NULL, prompt_version INTEGER NOT NULL,"
" model TEXT NOT NULL, result_json TEXT NOT NULL,"
@@ -2936,10 +3259,21 @@ class PostgresStore:
*,
content_hash: str = "",
) -> list[int]:
- """Postgres twin of :meth:`UltraStore.replace_documents`."""
+ """Postgres twin of :meth:`UltraStore.replace_documents` — including
+ the keep-identical-passages rule that protects the live vectors of a
+ running rebuild (see :func:`_documents_unchanged`)."""
kind = DocType(doc_type).value
now = _iso_utc()
async with self._txn() as conn:
+ old_rows = await self._fetchall(
+ conn,
+ "SELECT id, chunk_index, text_norm, content_hash FROM uw_documents"
+ " WHERE item_id = %s AND doc_type = %s",
+ (item_id, kind),
+ )
+ if _documents_unchanged(old_rows, chunks, content_hash):
+ by_index = {int(row["chunk_index"]): int(row["id"]) for row in old_rows}
+ return [by_index[int(getattr(c, "index", 0))] for c in chunks]
await conn.execute(
"DELETE FROM uw_documents WHERE item_id = %s AND doc_type = %s",
(item_id, kind),
@@ -2973,6 +3307,48 @@ class PostgresStore:
dim_raw = await self.get_meta(META_EMBED_DIM)
return model, int(dim_raw) if dim_raw else None
+ async def _pending_space(self) -> tuple[str | None, int | None]:
+ model = await self.get_meta(META_PENDING_EMBED_MODEL)
+ dim_raw = await self.get_meta(META_PENDING_EMBED_DIM)
+ return model, int(dim_raw) if dim_raw else None
+
+ async def _writes_to_active_space(self, model: str, dim: int) -> bool:
+ """Postgres twin of :meth:`UltraStore._writes_to_active_space`."""
+ pinned_model, pinned_dim = await self._pinned_space()
+ if pinned_model is None or pinned_dim is None:
+ await self.set_meta(META_EMBED_MODEL, model)
+ await self.set_meta(META_EMBED_DIM, str(dim))
+ return True
+ if pinned_model == model and pinned_dim == dim:
+ return True
+ pending_model, pending_dim = await self._pending_space()
+ if pending_model is not None and pending_model == model:
+ if pending_dim is None:
+ await self.set_meta(META_PENDING_EMBED_DIM, str(dim))
+ elif pending_dim != dim:
+ raise UltraStoreError(
+ f"embedding dimension mismatch: the rebuild of {model!r} "
+ f"started at dim={pending_dim} but got dim={dim}"
+ )
+ return False
+ if pinned_model == model:
+ log.warning(
+ "UltraWiki: model %r now answers with dim=%d instead of %d — "
+ "rebuilding the vector space in the background",
+ model,
+ dim,
+ pinned_dim,
+ )
+ await self.begin_reembed(model, dim=dim)
+ return False
+ raise UltraStoreError(
+ "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 "
+ "through begin_reembed() (rebuilds the corpus in the background "
+ "while search keeps using the current vectors)."
+ )
+
async def store_embedding(
self,
document_id: int,
@@ -2985,34 +3361,24 @@ class PostgresStore:
raise UltraStoreError(
f"vector has {len(vector)} components but dim={dim} was declared"
)
- pinned_model, pinned_dim = await self._pinned_space()
- if pinned_model is None or pinned_dim is None:
- await self.set_meta(META_EMBED_MODEL, model)
- await self.set_meta(META_EMBED_DIM, str(dim))
- elif pinned_model != model or pinned_dim != dim:
- raise UltraStoreError(
- "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 "
- "requires reset_vectors() (re-embeds the corpus)."
- )
- vec_ok, _ = await self._ensure_vec(dim)
+ active = await self._writes_to_active_space(model, dim)
+ vec_ok = False
+ if active:
+ vec_ok, _ = await self._ensure_vec(dim)
now = _iso_utc()
async with self._txn() as conn:
await conn.execute(
"INSERT INTO uw_embeddings"
" (document_id, model, dim, vector, created_at)"
" VALUES (%s, %s, %s, %s, %s)"
- " ON CONFLICT (document_id) DO UPDATE SET model = %s,"
- " dim = %s, vector = %s, created_at = %s",
+ " ON CONFLICT (document_id, model, dim) DO UPDATE"
+ " SET vector = %s, created_at = %s",
(
document_id,
model,
dim,
pack_vector(vector),
now,
- model,
- dim,
pack_vector(vector),
now,
),
@@ -3063,11 +3429,21 @@ class PostgresStore:
" REFERENCES uw_documents(id) ON DELETE CASCADE,"
f" embedding vector({int(dim)}) NOT NULL)"
)
- # Backfill vectors stored while the index was unavailable.
+ # Backfill vectors stored while the index was unavailable — from the
+ # ACTIVE space only, never a shadow rebuild's partial one.
+ active_model, _ = await self._pinned_space()
+ await conn.execute(
+ "DELETE FROM uw_vec WHERE document_id NOT IN"
+ " (SELECT document_id FROM uw_embeddings"
+ " WHERE model = %s AND dim = %s)",
+ (active_model or "", int(dim)),
+ )
missing = await self._fetchall(
conn,
"SELECT document_id, vector FROM uw_embeddings"
- " WHERE document_id NOT IN (SELECT document_id FROM uw_vec)",
+ " WHERE model = %s AND dim = %s"
+ " AND document_id NOT IN (SELECT document_id FROM uw_vec)",
+ (active_model or "", int(dim)),
)
for row in missing:
literal = self._pgvector_literal(unpack_vector(bytes(row["vector"])))
@@ -3088,9 +3464,54 @@ class PostgresStore:
await conn.execute("DROP TABLE IF EXISTS uw_vec")
await conn.execute("DELETE FROM uw_embeddings")
await conn.execute(
- "DELETE FROM uw_meta WHERE key IN (%s, %s)",
- (META_EMBED_MODEL, META_EMBED_DIM),
+ "DELETE FROM uw_meta WHERE key IN (%s, %s, %s, %s)",
+ (
+ META_EMBED_MODEL,
+ META_EMBED_DIM,
+ META_PENDING_EMBED_MODEL,
+ META_PENDING_EMBED_DIM,
+ ),
+ )
+ await conn.execute(
+ "UPDATE uw_items SET state = %s, updated_at = %s"
+ " WHERE state IN (%s, %s)",
+ (
+ ItemState.KEYWORD_INDEXED.value,
+ _iso_utc(),
+ ItemState.EMBEDDED.value,
+ ItemState.DISTILLED.value,
+ ),
+ )
+ self._vec_state = None
+ self._vec_dim = None
+
+ async def begin_reembed(self, model: str, *, dim: int | None = None) -> bool:
+ """Postgres twin of :meth:`UltraStore.begin_reembed`."""
+ pinned_model, pinned_dim = await self._pinned_space()
+ same_space = pinned_model == model and (dim is None or pinned_dim == dim)
+ if pinned_model is None or pinned_dim is None or same_space:
+ await self.abort_reembed()
+ return False
+ async with self._txn() as conn:
+ await conn.execute(
+ "DELETE FROM uw_embeddings WHERE model != %s OR dim != %s",
+ (pinned_model, pinned_dim),
)
+ await conn.execute(
+ "INSERT INTO uw_meta (key, value) VALUES (%s, %s)"
+ " ON CONFLICT (key) DO UPDATE SET value = %s",
+ (META_PENDING_EMBED_MODEL, model, model),
+ )
+ if dim is None:
+ await conn.execute(
+ "DELETE FROM uw_meta WHERE key = %s", (META_PENDING_EMBED_DIM,)
+ )
+ else:
+ await conn.execute(
+ "INSERT INTO uw_meta (key, value) VALUES (%s, %s)"
+ " ON CONFLICT (key) DO UPDATE SET value = %s",
+ (META_PENDING_EMBED_DIM, str(int(dim)), str(int(dim))),
+ )
await conn.execute(
"UPDATE uw_items SET state = %s, updated_at = %s"
" WHERE state IN (%s, %s)",
@@ -3101,8 +3522,122 @@ class PostgresStore:
ItemState.DISTILLED.value,
),
)
+ return True
+
+ async def abort_reembed(self) -> bool:
+ """Postgres twin of :meth:`UltraStore.abort_reembed`."""
+ pending_model, _ = await self._pending_space()
+ if pending_model is None:
+ return False
+ pinned_model, pinned_dim = await self._pinned_space()
+ async with self._txn() as conn:
+ if pinned_model is not None and pinned_dim is not None:
+ await conn.execute(
+ "DELETE FROM uw_embeddings WHERE model != %s OR dim != %s",
+ (pinned_model, pinned_dim),
+ )
+ await conn.execute(
+ "DELETE FROM uw_meta WHERE key IN (%s, %s)",
+ (META_PENDING_EMBED_MODEL, META_PENDING_EMBED_DIM),
+ )
+ return True
+
+ async def _shadow_gap(
+ self, conn: Any, active: tuple[str, int], pending: tuple[str, int]
+ ) -> int:
+ """Postgres twin of :meth:`UltraStore._shadow_gap`."""
+ row = await self._fetchone(
+ conn,
+ "SELECT count(*) AS n FROM uw_embeddings a"
+ " JOIN uw_documents d ON d.id = a.document_id"
+ " JOIN uw_items i ON i.id = d.item_id"
+ " WHERE a.model = %s AND a.dim = %s"
+ " AND i.deleted_at IS NULL AND i.state != %s"
+ " AND NOT EXISTS (SELECT 1 FROM uw_embeddings p"
+ " WHERE p.document_id = a.document_id"
+ " AND p.model = %s AND p.dim = %s)",
+ (*active, ItemState.FAILED.value, *pending),
+ )
+ return 0 if row is None else int(row["n"])
+
+ async def promote_pending_space(self) -> bool:
+ """Postgres twin of :meth:`UltraStore.promote_pending_space`."""
+ pending_model, pending_dim = await self._pending_space()
+ if pending_model is None or pending_dim is None:
+ return False
+ active_model, active_dim = await self._pinned_space()
+ if active_model is None or active_dim is None:
+ return False
+ conn = await self._ensure_open()
+ gap = await self._shadow_gap(
+ conn, (active_model, active_dim), (pending_model, pending_dim)
+ )
+ if gap:
+ return False
+ async with self._txn() as txn:
+ await txn.execute(
+ "DELETE FROM uw_embeddings WHERE model = %s AND dim = %s",
+ (active_model, active_dim),
+ )
+ await txn.execute(
+ "INSERT INTO uw_meta (key, value) VALUES (%s, %s)"
+ " ON CONFLICT (key) DO UPDATE SET value = %s",
+ (META_EMBED_MODEL, pending_model, pending_model),
+ )
+ await txn.execute(
+ "INSERT INTO uw_meta (key, value) VALUES (%s, %s)"
+ " ON CONFLICT (key) DO UPDATE SET value = %s",
+ (META_EMBED_DIM, str(pending_dim), str(pending_dim)),
+ )
+ await txn.execute(
+ "DELETE FROM uw_meta WHERE key IN (%s, %s)",
+ (META_PENDING_EMBED_MODEL, META_PENDING_EMBED_DIM),
+ )
+ # Derived index: dropping it costs a local rebuild, not a re-embed.
+ await txn.execute("DROP TABLE IF EXISTS uw_vec")
self._vec_state = None
self._vec_dim = None
+ await self._ensure_vec(pending_dim)
+ log.info(
+ "UltraWiki embedding space promoted: %s (dim=%d) replaces %s",
+ pending_model,
+ pending_dim,
+ active_model,
+ )
+ return True
+
+ async def reembed_status(self) -> dict[str, Any]:
+ """Postgres twin of :meth:`UltraStore.reembed_status`."""
+ pending_model, pending_dim = await self._pending_space()
+ if pending_model is None:
+ return {}
+ active_model, active_dim = await self._pinned_space()
+ if active_model is None or active_dim is None:
+ return {"model": pending_model, "done": 0, "total": 0}
+ conn = await self._ensure_open()
+ row = await self._fetchone(
+ conn,
+ "SELECT count(*) AS n FROM uw_embeddings a"
+ " JOIN uw_documents d ON d.id = a.document_id"
+ " JOIN uw_items i ON i.id = d.item_id"
+ " WHERE a.model = %s AND a.dim = %s"
+ " AND i.deleted_at IS NULL AND i.state != %s",
+ (active_model, active_dim, ItemState.FAILED.value),
+ )
+ total = 0 if row is None else int(row["n"])
+ gap = (
+ total
+ if pending_dim is None
+ else await self._shadow_gap(
+ conn, (active_model, active_dim), (pending_model, pending_dim)
+ )
+ )
+ return {
+ "model": pending_model,
+ "done": max(0, total - gap),
+ "total": total,
+ "active_model": active_model,
+ }
# -- search legs ---------------------------------------------------------
@@ -3443,6 +3978,8 @@ __all__ = [
"MAX_ATTEMPTS",
"META_EMBED_DIM",
"META_EMBED_MODEL",
+ "META_PENDING_EMBED_DIM",
+ "META_PENDING_EMBED_MODEL",
"PG_CONNECT_TIMEOUT_S",
"PostgresStore",
"UltraStore",
diff --git a/tests/unit/ultrawiki/test_store.py b/tests/unit/ultrawiki/test_store.py
index 2f71d4414e..8f01f2fbbe 100644
--- a/tests/unit/ultrawiki/test_store.py
+++ b/tests/unit/ultrawiki/test_store.py
@@ -342,13 +342,22 @@ async def test_embedding_pin_and_dim_mismatch_rejection(store):
assert await store.get_meta(META_EMBED_MODEL) == "model-a"
assert await store.get_meta(META_EMBED_DIM) == "4"
- with pytest.raises(UltraStoreError, match="pinned"):
- await store.store_embedding(doc_id, model="model-a", dim=5, vector=[0] * 5)
+ # An unannounced model is refused: nothing may mix two vector spaces by
+ # accident (D-3). The deliberate path is begin_reembed().
with pytest.raises(UltraStoreError, match="pinned"):
await store.store_embedding(doc_id, model="model-b", dim=4, vector=[0] * 4)
with pytest.raises(UltraStoreError, match="components"):
await store.store_embedding(doc_id, model="model-a", dim=4, vector=[0] * 3)
+ # ...but a KNOWN name answering with a new width is a different model
+ # behind a familiar label. Rejecting it would dead-letter the whole corpus
+ # five attempts at a time, so it starts a background rebuild instead and
+ # the live space keeps serving search.
+ await store.store_embedding(doc_id, model="model-a", dim=5, vector=[0] * 5)
+ assert await store.get_meta(META_EMBED_MODEL) == "model-a"
+ assert await store.get_meta(META_EMBED_DIM) == "4"
+ assert (await store.reembed_status())["model"] == "model-a"
+
async def test_reset_vectors_round_trip(store):
await add_source(store)
@@ -375,6 +384,163 @@ async def test_reset_vectors_round_trip(store):
assert await store.get_meta(META_EMBED_DIM) == "8"
+# ---------------------------------------------------------------------------
+# Model switch — the shadow space (search never goes dark)
+# ---------------------------------------------------------------------------
+
+
[email protected](not HAS_SQLITE_VEC, reason="sqlite-vec not installed on this host")
+async def test_model_switch_keeps_search_alive_until_the_new_space_is_complete(store):
+ """The point of the whole shadow-space machinery.
+
+ Rebuilding IS unavoidable — vectors of two models are not comparable — but
+ going blind while it runs is not. The old vectors must keep answering right
+ up to the moment the new space is complete.
+ """
+ await add_source(store)
+ item1, doc1 = await _seed_embedded_item(store, 0)
+ item2, doc2 = await _seed_embedded_item(store, 1)
+ await store.store_embedding(doc1, model="model-a", dim=4, vector=[1, 0, 0, 0])
+ await store.store_embedding(doc2, model="model-a", dim=4, vector=[0, 1, 0, 0])
+
+ assert await store.begin_reembed("model-b") is True
+
+ # Mid-rebuild: the old space still answers, in its own dimension.
+ results, reason = await store.vector_search([1, 0.05, 0, 0], k=2)
+ assert reason == ""
+ assert [hit.item_id for hit in results] == [item1, item2]
+
+ # First document re-embedded — still not enough to swap.
+ await store.store_embedding(doc1, model="model-b", dim=3, vector=[1, 0, 0])
+ assert await store.promote_pending_space() is False
+ assert await store.get_meta(META_EMBED_MODEL) == "model-a"
+ progress = await store.reembed_status()
+ assert (progress["done"], progress["total"]) == (1, 2)
+ results, _ = await store.vector_search([1, 0.05, 0, 0], k=2)
+ assert [hit.item_id for hit in results] == [item1, item2]
+
+ # Last one lands: the swap happens, in the NEW geometry.
+ await store.store_embedding(doc2, model="model-b", dim=3, vector=[0, 1, 0])
+ assert await store.promote_pending_space() is True
+ assert await store.get_meta(META_EMBED_MODEL) == "model-b"
+ assert await store.get_meta(META_EMBED_DIM) == "3"
+ assert await store.reembed_status() == {}
+ results, reason = await store.vector_search([1, 0.05, 0], k=2)
+ assert reason == ""
+ assert [hit.item_id for hit in results] == [item1, item2]
+
+ # The retired space is gone — steady state holds exactly one.
+ results, reason = await store.vector_search([1, 0, 0, 0], k=2)
+ assert results == []
+ assert "pinned" in reason
+
+
+async def test_existing_database_migrates_to_the_shadow_space_key(tmp_path):
+ """Thousands of installs sit on the single-column key. Migration 0002 has
+ to widen it in place, keeping every vector — losing them would silently
+ blind semantic search on update, the exact outcome this work removes."""
+ import sqlite3
+
+ db_path = tmp_path / "ultrawiki.db"
+ legacy = sqlite3.connect(db_path)
+ legacy.executescript(
+ """
+ CREATE TABLE uw_documents (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ item_id INTEGER NOT NULL,
+ doc_type TEXT NOT NULL,
+ text_norm TEXT NOT NULL,
+ distill_json TEXT,
+ distill_version INTEGER NOT NULL DEFAULT 0,
+ content_hash TEXT NOT NULL,
+ created_at TEXT NOT NULL
+ );
+ CREATE TABLE uw_embeddings (
+ document_id INTEGER PRIMARY KEY REFERENCES uw_documents(id)
+ ON DELETE CASCADE,
+ model TEXT NOT NULL,
+ dim INTEGER NOT NULL,
+ vector BLOB NOT NULL,
+ created_at TEXT NOT NULL
+ );
+ INSERT INTO uw_documents
+ (id, item_id, doc_type, text_norm, content_hash, created_at)
+ VALUES (7, 1, 'raw', 'kept text', 'h1', '2026-01-01T00:00:00Z');
+ INSERT INTO uw_embeddings VALUES
+ (7, 'model-a', 4, X'0000803F000000000000000000000000',
+ '2026-01-01T00:00:00Z');
+ PRAGMA user_version = 1;
+ """
+ )
+ legacy.commit()
+ legacy.close()
+
+ migrated = UltraStore(db_path)
+ try:
+ await migrated.set_meta(META_EMBED_MODEL, "model-a")
+ await migrated.set_meta(META_EMBED_DIM, "4")
+ # The vector survived the key change...
+ assert await migrated.reembed_status() == {}
+ # ...and a second space now fits beside it.
+ await migrated.begin_reembed("model-b")
+ await migrated.store_embedding(7, model="model-b", dim=3, vector=[1, 0, 0])
+ status = await migrated.reembed_status()
+ assert (status["model"], status["done"]) == ("model-b", 0)
+ finally:
+ await migrated.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."""
+ 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])
+
+ await store.begin_reembed("model-b")
+ await store.store_embedding(doc, model="model-b", dim=3, vector=[1, 0, 0])
+
+ # Back to the live model: the half-built shadow is dropped, the pin never
+ # moved, and nothing has to be re-embedded.
+ assert await store.begin_reembed("model-a") is False
+ assert await store.get_meta(META_EMBED_MODEL) == "model-a"
+ assert await store.reembed_status() == {}
+ results, reason = await store.vector_search([1, 0, 0, 0], k=2)
+ if reason == "": # only when the host has sqlite-vec
+ assert [hit.item_id for hit in results] == [_item]
+
+
+async def test_reembedding_unchanged_content_keeps_the_live_vectors(store):
+ """``replace_documents`` is what the rebuild runs through, and documents
+ cascade to embeddings — so an identical passage set MUST reuse its rows,
+ or the live vectors die on the way to building their replacement."""
+ await add_source(store)
+ await store.upsert_items("src1", [make_item(0)])
+ claimed = await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=10)
+ item = claimed[0]
+ chunks = [SimpleNamespace(index=0, text="passage one", char_start=0, char_end=11)]
+
+ first = await store.replace_documents(
+ item["id"], DocType.RAW, chunks, content_hash=item["content_hash"]
+ )
+ await store.store_embedding(first[0], model="model-a", dim=4, vector=[1, 0, 0, 0])
+
+ again = await store.replace_documents(
+ item["id"], DocType.RAW, chunks, content_hash=item["content_hash"]
+ )
+ assert again == first # same rows, so the vector below survived
+ await store.begin_reembed("model-b")
+ status = await store.reembed_status()
+ assert status["total"] == 1
+
+ # Changed content still swaps the passage set out.
+ changed = [SimpleNamespace(index=0, text="passage two", char_start=0, char_end=11)]
+ replaced = await store.replace_documents(
+ item["id"], DocType.RAW, changed, content_hash=item["content_hash"]
+ )
+ assert replaced != first
+
+
# ---------------------------------------------------------------------------
# Vector leg — real extension round-trip + honest degradation
# ---------------------------------------------------------------------------
diff --git a/tests/unit/web/test_ultrawiki_routes.py b/tests/unit/web/test_ultrawiki_routes.py
index 02d1f1fed2..ac290629d5 100644
--- a/tests/unit/web/test_ultrawiki_routes.py
+++ b/tests/unit/web/test_ultrawiki_routes.py
@@ -341,7 +341,7 @@ def test_embedding_change_without_confirm_is_409(env) -> None:
_drive_pipeline(env)
response = env.client.put(
- "/api/ultrawiki/settings", json={"embedding_provider": "openai"}
+ "/api/ultrawiki/settings", json={"embedding_model": "fake-embed-2"}
)
assert response.status_code == 409
detail = response.json()["detail"]
@@ -350,21 +350,50 @@ def test_embedding_change_without_confirm_is_409(env) -> None:
confirmed = env.client.put(
"/api/ultrawiki/settings",
- json={"embedding_provider": "openai", "confirm_reembed": True},
+ json={"embedding_model": "fake-embed-2", "confirm_reembed": True},
)
assert confirmed.status_code == 200, confirmed.text
body = confirmed.json()
- assert body["changed"] == ["embedding_provider"]
+ assert body["changed"] == ["embedding_model"]
assert body["reembed_started"] is True
- assert env.cfg.ultrawiki.embedding_provider == "openai"
- assert 'embedding_provider = "openai"' in env.toml.read_text(encoding="utf-8")
+ assert env.cfg.ultrawiki.embedding_model == "fake-embed-2"
+ assert 'embedding_model = "fake-embed-2"' in env.toml.read_text(encoding="utf-8")
+
+ # The items go through the pipeline again, but their CURRENT vectors were
+ # NOT dropped: semantic search keeps answering while the new space is
+ # built in the background, and the status says so.
+ status = env.client.get("/api/ultrawiki/status").json()
+ assert status["counts"]["keyword_indexed"] == 2
+ assert status["slots"]["storage"]["vector"]["ready"] is True
+ reembed = status["reembed"]
+ assert reembed.get("model") == "fake-embed-2"
+ assert reembed.get("total", 0) > 0
+
+ hits = env.client.get("/api/ultrawiki/search", params={"q": "ledger"}).json()
+ assert hits["total"] >= 1
+
+
+def test_provider_change_keeping_the_model_needs_no_reembed(env) -> None:
+ """The vector space is the MODEL's, not the host's.
+
+ Re-embedding a corpus because the same model is now billed through another
+ provider is pure waste — the geometry is identical, so the existing vectors
+ stay valid and no confirmation is owed to the user either.
+ """
+ _activate(env)
+ _source_id, job_id = _approve_and_sync_folder(env)
+ _wait_for_job(env, job_id)
+ _drive_pipeline(env)
+
+ response = env.client.put(
+ "/api/ultrawiki/settings", json={"embedding_provider": "openai"}
+ )
+ assert response.status_code == 200, response.text
+ assert response.json()["reembed_started"] is False
- # The vectors were dropped: items fell back to keyword_indexed and wait
- # for the (deliberately unconfigured) background embed stage.
counts = env.client.get("/api/ultrawiki/status").json()["counts"]
- assert counts["embedded"] == 0
- assert counts["distilled"] == 0
- assert counts["keyword_indexed"] == 2
+ assert counts["keyword_indexed"] == 0
+ assert counts["embedded"] + counts["distilled"] == 2
def test_update_settings_without_changes_is_noop(env) -> None: