Skip to content

Preserve definition-site yield in define_method bodies - #250

Merged
284km merged 3 commits into
mainfrom
codex-misc-defined-method-blocks
Nov 25, 2026
Merged

284km merged 3 commits into
mainfrom
codex-misc-defined-method-blocks

Conversation

@284km

@284km 284km commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

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

  • 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 commands pass errno registration, gc_roots, dup_defs, dead_defs, meth_writes, name_spec, rx_caps, ns_names, name_len, and full record_hygiene.
  • Generated-C bracket gate: pass, 155 required / 1024 supplied. The completed loop note passes explicit record hygiene.

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:

File Tests / assertions Main evaluator RSS R7 evaluator RSS Main VM RSS R7 VM RSS
ruby/test_super.rb 4 / 10 167002112 164020224 166887424 164954112
ruby/test_method.rb 15 / 45 171786240 167559168 187236352 187121664
ruby/test_defined.rb 1 / 2 167788544 164970496 167215104 165003264
ruby/test_proc.rb 4 / 11 172425216 173932544 205062144 203882496

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:

Case Engine Main a9 R6 R7
capture eval 178569216 173424640 173473792
capture vm 159596544 158728192 158793728
super eval 178651136 165904384 166182912
super vm 158728192 158711808 158842880
plain eval 133054464 132251648 132399104
plain vm 129400832 128450560 126550016
yield_loop eval 83820544 83247104 83394560
yield_loop vm 88915968 88211456 88342528
super_loop eval 94699520 98287616 94076928
super_loop vm 91455488 94453760 90570752

Median instructions retired in the same runs, with identical checksumming:

Case Engine Main a9 R6 R7
capture eval 3365181446 3405127246 3405360184
capture vm 3066575314 3098169510 3093981482
super eval 3381558795 3078449921 3080146723
super vm 3108982611 3144507471 3147380666
plain eval 2332354405 2335530442 2334415418
plain vm 2647343844 2651857099 2649902723
yield_loop eval 13960861624 14067432839 14070688940
yield_loop vm 16241841675 16475207114 16464083442
super_loop eval 32854821737 29091434496 32465608223
super_loop vm 35831661609 31536971532 35541258075

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.

@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.

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.

Comment thread main.mere Resolved

@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.

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
284km marked this pull request as ready for review November 25, 2026 05:21

@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 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 &body captured the registrar's block: resolved. The bot comment was posted at 02:30Z on 76ff79da. The fix commit 2e269c37 came 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 positional define_method(:runp, body) through a helper all print :definition, with the original block and with another caller block, on both engines. Main prints :other or 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 of super(...) without &. Main matched Ruby when the call had no block, because run_meth_result swapped in the captured block. This PR removes that swap, so the implicit block of super is 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() }). Its super target ignores the block, so the corpus does not see it. A fix would use the lexical block (__dm_yield) as the implicit block of super in a define_method frame. The capture scan would also have to count a super without &. 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 yield pays for the new lookup. A loop of 400,000 yields in a plain def (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_block runs lv_has env "__dm_yield" on every yield. Calls to define_method methods got slightly cheaper (-0.9% evaluator, -0.3% VM), because the swap in run_meth_result is 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 is false when the body is registered through send(:define_method, &body), public_send(:define_singleton_method, &body) or instance_exec(body) { |b| define_method(:x, &b) }. Ruby says true. Plain define_method(n, &b) gives true. With this PR, yield already finds the block on those paths, so yield and block_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, and instance_method(...).bind/bind_call: all match.
  • yield, block_given?, defined?(yield), Proc.new without a block, binding: match, except the VM binding.eval case above.
  • A body Proc forwarded with &blk through 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 next work. break raises "break from proc-closure" and return raises "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) and ruby/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/pr250 is 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.

Comment thread main.mere Resolved
@284km
284km marked this pull request as draft November 25, 2026 07:37
@284km
284km marked this pull request as ready for review November 25, 2026 08:18

@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.

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 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.

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 ESuper and the VM's vm_super_direct now use lexical_yield_block when the body has __dm_yield, and the capture scan counts super too, so a body whose only use of the block is super() still captures it.
  • Ran on the author's build at this head (clean tree, binary newer than every .mere file), on the evaluator and MERE_RUBY_VM=1, against ruby 4.0.10: corpus 1105 is identical, and so is a probe of a Base whose save yields: super() and super(x) with a definition block (with and without a call-site block), super() { :explicit }, super(&nil), a definition without a block, and zsuper (super without parentheses, ruby's RuntimeError about implicit argument passing).
  • The loop note has the local results our merge policy asks for: fresh corpus --both and MERE_RUBY_VM=1 --both 884/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-tree against current main: clean. The only mere-pr-review-watch inline comment (02:30) predates the fix and was resolved at the last review.

Merging.

@284km
284km merged commit d263080 into main Nov 25, 2026
10 of 19 checks passed
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