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
|
@@ -0,0 +1,1250 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Guard lens — gating NaN/Inf finiteness check for scalar parameters.
|
|
3
|
+
|
|
4
|
+
STATUS: GATING. A genuine NaN-defect FAIL fails the build. `guard` is in both
|
|
5
|
+
ENFORCED_EXTRA_LENSES and ENFORCED_LENSES (src/forgeproof/lenses.py), and
|
|
6
|
+
_run_guard() sets objected=True on a FAIL verdict. This header read ADVISORY
|
|
7
|
+
until 2026-09-04; it had been false since the lens was promoted to gating.
|
|
8
|
+
|
|
9
|
+
The lens reports INCONCLUSIVE, never PASS, when it could not measure: an
|
|
10
|
+
unexercised parameter must not read as a clean one. That honesty path is what
|
|
11
|
+
makes gating defensible, and tests/verify_guard_lens.sh covers it.
|
|
12
|
+
|
|
13
|
+
The Guard lens needs no oracle. It feeds NaN/Inf into a function's scalar
|
|
14
|
+
parameters and checks whether the result hides the poison. The criterion:
|
|
15
|
+
|
|
16
|
+
- code raises on NaN/Inf input -> HANDLED, PASS
|
|
17
|
+
- code returns NaN/Inf in every float element -> HANDLED, PASS
|
|
18
|
+
- for NaN input, a returned finite float component that is
|
|
19
|
+
UNCHANGED vs the clean baseline is independent of the
|
|
20
|
+
poisoned input -> HANDLED, PASS
|
|
21
|
+
- for NaN input, a returned finite float component that is
|
|
22
|
+
CHANGED vs the clean baseline was influenced by the NaN -> DEFECT, FAIL
|
|
23
|
+
- a MIXTURE of finite and NaN/Inf float elements from NaN
|
|
24
|
+
input where any finite component CHANGED -> DEFECT, FAIL
|
|
25
|
+
|
|
26
|
+
Only float elements are judged. Ints and bools are treated as counters,
|
|
27
|
+
status flags or lengths, not numeric results, so a (count, NaN) tuple is
|
|
28
|
+
handled. Inf is recorded as an observation but never accused: a finite result
|
|
29
|
+
from +/-Inf may be the correct saturation limit (e.g. sigmoid(±Inf)), and this
|
|
30
|
+
lens has no oracle to tell the difference.
|
|
31
|
+
|
|
32
|
+
A scalar parameter is any parameter annotated as float/int (or with a numeric
|
|
33
|
+
default) that is not a container. Container parameters (list/dict/tuple/etc.)
|
|
34
|
+
are filled with small synthetic fixtures so the function can be exercised.
|
|
35
|
+
|
|
36
|
+
LIMITS (read before trusting):
|
|
37
|
+
* The lens can only exercise a function whose non-poisoned arguments can be
|
|
38
|
+
synthesised. G11 added shape-coherent synthesis for common matrix/vector
|
|
39
|
+
siblings (e.g. X and y share a row count; x_test matches feature count),
|
|
40
|
+
but exotic signatures still report INCONCLUSIVE.
|
|
41
|
+
* The tolerance-name rule (tolerance/tol/epsilon/eps/atol/rtol) is a
|
|
42
|
+
parameter-name HEURISTIC, honestly labelled, not a measurement.
|
|
43
|
+
* Componentwise reachability ("finite component unchanged vs clean baseline
|
|
44
|
+
is OK") IS implemented in G12, and G21 enforces it across MULTI_SHAPE_COUNT
|
|
45
|
+
genuinely different argument shapes. A finite component is only called
|
|
46
|
+
independent if it is unchanged in EVERY shape; any shape showing a changed
|
|
47
|
+
finite component is a swallowed-NaN defect.
|
|
48
|
+
* Fixture execution IS isolated in G17: each fixture is imported and called
|
|
49
|
+
in a subprocess with start_new_session=True, a hard wall-clock timeout,
|
|
50
|
+
os.killpg cleanup, and per-process CPU/memory limits. A fixture that
|
|
51
|
+
exceeds any limit is INCONCLUSIVE, never FAIL.
|
|
52
|
+
|
|
53
|
+
FALSE-POSITIVE CLASSES CLOSED by this version:
|
|
54
|
+
1. Inf-is-not-NaN: finite saturation limits at +/-Inf are allowed.
|
|
55
|
+
2. Counter-is-not-a-result: an int counter/status next to a NaN float is
|
|
56
|
+
handled; only float elements are judged.
|
|
57
|
+
3. Unexercised-is-not-defective: if the clean baseline cannot exercise the
|
|
58
|
+
code, the verdict is INCONCLUSIVE "parameter unreachable", never DEFECT.
|
|
59
|
+
4. Separable-is-not-swallowed: a finite component unchanged by a poisoned
|
|
60
|
+
input is mathematically independent and must not be accused.
|
|
61
|
+
Componentwise comparison is now enforced; the multi-shape guard is
|
|
62
|
+
adopted in the criterion and will be exercised by the fixtures."
|
|
63
|
+
|
|
64
|
+
5. Literal-harvest-is-not-domain-knowledge: numeric constants from the
|
|
65
|
+
function's own source are added as probe shapes (U4). This makes
|
|
66
|
+
membership and comparison branches reachable without hard-coding any
|
|
67
|
+
semantic map.
|
|
68
|
+
6. Unsynthesisable-sibling-is-not-exercisable: if a function has a
|
|
69
|
+
parameter the lens cannot synthesise (e.g. an unannotated callback),
|
|
70
|
+
its scalar siblings are counted as unexercised rather than judged on
|
|
71
|
+
invalid calls (U6).
|
|
72
|
+
|
|
73
|
+
Output contract:
|
|
74
|
+
* verdict:PASS|FAIL|INCONCLUSIVE <reason>
|
|
75
|
+
* detail:<line> (optional, limited to 50 lines)
|
|
76
|
+
* scope:params_total=N
|
|
77
|
+
* scope:params_judged=N
|
|
78
|
+
* scope:params_unreachable=N
|
|
79
|
+
* scope:params_unexercised=N
|
|
80
|
+
* scope:functions_total=N
|
|
81
|
+
* scope:functions_scanned=N
|
|
82
|
+
* scope:mode=UNMATCHED
|
|
83
|
+
|
|
84
|
+
The scope lines partition every scalar parameter into exactly one bucket
|
|
85
|
+
(judged, unreachable, unexercised) so a report layer can distinguish an
|
|
86
|
+
unmatched PASS (no oracle comparison) from a matched PASS.
|
|
87
|
+
|
|
88
|
+
The lens is advisory: it reports FAIL but does not gate. Its purpose is to
|
|
89
|
+
surface missing finiteness guards that silently turn poison into plausible
|
|
90
|
+
output.
|
|
91
|
+
"""
|
|
92
|
+
from __future__ import annotations
|
|
93
|
+
|
|
94
|
+
import argparse
|
|
95
|
+
import ast
|
|
96
|
+
import importlib.util
|
|
97
|
+
import inspect
|
|
98
|
+
import json
|
|
99
|
+
import math
|
|
100
|
+
import os
|
|
101
|
+
import resource
|
|
102
|
+
import signal
|
|
103
|
+
import subprocess
|
|
104
|
+
import sys
|
|
105
|
+
import tempfile
|
|
106
|
+
import textwrap
|
|
107
|
+
from pathlib import Path
|
|
108
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple
|
|
109
|
+
|
|
110
|
+
# Hard wall-clock timeout for a single fixture run. Short enough to prevent a
|
|
111
|
+
# submitted infinite loop from cooking the deploy host; long enough for real ML fixtures to
|
|
112
|
+
# finish their clean baseline. Must stay below the isolation test's 15s ceiling.
|
|
113
|
+
FIXTURE_TIMEOUT_SECONDS = 10
|
|
114
|
+
|
|
115
|
+
# CPU seconds allowed per fixture subprocess. Soft == hard so SIGKILL fires.
|
|
116
|
+
# Three baseline calls for a single-scalar fixture must fit inside the 15s test.
|
|
117
|
+
FIXTURE_CPU_LIMIT_SECONDS = 2
|
|
118
|
+
|
|
119
|
+
# Address-space limit per fixture subprocess. Large allocations that exceed this
|
|
120
|
+
# are treated as "could not measure" (INCONCLUSIVE), not as a clean PASS.
|
|
121
|
+
FIXTURE_MEMORY_LIMIT_BYTES = 256 * 1024 * 1024
|
|
122
|
+
|
|
123
|
+
# Number of genuinely different argument shapes to try when proving that a
|
|
124
|
+
# finite component is independent of a poisoned scalar. Coincidence at one
|
|
125
|
+
# shape is not evidence; independence must survive all shapes.
|
|
126
|
+
MULTI_SHAPE_COUNT = 4
|
|
127
|
+
|
|
128
|
+
# Maximum numeric literals harvested from a function's own source to use as
|
|
129
|
+
# additional probe shapes. U4: the discriminating values are often written in
|
|
130
|
+
# the code itself (status codes, thresholds, magic numbers); trying them makes
|
|
131
|
+
# membership/comparison branches reachable without domain knowledge.
|
|
132
|
+
MAX_HARVESTED_LITERALS = 8
|
|
133
|
+
|
|
134
|
+
POISON_NAN = [float("nan")]
|
|
135
|
+
POISON_INF = [float("inf"), float("-inf")]
|
|
136
|
+
|
|
137
|
+
# Sentinel returned when a parameter cannot be synthesised at all (e.g. an
|
|
138
|
+
# unannotated callback). Such parameters are not scalar poison targets and,
|
|
139
|
+
# if present as siblings, prevent the whole function from being exercised.
|
|
140
|
+
_UNABLE = object()
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
TOLERANCE_NAMES = frozenset({"tolerance", "tol", "epsilon", "eps", "atol", "rtol"})
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _valid_for(ann: Any, default: Any = inspect.Parameter.empty, pname: str = "") -> Tuple[Any, bool]:
|
|
147
|
+
"""Build a valid baseline argument from a type hint or parameter name.
|
|
148
|
+
|
|
149
|
+
Ported from c1-measurement/validator-COPY-from-dot5/executor.py (in au's ai-lab
|
|
150
|
+
on the deploy host; not part of this repo).
|
|
151
|
+
Precedence: declared default, annotation, parameter name, unknown.
|
|
152
|
+
Returns (value, ok); ok=False means the caller must supply a fallback.
|
|
153
|
+
"""
|
|
154
|
+
if default is not inspect.Parameter.empty and default is not None:
|
|
155
|
+
return default, True
|
|
156
|
+
|
|
157
|
+
s = str(ann).lower().replace("typing.", "")
|
|
158
|
+
|
|
159
|
+
if "callable" in s:
|
|
160
|
+
return _UNABLE, False
|
|
161
|
+
if "list[list" in s:
|
|
162
|
+
return [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], True
|
|
163
|
+
if "list[int]" in s:
|
|
164
|
+
return [0, 1, 0, 1, 1, 0], True
|
|
165
|
+
if "list" in s or "sequence" in s or "vector" in s:
|
|
166
|
+
return [1.0, 2.0, 3.0, 4.0, 5.0], True
|
|
167
|
+
if "tuple" in s:
|
|
168
|
+
return (1.0, 2.0), True
|
|
169
|
+
if "dict" in s:
|
|
170
|
+
return {"a": 1.0, "b": 2.0}, True
|
|
171
|
+
if "int" in s:
|
|
172
|
+
return 5, True
|
|
173
|
+
if "float" in s or "number" in s:
|
|
174
|
+
return 0.5, True
|
|
175
|
+
if "str" in s:
|
|
176
|
+
return "the quick brown fox", True
|
|
177
|
+
if "bool" in s:
|
|
178
|
+
return True, True
|
|
179
|
+
|
|
180
|
+
n = pname.lower()
|
|
181
|
+
if n in ("callback", "fn", "func", "function"):
|
|
182
|
+
return _UNABLE, False
|
|
183
|
+
if any(w in n for w in ("data", "samples", "values", "series", "arr", "xs", "ys", "points", "scores", "counts")):
|
|
184
|
+
return [1.0, 2.0, 3.0, 4.0, 5.0], True
|
|
185
|
+
if any(w in n for w in ("text", "name", "key", "line", "doc", "word")):
|
|
186
|
+
return "the quick brown fox", True
|
|
187
|
+
if n in ("x", "y", "z") or any(w in n for w in ("num", "count", "n_", "size", "k", "depth", "width", "seed")):
|
|
188
|
+
return 5, True
|
|
189
|
+
if any(w in n for w in ("prob", "rate", "alpha", "p1", "p2", "u", "var", "mean", "mu", "threshold", "eps", "value", "val")):
|
|
190
|
+
return 0.5, True
|
|
191
|
+
return None, False
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _value_is_scalar(v: Any) -> bool:
|
|
195
|
+
"""True for int/float numeric values (bools are status flags, not scalars)."""
|
|
196
|
+
return isinstance(v, (int, float)) and not isinstance(v, bool)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _baseline_for(param: inspect.Parameter, scalar_idx: int, sibling_names=frozenset(), shape_idx: int = 0) -> Tuple[Any, bool]:
|
|
200
|
+
"""Pick a baseline value and whether it is a scalar poison target.
|
|
201
|
+
|
|
202
|
+
Rule (per G9a refinement):
|
|
203
|
+
1. has a usable default -> use the default
|
|
204
|
+
2. has an annotation -> use _valid_for; non-scalar values are used as-is,
|
|
205
|
+
scalar values are routed to the varied scalar fallback so
|
|
206
|
+
multi-scalar signatures do not collapse onto a single constant
|
|
207
|
+
3. unannotated -> try _valid_for's name guess; scalar guesses fall back
|
|
208
|
+
to the varied scalar default, container guesses are used as-is;
|
|
209
|
+
a bare lowercase `y` paired with an uppercase `X` is treated as labels
|
|
210
|
+
4. a failed/degenerate clean call then earns INCONCLUSIVE honestly
|
|
211
|
+
"""
|
|
212
|
+
# Rule 1: honour declared defaults, but treat None as "no default".
|
|
213
|
+
if param.default is not inspect.Parameter.empty and param.default is not None:
|
|
214
|
+
return param.default, _value_is_scalar(param.default)
|
|
215
|
+
|
|
216
|
+
def _choose(val: Any) -> Tuple[Any, bool]:
|
|
217
|
+
"""Container values are used directly; scalar candidates are replaced by
|
|
218
|
+
the varied scalar fallback to prevent multi-scalar collapse.
|
|
219
|
+
The _UNABLE sentinel passes through unchanged."""
|
|
220
|
+
if val is _UNABLE:
|
|
221
|
+
return _UNABLE, False
|
|
222
|
+
if val is None:
|
|
223
|
+
return _scalar_default(param, scalar_idx, shape_idx), True
|
|
224
|
+
if _value_is_scalar(val):
|
|
225
|
+
return _scalar_default(param, scalar_idx, shape_idx), True
|
|
226
|
+
return val, False
|
|
227
|
+
|
|
228
|
+
# Rule 2: annotation only; do not let a name guess override an annotation.
|
|
229
|
+
if param.annotation is not inspect.Parameter.empty:
|
|
230
|
+
val, ok = _valid_for(param.annotation, inspect.Parameter.empty, param.name)
|
|
231
|
+
if ok:
|
|
232
|
+
return _choose(val)
|
|
233
|
+
|
|
234
|
+
# Rule 3: corpus-specific refinements for unannotated ML signatures.
|
|
235
|
+
n = param.name.lower()
|
|
236
|
+
if n in ("features", "x_train", "x_test") or param.name == "X":
|
|
237
|
+
return _varying_matrix(shape_idx), False
|
|
238
|
+
if n in ("labels", "targets", "y_train", "y_test"):
|
|
239
|
+
return _varying_label_vector(shape_idx), False
|
|
240
|
+
if n in ("texts", "documents"):
|
|
241
|
+
return [["the quick brown fox"], ["the quick brown fox"]], False
|
|
242
|
+
if n in ("text", "name", "key", "line", "doc", "word"):
|
|
243
|
+
return "the quick brown fox", False
|
|
244
|
+
if n in ("weights", "coeffs", "x_vals", "y_vals", "p1", "p2",
|
|
245
|
+
"point", "vector", "sample", "values", "counts"):
|
|
246
|
+
return _varying_float_vector(shape_idx), False
|
|
247
|
+
if n in ("data", "samples", "series", "arr", "xs", "ys", "points",
|
|
248
|
+
"scores"):
|
|
249
|
+
return _varying_float_vector(shape_idx), False
|
|
250
|
+
if n in ("priors", "probs", "probabilities"):
|
|
251
|
+
return {"a": 1.0, "b": 2.0}, False
|
|
252
|
+
if n in ("node", "tree", "root"):
|
|
253
|
+
return None, False
|
|
254
|
+
if n in ("callback", "fn", "func", "function"):
|
|
255
|
+
return _UNABLE, False
|
|
256
|
+
if param.name.lower() == "y" and "X" in sibling_names:
|
|
257
|
+
return _varying_label_vector(shape_idx), False
|
|
258
|
+
|
|
259
|
+
# Rule 3 continued: _valid_for name guess for remaining unannotated params.
|
|
260
|
+
val, ok = _valid_for("", inspect.Parameter.empty, param.name)
|
|
261
|
+
if ok:
|
|
262
|
+
return _choose(val)
|
|
263
|
+
|
|
264
|
+
return _scalar_default(param, scalar_idx, shape_idx), True
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _varying_matrix(shape_idx: int) -> List[List[float]]:
|
|
268
|
+
"""Return genuinely different matrix shapes across shape_idx."""
|
|
269
|
+
shapes = [
|
|
270
|
+
[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],
|
|
271
|
+
[[7.0, 8.0], [9.0, 10.0], [11.0, 12.0], [13.0, 14.0]],
|
|
272
|
+
[[15.0, 16.0, 17.0], [18.0, 19.0, 20.0], [21.0, 22.0, 23.0]],
|
|
273
|
+
[[24.0, 25.0], [26.0, 27.0]],
|
|
274
|
+
]
|
|
275
|
+
return shapes[shape_idx % len(shapes)]
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _varying_float_vector(shape_idx: int) -> List[float]:
|
|
279
|
+
"""Return genuinely different 1-D float vectors across shape_idx."""
|
|
280
|
+
vectors = [
|
|
281
|
+
[1.0, 2.0, 3.0, 4.0, 5.0],
|
|
282
|
+
[10.0, 20.0, 30.0],
|
|
283
|
+
[0.1, 0.2, 0.3, 0.4, 0.5, 0.6],
|
|
284
|
+
[100.0, -50.0, 25.0],
|
|
285
|
+
]
|
|
286
|
+
return vectors[shape_idx % len(vectors)]
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _varying_label_vector(shape_idx: int) -> List[int]:
|
|
290
|
+
"""Return genuinely different int label vectors across shape_idx."""
|
|
291
|
+
labels = [
|
|
292
|
+
[0, 1, 0, 1, 1, 0],
|
|
293
|
+
[1, 0, 1, 0],
|
|
294
|
+
[0, 0, 1, 1, 0, 1, 1],
|
|
295
|
+
[1, 1, 0, 0, 1],
|
|
296
|
+
]
|
|
297
|
+
return labels[shape_idx % len(labels)]
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _float_values(obj: Any) -> List[float]:
|
|
301
|
+
"""Return every float inside obj; ints and bools are excluded.
|
|
302
|
+
|
|
303
|
+
Floats inside lists, tuples, dicts, dataclasses and namedtuples are
|
|
304
|
+
collected so a (counter, result) tuple can be assessed by its result
|
|
305
|
+
element alone.
|
|
306
|
+
"""
|
|
307
|
+
if isinstance(obj, bool):
|
|
308
|
+
return []
|
|
309
|
+
if isinstance(obj, int):
|
|
310
|
+
return []
|
|
311
|
+
if isinstance(obj, float):
|
|
312
|
+
return [obj]
|
|
313
|
+
if isinstance(obj, (list, tuple)):
|
|
314
|
+
return [v for x in obj for v in _float_values(x)]
|
|
315
|
+
if isinstance(obj, dict):
|
|
316
|
+
return [v for x in obj.values() for v in _float_values(x)]
|
|
317
|
+
if hasattr(obj, "__dataclass_fields__"):
|
|
318
|
+
from dataclasses import asdict
|
|
319
|
+
return _float_values(asdict(obj))
|
|
320
|
+
if hasattr(obj, "_asdict"):
|
|
321
|
+
return _float_values(obj._asdict())
|
|
322
|
+
if hasattr(obj, "__dict__") and not isinstance(obj, type):
|
|
323
|
+
return _float_values(vars(obj))
|
|
324
|
+
return []
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _assess_floats(values: List[float]) -> str:
|
|
328
|
+
"""Classify a list of extracted float values against the criterion."""
|
|
329
|
+
if not values:
|
|
330
|
+
return "unknown"
|
|
331
|
+
has_nan = any(math.isnan(v) for v in values)
|
|
332
|
+
has_inf = any(math.isinf(v) for v in values)
|
|
333
|
+
has_finite = any(math.isfinite(v) for v in values)
|
|
334
|
+
if has_nan or has_inf:
|
|
335
|
+
if not has_finite:
|
|
336
|
+
return "poison_only"
|
|
337
|
+
return "mixture"
|
|
338
|
+
if has_finite:
|
|
339
|
+
return "finite"
|
|
340
|
+
return "unknown"
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _is_nan(v: Any) -> bool:
|
|
344
|
+
return isinstance(v, float) and math.isnan(v)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _is_inf(v: Any) -> bool:
|
|
348
|
+
return isinstance(v, float) and math.isinf(v)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _is_poison(v: Any) -> bool:
|
|
352
|
+
return _is_nan(v) or _is_inf(v)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _is_scalar_param(param: inspect.Parameter, sibling_names=frozenset(), shape_idx: int = 0) -> bool:
|
|
356
|
+
"""True if the chosen baseline value for this parameter is a scalar."""
|
|
357
|
+
# VAR_POSITIONAL / VAR_KEYWORD are not individually poisonable.
|
|
358
|
+
if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):
|
|
359
|
+
return False
|
|
360
|
+
_, is_scalar = _baseline_for(param, 0, sibling_names, shape_idx)
|
|
361
|
+
return is_scalar
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
SCALAR_DEFAULTS = [2.0, 0.5, 10.0, -3.0, 1.0, 0.01, 100.0, -0.5]
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _scalar_default(p: inspect.Parameter, idx: int, shape_idx: int = 0) -> Any:
|
|
368
|
+
"""Pick a deterministic scalar fallback for an un-typed parameter.
|
|
369
|
+
|
|
370
|
+
This is the "scalar 1.0 fallback" called only when annotation and name
|
|
371
|
+
give no guess. A varied sequence keeps multi-scalar signatures from
|
|
372
|
+
collapsing into identical values, which would hide reachability.
|
|
373
|
+
For multi-shape probing we also rotate per shape_idx so genuinely
|
|
374
|
+
different magnitudes are exercised.
|
|
375
|
+
"""
|
|
376
|
+
ann = p.annotation
|
|
377
|
+
is_int = (
|
|
378
|
+
ann is int
|
|
379
|
+
or (isinstance(ann, str) and ann.strip() == "int")
|
|
380
|
+
or (isinstance(p.default, int) and not isinstance(p.default, bool))
|
|
381
|
+
)
|
|
382
|
+
base = SCALAR_DEFAULTS[idx % len(SCALAR_DEFAULTS)]
|
|
383
|
+
# Rotate magnitude per shape to avoid coincidental collisions.
|
|
384
|
+
multipliers = [1.0, 10.0, 0.1, -1.0, 100.0, -0.1, 2.0, -10.0]
|
|
385
|
+
raw = base * multipliers[shape_idx % len(multipliers)]
|
|
386
|
+
return int(round(raw)) if is_int else raw
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _container_shape(value: Any) -> Optional[Tuple[int, ...]]:
|
|
390
|
+
"""Return shape for a regular container: (length,) for 1-D, (rows, cols) for 2-D."""
|
|
391
|
+
if not isinstance(value, (list, tuple)) or len(value) == 0:
|
|
392
|
+
return None
|
|
393
|
+
# 1-D vector: no nested list/tuple.
|
|
394
|
+
if not any(isinstance(x, (list, tuple)) for x in value):
|
|
395
|
+
return (len(value),)
|
|
396
|
+
# 2-D matrix: every row is a list/tuple of the same length.
|
|
397
|
+
if not all(isinstance(row, (list, tuple)) and len(row) > 0 for row in value):
|
|
398
|
+
return None
|
|
399
|
+
cols = len(value[0])
|
|
400
|
+
if not all(len(row) == cols for row in value):
|
|
401
|
+
return None
|
|
402
|
+
return (len(value), cols)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _param_shape_role(name: str, shape: Tuple[int, ...]) -> str:
|
|
406
|
+
"""Classify a container's role from its name and shape.
|
|
407
|
+
|
|
408
|
+
Role tells the coherence pass how this container relates to siblings:
|
|
409
|
+
matrix_data - training/feature matrix, anchors rows/cols
|
|
410
|
+
matrix_test - test matrix, must match matrix_data columns
|
|
411
|
+
matrix_la - linear-algebra operand, often needs to be square
|
|
412
|
+
label_vector - per-row target/label, must match matrix_data rows
|
|
413
|
+
sample_vector - single sample/query, must match matrix_data columns
|
|
414
|
+
"""
|
|
415
|
+
n = name.lower()
|
|
416
|
+
if len(shape) == 1:
|
|
417
|
+
if n in ("y", "y_train", "y_test", "labels", "targets", "classes",
|
|
418
|
+
"assignments", "groups"):
|
|
419
|
+
return "label_vector"
|
|
420
|
+
if n in ("x_test", "test_point", "query", "sample", "point",
|
|
421
|
+
"instance", "features"):
|
|
422
|
+
return "sample_vector"
|
|
423
|
+
if n in ("text", "doc", "word", "document"):
|
|
424
|
+
return "text"
|
|
425
|
+
return "vector"
|
|
426
|
+
if len(shape) == 2:
|
|
427
|
+
if n in ("x_test", "x_test_data", "test_data", "test_set"):
|
|
428
|
+
return "matrix_test"
|
|
429
|
+
if n in ("x_train", "x", "data", "samples", "features", "train_data",
|
|
430
|
+
"dataset"):
|
|
431
|
+
return "matrix_data"
|
|
432
|
+
return "matrix"
|
|
433
|
+
return "other"
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _resize_vector(value: Any, length: int) -> Any:
|
|
437
|
+
"""Resize a 1-D list/tuple to the requested length, cycling original items."""
|
|
438
|
+
if length <= 0 or not isinstance(value, (list, tuple)):
|
|
439
|
+
return value
|
|
440
|
+
base = list(value)
|
|
441
|
+
if len(base) == length:
|
|
442
|
+
return value
|
|
443
|
+
if len(base) > length:
|
|
444
|
+
return type(value)(base[:length])
|
|
445
|
+
extended = [base[i % len(base)] for i in range(length)]
|
|
446
|
+
return type(value)(extended)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _resize_matrix_cols(value: Any, cols: int) -> Any:
|
|
450
|
+
"""Resize each row of a matrix to the requested column count."""
|
|
451
|
+
if cols <= 0 or not isinstance(value, (list, tuple)):
|
|
452
|
+
return value
|
|
453
|
+
base = [list(row) for row in value]
|
|
454
|
+
new_rows = []
|
|
455
|
+
for row in base:
|
|
456
|
+
if len(row) == cols:
|
|
457
|
+
new_rows.append(row)
|
|
458
|
+
elif len(row) > cols:
|
|
459
|
+
new_rows.append(row[:cols])
|
|
460
|
+
else:
|
|
461
|
+
extended = [row[i % len(row)] if row else 0.0 for i in range(cols)]
|
|
462
|
+
new_rows.append(extended)
|
|
463
|
+
return type(value)(new_rows)
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _coherent_kwargs(kwargs: Dict[str, Any], sig: inspect.Signature) -> Dict[str, Any]:
|
|
467
|
+
"""Adjust generated container arguments so related shapes are compatible.
|
|
468
|
+
|
|
469
|
+
The per-type builder (_valid_for) cannot see sibling parameters, so a
|
|
470
|
+
matrix X and a vector y may get unrelated sizes. This pass resizes
|
|
471
|
+
label vectors to match matrix rows and sample/test vectors to match
|
|
472
|
+
matrix columns. Matrices in the same signature are forced to share a
|
|
473
|
+
column count (feature dimension) so X_train and X_test stay compatible.
|
|
474
|
+
"""
|
|
475
|
+
roles: Dict[str, str] = {}
|
|
476
|
+
shapes: Dict[str, Tuple[int, ...]] = {}
|
|
477
|
+
for name, val in kwargs.items():
|
|
478
|
+
shape = _container_shape(val)
|
|
479
|
+
if shape is not None:
|
|
480
|
+
roles[name] = _param_shape_role(name, shape)
|
|
481
|
+
shapes[name] = shape
|
|
482
|
+
|
|
483
|
+
if not shapes:
|
|
484
|
+
return kwargs
|
|
485
|
+
|
|
486
|
+
# Anchor row/column counts on a data matrix, preferring a training matrix.
|
|
487
|
+
data_matrix: Optional[str] = None
|
|
488
|
+
for name, role in roles.items():
|
|
489
|
+
if role == "matrix_data":
|
|
490
|
+
data_matrix = name
|
|
491
|
+
break
|
|
492
|
+
if data_matrix is None:
|
|
493
|
+
# Fall back to any 2-D matrix if no clear data matrix exists.
|
|
494
|
+
for name, shape in shapes.items():
|
|
495
|
+
if len(shape) == 2:
|
|
496
|
+
data_matrix = name
|
|
497
|
+
break
|
|
498
|
+
if data_matrix is None:
|
|
499
|
+
return kwargs
|
|
500
|
+
|
|
501
|
+
n_rows, n_cols = shapes[data_matrix]
|
|
502
|
+
|
|
503
|
+
# Label vectors must match the data matrix row count.
|
|
504
|
+
for name, role in roles.items():
|
|
505
|
+
if role == "label_vector":
|
|
506
|
+
kwargs[name] = _resize_vector(kwargs[name], n_rows)
|
|
507
|
+
|
|
508
|
+
# Sample/test vectors must match the data matrix column count.
|
|
509
|
+
for name, role in roles.items():
|
|
510
|
+
if role == "sample_vector":
|
|
511
|
+
kwargs[name] = _resize_vector(kwargs[name], n_cols)
|
|
512
|
+
|
|
513
|
+
# All matrices in the signature must share the same column count.
|
|
514
|
+
for name, shape in shapes.items():
|
|
515
|
+
if len(shape) != 2:
|
|
516
|
+
continue
|
|
517
|
+
rows, cols = shape
|
|
518
|
+
if cols != n_cols:
|
|
519
|
+
kwargs[name] = _resize_matrix_cols(kwargs[name], n_cols)
|
|
520
|
+
|
|
521
|
+
return kwargs
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _build_args(
|
|
525
|
+
sig: inspect.Signature,
|
|
526
|
+
poison_idx: Optional[int] = None,
|
|
527
|
+
poison_value: Optional[float] = None,
|
|
528
|
+
shape_idx: int = 0,
|
|
529
|
+
) -> Tuple[List[Any], Dict[str, Any], Optional[str], List[Any]]:
|
|
530
|
+
"""Construct positional/dict args for a test call.
|
|
531
|
+
|
|
532
|
+
Returns (args, kwargs, poisoned_name, scalar_clean_defaults).
|
|
533
|
+
shape_idx selects one of MULTI_SHAPE_COUNT genuinely different argument
|
|
534
|
+
shapes for the OTHER parameters; the poisoned scalar is always set via
|
|
535
|
+
scalar_defaults so it stays the clean baseline value in the clean run.
|
|
536
|
+
"""
|
|
537
|
+
args: List[Any] = []
|
|
538
|
+
kwargs: Dict[str, Any] = {}
|
|
539
|
+
scalar_params: List[inspect.Parameter] = []
|
|
540
|
+
scalar_defaults: List[Any] = []
|
|
541
|
+
sibling_names = set(sig.parameters)
|
|
542
|
+
|
|
543
|
+
for name, p in sig.parameters.items():
|
|
544
|
+
val, is_scalar = _baseline_for(p, len(scalar_params), sibling_names, shape_idx)
|
|
545
|
+
kwargs[name] = val
|
|
546
|
+
if is_scalar:
|
|
547
|
+
scalar_params.append(p)
|
|
548
|
+
scalar_defaults.append(val)
|
|
549
|
+
|
|
550
|
+
# G11: ensure matrix/vector siblings share a coherent shape. The per-type
|
|
551
|
+
# builder above cannot see sibling parameters, so labels may not match rows
|
|
552
|
+
# or a test point may not match feature count.
|
|
553
|
+
kwargs = _coherent_kwargs(kwargs, sig)
|
|
554
|
+
|
|
555
|
+
if poison_idx is not None and poison_idx < len(scalar_params):
|
|
556
|
+
p = scalar_params[poison_idx]
|
|
557
|
+
kwargs[p.name] = poison_value
|
|
558
|
+
return (
|
|
559
|
+
args,
|
|
560
|
+
kwargs,
|
|
561
|
+
scalar_params[poison_idx].name if poison_idx is not None and poison_idx < len(scalar_params) else None,
|
|
562
|
+
scalar_defaults,
|
|
563
|
+
)
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def _is_degenerate(obj: Any) -> bool:
|
|
567
|
+
"""True if a clean baseline result looks like no-op output.
|
|
568
|
+
|
|
569
|
+
Degenerate values (all-zero weights, empty collections, None) mean the
|
|
570
|
+
fixture probably did not exercise the algorithm, so a comparison is
|
|
571
|
+
not a valid reachability signal. Ints are counters/statuses/lengths,
|
|
572
|
+
not numeric results, so a single int (even 0) is not degenerate.
|
|
573
|
+
"""
|
|
574
|
+
if obj is None:
|
|
575
|
+
return True
|
|
576
|
+
if isinstance(obj, bool):
|
|
577
|
+
return False
|
|
578
|
+
if isinstance(obj, int):
|
|
579
|
+
return False
|
|
580
|
+
if isinstance(obj, float):
|
|
581
|
+
return obj == 0.0
|
|
582
|
+
if isinstance(obj, (list, tuple)):
|
|
583
|
+
if len(obj) == 0:
|
|
584
|
+
return True
|
|
585
|
+
return all(_is_degenerate(x) for x in obj)
|
|
586
|
+
if isinstance(obj, dict):
|
|
587
|
+
if len(obj) == 0:
|
|
588
|
+
return True
|
|
589
|
+
return all(_is_degenerate(x) for x in obj.values())
|
|
590
|
+
return False
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _canonical(obj: Any) -> Any:
|
|
594
|
+
"""Stable serialisation for clean-vs-poison comparison."""
|
|
595
|
+
if obj is None:
|
|
596
|
+
return None
|
|
597
|
+
if isinstance(obj, bool):
|
|
598
|
+
return obj
|
|
599
|
+
if isinstance(obj, (int, float)):
|
|
600
|
+
if isinstance(obj, float) and math.isnan(obj):
|
|
601
|
+
return "__NaN__"
|
|
602
|
+
if isinstance(obj, float) and math.isinf(obj):
|
|
603
|
+
return ("__Inf__" if obj > 0 else "__-Inf__")
|
|
604
|
+
return obj
|
|
605
|
+
if isinstance(obj, (list, tuple)):
|
|
606
|
+
return [_canonical(x) for x in obj]
|
|
607
|
+
if isinstance(obj, dict):
|
|
608
|
+
return {str(k): _canonical(v) for k, v in sorted(obj.items(), key=lambda kv: str(kv[0]))}
|
|
609
|
+
if hasattr(obj, "__dataclass_fields__"):
|
|
610
|
+
from dataclasses import asdict
|
|
611
|
+
return _canonical(asdict(obj))
|
|
612
|
+
if hasattr(obj, "_asdict"):
|
|
613
|
+
return _canonical(obj._asdict())
|
|
614
|
+
if hasattr(obj, "__dict__") and not isinstance(obj, type):
|
|
615
|
+
return _canonical(vars(obj))
|
|
616
|
+
return repr(obj)
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
class FixtureTimeoutError(Exception):
|
|
620
|
+
"""Raised when a fixture subprocess does not return within the timeout."""
|
|
621
|
+
pass
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def _limit_resources() -> None:
|
|
625
|
+
"""Set tight per-process resource ceilings in fixture subprocesses.
|
|
626
|
+
|
|
627
|
+
G17 defence in depth: even if a fixture escapes the wall-clock timeout by
|
|
628
|
+
forking or blocking, CPU and address-space hard limits kill it quickly.
|
|
629
|
+
"""
|
|
630
|
+
try:
|
|
631
|
+
resource.setrlimit(
|
|
632
|
+
resource.RLIMIT_CPU,
|
|
633
|
+
(FIXTURE_CPU_LIMIT_SECONDS, FIXTURE_CPU_LIMIT_SECONDS),
|
|
634
|
+
)
|
|
635
|
+
resource.setrlimit(
|
|
636
|
+
resource.RLIMIT_AS,
|
|
637
|
+
(FIXTURE_MEMORY_LIMIT_BYTES, FIXTURE_MEMORY_LIMIT_BYTES),
|
|
638
|
+
)
|
|
639
|
+
except (ValueError, OSError):
|
|
640
|
+
pass
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def _load_module(path: Path) -> Any:
|
|
644
|
+
"""Return the module after loading it in a separate, time-bounded child process.
|
|
645
|
+
|
|
646
|
+
G17: the fixture is submitted AI-generated code from strangers. It may contain
|
|
647
|
+
infinite loops, unbounded recursion, forking, or large allocations. Running it
|
|
648
|
+
in-process gives it the lens's privileges and lets it hang/cook the machine.
|
|
649
|
+
|
|
650
|
+
We therefore load the module inside a child Python process:
|
|
651
|
+
- start_new_session=True gives the child its own process group
|
|
652
|
+
- a hard wall-clock timeout in the parent reaps runaway fixtures
|
|
653
|
+
- os.killpg(os.getpgid(p.pid), SIGKILL) kills the whole tree, never p.kill()
|
|
654
|
+
|
|
655
|
+
The child serialises the names of public functions back to the parent. The
|
|
656
|
+
parent then re-imports the file to obtain live function objects. The second
|
|
657
|
+
in-process import is safe because the child already proved the top-level module
|
|
658
|
+
executes within the timeout; module-level loops are caught by the same timeout.
|
|
659
|
+
"""
|
|
660
|
+
probe_script = textwrap.dedent(
|
|
661
|
+
"""
|
|
662
|
+
import importlib.util
|
|
663
|
+
import inspect
|
|
664
|
+
import sys
|
|
665
|
+
path = sys.argv[1]
|
|
666
|
+
spec = importlib.util.spec_from_file_location("guard_fixture_under_test", path)
|
|
667
|
+
mod = importlib.util.module_from_spec(spec)
|
|
668
|
+
spec.loader.exec_module(mod)
|
|
669
|
+
names = []
|
|
670
|
+
for name in dir(mod):
|
|
671
|
+
if name.startswith("_"):
|
|
672
|
+
continue
|
|
673
|
+
obj = getattr(mod, name)
|
|
674
|
+
if callable(obj) and inspect.isfunction(obj) and obj.__module__ == mod.__name__:
|
|
675
|
+
names.append(name)
|
|
676
|
+
print("\\n".join(names))
|
|
677
|
+
"""
|
|
678
|
+
).strip() + "\n"
|
|
679
|
+
|
|
680
|
+
with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as child:
|
|
681
|
+
child.write(probe_script)
|
|
682
|
+
child_path = child.name
|
|
683
|
+
|
|
684
|
+
try:
|
|
685
|
+
p = subprocess.Popen(
|
|
686
|
+
[sys.executable, child_path, str(path)],
|
|
687
|
+
stdout=subprocess.PIPE,
|
|
688
|
+
stderr=subprocess.PIPE,
|
|
689
|
+
text=True,
|
|
690
|
+
start_new_session=True,
|
|
691
|
+
preexec_fn=_limit_resources,
|
|
692
|
+
)
|
|
693
|
+
try:
|
|
694
|
+
out, err = p.communicate(timeout=FIXTURE_TIMEOUT_SECONDS)
|
|
695
|
+
except subprocess.TimeoutExpired:
|
|
696
|
+
try:
|
|
697
|
+
os.killpg(os.getpgid(p.pid), signal.SIGKILL)
|
|
698
|
+
except (ProcessLookupError, PermissionError):
|
|
699
|
+
p.kill()
|
|
700
|
+
try:
|
|
701
|
+
out, err = p.communicate(timeout=10)
|
|
702
|
+
except Exception:
|
|
703
|
+
out, err = "", ""
|
|
704
|
+
raise FixtureTimeoutError(
|
|
705
|
+
f"fixture exceeded {FIXTURE_TIMEOUT_SECONDS}s"
|
|
706
|
+
)
|
|
707
|
+
if p.returncode != 0:
|
|
708
|
+
raise ImportError(f"fixture import failed: {err.strip() or 'unknown error'}")
|
|
709
|
+
function_names = [line.strip() for line in out.splitlines() if line.strip()]
|
|
710
|
+
finally:
|
|
711
|
+
try:
|
|
712
|
+
os.unlink(child_path)
|
|
713
|
+
except OSError:
|
|
714
|
+
pass
|
|
715
|
+
|
|
716
|
+
# Second in-process import is safe: the child proved module-level code terminates
|
|
717
|
+
# within FIXTURE_TIMEOUT_SECONDS. We need live callables in this process.
|
|
718
|
+
spec = importlib.util.spec_from_file_location("guard_fixture_under_test", str(path))
|
|
719
|
+
if spec is None or spec.loader is None:
|
|
720
|
+
raise ImportError(f"cannot load {path}")
|
|
721
|
+
mod = importlib.util.module_from_spec(spec)
|
|
722
|
+
spec.loader.exec_module(mod)
|
|
723
|
+
|
|
724
|
+
# If the child saw functions but the in-process import disagrees, trust the child.
|
|
725
|
+
if function_names:
|
|
726
|
+
for name in function_names:
|
|
727
|
+
if not hasattr(mod, name):
|
|
728
|
+
raise ImportError(f"fixture function {name} missing after import")
|
|
729
|
+
return mod
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def _json_safe(obj: Any) -> Any:
|
|
733
|
+
"""Convert a fixture result to a JSON-serialisable form for IPC.
|
|
734
|
+
|
|
735
|
+
Preserves NaN/Inf (json handles them as Python extensions), converts
|
|
736
|
+
tuples to lists, and falls back to repr for exotic objects.
|
|
737
|
+
"""
|
|
738
|
+
if isinstance(obj, bool):
|
|
739
|
+
return obj
|
|
740
|
+
if isinstance(obj, (int, float)):
|
|
741
|
+
return obj
|
|
742
|
+
if isinstance(obj, str):
|
|
743
|
+
return obj
|
|
744
|
+
if obj is None:
|
|
745
|
+
return None
|
|
746
|
+
if isinstance(obj, (list, tuple)):
|
|
747
|
+
return [_json_safe(x) for x in obj]
|
|
748
|
+
if isinstance(obj, dict):
|
|
749
|
+
return {str(k): _json_safe(v) for k, v in obj.items()}
|
|
750
|
+
if hasattr(obj, "__dataclass_fields__"):
|
|
751
|
+
from dataclasses import asdict
|
|
752
|
+
return _json_safe(asdict(obj))
|
|
753
|
+
if hasattr(obj, "_asdict"):
|
|
754
|
+
return _json_safe(obj._asdict())
|
|
755
|
+
return repr(obj)
|
|
756
|
+
|
|
757
|
+
|
|
758
|
+
def _run_fixture_call(path: Path, fn_name: str, args_json: str) -> Tuple[bool, Any, bool]:
|
|
759
|
+
"""Run a single function call in a subprocess, returning (raised, result, was_killed).
|
|
760
|
+
|
|
761
|
+
This is the second half of G17 isolation. _load_module only proves the
|
|
762
|
+
module imports safely; the actual function calls exercise poisoned inputs,
|
|
763
|
+
which may trigger adversarial code paths. We run each call in a fresh child
|
|
764
|
+
process with the same timeout + killpg + resource-limit discipline.
|
|
765
|
+
|
|
766
|
+
Returns:
|
|
767
|
+
(True, exception_message, was_killed) if the child raised or crashed.
|
|
768
|
+
(False, result, False) if it returned.
|
|
769
|
+
A timeout, crash, or resource violation is treated as "could not measure" by
|
|
770
|
+
the caller. was_killed is True when the child had to be SIGKILLed because it
|
|
771
|
+
hit the wall-clock timeout or RLIMIT_CPU/AS.
|
|
772
|
+
"""
|
|
773
|
+
call_script = textwrap.dedent(
|
|
774
|
+
"""
|
|
775
|
+
import importlib.util
|
|
776
|
+
import inspect
|
|
777
|
+
import json
|
|
778
|
+
import sys
|
|
779
|
+
|
|
780
|
+
def _json_safe(obj):
|
|
781
|
+
if isinstance(obj, bool):
|
|
782
|
+
return obj
|
|
783
|
+
if isinstance(obj, (int, float)):
|
|
784
|
+
return obj
|
|
785
|
+
if isinstance(obj, str):
|
|
786
|
+
return obj
|
|
787
|
+
if obj is None:
|
|
788
|
+
return None
|
|
789
|
+
if isinstance(obj, (list, tuple)):
|
|
790
|
+
return [_json_safe(x) for x in obj]
|
|
791
|
+
if isinstance(obj, dict):
|
|
792
|
+
return {str(k): _json_safe(v) for k, v in obj.items()}
|
|
793
|
+
if hasattr(obj, "__dataclass_fields__"):
|
|
794
|
+
from dataclasses import asdict
|
|
795
|
+
return _json_safe(asdict(obj))
|
|
796
|
+
if hasattr(obj, "_asdict"):
|
|
797
|
+
return _json_safe(obj._asdict())
|
|
798
|
+
return repr(obj)
|
|
799
|
+
|
|
800
|
+
path = sys.argv[1]
|
|
801
|
+
fn_name = sys.argv[2]
|
|
802
|
+
args, kwargs = json.loads(sys.argv[3])
|
|
803
|
+
spec = importlib.util.spec_from_file_location("guard_fixture_under_test", path)
|
|
804
|
+
mod = importlib.util.module_from_spec(spec)
|
|
805
|
+
spec.loader.exec_module(mod)
|
|
806
|
+
fn = getattr(mod, fn_name)
|
|
807
|
+
sig = inspect.signature(fn)
|
|
808
|
+
bound = sig.bind(*args, **kwargs)
|
|
809
|
+
bound.apply_defaults()
|
|
810
|
+
try:
|
|
811
|
+
result = fn(*bound.args, **bound.kwargs)
|
|
812
|
+
print("RESULT: " + json.dumps(_json_safe(result)))
|
|
813
|
+
except Exception as exc:
|
|
814
|
+
print("RAISED: " + type(exc).__name__ + ": " + str(exc))
|
|
815
|
+
"""
|
|
816
|
+
).strip() + "\n"
|
|
817
|
+
|
|
818
|
+
with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as child:
|
|
819
|
+
child.write(call_script)
|
|
820
|
+
child_path = child.name
|
|
821
|
+
|
|
822
|
+
try:
|
|
823
|
+
p = subprocess.Popen(
|
|
824
|
+
[sys.executable, child_path, str(path), fn_name, args_json],
|
|
825
|
+
stdout=subprocess.PIPE,
|
|
826
|
+
stderr=subprocess.PIPE,
|
|
827
|
+
text=True,
|
|
828
|
+
start_new_session=True,
|
|
829
|
+
preexec_fn=_limit_resources,
|
|
830
|
+
)
|
|
831
|
+
try:
|
|
832
|
+
out, err = p.communicate(timeout=FIXTURE_TIMEOUT_SECONDS)
|
|
833
|
+
except subprocess.TimeoutExpired:
|
|
834
|
+
try:
|
|
835
|
+
os.killpg(os.getpgid(p.pid), signal.SIGKILL)
|
|
836
|
+
except (ProcessLookupError, PermissionError):
|
|
837
|
+
p.kill()
|
|
838
|
+
try:
|
|
839
|
+
out, err = p.communicate(timeout=10)
|
|
840
|
+
except Exception:
|
|
841
|
+
out, err = "", ""
|
|
842
|
+
return True, f"fixture exceeded {FIXTURE_TIMEOUT_SECONDS}s", True
|
|
843
|
+
if p.returncode != 0:
|
|
844
|
+
err_text = err.strip() or out.strip() or "unknown error"
|
|
845
|
+
was_killed = p.returncode == -signal.SIGKILL or "Resource temporarily unavailable" in err_text
|
|
846
|
+
return True, f"fixture call failed: {err_text}", was_killed
|
|
847
|
+
out = out.strip()
|
|
848
|
+
if out.startswith("RAISED: "):
|
|
849
|
+
return True, out[8:], False
|
|
850
|
+
if out.startswith("RESULT: "):
|
|
851
|
+
try:
|
|
852
|
+
result = json.loads(out[8:])
|
|
853
|
+
except Exception:
|
|
854
|
+
result = out[8:]
|
|
855
|
+
return False, result, False
|
|
856
|
+
return True, f"unexpected fixture call output: {out!r}", False
|
|
857
|
+
finally:
|
|
858
|
+
try:
|
|
859
|
+
os.unlink(child_path)
|
|
860
|
+
except OSError:
|
|
861
|
+
pass
|
|
862
|
+
|
|
863
|
+
|
|
864
|
+
def _find_candidate_functions(mod: Any) -> List[Tuple[str, Callable]]:
|
|
865
|
+
"""Find top-level functions that look like the code's public API."""
|
|
866
|
+
out = []
|
|
867
|
+
for name in dir(mod):
|
|
868
|
+
if name.startswith("_"):
|
|
869
|
+
continue
|
|
870
|
+
obj = getattr(mod, name)
|
|
871
|
+
if callable(obj) and inspect.isfunction(obj) and obj.__module__ == mod.__name__:
|
|
872
|
+
out.append((name, obj))
|
|
873
|
+
return out
|
|
874
|
+
|
|
875
|
+
|
|
876
|
+
def _harvest_numeric_literals(fn: Callable) -> List[float]:
|
|
877
|
+
"""Collect numeric constants from a function's source.
|
|
878
|
+
|
|
879
|
+
U4: a function that branches on specific numbers (status codes, thresholds,
|
|
880
|
+
enum values) is only reachable if we probe those numbers. We read what the
|
|
881
|
+
code itself says about itself, not a domain map.
|
|
882
|
+
|
|
883
|
+
Returns a deduplicated list of finite float/int literals, capped at
|
|
884
|
+
MAX_HARVESTED_LITERALS. Source that cannot be retrieved yields an empty list.
|
|
885
|
+
"""
|
|
886
|
+
try:
|
|
887
|
+
source = inspect.getsource(fn)
|
|
888
|
+
except Exception:
|
|
889
|
+
return []
|
|
890
|
+
try:
|
|
891
|
+
tree = ast.parse(textwrap.dedent(source))
|
|
892
|
+
except Exception:
|
|
893
|
+
return []
|
|
894
|
+
|
|
895
|
+
literals: set = set()
|
|
896
|
+
for node in ast.walk(tree):
|
|
897
|
+
if isinstance(node, ast.Constant):
|
|
898
|
+
value = node.value
|
|
899
|
+
if isinstance(value, bool):
|
|
900
|
+
continue
|
|
901
|
+
if isinstance(value, (int, float)) and math.isfinite(value):
|
|
902
|
+
literals.add(float(value))
|
|
903
|
+
|
|
904
|
+
ordered = sorted(literals, key=lambda v: (abs(v), v < 0))
|
|
905
|
+
return ordered[:MAX_HARVESTED_LITERALS]
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
def _run_call(fn: Callable, args: List[Any], kwargs: Dict[str, Any]) -> Tuple[bool, Any, bool]:
|
|
909
|
+
"""Run a single function call in a subprocess, returning (raised, result, was_killed).
|
|
910
|
+
|
|
911
|
+
The lens now isolates fixture execution. This shim JSON-serialises the
|
|
912
|
+
argument bundle and delegates to the subprocess runner. Exotic arguments
|
|
913
|
+
that are not JSON-serialisable are reported as raised/INCONCLUSIVE.
|
|
914
|
+
"""
|
|
915
|
+
try:
|
|
916
|
+
payload = json.dumps((args, kwargs))
|
|
917
|
+
except (TypeError, ValueError) as exc:
|
|
918
|
+
return True, f"arguments not serialisable: {exc}", False
|
|
919
|
+
try:
|
|
920
|
+
path = Path(fn.__code__.co_filename)
|
|
921
|
+
except Exception:
|
|
922
|
+
return True, "cannot locate fixture source", False
|
|
923
|
+
raised, result, was_killed = _run_fixture_call(path, fn.__name__, payload)
|
|
924
|
+
if raised:
|
|
925
|
+
return True, Exception(result), was_killed
|
|
926
|
+
return False, result, False
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
def _componentwise_nan_defects(clean: Any, poisoned: Any) -> int:
|
|
930
|
+
"""Compare float elements pairwise across clean and poisoned results.
|
|
931
|
+
|
|
932
|
+
G12 componentwise reachability rule:
|
|
933
|
+
- poisoned component is NaN/Inf -> correct propagation, no defect
|
|
934
|
+
- poisoned component finite and UNCHANGED -> independent of poison, no defect
|
|
935
|
+
- poisoned component finite and CHANGED -> NaN influenced it = DEFECT
|
|
936
|
+
|
|
937
|
+
If the number or nesting of float elements differs, the NaN changed
|
|
938
|
+
control flow; any finite component in the poisoned result is a defect.
|
|
939
|
+
"""
|
|
940
|
+
clean_floats = _float_values(clean)
|
|
941
|
+
poisoned_floats = _float_values(poisoned)
|
|
942
|
+
if len(clean_floats) != len(poisoned_floats):
|
|
943
|
+
return sum(1 for v in poisoned_floats if math.isfinite(v))
|
|
944
|
+
defects = 0
|
|
945
|
+
for c, p in zip(clean_floats, poisoned_floats):
|
|
946
|
+
if not math.isfinite(p):
|
|
947
|
+
continue
|
|
948
|
+
if _canonical(c) != _canonical(p):
|
|
949
|
+
defects += 1
|
|
950
|
+
return defects
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
def _assess_result(result: Any) -> str:
|
|
954
|
+
"""Classify a return value by its float elements against the criterion."""
|
|
955
|
+
return _assess_floats(_float_values(result))
|
|
956
|
+
|
|
957
|
+
|
|
958
|
+
def evaluate_fixture(path: Path) -> Tuple[str, str, List[str], Dict[str, Any]]:
|
|
959
|
+
"""Return (verdict, reason, detail_lines, scope_counts).
|
|
960
|
+
|
|
961
|
+
Scope counts partition every scalar parameter into exactly one bucket so
|
|
962
|
+
downstream reports can say what an UNMATCHED PASS actually measured:
|
|
963
|
+
* params_total — scalar parameters found in scanned functions
|
|
964
|
+
* params_judged — at least one poison produced a discriminating result
|
|
965
|
+
* params_unreachable — every observed poison returned identical output to clean
|
|
966
|
+
* params_unexercised — no valid baseline could be built for any poison
|
|
967
|
+
* functions_total — public functions in the module
|
|
968
|
+
* functions_scanned — public functions with at least one scalar parameter
|
|
969
|
+
* mode — UNMATCHED (this lens has no reference oracle)
|
|
970
|
+
"""
|
|
971
|
+
scope: Dict[str, Any] = {
|
|
972
|
+
"params_total": 0,
|
|
973
|
+
"params_judged": 0,
|
|
974
|
+
"params_unreachable": 0,
|
|
975
|
+
"params_unexercised": 0,
|
|
976
|
+
"params_aborted": 0,
|
|
977
|
+
"functions_total": 0,
|
|
978
|
+
"functions_scanned": 0,
|
|
979
|
+
"mode": "UNMATCHED",
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
try:
|
|
983
|
+
mod = _load_module(path)
|
|
984
|
+
except FixtureTimeoutError as exc:
|
|
985
|
+
return "INCONCLUSIVE", str(exc), [], scope
|
|
986
|
+
except Exception as exc:
|
|
987
|
+
return "INCONCLUSIVE", f"could not load fixture: {type(exc).__name__}: {exc}", [], scope
|
|
988
|
+
|
|
989
|
+
candidates = _find_candidate_functions(mod)
|
|
990
|
+
scope["functions_total"] = len(candidates)
|
|
991
|
+
if not candidates:
|
|
992
|
+
return "PASS", "no public functions to test", [], scope
|
|
993
|
+
|
|
994
|
+
nan_objections: List[str] = []
|
|
995
|
+
nan_weak: List[str] = []
|
|
996
|
+
nan_unreachable: List[str] = []
|
|
997
|
+
nan_aborted: List[str] = []
|
|
998
|
+
inf_notes: List[str] = []
|
|
999
|
+
tested = 0
|
|
1000
|
+
exercised = False
|
|
1001
|
+
for fn_name, fn in candidates:
|
|
1002
|
+
try:
|
|
1003
|
+
sig = inspect.signature(fn)
|
|
1004
|
+
except Exception:
|
|
1005
|
+
continue
|
|
1006
|
+
scalar_params = [p for p in sig.parameters.values() if _is_scalar_param(p, set(sig.parameters), 0)]
|
|
1007
|
+
|
|
1008
|
+
# U6: if any sibling parameter is structurally unsynthesisable (e.g. an
|
|
1009
|
+
# unannotated callback), the whole function cannot be exercised honestly.
|
|
1010
|
+
# Count its scalar parameters as unexercised and move on.
|
|
1011
|
+
has_unable_sibling = any(
|
|
1012
|
+
_baseline_for(p, 0, set(sig.parameters), 0)[0] is _UNABLE
|
|
1013
|
+
for p in sig.parameters.values()
|
|
1014
|
+
)
|
|
1015
|
+
if has_unable_sibling:
|
|
1016
|
+
scope["params_total"] += len(scalar_params)
|
|
1017
|
+
scope["params_unexercised"] += len(scalar_params)
|
|
1018
|
+
continue
|
|
1019
|
+
|
|
1020
|
+
if not scalar_params:
|
|
1021
|
+
continue
|
|
1022
|
+
tested += 1
|
|
1023
|
+
|
|
1024
|
+
# U4: harvest the function's own numeric literals so membership/comparison
|
|
1025
|
+
# branches (status codes, thresholds, magic numbers) become reachable.
|
|
1026
|
+
fn_literals = _harvest_numeric_literals(fn)
|
|
1027
|
+
|
|
1028
|
+
for idx, p in enumerate(scalar_params):
|
|
1029
|
+
scope["params_total"] += 1
|
|
1030
|
+
param_had_valid_baseline = False
|
|
1031
|
+
param_handled_raise = False
|
|
1032
|
+
param_had_discrimination = False
|
|
1033
|
+
param_probe_aborted = False
|
|
1034
|
+
|
|
1035
|
+
for poison in POISON_NAN + POISON_INF:
|
|
1036
|
+
# G21 + U4: probe each scalar poison across MULTI_SHAPE_COUNT
|
|
1037
|
+
# genuinely different shapes for the OTHER parameters, plus any
|
|
1038
|
+
# numeric literals the function itself mentions for the poisoned
|
|
1039
|
+
# parameter. A finite component is only called "independent" if it
|
|
1040
|
+
# is unchanged in EVERY observation; any observation where it changes
|
|
1041
|
+
# proves the poison reached it.
|
|
1042
|
+
shape_observations: List[Tuple[Any, Any]] = []
|
|
1043
|
+
baseline_skips = 0
|
|
1044
|
+
raised_handled = 0
|
|
1045
|
+
probe_aborted = False
|
|
1046
|
+
|
|
1047
|
+
for shape_idx in range(MULTI_SHAPE_COUNT):
|
|
1048
|
+
try:
|
|
1049
|
+
args, kwargs, poisoned_name, scalar_defaults = _build_args(sig, idx, poison, shape_idx)
|
|
1050
|
+
except Exception:
|
|
1051
|
+
baseline_skips += 1
|
|
1052
|
+
continue
|
|
1053
|
+
|
|
1054
|
+
# Candidate clean values for the poisoned parameter: the shape's
|
|
1055
|
+
# default plus the function's own literals (deduped, capped).
|
|
1056
|
+
candidate_values: List[Any] = [scalar_defaults[idx]]
|
|
1057
|
+
for lit in fn_literals:
|
|
1058
|
+
if lit != scalar_defaults[idx]:
|
|
1059
|
+
candidate_values.append(lit)
|
|
1060
|
+
if len(candidate_values) > MAX_HARVESTED_LITERALS + 1:
|
|
1061
|
+
candidate_values = candidate_values[:MAX_HARVESTED_LITERALS + 1]
|
|
1062
|
+
|
|
1063
|
+
for clean_value in candidate_values:
|
|
1064
|
+
# Baseline: run with a clean value for the poisoned parameter.
|
|
1065
|
+
clean_kwargs = dict(kwargs)
|
|
1066
|
+
clean_kwargs[p.name] = clean_value
|
|
1067
|
+
clean_raised, clean_result, clean_killed = _run_call(fn, args, clean_kwargs)
|
|
1068
|
+
if clean_raised:
|
|
1069
|
+
if clean_killed:
|
|
1070
|
+
# The fixture consumed too much CPU/time even with a clean
|
|
1071
|
+
# input; further shapes/candidates will not help.
|
|
1072
|
+
probe_aborted = True
|
|
1073
|
+
break
|
|
1074
|
+
# A normal exception on this candidate: skip it.
|
|
1075
|
+
baseline_skips += 1
|
|
1076
|
+
continue
|
|
1077
|
+
if _is_degenerate(clean_result):
|
|
1078
|
+
# This candidate produced no-op output; skip it.
|
|
1079
|
+
baseline_skips += 1
|
|
1080
|
+
continue
|
|
1081
|
+
|
|
1082
|
+
param_had_valid_baseline = True
|
|
1083
|
+
raised, result, was_killed = _run_call(fn, args, kwargs)
|
|
1084
|
+
if raised:
|
|
1085
|
+
if was_killed:
|
|
1086
|
+
# The poisoned call was killed; treat the whole probe as
|
|
1087
|
+
# "could not measure" rather than as handled/raised.
|
|
1088
|
+
probe_aborted = True
|
|
1089
|
+
break
|
|
1090
|
+
# Loud failure is handled for both NaN and Inf; we know the
|
|
1091
|
+
# baseline reached this branch, so the raise is a real response.
|
|
1092
|
+
raised_handled += 1
|
|
1093
|
+
param_handled_raise = True
|
|
1094
|
+
continue
|
|
1095
|
+
shape_observations.append((clean_result, result))
|
|
1096
|
+
|
|
1097
|
+
if probe_aborted:
|
|
1098
|
+
break
|
|
1099
|
+
|
|
1100
|
+
if probe_aborted:
|
|
1101
|
+
# A resource KILL is not a measurement. The clean baseline may have
|
|
1102
|
+
# been perfectly valid; what failed is that the budget ran out before
|
|
1103
|
+
# anything was observed. The old code emitted "baseline invalid:
|
|
1104
|
+
# raised or degenerate" here, which sent a reader hunting for a bad
|
|
1105
|
+
# baseline that does not exist.
|
|
1106
|
+
param_probe_aborted = True
|
|
1107
|
+
nan_aborted.append(
|
|
1108
|
+
f"{fn_name}({poisoned_name}=...) probe ABORTED: resource limit "
|
|
1109
|
+
f"reached, nothing observed"
|
|
1110
|
+
)
|
|
1111
|
+
continue
|
|
1112
|
+
if not shape_observations and raised_handled == 0:
|
|
1113
|
+
nan_unreachable.append(
|
|
1114
|
+
f"{fn_name}({poisoned_name}=...) baseline invalid: raised or degenerate"
|
|
1115
|
+
)
|
|
1116
|
+
continue
|
|
1117
|
+
|
|
1118
|
+
exercised = True
|
|
1119
|
+
|
|
1120
|
+
if not shape_observations:
|
|
1121
|
+
# Every shape that had a valid baseline raised on poison;
|
|
1122
|
+
# the poison is handled by loud failure.
|
|
1123
|
+
continue
|
|
1124
|
+
|
|
1125
|
+
poison_label = "NaN" if _is_nan(poison) else ("+Inf" if poison > 0 else "-Inf")
|
|
1126
|
+
|
|
1127
|
+
# Reachability guard (multi-shape): if poison produced identical
|
|
1128
|
+
# output to clean at every observed shape, the parameter is unreachable.
|
|
1129
|
+
if all(_canonical(r) == _canonical(c) for c, r in shape_observations):
|
|
1130
|
+
nan_unreachable.append(
|
|
1131
|
+
f"{fn_name}({poisoned_name}={poison_label}) parameter unreachable: "
|
|
1132
|
+
f"poisoned output identical to clean baseline"
|
|
1133
|
+
)
|
|
1134
|
+
continue
|
|
1135
|
+
|
|
1136
|
+
param_had_discrimination = True
|
|
1137
|
+
|
|
1138
|
+
if _is_nan(poison):
|
|
1139
|
+
# G12 + G21: componentwise reachability across all shapes.
|
|
1140
|
+
defects_per_shape = [
|
|
1141
|
+
_componentwise_nan_defects(c, r) for c, r in shape_observations
|
|
1142
|
+
]
|
|
1143
|
+
if all(d == 0 for d in defects_per_shape):
|
|
1144
|
+
# Finite component is unchanged across all observed shapes -> independent.
|
|
1145
|
+
continue
|
|
1146
|
+
# At least one shape shows a changed finite component -> defect.
|
|
1147
|
+
total_defects = sum(defects_per_shape)
|
|
1148
|
+
is_tol = poisoned_name and poisoned_name.lower() in TOLERANCE_NAMES
|
|
1149
|
+
note = (
|
|
1150
|
+
f"{fn_name}({poisoned_name}=NaN) componentwise: "
|
|
1151
|
+
f"{total_defects} finite component(s) changed vs clean across {len(defects_per_shape)} shape(s)"
|
|
1152
|
+
)
|
|
1153
|
+
if is_tol:
|
|
1154
|
+
nan_weak.append(note + " [tolerance-name heuristic, not measured]")
|
|
1155
|
+
else:
|
|
1156
|
+
nan_objections.append(note)
|
|
1157
|
+
else:
|
|
1158
|
+
# Inf -> finite/mixture may be correct saturation; record, do not accuse.
|
|
1159
|
+
# Use the first shape's classification as representative.
|
|
1160
|
+
clean_result, result = shape_observations[0]
|
|
1161
|
+
assessment = _assess_result(result)
|
|
1162
|
+
inf_notes.append(
|
|
1163
|
+
f"{fn_name}({poisoned_name}={poison_label}) returned {assessment}: {type(result).__name__}"
|
|
1164
|
+
)
|
|
1165
|
+
if param_handled_raise or param_had_discrimination:
|
|
1166
|
+
scope["params_judged"] += 1
|
|
1167
|
+
elif param_probe_aborted:
|
|
1168
|
+
# ⛔ THIS BRANCH MUST PRECEDE params_unreachable. `unreachable` is
|
|
1169
|
+
# defined as "every OBSERVED poison returned output identical to the
|
|
1170
|
+
# clean baseline". An aborted probe observed NOTHING, so filing it there
|
|
1171
|
+
# claims a measurement that never happened.
|
|
1172
|
+
# Found by 6E 2026-09-04 and reproduced with controls: an aborted
|
|
1173
|
+
# parameter and a genuinely-unreachable one emitted BYTE-IDENTICAL
|
|
1174
|
+
# buckets, separated only by the verdict word -- and report.py renders
|
|
1175
|
+
# the buckets without recomputing them, so the two were indistinguishable
|
|
1176
|
+
# downstream. Both kill paths land here: the clean baseline being killed
|
|
1177
|
+
# and the poisoned probe being killed. Either way the honest answer is
|
|
1178
|
+
# "we stopped early", not "we measured and it did not matter".
|
|
1179
|
+
scope["params_aborted"] += 1
|
|
1180
|
+
elif param_had_valid_baseline:
|
|
1181
|
+
scope["params_unreachable"] += 1
|
|
1182
|
+
else:
|
|
1183
|
+
scope["params_unexercised"] += 1
|
|
1184
|
+
|
|
1185
|
+
scope["functions_scanned"] = tested
|
|
1186
|
+
if not tested:
|
|
1187
|
+
return "PASS", "no scalar parameters found to test", [], scope
|
|
1188
|
+
|
|
1189
|
+
detail = nan_objections + nan_weak + inf_notes + nan_unreachable + nan_aborted
|
|
1190
|
+
if nan_objections:
|
|
1191
|
+
return "FAIL", f"{len(nan_objections)} scalar NaN defect(s) found", detail, scope
|
|
1192
|
+
if not exercised:
|
|
1193
|
+
# Every scalar parameter we found was unreachable; the lens could not
|
|
1194
|
+
# actually exercise the code, so it must report INCONCLUSIVE.
|
|
1195
|
+
# COUNT PARAMETERS, NOT DETAIL LINES. The lists get one entry per poison
|
|
1196
|
+
# value per parameter, so len() reported "3 parameter(s)" for a
|
|
1197
|
+
# single-parameter function. The scope counts were already correct; the
|
|
1198
|
+
# headline just was not using them. Name every non-zero bucket: "aborted"
|
|
1199
|
+
# and "unreachable" are different claims and must not share a word.
|
|
1200
|
+
_parts = []
|
|
1201
|
+
if scope["params_aborted"]:
|
|
1202
|
+
_parts.append(
|
|
1203
|
+
f"{scope['params_aborted']} parameter(s) aborted "
|
|
1204
|
+
f"(resource limit, nothing observed)"
|
|
1205
|
+
)
|
|
1206
|
+
if scope["params_unreachable"]:
|
|
1207
|
+
_parts.append(f"{scope['params_unreachable']} parameter(s) unreachable")
|
|
1208
|
+
if scope["params_unexercised"]:
|
|
1209
|
+
_parts.append(
|
|
1210
|
+
f"{scope['params_unexercised']} parameter(s) unexercised (no valid baseline)"
|
|
1211
|
+
)
|
|
1212
|
+
return "INCONCLUSIVE", "; ".join(_parts) or "nothing could be measured", detail, scope
|
|
1213
|
+
if nan_weak:
|
|
1214
|
+
return "PASS", f"all NaN inputs handled; {len(nan_weak)} tolerance observation(s) recorded", detail, scope
|
|
1215
|
+
if inf_notes:
|
|
1216
|
+
return "PASS", f"all NaN inputs handled; {len(inf_notes)} Inf observation(s) recorded", detail, scope
|
|
1217
|
+
if nan_unreachable:
|
|
1218
|
+
return "PASS", f"all NaN inputs handled; {scope['params_unreachable']} parameter(s) recorded as unreachable", detail, scope
|
|
1219
|
+
return "PASS", "all scalar NaN/Inf inputs handled or propagated cleanly", detail, scope
|
|
1220
|
+
|
|
1221
|
+
|
|
1222
|
+
def main(argv: List[str]) -> int:
|
|
1223
|
+
ap = argparse.ArgumentParser(description="Guard lens (NaN/Inf finiteness)")
|
|
1224
|
+
ap.add_argument("--fixture", required=True, help="Python fixture file to analyse")
|
|
1225
|
+
args = ap.parse_args(argv[1:])
|
|
1226
|
+
|
|
1227
|
+
fixture = Path(args.fixture).resolve()
|
|
1228
|
+
if not fixture.exists():
|
|
1229
|
+
print("verdict:INCONCLUSIVE fixture not found")
|
|
1230
|
+
print("detail: path does not exist")
|
|
1231
|
+
return 0
|
|
1232
|
+
|
|
1233
|
+
verdict, reason, detail, scope = evaluate_fixture(fixture)
|
|
1234
|
+
print(f"verdict:{verdict} {reason}")
|
|
1235
|
+
if detail:
|
|
1236
|
+
for line in detail[:50]:
|
|
1237
|
+
print(f"detail:{line}")
|
|
1238
|
+
print(f"scope:params_total={scope['params_total']}")
|
|
1239
|
+
print(f"scope:params_judged={scope['params_judged']}")
|
|
1240
|
+
print(f"scope:params_unreachable={scope['params_unreachable']}")
|
|
1241
|
+
print(f"scope:params_unexercised={scope['params_unexercised']}")
|
|
1242
|
+
print(f"scope:params_aborted={scope['params_aborted']}")
|
|
1243
|
+
print(f"scope:functions_total={scope['functions_total']}")
|
|
1244
|
+
print(f"scope:functions_scanned={scope['functions_scanned']}")
|
|
1245
|
+
print(f"scope:mode={scope['mode']}")
|
|
1246
|
+
return 0
|
|
1247
|
+
|
|
1248
|
+
|
|
1249
|
+
if __name__ == "__main__":
|
|
1250
|
+
raise SystemExit(main(sys.argv))
|