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: scrub legacy UltraWiki tombstones

Ruben Lütke08a48e6ea741
diff --git a/jarvis/ultrawiki/pipeline.py b/jarvis/ultrawiki/pipeline.py
index 8ec96f22a3..6ad127ef06 100644
--- a/jarvis/ultrawiki/pipeline.py
+++ b/jarvis/ultrawiki/pipeline.py
@@ -76,6 +76,11 @@ KEYWORD_BATCH = 200
EMBED_BATCH = 32
DISTILL_BATCH = 4
+#: Legacy stores may contain tombstones created before source payloads and
+#: derivatives were scrubbed. Repair enough per pass to converge promptly,
+#: while keeping every transaction bounded and paced with normal ingest work.
+LEGACY_TOMBSTONE_REPAIR_BATCH = 5000
+
#: Items per pass of the deterministic event backfill. Bigger than the model
#: lanes because it costs no model call, no network and no vector: it reads a
#: distillation that is already on the row and does arithmetic on it. Bounded
@@ -487,6 +492,7 @@ class PipelineWorker:
if not attempted or self._media_mode() == "eager":
attempted += await self._media_pass()
await self._promote_pass()
+ attempted += await self._legacy_tombstone_repair_pass()
# Sample AFTER every pass, including passes that achieved nothing: a
# lane that is refused or paused has to keep feeding its meter, or a
# standstill would simply stop updating and read as the last healthy
@@ -496,6 +502,29 @@ class PipelineWorker:
meter.sample(now, self.processed.get(name, 0))
return attempted
+ async def _legacy_tombstone_repair_pass(self) -> int:
+ """Drain payloads/derivatives left by pre-invariant tombstones."""
+ repair = getattr(self._store, "repair_legacy_tombstones", None)
+ if repair is None:
+ return 0
+ try:
+ repaired = int(
+ await repair(limit=LEGACY_TOMBSTONE_REPAIR_BATCH) or 0
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001 — maintenance never kills ingestion
+ log.warning(
+ "UltraWiki legacy tombstone repair failed; retrying next pass",
+ exc_info=True,
+ )
+ return 0
+ if repaired:
+ log.info(
+ "UltraWiki scrubbed %d legacy tombstone payload(s)", repaired
+ )
+ return repaired
+
async def _reembed_is_running(self) -> bool:
"""Is a model switch rebuilding the vector space? Never raises.
diff --git a/jarvis/ultrawiki/store.py b/jarvis/ultrawiki/store.py
index 8c03363780..89d81ac341 100644
--- a/jarvis/ultrawiki/store.py
+++ b/jarvis/ultrawiki/store.py
@@ -572,6 +572,11 @@ class UltraStore(IdentityMixin, EventMixin):
self._readers_unavailable = False
self._reader_vec_loaded: set[int] = set()
self._pool_lock = asyncio.Lock()
+ # Older builds could set deleted_at without removing searchable
+ # derivatives or the original payload. The background pipeline drains
+ # those legacy rows in bounded batches; current writes keep the
+ # invariant after one clean pass has been observed.
+ self._legacy_tombstone_repair_done = False
# -- lifecycle ---------------------------------------------------------
@@ -1039,6 +1044,7 @@ class UltraStore(IdentityMixin, EventMixin):
if item.deleted:
if row is not None and row["deleted_at"] is None:
await self._purge_derived(conn, [row["id"]])
+ await self._clear_deleted_payload(conn, [row["id"]])
await conn.execute(
"UPDATE uw_items SET deleted_at = ?, updated_at = ?"
" WHERE id = ?",
@@ -1146,6 +1152,66 @@ class UltraStore(IdentityMixin, EventMixin):
chunk,
)
+ async def _clear_deleted_payload(
+ self, conn: aiosqlite.Connection, item_ids: Sequence[int]
+ ) -> None:
+ """Keep only a tombstone's stable identity, never its source content."""
+ for chunk in _chunks(list(item_ids)):
+ sql = (
+ "UPDATE uw_items SET thread_key = '', author_raw = '', title = ''," # noqa: S608
+ " body_raw = '', permalink = '', timestamp_utc = '',"
+ " areas_json = '[]', metadata_json = '{}', attempt_count = 0,"
+ " next_retry_at = NULL, last_error = NULL, reembed_pending = 0"
+ f" WHERE id IN ({_placeholders(len(chunk))})"
+ )
+ await conn.execute(sql, chunk)
+
+ async def repair_legacy_tombstones(self, *, limit: int = 5000) -> int:
+ """Scrub legacy tombstones and purge derivatives in bounded batches."""
+ if self._legacy_tombstone_repair_done:
+ return 0
+ batch_limit = min(10_000, max(1, int(limit)))
+ async with self._txn() as conn:
+ rows = await self._fetchall(
+ conn,
+ "SELECT id FROM uw_items WHERE deleted_at IS NOT NULL AND ("
+ " thread_key != '' OR author_raw != '' OR title != '' OR"
+ " body_raw != '' OR permalink != '' OR timestamp_utc != '' OR"
+ " areas_json != '[]' OR metadata_json != '{}' OR"
+ " attempt_count != 0 OR next_retry_at IS NOT NULL OR"
+ " last_error IS NOT NULL OR reembed_pending != 0) LIMIT ?",
+ (batch_limit,),
+ )
+ item_ids = [int(row["id"]) for row in rows]
+ remaining = batch_limit - len(item_ids)
+ if remaining:
+ # A partially repaired row may already have a blank payload
+ # while an old derivative remains. These code-owned tables are
+ # the three independent derivative roots on SQLite.
+ for table in ("uw_documents", "uw_events", "uw_fts"):
+ extra = await self._fetchall(
+ conn,
+ f"SELECT DISTINCT d.item_id AS id FROM {table} d" # noqa: S608
+ " JOIN uw_items i ON i.id = d.item_id"
+ " WHERE i.deleted_at IS NOT NULL LIMIT ?",
+ (remaining,),
+ )
+ known = set(item_ids)
+ item_ids.extend(
+ int(row["id"])
+ for row in extra
+ if int(row["id"]) not in known
+ )
+ remaining = batch_limit - len(item_ids)
+ if not remaining:
+ break
+ if not item_ids:
+ self._legacy_tombstone_repair_done = True
+ return 0
+ await self._purge_derived(conn, item_ids)
+ await self._clear_deleted_payload(conn, item_ids)
+ return len(item_ids)
+
@staticmethod
def _item_row_to_dict(row: aiosqlite.Row) -> dict[str, Any]:
return {
@@ -1563,6 +1629,7 @@ class UltraStore(IdentityMixin, EventMixin):
]
if doomed:
await self._purge_derived(conn, doomed)
+ await self._clear_deleted_payload(conn, doomed)
for chunk in _chunks(doomed):
await conn.execute(
f"UPDATE uw_items SET deleted_at = ?, updated_at = ?" # noqa: S608 — placeholders only
@@ -2711,6 +2778,7 @@ class PostgresStore(IdentityMixin, EventMixin):
self._lock = asyncio.Lock()
self._vec_state: tuple[bool, str] | None = None
self._vec_dim: int | None = None
+ self._legacy_tombstone_repair_done = False
async def _id_insert(self, conn: Any, sql: str, params: Sequence[Any]) -> int:
"""Identity-layer INSERT hook: Postgres reports the id via RETURNING."""
@@ -3272,6 +3340,7 @@ class PostgresStore(IdentityMixin, EventMixin):
if item.deleted:
if row is not None and row["deleted_at"] is None:
await self._purge_derived(conn, [row["id"]])
+ await self._clear_deleted_payload(conn, [row["id"]])
await conn.execute(
"UPDATE uw_items SET deleted_at = %s, updated_at = %s"
" WHERE id = %s",
@@ -3356,6 +3425,64 @@ class PostgresStore(IdentityMixin, EventMixin):
)
await conn.execute("DELETE FROM uw_events WHERE item_id = ANY(%s)", (ids,))
+ async def _clear_deleted_payload(
+ self, conn: Any, item_ids: Sequence[int]
+ ) -> None:
+ ids = list(item_ids)
+ if not ids:
+ return
+ await conn.execute(
+ "UPDATE uw_items SET thread_key = '', author_raw = '', title = '',"
+ " body_raw = '', permalink = '', timestamp_utc = '',"
+ " areas_json = '[]', metadata_json = '{}', attempt_count = 0,"
+ " next_retry_at = NULL, last_error = NULL, reembed_pending = 0"
+ " WHERE id = ANY(%s)",
+ (ids,),
+ )
+
+ async def repair_legacy_tombstones(self, *, limit: int = 5000) -> int:
+ """Postgres twin of the bounded legacy-tombstone repair."""
+ if self._legacy_tombstone_repair_done:
+ return 0
+ batch_limit = min(10_000, max(1, int(limit)))
+ async with self._txn() as conn:
+ rows = await self._fetchall(
+ conn,
+ "SELECT id FROM uw_items WHERE deleted_at IS NOT NULL AND ("
+ " thread_key != '' OR author_raw != '' OR title != '' OR"
+ " body_raw != '' OR permalink != '' OR timestamp_utc != '' OR"
+ " areas_json != '[]' OR metadata_json != '{}' OR"
+ " attempt_count != 0 OR next_retry_at IS NOT NULL OR"
+ " last_error IS NOT NULL OR reembed_pending != 0) LIMIT %s",
+ (batch_limit,),
+ )
+ item_ids = [int(row["id"]) for row in rows]
+ remaining = batch_limit - len(item_ids)
+ if remaining:
+ for table in ("uw_documents", "uw_events"):
+ extra = await self._fetchall(
+ conn,
+ f"SELECT DISTINCT d.item_id AS id FROM {table} d" # noqa: S608
+ " JOIN uw_items i ON i.id = d.item_id"
+ " WHERE i.deleted_at IS NOT NULL LIMIT %s",
+ (remaining,),
+ )
+ known = set(item_ids)
+ item_ids.extend(
+ int(row["id"])
+ for row in extra
+ if int(row["id"]) not in known
+ )
+ remaining = batch_limit - len(item_ids)
+ if not remaining:
+ break
+ if not item_ids:
+ self._legacy_tombstone_repair_done = True
+ return 0
+ await self._purge_derived(conn, item_ids)
+ await self._clear_deleted_payload(conn, item_ids)
+ return len(item_ids)
+
@staticmethod
def _item_row_to_dict(row: dict[str, Any]) -> dict[str, Any]:
return {
@@ -3684,6 +3811,7 @@ class PostgresStore(IdentityMixin, EventMixin):
]
if doomed:
await self._purge_derived(conn, doomed)
+ await self._clear_deleted_payload(conn, doomed)
await conn.execute(
"UPDATE uw_items SET deleted_at = %s, updated_at = %s"
" WHERE id = ANY(%s)",
diff --git a/tests/unit/ultrawiki/test_pipeline.py b/tests/unit/ultrawiki/test_pipeline.py
index 7f89a6cbe8..2596e50fac 100644
--- a/tests/unit/ultrawiki/test_pipeline.py
+++ b/tests/unit/ultrawiki/test_pipeline.py
@@ -174,6 +174,28 @@ async def test_full_ladder_captured_to_distilled(store, tmp_path):
assert any("What about Item 1?" in texts[0] for texts in backend.embed_calls if texts)
+async def test_pipeline_drains_legacy_tombstones_during_normal_passes(
+ store, monkeypatch
+):
+ calls: list[int] = []
+
+ async def repair(*, limit: int) -> int:
+ calls.append(limit)
+ return 2
+
+ monkeypatch.setattr(store, "repair_legacy_tombstones", repair)
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=lambda: None,
+ distill_fn=distill_never,
+ distill_ready_fn=DISTILL_READY,
+ )
+
+ assert await worker.run_once() == 2
+ assert calls == [5000]
+
+
# ---------------------------------------------------------------------------
# Unconfigured embedding slot — honest backlog
# ---------------------------------------------------------------------------
diff --git a/tests/unit/ultrawiki/test_store.py b/tests/unit/ultrawiki/test_store.py
index 388fd219e4..13802bdada 100644
--- a/tests/unit/ultrawiki/test_store.py
+++ b/tests/unit/ultrawiki/test_store.py
@@ -203,6 +203,10 @@ async def test_tombstones_and_reconcile_deletes(store):
assert (await store.counts()).total == 3
tombstoned = await store.get_item_by_external_id("src1", "ext-0000")
assert tombstoned["deleted_at"] is not None
+ assert tombstoned["title"] == ""
+ assert tombstoned["body_raw"] == ""
+ assert tombstoned["permalink"] == ""
+ assert tombstoned["metadata"] == {}
assert await store.keyword_search("number0") == []
# A FULL backfill that no longer yields ext-0001 tombstones it.
@@ -210,6 +214,9 @@ async def test_tombstones_and_reconcile_deletes(store):
removed = await store.reconcile_deletes("src1", survivors)
assert removed == 1
assert (await store.counts()).total == 2
+ reconciled = await store.get_item_by_external_id("src1", "ext-0001")
+ assert reconciled["deleted_at"] is not None
+ assert reconciled["body_raw"] == ""
assert await store.keyword_search("number1") == []
assert len(await store.keyword_search("number2")) == 1
@@ -217,6 +224,43 @@ async def test_tombstones_and_reconcile_deletes(store):
revived = await store.upsert_items("src1", [make_item(0)])
assert revived.changed == 1
assert (await store.counts()).total == 3
+ revived_row = await store.get_item_by_external_id("src1", "ext-0000")
+ assert revived_row["body_raw"] == make_item(0).body
+
+
+async def test_legacy_tombstone_repair_scrubs_payload_and_derivatives(store):
+ await add_source(store)
+ await store.upsert_items("src1", [make_item(0)])
+ [claimed] = await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=1)
+ await index_keyword(store, claimed)
+ await store.add_document(
+ claimed["id"], DocType.RAW, "legacy derived document"
+ )
+
+ # Reproduce a database written by the old path: deleted_at was set while
+ # the raw payload, FTS row and document were left behind.
+ conn = await store._ensure_open()
+ await conn.execute(
+ "UPDATE uw_items SET deleted_at = ? WHERE id = ?",
+ ("2026-07-28T13:40:00Z", claimed["id"]),
+ )
+
+ assert await store.repair_legacy_tombstones(limit=1) == 1
+ repaired = await store.get_item_by_external_id("src1", "ext-0000")
+ assert repaired["deleted_at"] == "2026-07-28T13:40:00Z"
+ assert repaired["title"] == ""
+ assert repaired["body_raw"] == ""
+ assert repaired["permalink"] == ""
+ assert repaired["metadata"] == {}
+ assert await store.keyword_search("number0") == []
+ row = await store._fetchone(
+ conn,
+ "SELECT COUNT(*) AS n FROM uw_documents WHERE item_id = ?",
+ (claimed["id"],),
+ )
+ assert row["n"] == 0
+ assert await store.repair_legacy_tombstones(limit=1) == 0
+ assert await store.repair_legacy_tombstones(limit=1) == 0
# ---------------------------------------------------------------------------