-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Fix int respect sys.set_int_max_str_digits
value
#6094
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Fix int respect sys.set_int_max_str_digits
value
#6094
Conversation
WalkthroughAdds a pre-validation step in PyObject::try_int to enforce a maximum digit length when converting strings to integers, returning a ValueError if exceeded; otherwise, proceeds with the existing conversion flow. No public API signatures changed. Changes
Sequence Diagram(s)sequenceDiagram
participant Caller
participant PyObject.try_int
participant VMState
participant Converter
Caller->>PyObject.try_int: convert PyStr to int
PyObject.try_int->>PyObject.try_int: trim and get bytes (val)
PyObject.try_int->>VMState: read int_max_str_digits
alt max_len > 0 and len(val) > max_len (+ sign)
PyObject.try_int-->>Caller: ValueError (digits limit exceeded)
else
PyObject.try_int->>Converter: try_convert(val)
Converter-->>PyObject.try_int: int or error
PyObject.try_int-->>Caller: result or error
end
Estimated code review effort🎯 2 (Simple) | ⏱️ ~7 minutes Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (1)
vm/src/protocol/number.rs (1)
79-88
: Add tests to lock in semantics (sign, underscores, bytes-like, boundary conditions).Please add/update tests to cover:
- Exactly at the limit vs. exceeding by 1 (positive and negative).
- Underscores are ignored in the count (e.g., "1_234_567" with limit 7 passes; with 6 fails).
- Leading/trailing whitespace (str and bytes-like).
- bytes, bytearray, and other bytes-like objects enforce the same limit.
- Limit disabled (set to 0) allows arbitrarily long inputs.
- Mixed inputs that would be invalid literals (e.g., "9"*N + "x"); verify limit vs. invalid-literal precedence matches CPython.
Example Python-level cases (pseudo):
- set_int_max_str_digits(5); int("+" + "1"*5) ok; int("-" + "1"*6) ValueError; int("1_2_3_4_5") ok; int(b" 123456 ") ValueError.
I can draft these tests if helpful.
📜 Review details
Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (2)
Lib/test/test_int.py
is excluded by!Lib/**
Lib/test/test_json/test_decode.py
is excluded by!Lib/**
📒 Files selected for processing (1)
vm/src/protocol/number.rs
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs
📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)
**/*.rs
: Follow the default rustfmt code style (cargo fmt
to format)
Always run clippy to lint code (cargo clippy
) before completing tasks. Fix any warnings or lints that are introduced by your changes
Follow Rust best practices for error handling and memory management
Use the macro system (pyclass
,pymodule
,pyfunction
, etc.) when implementing Python functionality in Rust
Files:
vm/src/protocol/number.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
- GitHub Check: Run snippets and cpython tests (macos-latest)
- GitHub Check: Run snippets and cpython tests (windows-latest)
- GitHub Check: Run rust tests (windows-latest)
- GitHub Check: Run snippets and cpython tests (ubuntu-latest)
- GitHub Check: Check the WASM package and demo
- GitHub Check: Run rust tests (ubuntu-latest)
- GitHub Check: Check Rust code with rustfmt and clippy
- GitHub Check: Ensure compilation on various targets
- GitHub Check: Run tests under miri
- GitHub Check: Run snippets and cpython tests on wasm-wasi
let val = s.as_wtf8().trim().as_bytes(); | ||
let max_len = vm.state.int_max_str_digits.load(); | ||
if max_len > 0 { | ||
let sign_len = usize::from(matches!(val.first(), Some(b'+' | b'-'))); | ||
let val_len = val.len(); | ||
if val_len > max_len + sign_len { | ||
return Err(vm.new_value_error(format!("Exceeds the limit ({max_len} digits) for integer string conversion: value has {val_len} digits; use sys.set_int_max_str_digits() to increase the limit"))); | ||
} | ||
} | ||
try_convert(self, val, vm) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Apply the same digit-limit enforcement to bytes-like inputs (PyBytes, PyByteArray, ArgBytesLike).
Per CPython, sys.set_int_max_str_digits applies to “string or bytes-like” conversions. The current change only guards PyStr; PyBytes, PyByteArray, and other bytes-like paths bypass the limit.
Recommend extracting the check into a shared helper and invoking it for all three branches, e.g.:
fn enforce_int_max_str_digits(vm: &VirtualMachine, buf: &[u8]) -> PyResult<()> {
let max_len = vm.state.int_max_str_digits.load();
if max_len == 0 {
return Ok(());
}
// Skip leading ASCII whitespace
let mut i = 0usize;
while i < buf.len() && buf[i].is_ascii_whitespace() {
i += 1;
}
// Skip optional sign
if i < buf.len() && matches!(buf[i], b'+' | b'-') {
i += 1;
}
// Count ASCII digits; ignore underscores; stop at first non-digit/underscore
let mut digits = 0usize;
while i < buf.len() {
match buf[i] {
b'0'..=b'9' => {
digits += 1;
if digits > max_len {
return Err(vm.new_value_error(format!(
"Exceeds the limit ({max_len} digits) for integer string conversion: value has {digits} digits; use sys.set_int_max_str_digits() to increase the limit"
)));
}
}
b'_' => {}
_ => break,
}
i += 1;
}
Ok(())
}
Then:
- In the PyStr branch, call
enforce_int_max_str_digits(vm, val)?;
beforetry_convert
. - In the PyBytes branch:
let val = bytes; enforce_int_max_str_digits(vm, val)?; try_convert(self, val, vm)
- In the PyByteArray branch:
let buf = bytearray.borrow_buf(); enforce_int_max_str_digits(vm, &buf)?; try_convert(self, &buf, vm)
- In the ArgBytesLike branch:
let buf = buffer.borrow_buf(); enforce_int_max_str_digits(vm, &buf)?; try_convert(self, &buf, vm)
This aligns behavior with CPython and prevents bypassing the limit via bytes-like inputs.
🤖 Prompt for AI Agents
In vm/src/protocol/number.rs around lines 79 to 88, the current digit-limit
enforcement is only applied to PyStr inputs and lets
PyBytes/PyByteArray/ArgBytesLike bypass sys.set_int_max_str_digits; add a shared
helper (e.g., enforce_int_max_str_digits(vm, buf: &[u8]) -> PyResult<()>) that
reads vm.state.int_max_str_digits, skips leading ASCII whitespace, optionally
skips a leading '+'/'-', then counts ASCII digits while ignoring underscores and
stops at first non-digit/underscore, returning the same ValueError message when
digits exceed the limit; call this helper before try_convert in the PyStr branch
and also in the PyBytes, PyByteArray (use borrowed buffer), and ArgBytesLike
branches so bytes-like inputs are validated the same way as strings.
Incorrect limit check: raw byte length counts non-digits and misreports; count actual digits (ignore sign and underscores).
The current check uses val.len()
and adjusts for a leading sign. This will:
- Over-count when underscores are present (valid numeric separators) and incorrectly raise a ValueError.
- Misreport “digits” when the string contains non-digits (e.g., trailing junk, non-ASCII), leading to false positives.
- Potentially report an inaccurate “value has {val_len} digits” number.
You should count only ASCII decimal digits, ignore a leading '+'/'-', ignore underscores, and stop at the first non-digit/underscore. Also, use the computed digit count in the error message.
Apply this diff within the changed block:
- let val = s.as_wtf8().trim().as_bytes();
- let max_len = vm.state.int_max_str_digits.load();
- if max_len > 0 {
- let sign_len = usize::from(matches!(val.first(), Some(b'+' | b'-')));
- let val_len = val.len();
- if val_len > max_len + sign_len {
- return Err(vm.new_value_error(format!("Exceeds the limit ({max_len} digits) for integer string conversion: value has {val_len} digits; use sys.set_int_max_str_digits() to increase the limit")));
- }
- }
- try_convert(self, val, vm)
+ let val = s.as_wtf8().trim().as_bytes();
+ // Enforce sys.set_int_max_str_digits on the actual number of digits,
+ // ignoring an optional sign and valid underscores.
+ let max_len = vm.state.int_max_str_digits.load();
+ if max_len > 0 {
+ // Skip optional leading sign.
+ let mut iter = val.iter().copied();
+ if matches!(iter.clone().next(), Some(b'+' | b'-')) {
+ iter.next();
+ }
+ // Count ASCII digits; ignore underscores; stop at first non-digit/underscore.
+ let mut digits = 0usize;
+ for b in iter {
+ match b {
+ b'0'..=b'9' => {
+ digits += 1;
+ if digits > max_len {
+ return Err(vm.new_value_error(format!(
+ "Exceeds the limit ({max_len} digits) for integer string conversion: value has {digits} digits; use sys.set_int_max_str_digits() to increase the limit"
+ )));
+ }
+ }
+ b'_' => {}
+ _ => break,
+ }
+ }
+ }
+ try_convert(self, val, vm)
🤖 Prompt for AI Agents
In vm/src/protocol/number.rs around lines 79 to 88, the length check currently
uses the raw byte length (adjusted only for a leading sign), which over-counts
when underscores or non-digit bytes are present and misreports the number of
digits; instead, iterate bytes starting after an optional leading '+' or '-',
count only ASCII digits (ignore '_' underscores), stop counting at the first
byte that is neither a digit nor an underscore, and use that computed
digit_count for both the limit comparison and the error message (i.e., if
digit_count > max_len then return Err with a message that uses digit_count and
max_len). Ensure underscores are skipped in the count and that the sign is not
counted as a digit.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good catch!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ShaharNaveh Thank you! I'm glad the analysis was helpful in identifying the digit counting issue. The fix should ensure proper compliance with sys.set_int_max_str_digits
by accurately counting only the actual numeric digits while ignoring underscores and signs.
Let me know if you need any assistance with implementing the corrections for both the digit counting logic and extending the validation to bytes-like inputs!
🐰✨
Happy to help catch those tricky edge cases!
(\ /)
( ..)
o(")(")
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
Summary by CodeRabbit