Skip to content

perf(studio): remove quadratic region scan in LaTeX preprocessing - #7538

Merged
shimmyshimmer merged 1 commit into
mainfrom
perf/studio-latex-region-scan
Jul 28, 2026
Merged

shimmyshimmer merged 1 commit into
mainfrom
perf/studio-latex-region-scan

Conversation

@shimmyshimmer

Copy link
Copy Markdown
Member

Problem

findCodeBlockRegions in studio/frontend/src/lib/latex.ts collects fenced regions first, then walks inline code spans. For each inline match it scanned every region found so far to decide whether that match sits inside a fence. Accepted inline spans are appended to the same array, so the scan grows with each match, making it quadratic in the number of inline spans.

This is on a hot path. preprocessLaTeX runs over the full message text on every animation frame while a response is streaming, and calls findCodeBlockRegions twice per call, so it shows up on code heavy answers.

Fix

Fenced matches and inline matches are both produced by RegExp.exec in ascending, non overlapping order, so the fenced list can be walked with a cursor instead of rescanned per match. Only a fenced region can contain an inline span, so previously accepted inline regions never needed to be checked at all.

Results

34,670 chars containing 2,100 inline spans, averaged over 40 calls:

before: 5.51 ms per call
after:  0.12 ms per call

In the app this is a secondary cost, so the end to end gain is smaller than the microbenchmark: on a stream of that text, dropped frames went from 167 to 76. The remaining cost there is a character scan inside Streamdown, not ours.

Correctness

Output is unchanged. A 4,000 case fuzz over fenced blocks, tilde fences, unclosed fences, inline spans inside and outside fences, adjacent backticks, tables and currency text produced identical region lists from the old and new implementations, with zero mismatches.

Typecheck and build pass.

findCodeBlockRegions scanned every region found so far for each inline code
match, and accepted inline spans were appended to the same array, making it
quadratic in the number of inline spans. preprocessLaTeX runs on the full
message text every animation frame while streaming and calls it twice.

Fenced and inline matches are both ascending and non-overlapping, so walk the
fenced list with a cursor instead. Only fenced regions can contain an inline
span, so previously accepted inline regions never needed checking.

34,670 chars with 2,100 inline spans: 5.51ms per call to 0.12ms.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 03e39002ef

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

Independently verified. No findings; safe to merge as is.

Equivalence. Two harnesses compared the merge-base and PR revisions of findCodeBlockRegions, and separately the exported preprocessLaTeX, over 1,311,798 cases: a curated corpus, every string of length 1 to 7 over [` ~ \n a $ \ space], unicode families covering astral pairs, lone surrogates, BOM, combining marks and ZWJ, constructed fence and inline adjacency cases aimed at the half-open <= cursor boundary, dense alternation up to 60 fences, 320k structured random documents, and documents up to 525 KB. Zero mismatches, and the arrays are already identical before the final sort.

Three specifics that looked like they could bite, and did not:

  • The cursor indexes regions while the loop pushes inline regions onto the same array. Safe by proof, not just by fencedCount: an earlier inline region can never contain a later inline match, since I_u.end > I_u.start >= I_t.end contradicts I_u.end <= I_t.end. A mutant using regions.length instead of the captured fencedCount survived all 1.05M cases, so the capture is clarity rather than load-bearing. Worth keeping either way.
  • Surrogates cannot matter. Both revisions use the same regexes and the same match.index arithmetic; only the filter differs. index is a UTF-16 code-unit offset regardless of the u flag.
  • Sort stability is unobservable: zero cases produced duplicate region starts, because a fence start needs ~ or a second backtick while an inline start needs a backtick followed by a non-backtick.

Mutation testing confirms the corpus discriminates rather than passing blindly: removing the lower bound, removing the upper bound, and freezing the cursor were all killed.

Performance. The old growth is about 3.9x per doubling of inline spans, the new about 2.0x. At 8000 spans, 880.7 ms to 1.0 ms. Worth noting for the description: preprocessLaTeX returns early unless the message contains a $, so the quadratic path only runs once one arrives. That is common rather than rare, though, since a shell prompt, a price, a jQuery or PHP snippet or any LaTeX supplies one. Replaying a stream at 230 tok/s with a $ in the first line, preprocessLaTeX alone went from 133.4 s of main-thread time and 3506 frames over the 16.7 ms budget, to 3.6 s and 0 frames over budget.

Consumers. findCodeBlockRegions is module-private with three references, both call sites consume it only through isInRegion, and neither mutates or stores it. preprocessLaTeX is the sole export and markdown-text.tsx its sole importer.

Below bar, pre-existing, and explicitly not for this PR: findCodeBlockRegions can return nested regions, which violates the "non-overlapping" precondition isInRegions binary search documents. Minimal witness "`~~~~~~~"`` gives [[0,8],[1,7],[8,11]], where isInRegion(7)is false although[0,8]covers it. Both revisions are equally affected andpreprocessLaTeX` output is identical on every case, so this PR neither introduces nor worsens it. Only degenerate unbalanced fence markers trigger it. Worth a separate follow-up.

npm run typecheck and npm run build pass; biome check src/lib/latex.ts reports the same 20 diagnostics as the base revision, all on untouched lines.

The red Repo tests (CPU) check is pre-existing and unrelated: test_shipping_code_names_an_encoding fails on studio/install_llama_prebuilt.py:5647,5656 from 7917c78, and fails identically on a clean main worktree with no PR changes. Several open PRs already fix it.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 03e39002ef

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@shimmyshimmer
shimmyshimmer merged commit 2989b17 into main Jul 28, 2026
40 of 41 checks passed
@shimmyshimmer
shimmyshimmer deleted the perf/studio-latex-region-scan branch July 28, 2026 12:47
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