Skip to content

Fix catastrophic backtracking in numeric regexes - #50

Merged
jakeboone02 merged 1 commit into
mainfrom
fix/numeric-regex-backtracking
Sep 9, 2026
Merged

Fix catastrophic backtracking in numeric regexes#50
jakeboone02 merged 1 commit into
mainfrom
fix/numeric-regex-backtracking

Conversation

@jakeboone02

@jakeboone02 jakeboone02 commented Sep 9, 2026

Copy link
Copy Markdown
Owner

Capture group 2 of both numeric patterns was an ambiguous nested quantifier:

-((?:\d(?:[,_]\d|\d)*)*)
+((?:\d(?:[,_]\d|\d)*)?)

Every string the inner group matches begins and ends with a digit, so concatenating two of them yields another string of the same shape. The outer * added no strings to the language, only exponentially many ways to split one digit run across iterations — which the engine explores in full whenever the overall match fails.

numericRegex.exec('1'.repeat(30) + '!') on Node/V8: 15.6 s → 0.08 ms. Growth is now flat rather than 4× per two digits.

Equivalence

? and * accept the same language here, so this is a pure performance change:

  • The reachable match lengths are identical — any prefix of the digit run that ends on a digit, since neither form can stop immediately after a , or _.
  • Both forms are greedy and explore those lengths longest-first, so the captured text is unchanged.
  • The group count is unchanged, so groups 1–7 keep their documented numbering.

A new test asserts this empirically: it reconstructs the old pattern from the new one and compares exec results across ~30 inputs covering separators, decimals, exponents, fractions, mixed numbers, signs, malformed separators, and trailing invalid characters. The existing 550-case fixture suite is unchanged and passes.

Scope

numericRegexWithTrailingInvalid carries the same construct and is fixed alongside numericRegex — the two must stay in sync, and consumers embedding its source in an anchored context would hit the same blowup. In isolation it does not backtrack today, because its permissive (\s*[^.\d/].*)? tail means a match almost never fails.

numericQuantity was never affected, for that reason. I also profiled romanNumeralRegex, romanNumeralUnicodeRegex, vulgarFractionsRegex, superSubDigitsRegex, normalizeDigits, parseRomanNumerals, and numericQuantity under currency/percentage/comma-decimal options at growing input sizes; none show superlinear growth, so no other pattern needed changing.

Changes

  • src/constants.ts — the two literals, plus a JSDoc note on numericRegex explaining why group 2 is ? and not *.
  • src/index.test.ts — new numeric regex backtracking suite: the equivalence comparison above, a source assertion guarding against a revert, and a timing regression test.
  • CHANGELOG.md — entry under Unreleased → Fixed.

bunx tsc, bun run build, bun run test (100% coverage held), bun run fmt --check, and bun run lint all pass locally.

Summary by CodeRabbit

  • Bug Fixes

    • Improved numeric input validation performance, preventing slowdowns when processing long digit sequences.
    • Preserved existing numeric matching behavior while ensuring invalid inputs fail faster.
  • Tests

    • Added coverage confirming matching behavior remains unchanged and long numeric inputs are handled efficiently.
  • Documentation

    • Documented the improved numeric pattern performance in the unreleased changes.

@pkg-pr-new

pkg-pr-new Bot commented Sep 9, 2026

Copy link
Copy Markdown

Open in StackBlitz

bun add https://pkg.pr.new/numeric-quantity@50
npm i https://pkg.pr.new/numeric-quantity@50
pnpm add https://pkg.pr.new/numeric-quantity@50

commit: c199910

@coderabbitai

coderabbitai Bot commented Sep 9, 2026

Copy link
Copy Markdown

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: fe6e0ba8-b992-4cfb-98ac-77a6b570a185

📥 Commits

Reviewing files that changed from the base of the PR and between 933fe40 and c199910.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • src/constants.ts
  • src/index.test.ts

Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The numeric regex patterns replace an ambiguous nested quantifier with ?. Tests verify equivalent matches and fast failure on long invalid digit runs. The changelog documents the fix.

Changes

Numeric regex backtracking fix

Layer / File(s) Summary
Regex quantifier and regression validation
src/constants.ts, src/index.test.ts, CHANGELOG.md
Both numeric regex patterns use ? for capture group 2. Tests compare match results with the previous form and enforce fast failure for long invalid inputs. The changelog documents the change.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to c1999

This change removes catastrophic backtracking from numeric parsing patterns while preserving tested matching and capture behavior. The updated patterns and regression coverage indicate no remaining merge-blocking risk.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes satisfy issue #49 by replacing the redundant outer * quantifier with ? in both numeric regex patterns. The tests and documentation address performance, language equivalence, captures, …
Out of Scope Changes check ✅ Passed The changes are limited to the requested regex fix, related tests, documentation, and the Unreleased changelog entry. No unrelated code changes are identified.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 2…
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: preventing catastrophic backtracking in the numeric regular expressions.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/numeric-regex-backtracking

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Sep 9, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (933fe40) to head (c199910).

Additional details and impacted files
@@            Coverage Diff            @@
##              main       #50   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            4         4           
  Lines          464       464           
=========================================
  Hits           464       464           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@jakeboone02
jakeboone02 merged commit 9765471 into main Sep 9, 2026
5 checks passed
@jakeboone02
jakeboone02 deleted the fix/numeric-regex-backtracking branch September 9, 2026 00:35
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.

Catastrophic backtracking in numericRegex on long digit runs

1 participant