oxidize-safe 0.3.0__tar.gz

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,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,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,261 @@
1
+ # oxidize-safe
2
+
3
+ **Move a slow Python function to Rust, and prove it still behaves the same, including on the inputs your real traffic never sends.**
4
+
5
+ Coding agents can now port a Python function to Rust in minutes. The usual way to
6
+ check the port is to record what the original does in a real run and replay it.
7
+ That catches a lot, but it only proves the cases you happened to record. Python
8
+ and Rust quietly disagree in places real traffic rarely goes: non-ASCII text,
9
+ emoji, integers past 2⁶³, NaN, empty inputs, library heuristics that switch on
10
+ at a size threshold.
11
+
12
+ `oxidize-safe` checks a port against the original on **recorded cases and
13
+ generated edge cases aimed at exactly those differences**, tells you *which*
14
+ difference broke it, and only lets your app use the Rust version once it passes.
15
+ You keep your Python app. Only the hot function moves.
16
+
17
+ ![oxidize-safe catching a Rust port that passes every recorded case](docs/demo.gif)
18
+
19
+ ## The demo: a port that passes every recorded case and is still wrong
20
+
21
+ The target is `difflib.SequenceMatcher(None, a, b).ratio()`: pure Python, used
22
+ for fuzzy matching everywhere, slow on long text. `examples/difflib_ratio` has
23
+ two Rust ports, built with [PyO3](https://pyo3.rs):
24
+
25
+ * `ratio_naive`: the port you typically get first. Clean, fast, and works on bytes.
26
+ * `ratio`: the faithful port. Works on Unicode code points and implements difflib's
27
+ "autojunk" heuristic.
28
+
29
+ First, record real traffic from a CLI "did you mean?" suggester:
30
+
31
+ ```
32
+ $ oxidize-safe --path . record original:ratio --run workload.py --out cases.jsonl
33
+ recorded 1798 distinct calls to original:ratio -> cases.jsonl
34
+ ```
35
+
36
+ Then check the naive port:
37
+
38
+ ```
39
+ $ oxidize-safe --path . check original:ratio difflib_rs:ratio_naive --cases cases.jsonl
40
+
41
+ recorded cases 1798/1798 match
42
+ generated cases 454/500 match
43
+
44
+ mismatches by pitfall:
45
+ non-ascii 46 Python strings are code points; Rust &str is UTF-8 bytes.
46
+ long-sequence 41 Library heuristics often switch on at a size threshold
47
+ (difflib's autojunk starts at 200).
48
+ astral-char 3 Characters outside the BMP are 4 UTF-8 bytes and 1 Python char.
49
+
50
+ simplest failing input per pitfall (shrunk):
51
+ [astral-char] args=('0', '0🏽')
52
+ python -> 0.6666666666666666 rust -> 0.3333333333333333
53
+ [long-sequence] args=('0a', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa... (210 chars)
54
+ python -> 0.0 rust -> 0.009900990099009901
55
+ [non-ascii] args=('0', '0ß')
56
+ python -> 0.6666666666666666 rust -> 0.5
57
+
58
+ verdict: FAIL, keep the Python version
59
+ ```
60
+
61
+ **Every one of the 1,798 recorded cases matched.** A replay-only check would have
62
+ shipped this port. The generated cases found two real bugs, and the report names both:
63
+
64
+ 1. **Bytes vs characters.** `'ß'` is one Python character but two UTF-8 bytes, so
65
+ `('0', '0ß')` is "1 of 3 characters differ" to Python and "2 of 4 bytes" to
66
+ the port.
67
+ 2. **A heuristic that only exists past 200 items.** For sequences of 200+, difflib
68
+ treats very common elements as junk. Your recordings were all short commands,
69
+ so they never triggered it.
70
+
71
+ The faithful port:
72
+
73
+ ```
74
+ $ oxidize-safe --path . check original:ratio difflib_rs:ratio --cases cases.jsonl --examples 1000
75
+
76
+ recorded cases 1798/1798 match
77
+ generated cases 1000/1000 match
78
+ pitfalls covered astral-char 72, empty 415, long-sequence 407, non-ascii 548, plain 219
79
+
80
+ verdict: PASS, safe to switch on
81
+ ```
82
+
83
+ And it's worth it:
84
+
85
+ | Workload | Python | Rust | Speed-up |
86
+ |---|---|---|---|
87
+ | 1,798 recorded "did you mean" calls | 9.7 ms | 1.3 ms | 7.7x |
88
+ | Two 500-char paragraphs | 0.4 ms | 0.05 ms | 7x |
89
+ | Two 2,000-char paragraphs | 1.0 ms | 0.11 ms | 9x |
90
+ | Two 8,000-char paragraphs | 3.9 ms | 0.27 ms | 15x |
91
+
92
+ Same result in every case. Measured on one Linux machine, best of 3; rerun with
93
+ `oxidize-safe bench` and `python examples/difflib_ratio/bench_long.py`.
94
+
95
+ ## Second demo: integer division and rounding
96
+
97
+ `examples/numeric` ports two one-liners that look too simple to get wrong:
98
+
99
+ ```python
100
+ def time_bucket(seconds: int, width: int) -> int:
101
+ return seconds // width * width
102
+
103
+ def round_score(score: float) -> int:
104
+ return round(score)
105
+ ```
106
+
107
+ Every recorded case (5,000 real timestamps) matches for every port. The generated
108
+ cases don't:
109
+
110
+ ```
111
+ $ oxidize-safe --path . check original:time_bucket numeric_rs:time_bucket_naive --cases bucket_cases.jsonl
112
+
113
+ recorded cases 5000/5000 match
114
+ generated cases 125/500 match
115
+ note: 41 mismatches raised a different exception type (PanicException means the Rust code panicked)
116
+
117
+ simplest failing input per pitfall (shrunk):
118
+ [int-beyond-i64] args=(1, 9223372036854775808)
119
+ python -> 0 rust -> raises OverflowError
120
+ [negative-int] args=(1, -2)
121
+ python -> 2 rust -> 0
122
+ [zero] args=(0, 0)
123
+ python -> raises ZeroDivisionError rust -> raises PanicException
124
+
125
+ verdict: FAIL, keep the Python version
126
+ ```
127
+
128
+ | Port | What it does | Result |
129
+ |---|---|---|
130
+ | `time_bucket_naive` | `seconds / width * width` on `i64` | FAIL: truncates, panics on 0, can't take big ints |
131
+ | `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`) |
132
+ | `time_bucket` | floor division, `ZeroDivisionError`, Python fallback past `i64` | PASS |
133
+ | `round_score_naive` | `score.round() as i64` | FAIL: `0.5` gives 1 (Python gives 0), NaN gives 0 instead of raising, `1e19` saturates |
134
+ | `round_score` | `round_ties_even`, Python's errors, Python fallback past `i64` | PASS |
135
+
136
+ This demo is about correctness, not speed: on functions this small the cost of
137
+ crossing from Python to Rust dominates (about 1.3x). Port hot loops, not one-liners.
138
+
139
+ ## Let an agent do the loop
140
+
141
+ `skills/oxidize-port/SKILL.md` is a Claude Code skill that closes the loop: the
142
+ agent scaffolds the crate, writes the port, runs `check`, reads the mismatches
143
+ by pitfall, fixes one cause at a time and repeats until it passes. The check is
144
+ the judge, and the skill forbids the shortcuts (editing cases, lowering
145
+ `--examples`, catching panics and calling Python instead).
146
+
147
+ Install it for your user or for one project:
148
+
149
+ ```bash
150
+ cp -r skills/oxidize-port ~/.claude/skills/ # or .claude/skills/ in your repo
151
+ ```
152
+
153
+ Then ask Claude Code to "port `mod:func` to Rust". Here is the run that produced
154
+ `examples/slugify`, porting this:
155
+
156
+ ```python
157
+ def slugify(title: str, max_len: int) -> str:
158
+ words = re.findall(r"\w+", title.lower())
159
+ return "-".join(words)[:max_len]
160
+ ```
161
+
162
+ | Round | Port | Check | What the report pointed at |
163
+ |---|---|---|---|
164
+ | 1 | split on `!is_alphanumeric()`, `max_len: usize`, byte slice | 231/500 | `('', -1)` raises OverflowError; `('00ß', 3)` panics mid-character |
165
+ | 2 | Python slice semantics on chars, big ints clamp | 498/500 | `('_', 1)`: untagged, so the logic differs. `\w` includes `_` |
166
+ | 3 | treat `_` as a word character | 2000/2000 | PASS, 3.8x faster |
167
+
168
+ Scaffold a port yourself with:
169
+
170
+ ```bash
171
+ oxidize-safe --path . init mod:func # ./func-rs/ with a stub, the Python source and its pitfalls
172
+ ```
173
+
174
+ ## Using the Rust version safely
175
+
176
+ ```python
177
+ from oxidize_safe import swap
178
+ from mylib.fuzzy import ratio as _ratio
179
+
180
+ ratio = swap(_ratio, "difflib_rs:ratio")
181
+ ```
182
+
183
+ `swap` returns the Rust function only if `oxidize-safe check` passed **for this
184
+ exact build** (the compiled module's SHA-256 is stored in `.oxidize-safe/lock.json`).
185
+ If the check failed, was never run, or the module was rebuilt since, you get the
186
+ original Python function back with a warning. A bad build can't silently replace
187
+ working code.
188
+
189
+ ## How it works
190
+
191
+ 1. **`record`** runs your script with the function wrapped and saves each distinct
192
+ call's arguments and result as JSONL.
193
+ 2. **`check`** compares the port with the original on:
194
+ * every recorded case, and
195
+ * Hypothesis-generated cases built from the function's type hints, biased
196
+ towards known Python/Rust differences: accented and CJK text, emoji, combining
197
+ characters, 200–600-character strings over small alphabets, integers just
198
+ past i64/u64, NaN/±inf/-0.0, and empty values.
199
+ 3. Comparison is strict: same type, same value, NaN equals NaN, `0.0` is not `-0.0`,
200
+ and both sides must raise the *same* exception type. A Rust panic arrives as
201
+ `PanicException` and counts as a mismatch, not a crash; its backtrace is kept
202
+ out of your terminal.
203
+ 4. Every mismatch is tagged with the pitfalls its inputs trigger, so the report
204
+ says *why*.
205
+ 5. For each pitfall, Hypothesis shrinks the failure to the simplest input that
206
+ still fails, preferring one that triggers only that pitfall, so each example
207
+ shows one cause. `--no-shrink` skips this.
208
+ 6. Mismatches whose inputs trigger no known pitfall are reported as `untagged`
209
+ (the logic itself differs) and shrunk the same way.
210
+ 7. Generation is deterministic, so the same port always gets the same report.
211
+
212
+ ## Pitfalls it targets today
213
+
214
+ | Tag | What goes wrong |
215
+ |---|---|
216
+ | `non-ascii` | Python strings are code points, Rust `&str` is UTF-8 bytes |
217
+ | `astral-char` | Emoji and rare CJK: 1 Python char, 4 bytes, 2 UTF-16 units |
218
+ | `long-sequence` | Size-triggered behaviour in libraries (200+ items) |
219
+ | `empty` | Empty strings and lists hit edge branches |
220
+ | `int-beyond-i64` | Python ints never overflow; Rust integers wrap, panic or fail to convert |
221
+ | `negative-int` | Python `//` and `%` floor; Rust `/` and `%` truncate, and `div_euclid` differs for negative divisors |
222
+ | `zero` | Division by zero raises in Python and panics in Rust |
223
+ | `half-float` | Python `round()` rounds halves to even; `f64::round` rounds away from zero |
224
+ | `float-beyond-i64` | `as i64` silently saturates; Python returns the exact integer |
225
+ | `float-special` | NaN, infinities and -0.0 |
226
+
227
+ ## Quick start
228
+
229
+ ```bash
230
+ pip install -e '.[dev]'
231
+
232
+ # build the demo port (needs a Rust toolchain)
233
+ cd examples/difflib_ratio
234
+ maturin develop --release
235
+
236
+ oxidize-safe --path . check original:ratio difflib_rs:ratio --cases cases.jsonl
237
+ ```
238
+
239
+ The test suite runs without Rust (it uses pure-Python stand-ins that reproduce
240
+ each bug class) and also exercises the real Rust demo when it's built:
241
+
242
+ ```bash
243
+ pytest -q
244
+ ```
245
+
246
+ ## Scope and limits
247
+
248
+ * **One function at a time**, with positional arguments typed as `str`, `int`,
249
+ `float`, `bool`, `bytes`, `list[...]`, `tuple[...]` or `Optional[...]`.
250
+ Methods, classes, side effects and async code are out of scope for now.
251
+ * Recording stores calls whose arguments and results are JSON-serialisable.
252
+ * Passing means "no difference found on these inputs", not a proof. The generated
253
+ cases make the search much wider than recordings alone; they don't make it complete.
254
+ * This is not a whole-app migration tool. If you want to move an entire service to
255
+ Rust, a record-and-replay tool like [rust-anything](https://github.com/erkamyaman/rust-anything)
256
+ is built for that. oxidize-safe is for the common case where you're staying in
257
+ Python and moving the hot path, and you want stronger evidence before you switch.
258
+
259
+ ## License
260
+
261
+ MIT
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "oxidize-safe"
7
+ version = "0.3.0"
8
+ description = "Move a slow Python function to Rust, and prove it still behaves the same, including on the edge cases a recorded run never hits."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Ahmed Elalfy" }]
14
+ keywords = ["rust", "pyo3", "hypothesis", "property-based-testing", "differential-testing", "performance"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Rust",
20
+ "Topic :: Software Development :: Testing",
21
+ "Framework :: Hypothesis",
22
+ ]
23
+ dependencies = ["hypothesis>=6.100"]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/ahmedelalfiee/oxidize-safe"
27
+ Issues = "https://github.com/ahmedelalfiee/oxidize-safe/issues"
28
+
29
+ [project.optional-dependencies]
30
+ dev = ["pytest>=8", "maturin>=1.5,<2"]
31
+
32
+ [project.scripts]
33
+ oxidize-safe = "oxidize_safe.cli:main"
34
+
35
+ [tool.setuptools.packages.find]
36
+ where = ["src"]
37
+
38
+ [tool.pytest.ini_options]
39
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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__"]
@@ -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))