Repository navigation
VM: a declaration block's def goes the evaluator's way (test_module's leak test inside its limit) - #289
Conversation
Class.new { def m }, Class.new { using X; def m } and Module.new { refine X
do def m end }: the evaluator proves such a block free of observers and
writes the def straight into the new class; the VM ran the block, its
definemethod through the class body's walker. vm_def_block_body reads the
VM block's program as the parsed form, for those three forms, and hands it
to the same proof and writer.
Instructions on the VM: 19.75 G -> 13.01 G for 300,000 Class.new { def },
37.90 G -> 28.49 G for test_complemented_method_entry_memory_leak's loop,
which now passes on the VM inside its time limit. Corpus 825.
284km
left a comment
There was a problem hiding this comment.
Review of ddc5f3d. No Critical, Major or Minor finding. Two Suggestions, inline.
What I ran
Builds: this branch's binary (at ddc5f3d, clean tree, built after every .mere change) and a main build at d586947. d586947 is two merges older than fd5f54b. The evaluator numbers below act as a control for that gap. Reference: ruby 4.0.10. Each probe ran on four executions: this branch's evaluator and VM, and main's VM and evaluator.
Read-back probes (26 small programs). On every probe, this branch's VM output is the same as main's VM output and as this branch's evaluator output. Where it differs from ruby, main differs in the same way (list below). Covered:
- a def with optional args (default with a side effect), rest, kwargs, keyrest, block param,
..., andrescue/ensurein the body: values,parameters,arity,owner,source_location, visibility. def self.xin the block, a def followed bynil, two defs,Class.new { |k| def ... }, a block with a local, a multi-line def (itsendline: the:returnTracePoint event is on the right line).Class.new(Base) { def m = super + 1 }withBase.inherited;superwith no superclass method.refinewith two defs,refine(C) { |x| def ... }, the refinement given as a local, a global (and an aliased global), a constant, a block parameter, and a block-local;superin a refined method;usingfollowed by a def that calls a refined method.private; def,private def, andinitialize,initialize_copy,respond_to_missing?and operator names (private or public as in ruby).method_added/singleton_method_addedon a superclass,Module#method_added, a prependedClass#inheritedthat defines a method on the new class, TracePoint:call/:return/:line/:b_call, a Thread blocked on a Queue, a suspended Fiber,define_methodandclass_evalmixed in.Class.new(&pr),Module.new(&pr),Class.new(&lambda),Class.new(&method(:m)), thenproc {},lambda {},define_method,Data.defineandStruct.newwith literal blocks (to look for a stale&prsource).Foo.new { def ... }on a non-Class receiver whose block is run later or never.Coverage.start(lines: true, methods: true)over a file with both a one-line and a multi-line form.- 50,000 classes made in a loop, then
GC.start, then calling the methods. - corpus 825 itself.
The shortcut is taken. I checked this by instruction count. Class.new(&pr) and Class.new(Object) { def ... } (the make_anon_cls_block entry) are about 20% cheaper on the VM. So is the using form. So the new path is the one my probes went through.
Measurement. Instructions retired (/usr/bin/time -l), median of 3, alternating main and this branch:
| program | execution | main (d586947) | this branch |
|---|---|---|---|
Class.new { def foo; end }, 300,000 times |
VM | 19.37 G | 12.86 G (-34%) |
| evaluator | 9.97 G | 9.99 G | |
class + refinement + using + .new, 100,000 times (my own loop, not the test's) |
VM | 29.76 G | 20.60 G (-31%) |
The first row reproduces your -34%.
merge-tree. git merge-tree --write-tree origin/main against this head is clean (exit 0).
What I read
- The observer proof is the same function with the same inputs on both paths. In
EMethodB,native_constructor_declaration_allowedgets the read-back body with the samebp0andenv. If the proof fails, the originalSVmbody runs. Inmake_anon_cls_block,native_definition_body(withnative_definition_allowed) is what the AST block reaches throughregister_class_blk0. So the VM block gets the same proof at both places. One difference: on themake_anon_cls_blockpath, only the one-def form is taken. Theusingandrefineforms there still run the block. That costs speed only, not correctness. - Coverage: the VM path is skipped when
cov_st[0] != 0, so it is skipped in any coverage state, not only while running. That is stricter than the evaluator, which takes its shortcut and counts lines itself (cov_line). This is safe. My coverage probe matches ruby. - The opcode checks are tight.
send_atneedsputselfas the receiver, argc 1, no splat or block-arg flag, and no kwargs.usingmust have no block.refinemust have a block whose program is exactly 3 instructions. Opcode 20 also coversgetblockparam. A block param as the argument resolves to a Proc. The proof then refuses it, so it falls back.
Suggestions (inline)
- The
EMethodBread-back runs side effects before the proof.vm_def_block_bodyruns for every.newwith a literal VM block, whatever the receiver and arguments. It writesdef_end_linesand sets state bit 2 ("a method was defined from this tree") on the tree, even when the shortcut is then not taken. If the block runs later,vm_definedoes the same, so nothing changes. If the block never runs, the tree is no longer unloaded at the end ofvm_runand is left to the collector. My probe of that case printed what ruby prints. Moving the two side effects into the commit, or running the read-back only for aClass/Modulereceiver with no arguments, would make "proof failed = nothing changed" literally true. vm_class_def_blockskips thepending_srcproc/pending_homeclear.native_include_body(the line above it) andregister_class_blk0both drop these before the native writer. I could not make the stale&prshow (proc {},lambda {},define_method,Data.defineafterClass.new(&pr)all matched ruby). It would still be safer to clear them the same way. (Small:igin the refine arm is bound but unused. The inner program's generation is not checked, only the outer one. This is fine as long as the inner id always comes from a live outer program.)
Pre-existing differences from ruby (same on main's VM and evaluator, not from this PR)
- TracePoint
:b_call/:b_returndo not fire for aClass.new { }block. Class.new(&-> { })andClass.new(&method(:m))do not raise ArgumentError (given 1, expected 0).usinginside a method (def mk(m) = Class.new { using m; ... }) is not refused with "Module#using is not permitted in methods".- A user-defined
Module#refine(prepended, or redefined throughalias_method) is never called. - A prepended
Class.newoverride raises "can't instantiate uninitialized class". - The order of
singleton_methodsfor a subclass whose superclass definesself.method_addedandself.singleton_method_added(the hooks themselves fire as in ruby).
Not checked
The full corpus, vm_check.sh, the vm_compare runs over test_module, test_refinement, test_class and test_method, and the leak test itself (per the review's scope, I relied on the PR's reported results). No RSS comparison.
CI on ddc5f3d: 2 workflows passed (NKF Wasm engine, Linux build dependency controls). The other 7 (CI, gem suites, Rake, runtime load path) were still queued when I posted this.
| let declaration_block = (true, bp0, bb, env) in | ||
| // (...and a block the ISeq VM compiled, whose program is one def: its | ||
| // parsed form, vm_def_block_body) | ||
| let declaration_block = (true, bp0, (if str_eq name "new" then (match vm_def_block_body bb with Nil -> bb | b9 -> b9) else bb), env) in |
There was a problem hiding this comment.
Suggestion: vm_def_block_body bb runs here for every .new with a literal VM block, before the receiver, the arguments and the proof are checked. It has side effects: vm_def_at writes def_end_lines and sets state bit 2 on the tree. When the proof fails, the block runs and vm_define makes the same changes, so that case is fine. When the block never runs (for example Foo.new { def x; end } where Foo#initialize ignores the block), the tree is marked "a method was defined from it". vm_run then leaves it to the collector instead of unloading it. My probe of that case printed what ruby prints. Moving those two writes into the commit (or computing the read-back only when recv is Class/Module and args is empty) would make a failed proof leave nothing behind.
| (let cscope = (if lv_has denv "__cref" then (match lv_get denv "__cref" with VStr h9 -> sget h9 | _ -> "") else "") in | ||
| let saved_file = cur_file () in | ||
| let saved_line = cur_line () in | ||
| let (done9, _) = native_definition_body world cls body cscope denv in |
There was a problem hiding this comment.
Suggestion: native_include_body just above and register_class_blk0 both drop pending_srcproc / pending_home before the native writer. This path does not. I could not make a stale &pr show after Class.new(&pr): proc {}, lambda {}, define_method and Data.define all matched ruby. Clearing them here too would keep the three native writers the same.
VM declaration blocks: read without side effects (#289's review)
test/ruby whole on both executions (#287) found one test at its time limit on the VM alone:
TestModule#test_complemented_method_entry_memory_leak, which makes, 300,000 times, a class with one def, a module refining it with one def, and a class using the refinement with one def. The VM took twice the evaluator's time for it, and the difference was the def inside a block.Why
The evaluator does not run such a block.
Class.new { def m ... end },Class.new { using X; def m ... end }andModule.new { refine X do def m ... end end }are proved free of anything that could observe the class (no hook, trace, thread or signal; a fresh class; the name not one of the hooks) and their def is written straight into the new class's method table (native_constructor_declaration,native_definition_body,native_include_body). That proof reads the parsed block.The VM's block has no parsed form: its body is the statement that runs its program (
SVm). So the proof failed, the block ran, and itsdefinemethodwent through the class body's walker (vm_define,register_class_v), a send from the VM through the evaluator's call layers on the way.The change
vm_def_block_bodyreads a VM block's program as the parsed form, for the three forms the proof takes:definemethod :m; putobject :m; leaveputself; getglobal/getlocal X; send :using, 1; popand the defusing Xand the defputself; getglobal/getlocal X; send :refine, 1, block; leave, the block's program a defrefine X dothe defendThe def is the one
vm_definewould have made (its name, parameters and body, the line of itsend, and the tree marked as one a method was defined from). The parsed form goes to the same proof and the same writer, at the two places the evaluator takes it: thenewcall with a literal block (EMethodB), andmake_anon_cls_blockfor the other ways a block reachesnew. Any other program, or a proof that fails, runs the block as before. Not while coverage runs.Numbers
Instructions, the median of three runs alternating main fd5f54b and this branch:
Class.new { def foo; end }, 300,000 timesThe test itself on the VM, three runs alternating, at a load of about 5: main stops at the 10 s limit each time (10.10 s); here it passes each time in 8.1 to 8.2 s. The evaluator takes 5.7 s.
What remains of the VM's difference in the test's loop is the
initializethe loop calls (a method call on the VM), not the def.Corpus 825 has each form and what it means: the method's owner, its line, a refinement used from the class's method, through
Method#unbind, a local as the argument, a superclass,initialize's visibility, a def named as a hook, a block of two defs, and the class'sinheritedhook. It matches ruby on both executions, here and on main.Checked
Against ruby 4.0.10 (tools/ref_ruby.sh), built with Mere 9dec2ff6, on main fd5f54b:
run_corpus.sh --both: 949/949 match ruby, with the hash index on and off (9 min 48 s).MERE_RUBY_VM=1 run_corpus.sh --both: 949/949 (10 min 47 s).tools/iseq/vm_check.sh: 245/245.unittest/vm_compare.shover test_module, test_refinement, test_class and test_method: 478 tests, VM_ONLY 0, EVAL_ONLY 0, VM_FILE 0 (MATCH 474 on each execution). On main, test_module's leak test was VM_ONLY at its time limit (Record test/ruby whole on both executions (VM_ONLY 2, VM_FILE 0) #287).🤖 Generated with Claude Code