Skip to content

C API: what C appends to a big String goes to the interpreter as the tail - #397

Merged
284km merged 8 commits into
mainfrom
capi-append-tail
Nov 28, 2026
Merged

284km merged 8 commits into
mainfrom
capi-append-tail

Conversation

@284km

@284km 284km commented Nov 28, 2026 •

Copy link
Copy Markdown
Owner

After #390, msgpack's whole suite still peaked at 2.65–2.89 GB on Linux. Two spec files besides packer_spec made most of it:

spec file alone (Linux, MB) mere-ruby ruby
cruby/buffer_io_spec 1,899 96
packer_spec 1,836 369
cruby/buffer_spec 1,714 138
the other 11 112–266 24–26

Most of the buffer specs' memory is the interpreter's, not the C API's. Their largest example, buffer_io_spec's 'random read', does the same with StringIO#read in place of MessagePack::Buffer, with no C extension. It still ends at 200–250 MB on both engines, against ruby's 15 MB, with 6.5 MB of live Strings. That part is the String store's arenas, which keep the bodies of dead and replaced Strings. It is handed on separately. This change is the C API's own part.

What the C API's part was

A ledger of malloc's blocks of 64 KiB or more, by caller with a call chain of seven frames (LD_PRELOAD, Linux), on 'random read' with GC.start in each round:

  • The mirror's own buffers and transit: 160 MB allocated in all, none of it held at the end.
  • write_back → mr_up → mu_capi_up → mu_sput → __lang_region_alloc_aligned: 832 MB allocated in all, 189 MB live at the peak, 154 MB still live after GC.start. The same rounds without the C extension: 357 MB in all.

msgpack's Buffer#read(n) from an IO starts from rb_str_buf_new(0). It then appends 32 KiB at a time with rb_str_cat, calling io.readpartial between appends. rb_str_cat appends in the String's struct, which is then watched, so at every readpartial the whole String so far went back with MR_STR_SET.

Each write-back did three things:

  • It copied the whole String into transit.
  • It made a new body in the interpreter (sset).
  • It dropped the String's cached answers: whether it is all ASCII, and whether it is valid UTF-8.

msgpack then reads RSTRING_LEN after the readpartial. C fetches the String again for that, and the fetch asked the interpreter for its ASCII-ness, which it had just forgotten. It rescanned the whole String every time: mu_str_is_ascii is most of main's samples in this loop.

What changed

  • mirror.c. A String's struct keeps the length it last synced with the interpreter (synced). At a write-back, MR_STR_CAT sends only the bytes past that length when:

    • that length is 64 KiB or more;
    • the String only grew;
    • its first synced bytes still hash as they did at the sync.

    Otherwise all of it goes, as MR_STR_SET, as before.

    • The hash now takes the length at its end (hash_end), not at its start, so one pass gives both the hash of what the String was and of what it is (hash_two). The first version hashed the synced part a second time, which made the same loop slower on Linux.
    • When rb_mere_string has just sent the tail of what C wrote through a pointer it kept, it fetches the String again, as below, instead of returning the struct as it is.
  • main.mere. MR_STR_CAT appends the bytes where the String is (sput (sget h ++ tail)), when the String is the length C says; otherwise it refuses and C sends all of it.

    • It keeps the String's two cached answers the way String#<< does: the bytes appended decide them (str_append_answers, split out of str_push with no change to it).
    • The bytes count as String bytes made, as a new String's do (str_pg_add), so the collector's pressure is asked once 16 MB of them have been made.
    • An earlier version queued the tail with str_push. But C fetches the String again after each call into Ruby, which folded the queue in at every crossing anyway (610 of 640 crossings in this loop). On macOS that version peaked 120–230 MiB above main in this loop.

The interpreter still makes the whole body again at every crossing, as main does, because C fetches the String after every call into Ruby. Not fetching a String the interpreter has not changed would need a per-String change count kept by every write to a String, a hot path. That is not part of this change.

Why the interpreter does not check that Ruby left the String alone

A write Ruby made since the sync is already in the struct's first synced bytes:

  • C reaches the bytes through rb_mere_string, which fetches the String again after any call into Ruby.
  • RSTRING, RSTRING_PTR, RSTRING_LEN, rb_str_set_len, rb_str_resize and rb_str_cat all go through it.
  • What C wrote first goes back before the fetch, and the bytes past the length C has not revealed stay in the buffer.

The only way past the fetch is a struct C kept across a call into Ruby and then wrote the length into. With an in-place change by Ruby in between:

  • ruby's String is Ruby's byte with C's bytes after it, because the buffer is the one both wrote;
  • with this change mere-ruby's String is the same, and so is what C reads through RSTRING_PTR afterwards;
  • before it, C's bytes replaced Ruby's change.

If Ruby's change moves ruby's buffer (replace, for one), the kept pointer is dangling in ruby too.

An earlier version marked each String the interpreter had not written since the sync, and refused MR_STR_CAT without the mark. That needed a check in sput and str_push, the String store's hot paths, and cost a loop of String writes 0.21%. A build that ignored the mark passed every contract. The one case the mark could change is the kept-struct one above, where it made the result differ from ruby's. So it was dropped.

Why the cached answers are not kept on their own

They are most of the instructions saved (below). But the interpreter can keep them only when it knows the new bytes are the old ones with more after them. Under MR_STR_SET it would have to compare the whole String to find that out. MR_STR_CAT is that knowledge, from the side that already has it: C's hash of the synced part.

Checked

Mere 9dec2ff6, reference ruby 4.0.10. The base is main 491cc5c; for the Linux numbers it is main f09341c, which differs from it only in corpus programs.

  • capi_check. On the evaluator and with --vm, 444 contracts pass on both sides, also under collection stress, and each negative control fails. The new contracts build a String 32 KiB at a time with rb_str_cat, Ruby seeing it after each piece:

    • with Ruby writing it once in between: <<, []=, replace, force_encoding, clear, and a write to a dup only;
    • with C writing it once in between: a byte in what was there, rb_str_set_len, rb_str_resize;
    • starting from a String Ruby made, and from an unfrozen dup of a frozen one;
    • a data object's String appended to in calls with collections between, marked by its dmark;
    • one a stopped Fiber holds across collections, appended to after;
    • the kept-struct case above, including what C then reads through RSTRING_PTR and a byte it writes there.

    On main's interpreter the kept-struct contract fails, and the others pass.

  • Mutants.

    • A build that sends the tail without checking the synced part's hash fails the contracts.
    • A build whose MR_STR_CAT appends the bytes twice fails them as well, so the contracts do go through MR_STR_CAT.
  • run_corpus.sh --both: the gates, then 1031/1031 with the hash index on and off. MERE_RUBY_VM=1 run_corpus.sh --both: 1031/1031.

  • capi_spec_check: 2420 of 2602, the recorded count. capi_mkmf_check passes. capi_gem_check: seventeen gems give the same output on both sides. headers_check: 194 headers, 10 patched, 22 vendored sources unchanged.

  • Instructions (macOS, the loop alone with start-up subtracted, median of three, alternating). "No cache" is this change with MR_STR_CAT dropping the cached answers (sset), for comparison:

    loop this change no cache
    Buffer#read 2 MiB from an IO ×100 −68.0% −1.1%
    Buffer#read 4,000 B ×20,000 +0.06% +0.14%
    Buffer#read 100 B ×50,000 +0.02% +0.05%
    Unpacker#feed 100 B ×100,000 +0.19% +0.27%
    msgpack to_s of 100 B ×100,000 +0.05% +0.10%
    String writes in Ruby (<<, []=, replace, clear) ×300,000 +0.22% +0.21%

    The small loops do not reach the new path; the rest is code layout.

  • Peak, macOS (Buffer#read 2 MiB from an IO, the run's maximum RSS; the machine was shared, so the runs alternate):

    main this change no cache
    ×30, MERE_RUBY_GC_TIGHT=1, 5 runs median 373 MiB (312–374) 350 (339–367) 350 (315–430)
    ×100, default, 7 runs median 649 MiB (632–750) 616 (421–825) —

    With the default collector the peak depends on when the collections fall, and the runs spread over 400 MiB. The footprint medians of those seven are 639 (main) and 679 MiB.

    Measured again with MERE_RUBY_GC_TIGHT=1, 7 runs alternating, median max RSS (range):

    main this change
    ×10 368 MiB (309–404) 316 MiB (266–333)
    ×30 373 MiB (316–412) 363 MiB (348–368)
  • A known exception: the GC_TIGHT peak on macOS. The review measured the same loop with its own builds and found this change above main:

    • ×10: 275 against 329–330 MiB, and 290 against 346 in another three runs;
    • ×30: 333–359 against 399, and 367–377 against 419;
    • ×200: mixed;
    • with the default collector, seven runs: 658 against 510 MiB, this change lower.

    In those runs the collector ran the same number of times on both sides and counted the same bytes. So the difference, +40–55 MiB, is outside what the interpreter's collector counts. It also follows how the loop is run: loaded from a wrapper, vmmap showed this change lower (265 against 340 MiB), and the runs above, the same binary's, have it lower too. It is not explained here.

  • Linux (docker, Debian, ruby:4.0.10, clang 19, aarch64; peak RSS from GNU time):

    • Buffer#read of 2 MiB from an IO ×100: 94 MB on both. User CPU 0.34–0.44 s on both over five runs each, plus one main run at 0.65 s.

    • The specs, with their random seeds fixed in a copy for the measurement (they pick a new one every run), five runs alternating:

      main: median (range) this change: median (range)
      buffer_io_spec 1,291 MB (1,106–1,386) 1,195 MB (1,118–1,466)
      buffer_spec 1,254 MB (1,167–1,753) 1,136 MB (1,071–1,269)
      whole suite 2,887 MB (2,758–3,631) 2,677 MB (2,491–4,114)

      Within the runs' own spread. The peaks are the interpreter's part described above.

Left

  • The interpreter's part. The String store's arenas keep the bodies of Strings that died or were replaced until a page is compacted. That is most of the buffer specs' memory, and the suite still peaks over CI's 2 GiB.
  • The fetch after every call into Ruby. C fetches a String it holds again even when the interpreter has not changed it. Here that makes the interpreter build the whole body at every crossing, and the C API hand all of it over.
  • The write-back hashes the whole String at every crossing, as before.

The record is loop/2026-11-28-capi-append-tail.md. The branch keeps its work-in-progress commits; they were pushed before review, so they were not squashed.

🤖 Generated with Claude Code

…CAT)

Paused mid-work (not ready for review). msgpack's Buffer#read with an IO
builds its result 32 KiB at a time with rb_str_cat between io.readpartial
calls, and every crossing wrote the whole String back (MR_STR_SET -> sset
-> sput), leaving a new body in the String page's arena each time: on
Linux, in buffer_io_spec's 'random read', 832 MB of bodies for about
105 MB read, 154 MB of them still held after GC.start.

- mirror.c: a String's struct keeps the length it last synced with the
  interpreter (`synced`). At write-back, when that is 64 KiB or more, the
  String only grew, and the synced part still hashes as it did, only the
  tail goes, as MR_STR_CAT; otherwise, and when the interpreter refuses,
  all of it, as before.
- main.mere / m_state.mere: str_capi_synced marks a String whose bytes are
  still the ones C synced (set by a big MR_STR_SET and by MR_STR_CAT,
  dropped by any write: sput, str_push; a read folding the queue in keeps
  it, sput_raw). MR_STR_CAT appends with str_push only while marked and of
  that length; gc_collect sweeps dead handles from it.
- capi/check: contracts for appends with Ruby writing in between (<<, []=,
  replace, force_encoding, clear, a dup), C writing in the middle, set_len,
  resize, a String from Ruby and a dup of a frozen one, a dmark holder
  and a stopped Fiber across collections.

Done: capi_check 443/443 on the evaluator and the VM, both sides, also
under stress. Mutants: skipping the C-side prefix check fails the
contracts; appending the tail twice fails them; ignoring the mark passes
them (within the C API's contract C re-reads the String after a call, so
the mark only matters for a write through a pointer kept across one).
Left: spec/mkmf/gem/headers, corpus on both engines, Linux before/after
(the example, buffer_io_spec, buffer_spec, the suite), small-append
instruction counts, then the loop record and the PR.
…tail

The record of the change in the commits before it, with its numbers:
loop/2026-11-28-capi-append-tail.md. msgpack's Buffer#read from an IO
appends 32 KiB at a time between reads, and each crossing wrote the
whole String back; now only what was appended goes (MR_STR_CAT, str_push
on the interpreter's side), when the String C last synced is 64 KiB or
more, still starts the struct, and is the length the interpreter has.

@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 27c1e7c (base main 491cc5c). I built both from source with Mere 9dec2ff6, on macOS (arm64), in my own checkout. Reference: ruby 4.0.10. "Head" below means this PR's build; "base" means main's.

Summary

The correctness design (option 2) holds up. I found no way for a legal C program to get a prefix change past the check. The 2 MiB peak regression is real, and on my runs it is bigger than the PR says. Only about half of it comes from the str_push queue. One Major and one Minor finding.

Findings

Major: the 2 MiB Buffer#read loop peaks well above main on macOS, and the queue is folded at every crossing anyway

Probe: MessagePack::Buffer.new(StringIO.new(data)).read(2 MiB), repeated, with msgpack 1.8.7 built for each binary. Peak is max RSS from /usr/bin/time -l.

run base head
×100, ordinary, 3 runs 597 / 435 / 370 MB 1,007 / 540 / 550 MB
×100, MERE_RUBY_GC_TIGHT=1, 2 runs 264 / 319 MB 495 / 447 MB
GC_TIGHT, ×10 / ×30 / ×200 243 / 328 / 282 MB 406 / 446 / 405 MB

The peak stays flat as the run gets longer, so this is not a leak. It is a higher plateau: +120 to +230 MB, or +50 to +90%. That is more than the 695 → 846 MiB in the description. Under the rule that nothing gets worse than main, I would not call this a small exception. The instruction win does reproduce: −68% (134.1G → 43.0G instructions).

What I found about the cause:

  1. The queue never lasts more than one crossing. msgpack runs RSTRING_LEN(string) and rb_str_buf_cat(string, ...) right after each readpartial (_msgpack_buffer_read_from_io_to_string). The epoch has moved by then, so rb_mere_string fetches the String again with MR_STR_GET. The interpreter's sget then folds the queue (str_flush), which builds a new body of the whole String. With MERE_RUBY_STORE_STATS=1, ten reads have 640 crossings and give str_pending_folds 610. So in msgpack's own loop, the interpreter still builds one whole body per crossing. It just does so in str_flush instead of sset. The description says "a String built this way costs amortized linear work", which is not true for this loop.
  2. The speed-up comes from the ASCII cache, not from the queue. I sampled base with sample. Its top frame is mu_str_is_ascii (1,475 samples, against 72 on head). sset drops str_ascii, and the next MR_DESCRIBE or fetch scans the whole String again. str_push keeps the cache and scans only the tail. That is the quadratic term this PR removes.
  3. The queue explains only part of the peak. I built a variant that folds right after the append (str_push ...; sget h in the MR_STR_CAT arm). Under GC_TIGHT, ×30: base 291 / 304, head 431 / 491, variant 379 / 395 MB. Its instruction count is the same as head's (17.0G against 16.6G). With MERE_RUBY_GC_LOG=1 the three builds run about as many collections (240 / 216 / 248). The largest bytes= seen at a collection's start is about the same too (89 / 85 / 60 MB). So the rest of the extra memory is outside what the collector counts. Most likely it is whole-size temporaries or C-side buffers that macOS's allocator keeps. I did not pin this down.

Suggested direction: since every crossing folds anyway, MR_STR_CAT does not gain from queuing. Append and fold at once (the variant above), or use a direct sput that keeps str_ascii / str_valid8 as str_push does. Then attribute what is left on macOS (malloc stack logging, or footprint at the peak) before merging. The other way is to make MR_STR_GET hand over the settled body and the queued chunks without folding. That would make the linear claim true, but it is a bigger change.

Minor: after a tail write-back in rb_mere_string, C's struct can differ from the interpreter's String

rb_mere_string returns early when write_back sent something (it sets body_epoch and does not fetch). After an MR_STR_SET that is fine, because the struct is then what the interpreter has. After an MR_STR_CAT in the kept-struct case, the interpreter has Ruby's prefix plus C's tail, but the struct still has the old prefix. My probe extends cat_kept: after r->len = len + 4096, C reads RSTRING_PTR(str)[5] (mode 1), then also writes RSTRING_PTR(str)[0] = 'Q' (mode 2):

mode 1: C sees byte 5 mode 2: final byte 5
ruby 4.0.10 90 (Ruby's) 90
head 107 (stale) 107 (Ruby's write lost)
base 107 107

This is not a regression: main loses Ruby's write as well. But in mode 1, head leaves the struct and the interpreter disagreeing within the call, and main never does that. It only reaches the kept-struct case, which the PR says it matches ruby on. Suggested fix: write_back reports which op it sent. On MR_STR_CAT, rb_mere_string falls through to the fetch instead of returning. Only the kept-struct path pays the O(n) cost. A contract for mode 1 would pin it down.

What I checked and found sound (by reading, plus the runs noted)

  • Prefix check. first is the hash of exactly the first synced - 1 bytes, with the length mixed in, and before is the hash taken at the last fetch or write-back. A fuzz test of the extracted hash functions agreed on 200,000 random pairs: hash_two's two results equal hash_bytes(s, had) and hash_bytes(s, n), and copy_hash agrees too. The hash is the same 64-bit four-lane hash the write-back already trusts. mix is a bijection in either argument, so a change inside one 8-byte lane is always caught. Any other change has a chance of about 2^-64 to slip through. That is acceptable for non-adversarial C.
  • Shrink then regrow (rb_str_set_len / rb_str_resize, then appends). The changed bytes are inside the first had bytes, so the hash differs and the write falls back to MR_STR_SET. A regrow that writes back the same bytes is correctly sent as a tail. The length check alone would not be enough, but it is never used alone.
  • Ruby writes between syncs. Every op that is not a read bumps mr_epoch (MR_STR_CAT included), and the C API flushes before any call into Ruby. So C always fetches again before it can append through rb_mere_string. Only a kept struct skips this (see the Minor finding).
  • synced freshness. It is set wherever body = T_STRING is set (str_take, mr_string_new_zeroed) and at every write-back. A struct calloc made starts at 0 (not known). new_zeroed uses 1 together with a hash that cannot match, so the first write-back is always whole.
  • Interpreter side. str_push does what String#<< does apart from the encoding negotiation, and MR_STR_SET does not change the encoding either. Frozen Strings take MR_STR_CAT as MR_STR_SET does (both on purpose). str_blen counts the queue without folding it.
  • Tests. I ran the head's capi_check.py against the head (all 444 api contracts pass, plus stress, and every negative control fails) and against base. On base, the first new contract to fail is the kept-struct one (api.rb:921). The cat_run cases before it pass, as the PR says. The script stops at the first failure, so I could not see the holder and Fiber cases on base. The :lshift and :set_len cases make had not a multiple of 32, which covers hash_two's tail path.
  • The author's local results are in the PR body and in loop/2026-11-28-capi-append-tail.md.

Not checked

  • Linux (the description says the peak there equals main's).
  • The --vm capi_check, the corpus, capi_spec, mkmf, the gem checks, and the instruction counts of the small loops. I took these from the author's report.
  • The macOS peak's remaining cause, beyond the measurements above.

CI

At the time of review: 4 workflows succeeded (Linux build dependency controls, NKF Wasm, Delegation/URI gem suites, Additional gem suites). CI, Gem suites, Small pure Ruby gem suites, Rake suite and Runtime load path controls were still queued.

Comment thread main.mere Outdated
// through skips that fetch -- and then the String is Ruby's bytes with
// C's tail after them, as in ruby (whose buffer the same pointer is).
| VStr h ->
if str_blen h == r.b then (let _ = str_push h (str_of_bytes (mr_capi_bytes ())) in 1)

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 (with the peak). In msgpack's Buffer#read, the queue this pushes into is folded at the very next crossing. After readpartial, C runs RSTRING_LEN / rb_str_buf_cat on this String. The epoch has moved, so rb_mere_string sends MR_STR_GET, and sget runs str_flush. MERE_RUBY_STORE_STATS shows str_pending_folds 610 for 640 crossings. So the interpreter still builds a whole body per crossing; only the place moved from sset to str_flush. The −68% comes from str_push keeping str_ascii: base spends its time in mu_str_is_ascii. A variant that folds right here (...; let _ = sget h in 1) keeps the same instruction count and lowers the macOS peak from 431–491 to 379–395 MB (base: 291–304). Folding at once, or a direct sput that keeps the caches, looks like the better fit. The rest of the gap still needs attributing; see the review body.

Comment thread capi/mirror.c
* 32 KiB at a time between IO reads; sending all of it at each read
* made the whole of it again in the interpreter every time. */
int sent = 0;
if (appended && first == before) {

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.

Minor. When this tail write-back runs from rb_mere_string, that is, in the kept-struct case, rb_mere_string then returns the struct without fetching. The interpreter now has Ruby's prefix plus C's tail, but the struct still has the old prefix. With a probe that reads RSTRING_PTR(str)[5] after r->len = len + 4096, ruby sees 90 (Ruby's byte) and head sees 107. If C then writes any prefix byte, the next MR_STR_SET drops Ruby's byte (main does this too). Suggestion: have write_back say it sent MR_STR_CAT, and let rb_mere_string fall through to the fetch in that case.

@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 27c1e7c against current main 856e61b, including the mirror refresh/write-back paths, transit handling and interpreter dispatch. No new actionable correctness finding in the reviewed changes. The guarded append path retains full-write fallback when the prefix hash changes or the interpreter length disagrees, and the new contracts cover Ruby/C mutation, encoding, retained data and Fiber roots.

Independent validation: Clang syntax checks pass for mirror.c, core.c and api_fixture.c using the repository headers plus an existing generated mere_capi.h for the documented compiler ABI. The first syntax attempt lacked that generated dependency and failed; it was an incomplete local setup, not a source-code failure. The standalone ASan/UBSan test of the verbatim hash helpers subsequently completed: 111,576 prefix/full-hash and copy-hash comparisons passed, including block-boundary and 64-KiB-threshold cases. This tests the native helpers, not the complete interpreter crossing. No interpreter rebuild, full capi_check, corpus/VM sweep or independent Linux/macOS resource acceptance was completed here; the PR's runtime and performance figures remain author evidence.

Merge acceptance remains pending. In particular, preserve the reported macOS large-read peak increase (695 to 846 MiB) and the whole msgpack suite exceeding 2 GiB; this PR does not establish a repair for that original resource gate. Hosted Linux build is still running and macOS/reference jobs remain queued. The runner-queue exception does not cover running tests or missing downstream acceptance. No merge while the recorded hold_all_merges/new_failure_review_required is active. COMMENT because the authenticated account owns the PR.

…swers, numbers

MR_STR_CAT appends in place and keeps the String's cached answers; the
queue folded at every crossing (C fetches the String after each call into
Ruby), and the instructions saved are the ASCII answer kept, not the
queue. The record corrects the first version's claims and has the
numbers again: macOS instructions against main and against a build that
drops the answers, macOS peaks with GC_TIGHT and with the default
collector, Linux with the specs' seeds fixed.

@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 5fa7d70 (fix commits 3b143cd, 956a5b8, 5fa7d70). I built base (main 491cc5c) and this head from source with Mere 9dec2ff6, on macOS arm64, and built msgpack 1.8.7 for each. Reference: ruby 4.0.10. Base and head runs alternate.

Earlier findings

Major (2 MiB peak above main; the queue folded at every crossing): resolved. One small reporting point is left; see the new Minor below.

  • MR_STR_CAT now appends in place (sput h (sget h ++ t)) and keeps the cached answers through str_append_answers. The PR text now says the amortized-linear claim does not hold here, and that the speed-up comes from the ASCII answer. Both are accurate.
  • Default collector, ×100, 7 runs. Max RSS: base median 658 MB (558–706), head 510 MB (488–676). Peak footprint: base 649 MB, head 500 MB. Head is now lower.
  • Instructions: ×30 goes from 43.8G to 16.7G (−62%); ×200 from 289G to 107G (−63%).
  • With MERE_RUBY_GC_LOG=1, ×10 under GC_TIGHT, base and head run the same 79 collections, with the same largest counted size at a collection's start (62.4 MB) and the same largest String store after one (43.7 MB). So the interpreter's side is now the same as main's.

Minor (stale struct after a tail write-back in rb_mere_string): resolved, verified by running.

  • write_back answers 2 after MR_STR_CAT, and rb_mere_string then fetches the String instead of returning.
  • My probe extends cat_kept: C reads RSTRING_PTR(str)[5] after writing r->len (mode 1), then also writes byte 0 (mode 2). Head now prints exactly what ruby prints: C sees 90, byte 5 stays 90, byte 0 is C's. Base still prints 107 / 107.
  • The extended contract (seen == 90, getbyte(0) == 87) covers both steps.

New findings

Minor: under GC_TIGHT, my runs still put head above main, which contradicts the PR's table. All numbers are MiB (max RSS / peak footprint), alternating runs:

base head
×10, 2 runs 275 / 266, 275 / 266 329 / 319, 330 / 320
×30, 2 runs 333 / 349, 359 / 349 399 / 389, 399 / 390
×200, 2 runs 360 / 378, 428 / 418 410 / 401, 399 / 389

An earlier set of 3 runs per size (max RSS only) agrees: ×10 base 290 / head 346, ×30 base 367–377 / head 419, ×200 base 350–387 / head 419–430.

So at ×10 and ×30, head is 40–55 MiB (12–19%) above main, with no overlap between the runs. At ×200 the results are mixed. This is the opposite of the PR's GC_TIGHT ×30 row (main 373, head 350). The interpreter's collections are the same on both sides (see above), so the gap is outside the stores the collector counts. It also depends on how the run is set up. When the same loop is loaded from a wrapper script, vmmap shows head lower (peak footprint 265 MiB against 340 MiB). The default collector puts head lower too.

I don't think this needs a code change. Under the "worse than main" rule, though, it should be reported in the PR as a known exception, with numbers, rather than shown as head below main. Please re-measure the GC_TIGHT row, or add these runs next to it.

No other new findings. What I checked:

  • str_append_answers is the old block of str_push moved out unchanged, so str_push behaves as before. It still runs only after str_len y == 0 returns. The sget h in MR_STR_CAT folds any queued chunks and drops the queue before sput, so nothing queued is lost when sset is skipped.

  • I wrote a probe extension that appends chunks with rb_str_cat to a 70,000-byte String. After each piece, Ruby asks ascii_only?, valid_encoding?, length, index('é'), count('é') and the last bytes, so the cached answers are set before the next tail goes. Cases:

    • ASCII, then UTF-8, then ASCII;
    • an invalid \xFF, then ASCII;
    • a character split across two tails (x\xC3 | \xA9yyy);
    • UTF-8 first, then ASCII;
    • BINARY non-ASCII bytes.

    Each case runs with a UTF-8 receiver, a BINARY receiver, and one that Ruby switches between UTF-8 and BINARY at every step. Head's output is the same as ruby's in all 15 runs, and so is base's.

  • write_back restores the transit before it returns 2. mr_mirrors_flush ignores the answer, so the flush path does not change.

  • 3b143cd counts the tail as String bytes made. Main's MR_STR_SET counted nothing, so this can only make collections come earlier.

Tests and runs

  • capi_check.py on head: api 444/444 on both sides and under stress. The other five scripts agree too, and every negative control fails as it must. I did not see the api.rb:756 nogvl_stubborn flake. I ran the evaluator only, not --vm.
  • The author's updated local results are in the PR body and in loop/2026-11-28-capi-append-tail.md.

Not checked

Linux, --vm, the corpus, capi_spec, mkmf and the gem checks. I took these from the author's report.

CI at 5fa7d70

Linux build dependency controls, NKF Wasm engine and Runtime load path controls succeeded. CI, Gem suites, Small pure Ruby, Additional and Delegation/URI were still queued when I posted.

@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 70cbf09dde061fcfc8395d361bd6b016af8bab44: no new actionable correctness findings.

Earlier feedback:

  • The stale-struct issue is fixed: a tail write-back returns 2, restores transit, and makes rb_mere_string fetch the interpreter's bytes. The extended kept-struct contract now passes, including C reading Ruby's changed byte and making another write.
  • MR_STR_CAT now appends directly and preserves the two cached answers through the extracted helper; the former per-crossing queue is gone. The latest commit changes only the record relative to 5fa7d70e, adding the requested macOS GC_TIGHT counterexamples. This addresses the reporting request. The remaining unexplained resource difference is still an acceptance concern, not a demonstrated memory repair.

Independent validation on macOS arm64:

  • Built the prospective integration of exact head 70cbf09d with freshly fetched current main 0f0413c5dbe6e6f9b4d0ad975f4a32c3b77ccad6, without conflicts. Tested tree: 72fb9627a352736dcaab59d5bbafea2819cdad55. Fresh ordinary O2, pinned Mere 9dec2ff6, mgz 661a01d8, clean reference Ruby 4.0.10. The main control reuses the fresh O2 build made earlier in this review session, with its tracked inputs unchanged.
  • Full capi_check.py on both evaluator and --vm: all six contract scripts agree with the reference, including 444 API contracts, and hold under GC stress. All six negative controls fail as required. Original per-run 120-second / 2-GiB limits and process-family monitoring remain enabled; no limit events. Current main's evaluator reproduces the expected kept-struct failure at api.rb:921 in normal and stress runs.
  • An independent C extension exercised 15 ASCII/UTF-8/BINARY scenarios, including invalid bytes and a character split across tails. All match reference stdout/stderr/exit on the integration's evaluator and VM, both normally and under GC stress; main also matches the normal encoding controls.
  • String corpus 03, 293 and 524: 12/12 integration comparisons match reference stdout/stderr/exit across both engines and Hash index on/off; the 12 main controls also match. Source checks for roots, duplicate/dead definitions, method writes, ivar doors, names and regex captures pass; generated-C depth is 155 within 1024; whitespace passes.

The first bounded-harness attempt was stopped before contract execution because the sandbox denied ps; the reported runs used the authorized escalation with the original monitor, rather than treating that restriction as a program failure.

I did not rerun Linux, the whole corpus, full msgpack suites or the macOS RSS benchmarks. Preserve the prior resource observations and original limits. Hosted Linux build is still running; macOS/reference jobs and downstream acceptance remain pending. The recorded hold_all_merges / new_failure_review_required still prevents merging, including already-reviewed candidates. COMMENT records verification, not merge acceptance.

@284km
284km merged commit a56107b into main Nov 28, 2026
11 of 20 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