oxidize-safe 0.3.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.
@@ -0,0 +1,7 @@
1
+ """oxidize-safe: move a slow Python function to Rust, and prove it still behaves the same."""
2
+
3
+ __version__ = "0.3.0"
4
+
5
+ from .swap import swap # noqa: E402
6
+
7
+ __all__ = ["swap", "__version__"]
oxidize_safe/bench.py ADDED
@@ -0,0 +1,32 @@
1
+ """Time the original and the port on the same inputs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from dataclasses import dataclass
7
+
8
+
9
+ @dataclass
10
+ class Timing:
11
+ python_s: float
12
+ rust_s: float
13
+ calls: int
14
+
15
+ @property
16
+ def speedup(self) -> float:
17
+ return self.python_s / self.rust_s if self.rust_s else float("inf")
18
+
19
+
20
+ def _time(func, inputs, repeat):
21
+ best = float("inf")
22
+ for _ in range(repeat):
23
+ start = time.perf_counter()
24
+ for args in inputs:
25
+ func(*args)
26
+ best = min(best, time.perf_counter() - start)
27
+ return best
28
+
29
+
30
+ def bench(original, candidate, inputs: list[tuple], repeat: int = 3) -> Timing:
31
+ """Best-of-`repeat` wall time for running every input once through each function."""
32
+ return Timing(_time(original, inputs, repeat), _time(candidate, inputs, repeat), len(inputs))
oxidize_safe/check.py ADDED
@@ -0,0 +1,268 @@
1
+ """Compare a Rust port against the original Python function.
2
+
3
+ Two passes:
4
+ 1. Recorded cases: what the function saw in a real run.
5
+ 2. Generated cases: Hypothesis inputs aimed at known Python/Rust pitfalls.
6
+
7
+ A port passes only if both agree on every case. Mismatches are grouped by
8
+ pitfall tag, so the report says *why* the port is wrong, not just that it is.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import contextlib
14
+ import hashlib
15
+ import json
16
+ import math
17
+ import os
18
+ import sys
19
+ import tempfile
20
+ import time
21
+ from collections import Counter, defaultdict
22
+ from dataclasses import dataclass, field
23
+ from pathlib import Path
24
+
25
+ from hypothesis import HealthCheck, given, settings
26
+
27
+ from . import pitfalls, strategies
28
+ from .record import load_cases
29
+ from .target import resolve, split_target
30
+
31
+ LOCK_PATH = Path(".oxidize-safe/lock.json")
32
+
33
+
34
+ @contextlib.contextmanager
35
+ def quiet_stderr():
36
+ """Silence the process-level stderr while ports run.
37
+
38
+ A Rust panic prints its message and backtrace straight to file descriptor 2,
39
+ bypassing Python. Thousands of generated cases would bury the report.
40
+ """
41
+ try:
42
+ sys.stderr.flush()
43
+ saved = os.dup(2)
44
+ except (OSError, ValueError):
45
+ yield
46
+ return
47
+ with tempfile.TemporaryFile() as sink:
48
+ os.dup2(sink.fileno(), 2)
49
+ try:
50
+ yield
51
+ finally:
52
+ sys.stderr.flush()
53
+ os.dup2(saved, 2)
54
+ os.close(saved)
55
+
56
+
57
+ def outcome(func, args):
58
+ try:
59
+ return ("ok", func(*args))
60
+ except (KeyboardInterrupt, SystemExit):
61
+ raise
62
+ except BaseException as exc: # noqa: BLE001 - PyO3 panics surface as BaseException
63
+ return ("raise", type(exc).__name__)
64
+
65
+
66
+ def same(a, b) -> bool:
67
+ """Strict equality: same outcome kind, same type, same value (NaN == NaN),
68
+ and the same exception type when both raise."""
69
+ if a[0] != b[0]:
70
+ return False
71
+ if a[0] == "raise":
72
+ # Callers catch specific types (`except ZeroDivisionError`), so the type
73
+ # must match. A Rust panic arrives as PanicException and never does.
74
+ return a[1] == b[1]
75
+ x, y = a[1], b[1]
76
+ if type(x) is not type(y):
77
+ return False
78
+ if isinstance(x, float):
79
+ return (math.isnan(x) and math.isnan(y)) or (x == y and math.copysign(1, x) == math.copysign(1, y))
80
+ if isinstance(x, (list, tuple)):
81
+ return len(x) == len(y) and all(same(("ok", p), ("ok", q)) for p, q in zip(x, y))
82
+ return x == y
83
+
84
+
85
+ @dataclass
86
+ class Mismatch:
87
+ source: str # "recorded" or "generated"
88
+ args: tuple
89
+ expected: tuple
90
+ got: tuple
91
+ tags: list[str]
92
+
93
+
94
+ @dataclass
95
+ class Report:
96
+ original: str
97
+ candidate: str
98
+ recorded_total: int = 0
99
+ recorded_failed: int = 0
100
+ generated_total: int = 0
101
+ generated_failed: int = 0
102
+ tag_coverage: Counter = field(default_factory=Counter)
103
+ mismatches: list[Mismatch] = field(default_factory=list)
104
+ exception_type_diffs: int = 0
105
+ minimal: dict = field(default_factory=dict) # tag -> Mismatch, shrunk by Hypothesis
106
+ seconds: float = 0.0
107
+
108
+ @property
109
+ def passed(self) -> bool:
110
+ return self.recorded_failed == 0 and self.generated_failed == 0
111
+
112
+ def by_tag(self) -> dict[str, list[Mismatch]]:
113
+ groups: dict[str, list[Mismatch]] = defaultdict(list)
114
+ for m in self.mismatches:
115
+ for tag in m.tags or ["untagged"]:
116
+ groups[tag].append(m)
117
+ return dict(groups)
118
+
119
+
120
+ def run_check(original_target: str, candidate_target: str, cases_path: Path | None,
121
+ examples: int = 500, seed: int = 0, shrink: bool = True) -> Report:
122
+ original = resolve(original_target)
123
+ candidate = resolve(candidate_target)
124
+ report = Report(original_target, candidate_target)
125
+ started = time.perf_counter()
126
+
127
+ def compare(args, source):
128
+ exp, got = outcome(original, args), outcome(candidate, args)
129
+ tags = sorted(pitfalls.tags_for(args))
130
+ if source == "generated":
131
+ report.tag_coverage.update(tags or ["plain"])
132
+ if exp[0] == got[0] == "raise" and exp[1] != got[1]:
133
+ report.exception_type_diffs += 1
134
+ if not same(exp, got):
135
+ report.mismatches.append(Mismatch(source, args, exp, got, tags))
136
+ return False
137
+ return True
138
+
139
+ # 1. Recorded cases
140
+ if cases_path is not None:
141
+ with quiet_stderr():
142
+ for case in load_cases(cases_path):
143
+ report.recorded_total += 1
144
+ if not compare(tuple(case["args"]), "recorded"):
145
+ report.recorded_failed += 1
146
+
147
+ # 2. Generated cases (deterministic with derandomize so reports are reproducible)
148
+ strategy = strategies.for_function(original)
149
+
150
+ @settings(max_examples=examples, database=None, derandomize=True, deadline=None,
151
+ suppress_health_check=list(HealthCheck))
152
+ @given(strategy)
153
+ def generated(args):
154
+ report.generated_total += 1
155
+ if not compare(args, "generated"):
156
+ report.generated_failed += 1
157
+
158
+ with quiet_stderr():
159
+ generated()
160
+ if shrink and report.mismatches:
161
+ report.minimal = shrink_by_tag(original, candidate, strategy, report)
162
+ report.seconds = time.perf_counter() - started
163
+ return report
164
+
165
+
166
+ def shrink_by_tag(original, candidate, strategy, report: Report) -> dict:
167
+ """For each pitfall that caused a mismatch, ask Hypothesis for the simplest
168
+ input that still fails. Prefer inputs that trigger *only* that pitfall, so
169
+ each example shows one cause instead of three tangled together."""
170
+ from hypothesis import find
171
+ from hypothesis.errors import NoSuchExample
172
+
173
+ def failing(args):
174
+ return not same(outcome(original, args), outcome(candidate, args))
175
+
176
+ out = {}
177
+ for tag in report.by_tag():
178
+ for want_only in ((True,) if tag == "untagged" else (True, False)):
179
+ def cond(args, tag=tag, want_only=want_only):
180
+ tags = pitfalls.tags_for(args)
181
+ if tag == "untagged":
182
+ ok = not tags
183
+ else:
184
+ ok = tags == {tag} if want_only else tag in tags
185
+ return ok and failing(args)
186
+ try:
187
+ args = find(strategy, cond, settings=settings(
188
+ max_examples=2000, database=None, derandomize=True, deadline=None,
189
+ suppress_health_check=list(HealthCheck)))
190
+ except NoSuchExample:
191
+ continue
192
+ except Exception:
193
+ # Shrinking only improves the report. Some Hypothesis releases
194
+ # crash in their own shrink passes; keep the unshrunk example.
195
+ break
196
+ out[tag] = Mismatch("shrunk", args, outcome(original, args), outcome(candidate, args),
197
+ sorted(pitfalls.tags_for(args)))
198
+ break
199
+ return out
200
+
201
+
202
+ def smallest_examples(report: Report, per_tag: int = 1) -> dict[str, list[Mismatch]]:
203
+ out = {}
204
+ for tag, items in report.by_tag().items():
205
+ out[tag] = sorted(items, key=lambda m: len(repr(m.args)))[:per_tag]
206
+ return out
207
+
208
+
209
+ def _show(result) -> str:
210
+ kind, value = result
211
+ return f"raises {value}" if kind == "raise" else _short(value)
212
+
213
+
214
+ def _short(value, width=70) -> str:
215
+ text = repr(value)
216
+ return text if len(text) <= width else text[: width - 15] + f"... ({len(text)} chars)"
217
+
218
+
219
+ def render(report: Report) -> str:
220
+ lines = [
221
+ f"oxidize-safe check: {report.candidate} vs {report.original}",
222
+ "",
223
+ f" recorded cases {report.recorded_total - report.recorded_failed:>5}/{report.recorded_total:<5} match",
224
+ f" generated cases {report.generated_total - report.generated_failed:>5}/{report.generated_total:<5} match",
225
+ ]
226
+ if report.tag_coverage:
227
+ cov = ", ".join(f"{t} {n}" for t, n in sorted(report.tag_coverage.items()))
228
+ lines.append(f" pitfalls covered {cov}")
229
+ if report.exception_type_diffs:
230
+ lines.append(f" note: {report.exception_type_diffs} mismatches raised a different exception type "
231
+ "(PanicException means the Rust code panicked)")
232
+ if report.mismatches:
233
+ lines += ["", " mismatches by pitfall:"]
234
+ groups = report.by_tag()
235
+ for tag, items in sorted(groups.items(), key=lambda kv: -len(kv[1])):
236
+ lines.append(f" {tag:<16} {len(items):>4} {pitfalls.explain(tag)}")
237
+ examples = {t: ms[0] for t, ms in smallest_examples(report).items()}
238
+ examples.update(report.minimal)
239
+ label = "simplest failing input per pitfall (shrunk)" if report.minimal else "smallest failing example per pitfall"
240
+ lines += ["", f" {label}:"]
241
+ for tag, m in sorted(examples.items()):
242
+ lines.append(f" [{tag}] args={_short(m.args)}")
243
+ lines.append(f" python -> {_show(m.expected)} rust -> {_show(m.got)}")
244
+ lines += ["", f" verdict: {'PASS, safe to switch on' if report.passed else 'FAIL, keep the Python version'}"
245
+ f" ({report.seconds:.1f}s)"]
246
+ return "\n".join(lines)
247
+
248
+
249
+ def file_hash(target: str) -> str:
250
+ module_name, _ = split_target(target)
251
+ import importlib
252
+
253
+ path = Path(importlib.import_module(module_name).__file__)
254
+ return hashlib.sha256(path.read_bytes()).hexdigest()
255
+
256
+
257
+ def write_lock(report: Report, path: Path = LOCK_PATH) -> None:
258
+ """Record the verdict for this exact build of the candidate."""
259
+ path.parent.mkdir(parents=True, exist_ok=True)
260
+ lock = json.loads(path.read_text()) if path.exists() else {}
261
+ lock[report.candidate] = {
262
+ "original": report.original,
263
+ "passed": report.passed,
264
+ "sha256": file_hash(report.candidate),
265
+ "recorded": [report.recorded_total, report.recorded_failed],
266
+ "generated": [report.generated_total, report.generated_failed],
267
+ }
268
+ path.write_text(json.dumps(lock, indent=2, sort_keys=True) + "\n")
oxidize_safe/cli.py ADDED
@@ -0,0 +1,113 @@
1
+ """oxidize-safe command line.
2
+
3
+ oxidize-safe init ORIGINAL [--out DIR]
4
+ oxidize-safe record ORIGINAL --run script.py --out cases.jsonl
5
+ oxidize-safe check ORIGINAL CANDIDATE [--cases cases.jsonl] [--examples 500]
6
+ oxidize-safe bench ORIGINAL CANDIDATE --cases cases.jsonl
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ from . import __version__
17
+ from .bench import bench
18
+ from .check import render, run_check, write_lock
19
+ from .pitfalls import explain
20
+ from .record import load_cases, record_run
21
+ from .target import add_paths, resolve
22
+
23
+
24
+ def main(argv: list[str] | None = None) -> int:
25
+ p = argparse.ArgumentParser(prog="oxidize-safe", description="Prove a Rust port behaves like the Python it replaces.")
26
+ p.add_argument("--version", action="version", version=__version__)
27
+ p.add_argument("--path", action="append", help="extra import path (repeatable)")
28
+ sub = p.add_subparsers(dest="cmd", required=True)
29
+
30
+ i = sub.add_parser("init", help="scaffold a PyO3 crate with a stub for the function")
31
+ i.add_argument("original", help="module:function")
32
+ i.add_argument("--out", type=Path, help="crate directory (default: ./<function>-rs)")
33
+ i.add_argument("--crate", help="Rust crate / Python module name (default: <function>_rs)")
34
+
35
+ r = sub.add_parser("record", help="record real calls to the original function")
36
+ r.add_argument("original", help="module:function")
37
+ r.add_argument("--run", required=True, help="script to run with the function wrapped")
38
+ r.add_argument("--out", required=True, type=Path)
39
+ r.add_argument("script_args", nargs="*")
40
+
41
+ c = sub.add_parser("check", help="compare the port on recorded and generated cases")
42
+ c.add_argument("original")
43
+ c.add_argument("candidate")
44
+ c.add_argument("--cases", type=Path)
45
+ c.add_argument("--examples", type=int, default=500)
46
+ c.add_argument("--json", type=Path, help="also write the full report as JSON")
47
+ c.add_argument("--no-lock", action="store_true", help="don't update .oxidize-safe/lock.json")
48
+ c.add_argument("--no-shrink", action="store_true", help="skip shrinking failures to the simplest input")
49
+
50
+ b = sub.add_parser("bench", help="time both versions on recorded inputs")
51
+ b.add_argument("original")
52
+ b.add_argument("candidate")
53
+ b.add_argument("--cases", type=Path, required=True)
54
+ b.add_argument("--repeat", type=int, default=3)
55
+
56
+ args = p.parse_args(argv)
57
+ add_paths(args.path)
58
+
59
+ if args.cmd == "init":
60
+ from .init import scaffold
61
+ from .target import split_target
62
+ name = split_target(args.original)[1]
63
+ out, candidate = scaffold(args.original, args.out or Path((args.crate or name + '_rs').replace('_', '-')), args.crate)
64
+ print(f"created {out}/ with a stub for {args.original}\n")
65
+ print("next:")
66
+ print(f" 1. write the port in {out}/src/lib.rs (the Python source and pitfalls are at the top)")
67
+ print(f" 2. (cd {out} && maturin develop --release)")
68
+ print(f" 3. oxidize-safe check {args.original} {candidate}")
69
+ return 0
70
+
71
+ if args.cmd == "record":
72
+ n = record_run(args.original, args.run, args.out, args.script_args)
73
+ print(f"recorded {n} distinct calls to {args.original} -> {args.out}")
74
+ return 0
75
+
76
+ if args.cmd == "check":
77
+ report = run_check(args.original, args.candidate, args.cases, args.examples, shrink=not args.no_shrink)
78
+ print(render(report))
79
+ if args.json:
80
+ args.json.write_text(json.dumps({
81
+ "passed": report.passed,
82
+ "recorded": [report.recorded_total, report.recorded_failed],
83
+ "generated": [report.generated_total, report.generated_failed],
84
+ "coverage": dict(report.tag_coverage),
85
+ "mismatches_by_tag": {t: len(ms) for t, ms in report.by_tag().items()},
86
+ "examples": {
87
+ tag: {"args": repr(m.args), "python": list(map(repr, m.expected)),
88
+ "candidate": list(map(repr, m.got)), "why": explain(tag)}
89
+ for tag, m in _examples(report).items()
90
+ },
91
+ }, indent=2))
92
+ if not args.no_lock:
93
+ write_lock(report)
94
+ return 0 if report.passed else 1
95
+
96
+ if args.cmd == "bench":
97
+ inputs = [tuple(c["args"]) for c in load_cases(args.cases)]
98
+ t = bench(resolve(args.original), resolve(args.candidate), inputs, args.repeat)
99
+ print(f"{t.calls} calls python {t.python_s * 1000:.1f} ms rust {t.rust_s * 1000:.1f} ms "
100
+ f"speed-up {t.speedup:.1f}x")
101
+ return 0
102
+ return 2
103
+
104
+
105
+ def _examples(report):
106
+ from .check import smallest_examples
107
+ out = {t: ms[0] for t, ms in smallest_examples(report).items()}
108
+ out.update(report.minimal)
109
+ return out
110
+
111
+
112
+ if __name__ == "__main__":
113
+ sys.exit(main())
oxidize_safe/init.py ADDED
@@ -0,0 +1,165 @@
1
+ """`oxidize-safe init`: scaffold a PyO3 crate for one Python function.
2
+
3
+ The stub has the right signature, the Python source as a comment, and the
4
+ pitfalls that apply to its argument types. Its body raises NotImplementedError,
5
+ so the first `check` fails loudly until the port is written.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import inspect
11
+ import re
12
+ import textwrap
13
+ import typing
14
+ from pathlib import Path
15
+
16
+ from .target import resolve, split_target
17
+
18
+ HINTS = {
19
+ "str": [
20
+ "Index and slice by chars (`s.chars()`), not bytes: Python counts code points.",
21
+ "Python's str methods are Unicode-aware: 'ß'.upper() is 'SS', 'İ'.lower() is 2 chars,",
22
+ " isalnum()/isdigit() accept non-ASCII. Rust's is_ascii_* versions do not.",
23
+ ],
24
+ "int": [
25
+ "Python ints are unbounded. Take `&Bound<PyAny>` and fall back to Python past i64,",
26
+ " or reject explicitly; an i64 argument raises OverflowError on big values.",
27
+ "Python // and % floor toward -inf; Rust / and % truncate. div_euclid is also",
28
+ " wrong for negative divisors. Division by zero must raise ZeroDivisionError, not panic.",
29
+ "Negative indexes and slice bounds count from the end in Python.",
30
+ ],
31
+ "float": [
32
+ "round() rounds halves to even: use f64::round_ties_even, not f64::round.",
33
+ "NaN/inf: round(nan) raises ValueError, int(inf) raises OverflowError.",
34
+ "`as i64` saturates silently; Python returns the exact integer.",
35
+ ],
36
+ "list": [
37
+ "Sizes past ~200 can switch on library heuristics (difflib's autojunk, for one).",
38
+ ],
39
+ }
40
+
41
+ PRELUDE = '''use pyo3::prelude::*;
42
+ use pyo3::exceptions::PyNotImplementedError;
43
+ '''
44
+
45
+
46
+ def rust_type(ann, arg: bool) -> str:
47
+ if ann is str:
48
+ return "&str" if arg else "String"
49
+ if ann is int:
50
+ return "i64"
51
+ if ann is float:
52
+ return "f64"
53
+ if ann is bool:
54
+ return "bool"
55
+ if ann is bytes:
56
+ return "&[u8]" if arg else "std::borrow::Cow<'static, [u8]>"
57
+ if ann is type(None) or ann is None:
58
+ return "()"
59
+ origin, params = typing.get_origin(ann), typing.get_args(ann)
60
+ if origin in (list, typing.List):
61
+ return f"Vec<{rust_type(params[0], False) if params else 'String'}>"
62
+ if origin in (tuple, typing.Tuple) and params and params[-1] is not Ellipsis:
63
+ inner = ", ".join(rust_type(p, False) for p in params)
64
+ return f"({inner},)" if len(params) == 1 else f"({inner})"
65
+ if origin is typing.Union and type(None) in params:
66
+ rest = [p for p in params if p is not type(None)]
67
+ if len(rest) == 1:
68
+ return f"Option<{rust_type(rest[0], arg)}>"
69
+ raise TypeError(f"init doesn't know a Rust type for {ann!r}")
70
+
71
+
72
+ def kinds(ann) -> set[str]:
73
+ out = set()
74
+ if ann in (str, int, float):
75
+ out.add(ann.__name__)
76
+ for p in typing.get_args(ann):
77
+ out |= kinds(p)
78
+ if typing.get_origin(ann) in (list, tuple):
79
+ out.add("list")
80
+ return out
81
+
82
+
83
+ def scaffold(target: str, out_dir: Path, crate: str | None = None) -> tuple[Path, str]:
84
+ func = resolve(target)
85
+ _, name = split_target(target)
86
+ crate = crate or f"{name}_rs"
87
+ if not re.fullmatch(r"[a-z_][a-z0-9_]*", crate):
88
+ raise ValueError(f"crate name must be a lowercase identifier, got {crate!r}")
89
+
90
+ hints = typing.get_type_hints(func)
91
+ params = list(inspect.signature(func).parameters)
92
+ missing = [p for p in params if p not in hints] + ([] if "return" in hints else ["return"])
93
+ if missing:
94
+ raise TypeError(f"{target} needs type hints for: {', '.join(missing)}")
95
+
96
+ args = ", ".join(f"{p}: {rust_type(hints[p], True)}" for p in params)
97
+ ret = rust_type(hints["return"], False)
98
+ used = set()
99
+ for p in params:
100
+ used |= kinds(hints[p])
101
+ used |= kinds(hints["return"])
102
+
103
+ try:
104
+ source = textwrap.dedent(inspect.getsource(func)).rstrip()
105
+ except (OSError, TypeError):
106
+ source = f"(source not available for {target})"
107
+ lines = ["// Python original:", "//"] + [f"// {l}" if l else "//" for l in source.splitlines()]
108
+ notes = [h for k in ("str", "int", "float", "list") if k in used for h in HINTS[k]]
109
+ if notes:
110
+ lines += ["//", "// Pitfalls for these types:"] + [f"// {n}" for n in notes]
111
+
112
+ body = f'''
113
+ #[pyfunction]
114
+ pub fn {name}({args}) -> PyResult<{ret}> {{
115
+ let _ = ({", ".join(params)}{"," if len(params) == 1 else ""});
116
+ Err(PyNotImplementedError::new_err("port not written yet"))
117
+ }}
118
+
119
+ #[pymodule]
120
+ fn {crate}(m: &Bound<'_, PyModule>) -> PyResult<()> {{
121
+ m.add_function(wrap_pyfunction!({name}, m)?)?;
122
+ Ok(())
123
+ }}
124
+ '''
125
+ lib = "\n".join(lines) + "\n\n" + PRELUDE + body
126
+
127
+ dash = crate.replace("_", "-")
128
+ out_dir.mkdir(parents=True, exist_ok=True)
129
+ (out_dir / "src").mkdir(exist_ok=True)
130
+ files = {
131
+ "Cargo.toml": f'''[package]
132
+ name = "{dash}"
133
+ version = "0.1.0"
134
+ edition = "2021"
135
+ publish = false
136
+
137
+ [lib]
138
+ name = "{crate}"
139
+ crate-type = ["cdylib"]
140
+
141
+ [dependencies]
142
+ pyo3 = "0.30"
143
+ ''',
144
+ "pyproject.toml": f'''[build-system]
145
+ requires = ["maturin>=1.5,<2"]
146
+ build-backend = "maturin"
147
+
148
+ [project]
149
+ name = "{dash}"
150
+ version = "0.1.0"
151
+ requires-python = ">=3.9"
152
+
153
+ [tool.maturin]
154
+ module-name = "{crate}"
155
+ ''',
156
+ "src/lib.rs": lib,
157
+ ".gitignore": "target/\n*.so\n",
158
+ }
159
+ for rel, text in files.items():
160
+ path = out_dir / rel
161
+ if path.exists():
162
+ raise FileExistsError(f"{path} already exists; not overwriting")
163
+ for rel, text in files.items():
164
+ (out_dir / rel).write_text(text)
165
+ return out_dir, f"{crate}:{name}"
@@ -0,0 +1,96 @@
1
+ """Where Python and Rust disagree, and how to recognise an input that hits it.
2
+
3
+ Each pitfall is a tag plus a predicate over one argument value. When a case
4
+ mismatches, its tags tell you *why* it probably did. That is the difference
5
+ between "3 cases failed" and "your port breaks on non-ASCII text".
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from typing import Any, Callable
12
+
13
+ I64_MIN, I64_MAX = -(2**63), 2**63 - 1
14
+
15
+ # tag -> (predicate, one-line explanation)
16
+ PITFALLS: dict[str, tuple[Callable[[Any], bool], str]] = {
17
+ "non-ascii": (
18
+ lambda v: isinstance(v, str) and not v.isascii(),
19
+ "Python strings are code points; Rust &str is UTF-8 bytes. Indexing or "
20
+ "len() on bytes gives different answers.",
21
+ ),
22
+ "astral-char": (
23
+ lambda v: isinstance(v, str) and any(ord(c) > 0xFFFF for c in v),
24
+ "Characters outside the BMP (emoji, rare CJK) are 4 UTF-8 bytes and 1 Python char.",
25
+ ),
26
+ "long-sequence": (
27
+ lambda v: isinstance(v, (str, list, tuple, bytes)) and len(v) >= 200,
28
+ "Library heuristics often switch on at a size threshold "
29
+ "(difflib's autojunk starts at 200).",
30
+ ),
31
+ "empty": (
32
+ lambda v: isinstance(v, (str, list, tuple, bytes, dict)) and len(v) == 0,
33
+ "Empty inputs hit edge branches (division by zero, first/last element).",
34
+ ),
35
+ "int-beyond-i64": (
36
+ lambda v: isinstance(v, int) and not isinstance(v, bool) and not (I64_MIN <= v <= I64_MAX),
37
+ "Python ints never overflow; Rust i64/u64 wrap, panic or fail to convert.",
38
+ ),
39
+ "negative-int": (
40
+ lambda v: isinstance(v, int) and not isinstance(v, bool) and v < 0,
41
+ "Python // and % round toward negative infinity; Rust / and % truncate toward "
42
+ "zero (-7 // 2 is -4 in Python, -7 / 2 is -3 in Rust). Negative indexes and "
43
+ "slice bounds count from the end in Python (s[:-2]).",
44
+ ),
45
+ "zero": (
46
+ lambda v: isinstance(v, (int, float)) and not isinstance(v, bool) and v == 0,
47
+ "Zero as a divisor raises ZeroDivisionError in Python; in Rust integer division "
48
+ "by zero panics.",
49
+ ),
50
+ "half-float": (
51
+ lambda v: isinstance(v, float) and math.isfinite(v) and v != int(v) and (v * 2).is_integer(),
52
+ "Python round() rounds halves to even (2.5 -> 2); Rust f64::round rounds them "
53
+ "away from zero (2.5 -> 3).",
54
+ ),
55
+ "float-beyond-i64": (
56
+ lambda v: isinstance(v, float) and math.isfinite(v) and abs(v) >= 2.0**63,
57
+ "Casting a float this large to a Rust integer (`as i64`) silently saturates at "
58
+ "i64::MAX; Python's int() and round() return the exact value.",
59
+ ),
60
+ "float-special": (
61
+ lambda v: isinstance(v, float) and (math.isnan(v) or math.isinf(v) or (v == 0.0 and math.copysign(1, v) < 0)),
62
+ "NaN, infinities and -0.0 compare and format differently than people expect.",
63
+ ),
64
+ }
65
+
66
+
67
+ def _walk(value: Any):
68
+ yield value
69
+ if isinstance(value, (list, tuple, set, frozenset)):
70
+ for item in value:
71
+ yield from _walk(item)
72
+ elif isinstance(value, dict):
73
+ for k, item in value.items():
74
+ yield from _walk(k)
75
+ yield from _walk(item)
76
+
77
+
78
+ def tags_for(args: tuple, kwargs: dict | None = None) -> set[str]:
79
+ """Every pitfall tag that any argument (or nested element) triggers."""
80
+ found: set[str] = set()
81
+ values = list(args) + list((kwargs or {}).values())
82
+ for value in values:
83
+ for v in _walk(value):
84
+ for tag, (pred, _) in PITFALLS.items():
85
+ try:
86
+ if pred(v):
87
+ found.add(tag)
88
+ except Exception:
89
+ pass
90
+ return found
91
+
92
+
93
+ def explain(tag: str) -> str:
94
+ if tag == "untagged":
95
+ return "No known pitfall in these inputs: the logic itself differs. Compare the code line by line."
96
+ return PITFALLS[tag][1] if tag in PITFALLS else ""
oxidize_safe/record.py ADDED
@@ -0,0 +1,64 @@
1
+ """Record what the original function actually sees in a real run.
2
+
3
+ Recorded cases are the baseline: if the port can't reproduce real traffic,
4
+ nothing else matters. They are also what most porting tools stop at, which is
5
+ why `check` adds generated cases on top.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import functools
11
+ import json
12
+ import runpy
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ from .target import load, split_target
17
+
18
+
19
+ def _jsonable(value):
20
+ json.dumps(value) # raises TypeError for values we can't store faithfully
21
+ return value
22
+
23
+
24
+ def record_run(target: str, script: str, out: Path, script_args: list[str] | None = None, limit: int = 5000) -> int:
25
+ """Run `script` with `target` wrapped; save each call's args and result as JSONL.
26
+
27
+ Returns the number of cases written. Identical calls are stored once.
28
+ """
29
+ module_name, attr = split_target(target)
30
+ module = load(module_name)
31
+ original = getattr(module, attr)
32
+ seen: set[str] = set()
33
+ out.parent.mkdir(parents=True, exist_ok=True)
34
+ fh = out.open("w", encoding="utf-8")
35
+
36
+ @functools.wraps(original)
37
+ def wrapper(*args, **kwargs):
38
+ result = original(*args, **kwargs)
39
+ if len(seen) < limit and not kwargs:
40
+ try:
41
+ line = json.dumps({"args": [_jsonable(a) for a in args], "result": _jsonable(result)},
42
+ ensure_ascii=False, sort_keys=True)
43
+ except TypeError:
44
+ return result
45
+ if line not in seen:
46
+ seen.add(line)
47
+ fh.write(line + "\n")
48
+ return result
49
+
50
+ setattr(module, attr, wrapper)
51
+ old_argv = sys.argv
52
+ sys.argv = [script, *(script_args or [])]
53
+ try:
54
+ runpy.run_path(script, run_name="__main__")
55
+ finally:
56
+ sys.argv = old_argv
57
+ setattr(module, attr, original)
58
+ fh.close()
59
+ return len(seen)
60
+
61
+
62
+ def load_cases(path: Path) -> list[dict]:
63
+ with path.open(encoding="utf-8") as fh:
64
+ return [json.loads(line) for line in fh if line.strip()]
@@ -0,0 +1,87 @@
1
+ """Hypothesis strategies that aim at the pitfalls instead of hoping to hit them.
2
+
3
+ Plain random inputs rarely produce a 250-character string where one letter
4
+ appears 30 times, or an integer past 2**63. These strategies mix ordinary
5
+ values with deliberately awkward ones, so a few hundred examples cover the
6
+ places where ports go wrong.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import inspect
12
+ import typing
13
+
14
+ from hypothesis import strategies as st
15
+
16
+ ASCII = st.text(alphabet=st.characters(min_codepoint=32, max_codepoint=126), max_size=40)
17
+ UNICODE = st.text(
18
+ alphabet=st.one_of(
19
+ st.sampled_from("éèüñçßøå"), # accented Latin
20
+ st.sampled_from("日本語中文한국어"), # CJK
21
+ st.sampled_from("😀🚀🦀👍🏽"), # astral-plane emoji
22
+ st.sampled_from("́‍"), # combining accent, zero-width joiner
23
+ st.characters(min_codepoint=32, max_codepoint=126),
24
+ ),
25
+ max_size=40,
26
+ )
27
+ # Long strings over a small alphabet: repeated characters make "popular"
28
+ # elements, which is what size-triggered heuristics react to.
29
+ LONG = st.integers(min_value=200, max_value=600).flatmap(
30
+ lambda n: st.text(alphabet=st.sampled_from("abcde é"), min_size=n, max_size=n)
31
+ )
32
+
33
+ TEXT = st.one_of(ASCII, UNICODE, LONG, st.just(""))
34
+ INTS = st.one_of(
35
+ st.integers(min_value=-1000, max_value=1000),
36
+ st.sampled_from([0, 1, -1, 2**63 - 1, -(2**63)]),
37
+ st.integers(min_value=2**63 - 5, max_value=2**64 + 5),
38
+ st.integers(max_value=-(2**63) + 5, min_value=-(2**64) - 5),
39
+ st.integers(),
40
+ )
41
+ FLOATS = st.one_of(
42
+ st.floats(allow_nan=False, allow_infinity=False, width=64),
43
+ st.integers(min_value=-1000, max_value=1000).map(lambda n: n + 0.5), # exact halves
44
+ st.sampled_from([float("nan"), float("inf"), float("-inf"), -0.0, 0.0, 1e308, 5e-324]),
45
+ )
46
+
47
+
48
+ def for_annotation(ann) -> st.SearchStrategy:
49
+ """A pitfall-biased strategy for one type annotation."""
50
+ if ann is str:
51
+ return TEXT
52
+ if ann is bool:
53
+ return st.booleans()
54
+ if ann is int:
55
+ return INTS
56
+ if ann is float:
57
+ return FLOATS
58
+ if ann is bytes:
59
+ return st.binary(max_size=300)
60
+ origin, params = typing.get_origin(ann), typing.get_args(ann)
61
+ if origin in (list, typing.List):
62
+ inner = for_annotation(params[0]) if params else TEXT
63
+ return st.lists(inner, max_size=20)
64
+ if origin in (tuple, typing.Tuple) and params and params[-1] is not Ellipsis:
65
+ return st.tuples(*[for_annotation(p) for p in params])
66
+ if origin is typing.Union:
67
+ return st.one_of(*[for_annotation(p) if p is not type(None) else st.none() for p in params])
68
+ raise TypeError(
69
+ f"oxidize-safe can't generate values for {ann!r} yet. "
70
+ "Supported: str, int, float, bool, bytes, list[...], tuple[...], Optional[...]."
71
+ )
72
+
73
+
74
+ def for_function(func) -> st.SearchStrategy:
75
+ """Strategy producing positional-argument tuples for `func`, from its type hints."""
76
+ hints = typing.get_type_hints(func)
77
+ params = [
78
+ p for p in inspect.signature(func).parameters.values()
79
+ if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)
80
+ ]
81
+ missing = [p.name for p in params if p.name not in hints]
82
+ if missing:
83
+ raise TypeError(
84
+ f"{func.__qualname__} needs type hints on {', '.join(missing)} "
85
+ "so oxidize-safe knows what to generate."
86
+ )
87
+ return st.tuples(*[for_annotation(hints[p.name]) for p in params])
oxidize_safe/swap.py ADDED
@@ -0,0 +1,41 @@
1
+ """Use the Rust version only if `oxidize-safe check` passed for this exact build.
2
+
3
+ from oxidize_safe import swap
4
+ from mylib.text import ratio as _ratio
5
+ ratio = swap(_ratio, "difflib_rs:ratio")
6
+
7
+ If the lock file is missing, the check failed, or the compiled module changed
8
+ since it was checked, you get the original Python function back (with a
9
+ warning), so a bad build can never silently replace working code.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import warnings
16
+ from pathlib import Path
17
+
18
+ from .check import LOCK_PATH, file_hash
19
+ from .target import resolve
20
+
21
+
22
+ def swap(original, candidate_target: str, lock_path: Path | str = LOCK_PATH):
23
+ lock_path = Path(lock_path)
24
+ reason = None
25
+ try:
26
+ entry = json.loads(lock_path.read_text()).get(candidate_target)
27
+ if entry is None:
28
+ reason = "it has never been checked"
29
+ elif not entry["passed"]:
30
+ reason = "its last check failed"
31
+ elif entry["sha256"] != file_hash(candidate_target):
32
+ reason = "the compiled module changed since it was checked"
33
+ else:
34
+ return resolve(candidate_target)
35
+ except FileNotFoundError:
36
+ reason = f"no lock file at {lock_path}"
37
+ except ImportError:
38
+ reason = "the Rust module isn't installed"
39
+ warnings.warn(f"oxidize-safe: using Python {original.__qualname__}, not {candidate_target}: {reason}.",
40
+ stacklevel=2)
41
+ return original
oxidize_safe/target.py ADDED
@@ -0,0 +1,28 @@
1
+ """Resolve `module:function` targets, with an optional extra import path."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ import sys
7
+
8
+
9
+ def split_target(target: str) -> tuple[str, str]:
10
+ if ":" not in target:
11
+ raise ValueError(f"expected 'module:function', got {target!r}")
12
+ module_name, attr = target.split(":", 1)
13
+ return module_name, attr
14
+
15
+
16
+ def load(module_name: str):
17
+ return importlib.import_module(module_name)
18
+
19
+
20
+ def resolve(target: str):
21
+ module_name, attr = split_target(target)
22
+ return getattr(load(module_name), attr)
23
+
24
+
25
+ def add_paths(paths: list[str] | None) -> None:
26
+ for p in paths or []:
27
+ if p not in sys.path:
28
+ sys.path.insert(0, p)
@@ -0,0 +1,285 @@
1
+ Metadata-Version: 2.4
2
+ Name: oxidize-safe
3
+ Version: 0.3.0
4
+ Summary: Move a slow Python function to Rust, and prove it still behaves the same, including on the edge cases a recorded run never hits.
5
+ Author: Ahmed Elalfy
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/ahmedelalfiee/oxidize-safe
8
+ Project-URL: Issues, https://github.com/ahmedelalfiee/oxidize-safe/issues
9
+ Keywords: rust,pyo3,hypothesis,property-based-testing,differential-testing,performance
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Rust
14
+ Classifier: Topic :: Software Development :: Testing
15
+ Classifier: Framework :: Hypothesis
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: hypothesis>=6.100
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest>=8; extra == "dev"
22
+ Requires-Dist: maturin<2,>=1.5; extra == "dev"
23
+ Dynamic: license-file
24
+
25
+ # oxidize-safe
26
+
27
+ **Move a slow Python function to Rust, and prove it still behaves the same, including on the inputs your real traffic never sends.**
28
+
29
+ Coding agents can now port a Python function to Rust in minutes. The usual way to
30
+ check the port is to record what the original does in a real run and replay it.
31
+ That catches a lot, but it only proves the cases you happened to record. Python
32
+ and Rust quietly disagree in places real traffic rarely goes: non-ASCII text,
33
+ emoji, integers past 2⁶³, NaN, empty inputs, library heuristics that switch on
34
+ at a size threshold.
35
+
36
+ `oxidize-safe` checks a port against the original on **recorded cases and
37
+ generated edge cases aimed at exactly those differences**, tells you *which*
38
+ difference broke it, and only lets your app use the Rust version once it passes.
39
+ You keep your Python app. Only the hot function moves.
40
+
41
+ ![oxidize-safe catching a Rust port that passes every recorded case](docs/demo.gif)
42
+
43
+ ## The demo: a port that passes every recorded case and is still wrong
44
+
45
+ The target is `difflib.SequenceMatcher(None, a, b).ratio()`: pure Python, used
46
+ for fuzzy matching everywhere, slow on long text. `examples/difflib_ratio` has
47
+ two Rust ports, built with [PyO3](https://pyo3.rs):
48
+
49
+ * `ratio_naive`: the port you typically get first. Clean, fast, and works on bytes.
50
+ * `ratio`: the faithful port. Works on Unicode code points and implements difflib's
51
+ "autojunk" heuristic.
52
+
53
+ First, record real traffic from a CLI "did you mean?" suggester:
54
+
55
+ ```
56
+ $ oxidize-safe --path . record original:ratio --run workload.py --out cases.jsonl
57
+ recorded 1798 distinct calls to original:ratio -> cases.jsonl
58
+ ```
59
+
60
+ Then check the naive port:
61
+
62
+ ```
63
+ $ oxidize-safe --path . check original:ratio difflib_rs:ratio_naive --cases cases.jsonl
64
+
65
+ recorded cases 1798/1798 match
66
+ generated cases 454/500 match
67
+
68
+ mismatches by pitfall:
69
+ non-ascii 46 Python strings are code points; Rust &str is UTF-8 bytes.
70
+ long-sequence 41 Library heuristics often switch on at a size threshold
71
+ (difflib's autojunk starts at 200).
72
+ astral-char 3 Characters outside the BMP are 4 UTF-8 bytes and 1 Python char.
73
+
74
+ simplest failing input per pitfall (shrunk):
75
+ [astral-char] args=('0', '0🏽')
76
+ python -> 0.6666666666666666 rust -> 0.3333333333333333
77
+ [long-sequence] args=('0a', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa... (210 chars)
78
+ python -> 0.0 rust -> 0.009900990099009901
79
+ [non-ascii] args=('0', '0ß')
80
+ python -> 0.6666666666666666 rust -> 0.5
81
+
82
+ verdict: FAIL, keep the Python version
83
+ ```
84
+
85
+ **Every one of the 1,798 recorded cases matched.** A replay-only check would have
86
+ shipped this port. The generated cases found two real bugs, and the report names both:
87
+
88
+ 1. **Bytes vs characters.** `'ß'` is one Python character but two UTF-8 bytes, so
89
+ `('0', '0ß')` is "1 of 3 characters differ" to Python and "2 of 4 bytes" to
90
+ the port.
91
+ 2. **A heuristic that only exists past 200 items.** For sequences of 200+, difflib
92
+ treats very common elements as junk. Your recordings were all short commands,
93
+ so they never triggered it.
94
+
95
+ The faithful port:
96
+
97
+ ```
98
+ $ oxidize-safe --path . check original:ratio difflib_rs:ratio --cases cases.jsonl --examples 1000
99
+
100
+ recorded cases 1798/1798 match
101
+ generated cases 1000/1000 match
102
+ pitfalls covered astral-char 72, empty 415, long-sequence 407, non-ascii 548, plain 219
103
+
104
+ verdict: PASS, safe to switch on
105
+ ```
106
+
107
+ And it's worth it:
108
+
109
+ | Workload | Python | Rust | Speed-up |
110
+ |---|---|---|---|
111
+ | 1,798 recorded "did you mean" calls | 9.7 ms | 1.3 ms | 7.7x |
112
+ | Two 500-char paragraphs | 0.4 ms | 0.05 ms | 7x |
113
+ | Two 2,000-char paragraphs | 1.0 ms | 0.11 ms | 9x |
114
+ | Two 8,000-char paragraphs | 3.9 ms | 0.27 ms | 15x |
115
+
116
+ Same result in every case. Measured on one Linux machine, best of 3; rerun with
117
+ `oxidize-safe bench` and `python examples/difflib_ratio/bench_long.py`.
118
+
119
+ ## Second demo: integer division and rounding
120
+
121
+ `examples/numeric` ports two one-liners that look too simple to get wrong:
122
+
123
+ ```python
124
+ def time_bucket(seconds: int, width: int) -> int:
125
+ return seconds // width * width
126
+
127
+ def round_score(score: float) -> int:
128
+ return round(score)
129
+ ```
130
+
131
+ Every recorded case (5,000 real timestamps) matches for every port. The generated
132
+ cases don't:
133
+
134
+ ```
135
+ $ oxidize-safe --path . check original:time_bucket numeric_rs:time_bucket_naive --cases bucket_cases.jsonl
136
+
137
+ recorded cases 5000/5000 match
138
+ generated cases 125/500 match
139
+ note: 41 mismatches raised a different exception type (PanicException means the Rust code panicked)
140
+
141
+ simplest failing input per pitfall (shrunk):
142
+ [int-beyond-i64] args=(1, 9223372036854775808)
143
+ python -> 0 rust -> raises OverflowError
144
+ [negative-int] args=(1, -2)
145
+ python -> 2 rust -> 0
146
+ [zero] args=(0, 0)
147
+ python -> raises ZeroDivisionError rust -> raises PanicException
148
+
149
+ verdict: FAIL, keep the Python version
150
+ ```
151
+
152
+ | Port | What it does | Result |
153
+ |---|---|---|
154
+ | `time_bucket_naive` | `seconds / width * width` on `i64` | FAIL: truncates, panics on 0, can't take big ints |
155
+ | `time_bucket_euclid` | `div_euclid`, the usual "fix" | FAIL: still wrong when the divisor is negative (`1 // -2` is `-1`, `1.div_euclid(-2)` is `0`) |
156
+ | `time_bucket` | floor division, `ZeroDivisionError`, Python fallback past `i64` | PASS |
157
+ | `round_score_naive` | `score.round() as i64` | FAIL: `0.5` gives 1 (Python gives 0), NaN gives 0 instead of raising, `1e19` saturates |
158
+ | `round_score` | `round_ties_even`, Python's errors, Python fallback past `i64` | PASS |
159
+
160
+ This demo is about correctness, not speed: on functions this small the cost of
161
+ crossing from Python to Rust dominates (about 1.3x). Port hot loops, not one-liners.
162
+
163
+ ## Let an agent do the loop
164
+
165
+ `skills/oxidize-port/SKILL.md` is a Claude Code skill that closes the loop: the
166
+ agent scaffolds the crate, writes the port, runs `check`, reads the mismatches
167
+ by pitfall, fixes one cause at a time and repeats until it passes. The check is
168
+ the judge, and the skill forbids the shortcuts (editing cases, lowering
169
+ `--examples`, catching panics and calling Python instead).
170
+
171
+ Install it for your user or for one project:
172
+
173
+ ```bash
174
+ cp -r skills/oxidize-port ~/.claude/skills/ # or .claude/skills/ in your repo
175
+ ```
176
+
177
+ Then ask Claude Code to "port `mod:func` to Rust". Here is the run that produced
178
+ `examples/slugify`, porting this:
179
+
180
+ ```python
181
+ def slugify(title: str, max_len: int) -> str:
182
+ words = re.findall(r"\w+", title.lower())
183
+ return "-".join(words)[:max_len]
184
+ ```
185
+
186
+ | Round | Port | Check | What the report pointed at |
187
+ |---|---|---|---|
188
+ | 1 | split on `!is_alphanumeric()`, `max_len: usize`, byte slice | 231/500 | `('', -1)` raises OverflowError; `('00ß', 3)` panics mid-character |
189
+ | 2 | Python slice semantics on chars, big ints clamp | 498/500 | `('_', 1)`: untagged, so the logic differs. `\w` includes `_` |
190
+ | 3 | treat `_` as a word character | 2000/2000 | PASS, 3.8x faster |
191
+
192
+ Scaffold a port yourself with:
193
+
194
+ ```bash
195
+ oxidize-safe --path . init mod:func # ./func-rs/ with a stub, the Python source and its pitfalls
196
+ ```
197
+
198
+ ## Using the Rust version safely
199
+
200
+ ```python
201
+ from oxidize_safe import swap
202
+ from mylib.fuzzy import ratio as _ratio
203
+
204
+ ratio = swap(_ratio, "difflib_rs:ratio")
205
+ ```
206
+
207
+ `swap` returns the Rust function only if `oxidize-safe check` passed **for this
208
+ exact build** (the compiled module's SHA-256 is stored in `.oxidize-safe/lock.json`).
209
+ If the check failed, was never run, or the module was rebuilt since, you get the
210
+ original Python function back with a warning. A bad build can't silently replace
211
+ working code.
212
+
213
+ ## How it works
214
+
215
+ 1. **`record`** runs your script with the function wrapped and saves each distinct
216
+ call's arguments and result as JSONL.
217
+ 2. **`check`** compares the port with the original on:
218
+ * every recorded case, and
219
+ * Hypothesis-generated cases built from the function's type hints, biased
220
+ towards known Python/Rust differences: accented and CJK text, emoji, combining
221
+ characters, 200–600-character strings over small alphabets, integers just
222
+ past i64/u64, NaN/±inf/-0.0, and empty values.
223
+ 3. Comparison is strict: same type, same value, NaN equals NaN, `0.0` is not `-0.0`,
224
+ and both sides must raise the *same* exception type. A Rust panic arrives as
225
+ `PanicException` and counts as a mismatch, not a crash; its backtrace is kept
226
+ out of your terminal.
227
+ 4. Every mismatch is tagged with the pitfalls its inputs trigger, so the report
228
+ says *why*.
229
+ 5. For each pitfall, Hypothesis shrinks the failure to the simplest input that
230
+ still fails, preferring one that triggers only that pitfall, so each example
231
+ shows one cause. `--no-shrink` skips this.
232
+ 6. Mismatches whose inputs trigger no known pitfall are reported as `untagged`
233
+ (the logic itself differs) and shrunk the same way.
234
+ 7. Generation is deterministic, so the same port always gets the same report.
235
+
236
+ ## Pitfalls it targets today
237
+
238
+ | Tag | What goes wrong |
239
+ |---|---|
240
+ | `non-ascii` | Python strings are code points, Rust `&str` is UTF-8 bytes |
241
+ | `astral-char` | Emoji and rare CJK: 1 Python char, 4 bytes, 2 UTF-16 units |
242
+ | `long-sequence` | Size-triggered behaviour in libraries (200+ items) |
243
+ | `empty` | Empty strings and lists hit edge branches |
244
+ | `int-beyond-i64` | Python ints never overflow; Rust integers wrap, panic or fail to convert |
245
+ | `negative-int` | Python `//` and `%` floor; Rust `/` and `%` truncate, and `div_euclid` differs for negative divisors |
246
+ | `zero` | Division by zero raises in Python and panics in Rust |
247
+ | `half-float` | Python `round()` rounds halves to even; `f64::round` rounds away from zero |
248
+ | `float-beyond-i64` | `as i64` silently saturates; Python returns the exact integer |
249
+ | `float-special` | NaN, infinities and -0.0 |
250
+
251
+ ## Quick start
252
+
253
+ ```bash
254
+ pip install -e '.[dev]'
255
+
256
+ # build the demo port (needs a Rust toolchain)
257
+ cd examples/difflib_ratio
258
+ maturin develop --release
259
+
260
+ oxidize-safe --path . check original:ratio difflib_rs:ratio --cases cases.jsonl
261
+ ```
262
+
263
+ The test suite runs without Rust (it uses pure-Python stand-ins that reproduce
264
+ each bug class) and also exercises the real Rust demo when it's built:
265
+
266
+ ```bash
267
+ pytest -q
268
+ ```
269
+
270
+ ## Scope and limits
271
+
272
+ * **One function at a time**, with positional arguments typed as `str`, `int`,
273
+ `float`, `bool`, `bytes`, `list[...]`, `tuple[...]` or `Optional[...]`.
274
+ Methods, classes, side effects and async code are out of scope for now.
275
+ * Recording stores calls whose arguments and results are JSON-serialisable.
276
+ * Passing means "no difference found on these inputs", not a proof. The generated
277
+ cases make the search much wider than recordings alone; they don't make it complete.
278
+ * This is not a whole-app migration tool. If you want to move an entire service to
279
+ Rust, a record-and-replay tool like [rust-anything](https://github.com/erkamyaman/rust-anything)
280
+ is built for that. oxidize-safe is for the common case where you're staying in
281
+ Python and moving the hot path, and you want stronger evidence before you switch.
282
+
283
+ ## License
284
+
285
+ MIT
@@ -0,0 +1,16 @@
1
+ oxidize_safe/__init__.py,sha256=dcQzZBfkrQKQkChXcc_nVbnUIY2OIMwmWF_Ge-HXp_w,197
2
+ oxidize_safe/bench.py,sha256=jBZ8oFHwPwgXRfcixrs1Z4DMBl096PrbR7TdRcMty-E,889
3
+ oxidize_safe/check.py,sha256=tabuIyf1ib-bVe1Q5r37tT2IQmLMvtyzdyJjzzHu9Q4,10160
4
+ oxidize_safe/cli.py,sha256=ez5C_eLt3wxwcZPUkXEPcVV1LK-XWUTyi5R77YBouxU,5006
5
+ oxidize_safe/init.py,sha256=Hx7DWAC03O9Vmeh6z1sRjznJwRe28P337E1_K871RZU,5725
6
+ oxidize_safe/pitfalls.py,sha256=LTD7QTcmRJtmT1TiMy7P8niCOVdeWaoXxwOc80GgcT0,4018
7
+ oxidize_safe/record.py,sha256=UfyRNZyMmQ_73bfX5csOF6PxhpKC7zd1tyxRjkZpz60,2092
8
+ oxidize_safe/strategies.py,sha256=x1gLlCxQNGuUAJj-L9ue-ebLvtSZcYa3G9N1Gm9OtOo,3533
9
+ oxidize_safe/swap.py,sha256=6J6pZeo-GTuCMVtY-bXrTuIBbO2FnV-JeGS_jkQu7GM,1496
10
+ oxidize_safe/target.py,sha256=KOEoXF91usKglMHumbUlD4QCvtYDv70oSphBiqKLxM0,729
11
+ oxidize_safe-0.3.0.dist-info/licenses/LICENSE,sha256=kaF0CCoTSP7VzMI5qrF_rWbJ-amiH_N07Mtxz8C7WPc,1090
12
+ oxidize_safe-0.3.0.dist-info/METADATA,sha256=Nx3da8kzK4GqhFwGydBScIejv0oKPDP5T2Yyf3MVSCo,12344
13
+ oxidize_safe-0.3.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
14
+ oxidize_safe-0.3.0.dist-info/entry_points.txt,sha256=0tMA0X_qdSJctqBJM-oC6diYgyMcRnATAGrqpzMG6bg,55
15
+ oxidize_safe-0.3.0.dist-info/top_level.txt,sha256=lBKIoTtKmFB42I4O4IWk34_BK-slNXPDFVkRNZ0rcAg,13
16
+ oxidize_safe-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ oxidize-safe = oxidize_safe.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ahmed Elalfy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ oxidize_safe