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.
Files changed (102) hide show
  1. python2rust/__init__.py +8 -0
  2. python2rust/__main__.py +5 -0
  3. python2rust/_core.py +44 -0
  4. python2rust/agent/__init__.py +0 -0
  5. python2rust/agent/agents.py +333 -0
  6. python2rust/agent/apply.py +516 -0
  7. python2rust/agent/finish.py +295 -0
  8. python2rust/agent/fixers.py +229 -0
  9. python2rust/agent/loop.py +441 -0
  10. python2rust/agent/patches.py +1165 -0
  11. python2rust/agent/port.py +579 -0
  12. python2rust/agent/prompts/judge_v2.md +96 -0
  13. python2rust/agent/review.py +34 -0
  14. python2rust/agent/rustlex.py +232 -0
  15. python2rust/cli/__init__.py +0 -0
  16. python2rust/cli/doctor.py +62 -0
  17. python2rust/cli/inputs.py +105 -0
  18. python2rust/cli/main.py +1162 -0
  19. python2rust/cli/ops.py +642 -0
  20. python2rust/cli/workflow.py +178 -0
  21. python2rust/core/__init__.py +38 -0
  22. python2rust/core/config.py +263 -0
  23. python2rust/core/constructs.py +124 -0
  24. python2rust/core/diagnostics.py +280 -0
  25. python2rust/core/emit/__init__.py +5 -0
  26. python2rust/core/emit/crates.py +51 -0
  27. python2rust/core/emit/render.py +561 -0
  28. python2rust/core/emit/schema.py +168 -0
  29. python2rust/core/emit/translate.py +304 -0
  30. python2rust/core/frontend/__init__.py +1 -0
  31. python2rust/core/frontend/module.py +896 -0
  32. python2rust/core/frontend/names.py +129 -0
  33. python2rust/core/frontend/project.py +277 -0
  34. python2rust/core/frontend/project_imports.py +173 -0
  35. python2rust/core/frontend/symbols.py +132 -0
  36. python2rust/core/frontend/walrus.py +59 -0
  37. python2rust/core/ir/__init__.py +1 -0
  38. python2rust/core/ir/nodes.py +675 -0
  39. python2rust/core/ir/rtypes.py +122 -0
  40. python2rust/core/ir/types.py +326 -0
  41. python2rust/core/lower/__init__.py +1 -0
  42. python2rust/core/lower/calls.py +1125 -0
  43. python2rust/core/lower/context.py +223 -0
  44. python2rust/core/lower/exceptions.py +317 -0
  45. python2rust/core/lower/exprs.py +845 -0
  46. python2rust/core/lower/fstrings.py +141 -0
  47. python2rust/core/lower/funcs.py +276 -0
  48. python2rust/core/lower/lowerer.py +366 -0
  49. python2rust/core/lower/modelcalls.py +195 -0
  50. python2rust/core/lower/models.py +645 -0
  51. python2rust/core/lower/stmts.py +722 -0
  52. python2rust/core/lower/testing.py +601 -0
  53. python2rust/core/lower/validation.py +253 -0
  54. python2rust/core/passes/__init__.py +1 -0
  55. python2rust/core/passes/aliasing.py +311 -0
  56. python2rust/core/passes/analysis.py +207 -0
  57. python2rust/core/passes/devirt.py +329 -0
  58. python2rust/core/passes/ownership.py +259 -0
  59. python2rust/core/passes/raises.py +275 -0
  60. python2rust/core/rt_lib.rs +2071 -0
  61. python2rust/data/README.md +81 -0
  62. python2rust/data/py2many_builtins.toml +4744 -0
  63. python2rust/errors.py +28 -0
  64. python2rust/py.typed +0 -0
  65. python2rust/report/__init__.py +0 -0
  66. python2rust/report/constructs.py +31 -0
  67. python2rust/report/contract.py +688 -0
  68. python2rust/report/corpus.py +323 -0
  69. python2rust/report/explain.py +168 -0
  70. python2rust/report/schemas.py +914 -0
  71. python2rust/server/__init__.py +0 -0
  72. python2rust/server/mcp_server.py +289 -0
  73. python2rust/server/mcp_workflow.py +100 -0
  74. python2rust/skill/SKILL.md +214 -0
  75. python2rust/verify/__init__.py +0 -0
  76. python2rust/verify/check.py +1135 -0
  77. python2rust/verify/equiv/__init__.py +1264 -0
  78. python2rust/verify/equiv/compare.py +455 -0
  79. python2rust/verify/equiv/harness.py +505 -0
  80. python2rust/verify/equiv/judge.py +358 -0
  81. python2rust/verify/equiv/procs.py +255 -0
  82. python2rust/verify/equiv/runner.py +248 -0
  83. python2rust/verify/equiv/types.py +543 -0
  84. python2rust/verify/keystore.py +76 -0
  85. python2rust/verify/ladder.py +396 -0
  86. python2rust/verify/sandbox.py +370 -0
  87. python2rust/verify/testrun.py +280 -0
  88. python2rust/workflow/__init__.py +0 -0
  89. python2rust/workflow/brief.py +312 -0
  90. python2rust/workflow/interview.py +366 -0
  91. python2rust/workflow/layout.py +103 -0
  92. python2rust/workflow/planner.py +409 -0
  93. python2rust/workflow/project.py +134 -0
  94. python2rust/workflow/schemas.py +265 -0
  95. python2rust/workflow/state.py +392 -0
  96. python2rust/workflow/staticscan.py +209 -0
  97. python2rust-0.1.0.dist-info/METADATA +395 -0
  98. python2rust-0.1.0.dist-info/RECORD +102 -0
  99. python2rust-0.1.0.dist-info/WHEEL +4 -0
  100. python2rust-0.1.0.dist-info/entry_points.txt +4 -0
  101. python2rust-0.1.0.dist-info/licenses/LICENSE +21 -0
  102. python2rust-0.1.0.dist-info/licenses/NOTICE +65 -0
@@ -0,0 +1,358 @@
1
+ """LLM judge for equivalence pairs the deterministic rules could not settle (prompt: judge_v2).
2
+
3
+ The judge only sees one function's source (and optionally the Rust source, comments removed) plus
4
+ the case values (arguments, both outputs, the rule-level diff). Everything it sees is untrusted
5
+ text (the Rust is written by an agent, the outputs by the code under test): code fences are
6
+ neutralised and every field sits between markers carrying a random per-call token the content
7
+ cannot know. It never reads files or the environment. Every call
8
+ is temperature 0. Because a wrong `same` is the costly error, a primary `same` must be confirmed by
9
+ a second, independently phrased call with the outputs swapped; anything else (`different`,
10
+ `unsure`, ill-formed output, disagreement) is `different`. `unjudged` is not a verdict about the
11
+ pair: the budget ran out or the backend failed.
12
+
13
+ Verdicts are cached outside the project (`default_cache_dir()`: the per-user cache directory next
14
+ to the keystore secret), keyed by everything a verdict depends on (both sources, the arguments,
15
+ both outputs, the profile, the prompt version, the backend and the model), and every entry carries
16
+ an HMAC under that secret: an entry edited by hand, copied from another machine or moved to another
17
+ key does not verify and is ignored. A cached `same` is not trusted for long (`CACHE_MAX_AGE`) and,
18
+ where the caller asks (`reconfirm_same`, which `apply` does), not at all: it is asked again with the
19
+ double call. The cache saves calls; it is never the reason a fix is accepted.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import hashlib
25
+ import json
26
+ import os
27
+ import re
28
+ import secrets
29
+ import time
30
+ from dataclasses import asdict, dataclass, replace
31
+ from importlib.resources import files
32
+ from pathlib import Path
33
+ from typing import Any
34
+
35
+ from python2rust.agent.agents import Backend, extract_json_object
36
+ from python2rust.agent.rustlex import LexError, lex
37
+
38
+ PROMPT_VERSION = "judge_v2"
39
+ CACHE_MAX_AGE = 7 * 24 * 3600 # seconds a cached `same` stays usable
40
+ _MAC_PURPOSE = "judge-cache"
41
+ VERDICTS = ("same", "different", "unsure")
42
+
43
+ _SECTION = re.compile(r"^<!-- (system|user:primary|user:confirm|user:spot) -->[ \t]*$", re.M)
44
+ _PLACEHOLDER = re.compile(r"\{\{(\w+)\}\}")
45
+
46
+
47
+ @dataclass
48
+ class JudgeCase:
49
+ function: str
50
+ python_source: str
51
+ rust_source: str | None
52
+ args: list[Any]
53
+ python_output: Any
54
+ rust_output: Any
55
+ diff: list[dict[str, Any]]
56
+
57
+
58
+ @dataclass
59
+ class JudgeResult:
60
+ verdict: str # same | different | unjudged
61
+ reason: str
62
+ confidence: float | None
63
+ calls: int
64
+ cached: bool
65
+ confirmed: bool
66
+
67
+
68
+ class _Unjudged(Exception):
69
+ """The budget ran out or the backend failed: no verdict about the pair."""
70
+
71
+
72
+ def load_prompts() -> dict[str, str]:
73
+ """The system prompt and user templates from prompts/judge_v2.md, keyed by section name."""
74
+ text = (
75
+ files("python2rust")
76
+ .joinpath(f"agent/prompts/{PROMPT_VERSION}.md")
77
+ .read_text(encoding="utf-8")
78
+ )
79
+ parts = _SECTION.split(text) # [preamble, name, body, name, body, ...]
80
+ return {name: body.strip("\n") for name, body in zip(parts[1::2], parts[2::2], strict=True)}
81
+
82
+
83
+ NO_RUST = "(not provided)"
84
+ UNLEXABLE_RUST = "(Rust source withheld: its comments could not be removed safely)"
85
+ _FENCE = re.compile(r"`{3,}|~{3,}")
86
+
87
+
88
+ def strip_rust_comments(source: str) -> str | None:
89
+ """`source` without line, doc and (nested) block comments; None when it cannot be tokenised.
90
+
91
+ Uses the strict Rust lexer, so a `//` inside a string, char or raw string literal survives and
92
+ a comment-like text can never hide from the stripper. Everything but the comments is kept
93
+ verbatim. Doc comments (`///`, `//!`, `/** */`) carry prose the code under test does not run,
94
+ and are the obvious place to address the judge.
95
+ """
96
+ try:
97
+ tokens = lex(source, strict=True)
98
+ except LexError:
99
+ return None
100
+ out, pos = [], 0
101
+ for t in tokens:
102
+ if t.kind != "comment":
103
+ continue
104
+ out.append(source[pos : t.start])
105
+ out.append("\n" if "\n" in source[t.start : t.end] else " ")
106
+ pos = t.end
107
+ out.append(source[pos:])
108
+ return re.sub(r"[ \t]+\n", "\n", "".join(out))
109
+
110
+
111
+ def _defang(text: str) -> str:
112
+ """Untrusted text may not open or close a code fence in the prompt."""
113
+ return _FENCE.sub("'" * 3, text)
114
+
115
+
116
+ def clean_case(case: JudgeCase) -> JudgeCase:
117
+ """The case as a judge (and a backend's payload) may see it: no Rust comments."""
118
+ if case.rust_source is None:
119
+ return case
120
+ stripped = strip_rust_comments(case.rust_source)
121
+ return replace(case, rust_source=UNLEXABLE_RUST if stripped is None else stripped)
122
+
123
+
124
+ def _now() -> float:
125
+ return time.time()
126
+
127
+
128
+ def default_cache_dir() -> Path:
129
+ """The judge cache: per user and machine, never inside a project (nothing there can edit it
130
+ into a verdict, and it is not committed by accident). `$XDG_CACHE_HOME`-aware."""
131
+ from python2rust.verify import keystore
132
+
133
+ return keystore.secret_path().parent / "judge"
134
+
135
+
136
+ def _dump(value: Any) -> str:
137
+ return json.dumps(value, sort_keys=True, ensure_ascii=False, default=str)
138
+
139
+
140
+ def _render(template: str, values: dict[str, str]) -> str:
141
+ # One pass, so a placeholder-looking string inside the case data is never substituted.
142
+ return _PLACEHOLDER.sub(lambda m: values.get(m[1], m[0]), template)
143
+
144
+
145
+ def _parse(text: str) -> tuple[str, str, float | None]:
146
+ """(verdict, reason, confidence); `unsure` and anything ill-formed collapse to `different`."""
147
+ obj = extract_json_object(text)
148
+ raw = obj.get("verdict") if obj else None
149
+ verdict = raw.strip().lower() if isinstance(raw, str) else ""
150
+ if verdict not in VERDICTS:
151
+ return "different", "ill-formed judge output", None
152
+ reason = obj.get("reason") if obj else None
153
+ reason = reason if isinstance(reason, str) and reason else verdict
154
+ conf = obj.get("confidence") if obj else None
155
+ confidence = (
156
+ min(1.0, max(0.0, float(conf)))
157
+ if isinstance(conf, int | float) and not isinstance(conf, bool) and conf == conf
158
+ else None
159
+ )
160
+ return ("different" if verdict == "unsure" else verdict), reason, confidence
161
+
162
+
163
+ def _token(texts: Any) -> str:
164
+ """A fresh random marker token that occurs in none of the (untrusted) texts."""
165
+ texts = list(texts)
166
+ while True:
167
+ token = secrets.token_hex(8)
168
+ if not any(token in t for t in texts):
169
+ return token
170
+
171
+
172
+ class Judge:
173
+ def __init__(
174
+ self,
175
+ backend: Backend,
176
+ *,
177
+ profile: dict[str, Any] | None = None,
178
+ cache_dir: Path | None = None,
179
+ budget: int = 20,
180
+ model: str = "",
181
+ reconfirm_same: bool = False,
182
+ ):
183
+ self.backend, self.profile, self.cache_dir = backend, profile, cache_dir
184
+ self.budget, self.model = budget, model
185
+ self.reconfirm_same = reconfirm_same # a cached `same` is only a hint: ask again
186
+ self.calls_used = self.cache_hits = self.spot_calls = 0
187
+ self._prompts = load_prompts()
188
+
189
+ def remaining(self) -> int:
190
+ return max(0, self.budget - self.calls_used)
191
+
192
+ def judge(self, case: JudgeCase) -> JudgeResult:
193
+ case = clean_case(case)
194
+ key = self._cache_key(case)
195
+ hit = self._cache_get(key)
196
+ if hit is not None and not (hit["verdict"] == "same" and self.reconfirm_same):
197
+ self.cache_hits += 1
198
+ return JudgeResult(**hit, calls=0, cached=True)
199
+ start = self.calls_used
200
+ try:
201
+ verdict, reason, conf = self._ask(case, "primary", "equiv-judge")
202
+ if verdict == "same":
203
+ v2, r2, c2 = self._ask(case, "confirm", "equiv-judge-confirm")
204
+ calls = self.calls_used - start
205
+ if v2 != "same":
206
+ result = JudgeResult(
207
+ "different",
208
+ f"judge disagreement (primary same, confirmation {v2}): {r2}",
209
+ c2,
210
+ calls,
211
+ False,
212
+ False,
213
+ )
214
+ else:
215
+ confs = [c for c in (conf, c2) if c is not None]
216
+ result = JudgeResult(
217
+ "same", reason, min(confs, default=None), calls, False, True
218
+ )
219
+ else:
220
+ result = JudgeResult("different", reason, conf, 1, False, False)
221
+ except _Unjudged as exc:
222
+ return JudgeResult("unjudged", str(exc), None, self.calls_used - start, False, False)
223
+ self._cache_put(key, result)
224
+ return result
225
+
226
+ def spot_check(self, case: JudgeCase) -> JudgeResult:
227
+ case = clean_case(case)
228
+ try:
229
+ verdict, reason, conf = self._ask(case, "spot", "equiv-judge-spot")
230
+ except _Unjudged as exc:
231
+ return JudgeResult("unjudged", str(exc), None, 0, False, False)
232
+ return JudgeResult(verdict, reason, conf, 1, False, False)
233
+
234
+ # -- internals ---------------------------------------------------------------------------
235
+
236
+ def _ask(self, case: JudgeCase, role: str, kind: str) -> tuple[str, str, float | None]:
237
+ spot = role == "spot"
238
+ if not spot and self.calls_used >= self.budget:
239
+ raise _Unjudged("judge budget exhausted")
240
+ swapped = role == "confirm"
241
+ label_a, label_b = ("Rust", "Python") if swapped else ("Python", "Rust")
242
+ out_a, out_b = (case.python_output, case.rust_output)
243
+ if swapped:
244
+ out_a, out_b = out_b, out_a
245
+ raw = {
246
+ "python_source": case.python_source,
247
+ "rust_source": case.rust_source or NO_RUST,
248
+ "args": json.dumps(case.args, ensure_ascii=False, default=str),
249
+ "output_a": json.dumps(out_a, ensure_ascii=False, default=str),
250
+ "output_b": json.dumps(out_b, ensure_ascii=False, default=str),
251
+ "diff": json.dumps(case.diff, ensure_ascii=False, default=str),
252
+ }
253
+ token = _token(raw.values())
254
+ values = {
255
+ name: (
256
+ f"<<<{token}:{name}>>>\n{_defang(text)}\n<<<END {token}:{name}>>>"
257
+ if name.endswith("source")
258
+ else f"<<<{token}:{name}>>> {_defang(text)} <<<END {token}:{name}>>>"
259
+ )
260
+ for name, text in raw.items()
261
+ }
262
+ user = _render(
263
+ self._prompts[f"user:{role}"],
264
+ {
265
+ **values,
266
+ "token": token,
267
+ "function": case.function,
268
+ "label_a": label_a,
269
+ "label_b": label_b,
270
+ },
271
+ )
272
+ if spot:
273
+ self.spot_calls += 1
274
+ else:
275
+ self.calls_used += 1
276
+ try:
277
+ completion = self.backend.complete(
278
+ kind,
279
+ asdict(case),
280
+ self._prompts["system"],
281
+ user,
282
+ temperature=0.0,
283
+ max_tokens=512,
284
+ )
285
+ except Exception as exc:
286
+ raise _Unjudged(f"judge backend failed: {exc}") from exc
287
+ return _parse(completion.text)
288
+
289
+ def _cache_key(self, case: JudgeCase) -> str:
290
+ name = getattr(self.backend, "name", type(self.backend).__name__)
291
+ parts = [
292
+ case.function,
293
+ hashlib.sha256(case.python_source.encode()).hexdigest(),
294
+ hashlib.sha256(
295
+ " ".join((case.rust_source or "").split()).encode()
296
+ ).hexdigest(), # layout-blind
297
+ _dump(case.args),
298
+ _dump(case.python_output),
299
+ _dump(case.rust_output),
300
+ self.profile,
301
+ PROMPT_VERSION,
302
+ name,
303
+ self.model,
304
+ ]
305
+ return hashlib.sha256(_dump(parts).encode()).hexdigest()
306
+
307
+ @staticmethod
308
+ def _signed(key: str, entry: dict[str, Any]) -> bytes:
309
+ return key.encode() + b"\n" + _dump(entry).encode() # bound to its key: not movable
310
+
311
+ def _cache_get(self, key: str) -> dict[str, Any] | None:
312
+ """The verified entry for `key` (verdict, reason, confidence, confirmed), else None."""
313
+ if self.cache_dir is None:
314
+ return None
315
+ from python2rust.verify import keystore
316
+
317
+ try:
318
+ data = json.loads((self.cache_dir / f"{key}.json").read_text(encoding="utf-8"))
319
+ entry = data["entry"]
320
+ if not keystore.verify_mac(_MAC_PURPOSE, self._signed(key, entry), data["mac"]):
321
+ return None
322
+ if entry["verdict"] not in ("same", "different") or not isinstance(
323
+ entry["reason"], str
324
+ ):
325
+ return None
326
+ if entry["verdict"] == "same":
327
+ age = _now() - float(entry["created"])
328
+ if not entry["confirmed"] or not -60 <= age <= CACHE_MAX_AGE:
329
+ return None # a `same` that was never double-called, stale or from the future
330
+ return {
331
+ "verdict": entry["verdict"],
332
+ "reason": entry["reason"],
333
+ "confidence": entry.get("confidence"),
334
+ "confirmed": bool(entry["confirmed"]),
335
+ }
336
+ except OSError, ValueError, KeyError, TypeError:
337
+ return None
338
+
339
+ def _cache_put(self, key: str, result: JudgeResult) -> None:
340
+ if self.cache_dir is None:
341
+ return
342
+ from python2rust.verify import keystore
343
+
344
+ entry = {
345
+ "verdict": result.verdict,
346
+ "reason": result.reason,
347
+ "confidence": result.confidence,
348
+ "confirmed": result.confirmed,
349
+ "created": _now(),
350
+ }
351
+ try:
352
+ tag = keystore.mac(_MAC_PURPOSE, self._signed(key, entry))
353
+ self.cache_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
354
+ tmp = self.cache_dir / f".{key}.{os.getpid()}.{secrets.token_hex(4)}.tmp"
355
+ tmp.write_text(_dump({"entry": entry, "mac": tag}), encoding="utf-8")
356
+ os.replace(tmp, self.cache_dir / f"{key}.json")
357
+ except OSError:
358
+ pass # no secret, no cache: the verdict still stands for this run
@@ -0,0 +1,255 @@
1
+ """Child processes of `verify --level equiv`: the Python runner and the Rust harness.
2
+
3
+ Both speak JSON lines (replies carry the prefix `@@P2R `; anything else a child prints is ignored).
4
+ `LineProc.request` enforces the per-call timeout by killing the child; the runners restart it and
5
+ report the call as `{"__timeout__": True}` (or `__dead__` / `__memory__` / `__output__`). This
6
+ module starts the runner script as a subprocess and never imports or executes user code itself.
7
+
8
+ A child's output is read in bounded chunks: a line may not exceed `LINE_CAP` bytes and one call may
9
+ not produce more than `CALL_CAP` bytes in all (a `print!` flood without newlines would otherwise
10
+ grow the parent's memory without bound); beyond either the child is killed and the call is reported
11
+ as `{"__output__": "output limit exceeded"}`. Children run in their own session and are killed as a
12
+ process group, so processes the user's code forks do not outlive the run (best effort: a child that
13
+ starts its own session escapes).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import contextlib
19
+ import json
20
+ import os
21
+ import queue
22
+ import signal
23
+ import subprocess
24
+ import sys
25
+ import threading
26
+ import time
27
+ from collections.abc import Callable
28
+ from pathlib import Path
29
+ from typing import Any
30
+
31
+ from python2rust.verify.equiv.harness import scratch_env
32
+
33
+ PREFIX = "@@P2R "
34
+ _PREFIX = PREFIX.encode()
35
+ LINE_CAP = 16 * 1024 * 1024 # bytes in one line, reply or not
36
+ CALL_CAP = 64 * 1024 * 1024 # bytes a child may write while one call is pending
37
+ _CHUNK = 64 * 1024
38
+ _RESTART = (
39
+ "__timeout__",
40
+ "__dead__",
41
+ "__memory__",
42
+ "__output__",
43
+ ) # replies after which a child restarts
44
+ RUNNER = Path(__file__).with_name("runner.py")
45
+
46
+
47
+ def _hook(d: dict[str, Any]) -> Any:
48
+ if len(d) == 1 and "$f" in d and d["$f"] in ("nan", "inf", "-inf"):
49
+ return float(d["$f"])
50
+ return d
51
+
52
+
53
+ def parse_reply(line: str) -> dict[str, Any]:
54
+ """One reply line -> dict (non-finite floats restored, key order kept)."""
55
+ try:
56
+ data = json.loads(line, object_hook=_hook)
57
+ except ValueError:
58
+ return {"__dead__": "garbled output"}
59
+ return data if isinstance(data, dict) else {"__dead__": "garbled output"}
60
+
61
+
62
+ def rss_mb(pid: int) -> float | None:
63
+ """Resident memory of a process in MiB, via `ps` (works on Linux and macOS)."""
64
+ try:
65
+ out = subprocess.run(
66
+ ["ps", "-o", "rss=", "-p", str(pid)], capture_output=True, text=True, timeout=5
67
+ ).stdout.strip()
68
+ return int(out) / 1024 if out else None
69
+ except OSError, ValueError, subprocess.SubprocessError:
70
+ return None
71
+
72
+
73
+ class LineProc:
74
+ """A long-lived child process spoken to in JSON lines."""
75
+
76
+ def __init__(self, argv: list[str], *, cwd: Path) -> None:
77
+ self.proc = subprocess.Popen(
78
+ argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
79
+ cwd=cwd, env=scratch_env(), bufsize=0, start_new_session=os.name != "nt",
80
+ ) # fmt: skip
81
+ self.lines: queue.Queue[str | None] = queue.Queue()
82
+ self.received = 0 # bytes the child wrote since the pending call began
83
+ self.flooded: str | None = None
84
+ threading.Thread(target=self._pump, daemon=True).start()
85
+
86
+ def _pump(self) -> None:
87
+ """Split the child's stdout into lines without ever holding more than a capped line."""
88
+ assert self.proc.stdout is not None
89
+ line, skipping, length = bytearray(), False, 0 # `line` only while it can be a reply
90
+ while True:
91
+ try:
92
+ chunk = self.proc.stdout.read(_CHUNK)
93
+ except OSError, ValueError:
94
+ break
95
+ if not chunk:
96
+ break
97
+ self.received += len(chunk)
98
+ if self.received > CALL_CAP:
99
+ self._flood()
100
+ break
101
+ for piece in chunk.splitlines(keepends=True):
102
+ done = piece.endswith(b"\n")
103
+ length += len(piece)
104
+ if length > LINE_CAP:
105
+ self._flood()
106
+ return
107
+ if not skipping:
108
+ line += piece
109
+ head = bytes(line[: len(_PREFIX)])
110
+ skipping = not _PREFIX.startswith(head) and not head.startswith(_PREFIX)
111
+ if skipping:
112
+ line.clear()
113
+ if done:
114
+ if not skipping and line.startswith(_PREFIX):
115
+ self.lines.put(line[len(_PREFIX) :].decode("utf-8", "replace"))
116
+ line, skipping, length = bytearray(), False, 0
117
+ self.lines.put(None)
118
+
119
+ def _flood(self) -> None:
120
+ self.flooded = "output limit exceeded"
121
+ self._kill_group()
122
+ self.lines.put(None)
123
+
124
+ def _kill_group(self) -> None:
125
+ """SIGKILL the child and everything in its process group (what the user's code forked)."""
126
+ if os.name != "nt":
127
+ with contextlib.suppress(ProcessLookupError, PermissionError):
128
+ os.killpg(self.proc.pid, signal.SIGKILL)
129
+ with contextlib.suppress(ProcessLookupError):
130
+ self.proc.kill()
131
+
132
+ def kill(self) -> None:
133
+ self._kill_group()
134
+ with contextlib.suppress(subprocess.TimeoutExpired):
135
+ self.proc.wait(timeout=5)
136
+
137
+ def request(
138
+ self, obj: dict[str, Any], timeout: float, over_limit: Callable[[int], bool] | None = None
139
+ ) -> dict[str, Any]:
140
+ assert self.proc.stdin is not None
141
+ if self.flooded:
142
+ return {"__output__": self.flooded}
143
+ self.received = 0
144
+ try:
145
+ self.proc.stdin.write((json.dumps(obj, allow_nan=False) + "\n").encode())
146
+ self.proc.stdin.flush()
147
+ except BrokenPipeError, OSError:
148
+ return {"__dead__": self.proc.poll()}
149
+ deadline, last_poll = time.monotonic() + timeout, 0.0
150
+ while True:
151
+ left = deadline - time.monotonic()
152
+ if left <= 0:
153
+ self.kill()
154
+ return {"__timeout__": True}
155
+ try:
156
+ line = self.lines.get(timeout=min(left, 0.1))
157
+ except queue.Empty:
158
+ if over_limit is not None and time.monotonic() - last_poll > 0.25:
159
+ last_poll = time.monotonic()
160
+ if over_limit(self.proc.pid):
161
+ self.kill()
162
+ return {"__memory__": True}
163
+ continue
164
+ if line is None:
165
+ with contextlib.suppress(subprocess.TimeoutExpired):
166
+ self.proc.wait(timeout=5)
167
+ if self.flooded:
168
+ return {"__output__": self.flooded}
169
+ return {"__dead__": self.proc.returncode}
170
+ return parse_reply(line)
171
+
172
+ def close(self) -> None:
173
+ try:
174
+ if self.proc.stdin:
175
+ self.proc.stdin.close()
176
+ self.proc.wait(timeout=2)
177
+ except OSError, subprocess.TimeoutExpired:
178
+ pass
179
+ self.kill() # also reaps what the child forked and left behind
180
+
181
+
182
+ class PythonRunner:
183
+ """The user's module, imported in a child process (`python -I runner.py`)."""
184
+
185
+ def __init__(
186
+ self,
187
+ path: str,
188
+ sig: dict[str, Any],
189
+ models: dict[str, Any],
190
+ *,
191
+ timeout: float,
192
+ memory_mb: int,
193
+ cwd: Path,
194
+ extra_path: list[str],
195
+ ) -> None:
196
+ self.init_req = {
197
+ "op": "init", "path": path, "extra_path": extra_path, "memory_mb": memory_mb,
198
+ "sig": sig, "models": models,
199
+ } # fmt: skip
200
+ self.timeout, self.memory_mb, self.cwd = timeout, memory_mb, cwd
201
+ self.proc: LineProc | None = None
202
+ self.info: dict[str, Any] = {}
203
+ self.restarts = 0
204
+
205
+ def start(self) -> dict[str, Any]:
206
+ self.proc = LineProc([sys.executable, "-I", str(RUNNER)], cwd=self.cwd)
207
+ self.info = self.proc.request(self.init_req, max(self.timeout, 30.0))
208
+ return self.info
209
+
210
+ def _over_limit(self, pid: int) -> bool:
211
+ if self.info.get("limits", {}).get("as"):
212
+ return False # the kernel enforces it
213
+ used = rss_mb(pid)
214
+ return used is not None and used > self.memory_mb
215
+
216
+ def _send(self, req: dict[str, Any]) -> dict[str, Any]:
217
+ assert self.proc is not None
218
+ reply = self.proc.request(req, self.timeout, self._over_limit)
219
+ if any(k in reply for k in _RESTART):
220
+ self.restarts += 1
221
+ self.proc.kill()
222
+ self.start()
223
+ return reply
224
+
225
+ def call(self, fn: str, args: list[Any], *, observe: list[int] | None = None) -> dict[str, Any]:
226
+ return self._send({"op": "call", "fn": fn, "args": args, "observe": observe or []})
227
+
228
+ def model(self, name: str, payload: Any) -> dict[str, Any]:
229
+ return self._send({"op": "model", "name": name, "payload": payload})
230
+
231
+ def close(self) -> None:
232
+ if self.proc is not None:
233
+ self.proc.close()
234
+
235
+
236
+ class RustRunner:
237
+ """The compiled harness binary."""
238
+
239
+ def __init__(self, exe: str, *, timeout: float, cwd: Path, memory_mb: int = 1024) -> None:
240
+ self.exe, self.timeout, self.cwd, self.memory_mb = exe, timeout, cwd, memory_mb
241
+ self.proc = LineProc([exe], cwd=cwd)
242
+
243
+ def _over_limit(self, pid: int) -> bool:
244
+ used = rss_mb(pid)
245
+ return used is not None and used > self.memory_mb
246
+
247
+ def call(self, key: str, args: list[Any]) -> dict[str, Any]:
248
+ reply = self.proc.request({"fn": key, "args": args}, self.timeout, self._over_limit)
249
+ if any(k in reply for k in _RESTART):
250
+ self.proc.kill()
251
+ self.proc = LineProc([self.exe], cwd=self.cwd)
252
+ return reply
253
+
254
+ def close(self) -> None:
255
+ self.proc.close()