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,203 @@
1
+ """EXP-19/T19 — upstream API contract version tracking.
2
+
3
+ Polls ``watched_specs`` rows: fetches each spec URL (honoring ``ETag`` /
4
+ ``If-None-Match``), computes a structural signature (content hash + declared
5
+ ``info.version``), and records a ``spec_events`` row when the signature
6
+ changes. First successful fetch establishes a baseline silently.
7
+
8
+ Zero-dependency: specs are treated as opaque bytes; "structural diff" means
9
+ content-hash + declared-version change detection, which is sufficient to
10
+ correlate upstream contract releases with SelfHeal drift events.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import json
17
+ import logging
18
+ import re
19
+ import urllib.error
20
+ import urllib.request
21
+ from collections.abc import Callable
22
+ from dataclasses import dataclass
23
+ from typing import TYPE_CHECKING, Any
24
+
25
+ if TYPE_CHECKING:
26
+ from selfheal_api.server_hosted import HostedStateStore
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ SPEC_FETCH_TIMEOUT_SECONDS = 30.0
31
+ MAX_WATCHED_SPECS_PER_ORG = 100
32
+
33
+ _UA = "selfheal-specwatch/0.1"
34
+ _VERSION_RE = re.compile(r'"version"\s*:\s*"([^"]+)"|^\s*version\s*:\s*([^\s#]+)', re.MULTILINE)
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class SpecFetchResult:
39
+ """Outcome of one spec fetch."""
40
+
41
+ status: int
42
+ etag: str | None
43
+ body: bytes | None
44
+ error: str | None = None
45
+
46
+
47
+ def fetch_spec(
48
+ url: str, etag: str | None = None, timeout: float = SPEC_FETCH_TIMEOUT_SECONDS
49
+ ) -> SpecFetchResult:
50
+ """GET ``url`` with an optional ``If-None-Match`` etag."""
51
+ headers = {"User-Agent": _UA, "Accept": "application/json, */*"}
52
+ if etag:
53
+ headers["If-None-Match"] = etag
54
+ req = urllib.request.Request(url, headers=headers, method="GET")
55
+ try:
56
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
57
+ return SpecFetchResult(
58
+ status=resp.status,
59
+ etag=resp.headers.get("ETag"),
60
+ body=resp.read(),
61
+ )
62
+ except urllib.error.HTTPError as exc:
63
+ if exc.code == 304:
64
+ return SpecFetchResult(status=304, etag=etag, body=None)
65
+ return SpecFetchResult(
66
+ status=exc.code, etag=None, body=None, error=f"http_{exc.code}"
67
+ )
68
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
69
+ return SpecFetchResult(status=0, etag=None, body=None, error=str(exc)[:200])
70
+
71
+
72
+ def spec_signature(body: bytes) -> tuple[str, str | None]:
73
+ """Return ``(content_sha256, declared_version_or_None)``."""
74
+ digest = hashlib.sha256(body).hexdigest()
75
+ version: str | None = None
76
+ try:
77
+ doc = json.loads(body)
78
+ if isinstance(doc, dict):
79
+ info = doc.get("info")
80
+ if isinstance(info, dict) and isinstance(info.get("version"), str):
81
+ version = info["version"]
82
+ except (ValueError, UnicodeDecodeError):
83
+ text = body.decode("utf-8", errors="replace")
84
+ match = _VERSION_RE.search(text)
85
+ if match:
86
+ version = (match.group(1) or match.group(2) or "").strip() or None
87
+ return digest, version
88
+
89
+
90
+ def poll_watched_spec(
91
+ row: dict[str, Any],
92
+ fetcher: Callable[..., SpecFetchResult] = fetch_spec,
93
+ ) -> dict[str, Any] | None:
94
+ """Poll one watched spec; returns an event dict when it changed.
95
+
96
+ Returns ``None`` for unchanged (304 / same signature) or first-seen
97
+ baseline establishment. On change, returns the ``spec_events`` payload
98
+ (caller persists it and updates the watched_specs row).
99
+ """
100
+ result = fetcher(str(row["spec_url"]), etag=row.get("etag"))
101
+ if result.error is not None or result.body is None:
102
+ return None
103
+ new_hash, new_version = spec_signature(result.body)
104
+ old_hash = row.get("last_seen_hash")
105
+ if old_hash is None:
106
+ # Baseline: record signature without emitting a version event.
107
+ return {
108
+ "baseline": True,
109
+ "new_hash": new_hash,
110
+ "new_version": new_version,
111
+ "etag": result.etag,
112
+ }
113
+ if new_hash == old_hash:
114
+ # Same content; refresh etag only.
115
+ return {
116
+ "unchanged": True,
117
+ "etag": result.etag,
118
+ }
119
+ return {
120
+ "baseline": False,
121
+ "old_version": row.get("last_seen_version"),
122
+ "new_version": new_version,
123
+ "old_hash": old_hash,
124
+ "new_hash": new_hash,
125
+ "etag": result.etag,
126
+ }
127
+
128
+
129
+ def run_spec_watch_cycle(
130
+ store: HostedStateStore,
131
+ *,
132
+ org_id: str | None = None,
133
+ fetcher: Callable[..., SpecFetchResult] = fetch_spec,
134
+ ) -> dict[str, Any]:
135
+ """Poll all watched specs (optionally one org); persist changes.
136
+
137
+ Returns ``{"checked": n, "changed": n, "baselined": n, "errors": n}``.
138
+ """
139
+ rows = store.list_watched_specs(org_id)
140
+ summary = {"checked": 0, "changed": 0, "baselined": 0, "errors": 0}
141
+ for row in rows:
142
+ summary["checked"] += 1
143
+ try:
144
+ outcome = poll_watched_spec(row, fetcher=fetcher)
145
+ except Exception as exc: # noqa: BLE001 - one bad spec must not stop the cycle
146
+ logger.warning(
147
+ "spec-watch poll failed org=%s repo=%s url=%s: %s",
148
+ row.get("org_id"),
149
+ row.get("repo"),
150
+ row.get("spec_url"),
151
+ exc,
152
+ )
153
+ summary["errors"] += 1
154
+ continue
155
+ if outcome is None:
156
+ continue
157
+ if outcome.get("baseline"):
158
+ store.update_watched_spec_signature(
159
+ str(row["org_id"]),
160
+ str(row["repo"]),
161
+ str(row["spec_url"]),
162
+ etag=outcome.get("etag"),
163
+ version=outcome.get("new_version"),
164
+ content_hash=str(outcome["new_hash"]),
165
+ )
166
+ summary["baselined"] += 1
167
+ continue
168
+ if outcome.get("unchanged"):
169
+ if outcome.get("etag"):
170
+ store.update_watched_spec_etag(
171
+ str(row["org_id"]),
172
+ str(row["repo"]),
173
+ str(row["spec_url"]),
174
+ str(outcome["etag"]),
175
+ )
176
+ continue
177
+ store.record_spec_event(
178
+ org_id=str(row["org_id"]),
179
+ repo=str(row["repo"]),
180
+ spec_url=str(row["spec_url"]),
181
+ old_version=outcome.get("old_version"),
182
+ new_version=outcome.get("new_version"),
183
+ old_hash=outcome.get("old_hash"),
184
+ new_hash=str(outcome["new_hash"]),
185
+ )
186
+ store.update_watched_spec_signature(
187
+ str(row["org_id"]),
188
+ str(row["repo"]),
189
+ str(row["spec_url"]),
190
+ etag=outcome.get("etag"),
191
+ version=outcome.get("new_version"),
192
+ content_hash=str(outcome["new_hash"]),
193
+ )
194
+ summary["changed"] += 1
195
+ logger.info(
196
+ "spec-watch change org=%s repo=%s url=%s %s -> %s",
197
+ row.get("org_id"),
198
+ row.get("repo"),
199
+ row.get("spec_url"),
200
+ outcome.get("old_version"),
201
+ outcome.get("new_version"),
202
+ )
203
+ return summary
selfheal_api/worker.py ADDED
@@ -0,0 +1,212 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import queue
5
+ import threading
6
+ from collections import OrderedDict
7
+ from typing import Any
8
+
9
+ from pydantic import BaseModel, ConfigDict
10
+
11
+ from selfheal_api.remediation import RemediationPipeline, RemediationRequest
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class _StopSentinel:
17
+ """Sentinel object used to signal the worker thread to exit."""
18
+
19
+
20
+ _STOP_SENTINEL = _StopSentinel()
21
+
22
+
23
+ class QueuedRemediationJob(BaseModel):
24
+ """Immutable job payload enqueued for asynchronous drift remediation."""
25
+
26
+ model_config = ConfigDict(frozen=True)
27
+
28
+ request: RemediationRequest
29
+ expected_model: type[BaseModel]
30
+ drifted_payload: dict[str, Any]
31
+ canonical_payload: dict[str, Any] | None = None
32
+ fingerprint: str
33
+
34
+
35
+ class WorkerStats(BaseModel):
36
+ """Thread-safe snapshot of remediation worker queue counters."""
37
+
38
+ model_config = ConfigDict(frozen=True)
39
+
40
+ enqueued: int
41
+ processed: int
42
+ succeeded: int
43
+ failed: int
44
+ dropped_full: int
45
+ deduplicated: int
46
+
47
+
48
+ class RemediationQueue:
49
+ """Bounded, deduplicating background worker queue for schema-drift remediation."""
50
+
51
+ def __init__(
52
+ self,
53
+ pipeline: RemediationPipeline,
54
+ *,
55
+ max_queue_size: int = 256,
56
+ max_seen_fingerprints: int = 4096,
57
+ ) -> None:
58
+ if max_queue_size < 1:
59
+ raise ValueError("max_queue_size must be at least 1")
60
+ if max_seen_fingerprints < 0:
61
+ raise ValueError("max_seen_fingerprints must be non-negative")
62
+
63
+ self._pipeline = pipeline
64
+ self._max_queue_size = max_queue_size
65
+ self._max_seen_fingerprints = max_seen_fingerprints
66
+
67
+ self._queue: queue.Queue[QueuedRemediationJob | _StopSentinel] = queue.Queue(
68
+ maxsize=max_queue_size
69
+ )
70
+ self._seen_fingerprints: OrderedDict[tuple[str, str], None] = OrderedDict()
71
+ self._in_flight: set[tuple[str, str]] = set()
72
+
73
+ self._lock = threading.Lock()
74
+ self._drained_cond = threading.Condition(self._lock)
75
+ self._thread: threading.Thread | None = None
76
+ self._stop_requested = False
77
+
78
+ self._pending = 0
79
+ self._enqueued = 0
80
+ self._processed = 0
81
+ self._succeeded = 0
82
+ self._failed = 0
83
+ self._dropped_full = 0
84
+ self._deduplicated = 0
85
+
86
+ def start(self) -> None:
87
+ """Start the background daemon worker thread if not already running."""
88
+ with self._lock:
89
+ if self._thread is not None and self._thread.is_alive():
90
+ return
91
+ self._stop_requested = False
92
+ self._thread = threading.Thread(
93
+ target=self._run_loop,
94
+ name="selfheal-remediation-worker",
95
+ daemon=True,
96
+ )
97
+ self._thread.start()
98
+
99
+ def stop(self, timeout: float = 5.0) -> None:
100
+ """Signal the worker thread to stop and wait up to ``timeout`` seconds."""
101
+ with self._lock:
102
+ self._stop_requested = True
103
+ thread = self._thread
104
+ if thread is None or not thread.is_alive():
105
+ with self._lock:
106
+ self._thread = None
107
+ return
108
+
109
+ try:
110
+ self._queue.put_nowait(_STOP_SENTINEL)
111
+ except queue.Full:
112
+ logger.debug(
113
+ "RemediationQueue stop sentinel dropped because queue is full; "
114
+ "worker will exit via stop flag"
115
+ )
116
+
117
+ thread.join(timeout=timeout)
118
+ with self._lock:
119
+ if not thread.is_alive():
120
+ self._thread = None
121
+
122
+ def enqueue(self, job: QueuedRemediationJob) -> bool:
123
+ """Enqueue a remediation job non-blockingly with org+fingerprint deduplication."""
124
+ dedup_id = (job.request.org_id, job.fingerprint)
125
+ with self._lock:
126
+ if self._max_seen_fingerprints > 0:
127
+ if dedup_id in self._in_flight:
128
+ self._deduplicated += 1
129
+ return False
130
+ if dedup_id in self._seen_fingerprints:
131
+ self._seen_fingerprints.move_to_end(dedup_id)
132
+ self._deduplicated += 1
133
+ return False
134
+
135
+ try:
136
+ self._queue.put_nowait(job)
137
+ except queue.Full:
138
+ self._dropped_full += 1
139
+ return False
140
+
141
+ if self._max_seen_fingerprints > 0:
142
+ self._in_flight.add(dedup_id)
143
+
144
+ self._enqueued += 1
145
+ self._pending += 1
146
+ return True
147
+
148
+ def wait_until_drained(self, timeout: float = 5.0) -> bool:
149
+ """Block until all enqueued jobs finish processing or ``timeout`` expires."""
150
+ with self._drained_cond:
151
+ return self._drained_cond.wait_for(lambda: self._pending == 0, timeout=timeout)
152
+
153
+ def stats(self) -> WorkerStats:
154
+ """Return a thread-safe snapshot of queue counters."""
155
+ with self._lock:
156
+ return WorkerStats(
157
+ enqueued=self._enqueued,
158
+ processed=self._processed,
159
+ succeeded=self._succeeded,
160
+ failed=self._failed,
161
+ dropped_full=self._dropped_full,
162
+ deduplicated=self._deduplicated,
163
+ )
164
+
165
+ def _run_loop(self) -> None:
166
+ while True:
167
+ with self._lock:
168
+ if self._stop_requested:
169
+ break
170
+ try:
171
+ item = self._queue.get(timeout=0.1)
172
+ except queue.Empty:
173
+ continue
174
+ if isinstance(item, _StopSentinel):
175
+ self._queue.task_done()
176
+ break
177
+
178
+ dedup_id = (item.request.org_id, item.fingerprint)
179
+ succeeded = False
180
+ try:
181
+ outcome = self._pipeline.run(
182
+ req=item.request,
183
+ expected_model=item.expected_model,
184
+ drifted_payload=item.drifted_payload,
185
+ canonical_payload=item.canonical_payload,
186
+ )
187
+ succeeded = outcome.status in {"pr_opened", "no_drift", "deduplicated"}
188
+ except Exception:
189
+ logger.exception(
190
+ "Remediation job failed for org=%s model=%s fingerprint=%s",
191
+ item.request.org_id,
192
+ item.request.model_name,
193
+ item.fingerprint,
194
+ )
195
+ finally:
196
+ with self._drained_cond:
197
+ if self._max_seen_fingerprints > 0:
198
+ self._in_flight.discard(dedup_id)
199
+ if succeeded:
200
+ self._seen_fingerprints[dedup_id] = None
201
+ self._seen_fingerprints.move_to_end(dedup_id)
202
+ while len(self._seen_fingerprints) > self._max_seen_fingerprints:
203
+ self._seen_fingerprints.popitem(last=False)
204
+ self._processed += 1
205
+ if succeeded:
206
+ self._succeeded += 1
207
+ else:
208
+ self._failed += 1
209
+ self._pending -= 1
210
+ if self._pending == 0:
211
+ self._drained_cond.notify_all()
212
+ self._queue.task_done()
sentinel/__init__.py ADDED
@@ -0,0 +1,33 @@
1
+ from sentinel.detector import (
2
+ DriftIssue,
3
+ DriftKind,
4
+ DriftReport,
5
+ PrimitiveKind,
6
+ RedactedValue,
7
+ detect_drift,
8
+ redact_payload,
9
+ )
10
+ from sentinel.guard import DriftDeduplicator, compute_drift_fingerprint, selfheal_guard
11
+ from sentinel.llm_fallback import (
12
+ AnthropicSchemaMappingProvider,
13
+ DeterministicMappingProvider,
14
+ SchemaMappingProvider,
15
+ is_valid_redacted_kind,
16
+ )
17
+
18
+ __all__ = [
19
+ "AnthropicSchemaMappingProvider",
20
+ "DeterministicMappingProvider",
21
+ "DriftDeduplicator",
22
+ "DriftIssue",
23
+ "DriftKind",
24
+ "DriftReport",
25
+ "PrimitiveKind",
26
+ "RedactedValue",
27
+ "SchemaMappingProvider",
28
+ "compute_drift_fingerprint",
29
+ "detect_drift",
30
+ "is_valid_redacted_kind",
31
+ "redact_payload",
32
+ "selfheal_guard",
33
+ ]