forgeproof-cli 0.2.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.
- forge_gate/__init__.py +44 -0
- forge_gate/_deprecated_cli.py +16 -0
- forgeproof/__init__.py +3 -0
- forgeproof/catalog.py +110 -0
- forgeproof/cli.py +560 -0
- forgeproof/config.py +339 -0
- forgeproof/data/gate_catalog.json +66 -0
- forgeproof/data/host_sets.json +7 -0
- forgeproof/debug_caller.py +271 -0
- forgeproof/debug_core.py +368 -0
- forgeproof/fixture_engine.py +81 -0
- forgeproof/fixtures/__init__.py +19 -0
- forgeproof/fixtures/decision_tree_id3.py +90 -0
- forgeproof/fixtures/gradient_descent_momentum.py +73 -0
- forgeproof/fixtures/kmeans_clustering.py +98 -0
- forgeproof/fixtures/knn_classifier.py +79 -0
- forgeproof/fixtures/linear_regression_gd.py +77 -0
- forgeproof/fixtures/logistic_regression.py +85 -0
- forgeproof/fixtures/naive_bayes_text.py +114 -0
- forgeproof/fixtures/perceptron.py +84 -0
- forgeproof/fixtures/polynomial_regression.py +67 -0
- forgeproof/fixtures/ridge_regression_normal_eq.py +75 -0
- forgeproof/ledger.py +633 -0
- forgeproof/lens_tools/__init__.py +11 -0
- forgeproof/lens_tools/guard_lens.py +1250 -0
- forgeproof/lens_tools/invariant_contracts/linear_regression_gd.json +74 -0
- forgeproof/lens_tools/invariant_contracts/polynomial_regression.json +86 -0
- forgeproof/lens_tools/invariant_contracts/ridge_regression_normal_eq.json +86 -0
- forgeproof/lens_tools/invariant_gate.py +199 -0
- forgeproof/lens_tools/metamorphic/__init__.py +9 -0
- forgeproof/lens_tools/metamorphic/relations.py +962 -0
- forgeproof/lens_tools/metamorphic/runner.py +112 -0
- forgeproof/lens_tools/twin_consensus.py +395 -0
- forgeproof/lenses.py +923 -0
- forgeproof/paths.py +56 -0
- forgeproof/reference/ORIGIN.md +29 -0
- forgeproof/reference/decision_tree_id3.py +197 -0
- forgeproof/reference/gradient_descent_momentum.py +141 -0
- forgeproof/reference/kmeans_clustering.py +139 -0
- forgeproof/reference/knn_classifier.py +118 -0
- forgeproof/reference/linear_regression_gd.py +106 -0
- forgeproof/reference/logistic_regression.py +141 -0
- forgeproof/reference/naive_bayes_text.py +152 -0
- forgeproof/reference/perceptron.py +123 -0
- forgeproof/reference/polynomial_regression.py +125 -0
- forgeproof/reference/ridge_regression_normal_eq.py +165 -0
- forgeproof/runner.py +147 -0
- forgeproof/scout/__init__.py +7 -0
- forgeproof/scout/behaviour.py +365 -0
- forgeproof/scout/box.py +581 -0
- forgeproof/scout/cards.py +180 -0
- forgeproof/scout/contract.py +37 -0
- forgeproof/scout/corpus.py +104 -0
- forgeproof/scout/embed.py +217 -0
- forgeproof/scout/engines/__init__.py +1 -0
- forgeproof/scout/engines/chaos.py +454 -0
- forgeproof/scout/engines/chaos_port.py +1331 -0
- forgeproof/scout/engines/chaos_runner.py +178 -0
- forgeproof/scout/engines/executor_port.py +239 -0
- forgeproof/scout/envfit.py +54 -0
- forgeproof/scout/experience.py +161 -0
- forgeproof/scout/fetchproxy.py +368 -0
- forgeproof/scout/ghcache.py +395 -0
- forgeproof/scout/ghpool.py +253 -0
- forgeproof/scout/ghsearch.py +248 -0
- forgeproof/scout/ids.py +82 -0
- forgeproof/scout/intent_lens.py +170 -0
- forgeproof/scout/learn.py +583 -0
- forgeproof/scout/meaning_lens.py +231 -0
- forgeproof/scout/outcomes.py +42 -0
- forgeproof/scout/plant.py +327 -0
- forgeproof/scout/ratify.py +214 -0
- forgeproof/scout/report.py +448 -0
- forgeproof/scout/rule2.py +177 -0
- forgeproof/scout/shape.py +107 -0
- forgeproof/scout/shape_lens.py +71 -0
- forgeproof/scout/signature.py +52 -0
- forgeproof/scout/slots.py +39 -0
- forgeproof/scout/upstream_facts.py +536 -0
- forgeproof/unsupported.py +83 -0
- forgeproof/verifier.py +208 -0
- forgeproof/view_coverage.py +166 -0
- forgeproof_cli-0.2.0.dist-info/METADATA +285 -0
- forgeproof_cli-0.2.0.dist-info/RECORD +89 -0
- forgeproof_cli-0.2.0.dist-info/WHEEL +5 -0
- forgeproof_cli-0.2.0.dist-info/entry_points.txt +3 -0
- forgeproof_cli-0.2.0.dist-info/licenses/LICENSE +201 -0
- forgeproof_cli-0.2.0.dist-info/licenses/NOTICE +23 -0
- forgeproof_cli-0.2.0.dist-info/top_level.txt +2 -0
forgeproof/debug_core.py
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
"""FAIL-evidence payload for forgeproof lenses. Taxonomy-agnostic.
|
|
2
|
+
|
|
3
|
+
A lens that FAILs must be able to say WHY in a form a human can act on: the
|
|
4
|
+
source under test, the failing input, a traceback if there was one, the
|
|
5
|
+
intermediate values that led to the wrong output, and — for the twin lens —
|
|
6
|
+
the compiler stderr when the C++ half didn't build. This module owns the
|
|
7
|
+
payload shape and the source-capture helper. Nothing more.
|
|
8
|
+
|
|
9
|
+
Every field the caller cannot recover post-mortem is a REQUIRED constructor
|
|
10
|
+
argument. The one that matters most is ``source_text``: forgeproof's five lens
|
|
11
|
+
adapters run patterns in ``NamedTemporaryFile(delete=False)`` subprocesses and
|
|
12
|
+
unlink the temp file in a ``finally:`` block after the subprocess dies
|
|
13
|
+
(``src/forgeproof/lenses.py:357/378``, ``src/forgeproof/lens_tools/guard_lens.py:679/817``). By
|
|
14
|
+
the time debug wants to introspect the FAIL, the source file is already gone
|
|
15
|
+
and ``inspect.getsource`` / ``traceback.extract_tb`` cannot recover it. The
|
|
16
|
+
``finally: unlink()`` is a safety boundary, not accidental — so the fix
|
|
17
|
+
belongs HERE, not in the isolation code. Callers pre-capture source with
|
|
18
|
+
``capture_source`` BEFORE they enter the ``finally:`` block, and hand the
|
|
19
|
+
text in as a required field.
|
|
20
|
+
|
|
21
|
+
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
|
22
|
+
EXTRACT-READY DISCIPLINE — three rules the module enforces on itself
|
|
23
|
+
(BRIEF-DEBUG-FEATURE-2026-09-05.md §3a). A future patterns-tool debug
|
|
24
|
+
caller must be able to import this module without picking up forgeproof
|
|
25
|
+
concepts. If any of these rules break, ``tests/verify_debug_core_purity.sh``
|
|
26
|
+
goes RED.
|
|
27
|
+
|
|
28
|
+
1. This module never imports from ``forgeproof.lenses`` or
|
|
29
|
+
``forgeproof.unsupported``. Dependency graph is one-way:
|
|
30
|
+
``lenses -> debug_core``, never back. If the core needs a type from a
|
|
31
|
+
lens, take a dataclass in the signature — do not reach across.
|
|
32
|
+
|
|
33
|
+
2. No U-code awareness inside the core. ``DebugEvidence.caller_label``
|
|
34
|
+
accepts an opaque ``str | None``; the core never inspects it, never
|
|
35
|
+
pattern-matches on ``U1``/``U2``/``U3``/``U4``, never imports the
|
|
36
|
+
registry. Routing on U-codes lives in the forgeproof caller layer.
|
|
37
|
+
|
|
38
|
+
3. Dataclasses in signatures, never ``LensResult`` or forgeproof-native
|
|
39
|
+
types. When a second caller shows up (patterns-tool or otherwise) it
|
|
40
|
+
must be able to construct the debug call from its own types without
|
|
41
|
+
depending on forgeproof. If a helper here would take a lens verdict,
|
|
42
|
+
it takes a plain dict or a locally-defined dataclass instead.
|
|
43
|
+
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
|
44
|
+
"""
|
|
45
|
+
from __future__ import annotations
|
|
46
|
+
|
|
47
|
+
import inspect
|
|
48
|
+
import traceback
|
|
49
|
+
from collections.abc import Callable, Sequence
|
|
50
|
+
from dataclasses import asdict, dataclass, field
|
|
51
|
+
from pathlib import Path
|
|
52
|
+
from types import TracebackType
|
|
53
|
+
from typing import Any, TypeVar
|
|
54
|
+
|
|
55
|
+
T = TypeVar("T")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class DebugEvidence:
|
|
60
|
+
"""One FAIL's evidence payload. Immutable; the caller composes it before
|
|
61
|
+
the isolation sandbox tears down, then hands it to a formatter.
|
|
62
|
+
|
|
63
|
+
Required fields carry what cannot be recovered post-mortem:
|
|
64
|
+
|
|
65
|
+
- ``source_text`` -- the code being tested, captured BEFORE unlink
|
|
66
|
+
- ``source_origin`` -- provenance of ``source_text`` (a resolved path,
|
|
67
|
+
or ``"<inline>"`` when the caller passed source
|
|
68
|
+
text directly rather than a file). A formatter
|
|
69
|
+
uses this to print a header the reader can find.
|
|
70
|
+
- ``failing_input`` -- the actual input value that produced the FAIL,
|
|
71
|
+
in a form the caller can serialise. The core
|
|
72
|
+
does not interpret it.
|
|
73
|
+
|
|
74
|
+
Optional fields are populated only by the components that own them
|
|
75
|
+
(traceback capture, intermediate-value dump, delta-debugger, compiler-
|
|
76
|
+
output parser, formatter). ``None`` means "not captured for this FAIL"
|
|
77
|
+
— distinct from an empty string / empty dict, which mean "captured and
|
|
78
|
+
was empty". A formatter must respect that distinction.
|
|
79
|
+
|
|
80
|
+
``caller_label`` is an opaque string the caller attaches for its own
|
|
81
|
+
routing (forgeproof puts a U-code here, patterns-tool would put a
|
|
82
|
+
check-name). The core never reads it. See rule 2 in the module
|
|
83
|
+
docstring.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
source_text: str
|
|
87
|
+
source_origin: str
|
|
88
|
+
failing_input: Any
|
|
89
|
+
|
|
90
|
+
traceback_text: str | None = None
|
|
91
|
+
intermediate_values: dict[str, Any] | None = None
|
|
92
|
+
compiler_output: str | None = None
|
|
93
|
+
shrunk_input: Any = None
|
|
94
|
+
|
|
95
|
+
caller_label: str | None = None
|
|
96
|
+
caller_metadata: dict[str, Any] = field(default_factory=dict)
|
|
97
|
+
|
|
98
|
+
def to_dict(self) -> dict[str, Any]:
|
|
99
|
+
return asdict(self)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def capture_source(target: str | Path | Any) -> tuple[str, str]:
|
|
103
|
+
"""Pre-capture source text so a later ``finally: unlink()`` in the caller
|
|
104
|
+
cannot destroy it. Returns ``(source_text, source_origin)``.
|
|
105
|
+
|
|
106
|
+
Accepts:
|
|
107
|
+
- a filesystem path (``str`` or ``Path``): read the file NOW
|
|
108
|
+
- a callable / module / class: fall back to ``inspect.getsource``
|
|
109
|
+
- an inline source string: pass through with origin ``"<inline>"``
|
|
110
|
+
|
|
111
|
+
Callers that write a ``NamedTemporaryFile(delete=False)`` and subprocess-
|
|
112
|
+
execute it MUST call this BEFORE the ``finally:`` block that unlinks
|
|
113
|
+
the temp file. That is the one line that would have burned the first
|
|
114
|
+
debug session on a determinism/guard FAIL — see module docstring.
|
|
115
|
+
"""
|
|
116
|
+
if isinstance(target, (str, Path)):
|
|
117
|
+
p = Path(target)
|
|
118
|
+
if p.exists() and p.is_file():
|
|
119
|
+
return p.read_text(), str(p.resolve())
|
|
120
|
+
# Not a live path. Accept as inline source only when the string
|
|
121
|
+
# actually looks like source; otherwise refuse rather than guess.
|
|
122
|
+
if isinstance(target, str) and (
|
|
123
|
+
"\n" in target
|
|
124
|
+
or target.lstrip().startswith(("def ", "class ", "import ", "from "))
|
|
125
|
+
):
|
|
126
|
+
return target, "<inline>"
|
|
127
|
+
raise FileNotFoundError(
|
|
128
|
+
f"capture_source: not a live file and not inline source: {target!r}. "
|
|
129
|
+
"If this is a temp file that has been unlinked, capture BEFORE the "
|
|
130
|
+
"finally: block that unlinks it."
|
|
131
|
+
)
|
|
132
|
+
try:
|
|
133
|
+
origin = f"<inspect:{getattr(target, '__name__', type(target).__name__)}>"
|
|
134
|
+
return inspect.getsource(target), origin
|
|
135
|
+
except (OSError, TypeError) as e:
|
|
136
|
+
raise ValueError(
|
|
137
|
+
f"capture_source: could not obtain source for {target!r}: {e}"
|
|
138
|
+
) from e
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
142
|
+
# Traceback + intermediate-value capture (step 3 of the brief)
|
|
143
|
+
#
|
|
144
|
+
# Both helpers stay taxonomy-agnostic. They know about Python exceptions and
|
|
145
|
+
# frames; they do not know about lenses, U-codes, or LensResult. This is
|
|
146
|
+
# rule 1 of the extract-ready discipline stated at the top of the file.
|
|
147
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
148
|
+
|
|
149
|
+
_TB_CAP_BYTES = 8_000 # generous; a formatted traceback is bounded by depth
|
|
150
|
+
_REPR_CAP = 200 # per-value repr cap — locals dumps stay bounded
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def capture_traceback(exc: BaseException, tb: TracebackType | None = None) -> str:
|
|
154
|
+
"""Format an exception + traceback into a bounded string.
|
|
155
|
+
|
|
156
|
+
Tail-truncates when it exceeds ``_TB_CAP_BYTES`` so a runaway recursion
|
|
157
|
+
trace cannot dominate the evidence payload. A trailing marker names the
|
|
158
|
+
truncation so a reader does not mistake a cut trace for the whole story.
|
|
159
|
+
"""
|
|
160
|
+
lines = traceback.format_exception(type(exc), exc, tb if tb is not None else exc.__traceback__)
|
|
161
|
+
text = "".join(lines)
|
|
162
|
+
if len(text) <= _TB_CAP_BYTES:
|
|
163
|
+
return text
|
|
164
|
+
keep = _TB_CAP_BYTES - 80
|
|
165
|
+
return text[:keep] + f"\n... [traceback truncated: {len(text) - keep} bytes elided]\n"
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _safe_repr(v: Any, cap: int = _REPR_CAP) -> str:
|
|
169
|
+
"""repr(v) that never itself raises and never returns more than ``cap``
|
|
170
|
+
characters. A custom ``__repr__`` that raises is a common defect in the
|
|
171
|
+
code we are trying to debug — we must not add a second failure on top.
|
|
172
|
+
|
|
173
|
+
NAMED LIMIT (6E review 2026-09-05): a ``__repr__`` that *hangs* (infinite
|
|
174
|
+
loop or blocking I/O) is NOT protected — Python has no interruptible-repr
|
|
175
|
+
primitive. If a hanging-repr defect is suspected, run the target under a
|
|
176
|
+
timeout at the caller layer, not here."""
|
|
177
|
+
try:
|
|
178
|
+
r = repr(v)
|
|
179
|
+
except Exception as e: # noqa: BLE001 — repr is the failure we defend against
|
|
180
|
+
return f"<unrepr-able: {type(v).__name__}: {type(e).__name__}>"
|
|
181
|
+
if len(r) > cap:
|
|
182
|
+
suffix = f"... [{len(r)} chars total]"
|
|
183
|
+
keep = max(0, cap - len(suffix))
|
|
184
|
+
return r[:keep] + suffix
|
|
185
|
+
return r
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def dump_leaf_locals(tb: TracebackType | None, *, source_only: str | None = None) -> dict[str, str] | None:
|
|
189
|
+
"""Return ``{name: safe_repr(value)}`` for the LEAF frame of a traceback.
|
|
190
|
+
|
|
191
|
+
"Leaf frame" is the innermost frame where the exception actually surfaced
|
|
192
|
+
-- typically the user's own code. Traversal skips no frames; the leaf is
|
|
193
|
+
just the last one in the ``tb_next`` chain.
|
|
194
|
+
|
|
195
|
+
``source_only``: when set, and when the leaf frame's ``co_filename`` does
|
|
196
|
+
NOT match, returns ``None`` -- protection against dumping stdlib locals
|
|
197
|
+
when the crash surfaced deep inside a library the user did not write.
|
|
198
|
+
A caller that wants everything passes ``source_only=None``.
|
|
199
|
+
|
|
200
|
+
NAMED LIMIT (6E review 2026-09-05): ``source_only=""`` filters EVERY
|
|
201
|
+
frame out (empty string never equals a real ``co_filename``). This is a
|
|
202
|
+
footgun for callers that build the filter from a possibly-empty variable
|
|
203
|
+
-- use ``None`` for "no filter", not ``""``. Callers must not pass ``""``
|
|
204
|
+
unless they specifically want to reject every frame.
|
|
205
|
+
|
|
206
|
+
Returns ``None`` (not an empty dict) when there is no frame to inspect,
|
|
207
|
+
or when ``source_only`` filtered the leaf out. Distinct from ``{}``
|
|
208
|
+
which would mean "leaf frame had no locals".
|
|
209
|
+
"""
|
|
210
|
+
if tb is None:
|
|
211
|
+
return None
|
|
212
|
+
# Walk to the leaf
|
|
213
|
+
while tb.tb_next is not None:
|
|
214
|
+
tb = tb.tb_next
|
|
215
|
+
frame = tb.tb_frame
|
|
216
|
+
if source_only is not None and frame.f_code.co_filename != source_only:
|
|
217
|
+
return None
|
|
218
|
+
return {name: _safe_repr(value) for name, value in frame.f_locals.items()}
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
222
|
+
# Delta debugging (step 4 of the brief §3.3, §8.2)
|
|
223
|
+
#
|
|
224
|
+
# Given a failing input and a predicate that says whether a subset still fails,
|
|
225
|
+
# shrink the input to a minimal subset that still fails. Zeller & Hildkamp
|
|
226
|
+
# 2002 ddmin, list-based form: the input is a sequence of elements; the
|
|
227
|
+
# minimal output is a subsequence.
|
|
228
|
+
#
|
|
229
|
+
# TAXONOMY-AGNOSTIC. The predicate is opaque — the core does not know or care
|
|
230
|
+
# whether "still fails" means "metamorphic relation still breaks" or "invariant
|
|
231
|
+
# still out of band" or "twin still disagrees". Rule 1 of the extract-ready
|
|
232
|
+
# discipline stated at the top of the file: no forgeproof imports.
|
|
233
|
+
#
|
|
234
|
+
# DETERMINISTIC. Partitions are index-based, chunk selection is left-to-right.
|
|
235
|
+
# Two runs on the same (elements, predicate) return the same ShrinkResult.
|
|
236
|
+
# Acceptance criterion 4 of the brief.
|
|
237
|
+
#
|
|
238
|
+
# BOUNDED. §8.2 of the brief: shrinking can be expensive; cap the search and
|
|
239
|
+
# report the cap. `max_steps` counts predicate evaluations; on hit, the loop
|
|
240
|
+
# returns the best-so-far and sets `hit_step_cap=True` so a formatter can say
|
|
241
|
+
# "shrunk to N elements after M steps (cap reached)".
|
|
242
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
@dataclass(frozen=True)
|
|
246
|
+
class ShrinkResult:
|
|
247
|
+
"""Outcome of a ddmin run.
|
|
248
|
+
|
|
249
|
+
``minimal`` is the smallest subset of the original that still made the
|
|
250
|
+
predicate return True. If the predicate never returned True (input did not
|
|
251
|
+
reproduce the failure at all), ``minimal`` equals the original input and
|
|
252
|
+
``predicate_ever_failed`` is False — callers must respect that distinction
|
|
253
|
+
rather than treating an unshrunk result as a shrunk one.
|
|
254
|
+
|
|
255
|
+
``steps`` counts predicate evaluations, not iterations of the outer loop.
|
|
256
|
+
``hit_step_cap`` is True iff the search exited because it reached
|
|
257
|
+
``max_steps`` rather than because the input was already minimal.
|
|
258
|
+
"""
|
|
259
|
+
|
|
260
|
+
minimal: list[Any]
|
|
261
|
+
steps: int
|
|
262
|
+
hit_step_cap: bool
|
|
263
|
+
predicate_ever_failed: bool
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def ddmin(
|
|
267
|
+
elements: Sequence[T],
|
|
268
|
+
still_fails: Callable[[list[T]], bool],
|
|
269
|
+
*,
|
|
270
|
+
max_steps: int = 200,
|
|
271
|
+
) -> ShrinkResult:
|
|
272
|
+
"""Return a minimal subset of ``elements`` for which ``still_fails`` is True.
|
|
273
|
+
|
|
274
|
+
The Zeller & Hildkamp 2002 ddmin, list-based. Partition the current
|
|
275
|
+
candidate into ``n`` chunks; if removing chunk i still fails, drop it and
|
|
276
|
+
reduce granularity; otherwise if removing every chunk passes, double n
|
|
277
|
+
and try again; stop when n exceeds the candidate size.
|
|
278
|
+
|
|
279
|
+
The predicate is called only with subsequences of the original
|
|
280
|
+
``elements`` (in original order) — never with reorderings, never with
|
|
281
|
+
duplicates. A predicate that RAISES is treated as PASS (do not shrink to
|
|
282
|
+
an input that crashed the predicate itself); the core cannot distinguish
|
|
283
|
+
"the predicate broke" from "the target broke differently" without more
|
|
284
|
+
signal, and the safe default is not to remove elements based on a
|
|
285
|
+
predicate error.
|
|
286
|
+
|
|
287
|
+
``max_steps`` caps the number of predicate evaluations. If hit, the
|
|
288
|
+
best-so-far is returned and ``hit_step_cap`` is True — the caller should
|
|
289
|
+
surface both to the human reading the debug artifact.
|
|
290
|
+
|
|
291
|
+
NAMED LIMIT: this shrinker operates on element SEQUENCES. A caller that
|
|
292
|
+
wants to shrink a source string first splits it into lines/tokens; a
|
|
293
|
+
caller that wants to shrink a dict of kwargs first flattens it to a list
|
|
294
|
+
of (key, value) pairs. Reconstructing the original type after shrinking
|
|
295
|
+
is the caller's job — the core stays type-agnostic on purpose.
|
|
296
|
+
"""
|
|
297
|
+
elements = list(elements)
|
|
298
|
+
|
|
299
|
+
def _run(subset: list[T]) -> bool:
|
|
300
|
+
try:
|
|
301
|
+
return bool(still_fails(subset))
|
|
302
|
+
except Exception: # noqa: BLE001 — predicate errors are PASS by policy
|
|
303
|
+
return False
|
|
304
|
+
|
|
305
|
+
steps = 0
|
|
306
|
+
ever_failed = False
|
|
307
|
+
|
|
308
|
+
# Verify the input reproduces the failure at all. Zeller ddmin assumes it
|
|
309
|
+
# does; if not we return the original unshrunk with the flag off so a
|
|
310
|
+
# caller can distinguish "already minimal" from "did not reproduce".
|
|
311
|
+
if not elements:
|
|
312
|
+
return ShrinkResult(minimal=[], steps=0, hit_step_cap=False, predicate_ever_failed=False)
|
|
313
|
+
steps += 1
|
|
314
|
+
if not _run(elements):
|
|
315
|
+
return ShrinkResult(
|
|
316
|
+
minimal=elements, steps=steps, hit_step_cap=False, predicate_ever_failed=False,
|
|
317
|
+
)
|
|
318
|
+
ever_failed = True
|
|
319
|
+
|
|
320
|
+
current = elements
|
|
321
|
+
n = 2
|
|
322
|
+
|
|
323
|
+
while len(current) >= 2:
|
|
324
|
+
if steps >= max_steps:
|
|
325
|
+
return ShrinkResult(
|
|
326
|
+
minimal=current, steps=steps, hit_step_cap=True, predicate_ever_failed=ever_failed,
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
# Partition current into n roughly-equal chunks by index.
|
|
330
|
+
size = len(current)
|
|
331
|
+
chunk_size = max(size // n, 1)
|
|
332
|
+
chunks: list[list[T]] = []
|
|
333
|
+
i = 0
|
|
334
|
+
while i < size and len(chunks) < n:
|
|
335
|
+
end = size if len(chunks) == n - 1 else min(i + chunk_size, size)
|
|
336
|
+
chunks.append(current[i:end])
|
|
337
|
+
i = end
|
|
338
|
+
|
|
339
|
+
# Try removing each chunk. First shrink that still fails wins; reduce
|
|
340
|
+
# granularity and restart the outer loop with the smaller candidate.
|
|
341
|
+
reduced = False
|
|
342
|
+
for idx, chunk in enumerate(chunks):
|
|
343
|
+
if steps >= max_steps:
|
|
344
|
+
return ShrinkResult(
|
|
345
|
+
minimal=current, steps=steps, hit_step_cap=True, predicate_ever_failed=ever_failed,
|
|
346
|
+
)
|
|
347
|
+
candidate = [x for j, c in enumerate(chunks) if j != idx for x in c]
|
|
348
|
+
if not candidate:
|
|
349
|
+
continue
|
|
350
|
+
steps += 1
|
|
351
|
+
if _run(candidate):
|
|
352
|
+
current = candidate
|
|
353
|
+
n = max(n - 1, 2)
|
|
354
|
+
reduced = True
|
|
355
|
+
break
|
|
356
|
+
|
|
357
|
+
if reduced:
|
|
358
|
+
continue
|
|
359
|
+
|
|
360
|
+
# No chunk-removal helped. Increase granularity; stop when n exceeds
|
|
361
|
+
# the candidate size (nothing left to partition).
|
|
362
|
+
if n >= len(current):
|
|
363
|
+
break
|
|
364
|
+
n = min(n * 2, len(current))
|
|
365
|
+
|
|
366
|
+
return ShrinkResult(
|
|
367
|
+
minimal=current, steps=steps, hit_step_cap=False, predicate_ever_failed=ever_failed,
|
|
368
|
+
)
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Shared engine code used by gate fixtures.
|
|
2
|
+
|
|
3
|
+
This module is imported by fixtures. It provides helpers to load a Python file
|
|
4
|
+
as a module and to compare/emit results.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import importlib.util
|
|
9
|
+
import json
|
|
10
|
+
import math
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, Callable, Dict, List, Tuple
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def load_module(path: str, module_name: str = "user_impl") -> Any:
|
|
17
|
+
"""Load a Python source file as a module."""
|
|
18
|
+
p = Path(path).resolve()
|
|
19
|
+
if not p.exists():
|
|
20
|
+
raise FileNotFoundError(f"File not found: {p}")
|
|
21
|
+
spec = importlib.util.spec_from_file_location(module_name, str(p))
|
|
22
|
+
if spec is None or spec.loader is None:
|
|
23
|
+
raise ImportError(f"Cannot load module from {p}")
|
|
24
|
+
mod = importlib.util.module_from_spec(spec)
|
|
25
|
+
spec.loader.exec_module(mod)
|
|
26
|
+
return mod
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def get_fn(mod: Any, name: str) -> Callable:
|
|
30
|
+
"""Get a function from a module, raising a clear error if missing."""
|
|
31
|
+
fn = getattr(mod, name, None)
|
|
32
|
+
if fn is None:
|
|
33
|
+
raise AttributeError(
|
|
34
|
+
f"Module {mod.__file__} must define function '{name}'"
|
|
35
|
+
)
|
|
36
|
+
if not callable(fn):
|
|
37
|
+
raise TypeError(f"'{name}' in {mod.__file__} is not callable")
|
|
38
|
+
return fn
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def approx_eq(a: Any, b: Any, rel_tol: float = 1e-5, abs_tol: float = 1e-8) -> bool:
|
|
42
|
+
"""Recursive approximate equality for floats, lists, and dicts."""
|
|
43
|
+
if isinstance(a, float) and isinstance(b, (int, float)):
|
|
44
|
+
return math.isclose(a, float(b), rel_tol=rel_tol, abs_tol=abs_tol)
|
|
45
|
+
if isinstance(a, int) and isinstance(b, int):
|
|
46
|
+
return a == b
|
|
47
|
+
if isinstance(a, list) and isinstance(b, list):
|
|
48
|
+
return len(a) == len(b) and all(approx_eq(x, y) for x, y in zip(a, b))
|
|
49
|
+
if isinstance(a, dict) and isinstance(b, dict):
|
|
50
|
+
return a.keys() == b.keys() and all(approx_eq(a[k], b[k]) for k in a)
|
|
51
|
+
return a == b
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def emit(result: Dict[str, Any]) -> None:
|
|
55
|
+
"""Print the structured gate result line."""
|
|
56
|
+
print("FORGE_GATE_RESULT " + json.dumps(result, sort_keys=True, default=str))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def run_both(
|
|
60
|
+
user_path: str,
|
|
61
|
+
aura_path: str,
|
|
62
|
+
fn_name: str,
|
|
63
|
+
build_fixture: Callable,
|
|
64
|
+
evaluate: Callable[[Any, Any], Dict[str, Any]],
|
|
65
|
+
) -> None:
|
|
66
|
+
"""Generic helper: build one fixture, run user and AURA functions, emit result."""
|
|
67
|
+
try:
|
|
68
|
+
user_mod = load_module(user_path, "user_impl")
|
|
69
|
+
aura_mod = load_module(aura_path, "aura_impl")
|
|
70
|
+
user_fn = get_fn(user_mod, fn_name)
|
|
71
|
+
aura_fn = get_fn(aura_mod, fn_name)
|
|
72
|
+
|
|
73
|
+
fixture = build_fixture()
|
|
74
|
+
user_out = user_fn(**fixture) if isinstance(fixture, dict) else user_fn(*fixture)
|
|
75
|
+
aura_out = aura_fn(**fixture) if isinstance(fixture, dict) else aura_fn(*fixture)
|
|
76
|
+
|
|
77
|
+
result = evaluate(user_out, aura_out)
|
|
78
|
+
emit(result)
|
|
79
|
+
except Exception as exc: # noqa: BLE001
|
|
80
|
+
emit({"status": "FAIL", "error": f"{type(exc).__name__}: {exc}"})
|
|
81
|
+
sys.exit(1)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Gate fixtures — one per curated pattern.
|
|
2
|
+
|
|
3
|
+
Each fixture is a standalone script that:
|
|
4
|
+
1. Loads the user's implementation from a file path (argv[1]).
|
|
5
|
+
2. Loads the signed AURA oracle for the same pattern.
|
|
6
|
+
3. Runs both on the same seed-locked fixture.
|
|
7
|
+
4. Emits a `FORGE_GATE_RESULT` JSON line.
|
|
8
|
+
|
|
9
|
+
Fixtures are executed by `forgeproof.runner.run_file` in a sandboxed subprocess.
|
|
10
|
+
"""
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, Dict
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def emit(result: Dict[str, Any]) -> None:
|
|
16
|
+
"""Print the structured gate result line."""
|
|
17
|
+
import json
|
|
18
|
+
|
|
19
|
+
print("FORGE_GATE_RESULT " + json.dumps(result, sort_keys=True, default=str))
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Gate fixture for decision_tree_id3.
|
|
3
|
+
|
|
4
|
+
PASS is decided by classification accuracy on a separable synthetic dataset,
|
|
5
|
+
not by matching the AURA oracle's exact tree structure.
|
|
6
|
+
"""
|
|
7
|
+
import random
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
_pkg = Path(__file__).resolve().parents[2]
|
|
12
|
+
if str(_pkg) not in sys.path:
|
|
13
|
+
sys.path.insert(0, str(_pkg))
|
|
14
|
+
|
|
15
|
+
from forgeproof.catalog import reference_path
|
|
16
|
+
from forgeproof.fixture_engine import approx_eq, emit, get_fn, load_module
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def main():
|
|
20
|
+
if len(sys.argv) < 2:
|
|
21
|
+
print("usage: decision_tree_id3.py <user_file.py>", file=sys.stderr)
|
|
22
|
+
sys.exit(2)
|
|
23
|
+
|
|
24
|
+
user_path = sys.argv[1]
|
|
25
|
+
aura_path = str(reference_path("decision_tree_id3"))
|
|
26
|
+
|
|
27
|
+
user_mod = load_module(user_path, "user_impl")
|
|
28
|
+
aura_mod = load_module(aura_path, "aura_impl")
|
|
29
|
+
|
|
30
|
+
user_build = get_fn(user_mod, "build_tree")
|
|
31
|
+
user_predict = get_fn(user_mod, "predict_tree")
|
|
32
|
+
aura_build = get_fn(aura_mod, "build_tree")
|
|
33
|
+
aura_predict = get_fn(aura_mod, "predict_tree")
|
|
34
|
+
|
|
35
|
+
random.seed(42)
|
|
36
|
+
n_samples = 100
|
|
37
|
+
# Balanced classes with deliberate overlap: 15% of each class leaks across
|
|
38
|
+
# the nominal x0 boundary, plus an uncorrelated second feature.
|
|
39
|
+
# This puts correct trees ~0.83 and broken/random trees ~0.63 on the test set.
|
|
40
|
+
X, y = [], []
|
|
41
|
+
leak = 0.15
|
|
42
|
+
for _ in range(n_samples // 2):
|
|
43
|
+
x0 = random.uniform(0, 2.5) if random.random() < (1 - leak) else random.uniform(2.5, 5)
|
|
44
|
+
x1 = random.uniform(0, 5)
|
|
45
|
+
X.append([x0, x1])
|
|
46
|
+
y.append(0)
|
|
47
|
+
for _ in range(n_samples // 2):
|
|
48
|
+
x0 = random.uniform(2.5, 5) if random.random() < (1 - leak) else random.uniform(0, 2.5)
|
|
49
|
+
x1 = random.uniform(0, 5)
|
|
50
|
+
X.append([x0, x1])
|
|
51
|
+
y.append(1)
|
|
52
|
+
|
|
53
|
+
# Shuffle then hold out 30 samples for testing to catch overfitting trees.
|
|
54
|
+
indices = list(range(n_samples))
|
|
55
|
+
random.shuffle(indices)
|
|
56
|
+
train_idx, test_idx = indices[:70], indices[70:]
|
|
57
|
+
X_train = [X[i] for i in train_idx]
|
|
58
|
+
y_train = [y[i] for i in train_idx]
|
|
59
|
+
X_test = [X[i] for i in test_idx]
|
|
60
|
+
y_test = [y[i] for i in test_idx]
|
|
61
|
+
|
|
62
|
+
user_tree = user_build(X_train, y_train, max_depth=5)
|
|
63
|
+
aura_tree = aura_build(X_train, y_train, max_depth=5)
|
|
64
|
+
|
|
65
|
+
user_preds = [user_predict(X_test[i], user_tree) for i in range(len(X_test))]
|
|
66
|
+
aura_preds = [aura_predict(X_test[i], aura_tree) for i in range(len(X_test))]
|
|
67
|
+
|
|
68
|
+
user_accuracy = sum(user_preds[i] == y_test[i] for i in range(len(X_test))) / len(X_test)
|
|
69
|
+
aura_accuracy = sum(aura_preds[i] == y_test[i] for i in range(len(X_test))) / len(X_test)
|
|
70
|
+
|
|
71
|
+
canonical_match = approx_eq(user_accuracy, aura_accuracy, rel_tol=1e-5)
|
|
72
|
+
|
|
73
|
+
metrics = {
|
|
74
|
+
"accuracy": round(user_accuracy, 6),
|
|
75
|
+
"oracle_accuracy": round(aura_accuracy, 6),
|
|
76
|
+
"canonical_match": canonical_match,
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
ok = user_accuracy >= 0.75
|
|
80
|
+
|
|
81
|
+
emit({
|
|
82
|
+
"status": "PASS" if ok else "FAIL",
|
|
83
|
+
"pattern": "decision_tree_id3",
|
|
84
|
+
"reason": "ID3 decision tree accuracy property holds" if ok else "ID3 decision tree accuracy property fails",
|
|
85
|
+
"metrics": metrics,
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
if __name__ == "__main__":
|
|
90
|
+
main()
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Gate fixture for gradient_descent_momentum.
|
|
3
|
+
|
|
4
|
+
PASS is decided by convergence properties (both solvers reach near-zero loss,
|
|
5
|
+
momentum converges in fewer iterations than vanilla), not by matching the
|
|
6
|
+
AURA oracle's exact iteration counts.
|
|
7
|
+
"""
|
|
8
|
+
import random
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
_pkg = Path(__file__).resolve().parents[2]
|
|
13
|
+
if str(_pkg) not in sys.path:
|
|
14
|
+
sys.path.insert(0, str(_pkg))
|
|
15
|
+
|
|
16
|
+
from forgeproof.catalog import reference_path
|
|
17
|
+
from forgeproof.fixture_engine import approx_eq, emit, get_fn, load_module
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def main():
|
|
21
|
+
if len(sys.argv) < 2:
|
|
22
|
+
print("usage: gradient_descent_momentum.py <user_file.py>", file=sys.stderr)
|
|
23
|
+
sys.exit(2)
|
|
24
|
+
|
|
25
|
+
user_path = sys.argv[1]
|
|
26
|
+
aura_path = str(reference_path("gradient_descent_momentum"))
|
|
27
|
+
|
|
28
|
+
user_mod = load_module(user_path, "user_impl")
|
|
29
|
+
aura_mod = load_module(aura_path, "aura_impl")
|
|
30
|
+
|
|
31
|
+
user_vanilla = get_fn(user_mod, "vanilla_gd")
|
|
32
|
+
user_momentum = get_fn(user_mod, "momentum_gd")
|
|
33
|
+
aura_vanilla = get_fn(aura_mod, "vanilla_gd")
|
|
34
|
+
aura_momentum = get_fn(aura_mod, "momentum_gd")
|
|
35
|
+
|
|
36
|
+
random.seed(42)
|
|
37
|
+
x0, y0 = 10.0, 10.0
|
|
38
|
+
|
|
39
|
+
user_vanilla_iters, user_vanilla_fx = user_vanilla(x0, y0)
|
|
40
|
+
user_momentum_iters, user_momentum_fx = user_momentum(x0, y0)
|
|
41
|
+
aura_vanilla_iters, aura_vanilla_fx = aura_vanilla(x0, y0)
|
|
42
|
+
aura_momentum_iters, aura_momentum_fx = aura_momentum(x0, y0)
|
|
43
|
+
|
|
44
|
+
canonical_match = (
|
|
45
|
+
approx_eq(user_vanilla_iters, aura_vanilla_iters, rel_tol=1e-5)
|
|
46
|
+
and approx_eq(user_momentum_iters, aura_momentum_iters, rel_tol=1e-5)
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
metrics = {
|
|
50
|
+
"vanilla_iters": user_vanilla_iters,
|
|
51
|
+
"momentum_iters": user_momentum_iters,
|
|
52
|
+
"vanilla_fx": round(user_vanilla_fx, 9),
|
|
53
|
+
"momentum_fx": round(user_momentum_fx, 9),
|
|
54
|
+
"speedup": round(user_vanilla_iters / max(user_momentum_iters, 1), 3),
|
|
55
|
+
"canonical_match": canonical_match,
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
ok = (
|
|
59
|
+
user_vanilla_fx < 1e-6
|
|
60
|
+
and user_momentum_fx < 1e-6
|
|
61
|
+
and user_momentum_iters < user_vanilla_iters
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
emit({
|
|
65
|
+
"status": "PASS" if ok else "FAIL",
|
|
66
|
+
"pattern": "gradient_descent_momentum",
|
|
67
|
+
"reason": "Momentum GD convergence properties hold" if ok else "Momentum GD convergence properties fail",
|
|
68
|
+
"metrics": metrics,
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
if __name__ == "__main__":
|
|
73
|
+
main()
|