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,426 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import hmac
5
+ import ipaddress
6
+ import json
7
+ import logging
8
+ import smtplib
9
+ import threading
10
+ import urllib.error
11
+ import urllib.parse
12
+ import urllib.request
13
+ from collections.abc import Sequence
14
+ from email.message import EmailMessage
15
+ from typing import Any, Protocol
16
+
17
+ from pydantic import BaseModel, ConfigDict
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ class DriftAlert(BaseModel):
23
+ """Zero-PII structural alert payload for schema drift notifications."""
24
+
25
+ model_config = ConfigDict(frozen=True)
26
+
27
+ org_id: str
28
+ model_name: str
29
+ fingerprint: str
30
+ issue_count: int
31
+ issue_kinds: tuple[str, ...]
32
+ pr_url: str | None = None
33
+
34
+
35
+ def format_slack_drift_alert(alert: DriftAlert) -> dict[str, Any]:
36
+ """Build a Slack Block Kit payload containing strictly structural metadata."""
37
+ kinds_text = ", ".join(alert.issue_kinds) if alert.issue_kinds else "none"
38
+ summary_text = (
39
+ f"Schema drift detected for {alert.model_name} "
40
+ f"(org={alert.org_id}, issues={alert.issue_count}, fp={alert.fingerprint})"
41
+ )
42
+
43
+ fields: list[dict[str, str]] = [
44
+ {"type": "mrkdwn", "text": f"*Org ID:*\n`{alert.org_id}`"},
45
+ {"type": "mrkdwn", "text": f"*Model:*\n`{alert.model_name}`"},
46
+ {"type": "mrkdwn", "text": f"*Fingerprint:*\n`{alert.fingerprint}`"},
47
+ {"type": "mrkdwn", "text": f"*Issue Count:*\n{alert.issue_count}"},
48
+ {"type": "mrkdwn", "text": f"*Issue Kinds:*\n`{kinds_text}`"},
49
+ ]
50
+
51
+ blocks: list[dict[str, Any]] = [
52
+ {
53
+ "type": "header",
54
+ "text": {
55
+ "type": "plain_text",
56
+ "text": f"Schema Drift Detected: {alert.model_name}",
57
+ },
58
+ },
59
+ {
60
+ "type": "section",
61
+ "fields": fields,
62
+ },
63
+ ]
64
+
65
+ if alert.pr_url is not None:
66
+ blocks.append(
67
+ {
68
+ "type": "section",
69
+ "text": {
70
+ "type": "mrkdwn",
71
+ "text": f"*Remediation PR:* <{alert.pr_url}|View Pull Request>",
72
+ },
73
+ }
74
+ )
75
+
76
+ return {
77
+ "text": summary_text,
78
+ "blocks": blocks,
79
+ }
80
+
81
+
82
+ class AlertNotifier(Protocol):
83
+ """Protocol for delivering zero-PII schema drift alerts."""
84
+
85
+ def notify(self, alert: DriftAlert) -> bool: ...
86
+
87
+
88
+ class MockAlertNotifier:
89
+ """In-memory thread-safe notifier for deterministic unit testing."""
90
+
91
+ def __init__(self, *, should_succeed: bool = True) -> None:
92
+ self._lock = threading.Lock()
93
+ self._should_succeed = should_succeed
94
+ self.alerts: list[DriftAlert] = []
95
+
96
+ def notify(self, alert: DriftAlert) -> bool:
97
+ with self._lock:
98
+ self.alerts.append(alert)
99
+ return self._should_succeed
100
+
101
+
102
+ def _validate_webhook_config(
103
+ webhook_url: str, timeout_s: float, *, allow_private_urls: bool = False
104
+ ) -> None:
105
+ parsed = urllib.parse.urlparse(webhook_url)
106
+ if parsed.scheme != "https" or not parsed.netloc or not parsed.hostname:
107
+ raise ValueError("webhook_url must be a valid https:// URL")
108
+ if timeout_s <= 0:
109
+ raise ValueError("timeout_s must be > 0")
110
+ if not allow_private_urls:
111
+ host = parsed.hostname.strip().lower().rstrip(".")
112
+ if host == "localhost" or host.endswith((".local", ".internal")):
113
+ raise ValueError("webhook_url must not target localhost or internal hosts")
114
+ try:
115
+ addr = ipaddress.ip_address(host)
116
+ except ValueError:
117
+ return
118
+ if (
119
+ addr.is_private
120
+ or addr.is_loopback
121
+ or addr.is_link_local
122
+ or addr.is_multicast
123
+ or addr.is_reserved
124
+ or addr.is_unspecified
125
+ ):
126
+ raise ValueError("webhook_url must not target private or link-local IP addresses")
127
+
128
+
129
+ def _post_json(
130
+ *,
131
+ webhook_url: str,
132
+ body: bytes,
133
+ headers: dict[str, str],
134
+ timeout_s: float,
135
+ alert: DriftAlert,
136
+ channel_label: str,
137
+ ) -> bool:
138
+ request = urllib.request.Request(
139
+ webhook_url,
140
+ data=body,
141
+ headers=headers,
142
+ method="POST",
143
+ )
144
+ try:
145
+ with urllib.request.urlopen(request, timeout=timeout_s) as response:
146
+ status = getattr(response, "status", 200)
147
+ return 200 <= int(status) < 300
148
+ except (urllib.error.URLError, OSError) as exc:
149
+ logger.warning(
150
+ "%s drift alert delivery failed for org=%s model=%s: %s",
151
+ channel_label,
152
+ alert.org_id,
153
+ alert.model_name,
154
+ type(exc).__name__,
155
+ )
156
+ return False
157
+
158
+
159
+ class UrllibSlackNotifier:
160
+ """Slack webhook notifier using stdlib urllib with fail-closed error handling."""
161
+
162
+ def __init__(
163
+ self,
164
+ webhook_url: str,
165
+ *,
166
+ timeout_s: float = 5.0,
167
+ allow_private_urls: bool = False,
168
+ ) -> None:
169
+ _validate_webhook_config(
170
+ webhook_url, timeout_s, allow_private_urls=allow_private_urls
171
+ )
172
+ self._webhook_url = webhook_url
173
+ self._timeout_s = timeout_s
174
+
175
+ def notify(self, alert: DriftAlert) -> bool:
176
+ payload = format_slack_drift_alert(alert)
177
+ body = json.dumps(payload).encode("utf-8")
178
+ return _post_json(
179
+ webhook_url=self._webhook_url,
180
+ body=body,
181
+ headers={"Content-Type": "application/json"},
182
+ timeout_s=self._timeout_s,
183
+ alert=alert,
184
+ channel_label="Slack",
185
+ )
186
+
187
+
188
+ class SignedWebhookNotifier:
189
+ """Generic JSON webhook notifier with optional HMAC-SHA256 request signing."""
190
+
191
+ def __init__(
192
+ self,
193
+ webhook_url: str,
194
+ *,
195
+ signing_secret: str = "",
196
+ timeout_s: float = 5.0,
197
+ allow_private_urls: bool = False,
198
+ ) -> None:
199
+ _validate_webhook_config(
200
+ webhook_url, timeout_s, allow_private_urls=allow_private_urls
201
+ )
202
+ self._webhook_url = webhook_url
203
+ self._signing_secret = signing_secret
204
+ self._timeout_s = timeout_s
205
+
206
+ def notify(self, alert: DriftAlert) -> bool:
207
+ body = json.dumps(
208
+ alert.model_dump(mode="json"),
209
+ separators=(",", ":"),
210
+ ).encode("utf-8")
211
+ headers: dict[str, str] = {"Content-Type": "application/json"}
212
+ if self._signing_secret:
213
+ digest = hmac.new(
214
+ self._signing_secret.encode("utf-8"),
215
+ body,
216
+ hashlib.sha256,
217
+ ).hexdigest()
218
+ headers["X-SelfHeal-Signature"] = f"sha256={digest}"
219
+
220
+ return _post_json(
221
+ webhook_url=self._webhook_url,
222
+ body=body,
223
+ headers=headers,
224
+ timeout_s=self._timeout_s,
225
+ alert=alert,
226
+ channel_label="Signed webhook",
227
+ )
228
+
229
+
230
+ _PD_SEVERITY_MAP: dict[str, str] = {
231
+ "type_mismatch": "critical",
232
+ "invalid_json": "critical",
233
+ "missing_field": "error",
234
+ "nullability_drift": "error",
235
+ "enum_drift": "error",
236
+ "extra_field": "warning",
237
+ }
238
+ _PD_SEVERITY_RANK = {"critical": 3, "error": 2, "warning": 1, "info": 0}
239
+
240
+
241
+ def _alert_severity(alert: DriftAlert) -> str:
242
+ """Highest PagerDuty severity implied by the alert's issue kinds."""
243
+ best = "info"
244
+ for kind in alert.issue_kinds:
245
+ sev = _PD_SEVERITY_MAP.get(kind, "error")
246
+ if _PD_SEVERITY_RANK.get(sev, 0) > _PD_SEVERITY_RANK.get(best, 0):
247
+ best = sev
248
+ return best
249
+
250
+
251
+ RecipientResolver = Any # Callable[[str], str | None]
252
+
253
+
254
+ class EmailAlertNotifier:
255
+ """SMTP email notifier for zero-PII drift alerts and weekly digests.
256
+
257
+ ``recipient`` may be a static address or a callable ``org_id -> address``
258
+ resolving per-org ``alert_email`` settings with env defaults upstream.
259
+ """
260
+
261
+ def __init__(
262
+ self,
263
+ *,
264
+ smtp_host: str,
265
+ smtp_port: int = 587,
266
+ smtp_user: str = "",
267
+ smtp_password: str = "",
268
+ from_addr: str,
269
+ recipient: str | RecipientResolver,
270
+ use_starttls: bool = True,
271
+ timeout_s: float = 10.0,
272
+ ) -> None:
273
+ if not smtp_host or not from_addr:
274
+ raise ValueError("smtp_host and from_addr are required")
275
+ self._smtp_host = smtp_host
276
+ self._smtp_port = smtp_port
277
+ self._smtp_user = smtp_user
278
+ self._smtp_password = smtp_password
279
+ self._from_addr = from_addr
280
+ self._recipient = recipient
281
+ self._use_starttls = use_starttls
282
+ self._timeout_s = timeout_s
283
+
284
+ def _resolve(self, org_id: str) -> str | None:
285
+ if callable(self._recipient):
286
+ result = self._recipient(org_id)
287
+ return result if isinstance(result, str) and result else None
288
+ return self._recipient or None
289
+
290
+ def _smtp_send(
291
+ self, to_addr: str, subject: str, body_text: str, *, log_org: str
292
+ ) -> bool:
293
+ msg = EmailMessage()
294
+ msg["From"] = self._from_addr
295
+ msg["To"] = to_addr
296
+ msg["Subject"] = subject
297
+ msg.set_content(body_text)
298
+ try:
299
+ with smtplib.SMTP(self._smtp_host, self._smtp_port, timeout=self._timeout_s) as smtp:
300
+ if self._use_starttls:
301
+ smtp.starttls()
302
+ if self._smtp_user:
303
+ smtp.login(self._smtp_user, self._smtp_password)
304
+ smtp.send_message(msg)
305
+ return True
306
+ except (OSError, smtplib.SMTPException) as exc:
307
+ logger.warning(
308
+ "Email delivery failed for org=%s: %s", log_org, type(exc).__name__
309
+ )
310
+ return False
311
+
312
+ def notify(self, alert: DriftAlert) -> bool:
313
+ to_addr = self._resolve(alert.org_id)
314
+ if to_addr is None:
315
+ logger.info("No email recipient for org=%s; skipping", alert.org_id)
316
+ return False
317
+ kinds = ", ".join(alert.issue_kinds) if alert.issue_kinds else "none"
318
+ pr_line = f"\nRemediation PR: {alert.pr_url}\n" if alert.pr_url else ""
319
+ body = (
320
+ f"Schema drift detected.\n\n"
321
+ f"Org: {alert.org_id}\n"
322
+ f"Model: {alert.model_name}\n"
323
+ f"Fingerprint: {alert.fingerprint}\n"
324
+ f"Issues: {alert.issue_count} ({kinds})\n"
325
+ f"{pr_line}"
326
+ )
327
+ return self._smtp_send(
328
+ to_addr,
329
+ f"[SelfHeal] Drift: {alert.model_name} ({alert.org_id})",
330
+ body,
331
+ log_org=alert.org_id,
332
+ )
333
+
334
+ def send_digest(self, org_id: str, subject: str, body_text: str) -> bool:
335
+ """Send a weekly digest email; returns False when no recipient resolves."""
336
+ to_addr = self._resolve(org_id)
337
+ if to_addr is None:
338
+ return False
339
+ return self._smtp_send(to_addr, subject, body_text, log_org=org_id)
340
+
341
+
342
+ class PagerDutyNotifier:
343
+ """PagerDuty Events API v2 trigger notifier for drift alerts."""
344
+
345
+ def __init__(
346
+ self,
347
+ *,
348
+ routing_key: str | RecipientResolver,
349
+ events_url: str = "https://events.pagerduty.com/v2/enqueue",
350
+ timeout_s: float = 5.0,
351
+ allow_private_urls: bool = False,
352
+ ) -> None:
353
+ _validate_webhook_config(
354
+ events_url, timeout_s, allow_private_urls=allow_private_urls
355
+ )
356
+ self._routing_key = routing_key
357
+ self._events_url = events_url
358
+ self._timeout_s = timeout_s
359
+
360
+ def _resolve_key(self, org_id: str) -> str | None:
361
+ if callable(self._routing_key):
362
+ result = self._routing_key(org_id)
363
+ return result if isinstance(result, str) and result else None
364
+ return self._routing_key or None
365
+
366
+ def notify(self, alert: DriftAlert) -> bool:
367
+ routing_key = self._resolve_key(alert.org_id)
368
+ if routing_key is None:
369
+ logger.info("No PagerDuty routing key for org=%s; skipping", alert.org_id)
370
+ return False
371
+ kinds = ", ".join(alert.issue_kinds) if alert.issue_kinds else "none"
372
+ payload = {
373
+ "routing_key": routing_key,
374
+ "event_action": "trigger",
375
+ "dedup_key": alert.fingerprint,
376
+ "client": "selfheal",
377
+ "payload": {
378
+ "summary": (
379
+ f"Schema drift: {alert.model_name} "
380
+ f"({alert.issue_count} issues)"
381
+ ),
382
+ "severity": _alert_severity(alert),
383
+ "source": f"selfheal:{alert.org_id}",
384
+ "component": alert.model_name,
385
+ "group": alert.org_id,
386
+ "custom_details": {
387
+ "org_id": alert.org_id,
388
+ "fingerprint": alert.fingerprint,
389
+ "issue_count": alert.issue_count,
390
+ "issue_kinds": kinds,
391
+ "pr_url": alert.pr_url or "",
392
+ },
393
+ },
394
+ }
395
+ body = json.dumps(payload).encode("utf-8")
396
+ return _post_json(
397
+ webhook_url=self._events_url,
398
+ body=body,
399
+ headers={"Content-Type": "application/json"},
400
+ timeout_s=self._timeout_s,
401
+ alert=alert,
402
+ channel_label="PagerDuty",
403
+ )
404
+
405
+
406
+ class CompositeAlertNotifier:
407
+ """Fan-out notifier that delivers alerts across multiple independent channels."""
408
+
409
+ def __init__(self, notifiers: Sequence[AlertNotifier]) -> None:
410
+ self._notifiers = tuple(notifiers)
411
+
412
+ def notify(self, alert: DriftAlert) -> bool:
413
+ any_succeeded = False
414
+ for notifier in self._notifiers:
415
+ try:
416
+ if notifier.notify(alert):
417
+ any_succeeded = True
418
+ except Exception as exc:
419
+ logger.warning(
420
+ "Alert notifier %s raised %s for org=%s model=%s",
421
+ type(notifier).__name__,
422
+ type(exc).__name__,
423
+ alert.org_id,
424
+ alert.model_name,
425
+ )
426
+ return any_succeeded
@@ -0,0 +1,277 @@
1
+ from __future__ import annotations
2
+
3
+ import threading
4
+ from typing import Any
5
+
6
+ from pydantic import BaseModel, ConfigDict
7
+
8
+ from selfheal_api.billing import BillingStore
9
+ from selfheal_api.github_app import GitHubAppClient, InstallationRecord, InstallationRegistry
10
+ from selfheal_api.ledger import DriftLedger
11
+ from selfheal_api.notifier import AlertNotifier, DriftAlert
12
+ from sentinel.detector import DriftReport, detect_drift
13
+ from sentinel.guard import compute_drift_fingerprint
14
+ from synthesizer.openapi_emitter import emit_openapi_schema_patch
15
+ from synthesizer.patcher import PatchResult, synthesize_patch, verify_patch
16
+ from synthesizer.zod_emitter import synthesize_zod_preprocessor
17
+
18
+
19
+ class RemediationRequest(BaseModel):
20
+ """Input parameters for an automated schema-drift remediation run."""
21
+
22
+ model_config = ConfigDict(frozen=True)
23
+
24
+ org_id: str
25
+ repo: str
26
+ model_name: str
27
+ model_source: str
28
+ base_branch: str = "main"
29
+
30
+
31
+ class RemediationOutcome(BaseModel):
32
+ """Structured result of an automated remediation pipeline execution."""
33
+
34
+ model_config = ConfigDict(frozen=True)
35
+
36
+ status: str
37
+ fingerprint: str
38
+ pr_url: str | None = None
39
+ zod_adapter: str | None = None
40
+ openapi_yaml: str | None = None
41
+ detail: str = ""
42
+
43
+
44
+ def _split_owner_repo(repo: str, record: InstallationRecord) -> tuple[str, str]:
45
+ if "/" in repo:
46
+ owner, repo_name = repo.split("/", 1)
47
+ return owner, repo_name
48
+ owner = record.account_login or record.org_id
49
+ return owner, repo
50
+
51
+
52
+ def _format_pr_body(
53
+ req: RemediationRequest,
54
+ fingerprint: str,
55
+ report: DriftReport,
56
+ patch_res: PatchResult,
57
+ zod_adapter: str,
58
+ openapi_yaml: str,
59
+ ) -> str:
60
+ kinds = ", ".join(str(issue.kind) for issue in report.issues) or "none"
61
+ return (
62
+ f"## Automated Schema Drift Remediation\n\n"
63
+ f"- **Model:** `{req.model_name}`\n"
64
+ f"- **Fingerprint:** `{fingerprint}`\n"
65
+ f"- **Issues ({len(report.issues)}):** `{kinds}`\n\n"
66
+ f"### Patched Pydantic Model\n\n"
67
+ f"```python\n{patch_res.patched_source.rstrip()}\n```\n\n"
68
+ f"### Zod Preprocessor\n\n"
69
+ f"```typescript\n{zod_adapter.rstrip()}\n```\n\n"
70
+ f"### OpenAPI 3.1.0 Patch\n\n"
71
+ f"```yaml\n{openapi_yaml.rstrip()}\n```\n"
72
+ )
73
+
74
+
75
+ class RemediationPipeline:
76
+ """Orchestrates installation checks, quota checks, drift patching, verification, and PRs."""
77
+
78
+ def __init__(
79
+ self,
80
+ billing_store: BillingStore,
81
+ installation_registry: InstallationRegistry,
82
+ github_client: GitHubAppClient,
83
+ drift_ledger: DriftLedger,
84
+ notifier: AlertNotifier | None = None,
85
+ ) -> None:
86
+ self.billing_store = billing_store
87
+ self.installation_registry = installation_registry
88
+ self.github_client = github_client
89
+ self.drift_ledger = drift_ledger
90
+ self.notifier = notifier
91
+ self._lock = threading.Lock()
92
+ self._in_flight: set[tuple[str, str, str]] = set()
93
+ self._completed_prs: dict[tuple[str, str, str], str] = {}
94
+
95
+ def run(
96
+ self,
97
+ req: RemediationRequest,
98
+ expected_model: type[BaseModel],
99
+ drifted_payload: dict[str, Any],
100
+ canonical_payload: dict[str, Any] | None = None,
101
+ ) -> RemediationOutcome:
102
+ """Execute the end-to-end remediation pipeline for a drifted payload."""
103
+ record = self.installation_registry.get_by_org(req.org_id)
104
+ if record is None:
105
+ return RemediationOutcome(
106
+ status="rejected_installation",
107
+ fingerprint="",
108
+ detail=f"No GitHub App installation found for org {req.org_id!r}",
109
+ )
110
+ if record.suspended:
111
+ return RemediationOutcome(
112
+ status="rejected_installation",
113
+ fingerprint="",
114
+ detail=f"GitHub App installation is suspended for org {req.org_id!r}",
115
+ )
116
+ if req.repo not in record.repositories:
117
+ return RemediationOutcome(
118
+ status="rejected_installation",
119
+ fingerprint="",
120
+ detail=f"Repository {req.repo!r} is not enabled for org {req.org_id!r}",
121
+ )
122
+
123
+ limits = self.billing_store.get_limits(req.org_id)
124
+ summary = self.drift_ledger.get_org_summary(req.org_id)
125
+ distinct_models = set(summary.top_models.keys())
126
+ if (
127
+ req.model_name not in distinct_models
128
+ and len(distinct_models) >= limits.max_models
129
+ ) or summary.prs_opened >= limits.max_models:
130
+ return RemediationOutcome(
131
+ status="rejected_quota",
132
+ fingerprint="",
133
+ detail=(
134
+ f"Quota exceeded for org {req.org_id!r}: "
135
+ f"{len(distinct_models)}/{limits.max_models} models"
136
+ ),
137
+ )
138
+
139
+ report = detect_drift(expected_model, drifted_payload)
140
+ fingerprint = compute_drift_fingerprint(report)
141
+ issue_kinds = tuple(str(issue.kind) for issue in report.issues)
142
+
143
+ if not report.has_drift:
144
+ self.drift_ledger.record_event(
145
+ org_id=req.org_id,
146
+ model_name=req.model_name,
147
+ fingerprint=fingerprint,
148
+ has_drift=False,
149
+ issue_count=0,
150
+ issue_kinds=(),
151
+ )
152
+ return RemediationOutcome(
153
+ status="no_drift",
154
+ fingerprint=fingerprint,
155
+ detail=f"No schema drift detected for {req.model_name}",
156
+ )
157
+
158
+ dedup_key = (req.org_id, req.model_name, fingerprint)
159
+ with self._lock:
160
+ if dedup_key in self._completed_prs:
161
+ completed_url = self._completed_prs[dedup_key] or None
162
+ return RemediationOutcome(
163
+ status="deduplicated",
164
+ fingerprint=fingerprint,
165
+ pr_url=completed_url,
166
+ detail=f"Remediation PR already opened for {req.model_name}",
167
+ )
168
+ if dedup_key in self._in_flight:
169
+ return RemediationOutcome(
170
+ status="deduplicated",
171
+ fingerprint=fingerprint,
172
+ detail=f"Remediation already in flight for {req.model_name}",
173
+ )
174
+
175
+ limits = self.billing_store.get_limits(req.org_id)
176
+ summary = self.drift_ledger.get_org_summary(req.org_id)
177
+ in_flight_for_org = [k for k in self._in_flight if k[0] == req.org_id]
178
+ distinct_models = set(summary.top_models.keys()) | {
179
+ k[1] for k in in_flight_for_org
180
+ }
181
+ if (
182
+ req.model_name not in distinct_models
183
+ and len(distinct_models) >= limits.max_models
184
+ ) or (summary.prs_opened + len(in_flight_for_org)) >= limits.max_models:
185
+ return RemediationOutcome(
186
+ status="rejected_quota",
187
+ fingerprint=fingerprint,
188
+ detail=(
189
+ f"Quota exceeded for org {req.org_id!r}: "
190
+ f"{len(distinct_models)}/{limits.max_models} models"
191
+ ),
192
+ )
193
+ self._in_flight.add(dedup_key)
194
+
195
+ try:
196
+ patch_res = synthesize_patch(
197
+ req.model_source, report, root_model=expected_model
198
+ )
199
+ verification = verify_patch(patch_res, drifted_payload, canonical_payload)
200
+ if not verification.passed:
201
+ self.drift_ledger.record_event(
202
+ org_id=req.org_id,
203
+ model_name=req.model_name,
204
+ fingerprint=fingerprint,
205
+ has_drift=True,
206
+ issue_count=len(report.issues),
207
+ issue_kinds=issue_kinds,
208
+ )
209
+ return RemediationOutcome(
210
+ status="failed_verification",
211
+ fingerprint=fingerprint,
212
+ detail=verification.error_detail
213
+ or "Patched model failed verification",
214
+ )
215
+
216
+ zod_adapter = synthesize_zod_preprocessor(patch_res.plan)
217
+ openapi_spec = emit_openapi_schema_patch(expected_model, patch_res.plan)
218
+
219
+ owner, repo_name = _split_owner_repo(req.repo, record)
220
+ pr_title = f"fix(selfheal): remediate schema drift for {req.model_name}"
221
+ pr_head = f"selfheal/{req.model_name.lower()}-{fingerprint[:12]}"
222
+ pr_body = _format_pr_body(
223
+ req=req,
224
+ fingerprint=fingerprint,
225
+ report=report,
226
+ patch_res=patch_res,
227
+ zod_adapter=zod_adapter,
228
+ openapi_yaml=openapi_spec.yaml_snippet,
229
+ )
230
+ pr_payload = self.github_client.open_pull_request(
231
+ owner=owner,
232
+ repo=repo_name,
233
+ title=pr_title,
234
+ head=pr_head,
235
+ base=req.base_branch,
236
+ body=pr_body,
237
+ draft=True,
238
+ )
239
+ raw_url = pr_payload.get("html_url")
240
+ pr_url = str(raw_url) if isinstance(raw_url, str) and raw_url else None
241
+
242
+ self.drift_ledger.record_event(
243
+ org_id=req.org_id,
244
+ model_name=req.model_name,
245
+ fingerprint=fingerprint,
246
+ has_drift=True,
247
+ issue_count=len(report.issues),
248
+ issue_kinds=issue_kinds,
249
+ pr_url=pr_url,
250
+ )
251
+
252
+ with self._lock:
253
+ self._completed_prs[dedup_key] = pr_url or ""
254
+
255
+ if self.notifier is not None:
256
+ self.notifier.notify(
257
+ DriftAlert(
258
+ org_id=req.org_id,
259
+ model_name=req.model_name,
260
+ fingerprint=fingerprint,
261
+ issue_count=len(report.issues),
262
+ issue_kinds=issue_kinds,
263
+ pr_url=pr_url,
264
+ )
265
+ )
266
+
267
+ return RemediationOutcome(
268
+ status="pr_opened",
269
+ fingerprint=fingerprint,
270
+ pr_url=pr_url,
271
+ zod_adapter=zod_adapter,
272
+ openapi_yaml=openapi_spec.yaml_snippet,
273
+ detail=f"Opened remediation PR for {req.model_name}",
274
+ )
275
+ finally:
276
+ with self._lock:
277
+ self._in_flight.discard(dedup_key)