Skip to content

Align Windows mmap ownership and resize with CPython - #9847

Merged
youknowone merged 3 commits into
RustPython:mainfrom
youknowdot:fix/windows-mmap-lifecycle
Nov 15, 2026
Merged

youknowone merged 3 commits into
RustPython:mainfrom
youknowdot:fix/windows-mmap-lifecycle

Conversation

@youknowdot

@youknowdot youknowdot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Make Windows mmap creation and resizing follow CPython 3.15's native mapping lifecycle rather than splitting named mappings and ordinary mappings between two implementations.

  • Use the same Win32 mapping path for file-backed, named, anonymous and untracked mappings. Retain exactly the file handle needed by trackfd=True, including for named mappings; use the duplicate after acquiring it.
  • Let CreateFileMappingW enforce access and extend files. Apply anonymous offsets too, and preserve the Windows constructor's CRT cursor-reset behavior.
  • Port the named-map sharing check, resize/remap recovery, name-reuse race detection and anonymous-copy ordering from Modules/mmapmodule.c. Keep the cursor unchanged when shrinking.
  • Accept __index__ in resize on Linux and Windows, preserving signed-size overflow diagnostics.
  • Close retained file handles even after a resize has invalidated the mapping.
  • Remove the obsolete Linux flush-alignment skip after running that test successfully against the existing native msync path.
  • Re-enable the Windows MmapTests class. The first Windows CI run confirmed 15 unexpected successes; remove exactly those obsolete expected-failure markers. The POSIX-only test’s remaining Windows marker is unchanged.

The added regression cases live in the existing stdlib_mmap.py snippet. They cover gaps in the stdlib tests: index conversion/reentrancy, the cursor after shrink, named file size and successful named resize, anonymous offset handling, and explicit close after a failed resize. No WASI mmap implementation changes.

Validation

  • CPython 3.15.0: complete stdlib_mmap.py snippet passes on Linux.
  • CPython 3.15.0: -m test test_mmap passes (55 tests, 7 skipped).
  • cargo check -p rustpython-host_env --target x86_64-pc-windows-gnu passes.
  • Windows GNU host crate Clippy with -D warnings passes.
  • Linux modified RustPython release build and complete stdlib_mmap.py snippet pass.
  • Modified RustPython -m test test_mmap passes (55 tests, 7 skipped).
  • All applicable pre-commit hooks and git diff --check pass.
  • Independent code review checked Win32 ownership and resize rollback against CPython 3.15; its findings were addressed and rechecked.

Windows CI also ran the complete stdlib_mmap.py snippet successfully under both CPython and RustPython, including the Windows-specific regression cases.

Windows runtime evidence from head efb849e90: Windows CI executed test_mmap (55 tests, 7 skipped) and failed only because 15 tests unexpectedly passed. Those exact 15 markers are removed in the follow-up commit; no implementation changes were needed. The latest head's CI is pending. No Windows performance measurement has been performed.

Summary by CodeRabbit

  • New Features
    • Windows memory mappings can now be resized, including named and anonymous mappings.
    • File-backed mappings support zero-length requests that derive their size from the file, with validation for empty files and invalid offsets.
  • Bug Fixes
    • Resize arguments now support index-compatible values and report errors for negative or out-of-range sizes.
    • Resizing and flushing mappings now handle Windows-specific mapping behavior more consistently.

@coderabbitai

coderabbitai Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The change adds resize support to Windows memory mappings and updates Python mmap construction, resizing, and mapping state handling. It also changes resize argument conversion on Linux and Windows and adds tests for size conversion and Windows mapping behavior.

Changes: Windows mmap behavior

Layer / File(s) Summary
Windows mapping type and resize
crates/host_env/src/mmap.rs
NamedMmap becomes WindowsMmap, which stores its optional mapping name and adds validity, size, and resize operations. Mapping creation returns the updated type.
Python mmap construction and access
crates/host_env/src/mmap.rs, crates/stdlib/src/mmap.rs
Windows construction prepares file mappings and uses WindowsMmap for mapping storage and slice access. It derives sizes for zero-length file-backed mappings and validates the file size, offset, and mapping tag.
Resize integration and validation
crates/stdlib/src/mmap.rs, extra_tests/snippets/stdlib_mmap.py
Python resize uses ArgIndex on Linux and Windows. Windows resize updates the mapping size or marks the mapping closed when it is invalid. Tests cover size conversion, cursor behavior, and Windows mapping resize cases.

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

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant PyMmap
  participant WindowsMmap
  participant WindowsMappingAPI
  PyMmap->>WindowsMmap: resize(file, offset, new_size)
  WindowsMmap->>WindowsMappingAPI: recreate mapping handle and view
  WindowsMappingAPI-->>WindowsMmap: mapping handle and view result
  WindowsMmap-->>PyMmap: resize result and validity
Loading

Suggested reviewers: youknowone

Merge Risk: Minimal · up to 52767

This change brings Windows mmap creation, resizing and cleanup in line with CPython 3.15. It also lets resize accept any integer-like size and adds regression tests. No concrete defects were found. The main remaining step is confirming that the latest Windows CI run passes.

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 "Align Windows mmap ownership and resize with CPython" matches the main change. The raw summary and objectives show Windows mmap creation, handle ownership, and resize were reworked to follo…
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 "Align Windows mmap ownership and resize with CPython" matches the main change. The raw summary and objectives show Windows mmap creation, handle ownership, and resize were reworked to follow CPython 3.15 behavior. The title is specific and concise. It does not mention the Linux resize index change or the re-enabled test markers, but those are secondary.

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 4f65ad0 and 5276794.

Files ignored due to path filters: 1

  • Lib/test/test_mmap.py is excluded by !Lib/**
Files selected for processing: 3

  • crates/host_env/src/mmap.rs
  • crates/stdlib/src/mmap.rs
  • extra_tests/snippets/stdlib_mmap.py

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

@github-actions

github-actions Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

📦 Library Dependencies

The following Lib/ modules were modified. Here are their dependencies:

[x] test: cpython/Lib/test/test_mmap.py (TODO: 1)

dependencies:

dependent tests: (2 tests)

  • mmap: test_os
    • multiprocessing.shared_memory: test_genericalias

Legend:

  • [+] path exists in CPython
  • [x] up-to-date, [ ] outdated

@youknowone
youknowone marked this pull request as ready for review November 15, 2026 07:48
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 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-11-15T07:58:03.794786Z 5276794 Draft marked ready
ℹ️ 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) November 15, 2026 07:49
@codspeed

codspeed Bot commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 62 untouched benchmarks
⏩ 4 skipped benchmarks1


Comparing youknowdot:fix/windows-mmap-lifecycle (5276794) with main (622b766)2

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

  2. No successful run was found on main (4f65ad0) during the generation of this report, so 622b766 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5276794061

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

self.view_ptr = core::ptr::null_mut();
if let Err(err) = extend_file(file, max_size as i64) {
file_resize_error = Some(err);
max_size = self.len as u64;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include the offset when restoring a failed file resize

On Windows, when a file-backed mapping has a nonzero offset and another view of the same file prevents resizing, extend_file fails and this fallback sets the replacement section’s maximum size to only self.len. The subsequent MapViewOfFile still requests self.len bytes at the original offset, exceeding that section’s bounds and causing PyMmap::resize to mark the mapping closed. For example, a 4096-byte view at ALLOCATIONGRANULARITY becomes unusable after catching the resize error, whereas the previous backend restored it. Use offset + self.len as the fallback section size so reads and subsequent resize retries remain possible.

Useful? React with 👍 / 👎.

@youknowone
youknowone merged commit a92510a into RustPython:main Nov 15, 2026
30 checks passed
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.

3 participants