Skip to content

perf: eliminate quadratic email lookahead in inline text - #4276

Open
yxshee wants to merge 4 commits into
markedjs:masterfrom
yxshee:perf/inline-text-email-lookahead
Open

yxshee wants to merge 4 commits into
markedjs:masterfrom
yxshee:perf/inline-text-email-lookahead

Conversation

@yxshee

@yxshee yxshee commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Marked version: 18.2.1 (master @ b20f69f2)

Markdown flavor: GitHub Flavored Markdown

Description

Cause

In GFM mode, inlineGfm.text (and inlineBreaks.text) ran an email look-ahead ((?=[a-zA-Z0-9.!#$%&'*+\/=?_{|}~-]+@)) at the start and in the lazy tail of every text token, and inlineGfm.urlre-scanned[A-Za-z0-9.+-]+(@)... at every position. On paragraphs of repeated emphasis spans (a, a), underscore-joined words (a), or punctuation runs (a!) — both with and without an @later in the paragraph — each token rescanned to the end of the run, resulting inO(n^2)` time.

Fix

  • Scan each GFM inlineTokens pass once in O(n) time via a per-pass WeakMap frame (beginInlineEmailScan / endInlineEmailScan in src/helpers.ts, matching the #4099 closer-scan lifecycle so source strings are never retained and Tokenizer gains no public methods).
    • Paragraphs without @ skip the scan entirely.
    • Paragraphs with @ locate every @ once, walk backward over [A-Za-z0-9._+-] (pairwise disjoint because @ is excluded), validate the domain with sticky emailDomainSticky, and record sorted disjoint [start, at) bare email ranges.
  • Tokenizer.url checks urlGfmNoEmail (guarded by an O(1) first-character check for protocol/www. starters) and resolves bare email autolinks in O(1) via findBareEmailAt.
  • Tokenizer.inlineText matches inlineTextGfmNoEmail / inlineTextBreaksNoEmail (without the bare email look-aheads) and clips at findNextBareEmailStart in O(1), respecting state.inLink and startInline extension clipping.
  • Custom rules.inline.url / rules.inline.text overrides and direct tokenizer.url() / tokenizer.inlineText() calls outside inlineTokens fall back to the existing regexes. The fallback inlineGfm.text look-ahead class is also tightened to [A-Za-z0-9._+-] to match inlineGfm.url.

(Note: like #4225, non-boundary www. sequences such as www.foo_@b.co_ `` before an invalid email domain now remain plain text rather than accidentally matching www. mid-token, consistent with GFM §6.5.)

Benchmarks (Node v26.7.0)

Input (5k / 10k / 20k reps) Before After
'*a*' 40 / 69 / 257 ms 5.0 / 12.3 / 44.3 ms
'a_' 58 / 234 / 989 ms 2.7 / 9.1 / 14.5 ms
'_a_' 143 / 682 / 2,457 ms 16.2 / 6.3 / 23.8 ms
'a_' + '@' 90 / 362 / 1,389 ms 3.8 / 14.0 / 5.8 ms
'a_' + ' foo@bar.com' 54 / 213 / 860 ms 5.0 / 4.7 / 9.6 ms
'*a*' + 'b@example.com' 22 / 77 / 268 ms 3.1 / 10.2 / 10.2 ms

Spec suite throughput (100x all 1,332 CommonMark + GFM specs): gfm: false 325 ms -> 287 ms, gfm: true 346 ms -> 343 ms.

Contributor

  • Test(s) exist to ensure functionality and minimize regression: added test/specs/redos/quadratic_inline_text_email.cjs (9 pathological cases, all >1 s before and <25 ms after) and edge-case unit tests in test/unit/Lexer.test.js. Full npm test (test:specs 2059 passing, test:unit 276 passing, test:umd, test:cjs, test:types, test:lint) passes locally.
  • no tests required for this PR.
  • If submitting new feature, it has been documented in the appropriate places.

Committer

In most cases, this should be a different person than the contributor.

Scan each inline pass once for valid bare GFM email autolink ranges instead of re-running the email look-ahead in inlineText and bare email scan in url from every token position.

Fixes markedjs#4272
@vercel

vercel Bot commented Nov 23, 2026

Copy link
Copy Markdown

@yxshee is attempting to deploy a commit to the MarkedJS Team on Vercel.

A member of the Team first needs to authorize it.

@vercel

vercel Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
marked-website Ready Ready Preview Nov 23, 2026 2:09am UTC

Request Review

Comment thread src/rules.ts Outdated

// Sticky matcher for the domain after `@` in a bare GFM email autolink,
// shared with the per-pass email scan in helpers.ts.
export const emailDomainSticky = edit(_emailDomain, 'y').getRegex();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Add this regex to other if you want to export it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the review @UziTech! Moved emailDomainSticky (along with urlGfmNoEmail, inlineTextGfmNoEmail, and inlineTextBreaksNoEmail) into other in src/rules.ts and updated src/helpers.ts and src/Tokenizer.ts to reference them there (25bca67).

Comment thread test/unit/Lexer.test.js

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The other tests should cover the changes so we don't need the lexer unit tests

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks @UziTech! Removed the new lexer unit tests in test/unit/Lexer.test.js in 45e83f2.

Comment thread src/Tokenizer.ts Outdated
Comment on lines +1324 to +1333
const cap = noEmailRule.exec(src);
if (cap) {
raw = cap[0];
if (!this.lexer.state.inLink && frame.emails.length > 0) {
const nextStart = findNextBareEmailStart(frame, frame.pos, frame.pos + raw.length, frame.pos + src.length);
if (nextStart !== -1) {
raw = raw.slice(0, nextStart - frame.pos);
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This makes a list of plain emails quadratic, which is linear on main. noEmailRule has no email stop, so it runs to the next delimiter (often the end of the paragraph) and only then is the match cut at the next email. Every gap between two emails rescans the rest:

marked.parse('a@b.co '.repeat(n))
// n        main     this PR
// 5000     4 ms     0.6 s
// 10000    6 ms     2.3 s
// 20000    10 ms    9.6 s
// 40000    18 ms    38 s   (280 KB)

The start of the next email is known before the regex runs, so the input can be cut first:

Suggested change
const cap = noEmailRule.exec(src);
if (cap) {
raw = cap[0];
if (!this.lexer.state.inLink && frame.emails.length > 0) {
const nextStart = findNextBareEmailStart(frame, frame.pos, frame.pos + raw.length, frame.pos + src.length);
if (nextStart !== -1) {
raw = raw.slice(0, nextStart - frame.pos);
}
}
}
const end = frame.pos + src.length;
const nextStart = !this.lexer.state.inLink && frame.emails.length > 0
? findNextBareEmailStart(frame, frame.pos, end, end)
: -1;
raw = noEmailRule.exec(nextStart === -1 ? src : src.slice(0, nextStart - frame.pos))?.[0];

With that 40000 emails take 22 ms, and 150k random inputs (emails, links, emphasis, html, breaks, pedantic, an inline extension) render the same as main (inputs without www.; with it the PR already differs, e.g. +www.x.co/@u is no longer a link, same as GitHub). findNextBareEmailStart then no longer needs its rawEnd argument. A redos spec with 'a@b.co '.repeat(40000) would guard it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Great catch, thank you @bardrop! Applied the pre-slice fix in Tokenizer.inlineText, removed the unused rawEnd parameter from findNextBareEmailStart, and added 'a@b.co '.repeat(40000) to test/specs/redos/quadratic_inline_text_email.cjs in 45e83f2 ('a@b.co '.repeat(40000) dropped from ~36.5 s to ~25 ms locally on Node v26.7.0, while the original *a* / a_ / _a_ cases stay ~8–22 ms).

@shubham21155102

Copy link
Copy Markdown

Tested 45e83f2 against another input that hits the same email lookahead: intraword underscores, since _ is a valid local-part character, so a__a__a… reads as one long candidate local part.

new Marked().parse(s), default options:

input n master (dd9fbbe) this PR
'a__'.repeat(n) 2k / 4k / 8k / 16k 58 / 194 / 700 / 2619 ms 1 / 3 / 7 / 14 ms
'_a'.repeat(n) 2k / 4k / 8k / 16k 20 / 70 / 246 / 1011 ms 1 / 2 / 4 / 8 ms

A CPU profile on master puts nearly all of the time in the inlineText and url regexes (the [A-Za-z0-9._+-]+(?=@) branch), not in emphasis. So this PR covers it too. It might be worth adding 'a__'.repeat(20000) to test/specs/redos/quadratic_inline_text_email.cjs, since none of the current cases has underscores.

@yxshee

yxshee commented Nov 28, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for profiling and sharing the intraword underscore numbers, @shubham21155102! Added 'a__'.repeat(20000) to test/specs/redos/quadratic_inline_text_email.cjs in af145685 — runs in ~20–25ms in the ReDoS suite and npm test is green.

This branch was successfully deployed

1 active (outdated) deployment
Preview — 9fb0e967 Deployed Nov 23, 2026 by vercel[bot]
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.

Quadratic time in the inline text rule: its email look-ahead rereads the rest of the paragraph

4 participants