python2rust 0.1.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.
- python2rust/__init__.py +8 -0
- python2rust/__main__.py +5 -0
- python2rust/_core.py +44 -0
- python2rust/agent/__init__.py +0 -0
- python2rust/agent/agents.py +333 -0
- python2rust/agent/apply.py +516 -0
- python2rust/agent/finish.py +295 -0
- python2rust/agent/fixers.py +229 -0
- python2rust/agent/loop.py +441 -0
- python2rust/agent/patches.py +1165 -0
- python2rust/agent/port.py +579 -0
- python2rust/agent/prompts/judge_v2.md +96 -0
- python2rust/agent/review.py +34 -0
- python2rust/agent/rustlex.py +232 -0
- python2rust/cli/__init__.py +0 -0
- python2rust/cli/doctor.py +62 -0
- python2rust/cli/inputs.py +105 -0
- python2rust/cli/main.py +1162 -0
- python2rust/cli/ops.py +642 -0
- python2rust/cli/workflow.py +178 -0
- python2rust/core/__init__.py +38 -0
- python2rust/core/config.py +263 -0
- python2rust/core/constructs.py +124 -0
- python2rust/core/diagnostics.py +280 -0
- python2rust/core/emit/__init__.py +5 -0
- python2rust/core/emit/crates.py +51 -0
- python2rust/core/emit/render.py +561 -0
- python2rust/core/emit/schema.py +168 -0
- python2rust/core/emit/translate.py +304 -0
- python2rust/core/frontend/__init__.py +1 -0
- python2rust/core/frontend/module.py +896 -0
- python2rust/core/frontend/names.py +129 -0
- python2rust/core/frontend/project.py +277 -0
- python2rust/core/frontend/project_imports.py +173 -0
- python2rust/core/frontend/symbols.py +132 -0
- python2rust/core/frontend/walrus.py +59 -0
- python2rust/core/ir/__init__.py +1 -0
- python2rust/core/ir/nodes.py +675 -0
- python2rust/core/ir/rtypes.py +122 -0
- python2rust/core/ir/types.py +326 -0
- python2rust/core/lower/__init__.py +1 -0
- python2rust/core/lower/calls.py +1125 -0
- python2rust/core/lower/context.py +223 -0
- python2rust/core/lower/exceptions.py +317 -0
- python2rust/core/lower/exprs.py +845 -0
- python2rust/core/lower/fstrings.py +141 -0
- python2rust/core/lower/funcs.py +276 -0
- python2rust/core/lower/lowerer.py +366 -0
- python2rust/core/lower/modelcalls.py +195 -0
- python2rust/core/lower/models.py +645 -0
- python2rust/core/lower/stmts.py +722 -0
- python2rust/core/lower/testing.py +601 -0
- python2rust/core/lower/validation.py +253 -0
- python2rust/core/passes/__init__.py +1 -0
- python2rust/core/passes/aliasing.py +311 -0
- python2rust/core/passes/analysis.py +207 -0
- python2rust/core/passes/devirt.py +329 -0
- python2rust/core/passes/ownership.py +259 -0
- python2rust/core/passes/raises.py +275 -0
- python2rust/core/rt_lib.rs +2071 -0
- python2rust/data/README.md +81 -0
- python2rust/data/py2many_builtins.toml +4744 -0
- python2rust/errors.py +28 -0
- python2rust/py.typed +0 -0
- python2rust/report/__init__.py +0 -0
- python2rust/report/constructs.py +31 -0
- python2rust/report/contract.py +688 -0
- python2rust/report/corpus.py +323 -0
- python2rust/report/explain.py +168 -0
- python2rust/report/schemas.py +914 -0
- python2rust/server/__init__.py +0 -0
- python2rust/server/mcp_server.py +289 -0
- python2rust/server/mcp_workflow.py +100 -0
- python2rust/skill/SKILL.md +214 -0
- python2rust/verify/__init__.py +0 -0
- python2rust/verify/check.py +1135 -0
- python2rust/verify/equiv/__init__.py +1264 -0
- python2rust/verify/equiv/compare.py +455 -0
- python2rust/verify/equiv/harness.py +505 -0
- python2rust/verify/equiv/judge.py +358 -0
- python2rust/verify/equiv/procs.py +255 -0
- python2rust/verify/equiv/runner.py +248 -0
- python2rust/verify/equiv/types.py +543 -0
- python2rust/verify/keystore.py +76 -0
- python2rust/verify/ladder.py +396 -0
- python2rust/verify/sandbox.py +370 -0
- python2rust/verify/testrun.py +280 -0
- python2rust/workflow/__init__.py +0 -0
- python2rust/workflow/brief.py +312 -0
- python2rust/workflow/interview.py +366 -0
- python2rust/workflow/layout.py +103 -0
- python2rust/workflow/planner.py +409 -0
- python2rust/workflow/project.py +134 -0
- python2rust/workflow/schemas.py +265 -0
- python2rust/workflow/state.py +392 -0
- python2rust/workflow/staticscan.py +209 -0
- python2rust-0.1.0.dist-info/METADATA +395 -0
- python2rust-0.1.0.dist-info/RECORD +102 -0
- python2rust-0.1.0.dist-info/WHEEL +4 -0
- python2rust-0.1.0.dist-info/entry_points.txt +4 -0
- python2rust-0.1.0.dist-info/licenses/LICENSE +21 -0
- python2rust-0.1.0.dist-info/licenses/NOTICE +65 -0
|
@@ -0,0 +1,1264 @@
|
|
|
1
|
+
"""`verify --level equiv`: does the compiled Rust give the same output as the original Python?
|
|
2
|
+
|
|
3
|
+
The top rung of the ladder (parse < fmt < check < clippy < test < equiv). For every function whose
|
|
4
|
+
signature is JSON-able and has no I/O, the original and the Rust run on the same inputs (doctest
|
|
5
|
+
examples, `assert f(...) == ...` cases of sibling test files, generated edge and random values) and
|
|
6
|
+
the outputs are compared (see `compare`). Pairs that only differ in presentation go to an
|
|
7
|
+
optional judge (see `judge`); without a judge they are `needs-judgement`.
|
|
8
|
+
|
|
9
|
+
Safety: this is the only place where user Python runs, and only through `runner` in a child
|
|
10
|
+
process, only with `--run-python`. This module itself never imports, evaluates or executes the
|
|
11
|
+
user's code: it reads source with `ast`, and takes inputs from `ast.literal_eval` of call arguments.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import ast
|
|
17
|
+
import contextlib
|
|
18
|
+
import doctest
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import random
|
|
22
|
+
import re
|
|
23
|
+
import shutil
|
|
24
|
+
from collections import Counter
|
|
25
|
+
from dataclasses import dataclass, field, replace
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
from python2rust.agent.agents import Backend
|
|
30
|
+
from python2rust.verify.check import CheckModule, crate_module_name
|
|
31
|
+
from python2rust.verify.equiv.compare import Profile, compare_case, drift_fails, drift_reason
|
|
32
|
+
from python2rust.verify.equiv.harness import (
|
|
33
|
+
HarnessPlan,
|
|
34
|
+
PlanFn,
|
|
35
|
+
PlanModel,
|
|
36
|
+
RustSig,
|
|
37
|
+
build_harness,
|
|
38
|
+
find_rust_fn,
|
|
39
|
+
make_workdir,
|
|
40
|
+
rust_models,
|
|
41
|
+
)
|
|
42
|
+
from python2rust.verify.equiv.judge import PROMPT_VERSION, Judge, JudgeCase, default_cache_dir
|
|
43
|
+
from python2rust.verify.equiv.procs import PythonRunner, RustRunner
|
|
44
|
+
from python2rust.verify.equiv.types import (
|
|
45
|
+
BOUNDARY_INTS,
|
|
46
|
+
Ty,
|
|
47
|
+
Unsupported,
|
|
48
|
+
compat,
|
|
49
|
+
finite_only,
|
|
50
|
+
fits,
|
|
51
|
+
gen_edges,
|
|
52
|
+
gen_random,
|
|
53
|
+
has_model,
|
|
54
|
+
hypothesis_available,
|
|
55
|
+
hypothesis_strategy,
|
|
56
|
+
parse_ann,
|
|
57
|
+
shrink,
|
|
58
|
+
to_wire,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
STATUSES = ("passed", "passed-judged", "failed", "needs-judgement", "not-applicable")
|
|
62
|
+
_IO_ROOTS = {
|
|
63
|
+
"os",
|
|
64
|
+
"subprocess",
|
|
65
|
+
"socket",
|
|
66
|
+
"requests",
|
|
67
|
+
"httpx",
|
|
68
|
+
"urllib",
|
|
69
|
+
"shutil",
|
|
70
|
+
"pathlib",
|
|
71
|
+
"sqlite3",
|
|
72
|
+
"random",
|
|
73
|
+
"time",
|
|
74
|
+
"uuid",
|
|
75
|
+
"secrets",
|
|
76
|
+
"threading",
|
|
77
|
+
"asyncio",
|
|
78
|
+
"http",
|
|
79
|
+
"smtplib",
|
|
80
|
+
"ftplib",
|
|
81
|
+
"tempfile",
|
|
82
|
+
"multiprocessing",
|
|
83
|
+
}
|
|
84
|
+
_IO_CALLS = {"open", "input", "exec", "eval", "compile", "__import__"}
|
|
85
|
+
_CLOCK_ATTRS = {"now", "utcnow", "today"}
|
|
86
|
+
_DOC_CAP, _TEST_CAP = 25, 25
|
|
87
|
+
_SLOW_SHRINK_STEPS = 3
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass
|
|
91
|
+
class EquivOptions:
|
|
92
|
+
call_timeout: float = 5.0
|
|
93
|
+
memory_mb: int = 1024
|
|
94
|
+
inputs: int = 50
|
|
95
|
+
compare: str = "functional" # functional | strict
|
|
96
|
+
seed: int = 0
|
|
97
|
+
profile: Profile = field(default_factory=Profile)
|
|
98
|
+
backend: Backend | None = None
|
|
99
|
+
judge_budget: int = 20
|
|
100
|
+
spot_check: int = 0
|
|
101
|
+
accept_judged: bool = False
|
|
102
|
+
# Callers pass the project's old cache path: any non-None value only switches the judge cache on.
|
|
103
|
+
# Entries live outside the project (`judge.default_cache_dir()`), MAC-signed.
|
|
104
|
+
judge_cache: Path | None = None
|
|
105
|
+
judge_reconfirm: bool = False # a cached `same` is asked again (apply sets this)
|
|
106
|
+
python_path: list[str] = field(default_factory=list)
|
|
107
|
+
use_hypothesis: bool = True
|
|
108
|
+
deps_from: str | None = None
|
|
109
|
+
offline: bool = False
|
|
110
|
+
timeout: float = 300
|
|
111
|
+
target_dir: str | None = None
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def judged_accepted(self) -> bool:
|
|
115
|
+
"""Judged passes count: `--accept-judged`, or `accept_judged = true` in the user's TOML."""
|
|
116
|
+
return self.accept_judged or self.profile.accept_judged
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# --- analysis (source text only) ----------------------------------------------------------------
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@dataclass
|
|
123
|
+
class FnPlan:
|
|
124
|
+
name: str
|
|
125
|
+
node: ast.FunctionDef
|
|
126
|
+
params: list[Ty]
|
|
127
|
+
param_names: list[str]
|
|
128
|
+
ret: Ty
|
|
129
|
+
rsig: RustSig
|
|
130
|
+
key: str
|
|
131
|
+
module: str
|
|
132
|
+
py_source: str
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@dataclass
|
|
136
|
+
class ModelPlan:
|
|
137
|
+
name: str
|
|
138
|
+
kind: str # pydantic | dataclass
|
|
139
|
+
fields: list[tuple[str, Ty, bool]] # (name, type, has default)
|
|
140
|
+
key: str
|
|
141
|
+
rust_ok: str | None # reason the Rust struct cannot be round-tripped
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _io_reason(node: ast.FunctionDef) -> str | None:
|
|
145
|
+
for n in ast.walk(node):
|
|
146
|
+
if isinstance(n, ast.Name) and n.id in _IO_CALLS and isinstance(n.ctx, ast.Load):
|
|
147
|
+
return f"uses {n.id}()"
|
|
148
|
+
if isinstance(n, ast.Attribute):
|
|
149
|
+
root = n
|
|
150
|
+
while isinstance(root, ast.Attribute):
|
|
151
|
+
root = root.value
|
|
152
|
+
if isinstance(root, ast.Name) and root.id in _IO_ROOTS:
|
|
153
|
+
return f"uses {root.id} (I/O or non-deterministic)"
|
|
154
|
+
if n.attr in _CLOCK_ATTRS:
|
|
155
|
+
return f"reads the clock ({n.attr})"
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _decorator_name(d: ast.expr) -> str:
|
|
160
|
+
target = d.func if isinstance(d, ast.Call) else d
|
|
161
|
+
return ast.unparse(target)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def analyze_function(
|
|
165
|
+
node: ast.FunctionDef | ast.AsyncFunctionDef,
|
|
166
|
+
source: str,
|
|
167
|
+
rust: str,
|
|
168
|
+
module: str,
|
|
169
|
+
models: set[str] | frozenset[str],
|
|
170
|
+
) -> FnPlan | str:
|
|
171
|
+
"""A plan for comparing this function, or the reason it is `not-applicable`."""
|
|
172
|
+
if isinstance(node, ast.AsyncFunctionDef):
|
|
173
|
+
return "async function"
|
|
174
|
+
a = node.args
|
|
175
|
+
if a.vararg or a.kwarg:
|
|
176
|
+
return "takes *args/**kwargs (no fixed JSON signature)"
|
|
177
|
+
if a.kwonlyargs:
|
|
178
|
+
return "has keyword-only parameters"
|
|
179
|
+
if any(
|
|
180
|
+
_decorator_name(d) not in ("cache", "lru_cache", "functools.cache", "functools.lru_cache")
|
|
181
|
+
for d in node.decorator_list
|
|
182
|
+
):
|
|
183
|
+
return f"decorated with @{_decorator_name(node.decorator_list[0])}"
|
|
184
|
+
if why := _io_reason(node):
|
|
185
|
+
return why
|
|
186
|
+
names = [x.arg for x in [*a.posonlyargs, *a.args]]
|
|
187
|
+
try:
|
|
188
|
+
params = [parse_ann(x.annotation, models) for x in [*a.posonlyargs, *a.args]]
|
|
189
|
+
ret = parse_ann(node.returns, models)
|
|
190
|
+
if any(has_model(t) for t in [*params, ret]):
|
|
191
|
+
raise Unsupported("model-typed parameter or result (covered by the model round trip)")
|
|
192
|
+
rsig = find_rust_fn(rust, node.name)
|
|
193
|
+
if not rsig.is_pub:
|
|
194
|
+
raise Unsupported("the Rust function is not pub")
|
|
195
|
+
if len(rsig.params) != len(params):
|
|
196
|
+
raise Unsupported(f"Rust takes {len(rsig.params)} parameter(s), Python {len(params)}")
|
|
197
|
+
for (pname, rty), pty in zip(rsig.params, params, strict=True):
|
|
198
|
+
if why := compat(pty, rty):
|
|
199
|
+
raise Unsupported(f"parameter {pname}: {why}")
|
|
200
|
+
rret = rsig.ret.args[0] if rsig.ret.kind == "result" else rsig.ret
|
|
201
|
+
if why := compat(ret, rret):
|
|
202
|
+
raise Unsupported(f"return type: {why}")
|
|
203
|
+
except Unsupported as exc:
|
|
204
|
+
return str(exc)
|
|
205
|
+
seg = ast.get_source_segment(source, node) or node.name
|
|
206
|
+
return FnPlan(node.name, node, params, names, ret, rsig, f"{module}::{node.name}", module, seg)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _is_model_class(node: ast.ClassDef) -> str | None:
|
|
210
|
+
if any(ast.unparse(b).split(".")[-1] == "BaseModel" for b in node.bases):
|
|
211
|
+
return "pydantic"
|
|
212
|
+
if any(_decorator_name(d).split(".")[-1] == "dataclass" for d in node.decorator_list):
|
|
213
|
+
return "dataclass"
|
|
214
|
+
return None
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _has_default(value: ast.expr | None) -> bool:
|
|
218
|
+
if value is None:
|
|
219
|
+
return False
|
|
220
|
+
if isinstance(value, ast.Call) and ast.unparse(value.func).split(".")[-1] == "Field":
|
|
221
|
+
kws = {k.arg for k in value.keywords}
|
|
222
|
+
if value.args:
|
|
223
|
+
first = value.args[0]
|
|
224
|
+
return not (isinstance(first, ast.Constant) and first.value is ...)
|
|
225
|
+
return bool(kws & {"default", "default_factory"})
|
|
226
|
+
return True
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def analyze_models(tree: ast.Module, rust: str, module: str) -> dict[str, ModelPlan | str]:
|
|
230
|
+
classes = {n.name: n for n in tree.body if isinstance(n, ast.ClassDef) and _is_model_class(n)}
|
|
231
|
+
rs = rust_models(rust)
|
|
232
|
+
out: dict[str, ModelPlan | str] = {}
|
|
233
|
+
for name, node in classes.items():
|
|
234
|
+
fields: list[tuple[str, Ty, bool]] = []
|
|
235
|
+
try:
|
|
236
|
+
for st in node.body:
|
|
237
|
+
if isinstance(st, ast.AnnAssign) and isinstance(st.target, ast.Name):
|
|
238
|
+
if "ClassVar" in ast.unparse(st.annotation):
|
|
239
|
+
continue
|
|
240
|
+
fields.append(
|
|
241
|
+
(
|
|
242
|
+
st.target.id,
|
|
243
|
+
parse_ann(st.annotation, set(classes)),
|
|
244
|
+
_has_default(st.value),
|
|
245
|
+
)
|
|
246
|
+
)
|
|
247
|
+
except Unsupported as exc:
|
|
248
|
+
out[name] = f"field type: {exc}"
|
|
249
|
+
continue
|
|
250
|
+
why = None
|
|
251
|
+
if name not in rs:
|
|
252
|
+
why = "no Rust struct of that name"
|
|
253
|
+
elif not rs[name]:
|
|
254
|
+
why = "the Rust struct does not derive both Serialize and Deserialize"
|
|
255
|
+
kind = _is_model_class(node) or "dataclass"
|
|
256
|
+
out[name] = ModelPlan(name, kind, fields, f"model:{module}::{name}", why)
|
|
257
|
+
return out
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
# --- inputs -------------------------------------------------------------------------------------
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _literal_calls(tree: ast.AST, fname: str, names: list[str]) -> list[list[Any]]:
|
|
264
|
+
"""Argument lists of calls `fname(<literals>)` found in `tree`, via ast.literal_eval only."""
|
|
265
|
+
out: list[list[Any]] = []
|
|
266
|
+
for n in ast.walk(tree):
|
|
267
|
+
if not (isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id == fname):
|
|
268
|
+
continue
|
|
269
|
+
try:
|
|
270
|
+
args = [ast.literal_eval(x) for x in n.args]
|
|
271
|
+
kw = {k.arg: ast.literal_eval(k.value) for k in n.keywords if k.arg}
|
|
272
|
+
except ValueError, TypeError, SyntaxError, MemoryError, RecursionError:
|
|
273
|
+
continue
|
|
274
|
+
if len(n.keywords) != len(kw) or any(k not in names for k in kw):
|
|
275
|
+
continue
|
|
276
|
+
rest = names[len(args) :]
|
|
277
|
+
if any(r not in kw for r in rest) or len(args) > len(names):
|
|
278
|
+
continue
|
|
279
|
+
out.append([*args, *(kw[r] for r in rest)])
|
|
280
|
+
return out
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def doc_cases(tree: ast.Module, plan: FnPlan) -> list[list[Any]]:
|
|
284
|
+
"""Call arguments from doctest examples in any docstring of the module."""
|
|
285
|
+
cases: list[list[Any]] = []
|
|
286
|
+
parser = doctest.DocTestParser()
|
|
287
|
+
for n in ast.walk(tree):
|
|
288
|
+
if isinstance(n, ast.Module | ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef):
|
|
289
|
+
doc = ast.get_docstring(n, clean=False)
|
|
290
|
+
if not doc or ">>>" not in doc:
|
|
291
|
+
continue
|
|
292
|
+
for ex in parser.get_examples(doc):
|
|
293
|
+
try:
|
|
294
|
+
sub = ast.parse(ex.source)
|
|
295
|
+
except SyntaxError:
|
|
296
|
+
continue
|
|
297
|
+
cases += _literal_calls(sub, plan.name, plan.param_names)
|
|
298
|
+
return cases
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def test_file_cases(py_path: Path, plan: FnPlan) -> list[list[Any]]:
|
|
302
|
+
"""Arguments of `assert f(<literals>) == <literal>` in sibling test files."""
|
|
303
|
+
stem, here = py_path.stem, py_path.parent
|
|
304
|
+
files = [
|
|
305
|
+
d / n
|
|
306
|
+
for d in (here, here / "tests", here.parent / "tests")
|
|
307
|
+
for n in (f"test_{stem}.py", f"{stem}_test.py")
|
|
308
|
+
]
|
|
309
|
+
cases: list[list[Any]] = []
|
|
310
|
+
for f in files:
|
|
311
|
+
try:
|
|
312
|
+
tree = ast.parse(f.read_text(encoding="utf-8"))
|
|
313
|
+
except OSError, SyntaxError, ValueError:
|
|
314
|
+
continue
|
|
315
|
+
for n in ast.walk(tree):
|
|
316
|
+
if (
|
|
317
|
+
isinstance(n, ast.Assert)
|
|
318
|
+
and isinstance(n.test, ast.Compare)
|
|
319
|
+
and len(n.test.ops) == 1
|
|
320
|
+
and isinstance(n.test.ops[0], ast.Eq)
|
|
321
|
+
):
|
|
322
|
+
sides = [n.test.left, n.test.comparators[0]]
|
|
323
|
+
cases += [c for s in sides for c in _literal_calls(s, plan.name, plan.param_names)]
|
|
324
|
+
return cases
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _key(args: list[Any]) -> str:
|
|
328
|
+
return json.dumps(to_wire(args), sort_keys=True, default=str)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def build_cases(
|
|
332
|
+
plan: FnPlan, doc: list[tuple[str, list[list[Any]]]], opts: EquivOptions
|
|
333
|
+
) -> list[tuple[str, list[Any]]]:
|
|
334
|
+
"""Ordered, de-duplicated (source, args): doctests, test files, edges, random, int probes."""
|
|
335
|
+
out: list[tuple[str, list[Any]]] = []
|
|
336
|
+
seen: set[str] = set()
|
|
337
|
+
|
|
338
|
+
def add(source: str, args: list[Any]) -> bool:
|
|
339
|
+
if not fits_all(plan.params, args) or (k := _key(args)) in seen:
|
|
340
|
+
return False
|
|
341
|
+
seen.add(k)
|
|
342
|
+
out.append((source, args))
|
|
343
|
+
return True
|
|
344
|
+
|
|
345
|
+
for source, items in doc:
|
|
346
|
+
for args in items:
|
|
347
|
+
add(source, args)
|
|
348
|
+
if not plan.params:
|
|
349
|
+
add("generated", [])
|
|
350
|
+
return out
|
|
351
|
+
rng = random.Random(f"{opts.seed}:{plan.name}")
|
|
352
|
+
edges = [gen_edges(t) for t in plan.params]
|
|
353
|
+
typical = [e[min(2, len(e) - 1)] if e else None for e in edges]
|
|
354
|
+
gen = 0
|
|
355
|
+
limit = max(opts.inputs // 2, 1)
|
|
356
|
+
for i, e in enumerate(edges): # one edge value at a time, the others typical
|
|
357
|
+
for v in e:
|
|
358
|
+
if gen < limit and add("edge", [*typical[:i], v, *typical[i + 1 :]]):
|
|
359
|
+
gen += 1
|
|
360
|
+
for k in range(max(map(len, edges))): # then all parameters at an edge together
|
|
361
|
+
if gen < limit and add("edge", [e[(k + j) % len(e)] for j, e in enumerate(edges)]):
|
|
362
|
+
gen += 1
|
|
363
|
+
tries = 0
|
|
364
|
+
while gen < opts.inputs and tries < opts.inputs * 20:
|
|
365
|
+
tries += 1
|
|
366
|
+
if add("generated", [gen_random(t, rng) for t in plan.params]):
|
|
367
|
+
gen += 1
|
|
368
|
+
for i, t in enumerate(plan.params): # past-i64 probes: reported as overflow drift, not noise
|
|
369
|
+
if t[0] == "int":
|
|
370
|
+
for v in BOUNDARY_INTS:
|
|
371
|
+
add("probe", [*typical[:i], v, *typical[i + 1 :]])
|
|
372
|
+
return out
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def fits_all(tys: list[Ty], args: list[Any]) -> bool:
|
|
376
|
+
return len(tys) == len(args) and all(fits(t, a) for t, a in zip(tys, args, strict=True))
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
# --- running one function -----------------------------------------------------------------------
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
@dataclass
|
|
383
|
+
class Ctx:
|
|
384
|
+
opts: EquivOptions
|
|
385
|
+
py: PythonRunner
|
|
386
|
+
rs: RustRunner
|
|
387
|
+
judge: Judge | None
|
|
388
|
+
would_send: list[dict[str, Any]]
|
|
389
|
+
judged: list[dict[str, Any]]
|
|
390
|
+
spot_pool: list[JudgeCase]
|
|
391
|
+
file: str
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _brief(reply: dict[str, Any]) -> Any:
|
|
395
|
+
post = {"args_after": to_wire(reply["args_after"])} if "args_after" in reply else {}
|
|
396
|
+
if "ok" in reply:
|
|
397
|
+
return {"ok": to_wire(reply["ok"]), **post}
|
|
398
|
+
if "err" in reply:
|
|
399
|
+
return {"err": reply["err"], **({"msg": reply["msg"]} if "msg" in reply else {}), **post}
|
|
400
|
+
return {k: v for k, v in reply.items()}
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _result(status: str, reason: str | None = None, **extra: Any) -> dict[str, Any]:
|
|
404
|
+
return {
|
|
405
|
+
"equiv": status,
|
|
406
|
+
"equiv_reason": reason,
|
|
407
|
+
"equiv_inputs": 0,
|
|
408
|
+
"equiv_counterexample": None,
|
|
409
|
+
"equiv_drift": [],
|
|
410
|
+
"equiv_skipped": {},
|
|
411
|
+
**extra,
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def _counter(args: list[Any], py: dict, rs: dict, diffs: list, shrunk: bool, **x: Any) -> dict:
|
|
416
|
+
return {
|
|
417
|
+
"args": to_wire(args),
|
|
418
|
+
"python": _brief(py),
|
|
419
|
+
"rust": _brief(rs),
|
|
420
|
+
"diff": [{k: v for k, v in d.items() if k != "soft"} for d in diffs[:5]],
|
|
421
|
+
"shrunk": shrunk,
|
|
422
|
+
**x,
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def run_function(plan: FnPlan, doc: list[tuple[str, list[list[Any]]]], ctx: Ctx) -> dict[str, Any]:
|
|
427
|
+
opts, prof = ctx.opts, ctx.opts.profile
|
|
428
|
+
strict = opts.compare == "strict"
|
|
429
|
+
compared = 0
|
|
430
|
+
skipped: Counter[str] = Counter()
|
|
431
|
+
|
|
432
|
+
observe = [i for i, (_, t) in enumerate(plan.rsig.params) if t.has_shared]
|
|
433
|
+
observations = [(i, plan.params[i]) for i in observe]
|
|
434
|
+
|
|
435
|
+
def evaluate(args: list[Any]) -> tuple[dict, dict, Any]:
|
|
436
|
+
wire = to_wire(args)
|
|
437
|
+
py = (
|
|
438
|
+
ctx.py.call(plan.name, wire, observe=observe)
|
|
439
|
+
if observe
|
|
440
|
+
else ctx.py.call(plan.name, wire)
|
|
441
|
+
)
|
|
442
|
+
rs = ctx.rs.call(plan.key, wire)
|
|
443
|
+
result = compare_case(args, py, rs, plan.ret, plan.name, prof, strict=strict,
|
|
444
|
+
observations=observations) # fmt: skip
|
|
445
|
+
return py, rs, result
|
|
446
|
+
|
|
447
|
+
def is_failure(res: Any) -> bool:
|
|
448
|
+
return res.kind == "hard" or drift_fails(res, prof)
|
|
449
|
+
|
|
450
|
+
soft: dict[str, tuple[list[Any], dict, dict, list]] = {}
|
|
451
|
+
drift: list[dict[str, Any]] = []
|
|
452
|
+
failing: tuple[list[Any], dict, dict, Any] | None = None
|
|
453
|
+
for _source, args in build_cases(plan, doc, opts):
|
|
454
|
+
py, rs, res = evaluate(args)
|
|
455
|
+
if res.kind == "skip":
|
|
456
|
+
skipped[res.reason] += 1
|
|
457
|
+
continue
|
|
458
|
+
compared += 1
|
|
459
|
+
if res.kind == "drift":
|
|
460
|
+
drift.append(
|
|
461
|
+
{
|
|
462
|
+
"args": to_wire(args),
|
|
463
|
+
"python": _brief(py),
|
|
464
|
+
"rust": _brief(rs),
|
|
465
|
+
"kind": res.reason,
|
|
466
|
+
}
|
|
467
|
+
)
|
|
468
|
+
if is_failure(res):
|
|
469
|
+
failing = (args, py, rs, res)
|
|
470
|
+
break
|
|
471
|
+
if res.kind == "soft":
|
|
472
|
+
soft.setdefault(_key(args), (args, py, rs, res.diffs))
|
|
473
|
+
shrunk = False
|
|
474
|
+
if failing is None and opts.use_hypothesis and plan.params and hypothesis_available():
|
|
475
|
+
tally = [0]
|
|
476
|
+
found = _hypothesis_search(plan.params, evaluate, is_failure, opts.inputs, tally)
|
|
477
|
+
compared += tally[0]
|
|
478
|
+
if found is not None:
|
|
479
|
+
failing, shrunk = found, True
|
|
480
|
+
if failing is not None:
|
|
481
|
+
args, py, rs, res = failing
|
|
482
|
+
if not shrunk:
|
|
483
|
+
slow = [
|
|
484
|
+
0
|
|
485
|
+
] # a Rust call that times out or blows the memory cap costs seconds: give up early
|
|
486
|
+
|
|
487
|
+
def still(trial: list[Any]) -> bool:
|
|
488
|
+
if slow[0] >= _SLOW_SHRINK_STEPS:
|
|
489
|
+
return False
|
|
490
|
+
_py, rs_reply, res = evaluate(trial)
|
|
491
|
+
slow[0] += any(k in rs_reply for k in ("__timeout__", "__memory__", "__output__"))
|
|
492
|
+
return is_failure(res)
|
|
493
|
+
|
|
494
|
+
small = shrink(plan.params, args, still)
|
|
495
|
+
if small != args:
|
|
496
|
+
py, rs, res = evaluate(small)
|
|
497
|
+
args, shrunk = small, True
|
|
498
|
+
out = _result(
|
|
499
|
+
"failed",
|
|
500
|
+
drift_reason(res, prof)
|
|
501
|
+
if res.kind == "drift"
|
|
502
|
+
else res.reason or (f"{res.diffs[0]['kind']} differs" if res.diffs else "differs"),
|
|
503
|
+
equiv_inputs=compared,
|
|
504
|
+
equiv_counterexample=_counter(args, py, rs, res.diffs, shrunk),
|
|
505
|
+
equiv_drift=drift[:5],
|
|
506
|
+
equiv_skipped=dict(skipped),
|
|
507
|
+
)
|
|
508
|
+
return out
|
|
509
|
+
if compared == 0:
|
|
510
|
+
why = ", ".join(f"{k} ({v}x)" for k, v in skipped.most_common(3)) or "no inputs"
|
|
511
|
+
return _result("not-applicable", f"no input could be compared: {why}")
|
|
512
|
+
base = {"equiv_inputs": compared, "equiv_drift": drift[:5], "equiv_skipped": dict(skipped)}
|
|
513
|
+
if not soft:
|
|
514
|
+
return {**_result("passed"), **base}
|
|
515
|
+
return {**_judge_soft(plan, list(soft.values()), ctx), **base}
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def _hypothesis_search(
|
|
519
|
+
params: list[Ty], evaluate: Any, is_failure: Any, n: int, tally: list[int]
|
|
520
|
+
) -> Any:
|
|
521
|
+
from hypothesis import HealthCheck, Phase, find, settings
|
|
522
|
+
from hypothesis import strategies as st
|
|
523
|
+
from hypothesis.errors import NoSuchExample
|
|
524
|
+
|
|
525
|
+
strat = st.tuples(*(hypothesis_strategy(t) for t in params))
|
|
526
|
+
|
|
527
|
+
def condition(values: tuple[Any, ...]) -> bool:
|
|
528
|
+
args = list(values)
|
|
529
|
+
res = evaluate(args)[2]
|
|
530
|
+
tally[0] += res.kind != "skip"
|
|
531
|
+
return is_failure(res)
|
|
532
|
+
|
|
533
|
+
cfg = settings(
|
|
534
|
+
max_examples=max(n, 1),
|
|
535
|
+
database=None,
|
|
536
|
+
derandomize=True,
|
|
537
|
+
deadline=None,
|
|
538
|
+
suppress_health_check=list(HealthCheck),
|
|
539
|
+
phases=[Phase.generate, Phase.shrink],
|
|
540
|
+
)
|
|
541
|
+
try:
|
|
542
|
+
best = find(strat, condition, settings=cfg)
|
|
543
|
+
except NoSuchExample:
|
|
544
|
+
return None
|
|
545
|
+
args = list(best)
|
|
546
|
+
py, rs, res = evaluate(args)
|
|
547
|
+
return args, py, rs, res
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
PER_KIND = 2 # distinct soft cases judged per kind of difference (the judge works on samples)
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _representatives(cases: list[tuple]) -> list[tuple]:
|
|
554
|
+
"""The simplest few cases of each difference kind: what is sent (or would be sent) to a judge."""
|
|
555
|
+
groups: dict[tuple[str, ...], list[tuple]] = {}
|
|
556
|
+
for c in sorted(cases, key=lambda c: len(_key(c[0]))):
|
|
557
|
+
groups.setdefault(tuple(sorted({d["kind"] for d in c[3]})), []).append(c)
|
|
558
|
+
return [c for g in groups.values() for c in g[:PER_KIND]]
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def _judge_soft(plan: FnPlan, cases: list[tuple], ctx: Ctx) -> dict[str, Any]:
|
|
562
|
+
"""Cases that differ only in presentation: judge them, or list them as needs-judgement."""
|
|
563
|
+
picked = _representatives(cases)
|
|
564
|
+
|
|
565
|
+
def case_of(c: tuple) -> JudgeCase:
|
|
566
|
+
a, py, rs, diffs = c
|
|
567
|
+
return JudgeCase(
|
|
568
|
+
plan.name,
|
|
569
|
+
plan.py_source,
|
|
570
|
+
plan.rsig.text,
|
|
571
|
+
to_wire(a),
|
|
572
|
+
_brief(py).get("ok", _brief(py)),
|
|
573
|
+
_brief(rs).get("ok", _brief(rs)),
|
|
574
|
+
[{k: v for k, v in d.items() if k != "soft"} for d in diffs],
|
|
575
|
+
)
|
|
576
|
+
|
|
577
|
+
judge_cases = [case_of(c) for c in picked]
|
|
578
|
+
first = judge_cases[0]
|
|
579
|
+
|
|
580
|
+
def shown(jc: JudgeCase, **extra: Any) -> dict[str, Any]:
|
|
581
|
+
return {
|
|
582
|
+
"args": jc.args,
|
|
583
|
+
"python": jc.python_output,
|
|
584
|
+
"rust": jc.rust_output,
|
|
585
|
+
"diff": jc.diff,
|
|
586
|
+
**extra,
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
if ctx.judge is None:
|
|
590
|
+
for jc in judge_cases[: max(ctx.opts.judge_budget, 1)]:
|
|
591
|
+
ctx.would_send.append({"file": ctx.file, "function": jc.function, **shown(jc)})
|
|
592
|
+
return _result(
|
|
593
|
+
"needs-judgement",
|
|
594
|
+
f"{len(cases)} output(s) differ only in presentation ({first.diff[0]['kind']}); "
|
|
595
|
+
"no judge configured",
|
|
596
|
+
equiv_counterexample={**shown(first), "shrunk": False},
|
|
597
|
+
)
|
|
598
|
+
confirmed: list[dict[str, Any]] = []
|
|
599
|
+
for jc in judge_cases:
|
|
600
|
+
r = ctx.judge.judge(jc)
|
|
601
|
+
entry = {
|
|
602
|
+
"file": ctx.file,
|
|
603
|
+
"function": jc.function,
|
|
604
|
+
**shown(jc),
|
|
605
|
+
"reason": r.reason,
|
|
606
|
+
"confidence": r.confidence,
|
|
607
|
+
"confirmed": r.confirmed,
|
|
608
|
+
"cached": r.cached,
|
|
609
|
+
}
|
|
610
|
+
if r.verdict == "different":
|
|
611
|
+
return _result(
|
|
612
|
+
"failed",
|
|
613
|
+
f"judge: {r.reason}",
|
|
614
|
+
equiv_counterexample={**shown(jc), "shrunk": False, "judge_reason": r.reason},
|
|
615
|
+
)
|
|
616
|
+
if r.verdict != "same":
|
|
617
|
+
return _result(
|
|
618
|
+
"needs-judgement",
|
|
619
|
+
f"judge could not rule: {r.reason}",
|
|
620
|
+
equiv_counterexample={**shown(jc), "shrunk": False},
|
|
621
|
+
)
|
|
622
|
+
confirmed.append(entry)
|
|
623
|
+
ctx.spot_pool.append(jc)
|
|
624
|
+
ctx.judged.extend(confirmed)
|
|
625
|
+
return _result(
|
|
626
|
+
"passed-judged",
|
|
627
|
+
f"{len(cases)} presentation-level difference(s); the judge ruled `same` on "
|
|
628
|
+
f"{len(confirmed)} representative case(s)",
|
|
629
|
+
)
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
# --- models -------------------------------------------------------------------------------------
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
def _payload_value(ty: Ty, rng: random.Random, models: dict[str, ModelPlan], depth: int = 0) -> Any:
|
|
636
|
+
k = ty[0]
|
|
637
|
+
if k == "model":
|
|
638
|
+
return _payload(models[ty[1]], rng, models, depth + 1)
|
|
639
|
+
if k == "opt":
|
|
640
|
+
return None if rng.random() < 0.2 else _payload_value(ty[1], rng, models, depth)
|
|
641
|
+
if k in ("list", "tuplev"):
|
|
642
|
+
return [_payload_value(ty[1], rng, models, depth + 1) for _ in range(rng.choice([0, 1, 2]))]
|
|
643
|
+
if k == "tuple":
|
|
644
|
+
return [_payload_value(t, rng, models, depth + 1) for t in ty[1]]
|
|
645
|
+
if k == "dict":
|
|
646
|
+
return {
|
|
647
|
+
rng.choice("abc"): _payload_value(ty[1], rng, models, depth + 1)
|
|
648
|
+
for _ in range(rng.choice([0, 1, 2]))
|
|
649
|
+
}
|
|
650
|
+
for _ in range(20):
|
|
651
|
+
v = gen_random(ty, rng)
|
|
652
|
+
if finite_only(ty, v):
|
|
653
|
+
return v
|
|
654
|
+
return gen_edges(ty)[0]
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
def _payload(
|
|
658
|
+
plan: ModelPlan,
|
|
659
|
+
rng: random.Random,
|
|
660
|
+
models: dict[str, ModelPlan],
|
|
661
|
+
depth: int = 0,
|
|
662
|
+
omit_defaults: bool = False,
|
|
663
|
+
) -> dict[str, Any]:
|
|
664
|
+
if depth > 3:
|
|
665
|
+
return {}
|
|
666
|
+
return {
|
|
667
|
+
n: _payload_value(t, rng, models, depth)
|
|
668
|
+
for n, t, dflt in plan.fields
|
|
669
|
+
if not (omit_defaults and dflt)
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def model_payloads(
|
|
674
|
+
plan: ModelPlan, models: dict[str, ModelPlan], opts: EquivOptions
|
|
675
|
+
) -> list[tuple[str, Any]]:
|
|
676
|
+
rng = random.Random(f"{opts.seed}:{plan.name}")
|
|
677
|
+
out: list[tuple[str, Any]] = [
|
|
678
|
+
("valid", _payload(plan, rng, models)) for _ in range(min(opts.inputs, 8))
|
|
679
|
+
]
|
|
680
|
+
out.append(("defaults", _payload(plan, rng, models, omit_defaults=True)))
|
|
681
|
+
required = [n for n, _, dflt in plan.fields if not dflt]
|
|
682
|
+
full = _payload(plan, rng, models)
|
|
683
|
+
for n in required[:3]:
|
|
684
|
+
out.append(("missing-field", {k: v for k, v in full.items() if k != n}))
|
|
685
|
+
if plan.fields:
|
|
686
|
+
first = plan.fields[0]
|
|
687
|
+
bad: Any = "x" if first[1][0] in ("list", "tuple", "tuplev", "dict", "model") else [1, 2]
|
|
688
|
+
out.append(("wrong-type", {**full, first[0]: bad}))
|
|
689
|
+
out.append(("extra-field", {**full, "__extra__": 1}))
|
|
690
|
+
return out
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
def run_model(plan: ModelPlan, models: dict[str, ModelPlan], ctx: Ctx) -> dict[str, Any]:
|
|
694
|
+
if plan.rust_ok:
|
|
695
|
+
return _result("not-applicable", plan.rust_ok)
|
|
696
|
+
compared = 0
|
|
697
|
+
for source, payload in model_payloads(plan, models, ctx.opts):
|
|
698
|
+
py = ctx.py.model(plan.name, payload)
|
|
699
|
+
if py.get("err") == "no-pydantic":
|
|
700
|
+
return _result("not-applicable", "pydantic is not importable in the runner")
|
|
701
|
+
rs = ctx.rs.call(plan.key, [payload])
|
|
702
|
+
res = compare_case(
|
|
703
|
+
[payload],
|
|
704
|
+
py,
|
|
705
|
+
rs,
|
|
706
|
+
("any",),
|
|
707
|
+
plan.name,
|
|
708
|
+
ctx.opts.profile,
|
|
709
|
+
strict=ctx.opts.compare == "strict",
|
|
710
|
+
)
|
|
711
|
+
if res.kind == "skip":
|
|
712
|
+
continue
|
|
713
|
+
compared += 1
|
|
714
|
+
if (
|
|
715
|
+
res.kind == "hard"
|
|
716
|
+
or drift_fails(res, ctx.opts.profile)
|
|
717
|
+
or (res.kind == "soft" and ctx.judge is None)
|
|
718
|
+
):
|
|
719
|
+
why = res.diffs[0]["kind"] if res.diffs else res.reason
|
|
720
|
+
status = "failed" if res.kind != "soft" else "needs-judgement"
|
|
721
|
+
return _result(
|
|
722
|
+
status,
|
|
723
|
+
f"{source} payload: {why}",
|
|
724
|
+
equiv_inputs=compared,
|
|
725
|
+
equiv_counterexample=_counter([payload], py, rs, res.diffs, False),
|
|
726
|
+
)
|
|
727
|
+
if res.kind == "soft":
|
|
728
|
+
return _result(
|
|
729
|
+
"needs-judgement",
|
|
730
|
+
f"{source} payload differs in presentation only",
|
|
731
|
+
equiv_inputs=compared,
|
|
732
|
+
equiv_counterexample=_counter([payload], py, rs, res.diffs, False),
|
|
733
|
+
)
|
|
734
|
+
if compared == 0:
|
|
735
|
+
return _result("not-applicable", "no payload could be compared")
|
|
736
|
+
return {**_result("passed"), "equiv_inputs": compared}
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
# --- the rung -----------------------------------------------------------------------------------
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
def _scratch_copy(work: Path, module: CheckModule, i: int) -> str:
|
|
743
|
+
if os.path.isfile(module.name):
|
|
744
|
+
return str(Path(module.name).resolve())
|
|
745
|
+
p = work / f"user_m{i:03d}.py"
|
|
746
|
+
p.write_text(module.python or "", encoding="utf-8")
|
|
747
|
+
return str(p)
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def _set(fn: dict[str, Any], res: dict[str, Any], accept_judged: bool) -> None:
|
|
751
|
+
fn.update({k: res[k] for k in res if k.startswith("equiv")})
|
|
752
|
+
st = res["equiv"]
|
|
753
|
+
rung = {
|
|
754
|
+
"passed": "pass",
|
|
755
|
+
"passed-judged": "pass" if accept_judged else "judged",
|
|
756
|
+
"failed": "fail",
|
|
757
|
+
"needs-judgement": "unverified",
|
|
758
|
+
"not-applicable": "skipped",
|
|
759
|
+
}[st]
|
|
760
|
+
fn["rungs"]["equiv"] = rung
|
|
761
|
+
lower = [r for k, r in fn["rungs"].items() if k != "equiv"]
|
|
762
|
+
if rung == "pass" and all(r in ("pass", "skipped") for r in lower):
|
|
763
|
+
fn["highest_rung"] = "equiv"
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
def _not_run(fn: dict[str, Any], why: str) -> None:
|
|
767
|
+
fn.update(_result("not-applicable", why))
|
|
768
|
+
fn["rungs"]["equiv"] = "skipped"
|
|
769
|
+
|
|
770
|
+
|
|
771
|
+
def _plan_for(
|
|
772
|
+
fn: dict[str, Any], u: Any, mod: str, top: dict[str, Any], model_names: set[str]
|
|
773
|
+
) -> FnPlan | str:
|
|
774
|
+
"""A plan for comparing the function (a ladder verdict entry), or why it is `not-applicable`."""
|
|
775
|
+
rungs = fn["rungs"]
|
|
776
|
+
if rungs.get("check") != "pass":
|
|
777
|
+
return f"did not pass cargo check ({rungs.get('check')})"
|
|
778
|
+
if not fn["has_item"] or fn["has_todo"]:
|
|
779
|
+
return "no translated Rust function (missing or todo!())"
|
|
780
|
+
if fn["function"] not in top:
|
|
781
|
+
return "method or nested function (needs an instance)"
|
|
782
|
+
return analyze_function(
|
|
783
|
+
top[fn["function"]], u.module.python or "", u.module.rust, mod, model_names
|
|
784
|
+
)
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
def static_applicability(module: CheckModule, fl: dict[str, Any], function: str) -> str | None:
|
|
788
|
+
"""None when `function` can be compared with the Python (a pure, module-level function with a
|
|
789
|
+
JSON-able signature), else the reason it cannot. Reads the sources only; nothing is executed.
|
|
790
|
+
|
|
791
|
+
`fl` is the module's ladder verdict (`has_item`, `has_todo` and the `check` rung of its functions).
|
|
792
|
+
"""
|
|
793
|
+
from python2rust.verify.ladder import Unit
|
|
794
|
+
|
|
795
|
+
fn = next((f for f in fl["functions"] if f["function"] == function), None)
|
|
796
|
+
if fn is None:
|
|
797
|
+
return "function not found"
|
|
798
|
+
tree = None
|
|
799
|
+
with contextlib.suppress(SyntaxError):
|
|
800
|
+
tree = ast.parse(module.python or "")
|
|
801
|
+
top = {
|
|
802
|
+
n.name: n
|
|
803
|
+
for n in (tree.body if tree else [])
|
|
804
|
+
if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef)
|
|
805
|
+
}
|
|
806
|
+
mod = crate_module_name([module], 0)
|
|
807
|
+
models = set(analyze_models(tree, module.rust, mod)) if tree else set()
|
|
808
|
+
plan = _plan_for(fn, Unit(module), mod, top, models)
|
|
809
|
+
return plan if isinstance(plan, str) else None
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
def run_equiv(
|
|
813
|
+
units: list[Any],
|
|
814
|
+
files: list[dict[str, Any]],
|
|
815
|
+
opts: EquivOptions,
|
|
816
|
+
only: str | None = None,
|
|
817
|
+
only_file: int | None = None,
|
|
818
|
+
) -> dict[str, Any]:
|
|
819
|
+
"""Fill in the equiv fields of every function in `files`; returns the document-level parts.
|
|
820
|
+
|
|
821
|
+
`units` are `ladder.Unit`s aligned with `files`. `only` restricts the run to one function and
|
|
822
|
+
`only_file` to the file at that index (used by `apply`: the other files are in the crate so
|
|
823
|
+
that `use crate::...` resolves, but are not compared).
|
|
824
|
+
"""
|
|
825
|
+
work = make_workdir()
|
|
826
|
+
try:
|
|
827
|
+
return _run(units, files, opts, only, only_file, work)
|
|
828
|
+
finally:
|
|
829
|
+
shutil.rmtree(work, ignore_errors=True)
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
def _run(
|
|
833
|
+
units: list[Any],
|
|
834
|
+
files: list[dict[str, Any]],
|
|
835
|
+
opts: EquivOptions,
|
|
836
|
+
only: str | None,
|
|
837
|
+
only_file: int | None,
|
|
838
|
+
work: Path,
|
|
839
|
+
) -> dict[str, Any]:
|
|
840
|
+
notes: list[str] = []
|
|
841
|
+
judge = (
|
|
842
|
+
Judge(
|
|
843
|
+
opts.backend,
|
|
844
|
+
profile=opts.profile.to_dict(),
|
|
845
|
+
cache_dir=default_cache_dir() if opts.judge_cache is not None else None,
|
|
846
|
+
budget=opts.judge_budget,
|
|
847
|
+
reconfirm_same=opts.judge_reconfirm,
|
|
848
|
+
model=getattr(opts.backend, "model", ""),
|
|
849
|
+
)
|
|
850
|
+
if opts.backend is not None and opts.compare != "strict"
|
|
851
|
+
else None
|
|
852
|
+
)
|
|
853
|
+
would_send: list[dict[str, Any]] = []
|
|
854
|
+
judged: list[dict[str, Any]] = []
|
|
855
|
+
spot_pool: list[JudgeCase] = []
|
|
856
|
+
plans: dict[int, dict[str, FnPlan]] = {}
|
|
857
|
+
mplans: dict[int, dict[str, ModelPlan]] = {}
|
|
858
|
+
trees: dict[int, ast.Module] = {}
|
|
859
|
+
modules = [u.module for u in units]
|
|
860
|
+
harness = HarnessPlan()
|
|
861
|
+
for i, (u, fl) in enumerate(zip(units, files, strict=True)):
|
|
862
|
+
mod = crate_module_name(modules, i)
|
|
863
|
+
harness.modules.append(mod)
|
|
864
|
+
if re.search(r"\bpub fn py2rs_module_init\s*\(\s*\)", u.module.rust):
|
|
865
|
+
harness.init_calls.append(f"{mod}::py2rs_module_init")
|
|
866
|
+
tree = None
|
|
867
|
+
with contextlib.suppress(SyntaxError):
|
|
868
|
+
tree = ast.parse(u.module.python or "")
|
|
869
|
+
top = {
|
|
870
|
+
n.name: n
|
|
871
|
+
for n in (tree.body if tree else [])
|
|
872
|
+
if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef)
|
|
873
|
+
}
|
|
874
|
+
model_defs = analyze_models(tree, u.module.rust, mod) if tree else {}
|
|
875
|
+
model_names = {n for n in model_defs}
|
|
876
|
+
plans[i], mplans[i] = {}, {}
|
|
877
|
+
if tree is not None:
|
|
878
|
+
trees[i] = tree
|
|
879
|
+
for fn in fl["functions"]:
|
|
880
|
+
if fn["kind"] != "function" or (only is not None and fn["function"] != only):
|
|
881
|
+
continue
|
|
882
|
+
if only_file is not None and i != only_file:
|
|
883
|
+
continue
|
|
884
|
+
name = fn["function"]
|
|
885
|
+
plan = _plan_for(fn, u, mod, top, model_names)
|
|
886
|
+
if isinstance(plan, str):
|
|
887
|
+
_not_run(fn, plan)
|
|
888
|
+
else:
|
|
889
|
+
plans[i][name] = plan
|
|
890
|
+
harness.fns.append(
|
|
891
|
+
PlanFn(
|
|
892
|
+
plan.key,
|
|
893
|
+
mod,
|
|
894
|
+
plan.rsig.ident,
|
|
895
|
+
[t for _, t in plan.rsig.params],
|
|
896
|
+
plan.rsig.ret,
|
|
897
|
+
)
|
|
898
|
+
)
|
|
899
|
+
if only is None:
|
|
900
|
+
fl["models"] = []
|
|
901
|
+
for name, m in model_defs.items():
|
|
902
|
+
if isinstance(m, str):
|
|
903
|
+
fl["models"].append({"model": name, **_result("not-applicable", m)})
|
|
904
|
+
else:
|
|
905
|
+
mplans[i][name] = m
|
|
906
|
+
if m.rust_ok is None:
|
|
907
|
+
harness.models.append(PlanModel(m.key, f"{mod}::{name}"))
|
|
908
|
+
results: dict[tuple[int, str], dict[str, Any]] = {}
|
|
909
|
+
mresults: dict[tuple[int, str], dict[str, Any]] = {}
|
|
910
|
+
limits = {"as": False}
|
|
911
|
+
if harness.fns or harness.models:
|
|
912
|
+
build = build_harness(
|
|
913
|
+
modules,
|
|
914
|
+
harness,
|
|
915
|
+
work,
|
|
916
|
+
deps_from=opts.deps_from,
|
|
917
|
+
offline=opts.offline,
|
|
918
|
+
timeout=opts.timeout,
|
|
919
|
+
target_dir=opts.target_dir,
|
|
920
|
+
)
|
|
921
|
+
if build.exe is None:
|
|
922
|
+
why = f"the comparison harness did not build: {build.error}"
|
|
923
|
+
for i, p in plans.items():
|
|
924
|
+
for name in p:
|
|
925
|
+
results[(i, name)] = _result("not-applicable", why)
|
|
926
|
+
for i, mp in mplans.items():
|
|
927
|
+
for name in mp:
|
|
928
|
+
mresults[(i, name)] = _result("not-applicable", why)
|
|
929
|
+
else:
|
|
930
|
+
rs = RustRunner(
|
|
931
|
+
build.exe, timeout=opts.call_timeout, cwd=work, memory_mb=opts.memory_mb
|
|
932
|
+
)
|
|
933
|
+
try:
|
|
934
|
+
for i, u in enumerate(units):
|
|
935
|
+
if not plans[i] and not any(m.rust_ok is None for m in mplans[i].values()):
|
|
936
|
+
continue
|
|
937
|
+
limits = _run_module(
|
|
938
|
+
i,
|
|
939
|
+
u,
|
|
940
|
+
plans[i],
|
|
941
|
+
mplans[i],
|
|
942
|
+
trees.get(i),
|
|
943
|
+
opts,
|
|
944
|
+
work,
|
|
945
|
+
rs,
|
|
946
|
+
judge,
|
|
947
|
+
would_send,
|
|
948
|
+
judged,
|
|
949
|
+
spot_pool,
|
|
950
|
+
files[i]["file"],
|
|
951
|
+
results,
|
|
952
|
+
mresults,
|
|
953
|
+
limits,
|
|
954
|
+
)
|
|
955
|
+
finally:
|
|
956
|
+
rs.close()
|
|
957
|
+
for (i, name), res in results.items():
|
|
958
|
+
_set(
|
|
959
|
+
next(f for f in files[i]["functions"] if f["function"] == name),
|
|
960
|
+
res,
|
|
961
|
+
opts.judged_accepted,
|
|
962
|
+
)
|
|
963
|
+
for (i, name), res in mresults.items():
|
|
964
|
+
files[i]["models"].append({"model": name, **res})
|
|
965
|
+
if only is None:
|
|
966
|
+
for fl in files:
|
|
967
|
+
_file_rung(fl, opts.judged_accepted)
|
|
968
|
+
return _doc_part(opts, judge, would_send, judged, spot_pool, limits, notes)
|
|
969
|
+
|
|
970
|
+
|
|
971
|
+
def _run_module(
|
|
972
|
+
i,
|
|
973
|
+
u,
|
|
974
|
+
plans,
|
|
975
|
+
mplans,
|
|
976
|
+
tree,
|
|
977
|
+
opts,
|
|
978
|
+
work,
|
|
979
|
+
rs,
|
|
980
|
+
judge,
|
|
981
|
+
would_send,
|
|
982
|
+
judged,
|
|
983
|
+
spot_pool,
|
|
984
|
+
fname,
|
|
985
|
+
results,
|
|
986
|
+
mresults,
|
|
987
|
+
limits,
|
|
988
|
+
):
|
|
989
|
+
py_path = _scratch_copy(work, u.module, i)
|
|
990
|
+
sig = {n: {"params": [list(t) for t in p.params], "ret": list(p.ret)} for n, p in plans.items()}
|
|
991
|
+
models = {
|
|
992
|
+
n: {"kind": m.kind, "fields": [[a, list(b), c] for a, b, c in m.fields]}
|
|
993
|
+
for n, m in mplans.items()
|
|
994
|
+
}
|
|
995
|
+
extra = [
|
|
996
|
+
str(Path(py_path).parent),
|
|
997
|
+
*os.environ.get("PYTHONPATH", "").split(os.pathsep),
|
|
998
|
+
*opts.python_path,
|
|
999
|
+
]
|
|
1000
|
+
runner = PythonRunner(
|
|
1001
|
+
py_path,
|
|
1002
|
+
sig,
|
|
1003
|
+
models,
|
|
1004
|
+
timeout=opts.call_timeout,
|
|
1005
|
+
memory_mb=opts.memory_mb,
|
|
1006
|
+
cwd=work,
|
|
1007
|
+
extra_path=[p for p in extra if p],
|
|
1008
|
+
)
|
|
1009
|
+
info = runner.start()
|
|
1010
|
+
try:
|
|
1011
|
+
if "ok" not in info:
|
|
1012
|
+
detail = info.get("kind") or info.get("err") or "runner failed"
|
|
1013
|
+
why = f"the Python module could not be loaded: {detail}: {info.get('msg', info)}"
|
|
1014
|
+
for n in plans:
|
|
1015
|
+
results[(i, n)] = _result("not-applicable", why)
|
|
1016
|
+
for n in mplans:
|
|
1017
|
+
mresults[(i, n)] = _result("not-applicable", why)
|
|
1018
|
+
return limits
|
|
1019
|
+
limits = info.get("limits", limits)
|
|
1020
|
+
ctx = Ctx(opts, runner, rs, judge, would_send, judged, spot_pool, fname)
|
|
1021
|
+
for n, plan in plans.items():
|
|
1022
|
+
if n in info.get("missing", []):
|
|
1023
|
+
results[(i, n)] = _result(
|
|
1024
|
+
"not-applicable", "the function is not defined at import time"
|
|
1025
|
+
)
|
|
1026
|
+
continue
|
|
1027
|
+
doc_items: list[tuple[str, list[list[Any]]]] = []
|
|
1028
|
+
if tree is not None:
|
|
1029
|
+
doc_items.append(("doctest", doc_cases(tree, plan)[:_DOC_CAP]))
|
|
1030
|
+
doc_items.append(("test", test_file_cases(Path(py_path), plan)[:_TEST_CAP]))
|
|
1031
|
+
results[(i, n)] = run_function(plan, doc_items, ctx)
|
|
1032
|
+
for n, m in mplans.items():
|
|
1033
|
+
if m.rust_ok is None and tree is not None:
|
|
1034
|
+
mresults[(i, n)] = run_model(m, mplans, ctx)
|
|
1035
|
+
elif m.rust_ok is not None:
|
|
1036
|
+
mresults[(i, n)] = _result("not-applicable", m.rust_ok)
|
|
1037
|
+
return limits
|
|
1038
|
+
finally:
|
|
1039
|
+
runner.close()
|
|
1040
|
+
|
|
1041
|
+
|
|
1042
|
+
def _file_rung(fl: dict[str, Any], accept_judged: bool) -> None:
|
|
1043
|
+
funcs = [f for f in fl["functions"] if f["kind"] == "function"]
|
|
1044
|
+
stats = [f.get("equiv") for f in funcs] + [m["equiv"] for m in fl.get("models", [])]
|
|
1045
|
+
n = Counter(s for s in stats if s)
|
|
1046
|
+
if n["failed"]:
|
|
1047
|
+
status, detail = "fail", f"{n['failed']} function(s)/model(s) differ from the Python"
|
|
1048
|
+
elif n["needs-judgement"]:
|
|
1049
|
+
status, detail = "unverified", f"{n['needs-judgement']} need judgement (no judge verdict)"
|
|
1050
|
+
elif n["passed-judged"] and not accept_judged:
|
|
1051
|
+
status, detail = (
|
|
1052
|
+
"unverified",
|
|
1053
|
+
(
|
|
1054
|
+
f"{n['passed-judged']} passed only by the judge (rerun with --accept-judged to accept)"
|
|
1055
|
+
),
|
|
1056
|
+
)
|
|
1057
|
+
elif n["passed"] or n["passed-judged"]:
|
|
1058
|
+
status, detail = "pass", f"{n['passed'] + n['passed-judged']} equivalent"
|
|
1059
|
+
else:
|
|
1060
|
+
status, detail = "skipped", "no function was applicable to equivalence testing"
|
|
1061
|
+
fl["rungs"]["equiv"] = {"status": status, "errors": n["failed"], "detail": detail}
|
|
1062
|
+
|
|
1063
|
+
|
|
1064
|
+
def _doc_part(
|
|
1065
|
+
opts: EquivOptions,
|
|
1066
|
+
judge: Judge | None,
|
|
1067
|
+
would_send: list,
|
|
1068
|
+
judged: list,
|
|
1069
|
+
spot_pool: list[JudgeCase],
|
|
1070
|
+
limits: dict,
|
|
1071
|
+
notes: list[str],
|
|
1072
|
+
) -> dict[str, Any]:
|
|
1073
|
+
spot: dict[str, Any] = {
|
|
1074
|
+
"requested": opts.spot_check,
|
|
1075
|
+
"sampled": 0,
|
|
1076
|
+
"disagreements": 0,
|
|
1077
|
+
"estimated_false_pass_rate": None,
|
|
1078
|
+
"reason": None,
|
|
1079
|
+
}
|
|
1080
|
+
if opts.spot_check:
|
|
1081
|
+
if judge is None:
|
|
1082
|
+
spot["reason"] = "no judge backend configured"
|
|
1083
|
+
elif not spot_pool:
|
|
1084
|
+
spot["reason"] = "no judged passes to sample"
|
|
1085
|
+
else:
|
|
1086
|
+
sample = random.Random(opts.seed).sample(
|
|
1087
|
+
spot_pool, min(opts.spot_check, len(spot_pool))
|
|
1088
|
+
)
|
|
1089
|
+
bad = sum(judge.spot_check(c).verdict != "same" for c in sample)
|
|
1090
|
+
spot.update(
|
|
1091
|
+
sampled=len(sample),
|
|
1092
|
+
disagreements=bad,
|
|
1093
|
+
estimated_false_pass_rate=round(bad / len(sample), 3),
|
|
1094
|
+
)
|
|
1095
|
+
# off: strict mode never asks; dry-run: nothing is sent, leftovers are listed
|
|
1096
|
+
mode = "on" if judge is not None else "off" if opts.compare == "strict" else "dry-run"
|
|
1097
|
+
return {
|
|
1098
|
+
"equiv": {
|
|
1099
|
+
"compare": opts.compare,
|
|
1100
|
+
"inputs_per_function": opts.inputs,
|
|
1101
|
+
"seed": opts.seed,
|
|
1102
|
+
"hypothesis": opts.use_hypothesis and hypothesis_available(),
|
|
1103
|
+
"profile": opts.profile.to_dict(),
|
|
1104
|
+
"limits": {
|
|
1105
|
+
"call_timeout_s": opts.call_timeout,
|
|
1106
|
+
"memory_mb": opts.memory_mb,
|
|
1107
|
+
"memory_limit": "rlimit" if limits.get("as") else "rss-watchdog",
|
|
1108
|
+
},
|
|
1109
|
+
"judge": {
|
|
1110
|
+
"mode": mode,
|
|
1111
|
+
"backend": getattr(opts.backend, "name", None),
|
|
1112
|
+
"model": getattr(opts.backend, "model", None),
|
|
1113
|
+
"prompt_version": PROMPT_VERSION,
|
|
1114
|
+
"budget": opts.judge_budget,
|
|
1115
|
+
"calls": judge.calls_used if judge else 0,
|
|
1116
|
+
"cache_hits": judge.cache_hits if judge else 0,
|
|
1117
|
+
"would_send": would_send,
|
|
1118
|
+
},
|
|
1119
|
+
"notes": notes,
|
|
1120
|
+
},
|
|
1121
|
+
"judged": judged,
|
|
1122
|
+
"spot_check": spot,
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
|
|
1126
|
+
# --- summary and apply --------------------------------------------------------------------------
|
|
1127
|
+
|
|
1128
|
+
|
|
1129
|
+
def summary_fields(files: list[dict[str, Any]]) -> dict[str, Any]:
|
|
1130
|
+
"""Headline numbers. `equivalent_by_rules` never includes judged passes."""
|
|
1131
|
+
funcs = [f for fl in files for f in fl["functions"] if f["kind"] == "function"]
|
|
1132
|
+
models = [m for fl in files for m in fl.get("models", [])]
|
|
1133
|
+
ran = [f for f in funcs if "equiv" in f]
|
|
1134
|
+
if not ran:
|
|
1135
|
+
return {
|
|
1136
|
+
k: None
|
|
1137
|
+
for k in (
|
|
1138
|
+
"equivalent_by_rules",
|
|
1139
|
+
"functionally_equivalent",
|
|
1140
|
+
"functions_equiv_applicable",
|
|
1141
|
+
"functions_equiv_failed",
|
|
1142
|
+
"functions_equiv_needs_judgement",
|
|
1143
|
+
"functions_equiv_not_applicable",
|
|
1144
|
+
"equiv_drift_findings",
|
|
1145
|
+
"models_equiv_passed",
|
|
1146
|
+
"models_equiv_total",
|
|
1147
|
+
)
|
|
1148
|
+
}
|
|
1149
|
+
n = Counter(f["equiv"] for f in ran)
|
|
1150
|
+
by_rules = n["passed"]
|
|
1151
|
+
return {
|
|
1152
|
+
"equivalent_by_rules": by_rules,
|
|
1153
|
+
"functionally_equivalent": by_rules + n["passed-judged"],
|
|
1154
|
+
"functions_equiv_applicable": len(ran) - n["not-applicable"],
|
|
1155
|
+
"functions_equiv_failed": n["failed"],
|
|
1156
|
+
"functions_equiv_needs_judgement": n["needs-judgement"],
|
|
1157
|
+
"functions_equiv_not_applicable": n["not-applicable"],
|
|
1158
|
+
"equiv_drift_findings": sum(len(f["equiv_drift"]) for f in ran),
|
|
1159
|
+
"models_equiv_passed": sum(m["equiv"] == "passed" for m in models),
|
|
1160
|
+
"models_equiv_total": len(models),
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
|
|
1164
|
+
def apply_decision(
|
|
1165
|
+
eq: dict[str, Any],
|
|
1166
|
+
*,
|
|
1167
|
+
needs_review: bool,
|
|
1168
|
+
acked: bool,
|
|
1169
|
+
comparable: bool = False,
|
|
1170
|
+
accept_judged: bool = False,
|
|
1171
|
+
) -> tuple[str, str | None]:
|
|
1172
|
+
"""How `apply` treats an equiv result: (accepted | failed | unverified, reason).
|
|
1173
|
+
|
|
1174
|
+
A rules-level pass is always accepted; a judged pass is `unverified` unless `accept_judged`
|
|
1175
|
+
(`--accept-judged` or `[equivalence] accept_judged = true`; `eq["accept_judged"]` carries it
|
|
1176
|
+
from `equiv_for_function`) and, for a TODO flagged needs_review, an explicit `--ack-review`
|
|
1177
|
+
names it (the ack alone also accepts it: it is the per-TODO human voucher); not-applicable
|
|
1178
|
+
does not block (it is reported); failed and needs-judgement block.
|
|
1179
|
+
|
|
1180
|
+
`comparable` says the function was judged comparable beforehand (see `static_applicability`):
|
|
1181
|
+
a `not-applicable` result at run time (the Python would not load, the harness did not build)
|
|
1182
|
+
then means the comparison could not be done, which is `unverified`, never a free pass.
|
|
1183
|
+
"""
|
|
1184
|
+
st = eq["status"]
|
|
1185
|
+
if st == "not-applicable" and comparable:
|
|
1186
|
+
return "unverified", f"equivalence could not be checked ({eq.get('reason')})"
|
|
1187
|
+
if st in ("passed", "not-applicable"):
|
|
1188
|
+
return "accepted", None
|
|
1189
|
+
if st == "passed-judged":
|
|
1190
|
+
if needs_review:
|
|
1191
|
+
if acked:
|
|
1192
|
+
return "accepted", None
|
|
1193
|
+
return "unverified", (
|
|
1194
|
+
"equivalence was established only by the judge and this TODO is flagged needs_review: "
|
|
1195
|
+
"needs a rules-level pass or --ack-review TODO_ID"
|
|
1196
|
+
)
|
|
1197
|
+
if not (accept_judged or eq.get("accept_judged")):
|
|
1198
|
+
return "unverified", (
|
|
1199
|
+
"equivalence was established only by the judge, which is not accepted by default: "
|
|
1200
|
+
"a human decides with --accept-judged (or accept_judged = true under [equivalence] "
|
|
1201
|
+
"in python2rust.toml)"
|
|
1202
|
+
)
|
|
1203
|
+
return "accepted", None
|
|
1204
|
+
if st == "failed":
|
|
1205
|
+
return "failed", f"the patched function differs from the Python: {eq.get('reason')}"
|
|
1206
|
+
return "unverified", f"equivalence unproven ({eq.get('reason')})"
|
|
1207
|
+
|
|
1208
|
+
|
|
1209
|
+
def judged_accepted_by(
|
|
1210
|
+
eq: dict[str, Any], *, needs_review: bool, acked: bool, accept_judged: bool
|
|
1211
|
+
) -> str | None:
|
|
1212
|
+
"""Who vouched for an accepted judged pass, for the `apply` document (None: nobody had to).
|
|
1213
|
+
|
|
1214
|
+
`accept-judged`: a plain function accepted because `--accept-judged` (or the TOML key) was
|
|
1215
|
+
given, which never lifts the needs_review rule; `ack-review`: a needs_review TODO accepted
|
|
1216
|
+
because its id was acknowledged. A rules-level pass, a failure or an unaccepted judged pass
|
|
1217
|
+
has no voucher.
|
|
1218
|
+
"""
|
|
1219
|
+
decision = apply_decision(
|
|
1220
|
+
eq, needs_review=needs_review, acked=acked, accept_judged=accept_judged
|
|
1221
|
+
)[0]
|
|
1222
|
+
if eq["status"] != "passed-judged" or decision != "accepted":
|
|
1223
|
+
return None
|
|
1224
|
+
return "ack-review" if needs_review else "accept-judged"
|
|
1225
|
+
|
|
1226
|
+
|
|
1227
|
+
def equiv_for_function(
|
|
1228
|
+
modules: list[CheckModule],
|
|
1229
|
+
index: int,
|
|
1230
|
+
files: list[dict[str, Any]],
|
|
1231
|
+
function: str,
|
|
1232
|
+
opts: EquivOptions,
|
|
1233
|
+
) -> dict[str, Any]:
|
|
1234
|
+
"""Equivalence of one function of `modules[index]` (the `apply` gate): the `equiv` apply fields.
|
|
1235
|
+
|
|
1236
|
+
`modules` is the whole crate the function lives in (project mode: its import component) and
|
|
1237
|
+
`files` its ladder verdicts; only the one function is compared. A cached judge `same` is never
|
|
1238
|
+
enough here: it is asked again (`judge_reconfirm`), so a judged result in the document always
|
|
1239
|
+
has `cached: false`.
|
|
1240
|
+
"""
|
|
1241
|
+
from python2rust.verify.ladder import Unit
|
|
1242
|
+
|
|
1243
|
+
opts = replace(opts, judge_reconfirm=True)
|
|
1244
|
+
fl = files[index]
|
|
1245
|
+
doc = run_equiv([Unit(m) for m in modules], files, opts, only=function, only_file=index)
|
|
1246
|
+
fn = next((f for f in fl["functions"] if f["function"] == function), None)
|
|
1247
|
+
if fn is None or "equiv" not in fn:
|
|
1248
|
+
return {
|
|
1249
|
+
"status": "not-applicable",
|
|
1250
|
+
"reason": "function not found",
|
|
1251
|
+
"inputs": 0,
|
|
1252
|
+
"counterexample": None,
|
|
1253
|
+
"drift": [],
|
|
1254
|
+
"judged": [],
|
|
1255
|
+
}
|
|
1256
|
+
return {
|
|
1257
|
+
"accept_judged": opts.judged_accepted,
|
|
1258
|
+
"status": fn["equiv"],
|
|
1259
|
+
"reason": fn["equiv_reason"],
|
|
1260
|
+
"inputs": fn["equiv_inputs"],
|
|
1261
|
+
"counterexample": fn["equiv_counterexample"],
|
|
1262
|
+
"drift": fn["equiv_drift"],
|
|
1263
|
+
"judged": [j for j in doc["judged"] if j["function"] == function],
|
|
1264
|
+
}
|