Bug #22618
openYJIT keeps old method entries alive after a method is redefined
Description
I redefine a method many times with define_method. A caller compiled by YJIT calls the method each time. Then the old method entries are never freed by GC, and the objects captured by their blocks are not freed either.
class Captured; end
class Foo; end
2000.times do
captured = Captured.new
Foo.define_method(:bar) { 1 }
Foo.new.bar
end
GC.start
p ObjectSpace.each_object(Captured).count
# no JIT: 1, --yjit: 1971
The block does not even use captured.
This is a minimal reproduction. To see the memory impact, give each object 10KB:
class Captured
def initialize = @data = "x" * 10_000
end
class Foo; end
400_000.times do
captured = Captured.new
Foo.define_method(:bar) { 1 }
Foo.new.bar
end
GC.start
puts "#{ObjectSpace.each_object(Captured).count} objects, " \
"RSS #{`ps -o rss= -p #{$$}`.to_i / 1024}MB"
# ruby 4.0.10, arm64-darwin
# no JIT: 1 objects, RSS 25MB
# --yjit: 243831 objects, RSS 2836MB
The count stops growing only when YJIT reaches --yjit-mem-size (128MB by default). What was kept until then is never freed.
I can reproduce this on 3.4.9, 4.0.10 and master (72d4cf2e9a).
https://github.com/ruby/ruby/commit/72d4cf2e9a
ZJIT does not have this problem.
This can happen in real apps. For example, Mongoid redefines a callback method on every call (probably a bug in Mongoid), so apps that use it with YJIT may see memory grow a lot: https://jira.mongodb.org/browse/MONGOID-6032
This looks similar to https://github.com/Shopify/ruby/issues/552, but the receiver here has no singleton class, so the fix there (https://github.com/ruby/ruby/pull/9693) does not seem to cover it.
No data to display