Repository navigation
A class defined inside a singleton class is an ordinary class - #288
Conversation
is_sng_cls was a prefix test, so a class keyed `(sng:X)::M` (defined by `singleton_class.class_eval`, ActiveSupport's Object#class_eval) counted as a singleton class: every def into it died in the frozen check, `new` refused it, `name` was nil and an instance's `.class` was Object. is_sng_cls is now true only for a whole singleton key. The sites that print or name a class keep a prefix test, written out, and print such a class through its singleton (`#<Class:Foo>::Out`). Every caller is listed with its reason in the loop record. Fixes has_many_associations_test's two lazily_evaluates_target_class tests (Rails-2, activerecord).
284km
left a comment
There was a problem hiding this comment.
Review of 6652b42 (first review of this PR).
Engines: "plain" is the tree-walking evaluator, "VM" is MERE_RUBY_VM=1. The reference is ruby 4.0.10. "main" below is a main build from d586947, which has neither this PR nor its problem fixed.
Summary
The change is right in direction. Reading the four groups and running probes, I found no site where the whole-key test gives a wrong answer for method lookup, ancestors, method_missing, define_method, alias_method, Comparable, visibility, super, prepend, hooks, freezing, new / allocate / dup, or constant lookup inside the singleton. One GC problem is new, though: a class inside an object's singleton class can now have methods and subclasses, and the collector still drops its tables when the object dies.
Findings
Major: a live class inside a dead object's singleton loses its methods, superclass and includes after GC
sng_key_id reads (sng:123)::N and (sng:123)::N#v as belonging to object 123. When object 123 is collected, gc_purge_sng / gc_purge_tbl drop every row whose key starts that way: the class's methods, its sup entry, its includes and its ancestor cache. A value that holds N itself keeps the object alive (the VClass arm of gc_mark_val marks the object). An instance of N also survived in my probe. But a subclass of N does not keep the object alive. So the subclass's inherited methods disappear, and its grandparent becomes Object.
class Base; def b; :b; end; end
module Mod; def mo; :mo; end; end
def mk
o = Object.new
o.singleton_class.class_eval "class N < Base; include Mod; def v; 1; end; end"
o.singleton_class::N
end
class Keep2 < mk; end
k2 = Keep2.new
300.times { Array.new(100) { "z" * 40 } }
GC.start; GC.start
p [(k2.v rescue $!.class), (k2.b rescue $!.class), (k2.mo rescue $!.class)]
p Keep2.superclass.superclassruby prints [1, :b, :mo] and Base. This branch prints [NoMethodError, NoMethodError, NoMethodError] and Object (plain, with and without MERE_RUBY_GC_TIGHT=1). The VM survived this small program by GC timing, but a loop of 200 Class.new(N) lost the methods in 194 of 200 on both engines. main cannot reach this: it refuses the subclass ("can't make subclass of singleton class") and the def.
Why it matters for this PR: making such a class "ordinary" means it can be subclassed and outlive the object whose singleton it was defined in. In the Rails test the defining object is the test instance, which dies after its test. Possible fixes: mark the object sng_key_id names when a class with a nested key (sng:<id>)::... is marked through a superclass or ancestor walk; or keep gc_purge_tbl to whole (sng:<id>) keys and (sng:<id>)#... keys only. A corpus program with a subclass, GC_TIGHT and a dropped object would pin it.
Minor: the display split at the first ):: breaks for a singleton whose key contains )::
A class defined in the singleton class of a nested class is keyed (sng:(sng:X)::M)::N2. cls_display, cls_display_nw and m_strutil's to_s cut at the FIRST )::, which is inside the singleton's own key.
o = Object.new
class << o; class M; end; end
m = o.singleton_class::M
class << m; class N2; def hi; :n2; end; end; end
n2 = m.singleton_class::N2
p n2.name
begin; n2.new.nope; rescue NoMethodError => e; p e.message; endruby: #<Class:0x..>::N2. This branch: #<Class:(sng:281474976710815>::M)::N2, in name, inspect and the NoMethodError message. main printed a different broken text for inspect (#<Class:#<Class:#<Object:0x..>>>::M)::N2). But on main name was nil and no instance could be made, so the message case is new. The fix is to find the ) that closes the first (sng: by depth, as gc_class_base does, then split there. Inline comments mark the three places.
Minor: an instance of a nested class prints its singleton with the raw key
o = Object.new
class << o; class M; end; end
p o.singleton_class::M.new.singleton_classruby: #<Class:#<#<Class:0x..>::M:0x..>>. This branch: #<Class:#<(sng:281474976710815)::M:0x..>>. In cls_display's object arm, display_cls returns (sng:X)::M, and only is_anon_cls names are sent through the printer. A str_starts_with ocn "(sng:" case there would fix it. main could not make the instance.
Suggestion: naming by a constant
M1 = o.singleton_class::M; M1.name is "M1" in ruby (a temporary name becomes permanent on the first constant assignment). Here it stays #<Class:#<Object:0x..>>::M. A class inside an anonymous class does take the constant's name here. main answered nil. This could join the Left list.
The Left items, compared with main
Foo::(sng:Foo)::Inner(andMo::(sng:Mo)::MIin a module): same on main.nameshows the raw key on both. The same shape also appears one level down:class << selfinside a class that is itself inside a singleton gives...::M::(sng:(sng:X)::M)::N.- The
#<Class:#<Object:0x..>>::Mdisplay: same on main. For a class singleton,#<Class:Foo>::Outis also what main prints; ruby prints#<Class:0x..>::Outthere too. Class#dupnot callingmethod_added: same on main (nil on both, ruby[:a]).
What I ran (binaries only, at 6652b42, clean tree, binary newer than every .mere file)
All on plain and VM, diffed against ruby 4.0.10, with main for comparison:
- Classes and modules inside
class << obj,class << selfin a class and in a module,class << Foofrom outside, a stringsingleton_class.class_eval, andinstance_eval/ blockclass_evaldefs. Checked methods, constants,name,inspect,to_s,ancestors,superclass,new/allocate/dup/clone,define_method,alias_method,attr_accessor,Comparable,singleton_class?,instance_methods,subclasses,method_missing/respond_to_missing?,instance_method(...).bind, cvars and ivars on the class,method_added,inherited,const_missing, protected / private,super,prepend,remove_method,undef_method, a frozen subclass, Marshal's error, raising a nestedStandardErrorsubclass. All match ruby except the display items above. - Singleton methods of objects, classes and modules,
class << selfmethods and attrs,singleton_methods: unchanged and correct. The singleton itself still refusesnew,allocate,dupandClass.new(sng), and a frozen object's singleton still refuses a def. - Nested singletons (
singleton_class.singleton_class,class << selfinsideclass << o, the singleton of a nested class): correct. - GC with
MERE_RUBY_GC_TIGHT=1: 3,000 objects each with a nested class (methods, a block, adefine_method), keeping 10% of the classes, 10% of instances only and 10% of the objects: all survivors work on both engines. Max RSS growth per dropped object is close to a plain singleton-method loop. The failure is the subclass case above. - corpus/1061: matches ruby on both engines; main dies at its first
def.
What I read
The four groups in the PR body and the loop note. Spot checks: lookup_meth, has_meth_b, ancestors_of_raw (a nested key now falls to its sup entry or Object, which is right), sng_supername, class_subclasses_native, hng_missing_hook, run_method_added, frz_const_check / frz_cls_check, meth_inspect_str, display_cls, obj_cls_name, and the GC owner functions (sng_key_id, gc_class_owner, gc_class_base, gc_owner_possible, gc_purge_sng).
Not checked
The full corpus, the gates and the Rails tests (the author's numbers are in the PR body). capi_describe_x from a C extension.
CI
At review time two workflows were green (NKF Wasm engine, Linux build dependency controls) and seven were queued, including CI.
git merge-tree with current main is clean.
| // a class defined INSIDE a singleton class, "(sng:N)::K": the singleton as | ||
| // ruby prints it, then the rest of the path (#<Class:#<Object:0x..>>::K) | ||
| if is_sng_cls c && (if str_eq (char_at c (str_len c - 1)) ")" then false else true) | ||
| if str_starts_with c "(sng:" && (if str_eq (char_at c (str_len c - 1)) ")" then false else true) |
There was a problem hiding this comment.
Minor: this cuts at the FIRST )::. For a class inside the singleton of a nested class, the key is (sng:(sng:X)::M)::N2, and the first ):: is inside the singleton's own key. The result is #<Class:(sng:281474976710815>::M)::N2 for name, inspect and error messages (ruby: #<Class:0x..>::N2). Finding the ) that closes the leading (sng: by depth, as gc_class_base does, would fix all three copies of this split.
| if is_sng_cls c then | ||
| // a class defined inside a singleton, "(sng:N)::K": the singleton, then | ||
| // the rest of the path, as cls_display shows it | ||
| if str_starts_with c "(sng:" && (if is_sng_whole c then false else true) && str_find_from c ")::" 0 > 0 then |
There was a problem hiding this comment.
Minor: the same first-):: split as in cls_display (see the comment there).
| // text and then the rest of its path -- cut as the singleton's own key it | ||
| // printed "#<Class:F)::K>") | ||
| if str_len c >= 6 && str_eq (substring c 0 5) "(sng:" | ||
| && (if str_eq (char_at c (str_len c - 1)) ")" then false else true) && str_find_from c ")::" 0 > 0 |
There was a problem hiding this comment.
Minor: the same first-):: split as in cls_display (see the comment there).
284km
left a comment
There was a problem hiding this comment.
Reviewed exact head 6652b4287f29e03a8254af000a60cd7ebff9a37a against fetched current main fd5f54b06168b798cef937eadffc0e3abeac3806 in a fresh temporary clone. Neither tree contains tracked AGENTS.md/CLAUDE.md instructions. I read the latest reviews, discussion and inline threads, including the concurrent review reporting GC lifetime and display problems. The two additional findings below concern the new Module#name path; the existing findings are not repeated inline.
The whole-key classification fixes the new corpus program and preserves the singleton/reflection controls checked here. Independent Darwin arm64 validation: 11 corpus programs / 22 evaluator-and-VM executions match Ruby 4.0.10 in stdout, stderr and exit status. These include corpus 1061, 175, 375, 200, 761, 969, 1106, 565 and 693 (some numbers have multiple programs). Main matches the other 20 executions and fails corpus 1061 in both engines. A further 20 head executions across five programs also match with MERE_RUBY_GC_STRESS=50 and hash indexing on/off. The separate name-dispatch/immutability probe reproduces both inline findings in both engines.
Head was freshly built with ordinary O2, pinned Mere 9dec2ff687a08433247dbdb7729bc19c8522e538 (clean compiler checkout) and mgz 661a01d8bb68f5acd68e3192bd47f081d179c436. Binary SHA-256: 48e79367ef0143e43b47ce45fd844be78272c9fb86f871c1bc85560b78f90585. For main, reused the previous ordinary O2 build, SHA-256 4b6653354044b69a007eeb09bbe2a80724b2c80bbfc26d01822ff386e405d2f3: compared all 2,592 current-main tracked blobs with that build checkout, finding only two documentation records and the headers_check.py mapping change, with runtime/build inputs identical; the mgz pin also matches. This is a head/main comparison, not a built prospective integration. git merge-tree reports a clean integration.
Static checks pass: dup_defs, gc_roots, name_len, ns_names, meth_writes and bracket_depth (155/1024). Diff whitespace checks pass. The first bracket-depth invocation lacked MR_C and stopped during setup; rerunning with MR_C=mr.c passed. No full corpus sweep, complete upstream files, Rails suite, Linux execution or platform/resource acceptance was independently repeated here; the author's broader results remain separate.
No merge. The existing Major GC finding remains open, and the recorded hold_all_merges / new_failure_review_required conditions remain active. Hosted #288 Linux build and some gem suites are executing, while macOS/reference coverage is queued; these are not solely unassigned runner queues. Latest main CI run 45617083533 exposes zero jobs at inspection, so it supplies no new coverage or clearance of recorded failures. Already-reviewed ready PR #254 was also reconsidered: its Linux build check remains FAILURE and other coverage is still running/queued. The other open mere-ruby PRs are drafts; merelang/mere has no open PRs. No CI result or resource bound is waived. COMMENT is used because the authenticated account owns this PR.
| // a class defined inside a singleton ("(sng:159)::M") is named by its | ||
| // place, as one inside an anonymous class is: "#<Class:#<T:0x..>>::M". | ||
| // It had no name, and ActiveRecord could not find its model's table. | ||
| (if str_starts_with c "(sng:" && (if is_sng_whole c then false else true) |
There was a problem hiding this comment.
[Major / P2] Share the namespace-aware name with the bound and super paths. This correction only runs in ordinary dispatch. Module.instance_method(:name).bind_call(k) and super from an override still call mod_name_val, whose singleton-prefix guard has now been narrowed, so they return the raw (sng:<id>)::M key. Repro: o = Object.new; class << o; class M; end; end; k = o.singleton_class::M. Module.instance_method(:name).bind_call(k) == k.name is false on both engines, versus true in Ruby 4.0.10. After def k.name; super; end, k.name.include?('(sng:') becomes true, versus false in Ruby. Current main returns nil through these paths; this change introduces the disagreement and exposes the internal key instead of the newly supported public name. Libraries that bind Module#name to bypass overrides, or decorate it with super, therefore still receive an unusable class name. Put the world-aware nested-class name calculation in a helper shared by ordinary dispatch, the bound native method and Module#name's super path, and cover all three routes.
| // place, as one inside an anonymous class is: "#<Class:#<T:0x..>>::M". | ||
| // It had no name, and ActiveRecord could not find its model's table. | ||
| (if str_starts_with c "(sng:" && (if is_sng_whole c then false else true) | ||
| then mkstr (cls_display world c) else mod_name_val c) |
There was a problem hiding this comment.
[Minor / P3] Preserve Module#name's frozen, stable return value. The new mkstr bypasses the freezing and caching in mod_name_val0, allocating a mutable string on every call. For the same nested-class setup, both k.name.frozen? and k.name.equal?(k.name) are false on evaluator and VM; Ruby 4.0.10 returns true for both. A caller can now mutate this name string where Ruby raises FrozenError, and repeated reflection loses the existing stable name identity. Cache and freeze the computed public name through the normal name storage, with a regression for frozen status and repeated-call identity.
… on every path (review of #288) - The collector read "(sng:123)::N" as object 123's, so the object's death dropped N's methods, superclass and includes while a subclass or a constant still held N. sng_own_id gives a nested key no owner, in gc_purge_tbl and gc_class_owner. - sng_nested_at finds the ")" that closes the singleton's key, so a class in the singleton of a nested class prints whole. - An instance's singleton class prints its class through cls_display. - mod_name_w answers Module#name for the ordinary call, bind_call and super, as the same frozen String. corpus/1062.
284km
left a comment
There was a problem hiding this comment.
Re-reviewed c097209. All three findings from our review and both mere-pr-review-watch inline findings (13:15, on 6652b42) are resolved. No Critical / Major / Minor findings remain.
Ran on the author's build at this head (clean tree, binary newer than every .mere file), with MERE_RUBY_GC_TIGHT=1, on the evaluator and MERE_RUBY_VM=1, against ruby 4.0.10, all identical:
- GC Major: a subclass of a class defined in a dropped object's singleton class (
Keep2 = Class.new(N), plus 200Class.new(N)), after 4 ×GC.start:[k2.v, k2.b, k2.mo]is[1, :b, :mo],Keep2.superclass.superclassisBase, and 200/200 survive.sng_own_idkeeps nested keys out of the object's purge and owner. - Bot P2:
Module.instance_method(:name).bind_call(k) == k.nameis true, anddef k.name = superno longer exposes(sng:. - Bot P3:
k.name.frozen?andk.name.equal?(k.name)are both true. - The instance-of-nested-class singleton no longer shows the internal key in
inspect.
Corpus 1061 and 1062 cover the GC shapes, the display, the three name routes, frozen and identity. The description reports corpus--both947/947 plain and VM and the 8 gates.M1 = o.singleton_class::Mnaming is under Left.git merge-treeagainst current main: clean.
Merging.
Two REDs of Rails-2 round 4 (activerecord, sqlite3), present since round 3: has_many_associations_test's
test_defining_has_many_association_with_{delete_all,nullify}_dependency_lazily_evaluates_target_class.Cause
The tests define a model with the test object's
class_eval, which ActiveSupport makessingleton_class.class_eval. So the class is defined inside a singleton class, and mere-ruby keys it(sng:159)::DeleteAllModel.is_sng_cls("is this a singleton class") was a prefix test and said yes for it. Everydefinto it then died in the frozen check (159)::read as an object id),newrefused it as a singleton,namewas nil and an instance's.classwas Object.On main,
class << o; class M; def hi; end; end; endalone fails.Change
is_sng_clsis true only for a whole singleton key(sng:X).str_starts_with c "(sng:":cls_display,cls_display_nw, the value printer's VClass arm, the explicitto_s/inspectarm,Module#name, m_strutil's world-freeto_s. A class inside a singleton prints through the singleton, split at)::(#<Class:Foo>::Out).obj_cls_nameandsng_base_cls(the.classof an instance) take the whole-key test too.Every caller of
is_sng_cls, and why the whole key is right there150 calls in 76 functions. A class inside a singleton is an ordinary class in ruby:
singleton_class?is false, it has instances, it is a subclass of its superclass, and its methods are its own. So "is c a singleton class" must be no for it at every site; only the printing sites above wanted the prefix, and they now say so.sng_inner,sng_supername,sng_base_cls,metaclass_class)(sng:159)::Mthese read159)::or the singleton's parent: the call is only defined for a whole key..classand#<Object:..>forinspect.new,allocate,dup/clone,Class.new(sng),instance_of?, binding, frozen def)newanddup(corpus 1061).a.singleton_class.superclasswas#<Class:Object>), andBase.subclasses/ M's ancestors left M out.main after this branch's base adds one more call, in
capi_describe_x's VClass arm (#284): CLASS_OF of a class is "Class" for a singleton class, else its metaclass(sng:c). With the whole key, a class inside a singleton gets its own metaclass, as any class does in CRuby (last group). The branch merges with main without a conflict.The per-function list is in
loop/2026-11-25-rails-ar-singleton-nested-class.md. The(sng:prefix tests written by hand elsewhere (m_state'smro_local_name, the GC owner keys, the nesting checks in eval_e) do not callis_sng_clsand are unchanged.Review changes (c097209)
(sng:123)::Nas object 123's, so the object's death dropped N's methods, superclass and includes while a subclass or constant still held N.sng_own_idgives a nested key no owner ingc_purge_tblandgc_class_owner, so N stays like a named class. A value holding N still keeps the object, for the singleton's constants N's methods can see.sng_nested_at(m_strutil) cuts at the)that closes the singleton's key, not the first)::, incls_display,cls_display_nwand m_strutil'sto_s. An instance's own singleton class prints its class throughcls_display.Module#name:mod_name_wanswers the ordinary call,Module.instance_method(:name).bind_callandsuperfrom adef self.name, and keeps the frozen String incls_name_str.Class.newsubclasses of N after 3 collections; the printed shapes; the threenamepaths, frozen and identical.Checked
def self., define_method, method_added, constants,new/allocate/dup,.class,is_a?,name,inspect,subclasses, ancestors, a stringclass_evalwithinherited, a frozen object's singleton, a class under a named class's singleton. Matches ruby on both engines; main dies at its firstdef../run_corpus.sh --both: 947/947, plain and withMERE_RUBY_VM=1, after the review's changes (the base is before corpus/1060).Left
class << selfwritten insideclass Foois keyedFoo::(sng:Foo)::Inner, soFoo.singleton_class.const_get(:Inner)is a NameError (as on main).#<Class:#<Object:0x..>>::Mwhere ruby prints#<Class:0x..>::M.dupdoes not callmethod_addedfor the methods it copies (any class).M1 = o.singleton_class::Mnames the classM1in ruby; here it keeps the name it had (main: nil).🤖 Generated with Claude Code