Files
ai-agent/backend/test_card_cache.py
gabrielvidalandClaude Opus 5.5 de07e009f1 feat(conversations): UUIDv7 conversation ids — the transcript path stays inside
A conversation (and every subagent) was addressed by its transcript's path
under the archive, which put the owner's home dir, project and branch names in
every URL a guest saw. Now each archived transcript has a UUIDv7:

- timestamp = the transcript's first timestamped record (ids sort by start,
  past conversations included); the other 74 bits = sha256(rel path), so a
  lost registry re-derives the same ids
- registry: conv_uids table in ai-agent.db (conversations/ids.py), bound at
  startup; tree._conv_id is the one door responses go through
- legacy path ids and bare session ids still resolve (_public_id) — old links,
  deploy.sh, the mail trigger, worker terminals
- access.session_of / catalog._meta_key resolve a uid before deriving the sid;
  TRANSCRIPTS_DIR / <id> joins replaced by ids.path_of
- SSE transcript events carry uids + a roots map (subagent → root); the guest
  filter trims it
- thread detail: owner-only `transcript` (the archived copy's host path)
- id_migration: at every start, mint missing uids and swap every known path id
  in /data/*.json for its uid (raw text, .bak-uids-<stamp> copies), re-key
  short titles + their side-call refs; cross-process safe for blue-green

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:04:20 +01:00

126 lines
5.5 KiB
Python

"""The list's per-card cache: a write remakes the card it touched, and only
that one — the rest are the same objects as before — while a card inside the
recency window still follows the clock.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import datetime
import json
import os
import pathlib
import tempfile
import time
import unittest
from unittest import mock
TMP = pathlib.Path(tempfile.mkdtemp())
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
"PROFILES_PATH": TMP / "profiles.json",
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
"NOTIF_READ_PATH": TMP / "nr.json",
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
"NEW_PROJECTS_PATH": TMP / "np.json", "PROJECTS_DIR": TMP / "projects",
"INTERNAL_API_TOKEN": "tok", "SIDECAR_TOKEN": "",
"PI_TRANSCRIPTS_DIR": "", "RUNNING_WINDOW_SECS": "600"}.items():
os.environ[k] = str(v)
import main # noqa: E402
from conversations import catalog, ids # noqa: E402
DEPS = main.app.state.ai
PROJ = "-home-x"
OLD, LIVE = 3600, 10 # seconds since the last record: settled / in the window
def ago(secs: float) -> str:
t = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(seconds=secs)
return t.isoformat(timespec="milliseconds").replace("+00:00", "Z")
def write(sid: str, secs: float, text: str = "hello", append: bool = False,
rel: str | None = None) -> str:
path = TMP / "arch" / PROJ / (rel or f"{sid}.jsonl")
path.parent.mkdir(parents=True, exist_ok=True)
recs = [{"sessionId": sid, "type": "user", "uuid": f"u{time.time_ns()}",
"timestamp": ago(secs), "message": {"role": "user", "content": text}},
{"sessionId": sid, "type": "assistant", "uuid": f"a{time.time_ns()}",
"timestamp": ago(secs - 1),
"message": {"role": "assistant", "id": f"m{time.time_ns()}",
"model": "claude-opus-5-5",
"content": [{"type": "text", "text": "ok"}],
"usage": {"input_tokens": 10, "output_tokens": 5}}}]
if rel:
for r in recs:
r["isSidechain"] = True
with path.open("a" if append else "w") as fh:
fh.write("\n".join(json.dumps(r) for r in recs) + "\n")
DEPS.indexer.scan_transcripts()
return ids.uid_for_rel(f"{PROJ}/{rel or sid + '.jsonl'}")
def cards() -> dict[str, dict]:
return {c["id"]: c for c in catalog._conversation_cards(DEPS, False)}
class CardCache(unittest.TestCase):
def setUp(self):
self.a = write("aaaaaaaa-0000-0000-0000-000000000001", OLD, "first")
self.b = write("bbbbbbbb-0000-0000-0000-000000000002", OLD, "second")
self.base = cards()
def test_a_version_bump_alone_rebuilds_nothing(self):
DEPS.store.summaries_version += 1
now = cards()
self.assertIs(now[self.a], self.base[self.a])
self.assertIs(now[self.b], self.base[self.b])
def test_a_write_remakes_only_its_own_card(self):
write("bbbbbbbb-0000-0000-0000-000000000002", OLD - 5, "more", append=True)
now = cards()
self.assertIs(now[self.a], self.base[self.a])
self.assertIsNot(now[self.b], self.base[self.b])
self.assertGreater(now[self.b]["messages"], self.base[self.b]["messages"])
def test_a_metadata_stamp_remakes_only_its_card(self):
DEPS.meta_store.update("aaaaaaaa-0000-0000-0000-000000000001",
{"title": "Renamed", "titleSource": "user"})
now = cards()
self.assertEqual(now[self.a]["title"], "Renamed")
self.assertIs(now[self.b], self.base[self.b])
def test_a_subagent_write_remakes_its_root(self):
write("aaaaaaaa-0000-0000-0000-000000000001", OLD,
rel="aaaaaaaa-0000-0000-0000-000000000001/subagents/agent-s1.jsonl")
now = cards()
self.assertEqual(now[self.a]["subagentCount"], 1)
self.assertGreater(now[self.a]["tokens"], self.base[self.a]["tokens"])
self.assertIs(now[self.b], self.base[self.b])
def test_a_live_card_follows_the_clock_a_settled_one_does_not(self):
live = write("cccccccc-0000-0000-0000-000000000003", LIVE, "running")
first = cards()
later = time.time() + catalog._CARDS_TIME_BUCKET_S + 1
with mock.patch("conversations.catalog.time.time", return_value=later):
now = cards()
self.assertIsNot(now[live], first[live]) # in the window: remade
self.assertIs(now[self.a], first[self.a]) # past it: kept
def test_the_cache_matches_a_cold_build(self):
write("bbbbbbbb-0000-0000-0000-000000000002", OLD - 5, "more", append=True)
DEPS.meta_store.update("aaaaaaaa-0000-0000-0000-000000000001", {"archived": True})
warm = json.dumps(sorted(cards().values(), key=lambda c: c["id"]), sort_keys=True)
for f in (False, True):
catalog._card_cache[f] = (None, {})
DEPS.store.summaries_version += 1
cold = json.dumps(sorted(cards().values(), key=lambda c: c["id"]), sort_keys=True)
self.assertEqual(warm, cold)
if __name__ == "__main__":
unittest.main()