Skip to content

Squeeze the instance variables' slab after a collection - #392

Draft
284km wants to merge 10 commits into
mainfrom
rails-ar-slab-compact
Draft

284km wants to merge 10 commits into
mainfrom
rails-ar-slab-compact

Conversation

@284km

@284km 284km commented Nov 27, 2026 •

Copy link
Copy Markdown
Owner

Current status: draft, resource acceptance still on hold. The completed alternating Linux comparison used Docker Debian arm64, Ruby 4.0.10 and Clang 19. Both builds hit the unchanged 2 GiB run.py family-RSS limit at the same fixture-loading point; the squeeze delayed the limit but did not bring eager_test below it. These are not Ubuntu CI-image acceptance results. The adverse observations remain below/in the linked record.

The VM stress run was stopped manually after 587 passing files, at file 523; files 524 onward are unverified, not currently running. The existing hold remains until the other eager_test peaks are reduced and the remaining stress coverage is completed.

The scratch-Vec ownership finding is fixed by a527ed5 and remains fixed in current head 41e38fd. Resolving that code thread does not clear the resource hold. This status update adds no new resource measurement or acceptance claim.

What this does

After a collection's mark and sweep, iv_slab_squeeze (m_state.mere) compacts the instance variables' slab when it holds more than 2 * live + 65536 slots. It runs only when the collection is not nc, meaning it doesn't interrupt the stack it serves.

  • How it compacts: every live area is copied to a scratch Vec, the slab is recycled, and the areas are pushed back. Each record's base is rewritten with the same size class and shape (iv_mk_rec nb cap shape). The free lists are reset.
  • Knobs:
    • MERE_RUBY_SLAB_SQUEEZE=1 squeezes at every collection that leaves a free slot. It is a check mode for the corpus, not a setting.
    • MERE_RUBY_SLAB_SQUEEZE_MAX=n makes at most n squeezes. It is a diagnostic, not a setting: I used it to see what a run that misses its later squeezes looks like.
  • Reporting: MERE_RUBY_GC_LOG prints each squeeze and the time of its collection, and MERE_RUBY_STORE_STATS gains a row iv_slab_squeezes.
  • Corpus: 1075.

Merge only after the Linux comparison is added to this PR (see "Before merging").

Why it is safe

  1. Size class and shape are kept. An area's capacity 2^class is re-encoded through iv_cap_class, so after a move iv_grow's n1 <= cap0 and the VM's sh_len s1 <= iv_rec_cap r still see the area that is there.
  2. No collection can happen between reading a base and writing through it.
    • The entry points in m_state take no callbacks and run before the evaluator.
    • iv_copy and ivar_names_of read the base and then call only m_state.
    • gc_mark_area runs inside the collection, before the squeeze.
    • The VM's reads and writes read the base at the point of use, and a write that misses re-reads iv_rec after assign_one.
  3. Stacks the collection interrupted, and suspended fibers' stacks, are safe. A value read out of the slab and held on one of those stacks pins its block through vec_recycle, which retires the arena instead of freeing it.

Corpus

mode result
plain 0 FAIL
MERE_RUBY_VM=1 1 FAIL: 503_tcp_connect_deadlines, timing; passes in sq-vm
SLAB_SQUEEZE=1 with SHAPES_CHECK 1014/1014
SLAB_SQUEEZE=1 VM=1 with SHAPES_CHECK 1014/1014
SLAB_SQUEEZE=1 GC_STRESS=50 1012/1014
SLAB_SQUEEZE=1 GC_STRESS=50 VM=1 stopped / incomplete, through file 523; see current status above
Fiber / Thread / Enumerator / Ractor files (128), squeeze plus stress, evaluator and VM 0 new differences
  • The two stress failures are not caused by the squeeze. 676_tail_calls does not finish under GC_STRESS=50 even without the squeeze (300 s). 526_objectspace_internal_class differs under GC_STRESS=50 on main too.
  • The VM stress run so far: an earlier run without keep-going passed every file up to 526 and stopped there.

eager_test under run.py (macOS)

The runs used run.py run --jobs 1 --side mere on activerecord/test/cases/associations/eager_test.rb, with a family RSS limit of 2 GiB and a 600 s wall limit. The two builds were run alternately: main + #374 with and without this change. Compressor pages are from vm_stat before and after each run (16 KiB pages).

build state cases time peak family RSS compressor pages
with the squeeze COMPLETE 198/199 435 s 1.29 GiB 867,500 -> 913,523
without COMPLETE 198/199 405 s 1.44 GiB 913,501 -> 829,104
with the squeeze COMPLETE 198/199 398 s 1.11 GiB 829,070 -> 977,191
without COMPLETE 198/199 386 s 1.71 GiB 977,119 -> 881,381
  • Neither build hits MEMORY_LIMIT on this machine. The one case that fails on both is test_exceptions_have_suggestions_for_fix. These runs had no --framework-bootstrap, so did_you_mean was not loaded.
  • The squeeze lowers peak RSS in both pairs: 1.20 GiB against 1.58 GiB on average, with about the same time. macOS RSS falls when the compressor takes pages, and the compressor held 13-15 GiB during these runs. The size of the gain is therefore not settled by these numbers. Linux, where CI applies the limit, has no compressor.

Fixture probe

The probe loads the 65,536-row citations fixture and then runs Citation.preload(:reference_of). All runs used MERE_RUBY_GC_TIGHT=1; figures are taken after preload, and peak is the process's peak memory footprint (/usr/bin/time -l).

The squeeze build (the same binary every time), 7 runs:

when squeezes preload footprint peak note
11-27 afternoon 1 465 s 2,785 MB 3.10 GB bad
11-27 afternoon 1 334 s 2,297 MB 2.67 GB bad
11-27 evening, GC_LOG 3 95 s 1,307 MB 1.51 GB
11-28 night 2 183 s 1,896 MB 2.20 GB middling
11-28 night 1 101 s 1,265 MB 1.60 GB
11-28 night, vmmap 2 126 s 1,387 MB 1.64 GB
11-28 night, vmmap 2 85 s 1,227 MB 1.53 GB

Diagnostic binaries, 5 runs. These are the same generated C plus lines that record retires and frees of arenas over 50 MB.

run squeezes preload footprint peak
GC_LOG 2 133 s 1,248 MB 1.63 GB
GC_LOG 2 87 s 1,303 MB 1.68 GB
buffered to exit 2 77 s 1,230 MB 1.55 GB
buffered to exit 2 89 s 1,262 MB 1.54 GB
buffered, SLAB_SQUEEZE_MAX=1 1 80 s 1,270 MB 1.52 GB

Without the squeeze, 4 runs:

when preload footprint peak
11-27 afternoon 94 s 1,427 MB 1.69 GB
11-27 afternoon 88 s 1,251 MB 1.57 GB
11-28 night, vmmap 89 s 1,231 MB 1.47 GB
11-28 night, vmmap 80 s 1,255 MB 1.85 GB

Open: bad runs under load

Three of the squeeze build's runs were heavy:

  • The two on the afternoon of 11-27, while the machine was loaded and the disk was down to about 10 GB free.
  • One on the night of 11-28, with 47 GB free.

The cause is not found. These were ruled out:

  • A retired arena that stays. In every diagnostic run, the first squeeze retires the slab's arena (339-353 MB, pinned by 4 stacks), and it is freed 11-17 s later. No arena over 50 MB is still retired at exit.
  • The number of squeezes. The bad runs made one squeeze and the good runs two or three, but a run held to one squeeze (SLAB_SQUEEZE_MAX=1) ends with the same slab size as the bad runs (4.85M slots against 4.74M) and is good.
  • Where the extra memory is. In vmmap after preload, most of the footprint is VM_ALLOCATE, the arenas: 508-758 MB resident and 366-564 MB compressed, on both builds. The MALLOC_* rows together stay near 120 MB.

The fixture probe in this sample does not show a clear gain from the squeeze: footprint after preload is 1,227-1,387 MB with it against 1,231-1,255 MB without. On macOS, freed pages may simply stay with the compressor.

Before merging

  • Linux resource acceptance: the completed Debian-arm64 comparison still hits 2 GiB on both builds; a passing comparison on the CI Ubuntu image remains absent. See the linked current-status record above.
  • Finish the VM stress corpus: files 524 onward remain unverified.

The working record is loop/2026-11-27-rails-ar-slab-squeeze.md.

🤖 Generated with Claude Code

An area given back went to its size's free list, and iv_slab never shrank:
it kept what it held at its highest. A YAML load of activerecord's citations
fixture left 7M slots, 356 MB, for 133k live objects.

iv_slab_squeeze, called by gc_collect after its mark and sweep -- where it
compacts the slab's arena, not under "nc" -- moves the live areas to the
slab's start when the slab is more than twice its live areas and 64K slots
besides, rewrites each record with its new base (same size class, same
shape), winds the slab back (vec_recycle) and empties the free lists.

Safe there as vec_compact is (note 560 §7.3: compacting outside the
collection segfaulted). A base is kept nowhere but in its record: the VM's
ivar cache keeps a shape and an index and reads the record; the door
functions that take a base are in m_state, ahead of the evaluator, and call
no Ruby between reading it and using it; a value read out of the slab and
held by an interrupted stack or a suspended fiber pins its block through
vec_recycle. Each area keeps its size class, so iv_grow's `n1 <= cap0` and
the VM's `sh_len s1 <= iv_rec_cap r` see the area that is there.

MERE_RUBY_STORE_STATS reports iv_slab_squeezes; MERE_RUBY_GC_LOG prints a
squeeze's slots and time, and each collection's time.
MERE_RUBY_SLAB_SQUEEZE=1 squeezes whenever a slot is free, for checking.

200,000 objects made and dropped, then 3,000 made: the slab 934k -> 134k
slots (24 -> 5 MB) in one squeeze of 2 ms (that collection, which also swept
the 200k, 69 ms; the others 5-12 ms). 30 rounds of making and dropping 20k
objects after it: no further squeeze.

corpus 1075.

@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 06332690. No Critical/Major/Minor findings in the code.

iv_slab_squeeze runs inside gc_collect, after mark and sweep and only off the "nc" path, where the slab's arena was already compacted. That keeps it clear of note 560 §7.3's out-of-collection compaction. It copies each live area at its own size class, rewrites only the base in the record through iv_rec_put (the same class and shape, so iv_grow's n1 <= cap0 and the VM cache's sh_len s1 <= iv_rec_cap r still see the real area), resets the free lists and winds back its scratch Vecs. A base lives only in records, the VM's ivar cache keeps shape and slot, and the door functions call no Ruby between reading a base and touching the slab, so nothing holds a stale base across it. The trigger (more than twice the live area slots plus 64K) leaves the slab at half the length of the next trigger. MERE_RUBY_SLAB_SQUEEZE=1 (squeeze at every collection, used for the stress corpus) and SQUEEZE_MAX are documented as checks and diagnostics, not settings.

The evidence is honest. On macOS, eager_test's family peak is 1.20 vs 1.58 GiB on average (two runs each, ranges not overlapping) at about the same time. The probe tables show that the bad runs cluster in busy hours and are unresolved. Since macOS's compressor can lower RSS on its own, I will merge once the Linux comparison (eager_test under run.py's limits, alternating with and without the squeeze) is in the description and the review bot has reviewed that head, as the description itself says.

@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 current head 06332690b113b7ebfc0df7c28fdb1ad8fb79c6c3 against current main 491cc5cab7e727606e1b00a141607e4742194d0a in fresh isolated checkouts. One Major (P2) code finding requires a fix: both scratch Vecs must acquire private arenas before their first large fill. See the inline comment. This finding is absent from the existing review.

The deferred record rewrite avoids changing obj_iv during its copy traversal, and retaining each area's capacity and shape preserves the VM cache's assumptions. Focused value-correctness checks support those aspects; they do not detect the first-use arena retention.

Independent validation:

  • Fresh ordinary O2 builds of both exact trees succeeded with CI-pinned Mere 9dec2ff687a08433247dbdb7729bc19c8522e538 and mgz 661a01d8bb68f5acd68e3192bd47f081d179c436; the three imported mgz source files were verified against that commit.
  • 48/48 comparisons match clean Ruby 4.0.10 stdout, stderr and exit status. These cover corpus 1075, 1065, 1064, 1066, 833, 235, 211, 125 and 694, plus an independent suspended-Fiber ivar probe, on main and candidate, evaluator and VM. Forced squeeze and shape checking were enabled; 1075 was also checked in normal squeeze mode, and the Fiber probe additionally used GC_STRESS=50.
  • Separate default-mode 1075 executions confirm one actual squeeze on each engine: 514,413 -> 34,130 slots on the evaluator and 514,413 -> 34,126 on the VM, both exit 0.
  • The pinned-compiler O2 scratch reproducer retains a 16 MiB default arena after recycling two 500,000-element Vecs, versus 4 MiB initially. Promoting both empty Vecs before filling them keeps the default arena at 4 MiB. This establishes allocator retention, not an explanation of the intermittent Rails slowdowns.
  • Ivar-door, method-write, duplicate/dead-definition, literal-length, namespace, generated-C GC-root and bracket-depth audits pass. The class-watermark check and its negative control pass. Diff whitespace passes.

Outstanding validation and merge blockers:

  • The executed Linux Additional upstream gem tests job failed Check anonymous Method-copy warning-state lifetime: post-GC RSS ratio 2.139370388, above the unchanged 2.0 bound; process exit 0 with no outer limit event. The identical check on current main passed at 1.791446628. These are separate hosted executions, not a controlled causal attribution, and the difference needs investigation. PR job, current-main job.
  • The core Linux build is still executing; macOS and downstream coverage are incomplete. Current-main core run 46078134440 exposes zero jobs. A successful small-gem job does not establish full core acceptance.
  • I did not run the full VM stress corpus or the alternating Linux Rails eager_test comparison. Both remain outstanding in the PR evidence, as does the reported intermittent probe regression.

No merge. The new P2 finding, executed CI failure and recorded hold_all_merges / new_failure_review_required prevent it; the runner-queue exception does not apply. Other open application PRs 385, 383, 373, 256 and draft 245 were considered under the same global holds; the compiler repository currently has no open PRs. Historical failures and original bounds remain preserved. COMMENT is used because the authenticated account owns this PR; the finding still requires a fix.

Comment thread m_state.mere Resolved
A Vec made with vec_new fills the default region, and vec_recycle cannot
give that back, so the first big squeeze's copies stayed there for good.
Both scratch Vecs are compacted when they are made, as cut_e and rxv_ls are.
One squeeze of 500,000 live areas: default region 130 MB -> 63 MB.

@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-review at a527ed56. The bot's Major is fixed: both scratch Vecs (iv_sq_vals, iv_sq_recs) get a private arena from birth with vec_compact, as cut_e and rxv_ls do, so the first squeeze's large scratch fill is reclaimable instead of staying in the default region. With a 500,000-area squeeze the default region goes from 5 blocks / 130 MB cap / 81 MB alloc to 4 / 63 / 40 MB, and corpus 1075 passes in five modes. Waiting, as the description says, for the Linux eager_test comparison and the review bot on this head before merging.

@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 review of a527ed5678aed761ca6a00fed044fec295ea5109 against current main 491cc5cab7e727606e1b00a141607e4742194d0a. The previous Major / P2 scratch-arena finding is fixed. No new actionable code findings. Both scratch Vecs now acquire private arenas before their first fill; the rest of the squeeze implementation is unchanged from the previously reviewed head.

Independent validation:

  • Fresh ordinary O2 candidate build succeeded using CI-pinned Mere 9dec2ff687a08433247dbdb7729bc19c8522e538 and mgz 661a01d8bb68f5acd68e3192bd47f081d179c436. Compiler identity and all three imported mgz sources were verified. The unchanged main O2 baseline was reused after checking its exact commit, clean tracked tree and recorded binary SHA256.
  • Repeating the 500,000-element scratch reproducer with the fix's exact empty vec_compact initialization gives both Vecs private ownership before filling them. The default arena stays at 4 MiB before filling, after filling and after recycling, rather than the previous unowned version's retained 16 MiB. This verifies the allocation-lifetime fix; it does not establish a cause for the intermittent Rails slowdowns.
  • 48 comparisons match Ruby 4.0.10 stdout, stderr and exit status: 24 on current head and 24 on unchanged main. They cover corpus 1075, 1065, 1064, 1066, 833, 235, 211, 125 and 694 plus the independent suspended-Fiber ivar probe, on evaluator and VM with forced squeeze and shape checking. Corpus 1075 also matches in normal mode; the Fiber probe also matches with GC_STRESS=50.
  • Four additional large corpus-1075 GC_STRESS=50 attempts hit the local 180-second per-process deadline: main and candidate, evaluator and VM. These are incomplete stress comparisons, not passes or evidence of a new candidate regression. The full VM stress corpus remains unverified here.
  • Ivar-door, method-write, duplicate-definition, dead-definition and name-tag audits pass. Generated-C GC roots and bracket depth pass (155 required, 1024 budget); diff whitespace passes.

Hosted resource evidence: the current-head Linux Additional gem suites job succeeds, including the anonymous Method-copy warning-state check: RSS ratio 1.612523867, below the unchanged 2.0 bound, exit 0, no outer limit event. Preserve the earlier head's 2.139370388 failure and main's 1.791446628 observation; this separate successful execution does not prove a root-cause repair.

No merge. The alternating Linux Rails eager_test comparison and completed full VM stress corpus are still absent from the PR evidence. At this check, hosted CI has 22 successful jobs, 5 running and 7 queued; core CI is incomplete. Latest main core CI also has an executing Linux build and pending downstream jobs. Recorded hold_all_merges / new_failure_review_required remain active, and the runner-queue exception does not cover executing or unverified tests. COMMENT is used because the authenticated account owns this PR.

@284km

284km commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

eager_test under run.py on Linux. Docker (Debian arm64, ruby 4.0.10, clang 19), gems installed by run.py in the container, family RSS limit 2 GiB. The squeeze build is this PR's head a527ed5; the other is main 491cc5c. The two were run alternately.

build state time to the limit peak family RSS cases done
this PR MEMORY_LIMIT 430 s 2.00 GiB 197 (196 pass, 1 F)
main MEMORY_LIMIT 371 s 2.00 GiB 197 (196 pass, 1 F)
this PR MEMORY_LIMIT 477 s 2.00 GiB 197 (196 pass, 1 F)
main MEMORY_LIMIT 314 s 2.00 GiB 197 (196 pass, 1 F)

Both builds hit the limit at the same place: the last two cases, which load the 65,536-row fixture. The squeeze reaches the limit later, but on Linux it does not get eager_test under 2 GiB. The macOS numbers above (both builds finishing) do not carry over to the Linux limit.

The VM stress run with CORPUS_KEEP_GOING=1 was stopped by hand at file 523: 587 files ok, 0 FAIL. It ran on the head before a527ed5. Files from 524 onward have not been run yet.

@284km
284km marked this pull request as draft November 28, 2026 00:05
@284km

284km commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

Back to draft and on hold. On Linux, the squeeze only delays eager_test's MEMORY_LIMIT; it does not bring the file under 2 GiB. The swings under load are also still unexplained. The branch and the record stay. This will be looked at again once the other peaks in eager_test (the fixture's Psych.unsafe_load and the preload) bring the Linux peak near the limit, to see whether the squeeze is then the last step under it. The rest of the VM stress run (files 524 onward) waits until then.

@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 review of 41e38fd9308c77a8c95dbe5ea52355966bd6ab1b against freshly fetched main 3c58e0494d2b28b3f7e1aa1211e7bd3dc678ec5e (prospective integration tree 09a3df35b59bb5f8aac763c3bbd9037e0079656f). No new actionable code findings. The previous Major/P2 scratch-arena finding remains fixed: both iv_sq_vals and iv_sq_recs acquire private arenas with vec_compact while empty, before the first squeeze fill. I left existing threads untouched.

The update and response correctly distinguish the fixed ownership defect from the outstanding resource acceptance. The completed alternating Debian-arm64 comparison reaches the unchanged 2 GiB family-RSS limit on both baseline and candidate. Delaying that limit is not a completed eager_test pass, and those Docker results are not acceptance on the CI Ubuntu image. The VM stress run was stopped at file 523; the remaining coverage is unverified. Keeping the PR draft and the resource hold is appropriate.

Independent checks in a fresh temporary clone:

  • Compared all tracked entries with reviewed fix a527ed56, on both the PR head and recomputed current-main integration: only the working-record Markdown file changes. The runtime and corpus remain byte-identical to that reviewed fix. Read the updated description, full record, existing reviews and discussion.
  • Ivar-door, method-write, duplicate-definition and dead-definition source checks pass; diff whitespace checks pass. No tracked AGENTS.md or CLAUDE.md exists on fetched base/head.
  • Inspected all 25 jobs of exact-head core CI run 46085906535: 24 succeeded, one evaluator-versus-VM comparison skipped. All 39 currently exposed PR checks are complete: 38 success, one skip. This functional CI completion does not supply the missing forced-squeeze VM stress or Linux eager_test resource acceptance.

No new native build, runtime execution, resource measurement or whole-suite comparison was performed in this follow-up. Earlier review evidence remains associated with its recorded compiler and baseline; source equality does not establish resource acceptance for current main or a different compiler. Latest main CI still records the Wasm runner-shutdown/exit-143 failure, and global merge holds remain preserved. No merge performed. COMMENT because this is the authenticated user's own PR.

This branch has not been deployed

No deployments
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