Skip to content

RDoc::Markdown#code takes superlinear time on long space/tab runs in inline code spans #1889

Backlog

Description

@imoshkinlocal

Summary

RDoc::Markdown#code trims "even spaces" by repeatedly running an anchored
regex until it stops matching:

def code text
  # trim even spaces
  text = $2 while /\A( +|\t+)(.*)\1\z/ =~ text
  # escape unescaped backslash at the end
  backslash_at_end = "\\" if /(?<!\\)(?:\\\\)*\\\z/.match?(text)
  "<code>#{text}#{backslash_at_end}</code>"
end

(on master today: lib/rdoc/markdown.rb:908; in rdoc 7.0.4, which ships with
Ruby 4.0.10: line 890)

The regex is anchored and requires the same leading and trailing run, so for
text that is mostly spaces/tabs it backtracks heavily, and the while loop
repeats O(n) times. A single inline code span with a long run of spaces
therefore costs superlinear (roughly quadratic-to-cubic) time: ~20 KB of
Markdown keeps a core busy for ~6 minutes. Memory stays constant, so this is a
CPU-only denial of service, but it is reachable anywhere rdoc is pointed at
Markdown that comes from a third party (docs generation over a fetched
README/CHANGELOG/comments).

Reproduction

require "rdoc"
require "rdoc/markdown"

n = (ARGV[0] || 1000).to_i
src = "`" + " " * n + "!`"
t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
RDoc::Markdown.new.parse(src)
dt = Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0
puts "n=%d parse=%.1f ms" % [n, dt * 1000]

Ruby 4.0.10 (rdoc 7.0.4), x86_64-linux:

n (spaces in span) RDoc::Markdown#parse
500 34 ms
1 000 132 ms
2 000 981 ms
4 000 7 123 ms
8 000 31 501 ms
20 000 ~358 000 ms

Each doubling multiplies the time by ~6–8×, so the growth is between quadratic
and cubic. The same happens on master (8.1.0, 07859df): the same input takes
24.8 s at n=8 000, i.e. the issue is still present and the hot spot is the
same code method.

code in isolation (same inputs, no parser overhead), rdoc 7.0.4:

n one call of the trim loop
1 000 65 ms
2 000 413 ms
4 000 2 973 ms

Cause

For text = " " * n + "!" the regex must try every possible length of
( +), then for each of them let (.*) backtrack looking for a position where
\1 is followed by \z; the trailing ! guarantees failure, so the engine
walks a quadratic (in practice worse) search space. On each outer iteration the
captured run is trimmed by min(leading_run, trailing_run), and the loop keeps
going while leading and trailing runs differ, giving O(n) iterations.

Suggested fix

Trim at the byte level instead of with the regex, removing the same "even"
number of bytes per iteration (capped at half of the remaining size). Short-
circuit when the text contains "\n", because . never matches a newline, so
the original loop can never trim such text at all.

   def code text
     # trim even spaces
-    text = $2 while /\A( +|\t+)(.*)\1\z/ =~ text
+    unless text.include?("\n")
+      s = 0
+      e = text.bytesize
+      while s < e
+        ch = text.getbyte(s)
+        break unless ch == 0x20 || ch == 0x09
+        lead = s
+        lead += 1 while lead < e && text.getbyte(lead) == ch
+        trail = e
+        trail -= 1 while trail > s && text.getbyte(trail - 1) == ch
+        run = [lead - s, e - trail, (e - s) / 2].min
+        break if run.zero?
+        s += run
+        e -= run
+      end
+      text = text.byteslice(s, e - s)
+    end
     # escape unescaped backslash at the end
     backslash_at_end = "\\" if /(?<!\\)(?:\\\\)*\\\z/.match?(text)
     "<code>#{text}#{backslash_at_end}</code>"

Validation of the patch (against master, 07859df)

  • Equivalence with the original code: 500 000 random strings (length 0–16,
    alphabet " ", "\t", "\n", "a", "b", "!", "é", "😀", " ",
    "\t\t", "`", " \t") plus exhaustively all strings over
    {" ", "\t", "\n", "x"} up to length 6 (5 461 strings) — 0 mismatches.
  • Existing tests pass: test/rdoc/rdoc_markdown_test.rb (127 tests) and
    test/rdoc/rdoc_markdown_test_test.rb (MarkdownTest 1.0.3 suite, 22 tests),
    run as ruby -Ilib -Itest ... — 100% passed.
  • End-to-end with the patch, same PoC: n=4 000 → 25 ms, 8 000 → 38 ms,
    20 000 → 88 ms, 100 000 → 596 ms, 400 000 → 2 154 ms (linear).

Happy to send this as a PR if the approach looks good.

Activity

  1. imoshkinlocal commented on Nov 26, 2026

    @imoshkinlocal
    Author

    Adding the exact PoCs and the equivalence harness behind the numbers in the
    report, so everything can be reproduced without any setup.

    1. End-to-end reproducer

    # rdoc_redos_poc.rb
    require "rdoc"
    require "rdoc/markdown"
    
    n = (ARGV[0] || 8000).to_i
    src = "`" + " " * n + "!`"     # one inline code span, mostly spaces
    
    t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    RDoc::Markdown.new.parse(src)
    dt = Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0
    
    puts "n=#{n} parse=#{(dt * 1000).round} ms"
    $ ruby -Ilib rdoc_redos_poc.rb 4000
    n=4000 parse=7123 ms
    $ ruby -Ilib rdoc_redos_poc.rb 8000      # rdoc master, 07859df
    n=8000 parse=24849 ms
    $ ruby -Ilib rdoc_redos_poc.rb 20000     # ~6 minutes, note the slope

    n=4000 with rdoc 7.0.4 (the version bundled with Ruby 4.0.10) and n=8000
    with master. Memory is flat — the loop only re-slices the same string; this is
    pure single-core CPU.

    The trailing ! is what makes the regex fail on every attempt, and is the
    worst case I measured. A span that is only spaces triggers the same code too
    (rdoc master: n=20 000 → 0.8 s, n=200 000 → 92 s), so no unusual characters
    are needed — the trigger is simply a long run of spaces/tabs in an inline code
    span, which is easy to hit in generated or copy-pasted Markdown.

    2. Equivalence harness for the proposed fix

    Standalone (no rdoc required) — compares the current trim loop with the linear
    implementation for 500 000 random strings plus an exhaustive sweep:

    # rdoc_equivalence_check.rb
    ORIGINAL = /\A( +|\t+)(.*)\1\z/
    
    def original(text)
      text = $2 while ORIGINAL =~ text
      "<code>#{text}</code>"
    end
    
    def proposed(text)
      unless text.include?("\n")
        s = 0
        e = text.bytesize
        while s < e
          ch = text.getbyte(s)
          break unless ch == 0x20 || ch == 0x09
          lead = s
          lead += 1 while lead < e && text.getbyte(lead) == ch
          trail = e
          trail -= 1 while trail > s && text.getbyte(trail - 1) == ch
          run = [lead - s, e - trail, (e - s) / 2].min
          break if run.zero?
          s += run
          e -= run
        end
        text = text.byteslice(s, e - s)
      end
      "<code>#{text}</code>"
    end
    
    bad = 0
    alphabet = [" ", "\t", "\n", "a", "b", "!", "é", "😀", "  ", "\t\t", "`", " \t"]
    rng = Random.new(42)
    500_000.times do
      str = Array.new(rng.rand(0..16)) { alphabet[rng.rand(alphabet.size)] }.join
      a = original(str)
      b = proposed(str)
      next if a == b
      bad += 1
      puts "MISMATCH #{str.inspect}: #{a.inspect} vs #{b.inspect}" if bad <= 10
    end
    
    checked = 0
    (0..6).each do |n|
      [" ", "\t", "\n", "x"].repeated_permutation(n) do |chars|
        str = chars.join
        checked += 1
        a = original(str)
        b = proposed(str)
        next if a == b
        bad += 1
        puts "MISMATCH #{str.inspect}: #{a.inspect} vs #{b.inspect}" if bad <= 10
      end
    end
    
    puts "mismatches=#{bad} random=500000 exhaustive=#{checked}"

    Output:

    mismatches=0 random=500000 exhaustive=5461
    

    The text.include?("\n") guard is required for equivalence: . never matches
    a newline, so the original loop can never trim text that contains one.

    3. Result on master with the fix

    n=4000    parse=25 ms
    n=8000    parse=38 ms
    n=20000   parse=88 ms
    n=100000  parse=596 ms
    n=400000  parse=2154 ms
    

    plus test/rdoc/rdoc_markdown_test.rb (127 tests) and
    test/rdoc/rdoc_markdown_test_test.rb (MarkdownTest 1.0.3 suite, 22 tests)
    both passing 100%.

  2. yppp commented on Nov 28, 2026

    @yppp

    I reproduced this independently on current master (07859df), with ruby 4.0.10 on aarch64-linux:

    n=1000 parse=77 ms
    n=2000 parse=547 ms
    n=4000 parse=4173 ms
    

    The growth is clearly superlinear (roughly 7x per doubling), matching the report.

    @imoshkinlocal — your proposed fix and equivalence harness look complete. Do you plan to open a PR with it yourself? If not, I'd be happy to turn it into a PR, including a regression test. I don't want to duplicate your work, so I thought I'd ask first.

  3. imoshkinlocal commented on Nov 29, 2026

    @imoshkinlocal
    Author

    Thanks — no need to duplicate: @adityawrk opened #1890 with this fix a few hours after your comment, while this thread was quiet. Same approach (linear walk, newline shortcut preserved, .kpeg and the generated parser both updated) plus a regression test with a 20,000-space span.

    I re-ran the harness from my earlier comment against that patch: 0 mismatches on the 5,461 exhaustive strings and 500,000 random ones, rake verify_generated reproduces the committed markdown.rb, and the three markdown test files pass (127 + 22 + 3). On x86-64 the old loop takes ~230 s on " " * 20_000 + "!", the new code ~0.6 ms.

    Your aarch64 numbers are still valuable — before/after on #1890 would show the fix on a second architecture. I've left the details in that PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions