Skip to content

C API: a String's bytes go straight into its struct, the safepoint is counted in C, and three calls stop being sends - #284

Merged
284km merged 4 commits into
mainfrom
capi-xfer-cost
Nov 25, 2026
Merged

284km merged 4 commits into
mainfrom
capi-xfer-cost

Conversation

@284km

@284km 284km commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

This lowers what a crossing between C and the interpreter costs: a String's bytes handed to C, the C API's safepoint, and three calls that sqlite3 makes for every row.

What changes

  • A String's bytes go straight into its struct.
    • When C reads a String (RSTRING_PTR), the interpreter now hands over its own String's bytes and length (mr_capi_give_str).
    • C copies them into the mirror while the request runs, comparing and hashing in the same pass (capi/mirror.c str_take / copy_hash).
    • Before, the bytes were copied three times: by bytes_of_str, into the transit buffer, and into the mirror. Then they were hashed separately.
    • The hash now uses four lanes past 32 bytes. Under 32 bytes it is the old single-lane hash.
    • body_hash is always_inline in write_back. The review found it was an out-of-line call there; this is fixed and checked in the binary.
  • The safepoint is counted in C.
    • The interpreter's answer to MR_SAFEPOINT is how many safepoints to pass over: 31, or 16 * N - 1 under MERE_RUBY_GC_STRESS=N.
    • Only the safepoints it is asked at decide whether to collect.
  • Only what is live in transit is saved. Before, a write-back or a safepoint also copied bytes an earlier request had already read: join_in_c copied its 64 KB String at every safepoint after it.
  • rb_obj_freeze, rb_ary_store and rb_enc_default_internal make no method call, as in CRuby:
    • rb_obj_freeze of a String, an Array or a Hash sets the flag (MR_FREEZE).
    • rb_ary_store at the end of an Array that is not frozen appends (MR_ARY_APPEND).
    • Anything else is still a method call, so the errors are ruby's own.
    • rb_enc_default_internal reads a C variable that Encoding.default_internal= writes.
  • capi/check contracts (api: 320 → 334 on the branch, 374 after merging main with Read C API frozen state without Ruby callbacks #278):
    • What C was lent (the RSTRING_PTR pointer and its bytes) and what it holds only in its locals stays put across collections in the middle of one call. This holds on both sides and under GC stress.
    • rb_ary_store and rb_obj_freeze are checked in every case.
    • So is default_internal as C reads it.
  • Read C API frozen state without Ruby callbacks #278: merged main with it. I checked that a freeze from Ruby followed by a read from C still shows the object frozen. MR_FREEZE is not a read-only request, so it advances the epoch, and rb_obj_freeze forgets the mirror's header.

Measured

  • Base is main 5276535, new is this branch; both built with mere 9dec2ff6 at -O2.
  • Each figure is the median of 3 runs, base and new alternately, using /usr/bin/time -l instructions retired.
  • Load average was 10 to 18.
base new
MiniSSL write_nonblock loop, 8 MiB 25.78 G 22.33 G (-13%)
...time inside write_nonblock 1.86 s 0.52 s
sqlite3 execute("select 1") x 5000 9.12 G 8.73 G (-4%)
sqlite3 prepared reset!; step x 30000 9.42 G 7.97 G (-15%)
join_in_c(3000), GC.disable (#267's suggestion) 2.18 G, 0.28 s 1.88 G, 0.14 s
hold_locals(20000), GC.disable (after the inlining) 28.42 G, 1.89 s 29.38 G, 1.58 s
capi/check api.rb, GC_STRESS=1 242.1 G 243.8 G
typeddata / ensure / fiber / numeric, GC_STRESS=1 33.30 / 34.33 / 5.48 / 2.52 G 33.37 / 34.29 / 5.49 / 2.52 G

hold_locals against main, after the inlining (median of 3, alternately):

N main this PR
5000 2.765 G 2.771 G +0.2%
10000 7.833 G 8.011 G +2.3%
20000 28.415 G 29.379 G +3.4%

The extra still grows with N squared: about 2.4 instructions per check of a touched String (the n < 32 test). Before the fix it was about 5.5.

Max RSS with MERE_RUBY_GC_TIGHT=1 (the scripts' data are fixed):

base new
MiniSSL 8 MiB 569.9 MB 552.5 MB
sqlite3 execute 130.5 MB 135.1 MB
sqlite3 step 125.8 MB 125.7 MB
5000 rows built by C 87.0 MB 86.2 MB

api.rb's peak varies from run to run on both builds (it starts threads): 179 / 179 / 206 MB on base, 193 / 209 / 193 MB here. Its collection-heavy contracts run alone are the same within 0.5 MB.

Ruby 4.0.10 on the same scripts takes 0.0033 ms per execute and 0.0002 ms per step, and the 8 MiB loop takes 0.02 s.

Checked

All checks ran on the merged build (2a1327d = this branch + main 779c7cc) against ruby 4.0.10.

  • run_corpus.sh --both: the gates, then 939/939 with the hash index on and off.
  • MERE_RUBY_VM=1 run_corpus.sh --both: 939/939, the same.
  • capi_check: the contracts agree on both sides (api 374), they hold under collection stress, and each negative control fails.
  • capi_spec_check: the reference passes what is recorded, and mere-ruby passes no less (2420 of 2602).
  • capi_mkmf_check: passes.
  • ruby/test_encoding.rb and ruby/test_m17n.rb, run on main's build and on this PR, each on the evaluator and with MERE_RUBY_VM=1: all four give 142 tests, MATCH 141, BOTH 1, RED 0.
  • capi_check on the VM: api.rb stops at line 596 (errinfo after a Ruby rescue). The review found main stopping there too, so it is an existing gap.
  • After the inlining: capi_check again. The contracts agree on both sides, hold under collection stress, and each negative control fails. The change is an inline attribute only, so I did not rerun the corpus for it.
  • capi_gem_check, with capi_gem_check: an install's make runs one compiler at a time #281's --build-jobs 1: all seventeen gems install and give the same output on both sides (173 lines), and the other-ruby control fails.

Left

See loop/2026-11-25-capi-xfer-cost.md.

  • The MiniSSL loop is still quadratic. Of the 16 MiB run's 7.9 s, 3.8 s is byteslice copying the tail it returns (ruby shares it).
  • Every crossing re-hashes every String the call has touched. This is quadratic in a call that reads many Strings, and it is the same on main.
  • With this PR, each check costs about 2.4 more instructions: hold_locals(20000) uses 3.4% more instructions and takes 16% less time.
  • str_take on the collector's reader path could call rb_memerror during a mark, but only if memory runs out (the review's suggestion; recorded).
  • sqlite3's execute is mostly its own Ruby code: the C API is about a quarter of it.
  • A data object's header is asked for again at every call (MR_DESCRIBE, 9% of a step).

🤖 Generated with Claude Code

… counted in C, and rb_obj_freeze / rb_ary_store / default_internal make no call

MR_STR_GET's bytes are the interpreter's own String, copied into the mirror
while the request runs, compared and hashed in the same pass (four lanes past
32 bytes); bytes_of_str's copy and the transit buffer's are gone. C counts the
safepoints and asks every 32nd (16*N-th under stress); only what is live in
transit is set aside. rb_obj_freeze of a String/Array/Hash and rb_ary_store at
an Array's end are answered without a method call, as CRuby's are, and
rb_enc_default_internal reads a variable Encoding.default_internal= writes.
capi/check: what C was lent and holds in locals across collections in one
call; rb_ary_store, rb_obj_freeze and default_internal from C.

@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 ec35b15e against current main d2630809. I found no new actionable issues in the diff. The direct String transfer remains request-scoped, and the added pointer-lifetime and builtin-operation contracts provide useful coverage.

Independent validation on macOS arm64, using fresh ordinary O2 builds, pinned Mere 9dec2ff687a08433247dbdb7729bc19c8522e538, mgz 661a01d8, and reference CRuby 4.0.10 (a704b7cd):

  • The unchanged capi_check.py runner passes against both the PR head and current main with the PR's contract sources: ensure 58, TypedData 115, loader 48 reference / 49 mere-ruby, numeric 13, fiber 16, and API 374. All six suites also pass under GC stress; all six negative controls fail as intended. Original 120-second / 2-GiB per-run limits were preserved.
  • Twenty additional String length/buffer boundaries, C writes after freeze, row construction, and default-internal encoding updates agree on reference/main/head, including stress on both mere-ruby builds.
  • A standalone probe extracted from the new copy/hash functions passes 20,480 cases under ASan and UBSan.
  • GC-root, dead-definition, and generated-C nesting checks pass (155 / 1024).

The sandbox initially blocked the test supervisor's ps inspection before contracts ran; validation above is from the approved reruns. I did not repeat the full corpus, native-gem matrix, or Linux resource acceptance. Hosted Linux build is still running and macOS/core downstream coverage remains pending. This review does not clear the policy's recorded all-merge hold, including the previously failed main Linux C API job; no merge was attempted.

@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 ec35b15 (first review of this PR). Mostly checked by running the PR's binary and main's binary; some points by reading only (marked).

"Main" below is a build of main d586947. That commit contains #278 (779c7cc) and is close to what this branch merged. Reference is ruby 4.0.10.

Findings

Minor: hold_locals(20000) +8% is a new cost per check, not main's cost moved.

  • main has the same quadratic. Net of startup, main's instructions grow about 4x for each doubling of N: 1.77 → 6.83 → 27.36 G for N = 5000 / 10000 / 20000.
  • The PR's extra instructions grow the same way: +0.10 → +0.49 → +2.19 G. So the extra is a cost added to each step of the quadratic. It is not a fixed cost, and it is not main's cost moved somewhere else.
  • The cause is in the binary. On main, write_back has the short hash inlined. On this PR, write_back calls an out-of-line body_hash, which then branches on n < 32. You can see this with nm / otool -tV -p _write_back. This happens 2 x 20000² / 2 ≈ 4e8 times (one write_back per touched String per flush), and 2.19 G / 4e8 ≈ 5.5 instructions per check: about the cost of a call, a prologue and a compare.
  • The loop record says the short hash is "inlined where write_back uses it, as before". The built binary does not do that.
  • Suggested fix: mark body_hash static inline __attribute__((always_inline)), or test len < 32 in write_back and call hash_short there. Then measure hold_locals again. Our merge rule says a result worse than main must be fixed in the PR. This is a new cost, so the rule applies.
  • Wall time does go down (1.80 → 1.50 s). Fewer safepoint round trips more than pay for it. The instruction count still goes up.

Suggestion: an error inside str_take now unwinds through the interpreter's frames (reading only).

  • str_take runs while the interpreter is still answering MR_STR_GET. That is inside capi_up, and on the collector's reader path it is in the middle of marking.
  • string_room can call rb_memerror() (malloc failed) or rb_raise ("string size too big").
  • Before this PR, that code ran after mr_up had returned, so only C frames were between it and the guard. Now the longjmp would cross the interpreter's frames, or a collection in progress.
  • This only happens when memory runs out, so it is not a blocker. A small fix: allocate the room in rb_mere_string before the request, or let str_take record the failure and raise after mr_up returns.

No Critical or Major findings.

What I checked

Correctness and GC safety (running). I wrote a probe extension with 60+ cases. It was built against ruby 4.0.10's headers and against capi/include. I ran it on the reference, the PR and main, in the evaluator, with MERE_RUBY_VM=1, with MERE_RUBY_GC_STRESS=1, and with both. All outputs are identical to ruby's. The cases:

  • Binary Strings with NUL and 0xFF bytes at lengths 3 / 31 / 32 / 33 / 80 / 1000, read through RSTRING_PTR.
  • C reads, Ruby changes one byte (first, middle, last) at lengths 5 to 1000, C reads again. This tests the "same length, different bytes" path of copy_hash across the 32-byte block boundary. Terminators were checked too.
  • Ruby grows, shrinks or replaces the String between the two reads. UTF-16LE and UTF-32LE, including the terminator.
  • C writes a byte and Ruby reads it in a block. Then Ruby writes the old byte back and C must see it. A write through a stale pointer after a crossing.
  • rb_str_resize (shrink and grow), rb_str_modify_expand + rb_str_set_len, and rb_str_modify on: a frozen String, a shared substring (a[1..]), a dup and a chilled literal.
  • Freeze from Ruby seen by C: OBJ_FROZEN after a block freezes it, then rb_str_modify raises FrozenError. Corpus 1020 also matches ruby in the evaluator, the VM and under stress.
  • rb_obj_freeze (MR_FREEZE) on: a chilled literal, an object with a singleton class (then def s.x → FrozenError), an Array with ivars, a Hash during each, String and Hash subclasses that override #freeze (not called), a plain Object, and a String C holds RSTRING_PTR of (the pointer is unchanged after the freeze, also with capacity:).
  • rb_ary_store (MR_ARY_APPEND) on: an Array with a singleton []=, a subclass whose []= raises, a shared slice (the source is not changed), a dup, a frozen Array (same FrozenError), a store during each, and a store followed by RARRAY_LEN / RARRAY_AREF.
  • rb_enc_default_internal after Encoding.default_internal= through =, send, public_send, method(...).call, a bad name (ArgumentError, value unchanged), nil, and -U on the command line. sqlite3 2.10.2 returns TEXT transcoded to ISO-8859-1 after Encoding.default_internal = 'ISO-8859-1', the same as main.
  • A pointer C borrowed and kept across 3000 crossings with collections: same pointer, same bytes, and the Strings held only in C's locals are intact.

tools/capi_check.py (running). Run from a scratch copy of the head tree against a clean ruby 4.0.10 source tree:

  • Evaluator: every contract agrees (api 374, typeddata 115, ensure 58, loader 48 on the reference and 49 on mere-ruby, as on main; numeric 13, fiber 16), they all pass under stress, and all six negative controls fail.
  • MERE_RUBY_VM=1 (through a wrapper, because capi_check drops MERE_RUBY_*): api.rb stops at the errinfo check after a Ruby rescue (the check(A.errinfo_now.nil?) after raise "E2"). Main's binary fails at the same contract with main's api.rb. With check made non-fatal, both binaries fail the same 4 errinfo lines and pass the rest, including this PR's new contracts, with and without stress. So this is a VM gap that predates this PR. It is not caused by this PR.

Performance (running). Instructions retired from /usr/bin/time -l, median of 3, main and PR run in turn. Load average was about 10.

main PR
join_in_c(3000), GC.disable 2.184 G, 0.38 s 1.882 G, 0.23 s
hold_locals(5000), GC.disable 2.778 G 2.874 G (+3.5%)
hold_locals(10000) 7.836 G 8.329 G (+6.3%)
hold_locals(20000) 28.366 G, 1.80 s 30.554 G, 1.50 s (+7.7%)
sqlite3 require + open only 3.457 G 3.451 G
sqlite3 prepared reset!; step x 30000 (3 columns, one TEXT) 10.771 G 8.060 G (-25%)

The join_in_c and hold_locals(20000) numbers match the author's. My step script freezes and stores one more TEXT value per row, so its gain is larger than the author's -15%. I did not have a puma/MiniSSL install, so I did not measure MiniSSL.

Memory (running), MERE_RUBY_GC_TIGHT=1, deterministic scripts, 3 runs each:

  • sqlite3 step x 30000: main 129.7 / 129.7 / 129.8 MB, PR 128.1 / 130.8 / 131.9 MB. No real difference.
  • C reading 400 Strings of 1 MiB, with a change between reads and GC on: main 361.7 / 389.4 / 405.0 MB, PR 312.2 / 314.8 / 309.7 MB. The PR is lower, and uses about 7% fewer instructions.

Merge. git merge-tree --write-tree origin/main origin/pr284 is clean against main d263080.

Bot inline comments. None on this PR.

Local results in the description

Present: run_corpus.sh --both (gates, then 939/939 with the hash index on and off), MERE_RUBY_VM=1 run_corpus.sh --both (939/939), capi_check, capi_spec_check (2420 of 2602, no less than recorded), capi_mkmf_check and capi_gem_check (17 gems, 173 lines, other-ruby control fails).

Not listed: any unit test file. One would fit the interpreter-side change to Encoding.default_internal=, for example test/ruby/test_encoding.rb or test_m17n. I did not run these. I only ran corpus 257, 339, 446, 722, 1018 and 1020 against ruby (evaluator and VM, all match). The capi_check run in the description is presumably the evaluator only. The VM run fails on main too, as shown above.

Not checked

  • MiniSSL / puma numbers (no install here).
  • A full corpus (other runs were using this machine).
  • Unit test files.
  • sqlite3 under MERE_RUBY_GC_STRESS=1: loading the gem under stress did not finish within my 280 to 300 s limit on either build, so I did not compare it.

CI

For ec35b15, two workflows have passed (NKF Wasm engine, Linux build dependency controls). CI and the gem-suite workflows were still queued when I posted this.

Merge criteria: not met yet. The Minor finding is open (hold_locals instructions are worse than main), and CI has not finished.

Comment thread capi/mirror.c
for (; i + 32 <= n; i += 32) hash_block(&h, s + i);
return hash_end(&h, s + i, n - i);
}
static inline __attribute__((always_inline)) uint64_t hash_bytes(const void *p, size_t n, uint64_t seed) {

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: in the built binary this does not reach write_back. body_hash (unchanged, not always_inline) is now an out-of-line function, and write_back calls it (bl _body_hash). On main the short hash was inlined into write_back. The flush calls this once per touched String per crossing, so the extra call and the n < 32 branch cost about 5.5 instructions in each step of the quadratic. That is the whole hold_locals +8% (+0.10 / +0.49 / +2.19 G at N = 5k / 10k / 20k, the same growth as the quadratic). Marking body_hash static inline __attribute__((always_inline)), or testing len < 32 in write_back, should bring it back to main's count.

Comment thread capi/mirror.c
m->as.string.as.heap.ptr = NULL;
m->as.string.as.heap.aux.capa = 0;
}
string_room(m, len > m->reserve ? len : m->reserve, term, m->heap_only ? ROOM_HEAP : ROOM_EXACT);

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: str_take now runs inside the interpreter's answer to MR_STR_GET. On the collector's reader path, that is during marking. string_room can rb_memerror() / rb_raise. Before this PR, that ran after mr_up had returned. Now the longjmp would cross the interpreter's frames. It only happens when memory runs out. Still, making the room before the request, or raising after mr_up returns, would keep the old property that only C frames are unwound.

It was an out-of-line call with the length tested again inside: about 5.5
instructions more per check of a touched String, quadratic in hold_locals.
Now 2.4 (the n < 32 test). Record: hold_locals against main, test_encoding
and test_m17n on both executions, the VM's api.rb gap, str_take under OOM.

@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 5b85254.

  • Minor (hold_locals +7.7%): mostly resolved. body_hash is now always_inline, and the author confirmed in the binary that write_back no longer calls it. hold_locals, main → PR, instructions: N=5000 +0.2%, 10000 +2.3%, 20000 +3.4% (was +7.7%), about 2.4 instructions per check (was about 5.5), which is the n < 32 test itself. Wall time at N=20000 is better than main (1.89 → 1.58 s), and the crossings this PR targets are much cheaper (sqlite3 step −25%, join_in_c −14%, lower max RSS when reading large Strings). I accept the remaining per-check cost on this stress contract as the price of the new path; it is recorded in the description.
  • The missing related tests are posted: test_encoding and test_m17n, main and this PR, evaluator and VM: 142 tests, MATCH 141 / BOTH 1 / RED 0 in all four.
  • capi_check on the VM stops at api.rb's errinfo contract on main too; it is recorded as a pre-existing VM gap. capi_check was re-run after the inline change and passes.
  • The OOM longjmp from str_take during a reader callback is recorded under Left.
  • git merge-tree against current main: clean. No mere-pr-review-watch inline comments.

Merging.

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