Repository navigation
Detect argument array mutation during String formatting - #260
Conversation
284km
left a comment
There was a problem hiding this comment.
Reviewed exact head 52f6c67d4db6a1973e9fb0592673784dc1c97e64 against fetched main 8b1b95256644eb7f5714ddb3094701f2ea3366bb. Existing reviews, discussion and inline threads were empty; neither fetched main nor head contains tracked AGENTS.md/CLAUDE.md instructions. One Major/P2 correctness finding is attached: live argument reads and result-encoding negotiation use different values after same-length replacement.
Keeping the original array local to each formatting invocation correctly avoids global source state and makes the final-conversion length check effective. Corpus 1111 matches all 11 reference output lines and exit status in evaluator and VM modes with GC stress period 50. Four additional encoding-replacement controls reproduce the attached issue on both engines. Source comparison confirms current main still formats from the original argument list, while this change reads replacement values but leaves rb_fmt_enc on the old list.
Build reuse: independently compared all 2,430 tracked files in the existing build checkout with this exact head (zero differences), verified the three imported mgz modules against pinned commit 661a01d8, inspected the successful ordinary O2 build log and verified the compiler checkout at 9dec2ff6 is clean. Copied binary SHA-256 24c6f0ef3c0bc1a645397bb2b5cea3aae0a3153f14bc7b5218e9592a87a96cd1. This is reuse, not a fresh compilation. Reference is the independent Ruby 4.0.10 installation.
No complete corpus, full upstream file, performance or platform/resource acceptance is claimed here. Hosted build and downstream coverage remain incomplete. No merge: draft status, the attached finding and recorded global merge holds prevent it. COMMENT is used because the authenticated account owns the PR.
284km
left a comment
There was a problem hiding this comment.
Follow-up review of exact head 9d5d311 against fetched current main a63e47c and prior reviewed 52f6c67. Read the existing finding/response, full formatter changes, live-array reads, directive conversions and callers. No tracked AGENTS.md/CLAUDE.md was found.
The earlier Major/P2 stale-result-encoding finding is fixed: encoding now follows each consumed conversion, with invocation-local state. Corpus 1111 covers replacement in both directions, already-consumed slots, callback results and nested formatting. All 20 lines match independent Ruby 4.0.10 on evaluator and VM with MERE_RUBY_GC_STRESS=50; related corpus 982 matches all 140 lines in both modes. No earlier inline comment is duplicated or thread resolved.
One new Major/P2 regression is attached: the non-String %p fallback invokes inspect twice. The focused reproducer succeeds on reference and the existing main control, but raises on both exact-head engines. Current main still has the previous single-inspection code path. Duplicate/dead-definition and diff whitespace gates pass.
Build reuse: all 2,430 tracked regular files match exact head byte for byte in the existing successful ordinary O2 build source; build log uses compiler checkout 9dec2ff6. Binary SHA-256 e1cecdff706dc82dbf816354117ccee827862016b21d9db087bd63c997000674. No fresh integration build, full corpus, whole upstream sprintf file, performance or affected-platform/resource acceptance was run here. Hosted unittest-harness and build-linux fail; other work is executing/queued. No merge: the new actionable finding, recorded global holds and incomplete acceptance prevent it. COMMENT because the authenticated account owns the PR.
284km
left a comment
There was a problem hiding this comment.
Review of head 9d5d3114, which is the first human review of this PR. The earlier reviews are from the automated watcher. Reference: Ruby 4.0.10. Comparison build ("base"): an O2 build of the merge base fdda9150, which is the PR's own base without its changes. PR build: an O2 build of a clean tree at 9d5d3114, with the binary newer than every .mere file. I ran every probe on the evaluator and on the VM (MERE_RUBY_VM=1).
Earlier findings
- [Major/P2] Stale result encoding after a same-length replacement (watcher,
52f6c67d): resolved. I ran it. A callback replaced the second slot. I tried all 25 pairs of UTF-8, ASCII-8BIT, Windows-31J, US-ASCII and ASCII-only binary. I also tried format strings in four encodings, replacing a slot that was already consumed,formatwith a splat,%p, and callback results. All 66 lines match Ruby on both engines. Base differs on 48 of them. - [Major/P2]
%pcallsinspecttwice when it returns a non-String (watcher, 04:13): confirmed, still open. I ran it. Wheninspectreturns123, Ruby calls it once. The PR calls it twice on both engines. Base calls it once.
New findings
- [Critical]
printfraises on any format that contains a non-ASCII byte. See the inline comment on the literal-byte branch ofrb_format_go.printf("日本語\n")raisesEncoding::CompatibilityError: incompatible character encodings: UTF-8 and. The second encoding name is empty. The same happens with$stdout.printf,$stderr.printf,STDOUT.printfandprintf(io, ...). Ruby and base print the text. Both engines are affected. Cause, from reading:rb_format(the printf path) never setsfmt_enc_cur, sofmt_enc_now ()returns"".enc_compat2 "UTF-8" "" "" bytethen answers "incompatible".format,sprintfandString#%still work, because they go throughrb_format_in. - [Minor] The same literal-byte check raises where Ruby succeeds.
"%sé" % ["\xFF".b],"%{a}é" % {a: "\xFF".b}and ato_sthat returns a BINARY string, followed by a UTF-8 literal. Ruby returns a BINARY string for each one. The PR raisesEncoding::CompatibilityError. Base already raised on the first one (with the names in the other order). It returned an invalid UTF-8 string for the other two. Ruby's sprintf checks the result so far against each converted argument only. It copies literal text without negotiating. The prefix already reaches each check through state slot 1, so I think the per-byterb_fmt_takecan simply be removed. That would also fix finding 1. - [Major] Formatting is slower, and the extra cost grows with the length of the literal text. See the inline comment on
vec_set state9 1 acc. I measured instructions retired with/usr/bin/time -l, as the median of 3 alternating runs. Process start (p 1) is about 0.92 G in both builds.
| Loop | Evaluator base → PR | VM base → PR |
|---|---|---|
format("%d %s %5.2f", i, "abc", 1.5) ×200k |
8.004 G → 8.182 G (+2.2%) | 7.304 G → 7.484 G (+2.5%) |
"%s" % x ×300k |
6.272 G → 6.456 G (+2.9%) | 6.553 G → 6.734 G (+2.8%) |
"Expected %s to be equal to %s, but the value was %d instead." % [...] ×100k |
4.661 G → 5.841 G (+25%) | 4.787 G → 5.963 G (+25%) |
"名前は%sで、年齢は%d歳、住所は%sです。" % [...] ×100k |
4.598 G → 10.136 G (×2.2) | 4.728 G → 10.265 G (×2.2) |
600 ASCII bytes + %s + 600 ASCII bytes ×5,000 |
2.826 G → 6.101 G (×2.2) | 2.843 G → 6.101 G (×2.1) |
300 × "あ" + %s + 300 × "い" ×10k |
2.464 G → 10.188 G (×4.1) | not run |
The ASCII rows have no high bytes, so the per-character cost there comes from vec_set state9 1 acc. It runs once for every literal character. I suspect that storing acc in the vector also stops the acc ++ c append from working in place, because the extra cost grows with length. I have not confirmed that. Storing the prefix only just before rb_fmt_dir (once per directive) should remove the cost. Dropping the per-byte take (finding 2) removes the non-ASCII part.
Other behaviour I compared with Ruby (ran, both engines)
These match Ruby: a callback that pushes, pops, clears or replaces the array (longer, shorter, same length); push then pop; mutation from inspect, to_int, to_f, width * and precision .*; numbered arguments; mutation in the final conversion; nested format inside a callback, including a nested format that mutates the outer array; a to_ary object; an Array subclass; %<name>s and %{name} with a Hash; %*d (positive and negative); %c with a String (also BINARY and Windows-31J) and with an Integer (also after a BINARY argument, where Ruby raises RangeError, which base did not); %p, %-10p, %.3p; too few arguments; too many arguments with $VERBOSE (warning) and $DEBUG (ArgumentError); frozen arrays, with and without a mutating callback; String#% with an Integer and a Hash; to_ary returning nil or a non-Array; format/sprintf with a splat (a copy, so no error); CompatibilityError messages for UTF-8 vs BINARY in both orders, and for Windows-31J; format strings in US-ASCII, BINARY, Windows-31J and EUC-JP; UTF-16LE arguments to %s.
Remaining differences are not caused by this PR. Base has them too:
"%*d" % ["5", 1]formats where Ruby raisesTypeError.$DEBUGdoes not print theException '...' at ...lines.- A custom
inspectthat returns Windows-31J text is escaped asあwhere Ruby writes\x{82A0}. (The BINARY case is now correct.) FrozenErrormessages print#<object>for an object.
Corpus 1111 matches Ruby on both engines (20 lines).
Upstream tests (ran, --seed=1, MERE_RUBY_GC_TIGHT=1, through unittest/try.sh)
ruby/test_sprintf.rbwithouttest_width_underflow: reference 34 tests / 37,679 assertions / 0 failures. PR: the same on both engines. Base: 2 failures on both engines (test_modify_argument_array,test_dangling_pointer_after_encoding_set). I excludedtest_width_underflowbecause it did not finish in several minutes on the PR build. I did not check whether base also hangs there.ruby/test_m17n.rb: PR and base both have 127 tests / 3,828 assertions / 0 failures / 1 skip on both engines. The reference has 3,830 assertions. Same as base, so no change.
Merge criteria
- The author's local results: full corpus
--bothpasses 884/884,MERE_RUBY_VM=1 --bothpasses 884/884, gates and record hygiene pass, and the seven chosentest_sprintf.rbtests pass. These are posted. Not posted: the whole oftest_sprintf.rbandtest_m17n.rb. My runs above cover both. - No corpus program uses
printfwith non-ASCII text, so the full corpus could not catch finding 1. Please add a corpus case for it. git merge-tree --write-treeagainst current mainf371c46fis clean.- CI on
9d5d3114:build-linuxfailed at "Check Ruby's C API against the reference with shared C sources", andunittest-harnessfailed atci_timing_check.py. Other open PRs fail at the same two steps in this round (for example thecodex-misc-lexical-scope,codex-parse-multibyte-sourceandcodex-misc-array-element-locationsbranches), so this does not look specific to this PR. The macOS jobs andunittest-referencewere still queued. - Open: 1 Critical, 2 Major (one of them the watcher's double
inspect), 1 Minor. The merge criteria are not met.
Not checked: the full upstream unit suite, Rails suites, max RSS, and Linux.
Merge waits for the pending manual main CI run to start.
284km
left a comment
There was a problem hiding this comment.
Follow-up review of exact head 8af9a97a61444ba68daff2bb95a8dc4e9b017c4a against fetched current main 164c75f30cae6dcaa33dc314c4d6b12218f36ef7. Read existing reviews, replies and all four inline threads, the formatter changes, entry points, conversion helpers and regression cases. Neither fetched base nor head contains tracked AGENTS.md/CLAUDE.md instructions.
The earlier Major/P2 double-inspection finding is fixed: %p invokes the original object's inspect once, then converts its returned value through dstr_conv. The callback-count and encoding cases are useful regressions. The previous live-array encoding fix is retained.
Independent focused checks with MERE_RUBY_GC_TIGHT=1: corpus 1111 (28 output lines), corpus 982 (140 lines) and the original inspect-once witness all match independent clean Ruby 4.0.10, including stdout, stderr and exit status, on evaluator and VM. The witness returns ["123", 1] on both engines.
The existing non-ASCII printf/literal negotiation finding remains open. The focused literal/printf witness reproduces the exceptions on both fresh-head engines: printf("日本語\n") raises Encoding::CompatibilityError (UTF-8 and an empty encoding), while Ruby prints the text. Binary substitution followed by a non-ASCII literal still raises for positional, named and callback cases where Ruby returns ASCII-8BIT. The existing per-literal-character performance finding also remains open: the prefix is still stored on every iteration of rb_format_go. I did not repeat the earlier instruction-count benchmarks or independently establish their underlying allocator cause. No duplicate inline finding is posted and no thread is resolved.
Fresh ordinary O2 build on Darwin arm64 using pinned compiler 9dec2ff6 (checkout verified clean) and all three imported mgz modules verified against 661a01d8; binary SHA-256 415194c5a6da9fa6be86c3bf15e14ed956013c3a64a964bc8b4d2237ee8a9c3b. Duplicate/dead-definition checks, generated-C bracket-depth check (155 required / 1024 supplied) and diff whitespace checks pass. This is an exact-head build, not a current-main integration build. Current-main formatter source was checked; no exact-current-main executable comparison is claimed.
No independent full corpus, complete upstream sprintf file, performance or Linux/platform resource acceptance is claimed. Hosted coverage is incomplete and the latest main CI has an actual executed build-linux C API checker failure (capi/vendor/erb_escape.c is not the tree's file), even though its aggregate is queued. No merge: draft status, the unresolved findings and recorded global holds prevent it. COMMENT because the authenticated account owns the PR.
284km
left a comment
There was a problem hiding this comment.
Re-review of head 8ce5765a. The previous human review was on 9d5d3114. Reference: Ruby 4.0.10. PR build: the author's O2 build of a clean tree at 8ce5765a (binary newer than every .mere file; SHA-256 matches the one in the description). Comparison builds: an O2 build of the merge base fdda9150 ("base"), and a clean build of current main 0cd831f0 ("main"). I ran every probe on the evaluator and on the VM (MERE_RUBY_VM=1).
Earlier findings
- [Critical]
printfwith a non-ASCII byte in the format raised: resolved. Ran it.printf("日本語\n"),$stdout.printf,STDOUT.printf,$stderr.printf,printf($stdout, ...), and a UTF-8 literal with UTF-8 arguments all print what Ruby prints, on both engines. (One related case is still wrong. See new finding 2.) - [Major]
%pcalledinspecttwice (watcher, 04:13): resolved. Ran it. The witness prints["123", 1]on both engines, like Ruby. I also triedinspectreturning a Symbol, nil, a Float, an Array, a BINARY String, a String subclass, an object with a customto_s, an object whoseto_sis not a String, and aninspectthat raises. All match Ruby, except an EUC-JP result. That one is escaped asあwhere Ruby writes\x{A4A2}. Main and base do the same, so it is not from this PR. - [Major] Format cost grew with the length of the literal text: resolved. Ran it. See the table below.
- [Minor] Literal text was negotiated against the result: resolved. Ran it.
"%sé" % ["\xFF".b],"%{a}é","%<a>sé", ato_sthat returns BINARY,"a%sé", width before a literal,formatandsprintfwith named arguments: all return BINARY strings like Ruby. The prefix still takes part in the check:"é%s" % ["\xFF".b],"%%é%s"and"\xFF%s".b % ["é"]raise like Ruby. Format strings in EUC-JP, Windows-31J, US-ASCII and BINARY, invalid UTF-8 literal bytes, and%cafter a literal also match. 24 of 24 lines match on both engines. Main matches 15. - The watcher's stale-encoding fix (same-length replacement): still holds. Ran it. A
to_scallback replaces the second slot. I tried all 25 pairs of UTF-8, BINARY, EUC-JP, ASCII and Windows-31J, plus the original witness, a slot that was already consumed, growth, and shrinking. 29 of 29 lines match Ruby on both engines. Main differs on 23.
New findings
-
[Major] Every formatting call keeps about 160 bytes that are never freed. See the inline comment on
rb_fmt_state. Max RSS grows in a straight line with the number ofString#%/formatcalls, andMERE_RUBY_GC_TIGHT=1does not help."%s" % xin a loop, evaluator, tight GC:Calls Base PR 100k 88 MB 104 MB 400k 102 MB 166 MB 800k 118 MB 245 MB The PR's extra memory grows by about 200 bytes per call; base grows by about 40. Each run's RSS was stable to within 0.1 MB over three runs. The VM is the same (for example
"%s" % x×300k: 113 MB → 159 MB). This already existed at3608af46, when the per-call state vector was added, so it is not from the two fix commits. My guess at the cause, from reading only:rb_fmt_stateallocates a newvecon every call. As far as I know, a Merevecis not freed when it is dropped. Slot 1 also holds the output prefix, so that string stays alive too. This fits the long UTF-8 case, which keeps about 1 KB more per call (93 MB → 104 MB for 10k calls). A long-running program that formats a lot of text would grow without bound. Logging is one example. Reusing one state (a pool, or a stack that is pushed and popped per call) should avoid it. Please also add a check of max RSS against the number of calls. -
[Minor]
printftreats every format string as UTF-8 when it checks encodings. See the inline comment onrb_format. A format with non-ASCII text in EUC-JP, Windows-31J or BINARY, followed by a non-ASCII argument in the same encoding, now raises. Ruby and main print it:printf("あ%s\n".encode("EUC-JP"), "い".encode("EUC-JP")) # Ruby 4.0.10 and main: prints the EUC-JP bytes # PR (both engines): Encoding::CompatibilityError: incompatible character encodings: UTF-8 and EUC-JP
The same happens with Windows-31J text,
printf("\xFF%s\n".b, "\xFE".b),%c,$stdout.printfandprintf(io, ...). This is a regression from main.rb_formatstarts the state as"UTF-8", so the format's own encoding is lost. The callers have the format String, so they could pass its encoding. That would also fixprintf("\xFF%s".b, "é"), which Ruby rejects but the PR and main print.
Formatting cost (ran)
Instructions retired from /usr/bin/time -l, median of 3 alternating runs, base fdda9150 → PR, and the PR compared with current main 0cd831f0:
| Loop | Evaluator base → PR | VM base → PR | PR vs main (ev / VM) |
|---|---|---|---|
process start (p 1) |
0.950 G → 0.954 G | 0.949 G → 0.952 G | −2.5% / −2.4% |
format("%d %s %5.2f", i, "abc", 1.5) ×200k |
10.227 G → 10.275 G (+0.5%) | 9.608 G → 9.655 G (+0.5%) | +0.2% / +0.3% |
"%s" % x ×300k |
9.606 G → 9.748 G (+1.5%) | 10.086 G → 10.219 G (+1.3%) | +1.1% / +0.9% |
| 60-character ASCII message ×100k | 5.877 G → 5.877 G (0.0%) | 6.064 G → 6.064 G (0.0%) | +0.7% / −0.6% |
| Japanese message ×100k | 5.950 G → 5.960 G (+0.2%) | 6.121 G → 6.134 G (+0.2%) | −0.3% / −0.2% |
600 + %s + 600 ASCII bytes ×5,000 |
2.992 G → 2.867 G (−4.2%) | 2.997 G → 2.873 G (−4.1%) | −5.1% / −5.0% |
300 × "あ" + %s + 300 × "い" ×10k |
8.629 G → 8.252 G (−4.4%) | 8.643 G → 8.268 G (−4.3%) | −4.6% / −4.6% |
All checksums match Ruby. The cost no longer grows with the length of the format. The loop bodies differ from my first table (they add .size), so compare within this table only. The instruction finding is resolved. Max RSS in the same runs is the subject of new finding 1 (for example format ×200k: 125 MB → 163 MB).
Upstream tests (ran, --seed=1, MERE_RUBY_GC_TIGHT=1, through unittest/try.sh)
| File | Reference | Main ev / VM | PR ev / VM |
|---|---|---|---|
ruby/test_sprintf.rb without test_width_underflow |
34 / 37,679 / 0 failures | 34 / 37,674 / 2 failures, both | 34 / 37,679 / 0 failures, both |
ruby/test_m17n.rb |
127 / 3,830 / 0 failures, 1 skip | 127 / 3,828 / 0 failures, 1 skip, both | same as main |
Main's two failures are test_modify_argument_array and test_dangling_pointer_after_encoding_set, which this PR fixes. test_width_underflow alone did not finish within 120 seconds on main or on the PR (evaluator). Both reached about 1.2 GB of RSS before the time limit, so the hang is not from this PR.
Merge criteria
- Author's local results are posted: full corpus
--both884/884,MERE_RUBY_VM=1 --both884/884, gates and record hygiene,test_sprintf.rb(withouttest_width_underflow) and the whole oftest_m17n.rb. My runs agree on the two upstream files. git merge-tree --write-tree origin/main origin/pr260(main0cd831f0) is clean.- CI on
8ce5765a:build-linuxfailed at "Check Ruby's C API against the reference with shared C sources". That is the step of the known shared red on main (capi/vendor/erb_escape.c, fixed by #273), so I do not count it against this PR. I could not read the log yet to confirm the file.unittest-plan,unittest-harness, "Linux build dependency controls" and "NKF Wasm engine" passed.build-macos,unittest-referenceand the gem suites are still queued. - Open: 1 Major (new finding 1), 1 Minor (new finding 2). The merge criteria are not met.
Not checked: the full corpus (I ran only targeted probes), the full upstream unit suite, Rails suites, and Linux.
284km
left a comment
There was a problem hiding this comment.
Follow-up review of exact head 8ce5765a46e905fb0ba86b27f7f59badc62157ab, the existing four finding threads and their replies, against fetched main 0cd831f0087be5ed703e8d92d6450bbbf9876326. No tracked AGENTS.md or CLAUDE.md instructions were found. No new actionable findings.
The earlier findings are addressed in the current source and focused execution: live-array replacements retain correct result encoding; %p calls inspect once; non-ASCII printf succeeds in a fresh process; binary results followed by UTF-8 literal text preserve Ruby's behavior. The literal loop now copies bytes without rb_fmt_take or per-character prefix-vector updates; prefix capture occurs only at directive boundaries. I have not independently repeated the author's instruction/RSS benchmark table or established an allocator cause.
Independent tight-GC comparisons against clean Ruby 4.0.10 all match stdout, stderr and exit status on evaluator and VM: corpus 1111 (40 output lines, including fresh-process printf entry points), corpus 982 (140 lines), and an additional fresh-process printf/binary-tail/inspect-once witness (5 lines). Dead-definition and diff whitespace checks pass. The prospective merge tree with fetched main is conflict-free; this is not a tested integration executable.
Build reuse is explicit: all 2,432 tracked files match the existing successful ordinary O2 build source byte for byte; the compiler checkout is clean at 9dec2ff6, and inflate/deflate/crc32 modules match pinned mgz 661a01d8. Copied binary SHA-256: a1e0168b907158da887d3f6ebabbcf3d89caceda912dc95f3d815969de7dbeb2. No fresh compilation, full corpus, whole upstream suites, Linux execution or resource acceptance was performed in this review. The author's broader evidence and the explicit test_width_underflow exclusion remain separately identified.
Hosted build-linux has an actual failed C API reference-check step; it is not merely waiting for a runner. Other Linux controls/gem jobs pass, while macOS/reference and downstream coverage remain incomplete. No merge: the recorded global holds and incomplete integration/platform acceptance remain. No existing inline finding is duplicated and no thread was resolved by this review. COMMENT because the authenticated account owns the PR.
284km
left a comment
There was a problem hiding this comment.
Re-review of head 08bd8c18. Our previous review was on 8ce5765a. Reference: Ruby 4.0.10. PR build: the author's O2 build of a clean tree at 08bd8c18. No .mere file is newer than the binary, and its SHA-256 matches the one in the description. Main build: a clean build of main d5869476 ("main"). For a few checks I also used a clean build of the merge base fdda9150 ("base"). I ran every probe on the evaluator and on the VM (MERE_RUBY_VM=1).
Earlier findings
-
[Major] Every format call kept about 160 bytes: resolved. Ran it. The loop
s = "%s" % x, run withMERE_RUBY_GC_TIGHT=1(collection driven by allocation count only), 3 runs each. Max RSS, min–max of the 3 runs:Calls Evaluator main Evaluator PR VM main VM PR 100k 92.1–92.2 MB 83.6–83.7 MB 104.1 MB 99.8 MB 400k 99.1–99.2 MB 85.5 MB 203.8 MB 190.5–190.6 MB 800k 111.8–111.9 MB 85.6–85.7 MB 324.4–325.6 MB 274.1–300.0 MB On the evaluator the PR is now flat. It is also flatter than main. On the VM both builds grow by about 300 bytes per iteration. This is not from this PR. Main grows the same way with no formatting at all:
s = x + "c"in the same loop goes from 106 MB at 100k to 301 MB at 800k on the VM. The PR stays below main at every count.I also checked that a slot is given back when formatting is left early. After 10k exits through a format call (
throwfromto_s, a rescuedArgumentError, a non-localreturnfrom a proc,next), 200k more plain format calls cost about the same as after 10k plain calls. If the slots were not released, every later call would scan 10k busy slots, and that would show as many billions of extra instructions. It did not. Formatting in a Thread that sleeps insideto_s, a killed Thread, and ato_sthat recurses untilSystemStackErrorall match Ruby, and formatting still works afterwards. -
[Minor]
printfassumed a UTF-8 format: resolved. Ran it, each case in a fresh process, comparing stdout, stderr and exit status bytes. These match Ruby on both engines: the EUC-JP witness, Windows-31J, BINARY ("\xFF%s".bwith"\xFE".b),%cwith a String and with an Integer in an EUC-JP format,%cin a BINARY format,$stdout.printf,STDOUT.printf,$stderr.printf,printf($stdout, ...), a format withto_str, a non-String format (TypeError), and a UTF-16LE format (refused like Ruby).printf("\xFF%s".b, "é")now raisesEncoding::CompatibilityErrorlike Ruby. Main prints it. Main also differs on the%ccases and the UTF-16LE case.
Earlier fixes, re-checked (ran)
- Non-ASCII
printf(printf("日本語 %s %d\n", ...),$stdout.printfwith%p): matches Ruby. %pcallsinspectonce: the watcher's witness prints["123", 1]. Aninspectthat returns a BINARY String also matches.- Literal text is not negotiated:
"%sé" % ["\xFF".b],"%{a}é","%<a>sé","a%sé", width,sprintfwith a name, and a BINARYto_sall match."é%s","%%é%s"and"\xFF%s".b % ["é"]still raise like Ruby. - Same-length replacement: all 25 pairs of UTF-8, BINARY, EUC-JP, US-ASCII and Windows-31J, where
to_sreplaces the next slot, match Ruby. Main differs. - The error paths that now read the encoding from the scratch slot: a KeyError from an EUC-JP format, read after more allocation, still has an EUC-JP message and the right key. The same holds for
named{...} after <...>. The encoding of a result is still right after more allocation. - Nested formatting, formatting inside two Fibers that are resumed out of order,
throwthrough a format, and the argument-array mutation cases all match Ruby. - Corpus 1111 and 982 (copied out of the tree and run there) match Ruby on both engines.
New findings
No Critical, Major or Minor finding.
- [Suggestion]
printf(io, ...)givesio.writea String tagged UTF-8. See the inline comment. Ruby passes the result's real encoding (EUC-JP, BINARY, ...). Main does the same as the PR, so this is not a regression. It only shows whenwritelooks at the encoding.
Two differences from Ruby that main has too, so they are not from this PR: format("%<a>s-%s", a: 1) says "unnumbered(1) mixed with numbered" where Ruby says "mixed with named". And the VM's memory growth in a top-level loop, described above.
Formatting cost (ran)
Instructions retired from /usr/bin/time -l, median of 3 alternating runs, main d5869476 vs PR. The loops add .size, and every checksum matches Ruby. Without tight GC:
| Loop | Evaluator main → PR | VM main → PR |
|---|---|---|
format("%d %s %5.2f", i, "abc", 1.5) ×200k |
10.225 G → 10.113 G (−1.1%) | 9.296 G → 9.208 G (−0.9%) |
"%s" % x ×300k |
9.547 G → 9.493 G (−0.6%) | 9.638 G → 9.593 G (−0.5%) |
| 60-character ASCII message ×100k | 5.725 G → 5.632 G (−1.6%) | 5.359 G → 5.263 G (−1.8%) |
| Japanese message ×100k | 6.123 G → 6.076 G (−0.8%) | 5.790 G → 5.684 G (−1.8%) |
600 + %s + 600 ASCII bytes ×5,000 |
2.969 G → 2.902 G (−2.3%) | 2.985 G → 2.903 G (−2.7%) |
With MERE_RUBY_GC_TIGHT=1 the PR is also 0.1% to 2.7% below main in every row. Runs of the same build differed by less than 0.7%. The PR's base is 137 commits behind main, so a small part of the difference may come from main. Max RSS is lower on the PR in every row.
Upstream tests (ran, --seed=1, tight GC, through unittest/try.sh)
ruby/test_sprintf.rbwithouttest_width_underflow: 34 tests, 37,679 assertions, 0 failures, on both engines. This matches the reference.ruby/test_m17n.rb: 127 tests, 3,828 assertions, 0 failures, 1 skip, on both engines. Same as our run on the previous head.
Merge criteria
- Open findings: none at Critical, Major or Minor.
- The author's local results for this head are posted: corpus
--both884/884,MERE_RUBY_VM=1 --both884/884, all source gates and record hygiene, the bracket gate,test_sprintf.rb(withouttest_width_underflow) and the whole oftest_m17n.rb. My runs of the two upstream files agree. git merge-tree --write-tree origin/main origin/pr260(maina9e68981) is clean.- CI on
08bd8c18: "NKF Wasm engine" and "Linux build dependency controls" passed. CI, the gem suites, Rake and runtime load path controls are still queued.
The criteria in this review are met, apart from CI, which has not run yet.
Not checked: the full corpus (I ran only targeted probes and corpus 1111 and 982), the full upstream unit suite, Rails suites, and Linux.
| match value9 with | ||
| | VStr handle9 -> | ||
| (let _ = fmt_ascii_guard world (senc_get handle9) in | ||
| let (out9, _) = rb_format_in env world (senc_get handle9) (sget handle9) args source9 in out9) |
There was a problem hiding this comment.
[Suggestion] printf(io, ...) gives io.write a String tagged UTF-8.
rb_format_in returns the result's encoding, but this line drops it. The printf(io, fmt, ...) caller then wraps the bytes with mkstr, so io.write gets a UTF-8 String:
o = Object.new
def o.write(s); p [s, s.encoding]; s.bytesize; end
printf(o, "あ%s".encode("EUC-JP"), "い".encode("EUC-JP"))
printf(o, "%s", "\xFF".b)
# Ruby 4.0.10: ["\x{A4A2}\x{A4A4}", #<Encoding:EUC-JP>] and ["\xFF", #<Encoding:BINARY (ASCII-8BIT)>]
# PR and main: ["\xA4\xA2\xA4\xA4", #<Encoding:UTF-8>] and ["\xFF", #<Encoding:UTF-8>]Main does the same, so this is not a regression. Output written to a real IO is correct, because only the bytes matter there. Returning the encoding here, and tagging the String with it in the printf(io, ...) caller, would match Ruby. This is optional for this PR.
There was a problem hiding this comment.
Recorded as a nonblocking follow-up in the PR description and local loop note. The explicit-IO wrapper still drops the result encoding before calling a custom write method; this matches main and is separate from the fixed printf input-encoding regression. The reviewed 08bd8c1 head is unchanged. I also recorded your independent top-level VM-loop growth control separately from the count.times scratch-retention benchmark, and retained the existing mixed-named diagnostic difference as a follow-up.
String#% now raises RuntimeError when argument conversion changes the source array length. Same-length replacements remain visible, and result encoding follows values actually consumed. %p calls inspect once.
The final review correction removes per-call formatter-state retention by recycling a reusable scratch arena on both success and failure. Nested calls and interleaved Fibers retain separate busy slots. printf now preserves its format String encoding, including EUC-JP, Windows-31J and binary formats. Literal bytes are copied without per-byte encoding negotiation or prefix retention.
Base: main fdda915. Reference: clean Ruby 4.0.10, verified with tools/ref_ruby.sh; no reference gems are installed. The final ordinary O2 build uses Mere 9dec2ff6 and mgz 661a01d8.
Completed final acceptance
Review correction: release scratch arenas and preserve printf encoding
The R6 review found two additional blockers. A fresh per-call Vec retained
its allocations, including the captured prefix, after formatting returned.
The printf wrapper also started every format as UTF-8 and lost the actual
String encoding before negotiation.
Formatting now borrows a reusable scratch slot. Each slot has a private
arena, recycled on both normal and exceptional return; clearing its String
fields alone would retain arena copies. Busy slots are kept separate for
nested calls and interleaved Fibers; a first-free search permits returns
in a different order. The resulting encoding is copied out before recycling.
Named keys and the original format encoding are invocation-local as well.
The printf entry points pass the String value through, preserving its
encoding and strict to_str conversion before the common formatting path.
Corpus 1111 adds EUC-JP, Windows-31J and binary printf formats in fresh
children, Kernel/stdout/STDOUT/stderr/explicit IO and File entry points,
percent-s and percent-c, and an incompatible binary/UTF-8 control. Captured
stdout/stderr bytes and status are checked. Nested named callbacks,
rescued errors, throw, and non-LIFO interleaved Fibers guard slot ownership.
The final O2 corpus 1111, corpus 982 and the exact literal review probe
match clean Ruby 4.0.10 on evaluator and VM with tight GC.
The final R8 ordinary O2 binary SHA-256 is
59dc7e3d5c4169c1ec4233b2b062a3bc8fc0312a53d951417a07bff9ec8cb032.
Compiler and mgz remain pinned at 9dec2ff6 and 661a01d8. This section
supersedes R6 acceptance for the corrected head.
The unchanged expanded upstream selections were repeated with --seed=1
and MERE_RUBY_GC_TIGHT=1, one file at a time. test_sprintf still excludes
only test_width_underflow, the separately known main/candidate resource
hang; that case is not claimed passing. Reference passes 34 tests / 37679
assertions. Main a63e47c passes 34 / 37674 with two failures; candidate
passes 34 / 37679 with no failures, on both engines. Whole test_m17n has
127 tests, zero failures and one skip: reference 3800 assertions, main and
candidate 3794 evaluator / 3796 VM. The count difference is preserved.
RSS against formatting call count
bench/string_format_retention.rb is measured with tight GC, --seed=1,
three alternating runs per binary, case, count and engine. Values are
maximum RSS bytes across those three runs; ordinary O2 binaries are main
d4e5ba5, reviewed R6 and final R8. All 216 executions finish successfully
and match the reference witness output. The main d4 control is separate
from the a63 control used for upstream files and instruction measurements.
Plain formatting no longer has the R6 linear retained-memory slope: R8
stays near 91-92 MB from 100000 to 800000 calls, while R6 grows from
109 MB to 245 MB. Nested, rescued and long formats also stay below the
unchanged main control at the largest counts. Their total process RSS
still includes normal interpreter warm-up; it is not claimed flat.
Six-shape instruction and RSS comparison
bench/string_format_literals.rb repeats the same six deterministic shapes
with --seed=1, tight GC and three alternating runs of main a63e47c, R6
and R8. Every checksum matches clean Ruby. Counts include checksum/bytesize
bookkeeping; they are not the reviewer's exact instruction totals. These
are medians for instructions and maxima across three runs for RSS bytes.
The final R8 generated-C bracket gate passes, 155 required / 1024 supplied.
sh run_corpus.sh --both: 884/884 pass, hash indexing ON and OFF.
MERE_RUBY_VM=1 sh run_corpus.sh --both: 884/884 pass, indexing ON/OFF.
Both fresh complete commands pass all source gates and full record_hygiene.
They run serially; no corpus program is excluded. The updated loop note
passes explicit record_hygiene before the single code/regression/record push.
No full unit suite or Rails component suite was run; no workflow changed.
Nonblocking follow-ups
Human re-review confirms both blockers fixed and no new Critical/Major/Minor finding. Its optional
printf(io, ...)suggestion is retained for a follow-up: a customwritemethod sees a UTF-8 label even when the result is EUC-JP/binary; main has the same behavior. The existing mixed-named-format error wording difference is also outside this correction.The reviewer also reproduced VM growth in top-level assignment loops on both main and candidate, including a control without formatting. The committed retention benchmark uses
count.times; its flat plain-case RSS does not claim that all VM loops have flat RSS. The formatter's additional retained scratch growth is fixed on both engines. These notes update the description without another push.