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
feat(ultrawiki): project the store into a readable wiki model
Ruben Lütke169f23dbc9c4
diff --git a/jarvis/ultrawiki/projection.py b/jarvis/ultrawiki/projection.pynew file mode 100644index 0000000000..97e0f029f9--- /dev/null+++ b/jarvis/ultrawiki/projection.py@@ -0,0 +1,329 @@+"""UltraWiki projection — turn the store's log into a readable wiki model.++The store is deliberately a log: one row per raw unit, thousands of small+fragments whose titles repeat by the hundred (a real corpus measured 4712+items across 261 distinct titles, the most common repeating 213 times). That+shape is right for retrieval and wrong for reading. Anything that shows the+corpus to a human — the Explore view, the Obsidian vault export — needs a+condensation layer first, or it renders hundreds of identical stubs linked to+nothing.++The readable units are one level up, and the distiller already extracted them:++- **Entities** — the people, places, organizations and projects named in+ ``uw_documents.distill_json``. They are the natural hubs of a graph.+- **Moments** — one distilled document each, titled by the ``question`` it+ answers, which is a real sentence instead of "Conversation on 2026-04-25".++Raw items never become pages. They stay evidence, reachable through+``permalink`` — mandatory from item one, so every claim can be traced back.++**Derived, never stored.** The full fold — query, JSON parse, entities,+mentions and co-occurrence — measures ~28 ms over a 1500-document corpus, so+the projection stays a computed view behind a fingerprint cache rather than a+second copy of the same truth in extra tables. A stored copy is precisely the+multi-layer drift class this repo has been bitten by repeatedly (BUG-008), and+it would also collide with the P5 identity tables (``uw_entities`` /+``uw_identifiers``), whose names are reserved for real, mergeable entities+with history. When P5 lands, this module reads from those tables instead and+both consuming surfaces stay unchanged.+"""++from __future__ import annotations++import asyncio+import json+import logging+import unicodedata+from collections import defaultdict+from dataclasses import dataclass+from typing import Any, Protocol+from weakref import WeakKeyDictionary++log = logging.getLogger(__name__)++__all__ = [+ "MAX_LABEL_CHARS",+ "MIN_LABEL_CHARS",+ "ProjectedEntity",+ "ProjectedMoment",+ "WikiProjection",+ "build_projection",+ "get_projection",+ "invalidate_projection",+ "normalize_entity_label",+]++#: Length bounds for an entity label. Below the floor a "name" is an initial+#: or stray punctuation; above the ceiling the distiller handed back a+#: sentence, not an entity — and it would also blow past filename limits.+MIN_LABEL_CHARS = 2+MAX_LABEL_CHARS = 80++#: Trimmed from both ends of a label. Deliberately punctuation only: there is+#: no stop-word blacklist anywhere in this module, because guessing which+#: entity is "not real" is how a wiki quietly loses content. Rarity is handled+#: by ranking and the graph threshold, never by dropping data.+_EDGE_PUNCTUATION = " \t\r\n.,;:!?-–—_'\"()[]{}<>/\\|*"+++class _ProjectionSource(Protocol):+ """The slice of the store this module reads (either backend satisfies it)."""++ async def distilled_rows(self) -> list[dict[str, Any]]: ...++ async def distilled_fingerprint(self) -> tuple[int, int, str]: ...+++def normalize_entity_label(raw: object) -> str | None:+ """Canonical display spelling of one entity label, or ``None`` to drop it.++ NFC normalization is load-bearing, not cosmetic: macOS hands text back+ decomposed, so without it the same name becomes two entities *and* two+ vault files that collide with each other on the next export.+ """+ if not isinstance(raw, str):+ return None+ collapsed = " ".join(raw.split())+ label = unicodedata.normalize("NFC", collapsed).strip(_EDGE_PUNCTUATION)+ if not MIN_LABEL_CHARS <= len(label) <= MAX_LABEL_CHARS:+ return None+ return label+++@dataclass(frozen=True, slots=True)+class ProjectedEntity:+ """One browsable entity page: who/what, how often, when, next to whom."""++ key: str # case-folded identity+ label: str # most frequent original spelling+ mentions: int+ item_ids: tuple[int, ...]+ first_seen: str # ISO-8601 UTC+ last_seen: str+ neighbors: tuple[tuple[str, int], ...] # (entity key, shared moments)+++@dataclass(frozen=True, slots=True)+class ProjectedMoment:+ """One distilled moment: a real question, its answer, and its evidence."""++ document_id: int+ item_id: int+ title: str+ summary: str+ resolution: str+ entity_keys: tuple[str, ...]+ timestamp_utc: str+ source_id: str+ source_label: str+ permalink: str++ @property+ def month(self) -> str:+ """``YYYY-MM`` bucket, empty when the timestamp is unusable."""+ return self.timestamp_utc[:7] if len(self.timestamp_utc) >= 7 else ""+++@dataclass(frozen=True, slots=True)+class WikiProjection:+ """The whole readable model: entities, moments, and the graph over them."""++ entities: tuple[ProjectedEntity, ...]+ moments: tuple[ProjectedMoment, ...]+ entity_by_key: dict[str, ProjectedEntity]+ moments_by_entity: dict[str, tuple[ProjectedMoment, ...]]++ def graph(self, *, min_mentions: int = 2) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:+ """Nodes + edges above a mention floor.++ The floor exists because the long tail dominates: on the reference+ corpus 947 entities collapse to 303 at two mentions and 72 at five.+ Drawing all of them at once is a hairball, not a map — so the view+ defaults to a threshold and offers the full set explicitly.++ Edges whose other endpoint fell below the floor are dropped, never+ left dangling at an invisible node.+ """+ kept = {e.key for e in self.entities if e.mentions >= min_mentions}+ nodes = [+ {+ "key": entity.key,+ "label": entity.label,+ "mentions": entity.mentions,+ "first_seen": entity.first_seen,+ "last_seen": entity.last_seen,+ }+ for entity in self.entities+ if entity.key in kept+ ]+ edges: list[dict[str, Any]] = []+ seen: set[tuple[str, str]] = set()+ for entity in self.entities:+ if entity.key not in kept:+ continue+ for other_key, weight in entity.neighbors:+ if other_key not in kept:+ continue+ pair = (+ (entity.key, other_key) if entity.key < other_key else (other_key, entity.key)+ )+ if pair in seen:+ continue+ seen.add(pair)+ edges.append({"source": pair[0], "target": pair[1], "weight": weight})+ return nodes, edges+++def _title_for(distilled: dict[str, Any], row: dict[str, Any]) -> str:+ """The most speaking title available, in descending order of usefulness.++ The item title is the LAST resort on purpose — it is the one that repeats+ by the hundred and made the corpus unreadable in the first place.+ """+ for candidate in (distilled.get("question"), distilled.get("summary")):+ if isinstance(candidate, str) and candidate.strip():+ return " ".join(candidate.split())+ fallback = row.get("title") or ""+ return " ".join(str(fallback).split())+++def _text_field(distilled: dict[str, Any], name: str) -> str:+ value = distilled.get(name)+ return value.strip() if isinstance(value, str) else ""+++async def build_projection(store: _ProjectionSource) -> WikiProjection:+ """Fold the store's distilled documents into the readable wiki model.++ Malformed rows are skipped with a debug line rather than raised: one bad+ distillation must never blank the whole wiki view.+ """+ rows = await store.distilled_rows()++ moments: list[ProjectedMoment] = []+ spellings: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))+ item_ids: dict[str, list[int]] = defaultdict(list)+ seen_times: dict[str, list[str]] = defaultdict(list)+ cooccurrence: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))+ by_entity: dict[str, list[ProjectedMoment]] = defaultdict(list)++ for row in rows:+ try:+ distilled = json.loads(row.get("distill_json") or "")+ except (json.JSONDecodeError, TypeError):+ log.debug(+ "projection: unparseable distillation for document %s",+ row.get("document_id"),+ )+ continue+ if not isinstance(distilled, dict):+ continue++ keys: list[str] = []+ for raw_label in distilled.get("entities") or []:+ label = normalize_entity_label(raw_label)+ if label is None:+ continue+ key = label.casefold()+ if key not in keys:+ keys.append(key)+ spellings[key][label] += 1++ timestamp = str(row.get("timestamp_utc") or "")+ moment = ProjectedMoment(+ document_id=int(row.get("document_id") or 0),+ item_id=int(row.get("item_id") or 0),+ title=_title_for(distilled, row),+ summary=_text_field(distilled, "summary"),+ resolution=_text_field(distilled, "resolution"),+ entity_keys=tuple(keys),+ timestamp_utc=timestamp,+ source_id=str(row.get("source_id") or ""),+ source_label=str(row.get("source_label") or ""),+ permalink=str(row.get("permalink") or ""),+ )+ moments.append(moment)++ for key in keys:+ item_ids[key].append(moment.item_id)+ seen_times[key].append(timestamp)+ by_entity[key].append(moment)+ for index, key in enumerate(keys):+ for other in keys[index + 1 :]:+ cooccurrence[key][other] += 1+ cooccurrence[other][key] += 1++ entities: list[ProjectedEntity] = []+ for key, variants in spellings.items():+ # Ties resolve alphabetically so a re-export is byte-identical.+ label = max(sorted(variants), key=lambda spelling: variants[spelling])+ times = sorted(t for t in seen_times[key] if t)+ neighbors = tuple(+ sorted(+ cooccurrence[key].items(),+ key=lambda pair: (-pair[1], pair[0]),+ )+ )+ entities.append(+ ProjectedEntity(+ key=key,+ label=label,+ mentions=len(item_ids[key]),+ item_ids=tuple(item_ids[key]),+ first_seen=times[0] if times else "",+ last_seen=times[-1] if times else "",+ neighbors=neighbors,+ )+ )++ entities.sort(key=lambda e: (-e.mentions, e.key))+ moments.sort(key=lambda m: (m.timestamp_utc, m.document_id), reverse=True)++ return WikiProjection(+ entities=tuple(entities),+ moments=tuple(moments),+ entity_by_key={e.key: e for e in entities},+ moments_by_entity={+ key: tuple(sorted(found, key=lambda m: (m.timestamp_utc, m.document_id), reverse=True))+ for key, found in by_entity.items()+ },+ )+++# ---------------------------------------------------------------------------+# Fingerprint cache+# ---------------------------------------------------------------------------++#: 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()+_CACHE_LOCK = asyncio.Lock()+++async def get_projection(store: _ProjectionSource) -> WikiProjection:+ """The cached projection, rebuilt whenever its input changed.++ 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.+ """+ fingerprint = await store.distilled_fingerprint()+ cached = _CACHE.get(store)+ if cached is not None and cached[0] == fingerprint:+ return cached[1]+ async with _CACHE_LOCK:+ cached = _CACHE.get(store)+ if cached is not None and cached[0] == fingerprint:+ return cached[1]+ projection = await build_projection(store)+ _CACHE[store] = (fingerprint, projection)+ return projection+++def invalidate_projection(store: _ProjectionSource | None = None) -> None:+ """Drop the cached projection — for tests and for an explicit refresh."""+ if store is None:+ _CACHE.clear()+ else:+ _CACHE.pop(store, None)diff --git a/jarvis/ultrawiki/store.py b/jarvis/ultrawiki/store.pyindex b2b0263f38..2266548ab5 100644--- a/jarvis/ultrawiki/store.py+++ b/jarvis/ultrawiki/store.py@@ -338,6 +338,35 @@ _OUTCOME_COLUMNS: tuple[str, ...] = ("last_tombstoned",)+#: Every live distilled document joined to its item and source — the whole+#: input of the readable projection (``jarvis.ultrawiki.projection``). Shared+#: verbatim by both backends because it binds no parameters, so the two+#: dialects cannot drift apart on the one query the wiki view depends on.+_DISTILLED_ROWS_SQL = (+ "SELECT d.id AS document_id, d.item_id, d.distill_json,"+ " i.title, i.timestamp_utc, i.permalink, i.source_id,"+ " s.label AS source_label"+ " FROM uw_documents d"+ " JOIN uw_items i ON i.id = d.item_id"+ " JOIN uw_sources s ON s.id = i.source_id"+ " WHERE d.distill_json IS NOT NULL AND d.distill_json != ''"+ " AND i.deleted_at IS NULL"+ " ORDER BY i.timestamp_utc DESC, d.id DESC"+)++#: Cheap change stamp over the same set. ``MAX(id)`` is what makes a RE-+#: distillation visible: ``add_document`` replaces the row, so the count is+#: unchanged and ``created_at`` may land in the same second, but the new row+#: always carries a higher id.+_DISTILLED_FINGERPRINT_SQL = (+ "SELECT COUNT(*) AS n, COALESCE(MAX(d.id), 0) AS max_id,"+ " COALESCE(MAX(d.created_at), '') AS newest"+ " FROM uw_documents d"+ " JOIN uw_items i ON i.id = d.item_id"+ " WHERE d.distill_json IS NOT NULL AND d.distill_json != ''"+ " AND i.deleted_at IS NULL"+)+# ---------------------------------------------------------------------------# SQLite reference backend@@ -1080,6 +1109,21 @@ class UltraStore:)return _counts_from_pairs((row["state"], row["n"]) for row in rows)+ async def distilled_rows(self) -> list[dict[str, Any]]:+ """Input rows of the readable projection (see ``_DISTILLED_ROWS_SQL``)."""+ conn = await self._ensure_open()+ rows = await self._fetchall(conn, _DISTILLED_ROWS_SQL)+ return [dict(row) for row in rows]++ async def distilled_fingerprint(self) -> tuple[int, int, str]:+ """Change stamp of the projection input, for caching the projection."""+ conn = await self._ensure_open()+ row = await self._fetchone(conn, _DISTILLED_FINGERPRINT_SQL)+ if row is None:+ return (0, 0, "")+ data = dict(row)+ return (int(data["n"]), int(data["max_id"]), str(data["newest"]))+async def reconcile_deletes(self, source_id: str, yielded_external_ids: set[str]) -> int:@@ -2443,6 +2487,21 @@ class PostgresStore:)return _counts_from_pairs((row["state"], row["n"]) for row in rows)+ async def distilled_rows(self) -> list[dict[str, Any]]:+ """Input rows of the readable projection (see ``_DISTILLED_ROWS_SQL``)."""+ conn = await self._ensure_open()+ rows = await self._fetchall(conn, _DISTILLED_ROWS_SQL)+ return [dict(row) for row in rows]++ async def distilled_fingerprint(self) -> tuple[int, int, str]:+ """Change stamp of the projection input, for caching the projection."""+ conn = await self._ensure_open()+ row = await self._fetchone(conn, _DISTILLED_FINGERPRINT_SQL)+ if row is None:+ return (0, 0, "")+ data = dict(row)+ return (int(data["n"]), int(data["max_id"]), str(data["newest"]))+async def reconcile_deletes(self, source_id: str, yielded_external_ids: set[str]) -> int:diff --git a/tests/unit/ultrawiki/test_projection.py b/tests/unit/ultrawiki/test_projection.pynew file mode 100644index 0000000000..fc494f2424--- /dev/null+++ b/tests/unit/ultrawiki/test_projection.py@@ -0,0 +1,394 @@+"""UltraWiki projection unit tests — the readable wiki model, fully offline.++The store is a log: thousands of small items whose titles repeat by the+hundred. The projection is what makes it readable — it folds the entities and+questions the distiller already extracted into browsable pages and a graph.++Covers: label normalization (NFC, whitespace, punctuation, length bounds),+case-folded identity with most-frequent-spelling display, moment titles and+their fallbacks, mention counts and first/last-seen bounds, co-occurrence+neighbours, tombstone and non-distilled exclusion, malformed JSON tolerance,+the graph threshold, and cache invalidation. Real UltraStore, no network.+"""++from __future__ import annotations++import json++import pytest++from jarvis.ultrawiki.projection import (+ build_projection,+ get_projection,+ normalize_entity_label,+)+from jarvis.ultrawiki.store import UltraStore+from jarvis.ultrawiki.types import DocType, ItemState, RawItem+++async def store(tmp_path):+ instance = UltraStore(tmp_path / "ultrawiki.db")+ await instance.open()+ yield instance+ await instance.close()+++async def seed_source(store: UltraStore, source_id: str = "src1") -> str:+ await store.upsert_source(source_id, connector="local-folder", label="Test source")+ return source_id+++async def seed_distilled(+ store: UltraStore,+ external_id: str,+ *,+ source_id: str = "src1",+ question: str = "",+ summary: str = "",+ resolution: str = "",+ entities: list[str] | None = None,+ timestamp_utc: str = "2026-01-02T10:00:00Z",+ raw_distill_json: str | None = None,+) -> int:+ """One captured item plus its distilled summary document."""+ await store.upsert_items(+ source_id,+ [+ RawItem(+ external_id=external_id,+ body=summary or question or external_id,+ permalink=f"app://{external_id}",+ timestamp_utc=timestamp_utc,+ title=f"Conversation on {timestamp_utc[:10]}",+ )+ ],+ )+ item = await store.get_item_by_external_id(source_id, external_id)+ assert item is not None+ payload = (+ raw_distill_json+ if raw_distill_json is not None+ else json.dumps(+ {+ "question": question,+ "summary": summary,+ "resolution": resolution,+ "entities": entities or [],+ "refs": [],+ }+ )+ )+ await store.add_document(+ item["id"],+ DocType.SUMMARY,+ summary or question,+ distill_json=payload,+ distill_version=1,+ )+ await store.mark_stage_done(item["id"], ItemState.DISTILLED)+ return int(item["id"])+++# ---------------------------------------------------------------------------+# Label normalization+# ---------------------------------------------------------------------------+++def test_normalize_collapses_whitespace_and_strips_edge_punctuation():+ assert normalize_entity_label(" Bora Bora, ") == "Bora Bora"+++def test_normalize_folds_decomposed_unicode_to_composed_form():+ # macOS hands text and filenames back DECOMPOSED (NFD). Without NFC the+ # same name is two entities AND two files that collide on re-export.+ # Spelled as escapes on purpose: written as literal characters the+ # source file gets normalized and this assertion passes vacuously.+ decomposed = "Cafe\u0301 Central" # e + COMBINING ACUTE ACCENT+ composed = "Caf\u00e9 Central" # LATIN SMALL LETTER E WITH ACUTE+ assert decomposed != composed+ assert normalize_entity_label(decomposed) == composed+++def test_normalize_rejects_labels_that_are_too_short_or_too_long():+ assert normalize_entity_label("a") is None+ assert normalize_entity_label("x" * 81) is None+++def test_normalize_rejects_blank_and_punctuation_only_labels():+ assert normalize_entity_label(" ") is None+ assert normalize_entity_label("...") is None+++# ---------------------------------------------------------------------------+# Entity folding+# ---------------------------------------------------------------------------+++async def test_spellings_differing_only_in_case_become_one_entity(store):+ await seed_source(store)+ await seed_distilled(store, "a", question="Q1", entities=["OpenClaw"])+ await seed_distilled(store, "b", question="Q2", entities=["openclaw"])+ await seed_distilled(store, "c", question="Q3", entities=["OpenClaw"])++ projection = await build_projection(store)++ assert [e.key for e in projection.entities] == ["openclaw"]+ entity = projection.entities[0]+ assert entity.mentions == 3+ # Display uses the spelling the corpus actually favours, not the first one+ # seen and not the case-folded key.+ assert entity.label == "OpenClaw"+++async def test_entity_records_mention_count_and_time_span(store):+ await seed_source(store)+ await seed_distilled(+ store,+ "a",+ question="Q1",+ entities=["Tahiti"],+ timestamp_utc="2026-01-05T10:00:00Z",+ )+ await seed_distilled(+ store,+ "b",+ question="Q2",+ entities=["Tahiti"],+ timestamp_utc="2026-03-09T10:00:00Z",+ )++ projection = await build_projection(store)+ entity = projection.entity_by_key["tahiti"]++ assert entity.mentions == 2+ assert entity.first_seen == "2026-01-05T10:00:00Z"+ assert entity.last_seen == "2026-03-09T10:00:00Z"+++async def test_entities_sort_by_mentions_descending(store):+ await seed_source(store)+ await seed_distilled(store, "a", question="Q1", entities=["Rare"])+ for i in range(3):+ await seed_distilled(store, f"b{i}", question="Q", entities=["Common"])++ projection = await build_projection(store)++ assert [e.label for e in projection.entities] == ["Common", "Rare"]+++async def test_entities_sharing_a_moment_become_neighbours(store):+ await seed_source(store)+ await seed_distilled(store, "a", question="Trip", entities=["Bora Bora", "Tahiti"])+ await seed_distilled(store, "b", question="Trip again", entities=["Bora Bora", "Tahiti"])+ await seed_distilled(store, "c", question="Elsewhere", entities=["Berlin"])++ projection = await build_projection(store)++ bora = projection.entity_by_key["bora bora"]+ assert bora.neighbors == (("tahiti", 2),)+ assert projection.entity_by_key["berlin"].neighbors == ()+++# ---------------------------------------------------------------------------+# Moments+# ---------------------------------------------------------------------------+++async def test_moment_title_is_the_distilled_question(store):+ await seed_source(store)+ await seed_distilled(+ store,+ "a",+ question="How do I get to Bora Bora?",+ summary="Discussed flight routes.",+ resolution="Fly via Tahiti.",+ entities=["Bora Bora"],+ )++ projection = await build_projection(store)+ moment = projection.moments[0]++ # NOT the item title, which repeats by the hundred in a real corpus.+ assert moment.title == "How do I get to Bora Bora?"+ assert moment.summary == "Discussed flight routes."+ assert moment.resolution == "Fly via Tahiti."+ assert moment.entity_keys == ("bora bora",)+ assert moment.permalink == "app://a"+++async def test_moment_without_a_question_falls_back_to_its_summary(store):+ await seed_source(store)+ await seed_distilled(store, "a", question="", summary="A note about caching.")++ projection = await build_projection(store)++ assert projection.moments[0].title == "A note about caching."+++async def test_moment_without_question_or_summary_falls_back_to_item_title(store):+ await seed_source(store)+ await seed_distilled(store, "a", question="", summary="")++ projection = await build_projection(store)++ assert projection.moments[0].title == "Conversation on 2026-01-02"+++async def test_moments_are_newest_first(store):+ await seed_source(store)+ await seed_distilled(store, "old", question="Older", timestamp_utc="2026-01-01T10:00:00Z")+ await seed_distilled(store, "new", question="Newer", timestamp_utc="2026-06-01T10:00:00Z")++ projection = await build_projection(store)++ assert [m.title for m in projection.moments] == ["Newer", "Older"]+++async def test_moment_carries_its_source_label(store):+ await seed_source(store)+ await seed_distilled(store, "a", question="Q")++ projection = await build_projection(store)++ assert projection.moments[0].source_label == "Test source"+++# ---------------------------------------------------------------------------+# Exclusions and tolerance+# ---------------------------------------------------------------------------+++async def test_items_without_a_distillation_produce_no_moment(store):+ source_id = await seed_source(store)+ await store.upsert_items(+ source_id,+ [+ RawItem(+ external_id="raw-only",+ body="Some raw text",+ permalink="app://raw-only",+ timestamp_utc="2026-01-02T10:00:00Z",+ )+ ],+ )+ item = await store.get_item_by_external_id(source_id, "raw-only")+ assert item is not None+ await store.add_document(item["id"], DocType.RAW, "Some raw text")++ projection = await build_projection(store)++ assert projection.moments == ()+ assert projection.entities == ()+++async def test_tombstoned_items_leave_the_projection(store):+ source_id = await seed_source(store)+ await seed_distilled(store, "gone", question="Q", entities=["Ghost"])+ await store.reconcile_deletes(source_id, set())++ projection = await build_projection(store)++ assert projection.moments == ()+ assert projection.entities == ()+++async def test_malformed_distillation_json_is_skipped_not_fatal(store):+ await seed_source(store)+ await seed_distilled(store, "bad", raw_distill_json="{not json")+ await seed_distilled(store, "good", question="Fine", entities=["Berlin"])++ projection = await build_projection(store)++ assert [m.title for m in projection.moments] == ["Fine"]+ assert [e.key for e in projection.entities] == ["berlin"]+++async def test_non_string_entity_values_are_ignored(store):+ await seed_source(store)+ await seed_distilled(+ store,+ "a",+ question="Q",+ raw_distill_json=json.dumps(+ {+ "question": "Q",+ "summary": "",+ "resolution": "",+ "entities": ["Berlin", 42, None, {"name": "x"}],+ "refs": [],+ }+ ),+ )++ projection = await build_projection(store)++ assert [e.key for e in projection.entities] == ["berlin"]+++async def test_empty_corpus_projects_to_an_empty_model(store):+ await seed_source(store)++ projection = await build_projection(store)++ assert projection.entities == ()+ assert projection.moments == ()+ assert projection.graph(min_mentions=1) == ([], [])+++# ---------------------------------------------------------------------------+# Graph+# ---------------------------------------------------------------------------+++async def test_graph_threshold_hides_entities_below_the_mention_floor(store):+ await seed_source(store)+ await seed_distilled(store, "a", question="Q1", entities=["Common", "Rare"])+ await seed_distilled(store, "b", question="Q2", entities=["Common"])++ projection = await build_projection(store)++ nodes, _ = projection.graph(min_mentions=2)+ assert [n["key"] for n in nodes] == ["common"]++ nodes, _ = projection.graph(min_mentions=1)+ assert {n["key"] for n in nodes} == {"common", "rare"}+++async def test_graph_drops_edges_whose_endpoint_was_filtered_out(store):+ await seed_source(store)+ await seed_distilled(store, "a", question="Q1", entities=["Common", "Rare"])+ await seed_distilled(store, "b", question="Q2", entities=["Common"])++ projection = await build_projection(store)+ _, edges = projection.graph(min_mentions=2)++ # An edge pointing at a hidden node would render as a dangling line.+ assert edges == []+++# ---------------------------------------------------------------------------+# Caching+# ---------------------------------------------------------------------------+++async def test_repeated_calls_reuse_the_cached_projection(store):+ await seed_source(store)+ await seed_distilled(store, "a", question="Q")++ first = await get_projection(store)+ second = await get_projection(store)++ assert first is second+++async def test_new_distillation_invalidates_the_cache(store):+ await seed_source(store)+ await seed_distilled(store, "a", question="Q")+ first = await get_projection(store)++ await seed_distilled(store, "b", question="Q2")+ second = await get_projection(store)++ assert second is not first+ assert len(second.moments) == 2