failslice 0.1.1__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.
failslice/__init__.py ADDED
@@ -0,0 +1,49 @@
1
+ """FailSlice: shrink multi-table data to a small, FK-consistent, verified reproducer.
2
+
3
+ Typical use::
4
+
5
+ import failslice
6
+
7
+ project = failslice.load_project("failslice.yaml")
8
+ report = failslice.check(project) # FK orphans, predicate determinism
9
+ result = failslice.reduce(project) # reduce, export, replay in a fresh process
10
+ print(result.minimality_label, result.verification.status)
11
+
12
+ See ``docs/design.md`` for the guarantees and their limits.
13
+ """
14
+
15
+ __version__ = "0.1.1"
16
+
17
+ from failslice.api import CheckReport, ReductionResult, check, reduce, validate_predicate, verify
18
+ from failslice.config import ConfigError, Project, load_project
19
+ from failslice.reducer import (
20
+ Budget,
21
+ DeterminismError,
22
+ Minimality,
23
+ PredicateNotFailingError,
24
+ ProgressEvent,
25
+ StopReason,
26
+ )
27
+ from failslice.safety import PredicateValidationError
28
+ from failslice.verify import VerificationReport
29
+
30
+ __all__ = [
31
+ "Budget",
32
+ "CheckReport",
33
+ "ConfigError",
34
+ "DeterminismError",
35
+ "Minimality",
36
+ "PredicateNotFailingError",
37
+ "PredicateValidationError",
38
+ "ProgressEvent",
39
+ "Project",
40
+ "ReductionResult",
41
+ "StopReason",
42
+ "VerificationReport",
43
+ "__version__",
44
+ "check",
45
+ "load_project",
46
+ "reduce",
47
+ "validate_predicate",
48
+ "verify",
49
+ ]
@@ -0,0 +1,14 @@
1
+ version: 1
2
+ tables:
3
+ customers: { path: data/generated/customers.csv, primary_key: id }
4
+ orders: { path: data/generated/orders.csv, primary_key: order_id }
5
+ lines: { path: data/generated/lines.csv }
6
+ foreign_keys:
7
+ - orders.customer_id -> customers.id
8
+ - lines.order_id -> orders.order_id
9
+ predicate:
10
+ # The bug: order 4242 was loaded twice, so joining lines to orders double-counts.
11
+ sql: |
12
+ SELECT (SELECT sum(l.amount) FROM lines l JOIN orders o USING (order_id))
13
+ <> (SELECT sum(amount) FROM lines)
14
+ settings: { seed: 0, max_evals: 5000, wall_clock_s: 300 }
@@ -0,0 +1,40 @@
1
+ """Generate the quickstart data: 1,000 customers, 5,001 orders, 20,000 order lines.
2
+
3
+ The planted bug: order 4242 was loaded twice ("late-arriving duplicate"), so joining
4
+ lines to orders double-counts that order's lines.
5
+
6
+ Run from this directory: ``python make_data.py`` (writes ``data/generated/*.csv``).
7
+ """
8
+
9
+ from pathlib import Path
10
+
11
+ import duckdb
12
+
13
+
14
+ def _literal(path: Path) -> str:
15
+ """``path`` as a SQL string literal (COPY ... TO takes no parameters)."""
16
+ return "'" + str(path).replace("'", "''") + "'"
17
+
18
+
19
+ def main(out: Path = Path(__file__).parent / "data" / "generated") -> None:
20
+ out.mkdir(parents=True, exist_ok=True)
21
+ con = duckdb.connect()
22
+ try:
23
+ con.execute(
24
+ "COPY (SELECT i AS id, 'customer ' || i AS name FROM range(1000) r(i)) "
25
+ f"TO {_literal(out / 'customers.csv')}"
26
+ )
27
+ con.execute(
28
+ "COPY (SELECT i AS order_id, i % 1000 AS customer_id FROM range(5000) r(i) "
29
+ f"UNION ALL SELECT 4242, 242) TO {_literal(out / 'orders.csv')}"
30
+ )
31
+ con.execute(
32
+ "COPY (SELECT i AS line_id, i % 5000 AS order_id, (i % 7) * 1.5 AS amount "
33
+ f"FROM range(20000) r(i)) TO {_literal(out / 'lines.csv')}"
34
+ )
35
+ finally:
36
+ con.close()
37
+
38
+
39
+ if __name__ == "__main__":
40
+ main()
failslice/api.py ADDED
@@ -0,0 +1,363 @@
1
+ """Public API: :func:`check`, :func:`reduce`, :func:`verify`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import datetime as _dt
7
+ import secrets
8
+ import threading
9
+ import time
10
+ from collections.abc import Callable
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import Any, Literal
14
+
15
+ from failslice.artifacts import Manifest, RunContext, finalize, minimality_label
16
+ from failslice.config import ConfigError, Project, resolve_inside
17
+ from failslice.engine import Engine
18
+ from failslice.predicate import Outcome
19
+ from failslice.reducer import (
20
+ Budget,
21
+ BudgetExhaustedError,
22
+ DeterminismError,
23
+ PredicateNotFailingError,
24
+ ProgressEvent,
25
+ Reducer,
26
+ ReductionStats,
27
+ StopReason,
28
+ )
29
+ from failslice.runspec import RunSpec
30
+ from failslice.safety import validate_predicate_sql
31
+ from failslice.supervisor import (
32
+ CANCELLED,
33
+ SupervisedOutcome,
34
+ run_check_supervised,
35
+ run_supervised,
36
+ write_checkpoint,
37
+ )
38
+ from failslice.verify import VerificationReport, verify_in_subprocess
39
+
40
+ __all__ = ["CheckReport", "ReductionResult", "check", "reduce", "validate_predicate", "verify"]
41
+
42
+ MIN_REPLAY_S = 10.0
43
+
44
+
45
+ def replay_reserve(wall_clock_s: float) -> float:
46
+ """Part of ``wall_clock_s`` kept back for export and the independent replay:
47
+ 10% but at least ``MIN_REPLAY_S``, and never more than half the budget (so short
48
+ budgets still leave time to reduce)."""
49
+ return min(max(MIN_REPLAY_S, 0.1 * wall_clock_s), 0.5 * wall_clock_s)
50
+
51
+
52
+ def validate_predicate(project: Project) -> None:
53
+ """Validate the predicate query against the safety rules (ADR 0007)."""
54
+ for sql in project.predicate_queries():
55
+ validate_predicate_sql(sql, project.tables.keys())
56
+
57
+
58
+ @dataclass
59
+ class CheckReport:
60
+ """Result of :func:`check`."""
61
+
62
+ ok: bool
63
+ tables: dict[str, dict[str, Any]] = field(default_factory=dict)
64
+ orphans: dict[str, int] = field(default_factory=dict)
65
+ outcomes: list[Outcome] = field(default_factory=list)
66
+ deterministic: bool = False
67
+ problems: list[str] = field(default_factory=list)
68
+ stop: Literal["budget", "killed", "crashed", "cancelled"] | None = None
69
+ """Set when the check did not finish: its budget ran out, or (isolated) it was killed
70
+ at its deadline or crashed."""
71
+
72
+
73
+ def check(
74
+ project: Project, *, isolate: bool = False, cancel: threading.Event | None = None
75
+ ) -> CheckReport:
76
+ """Validate the predicate, load the data, report FK orphans and run the
77
+ determinism check (the predicate must be TRUE on the full data, four times,
78
+ with identical signatures).
79
+
80
+ With ``isolate=True`` the check runs in a supervised child process (hard deadline
81
+ ``wall_clock_s``; one evaluation may not exceed ``eval_timeout_s`` plus a grace).
82
+ Setting ``cancel`` stops the check (in-process: before the next evaluation).
83
+ """
84
+ validate_predicate(project)
85
+ if isolate:
86
+ return run_check_supervised(project, cancel=cancel)
87
+ return check_in_process(project, cancel=cancel)
88
+
89
+
90
+ def check_in_process(
91
+ project: Project,
92
+ *,
93
+ before_eval: Callable[[], None] | None = None,
94
+ on_progress: Callable[[ProgressEvent], None] | None = None,
95
+ cancel: threading.Event | None = None,
96
+ ) -> CheckReport:
97
+ """The body of :func:`check` (validation already done). The callbacks let a
98
+ supervisor time every evaluation."""
99
+ report = CheckReport(ok=False)
100
+ engine = Engine(project)
101
+ try:
102
+ for name, info in engine.tables.items():
103
+ report.tables[name] = {
104
+ "rows": info.row_count,
105
+ "columns": [list(c) for c in info.columns],
106
+ "source": info.source,
107
+ }
108
+ report.orphans = dict(engine.orphan_counts)
109
+ reducer = Reducer(
110
+ engine,
111
+ Budget(max_evals=4, wall_clock_s=project.settings.wall_clock_s),
112
+ before_eval=before_eval,
113
+ on_progress=on_progress,
114
+ cancel=cancel,
115
+ )
116
+ try:
117
+ report.outcomes = reducer.check_determinism()
118
+ report.deterministic = True
119
+ report.ok = True
120
+ except DeterminismError as exc:
121
+ report.outcomes = exc.outcomes
122
+ report.problems.append(str(exc))
123
+ except BudgetExhaustedError as exc:
124
+ if exc.reason is StopReason.CANCELLED:
125
+ report.problems.append("check cancelled")
126
+ report.stop = "cancelled"
127
+ else:
128
+ report.problems.append(f"check stopped by its budget ({exc.reason.value})")
129
+ report.stop = "budget"
130
+ finally:
131
+ engine.close()
132
+ return report
133
+
134
+
135
+ @dataclass
136
+ class ReductionResult:
137
+ """Result of :func:`reduce`.
138
+
139
+ ``status`` is ``"reduced"`` when a configuration was observed TRUE and exported,
140
+ ``"no-candidate"`` when the run stopped before any confirmed configuration.
141
+ The reproducer is trustworthy only if ``verification.ok``.
142
+ """
143
+
144
+ run_dir: Path
145
+ status: Literal["reduced", "no-candidate", "cancelled"]
146
+ stats: ReductionStats | None
147
+ """Counters of the run; also present for ``no-candidate`` when the run got far
148
+ enough to count anything."""
149
+ verification: VerificationReport | None
150
+ notes: list[str] = field(default_factory=list)
151
+ spec: RunSpec | None = None
152
+ """The exported reproducer's contract (``spec.json``), if one was exported."""
153
+ failure: Literal["killed", "crashed", "cancelled"] | None = None
154
+ """The run was cancelled by the caller, or (isolated runs) the reduction process was
155
+ killed (deadline, unresponsive) or crashed."""
156
+ manifest: Manifest | None = None
157
+ """The run summary (``manifest.json``), written last."""
158
+
159
+ @property
160
+ def minimality_label(self) -> str:
161
+ """``1-minimal (verified)`` only if certification completed, the replay is
162
+ verified and the export was lossless; ``no reproducer`` without a candidate;
163
+ ``reduced, minimality not verified`` otherwise."""
164
+ return minimality_label(self, self.spec)
165
+
166
+
167
+ RUN_ID_PATTERN = r"^\d{8}T\d{6}Z-[0-9a-f]{6}$"
168
+ """Format of generated run ids (also the run directory name)."""
169
+
170
+
171
+ def new_run_id() -> str:
172
+ """A new run id: UTC timestamp plus 6 random hex digits."""
173
+ return _dt.datetime.now(_dt.UTC).strftime("%Y%m%dT%H%M%SZ") + "-" + secrets.token_hex(3)
174
+
175
+
176
+ def _new_run_dir(project: Project, out_dir: str | Path | None) -> tuple[Path, str]:
177
+ """Create the run directory; the run id is the directory's name."""
178
+ run_id = new_run_id()
179
+ if out_dir is None:
180
+ # Resolved like every other path, so a symlinked .failslice cannot redirect writes
181
+ # outside the allowed root.
182
+ run_dir = resolve_inside(
183
+ project.base_dir, Path(".failslice") / "runs" / run_id, project.root
184
+ )
185
+ else:
186
+ run_dir = Path(out_dir).resolve()
187
+ run_dir.mkdir(parents=True, exist_ok=True)
188
+ if any(p.name != ".gitkeep" for p in run_dir.iterdir()):
189
+ raise ConfigError(f"run directory {run_dir} is not empty")
190
+ return run_dir, run_dir.name
191
+
192
+
193
+ def reduce(
194
+ project: Project,
195
+ *,
196
+ out_dir: str | Path | None = None,
197
+ isolate: bool = False,
198
+ on_progress: Callable[[ProgressEvent], None] | None = None,
199
+ cancel: threading.Event | None = None,
200
+ ) -> ReductionResult:
201
+ """Reduce the project's data to a smaller configuration that keeps the predicate
202
+ TRUE, export it into a run directory and replay it in a fresh process.
203
+
204
+ Budgets and seed come from ``project.settings`` (use
205
+ :meth:`Project.with_settings` to change them). With ``isolate=True`` the reduction
206
+ runs in a supervised child process with hard deadlines; otherwise in-process,
207
+ where per-evaluation timeouts are cooperative (DuckDB interrupt).
208
+
209
+ Setting ``cancel`` stops the run: the child is killed (isolated) or the search stops
210
+ before its next evaluation (in-process); nothing is recovered, exported further or
211
+ replayed, and the result has status ``cancelled`` with only the report and manifest.
212
+ """
213
+ validate_predicate(project)
214
+ settings = project.settings
215
+ deadline = time.monotonic() + settings.wall_clock_s # covers reduction, export, replay
216
+ run_dir, run_id = _new_run_dir(project, out_dir)
217
+ context = RunContext.start(project, run_dir, run_id)
218
+ reserve = replay_reserve(settings.wall_clock_s)
219
+ budget = Budget(max_evals=settings.max_evals, wall_clock_s=settings.wall_clock_s - reserve)
220
+ notes: list[str] = []
221
+ stats: ReductionStats | None
222
+ failure: Literal["killed", "crashed", "cancelled"] | None = None
223
+ if isolate:
224
+ sup = run_supervised(
225
+ project,
226
+ run_dir,
227
+ run_id,
228
+ budget,
229
+ deadline=deadline - reserve,
230
+ on_progress=on_progress,
231
+ cancel=cancel,
232
+ )
233
+ stats = _supervised_stats(sup, notes)
234
+ if sup.killed_reason == CANCELLED:
235
+ failure = "cancelled"
236
+ elif sup.killed_reason:
237
+ failure = "killed"
238
+ elif sup.error:
239
+ failure = "crashed"
240
+ else:
241
+ stats = _reduce_in_process(project, run_dir, run_id, budget, on_progress, cancel)
242
+ if cancel is not None and cancel.is_set():
243
+ return _cancelled(context, run_dir, stats, notes, deadline, cancel)
244
+ if stats is None or not stats.confirmed:
245
+ notes.append("stopped before any configuration was confirmed TRUE")
246
+ result = ReductionResult(run_dir, "no-candidate", stats, None, notes, failure=failure)
247
+ return _finish(context, result, deadline, cancel)
248
+ remaining = deadline - time.monotonic()
249
+ if remaining <= 0:
250
+ verification = VerificationReport(
251
+ "unverified", detail="no time left for the independent replay (wall_clock_s)"
252
+ )
253
+ else:
254
+ verification = verify_in_subprocess(run_dir, timeout_s=remaining, cancel=cancel)
255
+ if verification.status == "cancelled":
256
+ return _cancelled(context, run_dir, stats, notes, deadline, cancel)
257
+ spec = RunSpec.read(run_dir)
258
+ notes.extend(spec.warnings)
259
+ result = ReductionResult(run_dir, "reduced", stats, verification, notes, spec, failure=failure)
260
+ return _finish(context, result, deadline, cancel)
261
+
262
+
263
+ def _finish(
264
+ context: RunContext,
265
+ result: ReductionResult,
266
+ deadline: float,
267
+ cancel: threading.Event | None,
268
+ ) -> ReductionResult:
269
+ """Write the artifacts; a cancel that arrives meanwhile turns the outcome into
270
+ ``cancelled`` (the manifest records the same)."""
271
+ manifest = finalize(context, result, deadline=deadline, cancel=cancel)
272
+ if manifest.status == "cancelled" and result.status != "cancelled":
273
+ result = dataclasses.replace(
274
+ result, status="cancelled", failure="cancelled", notes=list(manifest.notes)
275
+ )
276
+ result.manifest = manifest
277
+ return result
278
+
279
+
280
+ def _cancelled(
281
+ context: RunContext,
282
+ run_dir: Path,
283
+ stats: ReductionStats | None,
284
+ notes: list[str],
285
+ deadline: float,
286
+ cancel: threading.Event | None,
287
+ ) -> ReductionResult:
288
+ notes.append("cancelled by the caller: no recovery, replay or further artifacts")
289
+ result = ReductionResult(run_dir, "cancelled", stats, None, notes, failure="cancelled")
290
+ return _finish(context, result, deadline, cancel)
291
+
292
+
293
+ def _supervised_stats(sup: SupervisedOutcome, notes: list[str]) -> ReductionStats | None:
294
+ if sup.determinism_error is not None:
295
+ if sup.predicate_not_failing:
296
+ raise PredicateNotFailingError(sup.determinism_error, [])
297
+ raise DeterminismError(sup.determinism_error, [])
298
+ if sup.killed_reason:
299
+ notes.append(sup.killed_reason)
300
+ if sup.error:
301
+ notes.append(sup.error)
302
+ if sup.recovered:
303
+ notes.append("recovered the last checkpoint after the reduction process stopped")
304
+ if sup.stats is None:
305
+ return sup.unconfirmed_stats
306
+ return sup.stats
307
+
308
+
309
+ def _reduce_in_process(
310
+ project: Project,
311
+ run_dir: Path,
312
+ run_id: str,
313
+ budget: Budget,
314
+ on_progress: Callable[[ProgressEvent], None] | None,
315
+ cancel: threading.Event | None = None,
316
+ ) -> ReductionStats:
317
+ engine = Engine(project, allowed_directories=[run_dir])
318
+ try:
319
+ reducer = Reducer(
320
+ engine,
321
+ budget,
322
+ on_progress=on_progress,
323
+ on_accept=lambda eng: write_checkpoint(eng, run_dir, run_id, reducer.snapshot()),
324
+ on_confirmed=lambda eng: write_checkpoint(eng, run_dir, run_id, reducer.snapshot()),
325
+ cancel=cancel,
326
+ )
327
+ stats = reducer.run(certify=project.settings.minimality)
328
+ cancelled = cancel is not None and cancel.is_set()
329
+ if stats.confirmed and not cancelled: # never export a configuration not observed TRUE
330
+ engine.export(run_dir)
331
+ return stats
332
+ finally:
333
+ engine.close()
334
+
335
+
336
+ def classify(result: ReductionResult) -> tuple[str, str]:
337
+ """The outcome of a finished reduction as ``(status, kind)``, from the recorded reason.
338
+
339
+ ``status``: ``reduced`` (verified reproducer), ``cancelled``, ``no-candidate``,
340
+ ``unverified``, ``replay-failed``, ``integrity-failed``, ``artifact-error`` or ``error``.
341
+ ``kind`` is the CLI exit class: ``ok``, ``failed``, ``inconclusive``, ``error`` or
342
+ ``interrupted``. Shared by the CLI and the MCP server.
343
+ """
344
+ if result.status == "cancelled":
345
+ return "cancelled", "interrupted"
346
+ if result.status == "no-candidate":
347
+ if result.failure == "crashed":
348
+ return "error", "error"
349
+ return "no-candidate", "inconclusive"
350
+ v = result.verification
351
+ if v is None or v.status == "unverified":
352
+ return "unverified", "inconclusive"
353
+ if not v.ok:
354
+ return v.status, "failed"
355
+ m = result.manifest
356
+ if m is not None and any(st.status == "failed" for st in m.steps):
357
+ return "artifact-error", "error"
358
+ return "reduced", "ok"
359
+
360
+
361
+ def verify(run_dir: str | Path, *, timeout_s: float = 300.0) -> VerificationReport:
362
+ """Replay a run directory in a fresh process (see :mod:`failslice.verify`)."""
363
+ return verify_in_subprocess(run_dir, timeout_s=timeout_s)