"""Temporal memory experiment — 20 questions over statements that replaced each other. The question this answers ------------------------- Can Epimneme hold A -> B -> C and answer four different things from it? current "How do we deploy?" -> C, and never A or B historical "How did we deploy in 2021?" -> A transition "When did we stop doing A?" -> the statement that replaced it, with its date evolution "How has deployment changed?" -> A, B, C in order Retrieval only, scored on memory ids: no reader model, no judge, so a run is seconds and a result cannot be an artefact of a prompt. Three arms, in this order ------------------------- 1. ``--control`` against today's server. It has ``supersedes`` and nothing else, so `current` should pass and the other three cannot. This is the number the extension has to beat, and it confirms the harness can fail. 2. Hand-authored chains (the fixture as written) against a server with the contract below. This is the CEILING: if the data model cannot answer the questions when every link is correct, stop — extraction is irrelevant. 3. ``--links extracted.json``: an agent reads the raw threads and produces the same file shape; you read every memory it wrote and give each a ``gold_key`` naming the hand-authored statement it corresponds to (or none). The harness then scores its supersession edges against yours. This is the real experiment: a wrong edge silently replaces the truth. Decide before running (arm 2, then arm 3 against the same bars) -------------------------------------------------------------- current 5/5 in the top 3, and 0 stale statements anywhere in a top-5 historical >= 4/5 in the top 3, and 0 statements from another era in a top-5 transition >= 4/5 in the top 3, each carrying the right date evolution 5/5 complete chains in order arm 3 edges 0 wrong edges; a missing edge is a miss, a wrong one is damage The bundled fixture is synthetic. Passing it proves the plumbing. The hypothesis is only tested by a topic whose real history you know. Server contract this harness assumes (none of it exists yet) ----------------------------------------------------------- POST /api/sources {connector, external_id, title?, uri?, occurred_at?, content?} -> {id, status: created|unchanged|updated} POST /api/memories + valid_from, + sources: [{source_id, quote}], + superseded_by (store an OLDER statement under an existing newer one — history arriving backwards) DELETE /api/memories/{id}?reason=... -> invalidated_reason 'retracted' GET /api/memories/search + as_of=YYYY-MM-DD statements valid on that day + history=true current + superseded rows carry valid_from, supersedes, superseded_by GET /api/memories/{id}/chain -> {chain: [oldest ... newest]} ``as_of`` and ``history`` never return retracted, decayed or merged rows: history is what was once true, not what was once stored. ``as_of`` is passed explicitly. Turning "in 2021" into a date is the asking agent's job and is NOT tested here. Usage ----- python benchmarks/temporal_bench.py --token ... --control python benchmarks/temporal_bench.py --token ... python benchmarks/temporal_bench.py --token ... --order reverse python benchmarks/temporal_bench.py --links extracted.json (offline) """ from __future__ import annotations import argparse import asyncio import json import os import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from epimneme_client import EngramClient # noqa: E402 TYPES = ("current", "historical", "transition", "evolution") TOP_K = 5 # depth checked for stale statements GOLD_K = 3 # depth the right statement must appear within # ── HTTP (the client has no methods for the new endpoints yet) ─────────────── async def _call(client: EngramClient, method: str, path: str, **kw) -> dict: session = await client._ensure_session() async with session.request(method, f"{client.base_url}{path}", **kw) as resp: text = await resp.text() if resp.status >= 400: hint = " (endpoint missing: this server predates the temporal contract)" if resp.status in (404, 405) else "" raise SystemExit(f"{method} {path} -> {resp.status}: {text[:300]}{hint}") return json.loads(text) async def search(client, query, project, *, as_of=None, history=False, limit=TOP_K) -> list[dict]: params = {"query": query, "project": project, "limit": limit, "update_access": "false"} if as_of: params["as_of"] = as_of if history: params["history"] = "true" return (await _call(client, "GET", "/api/memories/search", params=params)).get("results", []) # ── Ingest ─────────────────────────────────────────────────────────────────── def ingest_order(memories: list[dict], order: str) -> list[dict]: """Chronological by valid_from, or reversed — newest first, as a backfill arrives.""" ordered = sorted(memories, key=lambda m: m.get("valid_from") or "") return ordered[::-1] if order == "reverse" else ordered async def ingest(client, fixture: dict, project: str, *, order: str, control: bool) -> dict[str, str]: """Store the fixture. Returns {memory key -> server id}.""" source_ids: dict[str, str] = {} if not control: for s in fixture.get("sources", []): body = {k: v for k, v in s.items() if k != "key"} source_ids[s["key"]] = (await _call(client, "POST", "/api/sources", json=body))["id"] successor_of = {m["supersedes"]: m["key"] for m in fixture["memories"] if m.get("supersedes")} ids: dict[str, str] = {} for m in ingest_order(fixture["memories"], order): body = {"content": m["content"], "kind": m.get("kind", "fact"), "project": project} if m.get("subject"): body["subject"] = m["subject"] # Link to whichever end of the edge is already stored. if m.get("supersedes") in ids: body["supersedes"] = ids[m["supersedes"]] if not control: body["valid_from"] = m.get("valid_from") body["sources"] = [ {"source_id": source_ids[s["source"]], "quote": s.get("quote")} for s in m.get("sources", []) ] if successor_of.get(m["key"]) in ids: body["superseded_by"] = ids[successor_of[m["key"]]] resp = await _call(client, "POST", "/api/memories", json=body) if "id" not in resp: # Dedup rejecting a superseding statement is itself a finding: # "we do Y now" was judged the same as "we do X". raise RuntimeError(f"memory {m['key']} was not stored: {resp}") ids[m["key"]] = resp["id"] for m in fixture["memories"]: if m.get("retract"): await _call(client, "DELETE", f"/api/memories/{ids[m['key']]}", params={"reason": m["retract"]}) return ids async def preflight(client, project: str) -> None: """Refuse a server that ignores `as_of`. FastAPI drops unknown query parameters silently, so an old server would answer every historical question with current rows and the table would read as a clean failure of the model rather than of the deployment. """ rows = await search(client, "deploy", project, as_of="1900-01-01") if rows: raise SystemExit( "server returned rows for as_of=1900-01-01: it is ignoring `as_of`.\n" "Deploy a build with the temporal contract, or pass --control." ) # ── Scoring ────────────────────────────────────────────────────────────────── def score_ranked(q: dict, ranked_keys: list[str | None], dates: dict[str, str | None]) -> dict: """Score current / historical / transition from a ranked list of memory keys.""" gold, forbid = q.get("gold", []), set(q.get("forbid", [])) stale = [k for k in ranked_keys[:TOP_K] if k in forbid] if q["type"] == "transition": hit = bool(gold) and gold[0] in ranked_keys[:GOLD_K] dated = hit and dates.get(gold[0]) == q["_gold_date"] return {"pass": hit and dated, "stale": stale, "note": "" if dated or not hit else "found, wrong or missing date"} hit = (not gold) or gold[0] in ranked_keys[:GOLD_K] return {"pass": hit and not stale, "stale": stale, "note": ""} async def run_question(client, q: dict, project: str, key_of: dict[str, str], control: bool) -> dict: kind = q["type"] rows = await search( client, q["query"], project, as_of=None if control else q.get("as_of"), history=(not control) and kind in ("transition", "evolution"), ) ranked = [key_of.get(r["id"]) for r in rows] if kind == "evolution": chain: list[str | None] = [] if rows and not control: body = await _call(client, "GET", f"/api/memories/{rows[0]['id']}/chain") chain = [key_of.get(c["id"]) for c in body.get("chain", [])] return {"pass": chain == q["gold"], "stale": [], "note": f"chain={chain}", "ranked": ranked} dates = {key_of.get(r["id"]): (r.get("valid_from") or "")[:10] or None for r in rows} return {**score_ranked(q, ranked, dates), "ranked": ranked} def report(rows: list[dict]) -> None: print(f"\n{'id':<4} {'type':<11} {'ok':<4} top-{TOP_K} (keys) / note") for r in rows: mark = "PASS" if r["pass"] else "FAIL" extra = f" STALE {r['stale']}" if r["stale"] else "" print(f"{r['id']:<4} {r['type']:<11} {mark:<4} {r['ranked']}{extra} {r['note']}") print() for t in TYPES: sub = [r for r in rows if r["type"] == t] if sub: stale = sum(1 for r in sub if r["stale"]) print(f"{t:<11} {sum(r['pass'] for r in sub)}/{len(sub)} stale-in-top-{TOP_K}: {stale}") print(f"{'total':<11} {sum(r['pass'] for r in rows)}/{len(rows)}") # ── Arm 3: are the extractor's supersession edges the right ones? ──────────── def score_links(gold: dict, extracted: dict) -> int: """Compare supersession edges. Returns the number of wrong edges.""" gold_edges = {(m["supersedes"], m["key"]) for m in gold["memories"] if m.get("supersedes")} to_gold = {m["key"]: m.get("gold_key") for m in extracted["memories"]} unmapped = sorted(k for k, g in to_gold.items() if not g) pred_edges, wrong = set(), [] for m in extracted["memories"]: if not m.get("supersedes"): continue edge = (to_gold.get(m["supersedes"]), to_gold.get(m["key"])) if edge in gold_edges: pred_edges.add(edge) else: wrong.append((m["supersedes"], m["key"], edge)) missing = sorted(gold_edges - pred_edges) n_pred = len(pred_edges) + len(wrong) print(f"gold edges {len(gold_edges)} extracted edges {n_pred}") print(f"precision {len(pred_edges)}/{n_pred} recall {len(pred_edges)}/{len(gold_edges)}") for old, new, edge in wrong: print(f" WRONG {old} -> {new} (maps to {edge[0]} -> {edge[1]})") for old, new in missing: print(f" missing {old} -> {new}") covered = {g for g in to_gold.values() if g} for k in sorted({m["key"] for m in gold["memories"]} - covered): print(f" not extracted {k}") if unmapped: print(f" no gold_key (extra statements, read them): {unmapped}") return len(wrong) # ── Main ───────────────────────────────────────────────────────────────────── async def run(args, fixture: dict) -> int: client = EngramClient(base_url=args.engram_url, token=args.token) try: if not args.no_cleanup: await client.clear_project(args.project) ids = await ingest(client, fixture, args.project, order=args.order, control=args.control) if not args.control: await preflight(client, args.project) key_of = {v: k for k, v in ids.items()} valid_from = {m["key"]: m.get("valid_from") for m in fixture["memories"]} rows = [] for q in fixture["questions"]: q = {**q, "_gold_date": valid_from.get(q["gold"][0]) if q.get("gold") else None} rows.append({"id": q["id"], "type": q["type"], **await run_question(client, q, args.project, key_of, args.control)}) print(f"arm: {'control (today)' if args.control else 'temporal'} ingest order: {args.order}") report(rows) if args.out: Path(args.out).write_text("".join(json.dumps(r) + "\n" for r in rows)) return 0 if all(r["pass"] for r in rows) else 1 finally: if not args.no_cleanup: await client.clear_project(args.project) await client.close() def main() -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("--fixture", default="benchmarks/data/test_temporal_fixture.json") ap.add_argument("--engram-url", default="http://localhost:8000") ap.add_argument("--token", default=os.environ.get("EPIMNEME_TOKEN", "")) ap.add_argument("--project", default="_temporal", help="Scratch project; it is cleared before and after. The key must be scoped to it.") ap.add_argument("--order", choices=("chrono", "reverse"), default="chrono", help="reverse = newest statement stored first, as when old threads are backfilled") ap.add_argument("--control", action="store_true", help="Today's API only: supersedes, no dates") ap.add_argument("--links", default="", help="Extracted corpus to score against the fixture's edges (offline)") ap.add_argument("--out", default="", help="Write per-question rows as JSONL") ap.add_argument("--no-cleanup", action="store_true") args = ap.parse_args() fixture = json.loads(Path(args.fixture).read_text()) counts = {t: sum(1 for q in fixture["questions"] if q["type"] == t) for t in TYPES} if args.links: return 1 if score_links(fixture, json.loads(Path(args.links).read_text())) else 0 print(f"{len(fixture['memories'])} memories, {len(fixture['questions'])} questions {counts}") return asyncio.run(run(args, fixture)) if __name__ == "__main__": sys.exit(main())