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,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema_version": 1,
|
|
3
|
+
"scenario_id": "incident-100-v1",
|
|
4
|
+
"policy_version": "background-only-v1",
|
|
5
|
+
"created_at": "2026-09-07T00:00:00Z",
|
|
6
|
+
"content": "Responders investigated an operational incident, compared telemetry, reviewed recovery steps, and collected background notes for a later handoff."
|
|
7
|
+
}
|
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
"""Durable, single-dispatch benchmark execution; never obtains answers from grading truth."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from dataclasses import asdict
|
|
5
|
+
from importlib import metadata
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from ..config import BudgetConfig, TokenizerConfig
|
|
9
|
+
from ..errors import BenchmarkError, ContextEngineError
|
|
10
|
+
from ..models import ChatRequest, Message, ToolCall, ToolDefinition, canonical_json
|
|
11
|
+
from ..providers.client import ProviderClient
|
|
12
|
+
from ..providers.contracts import (
|
|
13
|
+
ADAPTER_VERSION,
|
|
14
|
+
ENDPOINT,
|
|
15
|
+
Completion,
|
|
16
|
+
GenerationConfig,
|
|
17
|
+
PriceCard,
|
|
18
|
+
QuotaPolicy,
|
|
19
|
+
ReplayPolicy,
|
|
20
|
+
RetryConfig,
|
|
21
|
+
Usage,
|
|
22
|
+
fingerprint,
|
|
23
|
+
)
|
|
24
|
+
from ..providers.store import RuntimeStore
|
|
25
|
+
from ..providers.transport import GroqTransport
|
|
26
|
+
from .corpus import strict_json
|
|
27
|
+
from .harness import _prepare_validated
|
|
28
|
+
from .protocol import Manifest, check_manifest
|
|
29
|
+
from .results import MAX_RUN_BYTES, RESPONSE_FIELDS, record_response, validate_run
|
|
30
|
+
|
|
31
|
+
PROVIDER_DEPENDENCIES = ("httpx", "httpcore", "h11", "anyio", "typing-extensions")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def expected_request_key(row, profile, execution_id, scope, protocol):
|
|
35
|
+
configured = profile["clients"][row["model"]]
|
|
36
|
+
budget = BudgetConfig(
|
|
37
|
+
input_cap=row["budget"],
|
|
38
|
+
completion_reservation=protocol["generation"]["max_completion_tokens"],
|
|
39
|
+
**protocol["budget"],
|
|
40
|
+
)
|
|
41
|
+
return fingerprint(
|
|
42
|
+
{
|
|
43
|
+
"adapter": profile["adapter"],
|
|
44
|
+
"endpoint": profile["endpoint"],
|
|
45
|
+
"payload": GenerationConfig(**configured["generation"]).to_wire(
|
|
46
|
+
request_from_wire(row["request"])
|
|
47
|
+
),
|
|
48
|
+
"account": configured["quota"]["account_id"],
|
|
49
|
+
"scope": scope,
|
|
50
|
+
"security_scope": profile["security_scope"],
|
|
51
|
+
"snapshot_revision": profile["snapshot_revision"],
|
|
52
|
+
"policy_version": execution_id,
|
|
53
|
+
"budget": asdict(budget),
|
|
54
|
+
"counting": row["estimate"],
|
|
55
|
+
"prices": configured["prices"],
|
|
56
|
+
"transport": configured["transport"],
|
|
57
|
+
}
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def dependency_profile():
|
|
62
|
+
result = {}
|
|
63
|
+
for name in PROVIDER_DEPENDENCIES:
|
|
64
|
+
try:
|
|
65
|
+
result[name] = metadata.version(name)
|
|
66
|
+
except metadata.PackageNotFoundError:
|
|
67
|
+
result[name] = None
|
|
68
|
+
return result
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def execution_profile(manifest, clients, *, mode, max_run_cost_microusd):
|
|
72
|
+
if mode not in ("offline", "live") or type(max_run_cost_microusd) is not int:
|
|
73
|
+
raise BenchmarkError("Invalid execution mode or run spending cap")
|
|
74
|
+
if max_run_cost_microusd < 0 or max_run_cost_microusd > 10**12:
|
|
75
|
+
raise BenchmarkError("An explicit bounded run spending cap is required")
|
|
76
|
+
if set(clients) != set(manifest.data["models"]):
|
|
77
|
+
raise BenchmarkError("Every selected model requires its own configured client")
|
|
78
|
+
profiles = {}
|
|
79
|
+
for model, client in clients.items():
|
|
80
|
+
if not isinstance(client, ProviderClient):
|
|
81
|
+
raise BenchmarkError("Execution requires the controlled provider client")
|
|
82
|
+
client.quota.validate_prices(client.prices)
|
|
83
|
+
if (client.quota.billing_mode == "free_tier") != (max_run_cost_microusd == 0):
|
|
84
|
+
raise BenchmarkError("Only explicit free-tier accounts permit a zero run spending cap")
|
|
85
|
+
if asdict(client.generation) != dict(
|
|
86
|
+
model=model, tool_choice="none", **manifest.data["protocol"]["generation"]
|
|
87
|
+
):
|
|
88
|
+
raise BenchmarkError("Generation differs from the frozen protocol")
|
|
89
|
+
real = type(client.transport) is GroqTransport and client.transport.http_transport is None
|
|
90
|
+
if real != (mode == "live"):
|
|
91
|
+
raise BenchmarkError("Live and synthetic transports must not share provenance")
|
|
92
|
+
if client.counter.config != TokenizerConfig(**manifest.data["protocol"]["tokenizer"]):
|
|
93
|
+
raise BenchmarkError("Provider tokenizer differs from the frozen protocol")
|
|
94
|
+
profiles[model] = {
|
|
95
|
+
"quota": asdict(client.quota),
|
|
96
|
+
"prices": asdict(client.prices),
|
|
97
|
+
"generation": asdict(client.generation),
|
|
98
|
+
"retry": asdict(client.retries),
|
|
99
|
+
"replay": asdict(client.replay),
|
|
100
|
+
"transport": client.transport.namespace,
|
|
101
|
+
"ledger_path": str(client.store.path),
|
|
102
|
+
}
|
|
103
|
+
policies = {(p["ledger_path"], canonical_json(p["quota"])) for p in profiles.values()}
|
|
104
|
+
if len(policies) != 1:
|
|
105
|
+
raise BenchmarkError("All models must share one account, ledger and quota policy")
|
|
106
|
+
return {
|
|
107
|
+
"mode": mode,
|
|
108
|
+
"adapter": ADAPTER_VERSION,
|
|
109
|
+
"endpoint": ENDPOINT,
|
|
110
|
+
"dependencies": dependency_profile(),
|
|
111
|
+
"clients": profiles,
|
|
112
|
+
"max_run_cost_microusd": max_run_cost_microusd,
|
|
113
|
+
"security_scope": "synthetic-benchmark-v1",
|
|
114
|
+
"snapshot_revision": manifest.data["freeze"]["fixture_hashes"]["scenario"],
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def request_from_wire(value):
|
|
119
|
+
messages = []
|
|
120
|
+
for index, raw in enumerate(value["messages"]):
|
|
121
|
+
calls = tuple(
|
|
122
|
+
ToolCall(c["id"], c["function"]["name"], c["function"]["arguments"])
|
|
123
|
+
for c in raw.get("tool_calls", ())
|
|
124
|
+
)
|
|
125
|
+
messages.append(
|
|
126
|
+
Message(
|
|
127
|
+
f"benchmark:{index}",
|
|
128
|
+
raw["role"],
|
|
129
|
+
raw.get("content", ""),
|
|
130
|
+
raw.get("tool_call_id"),
|
|
131
|
+
calls,
|
|
132
|
+
)
|
|
133
|
+
)
|
|
134
|
+
tools = tuple(
|
|
135
|
+
ToolDefinition(
|
|
136
|
+
t["function"]["name"],
|
|
137
|
+
t["function"].get("description", ""),
|
|
138
|
+
canonical_json(t["function"]["parameters"]),
|
|
139
|
+
)
|
|
140
|
+
for t in value.get("tools", ())
|
|
141
|
+
)
|
|
142
|
+
return ChatRequest(tuple(messages), tools)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def bind_response(bundle, prepared, receipt, mode):
|
|
146
|
+
result = receipt["result"]
|
|
147
|
+
completion = Completion.from_dict(result["completion"]) if result["completion"] else None
|
|
148
|
+
origin = "test" if mode == "offline" else ("replay" if result["replay_of"] else "live")
|
|
149
|
+
finish = (
|
|
150
|
+
"stop"
|
|
151
|
+
if result["status"] in ("success", "replay")
|
|
152
|
+
else ("length" if result["status"] == "truncated" else "error")
|
|
153
|
+
)
|
|
154
|
+
usage = None
|
|
155
|
+
if completion and completion.usage.cached_input_tokens is not None:
|
|
156
|
+
u = completion.usage
|
|
157
|
+
usage = dict(
|
|
158
|
+
input_tokens=u.input_tokens,
|
|
159
|
+
output_tokens=u.output_tokens,
|
|
160
|
+
cached_input_tokens=u.cached_input_tokens,
|
|
161
|
+
)
|
|
162
|
+
code = result["error_code"]
|
|
163
|
+
code = (
|
|
164
|
+
code
|
|
165
|
+
if code in ("timeout", "transport", "rate_limit", "invalid_response")
|
|
166
|
+
else "provider_error"
|
|
167
|
+
)
|
|
168
|
+
return record_response(
|
|
169
|
+
bundle,
|
|
170
|
+
prepared,
|
|
171
|
+
answer=completion.content if finish != "error" else None,
|
|
172
|
+
finish_reason=finish,
|
|
173
|
+
origin=origin,
|
|
174
|
+
error_code=code if finish == "error" else None,
|
|
175
|
+
provider_request_id=completion.response_id if completion else None,
|
|
176
|
+
replay_of=result["replay_of"] if origin == "replay" else None,
|
|
177
|
+
provider_usage=usage,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def verify_receipt(receipt, model, profile):
|
|
182
|
+
"""Cross-check adapter results against captured ledger rows, not a claimed label."""
|
|
183
|
+
r, rows = receipt["result"], receipt["ledger_rows"]
|
|
184
|
+
if set(receipt) != {"result", "ledger_rows"} or not isinstance(rows, list):
|
|
185
|
+
raise BenchmarkError("Malformed adapter receipt")
|
|
186
|
+
ids = list(r["attempt_ids"])
|
|
187
|
+
expected = set(ids + ([r["replay_of"]] if r["replay_of"] else []))
|
|
188
|
+
if (
|
|
189
|
+
len(ids) != len(set(ids))
|
|
190
|
+
or {a["id"] for a in rows} != expected
|
|
191
|
+
or len(rows) != len(expected)
|
|
192
|
+
):
|
|
193
|
+
raise BenchmarkError("Receipt attempt ancestry mismatch")
|
|
194
|
+
for a in rows:
|
|
195
|
+
RuntimeStore._validate_row(a)
|
|
196
|
+
if a["usage_json"]:
|
|
197
|
+
usage = Usage(**json.loads(a["usage_json"]))
|
|
198
|
+
price = PriceCard(**json.loads(a["price_json"]))
|
|
199
|
+
if a["cost"] != price.observed_cost(usage) or a["charged_tokens"] != usage.total_tokens:
|
|
200
|
+
raise BenchmarkError("Ledger usage and calculated cost disagree")
|
|
201
|
+
if (
|
|
202
|
+
a["model"] != model
|
|
203
|
+
or a["request_key"] != r["request_key"]
|
|
204
|
+
or a["account"] != fingerprint(profile["clients"][model]["quota"]["account_id"])
|
|
205
|
+
or json.loads(a["price_json"]) != profile["clients"][model]["prices"]
|
|
206
|
+
):
|
|
207
|
+
raise BenchmarkError("Receipt ledger scope or pricing mismatch")
|
|
208
|
+
own = [a for a in rows if a["id"] in ids]
|
|
209
|
+
expected_cost = None if any(a["cost"] is None for a in own) else sum(a["cost"] for a in own)
|
|
210
|
+
if r["new_cost_microusd"] != expected_cost:
|
|
211
|
+
raise BenchmarkError("Receipt cost differs from attempt accounting")
|
|
212
|
+
if r["status"] == "replay":
|
|
213
|
+
if not r["replay_of"] or ids or r["new_cost_microusd"] != 0:
|
|
214
|
+
raise BenchmarkError("Replay must have ancestry and zero new spend")
|
|
215
|
+
elif r["replay_of"] is not None:
|
|
216
|
+
raise BenchmarkError("Non-replay has replay ancestry")
|
|
217
|
+
if r["completion"] is not None:
|
|
218
|
+
c = Completion.from_dict(r["completion"])
|
|
219
|
+
if c.model != model or not rows:
|
|
220
|
+
raise BenchmarkError("Completion model or ledger receipt missing")
|
|
221
|
+
source_id = r["replay_of"] or ids[-1]
|
|
222
|
+
source = next(a for a in rows if a["id"] == source_id)
|
|
223
|
+
if (
|
|
224
|
+
source["completion_hash"] != fingerprint(c.to_dict())
|
|
225
|
+
or json.loads(source["usage_json"]) != asdict(c.usage)
|
|
226
|
+
or source["cost"] != r["original_cost_microusd"]
|
|
227
|
+
):
|
|
228
|
+
raise BenchmarkError("Completion content or usage differs from ledger receipt")
|
|
229
|
+
expected_status = {
|
|
230
|
+
"stop": "success",
|
|
231
|
+
"length": "truncated",
|
|
232
|
+
"tool_calls": "tool_calls",
|
|
233
|
+
"content_filter": "filtered",
|
|
234
|
+
}[c.finish_reason]
|
|
235
|
+
if r["status"] not in (expected_status, "replay"):
|
|
236
|
+
raise BenchmarkError("Completion status mismatch")
|
|
237
|
+
if r["status"] == "replay" and c.finish_reason != "stop":
|
|
238
|
+
raise BenchmarkError("Partial completion cannot be replayed")
|
|
239
|
+
elif r["status"] != "error":
|
|
240
|
+
raise BenchmarkError("Successful outcome lacks completion")
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
class RunJournal:
|
|
244
|
+
"""Single-dispatch journal; unknown intents require operator recovery, never auto-resend."""
|
|
245
|
+
|
|
246
|
+
def __init__(self, path: Path, manifest: Manifest, profile: dict):
|
|
247
|
+
self.manifest, self.profile = manifest, profile
|
|
248
|
+
self.identity = {"manifest": manifest.data, "profile": profile}
|
|
249
|
+
self.execution_id = fingerprint(self.identity)
|
|
250
|
+
if str(Path(path).absolute()) in {p["ledger_path"] for p in profile["clients"].values()}:
|
|
251
|
+
raise BenchmarkError("Execution journal and provider ledger must be separate files")
|
|
252
|
+
self.store = RuntimeStore(path)
|
|
253
|
+
with self.store.transaction() as db:
|
|
254
|
+
db.execute("CREATE TABLE IF NOT EXISTS benchmark_identity(payload TEXT NOT NULL)")
|
|
255
|
+
db.execute("""CREATE TABLE IF NOT EXISTS benchmark_probes(
|
|
256
|
+
id TEXT PRIMARY KEY, phase TEXT NOT NULL, record TEXT NOT NULL,
|
|
257
|
+
receipt TEXT, reserved_cost INTEGER NOT NULL DEFAULT 0)""")
|
|
258
|
+
previous = db.execute("SELECT payload FROM benchmark_identity").fetchall()
|
|
259
|
+
if previous and (len(previous) != 1 or previous[0][0] != canonical_json(self.identity)):
|
|
260
|
+
raise BenchmarkError("Execution identity drift; cannot resume this journal")
|
|
261
|
+
if not previous:
|
|
262
|
+
db.execute(
|
|
263
|
+
"INSERT INTO benchmark_identity VALUES(?)", (canonical_json(self.identity),)
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
def snapshot(self):
|
|
267
|
+
with self.store.transaction() as db:
|
|
268
|
+
values = db.execute("SELECT * FROM benchmark_probes ORDER BY id").fetchall()
|
|
269
|
+
return [
|
|
270
|
+
{
|
|
271
|
+
"probe_id": r["id"],
|
|
272
|
+
"phase": r["phase"],
|
|
273
|
+
"record": strict_json(r["record"]),
|
|
274
|
+
"receipt": strict_json(r["receipt"]) if r["receipt"] else None,
|
|
275
|
+
"reserved_cost": r["reserved_cost"],
|
|
276
|
+
}
|
|
277
|
+
for r in values
|
|
278
|
+
]
|
|
279
|
+
|
|
280
|
+
def prepare(self, row):
|
|
281
|
+
with self.store.transaction() as db:
|
|
282
|
+
db.execute(
|
|
283
|
+
"INSERT OR IGNORE INTO benchmark_probes(id,phase,record) VALUES(?,?,?)",
|
|
284
|
+
(
|
|
285
|
+
row["probe_id"],
|
|
286
|
+
"done" if row["state"] == "non_fit" else "pending",
|
|
287
|
+
canonical_json(row),
|
|
288
|
+
),
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
def claim(self, identifier, reserved_cost):
|
|
292
|
+
with self.store.transaction() as db:
|
|
293
|
+
rows = db.execute("SELECT * FROM benchmark_probes").fetchall()
|
|
294
|
+
if any(r["phase"] == "dispatching" for r in rows):
|
|
295
|
+
return "uncertain_dispatch"
|
|
296
|
+
charged = 0
|
|
297
|
+
for r in rows:
|
|
298
|
+
receipt = strict_json(r["receipt"]) if r["receipt"] else None
|
|
299
|
+
cost = receipt["result"]["new_cost_microusd"] if receipt else 0
|
|
300
|
+
if cost is None:
|
|
301
|
+
return "uncertain_usage"
|
|
302
|
+
charged += cost
|
|
303
|
+
if charged + reserved_cost > self.profile["max_run_cost_microusd"]:
|
|
304
|
+
return "run_budget"
|
|
305
|
+
if (
|
|
306
|
+
db.execute(
|
|
307
|
+
"UPDATE benchmark_probes SET phase='dispatching',reserved_cost=? "
|
|
308
|
+
"WHERE id=? AND phase='pending'",
|
|
309
|
+
(reserved_cost, identifier),
|
|
310
|
+
).rowcount
|
|
311
|
+
!= 1
|
|
312
|
+
):
|
|
313
|
+
return "already_claimed"
|
|
314
|
+
return None
|
|
315
|
+
|
|
316
|
+
def finish(self, identifier, row, receipt, *, deferred=False):
|
|
317
|
+
with self.store.transaction() as db:
|
|
318
|
+
if (
|
|
319
|
+
db.execute(
|
|
320
|
+
"UPDATE benchmark_probes SET phase=?,record=?,receipt=? "
|
|
321
|
+
"WHERE id=? AND phase='dispatching'",
|
|
322
|
+
(
|
|
323
|
+
"pending" if deferred else "done",
|
|
324
|
+
canonical_json(row),
|
|
325
|
+
canonical_json(receipt) if receipt else None,
|
|
326
|
+
identifier,
|
|
327
|
+
),
|
|
328
|
+
).rowcount
|
|
329
|
+
!= 1
|
|
330
|
+
):
|
|
331
|
+
raise BenchmarkError("Dispatch intent lost; accounting requires review")
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def validate_execution(bundle, frozen, payload):
|
|
335
|
+
try:
|
|
336
|
+
if set(payload) != {
|
|
337
|
+
"schema_version",
|
|
338
|
+
"execution_id",
|
|
339
|
+
"manifest",
|
|
340
|
+
"profile",
|
|
341
|
+
"entries",
|
|
342
|
+
"digest",
|
|
343
|
+
}:
|
|
344
|
+
raise BenchmarkError("Unexpected execution snapshot fields")
|
|
345
|
+
if type(payload["schema_version"]) is not int or payload["schema_version"] != 2:
|
|
346
|
+
raise BenchmarkError("Unsupported execution snapshot")
|
|
347
|
+
if payload["digest"] != fingerprint({k: v for k, v in payload.items() if k != "digest"}):
|
|
348
|
+
raise BenchmarkError("Execution snapshot digest mismatch")
|
|
349
|
+
manifest = Manifest(canonical_json(payload["manifest"]))
|
|
350
|
+
check_manifest(bundle, frozen, manifest)
|
|
351
|
+
profile = payload["profile"]
|
|
352
|
+
if payload["execution_id"] != fingerprint({"manifest": manifest.data, "profile": profile}):
|
|
353
|
+
raise BenchmarkError("Execution identity mismatch")
|
|
354
|
+
if profile["mode"] not in ("offline", "live"):
|
|
355
|
+
raise BenchmarkError("Unknown execution provenance")
|
|
356
|
+
if profile["adapter"] != ADAPTER_VERSION or profile["endpoint"] != ENDPOINT:
|
|
357
|
+
raise BenchmarkError("Unsupported provider profile")
|
|
358
|
+
if set(profile["clients"]) != set(manifest.data["models"]):
|
|
359
|
+
raise BenchmarkError("Profile model selection mismatch")
|
|
360
|
+
maximum = profile["max_run_cost_microusd"]
|
|
361
|
+
if type(maximum) is not int or not 0 <= maximum <= 10**12:
|
|
362
|
+
raise BenchmarkError("Invalid recorded run spending cap")
|
|
363
|
+
for model, config in profile["clients"].items():
|
|
364
|
+
quota = QuotaPolicy(**config["quota"])
|
|
365
|
+
quota.validate_prices(PriceCard(**config["prices"]))
|
|
366
|
+
if (quota.billing_mode == "free_tier") != (maximum == 0):
|
|
367
|
+
raise BenchmarkError("Recorded free-tier policy and spending cap disagree")
|
|
368
|
+
RetryConfig(**config["retry"])
|
|
369
|
+
ReplayPolicy(**config["replay"])
|
|
370
|
+
if asdict(GenerationConfig(**config["generation"])) != dict(
|
|
371
|
+
model=model, tool_choice="none", **manifest.data["protocol"]["generation"]
|
|
372
|
+
):
|
|
373
|
+
raise BenchmarkError("Profile generation drift")
|
|
374
|
+
if config["transport"].startswith("groq-live-") != (profile["mode"] == "live"):
|
|
375
|
+
raise BenchmarkError("Transport provenance mismatch")
|
|
376
|
+
rows = []
|
|
377
|
+
for entry in payload["entries"]:
|
|
378
|
+
row, receipt = entry["record"], entry["receipt"]
|
|
379
|
+
if entry["probe_id"] != row["probe_id"] or entry["phase"] not in (
|
|
380
|
+
"done",
|
|
381
|
+
"pending",
|
|
382
|
+
"dispatching",
|
|
383
|
+
):
|
|
384
|
+
raise BenchmarkError("Journal state mismatch")
|
|
385
|
+
if type(entry["reserved_cost"]) is not int or entry["reserved_cost"] < 0:
|
|
386
|
+
raise BenchmarkError("Invalid reservation")
|
|
387
|
+
if receipt:
|
|
388
|
+
verify_receipt(receipt, row["model"], profile)
|
|
389
|
+
key = expected_request_key(
|
|
390
|
+
row,
|
|
391
|
+
profile,
|
|
392
|
+
payload["execution_id"],
|
|
393
|
+
bundle.get("scenario")["scope"],
|
|
394
|
+
manifest.data["protocol"],
|
|
395
|
+
)
|
|
396
|
+
if receipt["result"]["request_key"] != key:
|
|
397
|
+
raise BenchmarkError("Receipt belongs to a different assembled request")
|
|
398
|
+
prepared = {**row, **dict.fromkeys(RESPONSE_FIELDS), "state": "prepared"}
|
|
399
|
+
if (
|
|
400
|
+
bind_response(bundle, prepared, receipt, profile["mode"]) != row
|
|
401
|
+
or entry["phase"] != "done"
|
|
402
|
+
):
|
|
403
|
+
raise BenchmarkError("Adapter receipt differs from graded record")
|
|
404
|
+
elif row["state"] not in ("non_fit", "prepared"):
|
|
405
|
+
raise BenchmarkError("Outcome lacks adapter evidence")
|
|
406
|
+
if (entry["phase"] == "done") != (row["state"] != "prepared"):
|
|
407
|
+
raise BenchmarkError("Terminal journal state mismatch")
|
|
408
|
+
rows.append(row)
|
|
409
|
+
validation = validate_run(bundle, frozen, manifest, rows)
|
|
410
|
+
if any(g["status"] == "FAIL" and g["gate"] != "V4" for g in validation["gates"]):
|
|
411
|
+
raise BenchmarkError("Execution snapshot failed integrity gates")
|
|
412
|
+
return manifest, rows, validation
|
|
413
|
+
except BenchmarkError:
|
|
414
|
+
raise
|
|
415
|
+
except (ContextEngineError, KeyError, TypeError, ValueError, IndexError, StopIteration):
|
|
416
|
+
raise BenchmarkError("Malformed execution snapshot") from None
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def execution_snapshot(journal):
|
|
420
|
+
payload = {
|
|
421
|
+
"schema_version": 2,
|
|
422
|
+
"execution_id": journal.execution_id,
|
|
423
|
+
**journal.identity,
|
|
424
|
+
"entries": journal.snapshot(),
|
|
425
|
+
}
|
|
426
|
+
return {**payload, "digest": fingerprint(payload)}
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def load_execution(path, bundle, frozen):
|
|
430
|
+
try:
|
|
431
|
+
with Path(path).open("rb") as handle:
|
|
432
|
+
raw = handle.read(MAX_RUN_BYTES + 1)
|
|
433
|
+
payload = strict_json(raw.decode("utf-8"), maximum=MAX_RUN_BYTES)
|
|
434
|
+
validate_execution(bundle, frozen, payload)
|
|
435
|
+
return payload
|
|
436
|
+
except (OSError, UnicodeError):
|
|
437
|
+
raise BenchmarkError("Cannot read execution snapshot") from None
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def save_execution(path, payload):
|
|
441
|
+
"""Bounded compact export; indentation must not expand the full 744-slot evidence."""
|
|
442
|
+
raw = (canonical_json(payload) + "\n").encode("utf-8")
|
|
443
|
+
if len(raw) > MAX_RUN_BYTES:
|
|
444
|
+
raise BenchmarkError("Snapshot exceeds export limit; journal remains recoverable")
|
|
445
|
+
try:
|
|
446
|
+
path = Path(path)
|
|
447
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
448
|
+
with path.open("xb") as handle:
|
|
449
|
+
handle.write(raw)
|
|
450
|
+
except OSError:
|
|
451
|
+
raise BenchmarkError("Snapshot destination must be a new writable file") from None
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
async def execute(bundle, frozen, journal, clients, *, max_calls=744, allow_live=False):
|
|
455
|
+
check_manifest(bundle, frozen, journal.manifest)
|
|
456
|
+
profile = execution_profile(
|
|
457
|
+
journal.manifest,
|
|
458
|
+
clients,
|
|
459
|
+
mode=journal.profile["mode"],
|
|
460
|
+
max_run_cost_microusd=journal.profile["max_run_cost_microusd"],
|
|
461
|
+
)
|
|
462
|
+
if profile != journal.profile:
|
|
463
|
+
raise BenchmarkError("Provider execution profile drift")
|
|
464
|
+
if type(max_calls) is not int or not 0 <= max_calls <= 744:
|
|
465
|
+
raise BenchmarkError("Execution call batch must be within 0..744")
|
|
466
|
+
if profile["mode"] == "live" and (
|
|
467
|
+
not allow_live or journal.manifest.data["protocol"]["approval"] != "owner_approved"
|
|
468
|
+
):
|
|
469
|
+
raise BenchmarkError("Live benchmark requires authorization and approved registration")
|
|
470
|
+
payload = execution_snapshot(journal)
|
|
471
|
+
validate_execution(bundle, frozen, payload)
|
|
472
|
+
existing = {e["probe_id"]: e for e in payload["entries"]}
|
|
473
|
+
if any(e["phase"] == "dispatching" for e in existing.values()):
|
|
474
|
+
return {"status": "PAUSED", "reason": "uncertain_dispatch", "calls": 0}
|
|
475
|
+
calls = 0
|
|
476
|
+
# Contexts do not depend on model identity; reuse only within this immutable batch.
|
|
477
|
+
prepared_cache = {}
|
|
478
|
+
for slot in journal.manifest.slots:
|
|
479
|
+
entry = existing.get(slot["probe_id"])
|
|
480
|
+
if entry and entry["phase"] == "done":
|
|
481
|
+
continue
|
|
482
|
+
key = (slot["budget"], slot["variant"], slot["fact_id"])
|
|
483
|
+
if entry:
|
|
484
|
+
prepared = entry["record"]
|
|
485
|
+
elif key in prepared_cache:
|
|
486
|
+
prepared = {**prepared_cache[key], **slot}
|
|
487
|
+
else:
|
|
488
|
+
prepared = _prepare_validated(bundle, slot)
|
|
489
|
+
prepared_cache[key] = prepared
|
|
490
|
+
journal.prepare(prepared)
|
|
491
|
+
if prepared["state"] == "non_fit":
|
|
492
|
+
continue
|
|
493
|
+
if calls >= max_calls:
|
|
494
|
+
return {"status": "PAUSED", "reason": "batch_limit", "calls": calls}
|
|
495
|
+
client = clients[slot["model"]]
|
|
496
|
+
request = request_from_wire(prepared["request"])
|
|
497
|
+
if client.counter.count_request(request).to_dict() != prepared["estimate"]:
|
|
498
|
+
raise BenchmarkError("Provider counter or request serialization drift before dispatch")
|
|
499
|
+
reservation = client.prices.reserve_cost(
|
|
500
|
+
prepared["estimate"]["estimated_tokens"], client.generation.max_completion_tokens
|
|
501
|
+
)
|
|
502
|
+
blocked = journal.claim(slot["probe_id"], reservation)
|
|
503
|
+
if blocked:
|
|
504
|
+
return {"status": "PAUSED", "reason": blocked, "calls": calls}
|
|
505
|
+
p = journal.manifest.data["protocol"]
|
|
506
|
+
budget = BudgetConfig(
|
|
507
|
+
input_cap=slot["budget"],
|
|
508
|
+
completion_reservation=p["generation"]["max_completion_tokens"],
|
|
509
|
+
**p["budget"],
|
|
510
|
+
)
|
|
511
|
+
request = request_from_wire(prepared["request"])
|
|
512
|
+
scope = bundle.job(bundle.fact(slot["fact_id"])["question"]).arguments["pinned_facts"].scope
|
|
513
|
+
# Cancellation/crash preserves the committed intent; it must never be blindly redelivered.
|
|
514
|
+
result = await client.complete(
|
|
515
|
+
request,
|
|
516
|
+
budget,
|
|
517
|
+
scope=scope,
|
|
518
|
+
security_scope=profile["security_scope"],
|
|
519
|
+
snapshot_revision=profile["snapshot_revision"],
|
|
520
|
+
policy_version=journal.execution_id,
|
|
521
|
+
)
|
|
522
|
+
if result.error_code == "quota_exhausted" and not result.attempt_ids:
|
|
523
|
+
journal.finish(slot["probe_id"], prepared, None, deferred=True)
|
|
524
|
+
return {"status": "PAUSED", "reason": "quota", "calls": calls}
|
|
525
|
+
calls += 1
|
|
526
|
+
ids = set(result.attempt_ids) | ({result.replay_of} if result.replay_of else set())
|
|
527
|
+
receipt = {
|
|
528
|
+
"result": result.to_dict(include_content=True),
|
|
529
|
+
"ledger_rows": [
|
|
530
|
+
a for a in client.store.snapshot(client.quota)["attempts"] if a["id"] in ids
|
|
531
|
+
],
|
|
532
|
+
}
|
|
533
|
+
verify_receipt(receipt, slot["model"], profile)
|
|
534
|
+
row = bind_response(bundle, prepared, receipt, profile["mode"])
|
|
535
|
+
journal.finish(slot["probe_id"], row, receipt)
|
|
536
|
+
if result.new_cost_microusd is None:
|
|
537
|
+
return {"status": "PAUSED", "reason": "uncertain_usage", "calls": calls}
|
|
538
|
+
return {"status": "FINISHED", "reason": "all_slots_disposed", "calls": calls}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Ground truth belongs in fixture validation, never inside the reusable layer inputs."""
|
|
2
|
+
|
|
3
|
+
import unicodedata
|
|
4
|
+
|
|
5
|
+
from ..errors import ContractError, SummaryLeakageError
|
|
6
|
+
from ..layers.summarize import FrozenSummaryPolicy, SummarySnapshot
|
|
7
|
+
from ..models import text_value
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def validate_frozen_summary(
|
|
11
|
+
snapshot: SummarySnapshot, forbidden_answers: tuple[str, ...]
|
|
12
|
+
) -> FrozenSummaryPolicy:
|
|
13
|
+
"""Conservative identifier/alias gate, including case/spacing/punctuation variants.
|
|
14
|
+
|
|
15
|
+
Short aliases can cause false positives; fix the fixture rather than silently
|
|
16
|
+
exempting answers. This does not detect semantic paraphrases of an answer.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def normalized(text: str) -> str:
|
|
20
|
+
return "".join(c for c in unicodedata.normalize("NFKC", text).casefold() if c.isalnum())
|
|
21
|
+
|
|
22
|
+
if not forbidden_answers:
|
|
23
|
+
raise ContractError("Benchmark summary validation requires declared answer aliases")
|
|
24
|
+
summary = normalized(snapshot.content)
|
|
25
|
+
for answer in forbidden_answers:
|
|
26
|
+
text_value("answer_alias", answer)
|
|
27
|
+
value = normalized(answer)
|
|
28
|
+
if not value:
|
|
29
|
+
raise ContractError("Answer alias must contain letters or numbers")
|
|
30
|
+
if value in summary:
|
|
31
|
+
raise SummaryLeakageError("Frozen summary contains a declared answer alias")
|
|
32
|
+
return FrozenSummaryPolicy(snapshot)
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Independent deterministic evidence/answer grading; no model judge or substring guesses."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
import re
|
|
6
|
+
import unicodedata
|
|
7
|
+
|
|
8
|
+
from ..errors import BenchmarkError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def normalize(text: str) -> str:
|
|
12
|
+
if not isinstance(text, str):
|
|
13
|
+
raise BenchmarkError("Grading requires text")
|
|
14
|
+
text = unicodedata.normalize("NFKC", text).casefold()
|
|
15
|
+
return " ".join("".join(c for c in text if unicodedata.category(c) != "Cf").split())
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def present(text: str, aliases: tuple[str, ...]) -> bool:
|
|
19
|
+
"""Identifier boundaries: shard-1 is not shard-19, nor is 7 part of t7."""
|
|
20
|
+
value = normalize(text)
|
|
21
|
+
return any(
|
|
22
|
+
re.search(r"(?<![\w.-])" + re.escape(normalize(alias)) + r"(?!\w|[-.]\w)", value)
|
|
23
|
+
is not None
|
|
24
|
+
for alias in aliases
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def answer_correct(answer: str, aliases: tuple[str, ...]) -> bool:
|
|
29
|
+
"""Exact alias or one-field JSON answer; prose containing the answer is not enough."""
|
|
30
|
+
value = answer.strip()
|
|
31
|
+
if value.startswith("{"):
|
|
32
|
+
try:
|
|
33
|
+
pairs = json.loads(value, object_pairs_hook=lambda items: items)
|
|
34
|
+
except (ValueError, RecursionError):
|
|
35
|
+
return False
|
|
36
|
+
if not isinstance(pairs, list) or len(pairs) != 1 or pairs[0][0] != "answer":
|
|
37
|
+
return False
|
|
38
|
+
value = pairs[0][1]
|
|
39
|
+
if not isinstance(value, str):
|
|
40
|
+
return False
|
|
41
|
+
return normalize(value) in {normalize(a) for a in aliases}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def proportion(successes: int, denominator: int) -> dict:
|
|
45
|
+
if (
|
|
46
|
+
type(successes) is not int
|
|
47
|
+
or type(denominator) is not int
|
|
48
|
+
or not 0 <= successes <= denominator
|
|
49
|
+
):
|
|
50
|
+
raise BenchmarkError("Invalid metric denominator")
|
|
51
|
+
if denominator == 0:
|
|
52
|
+
return {"count": successes, "denominator": 0, "rate": None, "wilson95": None}
|
|
53
|
+
p, z = successes / denominator, 1.959963984540054
|
|
54
|
+
divisor = 1 + z * z / denominator
|
|
55
|
+
center = (p + z * z / (2 * denominator)) / divisor
|
|
56
|
+
radius = z * math.sqrt((p * (1 - p) + z * z / (4 * denominator)) / denominator) / divisor
|
|
57
|
+
return {
|
|
58
|
+
"count": successes,
|
|
59
|
+
"denominator": denominator,
|
|
60
|
+
"rate": p,
|
|
61
|
+
"wilson95": [max(0.0, center - radius), min(1.0, center + radius)],
|
|
62
|
+
}
|