Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Include/internal/pycore_ceval.h
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,7 @@ PyAPI_FUNC(void) _PyEval_FormatAwaitableError(PyThreadState *tstate, PyTypeObjec
PyAPI_FUNC(void) _PyEval_FormatExcCheckArg(PyThreadState *tstate, PyObject *exc, const char *format_str, PyObject *obj);
PyAPI_FUNC(void) _PyEval_FormatExcUnbound(PyThreadState *tstate, PyCodeObject *co, int oparg);
PyAPI_FUNC(void) _PyEval_FormatKwargsError(PyThreadState *tstate, PyObject *func, PyObject *kwargs, PyObject *dupkey);
PyAPI_FUNC(int) _PyEval_MergeKwargs(PyThreadState *tstate, PyObject *func, PyObject *dict, PyObject *kwargs);
PyAPI_FUNC(PyObject *) _PyEval_ImportFrom(PyThreadState *, PyObject *, PyObject *);

PyAPI_FUNC(PyObject *) _PyEval_LazyImportName(
Expand Down
3 changes: 2 additions & 1 deletion Include/internal/pycore_magic_number.h
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,7 @@ Known values:
Python 3.16a1 3706 (Add INTRINSIC_MATCH_CLASS_ISINSTANCE)
Python 3.16a1 3707 (GET_AWAITABLE also pushes NULL and None for SEND)
Python 3.16a1 3708 (GET_ANEXT also pushes NULL and None for SEND)
Python 3.16a1 3709 (Push a lone ** call argument without DICT_MERGE)

Python 3.17 will start with 3750

Expand All @@ -315,7 +316,7 @@ Known values:

*/

#define PYC_MAGIC_NUMBER 3708
#define PYC_MAGIC_NUMBER 3709
/* This is equivalent to converting PYC_MAGIC_NUMBER to 2 bytes
(little-endian) and then appending b'\r\n'. */
#define PYC_MAGIC_NUMBER_TOKEN \
Expand Down
65 changes: 65 additions & 0 deletions Lib/test/test_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,71 @@ def test_kwargs_order_preserved_in_c_functions(self):
self.assertEqual(list(collections.OrderedDict(b=1, a=2, c=3)),
['b', 'a', 'c'])

def test_kwargs_unpacking_mutation_isolated(self):
# gh-86199: a callee mutating its **kwargs must never affect the
# caller's dict.
def fn(**kw):
kw['injected'] = None
d = {'a': 1}
fn(**d)
self.assertEqual(d, {'a': 1})
e = {}
fn(**e)
self.assertEqual(e, {})

@cpython_only
@unittest.skipIf(_testcapi is None, "requires _testcapi")
def test_kwargs_unpacking_not_aliased_in_tp_call(self):
# gh-86199: a tp_call callee receives a private copy of the kwargs
# dict, never the caller's dict.
get_kwargs = _testcapi.get_kwargs # METH_VARARGS | METH_KEYWORDS
d = {'a': 1}
self.assertIsNot(get_kwargs(**d), d)
self.assertEqual(get_kwargs(**d), d)
e = {}
self.assertIsNot(get_kwargs(**e), e)

@cpython_only
@unittest.skipIf(_testcapi is None, "requires _testcapi")
def test_vectorcalldict_kwargs_not_aliased_in_tp_call(self):
# gh-86795: PyObject_VectorcallDict() must not hand the caller's
# kwargs dict to a tp_call callee either.
get_kwargs = _testcapi.get_kwargs # METH_VARARGS | METH_KEYWORDS
d = {'a': 1}
res = _testcapi.pyobject_fastcalldict(get_kwargs, (), d)
self.assertEqual(res, d)
self.assertIsNot(res, d)

@cpython_only
def test_kwargs_merge_saves_stack_pointer(self):
# gh-86199: DICT_MERGE can run arbitrary code (the keys() and
# __getitem__() of the mapping), so the frame's stack pointer must
# be saved first: the mapping has to be visible to the GC.
visible = []

class Mapping:
def keys(self):
referents = gc.get_referents(gen)
visible.append(any(x is self for x in referents))
gc.collect()
return ['b']

def __getitem__(self, key):
return 2

def fn(**kw):
return kw

mapping = Mapping()

def caller():
d = {'a': 1}
yield fn(**d, **mapping)

gen = caller()
self.assertEqual(next(gen), {'a': 1, 'b': 2})
self.assertEqual(visible, [True])

def test_frames_are_popped_after_failed_calls(self):
# GH-93252: stuff blows up if we don't pop the new frame after
# recovering from failed calls:
Expand Down
22 changes: 20 additions & 2 deletions Lib/test/test_capi/test_opt.py
Original file line number Diff line number Diff line change
Expand Up @@ -6151,11 +6151,12 @@ def testfunc(n):

def test_dict_merge(self):
def testfunc(n):
d = {"a": 1, "b": 2}
d = {"a": 1}
e = {"b": 2}
def f(**kwargs):
return kwargs
for _ in range(n):
x = f(**d)
x = f(**d, **e)
return x

res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
Expand All @@ -6166,6 +6167,23 @@ def f(**kwargs):
self.assertGreaterEqual(count_ops(ex, "_POP_TOP_NOP"), 1)
self.assertLessEqual(count_ops(ex, "_POP_TOP"), 2)

def test_call_function_ex_single_kwargs_unpack(self):
# gh-86199: f(**d) no longer copies d with DICT_MERGE
def testfunc(n):
d = {"a": 1, "b": 2}
def f(**kwargs):
return kwargs
for _ in range(n):
x = f(**d)
return x

res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
self.assertEqual(res, {"a": 1, "b": 2})
uops = get_opnames(ex)

self.assertNotIn("_DICT_MERGE", uops)
self.assertIn("_MAKE_CALLARGS_A_TUPLE", uops)

def test_list_extend(self):
def testfunc(n):
a = [1, 2, 3]
Expand Down
45 changes: 45 additions & 0 deletions Lib/test/test_free_threading/test_kwargs_unpack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import unittest
from unittest import TestCase

from test.support import threading_helper, import_helper

_testcapi = import_helper.import_module("_testcapi")

threading_helper.requires_working_threading(module=True)


class TestKwargsUnpackRace(TestCase):
def test_mutate_kwargs_during_unpack(self):
# gh-86199: unpacking a shared kwargs dict must tolerate another
# thread resizing it.
num_mutators, num_callers = 2, 6
iters = 1000
min_keys, max_keys = 4, 3000

fastcalldict = _testcapi.pyobject_fastcalldict

def target(**kwargs):
return len(kwargs)

shared = {f"k{i}": i for i in range(min_keys)}

def resize_kwargs():
for _ in range(iters):
for i in range(min_keys, max_keys):
shared[f"k{i}"] = i
for i in range(max_keys - 1, min_keys - 1, -1):
shared.pop(f"k{i}", None)

def call_target():
for _ in range(iters):
try:
fastcalldict(target, (), shared)
except Exception:
pass

threading_helper.run_concurrently(
[resize_kwargs] * num_mutators + [call_target] * num_callers)


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Speed up calls of the form ``f(**kwargs)`` by no longer always copying the
keyword arguments before the call; such calls are now up to 1.4x faster.
This also fixes :c:func:`PyObject_Call` and :c:func:`PyObject_VectorcallDict`
to copy the keyword arguments before passing them to a callee that would
otherwise receive the caller's dict, so a called object can no longer mutate
the caller's dict (:gh:`86795`), and makes unpacking a shared
keyword-arguments dict safe on the free-threaded build.
Loading
Loading