Files
ai-agent/backend/test_parser_version.py
gabrielvidalandClaude Opus 5.5 25c7cd49e2 test(indexer): pin the parser-version tests at 46
They test the per-row upgrade mechanism (46 → a bump to 47) and read the
module's PARSER_VERSION as "the current one": the first real bump since
they were written (47) made eight of them fail. Each test now runs with
PARSER_VERSION patched to 46.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:50:10 +01:00

428 lines
21 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Per-row parser versions (``transcripts.parser_version``).
A ``PARSER_VERSION`` bump no longer wipes the store: every row keeps serving
its summary until the throttled upgrade pass re-parses it, most recently
active first; a container never re-parses a row a *newer* one wrote (the
blue-green overlap); the first start of this code stamps the existing rows
with the global version they were parsed at instead of re-parsing them; and
``MIN_SERVABLE_VERSION`` is the escape hatch for a change that can't be
served stale. Imports ``main`` against throwaway paths (no threads)."""
import datetime
import json
import os
import pathlib
import sqlite3
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)
from fastapi.testclient import TestClient # noqa: E402
import conversations # noqa: E402
import indexer as ix_mod # noqa: E402
import main # noqa: E402
from db import Store # noqa: E402
from indexer import Indexer # noqa: E402
DEPS = main.app.state.ai
_SEQ = iter(range(1, 10_000))
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 records(sid: str, ask: str, n: int = 2) -> list[dict]:
out = []
for _ in range(n):
i = next(_SEQ)
base = {"sessionId": sid, "timestamp": ago(600 - i)}
out.append({**base, "type": "user", "uuid": f"u{i}",
"message": {"role": "user", "content": f"{ask} {i}"}})
out.append({**base, "type": "assistant", "uuid": f"a{i}",
"message": {"role": "assistant", "id": f"m{i}",
"model": "claude-opus-5-5",
"content": [{"type": "tool_use", "id": f"t{i}", "name": "Bash",
"input": {"command": "ls"}}],
"usage": {"input_tokens": 10, "output_tokens": 5}}})
return out
def write(path: pathlib.Path, recs: list[dict], mtime: float | None = None,
append: bool = False) -> pathlib.Path:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a" if append else "w") as fh:
fh.write("".join(json.dumps(r) + "\n" for r in recs))
if mtime is not None:
os.utime(path, (mtime, mtime))
return path
class _Base(unittest.TestCase):
"""A fresh store + archive per test, and an indexer on them."""
def setUp(self):
self.root = pathlib.Path(tempfile.mkdtemp(dir=TMP))
self.arch = self.root / "arch"
self.db = str(self.root / "ix.db")
self.store = Store(self.db)
patch = mock.patch.object(ix_mod, "REPARSE_DUTY", 1.0) # no rests in tests
patch.start()
self.addCleanup(patch.stop)
# The mechanism is tested at the version it was written at (46 → a
# bump to 47), whatever PARSER_VERSION the code is at now.
pin = mock.patch.object(ix_mod, "PARSER_VERSION", 46)
pin.start()
self.addCleanup(pin.stop)
def indexer(self, store=None) -> Indexer:
return Indexer(store or self.store, self.root, None, self.arch,
lambda: [], lambda p: "")
def conv(self, name: str, ask: str, mtime: float) -> pathlib.Path:
return write(self.arch / "-home-x" / f"{name}.jsonl",
records(f"sid-{name}", ask), mtime=mtime)
class Migration(_Base):
def _old_db(self, path: str, meta: str | None) -> list[str]:
"""A store as the pre-per-row indexer left it: no parser_version
column, the global version in `meta`, summaries big enough to spill
into overflow pages."""
db = sqlite3.connect(path)
db.executescript(
"CREATE TABLE transcripts (path TEXT PRIMARY KEY, mtime REAL, size INTEGER,"
" skills_json TEXT, summary_json TEXT, search_json TEXT);"
"CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT);")
if meta is not None:
db.execute("INSERT INTO meta VALUES ('parser_version', ?)", (meta,))
paths = [f"/arch/c{i}.jsonl" for i in range(40)]
for i, p in enumerate(paths):
db.execute("INSERT INTO transcripts VALUES (?,?,?,?,?,?)",
(p, 1000.0 + i, 10 + i, "{}",
json.dumps({"title": f"t{i}", "pad": "x" * 9000}),
json.dumps([{"text": "y" * 9000}])))
db.commit()
db.close()
return paths
def test_existing_rows_take_the_global_version_they_were_parsed_at(self):
path = str(self.root / "old.db")
paths = self._old_db(path, "46")
s = Store(path)
book = s.all_transcripts()
self.assertEqual(sorted(book), sorted(paths))
self.assertEqual({r["parser_version"] for r in book.values()}, {46})
self.assertEqual(s.stale_transcripts(46), [])
self.assertEqual(len(s.stale_transcripts(47)), 40)
# Nothing hidden, nothing lost: every summary still served as it was.
self.assertEqual(len(s.all_summaries()), 40)
self.assertEqual(s.get_summary(paths[3])["title"], "t3")
# The meta row stays: an older image beside this one compares it to its
# own version and wipes the store on a mismatch.
self.assertEqual(s.get_meta("parser_version"), "46")
# That older image's insert names no version: it gets 46, its own.
s._db.execute("INSERT INTO transcripts (path, mtime, size, skills_json, "
"summary_json, search_json) VALUES ('/arch/new.jsonl', 1, 1, '{}', '{}', NULL)")
self.assertEqual(s.transcript_book("/arch/new.jsonl")["parser_version"], 46)
# A second start is a no-op.
self.assertEqual({r["parser_version"] for r in Store(path).all_transcripts().values()},
{46})
def test_the_bookkeeping_reads_never_touch_the_blobs(self):
path = str(self.root / "old.db")
self._old_db(path, "46")
s = Store(path)
for sql in ("SELECT path, mtime, size, parser_version FROM transcripts",
"SELECT path, mtime, size, parser_version FROM transcripts "
"WHERE parser_version < 47 ORDER BY mtime DESC",
"SELECT path, mtime, size, parser_version FROM transcripts "
"INDEXED BY transcripts_book WHERE path='x'"):
plan = " ".join(r[-1] for r in s._db.execute("EXPLAIN QUERY PLAN " + sql))
self.assertIn("COVERING INDEX transcripts_book", plan, sql)
def test_no_global_version_means_version_zero(self):
path = str(self.root / "old.db")
self._old_db(path, None)
s = Store(path)
self.assertEqual({r["parser_version"] for r in s.all_transcripts().values()}, {0})
def test_deploying_this_reparses_nothing(self):
"""The live store: rows written by the global-version indexer at 46,
files unchanged. The first sweep and the upgrade pass of this code
(also 46) parse none of them."""
for i, name in enumerate(("a", "b", "c")):
self.conv(name, f"ask {name}", 1_700_000_000 + i)
self.indexer().scan_transcripts()
# Turn the store back into the pre-per-row shape, as on the lab now.
old = str(self.root / "old.db")
db = sqlite3.connect(old)
db.executescript(
"CREATE TABLE transcripts (path TEXT PRIMARY KEY, mtime REAL, size INTEGER,"
" skills_json TEXT, summary_json TEXT, search_json TEXT);"
"CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT);"
"INSERT INTO meta VALUES ('parser_version', '46');")
db.execute(f"ATTACH DATABASE '{self.db}' AS cur")
db.execute("INSERT INTO transcripts SELECT path, mtime, size, skills_json, "
"summary_json, search_json FROM cur.transcripts")
db.commit()
db.close()
store = Store(old)
ix = self.indexer(store)
with mock.patch.object(Indexer, "_parse_summary") as sweep, \
mock.patch.object(conversations, "parse_conversation") as one_shot:
ix.scan_transcripts()
self.assertEqual(ix.upgrade_rows(), 0)
sweep.assert_not_called()
one_shot.assert_not_called()
self.assertEqual(len(store.all_summaries()), 3)
class Bump(_Base):
def setUp(self):
super().setUp()
now = time.time()
self.paths = {n: self.conv(n, f"ask {n}", now - 3600 + i * 60)
for i, n in enumerate(("old", "mid", "new"))}
self.indexer().scan_transcripts() # all rows at 46
def test_a_bump_keeps_serving_every_row_and_upgrades_newest_first(self):
before = {p: dict(s) for p, s in self.store.all_summaries()}
parsed: list[str] = []
real = conversations.parse_conversation
def spy(ap, full=True):
parsed.append(pathlib.Path(ap).stem)
return real(ap, full=full)
with mock.patch.object(ix_mod, "PARSER_VERSION", 47):
ix = self.indexer() # the new image's indexer
with mock.patch.object(Indexer, "_parse_summary") as sweep:
ix.scan_transcripts()
sweep.assert_not_called() # no wipe, no re-parse
self.assertEqual({p: dict(s) for p, s in self.store.all_summaries()}, before)
with mock.patch.object(conversations, "parse_conversation", side_effect=spy):
self.assertEqual(ix.upgrade_rows(), 3)
self.assertEqual(parsed, ["new", "mid", "old"])
self.assertEqual({r["parser_version"] for r in self.store.all_transcripts().values()},
{47})
self.assertEqual(ix.upgrade_rows(), 0)
self.assertEqual({p: dict(s) for p, s in self.store.all_summaries()}, before,
"same parser, same summaries")
def test_the_pass_stops_at_its_deadline(self):
with mock.patch.object(ix_mod, "PARSER_VERSION", 47):
ix = self.indexer()
self.assertEqual(ix.upgrade_rows(deadline=time.monotonic()), 0)
self.assertEqual(len(self.store.stale_transcripts(47)), 3)
def test_the_pass_rests_to_its_duty_cycle(self):
waits: list[float] = []
with mock.patch.object(ix_mod, "PARSER_VERSION", 47), \
mock.patch.object(ix_mod, "REPARSE_DUTY", 0.25):
ix = self.indexer()
real = ix._upgrade_one
def slow(row):
time.sleep(0.02)
return real(row)
with mock.patch.object(ix, "_upgrade_one", side_effect=slow), \
mock.patch.object(ix._stop, "wait", side_effect=waits.append):
self.assertEqual(ix.upgrade_rows(), 3)
self.assertEqual(len(waits), 3)
for w in waits: # 3× the time the file took at a quarter of a core
self.assertGreaterEqual(w, 0.06)
self.assertLess(w, 1.0)
def test_a_row_that_fails_to_parse_is_not_retried_every_pass(self):
real, calls = conversations.parse_conversation, []
def flaky(ap, full=True):
calls.append(pathlib.Path(ap).stem)
if pathlib.Path(ap).stem == "mid":
raise ValueError("a parser bug")
return real(ap, full=full)
with mock.patch.object(ix_mod, "PARSER_VERSION", 47), \
mock.patch.object(conversations, "parse_conversation", side_effect=flaky):
ix = self.indexer()
self.assertEqual(ix.upgrade_rows(), 2)
self.assertEqual(ix.upgrade_rows(), 0)
self.assertEqual(calls.count("mid"), 1)
# Once the file changes, the sweep parses it (at 47) like any other.
write(self.paths["mid"], records("sid-mid", "more", 1), append=True)
ix.scan_transcripts()
self.assertEqual(self.store.stale_transcripts(47), [])
def test_a_file_that_moved_is_left_to_the_sweep(self):
with mock.patch.object(ix_mod, "PARSER_VERSION", 47):
ix = self.indexer()
write(self.paths["new"], records("sid-new", "more", 1), append=True)
self.assertEqual(ix.upgrade_rows(), 2) # "new" skipped
self.assertEqual([r["path"] for r in self.store.stale_transcripts(47)],
[str(self.paths["new"])])
ix.scan_transcripts() # changed → parsed at 47
self.assertEqual(self.store.stale_transcripts(47), [])
self.assertEqual(self.store.get_summary(str(self.paths["new"]))["userTurns"], 3)
class NoDowngrade(_Base):
def test_only_rows_older_than_its_own_version_numerically(self):
a = self.conv("a", "ask a", 1_700_000_000)
b = self.conv("b", "ask b", 1_700_000_100)
c = self.conv("c", "ask c", 1_700_000_200)
for p, v in ((a, 100), (b, 9), (c, 46)):
st = p.stat()
self.store.upsert_transcript(str(p), st.st_mtime, st.st_size, {},
{"title": f"by v{v}"}, version=v)
# A string compare would get both wrong: "100" < "46" < "9".
self.assertEqual(self.indexer().upgrade_rows(), 1)
self.assertEqual(self.store.get_summary(str(a))["title"], "by v100")
self.assertNotEqual(self.store.get_summary(str(b))["title"], "by v9")
self.assertEqual(self.store.get_summary(str(c))["title"], "by v46")
self.assertEqual(self.store.transcript_book(str(a))["parser_version"], 100)
self.assertEqual(self.store.transcript_book(str(b))["parser_version"], 46)
def test_the_upgrade_write_is_a_compare_and_set(self):
p = self.conv("a", "ask a", 1_700_000_000)
st = p.stat()
self.store.upsert_transcript(str(p), st.st_mtime, st.st_size, {}, {"title": "v45"},
version=45)
self.assertFalse(self.store.upgrade_transcript(
str(p), st.st_mtime + 1, st.st_size, 46, {}, {"title": "x"})) # row moved
self.store.upsert_transcript(str(p), st.st_mtime, st.st_size, {}, {"title": "v47"},
version=47)
self.assertFalse(self.store.upgrade_transcript(
str(p), st.st_mtime, st.st_size, 46, {}, {"title": "x"})) # newer row
self.assertEqual(self.store.get_summary(str(p))["title"], "v47")
def test_blue_green_converges_without_ping_pong(self):
"""Old (46) and new (47) containers on one DB file, each with its own
store. The new one upgrades everything; the old one then re-parses
nothing; a live change the old one writes (at 46) is upgraded once."""
for i, n in enumerate(("a", "b", "c")):
self.conv(n, f"ask {n}", 1_700_000_000 + i)
old_store, new_store = Store(self.db), Store(self.db)
old, new = self.indexer(old_store), self.indexer(new_store)
with mock.patch.object(ix_mod, "PARSER_VERSION", 46):
old.scan_transcripts()
with mock.patch.object(ix_mod, "PARSER_VERSION", 47):
self.assertEqual(new.upgrade_rows(), 3)
with mock.patch.object(ix_mod, "PARSER_VERSION", 46):
self.assertEqual(old.upgrade_rows(), 0)
old.scan_transcripts() # unchanged files: nothing
write(self.arch / "-home-x" / "b.jsonl", records("sid-b", "more", 1), append=True)
old.scan_transcripts(only=["-home-x/b.jsonl"]) # a live change: written at 46
self.assertEqual(old.upgrade_rows(), 0)
self.assertEqual(len(new_store.stale_transcripts(47)), 1)
with mock.patch.object(ix_mod, "PARSER_VERSION", 47):
self.assertEqual(new.upgrade_rows(), 1)
self.assertEqual(new.upgrade_rows(), 0)
with mock.patch.object(ix_mod, "PARSER_VERSION", 46):
self.assertEqual(old.upgrade_rows(), 0)
class MinServable(_Base):
def test_rows_below_the_floor_are_reparsed_before_they_are_served(self):
for i, n in enumerate(("a", "b")):
self.conv(n, f"ask {n}", 1_700_000_000 + i)
self.indexer().scan_transcripts() # at 46
paths = sorted(p for p, _ in self.store.all_summaries())
with mock.patch.object(ix_mod, "PARSER_VERSION", 47), \
mock.patch.object(ix_mod, "MIN_SERVABLE_VERSION", 47):
ix = self.indexer()
self.assertEqual(self.store.all_summaries(), [])
self.assertEqual(self.store.all_search_msgs(), {})
self.assertEqual(self.store.search_msgs(paths), {})
ix.scan_transcripts() # unchanged files, re-parsed
self.assertEqual(len(self.store.all_summaries()), 2)
self.assertEqual(self.store.stale_transcripts(47), [])
self.assertEqual(sorted(self.store.search_msgs(paths)), paths)
def test_summaries_carry_no_search_msgs(self):
# They live in search_json: a reader wants Store.search_msgs.
self.conv("a", "ask a", 1_700_000_000)
self.indexer().scan_transcripts()
[(path, summary)] = self.store.all_summaries()
self.assertNotIn("searchMsgs", summary)
self.assertNotIn("searchMsgs", self.store.get_summary(path))
[msgs] = self.store.search_msgs([path, path, None]).values()
self.assertEqual(msgs[0]["role"], "user")
self.assertIn("ask a", msgs[0]["text"])
def _ancient(summary: dict) -> dict:
"""A summary as a parser of long ago wrote it: the core fields only, the
old bucket names (`bash`, `task`), none of what later versions added."""
keep = ("sessionId", "title", "model", "userTurns", "assistantTurns", "messages",
"tokens", "cost", "startedAt", "endedAt", "project", "cwd", "gitBranch")
out = {k: summary[k] for k in keep if k in summary}
out["byTool"] = {{"shell": "bash", "todo": "task"}.get(k, k): v
for k, v in (summary.get("byTool") or {}).items()}
out["title"] = "served stale"
return out
class StaleOverTheApi(unittest.TestCase):
"""A row an old parser wrote, served by the real routes while it waits."""
SID = "22222222-3333-4444-5555-666666666666"
CID = f"-home-x/{SID}.jsonl"
def setUp(self):
self.c = TestClient(main.app, headers={"x-internal-auth": "tok"})
self.path = write(TMP / "arch" / self.CID, records(self.SID, "hello", 3))
DEPS.indexer.scan_transcripts()
summary = dict(DEPS.store.get_summary(str(self.path)))
st = self.path.stat()
DEPS.store.upsert_transcript(str(self.path), st.st_mtime, st.st_size, {},
_ancient(summary), version=12)
def card(self, **params):
r = self.c.get("/api/conversations", params={"sessions": self.SID, **params})
self.assertEqual(r.status_code, 200, r.text)
[card] = r.json()["conversations"]
return card
def test_an_old_summary_is_served_until_upgraded(self):
card = self.card(full=1)
self.assertEqual(card["title"], "served stale")
self.assertIn("bash", card["byTool"]) # the frontend's normBucket folds it
r = self.c.get("/api/conversation-summary", params={"id": self.CID})
self.assertEqual(r.status_code, 200, r.text)
# The open thread is always a fresh parse, never the stored row.
d = self.c.get("/api/conversation", params={"id": self.CID})
self.assertEqual(d.status_code, 200, d.text)
self.assertNotEqual(d.json()["title"], "served stale")
self.assertEqual(d.json()["userTurns"], 3)
with mock.patch.object(ix_mod, "REPARSE_DUTY", 1.0):
self.assertGreaterEqual(DEPS.indexer.upgrade_rows(), 1)
card = self.card(full=1)
self.assertNotEqual(card["title"], "served stale")
self.assertIn("shell", card["byTool"])
self.assertNotIn("bash", card["byTool"])
if __name__ == "__main__":
unittest.main()