Skip to content

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

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

ShaharNaveh
Copy link
Contributor

@ShaharNaveh ShaharNaveh commented Aug 14, 2025

Summary by CodeRabbit

  • New Features
    • Enforces a maximum digit length when converting strings to integers to prevent overly large inputs.
    • Provides a clear ValueError when the limit is exceeded, including guidance on how to adjust the limit.
    • Allows users to configure the limit via sys.set_int_max_str_digits() for flexibility across use cases.
    • Improves robustness by validating input length before conversion while preserving existing behavior for normal inputs.

Copy link
Contributor

coderabbitai bot commented Aug 14, 2025

Walkthrough

Adds 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

Cohort / File(s) Summary
Int conversion digit-limit check
vm/src/protocol/number.rs
Introduced max digit-length validation for string-to-int conversion using vm.state.int_max_str_digits; computes sign-aware length, raises ValueError with guidance if limit exceeded, else continues with try_convert.

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
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Poem

I nibble digits, one by one—
A carrot-count, then I am done.
Too many? Thump! I set a bound,
"Adjust the limit," echoes round.
With tidy paws, I guard the gate,
Your numbers pass—at measured rate. 🥕✨

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 Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@ShaharNaveh ShaharNaveh marked this pull request as ready for review August 14, 2025 07:41
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between a9a9e3b and 166ac41.

⛔ 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

Comment on lines +79 to +88
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)
Copy link
Contributor

@coderabbitai coderabbitai bot Aug 14, 2025

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)?; before try_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.

⚠️ Potential issue

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.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch!

Copy link
Contributor

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!

@ShaharNaveh ShaharNaveh marked this pull request as draft August 14, 2025 08:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant