← Back to PRs

#20799: fix: replace Math.max/min spread with reduce to prevent stack overflow

by mariusorani open 2026-02-19 09:36 View on GitHub →
size: XS
## Summary Fixes #20789 Replace spread operator usage in `Math.max/Math.min` calls with reduce-based alternatives to prevent `RangeError: Maximum call stack size exceeded` on large arrays (>100k elements). ## Changes ### `src/memory/mmr.ts` - `mmrRerank`: Score normalization now uses reduce instead of spread ### `src/infra/outbound/target-resolver.ts` - `pickAmbiguousMatch`: Rank selection now uses reduce instead of spread ### Not changed: `src/agents/auth-profiles/usage.ts` The array in `resolveProfileUnusableUntil` is filtered from a 2-element source (`[cooldownUntil, disabledUntil]`), so it will always have at most 2 elements. This is **not** a stack overflow risk and was intentionally left unchanged. ## Testing - [x] Changes are minimal and focused - [x] Logic remains identical (same min/max behavior) - [ ] CI checks ## AI Disclosure This PR was AI-assisted (Claude). I understand what the code does — it's a straightforward replacement of spread-based Math.max/min with reduce-based equivalents that handle large arrays safely. <!-- greptile_comment --> <h3>Greptile Summary</h3> Replaces `Math.max(...array)` and `Math.min(...array)` spread operators with `reduce()` implementations to prevent stack overflow on large arrays (>100k elements). **Changes:** - `src/memory/mmr.ts:140-141` - Score normalization in `mmrRerank()` now uses reduce for finding max/min scores - `src/infra/outbound/target-resolver.ts:321` - Rank selection in `pickAmbiguousMatch()` now uses reduce for finding best rank **Technical correctness:** The logic is identical - reduce-based implementations correctly replicate Math.max/min behavior while avoiding the call stack limit imposed by the spread operator. <h3>Confidence Score: 5/5</h3> - Safe to merge - focused fix with identical logic and no risk - The changes are minimal, well-documented, and maintain identical behavior while fixing a real stack overflow issue. The reduce implementations correctly handle edge cases (empty arrays, single elements) and the PR author correctly identified that `src/agents/auth-profiles/usage.ts` doesn't need changes since it only operates on 2-element arrays. - No files require special attention <sub>Last reviewed commit: 88a9fd2</sub> <!-- greptile_other_comments_section --> <sub>(3/5) Reply to the agent's comments like "Can you suggest a fix for this @greptileai?" or ask follow-up questions!</sub> <!-- /greptile_comment -->

Most Similar PRs