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.
@@ -0,0 +1,297 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import io
5
+ from collections.abc import Awaitable, Callable, Iterable
6
+ from typing import Any
7
+
8
+ from pydantic import BaseModel
9
+
10
+ from sentinel.detector import DriftReport, detect_drift
11
+ from sentinel.guard import (
12
+ DriftDeduplicator,
13
+ _normalize_raw_payload,
14
+ _safe_invoke_callback,
15
+ compute_drift_fingerprint,
16
+ )
17
+ from sentinel.llm_fallback import SchemaMappingProvider
18
+ from synthesizer.patcher import build_patch_plan
19
+
20
+ ASGIApp = Callable[
21
+ [
22
+ dict[str, Any],
23
+ Callable[..., Awaitable[dict[str, Any]]],
24
+ Callable[..., Awaitable[None]],
25
+ ],
26
+ Awaitable[None],
27
+ ]
28
+ WSGIStartResponse = Callable[..., Any]
29
+ WSGIApp = Callable[[dict[str, Any], WSGIStartResponse], Iterable[bytes]]
30
+
31
+
32
+ class RouteBinding(BaseModel, frozen=True):
33
+ """Binding between an HTTP path/method set and a target Pydantic model."""
34
+
35
+ path: str
36
+ model_cls: type[BaseModel]
37
+ methods: frozenset[str] = frozenset({"POST", "PUT", "PATCH"})
38
+ normalize: bool = True
39
+
40
+
41
+ def _build_route_index(
42
+ routes: dict[str, type[BaseModel]] | list[RouteBinding],
43
+ *,
44
+ default_normalize: bool,
45
+ ) -> dict[tuple[str, str], RouteBinding]:
46
+ bindings = (
47
+ [
48
+ RouteBinding(path=path, model_cls=model_cls, normalize=default_normalize)
49
+ for path, model_cls in routes.items()
50
+ ]
51
+ if isinstance(routes, dict)
52
+ else routes
53
+ )
54
+ index: dict[tuple[str, str], RouteBinding] = {}
55
+ for binding in bindings:
56
+ for method in binding.methods:
57
+ index[(binding.path, method.upper())] = binding
58
+ return index
59
+
60
+
61
+ def _update_asgi_content_length(scope: dict[str, Any], new_length: int) -> dict[str, Any]:
62
+ raw_headers = scope.get("headers")
63
+ if not isinstance(raw_headers, (list, tuple)):
64
+ return scope
65
+ updated_headers = [
66
+ (b"content-length", str(new_length).encode("ascii"))
67
+ if isinstance(name, bytes) and name.lower() == b"content-length"
68
+ else (name, value)
69
+ for name, value in raw_headers
70
+ ]
71
+ updated_scope = dict(scope)
72
+ updated_scope["headers"] = updated_headers
73
+ return updated_scope
74
+
75
+
76
+ def _maybe_normalize_bytes(
77
+ body: bytes,
78
+ binding: RouteBinding,
79
+ plan: Any,
80
+ *,
81
+ normalize: bool,
82
+ ) -> bytes:
83
+ if not (normalize and binding.normalize and plan is not None):
84
+ return body
85
+ normalized = _normalize_raw_payload(body, binding.model_cls, plan)
86
+ return normalized if isinstance(normalized, bytes) else body
87
+
88
+
89
+ class SelfHealASGIMiddleware:
90
+ """Framework-agnostic ASGI middleware for schema-drift detection and normalization."""
91
+
92
+ def __init__(
93
+ self,
94
+ app: ASGIApp,
95
+ routes: dict[str, type[BaseModel]] | list[RouteBinding],
96
+ *,
97
+ normalize: bool = True,
98
+ on_drift: Callable[[DriftReport, str], None] | None = None,
99
+ mapping_provider: SchemaMappingProvider | None = None,
100
+ deduplicator: DriftDeduplicator | None = None,
101
+ max_body_bytes: int = 1_048_576,
102
+ ) -> None:
103
+ self.app = app
104
+ self._normalize = normalize
105
+ self._on_drift = on_drift
106
+ self._mapping_provider = mapping_provider
107
+ self._deduplicator = deduplicator or DriftDeduplicator()
108
+ self._max_body_bytes = max_body_bytes
109
+ self._route_index = _build_route_index(routes, default_normalize=normalize)
110
+
111
+ async def __call__(
112
+ self,
113
+ scope: dict[str, Any],
114
+ receive: Callable[..., Awaitable[dict[str, Any]]],
115
+ send: Callable[..., Awaitable[None]],
116
+ ) -> None:
117
+ if scope.get("type") != "http":
118
+ await self.app(scope, receive, send)
119
+ return
120
+
121
+ path = str(scope.get("path", ""))
122
+ method = str(scope.get("method", "GET")).upper()
123
+ binding = self._route_index.get((path, method))
124
+ if binding is None:
125
+ await self.app(scope, receive, send)
126
+ return
127
+
128
+ chunks: list[bytes] = []
129
+ total_bytes = 0
130
+ more_body = True
131
+ disconnect_msg: dict[str, Any] | None = None
132
+ while more_body:
133
+ message = await receive()
134
+ msg_type = message.get("type")
135
+ if msg_type == "http.disconnect":
136
+ disconnect_msg = message
137
+ break
138
+ if msg_type == "http.request":
139
+ chunk = message.get("body", b"")
140
+ if isinstance(chunk, (bytes, bytearray)):
141
+ total_bytes += len(chunk)
142
+ if total_bytes > self._max_body_bytes:
143
+ await send(
144
+ {
145
+ "type": "http.response.start",
146
+ "status": 413,
147
+ "headers": [(b"content-type", b"application/json")],
148
+ }
149
+ )
150
+ await send(
151
+ {
152
+ "type": "http.response.body",
153
+ "body": b'{"error":"request body too large"}',
154
+ }
155
+ )
156
+ return
157
+ chunks.append(bytes(chunk))
158
+ more_body = bool(message.get("more_body", False))
159
+
160
+ body = b"".join(chunks)
161
+ if body:
162
+ report = detect_drift(binding.model_cls, body, mapping_provider=None)
163
+ if report.has_drift:
164
+ pre_fp = compute_drift_fingerprint(report)
165
+ is_new, plan = await self._deduplicator.begin_async(pre_fp)
166
+ if is_new:
167
+ try:
168
+ enriched = (
169
+ await asyncio.to_thread(
170
+ detect_drift,
171
+ binding.model_cls,
172
+ body,
173
+ self._mapping_provider,
174
+ )
175
+ if self._mapping_provider is not None
176
+ else report
177
+ )
178
+ plan = build_patch_plan(enriched, root_model=binding.model_cls)
179
+ self._deduplicator.complete(pre_fp, plan)
180
+ except BaseException:
181
+ self._deduplicator.abort(pre_fp)
182
+ raise
183
+ _safe_invoke_callback(
184
+ self._on_drift, enriched, compute_drift_fingerprint(enriched)
185
+ )
186
+ body = _maybe_normalize_bytes(
187
+ body, binding, plan, normalize=self._normalize
188
+ )
189
+
190
+ forwarded_scope = _update_asgi_content_length(scope, len(body))
191
+ body_sent = False
192
+
193
+ async def replay_receive() -> dict[str, Any]:
194
+ nonlocal body_sent
195
+ if not body_sent:
196
+ body_sent = True
197
+ return {"type": "http.request", "body": body, "more_body": False}
198
+ if disconnect_msg is not None:
199
+ return disconnect_msg
200
+ return await receive()
201
+
202
+ await self.app(forwarded_scope, replay_receive, send)
203
+
204
+
205
+ class SelfHealWSGIMiddleware:
206
+ """Framework-agnostic WSGI middleware for schema-drift detection and normalization."""
207
+
208
+ def __init__(
209
+ self,
210
+ app: WSGIApp,
211
+ routes: dict[str, type[BaseModel]] | list[RouteBinding],
212
+ *,
213
+ normalize: bool = True,
214
+ on_drift: Callable[[DriftReport, str], None] | None = None,
215
+ mapping_provider: SchemaMappingProvider | None = None,
216
+ deduplicator: DriftDeduplicator | None = None,
217
+ max_body_bytes: int = 1_048_576,
218
+ ) -> None:
219
+ self.app = app
220
+ self._normalize = normalize
221
+ self._on_drift = on_drift
222
+ self._mapping_provider = mapping_provider
223
+ self._deduplicator = deduplicator or DriftDeduplicator()
224
+ self._max_body_bytes = max_body_bytes
225
+ self._route_index = _build_route_index(routes, default_normalize=normalize)
226
+
227
+ def __call__(
228
+ self,
229
+ environ: dict[str, Any],
230
+ start_response: WSGIStartResponse,
231
+ ) -> Iterable[bytes]:
232
+ path = str(environ.get("PATH_INFO", ""))
233
+ method = str(environ.get("REQUEST_METHOD", "GET")).upper()
234
+ binding = self._route_index.get((path, method))
235
+ if binding is None:
236
+ return self.app(environ, start_response)
237
+
238
+ wsgi_input = environ.get("wsgi.input")
239
+ if wsgi_input is None:
240
+ return self.app(environ, start_response)
241
+
242
+ raw_length = environ.get("CONTENT_LENGTH")
243
+ if raw_length not in (None, ""):
244
+ try:
245
+ content_length = int(raw_length)
246
+ except (TypeError, ValueError):
247
+ content_length = 0
248
+ if content_length < 0 or content_length > self._max_body_bytes:
249
+ status_str = (
250
+ "413 Payload Too Large"
251
+ if content_length > self._max_body_bytes
252
+ else "400 Bad Request"
253
+ )
254
+ start_response(status_str, [("Content-Type", "application/json")])
255
+ return [b'{"error":"invalid or oversized body"}']
256
+ raw_body = wsgi_input.read(content_length)
257
+ else:
258
+ raw_body = wsgi_input.read(self._max_body_bytes + 1)
259
+ if len(raw_body) > self._max_body_bytes:
260
+ start_response(
261
+ "413 Payload Too Large", [("Content-Type", "application/json")]
262
+ )
263
+ return [b'{"error":"request body too large"}']
264
+
265
+ body = raw_body.encode("utf-8") if isinstance(raw_body, str) else bytes(raw_body)
266
+ if body:
267
+ report = detect_drift(binding.model_cls, body, mapping_provider=None)
268
+ if report.has_drift:
269
+ pre_fp = compute_drift_fingerprint(report)
270
+ is_new, plan = self._deduplicator.begin(pre_fp)
271
+ if is_new:
272
+ try:
273
+ enriched = (
274
+ detect_drift(
275
+ binding.model_cls,
276
+ body,
277
+ mapping_provider=self._mapping_provider,
278
+ )
279
+ if self._mapping_provider is not None
280
+ else report
281
+ )
282
+ plan = build_patch_plan(enriched, root_model=binding.model_cls)
283
+ self._deduplicator.complete(pre_fp, plan)
284
+ except BaseException:
285
+ self._deduplicator.abort(pre_fp)
286
+ raise
287
+ _safe_invoke_callback(
288
+ self._on_drift, enriched, compute_drift_fingerprint(enriched)
289
+ )
290
+ body = _maybe_normalize_bytes(
291
+ body, binding, plan, normalize=self._normalize
292
+ )
293
+
294
+ updated_environ = dict(environ)
295
+ updated_environ["wsgi.input"] = io.BytesIO(body)
296
+ updated_environ["CONTENT_LENGTH"] = str(len(body))
297
+ return self.app(updated_environ, start_response)
@@ -0,0 +1,333 @@
1
+ """``selfheal models init`` — infer Pydantic / Zod models from JSON payload samples.
2
+
3
+ CLI-only over user-supplied payload files (ADR-001: the control plane never
4
+ persists payload values). Inference unions field kinds across all supplied
5
+ samples, mirroring ``sentinel.detector._classify_list_kinds`` semantics.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ from dataclasses import dataclass, field
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ _INT_RE = re.compile(r"^[+-]?\d+$")
17
+ _FLOAT_RE = re.compile(r"^[+-]?(?:\d+\.\d+|\d+\.|\.\d+)(?:[eE][+-]?\d+)?$")
18
+ _ISO_DT_RE = re.compile(
19
+ r"^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)?$"
20
+ )
21
+
22
+
23
+ @dataclass
24
+ class FieldSchema:
25
+ """Inferred shape of one object field."""
26
+
27
+ name: str
28
+ py_types: set[str] = field(default_factory=set)
29
+ children: dict[str, FieldSchema] = field(default_factory=dict)
30
+ item: FieldSchema | None = None
31
+ nullable: bool = False
32
+ saw_missing: bool = False
33
+ saw_null: bool = False
34
+ is_object: bool = False
35
+ is_array: bool = False
36
+
37
+ @property
38
+ def optional(self) -> bool:
39
+ return self.nullable or self.saw_missing
40
+
41
+
42
+ def _scalar_py_type(value: Any) -> str:
43
+ if value is None:
44
+ return "None"
45
+ if isinstance(value, bool):
46
+ return "bool"
47
+ if isinstance(value, int):
48
+ return "int"
49
+ if isinstance(value, float):
50
+ return "float"
51
+ if isinstance(value, str):
52
+ stripped = value.strip()
53
+ if _ISO_DT_RE.match(stripped):
54
+ return "datetime"
55
+ if _INT_RE.match(stripped):
56
+ return "str" # keep wire type; pydantic coerces
57
+ if _FLOAT_RE.match(stripped):
58
+ return "str"
59
+ return "str"
60
+ return "Any"
61
+
62
+
63
+ def _zod_scalar(value: Any) -> str:
64
+ if value is None:
65
+ return "z.null()"
66
+ if isinstance(value, bool):
67
+ return "z.boolean()"
68
+ if isinstance(value, int):
69
+ return "z.number().int()"
70
+ if isinstance(value, float):
71
+ return "z.number()"
72
+ if isinstance(value, str):
73
+ return "z.string()"
74
+ return "z.any()"
75
+
76
+
77
+ def _merge_field(dst: FieldSchema, src: FieldSchema) -> None:
78
+ dst.py_types |= src.py_types
79
+ dst.nullable = dst.nullable or src.nullable
80
+ dst.saw_missing = dst.saw_missing or src.saw_missing
81
+ dst.saw_null = dst.saw_null or src.saw_null
82
+ dst.is_object = dst.is_object or src.is_object
83
+ dst.is_array = dst.is_array or src.is_array
84
+ if src.item is not None:
85
+ if dst.item is None:
86
+ dst.item = src.item
87
+ else:
88
+ _merge_field(dst.item, src.item)
89
+ for name, child in src.children.items():
90
+ if name in dst.children:
91
+ _merge_field(dst.children[name], child)
92
+ else:
93
+ dst.children[name] = child
94
+ dst.children[name].saw_missing = True
95
+
96
+
97
+ def infer_object_schema(samples: list[dict[str, Any]]) -> dict[str, FieldSchema]:
98
+ """Infer a field schema map from a list of JSON object samples."""
99
+ root: dict[str, FieldSchema] = {}
100
+ for sample in samples:
101
+ if not isinstance(sample, dict):
102
+ continue
103
+ for key, value in sample.items():
104
+ name = str(key)
105
+ fs = root.get(name)
106
+ if fs is None:
107
+ fs = FieldSchema(name=name)
108
+ root[name] = fs
109
+ if isinstance(value, dict):
110
+ fs.is_object = True
111
+ sub = infer_object_schema([value])
112
+ if not fs.children:
113
+ fs.children = sub
114
+ else:
115
+ for cname, existing in fs.children.items():
116
+ if cname in sub:
117
+ _merge_field(existing, sub[cname])
118
+ else:
119
+ existing.saw_missing = True
120
+ for cname, cfs in sub.items():
121
+ if cname not in fs.children:
122
+ cfs.saw_missing = True
123
+ fs.children[cname] = cfs
124
+ elif isinstance(value, list):
125
+ fs.is_array = True
126
+ item = FieldSchema(name="[]")
127
+ elements = value[:512]
128
+ dict_elems = [e for e in elements if isinstance(e, dict)]
129
+ scalar_types = {
130
+ _scalar_py_type(e)
131
+ for e in elements
132
+ if not isinstance(e, (dict, list)) and e is not None
133
+ }
134
+ if any(isinstance(e, list) for e in elements):
135
+ item.is_array = True
136
+ if scalar_types:
137
+ item.py_types |= scalar_types
138
+ if dict_elems:
139
+ item.is_object = True
140
+ item.children = infer_object_schema(dict_elems)
141
+ if fs.item is None:
142
+ fs.item = item
143
+ else:
144
+ _merge_field(fs.item, item)
145
+ elif value is None:
146
+ fs.saw_null = True
147
+ fs.nullable = True
148
+ else:
149
+ fs.py_types.add(_scalar_py_type(value))
150
+ # fields absent from some samples are optional
151
+ for sample in samples:
152
+ if not isinstance(sample, dict):
153
+ continue
154
+ for name, fs in root.items():
155
+ if name not in sample:
156
+ fs.saw_missing = True
157
+ return root
158
+
159
+
160
+ def load_payload_samples(path: Path) -> list[dict[str, Any]]:
161
+ """Load JSON object samples from a file or directory of *.json files."""
162
+ files: list[Path]
163
+ if path.is_dir():
164
+ files = sorted(p for p in path.rglob("*.json") if p.is_file())
165
+ elif path.is_file():
166
+ files = [path]
167
+ else:
168
+ raise FileNotFoundError(f"payload path not found: {path}")
169
+ samples: list[dict[str, Any]] = []
170
+ for f in files:
171
+ data: Any = json.loads(f.read_text(encoding="utf-8"))
172
+ if isinstance(data, dict):
173
+ samples.append(data)
174
+ elif isinstance(data, list):
175
+ samples.extend(x for x in data if isinstance(x, dict))
176
+ else:
177
+ raise ValueError(f"{f}: expected a JSON object or array of objects")
178
+ if not samples:
179
+ raise ValueError(f"no JSON object samples found under {path}")
180
+ return samples
181
+
182
+
183
+ def _py_annotation(fs: FieldSchema, class_names: dict[int, str]) -> str:
184
+ """Render a Python type annotation for a field schema."""
185
+ inner = _py_base(fs, class_names)
186
+ if fs.optional:
187
+ return f"{inner} | None" if inner != "None" else "None"
188
+ return inner
189
+
190
+
191
+ def _py_base(fs: FieldSchema, class_names: dict[int, str]) -> str:
192
+ types: set[str] = set(fs.py_types)
193
+ if fs.is_object and fs.children:
194
+ types.add(class_names.get(id(fs), "NestedModel"))
195
+ if fs.is_array:
196
+ if fs.item is not None and (fs.item.is_object or fs.item.children):
197
+ item_name = class_names.get(id(fs.item), "ItemModel")
198
+ types.add(f"list[{item_name}]")
199
+ elif fs.item is not None and fs.item.py_types:
200
+ item_types = sorted(t for t in fs.item.py_types if t != "None")
201
+ if item_types:
202
+ item_ann = " | ".join(item_types)
203
+ types.add(f"list[{item_ann}]")
204
+ else:
205
+ types.add("list[Any]")
206
+ else:
207
+ types.add("list[Any]")
208
+ if fs.is_object and not fs.children:
209
+ types.add("dict[str, Any]")
210
+ if not types:
211
+ types.add("Any")
212
+ types.discard("None")
213
+ if not types:
214
+ return "None"
215
+ ordered = sorted(types)
216
+ if len(ordered) == 1:
217
+ return ordered[0]
218
+ return " | ".join(ordered)
219
+
220
+
221
+ def _collect_class_names(root: dict[str, FieldSchema]) -> dict[int, str]:
222
+ """Assign NestedModelN names to object/list-of-object schemas, pre-order."""
223
+ names: dict[int, str] = {}
224
+ counter = 0
225
+
226
+ def visit(fs: FieldSchema) -> None:
227
+ nonlocal counter
228
+ if fs.is_object and fs.children:
229
+ counter += 1
230
+ names[id(fs)] = f"NestedModel{counter}"
231
+ if fs.item is not None:
232
+ visit(fs.item)
233
+ for child in fs.children.values():
234
+ visit(child)
235
+
236
+ for fs in root.values():
237
+ visit(fs)
238
+ return names
239
+
240
+
241
+ def emit_pydantic(model_name: str, root: dict[str, FieldSchema]) -> str:
242
+ """Render a Pydantic module for the inferred root object."""
243
+ class_names = _collect_class_names(root)
244
+ lines = [
245
+ "from __future__ import annotations",
246
+ "",
247
+ "from datetime import datetime",
248
+ "from typing import Any",
249
+ "",
250
+ "from pydantic import BaseModel",
251
+ "",
252
+ ]
253
+
254
+ def emit_class(name: str, fields: dict[str, FieldSchema], indent: str) -> None:
255
+ lines.append(f"{indent}class {name}(BaseModel):")
256
+ if not fields:
257
+ lines.append(f"{indent} pass")
258
+ return
259
+ for fname, fs in fields.items():
260
+ ann = _py_annotation(fs, class_names)
261
+ default = " = None" if fs.optional else ""
262
+ safe = fname if fname.isidentifier() else f'"{fname}"'
263
+ lines.append(f"{indent} {safe}: {ann}{default}")
264
+ lines.append("")
265
+
266
+ # emit nested classes first (post-order so deps exist)
267
+ emitted: set[int] = set()
268
+
269
+ def emit_nested(fs: FieldSchema) -> None:
270
+ if id(fs) in emitted:
271
+ return
272
+ if fs.item is not None:
273
+ emit_nested(fs.item)
274
+ for child in fs.children.values():
275
+ emit_nested(child)
276
+ if fs.is_object and fs.children:
277
+ cname = class_names[id(fs)]
278
+ if id(fs) not in emitted:
279
+ emitted.add(id(fs))
280
+ emit_class(cname, fs.children, "")
281
+
282
+ for fs in root.values():
283
+ emit_nested(fs)
284
+ emit_class(model_name, root, "")
285
+ return "\n".join(lines).rstrip() + "\n"
286
+
287
+
288
+ def _zod_for(fs: FieldSchema, class_names: dict[int, str]) -> str:
289
+ if fs.is_object and fs.children:
290
+ inner = ", ".join(
291
+ f"{k}: {_zod_for(v, class_names)}" for k, v in fs.children.items()
292
+ )
293
+ expr = f"z.object({{{inner}}})"
294
+ elif fs.is_array:
295
+ if fs.item is not None:
296
+ item_expr = _zod_for(fs.item, class_names)
297
+ else:
298
+ item_expr = "z.any()"
299
+ expr = f"z.array({item_expr})"
300
+ elif fs.py_types:
301
+ scalar_exprs = sorted({_zod_scalar_for_type(t) for t in fs.py_types if t != "None"})
302
+ if len(scalar_exprs) == 1:
303
+ expr = scalar_exprs[0]
304
+ else:
305
+ expr = f"z.union([{', '.join(scalar_exprs)}])"
306
+ else:
307
+ expr = "z.any()"
308
+ if fs.optional:
309
+ expr = f"{expr}.optional()"
310
+ return expr
311
+
312
+
313
+ def _zod_scalar_for_type(py_type: str) -> str:
314
+ return {
315
+ "str": "z.string()",
316
+ "int": "z.number().int()",
317
+ "float": "z.number()",
318
+ "bool": "z.boolean()",
319
+ "datetime": "z.string().datetime()",
320
+ "None": "z.null()",
321
+ "Any": "z.any()",
322
+ }.get(py_type, "z.any()")
323
+
324
+
325
+ def emit_zod(model_name: str, root: dict[str, FieldSchema]) -> str:
326
+ """Render a Zod schema module (schema, not the z.preprocess adapter)."""
327
+ class_names = _collect_class_names(root)
328
+ body = ", ".join(f"{k}: {_zod_for(v, class_names)}" for k, v in root.items())
329
+ return (
330
+ 'import { z } from "zod";\n\n'
331
+ f"export const {model_name}Schema = z.object({{{body}}});\n"
332
+ f"export type {model_name} = z.infer<typeof {model_name}Schema>;\n"
333
+ )