From 0b9d037c91435d3ac6f52082c0f159b22a2d95f9 Mon Sep 17 00:00:00 2001 From: Robolightning Date: Tue, 10 Nov 2026 19:42:57 +0300 Subject: [PATCH 1/6] Preserve errno across thread-state attachment in release builds Keep the existing _PyThreadState_Attach errno save/restore in release builds as well as debug builds. A release free-threaded attachment can wait for GC or critical-section resumption and change errno, causing valid directory EOF and cold FileFinder operations to raise spurious EAGAIN. Add a public directory/scandir/FileFinder regression under real child-local GC, without native diagnostic modules or third-party code. The identical test fails on current main 3.16 before the four-guard-line change and passes afterwards. Original IO, GC, threading and import suites also pass on the native musl release FT source build. No installed SDK is modified. --- Lib/test/test_free_threading/test_os.py | 82 +++++++++++++++++++++++++ Python/pystate.c | 4 -- 2 files changed, 82 insertions(+), 4 deletions(-) diff --git a/Lib/test/test_free_threading/test_os.py b/Lib/test/test_free_threading/test_os.py index 72582da29015e93..902a08844e6406a 100644 --- a/Lib/test/test_free_threading/test_os.py +++ b/Lib/test/test_free_threading/test_os.py @@ -10,8 +10,90 @@ NTHREADS = 10 +def _directory_scan_during_gc(directory, names): + import gc + import importlib.machinery + import json + import os + import threading + import time + + expected = set(names) + barrier = threading.Barrier(5) + stop = threading.Event() + errors = [] + collections = [] + + def collect(): + barrier.wait(timeout=15) + while not stop.is_set() and len(collections) < 512: + collections.append(gc.collect()) + time.sleep(0.0001) + + def scan(): + barrier.wait(timeout=15) + for _ in range(256): + try: + assert set(os.listdir(directory)) == expected + with os.scandir(directory) as entries: + assert {entry.name for entry in entries} == expected + finder = importlib.machinery.FileFinder( + directory, + (importlib.machinery.SourceFileLoader, + importlib.machinery.SOURCE_SUFFIXES), + ) + assert finder.find_spec('fixture') is not None + except BaseException as error: + errors.append(repr(error)) + + collector = threading.Thread(target=collect) + workers = [threading.Thread(target=scan) for _ in range(4)] + collector.start() + for worker in workers: + worker.start() + try: + for worker in workers: + worker.join(timeout=30) + finally: + stop.set() + collector.join(timeout=15) + assert not collector.is_alive() + assert all(not worker.is_alive() for worker in workers) + assert collections + return json.dumps(errors) + + @threading_helper.requires_working_threading() class TestOs(unittest.TestCase): + def test_directory_io_during_subinterpreter_gc(self): + from concurrent import interpreters + from concurrent.futures import ThreadPoolExecutor + import json + from pathlib import Path + import tempfile + + names = ('fixture.py',) + tuple(f'file_{n:02d}.txt' + for n in range(32)) + with tempfile.TemporaryDirectory() as directory: + for name in names: + Path(directory, name).write_text('VALUE = 73\n') + for _ in range(16): + children = [interpreters.create() for _ in range(4)] + try: + with ThreadPoolExecutor(max_workers=4) as pool: + futures = [pool.submit(child.call, + _directory_scan_during_gc, + directory, names) + for child in children] + results = [future.result(timeout=90) + for future in futures] + finally: + for child in children: + child.close() + for result in results: + errors = json.loads(result) + self.assertFalse(errors, errors[:3]) + @unittest.skipUnless(sysconfig.get_config_var('_Py_HAVE_STRERROR_R'), 'need _Py_HAVE_STRERROR_R macro') def test_strerror(self): diff --git a/Python/pystate.c b/Python/pystate.c index ce7197c4e054283..2b4e8b9d6660bc5 100644 --- a/Python/pystate.c +++ b/Python/pystate.c @@ -2383,11 +2383,9 @@ tstate_wait_attach(PyThreadState *tstate) void _PyThreadState_Attach(PyThreadState *tstate) { -#if defined(Py_DEBUG) // This is called from PyEval_RestoreThread(). Similar // to it, we need to ensure errno doesn't change. int err = errno; -#endif _Py_EnsureTstateNotNULL(tstate); if (current_fast_get() != NULL) { @@ -2434,9 +2432,7 @@ _PyThreadState_Attach(PyThreadState *tstate) _PyStats_Attach((_PyThreadStateImpl *)tstate); #endif -#if defined(Py_DEBUG) errno = err; -#endif } static void From 452cc04e036b0af34dc541d219d64764db937f5b Mon Sep 17 00:00:00 2001 From: Robolightning Date: Tue, 10 Nov 2026 21:18:08 +0300 Subject: [PATCH 2/6] gh-161769: Document errno preservation across thread-state attachment --- .../2026-11-10-18-17-09.gh-issue-161769.wL6r9A.rst | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-11-10-18-17-09.gh-issue-161769.wL6r9A.rst diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-10-18-17-09.gh-issue-161769.wL6r9A.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-10-18-17-09.gh-issue-161769.wL6r9A.rst new file mode 100644 index 000000000000000..7c7f24c92327fcd --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-10-18-17-09.gh-issue-161769.wL6r9A.rst @@ -0,0 +1,3 @@ +Preserve :c:var:`errno` across thread-state attachment in release builds, +preventing spurious directory I/O errors on free-threaded builds during +concurrent garbage collection. From 87ad37ccfc046a418ef0af97b6453d806e5b72d9 Mon Sep 17 00:00:00 2001 From: Robolightning Date: Tue, 10 Nov 2026 21:28:58 +0300 Subject: [PATCH 3/6] gh-161769: Render errno as a literal in NEWS Correct the new NEWS reference rejected by the actual Docs job. Keep the qualified native source and public regression unchanged. --- .../2026-11-10-18-17-09.gh-issue-161769.wL6r9A.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-10-18-17-09.gh-issue-161769.wL6r9A.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-10-18-17-09.gh-issue-161769.wL6r9A.rst index 7c7f24c92327fcd..f2425c70daa5cbd 100644 --- a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-10-18-17-09.gh-issue-161769.wL6r9A.rst +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-10-18-17-09.gh-issue-161769.wL6r9A.rst @@ -1,3 +1,3 @@ -Preserve :c:var:`errno` across thread-state attachment in release builds, +Preserve ``errno`` across thread-state attachment in release builds, preventing spurious directory I/O errors on free-threaded builds during concurrent garbage collection. From 920a86d1f31dd099d7b7aac434863aaaca2e8f21 Mon Sep 17 00:00:00 2001 From: Robolightning Date: Tue, 10 Nov 2026 22:15:28 +0300 Subject: [PATCH 4/6] gh-161769: Use standard long timeouts for concurrent regression Actual upstream TSanFT reached the new hard30second worker-join timeout before the scanners finished. Use test.support.LONG_TIMEOUT as recommended for slow/instrumented buildbots. Keep all scan/GC workload and assertions. Re-prove the identical adjusted test on both current3.15 andmain native release FT cores: actual BlockingIOError before, PASS after unchanged errno fix. Original failing CI log and native loaded-library hashes are retained. --- Lib/test/test_free_threading/test_os.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Lib/test/test_free_threading/test_os.py b/Lib/test/test_free_threading/test_os.py index 902a08844e6406a..83f1cc39d62faa2 100644 --- a/Lib/test/test_free_threading/test_os.py +++ b/Lib/test/test_free_threading/test_os.py @@ -17,6 +17,7 @@ def _directory_scan_during_gc(directory, names): import os import threading import time + from test import support expected = set(names) barrier = threading.Barrier(5) @@ -25,13 +26,13 @@ def _directory_scan_during_gc(directory, names): collections = [] def collect(): - barrier.wait(timeout=15) + barrier.wait(timeout=support.LONG_TIMEOUT) while not stop.is_set() and len(collections) < 512: collections.append(gc.collect()) time.sleep(0.0001) def scan(): - barrier.wait(timeout=15) + barrier.wait(timeout=support.LONG_TIMEOUT) for _ in range(256): try: assert set(os.listdir(directory)) == expected @@ -53,10 +54,10 @@ def scan(): worker.start() try: for worker in workers: - worker.join(timeout=30) + worker.join(timeout=support.LONG_TIMEOUT) finally: stop.set() - collector.join(timeout=15) + collector.join(timeout=support.LONG_TIMEOUT) assert not collector.is_alive() assert all(not worker.is_alive() for worker in workers) assert collections @@ -67,6 +68,7 @@ def scan(): class TestOs(unittest.TestCase): def test_directory_io_during_subinterpreter_gc(self): from concurrent import interpreters + from test import support from concurrent.futures import ThreadPoolExecutor import json from pathlib import Path @@ -85,7 +87,7 @@ def test_directory_io_during_subinterpreter_gc(self): _directory_scan_during_gc, directory, names) for child in children] - results = [future.result(timeout=90) + results = [future.result(timeout=support.LONG_TIMEOUT) for future in futures] finally: for child in children: From aac344d4957ec81eeeab4d7858d7fdb757e5eab6 Mon Sep 17 00:00:00 2001 From: Robolightning Date: Wed, 11 Nov 2026 07:41:41 +0300 Subject: [PATCH 5/6] gh-161769: Focus errno regression on ordinary threads and GC Replace the directory/SI lifecycle helper with one public listdir test using the existing run_concurrently helper. Four ordinary threads each collect GC and check a real directory. No FileFinder, JSON, subinterpreters, ThreadPool, custom stop/barrier or deadline logic is needed. The exact smaller test reproduced BlockingIOError errno11 before and passed after the unchanged native errno fix on both main and3.15 native Release FT musl cores. The existing strerror test remains unchanged and the full test_os module passes on both corrected runtimes. --- Lib/test/test_free_threading/test_os.py | 91 ++++--------------------- 1 file changed, 12 insertions(+), 79 deletions(-) diff --git a/Lib/test/test_free_threading/test_os.py b/Lib/test/test_free_threading/test_os.py index 83f1cc39d62faa2..5e0cb81630d58ab 100644 --- a/Lib/test/test_free_threading/test_os.py +++ b/Lib/test/test_free_threading/test_os.py @@ -10,91 +10,24 @@ NTHREADS = 10 -def _directory_scan_during_gc(directory, names): - import gc - import importlib.machinery - import json - import os - import threading - import time - from test import support - - expected = set(names) - barrier = threading.Barrier(5) - stop = threading.Event() - errors = [] - collections = [] - - def collect(): - barrier.wait(timeout=support.LONG_TIMEOUT) - while not stop.is_set() and len(collections) < 512: - collections.append(gc.collect()) - time.sleep(0.0001) - - def scan(): - barrier.wait(timeout=support.LONG_TIMEOUT) - for _ in range(256): - try: - assert set(os.listdir(directory)) == expected - with os.scandir(directory) as entries: - assert {entry.name for entry in entries} == expected - finder = importlib.machinery.FileFinder( - directory, - (importlib.machinery.SourceFileLoader, - importlib.machinery.SOURCE_SUFFIXES), - ) - assert finder.find_spec('fixture') is not None - except BaseException as error: - errors.append(repr(error)) - - collector = threading.Thread(target=collect) - workers = [threading.Thread(target=scan) for _ in range(4)] - collector.start() - for worker in workers: - worker.start() - try: - for worker in workers: - worker.join(timeout=support.LONG_TIMEOUT) - finally: - stop.set() - collector.join(timeout=support.LONG_TIMEOUT) - assert not collector.is_alive() - assert all(not worker.is_alive() for worker in workers) - assert collections - return json.dumps(errors) - - @threading_helper.requires_working_threading() class TestOs(unittest.TestCase): - def test_directory_io_during_subinterpreter_gc(self): - from concurrent import interpreters - from test import support - from concurrent.futures import ThreadPoolExecutor - import json + def test_listdir_during_gc(self): + import gc from pathlib import Path import tempfile - names = ('fixture.py',) + tuple(f'file_{n:02d}.txt' - for n in range(32)) with tempfile.TemporaryDirectory() as directory: - for name in names: - Path(directory, name).write_text('VALUE = 73\n') - for _ in range(16): - children = [interpreters.create() for _ in range(4)] - try: - with ThreadPoolExecutor(max_workers=4) as pool: - futures = [pool.submit(child.call, - _directory_scan_during_gc, - directory, names) - for child in children] - results = [future.result(timeout=support.LONG_TIMEOUT) - for future in futures] - finally: - for child in children: - child.close() - for result in results: - errors = json.loads(result) - self.assertFalse(errors, errors[:3]) + expected = {f"entry_{n}" for n in range(32)} + for name in expected: + Path(directory, name).touch() + + def worker(): + for _ in range(256): + gc.collect() + self.assertEqual(set(os.listdir(directory)), expected) + + run_concurrently(worker, nthreads=4) @unittest.skipUnless(sysconfig.get_config_var('_Py_HAVE_STRERROR_R'), 'need _Py_HAVE_STRERROR_R macro') From 3451dc8914e516966e8539779a99ad8ca9314ff6 Mon Sep 17 00:00:00 2001 From: Robolightning Date: Mon, 16 Nov 2026 23:03:21 +0300 Subject: [PATCH 6/6] gh-161769: preserve Windows error state during thread attachment --- Python/ceval_gil.c | 8 -------- Python/pystate.c | 15 +++++++++++++-- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/Python/ceval_gil.c b/Python/ceval_gil.c index 91c75cdd2ed4133..30aadae0db4435c 100644 --- a/Python/ceval_gil.c +++ b/Python/ceval_gil.c @@ -651,16 +651,8 @@ PyEval_SaveThread(void) void PyEval_RestoreThread(PyThreadState *tstate) { -#ifdef MS_WINDOWS - int err = GetLastError(); -#endif - _Py_EnsureTstateNotNULL(tstate); _PyThreadState_Attach(tstate); - -#ifdef MS_WINDOWS - SetLastError(err); -#endif } diff --git a/Python/pystate.c b/Python/pystate.c index 2b4e8b9d6660bc5..4bf39490766baa5 100644 --- a/Python/pystate.c +++ b/Python/pystate.c @@ -27,6 +27,10 @@ #include "pycore_time.h" // _PyTime_Init() #include "pycore_uniqueid.h" // _PyObject_FinalizePerThreadRefcounts() +#ifdef MS_WINDOWS +# include +#endif + /* -------------------------------------------------------------------------- CAUTION @@ -2383,8 +2387,12 @@ tstate_wait_attach(PyThreadState *tstate) void _PyThreadState_Attach(PyThreadState *tstate) { - // This is called from PyEval_RestoreThread(). Similar - // to it, we need to ensure errno doesn't change. + // Reattachment may wait for GC and change errno, even after a successful + // system call (gh-161769). Preserve the caller's error state in release + // builds as well as debug builds. +#ifdef MS_WINDOWS + DWORD last_error = GetLastError(); +#endif int err = errno; _Py_EnsureTstateNotNULL(tstate); @@ -2433,6 +2441,9 @@ _PyThreadState_Attach(PyThreadState *tstate) #endif errno = err; +#ifdef MS_WINDOWS + SetLastError(last_error); +#endif } static void