datapi-selfheal 0.3.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.
- datapi_selfheal-0.3.0.dist-info/METADATA +313 -0
- datapi_selfheal-0.3.0.dist-info/RECORD +35 -0
- datapi_selfheal-0.3.0.dist-info/WHEEL +5 -0
- datapi_selfheal-0.3.0.dist-info/entry_points.txt +3 -0
- datapi_selfheal-0.3.0.dist-info/licenses/LICENSE +21 -0
- datapi_selfheal-0.3.0.dist-info/top_level.txt +3 -0
- selfheal_api/__init__.py +106 -0
- selfheal_api/_sandbox_exec.py +124 -0
- selfheal_api/autoheal.py +658 -0
- selfheal_api/billing.py +738 -0
- selfheal_api/cli.py +958 -0
- selfheal_api/dashboard.py +1094 -0
- selfheal_api/eval_fixtures.py +39 -0
- selfheal_api/github_app.py +1050 -0
- selfheal_api/github_jwt.py +145 -0
- selfheal_api/ledger.py +305 -0
- selfheal_api/metrics.py +259 -0
- selfheal_api/middleware.py +297 -0
- selfheal_api/modelgen.py +333 -0
- selfheal_api/notifier.py +426 -0
- selfheal_api/remediation.py +277 -0
- selfheal_api/replay.py +126 -0
- selfheal_api/sandbox.py +157 -0
- selfheal_api/server.py +1480 -0
- selfheal_api/server_hosted.py +1656 -0
- selfheal_api/specwatch.py +203 -0
- selfheal_api/worker.py +212 -0
- sentinel/__init__.py +33 -0
- sentinel/detector.py +626 -0
- sentinel/guard.py +345 -0
- sentinel/llm_fallback.py +256 -0
- synthesizer/__init__.py +31 -0
- synthesizer/openapi_emitter.py +181 -0
- synthesizer/patcher.py +944 -0
- synthesizer/zod_emitter.py +336 -0
sentinel/guard.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import contextlib
|
|
5
|
+
import functools
|
|
6
|
+
import hashlib
|
|
7
|
+
import inspect
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import threading
|
|
11
|
+
from collections import OrderedDict
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from typing import Any, ParamSpec, TypeVar
|
|
14
|
+
|
|
15
|
+
from pydantic import BaseModel
|
|
16
|
+
|
|
17
|
+
from sentinel.detector import DriftReport, detect_drift
|
|
18
|
+
from sentinel.llm_fallback import SchemaMappingProvider
|
|
19
|
+
from synthesizer.patcher import PatchPlan, apply_patch_plan_in_memory, build_patch_plan
|
|
20
|
+
|
|
21
|
+
_logger = logging.getLogger("selfheal_api")
|
|
22
|
+
|
|
23
|
+
P = ParamSpec("P")
|
|
24
|
+
R = TypeVar("R")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def compute_drift_fingerprint(report: DriftReport) -> str:
|
|
28
|
+
items = sorted(
|
|
29
|
+
(
|
|
30
|
+
str(issue.kind),
|
|
31
|
+
tuple(str(s) for s in issue.path),
|
|
32
|
+
issue.expected_type,
|
|
33
|
+
issue.observed_kind,
|
|
34
|
+
tuple(str(s) for s in issue.candidate_source_path)
|
|
35
|
+
if issue.candidate_source_path is not None
|
|
36
|
+
else (),
|
|
37
|
+
)
|
|
38
|
+
for issue in report.issues
|
|
39
|
+
)
|
|
40
|
+
canonical = json.dumps(
|
|
41
|
+
{"model": report.model_name, "issues": items},
|
|
42
|
+
separators=(",", ":"),
|
|
43
|
+
).encode("utf-8")
|
|
44
|
+
return hashlib.sha256(canonical).hexdigest()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _resolve_future(fut: asyncio.Future[None]) -> None:
|
|
48
|
+
if not fut.done():
|
|
49
|
+
fut.set_result(None)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class _InFlightEntry:
|
|
53
|
+
__slots__ = ("async_waiters", "event")
|
|
54
|
+
|
|
55
|
+
def __init__(self) -> None:
|
|
56
|
+
self.event = threading.Event()
|
|
57
|
+
self.async_waiters: list[
|
|
58
|
+
tuple[asyncio.AbstractEventLoop, asyncio.Future[None]]
|
|
59
|
+
] = []
|
|
60
|
+
|
|
61
|
+
def notify_all(self) -> None:
|
|
62
|
+
self.event.set()
|
|
63
|
+
for loop, fut in self.async_waiters:
|
|
64
|
+
if not loop.is_closed():
|
|
65
|
+
with contextlib.suppress(RuntimeError):
|
|
66
|
+
loop.call_soon_threadsafe(_resolve_future, fut)
|
|
67
|
+
self.async_waiters.clear()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class DriftDeduplicator:
|
|
71
|
+
def __init__(self, max_fingerprints: int = 1024) -> None:
|
|
72
|
+
if max_fingerprints < 1:
|
|
73
|
+
raise ValueError("max_fingerprints must be >= 1")
|
|
74
|
+
self._max_fingerprints = max_fingerprints
|
|
75
|
+
self._lock = threading.Lock()
|
|
76
|
+
self._seen: OrderedDict[str, PatchPlan | None] = OrderedDict()
|
|
77
|
+
self._in_flight: dict[str, _InFlightEntry] = {}
|
|
78
|
+
|
|
79
|
+
def reserve(
|
|
80
|
+
self, fingerprint: str
|
|
81
|
+
) -> tuple[bool, PatchPlan | _InFlightEntry | None]:
|
|
82
|
+
"""Non-blocking reservation: returns (True, None) if caller owns resolution,
|
|
83
|
+
(False, plan) if already cached, or (False, entry) if another caller is in-flight.
|
|
84
|
+
"""
|
|
85
|
+
with self._lock:
|
|
86
|
+
if fingerprint in self._seen:
|
|
87
|
+
self._seen.move_to_end(fingerprint)
|
|
88
|
+
return False, self._seen[fingerprint]
|
|
89
|
+
if fingerprint in self._in_flight:
|
|
90
|
+
return False, self._in_flight[fingerprint]
|
|
91
|
+
self._in_flight[fingerprint] = _InFlightEntry()
|
|
92
|
+
return True, None
|
|
93
|
+
|
|
94
|
+
def begin(self, fingerprint: str) -> tuple[bool, PatchPlan | None]:
|
|
95
|
+
while True:
|
|
96
|
+
is_owner, result = self.reserve(fingerprint)
|
|
97
|
+
if is_owner:
|
|
98
|
+
return True, None
|
|
99
|
+
if isinstance(result, _InFlightEntry):
|
|
100
|
+
result.event.wait()
|
|
101
|
+
continue
|
|
102
|
+
return False, result
|
|
103
|
+
|
|
104
|
+
async def begin_async(
|
|
105
|
+
self, fingerprint: str, *, timeout: float | None = None
|
|
106
|
+
) -> tuple[bool, PatchPlan | None]:
|
|
107
|
+
"""Async reservation that waits without occupying an executor thread."""
|
|
108
|
+
loop = asyncio.get_running_loop()
|
|
109
|
+
deadline = loop.time() + timeout if timeout is not None else None
|
|
110
|
+
while True:
|
|
111
|
+
with self._lock:
|
|
112
|
+
if fingerprint in self._seen:
|
|
113
|
+
self._seen.move_to_end(fingerprint)
|
|
114
|
+
return False, self._seen[fingerprint]
|
|
115
|
+
if fingerprint not in self._in_flight:
|
|
116
|
+
self._in_flight[fingerprint] = _InFlightEntry()
|
|
117
|
+
return True, None
|
|
118
|
+
entry = self._in_flight[fingerprint]
|
|
119
|
+
fut = loop.create_future()
|
|
120
|
+
entry.async_waiters.append((loop, fut))
|
|
121
|
+
try:
|
|
122
|
+
if deadline is not None:
|
|
123
|
+
remaining = deadline - loop.time()
|
|
124
|
+
if remaining <= 0:
|
|
125
|
+
raise TimeoutError(
|
|
126
|
+
f"Timed out waiting for drift deduplication of {fingerprint[:8]}"
|
|
127
|
+
)
|
|
128
|
+
async with asyncio.timeout(remaining):
|
|
129
|
+
await fut
|
|
130
|
+
else:
|
|
131
|
+
await fut
|
|
132
|
+
finally:
|
|
133
|
+
with self._lock:
|
|
134
|
+
with contextlib.suppress(ValueError):
|
|
135
|
+
entry.async_waiters.remove((loop, fut))
|
|
136
|
+
|
|
137
|
+
def complete(self, fingerprint: str, plan: PatchPlan) -> None:
|
|
138
|
+
with self._lock:
|
|
139
|
+
self._seen[fingerprint] = plan
|
|
140
|
+
self._seen.move_to_end(fingerprint)
|
|
141
|
+
if len(self._seen) > self._max_fingerprints:
|
|
142
|
+
self._seen.popitem(last=False)
|
|
143
|
+
entry = self._in_flight.pop(fingerprint, None)
|
|
144
|
+
if entry is not None:
|
|
145
|
+
entry.notify_all()
|
|
146
|
+
|
|
147
|
+
def abort(self, fingerprint: str) -> None:
|
|
148
|
+
with self._lock:
|
|
149
|
+
entry = self._in_flight.pop(fingerprint, None)
|
|
150
|
+
if entry is not None:
|
|
151
|
+
entry.notify_all()
|
|
152
|
+
|
|
153
|
+
def check_and_record(self, fingerprint: str) -> bool:
|
|
154
|
+
with self._lock:
|
|
155
|
+
if fingerprint in self._seen:
|
|
156
|
+
self._seen.move_to_end(fingerprint)
|
|
157
|
+
return False
|
|
158
|
+
self._seen[fingerprint] = None
|
|
159
|
+
if len(self._seen) > self._max_fingerprints:
|
|
160
|
+
self._seen.popitem(last=False)
|
|
161
|
+
return True
|
|
162
|
+
|
|
163
|
+
def get_cached_plan(self, fingerprint: str) -> PatchPlan | None:
|
|
164
|
+
with self._lock:
|
|
165
|
+
return self._seen.get(fingerprint)
|
|
166
|
+
|
|
167
|
+
def set_cached_plan(self, fingerprint: str, plan: PatchPlan) -> None:
|
|
168
|
+
self.complete(fingerprint, plan)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _extract_payload_from_call(
|
|
172
|
+
func: Callable[..., Any], args: tuple[Any, ...], kwargs: dict[str, Any]
|
|
173
|
+
) -> tuple[str | bytes | dict[str, Any] | None, str, int | None]:
|
|
174
|
+
if "payload" in kwargs:
|
|
175
|
+
val = kwargs["payload"]
|
|
176
|
+
if isinstance(val, (str, bytes, dict)):
|
|
177
|
+
return val, "kwarg", None
|
|
178
|
+
return None, "none", None
|
|
179
|
+
|
|
180
|
+
sig = inspect.signature(func)
|
|
181
|
+
param_names = list(sig.parameters.keys())
|
|
182
|
+
pos_idx = 0
|
|
183
|
+
if param_names and param_names[0] in ("self", "cls"):
|
|
184
|
+
pos_idx = 1
|
|
185
|
+
if len(args) > pos_idx:
|
|
186
|
+
val = args[pos_idx]
|
|
187
|
+
if isinstance(val, (str, bytes, dict)):
|
|
188
|
+
return val, "pos", pos_idx
|
|
189
|
+
return None, "none", None
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _replace_payload_in_call(
|
|
193
|
+
args: tuple[Any, ...],
|
|
194
|
+
kwargs: dict[str, Any],
|
|
195
|
+
mode: str,
|
|
196
|
+
pos_idx: int | None,
|
|
197
|
+
new_payload: str | bytes | dict[str, Any],
|
|
198
|
+
) -> tuple[tuple[Any, ...], dict[str, Any]]:
|
|
199
|
+
if mode == "kwarg":
|
|
200
|
+
updated_kwargs = dict(kwargs)
|
|
201
|
+
updated_kwargs["payload"] = new_payload
|
|
202
|
+
return args, updated_kwargs
|
|
203
|
+
if mode == "pos" and pos_idx is not None:
|
|
204
|
+
args_list = list(args)
|
|
205
|
+
args_list[pos_idx] = new_payload
|
|
206
|
+
return tuple(args_list), kwargs
|
|
207
|
+
return args, kwargs
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _safe_invoke_callback(
|
|
211
|
+
on_drift: Callable[[DriftReport, str], None] | None,
|
|
212
|
+
report: DriftReport,
|
|
213
|
+
fingerprint: str,
|
|
214
|
+
) -> None:
|
|
215
|
+
if on_drift is None:
|
|
216
|
+
return
|
|
217
|
+
try:
|
|
218
|
+
on_drift(report, fingerprint)
|
|
219
|
+
except Exception as exc: # noqa: BLE001
|
|
220
|
+
_logger.warning(
|
|
221
|
+
"on_drift callback raised for model=%s fp=%s: %s",
|
|
222
|
+
report.model_name,
|
|
223
|
+
fingerprint[:8],
|
|
224
|
+
exc,
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _normalize_raw_payload(
|
|
229
|
+
raw_payload: str | bytes | dict[str, Any],
|
|
230
|
+
model_cls: type[BaseModel],
|
|
231
|
+
plan: PatchPlan,
|
|
232
|
+
) -> str | bytes | dict[str, Any]:
|
|
233
|
+
if isinstance(raw_payload, dict):
|
|
234
|
+
return apply_patch_plan_in_memory(raw_payload, plan, root_model=model_cls)
|
|
235
|
+
try:
|
|
236
|
+
decoded = (
|
|
237
|
+
raw_payload.decode("utf-8")
|
|
238
|
+
if isinstance(raw_payload, bytes)
|
|
239
|
+
else raw_payload
|
|
240
|
+
)
|
|
241
|
+
parsed = json.loads(decoded)
|
|
242
|
+
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
243
|
+
return raw_payload
|
|
244
|
+
if not isinstance(parsed, dict):
|
|
245
|
+
return raw_payload
|
|
246
|
+
norm_dict = apply_patch_plan_in_memory(parsed, plan, root_model=model_cls)
|
|
247
|
+
serialized = json.dumps(norm_dict)
|
|
248
|
+
return serialized.encode("utf-8") if isinstance(raw_payload, bytes) else serialized
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def selfheal_guard(
|
|
252
|
+
model_cls: type[BaseModel],
|
|
253
|
+
*,
|
|
254
|
+
on_drift: Callable[[DriftReport, str], None] | None = None,
|
|
255
|
+
mapping_provider: SchemaMappingProvider | None = None,
|
|
256
|
+
deduplicator: DriftDeduplicator | None = None,
|
|
257
|
+
normalize: bool = False,
|
|
258
|
+
) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
|
259
|
+
dedup = deduplicator or DriftDeduplicator()
|
|
260
|
+
|
|
261
|
+
def decorator(func: Callable[P, R]) -> Callable[P, R]:
|
|
262
|
+
if inspect.iscoroutinefunction(func):
|
|
263
|
+
|
|
264
|
+
@functools.wraps(func)
|
|
265
|
+
async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> Any:
|
|
266
|
+
raw_payload, mode, pos_idx = _extract_payload_from_call(
|
|
267
|
+
func, args, kwargs
|
|
268
|
+
)
|
|
269
|
+
if raw_payload is not None:
|
|
270
|
+
report = detect_drift(model_cls, raw_payload, mapping_provider=None)
|
|
271
|
+
if report.has_drift:
|
|
272
|
+
pre_fp = compute_drift_fingerprint(report)
|
|
273
|
+
is_new, plan = await dedup.begin_async(pre_fp)
|
|
274
|
+
if is_new:
|
|
275
|
+
try:
|
|
276
|
+
enriched = (
|
|
277
|
+
await asyncio.to_thread(
|
|
278
|
+
detect_drift,
|
|
279
|
+
model_cls,
|
|
280
|
+
raw_payload,
|
|
281
|
+
mapping_provider,
|
|
282
|
+
)
|
|
283
|
+
if mapping_provider is not None
|
|
284
|
+
else report
|
|
285
|
+
)
|
|
286
|
+
plan = build_patch_plan(enriched, root_model=model_cls)
|
|
287
|
+
dedup.complete(pre_fp, plan)
|
|
288
|
+
except BaseException:
|
|
289
|
+
dedup.abort(pre_fp)
|
|
290
|
+
raise
|
|
291
|
+
_safe_invoke_callback(
|
|
292
|
+
on_drift, enriched, compute_drift_fingerprint(enriched)
|
|
293
|
+
)
|
|
294
|
+
if normalize and plan is not None:
|
|
295
|
+
norm_payload = _normalize_raw_payload(
|
|
296
|
+
raw_payload, model_cls, plan
|
|
297
|
+
)
|
|
298
|
+
args_out, kwargs_out = _replace_payload_in_call(
|
|
299
|
+
args, kwargs, mode, pos_idx, norm_payload
|
|
300
|
+
)
|
|
301
|
+
return await func(*args_out, **kwargs_out)
|
|
302
|
+
return await func(*args, **kwargs)
|
|
303
|
+
|
|
304
|
+
return async_wrapper # type: ignore[return-value]
|
|
305
|
+
|
|
306
|
+
@functools.wraps(func)
|
|
307
|
+
def sync_wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
|
308
|
+
raw_payload, mode, pos_idx = _extract_payload_from_call(
|
|
309
|
+
func, args, kwargs
|
|
310
|
+
)
|
|
311
|
+
if raw_payload is not None:
|
|
312
|
+
report = detect_drift(model_cls, raw_payload, mapping_provider=None)
|
|
313
|
+
if report.has_drift:
|
|
314
|
+
pre_fp = compute_drift_fingerprint(report)
|
|
315
|
+
is_new, plan = dedup.begin(pre_fp)
|
|
316
|
+
if is_new:
|
|
317
|
+
try:
|
|
318
|
+
enriched = (
|
|
319
|
+
detect_drift(
|
|
320
|
+
model_cls, raw_payload, mapping_provider=mapping_provider
|
|
321
|
+
)
|
|
322
|
+
if mapping_provider is not None
|
|
323
|
+
else report
|
|
324
|
+
)
|
|
325
|
+
plan = build_patch_plan(enriched, root_model=model_cls)
|
|
326
|
+
dedup.complete(pre_fp, plan)
|
|
327
|
+
except BaseException:
|
|
328
|
+
dedup.abort(pre_fp)
|
|
329
|
+
raise
|
|
330
|
+
_safe_invoke_callback(
|
|
331
|
+
on_drift, enriched, compute_drift_fingerprint(enriched)
|
|
332
|
+
)
|
|
333
|
+
if normalize and plan is not None:
|
|
334
|
+
norm_payload = _normalize_raw_payload(
|
|
335
|
+
raw_payload, model_cls, plan
|
|
336
|
+
)
|
|
337
|
+
args_out, kwargs_out = _replace_payload_in_call(
|
|
338
|
+
args, kwargs, mode, pos_idx, norm_payload
|
|
339
|
+
)
|
|
340
|
+
return func(*args_out, **kwargs_out)
|
|
341
|
+
return func(*args, **kwargs)
|
|
342
|
+
|
|
343
|
+
return sync_wrapper
|
|
344
|
+
|
|
345
|
+
return decorator
|
sentinel/llm_fallback.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import http.client
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import threading
|
|
9
|
+
import urllib.error
|
|
10
|
+
import urllib.request
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from typing import Any, Protocol, runtime_checkable
|
|
13
|
+
|
|
14
|
+
_logger = logging.getLogger("selfheal_api")
|
|
15
|
+
|
|
16
|
+
_SAFE_KEY_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
|
|
17
|
+
_UUID_RE = re.compile(
|
|
18
|
+
r"^(?:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|[0-9a-fA-F]{32})$"
|
|
19
|
+
)
|
|
20
|
+
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
|
|
21
|
+
|
|
22
|
+
_VALID_PRIMITIVE_VALUES: frozenset[str] = frozenset(
|
|
23
|
+
{
|
|
24
|
+
"<null>",
|
|
25
|
+
"<bool>",
|
|
26
|
+
"<int>",
|
|
27
|
+
"<float>",
|
|
28
|
+
"<str>",
|
|
29
|
+
"<int_str>",
|
|
30
|
+
"<float_str>",
|
|
31
|
+
"<bool_str>",
|
|
32
|
+
"<iso_datetime>",
|
|
33
|
+
"<empty_list>",
|
|
34
|
+
"<empty_object>",
|
|
35
|
+
}
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def is_safe_key_segment(segment: str) -> bool:
|
|
40
|
+
if not _SAFE_KEY_RE.match(segment):
|
|
41
|
+
return False
|
|
42
|
+
if segment.isdigit():
|
|
43
|
+
return False
|
|
44
|
+
if _UUID_RE.match(segment):
|
|
45
|
+
return False
|
|
46
|
+
return True
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _is_safe_dot_key(dot_key: str) -> bool:
|
|
50
|
+
parts = dot_key.split(".")
|
|
51
|
+
if not parts:
|
|
52
|
+
return False
|
|
53
|
+
for part in parts:
|
|
54
|
+
if _EMAIL_RE.match(part) or _UUID_RE.match(part):
|
|
55
|
+
return False
|
|
56
|
+
if part.isdigit():
|
|
57
|
+
# Top-level digit-only keys or multi-digit IDs (>= 4 digits) are customer identifiers,
|
|
58
|
+
# whereas small nested numeric segments (e.g. "0", "1") represent list indices.
|
|
59
|
+
if len(parts) == 1 or len(part) >= 4:
|
|
60
|
+
return False
|
|
61
|
+
continue
|
|
62
|
+
if not is_safe_key_segment(part):
|
|
63
|
+
return False
|
|
64
|
+
return True
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def sanitize_candidate_paths(
|
|
68
|
+
candidates: list[tuple[tuple[str | int, ...], str]],
|
|
69
|
+
) -> dict[str, tuple[tuple[str | int, ...], str]]:
|
|
70
|
+
sanitized: dict[str, tuple[tuple[str | int, ...], str]] = {}
|
|
71
|
+
for path, kind in candidates:
|
|
72
|
+
if not path:
|
|
73
|
+
continue
|
|
74
|
+
if any(isinstance(seg, str) and not is_safe_key_segment(seg) for seg in path):
|
|
75
|
+
continue
|
|
76
|
+
if not is_valid_redacted_kind(kind):
|
|
77
|
+
raise ValueError(f"Unsafe non-redacted kind value: {kind!r}")
|
|
78
|
+
dot_key = ".".join(str(seg) for seg in path)
|
|
79
|
+
sanitized[dot_key] = (path, kind)
|
|
80
|
+
return sanitized
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def is_valid_redacted_kind(value: str) -> bool:
|
|
84
|
+
if value in _VALID_PRIMITIVE_VALUES:
|
|
85
|
+
return True
|
|
86
|
+
if value.startswith("list[") and value.endswith("]"):
|
|
87
|
+
inner = value[5:-1]
|
|
88
|
+
if not inner:
|
|
89
|
+
return False
|
|
90
|
+
parts = inner.split("|")
|
|
91
|
+
return all(part in _VALID_PRIMITIVE_VALUES for part in parts)
|
|
92
|
+
return False
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@runtime_checkable
|
|
96
|
+
class SchemaMappingProvider(Protocol):
|
|
97
|
+
def resolve_opaque_mappings(
|
|
98
|
+
self,
|
|
99
|
+
model_name: str,
|
|
100
|
+
missing_fields: dict[str, str],
|
|
101
|
+
extra_observed_kinds: dict[str, str],
|
|
102
|
+
) -> dict[str, tuple[str | int, ...]]: ...
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class DeterministicMappingProvider:
|
|
106
|
+
def __init__(
|
|
107
|
+
self,
|
|
108
|
+
mappings: dict[str, tuple[str | int, ...]]
|
|
109
|
+
| Callable[[str, dict[str, str], dict[str, str]], dict[str, tuple[str | int, ...]]],
|
|
110
|
+
) -> None:
|
|
111
|
+
self._mappings = mappings
|
|
112
|
+
|
|
113
|
+
def resolve_opaque_mappings(
|
|
114
|
+
self,
|
|
115
|
+
model_name: str,
|
|
116
|
+
missing_fields: dict[str, str],
|
|
117
|
+
extra_observed_kinds: dict[str, str],
|
|
118
|
+
) -> dict[str, tuple[str | int, ...]]:
|
|
119
|
+
for key, kind_val in extra_observed_kinds.items():
|
|
120
|
+
if not is_valid_redacted_kind(kind_val):
|
|
121
|
+
raise ValueError(f"Unredacted value detected at {key!r}: {kind_val!r}")
|
|
122
|
+
if callable(self._mappings):
|
|
123
|
+
return self._mappings(model_name, missing_fields, extra_observed_kinds)
|
|
124
|
+
result: dict[str, tuple[str | int, ...]] = {}
|
|
125
|
+
for missing_key in missing_fields:
|
|
126
|
+
if missing_key in self._mappings:
|
|
127
|
+
result[missing_key] = self._mappings[missing_key]
|
|
128
|
+
return result
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class AnthropicSchemaMappingProvider:
|
|
132
|
+
def __init__(
|
|
133
|
+
self,
|
|
134
|
+
api_key: str | None = None,
|
|
135
|
+
model: str = "claude-3-5-haiku-latest",
|
|
136
|
+
timeout_s: float = 5.0,
|
|
137
|
+
endpoint: str = "https://api.anthropic.com/v1/messages",
|
|
138
|
+
max_calls: int = 50,
|
|
139
|
+
) -> None:
|
|
140
|
+
if max_calls < 0:
|
|
141
|
+
raise ValueError("max_calls must be >= 0")
|
|
142
|
+
self._api_key = api_key or os.environ.get("ANTHROPIC_API_KEY", "")
|
|
143
|
+
self._model = model
|
|
144
|
+
self._timeout_s = timeout_s
|
|
145
|
+
self._endpoint = endpoint
|
|
146
|
+
self._max_calls = max_calls
|
|
147
|
+
self._calls_made = 0
|
|
148
|
+
self._lock = threading.Lock()
|
|
149
|
+
|
|
150
|
+
def set_max_calls(self, max_calls: int) -> None:
|
|
151
|
+
if max_calls < 0:
|
|
152
|
+
raise ValueError("max_calls must be >= 0")
|
|
153
|
+
with self._lock:
|
|
154
|
+
self._max_calls = max_calls
|
|
155
|
+
|
|
156
|
+
def resolve_opaque_mappings(
|
|
157
|
+
self,
|
|
158
|
+
model_name: str,
|
|
159
|
+
missing_fields: dict[str, str],
|
|
160
|
+
extra_observed_kinds: dict[str, str],
|
|
161
|
+
) -> dict[str, tuple[str | int, ...]]:
|
|
162
|
+
for key, kind_val in extra_observed_kinds.items():
|
|
163
|
+
if not is_valid_redacted_kind(kind_val):
|
|
164
|
+
raise ValueError(f"Unredacted value detected at {key!r}: {kind_val!r}")
|
|
165
|
+
safe_extra_kinds = {
|
|
166
|
+
k: v for k, v in extra_observed_kinds.items() if _is_safe_dot_key(k)
|
|
167
|
+
}
|
|
168
|
+
if not self._api_key or not missing_fields or not safe_extra_kinds:
|
|
169
|
+
return {}
|
|
170
|
+
with self._lock:
|
|
171
|
+
if self._calls_made >= self._max_calls:
|
|
172
|
+
_logger.warning(
|
|
173
|
+
"AnthropicSchemaMappingProvider call cap (%d) reached; failing closed",
|
|
174
|
+
self._max_calls,
|
|
175
|
+
)
|
|
176
|
+
return {}
|
|
177
|
+
self._calls_made += 1
|
|
178
|
+
|
|
179
|
+
prompt = (
|
|
180
|
+
"Map missing Pydantic model fields to candidate extra JSON paths using ONLY "
|
|
181
|
+
"the structural types provided. Return ONLY a JSON object mapping missing_field_key "
|
|
182
|
+
"to extra_path_key.\n"
|
|
183
|
+
f"Model: {model_name}\n"
|
|
184
|
+
f"Missing fields: {json.dumps(missing_fields)}\n"
|
|
185
|
+
f"Extra structural kinds: {json.dumps(safe_extra_kinds)}\n"
|
|
186
|
+
)
|
|
187
|
+
body = json.dumps(
|
|
188
|
+
{
|
|
189
|
+
"model": self._model,
|
|
190
|
+
"max_tokens": 256,
|
|
191
|
+
"messages": [{"role": "user", "content": prompt}],
|
|
192
|
+
}
|
|
193
|
+
).encode("utf-8")
|
|
194
|
+
|
|
195
|
+
req = urllib.request.Request(
|
|
196
|
+
self._endpoint,
|
|
197
|
+
data=body,
|
|
198
|
+
headers={
|
|
199
|
+
"content-type": "application/json",
|
|
200
|
+
"x-api-key": self._api_key,
|
|
201
|
+
"anthropic-version": "2023-06-01",
|
|
202
|
+
},
|
|
203
|
+
method="POST",
|
|
204
|
+
)
|
|
205
|
+
try:
|
|
206
|
+
with urllib.request.urlopen(req, timeout=self._timeout_s) as resp:
|
|
207
|
+
raw_resp = resp.read().decode("utf-8")
|
|
208
|
+
payload: Any = json.loads(raw_resp)
|
|
209
|
+
if not isinstance(payload, dict):
|
|
210
|
+
return {}
|
|
211
|
+
content_list = payload.get("content", [])
|
|
212
|
+
if not isinstance(content_list, list) or not content_list:
|
|
213
|
+
return {}
|
|
214
|
+
first_item = content_list[0]
|
|
215
|
+
if not isinstance(first_item, dict):
|
|
216
|
+
return {}
|
|
217
|
+
text = first_item.get("text", "")
|
|
218
|
+
if not isinstance(text, str) or not text.strip():
|
|
219
|
+
return {}
|
|
220
|
+
cleaned = text.strip()
|
|
221
|
+
if cleaned.startswith("```"):
|
|
222
|
+
cleaned = re.sub(r"^```(?:json)?\s*", "", cleaned)
|
|
223
|
+
cleaned = re.sub(r"\s*```$", "", cleaned)
|
|
224
|
+
mapping_raw: Any = json.loads(cleaned)
|
|
225
|
+
if not isinstance(mapping_raw, dict):
|
|
226
|
+
return {}
|
|
227
|
+
resolved: dict[str, tuple[str | int, ...]] = {}
|
|
228
|
+
for m_key, e_key in mapping_raw.items():
|
|
229
|
+
if (
|
|
230
|
+
isinstance(m_key, str)
|
|
231
|
+
and isinstance(e_key, str)
|
|
232
|
+
and m_key in missing_fields
|
|
233
|
+
and e_key in safe_extra_kinds
|
|
234
|
+
):
|
|
235
|
+
resolved[m_key] = tuple(
|
|
236
|
+
int(part) if part.isdigit() else part for part in e_key.split(".")
|
|
237
|
+
)
|
|
238
|
+
return resolved
|
|
239
|
+
except (
|
|
240
|
+
urllib.error.URLError,
|
|
241
|
+
http.client.HTTPException,
|
|
242
|
+
OSError,
|
|
243
|
+
TimeoutError,
|
|
244
|
+
json.JSONDecodeError,
|
|
245
|
+
KeyError,
|
|
246
|
+
AttributeError,
|
|
247
|
+
TypeError,
|
|
248
|
+
ValueError,
|
|
249
|
+
) as exc:
|
|
250
|
+
_logger.warning(
|
|
251
|
+
"AnthropicSchemaMappingProvider fallback failed for model=%s missing=%d: %s",
|
|
252
|
+
model_name,
|
|
253
|
+
len(missing_fields),
|
|
254
|
+
exc,
|
|
255
|
+
)
|
|
256
|
+
return {}
|
synthesizer/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from synthesizer.openapi_emitter import (
|
|
2
|
+
OpenAPIPatchSpec,
|
|
3
|
+
emit_openapi_document,
|
|
4
|
+
emit_openapi_schema_patch,
|
|
5
|
+
)
|
|
6
|
+
from synthesizer.patcher import (
|
|
7
|
+
PatchAction,
|
|
8
|
+
PatchPlan,
|
|
9
|
+
PatchResult,
|
|
10
|
+
VerificationResult,
|
|
11
|
+
apply_patch_plan_in_memory,
|
|
12
|
+
build_patch_plan,
|
|
13
|
+
synthesize_patch,
|
|
14
|
+
verify_patch,
|
|
15
|
+
)
|
|
16
|
+
from synthesizer.zod_emitter import synthesize_zod_preprocessor
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"OpenAPIPatchSpec",
|
|
20
|
+
"PatchAction",
|
|
21
|
+
"PatchPlan",
|
|
22
|
+
"PatchResult",
|
|
23
|
+
"VerificationResult",
|
|
24
|
+
"apply_patch_plan_in_memory",
|
|
25
|
+
"build_patch_plan",
|
|
26
|
+
"emit_openapi_document",
|
|
27
|
+
"emit_openapi_schema_patch",
|
|
28
|
+
"synthesize_patch",
|
|
29
|
+
"synthesize_zod_preprocessor",
|
|
30
|
+
"verify_patch",
|
|
31
|
+
]
|