driftcatch 0.1.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.
- driftcatch/__init__.py +146 -0
- driftcatch/_name.py +12 -0
- driftcatch/agentio.py +246 -0
- driftcatch/bisect.py +160 -0
- driftcatch/cli.py +1035 -0
- driftcatch/config.py +166 -0
- driftcatch/contracts.py +508 -0
- driftcatch/coverage.py +165 -0
- driftcatch/determinism.py +282 -0
- driftcatch/errors.py +149 -0
- driftcatch/intercept/__init__.py +8 -0
- driftcatch/intercept/http.py +400 -0
- driftcatch/intercept/tools.py +187 -0
- driftcatch/invariants.py +646 -0
- driftcatch/match/__init__.py +60 -0
- driftcatch/match/base.py +161 -0
- driftcatch/match/keys.py +61 -0
- driftcatch/match/normalizers.py +130 -0
- driftcatch/match/registry.py +82 -0
- driftcatch/match/resolve.py +195 -0
- driftcatch/match/strategies.py +146 -0
- driftcatch/mcp_server.py +417 -0
- driftcatch/providers.py +227 -0
- driftcatch/py.typed +0 -0
- driftcatch/pytest_plugin.py +170 -0
- driftcatch/record.py +162 -0
- driftcatch/recording/__init__.py +57 -0
- driftcatch/recording/fingerprint.py +75 -0
- driftcatch/recording/io.py +257 -0
- driftcatch/recording/schema.py +261 -0
- driftcatch/redact.py +127 -0
- driftcatch/replay.py +152 -0
- driftcatch/review.py +102 -0
- driftcatch/session.py +126 -0
- driftcatch/suite.py +135 -0
- driftcatch/take.py +632 -0
- driftcatch/trajectory.py +208 -0
- driftcatch/ui/__init__.py +15 -0
- driftcatch/ui/server.py +245 -0
- driftcatch/ui/templates/app.html +346 -0
- driftcatch/whatif.py +65 -0
- driftcatch-0.1.0.dist-info/METADATA +456 -0
- driftcatch-0.1.0.dist-info/RECORD +46 -0
- driftcatch-0.1.0.dist-info/WHEEL +4 -0
- driftcatch-0.1.0.dist-info/entry_points.txt +5 -0
- driftcatch-0.1.0.dist-info/licenses/LICENSE +21 -0
driftcatch/coverage.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Behaviour coverage.
|
|
2
|
+
|
|
3
|
+
Code coverage reports which *lines* ran. Nothing reports which agent
|
|
4
|
+
*behaviours* were ever tested, which is why teams ship agents with whole
|
|
5
|
+
branches - the not-found case, the refund-failed case - never exercised once.
|
|
6
|
+
|
|
7
|
+
The denominator comes for free: every recorded model call declares the tools
|
|
8
|
+
available to the agent, so DriftCatch knows which behaviours *could* happen, not
|
|
9
|
+
merely which ones did.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from pydantic import BaseModel, Field
|
|
15
|
+
|
|
16
|
+
from driftcatch.recording.schema import LLMEvent, Outcome, Recording, ToolEvent
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"CoverageReport",
|
|
20
|
+
"PathCoverage",
|
|
21
|
+
"ToolCoverage",
|
|
22
|
+
"analyse",
|
|
23
|
+
"declared_tools",
|
|
24
|
+
"render",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ToolCoverage(BaseModel):
|
|
29
|
+
"""Coverage of one tool: was it called, and was its failure path tested?"""
|
|
30
|
+
|
|
31
|
+
name: str
|
|
32
|
+
calls: int = 0
|
|
33
|
+
covered: bool = False
|
|
34
|
+
error_path_covered: bool = False
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class PathCoverage(BaseModel):
|
|
38
|
+
"""One distinct decision path the agent has been observed taking."""
|
|
39
|
+
|
|
40
|
+
path: str
|
|
41
|
+
recordings: int = 0
|
|
42
|
+
terminal: Outcome | None = None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class CoverageReport(BaseModel):
|
|
46
|
+
percent: float = 0.0
|
|
47
|
+
covered_units: int = 0
|
|
48
|
+
total_units: int = 0
|
|
49
|
+
tools: dict[str, ToolCoverage] = Field(default_factory=dict)
|
|
50
|
+
paths: list[PathCoverage] = Field(default_factory=list)
|
|
51
|
+
uncovered: list[str] = Field(default_factory=list)
|
|
52
|
+
recordings_analysed: int = 0
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def passing(self) -> bool:
|
|
56
|
+
return self.total_units > 0 and self.covered_units == self.total_units
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def declared_tools(recordings: list[Recording]) -> list[str]:
|
|
60
|
+
"""Every tool the agent was offered, across all recordings."""
|
|
61
|
+
names: set[str] = set()
|
|
62
|
+
for recording in recordings:
|
|
63
|
+
for event in recording.events:
|
|
64
|
+
if isinstance(event, LLMEvent):
|
|
65
|
+
for tool in event.request.tools:
|
|
66
|
+
name = tool.get("name")
|
|
67
|
+
if name:
|
|
68
|
+
names.add(str(name))
|
|
69
|
+
elif isinstance(event, ToolEvent):
|
|
70
|
+
names.add(event.name)
|
|
71
|
+
return sorted(names)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def analyse(recordings: list[Recording], known_tools: list[str] | None = None) -> CoverageReport:
|
|
75
|
+
"""Compute behaviour coverage across a corpus of recordings.
|
|
76
|
+
|
|
77
|
+
Each tool contributes two units of behaviour: its success path and its
|
|
78
|
+
failure path. Counting the failure path separately is the point - an agent
|
|
79
|
+
whose tools have never failed in testing is an agent whose error handling
|
|
80
|
+
has never run.
|
|
81
|
+
"""
|
|
82
|
+
tools = known_tools if known_tools is not None else declared_tools(recordings)
|
|
83
|
+
report = CoverageReport(recordings_analysed=len(recordings))
|
|
84
|
+
report.tools = {name: ToolCoverage(name=name) for name in tools}
|
|
85
|
+
|
|
86
|
+
path_counts: dict[str, PathCoverage] = {}
|
|
87
|
+
|
|
88
|
+
for recording in recordings:
|
|
89
|
+
for event in recording.events:
|
|
90
|
+
if not isinstance(event, ToolEvent):
|
|
91
|
+
continue
|
|
92
|
+
entry = report.tools.setdefault(event.name, ToolCoverage(name=event.name))
|
|
93
|
+
entry.calls += 1
|
|
94
|
+
entry.covered = True
|
|
95
|
+
if event.outcome is Outcome.ERROR:
|
|
96
|
+
entry.error_path_covered = True
|
|
97
|
+
|
|
98
|
+
path = " -> ".join(recording.trajectory.tools_called) or "(no tools)"
|
|
99
|
+
existing = path_counts.get(path)
|
|
100
|
+
if existing is None:
|
|
101
|
+
path_counts[path] = PathCoverage(
|
|
102
|
+
path=path, recordings=1, terminal=recording.trajectory.terminal
|
|
103
|
+
)
|
|
104
|
+
else:
|
|
105
|
+
existing.recordings += 1
|
|
106
|
+
|
|
107
|
+
report.paths = sorted(path_counts.values(), key=lambda p: (-p.recordings, p.path))
|
|
108
|
+
|
|
109
|
+
report.total_units = len(report.tools) * 2
|
|
110
|
+
report.covered_units = sum(
|
|
111
|
+
int(tool.covered) + int(tool.error_path_covered) for tool in report.tools.values()
|
|
112
|
+
)
|
|
113
|
+
report.percent = (
|
|
114
|
+
round(100 * report.covered_units / report.total_units, 1) if report.total_units else 0.0
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
uncovered: list[str] = []
|
|
118
|
+
for tool in report.tools.values():
|
|
119
|
+
if not tool.covered:
|
|
120
|
+
uncovered.append(f"{tool.name} (never called)")
|
|
121
|
+
elif not tool.error_path_covered:
|
|
122
|
+
uncovered.append(f"{tool.name} error path")
|
|
123
|
+
report.uncovered = uncovered
|
|
124
|
+
|
|
125
|
+
return report
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _bar(percent: float, width: int = 20) -> str:
|
|
129
|
+
filled = int(round(percent / 100 * width))
|
|
130
|
+
return "#" * filled + "." * (width - filled)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def render(report: CoverageReport) -> str:
|
|
134
|
+
"""The report users will screenshot. Make the gaps impossible to miss."""
|
|
135
|
+
lines = [
|
|
136
|
+
f" BEHAVIOUR COVERAGE {report.percent:>5.1f}% {_bar(report.percent)}",
|
|
137
|
+
f" {report.covered_units}/{report.total_units} behaviour units across "
|
|
138
|
+
f"{report.recordings_analysed} recording(s)",
|
|
139
|
+
"",
|
|
140
|
+
f" {'TOOL':<24}{'CALLED':>8}{'CALLS':>7}{'ERROR PATH':>13}",
|
|
141
|
+
f" {'-' * 52}",
|
|
142
|
+
]
|
|
143
|
+
for name in sorted(report.tools):
|
|
144
|
+
tool = report.tools[name]
|
|
145
|
+
lines.append(
|
|
146
|
+
f" {name:<24}{('yes' if tool.covered else 'NO'):>8}{tool.calls:>7}"
|
|
147
|
+
f"{('yes' if tool.error_path_covered else 'NO'):>13}"
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
if report.paths:
|
|
151
|
+
lines.extend(["", " DECISION PATHS"])
|
|
152
|
+
for path in report.paths:
|
|
153
|
+
lines.append(f" {path.recordings:>3}x {path.path}")
|
|
154
|
+
|
|
155
|
+
if report.uncovered:
|
|
156
|
+
lines.extend(["", f" {len(report.uncovered)} behaviour(s) with no coverage:"])
|
|
157
|
+
for item in report.uncovered:
|
|
158
|
+
lines.append(f" - {item}")
|
|
159
|
+
lines.append("")
|
|
160
|
+
lines.append(" Close a gap without re-recording:")
|
|
161
|
+
lines.append(" drift what-if <recording> --fail-tool <tool>")
|
|
162
|
+
else:
|
|
163
|
+
lines.extend(["", " every declared behaviour has coverage"])
|
|
164
|
+
|
|
165
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
"""Determinism measurement and the Tier 2 live behaviour check.
|
|
2
|
+
|
|
3
|
+
Replay cannot tell you what the model would decide today, because the model
|
|
4
|
+
isn't running. Only a live run can. That costs money and is genuinely
|
|
5
|
+
non-deterministic, so it is deliberate, guarded, and thresholded rather than
|
|
6
|
+
exact - and it reports *how* non-deterministic the agent is, so you know which
|
|
7
|
+
tests are safe to gate on.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import functools
|
|
13
|
+
import math
|
|
14
|
+
import os
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from typing import Any, TypeVar, cast
|
|
17
|
+
|
|
18
|
+
from pydantic import BaseModel, Field
|
|
19
|
+
|
|
20
|
+
from driftcatch._name import ENV_PREFIX
|
|
21
|
+
from driftcatch.config import Config, get_config
|
|
22
|
+
from driftcatch.errors import DriftCatchError
|
|
23
|
+
from driftcatch.recording.io import load_recording, recording_path
|
|
24
|
+
from driftcatch.recording.schema import Recording, Trajectory
|
|
25
|
+
from driftcatch.trajectory import diff as trajectory_diff
|
|
26
|
+
from driftcatch.trajectory import render as render_diff
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"DeterminismReport",
|
|
30
|
+
"LiveResult",
|
|
31
|
+
"TrajectoryGroup",
|
|
32
|
+
"analyse",
|
|
33
|
+
"live_allowed",
|
|
34
|
+
"live_check",
|
|
35
|
+
"render",
|
|
36
|
+
"run_live",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# ------------------------------------------------------------------ guard
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def live_allowed() -> bool:
|
|
46
|
+
"""Live runs spend real money, so they never happen by accident."""
|
|
47
|
+
if os.environ.get(f"{ENV_PREFIX}_ALLOW_LIVE") == "1":
|
|
48
|
+
return True
|
|
49
|
+
in_ci = any(os.environ.get(name) for name in ("CI", "GITHUB_ACTIONS", "GITLAB_CI"))
|
|
50
|
+
return not in_ci
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _require_live() -> None:
|
|
54
|
+
if not live_allowed():
|
|
55
|
+
raise DriftCatchError(
|
|
56
|
+
"live behaviour checks make real API calls and are disabled here. "
|
|
57
|
+
f"Set {ENV_PREFIX}_ALLOW_LIVE=1 to permit them."
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# ------------------------------------------------------------- statistics
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class TrajectoryGroup(BaseModel):
|
|
65
|
+
"""One distinct behaviour observed across repeated live runs."""
|
|
66
|
+
|
|
67
|
+
path: str
|
|
68
|
+
count: int
|
|
69
|
+
share: float
|
|
70
|
+
matches_golden: bool = False
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class DeterminismReport(BaseModel):
|
|
74
|
+
runs: int = 0
|
|
75
|
+
distinct: int = 0
|
|
76
|
+
groups: list[TrajectoryGroup] = Field(default_factory=list)
|
|
77
|
+
score: float = 0.0
|
|
78
|
+
recommended_pass_k: tuple[int, int] | None = None
|
|
79
|
+
golden_share: float | None = None
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def is_deterministic(self) -> bool:
|
|
83
|
+
return self.distinct <= 1
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def analyse(trajectories: list[Trajectory], golden: Trajectory | None = None) -> DeterminismReport:
|
|
87
|
+
"""Group repeated runs by behaviour and score how stable the agent is."""
|
|
88
|
+
runs = len(trajectories)
|
|
89
|
+
if runs == 0:
|
|
90
|
+
return DeterminismReport()
|
|
91
|
+
|
|
92
|
+
counts: dict[str, int] = {}
|
|
93
|
+
for trajectory in trajectories:
|
|
94
|
+
path = " -> ".join(trajectory.tools_called) or "(no tools)"
|
|
95
|
+
counts[path] = counts.get(path, 0) + 1
|
|
96
|
+
|
|
97
|
+
golden_path = None
|
|
98
|
+
if golden is not None:
|
|
99
|
+
golden_path = " -> ".join(golden.tools_called) or "(no tools)"
|
|
100
|
+
|
|
101
|
+
groups = [
|
|
102
|
+
TrajectoryGroup(
|
|
103
|
+
path=path,
|
|
104
|
+
count=count,
|
|
105
|
+
share=round(count / runs, 4),
|
|
106
|
+
matches_golden=(path == golden_path),
|
|
107
|
+
)
|
|
108
|
+
for path, count in sorted(counts.items(), key=lambda item: (-item[1], item[0]))
|
|
109
|
+
]
|
|
110
|
+
|
|
111
|
+
top = groups[0].count
|
|
112
|
+
score = round(top / runs, 4)
|
|
113
|
+
# Recommend a gate the agent can actually pass today, never rounding up into
|
|
114
|
+
# a threshold that would make CI flaky.
|
|
115
|
+
recommended = (max(1, math.floor(score * runs)), runs)
|
|
116
|
+
|
|
117
|
+
golden_share = None
|
|
118
|
+
if golden_path is not None:
|
|
119
|
+
golden_share = round(counts.get(golden_path, 0) / runs, 4)
|
|
120
|
+
|
|
121
|
+
return DeterminismReport(
|
|
122
|
+
runs=runs,
|
|
123
|
+
distinct=len(groups),
|
|
124
|
+
groups=groups,
|
|
125
|
+
score=score,
|
|
126
|
+
recommended_pass_k=recommended,
|
|
127
|
+
golden_share=golden_share,
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def render(report: DeterminismReport) -> str:
|
|
132
|
+
if report.runs == 0:
|
|
133
|
+
return " no runs to analyse"
|
|
134
|
+
lines = [
|
|
135
|
+
f" {report.runs} live run(s) - {report.distinct} distinct trajectory(ies)",
|
|
136
|
+
"",
|
|
137
|
+
]
|
|
138
|
+
for group in report.groups:
|
|
139
|
+
marker = " <- golden" if group.matches_golden else ""
|
|
140
|
+
lines.append(f" {group.share * 100:>5.1f}% {group.path}{marker}")
|
|
141
|
+
lines.extend(
|
|
142
|
+
[
|
|
143
|
+
"",
|
|
144
|
+
f" DETERMINISM SCORE {report.score:.2f}",
|
|
145
|
+
]
|
|
146
|
+
)
|
|
147
|
+
if report.recommended_pass_k:
|
|
148
|
+
k, n = report.recommended_pass_k
|
|
149
|
+
lines.append(f" recommended gate: pass_k=({k}, {n})")
|
|
150
|
+
if report.golden_share is not None and report.golden_share < 1.0:
|
|
151
|
+
lines.append(
|
|
152
|
+
f" warning: only {report.golden_share * 100:.0f}% of runs matched the golden behaviour"
|
|
153
|
+
)
|
|
154
|
+
return "\n".join(lines)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# ------------------------------------------------------------- live runner
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class LiveResult:
|
|
161
|
+
"""Outcome of repeating a scenario against the real model."""
|
|
162
|
+
|
|
163
|
+
def __init__(
|
|
164
|
+
self,
|
|
165
|
+
name: str,
|
|
166
|
+
trajectories: list[Trajectory],
|
|
167
|
+
golden: Recording | None,
|
|
168
|
+
config: Config,
|
|
169
|
+
) -> None:
|
|
170
|
+
self.name = name
|
|
171
|
+
self.trajectories = trajectories
|
|
172
|
+
self.golden = golden
|
|
173
|
+
self.config = config
|
|
174
|
+
self.report = analyse(trajectories, golden.trajectory if golden else None)
|
|
175
|
+
|
|
176
|
+
def matches(self, tolerance: str | None = None) -> int:
|
|
177
|
+
"""How many runs matched the golden behaviour."""
|
|
178
|
+
if self.golden is None:
|
|
179
|
+
return 0
|
|
180
|
+
level = tolerance or self.config.default_tolerance
|
|
181
|
+
return sum(
|
|
182
|
+
1
|
|
183
|
+
for trajectory in self.trajectories
|
|
184
|
+
if trajectory_diff(self.golden.trajectory, trajectory, level).matched
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
def assert_matches_golden(
|
|
188
|
+
self,
|
|
189
|
+
*,
|
|
190
|
+
pass_k: tuple[int, int] | None = None,
|
|
191
|
+
tolerance: str | None = None,
|
|
192
|
+
) -> LiveResult:
|
|
193
|
+
"""Assert that enough runs reproduced the approved behaviour.
|
|
194
|
+
|
|
195
|
+
``pass_k=(8, 10)`` means at least 8 of 10 runs must match. Exact match
|
|
196
|
+
across live runs is not a goal; models are not deterministic and a test
|
|
197
|
+
that pretends otherwise is a flaky test.
|
|
198
|
+
"""
|
|
199
|
+
if self.golden is None:
|
|
200
|
+
raise AssertionError(
|
|
201
|
+
f"no approved recording for {self.name!r} to compare live runs against"
|
|
202
|
+
)
|
|
203
|
+
level = tolerance or self.config.default_tolerance
|
|
204
|
+
required = pass_k[0] if pass_k else len(self.trajectories)
|
|
205
|
+
matched = self.matches(level)
|
|
206
|
+
if matched < required:
|
|
207
|
+
worst = next(
|
|
208
|
+
(
|
|
209
|
+
trajectory
|
|
210
|
+
for trajectory in self.trajectories
|
|
211
|
+
if not trajectory_diff(self.golden.trajectory, trajectory, level).matched
|
|
212
|
+
),
|
|
213
|
+
None,
|
|
214
|
+
)
|
|
215
|
+
detail = ""
|
|
216
|
+
if worst is not None:
|
|
217
|
+
detail = "\n" + render_diff(trajectory_diff(self.golden.trajectory, worst, level))
|
|
218
|
+
raise AssertionError(
|
|
219
|
+
f"live behaviour check failed for {self.name!r}: {matched}/"
|
|
220
|
+
f"{len(self.trajectories)} runs matched golden, needed {required}."
|
|
221
|
+
f"{detail}\n\n{render(self.report)}"
|
|
222
|
+
)
|
|
223
|
+
return self
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def run_live(
|
|
227
|
+
name: str,
|
|
228
|
+
runner: Callable[[], Any],
|
|
229
|
+
*,
|
|
230
|
+
runs: int = 5,
|
|
231
|
+
config: Config | None = None,
|
|
232
|
+
) -> LiveResult:
|
|
233
|
+
"""Run a scenario against the real model ``runs`` times and compare behaviour.
|
|
234
|
+
|
|
235
|
+
``runner`` is a zero-argument callable that exercises the agent.
|
|
236
|
+
"""
|
|
237
|
+
_require_live()
|
|
238
|
+
if runs < 1:
|
|
239
|
+
raise DriftCatchError("runs must be at least 1")
|
|
240
|
+
|
|
241
|
+
from driftcatch.take import take as open_take
|
|
242
|
+
|
|
243
|
+
cfg = config or get_config()
|
|
244
|
+
path = recording_path(name, cfg.recordings_dir)
|
|
245
|
+
golden = load_recording(path) if path.exists() else None
|
|
246
|
+
|
|
247
|
+
trajectories: list[Trajectory] = []
|
|
248
|
+
for _ in range(runs):
|
|
249
|
+
with open_take(name, mode="live") as take_obj:
|
|
250
|
+
runner()
|
|
251
|
+
trajectories.append(take_obj.trajectory)
|
|
252
|
+
|
|
253
|
+
return LiveResult(name, trajectories, golden, cfg)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def live_check(name: str, *, runs: int = 5) -> Callable[[F], F]:
|
|
257
|
+
"""Mark a test as a Tier 2 live behaviour check.
|
|
258
|
+
|
|
259
|
+
Skips rather than fails when live runs are not permitted, so a normal test
|
|
260
|
+
suite stays free and offline while the behaviour gate still exists in CI for
|
|
261
|
+
the runs that opt in.
|
|
262
|
+
"""
|
|
263
|
+
|
|
264
|
+
def decorator(fn: F) -> F:
|
|
265
|
+
@functools.wraps(fn)
|
|
266
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
267
|
+
if not live_allowed():
|
|
268
|
+
try:
|
|
269
|
+
import pytest
|
|
270
|
+
|
|
271
|
+
pytest.skip(
|
|
272
|
+
f"live behaviour check for {name!r} skipped; "
|
|
273
|
+
f"set {ENV_PREFIX}_ALLOW_LIVE=1 to run it"
|
|
274
|
+
)
|
|
275
|
+
except ImportError: # pragma: no cover
|
|
276
|
+
return None
|
|
277
|
+
return fn(*args, **kwargs)
|
|
278
|
+
|
|
279
|
+
wrapper.driftcatch_live = {"name": name, "runs": runs} # type: ignore[attr-defined]
|
|
280
|
+
return cast(F, wrapper)
|
|
281
|
+
|
|
282
|
+
return decorator
|
driftcatch/errors.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Exception hierarchy.
|
|
2
|
+
|
|
3
|
+
Every user-facing failure raises a ``DriftCatchError`` subclass carrying an
|
|
4
|
+
actionable message. Never raise a bare ``Exception`` from library code.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class DriftCatchError(Exception):
|
|
11
|
+
"""Base class for ordinary errors raised by DriftCatch."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class DriftSignal(BaseException):
|
|
15
|
+
"""Base for signals that must never be swallowed.
|
|
16
|
+
|
|
17
|
+
Derived from ``BaseException``, not ``Exception``, on purpose. These are
|
|
18
|
+
*test-framework control signals*, not application errors, and two layers of
|
|
19
|
+
well-meaning code would otherwise eat them:
|
|
20
|
+
|
|
21
|
+
* **Provider SDKs.** The Anthropic SDK catches ``Exception`` around its
|
|
22
|
+
request path and re-raises it as ``APIConnectionError``, which would
|
|
23
|
+
replace a precise "the system prompt changed at messages[0].content" with
|
|
24
|
+
a useless "Connection error".
|
|
25
|
+
* **The agent itself.** An agent with ``try: ... except Exception: fallback()``
|
|
26
|
+
would silently absorb a replay mismatch, the test would pass, and a real
|
|
27
|
+
behaviour regression would ship. That is a false green, which is worse than
|
|
28
|
+
a false red.
|
|
29
|
+
|
|
30
|
+
Catching these explicitly by name still works, which is all DriftCatch's own
|
|
31
|
+
internals need.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class RecordingNotFound(DriftCatchError):
|
|
36
|
+
"""No recording exists for the requested name."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class RecordingVersionError(DriftCatchError):
|
|
40
|
+
"""The recording file was written by an incompatible version."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class RecordingNotApproved(DriftCatchError):
|
|
44
|
+
"""A recording was used as golden before a human approved it."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class InvalidTransition(DriftCatchError):
|
|
48
|
+
"""An illegal recording status transition was attempted."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class NoMatchError(DriftSignal):
|
|
52
|
+
"""No recorded event matches the incoming request.
|
|
53
|
+
|
|
54
|
+
This is the framework's core signal: the agent sent a request it did not
|
|
55
|
+
send when the recording was made. It is never swallowed and never falls
|
|
56
|
+
through to a live call.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
reason: str,
|
|
62
|
+
*,
|
|
63
|
+
diverged_at: int | None = None,
|
|
64
|
+
diff: str | None = None,
|
|
65
|
+
) -> None:
|
|
66
|
+
self.reason = reason
|
|
67
|
+
self.diverged_at = diverged_at
|
|
68
|
+
self.diff = diff
|
|
69
|
+
location = f" at event #{diverged_at}" if diverged_at is not None else ""
|
|
70
|
+
message = f"No matching recorded event{location}: {reason}"
|
|
71
|
+
if diff:
|
|
72
|
+
message = f"{message}\n{diff}"
|
|
73
|
+
super().__init__(message)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class AmbiguousMatchError(DriftCatchError):
|
|
77
|
+
"""Several recorded events match equally well; the matcher must be tightened."""
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class RedactionError(DriftCatchError):
|
|
81
|
+
"""A secret survived redaction, so the recording was not written."""
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class RecordedError(DriftCatchError):
|
|
85
|
+
"""Re-raised stand-in for a failure captured during recording.
|
|
86
|
+
|
|
87
|
+
Used when the original exception type cannot be reconstructed. Recorded
|
|
88
|
+
failures must still surface on replay, otherwise retry and error-handling
|
|
89
|
+
paths would never be exercised.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class ConfigError(DriftCatchError):
|
|
94
|
+
"""The supplied configuration is invalid."""
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class PrunedRecording(DriftCatchError):
|
|
98
|
+
"""A pruned recording was replayed.
|
|
99
|
+
|
|
100
|
+
``drift prune`` discards response bodies to save space, keeping only the
|
|
101
|
+
trajectory. Such a recording can still be used for behaviour assertions and
|
|
102
|
+
coverage, but it can no longer reproduce a reply - and serving an empty one
|
|
103
|
+
would be a silent false green.
|
|
104
|
+
"""
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class RecordingWriteError(DriftCatchError):
|
|
108
|
+
"""A recording could not be written to disk."""
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class InvalidRecordingName(DriftCatchError):
|
|
112
|
+
"""A recording name is not a safe, simple identifier.
|
|
113
|
+
|
|
114
|
+
Names become filenames, and they arrive from places that are not always
|
|
115
|
+
trusted: CLI arguments, config, and - most importantly - an MCP tool call
|
|
116
|
+
made by a coding agent, which may itself be acting on content it read
|
|
117
|
+
somewhere. Without this check, ``../../../secrets`` reads and writes
|
|
118
|
+
outside the recordings directory.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class DriftDetected(DriftSignal):
|
|
123
|
+
"""A recording no longer reflects the inputs that produced it.
|
|
124
|
+
|
|
125
|
+
Raised only under ``drift_policy="fail"``. The default policy warns instead,
|
|
126
|
+
because a stale recording is information, not necessarily a failure - the
|
|
127
|
+
human decides.
|
|
128
|
+
|
|
129
|
+
A ``DriftSignal`` so that SDK and agent exception handling cannot bury it.
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class DriftWarning(UserWarning):
|
|
134
|
+
"""Warning issued when a recording goes stale under ``drift_policy="warn"``."""
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class UnapprovedReplayWarning(UserWarning):
|
|
138
|
+
"""Warning issued when replaying a recording no human has approved."""
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class LatencyNotMeasured(UserWarning):
|
|
142
|
+
"""A latency assertion ran during replay, where there is nothing to time.
|
|
143
|
+
|
|
144
|
+
Replay serves recorded bytes from disk, so the only durations available are
|
|
145
|
+
the ones captured when the run was recorded. Checking those during replay
|
|
146
|
+
would compare a fixed number against itself and pass forever, which is a
|
|
147
|
+
green light that means nothing. The assertion is skipped and this warning
|
|
148
|
+
explains why, rather than failing a test that is correctly written.
|
|
149
|
+
"""
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Boundary interception: HTTP model calls and Python tool calls."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from driftcatch.intercept.http import assemble_stream, intercept_http, response_from_event
|
|
6
|
+
from driftcatch.intercept.tools import tool
|
|
7
|
+
|
|
8
|
+
__all__ = ["assemble_stream", "intercept_http", "response_from_event", "tool"]
|