context-engineering-core 0.12.0__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.
- context_engine/__init__.py +15 -0
- context_engine/__main__.py +3 -0
- context_engine/_sqlite.py +19 -0
- context_engine/_windows_security.py +125 -0
- context_engine/_windows_storage.py +110 -0
- context_engine/adapters.py +148 -0
- context_engine/answers.py +90 -0
- context_engine/budget.py +93 -0
- context_engine/cli.py +222 -0
- context_engine/config.py +193 -0
- context_engine/context.py +116 -0
- context_engine/demo.py +98 -0
- context_engine/errors.py +91 -0
- context_engine/evaluation/__init__.py +1 -0
- context_engine/evaluation/commands.py +90 -0
- context_engine/evaluation/corpus.py +247 -0
- context_engine/evaluation/data/freeze.json +26 -0
- context_engine/evaluation/data/ground_truth.json +287 -0
- context_engine/evaluation/data/pin_retention.json +8 -0
- context_engine/evaluation/data/protocol.json +122 -0
- context_engine/evaluation/data/scenario.json +1226 -0
- context_engine/evaluation/data/summary_fixture.json +7 -0
- context_engine/evaluation/execution.py +538 -0
- context_engine/evaluation/fixtures.py +32 -0
- context_engine/evaluation/grading.py +62 -0
- context_engine/evaluation/harness.py +165 -0
- context_engine/evaluation/heldout/__init__.py +260 -0
- context_engine/evaluation/heldout/__main__.py +40 -0
- context_engine/evaluation/heldout/data/ground_truth.json +18 -0
- context_engine/evaluation/heldout/data/manifest.json +9 -0
- context_engine/evaluation/heldout/data/protocol.json +14 -0
- context_engine/evaluation/heldout/data/scenarios.json +18 -0
- context_engine/evaluation/heldout/data/scoring_manifest.json +4 -0
- context_engine/evaluation/heldout/data/scoring_protocol.json +12 -0
- context_engine/evaluation/heldout/scoring.py +176 -0
- context_engine/evaluation/protocol.py +264 -0
- context_engine/evaluation/reporting.py +294 -0
- context_engine/evaluation/results.py +331 -0
- context_engine/evaluation/run_commands.py +146 -0
- context_engine/evaluation/strategies.py +261 -0
- context_engine/inspection.py +266 -0
- context_engine/layers/__init__.py +18 -0
- context_engine/layers/cap.py +99 -0
- context_engine/layers/common.py +162 -0
- context_engine/layers/pin.py +68 -0
- context_engine/layers/retrieve.py +233 -0
- context_engine/layers/summarize.py +202 -0
- context_engine/layers/window.py +29 -0
- context_engine/mcp_server.py +267 -0
- context_engine/memory/__init__.py +5 -0
- context_engine/memory/codec.py +91 -0
- context_engine/memory/demo.py +90 -0
- context_engine/memory/store.py +770 -0
- context_engine/models.py +384 -0
- context_engine/pipeline.py +383 -0
- context_engine/providers/__init__.py +1 -0
- context_engine/providers/client.py +301 -0
- context_engine/providers/commands.py +138 -0
- context_engine/providers/contracts.py +324 -0
- context_engine/providers/credentials.py +66 -0
- context_engine/providers/memory.py +112 -0
- context_engine/providers/store.py +408 -0
- context_engine/providers/transport.py +195 -0
- context_engine/providers/windows_credentials.py +23 -0
- context_engine/py.typed +0 -0
- context_engine/service/__init__.py +1 -0
- context_engine/service/__main__.py +68 -0
- context_engine/service/app.py +404 -0
- context_engine/service/auth.py +132 -0
- context_engine/service/client.py +52 -0
- context_engine/service/control.py +134 -0
- context_engine/service/demo.py +151 -0
- context_engine/service/integrations.py +28 -0
- context_engine/service/schemas.py +59 -0
- context_engine/service/worker.py +59 -0
- context_engine/service/workers.py +156 -0
- context_engine/summaries.py +196 -0
- context_engine/tokens.py +171 -0
- context_engine/work.py +46 -0
- context_engineering_core-0.12.0.dist-info/METADATA +203 -0
- context_engineering_core-0.12.0.dist-info/RECORD +84 -0
- context_engineering_core-0.12.0.dist-info/WHEEL +4 -0
- context_engineering_core-0.12.0.dist-info/entry_points.txt +3 -0
- context_engineering_core-0.12.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
"""Deterministic scorecard, leaderboard and PNG figures from saved benchmark evidence only."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import io
|
|
5
|
+
import json
|
|
6
|
+
from importlib import metadata
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from statistics import median
|
|
9
|
+
|
|
10
|
+
from ..errors import BenchmarkError
|
|
11
|
+
from .execution import validate_execution
|
|
12
|
+
from .grading import proportion
|
|
13
|
+
from .results import assess_targets, statistics
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def scorecard(bundle, frozen, payload):
|
|
17
|
+
manifest, records, validation = validate_execution(bundle, frozen, payload)
|
|
18
|
+
receipt_by_id = {e["probe_id"]: e["receipt"] for e in payload["entries"] if e["receipt"]}
|
|
19
|
+
groups = statistics(manifest, records)
|
|
20
|
+
for group in groups:
|
|
21
|
+
selected = [
|
|
22
|
+
r
|
|
23
|
+
for r in records
|
|
24
|
+
if (r["model"], r["budget"], r["variant"])
|
|
25
|
+
== (group["model"], group["budget"], group["variant"])
|
|
26
|
+
]
|
|
27
|
+
receipts = [
|
|
28
|
+
receipt_by_id[r["probe_id"]] for r in selected if r["probe_id"] in receipt_by_id
|
|
29
|
+
]
|
|
30
|
+
costs = [r["result"]["new_cost_microusd"] for r in receipts]
|
|
31
|
+
group["new_cost_microusd"] = sum(c for c in costs if c is not None)
|
|
32
|
+
group["cost_complete"] = (
|
|
33
|
+
bool(receipts) and all(c is not None for c in costs) and group["pending"] == 0
|
|
34
|
+
)
|
|
35
|
+
group["unknown_cost_outcomes"] = sum(c is None for c in costs)
|
|
36
|
+
group["replays"] = sum(r["result"]["status"] == "replay" for r in receipts)
|
|
37
|
+
group["median_estimated_input_tokens"] = (
|
|
38
|
+
median(r["estimate"]["estimated_tokens"] for r in selected) if selected else None
|
|
39
|
+
)
|
|
40
|
+
group["median_estimated_input_reduction"] = (
|
|
41
|
+
median(
|
|
42
|
+
1 - r["estimate"]["estimated_tokens"] / r["raw_estimated_tokens"] for r in selected
|
|
43
|
+
)
|
|
44
|
+
if selected
|
|
45
|
+
else None
|
|
46
|
+
)
|
|
47
|
+
attempts = [
|
|
48
|
+
a
|
|
49
|
+
for receipt in receipts
|
|
50
|
+
for a in receipt["ledger_rows"]
|
|
51
|
+
if a["id"] in receipt["result"]["attempt_ids"]
|
|
52
|
+
]
|
|
53
|
+
usages = [json.loads(a["usage_json"]) for a in attempts if a["usage_json"]]
|
|
54
|
+
group["observed_attempt_usage"] = {
|
|
55
|
+
"input_tokens": sum(u["input_tokens"] for u in usages),
|
|
56
|
+
"output_tokens": sum(u["output_tokens"] for u in usages),
|
|
57
|
+
"cached_input_tokens_known": sum(u["cached_input_tokens"] or 0 for u in usages),
|
|
58
|
+
"reasoning_tokens_known": sum(u["reasoning_tokens"] or 0 for u in usages),
|
|
59
|
+
"cached_details_unknown": sum(u["cached_input_tokens"] is None for u in usages),
|
|
60
|
+
"reasoning_details_unknown": sum(u["reasoning_tokens"] is None for u in usages),
|
|
61
|
+
"attempts_with_usage": len(usages),
|
|
62
|
+
"attempts": len(attempts),
|
|
63
|
+
"unknown_usage_attempts": sum(a["cost"] is None for a in attempts),
|
|
64
|
+
}
|
|
65
|
+
group["zones"] = {}
|
|
66
|
+
for zone in ("early", "middle", "late"):
|
|
67
|
+
slots = [
|
|
68
|
+
s
|
|
69
|
+
for s in manifest.slots
|
|
70
|
+
if (s["model"], s["budget"], s["variant"])
|
|
71
|
+
== (group["model"], group["budget"], group["variant"])
|
|
72
|
+
and bundle.fact(s["fact_id"])["zone"] == zone
|
|
73
|
+
]
|
|
74
|
+
rows = [r for r in selected if bundle.fact(r["fact_id"])["zone"] == zone]
|
|
75
|
+
group["zones"][zone] = {
|
|
76
|
+
"retained": proportion(
|
|
77
|
+
sum(r["state"] != "non_fit" and r["retained_evidence"] for r in rows),
|
|
78
|
+
len(slots),
|
|
79
|
+
),
|
|
80
|
+
"answer_correct": proportion(
|
|
81
|
+
sum(r["answer_correct"] is True for r in rows), len(slots)
|
|
82
|
+
),
|
|
83
|
+
"completed": sum(r["state"] == "success" for r in rows),
|
|
84
|
+
}
|
|
85
|
+
if not any(r["state"] in ("success", "error", "truncated") for r in rows):
|
|
86
|
+
group["zones"][zone]["answer_correct"] = {
|
|
87
|
+
"count": None,
|
|
88
|
+
"denominator": len(slots),
|
|
89
|
+
"rate": None,
|
|
90
|
+
"wilson95": None,
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
"schema_version": 1,
|
|
94
|
+
"execution_id": payload["execution_id"],
|
|
95
|
+
"snapshot_digest": payload["digest"],
|
|
96
|
+
"mode": payload["profile"]["mode"],
|
|
97
|
+
"validity": validation,
|
|
98
|
+
"quality_acceptance": assess_targets(manifest, records, validation),
|
|
99
|
+
"configuration": manifest.data,
|
|
100
|
+
"provider_profile": payload["profile"],
|
|
101
|
+
"groups": groups,
|
|
102
|
+
"report_inference_calls": 0,
|
|
103
|
+
"warning": "Synthetic UNKNOWN responses and prices; not model-quality or API-cost evidence"
|
|
104
|
+
if payload["profile"]["mode"] == "offline"
|
|
105
|
+
else (
|
|
106
|
+
"Owner-confirmed free-tier pricing; zero configured charges are not a billing "
|
|
107
|
+
"attestation or paid-plan savings measurement; replay is not an independent answer"
|
|
108
|
+
if all(
|
|
109
|
+
c["quota"].get("billing_mode") == "free_tier"
|
|
110
|
+
for c in payload["profile"]["clients"].values()
|
|
111
|
+
)
|
|
112
|
+
else "Recorded usage and configured prices; replay is not an independent model answer"
|
|
113
|
+
),
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def leaderboard(card):
|
|
118
|
+
lines = [
|
|
119
|
+
"# Benchmark leaderboard",
|
|
120
|
+
"",
|
|
121
|
+
f"Validity: {card['validity']['status']}. Mode: {card['mode']}.",
|
|
122
|
+
"",
|
|
123
|
+
card["warning"],
|
|
124
|
+
"",
|
|
125
|
+
"Rows are in protocol order, not ranked across incompatible budgets or models.",
|
|
126
|
+
"",
|
|
127
|
+
"| Model | Budget | Variant | Fit | Retained | Correct / planned | Correct / completed "
|
|
128
|
+
"| Pending / errors / truncated | New cost (micro-USD) |",
|
|
129
|
+
"|---|---:|---|---|---|---|---|---|---:|",
|
|
130
|
+
]
|
|
131
|
+
|
|
132
|
+
def count(value):
|
|
133
|
+
numerator = value["count"] if value["count"] is not None else "unknown"
|
|
134
|
+
return f"{numerator} / {value['denominator']}"
|
|
135
|
+
|
|
136
|
+
for g in card["groups"]:
|
|
137
|
+
lines.append(
|
|
138
|
+
f"| {g['model']} | {g['budget']} | {g['variant']} | {count(g['fit_all_planned'])} | "
|
|
139
|
+
f"{count(g['retained_fitting_all_planned'])} | "
|
|
140
|
+
f"{count(g['answer_correct_all_planned'])} | {count(g['answer_correct_completed'])} | "
|
|
141
|
+
f"{g['pending']} / {g['errors']} / {g['truncated']} | "
|
|
142
|
+
f"{g['new_cost_microusd']}{'' if g['cost_complete'] else ' (known subtotal)'} |"
|
|
143
|
+
)
|
|
144
|
+
lines += [
|
|
145
|
+
"",
|
|
146
|
+
f"Quality acceptance: {card['quality_acceptance']['status']}.",
|
|
147
|
+
"",
|
|
148
|
+
"Retention requires fitting, source-backed evidence; it is not answer accuracy. "
|
|
149
|
+
"Unknown usage remains unknown.",
|
|
150
|
+
"Small correlated synthetic samples do not establish real-workload performance.",
|
|
151
|
+
"",
|
|
152
|
+
]
|
|
153
|
+
return "\n".join(lines)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def figures(card):
|
|
157
|
+
try:
|
|
158
|
+
from matplotlib.backends.backend_agg import FigureCanvasAgg
|
|
159
|
+
from matplotlib.figure import Figure
|
|
160
|
+
except ImportError:
|
|
161
|
+
raise BenchmarkError("PNG generation requires the reports extra") from None
|
|
162
|
+
panels = list(dict.fromkeys((g["model"], g["budget"]) for g in card["groups"]))
|
|
163
|
+
outputs = {}
|
|
164
|
+
for kind in ("context_cost", "recall_by_zone"):
|
|
165
|
+
fig = Figure(figsize=(12, 4 * len(panels)), layout="constrained")
|
|
166
|
+
FigureCanvasAgg(fig)
|
|
167
|
+
axes = fig.subplots(len(panels), 2, squeeze=False)
|
|
168
|
+
for row_index, (model, budget) in enumerate(panels):
|
|
169
|
+
groups = [g for g in card["groups"] if (g["model"], g["budget"]) == (model, budget)]
|
|
170
|
+
labels = [g["variant"] for g in groups]
|
|
171
|
+
left, right = axes[row_index]
|
|
172
|
+
title = f"{model.rsplit('/', 1)[-1]} | budget {budget}"
|
|
173
|
+
if kind == "context_cost":
|
|
174
|
+
values = [g["median_estimated_input_tokens"] or 0 for g in groups]
|
|
175
|
+
bars = left.bar(labels, values, color="#327e9e")
|
|
176
|
+
left.axhline(budget, color="#a43e3e", linestyle="--", label="Input allowance")
|
|
177
|
+
left.bar_label(
|
|
178
|
+
bars,
|
|
179
|
+
[
|
|
180
|
+
"N/A" if g["median_estimated_input_tokens"] is None else str(round(v))
|
|
181
|
+
for g, v in zip(groups, values, strict=True)
|
|
182
|
+
],
|
|
183
|
+
fontsize=8,
|
|
184
|
+
)
|
|
185
|
+
left.set_ylabel("Median estimated input tokens")
|
|
186
|
+
left.legend(fontsize=8)
|
|
187
|
+
costs = [g["new_cost_microusd"] for g in groups]
|
|
188
|
+
bars = right.bar(labels, costs, color="#86734b")
|
|
189
|
+
right.bar_label(
|
|
190
|
+
bars,
|
|
191
|
+
[
|
|
192
|
+
str(c) + ("*" if not g["cost_complete"] else "")
|
|
193
|
+
for g, c in zip(groups, costs, strict=True)
|
|
194
|
+
],
|
|
195
|
+
fontsize=8,
|
|
196
|
+
)
|
|
197
|
+
right.set_ylabel(
|
|
198
|
+
"Synthetic micro-USD"
|
|
199
|
+
if card["mode"] == "offline"
|
|
200
|
+
else "New estimated charge (micro-USD)"
|
|
201
|
+
)
|
|
202
|
+
right.set_title("New cost; * known subtotal, not full billing")
|
|
203
|
+
else:
|
|
204
|
+
for axis, metric in ((left, "retained"), (right, "answer_correct")):
|
|
205
|
+
for i, zone in enumerate(("early", "middle", "late")):
|
|
206
|
+
metrics = [g["zones"][zone][metric] for g in groups]
|
|
207
|
+
xs = [x + (i - 1) * 0.25 for x in range(len(groups))]
|
|
208
|
+
bars = axis.bar(
|
|
209
|
+
xs,
|
|
210
|
+
[m["rate"] or 0 for m in metrics],
|
|
211
|
+
width=0.24,
|
|
212
|
+
label=zone,
|
|
213
|
+
color=("#327e9e", "#bf8a45", "#6e9277")[i],
|
|
214
|
+
)
|
|
215
|
+
axis.bar_label(
|
|
216
|
+
bars,
|
|
217
|
+
[
|
|
218
|
+
f"{m['count']}/{m['denominator']}"
|
|
219
|
+
if m["denominator"] and m["count"] is not None
|
|
220
|
+
else "N/A"
|
|
221
|
+
for m in metrics
|
|
222
|
+
],
|
|
223
|
+
fontsize=6,
|
|
224
|
+
rotation=90,
|
|
225
|
+
padding=3,
|
|
226
|
+
)
|
|
227
|
+
axis.set_xticks(range(len(labels)), labels)
|
|
228
|
+
axis.set_ylim(0, 1.25)
|
|
229
|
+
axis.set_yticks((0, 0.5, 1), ("0%", "50%", "100%"))
|
|
230
|
+
axis.legend(fontsize=8, loc="upper left")
|
|
231
|
+
left.set_ylabel("Source-backed retained / planned")
|
|
232
|
+
right.set_ylabel("Correct answers / planned")
|
|
233
|
+
right.set_title(
|
|
234
|
+
"Synthetic answers only"
|
|
235
|
+
if card["mode"] == "offline"
|
|
236
|
+
else "Uncompleted answers remain in denominator"
|
|
237
|
+
)
|
|
238
|
+
left.set_title(title)
|
|
239
|
+
for axis in (left, right):
|
|
240
|
+
axis.spines[["top", "right"]].set_visible(False)
|
|
241
|
+
axis.grid(axis="y", alpha=0.15)
|
|
242
|
+
axis.set_axisbelow(True)
|
|
243
|
+
fig.suptitle(
|
|
244
|
+
f"{kind.replace('_', ' ').title()} — "
|
|
245
|
+
f"{card['mode'].upper()} / {card['validity']['status']}\n"
|
|
246
|
+
"Estimates and synthetic tests are not live-provider performance evidence",
|
|
247
|
+
fontsize=13,
|
|
248
|
+
)
|
|
249
|
+
buffer = io.BytesIO()
|
|
250
|
+
fig.savefig(
|
|
251
|
+
buffer, format="png", dpi=130, metadata={"Software": "context-engine-report-v1"}
|
|
252
|
+
)
|
|
253
|
+
outputs[kind + ".png"] = buffer.getvalue()
|
|
254
|
+
return outputs
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def export_report(directory, card):
|
|
258
|
+
outputs = {
|
|
259
|
+
"scorecard.json": (
|
|
260
|
+
json.dumps(card, ensure_ascii=False, indent=2, allow_nan=False) + "\n"
|
|
261
|
+
).encode(),
|
|
262
|
+
"leaderboard.md": leaderboard(card).encode(),
|
|
263
|
+
**figures(card),
|
|
264
|
+
}
|
|
265
|
+
for model in card["configuration"]["models"]:
|
|
266
|
+
projection = {
|
|
267
|
+
**card,
|
|
268
|
+
"groups": [g for g in card["groups"] if g["model"] == model],
|
|
269
|
+
"selected_model": model,
|
|
270
|
+
"projection_note": "Model-specific scorecard; parent manifest retained",
|
|
271
|
+
}
|
|
272
|
+
outputs[model.rsplit("/", 1)[-1] + "-results.json"] = (
|
|
273
|
+
json.dumps(projection, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
|
|
274
|
+
).encode()
|
|
275
|
+
manifest = {
|
|
276
|
+
"execution_id": card["execution_id"],
|
|
277
|
+
"snapshot_digest": card["snapshot_digest"],
|
|
278
|
+
"report_inference_calls": 0,
|
|
279
|
+
"matplotlib": metadata.version("matplotlib"),
|
|
280
|
+
"pillow": metadata.version("pillow"),
|
|
281
|
+
"files": {name: hashlib.sha256(raw).hexdigest() for name, raw in outputs.items()},
|
|
282
|
+
}
|
|
283
|
+
outputs["report-manifest.json"] = (json.dumps(manifest, indent=2) + "\n").encode()
|
|
284
|
+
try:
|
|
285
|
+
directory = Path(directory)
|
|
286
|
+
directory.mkdir(parents=True, exist_ok=False)
|
|
287
|
+
for name, raw in outputs.items():
|
|
288
|
+
with (directory / name).open("xb") as handle:
|
|
289
|
+
handle.write(raw)
|
|
290
|
+
except OSError:
|
|
291
|
+
raise BenchmarkError(
|
|
292
|
+
"Report destination must be a new writable directory; partial exports are not complete"
|
|
293
|
+
) from None
|
|
294
|
+
return manifest
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
"""Request/result validity, explicit denominators and immutable resume snapshots."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from dataclasses import asdict
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from statistics import median
|
|
7
|
+
|
|
8
|
+
from ..errors import BenchmarkError, ContextEngineError
|
|
9
|
+
from ..inspection import save_inspection
|
|
10
|
+
from ..models import canonical_json
|
|
11
|
+
from .corpus import Bundle, aliases, strict_json
|
|
12
|
+
from .grading import answer_correct, normalize, proportion
|
|
13
|
+
from .harness import _prepare_validated
|
|
14
|
+
from .protocol import Gate, Manifest, check_manifest, preflight
|
|
15
|
+
|
|
16
|
+
RESPONSE_FIELDS = {
|
|
17
|
+
"answer",
|
|
18
|
+
"answer_correct",
|
|
19
|
+
"finish_reason",
|
|
20
|
+
"error_code",
|
|
21
|
+
"response_origin",
|
|
22
|
+
"provider_request_id",
|
|
23
|
+
"replay_of",
|
|
24
|
+
"provider_usage",
|
|
25
|
+
}
|
|
26
|
+
TERMINAL = {"success", "error", "truncated", "non_fit"}
|
|
27
|
+
MAX_RUN_BYTES = 32_000_000
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def record_response(
|
|
31
|
+
bundle: Bundle,
|
|
32
|
+
prepared: dict,
|
|
33
|
+
*,
|
|
34
|
+
answer: str | None,
|
|
35
|
+
finish_reason: str,
|
|
36
|
+
origin: str,
|
|
37
|
+
error_code: str | None = None,
|
|
38
|
+
provider_request_id: str | None = None,
|
|
39
|
+
replay_of: str | None = None,
|
|
40
|
+
provider_usage: dict | None = None,
|
|
41
|
+
) -> dict:
|
|
42
|
+
"""Record supplied evidence of a response; this function never performs inference."""
|
|
43
|
+
if prepared["state"] != "prepared":
|
|
44
|
+
raise BenchmarkError("Only an admitted, unanswered probe can receive a response")
|
|
45
|
+
result = strict_json(canonical_json(prepared))
|
|
46
|
+
if finish_reason not in ("stop", "length", "error") or origin not in ("test", "live", "replay"):
|
|
47
|
+
raise BenchmarkError("Unsupported response disposition")
|
|
48
|
+
if finish_reason != "error" and not isinstance(answer, str):
|
|
49
|
+
raise BenchmarkError("Completed response requires answer text")
|
|
50
|
+
result.update(
|
|
51
|
+
state={"stop": "success", "length": "truncated", "error": "error"}[finish_reason],
|
|
52
|
+
answer=answer,
|
|
53
|
+
finish_reason=finish_reason,
|
|
54
|
+
response_origin=origin,
|
|
55
|
+
error_code=error_code,
|
|
56
|
+
provider_request_id=provider_request_id,
|
|
57
|
+
replay_of=replay_of,
|
|
58
|
+
provider_usage=provider_usage,
|
|
59
|
+
answer_correct=answer_correct(answer, aliases(bundle.fact(result["fact_id"])))
|
|
60
|
+
if finish_reason == "stop"
|
|
61
|
+
else None,
|
|
62
|
+
)
|
|
63
|
+
_check_response(bundle, result)
|
|
64
|
+
return result
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _check_response(bundle: Bundle, row: dict) -> None:
|
|
68
|
+
state = row["state"]
|
|
69
|
+
if state in ("prepared", "non_fit"):
|
|
70
|
+
if any(row[key] is not None for key in RESPONSE_FIELDS):
|
|
71
|
+
raise BenchmarkError("Unsent probe contains fabricated generation metadata")
|
|
72
|
+
return
|
|
73
|
+
expected_finish = {"success": "stop", "truncated": "length", "error": "error"}
|
|
74
|
+
if state not in expected_finish or row["finish_reason"] != expected_finish[state]:
|
|
75
|
+
raise BenchmarkError("Inconsistent generation disposition")
|
|
76
|
+
if row["response_origin"] not in ("test", "live", "replay"):
|
|
77
|
+
raise BenchmarkError("Missing response provenance")
|
|
78
|
+
if (
|
|
79
|
+
row["response_origin"] in ("live", "replay")
|
|
80
|
+
and (
|
|
81
|
+
not isinstance(row["provider_request_id"], str)
|
|
82
|
+
or not row["provider_request_id"].strip()
|
|
83
|
+
)
|
|
84
|
+
and state != "error"
|
|
85
|
+
):
|
|
86
|
+
raise BenchmarkError("Completed provider response lacks a request identifier")
|
|
87
|
+
if row["response_origin"] == "replay":
|
|
88
|
+
if not isinstance(row["replay_of"], str) or not row["replay_of"].strip():
|
|
89
|
+
raise BenchmarkError("Replay lacks an original response reference")
|
|
90
|
+
elif row["replay_of"] is not None:
|
|
91
|
+
raise BenchmarkError("Non-replay response claims replay ancestry")
|
|
92
|
+
if state == "error":
|
|
93
|
+
if (
|
|
94
|
+
not isinstance(row["error_code"], str)
|
|
95
|
+
or row["error_code"]
|
|
96
|
+
not in (
|
|
97
|
+
"timeout",
|
|
98
|
+
"quota",
|
|
99
|
+
"transport",
|
|
100
|
+
"rate_limit",
|
|
101
|
+
"provider_error",
|
|
102
|
+
"invalid_response",
|
|
103
|
+
)
|
|
104
|
+
or row["answer"] is not None
|
|
105
|
+
or row["answer_correct"] is not None
|
|
106
|
+
):
|
|
107
|
+
raise BenchmarkError("Invalid structured provider error")
|
|
108
|
+
else:
|
|
109
|
+
if row["error_code"] is not None or not isinstance(row["answer"], str):
|
|
110
|
+
raise BenchmarkError("Inconsistent completed response")
|
|
111
|
+
expected = (
|
|
112
|
+
answer_correct(row["answer"], aliases(bundle.fact(row["fact_id"])))
|
|
113
|
+
if state == "success"
|
|
114
|
+
else None
|
|
115
|
+
)
|
|
116
|
+
if type(row["answer_correct"]) is not type(expected) or row["answer_correct"] != expected:
|
|
117
|
+
raise BenchmarkError("Stored answer grade does not match response")
|
|
118
|
+
usage = row["provider_usage"]
|
|
119
|
+
if usage is not None:
|
|
120
|
+
if not isinstance(usage, dict) or set(usage) != {
|
|
121
|
+
"input_tokens",
|
|
122
|
+
"output_tokens",
|
|
123
|
+
"cached_input_tokens",
|
|
124
|
+
}:
|
|
125
|
+
raise BenchmarkError("Malformed provider usage")
|
|
126
|
+
if (
|
|
127
|
+
any(type(n) is not int or n < 0 for n in usage.values())
|
|
128
|
+
or usage["cached_input_tokens"] > usage["input_tokens"]
|
|
129
|
+
):
|
|
130
|
+
raise BenchmarkError("Inconsistent provider token usage")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def validate_run(
|
|
134
|
+
bundle: Bundle, frozen: dict, manifest: Manifest, records: list[dict] | tuple[dict, ...]
|
|
135
|
+
) -> dict:
|
|
136
|
+
gates = list(preflight(bundle, frozen))
|
|
137
|
+
try:
|
|
138
|
+
check_manifest(bundle, frozen, manifest)
|
|
139
|
+
except ContextEngineError:
|
|
140
|
+
gates = [g for g in gates if g.gate != "V5"] + [Gate("V5", "FAIL", "manifest_drift")]
|
|
141
|
+
if any(g.status == "FAIL" for g in gates):
|
|
142
|
+
gates += [
|
|
143
|
+
Gate("V3", "NOT_RUN", "preflight_failed"),
|
|
144
|
+
Gate("V4", "NOT_RUN", "preflight_failed"),
|
|
145
|
+
]
|
|
146
|
+
return _validation_result("INVALID", gates, [])
|
|
147
|
+
slots = {slot["probe_id"]: slot for slot in manifest.slots}
|
|
148
|
+
seen = set()
|
|
149
|
+
prepared_cache = {}
|
|
150
|
+
try:
|
|
151
|
+
if not isinstance(records, (list, tuple)):
|
|
152
|
+
raise BenchmarkError("Records must be an array")
|
|
153
|
+
for row in records:
|
|
154
|
+
if not isinstance(row, dict) or row["probe_id"] in seen or row["probe_id"] not in slots:
|
|
155
|
+
raise BenchmarkError("Duplicate or unknown probe disposition")
|
|
156
|
+
seen.add(row["probe_id"])
|
|
157
|
+
slot = slots[row["probe_id"]]
|
|
158
|
+
key = (slot["budget"], slot["variant"], slot["fact_id"])
|
|
159
|
+
if key not in prepared_cache:
|
|
160
|
+
prepared_cache[key] = _prepare_validated(bundle, slot)
|
|
161
|
+
prepared = {**prepared_cache[key], **slot}
|
|
162
|
+
if set(row) != set(prepared):
|
|
163
|
+
raise BenchmarkError("Malformed result fields")
|
|
164
|
+
unchanged = set(prepared) - RESPONSE_FIELDS - {"state"}
|
|
165
|
+
if canonical_json({k: row[k] for k in unchanged}) != canonical_json(
|
|
166
|
+
{k: prepared[k] for k in unchanged}
|
|
167
|
+
):
|
|
168
|
+
raise BenchmarkError(
|
|
169
|
+
"Saved request, accounting or evidence differs from measured assembly"
|
|
170
|
+
)
|
|
171
|
+
if prepared["state"] == "non_fit" and row["state"] != "non_fit":
|
|
172
|
+
raise BenchmarkError("Oversized request was admitted")
|
|
173
|
+
if prepared["state"] != "non_fit" and row["state"] == "non_fit":
|
|
174
|
+
raise BenchmarkError("Fitting request mislabeled as oversized")
|
|
175
|
+
_check_response(bundle, row)
|
|
176
|
+
gates.append(Gate("V3", "PASS", "requests_reassembled_and_recounted"))
|
|
177
|
+
except (ContextEngineError, KeyError, TypeError, ValueError, IndexError):
|
|
178
|
+
gates += [
|
|
179
|
+
Gate("V3", "FAIL", "request_or_result_integrity"),
|
|
180
|
+
Gate("V4", "NOT_RUN", "request_check_failed"),
|
|
181
|
+
]
|
|
182
|
+
return _validation_result("INVALID", gates, [])
|
|
183
|
+
terminal = {row["probe_id"] for row in records if row["state"] in TERMINAL}
|
|
184
|
+
pending = [identifier for identifier in slots if identifier not in terminal]
|
|
185
|
+
if any(row["state"] == "truncated" for row in records):
|
|
186
|
+
gates.append(Gate("V4", "FAIL", "generation_truncated"))
|
|
187
|
+
status = "INVALID"
|
|
188
|
+
elif pending:
|
|
189
|
+
any_response = any(row["state"] in ("success", "error") for row in records)
|
|
190
|
+
status = "INTERRUPTED" if any_response or len(seen) < len(slots) else "PREPARED"
|
|
191
|
+
gates.append(Gate("V4", "NOT_RUN", "pending_probe_dispositions"))
|
|
192
|
+
else:
|
|
193
|
+
gates.append(Gate("V4", "PASS", "all_probes_have_terminal_dispositions"))
|
|
194
|
+
status = (
|
|
195
|
+
"TEST_ONLY" if any(row["response_origin"] == "test" for row in records) else "VALID"
|
|
196
|
+
)
|
|
197
|
+
return _validation_result(status, gates, pending)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _validation_result(status, gates, pending):
|
|
201
|
+
return {
|
|
202
|
+
"status": status,
|
|
203
|
+
"gates": [asdict(g) for g in sorted(gates, key=lambda g: g.gate)],
|
|
204
|
+
"pending_probe_ids": pending,
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def statistics(manifest: Manifest, records) -> list[dict]:
|
|
209
|
+
"""After integrity validation, report separate model/budget/variant groups."""
|
|
210
|
+
rows = {r["probe_id"]: r for r in records}
|
|
211
|
+
result = []
|
|
212
|
+
for model in manifest.data["models"]:
|
|
213
|
+
for budget in manifest.data["budgets"]:
|
|
214
|
+
for variant in manifest.data["variants"]:
|
|
215
|
+
planned = [
|
|
216
|
+
s
|
|
217
|
+
for s in manifest.slots
|
|
218
|
+
if (s["model"], s["budget"], s["variant"]) == (model, budget, variant)
|
|
219
|
+
]
|
|
220
|
+
measured = [rows[s["probe_id"]] for s in planned if s["probe_id"] in rows]
|
|
221
|
+
fitting = [r for r in measured if r["state"] != "non_fit"]
|
|
222
|
+
completed = [r for r in measured if r["state"] == "success"]
|
|
223
|
+
correct = sum(r["answer_correct"] for r in completed)
|
|
224
|
+
attempted = [r for r in measured if r["state"] in ("success", "error", "truncated")]
|
|
225
|
+
result.append(
|
|
226
|
+
{
|
|
227
|
+
"model": model,
|
|
228
|
+
"budget": budget,
|
|
229
|
+
"variant": variant,
|
|
230
|
+
"planned": len(planned),
|
|
231
|
+
"measured": len(measured),
|
|
232
|
+
"fit_all_planned": proportion(len(fitting), len(planned)),
|
|
233
|
+
"literal_fact_present_measured": proportion(
|
|
234
|
+
sum(r["fact_present"] for r in measured), len(measured)
|
|
235
|
+
),
|
|
236
|
+
"retained_fitting_all_planned": proportion(
|
|
237
|
+
sum(r["retained_evidence"] for r in fitting), len(planned)
|
|
238
|
+
),
|
|
239
|
+
"answer_correct_all_planned": proportion(correct, len(planned))
|
|
240
|
+
if attempted
|
|
241
|
+
else {
|
|
242
|
+
"count": None,
|
|
243
|
+
"denominator": len(planned),
|
|
244
|
+
"rate": None,
|
|
245
|
+
"wilson95": None,
|
|
246
|
+
},
|
|
247
|
+
"answer_correct_completed": proportion(correct, len(completed)),
|
|
248
|
+
"errors": sum(r["state"] == "error" for r in measured),
|
|
249
|
+
"truncated": sum(r["state"] == "truncated" for r in measured),
|
|
250
|
+
"non_fit": len(measured) - len(fitting),
|
|
251
|
+
"pending": len(planned) - sum(r["state"] in TERMINAL for r in measured),
|
|
252
|
+
"abstentions": sum(normalize(r["answer"]) == "unknown" for r in completed),
|
|
253
|
+
"provider_usage_unknown": sum(
|
|
254
|
+
r["provider_usage"] is None for r in attempted
|
|
255
|
+
),
|
|
256
|
+
"test_responses": sum(r["response_origin"] == "test" for r in measured),
|
|
257
|
+
"cost": None,
|
|
258
|
+
}
|
|
259
|
+
)
|
|
260
|
+
return result
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def assess_targets(manifest: Manifest, records, validation: dict) -> dict:
|
|
264
|
+
"""Quality cannot pass on a partial run, mock responses or unapproved registration."""
|
|
265
|
+
p = manifest.data["protocol"]
|
|
266
|
+
if validation["status"] != "VALID" or p["approval"] != "owner_approved":
|
|
267
|
+
return {
|
|
268
|
+
"status": "NOT_EVALUATED",
|
|
269
|
+
"reason": "requires_valid_real_run_and_owner_registration",
|
|
270
|
+
}
|
|
271
|
+
primary = [
|
|
272
|
+
r
|
|
273
|
+
for r in records
|
|
274
|
+
if r["variant"] == "A5" and r["budget"] == 900 and r["model"] == p["models"][0]
|
|
275
|
+
]
|
|
276
|
+
if len(primary) != 31 or len({r["fact_id"] for r in primary}) != 31:
|
|
277
|
+
return {"status": "NOT_EVALUATED", "reason": "requires_all_primary_probes"}
|
|
278
|
+
observed = {
|
|
279
|
+
"fit": sum(r["state"] != "non_fit" for r in primary),
|
|
280
|
+
"retained": sum(r["state"] != "non_fit" and r["retained_evidence"] for r in primary),
|
|
281
|
+
"correct": sum(r["answer_correct"] is True for r in primary),
|
|
282
|
+
"median_input_reduction": median(
|
|
283
|
+
1 - r["estimate"]["estimated_tokens"] / r["raw_estimated_tokens"] for r in primary
|
|
284
|
+
),
|
|
285
|
+
}
|
|
286
|
+
passed = all(observed[key] >= p["targets"][key] for key in observed)
|
|
287
|
+
return {"status": "PASS" if passed else "FAIL", "observed": observed}
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def save_run(path: Path, bundle: Bundle, frozen: dict, manifest: Manifest, records) -> None:
|
|
291
|
+
validation = validate_run(bundle, frozen, manifest, records)
|
|
292
|
+
if validation["status"] == "INVALID":
|
|
293
|
+
raise BenchmarkError("Cannot export an invalid resume snapshot")
|
|
294
|
+
payload = {
|
|
295
|
+
"schema_version": 1,
|
|
296
|
+
"run_id": manifest.run_id,
|
|
297
|
+
"manifest": manifest.data,
|
|
298
|
+
"records": records,
|
|
299
|
+
}
|
|
300
|
+
if (
|
|
301
|
+
len((json.dumps(payload, indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode())
|
|
302
|
+
> MAX_RUN_BYTES
|
|
303
|
+
):
|
|
304
|
+
raise BenchmarkError("Run snapshot exceeds byte limit")
|
|
305
|
+
save_inspection(path, payload)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def load_run(path: Path, bundle: Bundle, frozen: dict):
|
|
309
|
+
try:
|
|
310
|
+
with path.open("rb") as handle:
|
|
311
|
+
raw = handle.read(MAX_RUN_BYTES + 1)
|
|
312
|
+
if len(raw) > MAX_RUN_BYTES:
|
|
313
|
+
raise BenchmarkError("Run snapshot exceeds byte limit")
|
|
314
|
+
payload = strict_json(raw.decode("utf-8"), maximum=MAX_RUN_BYTES)
|
|
315
|
+
if (
|
|
316
|
+
set(payload) != {"schema_version", "run_id", "manifest", "records"}
|
|
317
|
+
or type(payload["schema_version"]) is not int
|
|
318
|
+
or payload["schema_version"] != 1
|
|
319
|
+
):
|
|
320
|
+
raise BenchmarkError("Unsupported run snapshot schema")
|
|
321
|
+
manifest = Manifest(canonical_json(payload["manifest"]))
|
|
322
|
+
if payload["run_id"] != manifest.run_id:
|
|
323
|
+
raise BenchmarkError("Run identity mismatch")
|
|
324
|
+
validation = validate_run(bundle, frozen, manifest, payload["records"])
|
|
325
|
+
if validation["status"] == "INVALID":
|
|
326
|
+
raise BenchmarkError("Resume snapshot failed validity gates")
|
|
327
|
+
return manifest, payload["records"], validation
|
|
328
|
+
except BenchmarkError:
|
|
329
|
+
raise
|
|
330
|
+
except (OSError, UnicodeError, KeyError, TypeError, ValueError):
|
|
331
|
+
raise BenchmarkError("Cannot read a valid resume snapshot") from None
|