Skip to content

Commit 9feed03

Browse files
authored
Merge branch 'main' into fix/gh-111066-unpickler-memo
2 parents 2b47fc3 + e0d0f2e commit 9feed03

41 files changed

Lines changed: 738 additions & 244 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎Doc/builtins/functions.rst‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1181,6 +1181,11 @@ are always available. They are listed here in alphabetical order.
11811181
a :exc:`TypeError` exception is raised. :exc:`TypeError` may not be
11821182
raised for an invalid type if an earlier check succeeds.
11831183

1184+
If *object* has a ``__class__`` attribute that differs from
1185+
:func:`type(object) <type>` (for example a proxy, or a :mod:`unittest.mock`
1186+
object created with a *spec*), ``True`` is also returned when that class
1187+
is a subclass of *classinfo*.
1188+
11841189
.. versionchanged:: 3.10
11851190
*classinfo* can be a :ref:`types-union`.
11861191

‎Include/internal/pycore_ceval.h‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -350,9 +350,10 @@ _PyEval_SpecialMethodCanSuggest(PyObject *self, int oparg);
350350
#define _PY_EVAL_PLEASE_STOP_BIT (1U << 5)
351351
#define _PY_EVAL_EXPLICIT_MERGE_BIT (1U << 6)
352352
#define _PY_EVAL_JIT_INVALIDATE_COLD_BIT (1U << 7)
353+
#define _PY_EVAL_PROCESS_DELAYED_BIT (1U << 8)
353354

354355
/* Reserve a few bits for future use */
355-
#define _PY_EVAL_EVENTS_BITS 8
356+
#define _PY_EVAL_EVENTS_BITS 9
356357
#define _PY_EVAL_EVENTS_MASK ((1 << _PY_EVAL_EVENTS_BITS)-1)
357358

358359
static inline void

‎Include/internal/pycore_qsbr.h‎

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,6 @@ struct _qsbr_thread_state {
6161
// and in a different thread.
6262
size_t deferred_page_memory;
6363

64-
// True if the deferred memory frees should be processed.
65-
bool should_process;
66-
6764
// Is this thread state allocated?
6865
bool allocated;
6966
struct _qsbr_thread_state *freelist_next;
@@ -142,14 +139,6 @@ _Py_qsbr_advance(struct _qsbr_shared *shared);
142139
extern uint64_t
143140
_Py_qsbr_shared_next(struct _qsbr_shared *shared);
144141

145-
// Return true if deferred memory frees held by QSBR should be processed to
146-
// determine if they can be safely freed.
147-
static inline bool
148-
_Py_qsbr_should_process(struct _qsbr_thread_state *qsbr)
149-
{
150-
return qsbr->should_process;
151-
}
152-
153142
// Have the read sequences advanced to the given goal? If this returns true,
154143
// it safe to reclaim any memory tagged with the goal (or earlier goal).
155144
extern bool

‎Include/refcount.h‎

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -254,13 +254,12 @@ PyAPI_FUNC(void) _Py_DecRef(PyObject *);
254254

255255
static inline Py_ALWAYS_INLINE void Py_INCREF(PyObject *op)
256256
{
257-
#if (defined(Py_LIMITED_API) && (Py_LIMITED_API+0 >= 0x030c0000 || defined(Py_REF_DEBUG))) \
258-
|| defined(_Py_OPAQUE_PYOBJECT)
259-
// Stable ABI implements Py_INCREF() as a function call on limited C API
260-
// version 3.12 and newer, abi3t, and on Python built in debug mode.
261-
// _Py_IncRef() was added to Python 3.10.0a7, use Py_IncRef() on older versions.
262-
// Py_IncRef() accepts NULL whereas _Py_IncRef() doesn't.
263-
# if Py_LIMITED_API+0 >= 0x030a00A7
257+
#if defined(Py_LIMITED_API) || defined(_Py_OPAQUE_PYOBJECT)
258+
// gh-158401: The stable ABI now implements Py_INCREF() as a function
259+
// call on all limited C API versions. _Py_IncRef() was added to Python
260+
// 3.10.0a7, use Py_IncRef() on older versions. Py_IncRef() accepts NULL,
261+
// whereas _Py_IncRef() doesn't.
262+
# if Py_LIMITED_API+0 >= _Py_PACK_VERSION(3, 10)
264263
_Py_IncRef(op);
265264
# else
266265
Py_IncRef(op);
@@ -324,14 +323,13 @@ PyAPI_FUNC(void) _Py_MergeZeroLocalRefcount(PyObject *);
324323
#endif // Py_GIL_DISABLED
325324
#endif // Py_LIMITED_API
326325

327-
#if (defined(Py_LIMITED_API) && (Py_LIMITED_API+0 >= 0x030c0000 || defined(Py_REF_DEBUG))) \
328-
|| defined(_Py_OPAQUE_PYOBJECT)
329-
// Stable ABI implements Py_DECREF() as a function call on limited C API
330-
// version 3.12 and newer, abi3t, and on Python built in debug mode.
331-
// _Py_DecRef() was added to Python 3.10.0a7, use Py_DecRef() on older versions.
332-
// Py_DecRef() accepts NULL whereas _Py_DecRef() doesn't.
326+
#if defined(Py_LIMITED_API) || defined(_Py_OPAQUE_PYOBJECT)
327+
// gh-158401: The stable ABI now implements Py_DECREF() as a function call
328+
// on all limited C API versions. _Py_DecRef() was added to Python 3.10.0a7,
329+
// use Py_DecRef() on older versions. Py_DecRef() accepts NULL, whereas
330+
// _Py_DecRef() doesn't.
333331
static inline void Py_DECREF(PyObject *op) {
334-
# if Py_LIMITED_API+0 >= 0x030a00A7
332+
# if Py_LIMITED_API+0 >= _Py_PACK_VERSION(3, 10)
335333
_Py_DecRef(op);
336334
# else
337335
Py_DecRef(op);

‎InternalDocs/qsbr.md‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -116,20 +116,22 @@ its last advance:
116116
is larger than `QSBR_FREE_MEM_LIMIT` (1 MiB), when the accumulated deferred
117117
memory exceeds that limit, or when the count exceeds `QSBR_DEFERRED_LIMIT`
118118
(127, sized so a chunk of work items is processed before it overflows).
119-
Crossing any of these thresholds also sets a per-thread `should_process`
120-
flag, signalling that the deferred-free list should be drained.
119+
Crossing any of these thresholds also sets the thread's
120+
`_PY_EVAL_PROCESS_DELAYED_BIT` eval breaker bit, signalling that the
121+
deferred-free list should be drained.
121122

122123
* For mimalloc pages held by QSBR, the thread tracks `deferred_page_memory`
123124
and advances `wr_seq` when either the individual page or the accumulated
124125
page memory exceeds `QSBR_PAGE_MEM_LIMIT` (4096 * 20 bytes). Advancing
125126
promptly here matters because a held page cannot be reused for a different
126127
size class or by a different thread.
127128

128-
Processing of the deferred-free list normally happens from the eval breaker
129-
(rather than from inside `_PyMem_FreeDelayed`), which gives the global
130-
`rd_seq` a better chance to have advanced far enough that items can actually
131-
be freed. `_PyMem_ProcessDelayed` is still called from the free path as a
132-
safety valve when a work-item chunk fills up.
129+
Processing of the deferred-free list happens from the eval breaker rather
130+
than from inside `_PyMem_FreeDelayed`. This gives the global `rd_seq` a better
131+
chance to have advanced far enough that items can actually be freed. It is
132+
also required for correctness: items queued by `_PyObject_XDecRefDelayed` may
133+
run arbitrary code when they are released, and the callers of
134+
`_PyMem_FreeDelayed` may be in the middle of mutating a dict, list or type.
133135

134136
This optimization improves runtime speed but may increase peak memory usage
135137
by slightly delaying when memory can be reclaimed; the size-based thresholds

‎Lib/asyncio/subprocess.py‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -77,13 +77,14 @@ def pipe_connection_lost(self, fd, exc):
7777
if pipe is not None:
7878
pipe.close()
7979
self.connection_lost(exc)
80-
if exc is None:
81-
self._stdin_closed.set_result(None)
82-
else:
83-
self._stdin_closed.set_exception(exc)
84-
# Since calling `wait_closed()` is not mandatory,
85-
# we shouldn't log the traceback if this is not awaited.
86-
self._stdin_closed._log_traceback = False
80+
if not self._stdin_closed.done():
81+
if exc is None:
82+
self._stdin_closed.set_result(None)
83+
else:
84+
self._stdin_closed.set_exception(exc)
85+
# Since calling `wait_closed()` is not mandatory,
86+
# we shouldn't log the traceback if this is not awaited.
87+
self._stdin_closed._log_traceback = False
8788
return
8889
if fd == 1:
8990
reader = self.stdout

‎Lib/importlib/_bootstrap_external.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1461,6 +1461,13 @@ def _find_children(self):
14611461
while True:
14621462
try:
14631463
entry = next(scan_iterator)
1464+
except StopIteration:
1465+
break
1466+
except OSError:
1467+
# A failing scan cannot make progress; end the listing
1468+
# like _fill_cache() treats an unreadable directory.
1469+
break
1470+
try:
14641471
if entry.name == _PYCACHE:
14651472
continue
14661473
# packages
@@ -1474,9 +1481,7 @@ def _find_children(self):
14741481
if entry.name.endswith(suffix)
14751482
}
14761483
except OSError:
1477-
pass # ignore exceptions from next(scan_iterator) and os.DirEntry
1478-
except StopIteration:
1479-
break
1484+
pass # skip entries whose os.DirEntry methods fail
14801485

14811486
def discover(self, parent=None):
14821487
if parent and parent.submodule_search_locations is None:

‎Lib/test/test_asyncio/test_subprocess.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,31 @@ async def write_stdin(proc, data):
435435
self.loop.run_until_complete, coro)
436436
self.loop.run_until_complete(proc.wait())
437437

438+
def test_stdin_wait_closed_cancelled(self):
439+
# gh-162217: cancelling a task waiting in stdin.wait_closed() must
440+
# not make pipe_connection_lost() fail with InvalidStateError.
441+
async def main():
442+
proc = await asyncio.create_subprocess_exec(
443+
*PROGRAM_CAT,
444+
stdin=subprocess.PIPE,
445+
stdout=subprocess.DEVNULL,
446+
)
447+
try:
448+
task = asyncio.create_task(proc.stdin.wait_closed())
449+
await asyncio.sleep(0)
450+
task.cancel()
451+
with self.assertRaises(asyncio.CancelledError):
452+
await task
453+
finally:
454+
proc.stdin.close()
455+
await proc.wait()
456+
457+
messages = []
458+
self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx))
459+
460+
self.loop.run_until_complete(main())
461+
self.assertEqual(messages, [])
462+
438463
def test_communicate_ignore_broken_pipe(self):
439464
# buffer large enough to feed the whole pipe buffer
440465
large_data = b'x' * support.PIPE_MAX_SIZE

‎Lib/test/test_ctypes/test_arrays.py‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
import ctypes
22
import sys
3+
import threading
34
import unittest
5+
from concurrent.futures import ThreadPoolExecutor
46
from ctypes import (Structure, Array, ARRAY, sizeof, addressof,
57
create_string_buffer, create_unicode_buffer,
68
c_char, c_wchar, c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint,
79
c_long, c_ulonglong, c_float, c_double, c_longdouble)
8-
from test.support import bigmemtest, _2G, threading_helper, Py_GIL_DISABLED
10+
from test.support import (bigmemtest, _2G, threading_helper,
11+
Py_GIL_DISABLED, SHORT_TIMEOUT)
912
from ._support import (_CData, PyCArrayType, Py_TPFLAGS_DISALLOW_INSTANTIATION,
1013
Py_TPFLAGS_IMMUTABLETYPE)
1114

@@ -288,5 +291,49 @@ def run():
288291
raise cm.exc_value
289292

290293

294+
class ArrayTypeCacheTest(unittest.TestCase):
295+
# gh-160978: the array type cache could hand out distinct type objects for
296+
# the same (item type, length) pair when the array type was created from
297+
# more than one thread at a time.
298+
299+
@threading_helper.requires_working_threading()
300+
def test_concurrent_creation_with_set_name(self):
301+
# Creating the array type runs Python code -- ``__set_name__`` here --
302+
# which lets a second thread reach the cache before the first one has
303+
# stored its type. Without the fix this fails on the default build as
304+
# well, so it guards the fix even where threads cannot interleave
305+
# freely.
306+
barrier = threading.Barrier(2)
307+
308+
class Meta(type(c_int)):
309+
def __set_name__(cls, owner, name):
310+
barrier.wait(timeout=SHORT_TIMEOUT)
311+
312+
class Item(c_int, metaclass=Meta):
313+
pass
314+
315+
with ThreadPoolExecutor(2) as pool:
316+
first, second = pool.map(lambda _: Item * 100, range(2))
317+
318+
self.assertIs(first, second)
319+
# Raises TypeError if the two types are distinct.
320+
first.from_param(second())
321+
322+
@threading_helper.requires_working_threading()
323+
def test_concurrent_creation_returns_identical_types(self):
324+
nthreads = 8
325+
barrier = threading.Barrier(nthreads)
326+
327+
def make_type(length):
328+
barrier.wait(timeout=SHORT_TIMEOUT)
329+
return c_int * length
330+
331+
with ThreadPoolExecutor(nthreads) as pool:
332+
for length in range(1, 51):
333+
types = list(pool.map(make_type, [length] * nthreads))
334+
barrier.reset()
335+
self.assertEqual(len(set(types)), 1)
336+
337+
291338
if __name__ == '__main__':
292339
unittest.main()

‎Lib/test/test_external_inspection.py‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2068,23 +2068,19 @@ def test_empty_native_thread_stack(self):
20682068
"Test only runs on Linux with process_vm_readv support",
20692069
)
20702070
def test_popping_python_frame_is_not_native(self):
2071-
script = """\
2071+
script_body = """\
20722072
def leaf(depth):
20732073
if depth:
20742074
leaf(depth - 1)
20752075
20762076
while True:
20772077
leaf(300)
20782078
"""
2079-
with _managed_subprocess([sys.executable, "-c", script]) as process:
2080-
for _ in busy_retry(SHORT_TIMEOUT):
2081-
try:
2082-
unwinder = RemoteUnwinder(
2083-
process.pid, native=True, gc=False, cache_frames=False,
2084-
)
2085-
except RuntimeError:
2086-
continue
2087-
break
2079+
2080+
with self._target_process(script_body) as (process, _, _):
2081+
unwinder = RemoteUnwinder(
2082+
process.pid, native=True, gc=False, cache_frames=False,
2083+
)
20882084
# The unwinder can attach before the main loop starts.
20892085
_get_stack_trace_with_retry(
20902086
unwinder,

0 commit comments

Comments
 (0)