Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
@ fix(ultrawiki): bound one item's identity work and skip the empty write
Ruben Lütkebf1c2956d2c9
diff --git a/jarvis/ultrawiki/event_store.py b/jarvis/ultrawiki/event_store.pyindex 3187946d46..69a158d941 100644--- a/jarvis/ultrawiki/event_store.py+++ b/jarvis/ultrawiki/event_store.py@@ -24,6 +24,12 @@ The contract this module keeps:keeps its spelling and stays searchable rather than being dropped. Linkingis cheap and always allowed; CREATING a person is gated on the event's ownconfidence, because a new entity outlives the guess that produced it.+- **One item spends a bounded identity budget.** The per-event caps multiply+ out to sixty candidate scans and hundreds of queued proposals per document,+ which would defeat the identity layer's "the queue stays short by design".+ ``MAX_IDENTITY_NAMES_PER_ITEM`` / ``MAX_ENTITIES_CREATED_PER_ITEM`` /+ ``MAX_IDENTITY_PROPOSALS_PER_ITEM`` bound the whole item; the excess links+ or keeps its spelling, deterministically, and nothing raises.- **The keyword card is stored, not recomputed.** ``search_text`` lives on therow, so both dialects index the identical text and a search cannot dependon which engine answered.@@ -137,8 +143,16 @@ class EventMixin::data:`~jarvis.ultrawiki.events.ENTITY_CREATE_CONFIDENCE` links butnever creates, so a low-confidence derivation cannot flood the Peopleview with whatever it happened to name.++ Storing NOTHING for an item that already has nothing writes nothing at+ all. That is the overwhelmingly common case — most items yield no+ events — and without the check the empty case would be the most+ expensive thing on the pass: one write transaction and one DELETE round+ trip per item, forever, to delete zero rows."""item_id = int(item_id)+ if not events and not await self._ev_has_events(item_id):+ return []resolved = await self._ev_resolve_names(events, create_entities=create_entities)now = _utc_now_iso()new_ids: list[int] = []@@ -166,7 +180,9 @@ class EventMixin:A name the identity layer refuses to decide (several live holders) mapsto ``None`` and is stored by its spelling — an honest "I know the name,not who it is" beats guessing, and guessing is the wrong-merge failure- the whole identity layer exists to prevent.+ the whole identity layer exists to prevent. A name this method never+ got to at all lands in the same place, which is why exceeding a budget+ below degrades instead of failing.Creating an entity is gated TWICE, because it is the only irreversiblehalf of this: the caller has to allow it at all, and the name has to@@ -175,9 +191,14 @@ class EventMixin:that the name still LINKS to whoever the user already curated and isotherwise stored as plain text — searchable, and nobody new in thePeople view.++ Everything here is bounded PER ITEM, not per event+ (:data:`~jarvis.ultrawiki.events.MAX_IDENTITY_NAMES_PER_ITEM` and+ friends): one document must not be able to spend sixty fuzzy candidate+ scans or fill the confirmation queue by itself."""from jarvis.ultrawiki.events import ( # noqa: PLC0415 — lazy (AP-26)- ENTITY_CREATE_CONFIDENCE,+ MAX_IDENTITY_NAMES_PER_ITEM,)from jarvis.ultrawiki.identity import EntityKind # noqa: PLC0415 — lazy (AP-26)@@ -196,26 +217,116 @@ class EventMixin:wanted.append((event.place, EntityKind.PLACE))best[slot] = max(best.get(slot, 0.0), confidence)+ if len(wanted) > MAX_IDENTITY_NAMES_PER_ITEM:+ log.info(+ "UltraWiki events: item names %d distinct entities, resolving the"+ " first %d — the rest keep their spelling and stay searchable",+ len(wanted),+ MAX_IDENTITY_NAMES_PER_ITEM,+ )+ wanted = wanted[:MAX_IDENTITY_NAMES_PER_ITEM]+ if not wanted:+ return {}++ # One transaction for the whole document instead of one per name. The+ # batch is all-or-nothing by construction, so a failure inside it+ # replays through the independent per-name path rather than costing the+ # item every participant it had already resolved.+ batch = getattr(self, "identity_batch", None)+ if callable(batch):+ try:+ async with batch() as resolve:+ return await self._ev_resolve_with(+ resolve, wanted, best, create_entities=create_entities+ )+ except Exception: # noqa: BLE001 — identity never fails an event+ log.debug(+ "batched event identity resolution failed — replaying the"+ " %d names one transaction at a time",+ len(wanted),+ exc_info=True,+ )+ return await self._ev_resolve_with(+ self.resolve_identity, # type: ignore[attr-defined]+ wanted,+ best,+ create_entities=create_entities,+ isolate=True,+ )++ async def _ev_resolve_with(+ self,+ resolve: Any,+ wanted: Sequence[tuple[str, Any]],+ best: dict[tuple[str, str], float],+ *,+ create_entities: bool,+ isolate: bool = False,+ ) -> dict[tuple[str, str], int | None]:+ """Run *wanted* through *resolve*, spending the per-item budgets.++ ``isolate`` contains a failing name to itself; the batched caller must+ leave it off, because a raise there has already rolled its transaction+ back and nothing after it can be trusted.+ """+ from jarvis.ultrawiki.events import ( # noqa: PLC0415 — lazy (AP-26)+ ENTITY_CREATE_CONFIDENCE,+ MAX_ENTITIES_CREATED_PER_ITEM,+ MAX_IDENTITY_PROPOSALS_PER_ITEM,+ )+ from jarvis.ultrawiki.identity import ( # noqa: PLC0415 — lazy (AP-26)+ MAX_PROPOSALS,+ EntityKind,+ )+out: dict[tuple[str, str], int | None] = {}+ created = 0+ queued = 0for name, kind in wanted:slot = ("person" if kind is EntityKind.PERSON else "place", name.casefold())- may_create = create_entities and (- best.get(slot, 0.0) >= ENTITY_CREATE_CONFIDENCE+ # Both budgets gate CREATION only. A name that arrives after they+ # are spent still links to an entity the user already curated — the+ # cap withholds new rows, it does not withhold knowledge.+ #+ # The queue budget RESERVES a full proposal batch rather than+ # merely checking the running total, so the documented ceiling is+ # literally true: one item can never leave more than+ # MAX_IDENTITY_PROPOSALS_PER_ITEM pending pairs behind.+ may_create = (+ create_entities+ and best.get(slot, 0.0) >= ENTITY_CREATE_CONFIDENCE+ and created < MAX_ENTITIES_CREATED_PER_ITEM+ and queued + MAX_PROPOSALS <= MAX_IDENTITY_PROPOSALS_PER_ITEM)try:- resolution = await self.resolve_identity( # type: ignore[attr-defined]+ resolution = await resolve(name=name,kind=kind,source_ref="uw_events",create=may_create,)- except Exception: # noqa: BLE001 — a refused link never fails an event+ except Exception:+ if not isolate:+ raiselog.debug("event identity resolution failed for %r", name, exc_info=True)out[slot] = Nonecontinueout[slot] = _as_int(getattr(resolution, "entity_id", None))+ if getattr(resolution, "created", False):+ created += 1+ queued += len(getattr(resolution, "queued", ()) or ())return out+ async def _ev_has_events(self, item_id: int) -> bool:+ """Cheap "is there anything to clear" probe, outside any transaction."""+ conn = await self._ensure_open() # type: ignore[attr-defined]+ row = await self._ev_row(+ conn,+ "SELECT 1 AS present FROM uw_events WHERE item_id = ? LIMIT 1",+ (int(item_id),),+ )+ return row is not None+async def _ev_insert(self,conn: Any,diff --git a/jarvis/ultrawiki/events.py b/jarvis/ultrawiki/events.pyindex d911ff1471..a7b469240e 100644--- a/jarvis/ultrawiki/events.py+++ b/jarvis/ultrawiki/events.py@@ -50,7 +50,10 @@ __all__ = ["ENTITY_CREATE_CONFIDENCE","EVENT_KIND_VALUES","EVENT_VERSION",+ "MAX_ENTITIES_CREATED_PER_ITEM","MAX_EVENTS_PER_ITEM",+ "MAX_IDENTITY_NAMES_PER_ITEM",+ "MAX_IDENTITY_PROPOSALS_PER_ITEM","MAX_PARTICIPANTS","RELATIVE_VOCABULARY","TIME_ANCHOR_VALUES",@@ -149,6 +152,41 @@ MAX_LEGACY_EVENTS = 2DEFAULT_CONFIDENCE = 0.5LEGACY_CONFIDENCE = 0.35+#: Per-ITEM identity budget. The caps above bound one EVENT; multiplied out+#: they leave one document free to spend 5 x 12 participants + 5 places = 65+#: identity resolutions, each of which scans up to+#: :data:`~jarvis.ultrawiki.identity.FUZZY_CANDIDATE_LIMIT` names and may+#: queue :data:`~jarvis.ultrawiki.identity.MAX_PROPOSALS` proposals — roughly+#: 300 pending rows from a SINGLE import, against the identity layer's design+#: property that the confirmation queue stays short enough for a human to+#: actually work through.+#:+#: The three budgets below bound the whole item instead, and each one is set+#: so that a genuinely busy real document still lands intact:+#:+#: - Names: one full :data:`MAX_PARTICIPANTS` roster (a dozen people is+#: already an unusually crowded note) plus room for the places and a few+#: names the other events add. Real documents repeat their people, so this+#: is only ever reached by an extraction that invented names.+#: - Creations: the irreversible half — a new row in the People view outlives+#: the guess that produced it — so it is bounded well below the name budget.+#: - Proposals: what one import may add to the confirmation queue. Ten pairs+#: is already more than anyone triages in one sitting. Enforced by RESERVING+#: a whole :data:`~jarvis.ultrawiki.identity.MAX_PROPOSALS` batch before each+#: creating resolution, so the number is a hard ceiling rather than an+#: average that a final batch can overshoot.+#:+#: Exceeding a budget is never an error: the excess names still LINK to+#: whoever the user already curated and are otherwise stored by their spelling+#: (searchable, nobody new invented). The drop is deterministic — document+#: order, first come first served — so the name budget selects the same prefix+#: on every pass over unchanged content. The creation budget converges instead+#: of repeating: a person an earlier pass created is simply linked by the next+#: one, which is what re-derivation is supposed to do.+MAX_IDENTITY_NAMES_PER_ITEM = 16+MAX_ENTITIES_CREATED_PER_ITEM = 8+MAX_IDENTITY_PROPOSALS_PER_ITEM = 10+#: An event below this confidence may LINK its participants and place to#: entities that already exist, but never CREATES one. Creating is the#: expensive direction: a new row shows up in the People view, seeds the mergediff --git a/jarvis/ultrawiki/identity_store.py b/jarvis/ultrawiki/identity_store.pyindex 9a7752960a..d10ee2f99d 100644--- a/jarvis/ultrawiki/identity_store.py+++ b/jarvis/ultrawiki/identity_store.py@@ -38,9 +38,11 @@ from __future__ import annotationsimport jsonimport logging-from collections.abc import Iterable, Sequence+from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Sequence+from contextlib import asynccontextmanagerfrom dataclasses import dataclass, fieldfrom datetime import UTC, datetime+from functools import partialfrom typing import Anyfrom jarvis.ultrawiki.identity import (@@ -1079,6 +1081,33 @@ class IdentityMixin:(provenance); stamping the ENTITY's own provenance is the separate,idempotent :meth:`set_entity_source_ref`."""+ async with self._txn() as conn: # type: ignore[attr-defined]+ return await self._id_resolve_one(+ conn,+ name=name,+ emails=emails,+ phones=phones,+ handles=handles,+ contact_slug=contact_slug,+ kind=kind,+ source_ref=source_ref,+ create=create,+ )++ async def _id_resolve_one(+ self,+ conn: Any,+ *,+ name: str = "",+ emails: Sequence[str] = (),+ phones: Sequence[str] = (),+ handles: Sequence[str] = (),+ contact_slug: str = "",+ kind: EntityKind | str = EntityKind.PERSON,+ source_ref: str = "",+ create: bool = True,+ ) -> Resolution:+ """:meth:`resolve_identity` for a transaction the caller already owns."""observed = self._id_observe(name=name,emails=emails,@@ -1086,19 +1115,41 @@ class IdentityMixin:handles=handles,contact_slug=contact_slug,)- name_value = normalize_name(name) if name else None- now = _utc_now_iso()+ return await self._id_resolve(+ conn,+ observed,+ name_value=normalize_name(name) if name else None,+ display_name=str(name or "").strip(),+ kind=kind,+ source_ref=source_ref,+ create=create,+ now=_utc_now_iso(),+ )++ @asynccontextmanager+ async def identity_batch(+ self,+ ) -> AsyncIterator[Callable[..., Awaitable[Resolution]]]:+ """Resolve SEVERAL observations inside ONE transaction.++ :meth:`resolve_identity` opens its own transaction per call, which is+ right for a single observation and wasteful for a document that names a+ dozen people: N names cost N ``BEGIN``/``COMMIT`` round trips and N+ turns of the store lock. Yields a callable with+ :meth:`resolve_identity`'s keyword signature, bound to one open+ transaction.++ The trade belongs to the caller and is deliberately not hidden: one+ transaction is ONE failure domain. A statement that raises inside the+ block rolls the WHOLE batch back — including the entities earlier calls+ created — so a caller that must not lose the rest catches the exception+ and replays the observations through :meth:`resolve_identity`, which is+ independent per call. Not a fallback for convenience: on Postgres a+ failed statement poisons the surrounding transaction, so continuing+ inside the block is not an option in the first place.+ """async with self._txn() as conn: # type: ignore[attr-defined]- return await self._id_resolve(- conn,- observed,- name_value=name_value,- display_name=str(name or "").strip(),- kind=kind,- source_ref=source_ref,- create=create,- now=now,- )+ yield partial(self._id_resolve_one, conn)@staticmethoddef _id_observe(diff --git a/jarvis/ultrawiki/pipeline.py b/jarvis/ultrawiki/pipeline.pyindex 7980e36a19..084eec50e8 100644--- a/jarvis/ultrawiki/pipeline.py+++ b/jarvis/ultrawiki/pipeline.py@@ -1242,7 +1242,9 @@ class PipelineWorker:if not events:# Still a replace: an item that USED to yield events and no# longer does must lose them, or a corrected source leaves the- # old answer standing.+ # old answer standing. The store answers the common case (an+ # item that never had any) with one indexed lookup and no write+ # transaction, so the empty majority costs almost nothing.await replace(int(item["id"]), [])returnawait replace(int(item["id"]), events)diff --git a/tests/unit/ultrawiki/test_event_store.py b/tests/unit/ultrawiki/test_event_store.pyindex 07dbf63195..8d9f4c0663 100644--- a/tests/unit/ultrawiki/test_event_store.py+++ b/tests/unit/ultrawiki/test_event_store.py@@ -11,18 +11,24 @@ no model. What it proves:it, and an unresolvable name keeps its spelling instead of vanishing,5. the bi-temporal window matches by OVERLAP, so a coarse event is notinvisible to a question about a day inside it,-6. both dialects declare the same logical schema.+6. both dialects declare the same logical schema,+7. one item spends a BOUNDED identity budget, and storing nothing for an item+ that has nothing writes nothing at all."""from __future__ import annotationsimport sqlite3+from contextlib import asynccontextmanagerfrom datetime import UTC, datetimefrom pathlib import Pathimport pytestfrom jarvis.ultrawiki.events import (+ MAX_ENTITIES_CREATED_PER_ITEM,+ MAX_IDENTITY_NAMES_PER_ITEM,+ MAX_IDENTITY_PROPOSALS_PER_ITEM,DerivedEvent,EventKind,EventTime,@@ -548,6 +554,220 @@ async def test_the_event_leg_reports_both_clocks(store):assert hits[0].recorded_utc == "2026-03-14T08:00:00Z"+# ---------------------------------------------------------------------------+# Per-item identity budget — one document is never unbounded work+# ---------------------------------------------------------------------------+++def crowd(prefix: str, count: int) -> tuple[str, ...]:+ """``count`` distinct participant names in a stable order."""+ return tuple(f"{prefix} {index:02d}" for index in range(1, count + 1))+++#: Names dissimilar enough that none of them proposes itself to another, so a+#: test about the CREATION budget is not decided by the proposal budget.+UNRELATED_NAMES = (+ "Ada Kestrel",+ "Boris Nwosu",+ "Chandra Vella",+ "Devi Oyelaran",+ "Emil Rousseau",+ "Farah Kimathi",+ "Goran Petrov",+ "Hana Ishikawa",+ "Ivo Bergqvist",+ "Juno Almeida",+ "Kiran Adeyemi",+ "Lena Vukovic",+)+++def guest_list(names: tuple[str, ...]) -> list[DerivedEvent]:+ """Two realistically shaped events splitting *names* between them."""+ half = len(names) // 2+ return [+ event(title="Reception", participants=names[:half], place=""),+ event(+ title="Afterparty",+ when=datetime(2026, 3, 13, 23, 0, tzinfo=UTC),+ participants=names[half:],+ place="",+ ),+ ]+++def linked_names(rows: list[dict]) -> dict[str, object]:+ return {+ participant["display_name"]: participant["entity_id"]+ for row in rows+ for participant in row["participants"]+ }+++async def test_one_item_resolves_a_bounded_number_of_distinct_names(store):+ """The per-EVENT caps multiply out to sixty resolutions per document; the+ per-item budget is what keeps one import from paying all of them."""+ names = crowd("Guest", MAX_IDENTITY_NAMES_PER_ITEM + 6)+ for name in names: # already curated, so creation is not what is measured+ await store.upsert_entity(display_name=name)+ item_id = await add_item(store)+ await store.replace_events(item_id, guest_list(names))++ resolved = linked_names(await store.list_events())+ # Nothing is dropped from the EVENT — the evidence stays complete.+ assert set(resolved) == set(names)+ linked = {name for name, entity in resolved.items() if entity is not None}+ # ...but only the budgeted prefix reached the identity layer, and which+ # names those are is decided by document order alone.+ assert linked == set(names[:MAX_IDENTITY_NAMES_PER_ITEM])+++async def test_the_name_budget_drops_the_same_names_on_every_pass(store):+ """A cap that drops a different tail each time would make re-derivation+ non-idempotent, which is the one thing this write path may not be."""+ names = crowd("Guest", MAX_IDENTITY_NAMES_PER_ITEM + 6)+ for name in names:+ await store.upsert_entity(display_name=name)+ item_id = await add_item(store)++ await store.replace_events(item_id, guest_list(names))+ first = linked_names(await store.list_events())+ await store.replace_events(item_id, guest_list(names))+ second = linked_names(await store.list_events())++ assert first == second+++async def test_one_item_creates_a_bounded_number_of_new_people(store):+ """A new row in the People view outlives the guess that produced it, so+ the irreversible direction is capped hardest."""+ names = UNRELATED_NAMES+ assert len(names) > MAX_ENTITIES_CREATED_PER_ITEM+ item_id = await add_item(store)+ await store.replace_events(item_id, [event(participants=names, place="")])++ people = await store.list_people(kind=None, limit=100)+ assert len(people) == MAX_ENTITIES_CREATED_PER_ITEM+ assert {person["display_name"] for person in people} == set(+ names[:MAX_ENTITIES_CREATED_PER_ITEM]+ )+ # The names past the cap are still ON the event, spelled out and+ # searchable — the budget withholds rows, never evidence.+ resolved = linked_names(await store.list_events())+ assert set(resolved) == set(names)+ assert all(resolved[name] is None for name in names[MAX_ENTITIES_CREATED_PER_ITEM:])+++async def test_a_name_past_the_budget_still_links_to_a_known_person(store):+ """Degradation withholds CREATION, not knowledge: a curated person named+ after the budget is spent must still be linked."""+ known = await store.upsert_entity(display_name="Marlow Vance")+ names = (*UNRELATED_NAMES, "Marlow Vance")+ item_id = await add_item(store)+ await store.replace_events(item_id, [event(participants=names, place="")])++ assert linked_names(await store.list_events())["Marlow Vance"] == known+++async def test_one_item_never_floods_the_confirmation_queue(store):+ """The queue is only useful while a human can still work through it."""+ for name in crowd("Person", 6):+ await store.upsert_entity(display_name=name)+ before = (await store.identity_counts())["pending_confirmations"]+ item_id = await add_item(store)+ # Every one of these is a near-name of all six curated ones, so without a+ # per-item budget each creation would queue its own full proposal batch.+ newcomers = crowd("Persona", 10)+ await store.replace_events(item_id, [event(participants=newcomers, place="")])++ counts = await store.identity_counts()+ added = counts["pending_confirmations"] - before+ assert 0 < added <= MAX_IDENTITY_PROPOSALS_PER_ITEM+ # The budget stopped creation early rather than raising.+ resolved = linked_names(await store.list_events())+ assert set(resolved) == set(newcomers)+ assert any(entity is None for entity in resolved.values())+++async def test_a_failed_identity_batch_replays_the_names_one_by_one(store):+ """One transaction is ONE failure domain: a rollback mid-batch must cost+ the item nothing, because identity may never fail an event."""+ real_batch = store.identity_batch+ attempts = {"batch": 0}++ @asynccontextmanager+ async def failing_batch():+ attempts["batch"] += 1+ async with real_batch() as resolve:+ seen = 0++ async def wrapped(**kwargs):+ nonlocal seen+ seen += 1+ if seen > 1: # the first name is already written — and lost+ raise RuntimeError("batch refused")+ return await resolve(**kwargs)++ yield wrapped++ store.identity_batch = failing_batch+ try:+ item_id = await add_item(store)+ await store.replace_events(item_id, [event()])+ finally:+ del store.identity_batch++ stored = (await store.list_events())[0]+ assert attempts["batch"] == 1+ assert stored["participants"][0]["entity_id"] is not None+ assert stored["place_entity_id"] is not None+ # The rolled-back half must not survive as a duplicate.+ assert len(await store.list_people(kind=None, limit=50)) == 2+++# ---------------------------------------------------------------------------+# The empty case — most items yield no events at all+# ---------------------------------------------------------------------------+++def spy_on_transactions(store, monkeypatch) -> list[str]:+ """Record every write transaction the store opens from here on."""+ opened: list[str] = []+ original = store._txn++ def spy():+ opened.append("txn")+ return original()++ monkeypatch.setattr(store, "_txn", spy)+ return opened+++async def test_an_item_that_never_had_events_is_not_written_at_all(+ store, monkeypatch+):+ """The overwhelming majority of items derive nothing; a write transaction+ each would make the empty case the most expensive thing on the pass."""+ item_id = await add_item(store)+ opened = spy_on_transactions(store, monkeypatch)++ assert await store.replace_events(item_id, []) == []++ assert opened == []+++async def test_an_item_that_HAD_events_is_still_cleared(store, monkeypatch):+ """The early-out may not resurrect a corrected source's old answer."""+ item_id = await add_item(store)+ await store.replace_events(item_id, [event()])+ opened = spy_on_transactions(store, monkeypatch)++ await store.replace_events(item_id, [])++ assert opened # the clearing write really happened+ assert await store.list_events() == []++async def test_the_backfill_reader_walks_distilled_items_once(store):"""The lane that gives an ALREADY distilled corpus its events without asingle model call — it reads the distillation that is already stored."""