Skip to content

Make Python list append and insert growth fallible - #10168

Open
youknowdot wants to merge 7 commits into
RustPython:mainfrom
youknowdot:fallible-list-growth-3494
Open

youknowdot wants to merge 7 commits into
RustPython:mainfrom
youknowdot:fallible-list-growth-3494

Conversation

@youknowdot

@youknowdot youknowdot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Why

Carry forward the fallible list allocation work proposed by coolreader18 in #3494. The current VM already handles reservation failures in list extension and repetition, but append and insert still used infallible growth. CPython 3.15.2 propagates a failed list resize through its append and insert entry points.

Change

  • Reserve capacity before updating the list mutation counter. Release the write lock before constructing MemoryError on failure.
  • Propagate errors from ordinary append/insert, LIST_APPEND and CALL_LIST_APPEND and the existing internal callers for exception notes, GenericAlias.dir, and zipimport hook insertion.
  • Reuse the existing Rust Vec reservation API and VM MemoryError path instead of introducing the original broad allocation abstraction. No C-API changes or general allocator-recovery claims.

Scope of verification

The standard selectors for list operations/comprehensions, exception notes and GenericAlias directory output passed on both CPython 3.15.2 and RustPython on Linux (11 each). A bounded warm-up exercised both append opcodes; signatures and regular ZIP import also passed. The Rust unit check passed and tests a deterministic capacity rejection without requesting a real allocation. Full workspace, other platforms, C API, host allocator exhaustion and wall-time performance are not claimed.

Refs #3494.

Follow-up commits

  • Reserve both copied list buffers fallibly for concatenation, and use the same fallible snapshot for list.copy. Preserve the existing separate list snapshots and do not run Python code while copying.
  • Feed the exact-size replacement iterator to contiguous vector slice assignment rather than making a temporary copy. This removes one allocation; it does not make every possible splice growth fallible.
  • Reserve the intermediate exact-list snapshot fallibly before destination growth in extend and +=. Keep self-extension and subclass iteration behavior unchanged.
  • CPython 3.15.2 and RustPython each passed 7 canonical list selectors and 8 canonical array selectors, plus ordinary self-concat/subclass/object identity and copy-signature controls. Native CLI Clippy passed with warnings denied. No real OOM, performance measurement, or C API coverage claimed.

Most remaining changes in #3494 were error-conversion API refactors rather than allocation changes. List extend already reserved its destination fallibly; this PR also covers the exact-list intermediate snapshot. In-place and ordinary sequence, byte and string repetition already reserve fallibly on main. The existing VM MemoryError mechanism is reused; this PR does not claim every RustPython allocation is recoverable.

Replacement scope for #3494

  • Native list extension now reserves its exact sources fallibly, including sets, dictionaries and dictionary views, without holding both source and destination locks. Existing subclass iteration remains unchanged.
  • Rust reservation errors map through the VM's prewarmed MemoryError path. The deterministic overflow test verifies the list and its mutation counter stay unchanged when reservation fails, without attempting a large allocation.
  • This PR carries forward the original list growth, checked repetition failure handling (already on main), temporary splice-buffer removal, and reservation-error conversion. It does not replay unrelated error-mapping API changes. The copy-prefix repetition prototype is excluded: it sped up small inputs, but regressed larger strings in matched local tests. Existing repetition behavior is unchanged.
  • Linux: 60 CPython 3.15.2 differential cases, 11 canonical list/dict tests, the targeted Rust capacity test, and CLI Clippy with warnings denied passed for the final conversion. Native cross-platform scopes depend on CI; arbitrary allocator exhaustion and general fallible Python object allocation are not claimed.

Summary by CodeRabbit

  • Bug Fixes
    • List operations now report memory allocation failures without partially changing list contents.
    • List copying, concatenation, and extension handle allocation failures consistently.
    • Import setup now reports failures when registering zip import hooks instead of continuing with a warning.
    • Errors during exception notes and attribute handling are now propagated correctly.
    • Sequence updates and collection copying avoid unnecessary intermediate allocations.
    • Repeating bytes now handles overflow and allocation failures without altering the original value.

Carry forward the fallible list growth approach from coolreader18 in RustPython#3494 using the current VM MemoryError and Vec reservation paths.

Assisted-by: Codex:GPT-6.2
@coderabbitai

coderabbitai Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

List and byte operations now handle allocation failures through fallible paths. List extension supports snapshots of native collections. Zipimport setup moves path-hook insertion outside its warning fallback. Slice replacement passes cloned items directly to Vec::splice.

Changes: Fallible list operations

Layer / File(s) Summary
Fallible collection snapshots
crates/vm/src/builtins/list.rs, crates/vm/src/builtins/set.rs, crates/vm/src/dict_inner.rs, crates/vm/src/vm/vm_ops.rs, crates/vm/src/exceptions.rs
Lists, sets, frozensets, dictionaries, and dictionary views provide fallible snapshots for list operations. A borrowed-object helper contains the existing length-hint logic. Snapshot tests check live-entry ordering.
Fallible list operations and callers
crates/vm/src/builtins/list.rs, crates/vm/src/builtins/genericalias.rs, crates/vm/src/exceptions.rs, crates/vm/src/frame.rs
List growth, append, insert, extend, copy, and concatenation use fallible allocation paths. Reservation errors convert to Python memory errors. Append callers pass the VM and propagate errors. A test checks that failed growth leaves list contents and the mutation counter unchanged.

Byte repetition

Layer / File(s) Summary
In-place byte repetition
crates/vm/src/bytes_inner.rs
PyBytesInner::imul checks repetition overflow and reserves capacity before extending nonempty input. Tests check repetition results and unchanged input after overflow.

Zipimport setup errors

Layer / File(s) Summary
Limit the warning fallback
crates/vm/src/import.rs
The warning fallback covers import, importer lookup, and sys.path_hooks conversion failures. Path-hook insertion occurs outside the fallback, so insertion errors propagate.

Slice replacement

Layer / File(s) Summary
Pass replacements to splice
crates/vm/src/sliceable.rs
do_set_range passes cloned items directly to Vec::splice instead of first collecting them into a Vec.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested reviewers: youknowone, shaharnaveh

Merge Risk: Minimal · up to 1f54e

This change makes list append, insert, extend, copy and concatenation return a MemoryError instead of aborting when allocation fails. It also makes zipimport hook-insertion failures propagate instead of being swallowed. No merge-blocking problem was found in the reviewed changes, and the rollback is a simple code revert.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "Make Python list append and insert growth fallible" matches the main change in the changeset. The raw summary shows list.rs now reserves capacity fallibly before mutation, append and insert…
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.
Full details: Title check

Explanation

The title "Make Python list append and insert growth fallible" matches the main change in the changeset. The raw summary shows list.rs now reserves capacity fallibly before mutation, append and insert return PyResult<()>, and frame.rs, exceptions.rs, import.rs, and genericalias.rs propagate the new error paths. The title does not cover the extend, copy, concatenation, dict snapshot, bytearray repetition, or sliceable changes, which is acceptable because the title need not list every detail.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 26a2a56 and 1f54e4e.

Files selected for processing: 1

  • crates/vm/src/bytes_inner.rs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

Continue the list portion of coolreader18’s RustPython#3494 using existing buffer reservations and keep Python behavior and locking unchanged.

Assisted-by: Codex:GPT-6.2
Carry forward the exact-size iterator improvement in coolreader18’s RustPython#3494 without changing the slice interface.

Assisted-by: Codex:GPT-6.2
Avoid the infallible intermediate source copy for list.extend and +=. Keep self-extension and subclass iteration behavior unchanged.

Assisted-by: Codex:GPT-6.2
@youknowone
youknowone marked this pull request as ready for review December 4, 2026 03:14
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-04T08:56:16.667404Z 1f54e4e New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@youknowone
youknowone enabled auto-merge (squash) December 4, 2026 05:22
Copy live entries once under the source read guard and release it before allocating Python item tuples or growing the destination. Preserve the normal iterator path for subclasses.

Assisted-by: Codex:GPT-6.2
auto-merge was automatically disabled December 4, 2026 05:49

Head branch was pushed to by a user without write access

Carry forward the original TryReserveError conversion; preserve the current prewarmed MemoryError and release the list guard before reporting failure.

Assisted-by: Codex:GPT-6.2
@codspeed

codspeed Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 62 untouched benchmarks
⏩ 4 skipped benchmarks1


Comparing youknowdot:fallible-list-growth-3494 (26a2a56) with main (6aa2043)

Open in CodSpeed

Footnotes

  1. 4 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. ↩

Reserve before mutation and copy already initialized prefixes as CPython does, with a fill for one-byte seeds. Keep the existing bytearray export checks and leave generic repetition unchanged.

Assisted-by: Codex:GPT-6.2
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