Skip to content

Respect private constant qualifiers in defined? - #249

Merged
284km merged 3 commits into
mainfrom
codex-misc-lexical-scope
Nov 25, 2026
Merged

284km merged 3 commits into
mainfrom
codex-misc-lexical-scope

Conversation

@284km

@284km 284km commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Respect private constant qualifiers in defined? while preserving Object-qualified pending autoloads and namespace aliases. The corrected O2 source passes the complete evaluator and VM corpus, 884/884 each with both hash-index settings.

Private constant qualifiers in defined?

B5. Branch base: main ab5a9bfd. Reference: clean Ruby 4.0.10, revision
a704b7cd95. Build: Mere 9dec2ff6, mgz 661a01d8, O2. No reference
gems were installed.

Corpus 1104 covers private qualifier chains, absolute paths, aliases, legal
lexical access to a bare private constant, inheritance and const_missing side
effects. Both engines match Ruby. The evaluator checks each real qualifier
without invoking const_missing; the VM uses the namespace value it already
resolved.

Initial upstream comparisons (before the autoload correction)

Unchanged Ruby 4.0.10 files run one at a time through unittest/try.sh.
Every invocation uses --seed=1 and MERE_RUBY_GC_TIGHT=1. Reference,
main and candidate pass the selections below on both engines. RSS is the
maximum resident set size in bytes from /usr/bin/time -l.

Selection Result Main evaluator Candidate evaluator Main VM Candidate VM
ruby/test_defined.rb 2 tests, 4 assertions, 0 failures, 0 errors, 0 skips 163102720 164331520 163168256 164282368
ruby/test_module.rb 10 tests, 54 assertions, 0 failures, 0 errors, 0 skips 176881664 176668672 204767232 206028800

Initial acceptance history

The first full sweep failed on existing corpus 361, as detailed below.
The initial focused selections did not reveal that regression. The failed
sweep is preserved as development evidence and is not counted as a pass.

Full-corpus autoload regression and correction

The first complete evaluator sweep exposed a regression in existing
corpus 361: defined?(Object::AutoA361), a pending top-level autoload,
answered nil. The new scoped-read path looked only for Object-qualified
registry keys, while Object's top-level autoloads use bare names.

The Object receiver now delegates its final defined? query to the existing
absolute top-level lookup, preserving privacy and pending-autoload behavior
without loading the final constant. Corpus 1104 additionally checks both
Object-qualified and absolute pending constants, no eager load, and loading
an intermediate qualifier when required. Existing 361 and 736 plus 1104
match the clean reference on both engines with tight GC.

The corrected O2 evaluator sweep passes 884/884 programs with the hash
index ON and OFF, including all source gates and full record_hygiene.
The subsequent VM sweep also passes 884/884 with both index settings.
The failed historical sweep is not counted as a pass. Selected unchanged
upstream cases were repeated with seed 1 and tight GC, all passing:

File Tests/assertions Main evaluator RSS Candidate evaluator RSS Main VM RSS Candidate VM RSS
ruby/test_defined.rb 2 / 4 162332672 165036032 162463744 166248448
ruby/test_module.rb 10 / 54 175570944 175685632 203112448 204242944

Completed acceptance on the corrected O2 source

sh run_corpus.sh --both and the subsequent
MERE_RUBY_VM=1 sh run_corpus.sh --both each pass 884/884 programs,
with the hash index ON and OFF. Both pass all source gates and full
record_hygiene. MR_C=mr.c sh tools/bracket_depth_check.sh passes on the
final emitted C; the loop record is also checked explicitly.

The mere-pr-review-watch Object-autoload finding is fixed in 9081c5f,
with an English inline reply and regression cases. No full unit suite or
Rails component suite was run, and no workflow is changed.

@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 ac3b55b863de7e98a4dfac7fbff1c26807022b70 against fetched current main d03cbb83 using a fresh isolated checkout. Existing reviews, discussion and inline threads were empty; neither head nor main contains tracked AGENTS.md/CLAUDE.md instructions. One Major/P2 regression is attached: qualified Object autoloads are no longer recognized by defined?.

The per-qualifier visibility check and preserving the VM namespace value address useful private-constant cases. However, the new EConst redirection bypasses the existing Object/top-level autoload normalization and exposes the narrower EScopedRead lookup.

Actual hosted evidence: Linux job 138902675958 in run 45523998469 built merge 6d39f3f (this exact head into main 323706a7). Its new corpus 1104 passes, but existing corpus 361 fails with hash indexing both ON and OFF: defined?(Object::AutoA361) changes from "constant" to nil. The completed sweep reports 892/893 matches. I read the actual job metadata and log; this is an executed regression, not runner queueing.

Independent clean Ruby 4.0.10 and an older-main control both recognize pending Object::, absolute and bare autoload names without loading their file. Fresh current-main/head source comparison confirms why the newly redirected lookup loses that Object case. A local candidate binary was rejected because it was older than a runtime input; no local exact-head runtime pass, fresh compilation, full upstream run or platform/resource acceptance is claimed. Hosted VM/macOS and downstream acceptance remains incomplete.

Independent static checks pass: duplicate definitions, name specifications/lengths, namespace names, regex-capture writes and diff whitespace.

No merge: draft status, the attached finding, the failing hosted corpus and recorded global merge holds prevent it. COMMENT is used because the authenticated account owns this PR.

Comment thread main.mere Resolved
@284km
284km marked this pull request as ready for review November 25, 2026 03:59

@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 9ea04614 (first human-side review; the earlier reviews are from the mere-pr-review-watch bot).

Earlier finding

  • Bot Major/P2, "Preserve the Object/top-level pending-autoload lookup" (main.mere:3598): resolved. Verified by running. The VClass "Object" arm in the EScopedRead branch of defined? now hands the last segment to the existing ::X path. That path reads the bare autoload key. Corpus 361 now matches Ruby on both engines (see below). defined?(Object::X) for a pending autoload is "constant" and the file does not run.

What I ran

Binaries:

  • Candidate: the author's build at this exact head (clean tree, O2, binary newer than every .mere file).
  • Base: a main build at ab5a9bfd, the PR's merge base. It does not contain the PR.
  • Reference: Ruby 4.0.10 (a704b7cd95).

Every case below ran on the evaluator (MERE_RUBY_VM unset) and on the VM (MERE_RUBY_VM=1).

  1. Corpus 361, 736, 1104, hash index ON and OFF: the candidate matches Ruby in all 12 runs. The base fails 1104 in all 4 runs, as expected. The base passes 361 and 736.
  2. Private-constant probes (about 45 cases). The candidate matches Ruby on both engines in every case. The base evaluator differs in 7 of them and the base VM in 3, so the PR fixes real gaps:
    • A::B and A::B::C with B private; ::A, ::A::B, Object::A::B;
    • self::X and A2::X inside the class body and inside a singleton method;
    • a private constant reached through an included module and through a superclass (Kid::Sec, Kid::PSec), inside and outside class Kid;
    • Foo::Bar inside class Foo (nil), while bare Bar there is "constant";
    • a private top-level constant: Object::X and ::X give nil, bare X gives "constant";
    • defined?(A::B.c), defined?(A::B = 1), an Integer or nil qualifier, a method qualifier that raises, a const_missing that raises, and a const_missing hook (not called);
    • private_constant after const_set, and an alias of the holder module.
  3. Autoload probes: pending constants under Object::, ::, a bare name, a nested module and a private autoload. Loaded constants too. A qualifier whose autoload file raises gives nil. The candidate matches Ruby on both engines, including which files ran and in what order. defined? on the last segment never loads its file. A pending qualifier is loaded, as Ruby does. The base differs on ::AlAbs::X (nil, and the file was not loaded).
  4. Built-in and lexical constants (Errno, Float, Process, IO, File::Constants, Encoding, Thread, Enumerator, JSON, URI, Net::HTTP, Struct bodies, a BasicObject subclass, a singleton class body, module_eval strings, nested lexical heads). The candidate prints exactly what the base prints. Two cases differ from Ruby on both builds: Thread::Backtrace::Location and Gem::Version/Gem::Requirement::DefaultRequirement. These are older gaps, not caused by this PR.
  5. Unchanged upstream tests (seed 1, MERE_RUBY_GC_TIGHT=1): the full ruby/test_defined.rb (39 tests, 171 assertions), ruby/test_module.rb -n /const|autoload|private/ (45 tests, 286 assertions) and the full ruby/test_autoload.rb (28 tests, 111 assertions, 1 skip). All pass on both engines. The counts match Ruby and the base.
  6. git merge-tree --write-tree against current main f371c46f is clean. Corpus number 1104 is free on main.

Scope of the change

The evaluator change only touches the EDefined arm. The VM change only touches vm_defined. Plain constant reads do not go through either. Timing agrees with that: 1.5M qualified reads in a loop took the same time on both builds (evaluator medians 3.02 s candidate and 3.11 s base, 5 runs each).

New findings

No Critical, Major or Minor findings.

  • Suggestion: qualified defined? is about 1.6x slower in the evaluator (inline comment). One million qualified defined? calls took a median of 2.81 s on the candidate and 1.69 s on the base (5 runs each, machine under load). A quieter earlier run gave 1.91 s and 1.14 s. The VM did not change clearly (2.16 s and 2.43 s). The cost is about 1 microsecond per call, so this does not block. It may matter for code that calls defined?(A::B::C) in a hot path.
  • Suggestion: the old qualified-name code in the EConst arm of defined? can no longer run (inline comment). The new guard sends every name with an inner :: to the scoped path. The large else if str_contains name "::" block and the Object:: half of the earlier condition now only see bare names or ::X. Removing them, or adding a comment that says they are kept on purpose, would make the code easier to follow. Also, the existing comment "Resolve A::B::C one segment at a time..." now sits above defined_const_chain and no longer describes the function under it.

Note (older bug, not caused by this PR)

A plain read of A::B::C with B private returns 1 on both engines, in the base and in the candidate. Ruby raises NameError: private constant A::B referenced. A::B::C ||= 8 has the same problem in the evaluator. After this PR, defined?(A::B::C) is nil but the read still succeeds, so they disagree. This is worth a follow-up issue. It is not a reason to hold this PR.

Author's local results

The PR body and the loop note have the results the merge policy asks for:

  • run_corpus.sh --both: 884/884, hash index ON and OFF, with all source gates and record_hygiene.
  • MERE_RUBY_VM=1 run_corpus.sh --both: 884/884, hash index ON and OFF.
  • The relevant upstream files ruby/test_defined.rb and ruby/test_module.rb: only a selection of tests, with seed 1 and tight-GC RSS, for main and the candidate on both engines. I ran the full test_defined.rb and test_autoload.rb above, and they pass.

The first, failing sweep is kept in the record and correctly not counted.

CI

The run for this head (45543675414) is still in progress. Two jobs failed. Neither failure comes from this PR:

  • build-linux stops at the C API header check: "capi/vendor/erb_escape.c is not the tree's file". Other open PRs (for example #268 and #272) fail with the same message. Because of this, the Linux corpus steps were skipped. So CI has no corpus result for this head yet.
  • unittest-harness fails tools/ci_timing_check.py: the timing report's needs list is missing unittest-vm. This PR does not touch any workflow.

The Linux gem suites pass. The macOS jobs are pending.

Not checked

  • I did not run the full corpus myself. I ran 361, 736 and 1104 only.
  • I did not run the full unit suite, the Rails suites or an RSS comparison.

Merge waits for the pending manual main CI run to start.

Comment thread main.mere
// defined?(recv::Const): the receiver may raise or be a non-class
// (e.g. `a::B` where a() returns nil) — then the const is undefined.
let rv = defined_eval_recv env world blk recv in
let rv = (if defined_const_chain recv

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 (performance): for a chain of n segments this runs defined? on the whole prefix, which recurses the same way, and then defined_eval_recv evaluates the prefix again. So the prefix reads grow roughly with n squared. In a loop of 1M qualified defined? calls the evaluator went from a median of 1.69 s on main ab5a9bfd to 2.81 s at this head (5 runs each). Plain reads did not change. One option is to keep the value from the inner check and reuse it, instead of evaluating the prefix again. Not blocking.

Comment thread main.mere
(if str_starts_with name "::" then substring name 2 (str_len name) else name) "::" ->
// Evaluate the qualifier through real scoped reads. A flat table hit
// bypasses private intermediate constants and namespace aliases.
eval_e env world blk (EDefined (defined_const_path name))

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 (readability): this guard now catches every name with an inner ::. So, in the EConst name arm below, the Object:: half of the top-level condition and the whole else if str_contains name "::" block (the lexical head, ancestor and autoload-qualifier handling) only ever see bare names or ::X, and cannot match. Please remove them, or add a comment that says they are kept on purpose. Otherwise a later fix may go into code that never runs.

Comment thread main.mere
// Resolve `A::B::C` one segment at a time, firing an autoload whenever the
// next segment is not there yet. VNil means "not found" (a constant whose
// value really is nil falls through to the caller's NameError).
and defined_const_chain = fn (expr: Expr) ->

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.

Nit: the comment just above ("Resolve A::B::C one segment at a time, firing an autoload...") describes const_walk, but it now sits above defined_const_chain. Moving the two new helpers above that comment, with a one-line comment of their own, would keep it next to const_walk.

@284km
284km merged commit 003a589 into main Nov 25, 2026
9 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