diff --git a/Makefile b/Makefile index 74dabf9df0..1f38aa7109 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: bootstrap dev dev-cloud down down-all migrate migrate-status migrate-dry schema-dump schema-check bench-matrix server frontend-build frontend-dev init onboard test test-unit test-integration test-sdk-adapters test-mixed-version test-unit-cov ingest bench bench-quick bench-algorithm-gate bench-quality-gate bench-code-intel-dry bench-code-portability-dry bench-code-intel bench-code-legs bench-clickgap-replay lint format format-check typecheck mypy-gate install clean bench-clickgap-golden +.PHONY: bootstrap dev dev-cloud down down-all migrate migrate-status migrate-dry schema-dump schema-check bench-matrix server frontend-build frontend-dev init onboard test test-unit test-integration test-sdk-adapters test-mixed-version test-unit-cov ingest bench bench-quick bench-algorithm-gate bench-quality-gate bench-revision bench-revision-dry bench-code-intel-dry bench-code-portability-dry bench-code-intel bench-code-legs bench-clickgap-replay lint format format-check typecheck mypy-gate install clean bench-clickgap-golden # Interpreter for the python-invoking targets: the local .venv, which CI also # builds from uv.lock (`uv sync --locked`). @@ -271,6 +271,42 @@ bench-quality-gate: --min-recall $(or $(MIN_RECALL),0.80) \ --out /tmp/loom_quality_gate_$$(date +%s).csv +# Corrections and time: four harnesses on one generated corpus, the episodes of +# bench/pi_llm.py. A real-provider run, never CI: the defaults write 400 +# namespaces and send 4,200 memory.ask calls. +# make bench-revision EPISODES=5 # what ran, before the full run +# make bench-revision OUT=/tmp/revision ORG=dev DEPTHS=1,2,5,10 REPEATS=3 +# The legs run in one shell that continues past a leg with failed cases and +# exits non-zero at the end if any leg did. pi_llm.py and fama_forgetting.py +# call the server (LOOM_BASE_URL, and an org-admin LOOM_API_KEY for the +# erasure); models_used, forget_switch_eval.py and the audit inside pi_llm.py +# read the server's .env at the repository root. The audit's judge needs +# OPENAI_API_KEY: pi_llm.py exits 2 before its first write without it. +REVISION_DEPTHS = 1,2,5,10 +REVISION_PI_LLM = bench/pi_llm.py --namespace bench-revision \ + --kinds current,current_2hop,asof,asof_2hop \ + --depths $(or $(DEPTHS),$(REVISION_DEPTHS)) --episodes $(or $(EPISODES),100) \ + --repeats $(or $(REPEATS),3) --gate --gate-min-delta -4 + +bench-revision: + @out=$(or $(OUT),/tmp/loom_revision_$$(date +%s)); mkdir -p $$out; rc=0; \ + $(BENCH_PYTHON) -m bench.models_used --out $$out/models.json || rc=1; \ + $(BENCH_PYTHON) $(REVISION_PI_LLM) \ + --base-url $(or $(LOOM_BASE_URL),http://localhost:7777) --org $(or $(ORG),dev) \ + --out $$out/pi_llm.jsonl --audit-out $$out/supersession_audit.json || rc=1; \ + $(BENCH_PYTHON) bench/fama_forgetting.py \ + --base-url $(or $(LOOM_BASE_URL),http://localhost:7777) --org $(or $(ORG),dev) \ + --episodes $(or $(EPISODES),100) --out $$out/fama_forgetting.csv || rc=1; \ + $(BENCH_PYTHON) bench/forget_switch_eval.py --corpus-episodes $(or $(EPISODES),100) \ + --runs $(or $(REPEATS),3) --out $$out/forget_switch_eval.json || rc=1; \ + echo "bench-revision: artifacts in $$out"; exit $$rc + +# The pi_llm.py leg with scripted readers in place of the server: the flags, +# the scorer, the gate and the artifact writer, offline. +bench-revision-dry: + @out=$(or $(OUT),/tmp/loom_revision_dry_$$(date +%s)); mkdir -p $$out; \ + $(BENCH_PYTHON) $(REVISION_PI_LLM) --dry --out $$out/pi_llm.jsonl + # Code-intelligence gates (real-provider deployment; NEVER CI — the CI # embedder is fake, and a green gate on fake embeddings is worse than none). bench-code-intel-dry: diff --git a/bench/README.md b/bench/README.md index 8b5eb2a3cc..a55d4615fc 100644 --- a/bench/README.md +++ b/bench/README.md @@ -132,7 +132,13 @@ built from it is right. - **`perltqa.py`** — PerLTQA: per-character memory banks, anchor reproduction, reference recall and an optional correctness judge. - **`pi_llm.py`** — proactive interference: an attribute updated n times, - then asked for its current value; reports the stale-retrieval rate. + then asked for its value; reports the stale-retrieval rate. `--kinds` adds + a question that needs two facts (the project's owning team, then the latest + update) and both questions as of the day of an earlier update; `--gate` + pairs one-fact with two-fact questions inside an episode; `--out` writes + every answer; `--dry` checks the scorer offline. `make bench-revision` runs + it with `fama_forgetting.py`, `forget_switch_eval.py` and the supersession + audit on the one generated corpus. - **`dialogue_consistency.py`** — a dialogue run autoregressively through `memory.ask`, each turn graded by an entailment judge (`bench/rubrics/entailment.md`); consistency by turn index. @@ -160,7 +166,8 @@ built from it is right. - **`okf_roundtrip.py`** — export a namespace as an OKF bundle, import it into a fresh namespace, and measure what was lost. - **`forget_switch_eval.py`** — forget / switch / correction cases - through `set_from_messages`. + through `set_from_messages`; `--corpus-episodes N` appends one switch case + per episode of `pi_llm.py`'s corpus. External harnesses with loom plugged in live in their own folders: `memoryarena/` (MemoryArena's gym; see its README) and `memorydata/` @@ -181,6 +188,8 @@ External harnesses with loom plugged in live in their own folders: resolver by arithmetic. - **`supersession_audit.py`** — what each supersession did to the fact (restates, extends, corrects, …), from `loom.memory_versions`. + `--namespace` repeats; `pi_llm.py --audit-out` runs it on a run's + namespaces before they are erased. Rates are null when no key was rewritten. - **`conflict_resolver_long_session.py`** — one user's twelve sessions in a `newest_wins` namespace, against a server with the conflict resolver on and one with it off: the share of changing attributes left with one live value, @@ -190,6 +199,8 @@ External harnesses with loom plugged in live in their own folders: - **`fama_forgetting.py`**, **`mutation_sequence.py`**, **`temporal_assertions.py`** — bi-temporal invariants: a closed validity interval is never surfaced after it closes and stays queryable inside it. + `fama_forgetting.py --episodes N` checks the first two updates of N + episodes of `pi_llm.py`'s corpus. ## Agents, operations and cost @@ -418,6 +429,7 @@ Langfuse's run-comparison view shows which queries moved. Details: | Does the memory guidance leave a clean namespace? | `skill_eval.py` (graded by `namespace.audit`) | | Did I just regress cross-tool retrieval? | `cross_tool_validate.py` (fast, 6 queries) | | Did the extractor write what the turns say, and every gold turn? | `memory_integrity.py` (MI + FMR via `memory.evidence`) | +| Does a corrected fact stay current when the question needs a second fact? | `make bench-revision` (`make bench-revision-dry` for the offline check) | | Does aggregation still work? | `aggregate.py` | | Does a coding agent get the right answer and reuse prior fixes? | `coding_agent_qa.py` (`--dry` for the offline gate) | | Does write/search latency degrade at scale? | `locomo.py` | diff --git a/bench/fama_forgetting.py b/bench/fama_forgetting.py index 441e2eebac..3763d90e70 100644 --- a/bench/fama_forgetting.py +++ b/bench/fama_forgetting.py @@ -22,6 +22,11 @@ the live extractor would. Use single-valued relations only (`works_at`, `lives_in`, …) or the closure won't fire. +Cases: the two inline ones, or with `--episodes N` the first two updates of N +episodes of `bench/pi_llm.py`'s generated corpus (`corpus_cases`), written +under `module_status`, which the `_status` suffix makes single-valued. +`--org` names the org the namespaces are minted in (default `dev`). + Run (needs a live control plane + CH): python bench/fama_forgetting.py --base-url http://localhost:7777 \ --token "$LOOM_API_KEY" --out bench/fama_forgetting.csv @@ -36,11 +41,13 @@ import time import uuid from dataclasses import dataclass +from datetime import date, timedelta from pathlib import Path from typing import Any import httpx +from bench import pi_llm from bench._http import post_json from bench.bench_namespaces import ( erase_on_exit_sync, @@ -93,6 +100,38 @@ class ForgetCase: ), ] +# The generated corpus's attribute as a relation. Single-valued by the +# `_status` suffix rule (`is_single_valued_relation`), so update 1 closes +# update 0's interval. +CORPUS_RELATION = "module_status" + + +def corpus_cases(n: int) -> list[ForgetCase]: + """Updates 0 and 1 of the first `n` episodes of `pi_llm`'s corpus, one case + each: read at noon of update 0's day (inside its interval) and the day + after update 1 (after the close). The subject is the entity in lower case, + as the triple stores it.""" + cases = [] + for ep in range(n): + entity = pi_llm.entity_of(ep) + old, new = pi_llm._val(ep, 0), pi_llm._val(ep, 1) + opened, _ = pi_llm.update_text(entity, 0, old) + closed, _ = pi_llm.update_text(entity, 1, new) + cases.append( + ForgetCase( + case_id=f"corpus-e{ep}", + subject=entity.lower(), + relation=CORPUS_RELATION, + old_object=old, + new_object=new, + opened_at=opened, + closed_at=closed, + as_of_within=f"{opened}T12:00:00", + as_of_after=(date.fromisoformat(closed) + timedelta(days=1)).isoformat(), + ) + ) + return cases + def _post( client: httpx.Client, base_url: str, op: str, body: dict[str, Any], token: str @@ -173,16 +212,17 @@ def run_case( base_url: str, token: str, case: ForgetCase, + org: str, ) -> list[dict[str, str]]: namespace = f"bench-fama-{uuid.uuid4().hex[:10]}" - remember_bench_namespace("dev", namespace) + remember_bench_namespace(org, namespace) register_bench_namespace_sync( lambda p, b: _post(client, base_url, p.removeprefix("/v1/"), b, token), - org="dev", + org=org, namespace=namespace, description="forgetting case", ) - identity = {"org": "dev", "namespace": namespace, "agent": "fama-bench"} + identity = {"org": org, "namespace": namespace, "agent": "fama-bench"} # 1. Open the old fact, then close it by writing the contradicting # new fact dated at closed_at. The new write closes the prior open @@ -281,9 +321,18 @@ def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--base-url", default="http://localhost:7777") parser.add_argument("--token", default="") + parser.add_argument("--org", default="dev") + parser.add_argument( + "--episodes", + type=int, + default=0, + help="run the first N episodes of pi_llm's generated corpus, one case each; " + "0 = the two inline cases", + ) parser.add_argument("--out", default="bench/fama_forgetting.csv") args = parser.parse_args() token = args.token or os.environ.get("LOOM_API_KEY", "") + cases = corpus_cases(args.episodes) if args.episodes else CASES out_rows: list[dict[str, str]] = [] with httpx.Client() as client: @@ -294,10 +343,10 @@ def main() -> int: # Each case's namespace is erased when the run exits, after a failure too. with erase_on_exit_sync( lambda p, b: _post(client, args.base_url, p.removeprefix("/v1/"), b, token), - org="dev", + org=args.org, ): - for case in CASES: - out_rows.extend(run_case(client, args.base_url, token, case)) + for case in cases: + out_rows.extend(run_case(client, args.base_url, token, case, args.org)) out_path = Path(args.out) out_path.parent.mkdir(parents=True, exist_ok=True) diff --git a/bench/forget_switch_eval.py b/bench/forget_switch_eval.py index a4630b4b00..3a5e75a307 100644 --- a/bench/forget_switch_eval.py +++ b/bench/forget_switch_eval.py @@ -14,6 +14,11 @@ unless the user asked to forget it); - a pure forget does not re-store what it forgot (`not_written`, whole words). +The hand-written cases share the stored rows of `EXISTING`. `--corpus-episodes N` +appends one `corpus_switch` case per episode of `bench/pi_llm.py`'s generated +corpus (`corpus_cases`): the stored row is update 0, the turn is update 1's +sentence, the new value must be written and only the stored row may be retired. + Usage (inside a server container, a copy of the tree under test first on sys.path): python bench/forget_switch_eval.py --tier compact --runs 2 """ @@ -30,6 +35,11 @@ from dataclasses import dataclass, field from typing import Any +try: + from bench import pi_llm +except ModuleNotFoundError: # `python bench/forget_switch_eval.py` puts bench/ on sys.path + import pi_llm # type: ignore[no-redef] + EXISTING: list[dict[str, str]] = [ {"memory_key": "user_editor", "value": "User prefers Neovim."}, {"memory_key": "user_deploy_day", "value": "User deploys on Tuesdays."}, @@ -58,6 +68,9 @@ class Case: must_retire: set[str] = field(default_factory=set) may_retire: set[str] = field(default_factory=set) not_written: list[str] = field(default_factory=list) + # The rows stored before the turns: what extraction sees as existing + # memories, and the only keys whose retirement is scored. + existing: list[dict[str, str]] = field(default_factory=lambda: EXISTING) def _u(t: str) -> tuple[str, str]: @@ -381,6 +394,35 @@ def _a(t: str) -> tuple[str, str]: ] +def corpus_cases(n: int) -> list[Case]: + """One `corpus_switch` case per episode of `pi_llm`'s corpus: update 0 is + the stored row and update 1's sentence is the turn. The new value must be + written. Its token is matched as its two parts, since `_words` turns the + hyphen into a space and the whole token never matches. The update names no + request to forget, so the stored row may be retired and nothing else.""" + cases = [] + for ep in range(n): + entity = pi_llm.entity_of(ep) + new = pi_llm._val(ep, 1) + key = f"{entity.lower()}_assigned_module" + cases.append( + Case( + name=f"corpus_e{ep}", + kind="corpus_switch", + turns=[_u(pi_llm.update_text(entity, 1, new)[1])], + must_write=[new.split("-")], + may_retire={key}, + existing=[ + { + "memory_key": key, + "value": pi_llm.update_text(entity, 0, pi_llm._val(ep, 0))[1], + } + ], + ) + ) + return cases + + def _words(text: str) -> str: return " " + re.sub(r"[^a-z0-9:$]+", " ", text.lower()) + " " @@ -400,7 +442,7 @@ def score(case: Case, retired: set[str], written: list[dict[str, str]]) -> tuple for k in case.must_retire - retired: why.append(f"not retired {k}") extra = retired - case.must_retire - case.may_retire - extra = {k for k in extra if k in {e["memory_key"] for e in EXISTING}} + extra = {k for k in extra if k in {e["memory_key"] for e in case.existing}} if extra: why.append(f"over-retired {sorted(extra)}") for word in case.not_written: @@ -465,7 +507,7 @@ async def run_case(case: Case, tier: str) -> dict[str, Any]: agent="forget-switch-eval", messages=[{"role": r, "content": t} for r, t in case.turns], observation_date="2026-09-24", - existing_memories=[dict(e) for e in EXISTING], + existing_memories=[dict(e) for e in case.existing], llm_cache=False, ) t0 = time.monotonic() @@ -505,6 +547,13 @@ async def main() -> int: ap.add_argument("--runs", type=int, default=2) ap.add_argument("--out", default="") ap.add_argument("--only", default="") + ap.add_argument( + "--corpus-episodes", + type=int, + default=0, + help="append one corpus_switch case for each of the first N episodes of " + "pi_llm's generated corpus", + ) ap.add_argument("--concurrency", type=int, default=6) args = ap.parse_args() from server.core.ch import get_client @@ -513,7 +562,11 @@ async def main() -> int: await get_client().connect() if args.tier == "full": settings.memory_extract_compact_prompt_max_chars = 0 - cases = [c for c in CASES if not args.only or c.name in args.only.split(",")] + cases = [ + c + for c in [*CASES, *corpus_cases(args.corpus_episodes)] + if not args.only or c.name in args.only.split(",") + ] sem = asyncio.Semaphore(args.concurrency) async def one(c: Case, run: int) -> dict[str, Any]: diff --git a/bench/pi_llm.py b/bench/pi_llm.py index d116daddb4..e74c689a8d 100644 --- a/bench/pi_llm.py +++ b/bench/pi_llm.py @@ -1,10 +1,10 @@ """Proactive-interference (PI) stale-retrieval benchmark for loom. Adapted from the proactive-interference paradigm: an entity's attribute is UPDATED n -times, then queried for its CURRENT value. Every prior value is stale and constitutes -interference; a read that systematically returns an OVERWRITTEN value is the failure -being measured. This bench turns that into a number loom does not otherwise measure: the -**stale-retrieval rate**, not just accuracy. +times, then queried. Every prior value is stale and constitutes interference; a read +that returns an OVERWRITTEN value is the failure being measured. This bench turns +that into a number loom does not otherwise measure: the **stale-retrieval rate**, +not just accuracy. Unlike LoCoMo (mixed reasoning), this isolates supersession/staleness on loom's real ingest+ask path: each update is a separate `set_from_messages` call with an @@ -12,11 +12,36 @@ through `memory.ask` synthesis. Scoring is deterministic (distinct coined value tokens, substring match) — no judge, so it is cheap and repeatable. -Metrics per PI depth n: - accuracy answer contains the LATEST value - stale_rate answer contains ANY superseded value (the PI failure) - clean_correct latest present AND no superseded present (strictest) +Question kinds (`--kinds`, default `current`), all asked on the one ingest: + current the entity's module today + current_2hop today's module of "the project owned by team ". The text + never names the entity, so the answer needs two facts: the + ownership fact (written once, before the updates) and the + latest update, the one that superseded the others + asof the entity's module on the day of a middle update, sent with + `as_of` = the last second of that day (depth 2 and up) + asof_2hop that day's module, asked through the owning team + +Metrics per PI depth n and kind: + accuracy answer contains the gold value + stale_rate answer contains a value written before the gold (the PI failure) + later_rate answer contains a value written after the as-of time + clean_correct gold present AND no other value present (strictest) abstain_rate answer contains no value token at all + flip_rate share of items whose `--repeats` labels disagreed + +`--repeats N` asks each question N times; an item keeps the majority of its +`clean_correct` labels, so an abstention is a wrong answer. `--gate` pairs each +one-fact question (arm A) with the two-fact question of the same episode, depth +and time (arm B) and prints the paired bootstrap verdict of `bench/_gate.py`, +resampling whole episodes. `--out` writes JSONL: a header (flags, the server's +instrument, the gate), then one line per namespace and question with every +repeat's answer and label and the reply fields that show the second hop and the +supersession filter ran. `--audit-out` runs `supersession_audit.audit` over the +run's namespaces before they are erased; it needs `OPENAI_API_KEY` for the +audit's judge and the server's `.env` for ClickHouse, and the run exits 2 before +its first write without either. `--dry` contacts no server: two scripted readers +check the scorer, and the gate and `--out` run as in a real run. Each (depth, episode) gets its own namespace under `--namespace` plus a per-run id, registered as bench and erased when the run ends (`--keep-namespaces` keeps them). @@ -25,33 +50,59 @@ Usage: LOOM_API_KEY=... python bench/pi_llm.py --base-url http://localhost:7777 \\ --namespace pi-bench --episodes 20 --depths 1,2,5,10,15,20,30 + python bench/pi_llm.py --dry --kinds current,current_2hop,asof,asof_2hop --gate """ from __future__ import annotations import argparse import asyncio +import json import os import sys import uuid +from collections.abc import Awaitable, Callable, Iterable +from dataclasses import dataclass from datetime import date, timedelta +from pathlib import Path +from typing import Any import httpx try: - from bench._gate import measurement_fields + from bench import supersession_audit + from bench._gate import ( + add_gate_arguments, + flip_rate, + gate_from_args, + majority_label, + measurement_fields, + ) from bench.bench_namespaces import ( erase_on_exit, register_bench_namespace, remember_bench_namespace, ) + from bench.quality import run_metadata except ModuleNotFoundError: # `python bench/pi_llm.py` puts bench/ itself on sys.path - from _gate import measurement_fields # type: ignore[no-redef] + import supersession_audit # type: ignore[no-redef] + from _gate import ( # type: ignore[no-redef] + add_gate_arguments, + flip_rate, + gate_from_args, + majority_label, + measurement_fields, + ) from bench_namespaces import ( # type: ignore[no-redef] erase_on_exit, register_bench_namespace, remember_bench_namespace, ) + from quality import run_metadata # type: ignore[no-redef] + +# One request to the server: `post(path, body)` answers the decoded reply, or +# `{"_err": ...}` for a call that failed. +Post = Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]] _ENTITIES = [ "Quorvex", @@ -140,6 +191,124 @@ def update_text(entity: str, k: int, value: str, base_day: int = 1) -> tuple[str return day, text +def entity_of(ep: int) -> str: + return f"{_ENTITIES[ep % len(_ENTITIES)]}{ep}" + + +def owner_of(ep: int) -> str: + """The team that owns the episode's project: a coined name half the list + away, so it is never the episode's entity.""" + return _ENTITIES[(ep + 15) % len(_ENTITIES)] + + +def bridge_text(entity: str, owner: str, base_day: int = 1) -> tuple[str, str]: + """(observation_date, sentence) of the ownership fact a two-fact question + needs. It is dated the day before update 0, so a read as of any update's + day sees it.""" + day = (_EPOCH + timedelta(days=base_day - 1)).isoformat() + return day, f"Project ownership record: as of {day}, team {owner} owns the project {entity}." + + +KINDS = ("current", "current_2hop", "asof", "asof_2hop") + + +@dataclass(frozen=True) +class Question: + kind: str + text: str + # None = asked today; else the instant `memory.ask` replays (`as_of`). + as_of: str | None + # The value token a correct answer holds. + gold: str + # The values written before the gold (stale in an answer) and after the + # as-of time (not yet true at it). + earlier: tuple[str, ...] + later: tuple[str, ...] + # The writes the answer needs: "bridge" (the ownership fact), "update:". + gold_facts: tuple[str, ...] + # The update that replaced an earlier value (asked today) or the gold + # (as-of); None at depth 1, where nothing was superseded. + superseding_write: str | None + + +def asof_index(depth: int) -> int: + """The update an as-of question asks about: a middle one, so at least one + later update superseded it.""" + return (depth - 1) // 2 + + +def questions(ep: int, depth: int, kinds: Iterable[str], base_day: int = 1) -> list[Question]: + """The episode's questions of `kinds`, in `KINDS` order. Depth 1 has one + value and no earlier day to ask about: it yields no as-of question.""" + entity = entity_of(ep) + values = tuple(_val(ep, k) for k in range(depth)) + wanted = set(kinds) + out: list[Question] = [] + for kind in KINDS: + asof = kind.startswith("asof") + if kind not in wanted or (asof and depth < 2): + continue + two_fact = kind.endswith("_2hop") + subject = f"the project owned by team {owner_of(ep)}" if two_fact else entity + superseding: str | None + if asof: + k = asof_index(depth) + day, _ = update_text(entity, k, values[k], base_day) + text = ( + f"What module was {subject} assigned to on {day}? " + "Give the module assigned on that day only." + ) + as_of, superseding = f"{day}T23:59:59", f"update:{k + 1}" + else: + k = depth - 1 + text = f"What module is {subject} currently assigned to? Give the current module only." + as_of, superseding = None, (f"update:{k}" if k else None) + out.append( + Question( + kind=kind, + text=text, + as_of=as_of, + gold=values[k], + earlier=values[:k], + later=values[k + 1 :], + gold_facts=(*(("bridge",) if two_fact else ()), f"update:{k}"), + superseding_write=superseding, + ) + ) + return out + + +# What `score_answer` returns, and what a question's row keeps of it. +FLAGS = ("has_gold", "has_stale", "has_later", "clean_correct", "abstain") +# What a repeat keeps of the reply: the rows the answer read, what the +# supersession filter took out, and the entities the second hop followed. +REPLY_FIELDS = ( + "source", + "memory_keys", + "superseded_dropped", + "stale_sentences_masked", + "entity_followed", + "decomposed_parts", +) + + +def score_answer(answer: str, q: Question) -> dict[str, bool]: + """One answer against its question, by token match (pure). `clean_correct` + is the gold and no other value of the episode; an answer with no value at + all is an abstention.""" + a = (answer or "").lower() + has_gold = q.gold.lower() in a + has_stale = any(v.lower() in a for v in q.earlier) + has_later = any(v.lower() in a for v in q.later) + return { + "has_gold": has_gold, + "has_stale": has_stale, + "has_later": has_later, + "clean_correct": has_gold and not (has_stale or has_later), + "abstain": not (has_gold or has_stale or has_later), + } + + async def _post(cl: httpx.AsyncClient, base: str, path: str, body: dict, tok: str) -> dict: for _ in range(5): try: @@ -157,46 +326,120 @@ async def _post(cl: httpx.AsyncClient, base: str, path: str, body: dict, tok: st return {"_err": "retries"} -async def run_episode(cl, base, tok, ns, org, ep, depth, base_day, credit=False) -> dict: - entity = _ENTITIES[ep % len(_ENTITIES)] + f"{ep}" +async def run_episode( + post: Post, + ns: str, + org: str, + ep: int, + depth: int, + base_day: int = 1, + credit: bool = False, + kinds: Iterable[str] = ("current",), + repeats: int = 1, +) -> list[dict[str, Any]]: + """Write one episode and ask its questions of `kinds`, each `repeats` times + on the one ingest: one row per question.""" + entity = entity_of(ep) + asked = questions(ep, depth, kinds, base_day) # n updates to the same entity attribute, oldest -> newest. - for k in range(depth): - obs_date, text = update_text(entity, k, _val(ep, k), base_day) + writes = [ + (f"ep{ep}-s{k}", *update_text(entity, k, _val(ep, k), base_day)) for k in range(depth) + ] + if any("bridge" in q.gold_facts for q in asked): + writes.insert(0, (f"ep{ep}-bridge", *bridge_text(entity, owner_of(ep), base_day))) + for session_id, obs_date, text in writes: body = { "org": org, "namespace": ns, "agent": "pi", "user_id": f"ep{ep}", - "session_id": f"ep{ep}-s{k}", + "session_id": session_id, "messages": [{"role": "user", "content": text}], "max_tokens": 1024, "observation_date": obs_date, } - res = await _post(cl, base, "/v1/memory.set_from_messages", body, tok) + res = await post("/v1/memory.set_from_messages", body) if res.get("_err"): - return {"ep": ep, "depth": depth, "error": res} - # query the CURRENT value - q = f"What module is {entity} currently assigned to? Give the current module only." - ask = {**measurement_fields("ask", credit=credit), "org": org, "namespace": ns, "query": q} - ans = await _post(cl, base, "/v1/memory.ask", ask, tok) + return [_item(ns, ep, depth, q, [{"label": "ERROR", "error": res}]) for q in asked] + rows = [] + for q in asked: + ask = { + **measurement_fields("ask", credit=credit), + "org": org, + "namespace": ns, + "query": q.text, + } + if q.as_of: + ask["as_of"] = q.as_of + if repeats > 1: + # A cached completion or a served precedent repeats the first answer's + # bytes: the repeats would agree whatever the reader does. + ask.update(llm_cache=False, precedents=False) + runs = [_repeat(await post("/v1/memory.ask", ask), q) for _ in range(repeats)] + rows.append(_item(ns, ep, depth, q, runs)) + return rows + + +def _repeat(ans: dict[str, Any], q: Question) -> dict[str, Any]: + """One ask of one question: the full answer, its score and label, and the + reply's `REPLY_FIELDS`.""" if ans.get("_err"): - return {"ep": ep, "depth": depth, "error": ans} - answer = (ans.get("answer") or "").lower() - latest = _val(ep, depth - 1).lower() - stale_vals = [_val(ep, k).lower() for k in range(depth - 1)] - has_latest = latest in answer - has_stale = any(sv in answer for sv in stale_vals) - has_any = has_latest or has_stale + return {"label": "ERROR", "error": ans} + answer = str(ans.get("answer") or "") + score = score_answer(answer, q) return { + "answer": answer, + "label": "CORRECT" if score["clean_correct"] else "WRONG", + **score, + **{f: ans.get(f) for f in REPLY_FIELDS}, + } + + +def _item( + ns: str, ep: int, depth: int, q: Question, repeats: list[dict[str, Any]] +) -> dict[str, Any]: + """One question's row. The label is the majority of its repeats' labels and + each flag the majority of the answered repeats (a tie is False), so an item + that abstains as often as it answers is wrong. `error` when no repeat + answered.""" + labels = [r["label"] for r in repeats] + row = { + "namespace": ns, "ep": ep, "depth": depth, - "source": ans.get("source"), - "has_latest": has_latest, - "has_stale": has_stale, - "clean_correct": has_latest and not has_stale, - "abstain": not has_any, - "answer": answer[:120], + "kind": q.kind, + "question": q.text, + "as_of": q.as_of, + "gold": q.gold, + "gold_facts": list(q.gold_facts), + "superseding_write": q.superseding_write, + "label": majority_label(labels), + "labels": labels, + "repeats": repeats, } + answered = [r for r in repeats if "error" not in r] + if not answered: + return {**row, "error": repeats[0]["error"]} + return {**row, **{f: majority_label([r[f] for r in answered]) == "CORRECT" for f in FLAGS}} + + +def gate_pairs( + rows: Iterable[dict[str, Any]], +) -> tuple[dict[Any, list[str]], dict[Any, list[str]], dict[Any, str]]: + """The paired gate's arms from question rows: A the one-fact kind, B the + two-fact kind of the same (episode, depth, time), where time is today or + as-of. A row that errored is left out, so its item is not paired. The + clusters are episodes: one coined entity serves every depth.""" + a: dict[Any, list[str]] = {} + b: dict[Any, list[str]] = {} + clusters: dict[Any, str] = {} + for r in rows: + if r.get("error"): + continue + key = (r["ep"], r["depth"], "asof" if r["kind"].startswith("asof") else "current") + (b if r["kind"].endswith("_2hop") else a)[key] = r["labels"] + clusters[key] = str(r["ep"]) + return a, b, clusters def _parse(argv: list[str] | None) -> argparse.Namespace: @@ -207,91 +450,285 @@ def _parse(argv: list[str] | None) -> argparse.Namespace: p.add_argument("--namespace", default="pi-bench", help="namespace prefix") p.add_argument("--episodes", type=int, default=20) p.add_argument("--depths", default="1,2,5,10,15,20,30") + p.add_argument( + "--kinds", + default="current", + help=f"comma-separated question kinds, of {', '.join(KINDS)}; a *_2hop kind writes " + "the ownership fact before the updates, an asof* kind is asked from depth 2", + ) p.add_argument("--concurrency", type=int, default=4) p.add_argument( "--keep-namespaces", action="store_true", help="do not erase this run's namespaces" ) + add_gate_arguments(p) # --repeats / --gate* / --credit / --judge-calibration + p.add_argument( + "--out", default="", help="JSONL: a header line, then one line per namespace and question" + ) p.add_argument( - "--credit", + "--audit-out", + default="", + help="write supersession_audit's record of this run's namespaces, read from " + "ClickHouse through the server's .env before they are erased; needs " + "OPENAI_API_KEY for the audit's judge", + ) + p.add_argument( + "--dry", action="store_true", - help="send the server's crediting default (ask reinforce) instead of the " - "evaluation-read field", + help="contact no server: two scripted readers check the scorer; the gate and " + "--out run as in a real run", ) - return p.parse_args(argv) - - -def _row(depth: int, res: list[dict]) -> dict: + args = p.parse_args(argv) + args.kinds = [k.strip() for k in args.kinds.split(",") if k.strip()] + if unknown := sorted(set(args.kinds) - set(KINDS)): + p.error(f"--kinds: unknown {', '.join(unknown)}; choose from {', '.join(KINDS)}") + if args.dry and args.audit_out: + p.error("--audit-out reads the run's namespaces from ClickHouse; --dry writes none") + if args.repeats < 1: + p.error("--repeats: a question is asked at least once") + return args + + +def _row(depth: int, res: list[dict], kind: str = "current") -> dict: ok = [r for r in res if not r.get("error")] n = max(1, len(ok)) + + def rate(flag: str) -> float: + return 100 * sum(r[flag] for r in ok) / n + return { "depth": depth, + "kind": kind, "n": len(ok), "errors": len(res) - len(ok), - "accuracy": 100 * sum(r["has_latest"] for r in ok) / n, - "stale_rate": 100 * sum(r["has_stale"] for r in ok) / n, - "clean_correct": 100 * sum(r["clean_correct"] for r in ok) / n, - "abstain": 100 * sum(r["abstain"] for r in ok) / n, + "accuracy": rate("has_gold"), + "stale_rate": rate("has_stale"), + "later_rate": rate("has_later"), + "clean_correct": rate("clean_correct"), + "abstain": rate("abstain"), + "flip_rate": flip_rate(r["labels"] for r in ok), } +_HEAD = ( + "depth kind n accuracy stale_rate later_rate clean_correct abstain flip_rate" +) + + +def _line(row: dict) -> str: + flip = "-" if row["flip_rate"] is None else f"{100 * row['flip_rate']:.1f}%" + return ( + f"{row['depth']:5d} {row['kind']:<12} {row['n']:3d} {row['accuracy']:7.1f}% " + f"{row['stale_rate']:9.1f}% {row['later_rate']:9.1f}% {row['clean_correct']:12.1f}% " + f"{row['abstain']:6.1f}% {flip:>9} errs={row['errors']}" + ) + + +Episode = Callable[[int, int], Awaitable[list[dict[str, Any]]]] + + +async def _run_depths( + args: argparse.Namespace, depths: list[int], episode: Episode +) -> tuple[list[dict[str, Any]], list[dict]]: + """Each depth's episodes through `episode(ep, depth)`, with the depth's table + lines printed as it finishes: (question rows, table rows).""" + print(_HEAD) + items: list[dict[str, Any]] = [] + table: list[dict] = [] + for depth in depths: + done = await asyncio.gather(*[episode(ep, depth) for ep in range(args.episodes)]) + at_depth = [row for rows in done for row in rows] + items.extend(at_depth) + for kind in KINDS: + of_kind = [r for r in at_depth if r["kind"] == kind] + if of_kind: + table.append(_row(depth, of_kind, kind)) + print(_line(table[-1])) + return items, table + + +def _finish( + args: argparse.Namespace, + run_id: str, + instrument: dict[str, object], + items: list[dict[str, Any]], + table: list[dict], +) -> int: + """The headline, the gate and `--out` of a run's rows. Returns 1 when every + episode errored.""" + hi = [r for r in table if r["kind"] == "current" and r["depth"] >= 10] + if hi: + avg_stale = sum(r["stale_rate"] for r in hi) / len(hi) + print(f"\nPI stale-retrieval rate at depth>=10 (mean): {avg_stale:.1f}%") + gate = None + if args.gate: + a, b, clusters = gate_pairs(items) + if set(a) & set(b): + gate = gate_from_args(args, a, b, clusters=clusters) + print("\nA = the one-fact question, B = the two-fact question of the same item") + print("\n".join(gate.lines())) + else: + # An empty pair has a lower bound of 0, which would read as a pass. + print("\ngate: no item answered as both a one-fact and a two-fact question") + if args.out: + # The header records what was measured: not the credential, the + # server's address or this machine's paths. + unrecorded = ("token", "base_url", "out", "audit_out") + flags = {k: v for k, v in vars(args).items() if k not in unrecorded} + header = { + "record": "header", + "run_id": run_id, + "flags": flags, + "instrument": instrument, + "gate": gate.as_dict() if gate else None, + } + with open(args.out, "w", encoding="utf-8") as f: + for record in (header, *({"record": "question", **r} for r in items)): + f.write(json.dumps(record) + "\n") + print(f"wrote {args.out}") + if table and not any(r["n"] for r in table): + print("every episode errored: no measurement was taken", file=sys.stderr) + return 1 + return 0 + + +def _scripted_post( + ep: int, depth: int, kinds: Iterable[str], pick: Callable[[Question], str] +) -> Post: + """The server of a `--dry` episode: every write succeeds and every ask is + answered with the value `pick` names for its question.""" + asked = {(q.text, q.as_of): q for q in questions(ep, depth, kinds)} + + async def post(path: str, body: dict[str, Any]) -> dict[str, Any]: + if path != "/v1/memory.ask": + return {} + q = asked[(body["query"], body.get("as_of"))] + return {"answer": f"The assigned module is {pick(q)}.", "source": "scripted"} + + return post + + +async def _dry(args: argparse.Namespace, depths: list[int], run_id: str) -> int: + """`--dry`: the run with scripted readers in place of the server. The first + answers every question with its gold and must score clean on all of them; + the second answers with another value of the episode and must score clean on + none at depth 2 and up (depth 1 has no other value). The gate and `--out` + read the first reader's rows.""" + + def reader(pick: Callable[[Question], str]) -> Episode: + async def episode(ep: int, depth: int) -> list[dict[str, Any]]: + return await run_episode( + _scripted_post(ep, depth, args.kinds, pick), + f"{args.namespace}-{run_id}-d{depth}-e{ep}", + args.org, + ep, + depth, + 1, + args.credit, + args.kinds, + args.repeats, + ) + + return episode + + print("dry run: no server. Scripted reader 1 answers the gold value:") + gold, table = await _run_depths(args, depths, reader(lambda q: q.gold)) + print("\nScripted reader 2 answers another value of the episode:") + other, _ = await _run_depths( + args, depths, reader(lambda q: next(iter(q.earlier + q.later), "")) + ) + code = _finish(args, run_id, run_metadata({}), gold, table) + missed = sum(not r["clean_correct"] for r in gold) + passed = sum(r["clean_correct"] for r in other if r["depth"] >= 2) + if missed or passed: + print( + f"dry self-check failed: {missed} gold answer(s) not clean, " + f"{passed} answer(s) with another value clean", + file=sys.stderr, + ) + return 1 + print("\ndry self-check passed: gold answers are clean, answers with another value are not") + return code + + +async def _audit_blocker() -> str: + """Why `--audit-out` cannot run, or "" when it can. The audit follows the + asks and reads versions the run erases when it ends, so what it needs is + checked before the first write.""" + if not os.environ.get("OPENAI_API_KEY"): + # Without it the audit labels only byte-identical pairs and still names its judge. + return "--audit-out needs OPENAI_API_KEY for the audit's judge" + try: + await supersession_audit.connect() + except Exception as e: # noqa: BLE001 — any failed connect is one refusal, before the spend + return f"--audit-out cannot reach ClickHouse through the server's .env: {e}" + return "" + + async def main(argv: list[str] | None = None) -> int: args = _parse(argv) + depths = [int(x) for x in args.depths.split(",") if x.strip()] + run_id = uuid.uuid4().hex[:6] + if args.dry: + return await _dry(args, depths, run_id) tok = args.token if not tok: print("need --token or LOOM_API_KEY", file=sys.stderr) return 2 - depths = [int(x) for x in args.depths.split(",") if x.strip()] + if args.audit_out and (blocker := await _audit_blocker()): + print(blocker, file=sys.stderr) + return 2 sem = asyncio.Semaphore(args.concurrency) - run_id = uuid.uuid4().hex[:6] - print("depth n accuracy stale_rate clean_correct abstain") - rows = [] async with httpx.AsyncClient() as cl: + health = await cl.get(args.base_url + "/v1/health", timeout=5.0) + if health.status_code != 200: + print(f"server unhealthy: {health.status_code}", file=sys.stderr) + return 2 + instrument = run_metadata(health.json()) + + async def send(path: str, body: dict[str, Any]) -> dict[str, Any]: + return await _post(cl, args.base_url, path, body, tok) async def post(path: str, body: dict) -> dict: - out = await _post(cl, args.base_url, path, body, tok) + out = await send(path, body) if out.get("_err"): raise RuntimeError(f"{path}: {out}") return out + # ONE entity per namespace: the PI paradigm isolates a single + # entity per episode. Near-identical template sentences of + # different entities in one namespace sit above the conflict + # threshold (only the subject differs) and flag each other, + # which is a bench artifact, not same-entity interference. + async def episode(ep: int, depth: int) -> list[dict[str, Any]]: + ns = f"{args.namespace}-{run_id}-d{depth}-e{ep}" + remember_bench_namespace(args.org, ns) + await register_bench_namespace( + post, + org=args.org, + namespace=ns, + description=f"PI depth {depth} episode {ep}", + keep=args.keep_namespaces, + ) + async with sem: + return await run_episode( + send, ns, args.org, ep, depth, 1, args.credit, args.kinds, args.repeats + ) + async with erase_on_exit(post, org=args.org, keep=args.keep_namespaces): - for depth in depths: - # ONE entity per namespace: the PI paradigm isolates a single - # entity per episode. Near-identical template sentences of - # different entities in one namespace sit above the conflict - # threshold (only the subject differs) and flag each other, - # which is a bench artifact, not same-entity interference. - async def _one(ep, depth=depth): - ns = f"{args.namespace}-{run_id}-d{depth}-e{ep}" - remember_bench_namespace(args.org, ns) - await register_bench_namespace( - post, - org=args.org, - namespace=ns, - description=f"PI depth {depth} episode {ep}", - keep=args.keep_namespaces, - ) - async with sem: - return await run_episode( - cl, args.base_url, tok, ns, args.org, ep, depth, 1, args.credit - ) - - row = _row(depth, await asyncio.gather(*[_one(ep) for ep in range(args.episodes)])) - print( - f"{depth:5d} {row['n']:2d} {row['accuracy']:7.1f}% " - f"{row['stale_rate']:8.1f}% {row['clean_correct']:11.1f}% " - f"{row['abstain']:6.1f}% errs={row['errors']}" + items, table = await _run_depths(args, depths, episode) + # The table, the gate and --out come first: a failed audit keeps the answers. + code = _finish(args, run_id, instrument, items, table) + if args.audit_out: + # Inside the block: its exit erases the versions the audit reads. + record = await supersession_audit.audit( + args.org, sorted({r["namespace"] for r in items}), sample=0 ) - rows.append(row) - # headline - hi = [r for r in rows if r["depth"] >= 10] - if hi: - avg_stale = sum(r["stale_rate"] for r in hi) / len(hi) - print(f"\nPI stale-retrieval rate at depth>=10 (mean): {avg_stale:.1f}%") - if rows and not any(r["n"] for r in rows): - print("every episode errored: no measurement was taken", file=sys.stderr) - return 1 - return 0 + Path(args.audit_out).write_text( + json.dumps(record, indent=1, default=str), encoding="utf-8" + ) + print(f"wrote {args.audit_out}") + return code if __name__ == "__main__": diff --git a/bench/supersession_audit.py b/bench/supersession_audit.py index 1c7f7741d2..6d346a2086 100644 --- a/bench/supersession_audit.py +++ b/bench/supersession_audit.py @@ -21,10 +21,19 @@ should not have replaced anything (a reuse buries a fact; a restatement is a row with no information). `narrows` is the omission rate. `corrects` and `contradicts` are the pairs the temporal and conflict work should be looking at. +Both rates are null (printed `n/a`) when no pair was labelled: a namespace whose +keys were never rewritten has no rate, not a rate of zero. + +The audit pairs versions of one key. A value retired behind another key +(`superseded_by`) is not a pair and is not audited. OPENAI_API_KEY=... python bench/supersession_audit.py --org \\ --namespace --days 7 --sample 200 --out /tmp/audit.json +`--namespace` repeats: one audit over several namespaces. `audit()` is the same +run as a function; `bench/pi_llm.py --audit-out` calls it on the namespaces it +minted, before it erases them. + Reads ClickHouse through `server.core.ch` (the server's own `.env`, run from the repo root), read-only. Pure core (`pair_versions`, `summarize`) tested in `bench/test_supersession_audit.py`. @@ -47,6 +56,7 @@ LABELS = ("restates", "extends", "narrows", "corrects", "contradicts", "unrelated") FALSE_SUPERSESSION = ("unrelated", "restates") +DEFAULT_JUDGE = "gpt-4o-mini" JUDGE_SYSTEM = ( "You audit updates to a memory store. You are shown the OLDER and the NEWER " @@ -80,13 +90,18 @@ class Summary: pairs: int labels: Counter = field(default_factory=Counter) + # Both rates are None when no pair was labelled: there is nothing to rate. @property - def false_supersession_rate(self) -> float: - return sum(self.labels[k] for k in FALSE_SUPERSESSION) / self.pairs if self.pairs else 0.0 + def false_supersession_rate(self) -> float | None: + return sum(self.labels[k] for k in FALSE_SUPERSESSION) / self.pairs if self.pairs else None @property - def omission_rate(self) -> float: - return self.labels["narrows"] / self.pairs if self.pairs else 0.0 + def omission_rate(self) -> float | None: + return self.labels["narrows"] / self.pairs if self.pairs else None + + +def _pct(rate: float | None) -> str: + return "n/a" if rate is None else f"{100 * rate:.1f}%" def pair_versions(rows: list[dict[str, Any]]) -> list[VersionPair]: @@ -181,7 +196,7 @@ async def _judge( return parse_label(str(data["choices"][0]["message"]["content"] or "")) -async def _fetch(org: str, namespace: str, days: int, ch: Any) -> list[dict[str, Any]]: +async def _fetch(org: str, namespaces: list[str], days: int, ch: Any) -> list[dict[str, Any]]: # Every version of every key that received more than one version in the # window, across sessions (a supersession is a later session writing the # same key). No FINAL — the versions table is the history, not the state. @@ -190,42 +205,62 @@ async def _fetch(org: str, namespace: str, days: int, ch: Any) -> list[dict[str, SELECT namespace, agent, user_id, session_id, memory_key, version, value, toString(created_at) AS created_at FROM loom.memory_versions - WHERE org = {org:String} AND namespace = {ns:String} + WHERE org = {org:String} AND namespace IN {nss:Array(String)} AND (org, namespace, agent, user_id, memory_key) IN ( SELECT org, namespace, agent, user_id, memory_key FROM loom.memory_versions - WHERE org = {org:String} AND namespace = {ns:String} + WHERE org = {org:String} AND namespace IN {nss:Array(String)} AND created_at > now() - INTERVAL {days:UInt32} DAY GROUP BY org, namespace, agent, user_id, memory_key HAVING uniq(version) > 1) AND redacted_at IS NULL """, - params={"org": org, "ns": namespace, "days": int(days)}, + params={"org": org, "nss": list(namespaces), "days": int(days)}, ) -async def main_async(args: argparse.Namespace) -> int: - import httpx - +async def connect() -> Any: + """The server's ClickHouse client, connected once: the one `audit` reads + through. A run that pays for its writes before the audit calls this first, + so a ClickHouse that does not answer is found before the spend.""" from server.core.ch import get_client ch = get_client() - await ch.connect() - rows = await _fetch(args.org, args.namespace, args.days, ch) + if not ch.connected: + await ch.connect() + return ch + + +async def audit( + org: str, + namespaces: list[str], + *, + days: int = 7, + sample: int = 200, + seed: int = 7, + judge: str = DEFAULT_JUDGE, + concurrency: int = 4, +) -> dict[str, Any]: + """Label the version pairs of `namespaces` (`sample` of them; 0 = every pair), + print the summary and return the record `--out` writes.""" + import httpx + + ch = await connect() + rows = await _fetch(org, namespaces, days, ch) pairs = pair_versions(rows) - rng = random.Random(args.seed) - if args.sample and len(pairs) > args.sample: - pairs = rng.sample(pairs, args.sample) + rng = random.Random(seed) + if sample and len(pairs) > sample: + pairs = rng.sample(pairs, sample) identical = sum(1 for p in pairs if _identical(p)) print( - f"supersession audit: {args.org}/{args.namespace} days={args.days} " + f"supersession audit: {org} namespaces={len(namespaces)} days={days} " f"version rows={len(rows)} pairs={len(pairs)} byte-identical={identical}" ) api_key = os.environ.get("OPENAI_API_KEY", "") usage = {"tin": 0, "tout": 0, "calls": 0} if not api_key: print("OPENAI_API_KEY unset: labelling only byte-identical pairs as restates") - sem = asyncio.Semaphore(args.concurrency) + sem = asyncio.Semaphore(concurrency) async with httpx.AsyncClient() as client: async def one(p: VersionPair) -> None: @@ -234,14 +269,13 @@ async def one(p: VersionPair) -> None: p.label = "restates" if _identical(p) else "" return try: - p.label = await _judge( - client, api_key=api_key, model=args.judge, p=p, usage=usage - ) + p.label = await _judge(client, api_key=api_key, model=judge, p=p, usage=usage) except Exception as e: # noqa: BLE001 — one failed judge is an unlabelled pair print(f" judge failed for {p.memory_key}: {e}", file=sys.stderr) await asyncio.gather(*[one(p) for p in pairs]) s = summarize(pairs) + false_rate, omission_rate = s.false_supersession_rate, s.omission_rate print( f"\n# labelled pairs: {s.pairs} (judge calls {usage['calls']}, " f"tokens in/out {usage['tin']}/{usage['tout']})" @@ -249,47 +283,46 @@ async def one(p: VersionPair) -> None: for k in LABELS: n = s.labels[k] print(f" {k:<12} {n:>5} {100 * n / s.pairs if s.pairs else 0:5.1f}%") - print( - "\n false-supersession rate (unrelated + restates): " - f"{100 * s.false_supersession_rate:.1f}%" + print(f"\n false-supersession rate (unrelated + restates): {_pct(false_rate)}") + print(f" omission rate (narrows): {_pct(omission_rate)}") + return { + "org": org, + "namespaces": list(namespaces), + "days": days, + "judge": judge, + "version_rows": len(rows), + "pairs": len(pairs), + "labelled": s.pairs, + "labels": dict(s.labels), + "false_supersession_rate": None if false_rate is None else round(false_rate, 4), + "omission_rate": None if omission_rate is None else round(omission_rate, 4), + "examples": { + k: [ + {"key": p.memory_key, "older": p.older_value[:200], "newer": p.newer_value[:200]} + for p in pairs + if p.label == k + ][:5] + for k in LABELS + }, + } + + +async def main_async(args: argparse.Namespace) -> int: + record = await audit( + args.org, + args.namespace, + days=args.days, + sample=args.sample, + seed=args.seed, + judge=args.judge, + concurrency=args.concurrency, ) - print(f" omission rate (narrows): {100 * s.omission_rate:.1f}%") if args.out: - Path(args.out).write_text( - json.dumps( - { - "org": args.org, - "namespace": args.namespace, - "days": args.days, - "judge": args.judge, - "version_rows": len(rows), - "pairs": len(pairs), - "labelled": s.pairs, - "labels": dict(s.labels), - "false_supersession_rate": round(s.false_supersession_rate, 4), - "omission_rate": round(s.omission_rate, 4), - "examples": { - k: [ - { - "key": p.memory_key, - "older": p.older_value[:200], - "newer": p.newer_value[:200], - } - for p in pairs - if p.label == k - ][:5] - for k in LABELS - }, - }, - indent=1, - default=str, - ) - ) + Path(args.out).write_text(json.dumps(record, indent=1, default=str)) print(f"wrote {args.out}") - if args.max_false_rate is not None and s.false_supersession_rate > args.max_false_rate: - print( - f"GATE: false-supersession rate {s.false_supersession_rate:.3f} > {args.max_false_rate}" - ) + rate = record["false_supersession_rate"] + if args.max_false_rate is not None and rate is not None and rate > args.max_false_rate: + print(f"GATE: false-supersession rate {rate:.3f} > {args.max_false_rate}") return 1 return 0 @@ -299,11 +332,13 @@ def main(argv: list[str] | None = None) -> int: description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) p.add_argument("--org", required=True) - p.add_argument("--namespace", required=True) + p.add_argument( + "--namespace", action="append", required=True, help="repeat to audit several namespaces" + ) p.add_argument("--days", type=int, default=7) p.add_argument("--sample", type=int, default=200, help="0 = every pair") p.add_argument("--seed", type=int, default=7) - p.add_argument("--judge", default="gpt-4o-mini") + p.add_argument("--judge", default=DEFAULT_JUDGE) p.add_argument("--concurrency", type=int, default=4) p.add_argument("--max-false-rate", type=float, default=None) p.add_argument("--out", default="") diff --git a/bench/test_forget_switch_eval.py b/bench/test_forget_switch_eval.py new file mode 100644 index 0000000000..2cc8acaad4 --- /dev/null +++ b/bench/test_forget_switch_eval.py @@ -0,0 +1,44 @@ +"""Storage-free tests for bench/forget_switch_eval.py's scorer on the generated corpus.""" + +from __future__ import annotations + +from dataclasses import replace + +from bench import pi_llm +from bench.forget_switch_eval import CASES, EXISTING, corpus_cases, score + + +def test_a_corpus_case_scores_the_new_value_and_an_over_retirement() -> None: + cases = corpus_cases(3) + assert [c.kind for c in cases] == ["corpus_switch"] * 3 + case = cases[2] + (stored,) = case.existing + old, new = pi_llm._val(2, 0), pi_llm._val(2, 1) + assert old in stored["value"] and new in case.turns[0][1] and old not in case.turns[0][1] + assert case.may_retire == {stored["memory_key"]} and not case.must_retire + + written = [{"memory_key": "blenthar2_module", "value": f"Blenthar2's module is now {new}."}] + assert score(case, set(), written) == (True, []) + # Retiring the stored row is allowed; keeping the old value only is a missing write. + assert score(case, {stored["memory_key"]}, written) == (True, []) + ok, why = score(case, set(), [{"memory_key": "k", "value": f"Blenthar2's module is {old}."}]) + assert not ok and why == [f"missing write {new.split('-')}"] + + # The case's own rows decide what an over-retirement is: a key of the + # hand-written cases' store is not one of them, a second stored row is. + assert EXISTING[0]["memory_key"] == "user_editor" + assert score(case, {"user_editor"}, written) == (True, []) + two_rows = replace( + case, existing=[stored, {"memory_key": "blenthar2_owner", "value": "Team Ysolde owns it."}] + ) + assert score(two_rows, {"blenthar2_owner"}, written) == ( + False, + ["over-retired ['blenthar2_owner']"], + ) + + +def test_the_hand_written_cases_keep_the_shared_store() -> None: + assert all(c.existing is EXISTING for c in CASES) + editor = next(c for c in CASES if c.name == "nl_editor") + ok, why = score(editor, {"user_city"}, [{"memory_key": "k", "value": "User uses Zed."}]) + assert not ok and why == ["over-retired ['user_city']"] diff --git a/bench/test_supersession_audit.py b/bench/test_supersession_audit.py index a16a3e7111..a58059ccca 100644 --- a/bench/test_supersession_audit.py +++ b/bench/test_supersession_audit.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio import sys from pathlib import Path @@ -9,6 +10,8 @@ from bench.supersession_audit import ( VersionPair, + _fetch, + _pct, pair_versions, parse_label, summarize, @@ -68,3 +71,27 @@ def test_summary_rates_count_reuse_and_restatement_as_false_supersession() -> No assert s.labels["restates"] == 2 and s.labels["unrelated"] == 1 assert round(s.false_supersession_rate, 3) == 0.5 assert round(s.omission_rate, 3) == round(1 / 6, 3) + + +def test_rates_are_null_without_a_labelled_pair() -> None: + # No pair, or pairs the judge never labelled: there is no rate, not a rate of zero. + for pairs in ([], [VersionPair("n", "k", 1, 2, "a", "b")]): + s = summarize(pairs) + assert s.pairs == 0 + assert s.false_supersession_rate is None and s.omission_rate is None + assert _pct(None) == "n/a" and _pct(0.0) == "0.0%" and _pct(0.125) == "12.5%" + + +def test_fetch_binds_every_namespace() -> None: + class Recorder: + async def query_all(self, sql: str, params: dict) -> list[dict]: + self.sql, self.params = sql, params + return [] + + ch = Recorder() + names = ["bench-revision-ab12cd-d1-e0", "bench-revision-ab12cd-d2-e0", "x') OR ('1'='1"] + assert asyncio.run(_fetch("dev", names, 1, ch)) == [] + assert ch.params == {"org": "dev", "nss": names, "days": 1} + # The outer read and the key subquery both scope to the bound list. + assert ch.sql.count("namespace IN {nss:Array(String)}") == 2 + assert not [n for n in names if n in ch.sql] diff --git a/bench/test_temporal_assertions.py b/bench/test_temporal_assertions.py index 3e2ab989ae..2d8858c734 100644 --- a/bench/test_temporal_assertions.py +++ b/bench/test_temporal_assertions.py @@ -16,6 +16,7 @@ from datetime import datetime +from bench.fama_forgetting import CORPUS_RELATION, corpus_cases from bench.temporal_assertions import ( forgetting_violation, step_field_ok, @@ -111,6 +112,27 @@ def test_step_field_state_mismatch_and_cleared() -> None: ) +def test_corpus_cases_sit_inside_and_after_their_interval() -> None: + from server.memory.domain.graph_quality import canonical_entity_text, is_single_valued_relation + + cases = corpus_cases(100) + assert len({c.case_id for c in cases}) == 100 + for c in cases: + # The old value's interval is [opened_at, closed_at]: one read inside it, + # one strictly after it. + assert triple_visible_as_of(c.opened_at, c.closed_at, c.as_of_within) + assert not triple_visible_as_of(c.opened_at, c.closed_at, c.as_of_after) + assert forgetting_violation( + valid_from=c.opened_at, valid_to=c.closed_at, as_of=c.as_of_after, surfaced=True + ) + assert c.relation == CORPUS_RELATION and c.old_object != c.new_object + # facts.list is asked for the names as the triple stores them. + for name in (c.subject, c.old_object, c.new_object): + assert canonical_entity_text(name) == name + # A relation that is not single-valued never closes the old interval. + assert is_single_valued_relation(CORPUS_RELATION) + + def _main() -> int: failures = 0 for name, fn in sorted(globals().items()): diff --git a/docs/benchmarks/coverage.md b/docs/benchmarks/coverage.md index be6ae5570b..449e10a948 100644 --- a/docs/benchmarks/coverage.md +++ b/docs/benchmarks/coverage.md @@ -25,7 +25,7 @@ The [results ledger](./results.md) is the source of published numbers; the | Memory retrieval | Does the right memory rank near the top? | recall@k, rank@1, MRR and distractor intrusion | **Published** | LongMemEval-S, LoCoMo, MuSiQue and MemoryAgentBench artifacts in the [results ledger](./results.md). | | Memory answers | Does the final answer correctly use the retrieved evidence? | answer accuracy, citation correctness and per-category failures | **Published** | LongMemEval-S, LoCoMo, MemBench, MemoryAgentBench and PerLTQA. | | Unknown questions | Does Loom abstain instead of answering from weak evidence? | abstain precision/recall, false-answer rate and answerable recall | **Partial** | LoCoMo adversarial questions and ten code abstain probes are published; a larger calibrated memory abstention set is still required. | -| Corrections and time | Does the current value replace stale facts while historical queries stay correct? | current-value accuracy, stale-answer rate, temporal accuracy and supersession precision | **Harness only** | Publish `pi_llm.py`, `forget_switch_eval.py`, `fama_forgetting.py` and `supersession_audit.py` on one shared public corpus. | +| Corrections and time | Does the current value replace stale facts while historical queries stay correct? | current-value accuracy, stale-answer rate, temporal accuracy and supersession precision | **Harness only** | `make bench-revision` runs `pi_llm.py`, `forget_switch_eval.py`, `fama_forgetting.py` and `supersession_audit.py` on one generated corpus that committed code rebuilds, with a question that needs two facts, one of them superseded ([running](./running.md#corrections-and-time)). Run it with real providers and commit its artifacts. | | Cross-tool continuity | Does a fact written by one client help another client in a later session? | cross-client recall, provenance, capture loss and latency | **Harness only** | `cross_tool_validate.py` has six queries; publish a larger Claude Code, Codex and Cursor matrix with raw captures. | | Memory efficiency | Does retrieval save context, model spend and turns? | task success, prompt/output tokens, model cost and construction break-even | **Partial** | The paired LongMemEval comparison reports 91% fewer prompt tokens for retrieval and estimates when the saved tokens offset memory construction. It does not measure model spend or turns. | | Knowledge retrieval | Does document RAG find and cite the right passage? | chunk recall@k, answer accuracy, citation precision, abstention, latency and tokens | **Partial** | [Design decisions](./results.md#design-decisions-from-design-documents) arm 2 measures answer accuracy over `loom_search` knowledge hits (A and D precision and recall against gold), citation precision and recall, abstention and injected tokens, on a private set of five documents with one judge; chunk recall@k, latency and a public set (`narrativeqa.py` with a fixed reader, hard unanswerable and citation cases) are still required. | @@ -58,8 +58,11 @@ measured; it does not prove that Loom performs well. Each item below answers evaluation questions from the matrix above: -- **Write integrity and corrections:** extraction precision, false-memory rate, - supersession and stale-answer rate on one public conversational corpus. +- **Write integrity:** extraction precision and false-memory rate on one public + conversational corpus. +- **Corrections and time:** the artifacts of `make bench-revision`, run with real + providers: current-value and as-of accuracy for one-fact and two-fact questions, + stale-answer rate, interval checks and the supersession audit. - **Knowledge RAG:** retrieval, answer and citation quality on text documents, followed by a licensed format-fidelity corpus for PDF, CSV and structured text. - **End-to-end code-agent outcome:** leak-controlled patch generation and test success, diff --git a/docs/benchmarks/methodology.md b/docs/benchmarks/methodology.md index acccee6212..4715f36f54 100644 --- a/docs/benchmarks/methodology.md +++ b/docs/benchmarks/methodology.md @@ -29,6 +29,7 @@ Each harness keeps its source's category labels, so a result reads per category. | `code_intel_qa.py` | Row `type`: `symbol_def`, `callers`, `conceptual`, `hub`, `history`, `test_set`, `abstain_probe`; plus `lane` and `facets`. | | `coding_agent_qa.py` | Bug-fix landing, infra fix, refactor location, flaky test, perf leak, schema migration, multi-session causal, temporal, team convention. | | `op_planning.py` | Each task's `class`: `instruction_type` × `structure`. | +| `pi_llm.py` | `--kinds`: `current`, `current_2hop`, `asof`, `asof_2hop`. One fact or two, asked today or as of an earlier update's day; reported per update depth. | ## Ground truth diff --git a/docs/benchmarks/overview.md b/docs/benchmarks/overview.md index f3e3a30fcb..d51671ef81 100644 --- a/docs/benchmarks/overview.md +++ b/docs/benchmarks/overview.md @@ -15,22 +15,22 @@ docstring is its manual: protocol, flags and a run command. Harnesses are standalone scripts: argparse plus an HTTP client, no shared fixtures, no test runner. -| Area | Question | Main harnesses | -| ------------------------ | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -| Retrieval recall | Did the right memory land in the top K? | `quality.py`, `retrieval_recall.py`, `k_curve.py`, `plane_ablation.py`, `hard_distractors.py` | -| Answer accuracy | Is the answer built from retrieved memory correct, under a pinned reader and judge? | `longmemeval.py`, `locomo_qa.py`, `memoryagentbench.py`, `membench.py`, `beam.py`, `musique.py`, `msc_dmr.py`, … | -| Write-side quality | Did extraction write what the turns say, and only that? | `extraction_eval.py`, `graph_eval.py`, `memory_integrity.py`, `supersession_audit.py` | -| Time and revision | Is a superseded fact hidden after its interval closes and visible inside it? | `fama_forgetting.py`, `mutation_sequence.py`, `fact_consolidation.py`, `pi_llm.py` | -| Agents and operations | Did an agent pick the right op and leave the store in the right shape? | `op_planning.py`, `skill_eval.py`, `op_trajectories.py`, `procedure_replay.py` | -| Cost | What does an answer or a session cost? | `ask_cost_rollup.py`, `session_ab.py`, `route_replay.py`, `ch_cost_by_op.py` | -| Safety and privacy | Does erasure reach every tier; can a prompt-only attacker extract or poison memory? | `erasure_compliance.py`, `memory_extraction_redteam.py`, `memory_poison.py`, `sensitivity_leakage.py` | -| Code index | Does the code index find definitions, callers and conceptual answers, and abstain on the rest? | `code_intel_qa.py`, `code_plane_ablation.py`, `code_shunt_tokens.py`, `code_ask_cache_threshold/` | -| Document parsing | Does the extractor read a document's text, headings, tables and pages, and lose nothing? | `docparse/` (offline) | -| Tracker | Does `tracker.similar` find the older duplicate an issue was closed against? | `tracker_similar_bench.py` | -| Latency and index health | Where does search time go; would a vector index return what brute force does? | `search_latency.py`, `vector_tenant_recall.py`, `ann_final_staleness.py`, `vector_index_vs_exact.py`, `scripts/ops/benchmark.py` | -| Write load | What latency and how many ClickHouse parts does a sustained write rate cost? | `write_rate.py` | -| Scale | Which ceiling does memory hit first as namespaces, orgs and keys grow? | `scale_load.py` | -| Consumer acceptance | Does one kind of deployment get precise answers at an acceptable cost? | `acceptance/{code_agent,memory_app,plugin,harness}.py` | +| Area | Question | Main harnesses | +| ------------------------ | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| Retrieval recall | Did the right memory land in the top K? | `quality.py`, `retrieval_recall.py`, `k_curve.py`, `plane_ablation.py`, `hard_distractors.py` | +| Answer accuracy | Is the answer built from retrieved memory correct, under a pinned reader and judge? | `longmemeval.py`, `locomo_qa.py`, `memoryagentbench.py`, `membench.py`, `beam.py`, `musique.py`, `msc_dmr.py`, … | +| Write-side quality | Did extraction write what the turns say, and only that? | `extraction_eval.py`, `graph_eval.py`, `memory_integrity.py` | +| Time and revision | Is a superseded fact hidden after its interval closes and visible inside it, also through a second fact? | `pi_llm.py`, `forget_switch_eval.py`, `fama_forgetting.py`, `supersession_audit.py`, `mutation_sequence.py`, `fact_consolidation.py` | +| Agents and operations | Did an agent pick the right op and leave the store in the right shape? | `op_planning.py`, `skill_eval.py`, `op_trajectories.py`, `procedure_replay.py` | +| Cost | What does an answer or a session cost? | `ask_cost_rollup.py`, `session_ab.py`, `route_replay.py`, `ch_cost_by_op.py` | +| Safety and privacy | Does erasure reach every tier; can a prompt-only attacker extract or poison memory? | `erasure_compliance.py`, `memory_extraction_redteam.py`, `memory_poison.py`, `sensitivity_leakage.py` | +| Code index | Does the code index find definitions, callers and conceptual answers, and abstain on the rest? | `code_intel_qa.py`, `code_plane_ablation.py`, `code_shunt_tokens.py`, `code_ask_cache_threshold/` | +| Document parsing | Does the extractor read a document's text, headings, tables and pages, and lose nothing? | `docparse/` (offline) | +| Tracker | Does `tracker.similar` find the older duplicate an issue was closed against? | `tracker_similar_bench.py` | +| Latency and index health | Where does search time go; would a vector index return what brute force does? | `search_latency.py`, `vector_tenant_recall.py`, `ann_final_staleness.py`, `vector_index_vs_exact.py`, `scripts/ops/benchmark.py` | +| Write load | What latency and how many ClickHouse parts does a sustained write rate cost? | `write_rate.py` | +| Scale | Which ceiling does memory hit first as namespaces, orgs and keys grow? | `scale_load.py` | +| Consumer acceptance | Does one kind of deployment get precise answers at an acceptable cost? | `acceptance/{code_agent,memory_app,plugin,harness}.py` | [`bench/memoryarena/`](../../bench/memoryarena/README.md) (an agent gym that scores later sessions of dependent tasks) and [`bench/memorydata/`](../../bench/memorydata/README.md) @@ -50,6 +50,8 @@ published-result reproduction. | `make bench-algorithm-gate` | `extraction_eval.py` and `graph_eval.py` on the regression fixtures | a server with a real extraction LLM | | `make bench-quick` | `longmemeval.py` on 30 shuffled items with the pinned reader and judge | the downloaded LongMemEval file, `LOOM_API_KEY`, `OPENAI_API_KEY` | | `make bench-matrix` | `matrix.py`: search mode × rerank × pool width on LongMemEval | as `bench-quick` | +| `make bench-revision` | `pi_llm.py`, `fama_forgetting.py`, `forget_switch_eval.py`, one corpus | a server with real providers, an org-admin token, its `.env` | +| `make bench-revision-dry` | `pi_llm.py --dry`: scorer, gate and artifact writer on scripted readers | nothing (offline) | | `make bench-code-intel-dry` | `code_intel_qa.py --dry`: the scorer on a perfect synthetic retrieval | nothing (offline) | | `make bench-code-intel` | `code_intel_qa.py` with the rollout floors | a server with an indexed ClickHouse repository, real embedder | | `make bench-code-legs` | `code_intel_qa.py --compare-extra` for three leg ablations, each paired | as `bench-code-intel` | diff --git a/docs/benchmarks/running.md b/docs/benchmarks/running.md index b7ea3e814e..e34dad3fab 100644 --- a/docs/benchmarks/running.md +++ b/docs/benchmarks/running.md @@ -187,6 +187,7 @@ judge. `OPENAI_BASE_URL` points them at a compatible gateway; `BENCH_READER_MODE ```bash make test-unit # includes `pytest bench -q`: every harness's scoring core make bench-code-intel-dry # code_intel_qa scorer on a perfect synthetic retrieval +make bench-revision-dry # pi_llm scorer, gate and artifact writer on two scripted readers python bench/coding_agent_qa.py --dry python bench/code_plane_ablation.py selftest python bench/acceptance/code_agent.py --dry @@ -236,6 +237,59 @@ BENCH_N=3 make bench-matrix # smoke: 3 items per config `bench/matrix_runs/`. Neither is gitignored; keep them out of a commit. Pass the calibration JSON to any gated bench with `--judge-calibration`. +### Corrections and time + +`make bench-revision` runs four harnesses on one generated corpus: the episodes of +`pi_llm.py`, in which a team owns a coined project and the project's module is updated +`depth` times. Committed code rebuilds the corpus, so it needs no download. The legs run +in one shell: a leg with failed cases does not stop the next, and the target exits +non-zero if any leg did. + +```bash +make bench-revision-dry # offline: the flags, the scorer, the gate and the JSONL writer +make bench-revision EPISODES=5 # a short run that shows what ran, before the full one +make bench-revision # 100 episodes at depths 1, 2, 5 and 10, three asks per question +``` + +| Variable | Default | Sets | +| ---------- | ------------------------------ | ---------------------------------------------------------- | +| `EPISODES` | `100` | episodes per depth in `pi_llm.py`; cases in the other legs | +| `DEPTHS` | `1,2,5,10` | updates per episode in `pi_llm.py` | +| `REPEATS` | `3` | asks per question; runs of `forget_switch_eval.py` | +| `ORG` | `dev` | the org the bench namespaces are minted in | +| `OUT` | `/tmp/loom_revision_` | the directory the artifacts land in | + +| Leg | Needs | Writes | +| ------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | +| `python -m bench.models_used` | the server's `.env` at the repository root | `models.json`: every model the server runs with | +| `pi_llm.py` with the four `--kinds`, `--gate` and `--gate-min-delta -4` | `LOOM_BASE_URL`, an org-admin `LOOM_API_KEY` (the erasure), and the server's embedder, extraction LLM and ask models | `pi_llm.jsonl`: a header (flags, instrument, gate), then one line per namespace and question with every repeat's answer and label | +| `supersession_audit.audit`, which `pi_llm.py --audit-out` calls on its namespaces before it erases them | the server's `.env` (it reads ClickHouse) and `OPENAI_API_KEY` for its judge | `supersession_audit.json` | +| `fama_forgetting.py --episodes` | `LOOM_BASE_URL` and `LOOM_API_KEY`; no LLM | `fama_forgetting.csv` | +| `forget_switch_eval.py --corpus-episodes` | the server's `.env`: the extraction LLM and a ClickHouse connection | `forget_switch_eval.json` | + +At the defaults `pi_llm.py` writes 400 namespaces with 2,200 `memory.set_from_messages` +calls and sends 4,200 `memory.ask` calls; `forget_switch_eval.py` makes 435 extraction +calls, and the audit one judge call per rewritten version of a key (1,400 when every +update rewrites one key). The audit runs after the asks, on namespaces the run erases when +it ends, so `pi_llm.py --audit-out` checks `OPENAI_API_KEY` and the ClickHouse connection +before its first write and exits 2 without either. + +`pi_llm.py` asks four kinds of question on one ingest: the project's module today +(`current`); the module of "the project owned by team …" (`current_2hop`), which never +names the project and so needs the ownership fact and the latest update; and both again +as of the day of a middle update (`asof`, `asof_2hop`, sent with `as_of`). An answer is +scored by token match, and an item keeps the majority of its repeats' labels, so an +abstention is wrong. The gate pairs each one-fact question with the two-fact question of +the same episode, depth and time and resamples whole episodes +([the verdict](./methodology.md#the-verdict)). It reads `pass` when the lower bound of +two-fact minus one-fact accuracy is above -4 points, `fail` when the upper bound is below +it, and `unresolved` otherwise; an unresolved run needs more episodes, not more repeats. + +Each repeat keeps the reply's `entity_followed`, `superseded_dropped` and +`stale_sentences_masked`, which show whether the second hop and the supersession filter +ran. The audit pairs versions of one key: a value retired behind another key is not a +pair, and both audit rates are null when no key was rewritten. + ### Code index The code benches need a server that indexes the fixture's repository (ClickHouse/ClickHouse @@ -365,7 +419,8 @@ non-commercial: research runs only. | MemoryData testbed | `bench/memorydata/` | Clone the testbed and add the adapter ([README](../../bench/memorydata/README.md)) | not recorded | `pi_llm.py`, `nested_kv.py`, `locomo.py` (LoCoMo-shaped turns for latency) and -`hard_distractors.py` generate their own corpus. +`hard_distractors.py` generate their own corpus. `fama_forgetting.py --episodes` and +`forget_switch_eval.py --corpus-episodes` build their cases from `pi_llm.py`'s episodes. ### Deployment data @@ -403,6 +458,7 @@ These read data that belongs to a deployment and never enters the repository: | Harness | Default output | | ------------------------------------- | --------------------------------------------------------------------- | | Make targets | `/tmp/_.csv` as listed above, or stdout | +| `make bench-revision` | `OUT` (default `/tmp/loom_revision_/`), one file per leg | | `quality.py` | `--out` (default `bench/quality.csv`) plus `.meta.json` | | `extraction_eval.py`, `graph_eval.py` | `--out` (default `bench/extraction_eval.csv`, `bench/graph_eval.csv`) | | `matrix.py` | `bench/MATRIX_RESULTS.md`, `bench/matrix_runs/.csv` | diff --git a/tests/unit/test_bench_pi_llm.py b/tests/unit/test_bench_pi_llm.py index f21989e6be..46a7980b77 100644 --- a/tests/unit/test_bench_pi_llm.py +++ b/tests/unit/test_bench_pi_llm.py @@ -1,9 +1,27 @@ -"""bench/pi_llm.py — the update dates order the updates the way the bench -scores them, at every depth it runs.""" +"""bench/pi_llm.py — the generated corpus, its questions and scorer, the paired +gate over one-fact and two-fact questions, and the offline dry run.""" from __future__ import annotations -from bench import pi_llm +import inspect +import json +import random +import re +from datetime import datetime +from pathlib import Path +from typing import Any + +import httpx +import pytest + +from bench import bench_namespaces, pi_llm, supersession_audit +from bench._gate import DEFAULT_BAND_PP, gate_from_args +from bench.bootstrap import paired_bootstrap +from bench.quality import run_metadata + +ROOT = Path(__file__).resolve().parents[2] +EPISODES = 100 +DEPTHS = (1, 2, 5, 10) def test_update_dates_strictly_increase_past_a_month() -> None: @@ -15,11 +33,375 @@ def test_update_dates_strictly_increase_past_a_month() -> None: def test_row_scores_only_the_episodes_that_answered() -> None: + flags = {"has_later": False, "abstain": False, "labels": ["CORRECT"]} res = [ - {"has_latest": True, "has_stale": False, "clean_correct": True, "abstain": False}, - {"has_latest": True, "has_stale": True, "clean_correct": False, "abstain": False}, + {**flags, "has_gold": True, "has_stale": False, "clean_correct": True}, + {**flags, "has_gold": True, "has_stale": True, "clean_correct": False}, {"error": {"_err": 500}}, ] row = pi_llm._row(5, res) assert row["n"] == 2 and row["errors"] == 1 assert row["accuracy"] == 100.0 and row["stale_rate"] == 50.0 and row["clean_correct"] == 50.0 + + +def _update(fact: str) -> int: + return int(fact.removeprefix("update:")) + + +def test_every_two_fact_question_names_its_gold_facts_the_superseding_write_and_the_as_of_time() -> ( + None +): + for ep in range(EPISODES): + entity = pi_llm.entity_of(ep) + bridge_day, _ = pi_llm.bridge_text(entity, pi_llm.owner_of(ep)) + for depth in DEPTHS: + values = [pi_llm._val(ep, k) for k in range(depth)] + days = [ + datetime.fromisoformat(pi_llm.update_text(entity, k, v)[0]) + for k, v in enumerate(values) + ] + # Every as-of read sees the ownership fact. + assert datetime.fromisoformat(bridge_day) < days[0] + questions = pi_llm.questions(ep, depth, pi_llm.KINDS) + # Depth 1 has one value: no earlier day to ask about. + assert [q.kind for q in questions] == list(pi_llm.KINDS[: 4 if depth > 1 else 2]) + for q in questions: + k = _update(q.gold_facts[-1]) + two_fact = q.kind.endswith("_2hop") + assert q.gold_facts == (("bridge", f"update:{k}") if two_fact else (f"update:{k}",)) + assert q.gold == values[k] + assert q.earlier == tuple(values[:k]) + if depth == 1: + assert q.superseding_write is None # the control: nothing was superseded + continue + assert q.superseding_write is not None + s = _update(q.superseding_write) + assert 0 < s < depth + if q.kind.startswith("asof"): + assert k == pi_llm.asof_index(depth) and s == k + 1 + assert q.as_of is not None + assert days[k] < datetime.fromisoformat(q.as_of) < days[s] + assert q.later == tuple(values[s:]) + else: + assert k == s == depth - 1 and q.as_of is None and q.later == () + + +def test_a_two_fact_question_never_names_the_entity_and_no_token_hides_in_another() -> None: + for ep in range(EPISODES): + entity, owner = pi_llm.entity_of(ep).lower(), pi_llm.owner_of(ep).lower() + name = pi_llm._ENTITIES[ep % len(pi_llm._ENTITIES)].lower() + assert name not in owner + for depth in DEPTHS: + questions = pi_llm.questions(ep, depth, pi_llm.KINDS) + for q in questions: + if q.kind.endswith("_2hop"): + assert name not in q.text.lower() and owner in q.text.lower() + else: + assert entity in q.text.lower() + values = [pi_llm._val(ep, k) for k in range(depth)] + bridge = pi_llm.bridge_text(entity, owner)[1].lower() + texts = [entity, owner, bridge, *(q.text.lower() for q in questions)] + for v in values: + assert not [t for t in texts if v in t] + assert not [other for other in values if other != v and v in other] + + +async def test_the_default_kind_sends_the_requests_it_sent_before() -> None: + sent: list[tuple[str, dict]] = [] + + async def post(path: str, body: dict) -> dict: + sent.append((path, body)) + return {"answer": "borealis-e3"} if path == "/v1/memory.ask" else {} + + args = pi_llm._parse([]) + ns = "pi-bench-abc123-d2-e3" + rows = await pi_llm.run_episode(post, ns, "dev", 3, 2, 1, args.credit, args.kinds, args.repeats) + + def write(k: int, day: str, value: str) -> tuple[str, dict]: + text = ( + f"Project status update: as of {day}, Crumwald3's assigned module " + f"is now {value} (this supersedes any earlier assignment)." + ) + return ( + "/v1/memory.set_from_messages", + { + "org": "dev", + "namespace": ns, + "agent": "pi", + "user_id": "ep3", + "session_id": f"ep3-s{k}", + "messages": [{"role": "user", "content": text}], + "max_tokens": 1024, + "observation_date": day, + }, + ) + + assert sent == [ + write(0, "2026-01-02", "azimuthal-e3"), + write(1, "2026-01-03", "borealis-e3"), + ( + "/v1/memory.ask", + { + "reinforce": False, + "org": "dev", + "namespace": ns, + "query": "What module is Crumwald3 currently assigned to? " + "Give the current module only.", + }, + ), + ] + assert [(r["kind"], r["label"]) for r in rows] == [("current", "CORRECT")] + + +def test_score_answer_on_recorded_answers() -> None: + # Episode 0 at depth 5: azimuthal, borealis, cindral, duskwane, emberlyn (-e0). + current, _, asof, _ = pi_llm.questions(0, 5, pi_llm.KINDS) + assert (current.gold, asof.gold) == ("emberlyn-e0", "cindral-e0") + clean = pi_llm.score_answer( + "Quorvex0 is currently assigned to the Emberlyn-e0 module.", current + ) + assert clean == { + "has_gold": True, + "has_stale": False, + "has_later": False, + "clean_correct": True, + "abstain": False, + } + # The gold beside an earlier value is not a clean answer. + moved = pi_llm.score_answer("It moved from duskwane-e0 to emberlyn-e0.", current) + assert moved["has_gold"] and moved["has_stale"] and not moved["clean_correct"] + # A value written after the as-of time is wrong, with or without the gold. + leaked = pi_llm.score_answer("On 2026-01-04 the module was emberlyn-e0.", asof) + assert leaked["has_later"] and not leaked["has_gold"] and not leaked["clean_correct"] + assert not leaked["abstain"] and not leaked["has_stale"] + both = pi_llm.score_answer("cindral-e0 that day; duskwane-e0 from the next.", asof) + assert both["has_gold"] and both["has_later"] and not both["clean_correct"] + assert pi_llm.score_answer("It was cindral-e0.", asof)["clean_correct"] + # No value at all is an abstention, never a correct answer. + for answer in ("I don't have a record of that project's module.", ""): + none = pi_llm.score_answer(answer, asof) + assert none["abstain"] and not none["clean_correct"] + + +# One label list per kind, each of its own length: a pair built from the wrong +# kind, depth or episode holds a list of the wrong length. +_LABELS = { + "current": ["CORRECT"], + "current_2hop": ["WRONG"] * 2, + "asof": ["CORRECT"] * 3, + "asof_2hop": ["WRONG"] * 4, +} + + +def test_gate_pairs_one_fact_with_two_fact_inside_an_episode() -> None: + rows = [ + {"ep": ep, "depth": depth, "kind": q.kind, "labels": _LABELS[q.kind]} + for ep in range(20) + for depth in (1, 2) + for q in pi_llm.questions(ep, depth, pi_llm.KINDS) + ] + # Episode 0's one-fact question at depth 1 errored: its pair is gone. + assert (rows[0]["ep"], rows[0]["depth"], rows[0]["kind"]) == (0, 1, "current") + rows[0] = {**rows[0], "labels": ["ERROR"], "error": {"_err": 500}} + a, b, clusters = pi_llm.gate_pairs(rows) + items = {(ep, 1, "current") for ep in range(20)} | { + (ep, 2, time) for ep in range(20) for time in ("current", "asof") + } + assert set(b) == items and set(a) == items - {(0, 1, "current")} + for key in a: + assert a[key] == _LABELS[key[2]] and b[key] == _LABELS[f"{key[2]}_2hop"] + assert clusters[key] == str(key[0]) + # Every two-fact answer stale, every one-fact answer clean: the two-fact + # question is 100 points worse, far below the -4 margin. + args = pi_llm._parse(["--gate", "--gate-min-delta", "-4"]) + gate = gate_from_args(args, a, b, clusters=clusters) + assert (gate.n, gate.clusters) == (59, 20) + assert (gate.accuracy_a, gate.accuracy_b, gate.verdict) == (1.0, 0.0, "fail") + + +def test_the_planned_run_is_wide_enough() -> None: + # The run `make bench-revision` starts, read from its target. + makefile = (ROOT / "Makefile").read_text() + kinds = re.search(r"--kinds (\S+)", makefile) + depths = re.search(r"^REVISION_DEPTHS = (\S+)$", makefile, re.MULTILINE) + episodes = re.search(r"--episodes \$\(or \$\(EPISODES\),(\d+)\)", makefile) + assert kinds and depths and episodes + rows = [ + {"ep": ep, "depth": depth, "kind": q.kind, "labels": ["CORRECT"]} + for ep in range(int(episodes.group(1))) + for depth in (int(d) for d in depths.group(1).split(",")) + for q in pi_llm.questions(ep, depth, kinds.group(1).split(",")) + ] + a, b, clusters = pi_llm.gate_pairs(rows) + keys = sorted(set(a) & set(b)) + assert len(keys) == 700 and len({clusters[k] for k in keys}) == 100 + # One pair in five differs between the arms, placed at random across the + # episodes: the interval then has a half-width of about 3.1 points. + deltas = [1.0] * 70 + [0.0] * 560 + [-1.0] * 70 + random.Random(0).shuffle(deltas) + boot = paired_bootstrap(deltas, [clusters[k] for k in keys]) + assert (boot.wins, boot.ties, boot.losses) == (70, 560, 70) + assert 3.0 < 100 * (boot.ub - boot.lb) / 2 < DEFAULT_BAND_PP + + +_DRY = ["--dry", "--kinds", ",".join(pi_llm.KINDS), "--depths", "1,2,5", "--episodes", "4"] + + +async def test_dry_run_passes_and_writes_the_artifact_shape( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + out = tmp_path / "pi_llm.jsonl" + flags = [*_DRY, "--repeats", "3", "--gate", "--gate-min-delta", "-4", "--out", str(out)] + assert await pi_llm.main(flags) == 0 + header, *rows = [json.loads(line) for line in out.read_text().splitlines()] + assert header["record"] == "header" and len(header["run_id"]) == 6 + assert header["flags"]["dry"] is True and header["flags"]["repeats"] == 3 + assert header["flags"]["kinds"] == list(pi_llm.KINDS) + # Neither the credential, the server's address nor a local path is recorded. + assert not {"token", "base_url", "out", "audit_out"} & set(header["flags"]) + assert header["instrument"] == run_metadata({}) + # Depth 1 pairs the two questions asked today; depths 2 and 5 add the as-of pair. + assert header["gate"]["n"] == 4 * (1 + 2 + 2) and header["gate"]["clusters"] == 4 + assert header["gate"]["verdict"] == "pass" and header["gate"]["min_delta_pp"] == -4.0 + assert len(rows) == 4 * (2 + 4 + 4) + for row in rows: + assert row["record"] == "question" + assert row["namespace"].endswith(f"-d{row['depth']}-e{row['ep']}") + question = next( + q + for q in pi_llm.questions(row["ep"], row["depth"], pi_llm.KINDS) + if q.kind == row["kind"] + ) + assert row["question"] == question.text and row["as_of"] == question.as_of + assert row["gold"] == question.gold and row["gold_facts"] == list(question.gold_facts) + assert row["superseding_write"] == question.superseding_write + assert row["label"] == "CORRECT" and row["labels"] == ["CORRECT"] * 3 + assert row["has_gold"] and row["clean_correct"] + assert not (row["has_stale"] or row["has_later"] or row["abstain"]) + assert len(row["repeats"]) == 3 + for repeat in row["repeats"]: + assert set(repeat) >= { + "answer", + "label", + "source", + "memory_keys", + "superseded_dropped", + "stale_sentences_masked", + "entity_followed", + "decomposed_parts", + } + assert question.gold in repeat["answer"] and repeat["label"] == "CORRECT" + + # A scorer that calls every answer clean passes the reader that gives another value. + always_clean = {"has_gold": True, "has_stale": False, "has_later": False} + monkeypatch.setattr( + pi_llm, + "score_answer", + lambda _a, _q: {**always_clean, "clean_correct": True, "abstain": False}, + ) + assert await pi_llm.main(_DRY) == 1 + + +def test_a_run_with_no_repeat_is_refused_when_its_flags_are_read( + capsys: pytest.CaptureFixture[str], +) -> None: + # A question asked no time has no label: refused before an episode is written. + for repeats in ("0", "-1"): + with pytest.raises(SystemExit) as refused: + pi_llm._parse(["--repeats", repeats]) + assert refused.value.code == 2 + assert "--repeats" in capsys.readouterr().err + + +_REAL_ASYNC_CLIENT = httpx.AsyncClient +# What a run with --audit-out does, in order: ("clickhouse.connect", {}), +# ("clickhouse.query", params) and (op, body) of each request to the server. +Calls = list[tuple[str, dict[str, Any]]] + + +class _ClickHouse: + """`server.core.ch`'s client: it records a connect and a query in `calls`, + or fails to connect with `error`.""" + + def __init__(self, calls: Calls, error: Exception | None = None) -> None: + self.calls, self.error, self.connected = calls, error, False + + async def connect(self) -> None: + if self.error: + raise self.error + self.calls.append(("clickhouse.connect", {})) + self.connected = True + + async def query_all(self, sql: str, params: dict[str, Any]) -> list[dict[str, Any]]: + self.calls.append(("clickhouse.query", params)) + return [] + + +def _audited_run( + monkeypatch: pytest.MonkeyPatch, error: Exception | None = None +) -> tuple[Calls, list[str]]: + """A server that answers every request and a ClickHouse beside it: (the + calls both received, the flags of a run of two episodes at depth 2).""" + from server.core import ch + + calls: Calls = [] + monkeypatch.setattr(bench_namespaces, "_MINTED", []) + clickhouse = _ClickHouse(calls, error) + monkeypatch.setattr(ch, "get_client", lambda: clickhouse) + + def handler(request: httpx.Request) -> httpx.Response: + op = request.url.path.rsplit("/", 1)[-1] + calls.append((op, json.loads(request.content or b"{}"))) + return httpx.Response(200, json={"answer": "no module on record"}) + + monkeypatch.setattr( + httpx, + "AsyncClient", + lambda **kw: _REAL_ASYNC_CLIENT(transport=httpx.MockTransport(handler), **kw), + ) + return calls, ["--token", "t", "--episodes", "2", "--depths", "2"] + + +async def test_audit_out_is_refused_before_the_first_request_without_its_judge_key_or_clickhouse( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + out = tmp_path / "supersession_audit.json" + # No key for the audit's judge: it would label no pair after the asks were paid for. + calls, flags = _audited_run(monkeypatch) + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + assert await pi_llm.main([*flags, "--audit-out", str(out)]) == 2 + assert calls == [] and not out.exists() + assert "OPENAI_API_KEY" in capsys.readouterr().err + # ClickHouse does not answer: the audit could not read the versions before they are erased. + calls, flags = _audited_run(monkeypatch, error=OSError("connection refused")) + monkeypatch.setenv("OPENAI_API_KEY", "k") + assert await pi_llm.main([*flags, "--audit-out", str(out)]) == 2 + assert calls == [] and not out.exists() + assert "ClickHouse" in capsys.readouterr().err + # Without --audit-out the run needs neither. + monkeypatch.delenv("OPENAI_API_KEY") + assert await pi_llm.main(flags) == 0 + assert [op for op, _ in calls][:2] == ["health", "namespace.register"] + + +async def test_audit_out_reads_the_runs_namespaces_over_the_audits_own_window( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + out = tmp_path / "supersession_audit.json" + calls, flags = _audited_run(monkeypatch) + monkeypatch.setenv("OPENAI_API_KEY", "k") + assert await pi_llm.main([*flags, "--audit-out", str(out)]) == 0 + ops = [op for op, _ in calls] + # ClickHouse is connected once, before the server is asked anything. + assert ops[:2] == ["clickhouse.connect", "health"] and ops.count("clickhouse.connect") == 1 + assert ops.count("memory.set_from_messages") == 4 and ops.count("memory.ask") == 2 + # The audit reads after the last ask and before the erasure. + assert ops[-2:] == ["clickhouse.query", "erasure.request"] + minted = sorted(body["namespace"] for op, body in calls if op == "namespace.register") + assert len(minted) == 2 + # A narrower window than the audit's own drops the keys of a run that outlasts it. + window = inspect.signature(supersession_audit.audit).parameters["days"].default + assert calls[-2][1] == {"org": "dev", "nss": minted, "days": window} + record = json.loads(out.read_text()) + assert record["namespaces"] == minted and record["days"] == window + assert (record["pairs"], record["false_supersession_rate"]) == (0, None)