Skip to content

A class is another class where ruby makes one: remove_const, and super from a class's #dup - #262

Merged
284km merged 2 commits into
mainfrom
rails-ar-r14
Nov 25, 2026
Merged

284km merged 2 commits into
mainfrom
rails-ar-r14

Conversation

@284km

@284km 284km commented Nov 25, 2026

Copy link
Copy Markdown
Owner

The two causes of Rails-2 round 3 that make a class another class (45 of its 133 RED). Split out of r13 (#236, #240, #246) at review's request.

Read first: migration_test's 37 RED are gone, but the file will be WALL_LIMIT in a round of the whole suite. See "migration_test now passes, and no longer fits in a round's 600 seconds" below. The slowness is not from this change; it was hidden on main because the 12th test dropped the table.

The checks below ran on the branch based on main c0a5f15. It was rebased onto 8b1b952 (#257) before the push, with no conflict.

Two places where mere-ruby answered an existing class where ruby makes a new one. Together they are 45 of the 133 RED of Rails-2 round 3 (activerecord, sqlite3 adapter, main 30de57d with #225, ruby 4.0.10).

A class defined again under a removed name is a new class (37)

After Object.send(:remove_const, :Name), class Name makes a NEW class. The old one is still there for whoever holds it (its instances, a variable), and the new one has none of its methods, constants, mixins or superclass.

Rails' migrator loads a migration this way:

Object.send(:remove_const, name) rescue nil
load(File.expand_path(filename))
name.constantize.new(name, version)

activerecord's migration_test defines, in the test file itself,

class ValidPeopleHaveLastNames < ActiveRecord::Migration::Current
  def change
    drop_table :people
  end
end

to check that a name collision across directories is harmless. Here, class ValidPeopleHaveLastNames in the migration file reopened the old class, so its #change was still there and migrator.up dropped the people table.
The test that ran it failed, and so did the 36 tests after it in the file.

The tables key a class by its name, so a class could not simply be made again under the same key.
A removed name (cls_removed) now goes the way a Ruby::Box's new class already went: a new class under an internal name of its own, with the constant pointing at it and Name to show (name_anon), as Name = Class.new would do. The old class keeps its key and everything in it.
This is done in the three places a class statement defines a class: the top level, a nested class in a class body, and a nested class X < expr.

remove_const marks the name for any class or module it removes. It marked it only when the constant held the class keyed by that name, so a class defined again a second time (under an internal name) was not marked, and the next class Name reopened the first one.

Before, the top-level arm deleted the old class's constants and reopened it, keeping its methods. That deletion is gone: the new class has no constants because it is new.

Corpus 1057: methods, constants, mixins, class-level instance variables and singleton methods stay with the old class. The old instance keeps its class. The new class is reopened by its name. Another superclass is no mismatch. A superclass given by an expression works.
A module, and a class where a module was. A nested class written both ways. #inherited hears of the new class. Putting the old class back under the name reopens it. The migrator's remove-load-constantize loop, three times.

super from a class's own #dup answers a copy (8)

module ActiveRecord::Inheritance::ClassMethods
  def dup
    other = super
    other.set_base_class
    other
  end
end

super reached the class dispatch's dup / clone arm, which declines when the class's singleton has a method of that name. It did not read the mark that super sets to ask for the builtin (skip9, bi_skip), so the call fell through and answered the class itself:
NumericData.dup.equal?(NumericData) was true. numericality_validation_test builds throwaway models with NumericData.dup, so a validation added to the "copy" was added to NumericData and to every later copy. Eight tests failed on validations other tests had added.

The two arms (classes, and builtin modules) take skip9 as well as "no method of its own". work2026-44 found the same answer from Class.new { def self.dup = super } while reviewing #221.

Corpus 1058 covers Class.new { def self.dup = super }, a module the class extends with #dup and #clone that call super, the copy's methods, the copy's own additions not reaching the original, two copies being two classes, a named copy, a module, and a class with no #dup of its own.
It also covers what a copy carries:

  • A class's copy has its class methods, by #dup and by #clone alike. A class's singleton class is copied with it, and the copy's is another one.
  • An ordinary object's #dup leaves its singleton methods behind and #clone keeps them.
  • clone(freeze: true) and clone(freeze: false), and #dup of a frozen class, which is not frozen. clone(freeze: true) of a class that is not frozen gave an unfrozen copy on main too (with or without a #clone of its own); the copy is frozen now, after its initialize_clone.

The test files

Each file alone, in round 3's tree, starting from an empty debug.log:

file round 3 main this change ruby
numericality_validation_test 14 runs, 8 failures 14 runs, 8 failures 14 runs, 0 failures 14 runs, 0 failures
migration_test 67 runs, 37 errors (501 s) 67 runs, 37 errors (353 s) no error in the first 33 tests; stopped by hand at 4,786 s 67 runs, 0 errors (11 s)

migration_test now passes, and no longer fits in a round's 600 seconds

In a round of the whole suite, migration_test will be WALL_LIMIT. Its 37 RED are gone, but the file does not finish within the 600 s a file is given: the first 33 tests all passed, taking 15 s to 330 s each, and the run was stopped by hand at 4,786 s (max RSS 3,279 MB).
In round 3 the file had 30 MATCH and 37 RED. After this change its cases are not counted at all until the file gets faster.

Where the time goes. Not in the tests but in MigrationTest's teardown: 11 s to 20 s per test, against 0.15 s for ruby.
The teardown removes 14 columns that are not in people (remove_column ... rescue nil), and on sqlite every remove_column rebuilds the table through alter_table, about 72 SQL statements each.
A statement costs about 7 ms here and about 0.07 ms in ruby (select 1 alone is 8 ms), so the teardown is around 1,000 statements at 100 times ruby's cost. With the logger turned off, the same 12 remove_column calls repeated 8 times take 8.5 s then about 7 s each round.
With it on, they take 12.8 s rising to 23 s. So about half of the cost, and the rise, are in writing each statement to debug.log. (The machine's load average was 31 to 49 during these runs; the ratios hold, the absolute numbers are high.)

This was there on main too. On main the first 11 tests take 10 s rising to 25 s. Then the 12th test drops people (the reopened class's #change), and the remaining 55 fail at once, so the file ended within 600 s.
This change does not make anything slower: loading the migrations again (remove_const and load, 12 times) takes 1.3 s each time and the removed classes are collected.

The cost of a statement is the next thing to work on, separately: the sqlite3 extension's path through the C API (prepare, step, building the result rows) and the logger.

Checked.

  • Corpus 1057 and 1058 match ruby 4.0.10 with and without MERE_RUBY_VM=1. On main both differ, evaluator and VM alike.
  • run_corpus.sh --both: 879/879. MERE_RUBY_VM=1 run_corpus.sh --both: 879/879.
  • The source gates: dead_defs, dup_defs, gc_roots, meth_writes, name_len, ns_names, bracket_depth. tools/loop_rss_check.sh. mspec/record_hygiene.sh.

Left.

  • Corpus 1057 does not compare Base.subclasses: in ruby it lists the removed class too until a GC collects it, so the answer depends on the collector.
  • ObjectSpace.each_object(Class) does not find a removed class that is still held: with old = A; Object.send(:remove_const, :A); class A; end, ruby counts two classes named "A" and this counts one. Left out of corpus 1057.

🤖 Generated with Claude Code

…r from a class's #dup

After `remove_const`, `class Name` makes a new class: here it reopened
the old one, so Rails' migrator ran the test file's own
`ValidPeopleHaveLastNames#change` and dropped `people` (migration_test,
37 RED). A removed name now gets a new class under an internal name of
its own, in the three places a class statement defines one, and
remove_const marks the name for any class or module it removes.

`super` from a class's own #dup or #clone reached the dispatch arm that
declines when the class defines that name, and answered the class itself
(ActiveRecord's Inheritance#dup: numericality_validation_test, 8 RED).
The arm reads the mark super sets. `clone(freeze: true)` freezes the copy.

Corpus 1057 and 1058. migration_test now passes its tests and no longer
fits in 600 s: the loop file says where its time goes.

@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 3bad371. One Major (a regression against main); the rest reads well.

Major: a constant of a removed class shows through the re-created class.

class AutoloadTest; X = 1; end
Object.send(:remove_const, :AutoloadTest)
class AutoloadTest; X = 2; end
p AutoloadTest::X   # ruby 2, main 2, this head 1 (both modes)

The same happens without re-assigning: after remove_const and class Foo < String; end, Foo::X answers the old class's 1 where ruby raises NameError. The cause looks like the removal of the block in register_class_statement that deleted the Name::* constant keys when a removed name was defined again. The new class is now a fresh internal one, but Name::X lookups still find the old key. Either keep the old keys reachable only from the old class, or keep deleting/re-keying them when the name is re-created. Add both shapes to corpus 1057.

Checked and fine on the author's build of this branch (built before the rebase onto #257, with the same logic), against ruby 4.0.10, the evaluator and MERE_RUBY_VM=1:

  • remove_const then class Foo < String: a new class with a new superclass; the old instance keeps its old methods; the old class keeps its name and constant.
  • A second remove_const and re-creation.
  • A nested M::In re-created empty.
  • Class.new { def self.dup = super }: a distinct copy that keeps the singleton method and is anonymous.
  • clone(freeze: true) of a class freezes only the copy.
  • inherited fires for each re-creation.

main differed on 19 lines.

Pre-existing, not this PR: a NoMethodError on an instance of a String subclass says "for an instance of String"; ruby says the subclass name.

git merge-tree against current main: clean. No mere-pr-review-watch inline comments.

… constants

Constants are keyed by their full name (Name::X), the same key for the old
class and the new one, so the new class saw the old one's constants:
class A; X = 1; end, removed, class A; X = 2; end printed 1, and
class A < String; end still answered A::X. The three places that make the
new class now drop the old Name:: keys, as main did before reopening.

Corpus 1057 covers both shapes, at the top level and nested. The loop
record keeps the per-statement SQL cost table.
@284km

284km commented Nov 25, 2026

Copy link
Copy Markdown
Owner Author

Fixed in 9f59e95. The three places that make the new class now drop the old Name:: constant keys before defining it, as main did before reopening, so AutoloadTest::X is 2 and class AutoloadTest < String raises NameError for X (top level and nested). Corpus 1057 has both shapes and a nested one; it matches ruby 4.0.10 on the evaluator and with MERE_RUBY_VM=1. run_corpus.sh --both is 896/896 both ways, and the source gates, loop_rss_check and record_hygiene pass.

The cost of this: a removed class that is still held loses its constants (old::X raises NameError where ruby answers the old X), which is what main does too. That is under Left in the loop record, which also now carries the per-statement SQL cost table.

@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 9f59e95. The Major from the last review (a removed class's constants showing through the re-created class) is resolved. No Critical / Major / Minor findings remain.

  • cls_removed_forget drops the old class's Name::* constant keys when a removed name is defined again, at all three places a removed name is re-created (top level, nested, and class A::B). This is what main did before the re-creation became a fresh class.
  • 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, all identical:
    • AutoloadTest::X after remove_const and X = 2: 2.
    • Foo::X after remove_const and class Foo < String; end: NameError.
    • Nested M::In::Y after re-creating M::In empty: NameError; M::In2::Z reassigned inside the module: 3.
    • The re-created class is a new object; the old one keeps its name; a plain reopen keeps its constants.
  • The trade-off is written under Left: a reference to the old class held in a variable no longer sees its constants (old::X is a NameError; ruby returns the old X). main behaves the same, so this is not a regression.
  • cls_removed_forget scans the whole constant table, but only when a removed name is defined again, which is rare (reloading). Fine.
  • The loop note has the local results our merge policy asks for: corpus --both 896/896 and MERE_RUBY_VM=1 --both 896/896, the seven source gates, loop_rss_check and record_hygiene.
  • git merge-tree against current main: clean. No mere-pr-review-watch inline comments.

Merging.

@284km
284km merged commit 5276535 into main Nov 25, 2026
5 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