Skip to content

C API: a big String C makes empty is made in its struct - #390

Merged
284km merged 1 commit into
mainfrom
capi-lazy-zeroed
Nov 27, 2026
Merged

284km merged 1 commit into
mainfrom
capi-lazy-zeroed

Conversation

@284km

@284km 284km commented Nov 27, 2026

Copy link
Copy Markdown
Owner

After #386, msgpack's packer spec still peaked at 1.6–2.1 GB on Linux (ruby: 0.37 GB), and the whole suite at 2.5–3.2 GB. The memory at the peak was big Strings living in several copies at once. This removes two of the copies for the String C makes empty and then writes.

What was at the peak

The RSS was read at each step of the packer callbacks (Linux, after #386):

  • Each 6 MB String written. Ruby grows by 6 MB, mere-ruby by 23 MB. msgpack keeps a big String by reference: it calls rb_str_dup and uses the dup's RSTRING_PTR. Here that is the String, the dup's copy in the interpreter and the dup's struct. CRuby's dup shares the bytes. That is left for later.
  • Each return from a nested level. Ruby grows by about 6 MB, mere-ruby by 100–300 MB. The recursive packer turns each level's whole buffer into one String with msgpack_buffer_all_as_string: rb_str_new(NULL, n), then a write through RSTRING_PTR. On mere-ruby those bytes lived four times over:
    • zeroed in transit;
    • a String of zeros in the interpreter;
    • fetched back into the struct and written there;
    • written back into a new String in the interpreter.

What changed

rb_str_new(NULL, n) with n of 64 KiB or more (string.c make) now calls mr_string_new_zeroed (mirror.c):

  • The interpreter makes an empty String.
  • The n zero bytes are made in the struct's own buffer, where C is about to write them.
  • The struct is watched (touch). Its hash is not the hash of what the interpreter has.

So at the next crossing the bytes go to the interpreter as any write C makes does. mr_up flushes the watched structs before every request that is not a read, and at the end of the call, so Ruby never sees the String empty. That leaves two copies, the struct and the interpreter's String, where there were four.

Smaller Strings are made as before. The only change for them is one comparison.

Checked

Mere 9dec2ff6, reference ruby 4.0.10. The RSS and instruction figures were taken on #386's head (d10fa18) + this change, before main moved; the checks below were run again on main (7fd8c47) + this change.

Linux (docker, Debian, ruby:4.0.10, clang 19, aarch64). Peak RSS from GNU time, three rounds each:

packer example peak whole suite peak suite time
main (c913da2) 1,589 / 1,831 / 2,140 MB 2,572 / 3,350 / 3,618 MB 122.9 / 129.7 / 131.5 s
#386 1,589 / 1,917 / 2,026 MB 2,458 / 2,756 / 3,219 MB 116.7 / 122.3 / 129.8 s
this 1,448 / 1,537 / 1,663 MB 2,495 / 2,554 / 2,615 MB 105.7 / 108.5 / 108.9 s

macOS, the packer example on the evaluator: it ends at 593 / 618 MB (#386: 829–868 MB).

  • Small Strings (macOS, instructions of the loop alone with start-up subtracted, median of three, alternating with C API: map and unmap big buffers instead of leaving them in malloc's cache #386's build):
    • to_s of 100 B ×100,000: +0.11%
    • Unpacker#feed 100 B ×100,000: +0.14%
    • 1 in 16 of 200 B ×100,000: +0.16%
    • to_s of 4,000 B ×50,000: +0.66%. That is +0.3% of the whole run, the same in all three runs. The small path gains one comparison, so the rest is the code's layout.
  • capi_check. On the evaluator and with --vm, 426 contracts pass on both sides, also under collection stress, and each negative control fails. The new contracts:
    • C writes the first half of a big rb_str_new(NULL, n), Ruby reads it, C writes the second half, and Ruby reads both.
    • The same, then rb_str_resize to a quarter, rb_str_set_len and rb_str_modify, each with a write after it.
    • A data object holds one alone, marked by its dmark, across collections.
    • A stopped Fiber holds one across a collection.
    • Twelve are made in a row, with collections between them.
  • A build that does not watch the new struct (so its bytes never reach the interpreter) fails these contracts.
  • The eleven corpus programs that use a native extension match ruby under MERE_RUBY_GC_STRESS=1 on the evaluator and on the VM.
  • run_corpus.sh --both: the gates, then 1029/1029 with the hash index on and off. MERE_RUBY_VM=1 run_corpus.sh --both: 1029/1029.
  • 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.

Left

  • Sharing the bytes of rb_str_dup / rb_str_new_frozen for big Strings. That is the +17 MB per write above.
  • The write-back still passes through transit. The bytes are in transit once more while they are sent.
  • The whole suite still peaks at about 2.5 GB on Linux, over CI's 2 GiB. This example is not the only part of it.

The record is loop/2026-11-28-capi-lazy-zeroed.md.

🤖 Generated with Claude Code

rb_str_new(NULL, n) with n of 64 KiB or more (string.c make) now calls
mr_string_new_zeroed (mirror.c): the interpreter makes an empty String,
the n zero bytes are made in the struct's own buffer where C is about
to write them, and the struct is watched with a hash that is not the
interpreter's. At the next crossing the bytes go to the interpreter as
any write C makes does, and mr_up flushes watched structs before every
request that is not a read, so Ruby never sees the String empty.

msgpack's recursive packer builds each level's String this way; its
bytes lived four times over (transit, a String of zeros, the struct,
the written-back String) and now live twice. On Linux the packer
example peaks at 1.4-1.7 GB (from 1.6-2.0 GB) and the whole suite at
2.5-2.6 GB (from 2.5-3.2 GB), 10-20 s faster. Small Strings gain one
comparison.

New capi_check contracts: writes on both sides of a read, then
rb_str_resize, rb_str_set_len and rb_str_modify; a data object's dmark
holding one across collections; a stopped Fiber holding one; twelve in
a row with collections between. The record is
loop/2026-11-28-capi-lazy-zeroed.md.

@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 dedcb47a5dc86559428da8b9eb4f060f27d9b55e against fetched current main ad5fe0e13de26cc0673b5f8c9d0f87012f07bccb, including the surrounding mirror, transit, encoding, GC and Fiber code. Existing reviews, discussion and review threads were empty; no tracked AGENTS.md or CLAUDE.md was found. No actionable code findings.

The new path retains the existing mirror buffer ownership and crossing/return write-back mechanism. Registering the newly created mirror with touch is essential, including when C returns the String without asking for its pointer. The added two-stage writes, resize/set-length/modify, marked-holder and suspended-Fiber contracts cover the important synchronization and lifetime cases.

Independent validation on Darwin arm64, using fresh ordinary O2 builds with pinned Mere 9dec2ff6 and all 18 imported mgz files checked against 661a01d8:

  • Built this exact head and a clean prospective integration with current main (tree 491f8a9a35d68e89b7269d52ab89225b2bec5baf). No existing interpreter binary was reused.
  • On the integration, complete capi_check.py runs passed on the evaluator and with --vm: all six contract groups agree with pinned Ruby 4.0.10/source a704b7cd, hold under GC stress, and all six negative controls fail as required in each engine. The API group passes 426 contracts.
  • On the exact PR head, the 426 API contracts also pass on both engines, normally and with MERE_RUBY_GC_STRESS=1.
  • A separate shared C fixture passes 96 boundary contracts against reference Ruby and in each of eight head/integration × evaluator/VM × normal/stress configurations: sizes immediately around 64 KiB and 1 MiB, five encodings including UTF-16LE/UTF-32BE, terminators, untouched return values, GC between pointer acquisition and writing, shrinking and appending.
  • GC-root, diff-whitespace and emitted-C depth checks pass (155/1024). Original 120-second / 2 GiB process-family limits were retained, with no limit events. The sandbox denied the supervisor's ps; authorized elevated execution succeeded. That restriction is not an application failure.

I did not independently rerun the full corpus, original CRuby files, msgpack suite/RSS measurements, instruction benchmarks or Linux resource acceptance. The note correctly retains the whole-suite Linux peak above CI's 2 GiB bound; these focused passes do not establish a memory-limit repair.

At the recorded CI inspection, hosted coverage remained incomplete. The PR's Linux C API step succeeded, but its Linux job is executing network checks, macOS is building, and reference/downstream coverage is unfinished. Current-main CI 46063902634 has executing Linux corpus/reference work and queued downstream coverage; this is not solely unassigned-runner queueing. No merge: recorded hold_all_merges / new_failure_review_required remain active, and no historical failure or original bound is waived. Previously reviewed open candidates were also considered: #373/#383 retain Major findings, #245 is draft, and #256/#385/#388 remain subject to the recorded holds and integration/acceptance requirements. COMMENT because the authenticated account owns the 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.

Review of dedcb47a. No Critical/Major/Minor findings. rb_str_new(NULL, len) of 64 KiB or more now makes an empty interpreter String and the zero bytes in the C struct only, marked as written (hash xor 1), so the bytes reach the interpreter once, at the next crossing after C has filled them. That replaces four copies of each recursive-packer level. The contract adds the create-write-read and resize paths, and capi_check (426/426 on both sides, also under stress), spec, mkmf, gems and headers pass on main. The small-String cost (+0.1% to +0.7%, from one added comparison) is small and recorded, and I accept it. The suite still peaks at about 2.5 GB on Linux, as the description says. The test merge with current main is clean. I will merge once the review bot has reviewed this head.

@284km
284km merged commit f09341c into main Nov 27, 2026
14 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