Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -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`).
Expand Down Expand Up @@ -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:
Expand Down
16 changes: 14 additions & 2 deletions bench/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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/`
Expand All @@ -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,
Expand All @@ -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

Expand Down Expand Up @@ -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` |
61 changes: 55 additions & 6 deletions bench/fama_forgetting.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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)
Expand Down
59 changes: 56 additions & 3 deletions bench/forget_switch_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
"""
Expand All @@ -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."},
Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -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()) + " "

Expand All @@ -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:
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand All @@ -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]:
Expand Down
Loading
Loading