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/match/base.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Core matcher types.
|
|
2
|
+
|
|
3
|
+
The matcher answers one question: *for this request, which recorded event do I
|
|
4
|
+
serve?* Everything else in DriftCatch is plumbing around that answer.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from enum import StrEnum
|
|
12
|
+
from typing import Any, Literal, Protocol
|
|
13
|
+
|
|
14
|
+
from driftcatch.recording.schema import Event
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"Confidence",
|
|
18
|
+
"Kind",
|
|
19
|
+
"Match",
|
|
20
|
+
"MatchContext",
|
|
21
|
+
"MatchQuery",
|
|
22
|
+
"MatchRecord",
|
|
23
|
+
"MatchResult",
|
|
24
|
+
"MatchState",
|
|
25
|
+
"Matcher",
|
|
26
|
+
"NoMatch",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
Kind = Literal["llm", "tool"]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Confidence(StrEnum):
|
|
33
|
+
"""How sure the matcher is, reported on every match.
|
|
34
|
+
|
|
35
|
+
``EXACT`` the raw payloads were identical.
|
|
36
|
+
``NORMALIZED`` they matched only after normalizers stripped noise.
|
|
37
|
+
``FUZZY`` a similarity threshold was used. Fails under ``strict``.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
EXACT = "exact"
|
|
41
|
+
NORMALIZED = "normalized"
|
|
42
|
+
FUZZY = "fuzzy"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class MatchQuery:
|
|
47
|
+
"""An outgoing request, in the shape the matcher compares."""
|
|
48
|
+
|
|
49
|
+
kind: Kind
|
|
50
|
+
payload: dict[str, Any]
|
|
51
|
+
name: str | None = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class Match:
|
|
56
|
+
"""A recorded event chosen for the request."""
|
|
57
|
+
|
|
58
|
+
event: Event
|
|
59
|
+
confidence: Confidence
|
|
60
|
+
score: float = 1.0
|
|
61
|
+
matcher: str = ""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class NoMatch:
|
|
66
|
+
"""No recorded event fits.
|
|
67
|
+
|
|
68
|
+
This is the framework's core signal, not an inconvenience: the agent sent a
|
|
69
|
+
request it did not send when the recording was made.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
reason: str
|
|
73
|
+
diverged_at: int | None = None
|
|
74
|
+
diff: str | None = None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
MatchResult = Match | NoMatch
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass
|
|
81
|
+
class MatchRecord:
|
|
82
|
+
"""One line of the match audit trail, surfaced by ``drift audit``."""
|
|
83
|
+
|
|
84
|
+
order: int
|
|
85
|
+
kind: Kind
|
|
86
|
+
event_index: int
|
|
87
|
+
confidence: Confidence
|
|
88
|
+
matcher: str
|
|
89
|
+
key: str
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass
|
|
93
|
+
class MatchState:
|
|
94
|
+
"""Mutable per-session matching state.
|
|
95
|
+
|
|
96
|
+
``consumed`` is the mechanism that makes repeated identical requests work:
|
|
97
|
+
the first call takes event A, so the second call naturally takes event B.
|
|
98
|
+
That single rule covers retries and ``pending -> done`` polling without a
|
|
99
|
+
separate counter.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
consumed: set[int] = field(default_factory=set)
|
|
103
|
+
counters: dict[str, int] = field(default_factory=dict)
|
|
104
|
+
trail: list[MatchRecord] = field(default_factory=list)
|
|
105
|
+
#: Normalized payloads and match keys, cached for the whole session and
|
|
106
|
+
#: keyed by (event index, normalizer signature). Without this, every request
|
|
107
|
+
#: re-normalizes every candidate, which is O(n^2) normalizations over a run
|
|
108
|
+
#: and becomes the dominant cost on long recordings.
|
|
109
|
+
payload_cache: dict[tuple[int, str], dict[str, Any]] = field(default_factory=dict)
|
|
110
|
+
key_cache: dict[tuple[int, str], str] = field(default_factory=dict)
|
|
111
|
+
|
|
112
|
+
def available(self, candidates: Sequence[Event], kind: Kind) -> list[Event]:
|
|
113
|
+
"""Candidates of ``kind`` that have not been served yet, in order."""
|
|
114
|
+
wanted = "llm" if kind == "llm" else "tool"
|
|
115
|
+
return [e for e in candidates if e.type == wanted and e.index not in self.consumed]
|
|
116
|
+
|
|
117
|
+
def take(self, event: Event) -> None:
|
|
118
|
+
self.consumed.add(event.index)
|
|
119
|
+
|
|
120
|
+
def note(self, query: MatchQuery, match: Match, key: str) -> None:
|
|
121
|
+
self.counters[key] = self.counters.get(key, 0) + 1
|
|
122
|
+
self.trail.append(
|
|
123
|
+
MatchRecord(
|
|
124
|
+
order=len(self.trail),
|
|
125
|
+
kind=query.kind,
|
|
126
|
+
event_index=match.event.index,
|
|
127
|
+
confidence=match.confidence,
|
|
128
|
+
matcher=match.matcher,
|
|
129
|
+
key=key,
|
|
130
|
+
)
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class MatchContext(Protocol):
|
|
135
|
+
"""Normalized views of the query and candidates, cached per resolution.
|
|
136
|
+
|
|
137
|
+
Normalization happens once, in ``resolve``, so strategies never re-run the
|
|
138
|
+
pipeline and every strategy compares like for like.
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
normalizers: list[str]
|
|
142
|
+
query_key: str
|
|
143
|
+
|
|
144
|
+
def normalized_query(self) -> dict[str, Any]: ...
|
|
145
|
+
def key_of(self, event: Event) -> str: ...
|
|
146
|
+
def payload_of(self, event: Event) -> dict[str, Any]: ...
|
|
147
|
+
def raw_equal(self, event: Event) -> bool: ...
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class Matcher(Protocol):
|
|
151
|
+
"""Strategy interface. Register implementations by name."""
|
|
152
|
+
|
|
153
|
+
name: str
|
|
154
|
+
|
|
155
|
+
def match(
|
|
156
|
+
self,
|
|
157
|
+
query: MatchQuery,
|
|
158
|
+
candidates: Sequence[Event],
|
|
159
|
+
state: MatchState,
|
|
160
|
+
ctx: MatchContext,
|
|
161
|
+
) -> MatchResult: ...
|
driftcatch/match/keys.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Turning requests and events into comparable payloads.
|
|
2
|
+
|
|
3
|
+
Matching compares *payloads*, never raw bytes. A payload is the small, provider
|
|
4
|
+
agnostic projection of a request that actually determines behaviour.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from driftcatch.match.base import Kind, MatchQuery
|
|
12
|
+
from driftcatch.recording.fingerprint import canonical, hash_str
|
|
13
|
+
from driftcatch.recording.schema import Event, LLMEvent, LLMRequest, ToolEvent
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"event_payload",
|
|
17
|
+
"key_for",
|
|
18
|
+
"llm_query",
|
|
19
|
+
"tool_query",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def event_payload(event: Event) -> dict[str, Any]:
|
|
24
|
+
"""The comparable projection of a recorded event."""
|
|
25
|
+
if isinstance(event, LLMEvent):
|
|
26
|
+
return {
|
|
27
|
+
"model": event.request.model,
|
|
28
|
+
"messages": event.request.messages,
|
|
29
|
+
"tools": event.request.tools,
|
|
30
|
+
"params": event.request.params,
|
|
31
|
+
}
|
|
32
|
+
if isinstance(event, ToolEvent):
|
|
33
|
+
return {"name": event.name, "args": event.args}
|
|
34
|
+
raise TypeError(f"unsupported event type: {type(event)!r}") # pragma: no cover
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def llm_query(request: LLMRequest) -> MatchQuery:
|
|
38
|
+
"""Build a query from an outgoing model call."""
|
|
39
|
+
return MatchQuery(
|
|
40
|
+
kind="llm",
|
|
41
|
+
payload={
|
|
42
|
+
"model": request.model,
|
|
43
|
+
"messages": request.messages,
|
|
44
|
+
"tools": request.tools,
|
|
45
|
+
"params": request.params,
|
|
46
|
+
},
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def tool_query(name: str, args: dict[str, Any]) -> MatchQuery:
|
|
51
|
+
"""Build a query from an outgoing tool call."""
|
|
52
|
+
return MatchQuery(kind="tool", payload={"name": name, "args": args}, name=name)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def key_for(payload: dict[str, Any]) -> str:
|
|
56
|
+
"""Stable hash of a payload, used as the match key."""
|
|
57
|
+
return hash_str(canonical(payload))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def kind_of(event: Event) -> Kind:
|
|
61
|
+
return "llm" if isinstance(event, LLMEvent) else "tool"
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Built-in normalizers: deciding what counts as noise.
|
|
2
|
+
|
|
3
|
+
A normalizer strips values that vary run to run but do not change behaviour.
|
|
4
|
+
Without them, a fresh timestamp or a random tool-call id would look like drift.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from driftcatch.match.registry import normalizer
|
|
13
|
+
from driftcatch.redact import redact
|
|
14
|
+
|
|
15
|
+
__all__ = ["apply_normalizers"]
|
|
16
|
+
|
|
17
|
+
_TIMESTAMP_KEY = re.compile(r"(created|timestamp|_at$|^time$|^date$)", re.IGNORECASE)
|
|
18
|
+
_UUID = re.compile(
|
|
19
|
+
r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", re.IGNORECASE
|
|
20
|
+
)
|
|
21
|
+
#: Provider-generated correlation ids for tool calls.
|
|
22
|
+
_TOOL_CALL_ID = re.compile(r"^(call_|toolu_|fc_|tooluse_)[A-Za-z0-9_\-]{6,}$")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@normalizer("drop_timestamps")
|
|
26
|
+
def drop_timestamps(payload: dict[str, Any]) -> dict[str, Any]:
|
|
27
|
+
"""Remove keys that carry wall-clock values."""
|
|
28
|
+
|
|
29
|
+
def strip(node: Any) -> Any:
|
|
30
|
+
if isinstance(node, dict):
|
|
31
|
+
return {
|
|
32
|
+
key: strip(value)
|
|
33
|
+
for key, value in node.items()
|
|
34
|
+
if not _TIMESTAMP_KEY.search(str(key))
|
|
35
|
+
}
|
|
36
|
+
if isinstance(node, list):
|
|
37
|
+
return [strip(item) for item in node]
|
|
38
|
+
return node
|
|
39
|
+
|
|
40
|
+
result = strip(payload)
|
|
41
|
+
return result if isinstance(result, dict) else payload
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@normalizer("mask_uuids")
|
|
45
|
+
def mask_uuids(payload: dict[str, Any]) -> dict[str, Any]:
|
|
46
|
+
"""Replace UUID-shaped strings with a stable placeholder."""
|
|
47
|
+
|
|
48
|
+
def mask(node: Any) -> Any:
|
|
49
|
+
if isinstance(node, dict):
|
|
50
|
+
return {key: mask(value) for key, value in node.items()}
|
|
51
|
+
if isinstance(node, list):
|
|
52
|
+
return [mask(item) for item in node]
|
|
53
|
+
if isinstance(node, str):
|
|
54
|
+
return _UUID.sub("<uuid>", node)
|
|
55
|
+
return node
|
|
56
|
+
|
|
57
|
+
result = mask(payload)
|
|
58
|
+
return result if isinstance(result, dict) else payload
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@normalizer("normalize_tool_call_ids")
|
|
62
|
+
def normalize_tool_call_ids(payload: dict[str, Any]) -> dict[str, Any]:
|
|
63
|
+
"""Rewrite provider tool-call ids to positional placeholders.
|
|
64
|
+
|
|
65
|
+
Mandatory in the default set. Providers mint a fresh random id for every
|
|
66
|
+
request, so without this every single match would miss.
|
|
67
|
+
"""
|
|
68
|
+
seen: dict[str, str] = {}
|
|
69
|
+
|
|
70
|
+
def collect(node: Any) -> None:
|
|
71
|
+
if isinstance(node, dict):
|
|
72
|
+
for key, value in node.items():
|
|
73
|
+
if (
|
|
74
|
+
key in {"id", "tool_call_id", "tool_use_id"}
|
|
75
|
+
and isinstance(value, str)
|
|
76
|
+
and _TOOL_CALL_ID.match(value)
|
|
77
|
+
and value not in seen
|
|
78
|
+
):
|
|
79
|
+
seen[value] = f"<tc:{len(seen)}>"
|
|
80
|
+
collect(value)
|
|
81
|
+
elif isinstance(node, list):
|
|
82
|
+
for item in node:
|
|
83
|
+
collect(item)
|
|
84
|
+
|
|
85
|
+
def rewrite(node: Any) -> Any:
|
|
86
|
+
if isinstance(node, dict):
|
|
87
|
+
return {key: rewrite(value) for key, value in node.items()}
|
|
88
|
+
if isinstance(node, list):
|
|
89
|
+
return [rewrite(item) for item in node]
|
|
90
|
+
if isinstance(node, str) and node in seen:
|
|
91
|
+
return seen[node]
|
|
92
|
+
return node
|
|
93
|
+
|
|
94
|
+
collect(payload)
|
|
95
|
+
if not seen:
|
|
96
|
+
return payload
|
|
97
|
+
result = rewrite(payload)
|
|
98
|
+
return result if isinstance(result, dict) else payload
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@normalizer("json_canonical")
|
|
102
|
+
def json_canonical(payload: dict[str, Any]) -> dict[str, Any]:
|
|
103
|
+
"""Recursively sort dictionary keys so key order cannot look like drift."""
|
|
104
|
+
|
|
105
|
+
def sort(node: Any) -> Any:
|
|
106
|
+
if isinstance(node, dict):
|
|
107
|
+
return {key: sort(node[key]) for key in sorted(node, key=str)}
|
|
108
|
+
if isinstance(node, list):
|
|
109
|
+
return [sort(item) for item in node]
|
|
110
|
+
return node
|
|
111
|
+
|
|
112
|
+
result = sort(payload)
|
|
113
|
+
return result if isinstance(result, dict) else payload
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@normalizer("redact_secrets")
|
|
117
|
+
def redact_secrets(payload: dict[str, Any]) -> dict[str, Any]:
|
|
118
|
+
"""Strip credentials so they never influence a match key."""
|
|
119
|
+
cleaned, _ = redact(payload, ["default"])
|
|
120
|
+
return cleaned if isinstance(cleaned, dict) else payload
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def apply_normalizers(payload: dict[str, Any], names: list[str]) -> dict[str, Any]:
|
|
124
|
+
"""Apply the named normalizers in order."""
|
|
125
|
+
from driftcatch.match.registry import get_normalizer
|
|
126
|
+
|
|
127
|
+
result = payload
|
|
128
|
+
for name in names:
|
|
129
|
+
result = get_normalizer(name)(result)
|
|
130
|
+
return result
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Name-based registry for matchers and normalizers.
|
|
2
|
+
|
|
3
|
+
Built-ins and user-supplied implementations live in the same registry, so a
|
|
4
|
+
custom matcher is a first-class citizen selectable by name from config.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from typing import Any, TypeVar
|
|
11
|
+
|
|
12
|
+
from driftcatch.errors import ConfigError
|
|
13
|
+
from driftcatch.match.base import Matcher
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"Normalizer",
|
|
17
|
+
"get_matcher",
|
|
18
|
+
"get_normalizer",
|
|
19
|
+
"list_matchers",
|
|
20
|
+
"list_normalizers",
|
|
21
|
+
"matcher",
|
|
22
|
+
"normalizer",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
Normalizer = Callable[[dict[str, Any]], dict[str, Any]]
|
|
26
|
+
|
|
27
|
+
_MATCHERS: dict[str, Matcher] = {}
|
|
28
|
+
_NORMALIZERS: dict[str, Normalizer] = {}
|
|
29
|
+
|
|
30
|
+
M = TypeVar("M", bound=Matcher)
|
|
31
|
+
N = TypeVar("N", bound=Normalizer)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def matcher(name: str) -> Callable[[type[M]], type[M]]:
|
|
35
|
+
"""Register a matcher class under ``name``."""
|
|
36
|
+
|
|
37
|
+
def register(cls: type[M]) -> type[M]:
|
|
38
|
+
instance = cls()
|
|
39
|
+
instance.name = name
|
|
40
|
+
_MATCHERS[name] = instance
|
|
41
|
+
return cls
|
|
42
|
+
|
|
43
|
+
return register
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def normalizer(name: str) -> Callable[[N], N]:
|
|
47
|
+
"""Register a normalizer function under ``name``."""
|
|
48
|
+
|
|
49
|
+
def register(fn: N) -> N:
|
|
50
|
+
_NORMALIZERS[name] = fn
|
|
51
|
+
return fn
|
|
52
|
+
|
|
53
|
+
return register
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def register_matcher(name: str, instance: Matcher) -> None:
|
|
57
|
+
"""Register an already-built matcher instance (used by ``chain``)."""
|
|
58
|
+
_MATCHERS[name] = instance
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def get_matcher(name: str) -> Matcher:
|
|
62
|
+
try:
|
|
63
|
+
return _MATCHERS[name]
|
|
64
|
+
except KeyError:
|
|
65
|
+
known = ", ".join(sorted(_MATCHERS)) or "none"
|
|
66
|
+
raise ConfigError(f"unknown matcher {name!r}. Registered matchers: {known}") from None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def get_normalizer(name: str) -> Normalizer:
|
|
70
|
+
try:
|
|
71
|
+
return _NORMALIZERS[name]
|
|
72
|
+
except KeyError:
|
|
73
|
+
known = ", ".join(sorted(_NORMALIZERS)) or "none"
|
|
74
|
+
raise ConfigError(f"unknown normalizer {name!r}. Registered normalizers: {known}") from None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def list_matchers() -> list[str]:
|
|
78
|
+
return sorted(_MATCHERS)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def list_normalizers() -> list[str]:
|
|
82
|
+
return sorted(_NORMALIZERS)
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Resolution pipeline: normalize, match, and explain failures precisely.
|
|
2
|
+
|
|
3
|
+
The failure path matters as much as the success path. When a request does not
|
|
4
|
+
match, DriftCatch reports the **first divergence only** and stops. One prompt
|
|
5
|
+
change must produce one clear error, never a cascade of fifty.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Sequence
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from driftcatch.config import Config
|
|
14
|
+
from driftcatch.errors import NoMatchError
|
|
15
|
+
from driftcatch.match.base import (
|
|
16
|
+
Confidence,
|
|
17
|
+
Match,
|
|
18
|
+
MatchQuery,
|
|
19
|
+
MatchState,
|
|
20
|
+
NoMatch,
|
|
21
|
+
)
|
|
22
|
+
from driftcatch.match.keys import event_payload, key_for
|
|
23
|
+
from driftcatch.match.normalizers import apply_normalizers
|
|
24
|
+
from driftcatch.match.registry import get_matcher
|
|
25
|
+
from driftcatch.recording.fingerprint import canonical
|
|
26
|
+
from driftcatch.recording.schema import Event
|
|
27
|
+
|
|
28
|
+
__all__ = ["NormalizationContext", "resolve"]
|
|
29
|
+
|
|
30
|
+
_MAX_VALUE_CHARS = 160
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class NormalizationContext:
|
|
34
|
+
"""Normalized views of the query and candidates.
|
|
35
|
+
|
|
36
|
+
Candidate payloads and keys are cached on the :class:`MatchState`, so they
|
|
37
|
+
survive across every resolution in a session rather than being recomputed
|
|
38
|
+
from scratch for each request.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
query: MatchQuery,
|
|
44
|
+
normalizers: list[str],
|
|
45
|
+
state: MatchState | None = None,
|
|
46
|
+
) -> None:
|
|
47
|
+
self.normalizers = list(normalizers)
|
|
48
|
+
self._signature = ",".join(self.normalizers)
|
|
49
|
+
self._state = state
|
|
50
|
+
self._raw_query = query.payload
|
|
51
|
+
self._norm_query = apply_normalizers(query.payload, self.normalizers)
|
|
52
|
+
self.query_key = key_for(self._norm_query)
|
|
53
|
+
self._local_payloads: dict[tuple[int, str], dict[str, Any]] = {}
|
|
54
|
+
self._local_keys: dict[tuple[int, str], str] = {}
|
|
55
|
+
self._raw: dict[int, dict[str, Any]] = {}
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def _payloads(self) -> dict[tuple[int, str], dict[str, Any]]:
|
|
59
|
+
return self._state.payload_cache if self._state is not None else self._local_payloads
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def _keys(self) -> dict[tuple[int, str], str]:
|
|
63
|
+
return self._state.key_cache if self._state is not None else self._local_keys
|
|
64
|
+
|
|
65
|
+
def normalized_query(self) -> dict[str, Any]:
|
|
66
|
+
return self._norm_query
|
|
67
|
+
|
|
68
|
+
def raw_query(self) -> dict[str, Any]:
|
|
69
|
+
return self._raw_query
|
|
70
|
+
|
|
71
|
+
def payload_of(self, event: Event) -> dict[str, Any]:
|
|
72
|
+
cache_key = (event.index, self._signature)
|
|
73
|
+
if cache_key not in self._payloads:
|
|
74
|
+
self._payloads[cache_key] = apply_normalizers(event_payload(event), self.normalizers)
|
|
75
|
+
return self._payloads[cache_key]
|
|
76
|
+
|
|
77
|
+
def raw_payload_of(self, event: Event) -> dict[str, Any]:
|
|
78
|
+
if event.index not in self._raw:
|
|
79
|
+
self._raw[event.index] = event_payload(event)
|
|
80
|
+
return self._raw[event.index]
|
|
81
|
+
|
|
82
|
+
def key_of(self, event: Event) -> str:
|
|
83
|
+
cache_key = (event.index, self._signature)
|
|
84
|
+
if cache_key not in self._keys:
|
|
85
|
+
self._keys[cache_key] = key_for(self.payload_of(event))
|
|
86
|
+
return self._keys[cache_key]
|
|
87
|
+
|
|
88
|
+
def raw_equal(self, event: Event) -> bool:
|
|
89
|
+
return canonical(self.raw_payload_of(event)) == canonical(self._raw_query)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _truncate(value: Any) -> str:
|
|
93
|
+
text = value if isinstance(value, str) else canonical(value)
|
|
94
|
+
if len(text) > _MAX_VALUE_CHARS:
|
|
95
|
+
return f"{text[:_MAX_VALUE_CHARS]}..."
|
|
96
|
+
return text
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _first_difference(recorded: Any, current: Any, path: str = "") -> tuple[str, Any, Any] | None:
|
|
100
|
+
"""Depth-first search for the first place two payloads disagree."""
|
|
101
|
+
if isinstance(recorded, dict) and isinstance(current, dict):
|
|
102
|
+
for key in sorted(set(recorded) | set(current), key=str):
|
|
103
|
+
child = f"{path}.{key}" if path else str(key)
|
|
104
|
+
if key not in recorded:
|
|
105
|
+
return child, "<absent>", current[key]
|
|
106
|
+
if key not in current:
|
|
107
|
+
return child, recorded[key], "<absent>"
|
|
108
|
+
found = _first_difference(recorded[key], current[key], child)
|
|
109
|
+
if found is not None:
|
|
110
|
+
return found
|
|
111
|
+
return None
|
|
112
|
+
if isinstance(recorded, list) and isinstance(current, list):
|
|
113
|
+
for index in range(max(len(recorded), len(current))):
|
|
114
|
+
child = f"{path}[{index}]"
|
|
115
|
+
if index >= len(recorded):
|
|
116
|
+
return child, "<absent>", current[index]
|
|
117
|
+
if index >= len(current):
|
|
118
|
+
return child, recorded[index], "<absent>"
|
|
119
|
+
found = _first_difference(recorded[index], current[index], child)
|
|
120
|
+
if found is not None:
|
|
121
|
+
return found
|
|
122
|
+
return None
|
|
123
|
+
if recorded != current:
|
|
124
|
+
return path or "<root>", recorded, current
|
|
125
|
+
return None
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _divergence_report(
|
|
129
|
+
query: MatchQuery,
|
|
130
|
+
candidates: Sequence[Event],
|
|
131
|
+
state: MatchState,
|
|
132
|
+
ctx: NormalizationContext,
|
|
133
|
+
) -> tuple[int | None, str]:
|
|
134
|
+
"""Build the human-readable explanation of why nothing matched."""
|
|
135
|
+
available = state.available(candidates, query.kind)
|
|
136
|
+
if not available:
|
|
137
|
+
return None, (
|
|
138
|
+
f" the recording holds no further {query.kind} events, but the agent "
|
|
139
|
+
f"made another {query.kind} call.\n"
|
|
140
|
+
" The agent is doing more work than it did when this was recorded."
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
nearest = available[0]
|
|
144
|
+
difference = _first_difference(ctx.payload_of(nearest), ctx.normalized_query())
|
|
145
|
+
|
|
146
|
+
lines = [f" diverged at event #{nearest.index} ({query.kind})"]
|
|
147
|
+
if difference is None:
|
|
148
|
+
lines.append(" payloads agree after normalization but no strategy accepted them;")
|
|
149
|
+
lines.append(" the matcher may be too strict for this recording.")
|
|
150
|
+
return nearest.index, "\n".join(lines)
|
|
151
|
+
|
|
152
|
+
where, recorded_value, current_value = difference
|
|
153
|
+
lines.append(f" field: {where}")
|
|
154
|
+
lines.append(f" recorded: {_truncate(recorded_value)}")
|
|
155
|
+
lines.append(f" current: {_truncate(current_value)}")
|
|
156
|
+
lines.append("")
|
|
157
|
+
lines.append(" The agent sent a request it did not send when this was recorded.")
|
|
158
|
+
lines.append(" If the change is intended, re-record and re-approve:")
|
|
159
|
+
lines.append(" drift record # the previous version is archived")
|
|
160
|
+
lines.append(" drift approve <name> --by <who>")
|
|
161
|
+
return nearest.index, "\n".join(lines)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def resolve(
|
|
165
|
+
query: MatchQuery,
|
|
166
|
+
candidates: Sequence[Event],
|
|
167
|
+
state: MatchState,
|
|
168
|
+
config: Config,
|
|
169
|
+
) -> Match:
|
|
170
|
+
"""Pick the recorded event for ``query`` or raise :class:`NoMatchError`.
|
|
171
|
+
|
|
172
|
+
Never falls through to a live call and never serves a nearby response: a
|
|
173
|
+
false green is worse than a false red.
|
|
174
|
+
"""
|
|
175
|
+
ctx = NormalizationContext(query, config.normalizers, state)
|
|
176
|
+
result = get_matcher(config.matcher).match(query, candidates, state, ctx)
|
|
177
|
+
|
|
178
|
+
if isinstance(result, NoMatch):
|
|
179
|
+
index, diff = _divergence_report(query, candidates, state, ctx)
|
|
180
|
+
raise NoMatchError(
|
|
181
|
+
result.reason,
|
|
182
|
+
diverged_at=result.diverged_at if result.diverged_at is not None else index,
|
|
183
|
+
diff=diff,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
if config.strict and result.confidence is Confidence.FUZZY:
|
|
187
|
+
raise NoMatchError(
|
|
188
|
+
f"only a fuzzy match was available (score {result.score:.2f}) and strict "
|
|
189
|
+
"mode is on. Tighten the matcher or set strict=False deliberately.",
|
|
190
|
+
diverged_at=result.event.index,
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
state.take(result.event)
|
|
194
|
+
state.note(query, result, ctx.query_key)
|
|
195
|
+
return result
|