Skip to content

Honor Hash conversion hooks in Array joins - #412

Merged
284km merged 3 commits into
mainfrom
codex-misc-hash-join-protocols
Nov 30, 2026
Merged

284km merged 3 commits into
mainfrom
codex-misc-hash-join-protocols

Conversation

@284km

@284km 284km commented Nov 30, 2026

Copy link
Copy Markdown
Owner

Array joins now ask Hash elements for to_str, then to_ary, before falling back to to_s. Hash-subclass and singleton overrides participate in both the top-level string preflight and the actual join. Match Ruby's repeated conversion calls, private methods, native aliases, missing-method decline, TypeErrors for incorrect conversion results, and recursive conversion guards. Error messages use ordinary class names, including subclass results and singleton receivers.

The existing Hash inspection/fallback and encoding behavior from #395 is preserved. Ordinary untagged Hash receivers use a protocol cache keyed by method generation with two integer slots and an integer tag lookup; they do not build an hng_key for each element. The cache is invalidated when methods change, including a callback defining a new conversion during the join, and unrelated classes' aliases do not disable it. It retains no anonymous owner or Ruby object.

Corpus 1164 covers string/array precedence, nil/wrong returns, private/singleton/native-alias methods, respond_to?/respond_to_missing?/method_missing, recursion, nested arrays, encoding, class-level hook addition/removal and callback redefinition. It matches ruby on both engines, including GC stress. Existing join controls 976 and 1009 match on both main and the candidate.

Original CRuby ruby/test_array.rb, unchanged: test_join, test_join2, test_join_recheck_elements_type, test_join_recheck_array_length, including inherited Array-subclass cases: 8 tests, 88 assertions, 0 failures/errors/skips on reference, current main evaluator/VM and candidate evaluator/VM.

Validation uses main 9d1c0f3, clean ruby 4.0.10 through tools/ref_ruby.sh, pinned Mere 9dec2ff6 and mgz 661a01d8, ordinary O2. Candidate SHA-256: 2f9c210d9c667b1bfed40b797834533a0c526a2d2586d653ace9c6ccf271d1d3. Runtime input hashes are verified before and after runs; evaluator runs leave MERE_RUBY_VM unset.

  • sh run_corpus.sh --both: 1040/1040 PASS, index on/off.
  • MERE_RUBY_VM=1 sh run_corpus.sh --both: 1040/1040 PASS, index on/off.
  • MERE_RUBY_VM=1 sh tools/iseq/vm_corpus.sh -j 2: 1040 on the VM, 0 fallback, 0 FAIL.
  • All source gates pass: StrBuf region ownership, GC roots, duplicate/dead definitions, method writes, ivar door, names/namespaces/lengths, regexp captures, bracket depth. Packed GC mark checks pass under O2 and ASan/UBSan; record_hygiene and staged/unstaged whitespace checks pass.

bench/hash_join_conversions.rb MODE 10000 --seed=1 versus the same mode with count 0, on the same pinned binaries. Each engine uses MERE_RUBY_GC_TIGHT=1 and three alternating main/candidate pairs. Per-call instructions are (median I(10000) - median I(0)) / 10000, including loop dispatch; RSS is the maximum of the three count-10000 runs, in MiB. These measurements include the loop and use the workload committed in this PR.

Workload Engine Instructions/call, main → candidate Change Max RSS, main → candidate
plain evaluator 46,342.6 → 46,768.1 +0.918% 84.922 → 84.906
plain_alias evaluator 46,301.3 → 46,483.6 +0.394% 84.875 → 84.906
subclass evaluator 59,525.3 → 88,281.3 +48.309% 84.422 → 84.391
string evaluator 28,230.1 → 28,173.0 -0.202% 82.125 → 82.156
plain VM 48,233.3 → 48,744.8 +1.061% 84.891 → 84.906
plain_alias VM 48,337.6 → 48,795.2 +0.947% 84.891 → 84.953
subclass VM 62,465.4 → 91,523.7 +46.519% 85.531 → 85.500
string VM 29,891.2 → 30,269.7 +1.266% 82.094 → 82.156

The subclass workload deliberately defines to_str and to_s with the same output: main skips the required to_str calls, while the candidate performs Ruby's preflight and actual conversion. Its extra dispatch cost is reported rather than treated as an equivalent path without conversion overrides. plain_alias defines a native alias only on an unrelated Hash subclass; ordinary Hash joins stay on their ordinary path. No collector or arena-policy changes are included.

Local validation is complete; exact-head review and hosted CI remain. No runner-queue exception or merge-hold waiver is claimed.

@284km 284km left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed exact head 5e5a093 against PR base 9d1c0f3 and current main 98aa453. No new actionable findings.

The Hash conversion path preserves to_str/to_ary/to_s precedence, checks conversion result types, and guards recursive conversions. The ordinary-Hash cache stores only integer facts and rechecks method generations; the regression coverage for callback redefinition and unrelated native aliases is useful.

Independent validation in isolated temporary checkouts:

  • Fresh ordinary O2 builds of head and current main with local Mere v0.1.732 and mgz 661a01d8. Candidate SHA-256: 6ab9ff96e63c47307cb5a54751c23a909431835fd15211b5fbe22333eb9613e7. Main SHA-256: f7ff7b5ac130ad4d566700a22f76a79b8e259c80721e2e0f8d4ed3658128d18d. Both tracked trees remain clean; all 2,900 candidate repository/dependency file hashes remain unchanged across the final validation. Reference: clean Ruby 4.0.10 via tools/ref_ruby.sh; evaluator runs leave MERE_RUBY_VM unset.
  • Corpus1164 matches Ruby on evaluator and VM, each under default settings, hash index disabled, GC stress=32, or method cache disabled (8/8). Existing corpus976/1009 match on both revisions in all eight configurations (32/32 comparisons). Main does not match the new fixture, as expected.
  • An independent 43-case probe covers wrong/nil conversion results, private/native/inherited aliases, missing-method hooks, multiple Hash elements, callback changes to methods and array contents, recursion, GC, refinements, and anonymous included/prepended modules. Every configuration retains all five reference-matching main cases and increases that count to 42. The remaining array-shift case diverges on both revisions: Ruby raises EncodingError after the conversion mutates the leading array elements; candidate returns the joined shortened array. This is not a full conformance pass.
  • The unchanged original ruby/test_array.rb, selecting test_join/test_join2/test_join_recheck_elements_type/test_join_recheck_array_length including inherited Array-subclass cases: 8 tests, 88 assertions, 0 failures/errors/skips on reference, main evaluator/VM, and candidate evaluator/VM.
  • Generated-C/source StrBuf ownership, GC roots, duplicate/dead definitions, method writes, ivar door and diff whitespace checks pass.

I did not independently repeat the full corpus sweeps, performance measurements, sanitizer runs or platform/resource acceptance reported by the author. Hosted CI is incomplete: build-linux and gem suites are executing; build-macos, unittest-reference and additional coverage are queued. Latest main CI run46359889217 was inspected job by job: plan/harness/build-macos succeeded, build-linux is executing, and reference/corpus are queued; downstream completion is not established. No runner-queue exception or recorded global merge-hold clearance is claimed. This remains draft and is not merged.

@284km
284km marked this pull request as ready for review November 30, 2026 05:39

@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 5e5a093c (main.mere in Array#join's Hash arm, a generation-stamped cache in m_state.mere, corpus 1164, bench).

  • A Hash element of join now goes through to_str, then to_ary (joined recursively with the same separator and the recursion guard), then to_s, as CRuby's ary_join_1 does. Wrong return types raise the TypeError message Ruby gives. The top-level pre-pass also probes the first Hash's to_str, matching rb_ary_join's first loop. Corpus 1164 covers subclasses, singleton/aliased hooks, respond_to? arity and include_all, method_missing, wrong return types and recursion.
  • An ordinary Hash skips all probing via plain_hash9. It checks that Hash itself defines none of the five hooks and caches the answer per MRO generation, so plain joins stay within ~+1%.
  • Cost note: a Hash subclass element costs +48% per join (59k → 88k instructions, evaluator), because it really has to be asked. That is required by the semantics and is in the body; fine.

No findings from me.

@284km
284km merged commit f0f372e into main Nov 30, 2026
15 of 19 checks passed
@284km

284km commented Dec 1, 2026

Copy link
Copy Markdown
Owner Author

Investigated the intermittent build-linux Module gate timeouts at f0f372e7, comparing 98aa4531, ce0fd9cf (#408), and f0f372e7 (#412).

Conclusion: the evidence supports runner-dependent throughput exposing pre-existing tight timeout headroom. There is no material local slowdown attributable to #408 or #412. The failing and passing f0f372e7 jobs ran byte-identical Linux binaries. The available logs cannot distinguish CPU hardware/provider performance from contention; calling this proven CPU load specifically would overstate the evidence.

CI evidence and actual headroom

These are case times from the uploaded class-module-Linux/module.log artifacts. Each child has upstream's original 10-second timeout; case times include a little parent overhead.

Run / source iclass complemented entry clone control prepend_gc control Complete file
46359889217, 98aa4531, green 9.30 s 8.86 s 5.02 s 1.16 s 31.831 s
46362164472, f0f372e7, failed 10.05 s, timeout 10.04 s, timeout 6.30 s 1.52 s 36.854 s
46425224035, same f0f372e7, scheduled pass 7.50 s 6.84 s 4.03 s 0.90 s 25.436 s

The green pre-change run had only 0.70 s / 7.0% and 1.14 s / 11.4% nominal headroom. The scheduled pass had 2.50 s / 25.0% and 3.16 s / 31.6%. Thus the marginal budget predates both changes. The failed runner was slower on the unrelated controls too: clone 1.56x, prepend_gc 1.69x versus the scheduled pass.

Both f0f372e7 artifacts report binary SHA-256 6c1dc1d1772d5de0828c9d4c3180402db3d5764ae120a4ec2b50fc37b238e86e, compiler 9dec2ff687a08433247dbdb7729bc19c8522e538, test SHA-256 6b9b0fe714d15e2d08ac9ac6954b5f429754b2507eec2960b9544bc54eb8cdbc, and runner image ubuntu-24.04 / 20261122.23.1. Their provisioner logs differ: Azure/eastus for the failure, AWS/us-west-2 for the pass. The failed file completed with 195 tests / 1,234 assertions / 0 failures / 2 timeout errors; both green files had 195 / 1,240 / 0 / 0 / 0 skips. The outer 600-second / 2-GiB supervisor did not fire.

Local comparison: median of three, both engines

Separate clean source worktrees, each built with the exact CI-pinned Mere compiler commit above, mgz 661a01d8bb68f5acd68e3192bd47f081d179c436, and ordinary sh tools/build.sh (O2, compiler-default native region cache 64). Host: Apple M2 Pro, macOS arm64, Apple clang 21.0.0. These are native macOS measurements with CI's compiler revision/build mode, not Linux/x86-64 instruction counts or a claim that the binaries match the Linux executable.

Ruby source/reference: a704b7cd95a42cc0cf5f307137bf3aac0285b915 / Ruby 4.0.10. Selected the unchanged original tests with -n /test_iclass_memory_leak/ and -n /test_complemented_method_entry_memory_leak/, using the gate's environment/bootstrap and seed 1. Evaluator: MERE_RUBY_VM absent; VM: MERE_RUBY_VM=1. MERE_RUBY_VM=why confirmed both captured child programs are eligible for the VM.

No builds or profiling overlapped these benchmarks. Repetitions alternated commits (baseline→#408→#412, reverse, forward), sequentially. A parent-only EnvUtil.invoke_ruby observer captured the input and put /usr/bin/time -l -o FILE in the child precommand. Wall time is monotonic time around that original child invocation; instructions are hardware instructions retired for the leak child, including its startup/preparation/memory probes/final GC, not interpreter bytecode counts or the whole 195-test parent. Input, iterations, original 10-second timeout, and both < 2.0 memory assertions were preserved. The only input differences across the 18 runs per test were upstream's random diagnostic tokens. All 36 selected runs passed: one test / three assertions each, 108 assertions total, no failures/errors/skips.

Engine Test Source Child wall, median Retired instructions, median (billions)
evaluator iclass 98aa4531 4.483 s 49.26839
evaluator iclass ce0fd9cf 4.555 s 49.28193
evaluator iclass f0f372e7 4.498 s 49.28861
evaluator complemented entry 98aa4531 5.360 s 59.50229
evaluator complemented entry ce0fd9cf 5.386 s 59.42088
evaluator complemented entry f0f372e7 5.432 s 59.47482
vm iclass 98aa4531 4.762 s 50.82413
vm iclass ce0fd9cf 4.799 s 50.81978
vm iclass f0f372e7 4.847 s 50.84341
vm complemented entry 98aa4531 7.934 s 82.82837
vm complemented entry ce0fd9cf 7.883 s 82.84483
vm complemented entry f0f372e7 7.954 s 82.80419

Across both changes and all four engine/workload combinations, median instructions stay within 0.14% of 98aa4531. For #412 versus that baseline, median wall changes are +0.34% / +1.35% (evaluator iclass / complemented) and +1.79% / +0.25% (VM); median instructions change +0.041% / −0.046% / +0.038% / −0.029%. This does not reproduce the roughly 1.6–1.7x CI throughput difference.

Where the leak loop spends time

Separate diagnostic runs on f0f372e7 added monotonic timestamps and GC.total_time / GC.count reads immediately around the original loop and timed the original final GC.start. These instrumented observations are not included in the medians above.

Engine Loop Loop wall GC inside loop Collections inside loop Final GC wall
evaluator iclass 4.480 s 2.056 s (45.9%) 182 7.49 ms
evaluator complemented entry 5.334 s 1.413 s (26.5%) 150 8.64 ms
vm iclass 4.433 s 2.100 s (47.4%) 182 7.49 ms
vm complemented entry 7.844 s 2.047 s (26.1%) 372 3.87 ms

Three-second sample runs (1-ms interval) used the exact original captured child input, separately from timing. On the evaluator iclass worker, GC occupied 1,177/2,563 samples (45.9%); gc_sweep_classes occupied 690 (26.9%, included in GC), and core_metadata_build 1,174 (45.8%, outside GC). gc_sweep_class_table occupied 545 (21.3%) and gc_class_owner 244 (9.5%); these are nested inclusive counts, not additive. The complemented-entry worker spent 660/2,555 samples in GC (25.8%) and 323 (12.6%) in class sweeping. The main thread's pthread_join wait was excluded from these worker percentages. This is repeated class metadata construction/marking/sweeping during the loop, not a long final GC or a slow memory-status subprocess.

Proposed fix

Keep the upstream 10-second child deadline, original iteration counts, and memory assertions. Target class-metadata construction and collection cost in a separate optimization: reuse owner classification within a collection across marking and the many gc_sweep_class_table walks, and reduce the string-key/map allocation and survivor-compaction work shared by core_metadata_build / the class tables. For example, a collection-scoped owner index can avoid reparsing the same anonymous class/method owner in several tables without introducing permanent Ruby roots or changing when classes die. Source points: gc_class_owner, gc_sweep_class_table, core_metadata_build.

That is an optimization proposal supported by these profiles, not an implemented or measured speedup. Require unchanged full Module acceptance (195 tests / 1,240 assertions / zero failures/errors/skips), both engines, unchanged memory bounds, and demonstrate at least 2 seconds of child headroom (target ≤8 s, median of three) on the slower Linux runner class before calling the flake repaired. Record CPU model/provider and CPU/pressure telemetry for that verification so hardware differences and contention can be separated. Retrying identical code can confirm runner variation but does not add headroom.

No source/CI timeout change or revert of #408/#412 is warranted by this comparison. In particular, the two timed-out children were killed before completion: 10.05/10.04 s are censored durations, not evidence that a 10.1-second limit would suffice. No limit was raised.

All three local samples (wall seconds / retired instructions in billions), in repetition order
Engine Test Source Repeat 1 Repeat 2 Repeat 3
evaluator iclass 98aa4531 4.584656 / 49.349592336 4.397483 / 49.236454673 4.482654 / 49.268388454
evaluator iclass ce0fd9cf 4.423520 / 49.366129239 4.583286 / 49.281927030 4.555190 / 49.185619079
evaluator iclass f0f372e7 4.541523 / 49.301978908 4.496226 / 49.237194489 4.497864 / 49.288608721
evaluator complemented entry 98aa4531 5.271094 / 59.502293038 5.359570 / 59.486448868 5.420210 / 59.539897095
evaluator complemented entry ce0fd9cf 5.449232 / 59.420880098 5.347098 / 59.465015736 5.386089 / 59.331688042
evaluator complemented entry f0f372e7 5.527028 / 59.519305883 5.432123 / 59.474820074 5.423821 / 59.466225441
vm iclass 98aa4531 4.708748 / 50.867079060 4.776189 / 50.824131702 4.761923 / 50.778575443
vm iclass ce0fd9cf 4.799027 / 50.819777936 4.752555 / 50.879096084 4.810398 / 50.787393643
vm iclass f0f372e7 4.775401 / 50.952495553 4.865158 / 50.808358020 4.847286 / 50.843413846
vm complemented entry 98aa4531 7.729917 / 83.052024424 7.934421 / 82.828367388 7.964422 / 82.592651996
vm complemented entry ce0fd9cf 7.420421 / 82.844831162 7.882703 / 82.994753557 7.945609 / 82.780326452
vm complemented entry f0f372e7 7.954153 / 82.750865383 7.795520 / 82.829551897 8.039501 / 82.804190110

Build provenance (local executable SHA-256):

  • compiler: 0591c876caf98c8d3d03fca02590add6aa3944a80d07c1267613a35a3621c591
  • 98aa: 3842c51f590dc3a0ab9005022307dc374fca9fb8e912337e335ad9a5b79cfe5f
  • ce0f: 9f78a21dab2200980b5ccfd92d8381dd6d473b1ac76db4c714c42007517fe45e
  • f0f3: 21fbbb956bd78ca38c0894603e2c0b974701977c4b90118303ff511da23decce

Canonical child-input SHA-256 after replacing only upstream's two random tokens: iclass 79298f273c647ae9dea709fb32021af830f484101218bf74b87069d49af88d8a; complemented entry d72dac14e7ab74fc09b0e3ff5f0bab8b8e8468fa7167cfeda2c9342f36fbfa48.

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