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): give an already-distilled corpus its events, for no tokens

Ruben Lütke1e9e242b3014
diff --git a/jarvis/ultrawiki/distill.py b/jarvis/ultrawiki/distill.py
index 031492243f..afd427da36 100644
--- a/jarvis/ultrawiki/distill.py
+++ b/jarvis/ultrawiki/distill.py
@@ -34,11 +34,21 @@ path. Two rules make that array safe to consume:
timestamp is asking for a wrong answer that looks right; the resolver
anchors every relative expression against the item's own timestamp.
-The bump invalidates every cached distillation, so a corpus re-distills
-incrementally in the background at the cheap router tier. Nothing is lost
-meanwhile: items keep their existing summary document until the new one
-lands, and events are also derived from PRE-v2 distillations wherever they
-state an absolute date (``events.derive_events``'s legacy path).
+**What the bump does and does not do.** It changes the cache key, so every
+distillation from here on is a v2 one and no v1 cache row can be served for
+it. It does NOT re-distill an existing corpus: the pipeline's distillation
+stage claims only items that are not distilled yet, and re-running a whole
+corpus through a model is a cost no version bump gets to decide on the
+owner's behalf.
+
+That is affordable because events do not actually need a v2 distillation. An
+already-distilled corpus gets them from the text it already stores, wherever
+that states an absolute date (``events.derive_events``'s legacy path), driven
+by the pipeline's deterministic backfill lane
+(``pipeline.PipelineWorker._events_backfill_pass``) — no model call, no
+network, no re-embedding. A v2 distillation is simply richer when it arrives:
+the model states the kind, the place, the participants and a relative date
+this module could never recover from prose.
"""
from __future__ import annotations
diff --git a/jarvis/ultrawiki/pipeline.py b/jarvis/ultrawiki/pipeline.py
index 75361a11ea..7980e36a19 100644
--- a/jarvis/ultrawiki/pipeline.py
+++ b/jarvis/ultrawiki/pipeline.py
@@ -58,6 +58,8 @@ __all__ = [
"KEYWORD_BATCH",
"EMBED_BATCH",
"DISTILL_BATCH",
+ "EVENTS_BACKFILL_BATCH",
+ "EVENTS_BACKFILL_CURSOR",
"MEDIA_BATCH",
"MAX_EMBED_CHARS",
"MAX_MEDIA_BYTES",
@@ -74,6 +76,17 @@ KEYWORD_BATCH = 200
EMBED_BATCH = 32
DISTILL_BATCH = 4
+#: 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
+#: anyway so a first boot on a large corpus stays a background job.
+EVENTS_BACKFILL_BATCH = 100
+
+#: ``uw_meta`` key holding the id the event backfill has walked up to. Carries
+#: the extraction version, so bumping ``events.EVENT_VERSION`` re-opens the
+#: lane over the whole corpus by itself instead of needing a migration.
+EVENTS_BACKFILL_CURSOR = "events_backfill_cursor"
+
#: How long the embedding-dependent stages sleep after the provider answered
#: with a rate/quota rejection. A depleted quota is GLOBAL: retrying the batch
#: members individually just multiplied one 429 into 33 per pass, thousands of
@@ -300,6 +313,9 @@ class PipelineWorker:
#: identity of a vector space, and therefore of whatever is refusing
#: to fill it.
self._embed_slot_key = ""
+ #: ``False`` once the deterministic event backfill has drained the
+ #: corpus, so the finished lane costs one ``uw_meta`` read per pass.
+ self._events_backfill_open = True
#: The live provider-level embedding block, or ``None`` while vectors
#: are coming back. Survives the individual cooldown naps: what matters
#: to a reader is "this has been refused since yesterday evening", not
@@ -428,6 +444,13 @@ class PipelineWorker:
attempted += await self._keyword_pass()
attempted += await self._embed_pass()
attempted += await self._distill_pass()
+ # The event backfill runs only in the gaps too, and unlike the lanes
+ # above it terminates: once it has walked the corpus it costs one meta
+ # read per pass. Counted as attempted work so pacing sees it — it is
+ # cheap, not free, and a large corpus should not spin through it at
+ # full speed on a laptop.
+ if not attempted:
+ attempted += await self._events_backfill_pass()
# Media enrichment runs only in the gaps. It is the one stage that can
# be skipped forever without anything breaking, so by default it never
# takes a turn away from a stage that cannot. "eager" opts out of that
@@ -1233,6 +1256,71 @@ class PipelineWorker:
exc_info=True,
)
+ # -- event backfill over an already-distilled corpus ----------------------
+
+ async def _events_backfill_pass(self) -> int:
+ """Derive events for items distilled BEFORE this feature existed.
+
+ The distillation stage only ever claims items that are not yet
+ distilled, so a corpus imported earlier would never reach
+ :meth:`_derive_events` — its owner would be told the knowledge base
+ answers episodic questions while it silently answered none of them.
+
+ This lane closes that gap for exactly ZERO model calls: it re-reads the
+ distillation JSON already stored on each item and runs the same pure
+ derivation. It walks the corpus once, by id, remembering how far it got
+ in ``uw_meta``, and then costs one meta read per pass forever. Every
+ capability it needs is probed, so a third-party store or a test fake
+ simply has no backfill (and no error).
+ """
+ if not self._events_backfill_open:
+ return 0
+ ultrawiki = getattr(self._cfg, "ultrawiki", None)
+ if not bool(getattr(ultrawiki, "events_enabled", True)):
+ return 0
+ reader = getattr(self._store, "items_with_distillation", None)
+ get_meta = getattr(self._store, "get_meta", None)
+ set_meta = getattr(self._store, "set_meta", None)
+ if not callable(reader) or not callable(get_meta) or not callable(set_meta):
+ self._events_backfill_open = False
+ return 0
+ from jarvis.ultrawiki.events import EVENT_VERSION # noqa: PLC0415 — lazy (AP-26)
+
+ key = f"{EVENTS_BACKFILL_CURSOR}_v{EVENT_VERSION}"
+ try:
+ raw = await get_meta(key)
+ cursor = int(str(raw or "0"))
+ except (TypeError, ValueError):
+ cursor = 0
+ except Exception: # noqa: BLE001 — a store without the table has no lane
+ log.debug("event backfill: cursor unreadable", exc_info=True)
+ self._events_backfill_open = False
+ return 0
+ if cursor < 0: # the sentinel this lane writes when it is finished
+ self._events_backfill_open = False
+ return 0
+ try:
+ items = await reader(after_id=cursor, limit=EVENTS_BACKFILL_BATCH)
+ except Exception: # noqa: BLE001 — never fails a pass
+ log.debug("event backfill: read failed", exc_info=True)
+ self._events_backfill_open = False
+ return 0
+ if not items:
+ await self._store.set_meta(key, "-1")
+ self._events_backfill_open = False
+ log.info("UltraWiki: episodic event backfill complete")
+ return 0
+ for item in items:
+ try:
+ fields = json.loads(str(item.get("distill_json") or "{}"))
+ except ValueError:
+ fields = {}
+ if isinstance(fields, dict):
+ await self._derive_events(item, fields)
+ cursor = max(cursor, int(item["id"]))
+ await self._store.set_meta(key, str(cursor))
+ return len(items)
+
# -- media enrichment ----------------------------------------------------
async def _media_pass(self) -> int:
diff --git a/tests/unit/ultrawiki/test_pipeline.py b/tests/unit/ultrawiki/test_pipeline.py
index c725f2669a..d45f667f11 100644
--- a/tests/unit/ultrawiki/test_pipeline.py
+++ b/tests/unit/ultrawiki/test_pipeline.py
@@ -927,3 +927,101 @@ async def test_hard_cancel_reraises_cancelled_error(store):
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
+
+
+# ---------------------------------------------------------------------------
+# The deterministic event backfill (P5 review, finding 8)
+# ---------------------------------------------------------------------------
+
+
+async def test_event_backfill_gives_an_already_distilled_corpus_its_events(store):
+ """The distillation stage claims only items that are NOT yet distilled, so
+ a corpus imported before the event tables existed would never reach event
+ derivation at all. The backfill closes that without one model call."""
+ from jarvis.ultrawiki.pipeline import EVENTS_BACKFILL_CURSOR
+ from jarvis.ultrawiki.types import DocType
+
+ await store.upsert_items("src1", [make_item(1)])
+ item = await store.get_item_by_external_id("src1", "ext-0001")
+ item_id = int(item["id"])
+ await store.mark_stage_done(item_id, ItemState.KEYWORD_INDEXED)
+ await store.mark_stage_done(item_id, ItemState.EMBEDDED)
+ await store.mark_stage_done(item_id, ItemState.DISTILLED)
+ await store.add_document(
+ item_id,
+ DocType.SUMMARY,
+ "summary text",
+ distill_json=json.dumps(
+ {"question": "When did it start?", "summary": "It began on 2026-02-02."}
+ ),
+ distill_version=1,
+ )
+ assert await store.list_events() == []
+
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=lambda: FakeEmbeddingBackend(),
+ distill_fn=distill_never, # the whole point: no model is involved
+ distill_ready_fn=DISTILL_READY,
+ )
+ assert await worker._events_backfill_pass() == 1
+ events = await store.list_events()
+ assert len(events) == 1
+ assert events[0]["occurred_at"].startswith("2026-02-02")
+ # ... and the mentioned entities did NOT become people.
+ assert await store.list_people(kind=None, limit=50) == []
+
+ # The lane terminates: a second pass drains, a third costs one meta read.
+ assert await worker._events_backfill_pass() == 0
+ assert worker._events_backfill_open is False
+ from jarvis.ultrawiki.events import EVENT_VERSION
+
+ assert await store.get_meta(f"{EVENTS_BACKFILL_CURSOR}_v{EVENT_VERSION}") == "-1"
+
+
+async def test_event_backfill_resumes_from_its_cursor(store):
+ """It walks the corpus once, by id, and survives a restart mid-corpus."""
+ from jarvis.ultrawiki.events import EVENT_VERSION
+ from jarvis.ultrawiki.pipeline import EVENTS_BACKFILL_CURSOR
+ from jarvis.ultrawiki.types import DocType
+
+ await store.upsert_items("src1", [make_item(1), make_item(2)])
+ ids = []
+ for index in (1, 2):
+ row = await store.get_item_by_external_id("src1", f"ext-{index:04d}")
+ item_id = int(row["id"])
+ ids.append(item_id)
+ await store.add_document(
+ item_id, DocType.SUMMARY, "t", distill_json='{"summary": "on 2026-02-02"}'
+ )
+ key = f"{EVENTS_BACKFILL_CURSOR}_v{EVENT_VERSION}"
+ await store.set_meta(key, str(ids[0]))
+
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=lambda: FakeEmbeddingBackend(),
+ distill_fn=distill_never,
+ distill_ready_fn=DISTILL_READY,
+ )
+ assert await worker._events_backfill_pass() == 1
+ assert {event["item_id"] for event in await store.list_events()} == {ids[1]}
+ assert await store.get_meta(key) == str(ids[1])
+
+
+async def test_event_backfill_is_silent_on_a_store_that_cannot_do_it(store):
+ """A third-party store or a test fake simply has no backfill — and no error."""
+
+ class Bare:
+ pass
+
+ worker = PipelineWorker(
+ Bare(),
+ make_cfg(),
+ embedding_backend_factory=lambda: None,
+ distill_fn=distill_never,
+ distill_ready_fn=DISTILL_READY,
+ )
+ assert await worker._events_backfill_pass() == 0
+ assert worker._events_backfill_open is False