Skip to content

Avoid quadratic backtracking in numeric prefix validation - #140

Merged
taketo1113 merged 1 commit into
ruby:masterfrom
imoshkinlocal:ipaddr-prefix-linear-time
Nov 27, 2026
Merged

taketo1113 merged 1 commit into
ruby:masterfrom
imoshkinlocal:ipaddr-prefix-linear-time

Conversation

@imoshkinlocal

Copy link
Copy Markdown
Contributor

[1-9]+ and \d* overlap in the numeric-prefix branch of IPAddr#mask!, so an
invalid prefix such as "1" * 32_000 + "x" can be split between the two
quantifiers in O(n) ways and the engine backtracks through all of them before
giving up. Both IPAddr.new("1.2.3.4/...") and IPAddr#prefix= go through
mask!.

On Ruby 3.1.2 (regexp engine without memoization):

IPAddr.new("1.2.3.4/" + "1" * 16_000 + "x")  # ~1.5 s
IPAddr.new("1.2.3.4/" + "1" * 32_000 + "x")  # ~7.0 s

[1-9]\d* accepts exactly the same language — the first character must be
1-9, the rest digits — without leaving the engine a choice of where to split,
so there is nothing to backtrack into. The sibling /\A\d+\z/ used for the
leading-zero check has no overlapping quantifiers and is left as is.

Test

test_mask_long_invalid_prefix uses assert_linear_performance (available
through test/lib/helper.rb and test-unit-ruby-core) over
[5, 10, 20, 40, 80], i.e. prefixes of 2 500 to 40 000 digits. Measured on
Ruby 3.1.2:

  • without the fix: fails in ~8 s (quadratic blow-up at the last step),
  • with the fix: passes in ~0.3 s.

Full suite: 43 tests, 657 assertions, 0 failures.

Note for reviewers

On Ruby >= 3.2 the regexp engine memoizes matches, so the difference is not
observable there and the timing guard passes trivially. The gem still declares
required_ruby_version >= 2.4, so the quadratic behaviour is shipped to Ruby
2.4-3.1 users, including several LTS distributions; the test is a regression
guard for engines without memoization.

@imoshkinlocal
imoshkinlocal requested a review from knu as a code owner November 13, 2026 14:09
@imoshkinlocal

Copy link
Copy Markdown
Contributor Author

@taketo1113 thanks for merging the recent PRs and keeping the gem moving — much appreciated.

Could you take a look at this one when you get a chance?
The build workflow for this branch is stuck in action_required (first PR from this fork), so no CI results are visible yet — it needs a maintainer to approve the run. I requested a review from @knu as code owner, but I'm pinging you since you've been merging the recent PRs.

Locally: 43 tests, 657 assertions, 0 failures on Ruby 3.1.2 (the engine without regexp memoization); the new guard takes ~8 s on the old pattern and ~0.3 s with the fix.

@taketo1113

Copy link
Copy Markdown
Collaborator

@imoshkinlocal Thanks.

Could you run benchmarks before and after the change on recent Ruby versions, such as Ruby 4.0?
If the benchmark results look good, I think we can merge this without adding test code.

@imoshkinlocal

imoshkinlocal commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Benchmarks: before vs after

Thanks for the trust, @taketo1113 — here are the before/after numbers on 3.4.13 and
4.0.10, plus 3.1.2 as a reference engine without regexp memoisation; a reproducer is at
the bottom.

TL;DR On 4.0.10 the failing-prefix case is 4.2x faster and the success path is
unchanged. On an engine without regexp memoisation (3.1.2) a single IPAddr.new call
with a 64,000-character prefix drops from 14.2 s to 1.3 ms.

Setup

  • before = lib/ipaddr.rb at b1a23eb with that single line reverted to
    /\A(0|[1-9]+\d*)\z/ (which is exactly what master has today); after = the PR
    as is. The two files are byte-identical except for this one line, so the comparison
    isolates the regexp change.
  • Each sample runs in a fresh process (ruby --disable-gems -I<variant>), timed with
    Process::CLOCK_MONOTONIC; the tables show the median (plus the best-of-N in brackets
    for the hot-path cases). For the after variant a single call takes microseconds, so
    each sample is amortised over 100–1000 iterations to keep timer resolution out of the
    picture.
  • Input for the vulnerable path: IPAddr.new("1.2.3.4/" + "1" * n + "x") — a long
    numeric prefix followed by a non-digit, i.e. exactly the shape where [1-9]+\d*
    has to retry at every split point.
  • Hot-path controls: valid = IPAddr.new("10.0.0.0/8") in a loop,
    mask = IPAddr#prefix = 8 on an existing address.
  • Hardware: Intel i5-1240P (KVM, 10 vCPU). 3.4.13 and 4.0.10 are the official
    ruby:3.4-slim / ruby:4.0-slim images (built 2026-11-19) on that host; 3.1.2 is
    the distro build, kept as a data point for an engine without regexp memoisation.

Invalid prefix (the quadratic case)

n 3.1.2 before 3.1.2 after 3.4.13 before 3.4.13 after 4.0.10 before 4.0.10 after
1,000 2.55 ms 26 µs 67 µs 26 µs 84 µs 30 µs
2,000 10.28 ms 38 µs 128 µs 43 µs 197 µs 52 µs
4,000 42.02 ms 70 µs 306 µs 80 µs 329 µs 97 µs
8,000 171.71 ms 157 µs 570 µs 168 µs 523 µs 188 µs
16,000 700.68 ms 257 µs 1.12 ms 294 µs 1.21 ms 369 µs
32,000 3.26 s 600 µs 2.18 ms 678 µs 2.09 ms 766 µs
64,000 14.25 s 1.26 ms 6.77 ms 1.44 ms 6.32 ms 1.51 ms

Fitted exponent of time ~ n^p between the smallest and the largest n:

Ruby before after
3.1.2 n^2.07 n^0.94
3.4.13 n^1.11 n^0.97
4.0.10 n^1.04 n^0.94

Raw regexp and hot paths

Ruby case n before after speedup
3.1.2 raw 64,000 10.70 s 491 µs 21,815x
3.1.2 valid 100,000 393.92 ms (302.00 ms) 319.98 ms (316.16 ms) 0.96x
3.1.2 mask 8 5.03 ms (4.90 ms) 5.07 ms (4.79 ms) 1.02x
3.4.13 raw 64,000 3.31 ms 525 µs 6.31x
3.4.13 valid 100,000 450.09 ms (400.31 ms) 441.19 ms (388.78 ms) 1.03x
3.4.13 mask 8 4.14 ms (3.96 ms) 4.02 ms (3.82 ms) 1.04x
4.0.10 raw 64,000 3.76 ms 559 µs 6.73x
4.0.10 valid 100,000 369.61 ms (361.42 ms) 359.67 ms (352.25 ms) 1.03x
4.0.10 mask 8 3.99 ms (3.86 ms) 4.09 ms (3.81 ms) 1.01x

For valid and mask the time is the median with the best-of-N in brackets, and the
speedup column is computed from the best-of-N numbers.

Verdict

  • 3.1.2 (no regexp memoisation): quadratic before — 4.0–4.7x
    per doubling, 14.25 s for a single call at n=64,000 — and linear after:
    1.26 ms, ~11,300x faster.
  • 3.4.13 / 4.0.10: memoisation already keeps the old pattern linear, so the blow-up does
    not reproduce, but the change is still 4.2–4.7x
    faster on the failing input (6.3–6.7x as a bare regexp),
    and linearity no longer depends on the engine memoising this pattern.
  • No regressions: the success path stays within 0.96–1.04x,
    and the outcome (address or exact exception class) is identical on all 410 inputs I
    compared.

If you'd rather merge without test code, I can remove test/test_ipaddr.rb from this branch
so the PR is just the one-line change.

Minimal reproducer
# ruby -Ilib/path repro.rb  (min of 3 runs, after a warm-up)
require "ipaddr"

def elapsed(n)
  addr = "1.2.3.4/" + "1" * n + "x"
  t = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  begin
    IPAddr.new(addr)
  rescue IPAddr::Error
  end
  Process.clock_gettime(Process::CLOCK_MONOTONIC) - t
end

elapsed(100) # warm-up
[1_000, 4_000, 16_000, 64_000].each do |n|
  printf "n=%-6d %.6f s\n", n, 1.upto(3).map { elapsed(n) }.min
end

On this machine that prints:

Ruby 3.1.2, before:  n=1000 0.003454 s   n=4000 0.059377 s   n=16000 1.009584 s   n=64000 18.693702 s
Ruby 3.1.2, after:   n=1000 0.000033 s   n=4000 0.000117 s   n=16000 0.000298 s   n=64000 0.001273 s

Ruby 4.0.10, before: n=1000 0.000087 s   n=4000 0.000409 s   n=16000 0.001240 s   n=64000 0.005930 s
Ruby 4.0.10, after:  n=1000 0.000043 s   n=4000 0.000180 s   n=16000 0.000434 s   n=64000 0.002444 s

[1-9]+ and \d* overlap in the numeric-prefix branch of IPAddr#mask!, so an
invalid prefix such as "1" * 32000 + "x" can be split between them in O(n)
ways and the engine backtracks through all of them before giving up.

Both IPAddr.new and IPAddr#prefix= go through mask!.  [1-9]\d* accepts the
same strings without giving the engine a choice of where to split.
@taketo1113
taketo1113 force-pushed the ipaddr-prefix-linear-time branch from b1a23eb to 31e1e6b Compare November 27, 2026 13:07

@taketo1113 taketo1113 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thank you for checking.

There don't seem to be any negative impacts on Ruby 4.0 or other versions, so I will merge it.

@taketo1113
taketo1113 merged commit cb5e515 into ruby:master Nov 27, 2026
29 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.

2 participants