Repository navigation
Native gems round 3: puma 8.1.2's own suite - #267
Conversation
…w of a Hash subclass, child stdio blocking
- RbConfig configure_args says --with-openssl-dir=<prefix> when the build
named an OpenSSL directory, so an extension's dir_config('openssl') finds
it: puma's MiniSSL is built (capi/check/mkmf.rb has the contract)
- super from a def self.new of a Hash, Array or String subclass is the class
dispatch's construction, backed by the builtin's storage (corpus 909)
- a spawned child's fds 0, 1 and 2 are cleared of O_NONBLOCK before it
starts, as ruby's child does before exec (corpus 910)
kill(1) read `kill -s KILL -123` as a second signal, so a group that was there answered ESRCH and its members ran on; `--` now goes before the pid. puma's integration helper stops an unresponsive server by its group. corpus 911.
… into a frozen String - mr_up sends MR_SAFEPOINT before a String's bytes are fetched, a call and a new String, with the transit set aside; capi_up answers it with gc_point_capi (under GC stress, every 16*N-th). A C call that only calls back through the C API was never collected in. - each request runs in a region of its own: what it made went to the region of the statement that called C, open for the whole call. puma's HTTP parser on 12 x 1024 headers: 5.4 GB peak, now 276 MB. - the write-back of what C wrote through RSTRING_PTR changes a frozen String's bytes, as in ruby; it raised FrozenError (puma's parser upcases header names in the request it is given). - capi/check/api.rb: join_in_c, hold_locals (C locals across allocating requests, also paused in a Fiber), write_frozen.
Delivery tested in_thread (), which every method call clears for its body, so a thread inside a method read as the main one: puma's TERM trap ran on its reactor thread. Delivery now asks sig_off_main (under the scheduler, a thread that is not sch_main), a join is one of the waits a signal wakes, and sch_join runs the waiting trap before it joins on. corpus 912.
Traps run on the main thread, and only the scheduler's idle wait woke it for one; a thread that took the signal at a statement left it queued. In a process whose threads never all wait -- a puma worker serving requests, its main thread joining the server thread -- the trap never ran, and a mold promotion's URG was lost. sig_poll now wakes the main thread when it waits in a wait a trap may interrupt.
…dable A cluster's workers accept on one listener; a connection another worker took makes accept(2) say EAGAIN, a client gone before it was taken ECONNABORTED. tcp_accept folds errno into three codes and every refusal was SocketError "accept failed", which puma logged as a Listen loop error. accept now goes through mr_sock_accept (-errno) and answers as ext/socket/init.c does, for TCPServer, UNIXServer and Socket.
…er process took the connection
284km
left a comment
There was a problem hiding this comment.
First review of a542e52. Summary: one Major finding (Linux only), two Suggestions. Everything else I probed matches ruby 4.0.10.
Findings
Major: Process.kill(0, pid) breaks on Linux. See the inline comment. The new -- is fine for bash, but Linux /bin/sh is dash. In dash, kill -0 -- PID fails with "Illegal number: -". The same happens for a numbered signal that has no name (kill -34 -- PID). Then ps -p finds the process, so mere-ruby raises Errno::EPERM where ruby returns 1. For a negative pid it raises Errno::ESRCH. Corpus 911 line 8 (Process.kill(0, -pid)) takes this path. So I expect the Linux corpus job ("Compare every corpus program on Linux") to fail on it. I checked the shell commands in dash on macOS and in ubuntu:24.04 (exit 2). kill -s 0 -- PID works in dash and in bash. I did not run a Linux mere-ruby build.
Suggestion: the C API safepoint costs every request something, even when no collection is due. Before each String fetch, call and new String, mr_up saves the transit buffers (a malloc and a copy of the bytes in transit) and makes one extra up-call. I timed ApiFixture.join_in_c(3000) from the PR's fixture, which makes a 64 KB String each turn, with GC.disable. main 2e402b9 took 0.16–0.21 s. This branch took 0.29–0.37 s. That is 3 runs each, at load average about 28. hold_locals(20000) (4 KB Strings) was about the same on both builds. A cheap check on the C side ("is a collection due?") before the save would remove most of this. This does not block. The memory bound is worth it.
Suggestion (not a regression): super from a new defined in a module still makes a plain object. Two cases: a builtin subclass that extends the module, or one that prepends it to its singleton class. Example: module M; def new(*a) = super; end; class A1 < Array; extend M; end; A1.new(2, :q). ruby gives [:q, :q]. This branch and main both give #<A1:0x...>. The same happens for a String subclass with a prepended new. Those calls go through super_native_or_missing, not super_cls_new. A follow-up is fine.
What I ran
I compared ruby 4.0.10, this branch (evaluator and MERE_RUBY_VM=1) and main 2e402b9 (no PR). The PR binary was built after the head commit, and its tree was clean.
- Corpus 909–912, 916 and 917: this branch matches ruby in both modes. main differs on all six.
- Traps, with a trap during each of these:
sleep,joinon a busy thread,Queue#pop(also with a busy thread),IO.select, a ConditionVariable wait, and a Fiber that sleeps on the main thread. I also tried two signals in a row (self and from a thread), a trap that raises (in sleep and in join),Process.killsent from a thread inside a method, and"IGNORE"/"DEFAULT". All match ruby in both modes, andThread.current == Thread.mainis true in every trap. main runs the trap off the main thread in three of these cases. A trap does not cutsleepshort. - accept:
accept_nonblock(exception: false)returns:wait_readablefor TCPServer, UNIXServer and Socket. The exception form raisesIO::EAGAINWaitReadable(anIO::WaitReadable).accept,sysaccept, accept afterclose(IOError), and a blocking accept in a thread while other threads run: all match. The blocking path retries only after__wait_readable, so a lost race waits again and does not spin. I checked the errno mapping againstext/socket/init.cby reading: EAGAIN givesIO::EAGAINWaitReadable, ECONNABORTED/EPROTO give their Errno extended withIO::WaitReadable, and the blocking path raises ECONNABORTED. I did not produce ECONNABORTED or EMFILE for real. superinself.new: Hash, Array and String subclasses, each with its owninitialize.initializeruns once each time. Block, keywords andcapacity:are passed through. An override chain (H2 < H1, both withself.new), a sub-subclass,supercalled twice,initializethat raises followed by a normalnew(the skip flag does not leak), and a nested builtin subclass made insideinitialize: all match ruby. Set, Exception and plain-class subclasses behave as on main and match ruby.Process.kill: on macOS, a negative pid with 0, a name, a Symbol and a number; ESRCH after the group is gone; ArgumentError for a bad name. All match ruby. main raised ESRCH forkill("CONT", -pgid).- Frozen String: none of nine Ruby-level ways to change a frozen String gets through (
<<,setbyte,replace,upcase!,force_encoding,read/readpartialinto it,clear,pack(buffer:)). All raise FrozenError, as on main and in ruby. - Child stdio: a 300 KB child write through
out:,[:out, :err] =>,1 => fdandSTDOUT =>redirects. The whole output arrives, as in ruby. main stops at 64 KB. tools/capi_check.pyon this binary, from the PR tree: the contracts agree on both sides, they hold under stress (hold_locals,join_in_c,write_frozenincluded), and every negative control fails.git merge-tree --write-tree origin/main origin/pr267is clean.
What I checked by reading
- Frozen write-back: op 3 (MR_STR_SET) is sent only by
write_backincapi/mirror.c, which writes back what C put throughRSTRING_PTR. The C functions that change a String go throughrb_str_modify(or a Ruby method), and both still refuse a frozen String. So Ruby code cannot use this to change a frozen String. - GC safety at
MR_SAFEPOINT: the roots are the registered addresses and objects, plus the C stack betweencapi_baseand the current depth. That is the same root set as for a collection that runs inside a Ruby method that C calls. The values a request puts in transit (words) are not roots during the safepoint. Its receiver and block aremr_uparguments, so they are on the stack. The arguments ofrb_funcallvare rooted only by the caller's ownargv, which is the same rule ruby has for a heap-allocatedargv. I found no case that this rule does not cover. - The region per up-call frees the bytes copied for a request when the request ends. C gets its own copy (
mr_capi_give), so C never reads the freed bytes.
Local results and CI
The PR body lists, on macOS with ruby 4.0.10: the gates, run_corpus.sh --both (902/902), the MERE_RUBY_VM=1 corpus (902 on the VM, 0 fallbacks), capi_check, capi_spec_check, capi_mkmf_check and the puma results. capi_gem_check fails on the reference side only (ruby's own gem install prism hit the 2 GiB limit). The body explains this. There is no Linux run, and the Linux run is where the Major finding shows. CI for a542e52: 2 jobs passed, 7 still queued.
What I did not check
puma's suite, the gem checks, the full corpus, Linux execution of the mere-ruby binary, ASan.
| // read `kill -s KILL -123` as a second signal, "invalid | ||
| // signal specification" -- ESRCH for a group that was | ||
| // there; puma's tests stop a server by its group) | ||
| ++ " -- " ++ str_of_int pid9 ++ " 2>/dev/null") == 0 then VInt 1 |
There was a problem hiding this comment.
Major (Linux). Linux /bin/sh is dash, and dash's kill does not take -- after -0 or -N. kill -0 -- 123 fails with "Illegal number: -" (exit 2). The -s NAME -- 123 form works, because -s goes through dash's option parser. So on Linux, Process.kill(0, other_pid) raises Errno::EPERM when the process exists, and Errno::ESRCH for a negative pid. ruby returns 1. Corpus 911 line 8 (Process.kill(0, -pid)) takes this path. Checked in dash on macOS and in the ubuntu:24.04 image. kill -s 0 -- PID (and -s <number>) works in both dash and bash. One fix: always use -s.
There was a problem hiding this comment.
Fixed in 9f4a41c. The command is now always kill -s <name or number> -- <pid>, so -0 and -<N> no longer reach dash's argument parser.
I checked this in ubuntu:24.04 (arm64, /bin/sh -> dash), compiling mr.c with tools/build.sh --cc-only --fast:
- The a542e52 build fails corpus 911 the way you predicted:
Errno::ESRCHat line 8 (Process.kill(0, -pid)), where ruby prints1. - The 9f4a41c build matches ruby 4.0.10 on corpus 909-917, on the evaluator and with
MERE_RUBY_VM=1. - In dash on its own,
kill -0 -- PIDandkill -34 -- PIDexit 2 ("Illegal number: -"), andkill -s 0 -- PIDexits 0.
On macOS: 902/902 with run_corpus.sh --both, and 902 on the VM with 0 fallbacks.
I recorded both suggestions under Left, in the PR body and in the loop record.
| * transit is set aside around it. (Not for MR_STR_SET / MR_ARY_SET: those | ||
| * are the write-back itself, in the middle of a flush; nor while a | ||
| * collection is marking, whose dmark asked this.) */ | ||
| if ((op == MR_STR_GET || op == MR_SEND || op == MR_STR_NEW) && !mr_capi_marking()) { |
There was a problem hiding this comment.
Suggestion. This runs for every String fetch, call and new String, even when no collection is due. Each time it does a transit save (malloc plus a copy of the bytes in transit, e.g. a 64 KB rb_str_new) and one more up-call. With GC.disable, ApiFixture.join_in_c(3000) took 0.29–0.37 s here, against 0.16–0.21 s on main (3 runs each, load about 28). A check on the C side for whether a collection is due, before the save, would avoid most of the cost.
Linux's /bin/sh is dash, whose kill reads `kill -0 -- PID` and `kill -34 -- PID` as "Illegal number: -". Process.kill(0, pid) then raised EPERM, and ESRCH for a process group, where ruby returns 1 (corpus 911 line 8 on Linux). The review's two suggestions are recorded under Left.
284km
left a comment
There was a problem hiding this comment.
Re-reviewed 9f4a41c. The Major is resolved.
Process.killnow always callskill -s <name or number> -- <pid>. dash's kill reads-sthrough its option parser, so-s 0 --and numeric signals work there as in bash. I checkedkill -s 0 -- PIDandkill -s 15 -- PIDunder dash, andkill -s 0 -- -PGIDfor a process group.- The author ran corpus 909–917 on ubuntu:24.04 (/bin/sh is dash): the build before this fix gives ESRCH on corpus 911 line 8, and this head matches ruby 4.0.10 on the evaluator and the VM. On macOS, corpus --both is 902/902 and the VM corpus runs all 902 on the VM.
- The two Suggestions (the C API safepoint's constant cost,
superfrom a module-definednew) are recorded under Left in the description and the loop note. git merge-treeagainst current main: clean. No mere-pr-review-watch inline comments.
No open Critical / Major / Minor findings, and the local results are posted. Merging.
What this is
Native gems, round 3 (note 558): puma 8.1.2's own test suite (
test/runner, minitest), run on mere-ruby and on thereference. Where the two differ, mere-ruby is fixed. nokogiri is not in this round; corpus 915 is held for it.
The full record is
loop/2026-11-24-native-gems-r3.md: how puma is run, each cause, repros and every table.Fixes
RbConfig::CONFIG['configure_args']says--with-openssl-dir=<prefix>when the build named an OpenSSL. puma's extconf then finds it, so MiniSSL is built.superfrom adef self.newof a Hash, Array or String subclass makes an instance backed by the builtin. It used to make a plain object (puma'sHeaderHash).stdfd_clear_nonblockmakes them. curl stopped at 64 KB on anIO.pipeend.Process.killwith a negative pid signals that process group.kill(1)had read-pgidas a signal name. 9f4a41c always useskill -s, so dash takes it too (below).MR_SAFEPOINT).Thread#join.WaitReadable.The C API change (a0a5cb4) bounds memory on puma's parser with N × 1024 identical headers. The before build is
#190's 9aa9a0c:
New capi/check contracts:
join_in_c,hold_locals(also paused in a Fiber),write_frozen, and the api fixture'sadditions.
The two bugs the trap fix exposed (8f75e0c → 881e115, 83828d2)
After 8f75e0c, traps run on the main thread, which exposed two more bugs. The cases below are run on ruby 4.0.10,
on main 2e402b9 built with the same Mere (9dec2ff6), and on this branch. Each run is bounded at 20 s; exit 142
means it hit that bound.
881e115: a signal taken on a busy thread never ran its trap. The signal stayed queued for the main thread. Only
the scheduler's idle wait woke the main thread for it. In a puma worker the threads are never all waiting, and the
main thread is joining the server thread. So the mold promotion's URG never ran: "Promoting worker N to mold" was
logged, and nothing followed. Now
sig_pollwakes the main thread when it waits in a sleep, a join or a queue.n += 1 until $stop; main joins it; USR2 from outside)true,[true]true,[true]83828d2: accept(2) errors were all
SocketError "accept failed". A cluster's workers share one listener. Whenanother worker takes the connection first, or the client has already gone, accept(2) says EAGAIN or ECONNABORTED.
puma logged these as "Listen loop" errors: 50 in main's mold_worker group, 0 on this branch. Accept now goes through
mr_sock_accept(tools/socket_glue.c), which returns-errno, and answers the wayext/socket/init.cdoes, forTCPServer, UNIXServer and Socket:
IO::EAGAINWaitReadable.IO::WaitReadable.120,[]On main the race is what goes wrong. A connection taken between the readiness check and accept(2) sent the process
into the blocking accept, which waited for a next connection, so the children never reported.
Review fix: kill(1) under dash (9f4a41c)
The first review (a542e52) found a Major issue that shows only on Linux. 761f7d8 put
--before the pid but keptkill -0(signal 0) andkill -<N>(a number with no name). Linux's/bin/shis dash, and dash's kill reads bothkill -0 -- PIDandkill -34 -- PIDas "Illegal number: -" and exits 2. As a result:Process.kill(0, other_pid)raisedErrno::EPERM, becauseps -pstill found the process.Errno::ESRCH.The command is now always
kill -s <name or number> -- <pid>.-sgoes through dash's option parser, and the-sformworks in both dash and bash.
Linux measurements. Environment:
ubuntu:24.04(arm64,/bin/sh→ dash).mr.cwas emitted on macOS by Mere9dec2ff6 and compiled in the container with
tools/build.sh --cc-only --fast.kill -0 -- PIDandkill -34 -- PIDexit 2 ("Illegal number: -");kill -s 0 -- PIDexits 0Errno::ESRCHat line 8 (Process.kill(0, -pid)), where ruby prints1MERE_RUBY_VM=1On macOS with the fix:
run_corpus.sh --both: 902/902.tools/iseq/vm_corpus.sh: 902 on the VM, 0 fell back, 0 FAIL.puma's suite
test_integration_cluster, group by group, on three builds (reference ruby 4.0.10)
Each group ran alone on each build, one build at a time. main 2e402b9 has its own GEM_HOME and puma tree, built by
its own mkmf. The load average was 25–45 throughout, once 140, from other sessions.
test_thread_log passes on this branch.
Unit and the other integration files
Unit (
test/runner -v --unit --seed=1) on 0238f6e, each side on its own tree and GEM_HOME. The mere side's pumaextension was rebuilt with this build's mkmf, and
Puma::HAS_SSLis true. Load average 11.11 at the start, 6.62 atthe end.
I did not run puma's full integration suite again on this build. The per-file integration table in the record
(one file at a time,
--exclude=/test_horrible_queries/) was measured against ruby 4.0.9, before the reference movedto 4.0.10. On that run every file other than cluster, pumactl, single and preserve_bundler_env matched the
reference.
Left
Each item gives its cause and main's result on the same test.
Failures that are not time limits
Bundler.with_unbundled_env, which takes the reference stdlib out of RUBYLIB. That is how this harness givesmere-ruby its stdlib, so
require 'rubygems'fails. main fails the same 7 of 7 cluster ones. Fixing it needs amere-ruby installed with its stdlib in its own rubylibdir.
17. main is the same (19 against 17). Not investigated.
Failures at a time limit (a log line not seen in time, TestTookTooLong, or puma's 2 s worker check-in)
reforks_at_each_threshold (phase 1): main fails both the same way. Both logs first show "Out-of-sync worker list"
for the worker that was just sent TERM. Cause not found.
refork_phased_restart_with_fork_worker_and_high_worker_count: "Worker N failed to check in within 2 seconds".
main fails both the same way.
main fails it the same way.
twice.
_threadsvariant.Not rerun on main's build.
RackUp#test_bin (boot takes 2.7 s here against 0.27 s). main's build has no MiniSSL, so the first is not run
there.
String C touched, to see whether C wrote into it.
From the review, left for a follow-up
mr_upsaves the transit buffers and makes one extra up-call, even when no collection is due. The reviewer measured
ApiFixture.join_in_c(3000)withGC.disable: 0.29–0.37 s here against 0.16–0.21 s on main (3 runs each,load ≈ 28). A C-side "is a collection due?" check before the save would remove most of this cost.
superfrom anewdefined in a module still makes a plain object. This is not a regression: main behaves thesame. Example:
module M; def new(*a) = super; end; class A1 < Array; extend M; end; A1.new(2, :q)gives[:q, :q]on ruby and a bare#<A1>here. A String subclass with a prependednewbehaves the same way. Thesecalls go through
super_native_or_missing, notsuper_cls_new.Seen on the way, not fixed:
$stdout.reopen(file)does not share the File's position. A File here keeps itsown position.
Local results (reference ruby 4.0.10, Mere 9dec2ff6)
I ran the full set at 0238f6e (main 8b1b952 merged). After main moved, I merged it again at a542e52
(#248, #261, #264, #266; no conflicts) and reran the starred checks. The commits in between change only the record.
* Gates, bracket_depth and record_hygiene pass.
*
run_corpus.sh --both: 902/902 with the hash index on and off (900/900 at 0238f6e).*
MERE_RUBY_VM=1corpus (tools/iseq/vm_corpus.sh): 902 on the VM, 0 fell back, 0 FAIL, 0 against the list of fallbacks.* capi_check: the contracts agree on both sides and hold under collection stress, and each negative control fails.
capi_spec_check and capi_mkmf_check pass.
capi_gem_check: fails, on the reference side, twice in a row. ruby 4.0.10's own
gem install prismwas killed atthe 2 GiB limit:
The cause is in the reference side's build, not in this branch. RubyGems adds
-j<nprocessors>(10 here) tomakewhen MAKEFLAGS has no
-j(rubygems/ext/builder.rb:46-47). The check removes MAKEFLAGS and measures the wholeprocess tree, so prism's large C files compile ten at a time.
morning's run for erb/escape is ruby's C extension, linked into the executable #253 (load 59, so the compiles overlapped less).
usediffers in one place only: the reference falls back to its default prism 1.8.2, while mere-rubyinstalled prism 2.1.0 (797,680 KB, 28 s).
useare the same, and every other gem installs on both sides.I have not changed the check here. Whether to give
gem installa fixed-jis a separate decision.🤖 Generated with Claude Code