Skip to content

An object's variables: the rest of the way through the door (note 559, step 2a) - #299

Merged
284km merged 1 commit into
mainfrom
rails-ar-ivar-walks
Nov 25, 2026
Merged

284km merged 1 commit into
mainfrom
rails-ar-ivar-walks

Conversation

@284km

@284km 284km commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Step 2a of note 559 (aidocs): #295 put every reader and writer of one object's variable behind iv_get / iv_set and the rest. What still read an object's key "<id>@<name>" itself now asks the door too, so that step 2b (shapes, the values in one slab) changes what the door does and not who calls it. What is kept is unchanged: the keys are the same Strings.

What moved

  • Whose a key is, and where its name starts: iv_key_owner (was the collector's gc_owner_of), iv_key_name_at, iv_name_eq, iv_name, iv_del_at, in m_state beside iv_key.
    • The collector's marking (gc_fixpoint) and sweep (gc_collect) ask it. The sweep deletes a dead object's variables with iv_del_at and finds a File's descriptor by iv_name_eq .. "__f_fd".
    • flush_files_at_exit, ivar_names_walk and iv_copy (dup, clone) ask it too; iv_copy no longer goes through ivars_copy_pfx, which is left to a Proc's and a Binding's keys.
  • A key handed around: exc_cause_link_to answers the exception's id (-1 for none) instead of a key, and its caller uses iv_get / iv_set .. "__cause".
  • The thread-locals: fb_tl_base answered a Thread's or a Fiber's id as text, and Thread#[], #[]=, #key?, #keys, #fetch, thread_variable_* built <id>@__tl_<key> from it. It is fb_tl_owner now (the id as a number), and those 11 sites go through iv_*.

The other walks of the table are of other owners' keys (a String's, an Array's, a Hash's, a class's, a Proc's, a Binding's), which step 2b leaves where they are.

A callback per variable is too dear

The first version had the door walk the table and call back with owner, name and value (a curried closure of four arguments). On 30 collections of 100,000 objects with four variables, that was +33% instructions, and +43% without the name's substring: each call of a curried closure through a parameter makes its partial applications. So the walks call map_iter themselves and ask the door only about a key.

Measured

Instructions retired, median of 3 runs taken in turn, MERE_RUBY_GC_TIGHT=1. Both binaries built with CI's Mere (9dec2ff6); the base is main with #295 (7554912).

loop evaluator VM
30 GC.start over 100,000 objects of 4 variables -0.3% -0.2%
300 dup and clone among 20,000 objects +0.6% +0.6%
s += @x, 300,000 times -0.0% -0.2%
@x = i -0.1% +0.2%
s += a.x (attr_accessor) +0.1% +0.1%
control (no instance variable) +0.0% -0.3%

The copy still walks the whole table, as before; step 2b makes it the object's own variables.

Checked

The record is loop/2026-11-26-rails-ar-ivar-walks.md.

🤖 Generated with Claude Code

…, step 2a)

What still read an object's key "<id>@<name>" itself asks the door now
(iv_key_owner, iv_key_name_at, iv_name_eq, iv_name, iv_del_at): the
collector's marking and sweep, flush_files_at_exit, ivar_names_walk and
iv_copy. exc_cause_link_to answers the exception's id rather than a key,
and the thread-locals' base is an id (fb_tl_owner) whose variables go
through iv_*. What is kept is unchanged.

The walks call map_iter themselves: a curried callback of the door's,
called per variable, made a collection 33-43% dearer in instructions.

@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 step 2a (note 559). Head 5ac43f11. Reference: ruby 4.0.10.

Verdict: no Critical, Major or Minor finding in this diff. Two Suggestions and two pre-existing bugs (not caused by this PR) are below.

What I read

I read the old and new code side by side for every changed site.

  • Mark (gc_fixpoint). iv_key_owner is gc_owner_of moved to m_state, character for character. The owner of every key is the same. So the owner chains, and what is marked, are the same.
  • Sweep (gc_collect). The set of deleted keys is the same: owner >= 0 and owner not live. iv_del_at is map_delete of the same key, as gc_drop_s was. The iv_idx sweep still uses the same owner parse.
  • Key shapes. "@name" gives the same owner and name as before. Keys that do not start with a digit ("cls:..", "str:..", "arr:..", "hsh:..", "prc:..", "bnd:..", "$exc") give -1, as before, and still go to gc_owned_meta_add. Thread-locals are "@_tl..", the same Strings as before, because fb_tl_owner returns the same id as a number. A name that contains "@" ("12@a@b") gives owner 12 and name "a@b" in both versions, because iv_key_name_at uses the first "@".
  • iv_copy. Same prefix test and same iv_put writes as ivars_copy_pfx. The only change is the order of writes (walk order instead of a second Map), and the probes show the same instance_variables order after dup and clone.
  • Thread-locals. iv_has, iv_get, iv_set, iv_del build the same keys. iv_set goes through iv_put, as the old writes did, so the name index sees the same writes.
  • exc_cause_link_to. It returns the id instead of the key. The caller reads and writes the same "@__cause" key.

Two small changes in behaviour (both for the better)

"Behaviour" here means only what a Ruby program can see.

  1. The sweep now checks the exact name __f_fd. Before, it checked that the key ends with "@__f_fd". flush_files_at_exit changed the same way for __f_buf. These differ only for a name that contains "@". Ruby rejects such names, but mere-ruby accepts them today (see pre-existing bug A). I ran this probe:

    f = File.open(path, "w"); fd = f.fileno
    o = Object.new; o.instance_variable_set("@x@__f_fd", fd); o = nil
    GC.start; f.syswrite("hello\n")

    Main gives Errno::EBADF, because the sweep closed the descriptor of a live File. This PR gives :ok, the same as ruby. So the change fixes a corner case. It is worth one line in the PR text, because the PR says nothing changes.

  2. In ivar_names_walk (the fallback listing), a key "@" with an empty name used to be skipped and is now listed as "". I could not create such a key from Ruby: instance_variable_set("@") raises NameError. So this is reading only.

Probes (run, both engines, ruby 4.0.10)

I built head and its merge base (8c6699f) with CI's Mere (9dec2ff6). The emitted C of my head build is byte-identical to the author's build.

Each probe ran with MERE_RUBY_VM unset and =1, under plain, MERE_RUBY_GC_TIGHT=1, MERE_RUBY_GC_STRESS=50 and MERE_RUBY_GC_STRESS=1. For STRESS=1 I used smaller copies of the same programs. That is 48 runs per build. All exited 0, and head output = base output in all 48.

  • Objects with 4 ivars, most dropped across rounds of GC.start. Survivors keep their values. Also covered: classes with ivars, Strings, Arrays and Hashes with ivars, a Struct with an extra ivar, dup/clone/frozen clone of survivors, and instance_variables order after remove and re-add. All the same as ruby.
  • A cause chain 4 deep (raise in rescue, 3 levels), checked after GC. Also: raise a, cause: b (circular causes), cause: nil, and #exception(msg) keeping ivars. All the same as ruby.
  • The at_exit path that uses exc_cause_link_to: an at_exit that raises "outer" with cause "inner" after another at_exit raised "previous". The report is the same as ruby, plain and with STRESS=1.
  • Thread#[], []=, key?, keys, fetch, thread_variable_* in 4 threads plus a Fiber, with GC in each thread. Head = base. Both differ from ruby in one pre-existing way (bug B).
  • Files: 30 Files written without close, 29 dropped, then GC, a write to the kept one, an unflushed print, and exit. All file contents are the same as ruby, plain and with STRESS=1, on both engines.
  • One object with 400 ivars. This passes the 4 KB index limit, so instance_variables uses ivar_names_walk. I ran it with MERE_RUBY_IVAR_INDEX_CHECK=1: no mismatch, and the same as ruby after remove/re-add and dup.

Instructions retired (run)

Median of 3, alternating base and head, MERE_RUBY_GC_TIGHT=1, both built with Mere 9dec2ff6.

loop evaluator VM
300 dup + clone among 20,000 objects of 4 ivars +0.68% +0.77%
20 GC.start over 100,000 objects of 4 ivars +0.08% +0.25%
control (same dup/clone loop on Arrays, no ivars) +0.09% +0.15%

The dup/clone cost is close to your +0.6%. My GC loop shows +0.1/+0.25%, while you measured -0.3/-0.2%. Both are within about 0.3% and look like noise to me. The ranges overlap for the evaluator, and nearly overlap for the VM.

Suggestions

  • main.mere, about line 2412: the comment line "(...and a dead owner's names in ivar_names_of's index, iv_idx)" is now there twice (inline).
  • The sweep comment says deleting dead keys "allocates nothing". The sweep now pushes three Vecs for each dead key instead of one. This is not a problem, but the comment may need a word.

Pre-existing bugs (the same on main, not caused by this PR)

  • A. instance_variable_set("@a@b", 1) is accepted and listed as :"@a@b". Ruby raises NameError. This is what makes the __f_fd corner above reachable.
  • B. Fiber-locals and thread variables share one list. Thread.new { Thread.current[:x] = 1; Thread.current.thread_variable_set(:z, 2); [Thread.current.keys, Thread.current.thread_variables] }.value gives [[:x, :z], [:x, :z]] in mere-ruby and [[:x], [:z]] in ruby. The same happens on the main thread. Also, thread_variable_set(:tv, nil) removes :tv from thread_variables, but ruby keeps it. Both values of fb_tl_owner are the thread's id when the root fiber runs, so the two kinds share "__tlk". 2b might be a good place to fix this.

Scope

  • Note 559 §8 put the name index (iv_idx) and the Prism loader (iv_put_new / iv_file_new) in 2a. This PR leaves them for 2b and says so in the loop record. That is fine with me. I checked the other whole-table walks in main.mere: they are all over String, Array, Hash, class, Proc or Binding keys, as the PR says.

Not checked

The full corpus, the gates, RSS, and Linux. I ran only small probes.

Merge state

git merge-tree --write-tree origin/main with this head: clean, no conflicts. CI at this head: 2 jobs passed, 1 running (Rake suite), 5 queued (CI, Gem suites, and others).

Comment thread main.mere
let _ = drop_iv 0 in
let _ = (if nc then () else map_compact ivars) in
// (...and a dead owner's names in ivar_names_of's index, iv_idx)
// (...and a dead owner's names in ivar_names_of's index, iv_idx)

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: this comment line is the same as the line above it. One of the two can go.

@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 exact head 5ac43f11e855d04410ecc5c4703e936b2281eddb. No additional actionable code finding established. The existing same-head review covers the semantic probes and suggestions; this update records newly completed CI evidence rather than repeating those comments.

The Additional upstream gem tests / ubuntu-24.04 job has actually failed, before the original gem files ran. Its O2 build succeeded, using that workflow's pinned compiler 408b03d9. The failing step is Check anonymous Method-copy warning-state lifetime. I downloaded the method-copy-memory-Linux artifact and verified that its check SHA-256 matches the unchanged checker in this head:

  • Reference: all 21 RSS samples and completion marker present; peak post-GC/initial ratio 1.080593, healthy.
  • Mere: all 21 samples and completion marker present, exit 0 with no outer limit event; initial RSS 86,848 KiB, maximum collected sample 184,876 KiB, ratio 2.128731, exceeding the unchanged 2.0 bound. The checker therefore fails correctly. Original 600-second and 2-GiB family limits remain unchanged.

This is observed hosted execution, not a local sandbox restriction or solely runner queueing. It does not by itself establish that this PR caused the growth. The corresponding current-main workflow is pending with zero exposed jobs, so there is no completed same-main comparison here. Before merging, compare this unchanged check on current main and the prospective integration on the affected platform; retain this failure and the original bounds. No allocator/GC cause or repair is established.

Independent source checks in a fresh temporary clone: dead definitions, duplicate definitions, method writes, name lengths and namespace names pass; diff whitespace passes. I read the changed functions, helpers and callers against fetched main 1a3380b0e5738ee3ed4436c1eb94843e94ac9676. Neither fetched main nor head contains tracked AGENTS.md/CLAUDE.md instructions. The prospective merge is conflict-free (tree 4700b722b6f76842c91a914d182ab90fc3e9b01f), but it was not built or executed here. I did not independently repeat runtime probes, the full corpus, whole upstream files or performance/resource measurements.

No merge: the actual failed check, executing Linux build and incomplete downstream/macOS coverage do not qualify for the queue-only exception. Main CI run 45663174315 was inspected and exposes zero jobs while pending; it clears no recorded failure. The recorded hold_all_merges and new_failure_review_required conditions remain active. Already-reviewed ready PRs #254, #272 and #290 also retain failed checks; #290 has an unresolved Major/P2 code finding, and #272 retains its review blockers. The remaining open PRs are drafts; merelang/mere has no open PRs. COMMENT 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.

Owner decision on the one number above main: dup+clone is +0.68% (evaluator) / +0.77% (VM) because iv_copy still walks the whole table. This is accepted as temporary for step 2a. Step 2b (shape + slab, note 559 §8) must show dup+clone at or below main. Everything else meets the merge criteria (no Critical/Major/Minor; corpus 955/955 plain and VM; gates; merge-tree clean; no bot inline comments). Merging.

@284km
284km merged commit f13ccfc into main Nov 25, 2026
26 of 29 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