Files
mempalace/tests/test_backfill_authored_at.py
T
cff43adb63 feat(convo): preserve authored timestamp from transcripts (#1890)
* feat(convo): preserve authored timestamp from transcripts

Conversation drawers only carried `filed_at` (ingest time), so a bulk
re-mine collapsed every drawer to a single instant and the chronological
signal was lost — even though each Claude Code / Codex JSONL line already
carries an ISO-8601 `timestamp`. The recency-window fallback and any
date-aware consumer then saw ingest order, not when content was written.

- convo_miner: derive `authored_at` (per-file max line `timestamp`) and
  store it as drawer metadata; falls back to `filed_at` when absent
- searcher: surface `authored_at` in search results, and break exact
  hybrid-score ties toward the more recently authored drawer (ISO strings
  sort chronologically; missing dates sort oldest) — benchmark-neutral as
  it only reorders exact ties
- tests: cover `_extract_authored_at` (latest wins, skips/tolerates lines
  without timestamps, non-jsonl/missing -> None) and the tie-break

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(search): surface authored_at in CLI + backfill for existing data

Completes the authored_at work so the field is visible end-to-end and
existing palaces can adopt it without re-mining.

- layers: CLI `search` output shows an `authored:` date line per result
  (peer of the existing date; markdown drawers fall back to filed_at)
- scripts/backfill_authored_at.py: in-place migration that stamps
  authored_at on convos drawers from their source transcripts — metadata
  only (no re-embedding), idempotent, dry-run by default
- docs/authored-at.md: documents created_at (ingest) vs authored_at
  (written) and both backfill paths (in-place / drop-and-recreate)
- tests: backfill integration tests over an ephemeral ChromaDB collection

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(search): address review — non-string timestamp guard + top-level authored_at tiebreak

Two correctness fixes from the PR review:

- _extract_authored_at: only compare when the parsed `timestamp` is a str.
  A non-string timestamp on a malformed/foreign JSONL line previously raised
  TypeError outside the try and could crash the mine.
- _hybrid_rank: the tie-break read `authored_at` only from nested `metadata`,
  but the search_memories path (MCP / Claude Code) carries it at the top level
  of each hit — so the tie-break silently no-op'd there. Read both shapes.
- tests: non-string timestamp cases, and a top-level-shape tie-break test
  (which fails before this fix).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* style: apply ruff format to authored_at changes

CI ruff format --check flagged 4 files; ruff check already passed.
Formatting only — no behavior change.

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Igor Lins e Silva <4753812+igorls@users.noreply.github.com>
2026-06-28 18:13:06 -03:00

87 lines
3.2 KiB
Python

"""Integration tests for the authored_at backfill migration (scripts/)."""
import importlib.util
import uuid
from pathlib import Path
import chromadb
# The migration ships as a script, not a package module; load it directly.
_SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "backfill_authored_at.py"
_spec = importlib.util.spec_from_file_location("backfill_authored_at", _SCRIPT)
backfill_mod = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(backfill_mod)
def _collection():
# Unique name per call: EphemeralClient shares one in-memory instance across the
# process, so a fixed collection name would leak drawers between tests.
client = chromadb.EphemeralClient()
return client.create_collection(f"drawers_{uuid.uuid4().hex}")
def _add(col, drawer_id, source_file, authored_at=None):
meta = {"ingest_mode": "convos", "source_file": source_file, "filed_at": "2026-06-27T00:00:00"}
if authored_at is not None:
meta["authored_at"] = authored_at
col.add(ids=[drawer_id], documents=["hello"], metadatas=[meta], embeddings=[[0.1, 0.2, 0.3]])
def _transcript(dir_path, name, *timestamps):
dir_path.mkdir(parents=True, exist_ok=True)
f = dir_path / name
f.write_text("".join(f'{{"timestamp": "{ts}"}}\n' for ts in timestamps))
return f
def test_backfill_sets_latest_timestamp(tmp_path):
sessions = tmp_path / "claude"
_transcript(sessions, "abc.jsonl", "2026-06-10T08:00:00.000Z", "2026-06-12T09:00:00.000Z")
col = _collection()
# Stored source_file uses an old mount prefix; resolution is by basename.
_add(col, "d1", "/old/mount/abc.jsonl")
stats = backfill_mod.backfill_authored_at(col, [str(sessions)], apply=True)
assert stats["scanned"] == 1
assert stats["updated"] == 1
got = col.get(ids=["d1"], include=["metadatas"])["metadatas"][0]
assert got["authored_at"] == "2026-06-12T09:00:00.000Z"
def test_dry_run_writes_nothing(tmp_path):
sessions = tmp_path / "claude"
_transcript(sessions, "abc.jsonl", "2026-06-12T09:00:00.000Z")
col = _collection()
_add(col, "d1", "/old/mount/abc.jsonl")
stats = backfill_mod.backfill_authored_at(col, [str(sessions)], apply=False)
assert stats["updated"] == 1 # would update
assert "authored_at" not in col.get(ids=["d1"], include=["metadatas"])["metadatas"][0]
def test_idempotent_second_run_updates_nothing(tmp_path):
sessions = tmp_path / "claude"
_transcript(sessions, "abc.jsonl", "2026-06-12T09:00:00.000Z")
col = _collection()
_add(col, "d1", "/old/mount/abc.jsonl")
backfill_mod.backfill_authored_at(col, [str(sessions)], apply=True)
stats2 = backfill_mod.backfill_authored_at(col, [str(sessions)], apply=True)
assert stats2["updated"] == 0
def test_unresolved_transcript_is_left_alone(tmp_path):
sessions = tmp_path / "claude"
sessions.mkdir()
col = _collection()
_add(col, "d1", "/old/mount/missing.jsonl") # no file on disk
stats = backfill_mod.backfill_authored_at(col, [str(sessions)], apply=True)
assert stats["updated"] == 0
assert stats["unresolved_files"] == 1
assert "authored_at" not in col.get(ids=["d1"], include=["metadatas"])["metadatas"][0]