Skip to content

VM: a declaration block's def goes the evaluator's way (test_module's leak test inside its limit) - #289

Merged
284km merged 1 commit into
mainfrom
stage10-vm-def-in-block
Nov 25, 2026
Merged

284km merged 1 commit into
mainfrom
stage10-vm-def-in-block

Conversation

@284km

@284km 284km commented Nov 25, 2026

Copy link
Copy Markdown
Owner

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 } and Module.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 its definemethod went 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_body reads a VM block's program as the parsed form, for the three forms the proof takes:

the program the parsed form
definemethod :m; putobject :m; leave the def
putself; getglobal/getlocal X; send :using, 1; pop and the def using X and the def
putself; getglobal/getlocal X; send :refine, 1, block; leave, the block's program a def refine X do the def end

The def is the one vm_define would have made (its name, parameters and body, the line of its end, 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: the new call with a literal block (EMethodB), and make_anon_cls_block for the other ways a block reaches new. 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:

program execution main here
Class.new { def foo; end }, 300,000 times VM 19.75 G 13.01 G (-34%)
evaluator 9.95 G 9.97 G
the test's loop (class, refinement, using), 100,000 times VM 37.90 G 28.49 G (-25%)
evaluator 20.24 G 20.27 G

The 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 initialize the 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's inherited hook. 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.sh over 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).
  • The source gates: dead_defs, dup_defs, gc_roots, meth_writes, name_len, ns_names, bracket_depth and record_hygiene each exit 0.

🤖 Generated with Claude Code

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 284km left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, ..., and rescue/ensure in the body: values, parameters, arity, owner, source_location, visibility.
  • def self.x in the block, a def followed by nil, two defs, Class.new { |k| def ... }, a block with a local, a multi-line def (its end line: the :return TracePoint event is on the right line).
  • Class.new(Base) { def m = super + 1 } with Base.inherited; super with no superclass method.
  • refine with 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; super in a refined method; using followed by a def that calls a refined method.
  • private; def, private def, and initialize, initialize_copy, respond_to_missing? and operator names (private or public as in ruby).
  • method_added / singleton_method_added on a superclass, Module#method_added, a prepended Class#inherited that defines a method on the new class, TracePoint :call/:return/:line/:b_call, a Thread blocked on a Queue, a suspended Fiber, define_method and class_eval mixed in.
  • Class.new(&pr), Module.new(&pr), Class.new(&lambda), Class.new(&method(:m)), then proc {}, lambda {}, define_method, Data.define and Struct.new with literal blocks (to look for a stale &pr source).
  • 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_allowed gets the read-back body with the same bp0 and env. If the proof fails, the original SVm body runs. In make_anon_cls_block, native_definition_body (with native_definition_allowed) is what the AST block reaches through register_class_blk0. So the VM block gets the same proof at both places. One difference: on the make_anon_cls_block path, only the one-def form is taken. The using and refine forms 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_at needs putself as the receiver, argc 1, no splat or block-arg flag, and no kwargs. using must have no block. refine must have a block whose program is exactly 3 instructions. Opcode 20 also covers getblockparam. A block param as the argument resolves to a Proc. The proof then refuses it, so it falls back.

Suggestions (inline)

  1. The EMethodB read-back runs side effects before the proof. vm_def_block_body runs for every .new with a literal VM block, whatever the receiver and arguments. It writes def_end_lines and 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_define does the same, so nothing changes. If the block never runs, the tree is no longer unloaded at the end of vm_run and 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 a Class/Module receiver with no arguments, would make "proof failed = nothing changed" literally true.
  2. vm_class_def_block skips the pending_srcproc / pending_home clear. native_include_body (the line above it) and register_class_blk0 both drop these before the native writer. I could not make the stale &pr show (proc {}, lambda {}, define_method, Data.define after Class.new(&pr) all matched ruby). It would still be safer to clear them the same way. (Small: ig in 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_return do not fire for a Class.new { } block.
  • Class.new(&-> { }) and Class.new(&method(:m)) do not raise ArgumentError (given 1, expected 0).
  • using inside 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 through alias_method) is never called.
  • A prepended Class.new override raises "can't instantiate uninitialized class".
  • The order of singleton_methods for a subclass whose superclass defines self.method_added and self.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.

Comment thread main.mere
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

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread main.mere
(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

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@284km
284km merged commit 34ba966 into main Nov 25, 2026
9 of 19 checks passed
284km added a commit that referenced this pull request Nov 25, 2026
VM declaration blocks: read without side effects (#289's review)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant