Skip to content

Commit 1ce1414

Browse files
feat(eval): precision@K guardrail and a value-based paired cluster bootstrap
The §5 pre-registration reports precision@5 beside recall so a widen step that buys recall with junk rows shows up as a number, not a footnote. precision_values reads the gold ids from the ruler's items (ItemScore carries the ranked list but not the answer key) and divides by K even when fewer sessions came back -- an empty or crashed answer is 0.0, never undefined -- and precision_at_k macro-averages it over strata exactly like recall. ArmResult grows a `precision` field and the receipt's metric block a `precision@K` key; existing keys are untouched. paired_cluster_bootstrap is the one resampling scheme every paired interval uses, over an arbitrary per-item value map; cluster_bootstrap now delegates to it over hits. That this changed nothing is pinned rather than asserted: a new test recomputes the Stage 2 receipt's mcp_vs_frozen and frozen_vs_mcp intervals from that receipt's own per-item rows with the frozen seed and resample count and requires float equality with the committed values. The value bootstrap reports `lower_above_zero` (D-12's clause 1) and never `established`, so the weaker §5 rule cannot be mistaken for the programme's established-lift rule.
1 parent cbc4d94 commit 1ce1414

3 files changed

Lines changed: 260 additions & 14 deletions

File tree

‎packages/agent-session-tools/src/agent_session_tools/eval/gold.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import hashlib
1515
import json
1616
import time
17-
from dataclasses import dataclass
17+
from dataclasses import dataclass, field
1818
from pathlib import Path
1919
from typing import TYPE_CHECKING, Any
2020

@@ -26,6 +26,7 @@
2626
hit_and_rank,
2727
latency_percentiles,
2828
mrr_at_k,
29+
precision_at_k,
2930
recall_at_k,
3031
)
3132
from .seam import ArmError, Query, classify_failure
@@ -133,11 +134,14 @@ class ArmResult:
133134
latency_ms: dict[str, float]
134135
config: dict[str, Any]
135136
k: int
137+
#: Macro precision@K (§5 guardrail); the same shape as ``recall``.
138+
precision: dict[str, Any] = field(default_factory=dict)
136139

137140
def metrics(self) -> dict[str, Any]:
138141
"""The receipt's per-arm metric block (no timings -- those are separate)."""
139142
return {
140143
f"recall@{self.k}": self.recall,
144+
f"precision@{self.k}": self.precision,
141145
f"mrr@{self.k}": self.mrr,
142146
"crashes": self.crashes,
143147
"n": len(self.per_item),
@@ -187,6 +191,7 @@ def score_arm(arm: Retriever, items: Sequence[dict[str, Any]], k: int = K) -> Ar
187191
name=arm.name,
188192
per_item=per_item,
189193
recall=recall_at_k(per_item),
194+
precision=precision_at_k(per_item, items, k),
190195
mrr=mrr_at_k(per_item),
191196
errors_by_kind=errors_by_kind(per_item),
192197
crashes=crash_count(per_item),

‎packages/agent-session-tools/src/agent_session_tools/eval/metrics.py‎

Lines changed: 115 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,104 @@ def _clusters_of(
135135
return dict(clusters)
136136

137137

138+
def precision_values(
139+
per_item: Mapping[str, ItemScore], items: Sequence[Mapping[str, Any]], k: int
140+
) -> dict[str, float]:
141+
"""Per-item precision@k: gold sessions among the first ``k`` ranked, over ``k``.
142+
143+
The denominator is ``k`` even when the arm returned fewer sessions -- an
144+
empty (or crashed) answer is precision ``0.0``, never undefined -- so a
145+
widen step that returns five sessions to find one gold is scored against
146+
the same denominator as an ``AND`` arm that returned one (§5
147+
pre-registration, guardrail 2). Gold ids are read from ``items`` because
148+
:class:`ItemScore` carries the ranked list but not the ruler's answer key.
149+
"""
150+
gold = {str(item["id"]): set(item["gold_session_ids"]) for item in items}
151+
return {
152+
item_id: len(set(score.ranked[:k]) & gold.get(item_id, set())) / k
153+
for item_id, score in per_item.items()
154+
}
155+
156+
157+
def macro_average_values(
158+
per_item: Mapping[str, ItemScore], values: Mapping[str, float]
159+
) -> dict[str, Any]:
160+
""":func:`macro_average` over an arbitrary per-item value map (strata from ``per_item``)."""
161+
by_stratum: defaultdict[str, list[float]] = defaultdict(list)
162+
for item_id, score in per_item.items():
163+
by_stratum[score.stratum].append(values[item_id])
164+
if not by_stratum:
165+
return {"by_stratum": {}, "macro": 0.0}
166+
strata = {name: sum(vals) / len(vals) for name, vals in sorted(by_stratum.items())}
167+
return {"by_stratum": strata, "macro": sum(strata.values()) / len(strata)}
168+
169+
170+
def precision_at_k(
171+
per_item: Mapping[str, ItemScore], items: Sequence[Mapping[str, Any]], k: int
172+
) -> dict[str, Any]:
173+
"""Macro precision@K over strata (a guardrail, reported beside recall)."""
174+
return macro_average_values(per_item, precision_values(per_item, items, k))
175+
176+
177+
def _macro_diff_values(
178+
sample: Iterable[str],
179+
clusters: Mapping[str, list[str]],
180+
stratum_of: Mapping[str, str],
181+
a_values: Mapping[str, float],
182+
b_values: Mapping[str, float],
183+
) -> float:
184+
"""Macro (over strata present in the sample) paired difference ``a - b``."""
185+
by_stratum: defaultdict[str, list[float]] = defaultdict(list)
186+
for cluster in sample:
187+
for item_id in clusters[cluster]:
188+
by_stratum[stratum_of[item_id]].append(
189+
a_values[item_id] - b_values[item_id]
190+
)
191+
if not by_stratum:
192+
return 0.0
193+
return sum(sum(v) / len(v) for v in by_stratum.values()) / len(by_stratum)
194+
195+
196+
def paired_cluster_bootstrap(
197+
a_values: Mapping[str, float],
198+
b_values: Mapping[str, float],
199+
items: Sequence[Mapping[str, Any]],
200+
resamples: int = RESAMPLES,
201+
seed: int = SEED,
202+
) -> dict[str, Any]:
203+
"""Paired cluster bootstrap of a macro-averaged per-item value difference ``a - b``.
204+
205+
The one resampling scheme every paired interval in the harness uses: gold
206+
clusters (not items) are drawn with replacement, ``resamples`` times, from
207+
``random.Random(seed)``, and the percentile CI95 of the macro difference
208+
is reported. :func:`cluster_bootstrap` is this over hits; precision and
209+
MRR intervals pass their own per-item values. ``lower_above_zero`` is the
210+
§5 adopt clause 1 (D-12) -- weaker than :data:`.MIN_LIFT`, and named so
211+
the two are never confused.
212+
"""
213+
clusters = _clusters_of(items)
214+
names = sorted(clusters)
215+
stratum_of = {str(item["id"]): str(item["stratum"]) for item in items}
216+
rng = random.Random(seed) # nosec B311 - statistical bootstrap, not cryptography
217+
point = _macro_diff_values(names, clusters, stratum_of, a_values, b_values)
218+
draws = sorted(
219+
_macro_diff_values(
220+
rng.choices(names, k=len(names)), clusters, stratum_of, a_values, b_values
221+
)
222+
for _ in range(resamples)
223+
)
224+
lower = draws[int(0.025 * resamples)] if names else 0.0
225+
upper = draws[max(int(0.975 * resamples) - 1, 0)] if names else 0.0
226+
return {
227+
"point": point,
228+
"ci95": [lower, upper],
229+
"resamples": resamples,
230+
"seed": seed,
231+
"clusters": len(names),
232+
"lower_above_zero": lower > 0.0,
233+
}
234+
235+
138236
def _macro_diff(
139237
sample: Iterable[str],
140238
clusters: Mapping[str, list[str]],
@@ -164,24 +262,24 @@ def cluster_bootstrap(
164262
Gold clusters (not items) are the resampling unit, because items inside a
165263
cluster share a session and are not independent. Percentile CI95; a lift
166264
is *established* only when the lower bound clears :data:`.MIN_LIFT`.
265+
:func:`paired_cluster_bootstrap` over the per-item hits, with the same
266+
draws in the same order (pinned against a committed receipt by
267+
``tests/test_eval_metrics.py``).
167268
"""
168-
clusters = _clusters_of(items)
169-
names = sorted(clusters)
170-
rng = random.Random(seed) # nosec B311 - statistical bootstrap, not cryptography
171-
point = _macro_diff(names, clusters, a_per_item, b_per_item)
172-
draws = sorted(
173-
_macro_diff(rng.choices(names, k=len(names)), clusters, a_per_item, b_per_item)
174-
for _ in range(resamples)
269+
stats = paired_cluster_bootstrap(
270+
{item_id: float(score.hit) for item_id, score in a_per_item.items()},
271+
{item_id: float(score.hit) for item_id, score in b_per_item.items()},
272+
items,
273+
resamples=resamples,
274+
seed=seed,
175275
)
176-
lower = draws[int(0.025 * resamples)]
177-
upper = draws[max(int(0.975 * resamples) - 1, 0)]
178276
return {
179-
"point": point,
180-
"ci95": [lower, upper],
277+
"point": stats["point"],
278+
"ci95": stats["ci95"],
181279
"resamples": resamples,
182280
"seed": seed,
183-
"clusters": len(names),
184-
"established": lower >= MIN_LIFT,
281+
"clusters": stats["clusters"],
282+
"established": stats["ci95"][0] >= MIN_LIFT,
185283
}
186284

187285

@@ -238,7 +336,11 @@ def non_inferiority(
238336
"hit_and_rank",
239337
"latency_percentiles",
240338
"macro_average",
339+
"macro_average_values",
241340
"mrr_at_k",
242341
"non_inferiority",
342+
"paired_cluster_bootstrap",
343+
"precision_at_k",
344+
"precision_values",
243345
"recall_at_k",
244346
]

‎packages/agent-session-tools/tests/test_eval_metrics.py‎

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66

77
from __future__ import annotations
88

9+
import json
10+
from pathlib import Path
11+
912
import pytest
1013

1114
from agent_session_tools.eval import MIN_LIFT, NON_INFERIORITY_MARGIN, RESAMPLES, SEED
@@ -19,6 +22,9 @@
1922
macro_average,
2023
mrr_at_k,
2124
non_inferiority,
25+
paired_cluster_bootstrap,
26+
precision_at_k,
27+
precision_values,
2228
recall_at_k,
2329
)
2430

@@ -215,3 +221,136 @@ def test_one_stratum_can_be_scored_alone(self):
215221
assert result["stratum"] == "P"
216222
assert result["clusters"] == 2
217223
assert result["point"] == 0.0
224+
225+
226+
# --------------------------------------------------------------------------- §5 additions
227+
# precision@K (guardrail) and the value-based paired bootstrap the recall
228+
# bootstrap now delegates to. The delegation is pinned against a COMMITTED
229+
# receipt: the interval recorded at Stage 2 must be reproduced bit for bit from
230+
# that receipt's own per-item rows, or the ruler has moved.
231+
232+
_STAGE2_RECEIPT = (
233+
Path(__file__).resolve().parents[3]
234+
/ "docs/architecture/session-memory/receipts/semantic-layer/stage2-gold-v2.json"
235+
)
236+
_GOLD_DEV = (
237+
Path(__file__).resolve().parents[3]
238+
/ "docs/architecture/session-memory/receipts/gold-v2-dev.json"
239+
)
240+
241+
242+
def _ranked_items() -> tuple[dict[str, ItemScore], list[dict]]:
243+
"""Four items with ranked lists; gold ids chosen so precision is hand-computable."""
244+
per_item = {
245+
"k1": ItemScore("K", "c1", 1, 1.0, 1, ranked=("g1", "x", "y", "z", "w")),
246+
"k2": ItemScore("K", "c1", 1, 0.5, 2, ranked=("x", "g2a", "g2b")),
247+
"p1": ItemScore("P", "c2", 0, 0.0, None, ranked=("x", "y")),
248+
"r1": ItemScore(
249+
"R", "c3", 0, 0.0, None, ranked=()
250+
), # a crash or an empty answer
251+
}
252+
items = [
253+
{"id": "k1", "cluster": "c1", "stratum": "K", "gold_session_ids": ["g1"]},
254+
{
255+
"id": "k2",
256+
"cluster": "c1",
257+
"stratum": "K",
258+
"gold_session_ids": ["g2a", "g2b"],
259+
},
260+
{"id": "p1", "cluster": "c2", "stratum": "P", "gold_session_ids": ["g3"]},
261+
{"id": "r1", "cluster": "c3", "stratum": "R", "gold_session_ids": ["g4"]},
262+
]
263+
return per_item, items
264+
265+
266+
class TestPrecisionAtK:
267+
def test_per_item_precision_divides_by_k_not_by_what_came_back(self):
268+
per_item, items = _ranked_items()
269+
assert precision_values(per_item, items, 5) == {
270+
"k1": 1 / 5,
271+
"k2": 2 / 5, # both gold sessions inside the first five
272+
"p1": 0.0,
273+
"r1": 0.0, # nothing returned is precision 0, never undefined
274+
}
275+
276+
def test_only_the_first_k_ranks_count(self):
277+
per_item, items = _ranked_items()
278+
assert precision_values(per_item, items, 1) == {
279+
"k1": 1.0,
280+
"k2": 0.0,
281+
"p1": 0.0,
282+
"r1": 0.0,
283+
}
284+
285+
def test_macro_precision_averages_strata_not_items(self):
286+
per_item, items = _ranked_items()
287+
result = precision_at_k(per_item, items, 5)
288+
assert result["by_stratum"] == pytest.approx({"K": 0.3, "P": 0.0, "R": 0.0})
289+
assert result["macro"] == pytest.approx(0.1)
290+
291+
def test_empty_input_is_zero_not_a_crash(self):
292+
assert precision_at_k({}, [], 5) == {"by_stratum": {}, "macro": 0.0}
293+
294+
295+
class TestPairedClusterBootstrap:
296+
def test_it_is_the_recall_bootstrap_when_fed_hits(self):
297+
a, b, items = _mixed_clusters()
298+
hits_a = {i: float(s.hit) for i, s in a.items()}
299+
hits_b = {i: float(s.hit) for i, s in b.items()}
300+
values = paired_cluster_bootstrap(hits_a, hits_b, items, resamples=500)
301+
recall = cluster_bootstrap(a, b, items, resamples=500)
302+
assert values["point"] == recall["point"]
303+
assert values["ci95"] == recall["ci95"]
304+
assert values["clusters"] == recall["clusters"] == 15
305+
306+
def test_lower_above_zero_is_strict_and_distinct_from_established(self):
307+
a, b, items = _paired([1, 0, 0, 0], ["K", "P", "R", "R"])
308+
values = paired_cluster_bootstrap(
309+
{i: float(s.hit) for i, s in a.items()},
310+
{i: float(s.hit) for i, s in b.items()},
311+
items,
312+
resamples=200,
313+
)
314+
# Resampling four one-item clusters can leave K out entirely: the
315+
# lower bound is exactly zero, which is NOT strictly above zero.
316+
assert values["ci95"][0] == 0.0
317+
assert values["lower_above_zero"] is False
318+
assert "established" not in values
319+
320+
def test_no_clusters_is_zero_not_a_crash(self):
321+
values = paired_cluster_bootstrap({}, {}, [], resamples=10)
322+
assert values["point"] == 0.0
323+
assert values["ci95"] == [0.0, 0.0]
324+
assert values["clusters"] == 0
325+
326+
@pytest.mark.skipif(
327+
not (_STAGE2_RECEIPT.exists() and _GOLD_DEV.exists()),
328+
reason="committed receipts not present in this checkout",
329+
)
330+
def test_it_reproduces_the_committed_stage2_intervals_bit_for_bit(self):
331+
"""The bootstrap arithmetic is pinned to a receipt in the repository.
332+
333+
Stage 2's ``mcp_vs_frozen`` interval (paired +0.052, CI95 [+0.011,
334+
+0.100]) is recomputed here from that receipt's own per-item rows with
335+
the frozen seed and resample count. Any drift in the draw order, the
336+
percentile arithmetic or the macro-over-strata fold shows up as an
337+
unequal float.
338+
"""
339+
receipt = json.loads(_STAGE2_RECEIPT.read_text())
340+
gold = json.loads(_GOLD_DEV.read_text())["items"]
341+
342+
def scores(arm: str) -> dict[str, ItemScore]:
343+
return {
344+
item_id: ItemScore(
345+
row["stratum"], row["cluster"], row["hit"], row["rr"]
346+
)
347+
for item_id, row in receipt["arms"][arm]["per_item"].items()
348+
}
349+
350+
for pair in ("mcp_vs_frozen", "frozen_vs_mcp"):
351+
a, b = pair.split("_vs_")
352+
fresh = cluster_bootstrap(scores(a), scores(b), gold)
353+
recorded = receipt["comparisons"][pair]
354+
assert fresh["point"] == recorded["point"], pair
355+
assert fresh["ci95"] == recorded["ci95"], pair
356+
assert fresh["established"] == recorded["established"], pair

0 commit comments

Comments
 (0)