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,658 @@
1
+ """Hosted auto-heal: drift webhook -> queued job -> sandboxed pipeline -> PR.
2
+
3
+ EXP-12/T13. ``AutoHealJob`` carries a *reference* (org/repo/model/payload),
4
+ never a live model class — classes cannot cross the sandbox process
5
+ boundary. ``HostedAutoHealRunner`` resolves the repo binding, fetches
6
+ ``model_source`` via the contents API, runs the tenant-code portion in
7
+ :mod:`selfheal_api.sandbox`, then keeps quota checks, the
8
+ installation-token PR write, ledger and notify in the parent process.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import queue
15
+ import threading
16
+ from collections import OrderedDict
17
+ from typing import Any, Protocol
18
+
19
+ from pydantic import BaseModel, ConfigDict
20
+
21
+ from selfheal_api.billing import BillingStore
22
+ from selfheal_api.github_app import (
23
+ GitHubAppClient,
24
+ InstallationRecord,
25
+ InstallationRegistry,
26
+ )
27
+ from selfheal_api.ledger import DriftLedger
28
+ from selfheal_api.notifier import AlertNotifier, DriftAlert
29
+ from selfheal_api.sandbox import SandboxError, run_isolated
30
+ from selfheal_api.server_hosted import HostedStateStore
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ # EXP-18: breaking-change drift kinds require explicit per-org authorization
35
+ # (``auto_heal_allowed_kinds``) before an auto-heal PR may be opened.
36
+ HIGH_IMPACT_KINDS = frozenset(
37
+ {"type_mismatch", "invalid_json", "missing_field", "nullability_drift"}
38
+ )
39
+
40
+
41
+ class AutoHealJob(BaseModel):
42
+ """Queued auto-heal work item. References repo+model, not live classes."""
43
+
44
+ model_config = ConfigDict(frozen=True)
45
+
46
+ org_id: str
47
+ repo: str
48
+ model_name: str
49
+ drifted_payload: dict[str, Any]
50
+ canonical_payload: dict[str, Any] | None = None
51
+
52
+
53
+ class AutoHealOutcome(BaseModel):
54
+ """Structured result of one auto-heal job."""
55
+
56
+ model_config = ConfigDict(frozen=True)
57
+
58
+ status: str
59
+ fingerprint: str = ""
60
+ pr_url: str | None = None
61
+ detail: str = ""
62
+
63
+
64
+ class AutoHealGitHubAuth(Protocol):
65
+ """Subset of :class:`GitHubAppAuth` the runner needs."""
66
+
67
+ def get_file(
68
+ self,
69
+ installation_id: int,
70
+ owner: str,
71
+ repo: str,
72
+ path: str,
73
+ ref: str,
74
+ ) -> tuple[bytes, str] | None: ...
75
+
76
+ def client_for_installation(self, installation_id: int) -> GitHubAppClient: ...
77
+
78
+
79
+ def _split_owner_repo(repo: str, record: InstallationRecord) -> tuple[str, str]:
80
+ if "/" in repo:
81
+ owner, repo_name = repo.split("/", 1)
82
+ return owner, repo_name
83
+ owner = record.account_login or record.org_id
84
+ return owner, repo
85
+
86
+
87
+ def _format_pr_body(
88
+ job: AutoHealJob,
89
+ fingerprint: str,
90
+ issue_kinds: list[str],
91
+ result: dict[str, Any],
92
+ ) -> str:
93
+ kinds = ", ".join(issue_kinds) or "none"
94
+ return (
95
+ "## Automated Schema Drift Remediation\n\n"
96
+ f"- **Org:** `{job.org_id}`\n"
97
+ f"- **Repo:** `{job.repo}`\n"
98
+ f"- **Model:** `{job.model_name}`\n"
99
+ f"- **Fingerprint:** `{fingerprint}`\n"
100
+ f"- **Issues ({len(issue_kinds)}):** `{kinds}`\n\n"
101
+ "### Patched Pydantic Model\n\n"
102
+ f"```python\n{str(result.get('patched_source') or '').rstrip()}\n```\n\n"
103
+ "### Zod Preprocessor\n\n"
104
+ f"```typescript\n{str(result.get('zod_adapter') or '').rstrip()}\n```\n\n"
105
+ "### OpenAPI 3.1.0 Patch\n\n"
106
+ f"```yaml\n{str(result.get('openapi_yaml') or '').rstrip()}\n```\n"
107
+ )
108
+
109
+
110
+ class HostedAutoHealRunner:
111
+ """Parent-process orchestrator for hosted auto-heal jobs."""
112
+
113
+ def __init__(
114
+ self,
115
+ *,
116
+ billing_store: BillingStore,
117
+ installation_registry: InstallationRegistry,
118
+ hosted_store: HostedStateStore,
119
+ drift_ledger: DriftLedger,
120
+ github_auth: AutoHealGitHubAuth,
121
+ notifier: AlertNotifier | None = None,
122
+ sandbox_timeout_seconds: float | None = None,
123
+ ) -> None:
124
+ self.billing_store = billing_store
125
+ self.installation_registry = installation_registry
126
+ self.hosted_store = hosted_store
127
+ self.drift_ledger = drift_ledger
128
+ self.github_auth = github_auth
129
+ self.notifier = notifier
130
+ self.sandbox_timeout_seconds = sandbox_timeout_seconds
131
+ self._lock = threading.Lock()
132
+ self._in_flight: set[tuple[str, str, str]] = set()
133
+ self._completed_prs: dict[tuple[str, str, str], str] = {}
134
+
135
+ def _escalate(
136
+ self,
137
+ job: AutoHealJob,
138
+ fingerprint: str,
139
+ issue_kinds: list[str],
140
+ model_source: str,
141
+ model_path: str,
142
+ detail: str,
143
+ ) -> None:
144
+ """EXP-18: record + notify a held remediation; never opens a PR."""
145
+ issue_count = len(issue_kinds)
146
+ self.drift_ledger.record_event(
147
+ org_id=job.org_id,
148
+ model_name=job.model_name,
149
+ fingerprint=fingerprint,
150
+ has_drift=True,
151
+ issue_count=issue_count,
152
+ issue_kinds=tuple(issue_kinds),
153
+ )
154
+ self.hosted_store.record_repair_run(
155
+ org_id=job.org_id,
156
+ repo=job.repo,
157
+ model_name=job.model_name,
158
+ model_path=model_path,
159
+ fingerprint=fingerprint,
160
+ original_source=model_source,
161
+ status="escalated",
162
+ )
163
+ if self.notifier is not None:
164
+ self.notifier.notify(
165
+ DriftAlert(
166
+ org_id=job.org_id,
167
+ model_name=job.model_name,
168
+ fingerprint=fingerprint,
169
+ issue_count=issue_count,
170
+ issue_kinds=tuple(issue_kinds),
171
+ )
172
+ )
173
+ logger.info(
174
+ "autoheal escalated org=%s model=%s fingerprint=%s: %s",
175
+ job.org_id,
176
+ job.model_name,
177
+ fingerprint[:12],
178
+ detail,
179
+ )
180
+
181
+ def _quota_reject(
182
+ self, org_id: str, model_name: str, in_flight_count: int = 0
183
+ ) -> AutoHealOutcome | None:
184
+ limits = self.billing_store.get_limits(org_id)
185
+ summary = self.drift_ledger.get_org_summary(org_id)
186
+ distinct_models = set(summary.top_models.keys())
187
+ if (
188
+ model_name not in distinct_models
189
+ and len(distinct_models) >= limits.max_models
190
+ ) or (summary.prs_opened + in_flight_count) >= limits.max_models:
191
+ return AutoHealOutcome(
192
+ status="rejected_quota",
193
+ detail=(
194
+ f"Quota exceeded for org {org_id!r}: "
195
+ f"{len(distinct_models)}/{limits.max_models} models"
196
+ ),
197
+ )
198
+ return None
199
+
200
+ def run(self, job: AutoHealJob) -> AutoHealOutcome:
201
+ """Execute one auto-heal job end to end."""
202
+ record = self.installation_registry.get_by_org(job.org_id)
203
+ if record is None:
204
+ return AutoHealOutcome(
205
+ status="rejected_installation",
206
+ detail=f"No GitHub App installation for org {job.org_id!r}",
207
+ )
208
+ if record.suspended:
209
+ return AutoHealOutcome(
210
+ status="rejected_installation",
211
+ detail=f"Installation suspended for org {job.org_id!r}",
212
+ )
213
+ # Kill switch: clearing auto_heal_enabled blocks new runs; jobs
214
+ # already inside the sandbox run to completion.
215
+ if not record.auto_heal_enabled:
216
+ return AutoHealOutcome(
217
+ status="disabled",
218
+ detail=f"Auto-heal disabled for org {job.org_id!r}",
219
+ )
220
+ if job.repo not in record.repositories:
221
+ return AutoHealOutcome(
222
+ status="rejected_installation",
223
+ detail=f"Repository {job.repo!r} not enabled for org {job.org_id!r}",
224
+ )
225
+
226
+ binding = self.hosted_store.get_repo_binding(job.org_id, job.repo)
227
+ if binding is None:
228
+ return AutoHealOutcome(
229
+ status="no_binding",
230
+ detail=f"No repo binding for {job.org_id!r}/{job.repo!r}",
231
+ )
232
+ model_path = binding["models_map"].get(job.model_name)
233
+ if not isinstance(model_path, str) or not model_path:
234
+ return AutoHealOutcome(
235
+ status="unbound_model",
236
+ detail=(
237
+ f"Model {job.model_name!r} has no path mapping in the "
238
+ f"{job.repo!r} binding"
239
+ ),
240
+ )
241
+
242
+ quota = self._quota_reject(job.org_id, job.model_name)
243
+ if quota is not None:
244
+ return quota
245
+
246
+ owner, repo_name = _split_owner_repo(job.repo, record)
247
+ try:
248
+ fetched = self.github_auth.get_file(
249
+ binding["installation_id"],
250
+ owner,
251
+ repo_name,
252
+ model_path,
253
+ binding["base_branch"],
254
+ )
255
+ except Exception as exc: # noqa: BLE001 - surface as job failure
256
+ logger.warning(
257
+ "autoheal source fetch failed org=%s repo=%s path=%s: %s",
258
+ job.org_id,
259
+ job.repo,
260
+ model_path,
261
+ exc,
262
+ )
263
+ return AutoHealOutcome(
264
+ status="source_fetch_failed",
265
+ detail=str(exc)[:300],
266
+ )
267
+ if fetched is None:
268
+ return AutoHealOutcome(
269
+ status="source_missing",
270
+ detail=f"{model_path} not found at {binding['base_branch']}",
271
+ )
272
+ try:
273
+ model_source = fetched[0].decode("utf-8")
274
+ except UnicodeDecodeError:
275
+ return AutoHealOutcome(
276
+ status="source_invalid",
277
+ detail=f"{model_path} is not valid UTF-8",
278
+ )
279
+
280
+ try:
281
+ result = run_isolated(
282
+ {
283
+ "model_name": job.model_name,
284
+ "model_source": model_source,
285
+ "drifted_payload": job.drifted_payload,
286
+ "canonical_payload": job.canonical_payload,
287
+ },
288
+ timeout_seconds=self.sandbox_timeout_seconds,
289
+ )
290
+ except SandboxError as exc:
291
+ logger.warning(
292
+ "autoheal sandbox failed org=%s model=%s: %s",
293
+ job.org_id,
294
+ job.model_name,
295
+ exc,
296
+ )
297
+ return AutoHealOutcome(status="sandbox_error", detail=str(exc)[:300])
298
+
299
+ if not result.get("ok"):
300
+ return AutoHealOutcome(
301
+ status="sandbox_error",
302
+ detail=str(result.get("error") or "sandbox returned ok=false")[:300],
303
+ )
304
+
305
+ fingerprint = str(result.get("fingerprint") or "")
306
+ issue_kinds = [str(k) for k in result.get("issue_kinds") or []]
307
+ has_drift = bool(result.get("has_drift"))
308
+
309
+ if not has_drift:
310
+ self.drift_ledger.record_event(
311
+ org_id=job.org_id,
312
+ model_name=job.model_name,
313
+ fingerprint=fingerprint,
314
+ has_drift=False,
315
+ issue_count=0,
316
+ issue_kinds=(),
317
+ )
318
+ return AutoHealOutcome(
319
+ status="no_drift",
320
+ fingerprint=fingerprint,
321
+ detail=f"No schema drift for {job.model_name}",
322
+ )
323
+
324
+ # EXP-18 gate 1: high-impact drift kinds need explicit org authorization.
325
+ unauthorized = (set(issue_kinds) & HIGH_IMPACT_KINDS) - set(
326
+ record.auto_heal_allowed_kinds
327
+ )
328
+ if unauthorized:
329
+ detail = (
330
+ "high-impact drift kinds require authorization: "
331
+ + ", ".join(sorted(unauthorized))
332
+ )
333
+ self._escalate(
334
+ job, fingerprint, issue_kinds, model_source, model_path, detail
335
+ )
336
+ return AutoHealOutcome(
337
+ status="escalated",
338
+ fingerprint=fingerprint,
339
+ detail=detail,
340
+ )
341
+
342
+ dedup_key = (job.org_id, job.model_name, fingerprint)
343
+ with self._lock:
344
+ if dedup_key in self._completed_prs:
345
+ return AutoHealOutcome(
346
+ status="deduplicated",
347
+ fingerprint=fingerprint,
348
+ pr_url=self._completed_prs[dedup_key] or None,
349
+ detail="Remediation PR already opened",
350
+ )
351
+ if dedup_key in self._in_flight:
352
+ return AutoHealOutcome(
353
+ status="deduplicated",
354
+ fingerprint=fingerprint,
355
+ detail="Remediation already in flight",
356
+ )
357
+ in_flight_for_org = sum(
358
+ 1 for key in self._in_flight if key[0] == job.org_id
359
+ )
360
+ quota = self._quota_reject(job.org_id, job.model_name, in_flight_for_org)
361
+ if quota is not None:
362
+ return quota
363
+ self._in_flight.add(dedup_key)
364
+
365
+ try:
366
+ # EXP-18 gate 2: below confidence (unverified or no-op patch)
367
+ # escalates to a human — notify + hold, no PR.
368
+ if not result.get("verify_passed") or not result.get("patch_applied"):
369
+ detail = str(
370
+ result.get("verify_error")
371
+ or "patch did not modify the model"
372
+ )[:300]
373
+ self._escalate(
374
+ job,
375
+ fingerprint,
376
+ issue_kinds,
377
+ model_source,
378
+ model_path,
379
+ detail,
380
+ )
381
+ return AutoHealOutcome(
382
+ status="escalated",
383
+ fingerprint=fingerprint,
384
+ detail=detail,
385
+ )
386
+
387
+ client = self.github_auth.client_for_installation(
388
+ binding["installation_id"]
389
+ )
390
+ pr_title = (
391
+ f"fix(selfheal): remediate schema drift for {job.model_name}"
392
+ )
393
+ pr_head = f"selfheal/{job.model_name.lower()}-{fingerprint[:12]}"
394
+ pr_body = _format_pr_body(job, fingerprint, issue_kinds, result)
395
+ pr_payload = client.open_pull_request(
396
+ owner=owner,
397
+ repo=repo_name,
398
+ title=pr_title,
399
+ head=pr_head,
400
+ base=binding["base_branch"],
401
+ body=pr_body,
402
+ draft=True,
403
+ )
404
+ raw_url = pr_payload.get("html_url")
405
+ pr_url = (
406
+ str(raw_url) if isinstance(raw_url, str) and raw_url else None
407
+ )
408
+
409
+ self.drift_ledger.record_event(
410
+ org_id=job.org_id,
411
+ model_name=job.model_name,
412
+ fingerprint=fingerprint,
413
+ has_drift=True,
414
+ issue_count=int(result.get("issue_count") or len(issue_kinds)),
415
+ issue_kinds=tuple(issue_kinds),
416
+ pr_url=pr_url,
417
+ )
418
+ with self._lock:
419
+ self._completed_prs[dedup_key] = pr_url or ""
420
+ self.hosted_store.record_repair_run(
421
+ org_id=job.org_id,
422
+ repo=job.repo,
423
+ model_name=job.model_name,
424
+ model_path=model_path,
425
+ fingerprint=fingerprint,
426
+ original_source=model_source,
427
+ status="pr_opened",
428
+ pr_url=pr_url,
429
+ )
430
+
431
+ if self.notifier is not None:
432
+ self.notifier.notify(
433
+ DriftAlert(
434
+ org_id=job.org_id,
435
+ model_name=job.model_name,
436
+ fingerprint=fingerprint,
437
+ issue_count=int(result.get("issue_count") or len(issue_kinds)),
438
+ issue_kinds=tuple(issue_kinds),
439
+ pr_url=pr_url,
440
+ )
441
+ )
442
+
443
+ return AutoHealOutcome(
444
+ status="pr_opened",
445
+ fingerprint=fingerprint,
446
+ pr_url=pr_url,
447
+ detail=f"Opened remediation PR for {job.model_name}",
448
+ )
449
+ finally:
450
+ with self._lock:
451
+ self._in_flight.discard(dedup_key)
452
+
453
+
454
+ class _StopSentinel:
455
+ pass
456
+
457
+
458
+ _STOP_SENTINEL = _StopSentinel()
459
+
460
+
461
+ class AutoHealWorker:
462
+ """Bounded, deduplicating background worker for auto-heal jobs."""
463
+
464
+ _HANDLED_STATUSES = {
465
+ "pr_opened",
466
+ "no_drift",
467
+ "deduplicated",
468
+ "disabled",
469
+ "no_binding",
470
+ "unbound_model",
471
+ "source_missing",
472
+ "source_invalid",
473
+ "source_fetch_failed",
474
+ "sandbox_error",
475
+ "escalated",
476
+ "failed_verification",
477
+ "rejected_installation",
478
+ "rejected_quota",
479
+ }
480
+
481
+ def __init__(
482
+ self,
483
+ runner: HostedAutoHealRunner,
484
+ *,
485
+ max_queue_size: int = 64,
486
+ max_seen_jobs: int = 1024,
487
+ ) -> None:
488
+ if max_queue_size < 1:
489
+ raise ValueError("max_queue_size must be at least 1")
490
+ self._runner = runner
491
+ self._max_seen = max_seen_jobs
492
+ self._queue: queue.Queue[AutoHealJob | _StopSentinel] = queue.Queue(
493
+ maxsize=max_queue_size
494
+ )
495
+ self._seen: OrderedDict[tuple[str, str, str], None] = OrderedDict()
496
+ self._in_flight: set[tuple[str, str, str]] = set()
497
+ self._lock = threading.Lock()
498
+ self._drained_cond = threading.Condition(self._lock)
499
+ self._thread: threading.Thread | None = None
500
+ self._stop_requested = False
501
+ self._pending = 0
502
+ self._enqueued = 0
503
+ self._processed = 0
504
+ self._succeeded = 0
505
+ self._failed = 0
506
+ self._dropped_full = 0
507
+ self._deduplicated = 0
508
+
509
+ def start(self) -> None:
510
+ with self._lock:
511
+ if self._thread is not None and self._thread.is_alive():
512
+ return
513
+ self._stop_requested = False
514
+ self._thread = threading.Thread(
515
+ target=self._run_loop,
516
+ name="selfheal-autoheal-worker",
517
+ daemon=True,
518
+ )
519
+ self._thread.start()
520
+
521
+ def stop(self, timeout: float = 5.0) -> None:
522
+ with self._lock:
523
+ self._stop_requested = True
524
+ thread = self._thread
525
+ if thread is None or not thread.is_alive():
526
+ with self._lock:
527
+ self._thread = None
528
+ return
529
+ try:
530
+ self._queue.put_nowait(_STOP_SENTINEL)
531
+ except queue.Full:
532
+ logger.debug("autoheal stop sentinel dropped; queue full")
533
+ thread.join(timeout=timeout)
534
+ with self._lock:
535
+ if not thread.is_alive():
536
+ self._thread = None
537
+
538
+ def enqueue(self, job: AutoHealJob) -> bool:
539
+ """Enqueue non-blockingly; dedup on (org, repo, model)."""
540
+ dedup_id = (job.org_id, job.repo, job.model_name)
541
+ with self._lock:
542
+ if dedup_id in self._in_flight or dedup_id in self._seen:
543
+ self._deduplicated += 1
544
+ if dedup_id in self._seen:
545
+ self._seen.move_to_end(dedup_id)
546
+ return False
547
+ try:
548
+ self._queue.put_nowait(job)
549
+ except queue.Full:
550
+ self._dropped_full += 1
551
+ return False
552
+ self._in_flight.add(dedup_id)
553
+ self._enqueued += 1
554
+ self._pending += 1
555
+ return True
556
+
557
+ def maybe_enqueue(
558
+ self,
559
+ org_id: str,
560
+ model_name: str,
561
+ drifted_payload: dict[str, Any],
562
+ canonical_payload: dict[str, Any] | None = None,
563
+ ) -> bool:
564
+ """Enqueue auto-heal for every bound repo covering ``model_name``.
565
+
566
+ Returns True when at least one job was accepted. Kill-switch and
567
+ binding checks happen here so disabled orgs never queue work.
568
+ """
569
+ record = self._runner.installation_registry.get_by_org(org_id)
570
+ if (
571
+ record is None
572
+ or record.suspended
573
+ or not record.auto_heal_enabled
574
+ ):
575
+ return False
576
+ accepted = False
577
+ for binding in self._runner.hosted_store.list_repo_bindings(org_id):
578
+ models_map = binding.get("models_map") or {}
579
+ if model_name not in models_map:
580
+ continue
581
+ job = AutoHealJob(
582
+ org_id=org_id,
583
+ repo=str(binding["repo"]),
584
+ model_name=model_name,
585
+ drifted_payload=drifted_payload,
586
+ canonical_payload=canonical_payload,
587
+ )
588
+ accepted = self.enqueue(job) or accepted
589
+ return accepted
590
+
591
+ def wait_until_drained(self, timeout: float = 10.0) -> bool:
592
+ with self._drained_cond:
593
+ return self._drained_cond.wait_for(
594
+ lambda: self._pending == 0, timeout=timeout
595
+ )
596
+
597
+ def stats(self) -> dict[str, int]:
598
+ with self._lock:
599
+ return {
600
+ "enqueued": self._enqueued,
601
+ "processed": self._processed,
602
+ "succeeded": self._succeeded,
603
+ "failed": self._failed,
604
+ "dropped_full": self._dropped_full,
605
+ "deduplicated": self._deduplicated,
606
+ "pending": self._pending,
607
+ }
608
+
609
+ def _run_loop(self) -> None:
610
+ while True:
611
+ with self._lock:
612
+ if self._stop_requested:
613
+ break
614
+ try:
615
+ item = self._queue.get(timeout=0.1)
616
+ except queue.Empty:
617
+ continue
618
+ if isinstance(item, _StopSentinel):
619
+ self._queue.task_done()
620
+ break
621
+
622
+ dedup_id = (item.org_id, item.repo, item.model_name)
623
+ handled = False
624
+ try:
625
+ outcome = self._runner.run(item)
626
+ handled = outcome.status in self._HANDLED_STATUSES
627
+ if outcome.status not in self._HANDLED_STATUSES:
628
+ logger.warning(
629
+ "autoheal unexpected status %s org=%s model=%s: %s",
630
+ outcome.status,
631
+ item.org_id,
632
+ item.model_name,
633
+ outcome.detail,
634
+ )
635
+ except Exception:
636
+ logger.exception(
637
+ "autoheal job crashed org=%s repo=%s model=%s",
638
+ item.org_id,
639
+ item.repo,
640
+ item.model_name,
641
+ )
642
+ finally:
643
+ with self._drained_cond:
644
+ self._in_flight.discard(dedup_id)
645
+ if handled and self._max_seen > 0:
646
+ self._seen[dedup_id] = None
647
+ self._seen.move_to_end(dedup_id)
648
+ while len(self._seen) > self._max_seen:
649
+ self._seen.popitem(last=False)
650
+ self._processed += 1
651
+ if handled:
652
+ self._succeeded += 1
653
+ else:
654
+ self._failed += 1
655
+ self._pending -= 1
656
+ if self._pending == 0:
657
+ self._drained_cond.notify_all()
658
+ self._queue.task_done()