Repository navigation
An object's instance variables in a shape and one slab (note 559, step 2b) - #322
Conversation
…p 2b)
An object's variables were entries of the ivars table, keyed "<id>@<name>",
with a name index beside them. They now sit in a shape transition tree and
one slab:
- A shape is a path of names from the root (shape 0). sh_next holds the
transitions, sh_slot memoizes (shape, name) -> slot, -1 too.
- obj_iv maps an object to its record: the slab base, the area's size class
and the shape. -1: the object is in the table ("too complex").
- The slab's areas are powers of two with a free list per size; slot 0 of a
free area links the next. A class's largest count so far sizes a new
area, as ruby's max_iv_count does.
- remove_instance_variable marks the slot removed; a later set of a visible
name moves it to the end, so the order is ruby's.
- Too complex: past MERE_RUBY_SHAPES_MAX shapes (2^18), 8 variations of a
class, 4,096 names in a shape, or 2^24 names. MERE_RUBY_SHAPES=0 puts
every object in the table; MERE_RUBY_SHAPES_CHECK=1 reports a write of an
object's variable to the table that went around the door.
The collector marks an object's area from the drain and gives a dead one's
area back at the sweep, then compacts obj_iv and the slab. Its pressure
counts the slots held as well as the table's entries, so a program that
makes and drops objects collects as often as before.
Some sixty places wrote "<id>@..." keys straight into the table (dup's copy,
Method's notes, Thread's masks, ArithmeticSequence, the Enumerator's ext);
all go through the door now. The Prism loader writes a node's values into
its type's shape at once.
Along the way: the duplicated comment in gc_collect is gone and the sweep's
comment says what it does. The loop record notes that since #299 a dead
object's @x@__f_fd no longer closes a File that is still open, and two bugs
main has: instance_variable_set("@A@b") is accepted, and a Thread's
fiber-locals and its thread variables share one listing.
Corpus 1064 (the order after a remove, against ruby 4.0.10) and 1065 (the
slab under collection, a second batch reuses the first's areas).
284km
left a comment
There was a problem hiding this comment.
Reviewed exact head 3fabca741f101899f6ff02293676c97191f123ba against fetched current main 0c89c8a3cb0d2d1c2169ad41a2fbcd3414ace745, including the complete diff, existing discussion/reviews (none), GC/class sweeping, copying, Prism loading, File cleanup and affected callers. Neither tree contains tracked AGENTS.md or CLAUDE.md instructions.
One Major/P2 finding: per-class capacity metadata survives collection of its anonymous owners (inline below). The shared shape/slab implementation and the added removal-order and collection corpus cases otherwise behaved correctly in the focused comparisons.
Validation actually run:
- Fresh, unmodified O2 builds of both trees using pinned Mere
9dec2ff6and mgz661a01d8on macOS arm64. - 24 corpus files, 56 comparisons per tree against Ruby 4.0.10: all matched exit status, stdout and stderr. Both evaluator and VM were exercised; both new files also passed with shapes disabled and with
MERE_RUBY_SHAPES_MAX=8. Shape-write checking reported no bypasses. - dead_defs, dup_defs, gc_roots, meth_writes, name_len, ns_names and record hygiene passed.
- Separate diagnostic O1 build of this head's emitted C, with a read-only exit counter: after 100 / 1,000 / 5,000 discarded anonymous classes and three explicit collections,
sh_cls_capretained 103 / 1,003 / 5,003 entries while the shape count stayed at 5 and ordinary object/class stores were collected. This diagnostic build is distinct from the unmodified O2 validation above.
Merge withheld: the P2 finding remains, hosted build-linux is still running, macOS/reference jobs remain queued, and downstream CI coverage is incomplete. The merge-policy record also retains an all-merges hold for the earlier main build-linux failure (capi/vendor/erb_escape.c tree-integrity check, run 45549386421); this review does not clear that hold or establish full platform/resource acceptance. COMMENT is used because the authenticated account is the PR author.
| else | ||
| (let cls = (if map_has obj_cls oid then map_get obj_cls oid else "Object") in | ||
| let h = (if map_has sh_cls_cap cls then map_get sh_cls_cap cls else 0) in | ||
| let _ = (if n1 > h then map_set sh_cls_cap cls n1 else ()) in |
There was a problem hiding this comment.
[Major/P2] Reclaim per-class capacity metadata when its class dies. Every fresh anonymous class (or object singleton class) that acquires an ivar inserts its name into sh_cls_cap, but neither this table nor sh_cls_var participates in gc_sweep_classes; there is no deletion/compaction path for them. The shape limit does not bound the capacity table: repeatedly running k = Class.new; k.new.instance_variable_set(:@x, 1) uses the same shape while adding a different class key each time. In a separate O1 diagnostic build of this exact head, 100 / 1,000 / 5,000 discarded classes followed by three GC.start calls left 103 / 1,003 / 5,003 capacity entries, with only 5 shapes and ordinary class/object stores reclaimed. Long-running code that creates transient classes/singletons therefore retains their names and map storage indefinitely. Please sweep these per-class tables using the existing class-owner liveness machinery, compact them when permitted, and add a repeated class-churn regression that checks metadata reaches a plateau.
There was a problem hiding this comment.
Fixed in 8101636: gc_sweep_classes drops a dead class's keys from sh_cls_var and sh_cls_cap (via gc_sweep_class_table, the same owner liveness as the class's other tables). run_corpus.sh now runs tools/shape_class_tables_check.rb first: 3,000 classes made and dropped (two shapes each, plus an object's singleton class per turn) must leave at most 300 keys. Without the sweep sh_cls_cap held 6,004; with it 34.
sh_cls_var and sh_cls_cap are kept by the class's name, and the shape bound does not bound them: a Class.new a turn whose object takes @x adds a key and no shape. gc_sweep_classes now drops a dead class's keys from both, as it does from the class's other tables, and compacts them when it may. run_corpus.sh runs tools/shape_class_tables_check.rb first, under MERE_RUBY_STORE_STATS=1 (which now prints both rows): 3,000 classes made and dropped, each with objects of two shapes, and an object's singleton class a turn, must leave at most 300 keys in each. Without the sweep sh_cls_cap held 6,004 keys; with it, 34.
284km
left a comment
There was a problem hiding this comment.
Review of the head 3fabca7 (note 559, step 2b). I ran built binaries and also read the diff.
Builds used
- This PR: a clean worktree at 3fabca7. The binary is newer than every
.merefile there. - main: a clean worktree at 751362a, which is this PR's base. The binary is newer than its
.merefiles. - Both builds emit the same runtime part of the C file (the first 6,000 lines of
mr.care equal). I read this as "the same Mere". I could not read the Mere revision from the binary itself. - The reference is ruby 4.0.10 (
tools/ref_ruby.sh).
Findings
Major: the embedding API still reads @__status from the table
tools/native_probe/embedding_api.mere (line 64, not in this diff) reads a SystemExit's status with the raw key:
| VObj id -> (match (if map_has ivars_g (str_of_int id ++ "@__status") then map_get ivars_g (str_of_int id ++ "@__status") else VNil) with VInt n -> n | _ -> 1)
exit 7 sets __status through iv_set (m_eval_leaf.mere). With this PR, that value is in the slab, not in the table. So this read finds nothing and gives 1.
embedding_host.c expects 7 in the pending-exit mode (exit 7) and in the exit-subclass mode. CI runs embedding_check.py in the "Check protected embedding lifecycle and archive" step. So I expect that step to fail, with exit code 23 or 27 from the host.
I found this by reading only. I did not build the embedding library, because I only run existing binaries. The CLI path is fine: exit 7 and raise SubExit.new(7) exit with 7 on both engines with this build.
Fix: iv_get_or ivars_g id "__status" VNil. This is the only raw read of an object key I found in any .mere file at this head. MERE_RUBY_SHAPES_CHECK=1 reports writes only, so it cannot catch a read like this one.
Merge criteria
- The #299 condition is met: dup and clone are below main. See the numbers below.
git merge-tree --write-tree origin/main origin/pr322is clean.git merge-tree --write-tree origin/pr321 origin/pr322is clean.- Neither main since 751362a nor #321 adds a raw
"<id>@..."access of the table. - CI was still queued when I wrote this. Only "Linux build dependency controls" and "NKF Wasm engine" had finished, and both passed. Please wait for the CI workflow because of the Major finding above.
What I ran
Every probe ran against ruby 4.0.10 in seven ways:
- this PR on the evaluator and on the VM;
MERE_RUBY_SHAPES=0;MERE_RUBY_SHAPES_MAX=8, on the evaluator and on the VM;MERE_RUBY_SHAPES_CHECK=1;- main.
1. Order and content of instance_variables: all the same as ruby, or the same as main
- A removed variable that is set again goes last. This held for one, two and three removals, and for removing and setting the same name twice.
- After
dupandclone, the removal marks are copied.instance_variable_defined?is false for a removed name, and the getter gives nil. Setting the name again on the copy moves it last, and the original does not change. - A
Marshal.load(Marshal.dump(x))round trip keeps the order, also after a remove and a set again. inspectshows the same order.instance_variable_defined?is right.remove_instance_variableof a missing name raises NameError with ruby's message.- On a frozen object, setting raises FrozenError with ruby's message.
clonestays frozen with the same variables.dupcan be written.clone(freeze: false)then remove and set again works. - I set dynamic names in a loop: 20 objects of one class, each with a different first name (more than 8 variations), and one object with 5,000 names. This goes past 4,096 names in one shape, so the object moves to the table. Order, values, remove and set again,
dup,cloneand Marshal all stay right across the switch. Other classes are not affected. - Objects of one class that set their variables in different orders, and
initializewith branches, list them as ruby does. - I checked a Struct subclass with variables (
dup,==, Marshal, remove and set again), an Exception subclass (raise,#exception(msg),dup) and a Comparable class (min,clamp, remove and set again). - Corpus 1064 and 1065 match on all seven ways.
2. GC safety
- I used one probe for this. It makes 3,000 objects of 2 and 5 variables (Strings, Arrays, Hashes and objects as values) and removes some variables. It keeps a few objects, drops the rest and runs
GC.start. Then it makes fresh objects of other classes and checks they have no variables. It does four such rounds, and at the end it checks every kept object's values. - The probe matches ruby on these runs:
- the evaluator and the VM;
MERE_RUBY_GC_STRESS=50on both engines;MERE_RUBY_GC_TIGHT=1on both engines;GC_STRESS=50withSHAPES_MAX=8.
- With
GC_STRESS=1, the full probe takes more than 300 s. A smaller copy (150 objects a round) matches ruby on both engines. - Corpus 1064 matches under
GC_STRESS=1,GC_STRESS=50andGC_TIGHT, on both engines. Corpus 1065 matches underGC_STRESS=50andGC_TIGHT, on both engines. UnderGC_STRESS=1it runs past 600 s. A smaller copy (1,000 objects a round instead of 20,000) matches underGC_STRESS=1on both engines. - I read the code for these points too:
- A dead object's area is cleared before it goes on the free list (
iv_area_free). So it holds no value after that. - A removed slot holds the mark, not the old value.
- Every
VObjmark goes throughgc_obj_pend, sogc_mark_areasees every live shaped object. - Liveness for a dead object uses the same
owner * 8test as the table's sweep.
- A dead object's area is cleared before it goes on the free list (
- The slab does not grow without bound. I kept 300,000 objects alive per batch, with
GC_TIGHT. The slab had 1,800,401 slots after 1 batch, 1,941,573 after 2 and 4 batches, and 1,976,993 after 8. There were 22 shapes.
3. Internal names and flush_files_at_exit
- I opened Files with a user variable that I removed and set again between writes.
instance_variablesshows only the user's name, as ruby does. A kept File that was never closed is flushed at exit on both engines, withSHAPES=0and underGC_STRESS=1. - I also checked a Thread (
[], thread variables, a user ivar),Time#localtimewith a user ivar,dupand remove, MatchData groups with a user ivar,Methodandunbind/bind, and ArithmeticSequence. The PR prints the same as main on all of them. - Not from this PR, and the same on main: a File that the program drops without closing loses its unflushed data. Ruby's finalizer flushes it.
- Not from this PR, and the same on main: user variables named
@__xare hidden frominstance_variables. With this PR,iv_name_hiddenalso treats them as internal, so they are set again in place. Their order cannot be seen today, so nothing changes. But if the listing ever stops hiding@__x, the order after a remove will be wrong.
4. Measurements
All numbers are instructions retired, the median of 3 runs taken in turn, with MERE_RUBY_GC_TIGHT=1. The two builds are listed above.
| program | evaluator | VM |
|---|---|---|
20,000 objects of 4 ivars, then 300 dup + clone |
-15.0% | -14.5% |
| the same with the 300 copies left out (setup only) | -14.6% | -14.2% |
| the 300 copies alone (the difference of the two rows) | -33% | -29% |
s += @x, 300,000 times |
-3.3% | -5.7% |
@x = i, 300,000 times |
-5.5% | -7.8% |
| control loop without ivars | +0.4% | -0.0% |
The ranges did not overlap, except for the control row.
Max RSS with GC_TIGHT, median of 3:
- dup/clone program: 109.6 → 88.0 MB on the evaluator, 114.7 → 88.5 MB on the VM.
- Make and drop, 4 batches of 300,000 objects of 2 and 5 ivars, each batch kept in an Array: 702.7 → 469.8 MB on the evaluator, 1,114.7 → 483.6 MB on the VM. One run of this PR on the evaluator peaked at 390 MB. Instructions: -42% and -43%.
Not checked
- The full corpus. I ran only 1064, 1065 and my own probes.
- The Rails boot and the eager_test fixture.
- The C extension paths beyond reading the
capi_gc_readchange. - The embedding library: I did not build it.
284km
left a comment
There was a problem hiding this comment.
Follow-up on unchanged head 3fabca741f101899f6ff02293676c97191f123ba, compared with freshly fetched current main 0c89c8a3cb0d2d1c2169ad41a2fbcd3414ace745. Read both existing reviews, the unresolved metadata thread, discussion and repository instructions (neither tree tracks AGENTS.md or CLAUDE.md).
One additional Major/P2 impact is documented inline: protected embedding diagnostics lose object-backed exception messages. This is a different field/observable contract from the already-reported SystemExit status read, so that existing finding is not repeated here. The prior per-class metadata finding also remains unfixed at this unchanged head.
Validation actually performed this follow-up:
- Compiled focused O2 probes with pinned Mere
9dec2ff6, using the actual ivar storage functions from each fetched tree and the unchangedvm_record_diagnosticfunction. Only unrelated value/class/string scaffolding was supplied. Current main reportsRuntimeError: original; this head reports onlyRuntimeError; disabling shapes restores the full message. These are component probes, not a new full embedding-library or corpus run. - Inspected the completed exact-head Linux job 139712147576. Both corpus steps passed, including 970/970 VM programs with zero fallbacks/failures. The protected embedding lifecycle step actually FAILED: host
lifecyclereturned 15 afterbetween_evals, which the checked-in host uses whenexception_statusafterexit 7is not 7. This independently confirms the existing status finding. The job stopped there; subsequent embedding modes and Module resource validation were not run.
Merge remains blocked by the unresolved findings and actual Linux CI failure. macOS/reference jobs and downstream coverage remain pending. The latest current-main CI run 45759725373 still returns zero jobs and is pending; it is not a passing baseline. The recorded all-merges hold is retained, and already-reviewed open candidates cannot bypass it. No full platform/resource acceptance is claimed. COMMENT is used because the authenticated account is the PR author.
| else | ||
| (let c = sh_child s nid oid in | ||
| if c < 0 then (let _ = iv_to_table tbl oid in iv_put tbl (iv_key oid name) v) | ||
| else iv_grow oid r0 c v)); |
There was a problem hiding this comment.
[Major/P2] Migrate the embedding diagnostic message reader too. Moving iv_set values into the slab also disconnects tools/native_probe/embedding_api.mere:vm_record_diagnostic: its VObj branch still reads "<id>@__exception_message" directly from ivars_g. Exception construction writes this field through iv_set, so ordinary object-backed exceptions now yield just RuntimeError instead of RuntimeError: original through the protected diagnostics API. A focused O2 probe using the actual storage and diagnostic functions reproduces the loss on this head; current main and this head with shapes disabled retain the message. This is additional to the already-reported __status read. Please use iv_get_or ivars_g id "__exception_message" VNil here as well, preserving the non-dispatching diagnostic path, and run the existing object-message, object-spoof-message and object-hook-message embedding modes; the hosted lifecycle failure currently stops the script before those modes.
There was a problem hiding this comment.
Fixed in 8bf41e6: both __exception_message and __status are read through iv_get_or. The embedding lifecycle / failure / stress / bundle checks pass locally, including object-message, object-spoof-message and object-hook-message. tools/iv_door_check.sh (run by run_corpus.sh, bac2017) now flags an object key built by hand outside the door, since SHAPES_CHECK only sees writes.
…he door vm_record_diagnostic and the exit status read "<id>@__exception_message" and "<id>@__status" straight from the table. With step 2b an object's variables are in its shape's slots, so both reads found nothing: an exit 7 answered 1 (pending-exit, exit-subclass) and a raised RuntimeError lost its message (object-message and the two beside it). Both go through iv_get_or now; the embedding lifecycle, failure, stress and bundle checks pass. tools/iv_door_check.sh looks for an object key built by hand anywhere but the door (str_of_int X ++ "@..."). MERE_RUBY_SHAPES_CHECK=1 catches a write around the door at run time; a read leaves no trace, so this reads the source. The sites it allows are listed in it, each with its reason.
284km
left a comment
There was a problem hiding this comment.
Re-review at bac20174 (commits 8101636, 8bf41e6, bac2017).
Resolved
- Major — embedding reads around the door. Both
__exception_messageand__statusnow go throughiv_get_or ivars_g id … VNil, keeping the non-dispatching path. This was the real cause of the redbuild-linuxon the previous head; the four CI embedding steps plus the object-message / spoof / hook modes pass locally per the PR body. - Major (bot) — per-class shape counts never reclaimed.
sh_cls_varandsh_cls_capare now swept with the other class tables ingc_sweep_classes, exposed in the store stats, andrun_corpus.shfails if 3,000 dropped classes leave more than 300 keys. Good to have that as a standing gate rather than a one-off probe. - Prevention.
tools/iv_door_check.shis a reasonable source check givenSHAPES_CHECKonly sees writes. I also grepped the head for"@__keys and parenthesisedstr_of_int (…) ++ "@forms that the pattern would not match: the only hit outsidem_stateispack_assoc_key(a String's key), which is correct while Strings are still in the table and which you have already scheduled for 2b′ with corpus 1066.
Suggestion (non-blocking): the check's pattern only matches str_of_int <ident> ++ "@; a key built through an intermediate variable or a parenthesised id would slip past it. Worth a comment in the script saying so, so nobody reads a green result as stronger than it is.
The test merge with current main (4920ac75, which now includes #321) is clean. With the corpus results (969/969 evaluator and VM, hash index on/off, no writes around the door) and dup+clone at −10.0% / −12.0% against main posted, I have no open Critical/Major/Minor items.
Note 559, step 2b. Steps 1 and 2a (#295, #299) put every read and write of an object's instance variable behind one door. This changes what is behind it: an object's variables move out of the
"<id>@<name>"table into a shape (a transition tree of names, shared by every object that sets them in the same order) and one slab of values with a free list per area size.The loop record (
loop/2026-11-26-rails-ar-ivar-shapes.md) has the design, the bounds, and the writers that went around the door.In short
obj_iv: one int per object (area base, size class, shape); -1 means "in the table" (too complex).MERE_RUBY_SHAPES_MAX(2^18) shapes, 8 variations of a class, 4,096 names, or 2^24 names.MERE_RUBY_SHAPES=0sends every object to the table (main's behaviour, for bisecting).remove_instance_variablemarks the slot; setting a visible name again moves it last, as ruby does (corpus 1064).MERE_RUBY_SHAPES_CHECK=1reports any that are left; under it the corpus reports none.@x@__f_fdno longer closes a live File, and lists two bugs main has:instance_variable_set("@a@b")is accepted, and fiber-locals and thread variables share one listing.Against main
Both sides were built with the Mere CI uses (9dec2ff6) on base f13ccfc. Instructions retired, median of 3 alternating runs,
MERE_RUBY_GC_TIGHT=1:s += @x@x = iGC.startover 100,000 objects of 4 ivarsdupandcloneamong 20,000 objects (#299's condition)Prism.parseof a 5,571-line filebin/rails runner)Rails boot peak RSS (GC_TIGHT, median of 3) doesn't change: 656 → 665 MB on the evaluator, 736 → 731 MB on the VM.
RSS of a live object: 1 ivar 514 → 238 B, 4 ivars 1,005 → 372 B, 10 ivars 1,378 → 632 B.
Objects made and dropped (300,000 a batch, GC_TIGHT):
The slab doesn't grow on the second and later batches.
eager_test's fixture (16,384 rows of
YAML.load): peak 1,099 → 997 MB, 94.3 → 73.6 s.Corpus
MERE_RUBY_SHAPES_CHECK=1: 969/969 on the evaluator and on the VM, and no writes around the door.MERE_RUBY_SHAPES_MAX=8andMERE_RUBY_SHAPES=0: 957/957 each.obj_iv. It's fixed here.MERE_RUBY_GC_STRESS=50: 5 failures on the evaluator, 6 on the VM. Each one fails on main the same way:Gates: dead_defs, dup_defs, gc_roots, meth_writes, name_len, ns_names, record hygiene.
Review fixes (8101636, 8bf41e6, bac2017)
tools/native_probe/embedding_api.mereread"<id>@__status"and"<id>@__exception_message"straight from the table. With shapes those reads find nothing, so anexit 7answered 1 and a raised RuntimeError lost its message. 8bf41e6 reads both throughiv_get_or.--failure-checks, stress, bundle) pass locally.tools/iv_door_check.sh, run byrun_corpus.sh, looks in the source for an object key built by hand outside the door.MERE_RUBY_SHAPES_CHECK=1only sees writes. The check flags the two old embedding lines and finds nothing now.ivars_gor a"@__name in the interpreter,tools/andcapi/, also listed in the loop record:"$exc": a key that isn't an object's.world's fourth member,fb_world, the class sweep, andmap_compactof the table.iv_has ivars_g id "__modbk": the door.iv_put_new ivars_g: a node in the table only."@__as_*","@__lz_*","@__fb_*","@__x_*": names passed toiv_get_at/iv_has_at/iv_del_at_name, which are the door.pack_assoc_key("str:<h>@__pk_assoc"): a String's ivar, still in the table in this step. Step 2b′ moves it behind the door.capi/'srb_ivar_get/rb_ivar_setwith@__io_*and@__capi_*: these reach the door through the C API's ivar call.sh_cls_varandsh_cls_capwere kept per class name and never dropped, so everyClass.newwhose object took an ivar left a key.gc_sweep_classesnow sweeps them with the class's other tables.run_corpus.shrunstools/shape_class_tables_check.rbfirst: 3,000 classes made and dropped must leave at most 300 keys.sh_cls_capheld 6,004 keys; with it, 34.closeisn't flushed, and a program's own@__xisn't listed byinstance_variables.Against main 751362a (this head)
Both sides built with Mere 9dec2ff6; instructions retired, median of 3,
MERE_RUBY_GC_TIGHT=1:dupandclones += @x@x = iGC.startover 100,000 objectsCorpus at this head: 969/969 on the evaluator and on the VM, with
MERE_RUBY_SHAPES_CHECK=1reporting no write around the door.Next: step 2b′, String/Array/Hash ivars on the same shapes and slab, follows as its own PR on top of this one.
🤖 Generated with Claude Code