Repository navigation
A String key's digest carries its encoding; group_by stores without the user's Hash#[] - #355
Conversation
…he user's Hash#[] Two findings on #351. 1. The hash index took a String's bytes alone. Two Strings are eql? only when their encodings are comparable too (rb_str_comparable), so "ab" in UTF-16LE and "ab".b were one key wherever a hash had its index: `{[] => 1, u16 => 2, bin => 3}.size` was 2, and group_by after it spilled past 16 keys the same. This was the Hash's, not group_by's. Now a String outside the class that compares by bytes alone -- every UTF-8 String, every ASCII-only one in an ASCII-compatible encoding, the empty one -- carries its encoding in the digest. The answer is memoised per encoding, so a String key with no encoding of its own pays one map_has. 2. group_by's non-plain keys went through invoke_val_c "[]" / "[]=", which dispatched a program's own Hash#[] / #[]=. ruby's group_by calls rb_hash_aref / rb_hash_aset. It now finds and stores the way the builtin doors do (hash_touch + hash_lookup_w for a key with its own #hash, the index otherwise; hash_store_key + hput_or_queue_w), not through them. Instructions retired (GC_TIGHT, median of 3), before #351 / main / this: group_by 10 elements, 3 keys 3.822 / 3.687 / 3.688 G group_by 100 elements, 100 keys 5.606 / 3.549 / 3.548 G group_by with Array keys 2.501 / 2.716 / 2.262 G Hash of 2,000 UTF-8 String keys 4.305 / 4.314 / 4.330 G (+0.4%) Hash of 2,000 binary String keys 4.339 / 4.342 / 4.435 G (+2.1%) corpus 1070 gets both, checked on the evaluator and the VM with the index on and off.
284km
left a comment
There was a problem hiding this comment.
Review of 378e5d49. No Critical/Major/Minor findings; fixes both post-merge Majors on #351.
- The real defect was in the Hash index, not
group_by.hkey_digestnow carries a String's encoding unless the String is in the class thatstr_comparablecompares by bytes alone: UTF-8, ASCII-only in an ASCII-compatible encoding, or empty. So{[] => 1, utf16 => 2, bin => 3}.sizeis 3 again, and grouping follows. The per-encoding answer is memoized by index inenc_names. gb_addfinds and stores a non-plain key the way the builtin[]/[]=do: the key's own#hash/#eql?throughhash_touch+hash_lookup_w, or the index, thenhash_store_key+hput_or_queue_w. It no longer dispatches the program'sHash#[]/Hash#[]=.
The cost is reported in the PR. group_by is back at or below the pre-#351 numbers, including Array keys. Hash with binary String keys is +2.1% and with UTF-8 keys +0.4%; that is the price of correct key equality, and I accept it as a small exception. The test merge with current main is clean. I will merge once the review bot has reviewed this head.
284km
left a comment
There was a problem hiding this comment.
Reviewed exact head 378e5d49b6d7882fbe6b307efab30f9faa0dde74 against current main 3fbe39217e583f5c0546254635da145ba1fed9cf. Both earlier Major findings on #351 are fixed: encoding-aware indexed grouping matches Ruby, and overriding Hash#[] / Hash#[]= no longer breaks grouping. The expanded corpus is useful. Two new Major / P2 regressions remain in the replacement lookup: bypassing Hash#default on a miss, and quadratic calls to a user key's #hash.
Validation: fresh ordinary O2 builds of both snapshots, pinned Mere 9dec2ff687a08433247dbdb7729bc19c8522e538 and mgz 661a01d8bb68f5acd68e3192bd47f081d179c436, compared with Ruby 4.0.10. Completed 128 base/head executions across 16 probe/corpus files on evaluator/VM, hash index ON/OFF, with MERE_RUBY_SHAPES_CHECK=1. Corpus 1070 and four related corpus files match Ruby in all 20 head configurations. An 17-encoding × 17-encoding × 6-byte-pattern matrix, including aliases, empty/invalid strings, nested Array keys and rehash/GC controls, matches Ruby in all four head configurations. Independent Hash override and custom/nested-key controls pass. Both new findings reproduce in all four configurations. The scaling probe has a pre-existing difference in Ruby's small-table transition call count (308 versus main's 299 at 100 keys); this does not explain head's 10,300 calls. GC-root, duplicate/dead-definition, name-length, method-write, bracket-depth (155/1024) and diff-whitespace checks pass.
Full corpus, instruction-retirement benchmarks, whole-file Rails/resource acceptance and complete hosted Linux/macOS coverage were not run locally in this review. Hosted CI remains incomplete, including core builds and downstream coverage; pending jobs are not recorded as passing. I did not merge this PR: the two new findings and the recorded hold_all_merges / new_failure_review_required prevent merging. Already-reviewed candidates remain subject to the same recorded hold.
| (let cur9 = (if key_has_user_hash world k9 then | ||
| (let _ = hash_touch gc_cenv0 world k9 in | ||
| let (f9, v9) = hash_lookup_w gc_cenv0 world hid9 (hderef hid9) k9 in | ||
| if f9 then v9 else VNil) |
There was a problem hiding this comment.
[Major / P2] Preserve Hash#default when the internal lookup misses
Returning VNil directly on a miss drops a Ruby callback that the old invoke_val_c "[]" path preserved. Bypassing user Hash#[] / #[]= is correct, but Ruby's rb_hash_aref still invokes an overridden Hash#default for a missing key. With a non-plain key, this now changes observable behavior:
class Hash
def default(key = nil)
raise "Hash#default was called"
end
end
begin
g = [[1], [1]].group_by(&:itself)
puts "groups=#{g.size}"
rescue => e
puts "#{e.class}: #{e.message}"
endRuby 4.0.10 and current main print RuntimeError: Hash#default was called; this head prints groups=1, on both engines with the index ON and OFF. Please retain the native missing-key/default behavior while bypassing [] / []=, and add a non-plain-key regression for an overridden default. This report is limited to the newly replaced lookup path.
| (let _ = hash_touch gc_cenv0 world k9 in | ||
| let (f9, v9) = hash_lookup_w gc_cenv0 world hid9 (hderef hid9) k9 in |
There was a problem hiding this comment.
[Major / P2] Cache the search key's hash once per lookup
hash_touch calls the query's #hash once, then hash_lookup_w calls it again through hkey_eql_w for each stored key. The old native [] path (hash_read_native) keeps one local search hash code across the walk. Consequently this replacement makes the number of user #hash callbacks quadratic, even when every key has a distinct hash and the result is correct:
class K
attr_reader :v
def initialize(v); @v = v; end
def hash; $calls += 1; @v.hash; end
def eql?(o); o.is_a?(K) && @v == o.v; end
end
keys = Array.new(100) { |i| K.new(i) }
$calls = 0
(keys + keys).group_by(&:itself)
puts $callsCurrent main calls #hash 299 times and Ruby 4.0.10 308 times; this head calls it 10,300 times in all four evaluator/VM × index ON/OFF configurations. At 20 keys the main/head counts are 59/460. For expensive custom hashes (including nested keys), this adds O(n²) Ruby callback work to the operation being optimized. It also unnecessarily repeats side effects. Please reuse/extract the native reader's local cached-code lookup without dispatching Hash#[], and cover callback scaling in the regression test.
Two findings on #355. 1. The internal lookup answered nil on a miss, so a program's own Hash#default was never asked; ruby's rb_hash_aref asks it. Now, when a program has one (asked once per group_by), every element goes through the Hash and a miss asks #default; an Array it answers is pushed onto and not stored, as group_by_i does. 2. For a key with its own #hash, hash_lookup_w asked the stored keys' codes through hkey_eql_w, once per stored key: 200 elements under 100 keys made 10,300 #hash calls (ruby 308, main 299). It now reads with hash_read_native -- the read `[]` itself makes, the search code taken once -- without dispatching Hash#[]: 299. Instructions retired, GC_TIGHT, median of 3 (before #351 / main / this): 10 elements, 1 / 3 / 10 keys 4.054 / 3.582 / 3.576, 3.822 / 3.684 / 3.711, 3.968 / 3.787 / 3.800 G 100 elements, 20 / 100 keys 3.732 / 3.233 / 3.235, 5.610 / 3.567 / 3.575 G Array keys 2.507 / 2.735 / 2.269 G corpus 1070: a Hash#default that raises, one that answers an Array, and the #hash count.
284km
left a comment
There was a problem hiding this comment.
Re-review at ced4a68b. Both bot Majors are fixed. When the program defines its own Hash#default, every element goes through the Hash and a miss asks default. An Array answer is pushed onto without being stored, as group_by_i does. A key with its own #hash is read through hash_read_native, which asks #hash once per lookup and keeps it for every comparison: 10,300 calls drop to 299, against Ruby's 308. Corpus 1070 covers both in four modes, and small group_by calls are still faster than before #351. I will merge once the review bot has reviewed this head.
284km
left a comment
There was a problem hiding this comment.
Reviewed exact head ced4a68bd66832cc2e00e34ba619431a02943c5f against fetched current main 391b560e5f3311f5ec4b0503684ccd1d0bbd7de4, including the previous review and both open threads. The two previously reported Majors are fixed for the covered cases: an existing Hash#default override is called on misses, its Array result is appended to without storing, and custom-key hash callbacks are linear again (100 keys: 299, matching main; Ruby: 308). The encoding-aware digest and bypass of user Hash#[] / #[]= also pass the focused controls. One new Major / P2 finding remains: caching the absence of Hash#default across execution of the grouping block loses a later method definition for non-plain keys.
Independent validation: fresh ordinary O2 builds of current main and this head with pinned Mere 9dec2ff687a08433247dbdb7729bc19c8522e538 and mgz 661a01d8bb68f5acd68e3192bd47f081d179c436; no runtime binary reuse. Completed 80 base/head executions across ten files, evaluator/VM and hash index ON/OFF, with MERE_RUBY_SHAPES_CHECK=1. All five related corpus files (including expanded 1070), both Hash override probes and the 17×17×6 encoding matrix match Ruby 4.0.10 on head in all four configurations. The callback scaling probe retains main's pre-existing small-table count difference from Ruby; the new dynamic-default probe passes on main and differs on head in all four configurations. GC-root, duplicate/dead-definition, name-length, method-write and bracket-depth (155/1024) gates and diff whitespace checks pass. The bracket gate's first invocation omitted MR_C; it passed when supplied the freshly generated C.
Full corpus, benchmarks, whole-file Rails/resource acceptance and complete Linux/macOS validation were not rerun. Hosted coverage remains incomplete, and current main CI has executing Linux/macOS builds as well as queued coverage. No merge: the actionable finding and recorded hold_all_merges / new_failure_review_required remain blockers. Already-reviewed #317/#326 were also considered; #326 still depends on unmerged #317, and the global hold applies to both. COMMENT because this is the authenticated user's own PR. Existing threads were left untouched.
| // (a program's own Hash#default is asked about every key group_by misses, | ||
| // as rb_hash_aref asks it -- so with one, every element goes through the | ||
| // Hash, and none through the list) | ||
| if has_meth world "Hash" "default" then gb_big world encl theblk true (mkhash Nil) xs |
There was a problem hiding this comment.
[Major / P2] Recheck the default method after yielding to the grouping block
The dflt flag is captured before any block runs and remains false through gb_spill/gb_big. Ruby code in that block can define Hash#default, so the replacement non-plain-key lookup then skips a callback that main's native reader still performs:
begin
p [1, 2].group_by { |i|
if i == 2
class Hash
def default(k = nil)
raise "default installed by grouping block"
end
end
end
[i]
}
rescue => e
puts "#{e.class}: #{e.message}"
endRuby 4.0.10 and current main print RuntimeError: default installed by grouping block; this head returns {[1] => [1], [2] => [2]}. Reproduced on evaluator/VM with the index ON/OFF. The first Array key ensures this is the replaced Hash lookup path, rather than the older small-plain-key shortcut. Please preserve current method lookup on misses after yielding (or invalidate the cached decision when the method table changes), and cover a default installed during iteration. The same cached decision also needs consideration when execution remains in the small-key path.
Whether a program had a Hash#default of its own was decided once, before the block ran, so one defined in the middle of the iteration -- in group_by's own block -- was not asked about the misses after it (#355's review). It is asked on each miss now, through gb_dflt: the answer is kept with mro_gen's epoch, which every write to a method table moves, and asked again only when the epoch has moved. In the list of few keys, a miss with a default now turns the list into the Hash. Instructions retired (GC_TIGHT, median of 3), main / this: 10 elements, 1 / 3 / 10 keys 3.550 / 3.548, 3.682 / 3.689, 3.774 / 3.786 G 100 elements, 20 / 100 keys 3.210 / 3.214, 3.540 / 3.555 G Array keys 2.720 / 2.261 G corpus 1070: a default defined at the 2nd of 2 elements, at the 25th and the 2nd of 30.
284km
left a comment
There was a problem hiding this comment.
Re-review at beb62961. The third Major is fixed. gb_dflt asks whether the program has its own Hash#default on each miss, memoized against the mro_gen epoch, so between two method-table writes it costs one comparison. The small-key list path asks too, and turns into the Hash once a default exists, so a default defined inside the block is called for the misses after it. Corpus 1070 adds definitions at the 2nd of 2 elements and the 25th and 2nd of 30, matching in four modes. Instructions are within +0.4% of main and below the numbers before #351. I will merge once the review bot has reviewed this head.
284km
left a comment
There was a problem hiding this comment.
Re-reviewed exact head beb6296188246baf30c8eef0b726517d5f98a12e against freshly fetched current main b9ca06d6700c44ded301131930a5dbd9107202be and read all three earlier Major/P2 threads. The previously reported findings are fixed in the tested scenarios: a default installed by the grouping block is observed on subsequent misses, an existing default is preserved while bypassing user Hash#[] / #[]=, and the search key's #hash is no longer invoked quadratically. Rechecking the default decision against the method-table epoch also covers the small-key path. No new actionable finding established; the expanded regression corpus usefully exercises both storage paths.
Independent Darwin arm64 validation: 104 main/head executions across 13 files, evaluator/strict VM and hash index ON/OFF, with tight GC and shape checks, against clean Ruby 4.0.10. All five related corpora (493, 515, 1007, 1051, expanded 1070) match reference stdout/stderr/exit status in all 20 head comparisons. The 17×17×6 encoding matrix plus rehash/GC controls matches in all four configurations. Existing-default, original dynamic-definition, custom/nested-key and independent define/restore/prepend/nested-grouping probes match on head. No previously reference-matching main row is lost. The callback-count probe retains main's counts (8/59/299 for 3/20/100 keys); Ruby prints 8/68/308, so those pre-existing small-table differences are not counted as exact passes. Additional undefined-default and per-instance-singleton-default probes retain pre-existing main gaps and are not claimed fixed. Overall, 40/52 head executions are exact reference matches; the other 12 are those three explicitly retained baseline probes.
The head binary is a fresh ordinary O2 build using pinned Mere 9dec2ff6 and mgz 661a01d8. The current-main control reuses the fresh O2 b9ca06d build made earlier in this review session, after rechecking tracked inputs against that commit and dependency blobs against the pinned tree; its binary SHA-256 is b2ebed475a61de9b38e6f0e4b886643af6cebb4a64a970c8a4f209876725e007. No tracked AGENTS.md/CLAUDE.md instructions occur in either tree. Nine source gates, generated-C bracket depth (155/1024), explicit record hygiene and diff whitespace pass. The prospective source integration with current main is clean, but no separate integration binary, full corpus, original whole-file Rails/resource suites, benchmarks or complete Linux/macOS acceptance was run.
No merge: recorded hold_all_merges / new_failure_review_required remains active for these and already-reviewed candidates. Exact-head Linux CI has an executed network-contract failure (net/http/test_http.rb, reference 85 tests/exit 0 versus candidate 85 tests/exit 1), also observed in the preceding main run; this review does not assign a cause or waive it. Other hosted coverage remains incomplete, and newest main CI currently exposes zero jobs. These are not exclusively covered unassigned runner queues. COMMENT because the authenticated account owns the PR. Existing review threads were left untouched.
Follow-up to #351's review (the two Major inline comments).
1. A String key's encoding in the hash index
[[], "ab".force_encoding("UTF-16LE"), "ab".b].group_by(&:itself)made 2 groups instead of ruby's 3. The bug was not in group_by:{[] => 1, u16 => 2, bin => 3}.sizewas also 2 in any hash that had its index.hkey_digesttreated a String as its bytes alone, but ruby's eql? also requires comparable encodings (rb_str_comparable).Some Strings compare by bytes alone: every UTF-8 String, every ASCII-only String in an ASCII-compatible encoding, and the empty String. All other Strings now carry their encoding in the digest. The answer is memoised per encoding index, so a UTF-8 String (no
str_encentry) pays onemap_has.2. group_by past a program's Hash#[] / #[]=
Once group_by's table moved into the Hash, a non-plain key went through
invoke_val_c "[]"/"[]=", which calls a program's ownHash#[]/#[]=. Ruby callsrb_hash_aref/rb_hash_aset. group_by now uses the same internals as the builtin doors, without dispatching through them:hash_touch+hash_lookup_wfor a key with its own#hash, the index otherwisehash_store_key+hput_or_queue_wInstructions retired
MERE_RUBY_GC_TIGHT=1, median of 3, Mere 9dec2ff6.Checked
MERE_RUBY_SHAPES_CHECK=1.Loop record:
loop/2026-11-27-rails-ar-group-by-follow.md.🤖 Generated with Claude Code