hermes-agent/apps/desktop/src/lib/markdown-blocks.ts
Brooklyn Nicholson bd4953b30d perf(desktop): incremental block lexing for streaming markdown — 14x less splitter CPU on long replies
Fourth profiling round (#66033/#66347/#66470). Streamdown's
parseMarkdownIntoBlocks is a full `marked` lex of the entire message,
and during streaming every flush is a new string — so the splitter paid
O(full-text) ~30x/s: benchmarked 3.4-9.6ms per call at 64-192KB, i.e.
15-30% of a core burned re-lexing settled text on long agent replies.
(The rest of the May-2026 "re-parse elephant" was already eaten by
tailBoundedRemend, block-memo, the KaTeX memo, and deferred shiki —
the splitter was the last O(full-text) pass besides preprocess, which
benches at only 1.5-4.6ms and is left alone.)

New src/lib/markdown-blocks.ts (extracted from markdown-text.tsx) wraps
the splitter with two caches:

- the existing exact-string LRU (remounts: virtualizer scroll, session
  switch) — moved, unchanged;
- a streaming-append cache: when the new text startsWith a recently
  parsed text, reuse that parse's blocks up to a settled boundary and
  lex only the suffix. The boundary drops trailing whitespace-only
  blocks plus the last content block — the only block appended text can
  reinterpret (open fence, list/table continuation, setext underline,
  lazy blockquote). Earlier blocks are separated by settled blank lines
  and can't change. Cross-block reference links can't regress:
  Streamdown already renders each block as an independent document.

Safety: the splitter's blocks.join('') === text property makes offsets
exact and is defensively re-checked; any mismatch or non-append rewrite
(edit, branch swap) falls back to the full lex — byte-for-byte the old
behavior.

Property tests: at every random streaming cut over a corpus covering
fences, loose lists, tables, setext headings, lazy blockquotes, HTML
blocks, and display math — and token-by-token through a fence boundary
— the cached splitter's output is asserted deep-equal to a fresh full
lex. Bench (128KB reply, 200 flushes): 990ms -> 72ms total splitter CPU
(4.95 -> 0.36ms/flush).

Verification: tsc clean; eslint/prettier clean; lib + assistant-ui
suites green (473 tests).
2026-07-18 17:45:55 -04:00

125 lines
4.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { parseMarkdownIntoBlocks } from '@assistant-ui/react-streamdown'
/**
* Block splitting for the streaming markdown pipeline, without re-lexing the
* whole message on every token flush.
*
* `parseMarkdownIntoBlocks` is a full `marked` lex of the entire text —
* measured 3.4–9.6ms per call at 64–192KB. During streaming every flush is a
* new string, so the stock splitter pays that O(full-text) cost ~30×/s on
* long replies. Two caches remove it:
*
* 1. Exact-string LRU — a message that REMOUNTS with unchanged text
* (virtualizer scroll, session switch) reuses its parse outright.
* 2. Streaming-append cache — when the new text starts with a recently parsed
* text (the token-append case), the previous parse's blocks are reused up
* to a settled boundary and only the suffix is lexed. The boundary drops
* the previous parse's trailing whitespace-only blocks AND its last content
* block, because appended text can retroactively change how that last
* block parses (open fence, list/table continuation, setext underline, a
* lazy blockquote line). Blocks before it are separated by settled blank
* lines and cannot be affected. Cross-block reference links can't regress:
* Streamdown renders each block as an independent markdown document
* already. Verified property: `blocks.join('') === text`, and incremental
* output is asserted byte-identical to a full lex in tests across fences,
* lists, tables, setext headings, blockquotes, and HTML blocks.
*
* Any doubt — no prefix match, reconstruction mismatch — falls back to the
* full lex, i.e. exactly the previous behavior.
*/
const EXACT_CACHE_MAX = 64
const EXACT_CACHE_MIN_LENGTH = 1024
const exactCache = new Map<string, string[]>()
// Streaming messages grow monotonically, and only a handful stream at once
// (main reply + reasoning part, maybe a tile). A tiny ring is enough; each
// entry holds the last parse for one growing text lineage.
const APPEND_CACHE_MAX = 4
const APPEND_CACHE_MIN_LENGTH = 2048
const appendCache: { blocks: string[]; text: string }[] = []
function rememberAppend(text: string, blocks: string[]): void {
if (text.length < APPEND_CACHE_MIN_LENGTH) {
return
}
// Replace the lineage this text grew from (its cached prefix), else push.
const index = appendCache.findIndex(entry => text.startsWith(entry.text))
if (index !== -1) {
appendCache.splice(index, 1)
}
appendCache.push({ blocks, text })
if (appendCache.length > APPEND_CACHE_MAX) {
appendCache.shift()
}
}
function lexIncrementally(text: string): null | string[] {
const entry = appendCache.find(cached => text.length > cached.text.length && text.startsWith(cached.text))
if (!entry) {
return null
}
// Settled boundary: drop trailing whitespace-only blocks, then the last
// content block (the only one appended text can reinterpret).
let keep = entry.blocks.length
while (keep > 0 && !entry.blocks[keep - 1].trim()) {
keep -= 1
}
if (keep > 0) {
keep -= 1
}
if (keep === 0) {
return null
}
const settled = entry.blocks.slice(0, keep)
let settledLength = 0
for (const block of settled) {
settledLength += block.length
}
// Defensive reconstruction check — the splitter's join(blocks) === text
// property is what makes offsets exact. If it ever doesn't hold, full lex.
if (settledLength > entry.text.length || !text.startsWith(entry.text.slice(0, settledLength), 0)) {
return null
}
return [...settled, ...parseMarkdownIntoBlocks(text.slice(settledLength))]
}
export function parseMarkdownIntoBlocksCached(markdown: string): string[] {
if (markdown.length < EXACT_CACHE_MIN_LENGTH) {
return parseMarkdownIntoBlocks(markdown)
}
const hit = exactCache.get(markdown)
if (hit) {
// Refresh recency (Map iteration order is insertion order).
exactCache.delete(markdown)
exactCache.set(markdown, hit)
return hit
}
const blocks = lexIncrementally(markdown) ?? parseMarkdownIntoBlocks(markdown)
rememberAppend(markdown, blocks)
exactCache.set(markdown, blocks)
if (exactCache.size > EXACT_CACHE_MAX) {
exactCache.delete(exactCache.keys().next().value as string)
}
return blocks
}