From 62ef42287310c749d51c5d4d821b3157a6597d20 Mon Sep 17 00:00:00 2001 From: Kumar Aditya Date: Sat, 28 Nov 2026 16:35:48 +0530 Subject: [PATCH] gh-162711: Only record branch history when tier 2 is enabled In the free-threaded build the main thread's bytecode is stored inline in the code object, so the store done by RECORD_BRANCH_TAKEN on every conditional jump caused false sharing with other threads reading co_tlbc and _co_instrumentation_version when calling the same function. The branch history is only used by the tier 2 optimizer, so only record it when _Py_TIER2 is defined. --- .../2026-11-28-11-20-00.gh-issue-162711.bR4hTq.rst | 3 +++ Python/ceval_macros.h | 9 +++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-11-28-11-20-00.gh-issue-162711.bR4hTq.rst diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-28-11-20-00.gh-issue-162711.bR4hTq.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-28-11-20-00.gh-issue-162711.bR4hTq.rst new file mode 100644 index 00000000000000..7ba8c6e4bbcf25 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-28-11-20-00.gh-issue-162711.bR4hTq.rst @@ -0,0 +1,3 @@ +Fix a performance regression in the :term:`free-threaded build` where a +thread ran slower while the main thread was executing the same function +concurrently. diff --git a/Python/ceval_macros.h b/Python/ceval_macros.h index 36921e35533433..27c9a8d8688533 100644 --- a/Python/ceval_macros.h +++ b/Python/ceval_macros.h @@ -384,8 +384,13 @@ static void dtrace_function_return(_PyInterpreterFrame *); } while (0); #endif -#ifdef ENABLE_SPECIALIZATION -/* Multiple threads may execute these concurrently if thread-local bytecode is +#if defined(ENABLE_SPECIALIZATION) && defined(_Py_TIER2) +/* The branch history is only used by the tier 2 optimizer. Don't record it + * otherwise: in the free-threaded build the main thread's bytecode is stored + * inline in the code object, so the store would cause false sharing with + * threads reading the code object's other fields. + * + * Multiple threads may execute these concurrently if thread-local bytecode is * disabled and they all execute the main copy of the bytecode. Specialization * is disabled in that case so the value is unused, but the RMW cycle should be * free of data races.