Bug #22500
closedKeyword arguments can be freed during argument setup when a method has more than 31 keywords
Description
# 32 optional keywords with static defaults, then a 33rd whose default is not static.
kws = (0...32).map { |i| "k#{i}: nil" }.join(", ")
eval "def m(#{kws}, k32: Object.new) = k1"
GC.stress = true
10.times { m(k1: Object.new).inspect }
GC.stress = false
puts "ok"
It runs clean if k0 is passed instead of k1, or with 31 keywords instead of 33.
Without GC.stress, we saw this as wrong values in CI on 4.0.6, with no crash. A keyword local of Temporalio::Worker#initialize (34 keywords) held an unrelated String in place of the Array passed for it.
vm_callee_setup_arg and vm_call_iseq_setup_kwparm_kwarg call args_setup_kw_parameters with the keyword locals above cfp->sp. Once a passed value is moved into its local, that slot holds the only reference. When an optional keyword at index 31 or higher is left to a default that is not static, args_setup_kw_parameters_not_found allocates the tracking set with rb_ident_set_new(). A GC started by that allocation does not mark the locals and frees the values.
#22335 has the same root cause. Its fix removed the method call from this window but kept the allocation.
PR: https://github.com/ruby/ruby/pull/19679 extends cfp->sp over the keyword locals during setup, as setup_parameters_complex does, but only for methods with more than 31 keywords. Shorter methods keep the current fast path. It adds a regression test to test/ruby/test_keyword.rb.
I investigated this with the help of an AI assistant (Claude Code), since I don't know the Ruby VM internals well. That includes the analysis of the mechanism and the patch, so please review them with that in mind.
Reproduced on master, 3.3.12, 3.4.9, 4.0.6, 4.0.8 and 4.0.9.
Files