Feature #22667
openDefine clear limits for number of arguments a method or block can have
Description
Context¶
Instructions Sequences (ISeq) are a very important contributor to Ruby applications memory usage, every method, every block etc has an associated ISeq, and Iseq are quite large.
On 4.0, the smallest possible Iseq (RubyVM::InstructionSequence.compile(''), just putnil; leave;) is between 448B and 480B large depending on which allocator is used.
Given it's quite idiomatic in Ruby to use lots of small methods, real world Ruby application tend to contain a lot of ISeq. For largish Rails application, Iseq quickly start occupying several hundred megabytes of memory:
require "objspace"
require "json"
GC.start
f = ObjectSpace.dump_all(output: :file)
f.rewind
n = b = 0
f.each_line do |l|
next unless l.include?(%q("imemo_type":"iseq"))
n += 1
b += JSON.parse(l)["memsize"]
end
puts "#{n} iseqs, #{(b / 1e6).round(1)} MB, #{b / n} B/iseq"
From one of our production app:
And that's just the memsize_of estimate, that doesn't account for the malloc overhead and padding.
A lot of that tend to be shared thanks to copy-on-write, but still.
I've recently made improvements in this space (on master the smallest ISeq is now 352B), but there's some further optimisations I'd like to do that I'm unclear if they're safe or not, mostly because Ruby doesn't have clearly defined limits for various constructs.
Number of arguments¶
Currently we use unsigned int to store the number of arguments a method or proc accepts, so theoretically, you could define a method that takes 4 billion positional arguments, but it's not even clear if attempting to do so would run into some other VM limit and how it would fail.
Should we specify a maximum number of arguments a method can take and fail anything larger with a SyntaxError? And if so what should that limit be? I personally think 255 would be more than plenty, but another options is 65536 (2**16).
Currently we store between 5 and 9 such arguments counts per Iseq, so 20 or 36B. a 255 limit on the total number of arguments would allow to pack that structure much tighter.
Line numbers¶
In ISeq we record the line number associated with each instruction, here again we use a full int, so theoretically a method could span on 4 billion lines (+/- 2 billions), that seems a bit ridiculous.
Should we enforce a limit there as well? Would it be ok to limit ISeqs to 65536 lines? Or is that too small and we should keep the current 2B limit?
Alternatively, even a signed 24bit limit (+/-8M lines) could be beneficial.
Edit: this was defined as 32bit (signed or unsigned depending on context) in https://bugs.ruby-lang.org/issues/20488#note-1