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,441 @@
|
|
|
1
|
+
"""The repair loop behind `python2rust port`: a pure engine with injectable fixers.
|
|
2
|
+
|
|
3
|
+
One round: check the whole crate once, group the errors by function, give each failing function to
|
|
4
|
+
the cheapest fixer that still applies, vet every candidate on its own (anti-cheat gate, brace balance,
|
|
5
|
+
the workspace's parse check), stage the survivors, check once more, and keep a candidate only if its
|
|
6
|
+
own function is clean afterwards and nothing got worse anywhere else. A failure that cannot be pinned
|
|
7
|
+
on one function (a syntax error, a new unattributed error, a new error in an untouched function) rolls
|
|
8
|
+
the staged candidates back and settles them again in halves, so one bad candidate can neither hide the
|
|
9
|
+
errors of the others nor ride along with them. Nothing here touches the
|
|
10
|
+
disk, cargo or the network: the `Workspace` and the `Fixer`s are injected, so tests drive it with
|
|
11
|
+
fakes. Fixers are tried in cost order (stored fix, deterministic autofix, small model, strong model);
|
|
12
|
+
a function moves to the next fixer after its attempts at one are used up and is retired to the review
|
|
13
|
+
queue when none is left.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import re
|
|
19
|
+
import time
|
|
20
|
+
from collections import Counter
|
|
21
|
+
from collections.abc import Callable, Sequence
|
|
22
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
from typing import Any, Protocol
|
|
25
|
+
|
|
26
|
+
from python2rust.agent.patches import (
|
|
27
|
+
constant_body_violations,
|
|
28
|
+
constant_body_warnings,
|
|
29
|
+
gate,
|
|
30
|
+
strip_noise,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class Err:
|
|
36
|
+
"""A compiler error attributed to a function (`suggestions` are rustc edits: byte spans)."""
|
|
37
|
+
|
|
38
|
+
code: str | None
|
|
39
|
+
message: str
|
|
40
|
+
rust_line: int | None = None
|
|
41
|
+
python_line: int | None = None
|
|
42
|
+
suggestions: tuple[dict[str, Any], ...] = ()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Failure:
|
|
47
|
+
"""A function that does not verify: it has compile errors and/or an open `todo!()`."""
|
|
48
|
+
|
|
49
|
+
key: str # "<file>::<function>"
|
|
50
|
+
file: str
|
|
51
|
+
function: str
|
|
52
|
+
python: str # the Python function's source
|
|
53
|
+
python_line: int
|
|
54
|
+
rust: str # the Rust function as generated (with any applied patches)
|
|
55
|
+
rust_line: int
|
|
56
|
+
errors: list[Err] = field(default_factory=list)
|
|
57
|
+
todos: int = 0
|
|
58
|
+
body: str = "" # text between the function's outer braces
|
|
59
|
+
# for deterministic autofix: the module text and the body's byte span inside it
|
|
60
|
+
file_text: str = ""
|
|
61
|
+
body_span: tuple[int, int] = (0, 0)
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def badness(self) -> int:
|
|
65
|
+
return len(self.errors) + self.todos
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass
|
|
69
|
+
class Report:
|
|
70
|
+
failures: dict[str, Failure] = field(default_factory=dict)
|
|
71
|
+
unattributed: list[Err] = field(default_factory=list) # errors outside any function
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def total(self) -> int:
|
|
75
|
+
return sum(f.badness for f in self.failures.values()) + len(self.unattributed)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass
|
|
79
|
+
class Candidate:
|
|
80
|
+
body: str
|
|
81
|
+
tokens: int = 0
|
|
82
|
+
note: str = ""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass
|
|
86
|
+
class Attempt:
|
|
87
|
+
"""What a fixer tried for a function and why it was not kept (fed back to later fixers)."""
|
|
88
|
+
|
|
89
|
+
fixer: str
|
|
90
|
+
outcome: (
|
|
91
|
+
str # no-candidate | gate | invalid | still-failing | not-better | breaks-other | error
|
|
92
|
+
)
|
|
93
|
+
detail: str = ""
|
|
94
|
+
body: str = ""
|
|
95
|
+
errors: list[Err] = field(default_factory=list)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class Fixer(Protocol):
|
|
99
|
+
name: str # tier name in the round log: overlay | autofix | agent | agent-strong
|
|
100
|
+
paid: bool # costs tokens / leaves the machine
|
|
101
|
+
max_attempts: int | None # per function; None = the loop's escalate_after
|
|
102
|
+
est_tokens: int
|
|
103
|
+
|
|
104
|
+
def applicable(self, f: Failure) -> bool: ...
|
|
105
|
+
def propose(self, f: Failure, history: Sequence[Attempt]) -> Candidate | None: ...
|
|
106
|
+
def task(self, f: Failure, history: Sequence[Attempt]) -> dict[str, Any]:
|
|
107
|
+
"""The exact request that would be sent (used by the dry run)."""
|
|
108
|
+
...
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class Workspace(Protocol):
|
|
112
|
+
def validate(self, key: str, body: str) -> str | None:
|
|
113
|
+
"""Why `body` is not a function body that parses in place (None: it parses)."""
|
|
114
|
+
...
|
|
115
|
+
|
|
116
|
+
def check(self) -> Report: ...
|
|
117
|
+
def stage(self, key: str, body: str) -> None: ...
|
|
118
|
+
def unstage(self, key: str) -> None: ...
|
|
119
|
+
def commit(self, key: str, tier: str, note: str) -> None: ...
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@dataclass
|
|
123
|
+
class Budget:
|
|
124
|
+
iterations: int = 8
|
|
125
|
+
tokens: int | None = None
|
|
126
|
+
seconds: float | None = None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def brace_problem(body: str) -> str | None:
|
|
130
|
+
"""Why the braces of `body` do not balance (comments, strings and chars do not count), or None."""
|
|
131
|
+
depth = 0
|
|
132
|
+
for n, line in enumerate(strip_noise(body).splitlines(), 1):
|
|
133
|
+
for c in line:
|
|
134
|
+
depth += (c == "{") - (c == "}")
|
|
135
|
+
if depth < 0:
|
|
136
|
+
return f"unbalanced braces: a closing brace on line {n} has no opening brace"
|
|
137
|
+
return f"unbalanced braces: {depth} opening brace(s) never closed" if depth else None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _shape(msg: str) -> str:
|
|
141
|
+
return re.sub(r"\d+", "#", msg) # line numbers move when a body above grows or shrinks
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _loose(r: Report) -> dict[str, tuple[int, str]]:
|
|
145
|
+
"""Errors a single function cannot own: unattributed ones and failures without a rustc code."""
|
|
146
|
+
out: dict[str, tuple[int, str]] = {}
|
|
147
|
+
errs = [e for f in r.failures.values() for e in f.errors if e.code is None] + r.unattributed
|
|
148
|
+
for e in errs:
|
|
149
|
+
n, _ = out.get(_shape(e.message), (0, e.message))
|
|
150
|
+
out[_shape(e.message)] = (n + 1, e.message)
|
|
151
|
+
return out
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _crate_problem(after: Report, before: Report, own: set[str]) -> tuple[str, str] | None:
|
|
155
|
+
"""Why `after` (the staged functions `own` applied) is worse than `before` in a way that no single
|
|
156
|
+
staged function's own errors explain: a new error without a rustc code (a syntax error aborts
|
|
157
|
+
the whole crate), a new unattributed error, or more problems in a function nobody staged.
|
|
158
|
+
Returns (attempt outcome, detail)."""
|
|
159
|
+
for key, f in sorted(after.failures.items()):
|
|
160
|
+
was = before.failures[key].badness if key in before.failures else 0
|
|
161
|
+
if key not in own and f.badness > was:
|
|
162
|
+
return (
|
|
163
|
+
"breaks-other",
|
|
164
|
+
f"it breaks {f.function}: {f.errors[0].message if f.errors else 'a new todo!()'}",
|
|
165
|
+
)
|
|
166
|
+
old = _loose(before)
|
|
167
|
+
for shape, (n, message) in sorted(_loose(after).items()):
|
|
168
|
+
if n > old.get(shape, (0, ""))[0]:
|
|
169
|
+
return "invalid", f"it breaks the crate: {message}"
|
|
170
|
+
return None
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@dataclass
|
|
174
|
+
class _State:
|
|
175
|
+
tier: int = 0
|
|
176
|
+
used: int = 0
|
|
177
|
+
history: list[Attempt] = field(default_factory=list)
|
|
178
|
+
retired: str | None = None
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@dataclass
|
|
182
|
+
class LoopResult:
|
|
183
|
+
status: str # converged | exhausted | budget | no_progress | dry_run
|
|
184
|
+
rounds: list[dict[str, Any]]
|
|
185
|
+
report: Report
|
|
186
|
+
review_queue: list[dict[str, Any]]
|
|
187
|
+
tokens: int
|
|
188
|
+
seconds: float
|
|
189
|
+
tasks: list[dict[str, Any]]
|
|
190
|
+
budget_hit: str | None = None
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def run(
|
|
194
|
+
ws: Workspace,
|
|
195
|
+
fixers: Sequence[Fixer],
|
|
196
|
+
*,
|
|
197
|
+
budget: Budget | None = None,
|
|
198
|
+
escalate_after: int = 2,
|
|
199
|
+
patience: int = 2,
|
|
200
|
+
workers: int = 4,
|
|
201
|
+
allow: Sequence[str] = (),
|
|
202
|
+
dry_run: bool = False,
|
|
203
|
+
clock: Callable[[], float] = time.monotonic,
|
|
204
|
+
start_round: int = 0,
|
|
205
|
+
) -> LoopResult:
|
|
206
|
+
budget = budget or Budget()
|
|
207
|
+
t0 = clock()
|
|
208
|
+
state: dict[str, _State] = {}
|
|
209
|
+
rounds: list[dict[str, Any]] = []
|
|
210
|
+
tasks: list[dict[str, Any]] = []
|
|
211
|
+
listed: set[tuple[str, str]] = set()
|
|
212
|
+
tokens = 0
|
|
213
|
+
stall = 0
|
|
214
|
+
report = ws.check()
|
|
215
|
+
status, budget_hit = "converged", None
|
|
216
|
+
|
|
217
|
+
def limit(f: Fixer) -> int:
|
|
218
|
+
return f.max_attempts if f.max_attempts is not None else escalate_after
|
|
219
|
+
|
|
220
|
+
while True:
|
|
221
|
+
if not report.failures:
|
|
222
|
+
status = "converged" if not report.unattributed else "exhausted"
|
|
223
|
+
break
|
|
224
|
+
if len(rounds) >= budget.iterations:
|
|
225
|
+
status, budget_hit = "budget", "iterations"
|
|
226
|
+
break
|
|
227
|
+
if budget.seconds is not None and clock() - t0 >= budget.seconds:
|
|
228
|
+
status, budget_hit = "budget", "seconds"
|
|
229
|
+
break
|
|
230
|
+
if budget.tokens is not None and tokens >= budget.tokens:
|
|
231
|
+
status, budget_hit = "budget", "tokens"
|
|
232
|
+
break
|
|
233
|
+
|
|
234
|
+
# 1. pick the cheapest applicable fixer for every active failing function
|
|
235
|
+
jobs: list[tuple[str, Fixer]] = []
|
|
236
|
+
reserved = 0
|
|
237
|
+
for key in sorted(report.failures):
|
|
238
|
+
f, st = report.failures[key], state.setdefault(key, _State())
|
|
239
|
+
while (
|
|
240
|
+
st.retired is None and st.tier < len(fixers) and not fixers[st.tier].applicable(f)
|
|
241
|
+
):
|
|
242
|
+
st.tier, st.used = st.tier + 1, 0
|
|
243
|
+
if st.retired is None and st.tier >= len(fixers):
|
|
244
|
+
st.retired = "no fixer applies" if not st.history else "all fixers exhausted"
|
|
245
|
+
if st.retired is not None:
|
|
246
|
+
continue
|
|
247
|
+
fx = fixers[st.tier]
|
|
248
|
+
if (
|
|
249
|
+
fx.paid
|
|
250
|
+
and budget.tokens is not None
|
|
251
|
+
and tokens + reserved + fx.est_tokens > budget.tokens
|
|
252
|
+
):
|
|
253
|
+
continue # cannot afford this one; may still afford a cheaper one later
|
|
254
|
+
reserved += fx.est_tokens if fx.paid else 0
|
|
255
|
+
jobs.append((key, fx))
|
|
256
|
+
if not jobs:
|
|
257
|
+
status = (
|
|
258
|
+
"exhausted" if all(s.retired for s in state.values()) or not state else "budget"
|
|
259
|
+
)
|
|
260
|
+
budget_hit = "tokens" if status == "budget" else None
|
|
261
|
+
break
|
|
262
|
+
if dry_run:
|
|
263
|
+
paid = [(k, fx) for k, fx in jobs if fx.paid]
|
|
264
|
+
for key, fx in paid:
|
|
265
|
+
if (key, fx.name) not in listed:
|
|
266
|
+
listed.add((key, fx.name))
|
|
267
|
+
tasks.append(fx.task(report.failures[key], state[key].history))
|
|
268
|
+
jobs = [(k, fx) for k, fx in jobs if not fx.paid]
|
|
269
|
+
if not jobs:
|
|
270
|
+
status = "dry_run"
|
|
271
|
+
break
|
|
272
|
+
|
|
273
|
+
# 2. run the fixers (bounded pool; results are consumed in key order => deterministic)
|
|
274
|
+
def call(job: tuple[str, Fixer], current: Report = report) -> tuple[Candidate | None, str]:
|
|
275
|
+
key, fx = job
|
|
276
|
+
try:
|
|
277
|
+
return fx.propose(current.failures[key], state[key].history), ""
|
|
278
|
+
except Exception as exc: # a failing backend must not kill the loop
|
|
279
|
+
return None, f"{type(exc).__name__}: {exc}"
|
|
280
|
+
|
|
281
|
+
with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
|
|
282
|
+
outcomes = list(pool.map(call, jobs))
|
|
283
|
+
|
|
284
|
+
before = report
|
|
285
|
+
entry: dict[str, Any] = {
|
|
286
|
+
"round": start_round + len(rounds) + 1,
|
|
287
|
+
"errors_before": before.total,
|
|
288
|
+
"failing_before": len(before.failures),
|
|
289
|
+
"tasks": len(jobs),
|
|
290
|
+
"fixed": Counter(),
|
|
291
|
+
"rejected": 0,
|
|
292
|
+
"gate_rejected": 0,
|
|
293
|
+
"invalid": 0,
|
|
294
|
+
"gate_warnings": 0,
|
|
295
|
+
"tokens": 0,
|
|
296
|
+
}
|
|
297
|
+
staged: list[tuple[str, Fixer, Candidate]] = []
|
|
298
|
+
failed: list[tuple[str, Fixer, Attempt]] = []
|
|
299
|
+
for (key, fx), (cand, error) in zip(jobs, outcomes, strict=True):
|
|
300
|
+
if cand is not None:
|
|
301
|
+
tokens += cand.tokens
|
|
302
|
+
entry["tokens"] += cand.tokens
|
|
303
|
+
if cand is None:
|
|
304
|
+
failed.append(
|
|
305
|
+
(key, fx, Attempt(fx.name, "error" if error else "no-candidate", error))
|
|
306
|
+
)
|
|
307
|
+
continue
|
|
308
|
+
sig = before.failures[key]
|
|
309
|
+
# an unbalanced body is reported as `invalid` below, not as a gate verdict
|
|
310
|
+
violations = [
|
|
311
|
+
v
|
|
312
|
+
for v in gate(cand.body, allow)
|
|
313
|
+
if v["token"] != "structure" or not brace_problem(cand.body)
|
|
314
|
+
]
|
|
315
|
+
# a body that is only a constant and ignores what the Python uses is a placeholder, as
|
|
316
|
+
# in `apply`: it compiles, which is exactly why it is not accepted
|
|
317
|
+
violations += constant_body_violations(cand.body, sig.rust, sig.python, allow)
|
|
318
|
+
if violations:
|
|
319
|
+
entry["gate_rejected"] += 1
|
|
320
|
+
v = violations[0]
|
|
321
|
+
failed.append(
|
|
322
|
+
(key, fx, Attempt(fx.name, "gate", f"{v['token']}: {v['message']}", cand.body))
|
|
323
|
+
)
|
|
324
|
+
continue
|
|
325
|
+
if reason := brace_problem(cand.body) or ws.validate(key, cand.body):
|
|
326
|
+
entry["invalid"] += 1
|
|
327
|
+
failed.append((key, fx, Attempt(fx.name, "invalid", reason, cand.body)))
|
|
328
|
+
continue
|
|
329
|
+
entry["gate_warnings"] += len(constant_body_warnings(cand.body, sig.rust, sig.python))
|
|
330
|
+
ws.stage(key, cand.body)
|
|
331
|
+
staged.append((key, fx, cand))
|
|
332
|
+
|
|
333
|
+
# 3. check all staged candidates once; keep a candidate only if its function is clean and
|
|
334
|
+
# nothing else got worse. A failure nobody can own rolls back and settles in halves.
|
|
335
|
+
stale = False # the crate on disk still holds a candidate that was rolled back
|
|
336
|
+
|
|
337
|
+
def settle(
|
|
338
|
+
group: list[tuple[str, Fixer, Candidate]],
|
|
339
|
+
base: Report,
|
|
340
|
+
checked: Report | None = None,
|
|
341
|
+
entry: dict[str, Any] = entry,
|
|
342
|
+
failed: list[tuple[str, Fixer, Attempt]] = failed,
|
|
343
|
+
) -> Report:
|
|
344
|
+
"""Decide `group` against `base` (the committed state); returns the committed state."""
|
|
345
|
+
nonlocal stale
|
|
346
|
+
if checked is None:
|
|
347
|
+
for key, _, cand in group:
|
|
348
|
+
ws.stage(key, cand.body)
|
|
349
|
+
checked, stale = ws.check(), False
|
|
350
|
+
problem = _crate_problem(checked, base, {key for key, _, _ in group})
|
|
351
|
+
if problem and len(group) > 1:
|
|
352
|
+
for key, _, _ in group:
|
|
353
|
+
ws.unstage(key)
|
|
354
|
+
mid = len(group) // 2
|
|
355
|
+
for half in (group[:mid], group[mid:]):
|
|
356
|
+
base = settle(half, base)
|
|
357
|
+
return base
|
|
358
|
+
rejected_any = False
|
|
359
|
+
for key, fx, cand in group:
|
|
360
|
+
now = checked.failures[key].badness if key in checked.failures else 0
|
|
361
|
+
was = base.failures[key].badness if key in base.failures else 0
|
|
362
|
+
if now == 0 and not problem:
|
|
363
|
+
ws.commit(key, fx.name, cand.note)
|
|
364
|
+
entry["fixed"][fx.name] += 1
|
|
365
|
+
state[key].used = 0
|
|
366
|
+
state[key].history.clear()
|
|
367
|
+
continue
|
|
368
|
+
ws.unstage(key)
|
|
369
|
+
rejected_any = True
|
|
370
|
+
errs = list(checked.failures[key].errors) if key in checked.failures else []
|
|
371
|
+
if problem:
|
|
372
|
+
entry["invalid" if problem[0] == "invalid" else "rejected"] += 1
|
|
373
|
+
attempt = Attempt(fx.name, problem[0], problem[1], cand.body, errs)
|
|
374
|
+
else:
|
|
375
|
+
entry["rejected"] += 1
|
|
376
|
+
left = f"{now} problem(s) of {was} left"
|
|
377
|
+
outcome = "still-failing" if now < was else "not-better"
|
|
378
|
+
attempt = Attempt(fx.name, outcome, left, cand.body, errs)
|
|
379
|
+
failed.append((key, fx, attempt))
|
|
380
|
+
if problem: # the only candidate was rolled back: the report is still `base`
|
|
381
|
+
stale = True
|
|
382
|
+
return base
|
|
383
|
+
if rejected_any:
|
|
384
|
+
checked, stale = ws.check(), False
|
|
385
|
+
return checked
|
|
386
|
+
|
|
387
|
+
after = settle(staged, before, ws.check()) if staged else before
|
|
388
|
+
if stale: # leave the crate as committed, not as the last rejected trial wrote it
|
|
389
|
+
after = ws.check()
|
|
390
|
+
|
|
391
|
+
# 4. escalate / retire functions whose attempt did not stick
|
|
392
|
+
tier_changed = False
|
|
393
|
+
for key, fx, attempt in failed:
|
|
394
|
+
st = state[key]
|
|
395
|
+
st.history.append(attempt)
|
|
396
|
+
st.used += 1
|
|
397
|
+
if st.used >= limit(fx):
|
|
398
|
+
st.tier, st.used = st.tier + 1, 0
|
|
399
|
+
tier_changed = True
|
|
400
|
+
if st.tier >= len(fixers):
|
|
401
|
+
st.retired = "all fixers exhausted"
|
|
402
|
+
entry["errors_after"] = after.total
|
|
403
|
+
entry["failing_after"] = len(after.failures)
|
|
404
|
+
entry["fixed"] = dict(sorted(entry["fixed"].items()))
|
|
405
|
+
rounds.append(entry)
|
|
406
|
+
progress = sum(entry["fixed"].values()) > 0 or after.total < before.total
|
|
407
|
+
report = after
|
|
408
|
+
stall = 0 if progress or tier_changed else stall + 1
|
|
409
|
+
if stall >= patience:
|
|
410
|
+
status = "no_progress"
|
|
411
|
+
break
|
|
412
|
+
if dry_run and not progress and not tier_changed:
|
|
413
|
+
status = "dry_run"
|
|
414
|
+
break
|
|
415
|
+
|
|
416
|
+
review: list[dict[str, Any]] = [
|
|
417
|
+
{
|
|
418
|
+
"key": k,
|
|
419
|
+
"function": report.failures[k].function,
|
|
420
|
+
"file": report.failures[k].file,
|
|
421
|
+
"python_line": report.failures[k].python_line,
|
|
422
|
+
"reason": s.retired or status,
|
|
423
|
+
"errors": [e.message for e in report.failures[k].errors][:5],
|
|
424
|
+
"todos": report.failures[k].todos,
|
|
425
|
+
}
|
|
426
|
+
for k, s in sorted(state.items())
|
|
427
|
+
if k in report.failures
|
|
428
|
+
]
|
|
429
|
+
review += [
|
|
430
|
+
{
|
|
431
|
+
"key": None,
|
|
432
|
+
"function": None,
|
|
433
|
+
"file": None,
|
|
434
|
+
"python_line": e.python_line,
|
|
435
|
+
"reason": "unattributed",
|
|
436
|
+
"errors": [e.message],
|
|
437
|
+
"todos": 0,
|
|
438
|
+
}
|
|
439
|
+
for e in report.unattributed
|
|
440
|
+
]
|
|
441
|
+
return LoopResult(status, rounds, report, review, tokens, clock() - t0, tasks, budget_hit)
|