Skip to content

Implement PEP 688 and rework the buffer protocol around managed exports - #8523

Draft
youknowone wants to merge 2 commits into
RustPython:mainfrom
youknowone:RustPython-3
Draft

Implement PEP 688 and rework the buffer protocol around managed exports#8523
youknowone wants to merge 2 commits into
RustPython:mainfrom
youknowone:RustPython-3

Conversation

@youknowone

Copy link
Copy Markdown
Member

Implements PEP 688 (__buffer__ / __release_buffer__) and reworks the buffer
protocol underneath it so the two commits together match the CPython 3.14
semantics.

__buffer__ / __release_buffer__

A Python-level __buffer__ is exposed through bf_getbuffer and
__release_buffer__ through bf_releasebuffer, mirroring slot_bf_getbuffer
and slot_bf_releasebuffer. memoryview.__buffer__(flags) and
memoryview.__release_buffer__(view) are added.

Managed exports

PyBuffer takes the _PyManagedBufferObject shape: one bf_getbuffer
acquisition is shared by every handle taken from it, cloning takes another share
instead of re-acquiring, and the exporter's release runs exactly once when the
last share goes away. This removes retain, the unsafe drop_without_release,
three impl Drops and the ManuallyDrop that previously stood in for the
refcount. abort_acquisition keeps bf_releasebuffer from running when
bf_getbuffer itself failed.

View offsets

The view start moves into BufferDescriptor::offset, the Py_buffer.buf
analogue, replacing the separate start fields on PyMemoryView and
PyBufferWrapper that let an exported buffer disagree with the view it came
from. Slicing goes through SaturatedSlice::adjust_indices_start, reproducing
PySlice_AdjustIndices.

Other fixes found along the way

  • zip_eq took its contiguous fast path when only one side's last dimension was
    contiguous (last_dim_is_contiguous).
  • for_each_segment and zip_eq mishandled zero-length and zero-dimensional
    views.
  • Buffer requests ignored the flags: BufferDescriptor::projected now reduces
    the descriptor for a request without PyBUF_ND / PyBUF_STRIDES /
    PyBUF_FORMAT, and a request without PyBUF_INDIRECT against an exporter with
    suboffsets is rejected.
  • memoryview slice assignment copies the source first when both sides reach the
    same root exporter.
  • bytearray.extend now holds the export across the resize.
  • marshal.loads takes y*, _overlapped takes w*/y*, FsPath no longer
    probes the buffer protocol, ord is rewritten over the concrete string types,
    and array's buffer slot is folded into a single slot_as_buffer.

Verification

  • Full regrtest sweep: 406 tests OK, run=40,778 failures=2, against a
    404 tests OK, run=40,740 failures=2 baseline. The one failure,
    test_future_stmt.test_future, is pre-existing and unrelated.
  • A 26-case differential harness matches CPython 3.14 including error messages.
  • extra_tests/snippets/builtin_memoryview.py gains 11 test functions, all of
    which pass on CPython 3.14 as well.
  • Buffer-related suites also run clean in a debug build, with debug_asserts
    live.

crates/stdlib/src/overlapped.rs is Windows-only and could not be compiled
locally, so it rests on CI.

🤖 Generated with Claude Code

https://claude.ai/code/session_01P9HewXGX8qcGSccUxGdSPV

A Python class could not export a buffer: the slot machinery had no
bf_getbuffer or bf_releasebuffer, and every consumer acquired buffers as
PyBUF_FULL_RO through a module of PyBUF_* constants.

Add both slots. PyBuffer::release now runs a Python __release_buffer__
before the exporter's own release, once per acquisition, which PyBuffer
tracks with an `acquired` flag that clones do not inherit. An export made
by a Python __buffer__ is held by a _buffer_wrapper payload that counts its
exports and drops the returned memoryview with the last one, and the view
handed to __release_buffer__ is a _buffer_window that owns no export, so
releasing it inside the hook is inert instead of re-entering it.

Replace the PyBUF_* constants with a BufferFlags bitflags type whose
composite requests are supersets of the simpler ones, so `contains` answers
the REQ_* questions, and pass the request to PyBuffer::from_object. Each
consumer now asks for what its counterpart asks for: y* arguments for
SIMPLE, w* for WRITABLE, BytesIO.write for CONTIG_RO, bytes(), bytearray()
and memoryview() for FULL_RO. memoryview checks the request in
memory_getbuf, and array.array and mmap.mmap expose __release_buffer__.

Test buffer support with PyObject::check_buffer (PyObject_CheckBuffer)
instead of attempting an acquisition, so an exception raised by __buffer__
is no longer reported as the object not being bytes-like, and a __buffer__
with side effects runs once. PyBytesInner becomes a y* conversion as a
result: bytes and bytearray methods no longer accept iterables of ints, and
find, index, count and __contains__ take the arguments
parse_args_finds_byte and bytes_contains describe.

A view exports its start offset in the descriptor rather than in its
window, which fixes a panic when collecting from a negative-stride view.

BytesIO.write rechecks closed after acquiring its buffer, which __buffer__
can close in between.

Assisted-by: Claude Code:claude-opus-5
Give `PyBuffer` the `_PyManagedBufferObject` shape: one `bf_getbuffer`
acquisition is shared by every handle taken from it, cloning takes another
share instead of re-acquiring, and the exporter's release runs once when the
last share goes away. Remove `retain`, the unsafe `drop_without_release`, the
three `impl Drop`s and the `ManuallyDrop` that stood in for this. Add
`abort_acquisition` so a failed request does not run `bf_releasebuffer`.

Move the view start into `BufferDescriptor::offset`, the `Py_buffer.buf`
analogue, and drop the separate `start` fields on `PyMemoryView` and
`PyBufferWrapper`. Slicing goes through `SaturatedSlice::adjust_indices_start`,
which reproduces `PySlice_AdjustIndices` and keeps the adjusted start.

Fix `zip_eq` to take its contiguous fast path only when both last dimensions
are contiguous, and make `for_each_segment` and `zip_eq` handle zero-length and
zero-dimensional views.

Add `BufferDescriptor::projected` so a request without `PyBUF_ND`,
`PyBUF_STRIDES` or `PyBUF_FORMAT` receives a correspondingly reduced
descriptor, and reject a request without `PyBUF_INDIRECT` against an exporter
that has suboffsets.

Copy the source first in `memoryview` slice assignment when both sides reach
the same root exporter.

Hold the export across the resize in `bytearray.extend`, take `y*` in
`marshal.loads`, stop probing the buffer protocol in `FsPath`, rewrite `ord`
over the concrete string types, fold `array`'s buffer slot into one
`slot_as_buffer`, take `w*`/`y*` in `_overlapped`, and thread the new `offset`
field through the `_ctypes` descriptors.

Assisted-by: Claude
@coderabbitai

coderabbitai Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: 6d425980-4113-409d-a6ca-de501dd71350

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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.

@github-actions

Copy link
Copy Markdown
Contributor

📦 Library Dependencies

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

[x] lib: cpython/Lib/struct.py
[ ] test: cpython/Lib/test/test_struct.py (TODO: 5)

dependencies:

  • struct

dependent tests: (179 tests)

  • struct: test_array test_buffer test_call test_compileall test_ctypes test_deque test_fcntl test_float test_gzip test_ioctl test_itertools test_logging test_math test_memoryview test_ordered_dict test_os test_pickle test_plistlib test_socket test_ssl test_str test_struct test_sys test_tools test_venv test_wave test_xml_etree_c test_xpickle test_zipfile test_zipimport test_zoneinfo
    • base64: test_base64 test_email test_gettext test_httpservers test_smtplib test_urllib2 test_urllib2_localnet test_xmlrpc
      • http.server: test_robotparser
      • logging.handlers: test_concurrent_futures test_pkgutil
      • secrets: test_secrets
      • smtplib: test_smtpnet
      • ssl: test_asyncio test_ftplib test_httplib test_imaplib test_poplib test_urllib
      • urllib.request: test_http_cookiejar test_pathlib test_pydoc test_sax test_site test_urllib2net test_urllibnet
    • ctypes: test_android test_bytes test_code test_codecs test_ctypes test_genericalias test_io test_ntpath
      • platform: test__locale test__osx_support test_asyncio test_baseexception test_builtin test_cmath test_mimetypes test_platform test_posix test_regrtest test_shutil test_strptime test_sysconfig test_time test_winreg test_wsgiref
      • webbrowser: test_webbrowser
    • dbm: test_dbm test_dbm_dumb test_dbm_sqlite3 test_shelve
    • gettext:
      • argparse: test_argparse
      • getopt: test_getopt
      • optparse: test_decimal test_optparse
    • gzip: test_fileinput test_tarfile
    • multiprocessing: test_asyncio test_concurrent_futures test_multiprocessing_main_handling test_re
      • concurrent.futures.process: test_concurrent_futures
    • pickle: test_annotationlib test_ast test_bool test_bz2 test_collections test_configparser test_coroutines test_csv test_defaultdict test_descr test_dict test_dictviews test_email test_enum test_enumerate test_exceptions test_fractions test_functools test_generators test_http_cookies test_importlib test_inspect test_ipaddress test_iter test_list test_lzma test_memoryio test_minidom test_opcache test_operator test_picklebuffer test_pickletools test_positional_only_arg test_random test_range test_set test_slice test_statistics test_string test_structseq test_super test_trace test_tuple test_turtle test_type_aliases test_type_params test_types test_typing test_unittest test_uuid test_xml_dom_minicompat test_xml_etree test_zipfile test_zlib test_zoneinfo
      • tracemalloc: test_tracemalloc
    • tarfile:
      • shutil: test_embed test_filecmp test_glob test_importlib test_largefile test_launcher test_modulefinder test_peg_generator test_py_compile test_reprlib test_string_literals test_subprocess test_support test_tempfile test_traceback test_unicode_file
    • zipfile: test_pdb test_zipapp test_zipfile test_zipfile64 test_zipimport_support
      • importlib.metadata: test_importlib
    • zipimport: test_cmd_line_script test_importlib
      • pkgutil: test_pyrepl test_runpy

[ ] test: cpython/Lib/test/test_memoryview.py (TODO: 7)

dependencies:

dependent tests: (no tests depend on memoryview)

[x] test: cpython/Lib/test/test_buffer.py

dependencies:

dependent tests: (no tests depend on buffer)

[x] lib: cpython/Lib/io.py
[ ] lib: cpython/Lib/_pyio.py
[ ] test: cpython/Lib/test/test_io.py (TODO: 13)
[x] test: cpython/Lib/test/test_bufio.py
[x] test: cpython/Lib/test/test_fileio.py (TODO: 1)
[ ] test: cpython/Lib/test/test_memoryio.py (TODO: 5)

dependencies:

  • io (native: _io, _thread, errno, msvcrt, sys)
    • _pyio
    • locale (native: _locale, builtins, encodings.aliases, sys)
    • warnings (native: _contextvars, _thread, _warnings, builtins, sys)
    • _collections_abc, abc, codecs, os, stat

dependent tests: (108 tests)

  • io: test__colorize test_android test_argparse test_ast test_asyncio test_base64 test_buffer test_bufio test_builtin test_bz2 test_calendar test_cmd test_cmd_line_script test_codecs test_compile test_compileall test_compiler_assemble test_concurrent_futures test_configparser test_contextlib test_csv test_dbm_dumb test_descr test_dis test_email test_enum test_file test_fileinput test_fileio test_ftplib test_generated_cases test_getpass test_gzip test_hashlib test_http_cookiejar test_httplib test_httpservers test_importlib test_inspect test_io test_json test_largefile test_logging test_lzma test_mailbox test_marshal test_memoryio test_memoryview test_mimetypes test_minidom test_multibytecodec test_optparse test_pathlib test_pdb test_peg_generator test_pickle test_pickletools test_platform test_plistlib test_pprint test_print test_profile test_pstats test_pty test_pulldom test_pydoc test_pyexpat test_pyrepl test_quopri test_regrtest test_robotparser test_sax test_shlex test_shutil test_site test_smtplib test_socket test_socketserver test_subprocess test_support test_sys test_tarfile test_tempfile test_threadedtempfile test_timeit test_tokenize test_traceback test_types test_typing test_unittest test_univnewlines test_urllib test_urllib2 test_uuid test_wave test_webbrowser test_winconsoleio test_wsgiref test_xml_dom_xmlbuilder test_xml_etree test_xml_etree_c test_xmlrpc test_xpickle test_zipapp test_zipfile test_zipimport test_zoneinfo test_zstd

[ ] test: cpython/Lib/test/test_marshal.py (TODO: 8)

dependencies:

dependent tests: (25 tests)

  • marshal: test_bool test_exceptions test_importlib test_inspect test_marshal test_zipimport
    • importlib._bootstrap_external: test_importlib test_unittest
      • modulefinder: test_importlib test_modulefinder
      • py_compile: test_argparse test_cmd_line_script test_compileall test_importlib test_multiprocessing_main_handling test_py_compile test_pydoc test_runpy
      • pydoc: test_enum
    • pkgutil: test_pkgutil test_pyrepl
    • profile: test_profile
    • pstats: test_pstats
    • zipimport: test_importlib test_zipimport_support

[x] lib: cpython/Lib/code.py
[x] test: cpython/Lib/test/test_code_module.py (TODO: 3)

dependencies:

  • code

dependent tests: (2 tests)
- [x] pdb: test_pdb
- [ ] sqlite3.main: test_sqlite3

[ ] lib: cpython/Lib/collections
[x] lib: cpython/Lib/_collections_abc.py
[x] test: cpython/Lib/test/test_collections.py
[x] test: cpython/Lib/test/test_deque.py (TODO: 2)
[x] test: cpython/Lib/test/test_defaultdict.py
[ ] test: cpython/Lib/test/test_ordered_dict.py (TODO: 7)

dependencies:

  • collections (native: _collections, _weakref, itertools, sys)
    • _collections_abc
    • warnings
    • _collections_abc, abc, annotationlib, copy, heapq, keyword, operator, reprlib

dependent tests: (331 tests)

  • collections: test_annotationlib test_array test_asyncio test_bisect test_builtin test_c_locale_coercion test_call test_collections test_configparser test_contains test_context test_copy test_csv test_ctypes test_defaultdict test_deque test_descr test_dict test_dictviews test_embed test_enum test_exception_group test_file test_fileinput test_fileio test_frame test_funcattrs test_functools test_genericalias test_hash test_httpservers test_inspect test_io test_ipaddress test_iter test_iterlen test_json test_logging test_math test_monitoring test_ordered_dict test_pathlib test_patma test_pickle test_plistlib test_pprint test_pydoc test_random test_reprlib test_richcmp test_set test_shelve test_sqlite3 test_statistics test_string test_struct test_sys test_traceback test_tuple test_types test_typing test_unittest test_urllib test_userdict test_userlist test_userstring test_weakref test_weakset test_with
    • ast: test_ast test_compile test_compiler_codegen test_dis test_fstring test_future_stmt test_peepholer test_peg_generator test_site test_ssl test_type_comments test_ucn test_unparse
      • annotationlib: test_grammar test_type_annotations test_type_params
      • dbm.dumb: test_dbm_dumb
      • inspect: test_abc test_argparse test_asyncgen test_buffer test_clinic test_code test_coroutines test_decimal test_generators test_ntpath test_operator test_posixpath test_signal test_turtle test_yield_from test_zipimport test_zipimport_support test_zoneinfo
      • pyclbr: test_pyclbr
      • traceback: test_asyncio test_code_module test_contextlib test_contextlib_async test_dictcomps test_exceptions test_http_cookiejar test_importlib test_listcomps test_pyexpat test_setcomps test_socket test_subprocess test_threadedtempfile test_threading test_unittest
    • asyncio: test_asyncio test_external_inspection test_os test_pdb
    • concurrent.futures._base: test_concurrent_futures
    • dbm.sqlite3: test_dbm_sqlite3
    • difflib: test_difflib test_profile test_sys_settrace
    • dis: test__opcode test_compiler_assemble test_dtrace test_opcache test_positional_only_arg test_type_cache
      • bdb: test_bdb
      • modulefinder: test_importlib test_modulefinder
      • trace: test_trace
    • email.feedparser: test_email
    • http.client: test_docxmlrpc test_hashlib test_unicodedata test_urllib2 test_wsgiref test_xmlrpc
      • urllib.request: test_sax test_urllib2_localnet test_urllib2net test_urllibnet
    • idlelib: test_idle
    • importlib.metadata: test_importlib
    • inspect:
      • cmd: test_cmd
      • dataclasses: test__colorize test_ctypes test_regrtest
      • pkgutil: test_pkgutil test_pyrepl test_runpy
      • rlcompleter: test_pyrepl test_rlcompleter
    • logging: test_support
      • hashlib: test_hmac test_smtplib test_tarfile
      • multiprocessing.util: test_compileall test_concurrent_futures
      • venv: test_venv
    • multiprocessing: test_fcntl test_memoryview test_multiprocessing_main_handling test_re
    • platform: test__locale test__osx_support test_baseexception test_cmath test_ctypes test_mimetypes test_platform test_posix test_shutil test_strptime test_sysconfig test_time test_winreg
    • pprint: test_htmlparser test_sys_setprofile
      • pickle: test_bool test_bytes test_bz2 test_codecs test_concurrent_futures test_ctypes test_email test_enumerate test_fractions test_http_cookies test_itertools test_list test_lzma test_memoryio test_minidom test_picklebuffer test_pickletools test_range test_slice test_str test_structseq test_super test_type_aliases test_unittest test_uuid test_xml_dom_minicompat test_xml_etree test_xpickle test_zipfile test_zlib test_zoneinfo
    • queue: test_android test_dummy_thread test_sched
    • selectors: test_selectors
      • socket: test_epoll test_exception_hierarchy test_ftplib test_httplib test_imaplib test_kqueue test_largefile test_mailbox test_mmap test_poplib test_pty test_smtpnet test_socketserver test_stat test_timeout test_urllib_response
      • subprocess: test_atexit test_audit test_cmd_line test_cmd_line_script test_ctypes test_faulthandler test_file_eintr test_gc test_gzip test_json test_launcher test_msvcrt test_osx_env test_peg_generator test_poll test_py_compile test_pyrepl test_quopri test_repl test_script_helper test_select test_tempfile test_unittest test_utf8_mode test_wait3 test_webbrowser test_zipfile
    • shlex: test_shlex
    • shutil: test_filecmp test_glob test_importlib test_string_literals test_unicode_file
      • ctypes.util: test_ctypes
      • ensurepip: test_ensurepip
      • pathlib: test_importlib test_pathlib test_tomllib test_tools test_winapi test_zipapp test_zstd
      • tempfile: test_cprofile test_doctest test_generated_cases test_importlib test_linecache test_pkg test_pstats test_pyrepl test_tabnanny test_termios test_tokenize test_winconsoleio test_zipfile64
      • zipfile: test_zipfile
    • statistics:
      • random: test_complex test_devpoll test_email test_float test_grp test_heapq test_int test_long test_numeric_tower test_pow test_pwd test_queue test_sort test_strtod test_thread
    • string: test_email test_fnmatch test_pyrepl test_secrets test_string
    • threading: test_concurrent_futures test_ctypes test_fork1 test_importlib test_ioctl test_pyrepl test_robotparser test_syslog test_threading_local
      • dummy_threading: test_dummy_threading
      • sysconfig: test_asdl_parser test_tools
    • traceback:
      • timeit: test_timeit
    • tracemalloc: test_tracemalloc
    • urllib.parse: test_urlparse
    • wave: test_wave

[x] test: cpython/Lib/test/test_structseq.py (TODO: 7)

dependencies:

dependent tests: (no tests depend on structseq)

[x] test: cpython/Lib/test/test_itertools.py (TODO: 4)

dependencies:

dependent tests: (56 tests)

  • itertools: test_annotationlib test_ast test_asyncio test_bdb test_buffer test_builtin test_call test_codeccallbacks test_collections test_compile test_concurrent_futures test_csv test_ctypes test_descr test_dis test_email test_exceptions test_functools test_genericalias test_hashlib test_heapq test_httplib test_importlib test_inspect test_io test_iterlen test_itertools test_launcher test_logging test_math test_memoryview test_mmap test_os test_peepholer test_platform test_pprint test_pyrepl test_queue test_range test_set test_shlex test_slice test_socket test_sort test_statistics test_str test_struct test_subprocess test_tokenize test_tuple test_typing test_unittest test_uuid test_winreg test_xml_etree test_zipfile

Legend:

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

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