Skip to content

fix: quadratic code-block scan in isInsideCodeBlock - #574

Open
Vikramb1 wants to merge 1 commit into
vercel:mainfrom
Vikramb1:fix/quadratic-code-block-scan
Open

fix: quadratic code-block scan in isInsideCodeBlock#574
Vikramb1 wants to merge 1 commit into
vercel:mainfrom
Vikramb1:fix/quadratic-code-block-scan

Conversation

@Vikramb1

Copy link
Copy Markdown

Problem

isInsideCodeBlock(text, position) rescans the entire prefix [0, position) on every call. Several handlers probe it once per candidate character — the link/image handler calls it for every [ while walking backwards — so total work is O(brackets × length).

The pathological case is exactly what streaming AI produces: a long, still-unclosed code fence full of brackets, re-repaired on every arriving token. Repro (58k chars):

const line = "const x = arr[i]; if (map[key]) { list[j] = grid[a][b]; }\n";
remend("\`\`\`ts\n" + line.repeat(1000)); // ~915ms on remend@1.3.0

That's ~915ms of main-thread time per streamed chunk when rendering a large code block.

Fix

Build the answer for every position in one linear pass (buildCodeBlockLookup, mirroring the original scan's control flow including escaped-backtick and triple-backtick handling), and cache it per text with a single-entry cache — handlers repeatedly probe the same string within one remend() call, so each probe becomes O(1) after one O(n) build. No signature changes; all six consuming handlers benefit.

Same repro after the fix: ~0.4ms (benchmark added, iterations: 10 to keep CI fast).

Behavior parity

  • New __tests__/code-block-utils.test.ts includes a verbatim copy of the previous implementation as a reference oracle and asserts equality at every position across mixed inputs (fences, inline code, escaped backticks, unclosed spans), plus a cache-correctness test with alternating texts.
  • Positions past text.length resolve to the end-of-scan state, matching the old loop's behavior.
  • Full existing suites pass unmodified: remend 464/464, streamdown 982/982.

Notes

  • Changeset included (patch).
  • pnpm check / check-types clean. pnpm build succeeds for all library packages (apps/test prerender needs AI Gateway credentials I don't have as an external contributor).

@vercel

vercel Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

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

A member of the Team first needs to authorize it.

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.

1 participant