Skip to content

Align native threading and libraries with Python 3.15 - #9148

Merged
youknowone merged 1 commit into
RustPython:mainfrom
youknowdot:split/threading-315-native
Oct 15, 2026
Merged

youknowone merged 1 commit into
RustPython:mainfrom
youknowdot:split/threading-315-native

Conversation

@youknowdot

Copy link
Copy Markdown
Contributor

Summary

Split the native threading work and its associated Python libraries from the larger Python 3.15 update, keeping them together in one six-file change.

  • Reject arguments to native RLock when the class retains its base initializer, while preserving subclasses with a custom initializer.
  • Preserve the existing lock ownership representation while polling contended acquisitions in detached slices, checking pending signals between unsuccessful nonterminal waits, and checking finalization before each blocking wait. Keep a single elapsed-time budget and round positive timeouts upward to nanoseconds.
  • When a signal handler acquires and retains an RLock during an already-pending outer acquisition, keep that outer acquisition contended without recursively acquiring the raw lock or overwriting the handler's ownership/count.
  • Encode Linux/macOS thread names using the existing filesystem UTF-8 encoding with replacement for unencodable characters.
  • Update threading, _threading_local, and the three related canonical test files from CPython d220409a13b77de7a6c30abe16ea90db01528edc, including the associated iterator utilities.

No C-API exports, foreign-thread cleanup, thread-handle/lifetime redesign, updater changes, or duplicate snippets are included.

Canonical Python provenance

All five Python files were generated through the actual scripts/update_lib CLI against that exact CPython source:

  • copy-lib for threading.py, including its existing _threading_local.py dependency
  • migrate for test_threading.py, lock_tests.py, and test_thread_local_bytecode.py
  • The existing patches metadata route for the final test_threading.py output

Four files are byte-identical to the pinned upstream source. test_threading.py differs only by five existing RustPython markers: four expected failures and one skip. The sixth original marker belonged to the obsolete ThreadTests.test_tstate_lock wrapper; its owner is absent from the pinned upstream class and its full TestCase ancestry, so only that metadata entry was removed before regenerating. No canonical assertions or test bodies were hand-edited, and no marker was removed based on an unrun test result.

Validation

At commit 54142418ba8fbbc8970e105c3d1e3cd8135e190f:

  • Normal commit hooks passed, including formatting/lint checks, redundant-patch checks, and spelling.
  • Narrow release build passed with --no-default-features --features threading,stdlib,stdio,importlib,host_env.
  • Strict VM Clippy passed: cargo clippy --release --offline --locked -p rustpython-vm --all-targets --no-default-features --features compiler,gc,host_env,stdio,importlib,encodings,threading -- -D warnings.
  • Independently reviewed, resource-bounded import-only gate passed against the original committed, cache-free library sources.
  • Exactly 15 selected canonical tests passed, with zero failures, errors, skips, expected failures, or unexpected successes. The selection covers Lock/RLock constructors and native RLock signature, plus single-thread iterator utilities. Source/origin inventories stayed unchanged before and after execution.

Selected tests under test.test_threading:

  • ThreadTests.test_lock_no_args
  • LockTests.test_constructor, LockTests.test_constructor_noargs
  • PyRLockTests.test_constructor, PyRLockTests.test_constructor_noargs
  • CRLockTests.test_constructor, CRLockTests.test_constructor_noargs, CRLockTests.test_signature
  • ThreadingIteratorToolsTests.test_serialize_generator_methods
  • ThreadingIteratorToolsTests.test_serialize_methods_attribute_error
  • ThreadingIteratorToolsTests.test_serialize_generator_methods_locking
  • ThreadingIteratorToolsTests.test_serialize_next_exception
  • ThreadingIteratorToolsTests.test_synchronized_preserves_wrapped_metadata
  • ThreadingIteratorToolsTests.test_concurrent_tee_zero_iterators
  • ThreadingIteratorToolsTests.test_concurrent_tee_negative_n

Limits and review notes

This remains a draft. The selected tests do not validate contended waits, finalization, or signal-handler reentrancy. Full workspace/C-API tests and broad threading, daemon, fork, signals, GC, shutdown, SetAsyncExc, and resource-limit suites were not run.

The 50 ms polling approach approximates OS signal interruption: a signal arriving during the terminal wait slice may be observed only after timeout or successful acquisition. This does not claim exact CPython interruption event ordering. Existing lifetime/handle behavior and _acquire_restore behavior are unchanged.

AI assistance was used for source preparation, review, and bounded validation. The commit carries the required Assisted-by trailer.

Preserve lock ownership and elapsed timeouts during interruptible waits; reject RLock constructor arguments and use replacement encoding for thread names. Generate associated libraries and tests from CPython d220409a13b77de7a6c30abe16ea90db01528edc using update_lib, retaining five existing markers and retiring one proven removed test owner.

AI-assisted source preparation and review. Runtime validation remains pending.

Assisted-by: OpenAI Codex:model version unavailable
@coderabbitai

coderabbitai Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration
  • Configuration used: Repository: RustPython/RustPython/.coderabbit.yml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b12bd99f-12ff-4585-b85f-0370eb8e6689
📥 Commits

Reviewing files that changed from the base of the PR and between 16e333b and 5414241.

⛔ Files ignored due to path filters: 5
  • Lib/_threading_local.py is excluded by !Lib/**
  • Lib/test/lock_tests.py is excluded by !Lib/**
  • Lib/test/test_thread_local_bytecode.py is excluded by !Lib/**
  • Lib/test/test_threading.py is excluded by !Lib/**
  • Lib/threading.py is excluded by !Lib/**
📒 Files selected for processing: 1
  • crates/vm/src/stdlib/_thread.rs
+----------------------------------------+
| If it was easy, it'd be called printf. |
+----------------------------------------+
  \
   \     /)/)
        ( '')
        /  |
      o(___)
✨ 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

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:

:4: SyntaxWarning: invalid decimal literal
:7: SyntaxWarning: "\z" is an invalid escape sequence. Such sequences will not work in the future. Did you mean "\z"? A raw string is also an option.
:10: SyntaxWarning: "\400" is an invalid octal escape sequence. Such sequences will not work in the future. Did you mean "\400"? A raw string is also an option.
:4: SyntaxWarning: invalid decimal literal
:7: SyntaxWarning: "\z" is an invalid escape sequence. Such sequences will not work in the future. Did you mean "\z"? A raw string is also an option.
:10: SyntaxWarning: "\400" is an invalid octal escape sequence. Such sequences will not work in the future. Did you mean "\400"? A raw string is also an option.
:4: SyntaxWarning: invalid decimal literal
:7: SyntaxWarning: "\z" is an invalid escape sequence. Such sequences will not work in the future. Did you mean "\z"? A raw string is also an option.
:10: SyntaxWarning: "\400" is an invalid octal escape sequence. Such sequences will not work in the future. Did you mean "\400"? A raw string is also an option.
[ ] lib: cpython/Lib/concurrent
[ ] test: cpython/Lib/test/test_concurrent_futures (TODO: 1)
[ ] test: cpython/Lib/test/test_interpreters
[ ] test: cpython/Lib/test/test__interpreters.py
[ ] test: cpython/Lib/test/test__interpchannels.py
[ ] test: cpython/Lib/test/test_crossinterp.py

dependencies:

  • concurrent (native: _crossinterp, _interpqueues, _interpreters, _queues, concurrent.futures, concurrent.futures._base, interpreter, itertools, multiprocessing.connection, multiprocessing.queues, multiprocessing.synchronize, process, sys, thread, time)
    • collections (native: _collections, _weakref, itertools, sys)
    • functools (native: _functools, _thread)
    • multiprocessing (native: _multiprocessing, _posixshmem, _posixsubprocess, _winapi, array, atexit, collections.abc, connection, context, dummy, errno, forkserver, heap, itertools, managers, mmap, msvcrt, multiprocessing.connection, pool, popen_fork, popen_forkserver, popen_spawn_posix, popen_spawn_win32, queues, resource_sharer, resource_tracker, sharedctypes, spawn, synchronize, sys, time, util, xmlrpc.client)
    • os (native: nt, os.path, posix, sys)
    • traceback (native: _missing_stdlib_info, _suggestions, collections.abc, importlib.machinery, importlib.resources.readers, importlib.util, itertools, sys, unicodedata)
    • types (native: _types, sys)
    • weakref (native: _weakref, atexit, gc, itertools, sys)
    • logging, queue, threading

dependent tests: (17 tests)

  • concurrent: test_asyncio test_compileall test_concurrent_futures test_context test_genericalias test_inspect test_struct test_sys test_threading test_types test_wmi
    • asyncio: test_asyncio test_external_inspection test_logging test_os test_pdb test_unittest

[x] lib: cpython/Lib/threading.py
[x] lib: cpython/Lib/_threading_local.py
[x] test: cpython/Lib/test/test_threading.py (TODO: 5)
[x] test: cpython/Lib/test/test_threadedtempfile.py
[x] test: cpython/Lib/test/test_threading_local.py

dependencies:

  • threading

dependent tests: (168 tests)

  • threading: test_android test_asyncio test_bytes test_bz2 test_code test_concurrent_futures test_context test_contextlib test_ctypes test_decimal test_docxmlrpc test_email test_enum test_enumerate test_external_inspection test_fork1 test_frame test_ftplib test_functools test_gc test_hashlib test_httplib test_httpservers test_imaplib test_importlib test_inspect test_io test_ioctl test_itertools test_largefile test_linecache test_logging test_memoryview test_opcache test_pathlib test_poll test_poplib test_pyrepl test_queue test_robotparser test_sched test_signal test_smtplib test_socket test_socketserver test_sqlite3 test_ssl test_subprocess test_super test_sys test_syslog test_termios test_threadedtempfile test_threading test_threading_local test_time test_urllib2_localnet test_weakref test_winreg test_wsgiref test_xmlrpc test_zstd
    • asyncio: test_asyncio test_concurrent_futures test_os test_pdb test_unittest
    • bdb: test_bdb
    • concurrent: test_compileall test_concurrent_futures test_genericalias test_struct test_types test_wmi
    • dummy_threading: test_dummy_threading
    • http.cookiejar: test_http_cookiejar test_urllib2
      • urllib.request: test_pathlib test_pydoc test_sax test_site test_urllib test_urllib2net test_urllibnet
    • importlib.util: test_asdl_parser test_ctypes test_doctest test_importlib test_pkgutil test_py_compile test_reprlib test_runpy test_zipfile test_zipimport
      • pkgutil: test_pyrepl
      • py_compile: test_argparse test_cmd_line_script test_importlib test_modulefinder test_multiprocessing_main_handling
      • pyclbr: test_pyclbr
      • sysconfig: test_c_locale_coercion test_cmd_line test_dtrace test_embed test_launcher test_osx_env test_peg_generator test_posix test_pyexpat test_regrtest test_support test_sysconfig test_tools test_venv
      • zipfile: test_shutil test_zipapp test_zipfile test_zipfile64 test_zipimport_support
    • logging: test_unittest
      • hashlib: test_hmac test_tarfile test_unicodedata
    • multiprocessing: test_fcntl test_re
    • queue: test_dummy_thread
    • subprocess: test_atexit test_audit test_ctypes test_faulthandler test_file_eintr test_gzip test_json test_msvcrt test_ntpath test_platform test_plistlib test_pyrepl test_quopri test_repl test_script_helper test_select test_sys_settrace test_tempfile test_traceback test_unittest test_utf8_mode test_wait3 test_webbrowser test_xpickle
      • ctypes.util: test_ctypes
      • ensurepip: test_ensurepip
      • platform: test__locale test__osx_support test_baseexception test_builtin test_cmath test_math test_mimetypes test_strptime
    • sysconfig:
      • trace: test_trace
    • zipfile:
      • shutil: test_filecmp test_glob test_peepholer test_string_literals test_unicode_file test_zoneinfo

[ ] lib: cpython/Lib/asyncio
[ ] test: cpython/Lib/test/test_asyncio (TODO: 3)

dependencies:

  • asyncio (native: _asyncio, _overlapped, _pyrepl.console, _pyrepl.main, _pyrepl.simple_interact, _remote_debugging, _winapi, asyncio.tools, base_events, collections.abc, concurrent.futures, coroutines, errno, events, exceptions, futures, graph, itertools, locks, log, math, msvcrt, protocols, queues, readline, runners, streams, sys, taskgroups, tasks, threads, time, timeouts, transports, unix_events, windows_events)
    • _colorize (native: builtins, collections.abc, nt, sys)
    • argparse (native: sys)
    • ast (native: _ast, sys)
    • code (native: builtins, readline, sys)
    • contextlib (native: sys)
    • dataclasses (native: itertools, sys)
    • inspect (native: _weakref, builtins, collections.abc, importlib.machinery, itertools, sys)
    • io (native: _io, _thread, errno, msvcrt, sys)
    • linecache (native: sys)
    • rlcompleter (native: main, atexit, builtins, readline)
    • site (native: _io, _pyrepl.main, _pyrepl.pager, _pyrepl.readline, _pyrepl.unix_console, _pyrepl.windows_console, atexit, builtins, errno, readline, sitecustomize, sys, usercustomize)
    • socket (native: _socket, array, errno, sys)
    • ssl (native: _ssl, errno, sys, time)
    • stat (native: _stat)
    • subprocess (native: _posixsubprocess, _winapi, builtins, errno, fcntl, grp, msvcrt, pwd, select, sys, time)
    • tokenize (native: _tokenize, builtins, itertools, sys)
    • collections, functools, os, traceback, types, weakref
    • contextvars, enum, heapq, logging, reprlib, selectors, signal, struct, threading, warnings

dependent tests: (8 tests)

  • asyncio: test_asyncio test_concurrent_futures test_external_inspection test_inspect test_logging test_os test_pdb test_unittest

[x] test: cpython/Lib/test/test_thread.py (TODO: 1)
[x] test: cpython/Lib/test/test_thread_local_bytecode.py
[x] test: cpython/Lib/test/test_threadsignals.py

dependencies:

dependent tests: (14 tests)
- [ ] concurrent.futures: test_asyncio test_compileall test_concurrent_futures test_context test_genericalias test_inspect test_struct test_wmi
- [ ] asyncio: test_asyncio test_external_inspection test_logging test_os test_pdb test_unittest

Legend:

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

@youknowone
youknowone marked this pull request as ready for review October 15, 2026 13:46
@youknowone
youknowone merged commit 8e5709e into RustPython:main Oct 15, 2026
31 checks passed
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T13:57:24.944901Z 5414241 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.

@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: 54142418ba

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

# PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
# exposed at the Python level. This test relies on ctypes to get at it.
@unittest.expectedFailure # TODO: RUSTPYTHON
@cpython_only

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep the RustPython async-exception test runnable

On every RustPython run, @cpython_only turns this already-marked expected failure into a skip, so the body is no longer exercised and eventual support for PyThreadState_SetAsyncExc cannot surface as an unexpected success. This body previously ran under expectedFailure and is not a crash or hang case, so keep the RustPython expected-failure marker without this skip.

AGENTS.md reference: AGENTS.md:L98-L101

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You’re right that this body is skipped on RustPython. The @cpython_only guard comes directly from exact CPython 3.15 final, and update_lib preserved the existing RustPython expectedFailure above it. This sync keeps upstream implementation guards intact, so I’m leaving the canonical decorator in place. This conclusion is source-only; I’m not claiming that the PyThreadState_SetAsyncExc test ran.

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