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
selfheal_api/replay.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, ConfigDict, ValidationError
|
|
9
|
+
|
|
10
|
+
from sentinel.detector import detect_drift
|
|
11
|
+
from synthesizer.patcher import PatchPlan, apply_patch_plan_in_memory
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ReplaySample(BaseModel):
|
|
15
|
+
"""Single recorded payload sample for regression replay."""
|
|
16
|
+
|
|
17
|
+
model_config = ConfigDict(frozen=True)
|
|
18
|
+
|
|
19
|
+
sample_id: str
|
|
20
|
+
payload: dict[str, Any]
|
|
21
|
+
expect_valid: bool = True
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ReplayReport(BaseModel):
|
|
25
|
+
"""Summary of replaying a corpus against a Pydantic model."""
|
|
26
|
+
|
|
27
|
+
model_config = ConfigDict(frozen=True)
|
|
28
|
+
|
|
29
|
+
model_name: str
|
|
30
|
+
total: int
|
|
31
|
+
passed: int
|
|
32
|
+
failed: int
|
|
33
|
+
drifted: int
|
|
34
|
+
failures: tuple[str, ...] = ()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def load_jsonl_samples(
|
|
38
|
+
path: str | Path,
|
|
39
|
+
*,
|
|
40
|
+
max_samples: int = 5000,
|
|
41
|
+
) -> list[ReplaySample]:
|
|
42
|
+
"""Load ReplaySample records from a JSONL file, skipping blank lines."""
|
|
43
|
+
if max_samples < 0:
|
|
44
|
+
raise ValueError("max_samples must be non-negative")
|
|
45
|
+
|
|
46
|
+
file_path = Path(path)
|
|
47
|
+
samples: list[ReplaySample] = []
|
|
48
|
+
with file_path.open("r", encoding="utf-8") as handle:
|
|
49
|
+
for line_no, raw_line in enumerate(handle, start=1):
|
|
50
|
+
stripped = raw_line.strip()
|
|
51
|
+
if not stripped:
|
|
52
|
+
continue
|
|
53
|
+
if len(samples) >= max_samples:
|
|
54
|
+
raise ValueError(f"Exceeded max_samples limit of {max_samples}")
|
|
55
|
+
try:
|
|
56
|
+
parsed = json.loads(stripped)
|
|
57
|
+
except json.JSONDecodeError as exc:
|
|
58
|
+
raise ValueError(f"Invalid JSON on line {line_no}") from exc
|
|
59
|
+
if not isinstance(parsed, dict):
|
|
60
|
+
raise ValueError(f"Expected JSON object on line {line_no}")
|
|
61
|
+
try:
|
|
62
|
+
sample = ReplaySample.model_validate(parsed)
|
|
63
|
+
except ValidationError as exc:
|
|
64
|
+
raise ValueError(
|
|
65
|
+
f"Invalid ReplaySample on line {line_no}: {type(exc).__name__}"
|
|
66
|
+
) from exc
|
|
67
|
+
samples.append(sample)
|
|
68
|
+
return samples
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _format_failure(sample_id: str, exc: Exception) -> str:
|
|
72
|
+
"""Format a failure string using exception type and error locs without raw PII."""
|
|
73
|
+
if isinstance(exc, ValidationError):
|
|
74
|
+
locs = ", ".join(
|
|
75
|
+
".".join(str(part) for part in err.get("loc", ())) or "<root>"
|
|
76
|
+
for err in exc.errors()
|
|
77
|
+
)
|
|
78
|
+
return f"{sample_id}: {type(exc).__name__} at {locs}"
|
|
79
|
+
return f"{sample_id}: {type(exc).__name__}"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def run_replay_corpus(
|
|
83
|
+
model_cls: type[BaseModel],
|
|
84
|
+
samples: Sequence[ReplaySample],
|
|
85
|
+
*,
|
|
86
|
+
plan: PatchPlan | None = None,
|
|
87
|
+
) -> ReplayReport:
|
|
88
|
+
"""Replay samples against model_cls, optionally applying a PatchPlan first."""
|
|
89
|
+
passed = 0
|
|
90
|
+
failed = 0
|
|
91
|
+
drifted = 0
|
|
92
|
+
failures: list[str] = []
|
|
93
|
+
|
|
94
|
+
for sample in samples:
|
|
95
|
+
drift_report = detect_drift(model_cls, sample.payload)
|
|
96
|
+
if drift_report.has_drift:
|
|
97
|
+
drifted += 1
|
|
98
|
+
|
|
99
|
+
try:
|
|
100
|
+
candidate = (
|
|
101
|
+
apply_patch_plan_in_memory(sample.payload, plan, root_model=model_cls)
|
|
102
|
+
if plan is not None
|
|
103
|
+
else sample.payload
|
|
104
|
+
)
|
|
105
|
+
model_cls.model_validate(candidate, strict=True)
|
|
106
|
+
except Exception as exc: # noqa: BLE001
|
|
107
|
+
if not sample.expect_valid:
|
|
108
|
+
passed += 1
|
|
109
|
+
else:
|
|
110
|
+
failed += 1
|
|
111
|
+
failures.append(_format_failure(sample.sample_id, exc))
|
|
112
|
+
else:
|
|
113
|
+
if sample.expect_valid:
|
|
114
|
+
passed += 1
|
|
115
|
+
else:
|
|
116
|
+
failed += 1
|
|
117
|
+
failures.append(f"{sample.sample_id}: ExpectedValidationFailure")
|
|
118
|
+
|
|
119
|
+
return ReplayReport(
|
|
120
|
+
model_name=model_cls.__name__,
|
|
121
|
+
total=len(samples),
|
|
122
|
+
passed=passed,
|
|
123
|
+
failed=failed,
|
|
124
|
+
drifted=drifted,
|
|
125
|
+
failures=tuple(failures),
|
|
126
|
+
)
|
selfheal_api/sandbox.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Isolated subprocess execution for tenant model code (EXP-12-SBX).
|
|
2
|
+
|
|
3
|
+
``expected_model`` materialization, drift detection, patch synthesis and
|
|
4
|
+
``verify_patch`` all exec tenant-controlled Python. Per the locked spec
|
|
5
|
+
they run in a scrubbed-env, rlimit-bounded subprocess; quota checks,
|
|
6
|
+
installation-token PR writes, ledger and notify stay in the parent.
|
|
7
|
+
|
|
8
|
+
Accepted residual (documented in PROJECT_SPEC.md §12): the child shares
|
|
9
|
+
host networking, so tenant code can reach api.github.com and the GCP
|
|
10
|
+
metadata server — it inherits no credentials and sees only IAM-scoped
|
|
11
|
+
metadata.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import subprocess
|
|
19
|
+
import sys
|
|
20
|
+
import tempfile
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
_PACKAGE_SRC = Path(__file__).resolve().parents[1]
|
|
25
|
+
|
|
26
|
+
_DEFAULT_TIMEOUT_SECONDS = 30.0
|
|
27
|
+
_MAX_STDOUT_BYTES = 16 * 1024 * 1024
|
|
28
|
+
_DEFAULT_MAX_MEMORY_MB = 1024
|
|
29
|
+
_DEFAULT_CPU_SECONDS = 25
|
|
30
|
+
_MAX_FILE_BYTES = 64 * 1024 * 1024
|
|
31
|
+
_MAX_OPEN_FILES = 64
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SandboxError(Exception):
|
|
35
|
+
"""Sandboxed pipeline execution failed or produced no result."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _package_pythonpath() -> str:
|
|
39
|
+
entries = [str(_PACKAGE_SRC)]
|
|
40
|
+
existing = os.environ.get("PYTHONPATH", "")
|
|
41
|
+
if existing:
|
|
42
|
+
entries.append(existing)
|
|
43
|
+
return os.pathsep.join(entries)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def scrubbed_env() -> dict[str, str]:
|
|
47
|
+
"""Minimal environment for the sandbox child — no control-plane secrets."""
|
|
48
|
+
candidates = {
|
|
49
|
+
"PATH": os.environ.get("PATH", ""),
|
|
50
|
+
"HOME": os.environ.get("HOME", ""),
|
|
51
|
+
"LANG": os.environ.get("LANG", "C.UTF-8"),
|
|
52
|
+
"LC_ALL": os.environ.get("LC_ALL", "C.UTF-8"),
|
|
53
|
+
"TMPDIR": os.environ.get("TMPDIR", tempfile.gettempdir()),
|
|
54
|
+
"SYSTEMROOT": os.environ.get("SYSTEMROOT", ""),
|
|
55
|
+
"WINDIR": os.environ.get("WINDIR", ""),
|
|
56
|
+
"PYTHONIOENCODING": "utf-8",
|
|
57
|
+
"PYTHONPATH": _package_pythonpath(),
|
|
58
|
+
}
|
|
59
|
+
return {key: value for key, value in candidates.items() if value}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _rlimit_values() -> list[tuple[int, tuple[int, int]]]:
|
|
63
|
+
try:
|
|
64
|
+
import resource
|
|
65
|
+
except ImportError: # pragma: no cover - non-POSIX
|
|
66
|
+
return []
|
|
67
|
+
cpu_seconds = int(
|
|
68
|
+
os.environ.get("SELFHEAL_SANDBOX_CPU_SECONDS", str(_DEFAULT_CPU_SECONDS))
|
|
69
|
+
)
|
|
70
|
+
max_memory = int(
|
|
71
|
+
os.environ.get(
|
|
72
|
+
"SELFHEAL_SANDBOX_MAX_MEMORY_MB", str(_DEFAULT_MAX_MEMORY_MB)
|
|
73
|
+
)
|
|
74
|
+
) * 1024 * 1024
|
|
75
|
+
specs: list[tuple[int, tuple[int, int]]] = [
|
|
76
|
+
(resource.RLIMIT_CPU, (cpu_seconds, cpu_seconds + 5)),
|
|
77
|
+
(resource.RLIMIT_AS, (max_memory, max_memory)),
|
|
78
|
+
(resource.RLIMIT_FSIZE, (_MAX_FILE_BYTES, _MAX_FILE_BYTES)),
|
|
79
|
+
(resource.RLIMIT_NOFILE, (_MAX_OPEN_FILES, _MAX_OPEN_FILES)),
|
|
80
|
+
(resource.RLIMIT_CORE, (0, 0)),
|
|
81
|
+
]
|
|
82
|
+
return specs
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _apply_rlimits() -> None:
|
|
86
|
+
try:
|
|
87
|
+
import resource
|
|
88
|
+
except ImportError: # pragma: no cover - non-POSIX
|
|
89
|
+
return
|
|
90
|
+
for res, limits in _rlimit_values():
|
|
91
|
+
try:
|
|
92
|
+
resource.setrlimit(res, limits)
|
|
93
|
+
except (ValueError, OSError):
|
|
94
|
+
continue
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _parse_result(stdout: str) -> dict[str, Any]:
|
|
98
|
+
"""Return the last JSON-parseable stdout line (tenant prints ignored)."""
|
|
99
|
+
for line in reversed(stdout.splitlines()):
|
|
100
|
+
line = line.strip()
|
|
101
|
+
if not line.startswith("{"):
|
|
102
|
+
continue
|
|
103
|
+
try:
|
|
104
|
+
parsed = json.loads(line)
|
|
105
|
+
except json.JSONDecodeError:
|
|
106
|
+
continue
|
|
107
|
+
if isinstance(parsed, dict):
|
|
108
|
+
return parsed
|
|
109
|
+
raise SandboxError("sandbox produced no JSON result on stdout")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def run_isolated(
|
|
113
|
+
job: dict[str, Any],
|
|
114
|
+
*,
|
|
115
|
+
timeout_seconds: float | None = None,
|
|
116
|
+
) -> dict[str, Any]:
|
|
117
|
+
"""Run the tenant-code pipeline portion in a bounded subprocess.
|
|
118
|
+
|
|
119
|
+
``job`` must contain ``model_name``, ``model_source``,
|
|
120
|
+
``drifted_payload`` and optional ``canonical_payload``. Returns the
|
|
121
|
+
child's JSON result; raises :class:`SandboxError` on transport,
|
|
122
|
+
timeout, or protocol failures.
|
|
123
|
+
"""
|
|
124
|
+
timeout = timeout_seconds or float(
|
|
125
|
+
os.environ.get("SELFHEAL_SANDBOX_TIMEOUT", str(_DEFAULT_TIMEOUT_SECONDS))
|
|
126
|
+
)
|
|
127
|
+
command = [sys.executable, "-m", "selfheal_api._sandbox_exec"]
|
|
128
|
+
kwargs: dict[str, Any] = {
|
|
129
|
+
"input": json.dumps(job).encode("utf-8"),
|
|
130
|
+
"stdout": subprocess.PIPE,
|
|
131
|
+
"stderr": subprocess.PIPE,
|
|
132
|
+
"env": scrubbed_env(),
|
|
133
|
+
"timeout": timeout,
|
|
134
|
+
}
|
|
135
|
+
if os.name == "posix":
|
|
136
|
+
kwargs["preexec_fn"] = _apply_rlimits
|
|
137
|
+
try:
|
|
138
|
+
proc = subprocess.run(command, **kwargs) # noqa: S603 - fixed argv
|
|
139
|
+
except subprocess.TimeoutExpired as exc:
|
|
140
|
+
raise SandboxError(
|
|
141
|
+
f"sandbox timed out after {timeout:.0f}s"
|
|
142
|
+
) from exc
|
|
143
|
+
except OSError as exc:
|
|
144
|
+
raise SandboxError(f"sandbox spawn failed: {exc}") from exc
|
|
145
|
+
|
|
146
|
+
stdout = proc.stdout[:_MAX_STDOUT_BYTES].decode("utf-8", errors="replace")
|
|
147
|
+
stderr_tail = proc.stderr[-2000:].decode("utf-8", errors="replace")
|
|
148
|
+
if proc.returncode != 0:
|
|
149
|
+
raise SandboxError(
|
|
150
|
+
f"sandbox exited {proc.returncode}: {stderr_tail.strip()[:400]}"
|
|
151
|
+
)
|
|
152
|
+
try:
|
|
153
|
+
return _parse_result(stdout)
|
|
154
|
+
except SandboxError as exc:
|
|
155
|
+
raise SandboxError(
|
|
156
|
+
f"sandbox result unparseable; stderr: {stderr_tail.strip()[:400]}"
|
|
157
|
+
) from exc
|