Repository navigation
Preserve definition-site yield in define_method bodies - #250
Conversation
284km
left a comment
There was a problem hiding this comment.
Reviewed exact head 76ff79da3c13d5d3452f01aeaabdb6877d05d30e against fetched current main d03cbb8371a10da6c974969606018eb91af60c84, including the changed implementation, callers, regression programs and validation record. Existing reviews, discussion and inline threads were read. Neither base nor head contains tracked AGENTS.md/CLAUDE.md instructions.
One Major/P2 finding is attached: define_method/define_singleton_method with a forwarded &body Proc captures the registrar methods block instead of the Procs own lexical yield block. Four independent controls reproduce the wrong registrar value on both engines under GC stress period 50. Two calls that pass the original definition block already succeed on the older-main control and now regress; the older main also has a separate pre-existing caller-block-dependent failure for the other two controls, which is not counted as newly introduced. Current-main source retains that older dispatch behavior. The new corpus does pass and covers direct literal and positional-Proc registration, but not a Proc forwarded as &body through an unrelated registration helper. Its lexical/caller block separation and explicit break-home metadata are useful improvements on the covered paths.
Independent Darwin arm64 validation: 2/2 focused executions match stdout, stderr and exit status from independent Ruby 4.0.10, in evaluator and VM modes. GC settings: stress=50, tight=unset. Programs: 1105_define_method_lexical_yield.rb. Static checks: dup_defs PASS; name_spec PASS; ns_names PASS; name_len PASS; rx_caps PASS. Diff whitespace checks pass.
Build reuse: verified all 2,429 tracked files against the exact head (zero differences), all three imported mgz modules against pin 661a01d8, ordinary O2 build mode and the successful build log using pinned compiler 9dec2ff6 (its checkout was verified clean). Reused binary SHA-256 4d8eede2b6b3a4fa6030808a7423cda2694e3641cccf347e521d9399049d2e47. This is not a fresh compilation or a tested current-main integration build.
I did not independently rerun the full corpus, complete upstream files, performance measurements or platform/resource acceptance. Those reported results and pending sweeps remain separate from these focused checks. Hosted build/downstream coverage remains incomplete. No merge: the PR is draft and recorded hold_all_merges / new_failure_review_required conditions remain active. COMMENT is used because the authenticated account owns this PR.
284km
left a comment
There was a problem hiding this comment.
Follow-up review of exact head 2e269c37d5a6c0b3472df0da5a7e2e47c312e29b, compared with the previous reviewed head and fetched current main a63e47c366505074dab80db9285b8a7b3b6d051b. I read the existing review, inline discussion, updated description, implementation, call sites and regression cases. Neither the fetched main nor this head contains tracked AGENTS.md/CLAUDE.md instructions.
The previous Major/P2 finding is fixed. Forwarded &body registration now derives lexical yield context from the supplied Proc's defining environment and yield markers on both define_method and define_singleton_method paths. Corpus 1105 covers the four reported calls through an unrelated registrar. I found no new actionable issue in this update.
Independent Darwin arm64 validation: all 17 output lines, stderr and exit status of corpus 1105 match clean Ruby 4.0.10 in evaluator and VM, normally and with GC stress period 50 (four matching executions). Three related regressions (124, 967 and 970) also match in both modes under stress50 (six matching executions). Duplicate-definition, dead-definition, GC-root and diff-whitespace checks pass. The GC-root check used the verified existing build's generated C. An initial invocation used an unsupported environment override and had no generated-C input; the correctly supplied C passed.
Build reuse is disclosed: all 2,429 tracked regular files match the exact head byte for byte, and all three imported mgz modules match pinned 661a01d8bb68f5acd68e3192bd47f081d179c436. Reused binary SHA-256 ac288e08455b6a26a5adbdfd48492c8472b581df455fb656ba1cab1a842077a0; its build marker says O2. I copied this binary into the isolated review checkout. This was not a fresh compilation or current-main integration build; I did not independently rerun full corpus, complete upstream files, performance or resource acceptance.
Actual hosted CI has executed failures, not merely runner queues: run 45539890616's unittest-harness fails the CI-timing dependency assertion because unittest-vm is absent from the report's needs; I independently reproduced the identical assertion on fetched main. Its build-linux job fails C API verification with capi/vendor/erb_escape.c is not the tree's file; subsequent corpus/platform checks were skipped. This review does not waive either failure or claim downstream coverage. Full final-head corpus acceptance is still pending in the description. No merge: the PR is draft and the recorded global merge holds remain active. COMMENT is used because the authenticated account owns this PR.
284km
left a comment
There was a problem hiding this comment.
Review of head 2e269c37d5a6c0b3472df0da5a7e2e47c312e29b. Reference: Ruby 4.0.10. "Main" below means clean main builds at d03cbb83 (after this PR's base) and, where noted, 2e402b94 (before it). "Evaluator" means MERE_RUBY_VM unset; "VM" means MERE_RUBY_VM=1.
Earlier finding
- [Major/P2] forwarded
&bodycaptured the registrar's block: resolved. The bot comment was posted at 02:30Z on76ff79da. The fix commit2e269c37came at 03:25Z. I re-ran the bot's program on the head binary.define_method(:run, &body),define_singleton_method(:run, &body)and the positionaldefine_method(:runp, body)through a helper all print:definition, with the original block and with another caller block, on both engines. Main prints:otheror raises ArgumentError. Corpus 1105 covers this.
New findings
-
[Minor]
super()in a define_method body lost the definition-site block. This is a regression from main. Ruby passes the body's lexical block (the block of the method the body was written in) as the implicit block ofsuper(...)without&. Main matched Ruby when the call had no block, becauserun_meth_resultswapped in the captured block. This PR removes that swap, so the implicit block ofsuperis now the caller's block or none:class Base; def save(*) = block_given? ? yield : :no_block; end def wrap(k) = k.define_method(:save) { |*a| super(*a) } k = Class.new(Base); wrap(k) { :definition_block } p k.new.save # ruby / main: :definition_block PR: :no_block p k.new.save(1) # ruby / main: :definition_block PR: :no_block k2 = Class.new(Base); k2.class_eval { define_method(:save) { super() } } p k2.new.save { :caller } # ruby: :no_block main and PR: :caller (old bug)
Same result on both engines. Corpus 967 already has this shape from activerecord (
define_method(:up) { yield(...); super() }). Itssupertarget ignores the block, so the corpus does not see it. A fix would use the lexical block (__dm_yield) as the implicit block ofsuperin a define_method frame. The capture scan would also have to count asuperwithout&. Please measure memory if the scan grows: #210 once doubled the max RSS of nested_attributes_test. -
[Suggestion] Memory per definition whose body yields. All runs use
MERE_RUBY_GC_TIGHT=1, 3 runs each, alternating. A loop defines 6,000 yield bodies inside methods called with a block, plus 6,000 non-yield bodies. Max RSS is 136.6 MB on the PR. On main it is 124.0 MB (d03cbb83) and 129.0 MB (2e402b94). That is about 1.2-2 KB more per captured body. If every body is non-yielding, the PR and main are equal (178.4 vs 177-179 MB). The extra cost is only on the paths this PR makes correct, so I do not block on it. One Rails file run with a fixed seed and tight GC (for example nested_attributes_test) would settle it. -
[Suggestion] Ordinary
yieldpays for the new lookup. A loop of 400,000 yields in a plaindef(no define_method at all) retires +1.6% instructions on the evaluator and +3.1% on the VM (medians: 7.011e9 vs 6.902e9, and 7.396e9 vs 7.173e9).lexical_yield_blockrunslv_has env "__dm_yield"on every yield. Calls to define_method methods got slightly cheaper (-0.9% evaluator, -0.3% VM), because the swap inrun_meth_resultis gone. A frame flag set only for define_method frames could skip the walk in ordinary methods. -
[Suggestion] Bugs that also exist on main. These are not regressions; a follow-up is fine.
block_given?in a forwarded body Proc isfalsewhen the body is registered throughsend(:define_method, &body),public_send(:define_singleton_method, &body)orinstance_exec(body) { |b| define_method(:x, &b) }. Ruby saystrue. Plaindefine_method(n, &b)givestrue. With this PR,yieldalready finds the block on those paths, soyieldandblock_given?now disagree.class_eval("define_method(:x) { yield }")inside a method called with a block: Ruby yields to that block. The PR raises LocalJumpError; main yielded to the caller's block.- VM only:
binding.eval("yield")in a define_method body defined under a block. Ruby and the PR evaluator return the definition block. The PR's VM raises LocalJumpError; main's VM returned the caller's block.
-
[Suggestion] The loop note still says the full corpus sweeps are "queued". The PR description has the results (884/884 in both modes). Please sync the record.
What I checked
Running, on the head binary (clean tree at the head, binary newer than every .mere file, SHA-256 matches the description) and on main, against Ruby 4.0.10, on both engines:
- define_method with a block body, a lambda,
method(:x).to_proc, an UnboundMethod, andinstance_method(...).bind/bind_call: all match. - yield,
block_given?,defined?(yield),Proc.newwithout a block,binding: match, except the VMbinding.evalcase above. - A body Proc forwarded with
&blkthrough three calls, with and without a caller block: match. Main was wrong. - Defining inside a method called with a block versus without one: match. Without one, the call raises LocalJumpError, as Ruby does.
- class_eval, instance_eval with
define_singleton_method,singleton_class,class << o, module_eval, Thread, Fiber,it,each_with_object, alias_method, a subclass, redefinition: match. - Lexical yield after the definer has returned: a normal value and
nextwork.breakraises "break from proc-closure" andreturnraises "unexpected return", as in Ruby. Main returned the break value. - Nested define_method, with and without forwarding the caller's
&c: match. - Corpus 1105, 124, 967 and 970 match on both engines.
instance_exec { define_method(:x) { ... } }on a class makes a private method, on main and on the PR. That is a separate bug.- Whole unchanged test files,
--seed=1, tight GC:ruby/test_method.rb(99 tests, 556 assertions, 1 failure, 1 skip) andruby/test_proc.rb(120 tests, 1149 assertions, 1 error, 1 skip). The counts are the same on PR and main, on both engines. Max RSS is within 3%. git merge-tree --write-tree origin/main origin/pr250is clean.
Reading only: the diff, dm_capture_body/dm_capture_blk, lexical_yield_block, yblk_env, and the GC handling of proc_home/lambda_ids/dm_captured. The new entries are dropped with their procs.
Not checked: the full corpus and gates (taken from the description), Rails component files, Linux.
CI at this head: build-macos passes. build-linux fails in the capi/vendor/erb_escape.c header check, a known main issue (fixed by #273). unittest-harness fails on the CI-timing unittest-vm dependency, which is also a main issue (fixed on main by #275). corpus is queued and unittest-reference is still running. The gem-suite workflows pass. "Small pure Ruby gem suites" is queued.
284km
left a comment
There was a problem hiding this comment.
Follow-up on new head 6f125ec, fetched after it changed during this review. The existing Minor finding about implicit super losing the definition-site block is fixed on evaluator and VM. I reproduced the original two-call failure on the previously reviewed 2e269c3 binary, then confirmed both calls match Ruby on this head. The implicit evaluator branch and the VM direct-super branch now select the lexical block; explicit &block, &nil and literal-block paths remain separate and are covered by expanded corpus 1105. The previous forwarded-Proc Major/P2 correction also remains covered. No new actionable issue found; existing nonblocking suggestions are not duplicated.
Independent Darwin arm64 checks: 20/20 executions match clean Ruby 4.0.10 in stdout, stderr and exit status: expanded corpus 1105 (28 lines), the original super reproducer and related corpus 124/967/970, on evaluator and VM with tight GC, both without additional stress and with stress period 50. Duplicate-definition and diff-whitespace checks pass. The capture scan was not expanded by this commit; source inspection confirms it already counts implicit super. The new memory/instruction tables and full 884/884 sweeps in the completed note are author-reported results; I did not independently repeat those measurements, full sweeps or complete upstream/Rails suites.
Build reuse: all tracked regular source files match the fetched head byte-for-byte; reused recorded ordinary O2 binary SHA-256 e689d5ee217bf7977bd938d2021e98e74152b70a786e4b0d06c82ae73dce2d2a with the existing compiler/mgz pins. This was not a fresh runtime build or prospective current-main integration validation. The old O2 binary was used only for the explicitly identified before-fix reproduction.
New-head hosted CI is still in progress, with macOS/reference jobs queued and downstream coverage incomplete. The prior-head corpus job's actual failure is the already reported C API erb_escape.c source-comparison error, not a new output mismatch; that failure is preserved and is not claimed fixed by this patch. No merge performed: recorded all-merges/new-failure holds remain active, and running jobs do not satisfy the queue-only exception. COMMENT is used because the authenticated account owns this PR.
284km
left a comment
There was a problem hiding this comment.
Re-reviewed 6f125ec. The Minor from the last review (an implicit-block super() / super(args) in a define_method body no longer passed the definition-site block) is resolved. No Critical / Major / Minor findings remain.
- The evaluator's
ESuperand the VM'svm_super_directnow uselexical_yield_blockwhen the body has__dm_yield, and the capture scan countssupertoo, so a body whose only use of the block issuper()still captures it. - Ran on the author's build at this head (clean tree, binary newer than every
.merefile), on the evaluator andMERE_RUBY_VM=1, against ruby 4.0.10: corpus 1105 is identical, and so is a probe of a Base whosesaveyields:super()andsuper(x)with a definition block (with and without a call-site block),super() { :explicit },super(&nil), a definition without a block, and zsuper (superwithout parentheses, ruby's RuntimeError about implicit argument passing). - The loop note has the local results our merge policy asks for: fresh corpus
--bothandMERE_RUBY_VM=1 --both884/884 with hash indexing ON and OFF, the source gates, record_hygiene, the bracket gate, the related upstream files with RSS, and a new bench whose max RSS (capture / super / plain / yield loop) is level with main. - The earlier Suggestions (the
lv_has "__dm_yield"cost on plain yields, the pre-existing send/instance_exec block_given? and class_eval string cases) stay follow-ups. git merge-treeagainst current main: clean. The only mere-pr-review-watch inline comment (02:30) predates the fix and was resolved at the last review.
Merging.
define_method and define_singleton_method preserve the body Proc's definition-site yield block, including forwarded Procs and implicit super. A caller block still reaches an explicit |&block| parameter; explicit &block, &nil and literal super blocks retain their specified behavior.
The human-review regression is fixed in both the evaluator implicit-super branch and the VM direct-super path. The existing capture scan already counts implicit super on both engines, so this correction does not retain additional body shapes. Corpus 1105 adds the regression and explicit-block controls; all 28 lines, plus related corpus 124, 967 and 970, match clean Ruby 4.0.10 on both engines with tight GC.
Branch base: main 5064429. Reference: clean Ruby 4.0.10 through tools/ref_ruby.sh; no gems installed into it. Final ordinary O2 binary uses Mere 9dec2ff6 and mgz 661a01d8.
Completed final validation
Review correction: implicit super uses the lexical block
The human review found a regression: super() and super(*args) without an
explicit block forwarded the method caller block after the frame swap was
removed. Clean Ruby passes the body Proc's lexical block. The exact expanded
1105 witness reproduces that difference on both R6 engines.
The evaluator's implicit-super branch and the VM's direct super path now
select the lexical block in a define_method frame. Explicit block-pass,
&nil and literal blocks retain their own paths. The existing body_yields
scan already counts implicit super: the evaluator uses yscan_defined and
the VM metadata explicitly includes super. The capture scan and its set of
retained bodies are unchanged by this correction.
Corpus 1105 adds implicit super with and without a caller/definition block,
rest arguments, caller &block parameters, explicit &block, &nil, literal
blocks, nested iterators and forwarded body Procs. All 28 lines match clean
Ruby on evaluator and VM with tight GC. Corpus 124, 967 and 970 also match
stdout, stderr and status on both engines.
The final ordinary O2 R7 binary SHA-256 is
e689d5ee217bf7977bd938d2021e98e74152b70a786e4b0d06c82ae73dce2d2a,
with unchanged compiler 9dec2ff6 and mgz 661a01d8 pins.
The generated-C bracket gate passes, 155 required / 1024 supplied.
Fresh R7 sh run_corpus.sh --both: 884/884 pass, hash indexing ON and OFF.
MERE_RUBY_VM=1 sh run_corpus.sh --both: 884/884 pass, indexing ON/OFF.
Both fresh complete commands pass all source gates and full record_hygiene.
No corpus program is excluded. Explicit hygiene for this completed loop
note passes before the single code/regression/benchmark/record push.
The nonblocking review suggestions remain recorded follow-ups: ordinary
yield's existing frame lookup cost; additional capture memory on yield
bodies; reflective block_given? and class_eval/String/binding.eval gaps.
This correction adds no capture scan and does not claim to fix those gaps.
R7 related upstream and memory comparisons
Unchanged upstream selections run one file at a time, --seed=1 and tight
GC, against clean reference, main a9e6898 and final R7. All five runs per
file pass, including the additional super/block selections:
bench/define_method_lexical_super.rb separately measures 6000 classes,
each with one captured-yield, implicit-super or plain body plus one plain
body; ordinary-yield and define_method-super loops run 400000 calls.
Three alternating ordinary O2 main-a9/R6/R7 runs per engine use tight GC
and --seed=1. All 90 outputs match Ruby. These are new deterministic
workloads, not a claim to reproduce the reviewer's exact benchmark totals.
Max RSS bytes across three runs:
Median instructions retired in the same runs, with identical checksumming:
Retained definition memory is unchanged from R6 within 0.3 MB in captured
and implicit-super cases; the capture scan has not grown. Ordinary-yield
instructions are +0.02% evaluator / -0.07% VM versus R6. Correct implicit
super now actually calls the definition block; the incorrect R6 path did
not call it. That loop is +11.6% / +12.7% versus the incorrect R6 path,
but -1.18% / -0.81% versus main a9. No ordinary-yield frame lookup
optimization or broad memory reduction is claimed by this correction.
The correction, expanded corpus, deterministic benchmark and completed record are included in one push after local acceptance. No full unit suite or Rails component suite was run, and no workflow was changed. Hosted CI/current-main integration remain separate from these local results; no merge is performed here.