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
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: datapi-selfheal
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Datapi SelfHeal: schema-drift detection and verified remediation engine
|
|
5
|
+
Author-email: CREOVA <engineering@creova.ai>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/creova-gif/selfheal-api
|
|
8
|
+
Project-URL: Repository, https://github.com/creova-gif/selfheal-api
|
|
9
|
+
Project-URL: Documentation, https://github.com/creova-gif/selfheal-api/tree/main/docs
|
|
10
|
+
Project-URL: Issues, https://github.com/creova-gif/selfheal-api/issues
|
|
11
|
+
Keywords: api,schema-drift,contract-testing,pydantic,openapi,remediation,webhooks,integration-reliability
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
18
|
+
Classifier: Topic :: System :: Monitoring
|
|
19
|
+
Requires-Python: >=3.12
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: pydantic>=2.14.4
|
|
23
|
+
Requires-Dist: libcst>=1.9.0
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pytest>=9.2.0; extra == "dev"
|
|
26
|
+
Requires-Dist: mypy>=2.4.1; extra == "dev"
|
|
27
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# Datapi SelfHeal: Schema-Drift Detection & Verified Remediation
|
|
31
|
+
|
|
32
|
+
> **Datapi SelfHeal** is the API reliability and verified-remediation capability
|
|
33
|
+
> within the [Datapi](https://github.com/creova-gif/datapi) ecosystem.
|
|
34
|
+
> *Build APIs. Keep them reliable.* — Detect drift. Verify the fix.
|
|
35
|
+
>
|
|
36
|
+
> (Formerly standalone as "SelfHealAPI"; the repository, license, and
|
|
37
|
+
> `selfheal` CLI/package identifiers are unchanged.)
|
|
38
|
+
|
|
39
|
+
[](https://github.com/creova-gif/selfheal-api/actions/workflows/ci.yml)
|
|
40
|
+
[](LICENSE)
|
|
41
|
+
[](CHANGELOG.md)
|
|
42
|
+
[](pyproject.toml)
|
|
43
|
+
|
|
44
|
+
Datapi SelfHeal detects third-party API payload drift at the system boundary, redacts all scalar values into structural primitives before analysis, and synthesizes `libcst` adapter patches that pass strict sandbox verification (`verify_patch`, `mypy --strict`, and `pytest`) before a pull request is opened.
|
|
45
|
+
|
|
46
|
+
```mermaid
|
|
47
|
+
flowchart LR
|
|
48
|
+
Payload["Incoming JSON Payload"] --> Sentinel["Sentinel (detect_drift / Zero-PII)"]
|
|
49
|
+
Sentinel --> Synthesizer["Synthesizer (libcst / Zod / OpenAPI 3.1)"]
|
|
50
|
+
Synthesizer --> Gate["Sandbox Gate (verify_patch, mypy --strict, pytest)"]
|
|
51
|
+
Gate --> Outputs["PR / Guard / Hosted Server"]
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Overview
|
|
55
|
+
|
|
56
|
+
Modern integrations break silently when upstream webhooks or REST APIs rename fields, coerce integers to strings, wrap scalars in lists, or nest properties. Datapi SelfHeal closes the loop between runtime detection and verified code remediation while enforcing a **Zero-PII boundary**:
|
|
57
|
+
|
|
58
|
+
1. **Sentinel (`src/sentinel/detector.py`)**: Validates incoming JSON payloads against Pydantic v2 models (`strict=True`), classifies every scalar into a zero-PII `PrimitiveKind` (`<str>`, `<int>`, `<int_str>`, `<float_str>`, `<bool_str>`, `<iso_datetime>`, `<null>`), and emits an immutable `DriftReport` with matched candidate source paths.
|
|
59
|
+
2. **Synthesizer (`src/synthesizer/patcher.py`)**: Transforms a `DriftReport` into a `PatchPlan` and applies a `libcst.CSTTransformer` to inject a typed `@model_validator(mode="before")` normalizer and safe union/literal widening without losing formatting.
|
|
60
|
+
3. **Sandbox Gate (`verify_patch`)**: Parses the patched CST, executes the model in an isolated namespace, validates both the drifted payload and canonical legacy payload with `strict=True`, and enforces `mypy --strict` + `pytest` before any patch is written or PR is opened.
|
|
61
|
+
|
|
62
|
+
- **Architecture, Security & Threat Model:** See [`AGENTS.md`](AGENTS.md), [`SECURITY.md`](SECURITY.md), [`docs/adr/001-redacted-ast-synthesis-and-sandbox-gate.md`](docs/adr/001-redacted-ast-synthesis-and-sandbox-gate.md), and [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md).
|
|
63
|
+
|
|
64
|
+
## Features
|
|
65
|
+
|
|
66
|
+
- **Zero-PII Scalar Redaction:** Raw payload values never leave your boundary for LLM fallback (`AnthropicSchemaMappingProvider`) or persistent storage (`DriftEventLedger`).
|
|
67
|
+
- **Formatting-Preserving `libcst` Patching:** Generates typed Pydantic v2 `@model_validator(mode="before")` adapters, nested sub-model normalizers, and list/scalar coercions.
|
|
68
|
+
- **Fail-Closed Verification Gate:** Every patch must pass `verify_patch`, `mypy --strict --shadow-file`, and `pytest` before disk write or PR creation.
|
|
69
|
+
- **Multi-Target Emitters:** Emit TypeScript Zod preprocessors (`--zod`) and OpenAPI 3.1 `x-selfheal-aliases` / `x-selfheal-coercions` schemas (`--openapi`).
|
|
70
|
+
- **Runtime Guard & Middleware:** Drop-in `@selfheal_guard` decorator (sync/async) plus zero-dependency `SelfHealASGIMiddleware` and `SelfHealWSGIMiddleware`.
|
|
71
|
+
- **Hosted Multi-Tenant Server & Drift Console:** Cloud Run-ready HTTP server with HMAC webhook verification, SQLite WAL event ledger, Slack/webhook alerting, and an XSS-safe HTML5 Drift Console (`GET /dashboard`).
|
|
72
|
+
- **Replay Regression Harness:** Deterministic `run_replay_corpus` verification over recorded redacted samples.
|
|
73
|
+
|
|
74
|
+
## Installation
|
|
75
|
+
|
|
76
|
+
Requires **Python 3.12+**. From PyPI:
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
pip install datapi-selfheal
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Or from source:
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
git clone https://github.com/creova-gif/selfheal-api.git
|
|
86
|
+
cd selfheal-api
|
|
87
|
+
|
|
88
|
+
python3.12 -m venv .venv
|
|
89
|
+
source .venv/bin/activate
|
|
90
|
+
pip install -e ".[dev]"
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
One-command E2E demo (seeded upstream drift → detection → verified patch → reviewable draft-PR artifact):
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
scripts/demo/run.sh # evidence lands in evaluations/demo/<timestamp>/
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Run the quality gates locally:
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
.venv/bin/ruff check src tests
|
|
103
|
+
.venv/bin/mypy --strict src tests
|
|
104
|
+
.venv/bin/pytest -v
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## Usage
|
|
108
|
+
|
|
109
|
+
### `selfheal` CLI (`init`, `check`, `heal`, `schema`, `replay`, `doctor`)
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
# Scaffold starter selfheal.config.json and GitHub Actions workflow
|
|
113
|
+
selfheal init
|
|
114
|
+
|
|
115
|
+
# Verify Python, SQLite, dependencies, and toolchain readiness (zero-secret output)
|
|
116
|
+
selfheal doctor --json
|
|
117
|
+
|
|
118
|
+
# Detect schema drift and emit zero-PII DriftReport JSON (exit 0=clean, 1=drift, 2=error)
|
|
119
|
+
selfheal check --model path/to/models.py:Invoice --payload drifted.json
|
|
120
|
+
|
|
121
|
+
# Emit standalone JSON Schema, OpenAPI 3.1.0, or TypeScript/Zod from any Pydantic model
|
|
122
|
+
selfheal schema --model path/to/models.py:Invoice --format openapi --out openapi.json
|
|
123
|
+
|
|
124
|
+
# Replay a JSONL corpus against a Pydantic model
|
|
125
|
+
selfheal replay --model path/to/models.py:Invoice --corpus samples.jsonl
|
|
126
|
+
|
|
127
|
+
# Hosted onboarding: exchange a GitHub App install token for an org API key
|
|
128
|
+
selfheal connect --install-token "$INSTALL_TOKEN" --repo owner/repo
|
|
129
|
+
|
|
130
|
+
# Generate Pydantic (or Zod) models from captured payload samples
|
|
131
|
+
selfheal models init --samples samples/*.json --format pydantic --out models.py
|
|
132
|
+
|
|
133
|
+
# Synthesize a libcst patch, run verify_patch + mypy --strict --shadow-file + pytest,
|
|
134
|
+
# preview the unified diff, emit TypeScript Zod & OpenAPI 3.1 outputs, write, and open a PR
|
|
135
|
+
selfheal heal \
|
|
136
|
+
--model path/to/models.py:Invoice \
|
|
137
|
+
--payload drifted.json \
|
|
138
|
+
--canonical canonical.json \
|
|
139
|
+
--diff \
|
|
140
|
+
--zod generated/invoice_adapter.ts \
|
|
141
|
+
--openapi generated/openapi.json \
|
|
142
|
+
--write \
|
|
143
|
+
--open-pr
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Useful `heal` flags:
|
|
147
|
+
- `--llm-fallback`: enable zero-PII `AnthropicSchemaMappingProvider` for opaque field renames.
|
|
148
|
+
- `--pytest-args "..."`: pass extra arguments to the `pytest` verification gate.
|
|
149
|
+
- `--branch <name>`: override the auto-generated `selfheal/<model>-<fingerprint>` branch name.
|
|
150
|
+
|
|
151
|
+
### Runtime Guard (`@selfheal_guard`)
|
|
152
|
+
|
|
153
|
+
Decorate sync or async boundary handlers to detect drift in-process, deduplicate identical drift fingerprints, and optionally normalize incoming payloads (`normalize=True`):
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
from sentinel.guard import DriftDeduplicator, selfheal_guard
|
|
157
|
+
from sentinel.llm_fallback import AnthropicSchemaMappingProvider
|
|
158
|
+
|
|
159
|
+
dedup = DriftDeduplicator(max_fingerprints=1024)
|
|
160
|
+
provider = AnthropicSchemaMappingProvider(max_calls=50)
|
|
161
|
+
|
|
162
|
+
@selfheal_guard(
|
|
163
|
+
Invoice,
|
|
164
|
+
mapping_provider=provider,
|
|
165
|
+
deduplicator=dedup,
|
|
166
|
+
normalize=True,
|
|
167
|
+
on_drift=lambda report, fp: print(f"Drift detected ({fp[:8]}): {len(report.issues)} issues"),
|
|
168
|
+
)
|
|
169
|
+
async def handle_webhook(payload: dict[str, object]) -> Invoice:
|
|
170
|
+
return Invoice.model_validate(payload)
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
### ASGI & WSGI Middleware
|
|
174
|
+
|
|
175
|
+
Inspect JSON request bodies at runtime without framework lock-in using `SelfHealASGIMiddleware` or `SelfHealWSGIMiddleware` with `RouteBinding`:
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
from selfheal_api import RouteBinding, SelfHealASGIMiddleware
|
|
179
|
+
|
|
180
|
+
app = SelfHealASGIMiddleware(
|
|
181
|
+
fastapi_or_starlette_app,
|
|
182
|
+
routes=[RouteBinding(path="/webhooks/invoice", model_cls=Invoice, normalize=True)],
|
|
183
|
+
on_drift=lambda report, fp: print(f"Route drift {fp[:8]}: {len(report.issues)} issues"),
|
|
184
|
+
)
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### Replay Regression Harness
|
|
188
|
+
|
|
189
|
+
Validate a `PatchPlan` against a corpus of recorded samples using `run_replay_corpus`:
|
|
190
|
+
|
|
191
|
+
```python
|
|
192
|
+
from selfheal_api.replay import ReplaySample, run_replay_corpus
|
|
193
|
+
|
|
194
|
+
samples = [ReplaySample(sample_id="stripe-v2", payload=drifted_payload)]
|
|
195
|
+
report = run_replay_corpus(Invoice, samples, plan=patch_result.plan)
|
|
196
|
+
assert report.failed == 0
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
### TypeScript / Zod Adapter Emission
|
|
200
|
+
|
|
201
|
+
Generate a typed TypeScript preprocessor alongside Python CST patches via `selfheal heal --zod <out.ts>` or programmatically with `synthesize_zod_preprocessor(plan)`:
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
import { z } from 'zod';
|
|
205
|
+
import { createSelfHealZodAdapter } from './invoice_adapter';
|
|
206
|
+
|
|
207
|
+
const InvoiceSchema = createSelfHealZodAdapter(
|
|
208
|
+
z.object({ id: z.string(), amount_cents: z.number().int() }),
|
|
209
|
+
);
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
### Hosted Multi-Tenant Server & Drift Console
|
|
213
|
+
|
|
214
|
+
Run the hosted webhook receiver locally or deploy to GCP Cloud Run using `Dockerfile` and [`deploy/cloudrun.yaml`](deploy/cloudrun.yaml):
|
|
215
|
+
|
|
216
|
+
```bash
|
|
217
|
+
python -m selfheal_api.server
|
|
218
|
+
# or via the installed console script:
|
|
219
|
+
selfheal-server
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
Endpoints:
|
|
223
|
+
- `GET /healthz` (`HEAD` supported): liveness probe.
|
|
224
|
+
- `GET /readyz` (`HEAD` supported): readiness probe verifying `DriftLedger`, `BillingStore`, and `InstallationRegistry` SQLite health.
|
|
225
|
+
- `GET /metrics` (`?format=prometheus`): JSON or Prometheus v0.0.4 telemetry metrics.
|
|
226
|
+
- `GET /openapi.json`: live OpenAPI 3.1.0 specification including registered `model_registry` schemas.
|
|
227
|
+
- `POST /webhooks/drift`: multi-tenant drift ingestion with HMAC verification, rate limiting, and Slack/webhook alerting.
|
|
228
|
+
- `POST /webhooks/stripe` & `POST /webhooks/github`: Stripe billing and GitHub App installation webhook handlers.
|
|
229
|
+
- `GET /dashboard`: WCAG 2.1 AA self-contained, CSP-strict HTML5 Drift Console with audit export links.
|
|
230
|
+
- `GET /console`: per-org integration health console (monitored dependencies, drift events, remediation proposals, verification evidence, PR status, spec-watch panels) scoped by `shk_*` API key.
|
|
231
|
+
- `GET /api/v1/events` (`?limit=...&offset=...&model=...`), `GET /api/v1/events/export` (`?format=csv|jsonl`), and `GET /api/v1/summary`: SQLite WAL zero-PII drift event ledger and audit export APIs.
|
|
232
|
+
- `POST /jobs/digest`, `POST /jobs/spec-watch`, `POST /jobs/revert`: jobs-token-guarded schedulers and the auto-heal revert path.
|
|
233
|
+
- `POST /orgs/<id>/install`, `POST /orgs/<id>/connect`, `POST /orgs/<id>/billing/*`: GitHub App install flow, repo binding + API keys, and Stripe checkout/portal.
|
|
234
|
+
|
|
235
|
+
## Configuration
|
|
236
|
+
|
|
237
|
+
See [`.env.example`](.env.example) for a starter template. The hosted server (`src/selfheal_api/server.py`), Cloud Run manifest (`deploy/cloudrun.yaml`), and LLM fallback provider (`src/sentinel/llm_fallback.py`) read the following environment variables:
|
|
238
|
+
|
|
239
|
+
| Variable | Default | Description |
|
|
240
|
+
| --- | --- | --- |
|
|
241
|
+
| `PORT` | `8080` | HTTP listen port for `selfheal-server` / Cloud Run. |
|
|
242
|
+
| `SELFHEAL_HOST` | `0.0.0.0` | Bind host address for `selfheal-server`. |
|
|
243
|
+
| `SELFHEAL_DB_PATH` | `:memory:` | SQLite WAL persistence path (e.g. `/data/selfheal.db`) for ledger, billing, and installations. |
|
|
244
|
+
| `SELFHEAL_RETENTION_DAYS` | `0` | Startup retention window in days (`> 0` prunes expired drift events on boot). |
|
|
245
|
+
| `SELFHEAL_MODELS` | `""` | Comma-separated `module.path:ClassName` specs loaded at startup. |
|
|
246
|
+
| `SELFHEAL_WEBHOOK_SECRET` | `""` | HMAC-SHA256 shared secret for `POST /webhooks/drift`. |
|
|
247
|
+
| `STRIPE_WEBHOOK_SECRET` | `""` | Stripe webhook signing secret (falls back to `SELFHEAL_STRIPE_WEBHOOK_SECRET`). |
|
|
248
|
+
| `GITHUB_APP_WEBHOOK_SECRET` | `""` | GitHub App webhook signing secret (falls back to `SELFHEAL_GITHUB_WEBHOOK_SECRET`). |
|
|
249
|
+
| `SELFHEAL_MAX_RPM` | `60` | Per-tenant requests-per-minute rate limit. |
|
|
250
|
+
| `SELFHEAL_MAX_LLM_CALLS` | `20` | Per-tenant cap on zero-PII LLM fallback calls. |
|
|
251
|
+
| `SELFHEAL_SLACK_WEBHOOK_URL` | `""` | Optional `https://` Slack webhook URL for zero-PII drift alerts. |
|
|
252
|
+
| `SELFHEAL_ALERT_WEBHOOK_URL` | `""` | Optional `https://` generic webhook URL for signed `DriftAlert` notifications. |
|
|
253
|
+
| `SELFHEAL_ALERT_WEBHOOK_SECRET` | `""` | Optional HMAC-SHA256 secret (`X-SelfHeal-Signature`) for `SELFHEAL_ALERT_WEBHOOK_URL`. |
|
|
254
|
+
| `ANTHROPIC_API_KEY` | `""` | API key for `AnthropicSchemaMappingProvider` when `--llm-fallback` is enabled. |
|
|
255
|
+
| `SELFHEAL_STATE_SECRET` | `""` | HMAC secret for hosted install-state nonces. |
|
|
256
|
+
| `SELFHEAL_JOBS_TOKEN` | `""` | Bearer token guarding `POST /jobs/*` endpoints. |
|
|
257
|
+
| `SELFHEAL_GITHUB_APP_ID` / `SELFHEAL_GITHUB_APP_PRIVATE_KEY` / `SELFHEAL_GITHUB_APP_SLUG` | `""` | GitHub App credentials for installation tokens, repo reads, and draft-PR creation. |
|
|
258
|
+
| `STRIPE_SECRET_KEY` / `STRIPE_PRICE_PRO` / `STRIPE_PRICE_TEAM` | `""` | Stripe billing configuration for hosted plans. |
|
|
259
|
+
| `SELFHEAL_DIGEST_INTERVAL_SECONDS` / `SELFHEAL_SPECWATCH_INTERVAL_SECONDS` | `604800` / `3600` | In-process scheduler intervals (`SELFHEAL_*_SCHEDULER=inprocess` to enable). |
|
|
260
|
+
|
|
261
|
+
## Documentation
|
|
262
|
+
|
|
263
|
+
- [`docs/product/PRD.md`](docs/product/PRD.md) — product requirements
|
|
264
|
+
- [`docs/architecture/overview.md`](docs/architecture/overview.md) — system architecture
|
|
265
|
+
- [`docs/design/`](docs/design/) — design system specification
|
|
266
|
+
- [`docs/security/`](docs/security/) — data handling + sandbox evaluation
|
|
267
|
+
- [`docs/operations/runbooks.md`](docs/operations/runbooks.md) — incident runbooks
|
|
268
|
+
- [`docs/deploy-cloud-run.md`](docs/deploy-cloud-run.md) — Cloud Run deployment
|
|
269
|
+
- [`docs/commercial/pricing.md`](docs/commercial/pricing.md) — pricing hypotheses
|
|
270
|
+
- [`research/`](research/) — market, competitor, and technical research
|
|
271
|
+
|
|
272
|
+
## Benchmarks
|
|
273
|
+
|
|
274
|
+
Measured on Python 3.12.12 (`pydantic 2.14.4`, `libcst 1.9.0`) across the 40-mutation benchmark suite simulating Stripe, HubSpot, and Weather API drift (`tests/test_drift_and_patch.py`):
|
|
275
|
+
|
|
276
|
+
| Metric | Target threshold | Measured result | Evidence |
|
|
277
|
+
| --- | --- | --- | --- |
|
|
278
|
+
| Drift detection recall | 100% | **100.0%** (40 / 40) | `test_40_mutation_benchmark_thresholds` |
|
|
279
|
+
| Auto-patch verification pass rate | >= 85% | **100.0%** (40 / 40) | `test_40_mutation_benchmark_thresholds` |
|
|
280
|
+
| Sentinel runtime check latency (median) | < 2.0 ms | **0.017 ms** (range 0.016 to 0.020 ms across 7 runs) | Bound by `pydantic-core` validation + dict traversal on 1 core |
|
|
281
|
+
| Sentinel runtime check latency (p99) | < 2.0 ms | **0.040 ms** (range 0.033 to 0.059 ms across 7 runs) | Bound by `ValidationError` formatting and token scoring |
|
|
282
|
+
|
|
283
|
+
Regenerate the benchmark numbers with:
|
|
284
|
+
|
|
285
|
+
```bash
|
|
286
|
+
PYTHONPATH=src .venv/bin/python -c "
|
|
287
|
+
import statistics
|
|
288
|
+
from tests.test_drift_and_patch import ALL_40_MUTATIONS
|
|
289
|
+
from sentinel import detect_drift
|
|
290
|
+
from synthesizer import synthesize_patch, verify_patch
|
|
291
|
+
|
|
292
|
+
for _, m, _, _, mut in ALL_40_MUTATIONS:
|
|
293
|
+
detect_drift(m, mut)
|
|
294
|
+
|
|
295
|
+
medians, p99s = [], []
|
|
296
|
+
for _ in range(7):
|
|
297
|
+
s = sorted(detect_drift(m, mut).elapsed_ms for _, m, _, _, mut in ALL_40_MUTATIONS)
|
|
298
|
+
medians.append(s[len(s) // 2])
|
|
299
|
+
p99s.append(s[int(len(s) * 0.99)])
|
|
300
|
+
|
|
301
|
+
detected = sum(1 for _, m, _, _, mut in ALL_40_MUTATIONS if detect_drift(m, mut).has_drift)
|
|
302
|
+
passed = sum(1 for _, m, src, can, mut in ALL_40_MUTATIONS if verify_patch(synthesize_patch(src, detect_drift(m, mut)), mut, can).passed)
|
|
303
|
+
print(f'Recall: {detected}/{len(ALL_40_MUTATIONS)} | Pass: {passed}/{len(ALL_40_MUTATIONS)} | Median: {statistics.median(medians):.3f}ms | p99: {statistics.median(p99s):.3f}ms')
|
|
304
|
+
"
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
## Contributing
|
|
308
|
+
|
|
309
|
+
Contributions are welcome! Please read [`CONTRIBUTING.md`](CONTRIBUTING.md) for local setup, quality gates (`ruff`, `mypy --strict`, `pytest`), ADR guidelines, and Zero-PII security requirements.
|
|
310
|
+
|
|
311
|
+
## License
|
|
312
|
+
|
|
313
|
+
Licensed under the [MIT License](LICENSE).
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
datapi_selfheal-0.3.0.dist-info/licenses/LICENSE,sha256=GvneYhoMnH5x7Z51g17UVqyH8jGh5-UUpvv3eNsTFso,1081
|
|
2
|
+
selfheal_api/__init__.py,sha256=rmamitpVdX6EVA_L2vPKgeSQ2isxGLLlaU5XYh_FnZE,2532
|
|
3
|
+
selfheal_api/_sandbox_exec.py,sha256=Hdg74OmFc1av47KsYR4W1C-MCnzs-_hIpR_hgxgxonQ,4648
|
|
4
|
+
selfheal_api/autoheal.py,sha256=lL7zuNtyA8vx1dteb0iAVh7ZstVvn1p60EDVI0z8SfU,23141
|
|
5
|
+
selfheal_api/billing.py,sha256=ilNzjaC1bQWYPsuRd9Z-5K_Or9UeLwk94miA_Bh_aAw,24877
|
|
6
|
+
selfheal_api/cli.py,sha256=KR0NHT3RGf4Ul0sDFzFj_3YiJs4q1FH1H4dumTFMNYU,32753
|
|
7
|
+
selfheal_api/dashboard.py,sha256=rT8Pj3iG5zfsESPl0B_wPEd4w0rdgRJRA2GouRIQFPA,32550
|
|
8
|
+
selfheal_api/eval_fixtures.py,sha256=9HMj5H6kDnF2thK7OYCvkc0TA4wlZ-xpjY_JNn1Yo2Q,932
|
|
9
|
+
selfheal_api/github_app.py,sha256=eGTaVp3ONPZWI0YoSTrZ1wkPvheicwpprGq3VLU_30Q,38213
|
|
10
|
+
selfheal_api/github_jwt.py,sha256=V7fNzVAOKAhLWraws3sqCsv8jBduUezv0oLwU4zvXH4,5108
|
|
11
|
+
selfheal_api/ledger.py,sha256=nXWn3hOXlmmq7H7Pj1Qhwh17lpV9vnTEh_EuSX8qjp8,9915
|
|
12
|
+
selfheal_api/metrics.py,sha256=HQWBGbppAlJxvlc_5Abi1EvHAMZEUQ1E1QyTMcWCzGA,9105
|
|
13
|
+
selfheal_api/middleware.py,sha256=YJnk-VWDhW38kGx1LlNFavChkBLkAHoYsfo32qHmw_4,11138
|
|
14
|
+
selfheal_api/modelgen.py,sha256=wPvdYNVR5Q1kIDiL0woAdRQ6Hn8qx9U1zmo44f9blP8,11379
|
|
15
|
+
selfheal_api/notifier.py,sha256=TuKreVlaM_4G_dLq6giq45PaCnHkA4TE-dI9NBA37Yc,13897
|
|
16
|
+
selfheal_api/remediation.py,sha256=rv-ijb4bsAg5hkcJ-pYdCvWiEdR9719uMLY2ZZgwO48,10520
|
|
17
|
+
selfheal_api/replay.py,sha256=auX_sIdvONtX69xhliWkZUflgQvhYP-9xS324y4fuvY,3923
|
|
18
|
+
selfheal_api/sandbox.py,sha256=7Ygn8AOaCHZ4eGAD0IEYXqk_RU0H80a-hOKZ-ykYQw0,5269
|
|
19
|
+
selfheal_api/server.py,sha256=yQiWobvkB3ZnS9zJCxCKlLnXdlTqVIwer4DOxOpxPz4,59231
|
|
20
|
+
selfheal_api/server_hosted.py,sha256=xi5Jgx-NNRfFnvkGrupNzt-1K5bD7nB6wJLHVlk0kpM,61194
|
|
21
|
+
selfheal_api/specwatch.py,sha256=KREoc3EBNWUxmbKcgtN5GFaMps8yfY0utrL_S_a2MYY,7027
|
|
22
|
+
selfheal_api/worker.py,sha256=UXgrOuiFJRjpSCTxYXSpUI_VyGu2v5pGd3W33bgmBEU,7274
|
|
23
|
+
sentinel/__init__.py,sha256=V77LHZX9wSd00dDb7_eqhO5Hf-dSYF1gzGuTuvbyzCs,775
|
|
24
|
+
sentinel/detector.py,sha256=iTINWPG1piEhx72LNCng1upZfiX9HKzZ99iU6jxzGCM,22103
|
|
25
|
+
sentinel/guard.py,sha256=uJZdnvBEhZR2a_gG6tl1AOoFUbYNgLV38ePr68fCH-w,13055
|
|
26
|
+
sentinel/llm_fallback.py,sha256=T69y2L6fzYzfyHVRoEBMXR7fXZAhI6mK4shST2g1Cv4,8753
|
|
27
|
+
synthesizer/__init__.py,sha256=LNJaQp0JiLjhY1SG-z3coAFmDCI6ESz3rKZYvJ54mvE,710
|
|
28
|
+
synthesizer/openapi_emitter.py,sha256=vxNMBw76ZiRr11sloEvaKLvv9QI0wcwZjWFodILgv6c,5925
|
|
29
|
+
synthesizer/patcher.py,sha256=IAYkHkl0j4g1mRMcNJEverc7P6pMPlmp1oyHei6s8is,35582
|
|
30
|
+
synthesizer/zod_emitter.py,sha256=ASZyktBNpEk8aeY0yumBJnCaFEOUod8t4eOylMNYQfQ,14285
|
|
31
|
+
datapi_selfheal-0.3.0.dist-info/METADATA,sha256=4B6GN_Ms3ECVYqQhKyDbXyl0wZkezAZA4hfWTZKgA_0,16584
|
|
32
|
+
datapi_selfheal-0.3.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
33
|
+
datapi_selfheal-0.3.0.dist-info/entry_points.txt,sha256=PAsUxZCmwwy3Ept2rq9slrsZG0BT4MCp41kgrEVQNu0,101
|
|
34
|
+
datapi_selfheal-0.3.0.dist-info/top_level.txt,sha256=nZMY35_4wl9x4LV66nUClqxfZ1P2Ie544_4oNsOz8yk,34
|
|
35
|
+
datapi_selfheal-0.3.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SelfHealAPI Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
selfheal_api/__init__.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
from selfheal_api.billing import BillingStore
|
|
2
|
+
from selfheal_api.github_app import InstallationRegistry
|
|
3
|
+
from selfheal_api.ledger import DriftEventRecord, DriftLedger, OrgDriftSummary
|
|
4
|
+
from selfheal_api.middleware import (
|
|
5
|
+
RouteBinding,
|
|
6
|
+
SelfHealASGIMiddleware,
|
|
7
|
+
SelfHealWSGIMiddleware,
|
|
8
|
+
)
|
|
9
|
+
from selfheal_api.notifier import (
|
|
10
|
+
AlertNotifier,
|
|
11
|
+
CompositeAlertNotifier,
|
|
12
|
+
DriftAlert,
|
|
13
|
+
SignedWebhookNotifier,
|
|
14
|
+
UrllibSlackNotifier,
|
|
15
|
+
)
|
|
16
|
+
from selfheal_api.remediation import (
|
|
17
|
+
RemediationOutcome,
|
|
18
|
+
RemediationPipeline,
|
|
19
|
+
RemediationRequest,
|
|
20
|
+
)
|
|
21
|
+
from selfheal_api.replay import ReplayReport, run_replay_corpus
|
|
22
|
+
from selfheal_api.server import ServerConfig, create_server
|
|
23
|
+
from selfheal_api.worker import RemediationQueue
|
|
24
|
+
from sentinel import (
|
|
25
|
+
AnthropicSchemaMappingProvider,
|
|
26
|
+
DeterministicMappingProvider,
|
|
27
|
+
DriftDeduplicator,
|
|
28
|
+
DriftIssue,
|
|
29
|
+
DriftKind,
|
|
30
|
+
DriftReport,
|
|
31
|
+
PrimitiveKind,
|
|
32
|
+
SchemaMappingProvider,
|
|
33
|
+
compute_drift_fingerprint,
|
|
34
|
+
detect_drift,
|
|
35
|
+
redact_payload,
|
|
36
|
+
selfheal_guard,
|
|
37
|
+
)
|
|
38
|
+
from synthesizer import (
|
|
39
|
+
PatchAction,
|
|
40
|
+
PatchPlan,
|
|
41
|
+
PatchResult,
|
|
42
|
+
VerificationResult,
|
|
43
|
+
apply_patch_plan_in_memory,
|
|
44
|
+
build_patch_plan,
|
|
45
|
+
emit_openapi_document,
|
|
46
|
+
emit_openapi_schema_patch,
|
|
47
|
+
synthesize_patch,
|
|
48
|
+
synthesize_zod_preprocessor,
|
|
49
|
+
verify_patch,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
__version__ = "0.3.0"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def healthcheck() -> str:
|
|
56
|
+
return "ok"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
__all__ = [
|
|
60
|
+
"AlertNotifier",
|
|
61
|
+
"AnthropicSchemaMappingProvider",
|
|
62
|
+
"BillingStore",
|
|
63
|
+
"CompositeAlertNotifier",
|
|
64
|
+
"DeterministicMappingProvider",
|
|
65
|
+
"DriftAlert",
|
|
66
|
+
"DriftDeduplicator",
|
|
67
|
+
"DriftEventRecord",
|
|
68
|
+
"DriftIssue",
|
|
69
|
+
"DriftKind",
|
|
70
|
+
"DriftLedger",
|
|
71
|
+
"DriftReport",
|
|
72
|
+
"InstallationRegistry",
|
|
73
|
+
"OrgDriftSummary",
|
|
74
|
+
"PatchAction",
|
|
75
|
+
"PatchPlan",
|
|
76
|
+
"PatchResult",
|
|
77
|
+
"PrimitiveKind",
|
|
78
|
+
"RemediationOutcome",
|
|
79
|
+
"RemediationPipeline",
|
|
80
|
+
"RemediationQueue",
|
|
81
|
+
"RemediationRequest",
|
|
82
|
+
"ReplayReport",
|
|
83
|
+
"RouteBinding",
|
|
84
|
+
"SchemaMappingProvider",
|
|
85
|
+
"SelfHealASGIMiddleware",
|
|
86
|
+
"SelfHealWSGIMiddleware",
|
|
87
|
+
"ServerConfig",
|
|
88
|
+
"SignedWebhookNotifier",
|
|
89
|
+
"UrllibSlackNotifier",
|
|
90
|
+
"VerificationResult",
|
|
91
|
+
"__version__",
|
|
92
|
+
"apply_patch_plan_in_memory",
|
|
93
|
+
"build_patch_plan",
|
|
94
|
+
"compute_drift_fingerprint",
|
|
95
|
+
"create_server",
|
|
96
|
+
"detect_drift",
|
|
97
|
+
"emit_openapi_document",
|
|
98
|
+
"emit_openapi_schema_patch",
|
|
99
|
+
"healthcheck",
|
|
100
|
+
"redact_payload",
|
|
101
|
+
"run_replay_corpus",
|
|
102
|
+
"selfheal_guard",
|
|
103
|
+
"synthesize_patch",
|
|
104
|
+
"synthesize_zod_preprocessor",
|
|
105
|
+
"verify_patch",
|
|
106
|
+
]
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Sandboxed child entrypoint for tenant model code (EXP-12-SBX).
|
|
2
|
+
|
|
3
|
+
Executed as ``python -m selfheal_api._sandbox_exec`` by
|
|
4
|
+
:func:`selfheal_api.sandbox.run_isolated`. Reads a JSON job from stdin,
|
|
5
|
+
materializes the tenant Pydantic model, runs detect -> synthesize ->
|
|
6
|
+
verify -> emit, and writes a single-line JSON result to real stdout.
|
|
7
|
+
|
|
8
|
+
stdout is kept clean for the result line: ``sys.stdout`` is rebound to
|
|
9
|
+
stderr before tenant code executes so stray ``print`` calls cannot
|
|
10
|
+
corrupt the protocol. The parent additionally parses the last
|
|
11
|
+
JSON-parseable stdout line, so ``os.write(1, ...)`` from tenant code
|
|
12
|
+
still cannot forge a result — worst case the job fails closed.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import sys
|
|
19
|
+
from typing import Any, TextIO
|
|
20
|
+
|
|
21
|
+
from pydantic import BaseModel
|
|
22
|
+
|
|
23
|
+
from sentinel.detector import detect_drift
|
|
24
|
+
from sentinel.guard import compute_drift_fingerprint
|
|
25
|
+
from synthesizer.openapi_emitter import emit_openapi_schema_patch
|
|
26
|
+
from synthesizer.patcher import synthesize_patch, verify_patch
|
|
27
|
+
from synthesizer.zod_emitter import synthesize_zod_preprocessor
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _materialize_model(model_name: str, model_source: str) -> type[BaseModel] | None:
|
|
31
|
+
"""Exec tenant model source and resolve the expected model class."""
|
|
32
|
+
namespace: dict[str, Any] = {"__name__": "_selfheal_tenant_model"}
|
|
33
|
+
exec(compile(model_source, "<tenant_model_source>", "exec"), namespace)
|
|
34
|
+
for value in namespace.values():
|
|
35
|
+
if (
|
|
36
|
+
isinstance(value, type)
|
|
37
|
+
and issubclass(value, BaseModel)
|
|
38
|
+
and value is not BaseModel
|
|
39
|
+
):
|
|
40
|
+
value.model_rebuild(_types_namespace=namespace, force=True)
|
|
41
|
+
candidate = namespace.get(model_name)
|
|
42
|
+
if isinstance(candidate, type) and issubclass(candidate, BaseModel):
|
|
43
|
+
return candidate
|
|
44
|
+
for value in namespace.values():
|
|
45
|
+
if (
|
|
46
|
+
isinstance(value, type)
|
|
47
|
+
and issubclass(value, BaseModel)
|
|
48
|
+
and value is not BaseModel
|
|
49
|
+
):
|
|
50
|
+
return value
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def run_job(job: dict[str, Any]) -> dict[str, Any]:
|
|
55
|
+
"""Run the tenant-code pipeline portion and return a JSON-able result."""
|
|
56
|
+
model_name = str(job.get("model_name") or "")
|
|
57
|
+
model_source = str(job.get("model_source") or "")
|
|
58
|
+
drifted_payload = job.get("drifted_payload")
|
|
59
|
+
canonical_payload = job.get("canonical_payload")
|
|
60
|
+
if not model_name or not model_source:
|
|
61
|
+
return {"ok": False, "error": "job missing model_name/model_source"}
|
|
62
|
+
if not isinstance(drifted_payload, dict):
|
|
63
|
+
return {"ok": False, "error": "drifted_payload must be a JSON object"}
|
|
64
|
+
|
|
65
|
+
model_cls = _materialize_model(model_name, model_source)
|
|
66
|
+
if model_cls is None:
|
|
67
|
+
return {
|
|
68
|
+
"ok": False,
|
|
69
|
+
"error": "no pydantic model class found in model_source",
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
report = detect_drift(model_cls, drifted_payload)
|
|
73
|
+
fingerprint = compute_drift_fingerprint(report)
|
|
74
|
+
result: dict[str, Any] = {
|
|
75
|
+
"ok": True,
|
|
76
|
+
"has_drift": report.has_drift,
|
|
77
|
+
"fingerprint": fingerprint,
|
|
78
|
+
"model_name": report.model_name,
|
|
79
|
+
"issue_count": len(report.issues),
|
|
80
|
+
"issue_kinds": [str(issue.kind) for issue in report.issues],
|
|
81
|
+
}
|
|
82
|
+
if not report.has_drift:
|
|
83
|
+
return result
|
|
84
|
+
|
|
85
|
+
patch_result = synthesize_patch(model_source, report, root_model=model_cls)
|
|
86
|
+
verification = verify_patch(
|
|
87
|
+
patch_result, drifted_payload, canonical_payload
|
|
88
|
+
)
|
|
89
|
+
result.update(
|
|
90
|
+
{
|
|
91
|
+
"patched_source": patch_result.patched_source,
|
|
92
|
+
"patch_applied": patch_result.applied,
|
|
93
|
+
"zod_adapter": synthesize_zod_preprocessor(patch_result.plan),
|
|
94
|
+
"openapi_yaml": emit_openapi_schema_patch(
|
|
95
|
+
model_cls, patch_result.plan
|
|
96
|
+
).yaml_snippet,
|
|
97
|
+
"verify_passed": verification.passed,
|
|
98
|
+
"verify_error": verification.error_detail,
|
|
99
|
+
}
|
|
100
|
+
)
|
|
101
|
+
return result
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def main() -> int:
|
|
105
|
+
# Keep protocol stdout clean: tenant prints land on stderr instead.
|
|
106
|
+
sys.stdout = sys.stderr
|
|
107
|
+
try:
|
|
108
|
+
job = json.load(sys.stdin)
|
|
109
|
+
if not isinstance(job, dict):
|
|
110
|
+
raise ValueError("job payload must be a JSON object")
|
|
111
|
+
result = run_job(job)
|
|
112
|
+
except Exception as exc: # noqa: BLE001 - child must always emit JSON
|
|
113
|
+
result = {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
|
|
114
|
+
result_line = json.dumps(result, separators=(",", ":")) + "\n"
|
|
115
|
+
real_stdout: TextIO = (
|
|
116
|
+
sys.__stdout__ if sys.__stdout__ is not None else sys.stderr
|
|
117
|
+
)
|
|
118
|
+
real_stdout.write(result_line)
|
|
119
|
+
real_stdout.flush()
|
|
120
|
+
return 0
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
if __name__ == "__main__":
|
|
124
|
+
raise SystemExit(main())
|