Skip to content

Respect Rational comparison overrides and Integer.sqrt arity - #244

Merged
284km merged 5 commits into
mainfrom
codex-misc-numeric-overrides
Nov 25, 2026
Merged

284km merged 5 commits into
mainfrom
codex-misc-numeric-overrides

Conversation

@284km

@284km 284km commented Nov 24, 2026 •

Copy link
Copy Markdown
Owner

Numeric Array min/max and sorting respect redefined comparators, and Integer.sqrt checks its exact one-argument arity even when called inside another class method.

The evaluator's min/max optimization now distinguishes array shapes as CRuby does: it is used only for an unsplatted literal with at least one nonstatic element. Static literals and splats use the ordinary Array method, with the best-so-far value as comparator receiver. Thus, after Rational#<=> is redefined to return 1, [0.5r, 0.25r].max and [0.5r, *tail].max keep (1/2), while a dynamic [Rational(1, 2), Rational(1, 3)].max returns (1/3). The VM already handled these shapes correctly.

Corpus 1100 covers static and splatted Rational/Float literals, dynamic literals, comparison callback order, 1/-1/0/nil answers, min/minmax/sort, comparator restoration, and Array method replacement during element evaluation. Corpus 1101 covers Integer.sqrt calls through class methods, send and Method#call, missing/excessive arguments and valid values. Corpus 930 checks saved native comparator aliases. All match clean Ruby 4.0.10 on evaluator and VM.

Base: main 2e402b94. Reference: clean Ruby 4.0.10 (a704b7cd95), verified with tools/ref_ruby.sh; no reference gems were installed. Ordinary O2 build: Mere 9dec2ff6, mgz 661a01d8. Final binary SHA-256: fb6d7b46def3b6cecb565229710821d1aaf43334539f2d15320e07b5e8b2d035.

Final R5 validation

  • sh run_corpus.sh --both: 883/883 pass, hash indexing ON and OFF.
  • MERE_RUBY_VM=1 sh run_corpus.sh --both: 883/883 pass, hash indexing ON and OFF.
  • Both fresh complete sweeps pass all source gates and full sh mspec/record_hygiene.sh.
  • MR_C=mr.c sh tools/bracket_depth_check.sh: pass, 155 required / 1024 supplied. The updated loop note passes explicit record hygiene.

Unchanged CRuby 4.0.10 files were compared with main 323706a7, one file at a time, using unittest/try.sh, fixed --seed=1, and MERE_RUBY_GC_TIGHT=1. Reference, main and candidate pass every selection on evaluator and VM. Max RSS below is /usr/bin/time -l bytes.

File Tests / assertions Main evaluator RSS Candidate evaluator RSS Main VM RSS Candidate VM RSS
ruby/test_array.rb 22 / 344 178765824 179912704 223510528 220364800
ruby/test_integer.rb 1 / 168 164790272 163512320 167165952 167837696
ruby/test_rational.rb 1 / 26 165347328 163954688 169476096 172539904
ruby/test_optimization.rb 2 / 24 170016768 170672128 171753472 170196992

Selections: test_array min/max/minmax, sort/sort!, incomparable and replacement/freeze cases; test_integer square_root; test_rational cmp; test_optimization array_min/array_max.

Hot-path cost

The generation-cached unchanged-comparator check remains in place. The deterministic 2,000-element / 200-iteration bench/numeric_comparison_overrides.rb --seed=1 was repeated as three alternating main/candidate runs per engine with tight GC. Every run prints 983200.0. Median instructions and maximum RSS across the three runs:

Engine Main instructions Candidate instructions Change Main max RSS bytes Candidate max RSS bytes
Evaluator 33667977953 33730502090 +0.19% 110559232 110723072
VM 33636517143 33685184567 +0.14% 112345088 111820800

The baseline is unchanged main 323706a, built with the same compiler/mgz pins. The new static-expression classifier adds no global object retention or cache. The earlier review confirmed ordinary Integer/Float/Rational arithmetic/comparison loops unchanged; these fresh measurements also include the array-shape correction.

Existing follow-ups recorded by review remain outside this correction: Integer/Rational coerce dispatch, max(n), each.max, max_by, sort_by, Array#<=>, and Rational#coerce/#== overrides. No full unit suite or Rails component suite was run. No workflow, upstream assertion, corpus exclusion or resource budget was changed. Code, regression cases and the completed loop record are pushed together.

@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 latest head 4764eec778c42dab76e68f9e796f6d737aa39418 against fetched current main 323706a71663464523037f00155a5c79917caa7e, including both commits, Array literal/ordinary dispatch, comparison helpers, saved native operators and Integer.sqrt's class-method boundary. Existing reviews, discussion and inline threads were empty; no tracked AGENTS.md or CLAUDE.md was found. No new actionable findings.

The separate literal/ordinary comparison direction and post-element method-replacement check preserve observable callback behavior. The latest correction keeps saved native numeric comparators as leaves while applying Ruby overrides at the Array comparison sites.

Independent focused validation on Darwin arm64, using clean Ruby 4.0.10 as reference:

  • Corpus 1100 and 1101 match stdout and exit status in evaluator and VM modes with GC stress period 50.
  • Existing corpus 930 also matches on both engines, covering the saved-native-operator regression documented during the earlier development sweep.
  • An additional TracePoint probe preserves all eight c_call/c_return events for literal and ordinary Array min/max on both engines.
  • All 8 executions match. Seven source gates (duplicate/dead definitions, name lengths/specification, namespace names, method writes and regex-capture writes) and diff whitespace checks pass.

Build reuse: I verified all 2,426 tracked files in the existing candidate checkout against fetched head and checked the clean pinned mgz submodule. The copied local O2 candidate SHA-256 is 887b27a3ba29a5c3082ef9b58981f56138ed06ad8c8507d27e8b26f67a31d3c4; O2 build mode and the successful build log were inspected. This is a reused local build, not a fresh compilation or downloaded CI artifact.

The prospective integration with current main is conflict-free (tree faa530dd41e41f57837aec122af614921271bbf1) but was not built/tested. I did not independently rerun the selected upstream files, full corpus, whole-file comparisons or platform/resource/performance acceptance. The reported earlier development-sweep failure is preserved; passing these focused cases does not establish a full corrected sweep. Current hosted Linux/macOS builds and supplementary tests are executing, with reference/downstream coverage incomplete. No merge: the PR remains a draft and the recorded global merge holds remain active. COMMENT is used because the authenticated account owns the PR.

@284km
284km marked this pull request as ready for review November 25, 2026 01:44

@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 c8a28e2 by reading. I could not find a clean build of this head on the machine to run probes against, so this review is reading only. No Critical / Major findings in the logic. One Minor about missing evidence:

  • What I read:
    • [a, b].max / .min on a literal array keeps CRuby's opt_newarray_send direction (the later element is the receiver), falling back to the Array method if it was replaced or refined, including a replacement made while the elements are evaluated.
    • Ordinary Array#min / max / minmax use the best-so-far as the receiver.
    • opt_cmp steps aside for a redefined <=> on the element's class.
    • sort / sort! take the world-aware path when numeric_cmp_changed.
    • Integer.sqrt checks its argument count.
    • The corpus 930 regression found during development (a saved native Float#<=> recursing) is covered.
  • Minor: hot-path cost not shown.
    • opt_cmp now calls numeric_user_method for every numeric comparison, and every Array#sort on numbers calls numeric_cmp_changed, which makes three lookups.
    • These are the common paths for min / max / sort of Integers and Floats.
    • Please post instruction counts before and after, on both modes, for a loop like:
      a = Array.new(2000) { |i| (i * 7919) % 2003 }; f = a.map { _1 * 0.5 }
      s = 0; 200.times { s += a.max + a.min + f.max; s += a.sort[3]; s += [a[1], a[2], a[3]].max }; p s
      On main (323706a + #253) it takes 33.6 G instructions on the evaluator and 33.6 G on the VM, and prints 983200.0 like ruby.
    • If the cost is visible, cache the "no comparator changed" answer behind the method-table generation, as int_ops_plain does.
  • git merge-tree against current main: clean. No mere-pr-review-watch inline comments.

@284km
284km marked this pull request as draft November 25, 2026 03:24
@284km

284km commented Nov 25, 2026

Copy link
Copy Markdown
Owner Author

Addressed in c91e8f0. The requested probe initially cost about 2.7% more instructions, so the unchanged-comparator answer is now cached by method-table generation. The repeated fixed-seed tight-GC probe prints 983200.0 throughout: evaluator main 33,777,153,198 -> candidate 33,800,438,393 instructions (+0.07%); VM 33,635,367,980 -> 33,675,326,648 (+0.12%). Max RSS is 110,575,616 -> 110,837,760 bytes and 112,377,856 -> 111,869,952 bytes. The baseline is the unchanged main 323706a O2 binary using the same pinned compiler. The benchmark is committed as bench/numeric_comparison_overrides.rb. Corpus 1100 now primes the plain cache before replacing Rational#<=>; it and corpus 930 match both engines. All selected unchanged upstream cases were repeated and pass. The corrected binary's full evaluator/VM corpus sweeps are running; the previous 883/883 sweeps in the record refer to R3.

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

Follow-up review of exact head c91e8f08b9ed0167f7cb8010aee17143fefa45d6, compared with the previously reviewed head and fetched current main a63e47c366505074dab80db9285b8a7b3b6d051b. I read existing reviews, discussion, the updated validation record, cache implementation and its callers. No tracked AGENTS.md/CLAUDE.md instructions were found in main or head.

The prior Minor request for hot-path evidence is addressed in the description and committed benchmark. The reported instruction deltas are now +0.07% / +0.12%; I did not independently repeat hardware-instruction measurements. The implementation caches only two integers behind the method-table generation, so comparator replacement invalidates the cached answer. Corpus 1100 now primes the unchanged-comparator cache before replacing Rational#<=> and also covers restoration. I found no new actionable issue in this update.

Independent Darwin arm64 validation: corpus 1100, 1101 and 930 match clean Ruby 4.0.10 in stdout, stderr and exit status on evaluator and VM with GC stress period 50 (six matching executions). Duplicate-definition, dead-definition, GC-root and diff-whitespace checks pass. An initial 930 invocation used an incorrect filename and produced no valid test result; the actual 930_saved_native_operators.rb passed on both engines.

Build reuse: all 2,427 tracked regular files match the exact head byte for byte, mgz is clean at pinned 661a01d8bb68f5acd68e3192bd47f081d179c436, and the successful ordinary O2 build log uses compiler 9dec2ff687a08433247dbdb7729bc19c8522e538. Copied binary SHA-256 ed496413f3d5a34457765d8806e692f53fb08be918b1844d090b022a8c5bc128. The GC-root check used this existing build's generated C after source verification. This was not a fresh compilation or tested integration with newer main. I did not independently rerun full corpus, complete upstream files, performance or resource acceptance; R3 whole-corpus results remain historical and final R4 sweeps remain pending.

Hosted run 45539851133 has executed failures: unittest-harness fails because unittest-vm is missing from the CI-timing report's needs (the same assertion was independently reproduced on fetched main); build-linux fails C API verification with capi/vendor/erb_escape.c is not the tree's file, skipping downstream checks. These are not just unassigned queues and are not waived by focused passes. No merge: the PR is draft and recorded global merge holds remain active. COMMENT is used because the authenticated account owns this PR.

@284km
284km marked this pull request as ready for review November 25, 2026 04:19

@284km 284km left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Re-review of head c91e8f08. This time I ran probes. The binary in the branch's own checkout matches the head: the tree is clean apart from the loop record, the binary is newer than every .mere file, and its SHA-256 is ed496413..., the same as the bot's verified build. The main build is an O2 build of the merge base 2e402b94 with the same mgz pin. The reference is Ruby 4.0.10. "Evaluator" means the default engine; "VM" means MERE_RUBY_VM=1.

Earlier findings

  • Ours, Minor: hot-path cost not shown → resolved (verified by running). The PR body and the comment now give instruction counts. numeric_cmp_changed caches its answer by the method-table generation. My counts (/usr/bin/time -l, MERE_RUBY_GC_TIGHT=1, median of 3, runs alternating between builds) agree with the posted ones:

    Loop Engine main 2e402b94 PR Change
    bench/numeric_comparison_overrides.rb evaluator 33,592,915,427 33,656,676,570 +0.19%
    same VM 33,603,303,218 33,651,011,209 +0.14%
    Integer/Float/Rational + - * % /, < <= > <=>, and Array max/min/sort/minmax on 500-element arrays (no literal [a, b].max) evaluator 24,531,264,295 24,508,102,049 -0.09%
    same VM 19,180,106,460 19,179,160,555 -0.00%
    the same loop plus [i, s].max and [f, 1.5].min in each step evaluator 28,215,043,814 25,315,492,678 -10.3%
    same VM 23,120,760,810 19,619,583,253 -15.1%

    The PR body reports +0.07% / +0.12% against 323706a7. My 323706a7 build gives about the same counts as 2e402b94. The plain numeric paths are unchanged. A literal [a, b].max is now faster because it no longer goes through the method call. All runs print the same value as Ruby.

  • Bot, 4764eec and c91e8f0: no actionable findings. There are no bot inline comments. Nothing is open from the bot.

New finding

  • Minor: on the evaluator, a static literal array or an array with a splat takes the opt_newarray_send comparison order. CRuby does not compile these with opt_newarray_send. A static literal (for example [0.5r, 0.25r] or [1.5, 2]) compiles to duparray followed by an ordinary Array#max call. A literal with a splat compiles to an ordinary call too. (Check with ruby --dump=insns.) So Ruby asks the best value so far, not the later element. The VM's ISeq compiler already does this correctly. The evaluator's new EMethod (EArr es, ...) branch matches every literal. Witness:
    class Rational
      alias orig <=>
      def <=>(other) = 1
    end
    s = [0.25r]
    p [0.5r, 0.25r].max, [0.5r, 0.25r].min, [0.5r, *s].max, [0.5r, *s].min
    class Rational
      alias <=> orig
    end
    Ruby 4.0.10, the PR's VM, and main's evaluator all print (1/2) (1/4) (1/2) (1/4). The PR's evaluator prints (1/4) (1/2) (1/4) (1/2). The same happens with Float#<=> and [1.5, 2].max. So the two engines now disagree, and the evaluator got worse than main for these shapes. Corpus 1100 does not cover this, because its literals are Rational(1, 2) calls, which are not static. Fix: take the literal branch only when no element is a splat and at least one element is not a static literal. That is the rule CRuby's compiler uses, and the VM compiler follows it.

Checked and matching Ruby 4.0.10 on both engines (PR build)

  • Corpus 930, 1100 and 1101.
  • Integer#<=> and Float#<=> overrides: max, min, minmax, sort, sort!, a non-static literal [x, y].max, and [[1, 2], [1, 3]].sort. The callback order is correct too. Only the number of comparisons inside sort differs (2 against 3), which depends on the sort algorithm.
  • Cache invalidation: a module prepended to Rational, with <=> defined after the prepend and then removed; define_method(:<=>) in class_eval; alias_method back to the original; a refinement of Rational#<=> (correctly ignored).
  • A Numeric subclass with its own <=>, coerce and +.
  • Integer.sqrt with 0, 1, 2 and 3 arguments, a splat, a keyword hash, send and Method#call.
  • The only regressions against main that I found are the three lines of the new finding above.

Pre-existing gaps (not caused by this PR; main behaves the same)

These are Suggestions for later work, not merge blockers:

  • An Integer receiver with a Rational argument. In Ruby, Integer#<=> coerces and then calls the overridden Rational#<=>. Mere compares directly. With <=> always returning 1, Ruby gives [1, Rational(3, 2)].max → 1. Mere gives (3/2). The PR scopes itself to the receiver's own <=>, so this is outside it.
  • max(n), Enumerable#max (each.max), max_by, sort_by and Array#<=> still ignore an overridden numeric <=>. An undefined Rational#<=> still compares instead of raising NoMethodError.
  • Overrides of Rational#coerce and Rational#== are not called from Integer/Float operators or include?.

Unit tests (run by me, unittest/try.sh, seed 1, tight GC, whole files)

PR and main give the same per-test results on both engines:

  • test_rational: 52 tests, 0 F/E.
  • test_float: 63 tests, 0 F/E.
  • test_comparable: 11 tests, 0 F/E.
  • test_integer: 1 E. It is a test_pow timeout, the same on main.
  • test_optimization: 3 F. The same three tests fail on main (string freeze memory, two tailcall tests).

Not checked by me

I did not run the full corpus, the MERE_RUBY_VM=1 corpus or the gates. The PR body says the R4 binary passes 883/883 in both sweeps with hash indexing ON and OFF, with all gates. The committed loop record still says those sweeps "are running". The update exists only in the local checkout, so please commit it.

Integration and CI

git merge-tree --write-tree with current main (003a5892) is clean. CI: build-linux fails in the erb_escape headers check (known, fixed by #273). unittest-harness fails in ci_timing_check (known, fixed by #275). build-macos, unittest-reference and the gem suites are still queued.

Comment thread main.mere Resolved
@284km
284km marked this pull request as draft November 25, 2026 04:49
@284km
284km marked this pull request as ready for review November 25, 2026 05:57

@284km 284km left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Re-reviewed 03a66fb. The Minor from the last review (the evaluator used opt_newarray_send's comparison order for static and splatted literals) is resolved. No Critical / Major / Minor findings remain.

  • extreme_literal_array now takes the newarray_send branch only when there is no splat and at least one element is not a static literal, which matches how CRuby compiles [..].max / .min (duparray + an ordinary call for static literals and splats).
  • Ran on the author's build at this head (clean tree, binary newer than every .mere file), on the evaluator and MERE_RUBY_VM=1, against ruby 4.0.10: corpus 1100 is identical, and an extra probe with Rational#<=> always 1 is identical too: [0.5r, 0.25r].max/.min, [0.5r, a].max (dynamic, newarray_send order), [0.5r, *t].max, [1/2r, 1/4r].max, negative rationals, plus ordinary Integer/String/Symbol literals after restoring <=>.
  • The loop note now records the R5 acceptance: corpus --both and MERE_RUBY_VM=1 --both 883/883 with hash indexing ON and OFF, the source gates, record_hygiene, the bracket gate, the related upstream selections with RSS, and the hot-path instructions (+0.19% evaluator, +0.14% VM).
  • git merge-tree against current main: clean. No mere-pr-review-watch inline comments.

Merging.

@284km
284km merged commit ecb2a78 into main Nov 25, 2026
10 of 19 checks passed
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