aid-runtime-python 0.1.161__py3-none-any.whl → 0.1.163__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.
- aid_runtime/__init__.py +13 -1
- aid_runtime/agents/__init__.py +24 -0
- aid_runtime/agents/loop.py +34 -1
- aid_runtime/agents/resume.py +398 -0
- aid_runtime/agents/state.py +24 -0
- aid_runtime/evals/__init__.py +2 -0
- aid_runtime/evals/gate.py +42 -1
- aid_runtime/evals/runner.py +31 -2
- {aid_runtime_python-0.1.161.dist-info → aid_runtime_python-0.1.163.dist-info}/METADATA +1 -1
- {aid_runtime_python-0.1.161.dist-info → aid_runtime_python-0.1.163.dist-info}/RECORD +12 -11
- {aid_runtime_python-0.1.161.dist-info → aid_runtime_python-0.1.163.dist-info}/WHEEL +0 -0
- {aid_runtime_python-0.1.161.dist-info → aid_runtime_python-0.1.163.dist-info}/top_level.txt +0 -0
aid_runtime/__init__.py
CHANGED
|
@@ -29,12 +29,15 @@ from aid_runtime.agents import (
|
|
|
29
29
|
AgentCheckpoint,
|
|
30
30
|
AgentDefinition,
|
|
31
31
|
AgentRuntime,
|
|
32
|
+
CheckpointRefusalError,
|
|
33
|
+
CheckpointSigner,
|
|
32
34
|
FileMemoryStore,
|
|
33
35
|
HumanApproval,
|
|
34
36
|
HumanDecision,
|
|
35
37
|
InProcessMemoryStore,
|
|
36
38
|
MemoryDefinition,
|
|
37
39
|
MemoryStore,
|
|
40
|
+
NonceStore,
|
|
38
41
|
PendingApproval,
|
|
39
42
|
Principal,
|
|
40
43
|
RunResult,
|
|
@@ -44,6 +47,8 @@ from aid_runtime.agents import (
|
|
|
44
47
|
StepRecord,
|
|
45
48
|
ThreadMemory,
|
|
46
49
|
ToolSpec,
|
|
50
|
+
nonce_store_from_env,
|
|
51
|
+
signer_from_env,
|
|
47
52
|
)
|
|
48
53
|
from aid_runtime.cache import CompletionCache, cache_key_for
|
|
49
54
|
from aid_runtime.concurrency import ConcurrencyLimiter
|
|
@@ -116,6 +121,7 @@ from aid_runtime.errors import (
|
|
|
116
121
|
)
|
|
117
122
|
from aid_runtime.evals import (
|
|
118
123
|
AgentEvalRunner,
|
|
124
|
+
AggregateBaseline,
|
|
119
125
|
ApprovalPolicy,
|
|
120
126
|
ApprovalRespected,
|
|
121
127
|
BaselineGate,
|
|
@@ -350,7 +356,7 @@ from aid_runtime.types import (
|
|
|
350
356
|
)
|
|
351
357
|
|
|
352
358
|
#: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
|
|
353
|
-
__version__ = "0.1.
|
|
359
|
+
__version__ = "0.1.163"
|
|
354
360
|
|
|
355
361
|
__all__ = [
|
|
356
362
|
"AGENT_LABEL",
|
|
@@ -396,6 +402,7 @@ __all__ = [
|
|
|
396
402
|
"AgentHandoffUnsupportedError",
|
|
397
403
|
"AgentRuntime",
|
|
398
404
|
"AgentTransferCycleError",
|
|
405
|
+
"AggregateBaseline",
|
|
399
406
|
"AidRuntimeError",
|
|
400
407
|
"AnthropicProvider",
|
|
401
408
|
"ApprovalPolicy",
|
|
@@ -407,6 +414,8 @@ __all__ = [
|
|
|
407
414
|
"Capability",
|
|
408
415
|
"CapabilityMismatchError",
|
|
409
416
|
"CaseOutcome",
|
|
417
|
+
"CheckpointRefusalError",
|
|
418
|
+
"CheckpointSigner",
|
|
410
419
|
"Chunk",
|
|
411
420
|
"Chunker",
|
|
412
421
|
"ChunkingSpec",
|
|
@@ -493,6 +502,7 @@ __all__ = [
|
|
|
493
502
|
"ModelCacheConfig",
|
|
494
503
|
"ModelGateway",
|
|
495
504
|
"ModelSpec",
|
|
505
|
+
"NonceStore",
|
|
496
506
|
"NormalizedContains",
|
|
497
507
|
"OpenAICompatibleEmbedder",
|
|
498
508
|
"OpenAICompatibleProvider",
|
|
@@ -625,6 +635,7 @@ __all__ = [
|
|
|
625
635
|
"local_trace_enabled",
|
|
626
636
|
"map_step",
|
|
627
637
|
"metric_names",
|
|
638
|
+
"nonce_store_from_env",
|
|
628
639
|
"normalize",
|
|
629
640
|
"open_connector",
|
|
630
641
|
"parallel",
|
|
@@ -650,6 +661,7 @@ __all__ = [
|
|
|
650
661
|
"rrf_score",
|
|
651
662
|
"run_evaluation",
|
|
652
663
|
"run_structured",
|
|
664
|
+
"signer_from_env",
|
|
653
665
|
"similarity",
|
|
654
666
|
"sync_support",
|
|
655
667
|
"tokenize",
|
aid_runtime/agents/__init__.py
CHANGED
|
@@ -60,8 +60,21 @@ from aid_runtime.agents.memory import (
|
|
|
60
60
|
render_context,
|
|
61
61
|
)
|
|
62
62
|
from aid_runtime.agents.policy import Principal, evaluate_policy, policy_source
|
|
63
|
+
from aid_runtime.agents.resume import (
|
|
64
|
+
DEFAULT_CHECKPOINT_TTL_MINUTES,
|
|
65
|
+
CheckpointRefusalError,
|
|
66
|
+
CheckpointSigner,
|
|
67
|
+
InProcessNonceStore,
|
|
68
|
+
NonceStore,
|
|
69
|
+
PostgresNonceStore,
|
|
70
|
+
SqliteNonceStore,
|
|
71
|
+
nonce_store_for,
|
|
72
|
+
nonce_store_from_env,
|
|
73
|
+
signer_from_env,
|
|
74
|
+
)
|
|
63
75
|
from aid_runtime.agents.state import (
|
|
64
76
|
AgentCheckpoint,
|
|
77
|
+
CheckpointIntegrity,
|
|
65
78
|
HumanDecision,
|
|
66
79
|
PendingApproval,
|
|
67
80
|
RunResult,
|
|
@@ -71,6 +84,7 @@ from aid_runtime.agents.state import (
|
|
|
71
84
|
)
|
|
72
85
|
|
|
73
86
|
__all__ = [
|
|
87
|
+
"DEFAULT_CHECKPOINT_TTL_MINUTES",
|
|
74
88
|
"DETECTORS",
|
|
75
89
|
"GUARDRAIL_ACTIONS",
|
|
76
90
|
"GUARDRAIL_STAGES",
|
|
@@ -82,6 +96,9 @@ __all__ = [
|
|
|
82
96
|
"AgentRuntime",
|
|
83
97
|
"BedrockGuardrailClient",
|
|
84
98
|
"BedrockGuardrailPolicy",
|
|
99
|
+
"CheckpointIntegrity",
|
|
100
|
+
"CheckpointRefusalError",
|
|
101
|
+
"CheckpointSigner",
|
|
85
102
|
"DecisionAsker",
|
|
86
103
|
"DecisionDefinition",
|
|
87
104
|
"Detection",
|
|
@@ -96,16 +113,20 @@ __all__ = [
|
|
|
96
113
|
"HumanApproval",
|
|
97
114
|
"HumanDecision",
|
|
98
115
|
"InProcessMemoryStore",
|
|
116
|
+
"InProcessNonceStore",
|
|
99
117
|
"ManagedGuardrailSettings",
|
|
100
118
|
"MemoryDefinition",
|
|
101
119
|
"MemoryStore",
|
|
102
120
|
"ModelArmorGuardrailClient",
|
|
103
121
|
"ModelArmorGuardrailSettings",
|
|
122
|
+
"NonceStore",
|
|
104
123
|
"PendingApproval",
|
|
124
|
+
"PostgresNonceStore",
|
|
105
125
|
"Principal",
|
|
106
126
|
"RunResult",
|
|
107
127
|
"RunStatus",
|
|
108
128
|
"RuntimeSpec",
|
|
129
|
+
"SqliteNonceStore",
|
|
109
130
|
"StepKind",
|
|
110
131
|
"StepRecord",
|
|
111
132
|
"ThreadMemory",
|
|
@@ -115,6 +136,9 @@ __all__ = [
|
|
|
115
136
|
"evaluate_policy",
|
|
116
137
|
"managed_guardrail_settings",
|
|
117
138
|
"model_armor_settings",
|
|
139
|
+
"nonce_store_for",
|
|
140
|
+
"nonce_store_from_env",
|
|
118
141
|
"policy_source",
|
|
119
142
|
"render_context",
|
|
143
|
+
"signer_from_env",
|
|
120
144
|
]
|
aid_runtime/agents/loop.py
CHANGED
|
@@ -68,6 +68,11 @@ from aid_runtime.agents.policy import (
|
|
|
68
68
|
evaluate_policy,
|
|
69
69
|
policy_source,
|
|
70
70
|
)
|
|
71
|
+
from aid_runtime.agents.resume import (
|
|
72
|
+
CheckpointSigner,
|
|
73
|
+
InProcessNonceStore,
|
|
74
|
+
NonceStore,
|
|
75
|
+
)
|
|
71
76
|
from aid_runtime.agents.state import (
|
|
72
77
|
AgentCheckpoint,
|
|
73
78
|
HumanDecision,
|
|
@@ -193,6 +198,8 @@ class AgentRuntime:
|
|
|
193
198
|
memory_store: MemoryStore | None = None,
|
|
194
199
|
tracer: Tracer | None = None,
|
|
195
200
|
limiter: ConcurrencyLimiter | None = None,
|
|
201
|
+
signer: CheckpointSigner | None = None,
|
|
202
|
+
nonces: NonceStore | None = None,
|
|
196
203
|
) -> None:
|
|
197
204
|
self._spec = spec
|
|
198
205
|
self._gateway = gateway
|
|
@@ -202,6 +209,11 @@ class AgentRuntime:
|
|
|
202
209
|
memory_store if memory_store is not None else InProcessMemoryStore()
|
|
203
210
|
)
|
|
204
211
|
self._tracer = tracer
|
|
212
|
+
# A run that pauses hands its checkpoint to whoever called `run`, so the app that
|
|
213
|
+
# exposes a resume route must sign. Left `None`, the loop behaves exactly as it did
|
|
214
|
+
# before: a library embedding it directly is not silently given a key.
|
|
215
|
+
self._signer = signer
|
|
216
|
+
self._nonces: NonceStore = nonces if nonces is not None else InProcessNonceStore()
|
|
205
217
|
self._guardrails = GuardrailEngine(spec.guardrails, decisions=spec.decisions)
|
|
206
218
|
self._tools_by_name: dict[str, ToolSpec] = {
|
|
207
219
|
definition.name: definition for definition in spec.tools.values()
|
|
@@ -220,6 +232,8 @@ class AgentRuntime:
|
|
|
220
232
|
ledger: CostLedger | None = None,
|
|
221
233
|
budget: Budget | None = None,
|
|
222
234
|
tracer: Tracer | None = None,
|
|
235
|
+
signer: CheckpointSigner | None = None,
|
|
236
|
+
nonces: NonceStore | None = None,
|
|
223
237
|
) -> AgentRuntime:
|
|
224
238
|
"""Build a runtime from an emitted IR document.
|
|
225
239
|
|
|
@@ -240,6 +254,8 @@ class AgentRuntime:
|
|
|
240
254
|
memory_store=memory_store,
|
|
241
255
|
tracer=tracer,
|
|
242
256
|
limiter=limiter,
|
|
257
|
+
signer=signer,
|
|
258
|
+
nonces=nonces,
|
|
243
259
|
)
|
|
244
260
|
|
|
245
261
|
@property
|
|
@@ -296,6 +312,7 @@ class AgentRuntime:
|
|
|
296
312
|
principal: Principal | None = None,
|
|
297
313
|
) -> RunResult:
|
|
298
314
|
"""Continue a paused run from its checkpoint, with a human's answer."""
|
|
315
|
+
checkpoint = await self._accept(checkpoint)
|
|
299
316
|
resolved = HumanDecision(decision)
|
|
300
317
|
self._restore_ledger(checkpoint)
|
|
301
318
|
start_cost = self._gateway.ledger.cost_usd
|
|
@@ -312,6 +329,18 @@ class AgentRuntime:
|
|
|
312
329
|
raise
|
|
313
330
|
return self._wrap(outcome, start_cost, start_tokens)
|
|
314
331
|
|
|
332
|
+
async def _accept(self, checkpoint: AgentCheckpoint) -> AgentCheckpoint:
|
|
333
|
+
"""Refuse a checkpoint this app did not issue, has expired, or already spent.
|
|
334
|
+
|
|
335
|
+
Called before anything the checkpoint carries is read, so a tampered pending call
|
|
336
|
+
is never authorized, priced or observed. A runtime built without a signer keeps the
|
|
337
|
+
pre-signing behaviour, which is what a direct library embedder already had.
|
|
338
|
+
"""
|
|
339
|
+
if self._signer is None:
|
|
340
|
+
return checkpoint
|
|
341
|
+
await self._signer.accept(checkpoint, self._nonces)
|
|
342
|
+
return checkpoint
|
|
343
|
+
|
|
315
344
|
async def _resume(
|
|
316
345
|
self,
|
|
317
346
|
checkpoint: AgentCheckpoint,
|
|
@@ -1057,7 +1086,7 @@ class AgentRuntime:
|
|
|
1057
1086
|
channel = approval.channel
|
|
1058
1087
|
else:
|
|
1059
1088
|
channel = _TOOL_CONFIRMATION
|
|
1060
|
-
|
|
1089
|
+
checkpoint = AgentCheckpoint(
|
|
1061
1090
|
agent_id=frame.agent.id,
|
|
1062
1091
|
step=frame.step,
|
|
1063
1092
|
messages=tuple(frame.messages),
|
|
@@ -1076,6 +1105,10 @@ class AgentRuntime:
|
|
|
1076
1105
|
escalation=escalation,
|
|
1077
1106
|
guardrails=tuple(frame.guardrails),
|
|
1078
1107
|
)
|
|
1108
|
+
# Signed here rather than at the route, so every pause path -- approval, tool
|
|
1109
|
+
# confirmation, guardrail escalation, and the nested caller of a delegate -- is
|
|
1110
|
+
# issued by the same key. A second signing site is a second thing to forget.
|
|
1111
|
+
return checkpoint if self._signer is None else self._signer.sign(checkpoint)
|
|
1079
1112
|
|
|
1080
1113
|
def _restore_ledger(self, checkpoint: AgentCheckpoint) -> None:
|
|
1081
1114
|
"""Carry a pause's spend into this process's ledger before resuming.
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
"""Checkpoint integrity: signing, expiry and replay refusal for a paused run.
|
|
2
|
+
|
|
3
|
+
A paused run is continued by handing the checkpoint back to ``POST /agents/resume``, so
|
|
4
|
+
the checkpoint *is* the capability. Before this module it was a bearer capability with no
|
|
5
|
+
integrity: the body was parsed into :class:`AgentCheckpoint` and replayed, so anyone
|
|
6
|
+
holding one could edit an approval decision or swap the pending tool-call arguments and
|
|
7
|
+
the loop would execute the edited call. A signature is what turns "a body shaped like a
|
|
8
|
+
checkpoint" into "a checkpoint this app issued".
|
|
9
|
+
|
|
10
|
+
Three properties are enforced here, and each has its own refusal reason:
|
|
11
|
+
|
|
12
|
+
* ``"tampered"`` -- the HMAC does not match the payload the signer covered. The signature
|
|
13
|
+
covers the *whole* checkpoint minus the signature itself, so a flipped approval
|
|
14
|
+
decision, a swapped argument and an extended expiry all fail the same check rather than
|
|
15
|
+
needing a field-by-field audit.
|
|
16
|
+
* ``"expired"`` -- ``expires_at`` (inside the signed payload, so it cannot be extended
|
|
17
|
+
without breaking the signature) is in the past.
|
|
18
|
+
* ``"replayed"`` -- the nonce was already claimed. Claiming is a store operation rather
|
|
19
|
+
than an in-memory check because a replay across two processes is the interesting case.
|
|
20
|
+
|
|
21
|
+
The secret is a *value read from the environment*, never a value in the spec: the
|
|
22
|
+
generated app names the variable and this module fails loudly when it is unset, because a
|
|
23
|
+
missing secret must not degrade into "unsigned".
|
|
24
|
+
|
|
25
|
+
Replay durability is limited by the nonce store, and that limit is real rather than
|
|
26
|
+
theoretical: :class:`InProcessNonceStore` forgets on restart and does not span replicas.
|
|
27
|
+
:class:`SqliteNonceStore` is durable and is what a ``state.kind: sqlite`` declaration
|
|
28
|
+
gets. A ``state.kind: postgres`` declaration is served in-process for now, which the
|
|
29
|
+
``ir/resume-replay-weak`` gate states on the document rather than leaving to be
|
|
30
|
+
discovered.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import asyncio
|
|
36
|
+
import hashlib
|
|
37
|
+
import hmac
|
|
38
|
+
import json
|
|
39
|
+
import os
|
|
40
|
+
import secrets
|
|
41
|
+
import sqlite3
|
|
42
|
+
import time
|
|
43
|
+
from dataclasses import dataclass, field
|
|
44
|
+
from pathlib import Path
|
|
45
|
+
from typing import Any, Protocol, runtime_checkable
|
|
46
|
+
|
|
47
|
+
from aid_runtime.agents.state import AgentCheckpoint, CheckpointIntegrity
|
|
48
|
+
from aid_runtime.errors import AidRuntimeError, ConfigurationError
|
|
49
|
+
|
|
50
|
+
__all__ = [
|
|
51
|
+
"DEFAULT_CHECKPOINT_TTL_MINUTES",
|
|
52
|
+
"CheckpointRefusalError",
|
|
53
|
+
"CheckpointSigner",
|
|
54
|
+
"InProcessNonceStore",
|
|
55
|
+
"NonceStore",
|
|
56
|
+
"PostgresNonceStore",
|
|
57
|
+
"SqliteNonceStore",
|
|
58
|
+
"checkpoint_payload",
|
|
59
|
+
"nonce_store_for",
|
|
60
|
+
"signer_from_env",
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
#: How long a checkpoint stays usable. Short on purpose: a pause is a question asked of
|
|
64
|
+
#: a person in the same change window, not a durable queue.
|
|
65
|
+
DEFAULT_CHECKPOINT_TTL_MINUTES = 15
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class CheckpointRefusalError(AidRuntimeError):
|
|
69
|
+
"""A resume body this app will not honour, with a stable machine-readable reason.
|
|
70
|
+
|
|
71
|
+
``reason`` is one of ``tampered``, ``expired``, ``replayed``, ``unsigned``. The
|
|
72
|
+
generated route maps it to a 403 and returns it as ``detail.reason``, so a caller can
|
|
73
|
+
tell "your checkpoint expired" from "your checkpoint was edited" without parsing
|
|
74
|
+
prose.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
def __init__(self, reason: str, message: str) -> None:
|
|
78
|
+
super().__init__(message)
|
|
79
|
+
self.reason = reason
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@runtime_checkable
|
|
83
|
+
class NonceStore(Protocol):
|
|
84
|
+
"""Remembers which checkpoints have been spent.
|
|
85
|
+
|
|
86
|
+
``claim`` must be atomic: two concurrent requests presenting the same checkpoint may
|
|
87
|
+
both reach it, and exactly one must be told ``True``. A store that reads then writes
|
|
88
|
+
would let both through.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
async def claim(self, *, nonce: str, expires_at: int, now: int) -> bool:
|
|
92
|
+
"""``True`` the first time ``nonce`` is seen, ``False`` every time after.
|
|
93
|
+
|
|
94
|
+
``now`` is the caller's clock, not this store's, so the pruning horizon and the
|
|
95
|
+
expiry the signer checked cannot disagree. A store that read the wall clock while
|
|
96
|
+
the signer took an injected one would prune a row before the replay check and
|
|
97
|
+
accept the replay.
|
|
98
|
+
"""
|
|
99
|
+
...
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class InProcessNonceStore:
|
|
103
|
+
"""A dict, and therefore a limit worth stating.
|
|
104
|
+
|
|
105
|
+
It is the honest default: a library must not decide where a host keeps its data. It
|
|
106
|
+
survives neither a restart nor a second replica, so a checkpoint replayed against
|
|
107
|
+
another worker is accepted there. ``profile: enterprise`` with no declared ``state``
|
|
108
|
+
is refused by ``ir/resume-replay-weak`` for exactly this reason.
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
def __init__(self) -> None:
|
|
112
|
+
self._seen: dict[str, int] = {}
|
|
113
|
+
self._lock = asyncio.Lock()
|
|
114
|
+
|
|
115
|
+
async def claim(self, *, nonce: str, expires_at: int, now: int) -> bool:
|
|
116
|
+
async with self._lock:
|
|
117
|
+
self._seen = {seen: expiry for seen, expiry in self._seen.items() if expiry > now}
|
|
118
|
+
if nonce in self._seen:
|
|
119
|
+
return False
|
|
120
|
+
self._seen[nonce] = expires_at
|
|
121
|
+
return True
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class SqliteNonceStore:
|
|
125
|
+
"""A file, and therefore durable across a restart.
|
|
126
|
+
|
|
127
|
+
``INSERT OR IGNORE`` is the atomic claim: SQLite reports whether it inserted, so two
|
|
128
|
+
workers sharing the file cannot both see ``True``. This is what a ``state.kind:
|
|
129
|
+
sqlite`` declaration is served by, because that declaration already means "a file on
|
|
130
|
+
a volume this process can reach".
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
def __init__(self, path: str | Path) -> None:
|
|
134
|
+
self._path = Path(path)
|
|
135
|
+
self._lock = asyncio.Lock()
|
|
136
|
+
|
|
137
|
+
async def claim(self, *, nonce: str, expires_at: int, now: int) -> bool:
|
|
138
|
+
async with self._lock:
|
|
139
|
+
return await asyncio.to_thread(self._claim, nonce, expires_at, now)
|
|
140
|
+
|
|
141
|
+
def _claim(self, nonce: str, expires_at: int, now: int) -> bool:
|
|
142
|
+
self._path.parent.mkdir(parents=True, exist_ok=True)
|
|
143
|
+
with sqlite3.connect(self._path) as connection:
|
|
144
|
+
connection.execute("PRAGMA journal_mode=WAL")
|
|
145
|
+
connection.execute(
|
|
146
|
+
"CREATE TABLE IF NOT EXISTS checkpoint_nonce ("
|
|
147
|
+
"nonce TEXT PRIMARY KEY, expires_at INTEGER NOT NULL)"
|
|
148
|
+
)
|
|
149
|
+
connection.execute("DELETE FROM checkpoint_nonce WHERE expires_at <= ?", (now,))
|
|
150
|
+
cursor = connection.execute(
|
|
151
|
+
"INSERT OR IGNORE INTO checkpoint_nonce (nonce, expires_at) VALUES (?, ?)",
|
|
152
|
+
(nonce, expires_at),
|
|
153
|
+
)
|
|
154
|
+
return cursor.rowcount == 1
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class PostgresNonceStore:
|
|
158
|
+
"""The same claim in the database the document already names.
|
|
159
|
+
|
|
160
|
+
``state.kind: postgres`` is the enterprise answer, so replay protection has to live
|
|
161
|
+
there rather than in a process: the whole point of a shared store is that the next
|
|
162
|
+
request may land anywhere. ``ON CONFLICT DO NOTHING`` plus ``RETURNING`` makes the
|
|
163
|
+
claim atomic in the database, which is the only place a claim can be atomic across
|
|
164
|
+
replicas.
|
|
165
|
+
|
|
166
|
+
The driver is optional, following the pgvector store: a deployment that never
|
|
167
|
+
declares `postgres` pays nothing for it, and one that does is told which extra to
|
|
168
|
+
install rather than discovering it at the first paused run.
|
|
169
|
+
"""
|
|
170
|
+
|
|
171
|
+
def __init__(self, dsn: str) -> None:
|
|
172
|
+
self._dsn = dsn
|
|
173
|
+
self._lock = asyncio.Lock()
|
|
174
|
+
self._ready = False
|
|
175
|
+
|
|
176
|
+
async def claim(self, *, nonce: str, expires_at: int, now: int) -> bool:
|
|
177
|
+
async with self._lock:
|
|
178
|
+
return await asyncio.to_thread(self._claim, nonce, expires_at, now)
|
|
179
|
+
|
|
180
|
+
def _claim(self, nonce: str, expires_at: int, now: int) -> bool:
|
|
181
|
+
psycopg = _load_psycopg()
|
|
182
|
+
with psycopg.connect(self._dsn) as connection:
|
|
183
|
+
if not self._ready:
|
|
184
|
+
connection.execute(
|
|
185
|
+
"CREATE TABLE IF NOT EXISTS checkpoint_nonce ("
|
|
186
|
+
"nonce TEXT PRIMARY KEY, expires_at BIGINT NOT NULL)"
|
|
187
|
+
)
|
|
188
|
+
self._ready = True
|
|
189
|
+
connection.execute("DELETE FROM checkpoint_nonce WHERE expires_at <= %s", (now,))
|
|
190
|
+
row = connection.execute(
|
|
191
|
+
"INSERT INTO checkpoint_nonce (nonce, expires_at) VALUES (%s, %s) "
|
|
192
|
+
"ON CONFLICT (nonce) DO NOTHING RETURNING nonce",
|
|
193
|
+
(nonce, expires_at),
|
|
194
|
+
).fetchone()
|
|
195
|
+
return row is not None
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _load_psycopg() -> Any:
|
|
199
|
+
"""Import the optional driver, or explain how to install it."""
|
|
200
|
+
try:
|
|
201
|
+
import psycopg
|
|
202
|
+
except ImportError as error:
|
|
203
|
+
raise ConfigurationError(
|
|
204
|
+
"a `state: postgres` declaration needs its driver for replay protection; "
|
|
205
|
+
"install it with `pip install aid-runtime-python[pgvector]` (the default "
|
|
206
|
+
"install omits psycopg)"
|
|
207
|
+
) from error
|
|
208
|
+
return psycopg
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def checkpoint_payload(checkpoint: AgentCheckpoint) -> bytes:
|
|
212
|
+
"""The canonical bytes a signature covers.
|
|
213
|
+
|
|
214
|
+
Everything except the signature itself. That includes the integrity block's own
|
|
215
|
+
``issued_at``, ``expires_at`` and ``nonce``: leaving those out would let a holder
|
|
216
|
+
move their deadline forward, and would let them swap the nonce of an already-spent
|
|
217
|
+
checkpoint to walk past replay protection. The pending calls, the approval channel
|
|
218
|
+
and the nested ``caller`` frames are inside too, so one signature binds all of them.
|
|
219
|
+
Sorted keys and no separator padding make the encoding reproducible in a second
|
|
220
|
+
process, which a signature requires.
|
|
221
|
+
"""
|
|
222
|
+
document = checkpoint.model_dump(mode="json", exclude={"integrity": {"signature"}})
|
|
223
|
+
return json.dumps(
|
|
224
|
+
document,
|
|
225
|
+
sort_keys=True,
|
|
226
|
+
separators=(",", ":"),
|
|
227
|
+
ensure_ascii=False,
|
|
228
|
+
default=str,
|
|
229
|
+
).encode("utf-8")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
@dataclass(frozen=True, slots=True)
|
|
233
|
+
class CheckpointSigner:
|
|
234
|
+
"""HMAC-SHA256 over :func:`checkpoint_payload`, plus the expiry it records.
|
|
235
|
+
|
|
236
|
+
``secret`` is read from the environment by the caller; it is never a spec value. The
|
|
237
|
+
dataclass is frozen and holds no mutable state, so one instance can be shared across
|
|
238
|
+
requests and a test can construct its own without touching the process environment.
|
|
239
|
+
"""
|
|
240
|
+
|
|
241
|
+
secret: str = field(repr=False)
|
|
242
|
+
ttl_seconds: int = DEFAULT_CHECKPOINT_TTL_MINUTES * 60
|
|
243
|
+
|
|
244
|
+
def __post_init__(self) -> None:
|
|
245
|
+
if not self.secret:
|
|
246
|
+
raise ValueError(
|
|
247
|
+
"CheckpointSigner needs a non-empty secret; an empty key would sign "
|
|
248
|
+
"every checkpoint identically"
|
|
249
|
+
)
|
|
250
|
+
if self.ttl_seconds <= 0:
|
|
251
|
+
raise ValueError("CheckpointSigner needs a positive ttl_seconds")
|
|
252
|
+
|
|
253
|
+
def _mac(self, payload: bytes) -> str:
|
|
254
|
+
return hmac.new(self.secret.encode("utf-8"), payload, hashlib.sha256).hexdigest()
|
|
255
|
+
|
|
256
|
+
def _digest(self, checkpoint: AgentCheckpoint) -> str:
|
|
257
|
+
"""The MAC of ``checkpoint`` excluding only the signature field.
|
|
258
|
+
|
|
259
|
+
Signing and verifying both go through here, so the two sides cannot drift into
|
|
260
|
+
covering different bytes: a signature that verifies against a payload it was not
|
|
261
|
+
computed over would accept an edited checkpoint.
|
|
262
|
+
"""
|
|
263
|
+
return self._mac(checkpoint_payload(checkpoint))
|
|
264
|
+
|
|
265
|
+
def sign(
|
|
266
|
+
self,
|
|
267
|
+
checkpoint: AgentCheckpoint,
|
|
268
|
+
*,
|
|
269
|
+
now: int | None = None,
|
|
270
|
+
nonce: str | None = None,
|
|
271
|
+
) -> AgentCheckpoint:
|
|
272
|
+
"""Return a copy of ``checkpoint`` carrying a fresh integrity block.
|
|
273
|
+
|
|
274
|
+
``now`` and ``nonce`` exist for tests; production passes neither. The return is a
|
|
275
|
+
new frozen model, so a caller that kept the unsigned value still has it.
|
|
276
|
+
"""
|
|
277
|
+
issued_at = int(time.time()) if now is None else int(now)
|
|
278
|
+
integrity = CheckpointIntegrity(
|
|
279
|
+
issued_at=issued_at,
|
|
280
|
+
expires_at=issued_at + self.ttl_seconds,
|
|
281
|
+
nonce=secrets.token_urlsafe(24) if nonce is None else nonce,
|
|
282
|
+
signature="",
|
|
283
|
+
)
|
|
284
|
+
unsigned = checkpoint.model_copy(update={"integrity": integrity})
|
|
285
|
+
signature = self._digest(unsigned)
|
|
286
|
+
return checkpoint.model_copy(
|
|
287
|
+
update={"integrity": integrity.model_copy(update={"signature": signature})}
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
def verify(self, checkpoint: AgentCheckpoint, *, now: int | None = None) -> CheckpointIntegrity:
|
|
291
|
+
"""Check signature and expiry. Returns the integrity block, or raises.
|
|
292
|
+
|
|
293
|
+
Replay is *not* checked here: it needs the store, and therefore an ``await``.
|
|
294
|
+
:meth:`accept` is the full check a request handler wants.
|
|
295
|
+
"""
|
|
296
|
+
integrity = checkpoint.integrity
|
|
297
|
+
if integrity is None:
|
|
298
|
+
raise CheckpointRefusalError(
|
|
299
|
+
"unsigned",
|
|
300
|
+
"this checkpoint carries no signature, so it was not issued by an app "
|
|
301
|
+
"built with checkpoint signing",
|
|
302
|
+
)
|
|
303
|
+
expected = self._digest(checkpoint)
|
|
304
|
+
if not hmac.compare_digest(expected, integrity.signature):
|
|
305
|
+
raise CheckpointRefusalError(
|
|
306
|
+
"tampered",
|
|
307
|
+
"this checkpoint's signature does not match its contents; it was edited "
|
|
308
|
+
"after it was issued",
|
|
309
|
+
)
|
|
310
|
+
moment = int(time.time()) if now is None else int(now)
|
|
311
|
+
if integrity.expires_at <= moment:
|
|
312
|
+
raise CheckpointRefusalError(
|
|
313
|
+
"expired",
|
|
314
|
+
f"this checkpoint expired at {integrity.expires_at}; a pause is valid for "
|
|
315
|
+
f"{self.ttl_seconds} seconds, so resume it sooner or start the run again",
|
|
316
|
+
)
|
|
317
|
+
return integrity
|
|
318
|
+
|
|
319
|
+
async def accept(
|
|
320
|
+
self,
|
|
321
|
+
checkpoint: AgentCheckpoint,
|
|
322
|
+
nonces: NonceStore,
|
|
323
|
+
*,
|
|
324
|
+
now: int | None = None,
|
|
325
|
+
) -> CheckpointIntegrity:
|
|
326
|
+
"""Signature, then expiry, then a one-time claim. Raises on any failure."""
|
|
327
|
+
moment = int(time.time()) if now is None else int(now)
|
|
328
|
+
integrity = self.verify(checkpoint, now=moment)
|
|
329
|
+
claimed = await nonces.claim(
|
|
330
|
+
nonce=integrity.nonce, expires_at=integrity.expires_at, now=moment
|
|
331
|
+
)
|
|
332
|
+
if not claimed:
|
|
333
|
+
raise CheckpointRefusalError(
|
|
334
|
+
"replayed",
|
|
335
|
+
"this checkpoint has already been spent; a resume is accepted once, so a "
|
|
336
|
+
"second presentation of the same checkpoint is refused",
|
|
337
|
+
)
|
|
338
|
+
return integrity
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def signer_from_env(
|
|
342
|
+
variable: str, *, ttl_seconds: int = DEFAULT_CHECKPOINT_TTL_MINUTES * 60
|
|
343
|
+
) -> CheckpointSigner:
|
|
344
|
+
"""Build a signer from ``os.environ[variable]``, naming the variable when it is unset."""
|
|
345
|
+
secret = os.environ.get(variable, "")
|
|
346
|
+
if not secret:
|
|
347
|
+
raise ConfigurationError(
|
|
348
|
+
f"{variable} is not set, but this app signs its checkpoints; set it to a "
|
|
349
|
+
"high-entropy secret before serving the resume route"
|
|
350
|
+
)
|
|
351
|
+
return CheckpointSigner(secret=secret, ttl_seconds=ttl_seconds)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def nonce_store_for(kind: str | None, location: str | None) -> NonceStore:
|
|
355
|
+
"""The most durable nonce store this build can offer for a declared ``state``.
|
|
356
|
+
|
|
357
|
+
Each declared kind claims the nonce where that declaration already points: ``sqlite``
|
|
358
|
+
names a file, ``postgres`` names a database. Both are durable across a restart and
|
|
359
|
+
across replicas. No declaration -- or a location that was not resolved from the
|
|
360
|
+
environment -- falls back to the in-process store, which ``ir/resume-replay-weak``
|
|
361
|
+
reports rather than this function hiding.
|
|
362
|
+
"""
|
|
363
|
+
if location:
|
|
364
|
+
if kind == "sqlite":
|
|
365
|
+
return SqliteNonceStore(location)
|
|
366
|
+
if kind == "postgres":
|
|
367
|
+
return PostgresNonceStore(location)
|
|
368
|
+
return InProcessNonceStore()
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def nonce_store_from_env(kind: str | None, variable: str | None) -> NonceStore:
|
|
372
|
+
"""The store a generated app builds from the variable its ``state`` declaration names.
|
|
373
|
+
|
|
374
|
+
``nonce_store_for`` falls back to the in-process store when it is handed no location,
|
|
375
|
+
which is right for a library and wrong here: the document declared a durable store, and
|
|
376
|
+
silently claiming the nonce in one worker would withdraw the replay protection the
|
|
377
|
+
build gate promised. So an unresolvable variable is refused by name, the same way
|
|
378
|
+
:func:`signer_from_env` refuses an unset signing key.
|
|
379
|
+
|
|
380
|
+
``kind`` of ``None`` means the document declared no store at all -- ``standard`` with a
|
|
381
|
+
warning from ``ir/resume-replay-weak`` -- and then the in-process store is exactly what
|
|
382
|
+
was declared, so it is returned rather than refused.
|
|
383
|
+
"""
|
|
384
|
+
if kind is None:
|
|
385
|
+
return InProcessNonceStore()
|
|
386
|
+
if variable is None:
|
|
387
|
+
raise ConfigurationError(
|
|
388
|
+
f"this app's state kind is {kind!r} but no urlEnv names where it lives; "
|
|
389
|
+
"declare state.urlEnv so a spent checkpoint can be claimed durably"
|
|
390
|
+
)
|
|
391
|
+
location = os.environ.get(variable, "")
|
|
392
|
+
if not location:
|
|
393
|
+
raise ConfigurationError(
|
|
394
|
+
f"{variable} is not set, but this app declares a {kind} state store; set it to "
|
|
395
|
+
"the connection string or file path, so a spent checkpoint is refused there "
|
|
396
|
+
"rather than only in the process that issued it"
|
|
397
|
+
)
|
|
398
|
+
return nonce_store_for(kind, location)
|
aid_runtime/agents/state.py
CHANGED
|
@@ -27,6 +27,7 @@ from aid_runtime.types import Message, ToolCall
|
|
|
27
27
|
|
|
28
28
|
__all__ = [
|
|
29
29
|
"AgentCheckpoint",
|
|
30
|
+
"CheckpointIntegrity",
|
|
30
31
|
"HumanDecision",
|
|
31
32
|
"PendingApproval",
|
|
32
33
|
"RunResult",
|
|
@@ -87,6 +88,25 @@ class HumanDecision(StrEnum):
|
|
|
87
88
|
REJECT = "reject"
|
|
88
89
|
|
|
89
90
|
|
|
91
|
+
class CheckpointIntegrity(BaseModel):
|
|
92
|
+
"""What makes a checkpoint something this app issued rather than something it parsed.
|
|
93
|
+
|
|
94
|
+
Every field sits inside the signed payload, so ``expires_at`` cannot be extended
|
|
95
|
+
without breaking the signature and ``nonce`` cannot be swapped to replay a spent
|
|
96
|
+
checkpoint under a fresh identity. The signature itself does not cover itself.
|
|
97
|
+
|
|
98
|
+
Absent on a runtime built without a signer (a library embedding the loop directly);
|
|
99
|
+
the generated app always passes one, so an HTTP checkpoint is never unsigned.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
103
|
+
|
|
104
|
+
issued_at: int = Field(ge=0)
|
|
105
|
+
expires_at: int = Field(ge=0)
|
|
106
|
+
nonce: str = Field(min_length=1)
|
|
107
|
+
signature: str = ""
|
|
108
|
+
|
|
109
|
+
|
|
90
110
|
class AgentCheckpoint(BaseModel):
|
|
91
111
|
"""Everything a paused agent needs to continue, and nothing that is derived."""
|
|
92
112
|
|
|
@@ -120,6 +140,10 @@ class AgentCheckpoint(BaseModel):
|
|
|
120
140
|
# answer to release on approval, a `tool-call` one holds `calls` to execute.
|
|
121
141
|
escalation: GuardrailEscalation | None = None
|
|
122
142
|
guardrails: tuple[GuardrailRecord, ...] = ()
|
|
143
|
+
# Set by the signer when the app was built with one. It is part of the model rather
|
|
144
|
+
# than a sibling value on the wire so a resumed request carries it in the same body a
|
|
145
|
+
# caller already holds, and so `extra: forbid` keeps rejecting anything else.
|
|
146
|
+
integrity: CheckpointIntegrity | None = None
|
|
123
147
|
|
|
124
148
|
|
|
125
149
|
class PendingApproval(BaseModel):
|
aid_runtime/evals/__init__.py
CHANGED
|
@@ -5,6 +5,7 @@ from __future__ import annotations
|
|
|
5
5
|
from aid_runtime.evals.agent_runner import AgentEvalRunner, ApprovalPolicy
|
|
6
6
|
from aid_runtime.evals.dataset import Dataset, EvalCase, require_reviewed
|
|
7
7
|
from aid_runtime.evals.gate import (
|
|
8
|
+
AggregateBaseline,
|
|
8
9
|
BaselineGate,
|
|
9
10
|
EvalBaseline,
|
|
10
11
|
EvalRun,
|
|
@@ -50,6 +51,7 @@ from aid_runtime.evals.trajectory import RunOutput, Trajectory
|
|
|
50
51
|
|
|
51
52
|
__all__ = [
|
|
52
53
|
"AgentEvalRunner",
|
|
54
|
+
"AggregateBaseline",
|
|
53
55
|
"ApprovalPolicy",
|
|
54
56
|
"ApprovalRespected",
|
|
55
57
|
"AssertMetric",
|
aid_runtime/evals/gate.py
CHANGED
|
@@ -96,6 +96,12 @@ class EvalRun(BaseModel):
|
|
|
96
96
|
dataset_version: str
|
|
97
97
|
runs: int = Field(gt=0)
|
|
98
98
|
metrics: tuple[MetricRun, ...] = Field(min_length=1)
|
|
99
|
+
#: Model spend per run, in the run's currency. Empty when the runner meters no cost,
|
|
100
|
+
#: which is a different answer from "every run spent zero": a promotion ceiling cannot
|
|
101
|
+
#: be judged against a runner that never measured anything.
|
|
102
|
+
cost_usd: tuple[float, ...] = ()
|
|
103
|
+
#: Wall-clock time of each run's model calls, in milliseconds, excluding scoring.
|
|
104
|
+
latency_ms: tuple[float, ...] = ()
|
|
99
105
|
|
|
100
106
|
def means(self) -> dict[str, float]:
|
|
101
107
|
return {entry.metric: statistics.fmean(entry.values) for entry in self.metrics}
|
|
@@ -142,6 +148,29 @@ class MetricBaseline(BaseModel):
|
|
|
142
148
|
)
|
|
143
149
|
|
|
144
150
|
|
|
151
|
+
class AggregateBaseline(BaseModel):
|
|
152
|
+
"""A recorded mean and spread over runs, in the unit of whatever holds it.
|
|
153
|
+
|
|
154
|
+
``mean`` is bounded below only. A metric's baseline is a pass rate and fits in
|
|
155
|
+
``[0, 1]``, but a spend average is a currency figure and a duration is milliseconds,
|
|
156
|
+
so the unit lives in the field name that refers to this record
|
|
157
|
+
(``EvalBaseline.cost``, ``EvalBaseline.latency``) and not in the bound.
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
161
|
+
|
|
162
|
+
runs: int = Field(gt=0)
|
|
163
|
+
mean: float = Field(ge=0.0)
|
|
164
|
+
stdev: float = Field(ge=0.0)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _aggregate(values: Sequence[float]) -> AggregateBaseline | None:
|
|
168
|
+
"""The recorded mean and spread of ``values``, or ``None`` when none were measured."""
|
|
169
|
+
if not values:
|
|
170
|
+
return None
|
|
171
|
+
return AggregateBaseline(runs=len(values), mean=statistics.fmean(values), stdev=_stdev(values))
|
|
172
|
+
|
|
173
|
+
|
|
145
174
|
class EvalBaseline(BaseModel):
|
|
146
175
|
"""A committed baseline: the accepted distribution for a dataset and model."""
|
|
147
176
|
|
|
@@ -152,6 +181,14 @@ class EvalBaseline(BaseModel):
|
|
|
152
181
|
model: str
|
|
153
182
|
metrics: tuple[MetricBaseline, ...] = Field(min_length=1)
|
|
154
183
|
note: str = ""
|
|
184
|
+
#: Recorded model spend per run, when the run that produced this baseline metered it.
|
|
185
|
+
#: Absent on a baseline recorded before spend was measured, and on one recorded from a
|
|
186
|
+
#: runner that meters nothing -- a scripted model in CI, for instance. ``aid eval
|
|
187
|
+
#: --compare`` refuses to judge ``allowedCostIncrease`` against either, rather than
|
|
188
|
+
#: read "not measured" as "no increase".
|
|
189
|
+
cost: AggregateBaseline | None = None
|
|
190
|
+
#: Recorded wall-clock time per run, in milliseconds, on the same terms as ``cost``.
|
|
191
|
+
latency: AggregateBaseline | None = None
|
|
155
192
|
|
|
156
193
|
@classmethod
|
|
157
194
|
def from_run(cls, run: EvalRun, *, model: str, note: str = "") -> EvalBaseline:
|
|
@@ -163,6 +200,8 @@ class EvalBaseline(BaseModel):
|
|
|
163
200
|
MetricBaseline.from_values(entry.metric, entry.values) for entry in run.metrics
|
|
164
201
|
),
|
|
165
202
|
note=note,
|
|
203
|
+
cost=_aggregate(run.cost_usd),
|
|
204
|
+
latency=_aggregate(run.latency_ms),
|
|
166
205
|
)
|
|
167
206
|
|
|
168
207
|
def metric(self, name: str) -> MetricBaseline:
|
|
@@ -180,7 +219,9 @@ class EvalBaseline(BaseModel):
|
|
|
180
219
|
return cls.from_json(Path(path).read_text(encoding="utf-8"))
|
|
181
220
|
|
|
182
221
|
def to_json(self) -> str:
|
|
183
|
-
|
|
222
|
+
# ``exclude_none`` keeps a baseline that recorded no spend byte-identical to what
|
|
223
|
+
# this method wrote before cost and latency were recorded at all.
|
|
224
|
+
return self.model_dump_json(indent=2, exclude_none=True) + "\n"
|
|
184
225
|
|
|
185
226
|
|
|
186
227
|
class Threshold(BaseModel):
|
aid_runtime/evals/runner.py
CHANGED
|
@@ -69,6 +69,12 @@ class DatasetRun(BaseModel):
|
|
|
69
69
|
dataset: str
|
|
70
70
|
dataset_version: str
|
|
71
71
|
outcomes: tuple[CaseOutcome, ...] = Field(min_length=1)
|
|
72
|
+
#: Model spend for this pass, in the run's currency, or ``None`` when the runner meters
|
|
73
|
+
#: nothing. ``None`` and ``0.0`` are different answers: only one of them can be compared
|
|
74
|
+
#: against a recorded baseline.
|
|
75
|
+
cost_usd: float | None = None
|
|
76
|
+
#: Wall-clock time of this pass's model calls, in milliseconds, excluding scoring.
|
|
77
|
+
latency_ms: float | None = None
|
|
72
78
|
|
|
73
79
|
def means(self) -> dict[str, float]:
|
|
74
80
|
"""Mean score per metric across the cases of this pass."""
|
|
@@ -202,6 +208,9 @@ async def evaluate_once(
|
|
|
202
208
|
raise ValueError("at least one metric is required")
|
|
203
209
|
label = dataset.name if eval_id is None else eval_id
|
|
204
210
|
outcomes: list[CaseOutcome] = []
|
|
211
|
+
spent = 0.0
|
|
212
|
+
elapsed = 0.0
|
|
213
|
+
metered = True
|
|
205
214
|
for case in dataset.cases:
|
|
206
215
|
cost_before = _runner_cost(runner)
|
|
207
216
|
started = perf_counter()
|
|
@@ -213,8 +222,9 @@ async def evaluate_once(
|
|
|
213
222
|
latency_ms = (perf_counter() - started) * 1000.0
|
|
214
223
|
# Metrics see the pipeline's own spend, measured before scoring, because "what did
|
|
215
224
|
# this task cost" is a property of the product and not of the harness auditing it.
|
|
225
|
+
case_cost = _spent_since(runner, cost_before)
|
|
216
226
|
context = RunContext(
|
|
217
|
-
cost_usd=
|
|
227
|
+
cost_usd=case_cost,
|
|
218
228
|
latency_ms=latency_ms,
|
|
219
229
|
metered=cost_before is not None,
|
|
220
230
|
trajectory=trajectory,
|
|
@@ -230,6 +240,11 @@ async def evaluate_once(
|
|
|
230
240
|
trajectory=trajectory,
|
|
231
241
|
)
|
|
232
242
|
)
|
|
243
|
+
# The pass total is the same pre-scoring figure the metrics saw, so a recorded
|
|
244
|
+
# baseline describes the product rather than the harness that audited it.
|
|
245
|
+
spent += case_cost
|
|
246
|
+
elapsed += latency_ms
|
|
247
|
+
metered = metered and cost_before is not None
|
|
233
248
|
# The published series is read after scoring, because a model-backed metric spends
|
|
234
249
|
# money too and a cost series that ignored the judge would report half the run.
|
|
235
250
|
record_eval_case(
|
|
@@ -238,7 +253,11 @@ async def evaluate_once(
|
|
|
238
253
|
latency_ms=latency_ms,
|
|
239
254
|
)
|
|
240
255
|
return DatasetRun(
|
|
241
|
-
dataset=dataset.name,
|
|
256
|
+
dataset=dataset.name,
|
|
257
|
+
dataset_version=dataset.version,
|
|
258
|
+
outcomes=tuple(outcomes),
|
|
259
|
+
cost_usd=spent if metered else None,
|
|
260
|
+
latency_ms=elapsed,
|
|
242
261
|
)
|
|
243
262
|
|
|
244
263
|
|
|
@@ -291,11 +310,19 @@ async def run_evaluation(
|
|
|
291
310
|
raise ValueError("at least one metric is required")
|
|
292
311
|
|
|
293
312
|
collected: dict[str, list[float]] = {metric.name: [] for metric in metrics}
|
|
313
|
+
costs: list[float] = []
|
|
314
|
+
latencies: list[float] = []
|
|
294
315
|
for _ in range(runs):
|
|
295
316
|
pass_result = await evaluate_once(dataset, runner, metrics, eval_id=eval_id)
|
|
296
317
|
means = pass_result.means()
|
|
297
318
|
for metric in metrics:
|
|
298
319
|
collected[metric.name].append(means[metric.name])
|
|
320
|
+
# A pass that metered nothing contributes no spend figure, so a run built from
|
|
321
|
+
# unmetered passes carries an empty tuple and a baseline recorded from it says so.
|
|
322
|
+
if pass_result.cost_usd is not None:
|
|
323
|
+
costs.append(pass_result.cost_usd)
|
|
324
|
+
if pass_result.latency_ms is not None:
|
|
325
|
+
latencies.append(pass_result.latency_ms)
|
|
299
326
|
|
|
300
327
|
return EvalRun(
|
|
301
328
|
dataset=dataset.name,
|
|
@@ -305,4 +332,6 @@ async def run_evaluation(
|
|
|
305
332
|
MetricRun(metric=metric.name, values=tuple(collected[metric.name]))
|
|
306
333
|
for metric in metrics
|
|
307
334
|
),
|
|
335
|
+
cost_usd=tuple(costs),
|
|
336
|
+
latency_ms=tuple(latencies),
|
|
308
337
|
)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: aid-runtime-python
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.163
|
|
4
4
|
Summary: The AID Framework Python runtime: model gateway with pinning and cost budgets, prompt registry, tool executor, OTel GenAI tracing, plain-async pipeline, and an eval harness that gates on statistical regression against a stored baseline.
|
|
5
5
|
Author: The AID Framework authors
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
aid_runtime/__init__.py,sha256=
|
|
1
|
+
aid_runtime/__init__.py,sha256=aq8poIy2LFueKsPEbAN84Bi3Z2oETd3b_kvauiwj_Jo,15187
|
|
2
2
|
aid_runtime/cache.py,sha256=jhw_EBd9dfWEUzYeibOvIkVBqqiLUjqF5WKEPz9GkhE,6836
|
|
3
3
|
aid_runtime/concurrency.py,sha256=z0tFQHw35ttFLKfazGBjCMPOLQOnUotE_OPpvR1piH4,2829
|
|
4
4
|
aid_runtime/control.py,sha256=y6wPn0fqYJv0nVSsjzpzfiaq1Y7zBoMxCpdrEuqkfvg,17529
|
|
@@ -18,24 +18,25 @@ aid_runtime/telemetry.py,sha256=ykAXCL3XFi0yok3xr-fjD3oGvVycdfyrqJ8nGKC_ZHc,1287
|
|
|
18
18
|
aid_runtime/tools.py,sha256=7LeaPI5aJioNe3vexUv94tvIRpOwxj1Ujt723qvO3UI,9906
|
|
19
19
|
aid_runtime/tracing.py,sha256=zGZi7faB87IRv5873B-sV2d3J_JGiQS4pbHFqjTElUs,12247
|
|
20
20
|
aid_runtime/types.py,sha256=91hwvBkjTkvCJ-WdQO3ezZZCyqzXmS7Ns1WP1m0EQzc,10916
|
|
21
|
-
aid_runtime/agents/__init__.py,sha256=
|
|
21
|
+
aid_runtime/agents/__init__.py,sha256=rf3k0hxHDO60S1TrON6d2-rTv1N8V4WvF47xsJ5bhE0,3709
|
|
22
22
|
aid_runtime/agents/chat_model.py,sha256=fZdCmSpoECuBVGZE1s8NmT2erT33RhDuLh3yJM6kAJE,14808
|
|
23
23
|
aid_runtime/agents/deep_agents.py,sha256=Eg_BLm2cg7T_tXSxR7ag8SEvTMCFBLHoIvln3BoWORw,26966
|
|
24
24
|
aid_runtime/agents/engine.py,sha256=3cXCYY806URDblYD500cfw7873IoVCy8BH1d4h2YAsc,5789
|
|
25
25
|
aid_runtime/agents/guardrails.py,sha256=0HhbToZBxPZHEDRLyD9BGS_jmV-TkKPGEhRynYxLXx8,32813
|
|
26
26
|
aid_runtime/agents/ir.py,sha256=MgqX5gEkq7vimXojtSNb5MuVeTIZaWkZCFitxAqSAe0,32855
|
|
27
|
-
aid_runtime/agents/loop.py,sha256=
|
|
27
|
+
aid_runtime/agents/loop.py,sha256=gTfFRcRuGuyZpNdw2PK168A9Cp6LHBLJMUpHUxXPTnE,55952
|
|
28
28
|
aid_runtime/agents/managed.py,sha256=SFyx6Rca2aoiMzA9q6B4Nfes6ZCjn_5_zN0SxzemIII,23247
|
|
29
29
|
aid_runtime/agents/memory.py,sha256=6_D6k2bzAiR2euNvzr6HB28wsUUq-R-WTQc12gkB8ao,9156
|
|
30
30
|
aid_runtime/agents/policy.py,sha256=ael0EW_hWfLu95rbqFMrR4WyqAPtgiSNvNw97xnthdw,6122
|
|
31
|
-
aid_runtime/agents/
|
|
32
|
-
aid_runtime/
|
|
31
|
+
aid_runtime/agents/resume.py,sha256=VAjJja2ZvXLLSRgz9Z_2b5Cs9Af5Kevr5qjuDpslpuw,17035
|
|
32
|
+
aid_runtime/agents/state.py,sha256=feXZtQeD3vcKpNUPsCXby0J15UqkoD4_Gi-aT3Up8RI,7174
|
|
33
|
+
aid_runtime/evals/__init__.py,sha256=5_qUGwiKR2l4p-F8RZ9QnxzFOxtNj7DWoEsA8uNyHIs,1991
|
|
33
34
|
aid_runtime/evals/agent_runner.py,sha256=E1Vg48gNAeQzGGSyp0cK8H5mxGlVEPBq-FTaaTQ-CLE,12594
|
|
34
35
|
aid_runtime/evals/dataset.py,sha256=ZmTP-jWx9f2udYPyzvTtOuUse5Mp-uj5WNBPy-7aHKM,5946
|
|
35
|
-
aid_runtime/evals/gate.py,sha256=
|
|
36
|
+
aid_runtime/evals/gate.py,sha256=uYUOw57MaGqSOsMvbB0C6MrjW4IbUJ57izyD6FSxkxw,17676
|
|
36
37
|
aid_runtime/evals/metrics.py,sha256=LvzKgW-7CNxcB0MmDXakDnwdgyzjpH8ceHq7mdi8mw4,28541
|
|
37
38
|
aid_runtime/evals/predicate.py,sha256=JaeN1LJFpliI4JHYdFPtXfjH5_Aad-2-U3ZC6_hManE,8726
|
|
38
|
-
aid_runtime/evals/runner.py,sha256=
|
|
39
|
+
aid_runtime/evals/runner.py,sha256=rI5AScHDPnwN5Ohw0I7zR2Df9pGSTE8Un6-lESCSV3g,12827
|
|
39
40
|
aid_runtime/evals/trajectory.py,sha256=X7ssDigfFuMkjM6mR6LGSbb03A8iNf4oRbVqeSsU7Ww,4444
|
|
40
41
|
aid_runtime/providers/__init__.py,sha256=5XMe1kPqckeyv2l_FrfYEiTPWOTGsPKpWtiiTdSn3ic,2284
|
|
41
42
|
aid_runtime/providers/anthropic.py,sha256=xh_fJyujnFRcknEHFRxA5M-izeR2hJtit-865RrISOQ,15853
|
|
@@ -62,7 +63,7 @@ aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJ
|
|
|
62
63
|
aid_runtime/retrieval/retriever.py,sha256=0Cx-_6Qcf2TRolFy4ktMseyyyr-WLphMYYHane0t9lA,24412
|
|
63
64
|
aid_runtime/retrieval/stores.py,sha256=mG261rUHZIzB7niiTj_DuUzcNMOd4QYENk5ArgI1iBo,6840
|
|
64
65
|
aid_runtime/retrieval/types.py,sha256=hJ5IRSD-PTfrc1xhuK6CBdX0Yr-S6L_JeSMPity8ecM,20447
|
|
65
|
-
aid_runtime_python-0.1.
|
|
66
|
-
aid_runtime_python-0.1.
|
|
67
|
-
aid_runtime_python-0.1.
|
|
68
|
-
aid_runtime_python-0.1.
|
|
66
|
+
aid_runtime_python-0.1.163.dist-info/METADATA,sha256=XBOwwaxOR6fnCKOlGWFeUYukKzWGBsttWdLvtLCG9Vw,17163
|
|
67
|
+
aid_runtime_python-0.1.163.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
68
|
+
aid_runtime_python-0.1.163.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
|
|
69
|
+
aid_runtime_python-0.1.163.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|