Skip to content

Validate TextIOWrapper chunk size#8265

Open
shAn-kor wants to merge 1 commit into
RustPython:mainfrom
shAn-kor:fix-textiowrapper-chunk-size-validation
Open

Validate TextIOWrapper chunk size#8265
shAn-kor wants to merge 1 commit into
RustPython:mainfrom
shAn-kor:fix-textiowrapper-chunk-size-validation

Conversation

@shAn-kor

@shAn-kor shAn-kor commented Jul 12, 2026

Copy link
Copy Markdown

Summary

TextIOWrapper._CHUNK_SIZE setter가 CPython과 동일하게 값을 검증하도록 수정합니다.

기존에는 usize로 바로 변환되면서 다음 값들이 정상적으로 설정될 수 있었습니다.

  • 0
  • 음수
  • isize 범위를 벗어난 큰 정수

이번 변경에서는 다음 동작을 적용합니다.

  • 0 이하의 값은 ValueError 발생
  • 인덱스 정수로 변환할 수 없는 값은 TypeError 발생
  • isize 범위를 벗어나는 정수는 ValueError 발생
  • __index__()를 제공하는 객체는 정상적으로 허용

동작을 검증하기 위한 extra snippet 테스트도 추가했습니다.

Tests

cd extra_tests
pytest -v snippets/stdlib_io.py

Summary by CodeRabbit

  • Bug Fixes

    • Improved validation when assigning TextIOWrapper._CHUNK_SIZE.
    • Invalid, non-positive, or excessively large values now produce appropriate errors.
    • Values supporting integer conversion through __index__ are accepted correctly.
    • Deleting _CHUNK_SIZE continues to raise an attribute error.
  • Tests

    • Added coverage for invalid numeric values, unsupported types, and custom indexable objects.

Match CPython for non-positive, oversized, and index-compatible values.

Assisted-by: Codex:GPT-5
@coderabbitai

coderabbitai Bot commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

The _CHUNK_SIZE setter now accepts indexable values, validates positive index-sized integers, preserves deletion errors, and reports conversion failures. Tests cover invalid values and custom __index__ objects.

TextIOWrapper chunk size validation

Layer / File(s) Summary
Setter parsing and validation
crates/vm/src/stdlib/_io.rs, extra_tests/snippets/stdlib_io.py
The setter manually converts and validates assigned values, while tests cover invalid integers, non-integer inputs, and custom __index__ objects.

Estimated code review effort: 2 (Simple) | ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly reflects the main change: validation of TextIOWrapper chunk size handling.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with 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.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
crates/vm/src/stdlib/_io.rs (1)

3208-3230: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Setter logic matches CPython's PyNumber_AsSsize_t semantics.

The order of checks (try_indexTypeError for non-index types; try_to_primitive::<isize>ValueError for overflow; <= 0ValueError) matches CPython's _CHUNK_SIZE setter, which calls PyNumber_AsSsize_t(arg, PyExc_ValueError) (converting overflow into ValueError instead of the default OverflowError) followed by a <= 0 check. The hardcoded 'int' in the overflow message is also consistent with CPython, since by that point the value has already been converted via __index__.

One small note: since chunk_size > 0 is already guaranteed by the preceding check, usize::try_from(chunk_size) can never fail on any supported platform (usize::MAX >= isize::MAX), making the .map_err(...) branch unreachable dead code. Not required, but chunk_size as usize would be simpler.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/vm/src/stdlib/_io.rs` around lines 3208 - 3230, In set_chunksize,
simplify the conversion after the chunk_size <= 0 validation by using a direct
conversion to usize instead of usize::try_from with an unreachable error
mapping; preserve the existing validation and error behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@extra_tests/snippets/stdlib_io.py`:
- Around line 90-104: Replace both `assert False` statements in the invalid
`_CHUNK_SIZE` test loops with explicit `raise AssertionError(...)` calls,
preserving the existing failure messages and exception expectations so the
checks remain active under optimized Python execution.

---

Nitpick comments:
In `@crates/vm/src/stdlib/_io.rs`:
- Around line 3208-3230: In set_chunksize, simplify the conversion after the
chunk_size <= 0 validation by using a direct conversion to usize instead of
usize::try_from with an unreachable error mapping; preserve the existing
validation and error behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 9a755fa4-7822-40d3-a03b-48d68a59e3ba

📥 Commits

Reviewing files that changed from the base of the PR and between 492e41c and dcd75ef.

📒 Files selected for processing (2)
  • crates/vm/src/stdlib/_io.rs
  • extra_tests/snippets/stdlib_io.py

Comment thread extra_tests/snippets/stdlib_io.py

@ShaharNaveh ShaharNaveh left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

tysm:)

welcome to the project

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.

2 participants