Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

perf(memory): read snapshot stamps without loading entity content

Bingxi Zhao (Frank)f5b905f5356e
diff --git a/deeptutor/services/memory/snapshot/__init__.py b/deeptutor/services/memory/snapshot/__init__.py
index 89d11f2d6..b18b44099 100644
--- a/deeptutor/services/memory/snapshot/__init__.py
+++ b/deeptutor/services/memory/snapshot/__init__.py
@@ -4,6 +4,9 @@ Public API:
- :func:`read_snapshot` — current entities for a surface (no I/O on
``state.json`` / ``changes.jsonl``).
+- :func:`read_stamps` — the same set without content: identity, label,
+ fingerprint, timestamp. What the diff and "what happened lately" both
+ actually need.
- :func:`refresh_snapshot` — re-read workspace, diff against last
persisted state, append changes, persist new state. Returns the
computed change list. Idempotent: a no-change refresh writes nothing
@@ -17,28 +20,44 @@ Public API:
from __future__ import annotations
from datetime import datetime, timezone
-from typing import Iterable
+from typing import Iterable, Sequence
from deeptutor.services.memory.paths import Surface
from deeptutor.services.memory.snapshot import adapters, store
from deeptutor.services.memory.snapshot.diff import diff_snapshots
-from deeptutor.services.memory.snapshot.entity import ChangeEntry, Entity
+from deeptutor.services.memory.snapshot.entity import (
+ ChangeEntry,
+ Entity,
+ EntityStamp,
+ Stamped,
+)
def read_snapshot(surface: Surface) -> list[Entity]:
return adapters.read_entities(surface)
-def pending_changes(surface: Surface, entities: list[Entity] | None = None) -> list[ChangeEntry]:
+def read_stamps(surface: Surface) -> list[EntityStamp]:
+ """Diff-shaped view of a surface, without its content. See :mod:`.adapters`."""
+ return adapters.read_stamps(surface)
+
+
+def pending_changes(
+ surface: Surface, entities: Sequence[Stamped] | None = None
+) -> list[ChangeEntry]:
"""Compute the diff between current workspace and the last persisted state.
Pure / read-only: never writes to ``state.json`` or ``changes.jsonl``.
Used by the L1 view to show "what would a refresh capture right now".
+
+ Accepts anything carrying ``id`` / ``label`` / ``fingerprint`` — a caller
+ that already has full :class:`Entity` objects (the L1 view, which needs
+ their content anyway) passes those; a caller that only needs the diff gets
+ the cheap :class:`EntityStamp` path by passing nothing.
"""
- if entities is None:
- entities = adapters.read_entities(surface)
- curr_fp = {e.id: e.fingerprint for e in entities}
- curr_labels = {e.id: e.label for e in entities}
+ stamps: Sequence[Stamped] = entities if entities is not None else adapters.read_stamps(surface)
+ curr_fp = {e.id: e.fingerprint for e in stamps}
+ curr_labels = {e.id: e.label for e in stamps}
prev = store.load_state(surface)
prev_fp = prev.get("fingerprints") or {}
@@ -53,10 +72,15 @@ def pending_changes(surface: Surface, entities: list[Entity] | None = None) -> l
def refresh_snapshot(surface: Surface) -> list[ChangeEntry]:
- entities = adapters.read_entities(surface)
- changes = pending_changes(surface, entities)
- curr_fp = {e.id: e.fingerprint for e in entities}
- curr_labels = {e.id: e.label for e in entities}
+ """Reconcile persisted state with the workspace and log what moved.
+
+ Runs on stamps, not full entities: a refresh only ever writes fingerprints
+ and labels, so reading message bodies here would be pure waste.
+ """
+ stamps = adapters.read_stamps(surface)
+ changes = pending_changes(surface, stamps)
+ curr_fp = {e.id: e.fingerprint for e in stamps}
+ curr_labels = {e.id: e.label for e in stamps}
store.append_changes(surface, changes)
store.save_state(
surface,
@@ -85,8 +109,11 @@ def clear_changes(surface: Surface) -> None:
__all__ = [
"Entity",
+ "EntityStamp",
+ "Stamped",
"ChangeEntry",
"read_snapshot",
+ "read_stamps",
"pending_changes",
"refresh_snapshot",
"read_changes",
diff --git a/deeptutor/services/memory/snapshot/adapters.py b/deeptutor/services/memory/snapshot/adapters.py
index 4dc4ccf27..46727ab2a 100644
--- a/deeptutor/services/memory/snapshot/adapters.py
+++ b/deeptutor/services/memory/snapshot/adapters.py
@@ -20,7 +20,7 @@ import logging
import sqlite3
from deeptutor.services.memory.paths import Surface
-from deeptutor.services.memory.snapshot.entity import Entity
+from deeptutor.services.memory.snapshot.entity import Entity, EntityStamp
from deeptutor.services.path_service import get_path_service
logger = logging.getLogger(__name__)
@@ -512,6 +512,59 @@ def read_quiz_entities() -> list[Entity]:
return out
+# ── Probes (identity + stamp, without content) ───────────────────────
+
+
+def probe_chat_entities() -> list[EntityStamp]:
+ """Chat stamps without reading a single message body.
+
+ Deliberately mirrors :func:`read_chat_entities`'s ``id`` / ``label`` /
+ ``fingerprint`` expression by expression. In particular the fingerprint is
+ ``_sha1(last_msg_id, updated_at)`` where ``last_msg_id`` is the id of the
+ last message under ``ORDER BY created_at ASC, id ASC`` — NOT ``MAX(id)``,
+ which would diverge whenever ids and timestamps disagree (clock skew, a
+ backfilled row). Selecting the first row of the reversed ordering picks the
+ same message. Sessions with no messages stamp ``0``, as the full read does.
+
+ Skipping ``content`` is the whole point: the full read concatenates every
+ message of every session, which is the wrong price to pay for a caller that
+ only wants to know what the sessions are called.
+ """
+ db_path = get_path_service().get_chat_history_db()
+ if not db_path.exists():
+ return []
+ out: list[EntityStamp] = []
+ try:
+ with sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) as conn:
+ conn.row_factory = sqlite3.Row
+ last_msg_id: dict[str, int] = {
+ row["session_id"]: row["id"]
+ for row in conn.execute(
+ "SELECT session_id, id FROM ("
+ " SELECT session_id, id, ROW_NUMBER() OVER ("
+ " PARTITION BY session_id ORDER BY created_at DESC, id DESC"
+ " ) AS rn FROM messages"
+ ") WHERE rn = 1"
+ )
+ }
+ for sess in conn.execute(
+ "SELECT id, title, updated_at FROM sessions ORDER BY updated_at DESC"
+ ):
+ sid = sess["id"]
+ out.append(
+ EntityStamp(
+ id=sid,
+ label=sess["title"] or sid,
+ fingerprint=_sha1(last_msg_id.get(sid, 0), sess["updated_at"]),
+ ts=_iso(sess["updated_at"]),
+ )
+ )
+ except sqlite3.Error as exc:
+ logger.warning("chat snapshot probe failed: %s", exc)
+ return []
+ return out
+
+
# ── Dispatch ─────────────────────────────────────────────────────────
@@ -525,6 +578,14 @@ _READERS = {
"quiz": read_quiz_entities,
}
+# Surfaces with a cheap stamps-only path. A surface belongs here only when
+# skipping content actually saves something: every other adapter reads a
+# bounded amount, so a second code path would be duplication without a payoff
+# — and a second chance to drift from its full reader.
+_PROBES = {
+ "chat": probe_chat_entities,
+}
+
def read_entities(surface: Surface) -> list[Entity]:
reader = _READERS.get(surface)
@@ -537,4 +598,25 @@ def read_entities(surface: Surface) -> list[Entity]:
return []
+def read_stamps(surface: Surface) -> list[EntityStamp]:
+ """Identity + label + fingerprint + timestamp for every entity on *surface*.
+
+ Uses the surface's probe when it has one and falls back to projecting the
+ full read otherwise, so a surface without a probe is simply slower — never
+ unsupported. A probe that raises also falls back rather than reporting an
+ empty surface, which the diff would otherwise read as "everything was
+ deleted".
+ """
+ probe = _PROBES.get(surface)
+ if probe is not None:
+ try:
+ return probe()
+ except Exception as exc:
+ logger.warning("snapshot probe failed surface=%s; full read: %s", surface, exc)
+ return [
+ EntityStamp(id=e.id, label=e.label, fingerprint=e.fingerprint, ts=e.ts)
+ for e in read_entities(surface)
+ ]
+
+
SUPPORTED_SURFACES: tuple[Surface, ...] = tuple(_READERS.keys()) # type: ignore[arg-type,assignment]
diff --git a/deeptutor/services/memory/snapshot/entity.py b/deeptutor/services/memory/snapshot/entity.py
index 5638c109c..1bb67fa27 100644
--- a/deeptutor/services/memory/snapshot/entity.py
+++ b/deeptutor/services/memory/snapshot/entity.py
@@ -13,7 +13,7 @@ dicts to produce ``ChangeEntry`` records.
from __future__ import annotations
from dataclasses import asdict, dataclass, field
-from typing import Any, Literal
+from typing import Any, Literal, Protocol, runtime_checkable
@dataclass
@@ -29,6 +29,41 @@ class Entity:
return asdict(self)
+@runtime_checkable
+class Stamped(Protocol):
+ """The three fields the diff engine actually reads off an entity."""
+
+ id: str
+ label: str
+ fingerprint: str
+
+
+@dataclass(frozen=True, slots=True)
+class EntityStamp:
+ """Just enough of an :class:`Entity` to identify and date it — no ``content``.
+
+ The diff compares fingerprints and carries labels for the change log; it
+ never looks at ``content``. Building content anyway costs the chat surface
+ every message body of every session, which is affordable for a
+ user-initiated refresh and not affordable for something that runs whenever
+ a page loads. A surface may therefore offer a *probe* that produces stamps
+ directly; see :func:`~deeptutor.services.memory.snapshot.adapters.read_stamps`.
+
+ A probe MUST derive ``id`` / ``label`` / ``fingerprint`` exactly as its full
+ adapter does, or a probe-driven refresh and a content-driven one would
+ disagree about what changed.
+
+ ``ts`` takes no part in the diff — it rides along because "what happened
+ recently" is a question worth answering without reading content either
+ (:func:`deeptutor.services.memory.recall.recent` asks exactly that).
+ """
+
+ id: str
+ label: str
+ fingerprint: str
+ ts: str = ""
+
+
ChangeKind = Literal["added", "modified", "removed"]
@@ -43,3 +78,6 @@ class ChangeEntry:
def to_dict(self) -> dict[str, Any]:
return asdict(self)
+
+
+__all__ = ["ChangeEntry", "ChangeKind", "Entity", "EntityStamp", "Stamped"]
diff --git a/tests/services/memory/test_snapshot_probes.py b/tests/services/memory/test_snapshot_probes.py
new file mode 100644
index 000000000..c88ee6542
--- /dev/null
+++ b/tests/services/memory/test_snapshot_probes.py
@@ -0,0 +1,178 @@
+"""Probe/full-read equivalence for the snapshot adapters.
+
+A probe exists to skip reading content. That is only safe while it agrees with
+its full adapter about *identity* — id, label and fingerprint — because the two
+feed the same diff: a refresh driven by one and a refresh driven by the other
+must not disagree about what changed. These tests pin that agreement, including
+the case that motivates the probe's odd-looking SQL.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+import sqlite3
+
+import pytest
+
+from deeptutor.services.memory.snapshot import adapters
+
+
+class _FakePathService:
+ def __init__(self, db_path: Path) -> None:
+ self._db_path = db_path
+
+ def get_chat_history_db(self) -> Path:
+ return self._db_path
+
+
+def _make_db(path: Path) -> sqlite3.Connection:
+ conn = sqlite3.connect(path)
+ conn.executescript(
+ """
+ CREATE TABLE sessions (
+ id TEXT PRIMARY KEY,
+ title TEXT,
+ created_at REAL,
+ updated_at REAL
+ );
+ CREATE TABLE messages (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ session_id TEXT,
+ role TEXT,
+ content TEXT,
+ capability TEXT,
+ created_at REAL
+ );
+ """
+ )
+ return conn
+
+
+def chat_db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> sqlite3.Connection:
+ db_path = tmp_path / "chat_history.db"
+ conn = _make_db(db_path)
+ monkeypatch.setattr(adapters, "get_path_service", lambda: _FakePathService(db_path))
+ yield conn
+ conn.close()
+
+
+def _stamps_of(entities) -> list[tuple[str, str, str]]:
+ return [(e.id, e.label, e.fingerprint) for e in entities]
+
+
+def test_probe_matches_full_read(chat_db: sqlite3.Connection) -> None:
+ chat_db.executemany(
+ "INSERT INTO sessions (id, title, created_at, updated_at) VALUES (?, ?, ?, ?)",
+ [
+ ("s1", "Chain rule", 1000.0, 1200.0),
+ ("s2", "Agentic RAG", 900.0, 1100.0),
+ ],
+ )
+ chat_db.executemany(
+ "INSERT INTO messages (session_id, role, content, capability, created_at) "
+ "VALUES (?, ?, ?, ?, ?)",
+ [
+ ("s1", "user", "what is the chain rule", "chat", 1000.0),
+ ("s1", "assistant", "it is...", "chat", 1010.0),
+ ("s2", "user", "explain retrieval", "chat", 900.0),
+ ],
+ )
+ chat_db.commit()
+
+ assert _stamps_of(adapters.probe_chat_entities()) == _stamps_of(adapters.read_chat_entities())
+
+
+def test_probe_matches_full_read_when_ids_and_timestamps_disagree(
+ chat_db: sqlite3.Connection,
+) -> None:
+ """The case ``MAX(id)`` would get wrong.
+
+ The full read orders by ``created_at ASC, id ASC`` and fingerprints the
+ *last* row of that ordering. A backfilled message (higher id, earlier
+ timestamp) is therefore not the one it picks — so a probe reaching for
+ ``MAX(id)`` would fingerprint a different message and report a phantom
+ change on every refresh.
+ """
+ chat_db.execute(
+ "INSERT INTO sessions (id, title, created_at, updated_at) VALUES (?, ?, ?, ?)",
+ ("s1", "Chain rule", 1000.0, 1200.0),
+ )
+ chat_db.executemany(
+ "INSERT INTO messages (id, session_id, role, content, capability, created_at) "
+ "VALUES (?, ?, ?, ?, ?, ?)",
+ [
+ (10, "s1", "user", "asked first", "chat", 1000.0),
+ (20, "s1", "assistant", "answered last", "chat", 1010.0),
+ # Imported/backfilled after the fact: highest id, earliest stamp.
+ (30, "s1", "user", "backfilled", "chat", 500.0),
+ ],
+ )
+ chat_db.commit()
+
+ probed = adapters.probe_chat_entities()
+ full = adapters.read_chat_entities()
+ assert _stamps_of(probed) == _stamps_of(full)
+ # And specifically: not the highest id.
+ assert probed[0].fingerprint == adapters._sha1(20, 1200.0)
+
+
+def test_probe_stamps_empty_session_as_zero(chat_db: sqlite3.Connection) -> None:
+ chat_db.execute(
+ "INSERT INTO sessions (id, title, created_at, updated_at) VALUES (?, ?, ?, ?)",
+ ("s1", "", 1000.0, 1000.0),
+ )
+ chat_db.commit()
+
+ probed = adapters.probe_chat_entities()
+ assert _stamps_of(probed) == _stamps_of(adapters.read_chat_entities())
+ # Untitled sessions fall back to the id, in both readers.
+ assert probed[0].label == "s1"
+ assert probed[0].fingerprint == adapters._sha1(0, 1000.0)
+
+
+def test_probe_returns_empty_without_a_database(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ missing = tmp_path / "nope.db"
+ monkeypatch.setattr(adapters, "get_path_service", lambda: _FakePathService(missing))
+ assert adapters.probe_chat_entities() == []
+
+
+def test_read_stamps_falls_back_for_surfaces_without_a_probe(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A surface with no probe is slower, never unsupported."""
+ from deeptutor.services.memory.snapshot.entity import Entity
+
+ monkeypatch.setitem(
+ adapters._READERS,
+ "book",
+ lambda: [Entity(id="b1", label="Calculus", ts="2026-08-01T00:00:00+00:00", content="...")],
+ )
+
+ stamps = adapters.read_stamps("book")
+
+ assert [(s.id, s.label) for s in stamps] == [("b1", "Calculus")]
+ assert stamps[0].ts == "2026-08-01T00:00:00+00:00"
+
+
+def test_read_stamps_falls_back_when_a_probe_raises(
+ monkeypatch: pytest.MonkeyPatch, chat_db: sqlite3.Connection
+) -> None:
+ """A broken probe must not read as "the surface is empty" — the diff would
+ take that for a mass deletion."""
+ chat_db.execute(
+ "INSERT INTO sessions (id, title, created_at, updated_at) VALUES (?, ?, ?, ?)",
+ ("s1", "Chain rule", 1000.0, 1200.0),
+ )
+ chat_db.commit()
+
+ def _boom() -> list:
+ raise RuntimeError("probe exploded")
+
+ monkeypatch.setitem(adapters._PROBES, "chat", _boom)
+
+ stamps = adapters.read_stamps("chat")
+
+ assert [s.label for s in stamps] == ["Chain rule"]