Skip to content

A big String is kept in an arena of its own - #400

Merged
284km merged 8 commits into
mainfrom
stage10-big-strings-own-arena
Nov 28, 2026
Merged

284km merged 8 commits into
mainfrom
stage10-big-strings-own-arena

Conversation

@284km

@284km 284km commented Nov 28, 2026 •

Copy link
Copy Markdown
Owner

After #393 took the StrBufs out of the default region, what the msgpack loop still kept was the String page in use. This is the loop with the C extension taken out:

r = Random.new(12345)
50.times { f = []; r.rand(4).times { f << r.bytes(r.rand(1024*1400)) }; io = StringIO.new(f.join); f.each { |s| io.read(s.size) }; GC.start }

What kept it

Strings live in pages of 4,096. A collection gives back a page none of whose Strings lived. A page that has live Strings it compacts, which gives back the bytes of the Strings that died in it. But Mere refuses a compaction while a suspended stack points into the arena. The collector runs on a coroutine, and the program's stack, stopped below it, points into the page in use. Mere compacts under a pin only once the arena has doubled since the first refusal (v0.1.651).

So the page in use kept every big String that died in it until its arena had doubled. A probe that is not in this change counted the loop's collections: 42 of 51 compactions were refused. The page grew to 44 to 54 MB before one went through, and came back to 23 MB, where 6.5 MB lived.

The change

A String of str_big_min bytes (256 KB) or more is kept in a Vec of its own, with an arena of its own. The page's slot holds "".

  • sraw looks in str_big when the slot is "" and some big String exists. sput, mkstr and mkstr_join put a big String there and a small one in the page. A big String made small again leaves str_big.
  • When a big String dies or is replaced, its Vec waits for the next sweep, and the sweep recycles it (vec_recycle) and pools it. Nothing points into that Vec then, whatever points into the page.
    • It is not recycled at once, because the old text may be in flight in the very call that replaces it: sput id (sraw id ++ tail).
    • It is not recycled at a sweep that runs on the program's stack (nc), as a compaction is not.
  • vec_recycle gives back the arena's growth and keeps one 256-byte block. It moves to a fresh arena where a suspended stack points into a block, and retires the old one.
  • str_bytes counts the big Strings' bytes, so the pressure sees them.

Counted until it is given back (review, Major)

A replaced or dead big String's Vec waits in str_big_dead for the sweep. Its bytes were taken off str_big_tot at once, so the pressure no longer saw them. A String replaced again and again by one that is already there makes no new handle, and nothing else asked for a collection: each replace counted one copy while every copy stayed. The bytes now stay in str_big_tot until the sweep recycles the Vec.

A big String written over another is bytes made, as mkstr counts them, so sput adds them to str_pg_add. The safepoint asks for the pressure once 16 MB have been made (#389). Main did not count them either: its page kept every replaced copy, and asked for no collection.

src = "a" * 1_048_576; s = +"x"; 128.times { s.replace(src) }, from one GC.start to the loop's end:

evaluator: collections RSS VM: collections RSS
main 0 68 → 198 MB 0 69 → 199 MB
this change, as reviewed 0 68 → 199 MB 0 69 → 200 MB
this change 4 68 → 115 MB 2 69 → 153 MB

Why 256 KB

threshold loop_rss cases of 32 KB Strings, VM, from the tree a loop of 20 KB Strings: instructions
256 KB 1.11 to 1.86 (three over 1.6) no change
16 KB 1.08 to 1.29 +3.3% on the evaluator, +3.5% on the VM

A String of 20 KB or so is a common size: a JSON document, a template's result. So the threshold is 256 KB. The 32 KB cases' VM ratios are the page in use, and they are bounded: 2,000 to 16,000 turns gave 1.39, 1.86, 1.58 and 1.19.

And Mere's own change

0e's Mere branch, arena-return-dead-pages, gives back a refused arena's pages that no live value and no pin can reach (madvise). It touches no mere-ruby source. It gives back RSS, but not macOS's footprint, and only for an arena that has handed out 8 MB or more. This change frees a big String's arena outright, at any size. The two do not conflict.

Numbers

The program above

Peak memory footprint on macOS. All builds are of main 856e61b with the same Mere. "#393" is the StrBuf change, and "both" is #393 with this change.

turns engine main #393 this change both
50 evaluator 266 MB 218 MB 236 MB 137 MB
50 VM 293 MB 210 MB 242 MB 142 MB
200 evaluator 641 MB 327 MB 620 MB 189 MB
200 VM 712 MB 304 MB 642 MB 205 MB

str_store after the last GC.start, 200 turns: 54 and 71 MB on main, 24 and 30 MB with both. ruby's footprint for 200 turns is 48 MB.

Instructions

Instructions retired, in billions. Each figure is the median of three runs taken alternately, and both sides are built with the same Mere.

program evaluator: main this change VM: main this change
small Strings: +, ==, a Hash read, interpolation, upcase, <<, 300,000 times 33.396 33.525 28.467 28.573
small Strings, 15 operations, 100,000 times 39.737 39.849 36.213 36.349
loop_plain 23.381 23.383 12.644 12.645
200.times { "a".b * 6_000_000 } 2.540 2.444 2.534 2.451
the program above 16.525 16.393 16.552 16.384

The look into str_big costs 0.3 to 0.4% on small Strings. Big Strings cost 0.8 to 3.8% less. Probably because they are no longer copied when a page is compacted, but that was not measured apart.

tools/loop_rss_check.rb

Three new cases, from the tree. The third makes no new handle, so nothing else asks for a collection: it is the review's case.

case engine main this change both
big Strings: s + "b", <<, sub! of 300 KB, 2,000 times evaluator 4.06 (FAIL) 4.24 (FAIL) 1.01
VM 5.15 (FAIL) 4.23 (FAIL) 1.03
a big String replaced, 2,000 times evaluator 1.35 1.00 1.00
VM 1.39 1.03 1.04
a big String replaced by another, both kept, 512 times evaluator 5.36 (FAIL) 1.02
VM 5.33 (FAIL) 1.13

The first needs #393 too: sub!'s StrBuf was the default region's.

Corpus 1150

Corpus 1150 does with Strings of 300 KB what a program does with any String, and prints what each one holds. It covers <<, []=, replace with a short String and back, slice!, dup, freeze, force_encoding, sub! and gsub!, five kept across 50 dead ones and a GC.start, an aliased one appended to, clear and growing again, join, and ObjectSpace.each_object. It matches ruby on both engines, and under GC stress on both. main matches too: it checks that behaviour is unchanged.

What is left

  • The page in use still keeps Strings under 256 KB that died in it, until its arena doubles. 0e's Mere change gives back their pages' RSS where the arena is past 8 MB.
  • The collector's survivor list (gc_str_surv) leaves its old copies in the default region as it grows: a high-water mark, as A StrBuf is made in a region of its own #393's record says.

Checked

On 6ab7818, which is main e47a4bb (with #393) and this change:

  • run_corpus.sh 1034/1034, corpus 1150 included. strbuf_region_check.py read a fresh mr.c.
  • vm_corpus.sh: all 1034 on the VM, 0 fallback, 0 FAIL.
  • vm_check 246/246.
  • The collector's root check.
  • tools/loop_rss_check.sh 28/28: "big Strings" at 1.01 and "a big String replaced" at 1.00.
  • tools/class_watermark_check.sh.
  • Corpus 1150 under GC stress on both engines.
  • After the review fix, on f69302f (main e47a4bb and this change): run_corpus.sh 1034/1034, vm_corpus.sh all 1034 on the VM with 0 fallback and 0 FAIL, vm_check 246/246, the root check, tools/loop_rss_check.sh 29/29 (the review's case at 1.02) and tools/class_watermark_check.sh. Corpus 1150 under GC stress on both engines.

The record is loop/2026-11-28-stage10-big-strings-own-arena.md.

🤖 Generated with Claude Code

@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 head ee088ac3 (m_state.mere +73/-6, main.mere +3, corpus 1150, two loop_rss cases).

What I checked:

  • Every way in and out of the page goes through the new paths. mkstr, mkstr_join and sput route a String of str_big_min (256 KB) or more to its own Vec and leave "" in the page slot. sraw falls back to str_big only when the slot is "", so small Strings pay one str_len test. I found no other reader of a page slot: the remaining str_store users are the sweep, str_bytes (which now adds str_big_tot) and diagnostics.
  • A dead big String is released. gc_collect's blank_s1 does sset s9 "" for every dead handle. sget returns the big text, so it is not "", and the blanking goes through sput and so through str_big_let_go. A replaced one goes the same way. Recycling waits for the next off-stack sweep, which is right given sput id (sraw id ++ tail) may still be reading the old text.
  • Corpus 1150 covers append, splice, replace (big → short → big), slice!, dup, freeze, a non-ASCII String re-tagged BINARY, sub!/gsub!, aliases (h = g; g << ...), clear-then-grow, join, survivors across GC.start, and ObjectSpace visibility.

Non-blocking notes:

  1. While every collection runs with nc, nothing is recycled and str_big_dead keeps the dead Vecs. That is no worse than main (the page kept them), but a line in the comment saying so would help later readers.
  2. str_big_pool keeps one 256-byte block per recycled Vec, bounded by the peak number of live big Strings. That is fine; noting it for the record.

No blocking findings from me. The numbers in the body are good: with #393, the 200-round repro peak goes from 641/712 to 189/205 MB, small Strings cost +0.3–0.4% and big ones save 0.8–3.8%. The merge waits for the automated reviewer on this head.

@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 exact head ee088ac3d06731e5fe1d7f5360f34592f285274e against current main/base 0f0413c5dbe6e6f9b4d0ad975f4a32c3b77ccad6, including the existing review, discussion, storage accessors, deferred append paths, collector sweep and pressure accounting. One new Major/P2 issue requires a fix: quarantined large-string payloads disappear from pressure accounting before their storage is recycled (inline).

The separate storage preserves String behavior in the focused checks: 20 exact exit/stdout/stderr comparisons against clean Ruby 4.0.10 passed. Corpus 1150 passes all eight evaluator/VM × Hash-index on/off × normal-GC/GC32 configurations; three existing string-page/ObjectSpace corpus programs pass both engines and Hash modes. GC-root and StrBuf-region audits pass against freshly emitted C.

Validation used a fresh ordinary O2 build of this exact head, pinned compiler 9dec2ff687a08433247dbdb7729bc19c8522e538 and mgz 661a01d8bb68f5acd68e3192bd47f081d179c436. Binary SHA-256: 9a345178e18a7e41365278de36f5ea9e07d98d06a0ba1f587072589ae9eee693. No reused interpreter binary. A separate O2 control using the verbatim current-base/head store functions counts 32 successive 1-MiB writes as 33,559,040 bytes on base versus 1,048,576 on head, with 31 payload Vecs still quarantined. This is a source-level base comparison, not a whole-interpreter base RSS measurement.

The fresh head interpreter reproduces the pressure problem with src = "x" * 1_048_576; s = +""; GC.start; 128.times { s.replace(src) }: automatic GC delta is zero on both engines. Evaluator RSS grows 69,472 → 203,280 KiB; VM 70,288 → 204,048 KiB. A subsequent explicit GC leaves samples at 203,648/204,320 KiB; these single samples do not establish a reclamation or allocator cause. RSS sampling required sandbox escalation because ps was restricted; the cited run completed with permission, so that restriction is not reported as interpreter behavior. I did not rerun the full corpus, original core suites, full RSS gate or Linux resource acceptance.

Merge remains blocked by this finding and the recorded hold_all_merges/new_failure_review_required. Latest main CI run 46101446305 is pending with zero exposed jobs, which does not clear the preserved failures. At the latest inspection, PR Linux build had already executed ten steps and was still running; macOS/reference builds were unassigned queues and downstream coverage remained incomplete. The queue exception does not apply. This is a COMMENT because the authenticated reviewer owns the PR; the Major finding still requires changes.

Comment thread m_state.mere Outdated
let str_big_let_go = fn (id: int) ->
if map_len str_big > 0 && map_has str_big id then
(let v = map_get str_big id in
let _ = vec_set str_big_tot 0 (vec_get str_big_tot 0 - str_len (vec_get v 0)) in

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.

[Major][P2] Keep quarantined payload bytes charged until the sweep. str_big_let_go subtracts the old payload immediately, although its Vec stays in str_big_dead until a later off-stack collection. Neither str_bytes nor gc_store_bytes counts those dead Vecs. Replacing one existing large String repeatedly from an existing source therefore keeps the reported usage nearly constant while allocating another payload and Vec every time, so the byte-pressure trigger no longer requests the collections that main requested. In an O2 harness using the verbatim current-base/head store functions, 32 successive 1-MiB writes are counted as 33,559,040 bytes on base but only 1,048,576 on head, with 31 payload Vecs still quarantined. Please include quarantined bytes in pressure accounting until recycling (or charge allocations since the last sweep), and add a regression that reuses both receiver and source so new String handles do not mask the missing pressure. A fresh exact-head interpreter build also reproduces the practical consequence on both evaluator and VM: 128 calls to s.replace(src) with a pre-existing 1-MiB src cause no automatic GC and increase RSS from about 69 MiB to about 199 MiB.

@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 ee088ac3..d9080f4d against the automated Major.

Fixed.

  • str_big_let_go no longer subtracts. str_big_sweep subtracts each dead Vec's bytes when it recycles it, so quarantined payloads stay in str_bytes (and therefore gc_store_bytes) until they are actually returned.
  • sput's big arm also adds the written bytes to str_pg_add, as mkstr does, so the safepoint asks about pressure after 16 MB of big writes even when no new handle is made.
  • The author's table shows the practical case recovering: 128 s.replace(src) of 1 MiB now triggers 4/2 automatic collections and ends at 115/153 MB instead of ~199 MB. Main was 198/199 MB with no collection, so this is better than main as well.
  • The new loop_rss case reuses both receiver and source, so no new handle can mask the missing pressure. It fails on main (5.36/5.33) and passes here (1.02/1.13).

Note, non-blocking: str_bytes returns str_pg_tot + str_pg_add + str_big_tot. A big write is now in both str_pg_add and str_big_tot until the current page's add counter is folded and reset, so it is briefly counted twice. That only makes pressure ask earlier, and the author notes the same overlap with #397's CAT path. A one-line comment at str_bytes saying the double count is intentional and bounded would help.

No blocking findings from me. The merge waits for the automated reviewer on this head.

@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 exact head d9080f4d20c017bb376a1a90fe87e341f7e26222, the earlier reviews and inline finding, and the fix since ee088ac3. The previous Major/P2 pressure-accounting finding is fixed: str_big_let_go retains the charge until recycling, and large writes through sput advance the safepoint allocation counter. The regression reuses both source and destination, so new handles cannot mask this path. No new actionable code findings.

Validation used a fresh ordinary O2 interpreter build with pinned compiler 9dec2ff687a08433247dbdb7729bc19c8522e538 and mgz 661a01d8bb68f5acd68e3192bd47f081d179c436; no interpreter binary reuse. Binary SHA-256: ac7beb74fb9abd1d195ad8d1e8f9c02db4f545e68981ce112b6a0362b4d85689. Corpus 1150 matches clean Ruby 4.0.10 exactly (exit/stdout/stderr) in all eight evaluator/VM × Hash-index on/off × normal/GC32 configurations. Fresh-C GC-root and StrBuf-region audits pass.

The original 128-replace reproducer now triggers 4 automatic collections on evaluator and 3 on VM. RSS samples are 69,408 → 118,800 KiB and 70,224 → 156,048 KiB; after explicit GC, 103,424/122,912 KiB. The added original loop_rss case passes both engines: 1.07 and 1.13, below the unchanged 1.6 bound. An O2 harness using the verbatim updated store functions counts 33,558,528 bytes with 31 quarantined Vecs, then 1,052,672 after sweep with zero quarantined Vecs. The first sandboxed RSS attempt could not run ps; these measurements are from the subsequently authorized unrestricted run, not zeros from the denied attempt.

Fetched current main is a56107b3e373b7bcb63c27f05d9142d1cbbd1d17; this validates the exact PR head, not a prospective integration with newer main. Full corpus, original whole-file resource acceptance and Linux acceptance were not rerun locally. Merge remains deferred under the recorded hold_all_merges / new_failure_review_required: the preserved main run 46028215730 artifact identifies TestModule#test_iclass_memory_leak as Timeout (195 tests, 1237 assertions, 0 failures, 1 error), rather than an unassigned queue. Latest main CI 46109272555 exposes no jobs yet. PR Linux build is still executing, macOS jobs are queued, and downstream acceptance is incomplete; the queue exception does not apply. COMMENT because the authenticated reviewer owns this PR; the specific prior finding is cleared, global holds are not.

@284km
284km merged commit c576ee4 into main Nov 28, 2026
12 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