Repository navigation
fix(studio): track Marked's def rule in the link definition probe - #9645
danielhanchen merged 25 commits into
Conversation
LINK_DEFINITION_RE decides which link reference definitions are held in the live tail. Marked keeps definitions in one document-wide map and emits no token for a label it has already seen, so a definition the probe misses is committed into an independently parsed block while a twin is still live, and the two lex apart. Missing one is the only direction that costs correctness; a false positive costs retention. The probe diverged from Marked's def rule, whose label is [^\]]+, in two ways, each reachable on the repeated-definition shape the suite sweeps: a label longer than 200 characters first mismatch at prefix 613 a label containing a line ending first mismatch at prefix 127 Marked puts no cap on the label and normalises its whitespace, so [foo\nbar] registers as "foo bar". Widen the class to admit a line ending, and raise the bound to 999. The bound is kept because it is what holds the scan linear. Every "[" is a start position, so a bound of B costs O(n*B) while no bound costs O(n^2): one 100k line dense with "[" costs 6.51ms at 200, 27.72ms at 999 and 1257.36ms unbounded. 999 is also CommonMark's label limit, so the whole valid range is covered. Two consumers pay for admitting a line ending. updateLinkDefinitionParity reads one block of a tail capped at STALLED_TAIL_CHARACTERS and returns early on a fence, so per chunk it is 0%. hasGlobalLinkReference reads the whole reply on every render, but only after LINK_REFERENCE_RE matches; at 50k with a reference present that is 0.045ms over short lines and 0.026ms over citations, both unchanged, against 2.45ms -> 11.95ms on one 50k line dense with "[". Closes unslothai#9540 Closes unslothai#9633
91bf4d7 to
72cfa2a
Compare
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
Security findingsAdvisory findings (1)ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bddd2f2dce
ℹ️ 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".
| // reference present: 0.045ms over short lines and 0.026ms over citations, both | ||
| // unchanged, against 2.45ms -> 11.95ms on one 50k line dense with `[`. That | ||
| // last shape is the price, and it is the same shape the bound above exists for. | ||
| const LINK_DEFINITION_RE = /\[(?:\\.|[^\]\\]){1,999}\]:/; |
There was a problem hiding this comment.
Restrict multiline matches to definition contexts
When a reply contains any real reference plus multiline bracket syntax that is not a definition—for example a fenced Python annotation like def f() -> list[\n str\n]:—the newly newline-permissive, unanchored regex matches from [ through ]: even though Marked treats the region as code. hasGlobalLinkReference() then makes IncrementalMarkdownCache.update() call the sticky renderFullDocument() path, disabling incremental parsing and reparsing the entire growing reply on every subsequent chunk; matching actual definition positions or excluding fenced content would avoid this newly introduced fallback.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The mechanism is right and the cost is real, but "newly introduced fallback" is not: this is a pre-existing false positive that the PR widens by one input shape, and both remedies suggested here are worse than it.
I built the base module (the shipped 200/no-newline regex) alongside head from the same source and streamed the same replies through IncrementalMarkdownCache in 24-character chunks, median of 5:
| reply | base | head |
|---|---|---|
9.4k, single-line list[str]: in a fence |
129.9us/chunk | 129.1us/chunk |
9.4k, wrapped list[\n str\n]: in a fence |
28.0us/chunk | 132.0us/chunk |
| 9.4k, no fence | 18.7us/chunk | 20.0us/chunk |
23k, single-line list[str]: in a fence |
310.2us/chunk | 313.3us/chunk |
23k, wrapped list[\n str\n]: in a fence |
22.2us/chunk | 312.6us/chunk |
| 23k, no fence | 20.4us/chunk | 20.1us/chunk |
An ordinary single-line annotation in a fence already puts hasGlobalLinkReference on the sticky document path on main, at the same cost, and that is the far more common way an LLM writes a return type. The blocks path is flat in reply length and the document path is linear in it, which is the cliff, but the PR does not open it.
On "matching actual definition positions": I tried anchoring to /^ {0,3}\[...\]:/m, which is what Marked's rule looks like read literally, and it is wrong. Marked registers definitions inside containers:
| input | Marked | anchored probe |
|---|---|---|
- [foo]: /url |
foo |
no |
- item\n - [foo]: /url |
foo |
no |
> [foo]: /url |
foo |
no |
> [foo]: /url |
foo |
no |
Every one of those is a false negative, which is the direction that costs correctness -- the definition is not held, it gets committed into an independently parsed block, and it lexes apart from its live twin. That is precisely the bug this PR closes, so anchoring would trade it back for a retention win. Excluding fenced content is the other suggestion, and that means scanning the whole reply for fences on every render, paying on the common path to save on the rare one, and it still leaves the unfenced shapes (value = d[\"key\"]: int in prose matches too).
Narrowing hasGlobalLinkReference without reintroducing a false negative is real work with its own measurement, in the same category as the LINK_REFERENCE_RE residual already listed under "Not addressed here". Filed separately rather than bolted on here.
There was a problem hiding this comment.
💡 Codex Security Review
Here are some automated security review suggestions for this pull request.
Reviewed commit: bddd2f2dce
ℹ️ About Codex security reviews in GitHub
This is an experimental Codex feature. Security reviews are triggered when:
- You comment "@codex security review"
- A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review
Once complete, Codex will leave suggestions, or a comment if no findings are found.
| // reference present: 0.045ms over short lines and 0.026ms over citations, both | ||
| // unchanged, against 2.45ms -> 11.95ms on one 50k line dense with `[`. That | ||
| // last shape is the price, and it is the same shape the bound above exists for. | ||
| const LINK_DEFINITION_RE = /\[(?:\\.|[^\]\\]){1,999}\]:/; |
There was a problem hiding this comment.
Security: Bound multiline definition scans before rendering
When a configured or compromised model/provider returns a long reply containing [ref][x], dense [\n pairs, and a trailing multiline definition, the newline-permissive regex scans up to 999 characters from every [ over the whole growing reply; markdownRenderKey() invokes it twice synchronously (and streaming invokes it again). An exact-pattern Node/V8 benchmark took 332 ms at 50k and 602 ms at 100k characters, versus 0.1/0.2 ms in the parent, allowing repeated Studio-tab stalls. This is fresh evidence beyond the prior false-positive comment: the cost is newline-crossing failed starts, not just sticky parsing. Use a single-pass/anchored scanner or enforce a total work budget.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This is the round-3 item again with a different framing, and it does not get past the same two objections.
The premise is a "configured or compromised model/provider" returning a crafted reply. That is adversarial input, and the bar here is what an ordinary reply contains. On the shapes a reply actually has, the probe does not show up at all: at 50k with a reference present it is 0.045ms over short lines and 0.026ms over citations, and markdownRenderKey got cheaper than the per-line filter it replaced (0.181 -> 0.069ms over short lines, 0.205 -> 0.087ms over citations, 0.078 -> 0.034ms over 1000 definitions), because the split and its allocation are gone. The single enormous [-dense line is the one shape that costs, it is already written into the comment on that constant as the price, and it is exactly what the 999 bound exists to keep linear -- unbounded is 16x worse again at 100k.
"Use an anchored scanner" is the same suggestion as round 3 and it is still wrong: Marked registers definitions inside containers, and - [foo]: /url, - item\n - [foo]: /url, > [foo]: /url and > [foo]: /url are all missed by /^ {0,3}\[...\]:/m. Those are false negatives, which is the direction that costs correctness and is the bug this PR closes. "Enforce a total work budget" is what {1,999} already is; the remaining term is the number of start positions, and a budget on that means giving up on definitions past some offset in the reply, which is the same false negative bought a different way.
Narrowing this without reintroducing a false negative is real work with its own measurement, and it belongs with the LINK_REFERENCE_RE residual already listed under "Not addressed here" rather than in this PR.
There was a problem hiding this comment.
Filed as #10529, with the base-against-head per-chunk table and the anchoring disproof, so it does not sit as an aside in this thread.
Every match of LINK_DEFINITION_RE opens with a `[`, so a `]:` with none in its 2999-character window cannot end one. The probe scanned anyway: it sliced and regex-tested that window for every `]:` in the reply, and markdownRenderKey runs this over the WHOLE reply on every streamed render. A reply carrying a link reference plus 500k of `]:` cost 289ms per render. Skip those occurrences by tracking the last `[` at or before the current `]:`. The cursor only moves forward and its lookahead is cached, so the whole check is one indexOf per `[`. Caching matters more than it looks: asking indexOf again after it has returned -1 rescans the rest of the reply and advances nothing, which measured SLOWER than no skip at all (282ms -> 881ms). The skip is a test, never a bound on the scan. The last `[` can fail where an earlier one matches, because the label class admits `[`: `[a[]:` matches from index 0 and not from index 2, so the slice still starts at the window. reply before after reference + 500k of `]:` 289ms 3.6ms reference + 48k of `]:` 25.7ms 1.0ms reference + TS index signatures 0.005ms 0.005ms reference + python slices 0.005ms 0.005ms 100k line dense with `[` 1.22ms 1.42ms Predicate unchanged: 12000 seeded inputs plus the window, astral-width, surrogate-cut and line-ending corners all agree with LINK_DEFINITION_RE.test.
A `[` in the window is not enough to make the scan worth paying for. `[]: ` keeps one in every window while never opening a definition, so each occurrence still sliced ~3000 characters and scanned every bracket start before the nonempty-label class failed: 500k cost 338ms inside a path markdownRenderKey runs on every streamed render. The label admits no bare `]`, so a match's `[` must also follow the last UNESCAPED `]` before the terminator. Bounding the window there collapses it to the failing label, 338ms -> 7.1ms, and the close cursor advances monotonically like the bracket one, so the whole check stays one indexOf per bracket. Unescaped is load-bearing: `[a\]b]:` keeps its escaped `]` inside the label where `[a]b]:` does not, so the bound only applies on an odd backslash run. reply before after reference + 500k of `[]: ` 338ms 7.1ms reference + 500k of `]: ` 3.3ms 4.7ms reference + 500k of `[abc]: ` 65.4ms 66.0ms Predicate unchanged: 30000 seeded inputs over an alphabet carrying escaped and bare brackets, plus the escape, window, astral-width and surrogate-cut corners, all agree with LINK_DEFINITION_RE.test.
Four blocks around hasLinkDefinition had grown to describe one scan between them, and the isEscaped helper landed between the scan's header comment and the function it describes, leaving it above the wrong definition. One header on the function, one line on the helper, one on the skip test. Comment lines this PR adds: 44 -> 33 in the module, 50 -> 41 in the suite. Every survivor carries a fact the code does not state -- which direction to err in, why the bound stays, why the lookahead is cached, the escape rule, and the measured numbers behind each. Comment-only, AST-verified against 69ec64b.
|
Review record for #9645, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#26. Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found. Round 1 — reviewed mirror
|
| input | href stored (17.0.6) | href stored (16.4.2) |
|---|---|---|
[g]: <a> |
a |
a |
[g]: <a> b> |
a> b |
a> b |
[g]: <a b> |
a b |
a b |
[g]: <a>b> |
a>b |
a>b |
So marked does backtrack to the later >, and LINK_DEFINITION_KEY_RE does stop at the first one: on the settled document the key is document:[g]: <a> while the stored href is a> b. Both halves of the report are accurate.
The consequence is what does not hold. A stale render needs a frame where marked's href moves while the string handed to Streamdown does NOT, because the memo compares children and re-renders on any change regardless of the key. Streamed See [t][g]. + 20 paragraphs + [g]: <a> b> one character at a time through IncrementalMarkdownCache:
frames where marked's href moved: [191, 193, 194]
of those, frames where the rendered string did NOT move: []
The href only ever moves because the destination text grew, and that growth is itself the children change. There is no frame that can retain the earlier href.
This is why the key is an invariant this file maintains rather than a correctness requirement, and why widening the expression is the wrong trade here: the obvious fix lets a destination run past its first > toward any later one, which is exactly the churn the key was narrowed to stop. A shape whose fix can only cost remounts and cannot fix a render is below the bar.
chatgpt-codex-connector[bot] on
studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts(on the mirror)@@ -50,13 +50,73 @@ const INLINE_CODE_UNDERSCORE_CONTEXT = "`a _b_ c`\n\n"; const INLINE_LATEX_CONTEXT = "\\(\n\n"; const FOOTNOTE_REFERENCE_RE = /\[\^[\w-]{1,200}\](?!:)/; const FOOTNOTE_DEFINITION_RE = /\[\^[\w-]{1,200}\]:/; -const LINK_DEFINITION_RE = /\[(?:\\.|[^\]\n\\]){1,200}\]:/; -// Inside a block marked did not lex as code, the container markers and their indentation -// have already been accounted for, so the label may sit behind any mix of them. -// A block quote marker may be followed by nothing, but a list marker needs whitespace after -// it or no list opens -- `-[label]:` is ordinary prose, not a bullet holding a definition. -const LINK_DEFINITION_LINE_RE = - /^[ \t]*(?:(?:>[ \t]*)|(?:(?:[-*+]|\d{1,9}[.)])[ \t]+))*\[(?:\\.|[^\]\n\\]){1,200}\]:/m; +// Marked's `def` label, `[^\]]+`: a miss is committed away and Marked emits no +// token for a label it has already seen, so err toward a false positive, which +// only costs retention. `\n` is in the class because Marked normalises label +// whitespace, `\\[\s\S]` because `.` rejected a label whose line ends in a +// backslash, `u` because without it `{1,999}` bounds 499 emoji. 999 is +// CommonMark's cap; unbounded would make every `[` an O(n) start position. +const LINK_DEFINITION_RE = /\[(?:\\[\s\S]|[^\]\\]){1,999}\]:/u; +// Widest match in UTF-16 units: 999 times `\` plus an astral code point, plus `[`. +const LINK_DEFINITION_WINDOW = 999 * 3 + 2; + +// Same predicate as the regex over the whole reply, since the pattern has no +// anchor or lookaround, but `]:` is rare where `[` is not (unslothai/unsloth#10529). +// Every match must open with a `[`, so a `]:` with none in its window cannot end +// one and is skipped before paying for the slice and the scan. `bracket` only +// ever moves forward, which keeps that check O(n) over the whole reply; +// `lastIndexOf` would reintroduce the quadratic scan it exists to remove, since +// its backward search is not bounded by the window. +function hasLinkDefinition(text: string): boolean { + let bracket = text.indexOf("["); + // The lookahead is CACHED, not recomputed per `]:`. Asking `indexOf` again + // after it has already returned -1 rescans the whole remaining reply and + // advances nothing, which is the quadratic this skip exists to remove -- + // measured, that mistake made a 500k reply SLOWER than no skip at all + // (282ms -> 881ms). Held this way the total is one `indexOf` per `[`. + let nextBracket = bracket < 0 ? -1 : text.indexOf("[", bracket + 1); + for (let end = text.indexOf("]:"); end >= 0; end = text.indexOf("]:", end + 1)) { + while (nextBracket >= 0 && nextBracket <= end) { + bracket = nextBracket; + nextBracket = text.indexOf("[", bracket + 1); + } + const start = end < LINK_DEFINITION_WINDOW ? 0 : end - LINK_DEFINITION_WINDOW; + // Note `start`, not `bracket`: the LAST `[` can fail where an earlier one + // matches, because the class admits `[` inside a label (`[a[]:` matches from + // index 0 and not from index 2), so this is only ever a skip test. + if (bracket < start || bracket > end) { + continue; + } + if (LINK_DEFINITION_RE.test(text.slice(start, end + 2))) { + return true; + } + } + return false; +} +// A label may sit behind any mix of container markers. A list marker needs +// whitespace after it or no list opens: `-[label]:` is prose, not a bullet. +const CONTAINER_PREFIX = "[ \t]*(?:(?:>[ \t]*)|(?:(?:[-*+]|\\d{1,9}[.)])[ \t]+))*"; +const LINK_DEFINITION_LINE_RE = new RegExp( + `^${CONTAINER_PREFIX}${LINK_DEFINITION_RE.source}`, + `m${LINK_DEFINITION_RE.flags}`, +); +// The probe plus exactly what Marked stores after the label, which is what has to +// move the remount key. Must be spelled as Marked spells it, never as "the rest of +// the line": this feeds a React key, so anything captured that Marked does not +// store remounts the subtree once per character of it. Angle destinations run to +// their `>` and may hold spaces; a bare one runs to whitespace and KEEPS a `>` +// (`[g]: https://x.test/a>b`). At most one title, on the destination's line or the +// one below but never both, and padding may precede the break. +// +// Residual: a wrapped title stops the key at its opening line, so the link keeps +// its old title until the message settles. +const LINK_DEFINITION_DESTINATION = "(?:<[^>\\n]*>?|[^\\s]*)"; +const LINK_DEFINITION_TITLE = "[\"'(][^\\n]*[\"')]"; +const LINK_DEFINITION_KEY_RE = new RegExp( + `${LINK_DEFINITION_LINE_RE.source}[ \\t]*(?:\\n${CONTAINER_PREFIX})?${LINK_DEFINITION_DESTINATION}` + + `(?:[ \\t]+${LINK_DEFINITION_TITLE}|[ \\t]*\\n${CONTAINER_PREFIX}${LINK_DEFINITION_TITLE})?`,
Remount when trailing text invalidates a definition
When a streamed definition grows from
[g]: /guideto[g]: /guide trailing prose, Marked removesgfrom its definition map because the extra same-line text makes the whole definition invalid, but this regex continues returning the keydocument:[g]: /guide. Since Streamdown's memo comparator ignores changed children, the already-rendered[guide][g]remains a link until streaming ends instead of reverting to literal text; the key must also change when a previously valid definition becomes invalid.Useful? React with 👍 / 👎.
Rejected on the mirror
Reply from danielhanchen:
Right about marked, and rejected on the premise this time rather than on reachability, because the premise is checkable and it is wrong.
The marked half reproduces exactly. Streamed through
lexer.tokens.links:
input href stored [g]: /guide/guide[g]: /guide trailing prosedropped and the key does freeze at
document:[g]: /guide. Both observations hold.The load-bearing claim is the next one, that Streamdown's memo comparator ignores changed children. It does not. From the shipped bundle,
node_modules/streamdown/dist/chunk-BO2N2NFS.js, the top-level comparator is:(e,t)=>e.children===t.children&&e.shikiTheme===t.shikiTheme&&e.isAnimating===t.isAnimating&&...
childrenis the FIRST term. A changed markdown string re-renders whatever the key does.So the stale render needs a frame where marked's definition map moves while
childrendoes not. Streamed one character at a time throughIncrementalMarkdownCache:frames where the stored href moved: [193, 194, 195, 196, 197, 198, 200] of those, frames where the rendered string did NOT move: []The definition can only be invalidated by text arriving, and that arrival is itself the
childrenchange. There is no frame that keeps the stale link.This is the third item resting on that comparator, so it is worth settling rather than re-deciding: the render key is an invariant this file maintains, not the thing that schedules a render.
renderGenerationcovers the one case where output must change while the string does not, a commit dropping retained blocks.
Round 3 — reviewed mirror 69ec64b84 (no equivalent commit found on this PR)
chatgpt-codex-connector[bot] (on the mirror)
Codex Review: Didn't find any major issues. Bravo.
Reviewed commit:
69ec64b847
No triage reaction was recorded on the mirror
Verdict
The round converged at mirror 69ec64b84 (no equivalent commit found on this PR).
This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.
Closes #9633. Partially addresses #9540: the retention half is fixed, the reference cap is not. See "What #9540 still needs" at the end.
Two reported symptoms, one cause:
LINK_DEFINITION_REhad drifted from the rule it exists to track. Fixing either alone leaves the other reachable through the same code path, so they are fixed together and the reasoning is shared.Rebased onto current
main. Every number below was re-measured against it, not against the base this PR opened on — #9796 landed in between and gaveLINK_DEFINITION_REtwo consumers it did not have before, which changes the cost story. That is called out in full under "What admitting a line ending costs".Rendering idempotency, first and as a gate
This changes which link reference definitions are held in the live tail, which decides what the incremental cache is allowed to commit, so the rendered document was checked before any timing was read.
Frame by frame, base against head. Both builds of the module were driven through the same stream and compared on every frame on the three things the renderer consumes: the Markdown string handed to Streamdown, the block list that string is split into, and the render generation that keys the component. The corpus is the one
tests/streaming-latex-corpus.test.tsalready sweeps — same fragments, same fixed seed (20260817), 40 documents loose and tight — so the gate runs over documents the suite already treats as representative rather than over anything picked for this change.Nothing an ordinary reply renders changes, on any frame.
The gate can report a difference. A zero table is only worth reading if the comparison is capable of a non-zero one, so the same comparison was run on the shapes the fix is about:
A 200-character single-line label is unaffected, as it must be. The other three change, which is the fix.
The cause
updateLinkDefinitionParityholds link reference definitions in the live tail because Marked keeps them in one document-wide map and emits no token for a label it has already seen. A definition the probe misses never setsparity.linkDefinition, sohasNeutralRepairParitystops blocking the commit, the definition is committed into an independently parsed block, and the retained block and the still-live twin are lexed apart. Nothing else in the parity set covers a definition, so the probe is the only thing standing between those two lexes.The probe was:
Marked's
defrule is:The label is
[^\]]+— any run up to the closing bracket, with no length cap and no exclusion of a line ending. The probe differed on both counts, and each difference is independently reachable on the repeated-definition shape the suite already sweeps (a definition, prose past the rollback window, then the same definition again). Swept at every prefix against currentmainwith the shipped probe:Ground truth for both is Marked's own definition map,
lexer.tokens.links, rather than inference from token shapes:[foo]: /urlfoo[<201 chars>]: /url[<5000 chars>]: /url[foo\nbar]: /urlfoo barMarked normalises the label's whitespace, so a label that soft-wraps registers as though it never had.
The fix
Track the rule: admit a line ending, and raise the bound to 999.
The two changes are independent — with the bound raised to 999 and
\nstill excluded, the newline case still diverges at prefix 127 — which is why both are needed and why one PR is the honest unit.Why the bound stays
Dropping it is the exact match for Marked, which has no cap, and it does close labels past 999. It was measured and rejected: the bound is what keeps the scan linear. Every
[is a start position and each scans until it can decide, so a bound of B costs O(n·B) while no bound costs O(n²).One long line dense with
[that never reaches]:, the worst case for the scan:999 stays linear at 2× length for 2× the work; unbounded costs 3.5×. 999 is also CommonMark's label limit, so the whole valid range is covered. A label past it is outside the spec and stays mis-lexed — recorded in the comment as the deliberate trade rather than left to be rediscovered.
What admitting a line ending costs
Since #9796 this regex has two consumers, and they are bounded differently. Isolated, admitting
\nis not free: the exclusion is what let a start position stop at the end of its line, so on bracket-dense prose the regex alone goes from 0.23–0.68ms to about 18ms per 50k.updateLinkDefinitionParity— unchanged at 0%. It reads one block of a live tail capped atSTALLED_TAIL_CHARACTERS, returns early on a fenced block, and is never reached on the full-document path. Measured per chunk throughIncrementalMarkdownCache:The balanced case matters more than it looks: unbalanced brackets stall into the full-document path, where the regex never runs, so only a balanced bracket-dense reply actually exercises it on every block.
hasGlobalLinkReference— the new one, and the one that is not bounded by the tail.markdown-text.tsxcallsmarkdownRenderKey(processedText)on every render, so this sees the whole reply. It is guarded by short-circuit:LINK_REFERENCE_RE.test(markdown) && LINK_DEFINITION_RE.test(markdown), so the definition probe only runs once a reference is already present.[Ordinary replies do not pay. The last row is the real price of this change, and it is the same shape the length bound above exists to contain — a single enormous line dense with
[that also carries a link reference.Per-chunk cost
A reply of ordinary prose carrying one long definition and a reference to it, streamed in 12-character chunks, median of 15 interleaved runs after 5 warmups. Both variants are built from the same module source with only the regex line replaced, and they alternate which runs first, so JIT state cannot decide the answer.
beforeis the shipped regex,afteris this PR's — both changes together, not the bound alone.Reading it honestly:
label 200row, which was already correct: a held definition costs 62.8us per chunk there, and a 250-character one now costs 52.0us on the same reply. Being right is not more expensive than it already was.no definitionandlabel 200are flat at -2% and ±0%; run to run they move by more than the change does.label 2000is unchanged with an unchanged tail. That is the documented residual past 999, not an oversight.Tests
Four cases added to
MARKDOWN_CASESintests/streaming-render-schedule.test.ts, following the repeated-definition shape already in that list: labels of 250 and 999, a soft-wrapped label, and a soft-wrapped label past the old bound. They are swept byincremental blocks match a full Streamdown split at every prefix.Both regressions were confirmed to fail independently on current
mainbefore the fix:tests/streaming-render-schedule.test.tsnpm test(full frontend suite)npm run typechecknpx eslinton both changed filesNot addressed here
LINK_REFERENCE_REcarries the same{1,200}cap and the same\nexclusion, and since #9796 it gates whether a reply renders as one document at all. Widening it would push more replies onto the whole-document path, which is a retention decision rather than a probe-accuracy one and deserves its own measurement. Left alone deliberately.Before and after in Studio
Two isolated Studio installs, each built by
install.sh --localfrom its own tree: BEFORE is this PR's merge base191b69c12, AFTER is head143e0b024. Both were driven through the same scene and fed the same 3,687 bytes of SSE by a scripted server in place of a model, so the two halves cannot differ in what was said, only in how it was rendered.The reply carries a definition whose label wraps onto a second line, which is #9633's half, then twelve paragraphs to push it past the rollback window, then a reference to it.
BEFORE renders the reference as its own source text,
See [the docs][the streaming guide] for the details.AFTER rendersSee the docs for the details.withthe docsa link to the definition's destination.Read out of the live DOM on both sides:
link_hrefs[]["https://example.com/streaming-guide"]guide_link_resolvedreference_literalWorth recording, because it is worse than the issue describes: this reply never reaches the document path on the merge base at all (
markdownRenderScopeisblocks, 28 blocks), so the reference stays broken after the turn ends rather than only while it streams. The same difference is present in the mid-stream shot.The full window, same pair:
Rebased, and re-shot
Rebased onto
maintwice as it moved; merges are clean and the streaming suites are 107/107 on themerged tree.
Reference resolution, before and after
Two isolated Studio installs built by
install.sh --localfrom their own trees, BEFORE the mergebase and AFTER the PR head, both driven through the same scene and fed the same 3,907 bytes of
SSE by a scripted server standing in for a model. The halves cannot differ in what was said, only in
how it was rendered.
The reply carries a definition whose label wraps onto a second line, then twelve paragraphs to push
it past the rollback window, then a reference to it.
BEFORE renders the reference as its own source text,
See [the docs][the streaming guide] for the details.AFTER rendersSee the docs for the details.withthe docsa link to the definition'sdestination.
Read out of the live DOM on both sides:
link_hrefs[]["https://example.com/streaming-guide"]link_texts[]["the docs"]guide_link_resolvedreference_literalPresent mid-stream, not only once the turn settles:
Both halves render all twelve paragraphs, which is what stops two empty bubbles from reading as a
clean before/after.
The pair was shot at head
f3bc420dd. The only later change to this PR's own files is the probe'swindow bound, whose predicate is proven identical to the regex over 30,000 seeded inputs plus the
escape, window, astral-width and surrogate-cut corners, so it cannot move a rendered pixel.
What #9540 still needs
#9540 states its symptom as "link resolves: no" for labels of 250 and 600 characters. Measured end to
end against streamdown's own marked, rendering each reply the way the scheduler routes it:
documentProsegates onLINK_REFERENCE_REbefore it reaches the definition probe, and that regexstill caps the reference label at
{0,200}. CommonMark requires a reference's label to match itsdefinition's label, so a definition label past 200 characters always has a reference past 200
characters, which never passes that gate. Instrumenting the probe confirms it rather than inferring
it: on #9540's repro the widened regex executes 0 times through
markdownRenderScopeand 96 timesthrough the retention path.
So what this PR fixes for #9540 is real but narrower than "closes": the definition is held in the
live tail, and the incremental block list stops diverging from a full split (first mismatch on the
merge base at prefix 613). The reported symptom needs
LINK_REFERENCE_REwidened too, which is theretention decision already flagged under "Not addressed here" and deserves its own measurement rather
than riding along here.