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

Open
wants to merge 5 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 configurable maximum digit length when converting strings/bytes to integers.
    • Users can adjust the limit via sys.set_int_max_str_digits().
  • Bug Fixes / Error Handling
    • Clearer, consistent errors for invalid literals, invalid bases, and digit-limit breaches with user-facing messages.
    • Non-string inputs with an explicit base now raise a TypeError instead of a ValueError.

Copy link
Contributor

coderabbitai bot commented Aug 14, 2025

Walkthrough

Centralizes bytes-to-int parsing and error handling: adds a BytesToIntError type and digit-limit enforcement in common::int::bytes_to_int, changes it to return Result, and wires a new handle_bytes_to_int_err mapper into the VM int conversion path and public protocol exports.

Changes

Cohort / File(s) Summary
Common int parsing
common/src/int.rs
Replaced bytes_to_int(lit, base) -> Option<BigInt> with bytes_to_int(buf, base, digit_limit) -> Result<BigInt, BytesToIntError>; added BytesToIntError enum (InvalidLiteral { base }, InvalidBase, DigitLimit { got, limit }); expanded parsing, base detection, underscore rules, digit counting, digit-limit enforcement, and tests.
VM protocol number helper
vm/src/protocol/number.rs
Added pub fn handle_bytes_to_int_err(e: BytesToIntError, obj: &PyObject, vm: &VirtualMachine) -> PyBaseExceptionRef; replaced inline error construction with map_err(handle_bytes_to_int_err) and now passes vm.state.int_max_str_digits into bytes_to_int.
VM builtins int conversion
vm/src/builtins/int.rs
Updated try_int_radix to call bytes_to_int(..., vm.state.int_max_str_digits.load()) for str, bytes, bytearray; map errors via handle_bytes_to_int_err; changed non-string-with-base branch to raise TypeError for non-string inputs with explicit base.
Protocol re-exports
vm/src/protocol/mod.rs
Re-exported handle_bytes_to_int_err from the number module (added to the pub use list).

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant try_int_radix
  participant bytes_to_int
  participant handle_err
  participant VMState

  Caller->>try_int_radix: int(x, base?)
  try_int_radix->>VMState: read int_max_str_digits
  try_int_radix->>bytes_to_int: bytes_to_int(buf, base, digit_limit)
  alt bytes_to_int Ok
    bytes_to_int-->>try_int_radix: BigInt
    try_int_radix-->>Caller: PyInt
  else bytes_to_int Err(BytesToIntError)
    bytes_to_int-->>handle_err: BytesToIntError
    handle_err-->>try_int_radix: PyBaseExceptionRef
    try_int_radix-->>Caller: raise exception
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

I hop through bytes and count each nibble—
I check the max, I keep it nimble.
If digits crowd like carrots tight,
I thump my paw and flash the light:
"Raise the limit," I kindly plead—
A tidy conversion's what I feed. 🥕

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

@ShaharNaveh ShaharNaveh marked this pull request as draft August 14, 2025 08:08
@ShaharNaveh ShaharNaveh force-pushed the fix-int-respect-max-str-sys branch from 166ac41 to e3b894b Compare August 16, 2025 11:04
@ShaharNaveh ShaharNaveh force-pushed the fix-int-respect-max-str-sys branch from 7044f6d to cf834d1 Compare August 16, 2025 11:24
@ShaharNaveh ShaharNaveh marked this pull request as ready for review August 16, 2025 13:35
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: 1

🔭 Outside diff range comments (1)
vm/src/protocol/number.rs (1)

75-84: Bug: Passing PyBytes where &[u8] is expected will not compile

In the PyBytes branch, try_convert expects a byte slice, but bytes is a PyBytes reference. Use .as_bytes().

Apply this fix:

-        } else if let Some(bytes) = self.downcast_ref::<PyBytes>() {
-            try_convert(self, bytes, vm)
+        } else if let Some(bytes) = self.downcast_ref::<PyBytes>() {
+            try_convert(self, bytes.as_bytes(), vm)
🧹 Nitpick comments (1)
common/src/int.rs (1)

153-208: Good tests; consider adding a few more edge cases

  • Ensure digit-limit does not shadow InvalidLiteral: e.g., ("1a...a", 10) where a’s exceed the limit should still be InvalidLiteral.
  • Verify underscore parsing across bases, including 0 auto-base: e.g., ("0_0", 0) and reject ("0x__10", 0).
  • Confirm that power-of-two bases are exempt from the limit, but non-powers like base 3 are limited.

I can draft these if helpful.

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

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

⛔ 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 (4)
  • common/src/int.rs (2 hunks)
  • vm/src/builtins/int.rs (2 hunks)
  • vm/src/protocol/mod.rs (1 hunks)
  • vm/src/protocol/number.rs (3 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/mod.rs
  • vm/src/builtins/int.rs
  • common/src/int.rs
  • vm/src/protocol/number.rs
🧬 Code Graph Analysis (4)
vm/src/protocol/mod.rs (1)
vm/src/protocol/number.rs (1)
  • handle_bytes_to_int_err (560-580)
vm/src/builtins/int.rs (3)
vm/src/protocol/number.rs (3)
  • handle_bytes_to_int_err (560-580)
  • obj (440-442)
  • obj (450-450)
common/src/int.rs (1)
  • bytes_to_int (41-145)
vm/src/builtins/bytearray.rs (2)
  • inner (196-198)
  • borrow_buf (88-90)
common/src/int.rs (1)
compiler/literal/src/float.rs (1)
  • parse_bytes (9-11)
vm/src/protocol/number.rs (1)
common/src/int.rs (1)
  • bytes_to_int (41-145)
🔇 Additional comments (10)
common/src/int.rs (4)

32-37: Public error type looks good and is future-proof

Clear, minimal variants that map well to Python exceptions. Deriving Eq/PartialEq aids testing. No issues.


46-48: Early base validation is correct

Rejecting non-zero bases outside 2..=36 matches CPython. Good placement before any heavy work.


64-77: Base autodetection and “old octal” path mirror CPython semantics

The error_if_nonzero flow aligns with longobject.c behavior. Nicely handled edge cases.


89-103: Prefix handling and single underscore after prefix match PEP 515

Stripping 0x/0o/0b and allowing exactly one underscore after the prefix is correct and matches CPython acceptance of literals like 0x_10.

vm/src/protocol/mod.rs (1)

15-16: Re-exporting handle_bytes_to_int_err is appropriate

Keeps error mapping centralized and available to builtins and other callers.

vm/src/builtins/int.rs (2)

18-19: Importing handle_bytes_to_int_err here keeps error mapping consistent

This avoids duplicating error message strings and ensures parity with protocol paths.


831-849: Digit-limit now enforced for str/bytes/bytearray with consistent error mapping

This addresses the earlier concern about bytes-like inputs bypassing sys.set_int_max_str_digits. The TypeError for non-string with explicit base matches CPython.

vm/src/protocol/number.rs (3)

8-12: New imports are correct and minimal

Brings in BytesToIntError and PyBaseExceptionRef for centralized error mapping. No issues.


50-54: Applying sys.set_int_max_str_digits inside try_int() is the right place

Loading the limit once and passing into bytes_to_int centralizes the guard. Good.


560-580: Centralized error mapping matches CPython messages

  • InvalidLiteral includes repr(obj)
  • InvalidBase wording matches CPython
  • DigitLimit message matches docs and includes both got and limit

Nice consolidation.

Comment on lines +109 to +113
// Leading underscore not allowed
if prev == b'_' || !prev.is_ascii_alphanumeric() {
return Err(BytesToIntError::InvalidLiteral { base });
}

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Count only valid digits for the given base and strip underscores before parsing

Two issues here:

  • The digit counter treats any ASCII alphanumeric as a “digit”, regardless of base. This can raise DigitLimit for inputs that are actually invalid for the base (e.g., many non-decimal letters in base 10), diverging from CPython which counts only valid digits.
  • BigUint::parse_bytes typically does not accept underscores. You validate underscores but don’t strip them before parsing. This can cause valid literals with underscores (e.g., "0_0_0") to parse as InvalidLiteral on backends that don’t ignore underscores.

Recommend:

  • Validate and count only digits that are valid in the resolved base.
  • Remove underscores before calling BigUint::parse_bytes.

Proposed patch:

@@
-    // Leading underscore not allowed
-    if prev == b'_' || !prev.is_ascii_alphanumeric() {
-        return Err(BytesToIntError::InvalidLiteral { base });
-    }
-
-    // Verify all characters are digits and underscores
-    let mut digits = 1;
-    for &cur in buf.iter().skip(1) {
-        if cur == b'_' {
-            // Double underscore not allowed
-            if prev == b'_' {
-                return Err(BytesToIntError::InvalidLiteral { base });
-            }
-        } else if cur.is_ascii_alphanumeric() {
-            digits += 1;
-        } else {
-            return Err(BytesToIntError::InvalidLiteral { base });
-        }
-
-        prev = cur;
-    }
+    // Leading underscore not allowed; also first char must be a valid digit for the base
+    #[inline]
+    fn to_digit(b: u8) -> Option<u32> {
+        match b {
+            b'0'..=b'9' => Some((b - b'0') as u32),
+            b'a'..=b'z' => Some((b - b'a' + 10) as u32),
+            b'A'..=b'Z' => Some((b - b'A' + 10) as u32),
+            _ => None,
+        }
+    }
+    if prev == b'_' || to_digit(prev).map_or(true, |v| v >= base) {
+        return Err(BytesToIntError::InvalidLiteral { base });
+    }
+
+    // Verify all characters are valid digits (for base) or underscores; count only valid digits
+    let mut digits = 1;
+    let mut saw_underscore = false;
+    for &cur in buf.iter().skip(1) {
+        if cur == b'_' {
+            // Double underscore not allowed
+            if prev == b'_' {
+                return Err(BytesToIntError::InvalidLiteral { base });
+            }
+            saw_underscore = true;
+        } else if let Some(v) = to_digit(cur) {
+            if v >= base {
+                return Err(BytesToIntError::InvalidLiteral { base });
+            }
+            digits += 1;
+        } else {
+            return Err(BytesToIntError::InvalidLiteral { base });
+        }
+
+        prev = cur;
+    }
@@
-    if digit_limit > 0 && !base.is_power_of_two() && digits > digit_limit {
+    if digit_limit > 0 && !base.is_power_of_two() && digits > digit_limit {
         return Err(BytesToIntError::DigitLimit {
             got: digits,
             limit: digit_limit,
         });
     }
 
-    let uint = BigUint::parse_bytes(buf, base).ok_or(BytesToIntError::InvalidLiteral { base })?;
+    // Strip underscores before parsing
+    let uint = if saw_underscore {
+        let stripped: Vec<u8> = buf.iter().copied().filter(|&b| b != b'_').collect();
+        BigUint::parse_bytes(&stripped, base)
+    } else {
+        BigUint::parse_bytes(buf, base)
+    }
+    .ok_or(BytesToIntError::InvalidLiteral { base })?;
     Ok(BigInt::from_biguint(sign.unwrap_or(Sign::Plus), uint))

This keeps the same validation rules but ensures:

  • Digit limit uses only base-valid digits.
  • Parsing succeeds for valid literals with underscores.

Also applies to: 114-129, 131-135, 136-142, 143-145

🤖 Prompt for AI Agents
In common/src/int.rs around lines 109-113 (and similarly 114-129, 131-135,
136-142, 143-145), the code currently treats any ASCII alphanumeric as a digit
and passes the raw string (with underscores) to BigUint::parse_bytes; change the
logic to (1) validate characters against the resolved base so only characters
that are valid digits for that base increment the digit counter and any other
alphanumeric character causes InvalidLiteral, and (2) build a new digit-only
byte buffer that strips underscores (but preserves digit characters) and pass
that cleaned buffer to BigUint::parse_bytes; keep existing checks for
leading/trailing/misplaced underscores but ensure underscores are removed before
parsing so literals like "0_0_0" parse correctly.

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