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: bound UltraWiki explore work and payloads

Ruben Lütkef61085ae7ac7
diff --git a/jarvis/ui/web/ultrawiki_explore_routes.py b/jarvis/ui/web/ultrawiki_explore_routes.py
index 78333b4a6d..7a808297cb 100644
--- a/jarvis/ui/web/ultrawiki_explore_routes.py
+++ b/jarvis/ui/web/ultrawiki_explore_routes.py
@@ -42,7 +42,6 @@ async def _explore_context(request: Request) -> tuple[Any, Any, dict[str, int]]:
store = await _store_of(service)
sources = await store.list_sources()
counts = await store.counts()
- distilled, _max_id, _newest = await store.distilled_fingerprint()
projection = await get_projection(store)
return (
store,
@@ -50,7 +49,7 @@ async def _explore_context(request: Request) -> tuple[Any, Any, dict[str, int]]:
{
"sources": len(sources),
"items": int(getattr(counts, "total", 0)),
- "distilled": int(distilled),
+ "distilled": int(getattr(counts, "distilled", 0)),
},
)
@@ -70,7 +69,9 @@ def _explore_reason(corpus: dict[str, int], entity_count: int) -> str:
return ExploreReason.OK.value
-def _entity_payload(entity: Any, projection: Any) -> dict[str, Any]:
+def _entity_payload(
+ entity: Any, projection: Any, *, neighbor_limit: int
+) -> dict[str, Any]:
"""One entity as the UI needs it — neighbours carry their display label,
because a raw case-folded key is not something to show a human."""
return {
@@ -79,6 +80,7 @@ def _entity_payload(entity: Any, projection: Any) -> dict[str, Any]:
"mentions": entity.mentions,
"first_seen": entity.first_seen,
"last_seen": entity.last_seen,
+ "neighbor_total": len(entity.neighbors),
"neighbors": [
{
"key": key,
@@ -87,7 +89,7 @@ def _entity_payload(entity: Any, projection: Any) -> dict[str, Any]:
),
"shared": shared,
}
- for key, shared in entity.neighbors
+ for key, shared in entity.neighbors[:neighbor_limit]
],
}
@@ -129,7 +131,10 @@ async def list_explore_entities(
page = matched[offset : offset + limit]
return {
"ok": True,
- "entities": [_entity_payload(entity, projection) for entity in page],
+ "entities": [
+ _entity_payload(entity, projection, neighbor_limit=12)
+ for entity in page
+ ],
"total": len(matched),
"corpus": corpus,
"reason": _explore_reason(corpus, len(projection.entities)),
@@ -153,7 +158,7 @@ async def get_explore_entity(
moments = projection.moments_by_entity.get(entity.key, ())
return {
"ok": True,
- "entity": _entity_payload(entity, projection),
+ "entity": _entity_payload(entity, projection, neighbor_limit=100),
"moments": [_moment_payload(m) for m in moments[:limit]],
"total": len(moments),
"corpus": corpus,
@@ -201,6 +206,18 @@ async def get_explore_graph(
le=100,
description="Hide entities mentioned fewer times than this",
),
+ max_nodes: int = Query(
+ default=250,
+ ge=1,
+ le=2000,
+ description="Maximum graph nodes returned",
+ ),
+ max_edges: int = Query(
+ default=1000,
+ ge=0,
+ le=10000,
+ description="Maximum graph edges returned",
+ ),
) -> dict[str, Any]:
"""Nodes + weighted edges above a mention floor.
@@ -209,12 +226,26 @@ async def get_explore_graph(
one-off at once is a hairball rather than a map.
"""
_store, projection, corpus = await _explore_context(request)
- nodes, edges = projection.graph(min_mentions=min_mentions)
+ all_nodes, all_edges = projection.graph(min_mentions=min_mentions)
+ nodes = all_nodes[:max_nodes]
+ kept = {str(node["key"]) for node in nodes}
+ eligible_edges = [
+ edge
+ for edge in all_edges
+ if edge["source"] in kept and edge["target"] in kept
+ ]
+ eligible_edges.sort(
+ key=lambda edge: (-int(edge["weight"]), edge["source"], edge["target"])
+ )
+ edges = eligible_edges[:max_edges]
return {
"ok": True,
"nodes": nodes,
"edges": edges,
"min_mentions": min_mentions,
+ "available_nodes": len(all_nodes),
+ "available_edges": len(eligible_edges),
+ "truncated": len(nodes) < len(all_nodes) or len(edges) < len(eligible_edges),
"total_entities": len(projection.entities),
"corpus": corpus,
"reason": _explore_reason(corpus, len(projection.entities)),
diff --git a/jarvis/ultrawiki/projection.py b/jarvis/ultrawiki/projection.py
index 97e0f029f9..9f50288251 100644
--- a/jarvis/ultrawiki/projection.py
+++ b/jarvis/ultrawiki/projection.py
@@ -34,6 +34,7 @@ from __future__ import annotations
import asyncio
import json
import logging
+import time
import unicodedata
from collections import defaultdict
from dataclasses import dataclass
@@ -297,27 +298,59 @@ async def build_projection(store: _ProjectionSource) -> WikiProjection:
#: Per-store cache. Weak keys so a closed store is collected with its entry;
#: the value carries the fingerprint the projection was built from.
-_CACHE: WeakKeyDictionary[Any, tuple[tuple[int, int, str], WikiProjection]] = WeakKeyDictionary()
+PROJECTION_CACHE_TTL_S = 15.0
+
+
+@dataclass(frozen=True, slots=True)
+class _ProjectionCacheEntry:
+ fingerprint: tuple[int, int, str]
+ projection: WikiProjection
+ checked_at: float
+
+
+_CACHE: WeakKeyDictionary[Any, _ProjectionCacheEntry] = WeakKeyDictionary()
_CACHE_LOCK = asyncio.Lock()
+_monotonic = time.monotonic
async def get_projection(store: _ProjectionSource) -> WikiProjection:
- """The cached projection, rebuilt whenever its input changed.
+ """The cached projection, refreshed shortly after its input changes.
- The fingerprint query is a single aggregate; the rebuild behind it is the
- expensive part, so concurrent callers serialize on one lock instead of
- each folding the same corpus.
+ A busy pipeline changes the fingerprint every few seconds. Checking it on
+ every UI request made the cache useless and repeatedly folded the entire
+ corpus while the user clicked around. The projection is a browse aid, not
+ the retrieval index, so a bounded 15-second stale window is preferable to
+ multi-second page loads. Explicit invalidation remains immediate.
"""
- fingerprint = await store.distilled_fingerprint()
+ checked_at = _monotonic()
cached = _CACHE.get(store)
- if cached is not None and cached[0] == fingerprint:
- return cached[1]
+ if (
+ cached is not None
+ and checked_at - cached.checked_at < PROJECTION_CACHE_TTL_S
+ ):
+ return cached.projection
async with _CACHE_LOCK:
cached = _CACHE.get(store)
- if cached is not None and cached[0] == fingerprint:
- return cached[1]
+ checked_at = _monotonic()
+ if (
+ cached is not None
+ and checked_at - cached.checked_at < PROJECTION_CACHE_TTL_S
+ ):
+ return cached.projection
+ fingerprint = await store.distilled_fingerprint()
+ if cached is not None and cached.fingerprint == fingerprint:
+ _CACHE[store] = _ProjectionCacheEntry(
+ fingerprint=fingerprint,
+ projection=cached.projection,
+ checked_at=checked_at,
+ )
+ return cached.projection
projection = await build_projection(store)
- _CACHE[store] = (fingerprint, projection)
+ _CACHE[store] = _ProjectionCacheEntry(
+ fingerprint=fingerprint,
+ projection=projection,
+ checked_at=checked_at,
+ )
return projection
diff --git a/tests/unit/ultrawiki/test_projection.py b/tests/unit/ultrawiki/test_projection.py
index fc494f2424..4cf11f7053 100644
--- a/tests/unit/ultrawiki/test_projection.py
+++ b/tests/unit/ultrawiki/test_projection.py
@@ -17,7 +17,9 @@ import json
import pytest
+from jarvis.ultrawiki import projection as projection_mod
from jarvis.ultrawiki.projection import (
+ PROJECTION_CACHE_TTL_S,
build_projection,
get_projection,
normalize_entity_label,
@@ -382,12 +384,20 @@ async def test_repeated_calls_reuse_the_cached_projection(store):
assert first is second
-async def test_new_distillation_invalidates_the_cache(store):
+async def test_new_distillation_refreshes_after_the_short_cache_window(
+ store, monkeypatch
+):
+ clock = [100.0]
+ monkeypatch.setattr(projection_mod, "_monotonic", lambda: clock[0])
await seed_source(store)
await seed_distilled(store, "a", question="Q")
first = await get_projection(store)
await seed_distilled(store, "b", question="Q2")
+ still_cached = await get_projection(store)
+ assert still_cached is first
+
+ clock[0] += PROJECTION_CACHE_TTL_S + 0.1
second = await get_projection(store)
assert second is not first
diff --git a/tests/unit/web/test_ultrawiki_explore_routes.py b/tests/unit/web/test_ultrawiki_explore_routes.py
index d5755e2395..21e6cd58f4 100644
--- a/tests/unit/web/test_ultrawiki_explore_routes.py
+++ b/tests/unit/web/test_ultrawiki_explore_routes.py
@@ -168,6 +168,7 @@ def test_entity_detail_carries_its_moments(env):
"How do I get to Bora Bora?",
]
assert [n["label"] for n in body["entity"]["neighbors"]] == ["Bora Bora"]
+ assert body["entity"]["neighbor_total"] == 1
def test_unknown_entity_is_a_404_not_an_empty_page(env):
@@ -241,6 +242,20 @@ def test_graph_floor_of_one_shows_the_whole_corpus(env):
assert len(body["nodes"]) == 3
+def test_graph_caps_payload_without_leaving_dangling_edges(env):
+ seed(env, TRIP)
+
+ body = env.client.get(
+ "/api/ultrawiki/explore/graph",
+ params={"min_mentions": 1, "max_nodes": 1, "max_edges": 1},
+ ).json()
+
+ assert len(body["nodes"]) == 1
+ assert body["edges"] == []
+ assert body["available_nodes"] == 3
+ assert body["truncated"] is True
+
+
# ---------------------------------------------------------------------------
# The three honest empty states
# ---------------------------------------------------------------------------