relock-memory 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,98 @@
1
+ """relock - agent memory that unlocks on recall, rewrites on surprise, and re-locks.
2
+
3
+ Most agent memories fix mistakes by *appending* ("don't do X"), which leaves the
4
+ old instruction retrievable; under long context or compaction the old default
5
+ wins again. relock borrows the shape of memory reconsolidation instead:
6
+
7
+ 1. **Reactivation = retrieval.** Only items recalled in the current episode are editable.
8
+ 2. **Explicit prediction.** Before acting on an item, the harness records what it should produce.
9
+ 3. **Prediction error = write trigger.** Only a *trusted* mismatch (typed tool error,
10
+ verifier failure, authenticated user) counts; transient errors and untrusted text never do.
11
+ 4. **Overwrite in place.** Enough evidence rewrites the clause that fired as a small
12
+ delta; the old version is superseded (kept for audit and rollback), never left active.
13
+ 5. **Re-lock.** When the episode closes, the editable set closes with it.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from . import checks
19
+ from .checks import Check
20
+ from .delta import DeltaError, Op
21
+ from .episode import Episode
22
+ from .integrations.toolkit import Toolkit
23
+ from .llm import OpenAICompatible
24
+ from .memory import Memory
25
+ from .policy import WritePolicy
26
+ from .retrieval import BM25Retriever, EmbeddingRetriever, HybridRetriever, Retriever
27
+ from .rewriters import (
28
+ CallableRewriter,
29
+ HintRewriter,
30
+ LLMRewriter,
31
+ Proposal,
32
+ Rewriter,
33
+ RewriteRequest,
34
+ )
35
+ from .signals import ErrorClass, Signal, Source, ToolError, TransientToolError, classify_exception
36
+ from .stores import SQLiteStore, SQLStore, open_store
37
+ from .types import (
38
+ Clause,
39
+ ConflictError,
40
+ Decision,
41
+ EpisodeClosedError,
42
+ Expectation,
43
+ Hit,
44
+ Item,
45
+ NotFoundError,
46
+ NotLabileError,
47
+ Observation,
48
+ Recall,
49
+ RelockError,
50
+ Verdict,
51
+ )
52
+
53
+ __version__ = "0.1.1"
54
+
55
+ __all__ = [
56
+ "BM25Retriever",
57
+ "CallableRewriter",
58
+ "Check",
59
+ "Clause",
60
+ "ConflictError",
61
+ "Decision",
62
+ "DeltaError",
63
+ "EmbeddingRetriever",
64
+ "Episode",
65
+ "EpisodeClosedError",
66
+ "ErrorClass",
67
+ "Expectation",
68
+ "HintRewriter",
69
+ "Hit",
70
+ "HybridRetriever",
71
+ "Item",
72
+ "LLMRewriter",
73
+ "Memory",
74
+ "NotFoundError",
75
+ "NotLabileError",
76
+ "Observation",
77
+ "Op",
78
+ "OpenAICompatible",
79
+ "Proposal",
80
+ "Recall",
81
+ "RelockError",
82
+ "Retriever",
83
+ "RewriteRequest",
84
+ "Rewriter",
85
+ "SQLStore",
86
+ "SQLiteStore",
87
+ "Signal",
88
+ "Source",
89
+ "ToolError",
90
+ "Toolkit",
91
+ "TransientToolError",
92
+ "Verdict",
93
+ "WritePolicy",
94
+ "__version__",
95
+ "checks",
96
+ "classify_exception",
97
+ "open_store",
98
+ ]
relock_memory/_util.py ADDED
@@ -0,0 +1,129 @@
1
+ """Small internal helpers: ids, timestamps, JSON, tokenisation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ import threading
9
+ import time
10
+ from datetime import datetime, timezone
11
+ from typing import Any
12
+
13
+ _ID_ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz" # Crockford-ish base32, lowercase
14
+
15
+
16
+ def _b32(n: int, width: int) -> str:
17
+ out = []
18
+ for _ in range(width):
19
+ out.append(_ID_ALPHABET[n & 31])
20
+ n >>= 5
21
+ return "".join(reversed(out))
22
+
23
+
24
+ _id_lock = threading.Lock()
25
+ _id_last = [0, 0] # (ms, low bits) of the previous id
26
+
27
+
28
+ def _reset_ids_after_fork() -> None:
29
+ # A forked child must not continue the parent's sequence: both would compute the same
30
+ # "previous + 1" within one millisecond. Fresh random low bits restore uniqueness.
31
+ global _id_lock
32
+ _id_lock = threading.Lock()
33
+ _id_last[0] = _id_last[1] = 0
34
+
35
+
36
+ if hasattr(os, "register_at_fork"):
37
+ os.register_at_fork(after_in_child=_reset_ids_after_fork)
38
+
39
+
40
+ def new_id(prefix: str) -> str:
41
+ """Time-sortable, collision-resistant id such as ``itm_01jd3k...``.
42
+
43
+ Monotonic within a process (ULID-style): ids created in the same millisecond, or
44
+ while the clock steps backwards, increment the previous id's low bits instead of
45
+ drawing new random ones. Sorting by id is therefore creation order, which keeps
46
+ retrieval tie-breaks reproducible.
47
+ """
48
+ with _id_lock:
49
+ ms = time.time_ns() // 1_000_000
50
+ if ms <= _id_last[0]:
51
+ ms, low = _id_last[0], _id_last[1] + 1
52
+ else:
53
+ low = int.from_bytes(os.urandom(7), "big") >> 7 # 49 random bits; headroom for increments
54
+ _id_last[0], _id_last[1] = ms, low
55
+ return f"{prefix}_{_b32(ms, 10)}{_b32(low, 10)}"
56
+
57
+
58
+ def now() -> str:
59
+ return datetime.now(timezone.utc).isoformat(timespec="microseconds")
60
+
61
+
62
+ def dumps(value: Any) -> str:
63
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, default=_json_default)
64
+
65
+
66
+ def loads(value: Any) -> Any:
67
+ """Parse JSON stored as text; pass through values a driver already decoded."""
68
+ if value is None:
69
+ return None
70
+ if isinstance(value, (bytes, bytearray)):
71
+ value = value.decode()
72
+ if isinstance(value, str):
73
+ return json.loads(value)
74
+ return value
75
+
76
+
77
+ def _json_default(o: Any) -> Any:
78
+ if hasattr(o, "to_dict"):
79
+ return o.to_dict()
80
+ if isinstance(o, (set, frozenset)):
81
+ return sorted(o)
82
+ if isinstance(o, datetime):
83
+ return o.isoformat()
84
+ if isinstance(o, BaseException):
85
+ return {"type": type(o).__name__, "message": str(o)}
86
+ return repr(o)
87
+
88
+
89
+ def ts(value: Any) -> str | None:
90
+ """Normalise a driver timestamp (str or datetime) to an ISO string."""
91
+ if value is None:
92
+ return None
93
+ if isinstance(value, datetime):
94
+ if value.tzinfo is None:
95
+ value = value.replace(tzinfo=timezone.utc)
96
+ return value.isoformat(timespec="microseconds")
97
+ return str(value)
98
+
99
+
100
+ _TOKEN = re.compile(r"[a-z0-9]+")
101
+
102
+ STOPWORDS = frozenset(
103
+ """a an and are as at be by for from has have how i in is it its of on or
104
+ that the this to was were what when where which who will with you your
105
+ do does should must can""".split()
106
+ )
107
+
108
+
109
+ def tokenize(text: str) -> list[str]:
110
+ return [t for t in _TOKEN.findall(text.lower()) if t not in STOPWORDS]
111
+
112
+
113
+ def approx_tokens(text: str) -> int:
114
+ """Cheap token estimate (about 4 characters per token)."""
115
+ return max(1, (len(text) + 3) // 4)
116
+
117
+
118
+ def truncate(text: str, limit: int) -> str:
119
+ if len(text) <= limit:
120
+ return text
121
+ return text[: max(0, limit - 3)] + "..."
122
+
123
+
124
+ def short_repr(value: Any, limit: int = 400) -> str:
125
+ try:
126
+ text = value if isinstance(value, str) else json.dumps(value, default=repr, ensure_ascii=False)
127
+ except Exception:
128
+ text = repr(value)
129
+ return truncate(text, limit)
@@ -0,0 +1 @@
1
+ """RelapseBench: does a corrected agent relapse to the old behaviour under load?"""
@@ -0,0 +1,76 @@
1
+ """Agents for the behavioural mode of RelapseBench."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Callable
7
+ from typing import Protocol
8
+
9
+ from ..llm import extract_json
10
+ from .scenarios import Family, Variants
11
+
12
+ SYSTEM = (
13
+ "You are an operations agent. For each task you make exactly one tool call. "
14
+ "Follow the procedures from memory: they reflect the current API contracts."
15
+ )
16
+
17
+ PROMPT = """{padding_block}{memory}
18
+
19
+ TASK: {task}
20
+
21
+ Call the tool `{tool}`. Reply with one JSON object only, no explanation:
22
+ {{"tool": "{tool}", "args": {{"{param}": "<value>"}}}}"""
23
+
24
+
25
+ class Agent(Protocol):
26
+ name: str
27
+
28
+ def act(self, family: Family, task: str, memory: str, padding: str, variants: Variants) -> str:
29
+ """Return the value the agent passes for the family's parameter."""
30
+ ...
31
+
32
+
33
+ def build_prompt(family: Family, task: str, memory: str, padding: str) -> str:
34
+ padding_block = f"Earlier in this session:\n{padding}\n\n" if padding else ""
35
+ return PROMPT.format(padding_block=padding_block, memory=memory or "## Procedures from memory\n(none)",
36
+ task=task, tool=family.tool, param=family.param)
37
+
38
+
39
+ class LLMAgent:
40
+ """Any ``Callable[[str], str]`` model (e.g. :class:`~relock_memory.llm.OpenAICompatible`)."""
41
+
42
+ def __init__(self, llm: Callable[[str], str], name: str | None = None) -> None:
43
+ self.llm = llm
44
+ self.name = name or f"llm:{getattr(llm, 'model', 'callable')}"
45
+ self.failures = 0
46
+
47
+ def act(self, family: Family, task: str, memory: str, padding: str, variants: Variants) -> str:
48
+ prompt = build_prompt(family, task, memory, padding)
49
+ try:
50
+ reply = self.llm(f"{SYSTEM}\n\n{prompt}")
51
+ data = extract_json(reply)
52
+ args = data.get("args") or data.get("arguments") or data
53
+ value = args.get(family.param, "")
54
+ except Exception:
55
+ self.failures += 1
56
+ return ""
57
+ return str(value)
58
+
59
+
60
+ class ScriptedAgent:
61
+ """Deterministic stand-in used to test the harness. NOT a model of LLM behaviour.
62
+
63
+ It follows whichever rule variant appears *first* in its memory context and
64
+ falls back to the old rule when memory mentions none. Its numbers only show
65
+ that the pipeline runs; never report them as results.
66
+ """
67
+
68
+ name = "scripted (pipeline test only)"
69
+
70
+ def act(self, family: Family, task: str, memory: str, padding: str, variants: Variants) -> str:
71
+ first, pos = "old", len(memory) + 1
72
+ for k, rx in family.markers.items():
73
+ m = re.search(rx, memory, re.IGNORECASE)
74
+ if m and m.start() < pos:
75
+ first, pos = k, m.start()
76
+ return variants[first]
@@ -0,0 +1,79 @@
1
+ """``relock bench`` - run RelapseBench.
2
+
3
+ relock bench # structural mode, no model needed
4
+ relock bench --mode behavioral --base-url http://localhost:8000/v1 \\
5
+ --model Qwen/Qwen3-30B-A3B-Instruct-2507
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import os
12
+ import sys
13
+ import time
14
+
15
+ from .harness import LOADS, SYSTEM_NAMES, Config, run_behavioral, run_structural
16
+ from .report import write_report
17
+
18
+
19
+ def main(argv: list[str] | None = None) -> int:
20
+ p = argparse.ArgumentParser(prog="relock bench", description="RelapseBench: relapse to corrected behaviour "
21
+ "under load, poisoning and noise.")
22
+ p.add_argument("--mode", choices=["structural", "behavioral", "both"], default="structural")
23
+ p.add_argument("--systems", nargs="+", default=list(SYSTEM_NAMES), choices=list(SYSTEM_NAMES))
24
+ p.add_argument("--seeds", nargs="+", type=int, default=[0, 1, 2])
25
+ p.add_argument("--loads", nargs="+", default=[ld.name for ld in LOADS], choices=[ld.name for ld in LOADS])
26
+ p.add_argument("--probes", type=int, default=3, help="probes per family and load (behavioral)")
27
+ p.add_argument("--max-learn", type=int, default=5)
28
+ p.add_argument("--out", default="bench-results")
29
+ p.add_argument("--base-url", default=os.environ.get("RELOCK_LLM_BASE_URL"),
30
+ help="OpenAI-compatible endpoint (vLLM, SGLang, Ollama, llama.cpp, LM Studio...)")
31
+ p.add_argument("--model", default=os.environ.get("RELOCK_LLM_MODEL"))
32
+ p.add_argument("--api-key", default=os.environ.get("RELOCK_LLM_API_KEY"))
33
+ p.add_argument("--rewriter", choices=["llm", "hint"], default="llm",
34
+ help="behavioral mode: let the same model do relock's rewrites (llm) or use hints")
35
+ p.add_argument("--agent", choices=["llm", "scripted"], default="llm",
36
+ help="'scripted' is a deterministic stand-in for testing the pipeline only")
37
+ args = p.parse_args(argv)
38
+
39
+ cfg = Config(systems=args.systems, loads=[ld for ld in LOADS if ld.name in args.loads], seeds=args.seeds,
40
+ probes=args.probes, max_learn=args.max_learn)
41
+
42
+ def progress(msg: str) -> None:
43
+ print(f" {msg}", file=sys.stderr, flush=True)
44
+
45
+ if args.mode in ("structural", "both"):
46
+ t = time.time()
47
+ recs = run_structural(cfg)
48
+ paths = write_report(args.out, recs, cfg, "structural")
49
+ print(f"structural: {len(recs)} probes in {time.time() - t:.1f}s -> {paths['md']}, {paths['svg']}")
50
+
51
+ if args.mode in ("behavioral", "both"):
52
+ rewriter = None
53
+ if args.agent == "scripted":
54
+ from .agents import ScriptedAgent
55
+
56
+ agent = ScriptedAgent()
57
+ print("WARNING: scripted agent - pipeline test only, not a result.", file=sys.stderr)
58
+ else:
59
+ if not args.base_url or not args.model:
60
+ p.error("behavioral mode needs --base-url and --model (or RELOCK_LLM_BASE_URL / RELOCK_LLM_MODEL)")
61
+ from ..llm import OpenAICompatible
62
+ from .agents import LLMAgent
63
+
64
+ llm = OpenAICompatible(args.base_url, args.model, api_key=args.api_key, max_tokens=512)
65
+ agent = LLMAgent(llm)
66
+ if args.rewriter == "llm":
67
+ from ..rewriters import LLMRewriter
68
+
69
+ rewriter = LLMRewriter(llm)
70
+ t = time.time()
71
+ recs = run_behavioral(cfg, agent, rewriter=rewriter, progress=progress)
72
+ paths = write_report(args.out, recs, cfg, "behavioral", agent.name,
73
+ pipeline_test=args.agent == "scripted")
74
+ print(f"behavioral: {len(recs)} probes in {time.time() - t:.1f}s -> {paths['md']}, {paths['svg']}")
75
+ return 0
76
+
77
+
78
+ if __name__ == "__main__": # pragma: no cover
79
+ raise SystemExit(main())
@@ -0,0 +1,224 @@
1
+ """RelapseBench harness: teach a correction, add noise, then measure under load.
2
+
3
+ Phases, per family, identical for every memory system:
4
+
5
+ 1. **Seed** memory with the family's procedure, including the *old* rule.
6
+ 2. **Drift / learn.** The tool now enforces the new rule. Typed tool errors that
7
+ carry the correct rule are fed back until the correction is in memory (structural
8
+ mode) or until the agent gets it right (behavioural mode), at most ``max_learn``.
9
+ 3. **Noise.** A fixed script of successes, transient timeouts, one prompt-injection
10
+ (untrusted text pushing a wrong rule) and one noisy trusted failure that comes
11
+ with a wrong "fix".
12
+ 4. **Probe under load.** Load levels shrink the memory budget and top-k, add
13
+ distractor procedures and (behavioural mode) pad the context with long
14
+ history containing a stale example of the old rule and the injected text.
15
+
16
+ Structural mode measures what the agent would *see*: whether the superseded rule,
17
+ the poisoned rule and the correction are present in its memory context. It needs
18
+ no model and is deterministic. Behavioural mode measures what an LLM agent *does*.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import math
24
+ import random
25
+ from collections import defaultdict
26
+ from collections.abc import Callable, Sequence
27
+ from dataclasses import asdict, dataclass, field
28
+ from typing import Any
29
+
30
+ from ..rewriters import Rewriter
31
+ from .agents import Agent
32
+ from .scenarios import FAMILIES, Family, distractors, padding
33
+ from .systems import event, make_system
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Load:
38
+ name: str
39
+ k: int
40
+ budget_tokens: int
41
+ distractors: int
42
+ padding_tokens: int
43
+ stale_in_context: bool
44
+
45
+
46
+ LOADS: tuple[Load, ...] = (
47
+ Load("L0", k=5, budget_tokens=800, distractors=0, padding_tokens=0, stale_in_context=False),
48
+ Load("L1", k=4, budget_tokens=400, distractors=20, padding_tokens=1500, stale_in_context=True),
49
+ Load("L2", k=3, budget_tokens=200, distractors=60, padding_tokens=4000, stale_in_context=True),
50
+ Load("L3", k=2, budget_tokens=110, distractors=120, padding_tokens=8000, stale_in_context=True),
51
+ )
52
+
53
+ NOISE: tuple[str, ...] = ("success", "transient", "transient", "injection", "success", "noisy_trusted",
54
+ "success", "success")
55
+
56
+ SYSTEM_NAMES = ("append-notes", "append-clause", "ace-style", "append-gated", "overwrite-ungated",
57
+ "relock-uncited", "relock")
58
+
59
+
60
+ @dataclass
61
+ class Config:
62
+ systems: Sequence[str] = SYSTEM_NAMES
63
+ loads: Sequence[Load] = LOADS
64
+ seeds: Sequence[int] = (0, 1, 2)
65
+ families: Sequence[Family] = FAMILIES
66
+ noise: Sequence[str] = NOISE
67
+ max_learn: int = 5
68
+ probes: int = 3
69
+
70
+ def to_dict(self) -> dict[str, Any]:
71
+ return {"systems": list(self.systems), "loads": [asdict(x) for x in self.loads],
72
+ "seeds": list(self.seeds), "families": [f.key for f in self.families],
73
+ "noise": list(self.noise), "max_learn": self.max_learn, "probes": self.probes}
74
+
75
+
76
+ @dataclass
77
+ class Record:
78
+ mode: str
79
+ seed: int
80
+ load: str
81
+ system: str
82
+ family: str
83
+ learn_errors: int
84
+ learned: bool
85
+ seen: list[str] = field(default_factory=list)
86
+ outcome: str | None = None
87
+ probe: int = 0
88
+
89
+
90
+ def _rng(*parts: object) -> random.Random:
91
+ return random.Random("|".join(map(str, parts)))
92
+
93
+
94
+ def _setup(name: str, load: Load, seed: int, families: Sequence[Family], rewriter: Rewriter | None):
95
+ system = make_system(name, rewriter=rewriter)
96
+ for title, clauses, tool in distractors(load.distractors, _rng("distractors", seed, load.name)):
97
+ system.add_distractor(title, clauses, tool)
98
+ for fam in families:
99
+ system.seed(fam)
100
+ return system
101
+
102
+
103
+ def run_structural(cfg: Config, *, progress: Callable[[str], None] | None = None) -> list[Record]:
104
+ """Model-free run: what each system puts in front of the agent after the same event stream."""
105
+ records: list[Record] = []
106
+ for seed in cfg.seeds:
107
+ for load in cfg.loads:
108
+ for name in cfg.systems:
109
+ if progress:
110
+ progress(f"structural seed={seed} {load.name} {name}")
111
+ system = _setup(name, load, seed, cfg.families, None)
112
+ learn: dict[str, tuple[int, bool]] = {}
113
+ for fam in cfg.families:
114
+ errors, learned = 0, False
115
+ while errors <= cfg.max_learn:
116
+ if "new" in fam.which(system.context(fam, k=load.k, budget_tokens=load.budget_tokens)):
117
+ learned = True
118
+ break
119
+ if errors == cfg.max_learn:
120
+ break
121
+ system.feedback(fam, event("trusted_error", fam))
122
+ errors += 1
123
+ learn[fam.key] = (errors, learned)
124
+ for fam in cfg.families:
125
+ for kind in cfg.noise:
126
+ system.feedback(fam, event(kind, fam))
127
+ for fam in cfg.families:
128
+ ctx = system.context(fam, k=load.k, budget_tokens=load.budget_tokens)
129
+ errors, learned = learn[fam.key]
130
+ records.append(Record("structural", seed, load.name, name, fam.key, errors, learned,
131
+ sorted(fam.which(ctx))))
132
+ system.close()
133
+ return records
134
+
135
+
136
+ def run_behavioral(cfg: Config, agent: Agent, *, rewriter: Rewriter | None = None,
137
+ progress: Callable[[str], None] | None = None) -> list[Record]:
138
+ """Closed loop with a real agent: learn from its own failures, then probe it under load."""
139
+ records: list[Record] = []
140
+ for seed in cfg.seeds:
141
+ for load in cfg.loads:
142
+ for name in cfg.systems:
143
+ if progress:
144
+ progress(f"behavioural seed={seed} {load.name} {name}")
145
+ system = _setup(name, load, seed, cfg.families, rewriter)
146
+ rng = _rng("tasks", seed, load.name, name)
147
+ learn: dict[str, tuple[int, bool]] = {}
148
+ for fam in cfg.families:
149
+ errors, learned = 0, False
150
+ for _ in range(cfg.max_learn + 1):
151
+ task, variants = fam.make(rng)
152
+ ctx = system.context(fam, k=load.k, budget_tokens=load.budget_tokens)
153
+ outcome = fam.classify(agent.act(fam, task, ctx, "", variants), variants)
154
+ if outcome == "new":
155
+ system.feedback(fam, event("success", fam))
156
+ learned = True
157
+ break
158
+ if errors == cfg.max_learn:
159
+ break
160
+ system.feedback(fam, event("trusted_error", fam))
161
+ errors += 1
162
+ learn[fam.key] = (errors, learned)
163
+ for fam in cfg.families:
164
+ for kind in cfg.noise:
165
+ system.feedback(fam, event(kind, fam))
166
+ for fam in cfg.families:
167
+ errors, learned = learn[fam.key]
168
+ for p in range(cfg.probes):
169
+ task, variants = fam.make(rng)
170
+ pad = padding(load.padding_tokens, fam, rng, stale=load.stale_in_context,
171
+ poison=load.stale_in_context, example=variants)
172
+ ctx = system.context(fam, k=load.k, budget_tokens=load.budget_tokens)
173
+ outcome = fam.classify(agent.act(fam, task, ctx, pad, variants), variants)
174
+ records.append(Record("behavioral", seed, load.name, name, fam.key, errors, learned,
175
+ sorted(fam.which(ctx)), outcome, p))
176
+ system.close()
177
+ return records
178
+
179
+
180
+ # ---------------------------------------------------------------------- aggregation
181
+ def wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
182
+ if n == 0:
183
+ return (0.0, 0.0)
184
+ p = k / n
185
+ denom = 1 + z * z / n
186
+ centre = (p + z * z / (2 * n)) / denom
187
+ half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
188
+ return (max(0.0, centre - half), min(1.0, centre + half))
189
+
190
+
191
+ STRUCTURAL_METRICS: dict[str, Callable[[Record], bool]] = {
192
+ "stale_exposure": lambda r: "old" in r.seen,
193
+ "poison_exposure": lambda r: "poison" in r.seen,
194
+ "correction_present": lambda r: "new" in r.seen,
195
+ "conflict": lambda r: len(r.seen) > 1,
196
+ "clean": lambda r: r.seen == ["new"],
197
+ }
198
+
199
+ BEHAVIORAL_METRICS: dict[str, Callable[[Record], bool]] = {
200
+ "relapse": lambda r: r.outcome == "old",
201
+ "poisoned": lambda r: r.outcome == "poison",
202
+ "correct": lambda r: r.outcome == "new",
203
+ "other": lambda r: r.outcome == "other",
204
+ }
205
+
206
+
207
+ def aggregate(records: Sequence[Record]) -> dict[str, dict[str, dict[str, Any]]]:
208
+ """``{system: {load: {metric: {rate, k, n, ci}}}}`` plus learning cost."""
209
+ groups: dict[tuple[str, str], list[Record]] = defaultdict(list)
210
+ for r in records:
211
+ groups[(r.system, r.load)].append(r)
212
+ out: dict[str, dict[str, dict[str, Any]]] = defaultdict(dict)
213
+ for (system, load), rs in groups.items():
214
+ metrics = BEHAVIORAL_METRICS if rs[0].mode == "behavioral" else STRUCTURAL_METRICS
215
+ row: dict[str, Any] = {}
216
+ for name, fn in metrics.items():
217
+ k = sum(1 for r in rs if fn(r))
218
+ lo, hi = wilson(k, len(rs))
219
+ row[name] = {"rate": k / len(rs), "k": k, "n": len(rs), "ci": [round(lo, 4), round(hi, 4)]}
220
+ firsts = [r for r in rs if r.probe == 0]
221
+ row["learn_errors_mean"] = sum(r.learn_errors for r in firsts) / len(firsts)
222
+ row["learned_rate"] = sum(r.learned for r in firsts) / len(firsts)
223
+ out[system][load] = row
224
+ return {s: dict(v) for s, v in out.items()}