Repository navigation
Conversation
smart_holder_from_unique_ptr and smart_holder_from_shared_ptr called keep_alive_impl() after init_instance(). On free-threaded builds another thread could find the registered instance and read its flags while has_patients was written. The generic cast path already uses this order. Part of pybind#6214. Assisted-by: ClaudeCode:claude-fable-5-2
|
— codex on behalf of Ralf — Preserve holder ownership if I tested both reproductions on CPython 3.15.2 with the GIL enabled and with a free-threaded build. The parent commit raised Generated by Codex. Ralf has yet to review these findings. |
…inter keep_alive_impl() can throw (no parent). It ran after the wrapper had owned = true and the raw pointer, but before the holder was constructed, so the wrapper cleanup and the temporary smart_holder both deleted the object. Call it immediately after make_new_instance() instead. Assisted-by: ClaudeCode:claude-fable-5-2
|
🤖 AI text below 🤖 The finding is correct. Fixed in the latest commit: in both branches,
|
🤖 AI text below 🤖
Description
Part of #6214, follow-up to #6215.
smart_holder_from_unique_ptrandsmart_holder_from_shared_ptrcalledkeep_alive_impl()afterinit_instance().init_instance()registers the instance, so on free-threaded builds another thread could find it and read its flags whilehas_patientswas written. This PR moves thekeep_alive_impl()call beforeinit_instance(). The generic cast path already uses this order.test_concurrent_cast_of_shared_cpp_objecthas a new case for thereference_internalpolicy. The race is only visible under ThreadSanitizer, which CI does not run. I checked it locally with a TSan build of CPython 3.14.7t: without the fix TSan reports the race (write inadd_patient, read in thevalue_and_holderconstructor) in 3 of 3 runs, and with the fix it reports nothing in 5 of 5 runs.This PR does not close #6214. Two races remain:
py::keep_alive<>on an instance that is already shared writeshas_patientswhile other threads read the same bitfield byte.Suggested changelog entry:
smart_holderinstance returned withreturn_value_policy::reference_internalwas visible to other threads before its keep-alive flag was set.