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,365 @@
|
|
|
1
|
+
"""The behaviour lens (design v1.4.5 §4a.3 lens 2, build step 6a): same inputs -> same outputs.
|
|
2
|
+
|
|
3
|
+
Pipeline for a query file against a pool, each stage a gate that filters and never votes:
|
|
4
|
+
1. signature (§3a, text only) -> the query's and each member's public functions;
|
|
5
|
+
2. environment fit (Q11): every import must resolve INSIDE the box (facts measured there);
|
|
6
|
+
3. contract: the candidate accepts the query's required arguments, kinds agree where annotated;
|
|
7
|
+
4. behaviour, in the isolation box: query at /src, candidates at /ref (read-only, 6E pre-note),
|
|
8
|
+
each pair in a FRESH interpreter; inputs = the ported executor's baseline + attack fixtures
|
|
9
|
+
(engines/executor_port.py) + seeded variants of the baseline. Score = agreeing inputs /
|
|
10
|
+
inputs where at least one side returned (both raising says nothing about meaning).
|
|
11
|
+
|
|
12
|
+
Rule 2 (§4a.4) runs before the lens is trusted: see ``rule2()``.
|
|
13
|
+
Known limit, stated: a candidate runs in the same interpreter as its pair's harness, so it can
|
|
14
|
+
forge ITS OWN pair's result line; it cannot touch any other pair (fresh process per pair).
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import hashlib
|
|
19
|
+
import json
|
|
20
|
+
import tempfile
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
from .. import config
|
|
25
|
+
from . import box, contract, envfit, shape_lens, signature, slots
|
|
26
|
+
from .outcomes import Outcome, blind, clean, found
|
|
27
|
+
|
|
28
|
+
NAME = "behaviour"
|
|
29
|
+
TAU = 0.9 # a hit agrees on at least 90% of the inputs where someone answered
|
|
30
|
+
MIN_CONSIDERED = 4 # fewer answered inputs than this: no score for the pair
|
|
31
|
+
MAX_PAIRS = 80 # per query; more are reported, never silently dropped
|
|
32
|
+
SEED = 20261111
|
|
33
|
+
PORT = Path(__file__).parent / "engines" / "executor_port.py"
|
|
34
|
+
|
|
35
|
+
PAIR = r'''
|
|
36
|
+
import contextlib, copy, importlib.util, inspect, io, json, math, random, signal, sys
|
|
37
|
+
sys.path.insert(0, "/src")
|
|
38
|
+
import executor_port as X
|
|
39
|
+
WORDS = ["alpha", "beta", "gamma", "delta", "fox", "data", "x", "lorem", "zeta", "omega"]
|
|
40
|
+
class TO(Exception): pass
|
|
41
|
+
def _h(*a): raise TO()
|
|
42
|
+
signal.signal(signal.SIGALRM, _h)
|
|
43
|
+
def load(path, name):
|
|
44
|
+
spec = importlib.util.spec_from_file_location(name, path); m = importlib.util.module_from_spec(spec)
|
|
45
|
+
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
|
46
|
+
signal.alarm(5); spec.loader.exec_module(m); signal.alarm(0)
|
|
47
|
+
return m
|
|
48
|
+
def call(fn, args):
|
|
49
|
+
try:
|
|
50
|
+
signal.alarm(3)
|
|
51
|
+
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
|
52
|
+
out = fn(*copy.deepcopy(args))
|
|
53
|
+
signal.alarm(0); return ("ok", out)
|
|
54
|
+
except BaseException as e:
|
|
55
|
+
signal.alarm(0); return ("raise", type(e).__name__)
|
|
56
|
+
def eq(a, b, d=0):
|
|
57
|
+
if d > 50: return False
|
|
58
|
+
if isinstance(a, bool) or isinstance(b, bool): return type(a) is type(b) and a == b
|
|
59
|
+
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
|
|
60
|
+
if isinstance(a, float) and isinstance(b, float) and math.isnan(a) and math.isnan(b): return True
|
|
61
|
+
try: return math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-12)
|
|
62
|
+
except Exception: return False
|
|
63
|
+
if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)):
|
|
64
|
+
return len(a) == len(b) and all(eq(x, y, d + 1) for x, y in zip(a, b))
|
|
65
|
+
if isinstance(a, dict) and isinstance(b, dict):
|
|
66
|
+
return a.keys() == b.keys() and all(eq(a[k], b[k], d + 1) for k in a)
|
|
67
|
+
try: return bool(a == b)
|
|
68
|
+
except BaseException: return False
|
|
69
|
+
def variant(v, rnd):
|
|
70
|
+
if isinstance(v, bool): return rnd.random() < 0.5
|
|
71
|
+
if isinstance(v, int): return rnd.randint(-3, 20)
|
|
72
|
+
if isinstance(v, float): return round(rnd.uniform(-10, 10), 3)
|
|
73
|
+
if isinstance(v, str): return " ".join(rnd.choice(WORDS) for _ in range(rnd.randint(1, 5)))
|
|
74
|
+
if isinstance(v, list):
|
|
75
|
+
if v and isinstance(v[0], list): return [[round(rnd.uniform(-5, 5), 3) for _ in v[0]] for _ in range(rnd.randint(1, 4))]
|
|
76
|
+
if v and isinstance(v[0], int) and not isinstance(v[0], bool): return [rnd.randint(-5, 9) for _ in range(rnd.randint(1, 7))]
|
|
77
|
+
return [round(rnd.uniform(-10, 10), 3) for _ in range(rnd.randint(1, 7))]
|
|
78
|
+
if isinstance(v, tuple): return tuple(variant(x, rnd) for x in v)
|
|
79
|
+
if isinstance(v, dict): return {k: variant(x, rnd) for k, x in v.items()}
|
|
80
|
+
return v
|
|
81
|
+
def main():
|
|
82
|
+
qpath, qfn, cpath, cfn, seed = sys.argv[1:6]
|
|
83
|
+
out = {}
|
|
84
|
+
try:
|
|
85
|
+
q = getattr(load(qpath, "q_mod"), qfn); c = getattr(load(cpath, "c_mod"), cfn)
|
|
86
|
+
except BaseException as e:
|
|
87
|
+
out["error"] = "load: " + type(e).__name__; print("BEHAV " + json.dumps(out)); return
|
|
88
|
+
params = [p for p in inspect.signature(q).parameters.values()
|
|
89
|
+
if p.kind in (p.POSITIONAL_OR_KEYWORD, p.POSITIONAL_ONLY) and p.default is p.empty]
|
|
90
|
+
base, ok = X.build_baseline(params)
|
|
91
|
+
if not ok:
|
|
92
|
+
out["error"] = "no-baseline"; print("BEHAV " + json.dumps(out)); return
|
|
93
|
+
inputs = [base] + [a for _r, a, _e, _i in X.attack_fixtures(params, base)]
|
|
94
|
+
rnd = random.Random(int(seed))
|
|
95
|
+
inputs += [[variant(v, rnd) for v in base] for _ in range(8)]
|
|
96
|
+
agree = considered = 0
|
|
97
|
+
for args in inputs:
|
|
98
|
+
a, b = call(q, args), call(c, args)
|
|
99
|
+
if a[0] == "raise" and b[0] == "raise":
|
|
100
|
+
continue
|
|
101
|
+
considered += 1
|
|
102
|
+
agree += a[0] == b[0] == "ok" and eq(a[1], b[1])
|
|
103
|
+
out.update(inputs=len(inputs), considered=considered, agree=agree)
|
|
104
|
+
print("BEHAV " + json.dumps(out))
|
|
105
|
+
main()
|
|
106
|
+
'''
|
|
107
|
+
|
|
108
|
+
DRIVER = r'''
|
|
109
|
+
import importlib.util, json, subprocess, sys
|
|
110
|
+
job = json.load(open("/src/job.json"))
|
|
111
|
+
if job["mode"] == "facts":
|
|
112
|
+
print("MOD " + json.dumps({n: importlib.util.find_spec(n) is not None for n in job["modules"]}))
|
|
113
|
+
sys.exit(0)
|
|
114
|
+
for p in job["pairs"]:
|
|
115
|
+
try:
|
|
116
|
+
r = subprocess.run([sys.executable, "/src/pair.py", p["q"], p["qfn"], p["c"], p["cfn"], str(job["seed"])],
|
|
117
|
+
capture_output=True, text=True, timeout=30)
|
|
118
|
+
line = next((l for l in r.stdout.splitlines() if l.startswith("BEHAV ")), None)
|
|
119
|
+
res = json.loads(line[6:]) if line else {"error": "no-result, exit %s" % r.returncode}
|
|
120
|
+
except subprocess.TimeoutExpired:
|
|
121
|
+
res = {"error": "timeout"}
|
|
122
|
+
print("PAIR " + json.dumps({"key": p["key"], **res}), flush=True)
|
|
123
|
+
'''
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@dataclass
|
|
127
|
+
class BHit:
|
|
128
|
+
score: float
|
|
129
|
+
item_id: str
|
|
130
|
+
pool: str
|
|
131
|
+
trust: str
|
|
132
|
+
kind: str
|
|
133
|
+
query_fn: str
|
|
134
|
+
cand_fn: str
|
|
135
|
+
agree: int
|
|
136
|
+
considered: int
|
|
137
|
+
slot: str = "top" # 8b s4: slot 10 = explore, drawn from pairs already scored
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass
|
|
141
|
+
class BehaviourResult:
|
|
142
|
+
outcome: Outcome
|
|
143
|
+
hits: list = field(default_factory=list)
|
|
144
|
+
scores: dict = field(default_factory=dict) # item_id -> best pair score (every compared item)
|
|
145
|
+
gates: dict = field(default_factory=dict)
|
|
146
|
+
looked_at: int = 0
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _file(item_id: str) -> str:
|
|
150
|
+
return "m_" + hashlib.sha1(item_id.encode()).hexdigest()[:16] + ".py"
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _box_job(job: dict, query: str | None, members: dict[str, str], timeout: float):
|
|
154
|
+
root = config.scratch_dir() / "behaviour"
|
|
155
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
156
|
+
with tempfile.TemporaryDirectory(dir=root) as d:
|
|
157
|
+
src, ref = Path(d) / "src", Path(d) / "ref"
|
|
158
|
+
src.mkdir(); ref.mkdir()
|
|
159
|
+
(src / "pair.py").write_text(PAIR)
|
|
160
|
+
(src / "driver.py").write_text(DRIVER)
|
|
161
|
+
(src / "executor_port.py").write_bytes(PORT.read_bytes())
|
|
162
|
+
(src / "job.json").write_text(json.dumps(job))
|
|
163
|
+
if query is not None:
|
|
164
|
+
(src / "query.py").write_text(query)
|
|
165
|
+
for name, body in members.items():
|
|
166
|
+
(ref / name).write_text(body)
|
|
167
|
+
return box.run(src, ["python3", "/src/driver.py"], timeout=timeout, ref=ref)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def env_facts(modules: set[str]) -> tuple[dict | None, Outcome | None]:
|
|
171
|
+
if not modules:
|
|
172
|
+
return {}, None
|
|
173
|
+
r = _box_job({"mode": "facts", "modules": sorted(modules)}, None, {}, 60)
|
|
174
|
+
if r.outcome.kind != "FOUND":
|
|
175
|
+
return None, r.outcome
|
|
176
|
+
line = next((l for l in r.stdout.splitlines() if l.startswith("MOD ")), None)
|
|
177
|
+
if line is None:
|
|
178
|
+
return None, blind(f"environment-fit: no facts from the box (exit {r.returncode})")
|
|
179
|
+
return json.loads(line[4:]), None
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def rank(query: str, members: list, *, pool: str, trust: str) -> BehaviourResult:
|
|
183
|
+
try:
|
|
184
|
+
qsigs = signature.extract(query)
|
|
185
|
+
q_imp = envfit.imports(query)
|
|
186
|
+
except SyntaxError:
|
|
187
|
+
return BehaviourResult(blind("query: not parseable as Python"))
|
|
188
|
+
if not qsigs:
|
|
189
|
+
return BehaviourResult(blind("query: no public top-level function with arguments"))
|
|
190
|
+
if envfit.runs_at_import(query):
|
|
191
|
+
return BehaviourResult(blind(f"query: runs code at import ({envfit.runs_at_import(query)}); "
|
|
192
|
+
"behaviour compares functions, not scripts"))
|
|
193
|
+
parsed, gates = [], {"unparseable": 0, "no-function": 0, "runs-at-import": 0, "env-fit": 0, "contract": 0}
|
|
194
|
+
for m in members:
|
|
195
|
+
try:
|
|
196
|
+
sigs, imp = signature.extract(m["body"]), envfit.imports(m["body"])
|
|
197
|
+
except SyntaxError:
|
|
198
|
+
gates["unparseable"] += 1; continue
|
|
199
|
+
if not sigs:
|
|
200
|
+
if signature.async_only(m["body"]): # 6E B6-3: not supported yet, not "no function"
|
|
201
|
+
gates["async-skipped"] = gates.get("async-skipped", 0) + 1
|
|
202
|
+
else:
|
|
203
|
+
gates["no-function"] += 1
|
|
204
|
+
continue
|
|
205
|
+
if envfit.runs_at_import(m["body"]):
|
|
206
|
+
gates["runs-at-import"] += 1; continue
|
|
207
|
+
parsed.append((m, sigs, imp))
|
|
208
|
+
facts, bad = env_facts(q_imp[0].union(*(imp[0] for _m, _s, imp in parsed)) if parsed else q_imp[0])
|
|
209
|
+
if bad is not None:
|
|
210
|
+
return BehaviourResult(bad, gates=gates)
|
|
211
|
+
ok, why = envfit.fits(q_imp, facts)
|
|
212
|
+
if not ok:
|
|
213
|
+
return BehaviourResult(blind(f"environment-fit: the query does not run in the box ({why})"), gates=gates)
|
|
214
|
+
pairs, files = [], {}
|
|
215
|
+
for m, sigs, imp in parsed:
|
|
216
|
+
if not envfit.fits(imp, facts)[0]:
|
|
217
|
+
gates["env-fit"] += 1; continue
|
|
218
|
+
mp = [(q, c) for q in qsigs for c in sigs if contract.fits(q, c)[0]]
|
|
219
|
+
if not mp:
|
|
220
|
+
gates["contract"] += 1; continue
|
|
221
|
+
files[m["item_id"]] = _file(m["item_id"])
|
|
222
|
+
for q, c in mp:
|
|
223
|
+
pairs.append((m["item_id"], q["entry"], c["entry"], m))
|
|
224
|
+
pairs.sort(key=lambda p: (p[0], p[1], p[2]))
|
|
225
|
+
gates["pairs"] = len(pairs)
|
|
226
|
+
if len(pairs) > MAX_PAIRS:
|
|
227
|
+
gates["over-cap"] = len(pairs) - MAX_PAIRS
|
|
228
|
+
pairs = pairs[:MAX_PAIRS]
|
|
229
|
+
if not pairs:
|
|
230
|
+
return BehaviourResult(clean(f"no member passed the gates ({_gate_text(gates)})"), gates=gates,
|
|
231
|
+
looked_at=len(members))
|
|
232
|
+
job = {"mode": "pairs", "seed": SEED, "pairs": [
|
|
233
|
+
{"key": i, "q": "/src/query.py", "qfn": qf, "c": "/ref/" + files[iid], "cfn": cf}
|
|
234
|
+
for i, (iid, qf, cf, _m) in enumerate(pairs)]}
|
|
235
|
+
bodies = {files[iid]: m["body"] for iid, _q, _c, m in pairs}
|
|
236
|
+
r = _box_job(job, query, bodies, 30 * len(pairs) + 60)
|
|
237
|
+
if r.outcome.kind != "FOUND":
|
|
238
|
+
return BehaviourResult(r.outcome, gates=gates, looked_at=len(members))
|
|
239
|
+
results = {}
|
|
240
|
+
for line in r.stdout.splitlines():
|
|
241
|
+
if line.startswith("PAIR "):
|
|
242
|
+
d = json.loads(line[5:]); results[d["key"]] = d
|
|
243
|
+
best, errors, kinds, no_answer = {}, 0, {}, 0
|
|
244
|
+
for i, (iid, qf, cf, m) in enumerate(pairs):
|
|
245
|
+
d = results.get(i)
|
|
246
|
+
if d is None or "error" in d:
|
|
247
|
+
errors += 1
|
|
248
|
+
k = (d or {}).get("error", "no-result")
|
|
249
|
+
kinds[k] = kinds.get(k, 0) + 1
|
|
250
|
+
continue
|
|
251
|
+
if d["considered"] < MIN_CONSIDERED: # 6E B6-1: "could not compare" is not "unrelated"
|
|
252
|
+
no_answer += 1
|
|
253
|
+
continue
|
|
254
|
+
s = d["agree"] / d["considered"]
|
|
255
|
+
if iid not in best or s > best[iid].score:
|
|
256
|
+
best[iid] = BHit(round(s, 3), iid, pool, trust, m.get("kind", "?"), qf, cf, d["agree"], d["considered"])
|
|
257
|
+
gates["pair-errors"] = errors
|
|
258
|
+
gates["no-answer"] = no_answer
|
|
259
|
+
if kinds:
|
|
260
|
+
gates["error-kinds"] = "; ".join(f"{k} {v}" for k, v in sorted(kinds.items(), key=lambda x: -x[1])[:4])
|
|
261
|
+
ranked = sorted(best.values(), key=lambda h: (-h.score, h.item_id))
|
|
262
|
+
top = [h for h in ranked if h.score >= TAU][:slots.TOP] # only agreeing pairs are hits
|
|
263
|
+
explore = slots.pick([h for h in ranked if h not in top], lens=NAME, query=query) # any scored pair
|
|
264
|
+
hits = top + ([explore] if explore is not None else [])
|
|
265
|
+
scores = {iid: h.score for iid, h in best.items()}
|
|
266
|
+
text = f"{len(pairs)} pair(s) run, {_gate_text(gates)}"
|
|
267
|
+
unlooked = errors + no_answer
|
|
268
|
+
if unlooked == len(pairs):
|
|
269
|
+
return BehaviourResult(blind(f"no pair could be compared ({text})"), [], scores, gates, len(members))
|
|
270
|
+
if unlooked > 0.1 * len(pairs): # P1: more than 10% of the run could not look -> the run is flagged
|
|
271
|
+
text = f"FLAGGED: {unlooked} of {len(pairs)} pairs BLIND (over 10%); " + text
|
|
272
|
+
# judged on the TOP hits only: the explore pair is a counterfactual, never a find (8b s4)
|
|
273
|
+
out = found(f"{len(top)} hit(s) at agreement >= {TAU}; {text}") if top else clean(f"none at agreement >= {TAU}; {text}")
|
|
274
|
+
return BehaviourResult(out, hits, scores, gates, len(members))
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _gate_text(g: dict) -> str:
|
|
278
|
+
return ", ".join(f"{k} {v}" for k, v in g.items() if v)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
# ---------------- Rule 2 (§4a.4): the known-case set, run before the lens is trusted ----------------
|
|
282
|
+
SQ_LOOP = """def sum_of_squares(xs):
|
|
283
|
+
total = 0
|
|
284
|
+
for x in xs:
|
|
285
|
+
total += x * x
|
|
286
|
+
return total
|
|
287
|
+
"""
|
|
288
|
+
SQ_GEN = """def energy(signal):
|
|
289
|
+
return sum(s * s for s in signal)
|
|
290
|
+
"""
|
|
291
|
+
SUM_FORK = """def sum_of_squares(xs):
|
|
292
|
+
total = 0
|
|
293
|
+
for x in xs:
|
|
294
|
+
total += x
|
|
295
|
+
return total
|
|
296
|
+
"""
|
|
297
|
+
MEAN = """def mean(xs):
|
|
298
|
+
return sum(xs) / len(xs)
|
|
299
|
+
"""
|
|
300
|
+
KW_TRAP = """def squares_total(nums: list) -> float:
|
|
301
|
+
# squares total of nums: counts the nums, acc of squares not computed here
|
|
302
|
+
acc = 0.0
|
|
303
|
+
for n in nums:
|
|
304
|
+
acc = acc + 1
|
|
305
|
+
return acc
|
|
306
|
+
"""
|
|
307
|
+
POOL = {"sq_loop": SQ_LOOP, "sq_gen": SQ_GEN, "sum_fork": SUM_FORK, "mean": MEAN, "kw_trap": KW_TRAP}
|
|
308
|
+
Q_SQ = """def squares_total(nums: list) -> float:
|
|
309
|
+
acc = 0.0
|
|
310
|
+
for n in nums:
|
|
311
|
+
acc = acc + n ** 2
|
|
312
|
+
return acc
|
|
313
|
+
"""
|
|
314
|
+
Q_NULL = """def word_count(text: str) -> int:
|
|
315
|
+
return len(text.split())
|
|
316
|
+
"""
|
|
317
|
+
RELATED = {"sq_loop", "sq_gen"}
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _pool():
|
|
321
|
+
return [{"item_id": f"rule2:{k}", "body": v, "lang": "python", "kind": "rule2"} for k, v in POOL.items()]
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def rule2(rank_fn=None) -> list[str]:
|
|
325
|
+
"""Each case says WHY it exists. Returns the failures; empty means the lens may be switched on."""
|
|
326
|
+
rank_fn = rank_fn or rank
|
|
327
|
+
fails = []
|
|
328
|
+
# 8b s4 review F1: the explore pair is a counterfactual, never a returned hit
|
|
329
|
+
def ids(r): return {h.item_id.split(":", 1)[1] for h in r.hits if getattr(h, "slot", "top") == "top"}
|
|
330
|
+
def score(r, k): return r.scores.get(f"rule2:{k}", 0.0)
|
|
331
|
+
r_ctl = rank_fn(SQ_LOOP, _pool(), pool="rule2", trust="fixture")
|
|
332
|
+
if r_ctl.outcome.kind != "FOUND" or score(r_ctl, "sq_loop") != 1.0:
|
|
333
|
+
fails.append(f"control: the query's own copy must agree 1.0 (got {score(r_ctl, 'sq_loop')}, {r_ctl.outcome.label()})")
|
|
334
|
+
# same look, different meaning: shape matches the fork, behaviour must not
|
|
335
|
+
if shape_lens.score(SQ_LOOP, SUM_FORK) < shape_lens.TAU:
|
|
336
|
+
fails.append("case invalid: shape no longer matches the fork, so it tests nothing")
|
|
337
|
+
if "sum_fork" in ids(r_ctl):
|
|
338
|
+
fails.append(f"same-look/different-meaning: the buggy fork was returned (score {score(r_ctl, 'sum_fork')})")
|
|
339
|
+
r = rank_fn(Q_SQ, _pool(), pool="rule2", trust="fixture")
|
|
340
|
+
# same meaning, different look; only behaviour gets it (shape and keyword miss)
|
|
341
|
+
if shape_lens.score(Q_SQ, SQ_GEN) >= shape_lens.TAU:
|
|
342
|
+
fails.append("case invalid: shape already matches sq_gen, so behaviour is not the only lens")
|
|
343
|
+
if "sq_gen" not in ids(r):
|
|
344
|
+
fails.append(f"same-meaning/different-look: sq_gen missed (score {score(r, 'sq_gen')}, {r.outcome.label()})")
|
|
345
|
+
if "sq_loop" not in ids(r):
|
|
346
|
+
fails.append(f"same-meaning: sq_loop missed (score {score(r, 'sq_loop')})")
|
|
347
|
+
if ids(r) - RELATED:
|
|
348
|
+
fails.append(f"unrelated returned: {sorted(ids(r) - RELATED)} (keyword trap / mean / fork)")
|
|
349
|
+
# keyword baseline: behaviour must separate related from unrelated better than keywords do
|
|
350
|
+
rel = [score(r, k) for k in RELATED]
|
|
351
|
+
unrel = [score(r, k) for k in POOL if k not in RELATED]
|
|
352
|
+
kw = {k: shape_lens.keyword_score(Q_SQ, v) for k, v in POOL.items()}
|
|
353
|
+
sep_b = min(rel) - max(unrel)
|
|
354
|
+
sep_k = min(kw[k] for k in RELATED) - max(kw[k] for k in POOL if k not in RELATED)
|
|
355
|
+
# 6E B6-2: the case must be able to fail: the keyword baseline has to MIS-rank (a trap above a
|
|
356
|
+
# true match), otherwise "beaten" is undefined
|
|
357
|
+
if not sep_k < 0:
|
|
358
|
+
fails.append(f"case invalid: keyword baseline separation {sep_k:.2f} is not negative, so it ranks nothing wrongly")
|
|
359
|
+
if not sep_b > sep_k:
|
|
360
|
+
fails.append(f"keyword baseline not beaten: behaviour separation {sep_b:.2f} vs keyword {sep_k:.2f}")
|
|
361
|
+
# null: a query with no related member returns nothing
|
|
362
|
+
r0 = rank_fn(Q_NULL, _pool(), pool="rule2", trust="fixture")
|
|
363
|
+
if ids(r0):
|
|
364
|
+
fails.append(f"null: returned {sorted(ids(r0))}")
|
|
365
|
+
return fails
|