Add numeric fast paths for binary arithmetic #1090
<!-- branch-diff -->
Branch diff: numeric-fast-paths
| Commit | Message | Production | Test | Docs | Other |
| --- | --- | --: | --: | --: | --: |
| 2fc8806c5 | Add numeric fast paths for bi… | +44 -1 | +52 -0 | +0 -0 | +0 -0 |
| a41157b8c | Add numeric fast paths for di… | +53 -1 | +68 -0 | +0 -0 | +0 -0 |
| bf10a3555 | Optimize augmented numeric as… | +8 -0 | +88 -11 | +0 -0 | +0 -0 |
| fd006f988 | Outline arithmetic fallbacks … | +3 -0 | +2 -2 | +0 -0 | +0 -0 |
| 7838c2b3a | Add numeric comparison fast p… | +55 -4 | +82 -0 | +0 -0 | +0 -0 |
| bca473441 | Cover subtraction overflow an… | +1 -13 | +8 -0 | +0 -0 | +0 -0 |
| d07b373ac | Restrict numeric comparison f… | +13 -14 | +16 -0 | +0 -0 | +0 -0 |
| | TOTAL | +147 -3 | +303 -0 | +0 -0 | +0 -0 |
<!-- cubic:review-summary:start -->
All reported issues were addressed across 2 files
<!-- cubic:review-summary:end -->
<sub>Reply with feedback, questions, or to request a fix.<br /><br />View guided diff | Re-trigger cubic</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_037b16113ac463257089232b1d50887ee9e1583cb84635856fdbba2f6c09f591:2fc8806c56f33a7773f21c50f5b84332eece920b:96771f28-92cc-57ea-81f0-5aace2bba8db -->
<!-- cubic:v=6dc4b87c-a7e2-406f-8e2c-b8e601b052b8 -->
<!-- cubic:review-run=96771f28-92cc-57ea-81f0-5aace2bba8db -->
<!-- metadata:{"confidence":9} -->
P2: run_no_limits discards RefCountOutput under the ref-count-return configuration, so this test cannot detect leaked heap entries from the new fast path. Run this script with run_ref_counts there and assert unreachable is empty.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/tests/binary_numeric.rs, line 51:
<comment>`run_no_limits` discards `RefCountOutput` under the `ref-count-return` configuration, so this test cannot detect leaked heap entries from the new fast path. Run this script with `run_ref_counts` there and assert `unreachable` is empty.</comment>
<file context>
@@ -0,0 +1,52 @@
+signed_zero(2, -0.0)
+";
+ let mut runner = MontyRun::new(code.to_owned(), "test.py", vec![], CompileOptions::default()).unwrap();
+ runner.run_no_limits(vec![]).unwrap();
+}
</file context>
</details>
#[cfg(feature = "ref-count-return")]
{
let output = runner.run_ref_counts(vec![]).unwrap();
assert!(output.unreachable.is_empty(), "leaked {:?}", output.unreachable);
}
#[cfg(not(feature = "ref-count-return"))]
runner.run_no_limits(vec![]).unwrap();
✅ Addressed in bf10a35
<!-- cubic:v=1a852710-8546-4c2d-9f6a-25f85883c198 -->
<!-- cubic:review-run=96771f28-92cc-57ea-81f0-5aace2bba8db -->
<!-- metadata:{"confidence":10} -->
P2: These BigInt cases compute expected arithmetic with Monty before calling check, so a wrong result can make both expected and actual values wrong. Use literal expected values to independently validate the BigInt path.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/tests/binary_numeric.rs, line 26:
<comment>These BigInt cases compute expected arithmetic with Monty before calling `check`, so a wrong result can make both expected and actual values wrong. Use literal expected values to independently validate the BigInt path.</comment>
<file context>
@@ -0,0 +1,52 @@
+check(-9223372036854775808, -1, -9223372036854775809, -9223372036854775807, 9223372036854775808)
+
+big = 1 << 100
+check(big, 2, big + 2, big - 2, big * 2)
+check(2, big, big + 2, 2 - big, big * 2)
+check(big, big, 1 << 101, 0, 1 << 200)
</file context>
</details>
check(big, 2, 1267650600228229401496703205378, 1267650600228229401496703205374, 2535301200456458802993406410752)
check(2, big, 1267650600228229401496703205378, -1267650600228229401496703205374, 2535301200456458802993406410752)
check(big, big, 2535301200456458802993406410752, 0, 1606938044258990275541962092341162602522202993782792835301376)
check(big, 2.0, 1.2676506002282294e30, 1.2676506002282294e30, 2.535301200456459e30)
check(2.0, big, 1.2676506002282294e30, -1.2676506002282294e30, 2.535301200456459e30)
✅ Addressed in bf10a35
<!-- cubic:v=3046eaa1-fe25-4913-a3b2-1dd329628836 -->
<!-- cubic:review-run=96771f28-92cc-57ea-81f0-5aace2bba8db -->
<!-- metadata:{"confidence":8} -->
P3: These entry points now scan both operands in the VM even when the operation cannot use the fast path, then perform the existing dispatch anyway. Keep the specialization behind the numeric value abstraction or otherwise avoid this unconditional pre-dispatch check for generic operands, and benchmark nonnumeric arithmetic to prevent a regression.
(Based on your team's feedback about VM-level type-specific dispatch.) [127709c5-6274-40ca-8065-b0c42034e211]
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/bytecode/vm/binary.rs, line 31:
<comment>These entry points now scan both operands in the VM even when the operation cannot use the fast path, then perform the existing dispatch anyway. Keep the specialization behind the numeric value abstraction or otherwise avoid this unconditional pre-dispatch check for generic operands, and benchmark nonnumeric arithmetic to prevent a regression.
(Based on your team's feedback about VM-level type-specific dispatch.) [127709c5-6274-40ca-8065-b0c42034e211]</comment>
<file context>
@@ -28,16 +28,28 @@ impl VM<'_> {
/// Binary addition.
pub(super) fn binary_add(&mut self) -> Result<(), RunError> {
+ if self.binary_numeric(i64::checked_add, |lhs, rhs| lhs + rhs, |lhs, rhs| lhs + rhs) {
+ return Ok(());
+ }
</file context>
</details>
<a href="https://www.cubic.dev/action/fix/violation/3046eaa1-fe25-4913-a3b2-1dd329628836" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://cubic.dev/buttons/fix-with-cubic-light.svg">
<img alt="Fix with cubic" src="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
</picture>
</a>
_Auto response from GPT-6 in Codex running fix-pr-comments:_ Confirmed. Both numeric test scripts now use a shared runner that calls run_ref_counts under ref-count-return and asserts that unreachable is empty. Both scripts pass with the leak assertions enabled. The fix is in the local working tree and has not been committed or pushed yet.
_Auto response from GPT-6 in Codex running fix-pr-comments:_ Confirmed. Replaced the BigInt arithmetic expectations with independent integer and float literals, including the BigInt division case added locally. Both scripts pass with reference-count leak checks enabled. The fix is in the local working tree and has not been committed or pushed yet.
_Auto response from GPT-6 in Codex running fix-pr-comments:_ The extra type checks on fallback operands are real, but a performance regression has not been measured. Checking the operand stack before cleanup guards is the intended optimization here; moving the specialization into the numeric abstraction would retain that guard overhead. I am leaving this thread open pending comparative numeric and nonnumeric benchmarks rather than claiming either a regression or a speedup.
Codecov Report
:white_check_mark: All modified and coverable lines are covered by tests.
:loudspeaker: Thoughts on this report? Let us know!
<!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->
Merging this PR will regress 1 benchmark
<details>
<summary><b>2 warnings</b></summary>
:warning: 10 benchmarks are dominated by system calls
> System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.
> Learn more about system calls
> See affected benchmarks
:warning: 15 benchmarks with a significant change ran on different hardware
> Their base and head results were measured on machines with a different CPU, core count or memory, so the changes might not come from the code. Run base and head on the same runner type.
> Learn more about Macro Runners
> See affected benchmarks
</details>
⚡ 14 improved benchmarks ❌ 1 regressed benchmark ✅ 111 untouched benchmarks ⏩ 92 skipped benchmarks[^skipped]
[!WARNING]
Please fix the performance issues or acknowledge them on CodSpeed.
Performance Changes
| | Mode | Benchmark | BASE | HEAD | Efficiency |
| --- | ---- | --------- | ------ | ------ | ---------- |
| ❌ | CPU Simulation | ` session_dump__monty | 2.2 ms | 2.5 ms | -12.42% |
| ⚡ | CPU Simulation | pyperformance_spectral_norm__monty | 122.9 ms | 87 ms | +41.25% |
| ⚡ | CPU Simulation | loop_mod_13__monty | 1,099.4 µs | 809.8 µs | +35.76% |
| ⚡ | CPU Simulation | loop_mod_13_limits__monty | 1,107.9 µs | 818.4 µs | +35.37% |
| ⚡ | CPU Simulation | fib__monty | 399.1 ms | 303.7 ms | +31.44% |
| ⚡ | CPU Simulation | string_random_access_interned_ascii__monty | 31 ms | 23.8 ms | +30.54% |
| ⚡ | CPU Simulation | pyperformance_nbody__monty | 100.9 ms | 79 ms | +27.64% |
| ⚡ | CPU Simulation | string_random_access_ascii__monty | 33.8 ms | 26.5 ms | +27.36% |
| ⚡ | CPU Simulation | dict_comp__monty | 1.5 ms | 1.2 ms | +19.16% |
| ⚡ | CPU Simulation | string_end_access_unicode__monty | 26.1 ms | 22.7 ms | +14.78% |
| ⚡ | CPU Simulation | str_index_scan__monty | 101.7 ms | 89.1 ms | +14.13% |
| ⚡ | CPU Simulation | pyperformance_barnes_hut__monty | 99.3 ms | 88.2 ms | +12.59% |
| ⚡ | CPU Simulation | pyperformance_fannkuch__monty | 21 ms | 18.8 ms | +11.52% |
| ⚡ | CPU Simulation | pair_tuples__monty | 166.1 ms | 150.1 ms | +10.66% |
| ⚡ | CPU Simulation | attr_dispatch_minimal__monty | 57.6 ms | 52.3 ms | +10.13% |
[!TIP]
Investigate this regression by commenting @codspeedbot fix this regression` on this PR, or directly use the CodSpeed MCP with your agent.
---
<sub>Comparing <code>jaheba:numeric-fast-paths</code> (ca6e090) with <code>main</code> (2118ee0)</sub>
<a href="https://app.codspeed.io/pydantic/monty/branches/jaheba%3Anumeric-fast-paths?utm_source=github&utm_medium=comment-v2&utm_content=button">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
<img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
</picture>
</a>
[^skipped]: 92 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.
<!-- cubic:v=7b039d6b-5ea7-4a5b-b3e7-9a3f3aa77122 -->
<!-- cubic:review-run=46ea1d7a-febe-5412-b05b-078844c2ea39 -->
<!-- metadata:{"confidence":8} -->
P2: #[inline(never)] forces every fallback through an out-of-line call, including operations with no numeric fast path. That adds overhead to &, |, shifts, @, and in-place &=/|= without numeric-path benefit. Remove these attributes or use an outlined strategy only after benchmarking both numeric and generic workloads.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/bytecode/vm/binary.rs, line 257:
<comment>`#[inline(never)]` forces every fallback through an out-of-line call, including operations with no numeric fast path. That adds overhead to `&`, `|`, shifts, `@`, and in-place `&=`/`|=` without numeric-path benefit. Remove these attributes or use an outlined strategy only after benchmarking both numeric and generic workloads.</comment>
<file context>
@@ -253,6 +253,8 @@ impl VM<'_> {
/// Applies a binary operation while owning stack-value cleanup.
+ /// Kept out of line so cleanup and generic dispatch stay outside numeric fast paths.
+ #[inline(never)]
fn binary_op(
&mut self,
</file context>
</details>
✅ Addressed in 7838c2b
<!-- cubic:review-summary:start -->
All reported issues were addressed across 2 files (changes from recent commits).
<!-- cubic:review-summary:end -->
<sub>Reply with feedback, questions, or to request a fix.<br /><br />View guided diff | Re-trigger cubic</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_ea8449455a19978323ba5d4050e372c3d03a312d17e6cc68c5eee277efcfd7f8:fd006f988eb325f8e6348d1abfc831fe938ddd22:46ea1d7a-febe-5412-b05b-078844c2ea39 -->
_Auto response from Codex (AI) running fix-pr-comments:_ Agreed. Removed both shared #[inline(never)] attributes and the outlining-specific comment locally. This restores the compiler's inlining choice for operators without numeric fast paths as well. We tested outlining against main and the previous PR build: it helped list += and Counter -=, but worsened fresh-worker bytes formatting to roughly 10% above main and gave variable BigInt results, so it was not a consistent fix. Arithmetic and comparison tests pass with explicit unreachable-heap assertions; targeted Clippy passes with warnings denied. The removal is not committed or pushed yet.
_Auto response from Codex (AI) running fix-pr-comments:_ Benchmarking is now complete. Matching release builds of main 996f6499 and PR bf10a355, measured serially, showed 6.5–42.8% lower latency on immediate numeric arithmetic. The 60–100-sample nonnumeric confirmations also found real small regressions: fresh-worker bytes formatting about +5.7%, list += about +3%, reused-worker Counter operations about +2–2.7%, and timedelta // about +2.8%; BigInt //= showed about +2%. Forcing the shared fallbacks out of line was subsequently tested and was mixed, including worse bytes formatting, so those attributes have now been removed locally. The VM pre-dispatch check remains; moving it behind the numeric abstraction would retain the cleanup-guard overhead this change targets. I am leaving this thread open because benchmarking confirms a tradeoff, not that the nonnumeric regressions are eliminated. Full raw results and source snapshots are retained locally for review.
<!-- cubic:v=7b949efb-752c-409e-b260-20abbd776b9d -->
<!-- cubic:review-run=c31ca55c-e725-5fc0-859c-d57c23c40bcd -->
<!-- metadata:{"confidence":9} -->
P3: These assertions never distinguish identity from numeric equality because both operands reuse the same binding. Test separate equal numeric values, such as 1 and 1.0, so an is fast-path regression cannot pass unnoticed.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/tests/compare_numeric.rs, line 66:
<comment>These assertions never distinguish identity from numeric equality because both operands reuse the same binding. Test separate equal numeric values, such as `1` and `1.0`, so an `is` fast-path regression cannot pass unnoticed.</comment>
<file context>
@@ -63,6 +63,12 @@ except TypeError:
else:
assert False
+number = 1
+result = number is number
+assert result is True
</file context>
</details>
number = 1
other_number = 1.0
result = number is other_number
assert result is False
result = number is not other_number
assert result is True
✅ Addressed in d07b373
<!-- cubic:v=11851063-2f19-4fe4-bd8b-fdbf787d8af7 -->
<!-- cubic:review-run=c31ca55c-e725-5fc0-859c-d57c23c40bcd -->
<!-- metadata:{"confidence":9} -->
P3: This fallback now adds numeric-ordering work to every identity and membership comparison involving immediate numbers, even though those operators cannot use the numeric fast path. Retain an early guard for Eq, NotEq, and the four ordering operators before inspecting the operand stack.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/bytecode/vm/compare.rs, line 137:
<comment>This fallback now adds numeric-ordering work to every identity and membership comparison involving immediate numbers, even though those operators cannot use the numeric fast path. Retain an early guard for `Eq`, `NotEq`, and the four ordering operators before inspecting the operand stack.</comment>
<file context>
@@ -146,7 +134,7 @@ impl VM<'_> {
CmpOperator::Gt => ordering.is_some_and(Ordering::is_gt),
CmpOperator::GtE => ordering.is_some_and(Ordering::is_ge),
- _ => unreachable!("non-numeric comparison operator"),
+ _ => return false,
};
</file context>
</details>
✅ Addressed in d07b373
<!-- cubic:review-summary:start -->
All reported issues were addressed across 3 files (changes from recent commits).
<!-- cubic:review-summary:end -->
<sub>Reply with feedback, questions, or to request a fix.<br /><br />View guided diff | Re-trigger cubic</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_11e58b31143f3e01aa90b76abca3b506e82297c88bb6dddcc2093dcc375332c2:bca473441b791148dba0c4ced18fb7831f04900f:c31ca55c-e725-5fc0-859c-d57c23c40bcd -->
_Auto response from Codex (AI) running fix-pr-comments:_ Added separate bindings for 1 and 1.0, asserting that equality is true while is is false and is not is true. Kept the same-binding identity cases too, and added numeric membership error cases. Comparison tests pass with and without ref-count-return, including explicit unreachable-heap assertions. This fix is local and not committed or pushed yet.
_Auto response from Codex (AI) running fix-pr-comments:_ Fixed by selecting the numeric callback before entering the stack helper. Direct ==/!= supply their callbacks, and compare_op invokes the helper only for the four ordering operators. Identity and membership bypass it entirely. The helper no longer accepts an unrestricted CmpOperator, so no unreachable/default operator arm is needed. Added identity tests distinguishing equal int/float values and numeric membership TypeError tests. Tests and Clippy pass; local LLVM coverage hits every executable line of the changed helper/dispatch block. Changes are local and not committed or pushed yet.
_Auto response from Codex (AI) running fix-pr-comments:_ The arithmetic pre-dispatch performance tradeoff remains open as discussed in the earlier benchmark results; this round does not claim those regressions are fixed. The new comparison-specific finding has been addressed separately so identity and membership avoid numeric stack inspection. No further arithmetic changes were made this round.
_Auto response from Codex (AI) running fix-pr-comments:_ This tradeoff is intentional and is the purpose of this PR: check whether immediate numeric operands can use a faster path before popping them and setting up cleanup guards; otherwise use the existing generic path. Moving the specialization behind the numeric abstraction would retain the guard and dispatch overhead that this optimization is intended to bypass.
We benchmarked both numeric and nonnumeric workloads. There are substantial numeric gains and measured overhead on some nonnumeric workloads, and we accept that tradeoff here. We are keeping the VM-level fast paths and resolving this as an intended design tradeoff.
jaheba
Binary addition, subtraction and multiplication currently pop operands and set up cleanup guards before dispatching by type. Handle immediate int/int, float/float and mixed int/float pairs directly on the operand stack, avoiding those guards and general type dispatch.
Overflowing integer results promote directly to BigInt using the existing i128 conversion helper. Existing BigInt operands and other types retain the general arithmetic path.
Validation: numeric arithmetic tests pass with and without
ref-count-return, covering overflow, BigInt operands, mixed numeric types, booleans, sequence fallbacks and signed zero. Formatting and diff checks pass. Performance has not been benchmarked.<!-- This is an auto-generated description by cubic. -->
---
Summary by cubic
Adds stack fast paths for binary arithmetic and numeric comparisons on immediate int/float operands, covering
+,-,*,/,//,%, their in-place forms, and==,!=,<,<=,>,>=. These avoid reference-count guards and general type dispatch.<sup>Written for commit ca6e09002fbbbad6f85a1b5bdacbd783f62d13c0. Summary will update on new commits.</sup>
<a href="https://cubic.dev/pr/pydantic/monty/pull/1090?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->