Skip to content

fix(studio): track Marked's def rule in the link definition probe - #9645

Merged
danielhanchen merged 25 commits into
unslothai:mainfrom
HughScott2002:fix/9540-9633-link-definition-probe
Sep 20, 2026
Merged

danielhanchen merged 25 commits into
unslothai:mainfrom
HughScott2002:fix/9540-9633-link-definition-probe

Conversation

@HughScott2002

@HughScott2002 HughScott2002 commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

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_RE had 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 gave LINK_DEFINITION_RE two 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.ts already 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.

frames compared 7,100
markdown differs 0
blocks differ 0
render generation differs 0
final document differs 0

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:

case frames markdown differs blocks differ render generation differs
label 200 522 0 0 0
label 250 622 330 9 0
newline in label 136 87 9 0
label 999 2,120 1,079 9 0

A 200-character single-line label is unaffected, as it must be. The other three change, which is the fix.

The cause

updateLinkDefinitionParity holds 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 sets parity.linkDefinition, so hasNeutralRepairParity stops 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:

const LINK_DEFINITION_RE = /\[(?:\\.|[^\]\n\\]){1,200}\]:/;

Marked's def rule is:

/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/

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 current main with the shipped probe:

label 180 200 201 250 600 999 soft-wrapped
first mismatching prefix none none 515 613 1313 2111 127

Ground truth for both is Marked's own definition map, lexer.tokens.links, rather than inference from token shapes:

input registered label
[foo]: /url foo
[<201 chars>]: /url registered
[<5000 chars>]: /url registered
[foo\nbar]: /url foo bar

Marked 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.

const LINK_DEFINITION_RE = /\[(?:\\.|[^\]\\]){1,999}\]:/;

The two changes are independent — with the bound raised to 999 and \n still 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:

line 200 999 unbounded
10k 0.73ms 2.82ms 17.07ms
50k 3.01ms 14.56ms 360.44ms
100k 6.51ms 27.72ms 1257.36ms

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 \n is 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 at STALLED_TAIL_CHARACTERS, returns early on a fenced block, and is never reached on the full-document path. Measured per chunk through IncrementalMarkdownCache:

case 200 (base) 999 999 + line ending
bracket-heavy, unbalanced 1464.5us 1468.3us 1473.1us (0%)
citations, balanced 1545.2us 1548.8us 1548.9us (0%)

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.tsx calls markdownRenderKey(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.

50k reply before after
no reference (short-circuits) 0.004ms 0.004ms
+ reference, short lines 0.044ms 0.045ms
+ reference, citations 0.024ms 0.026ms
+ reference, one 50k line dense with [ 2.45ms 11.95ms

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. before is the shipped regex, after is this PR's — both changes together, not the bound alone.

case chunks before/chunk after/chunk delta tail before tail after
no definition 45 14.0us 13.7us -2% 36 36
label 200 (held today) 81 63.0us 62.8us ±0% 960 960
label 250 (the bug) 89 11.2us 52.0us +362% 35 1056
label 999 214 16.6us 73.9us +345% 37 2556
newline in label 47 9.6us 43.7us +356% 33 551
label 2000 381 27.1us 27.2us +0% 30 30

Reading it honestly:

  • The three large deltas are measured against a broken baseline. Before this change those definitions were committed away, which is exactly why they were cheap — the tail columns show it: 35 characters against 1056. The comparison that means something is the label 200 row, 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.
  • A reply without a long or wrapped definition does not pay. no definition and label 200 are flat at -2% and ±0%; run to run they move by more than the change does.
  • label 2000 is unchanged with an unchanged tail. That is the documented residual past 999, not an oversight.

Tests

Four cases added to MARKDOWN_CASES in tests/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 by incremental blocks match a full Streamdown split at every prefix.

Both regressions were confirmed to fail independently on current main before the fix:

# with the shipped probe
✖ block mismatch at prefix 613 of "[xxx…]: /url\n\npart 0\n\n…"

# with the bound already raised to 999, newline still excluded
✖ block mismatch at prefix 127 of "[foo\nbar]: /url\n\npart 0\n\n…"
check result
tests/streaming-render-schedule.test.ts 17/17
streaming siblings (crlf-retention, latex-retro-edit, latex-corpus, has-prefix, open-fence-repair, horizontal-rule, escaped-inline-math) 77/77
npm test (full frontend suite) 6968/6968
npm run typecheck clean
npx eslint on both changed files clean

Not addressed here

LINK_REFERENCE_RE carries the same {1,200} cap and the same \n exclusion, 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 --local from its own tree: BEFORE is this PR's merge base 191b69c12, AFTER is head 143e0b024. 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.

reference resolution before and after

BEFORE renders the reference as its own source text, See [the docs][the streaming guide] for the details. AFTER renders See the docs for the details. with the docs a link to the definition's destination.

Read out of the live DOM on both sides:

fact BEFORE AFTER
link_hrefs [] ["https://example.com/streaming-guide"]
guide_link_resolved false true
reference_literal true false
intercepted completions requests 1 1
SSE bytes received 3,687 3,687
page errors none none

Worth recording, because it is worse than the issue describes: this reply never reaches the document path on the merge base at all (markdownRenderScope is blocks, 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:

full window before and after


Rebased, and re-shot

Rebased onto main twice as it moved; merges are clean and the streaming suites are 107/107 on the
merged tree.

Reference resolution, before and after

Two isolated Studio installs built by install.sh --local from their own trees, BEFORE the merge
base 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.

reference resolution before and after

BEFORE renders the reference as its own source text, See [the docs][the streaming guide] for the details. AFTER renders See the docs for the details. with the docs a link to the definition's
destination.

Read out of the live DOM on both sides:

fact BEFORE AFTER
link_hrefs [] ["https://example.com/streaming-guide"]
link_texts [] ["the docs"]
guide_link_resolved false true
reference_literal true false
SSE bytes received 3,907 3,907
page errors none none

Present mid-stream, not only once the turn settles:

mid-stream before and after

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's
window 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:

case merge base this branch
label 180 (control) resolves resolves
label 250 (#9540's own row) literal literal
label 600 (#9540's own row) literal literal
wrapped short label (#9633) literal resolves

documentProse gates on LINK_REFERENCE_RE before it reaches the definition probe, and that regex
still caps the reference label at {0,200}. CommonMark requires a reference's label to match its
definition'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 markdownRenderScope and 96 times
through 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_RE widened too, which is the
retention decision already flagged under "Not addressed here" and deserves its own measurement rather
than riding along here.

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
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-14T13:08:27.334230Z 143e0b0 Manual request
🔒 Security Review ✅ Completed 2026-09-09T21:45:33.226588Z 7c72813 Manual request

Security findings

Advisory findings (1)

ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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}\]:/;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

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 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.

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.

Filed as #10529.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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}\]:/;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge 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 👍 / 👎.

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.

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.

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.

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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 20, 2026
@unslothai unslothai deleted a comment from oobabooga Sep 20, 2026
@unslothai unslothai deleted a comment from oobabooga Sep 20, 2026
@unslothai unslothai deleted a comment from oobabooga Sep 20, 2026
@unslothai unslothai deleted a comment from oobabooga Sep 20, 2026
@unslothai unslothai deleted a comment from oobabooga Sep 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 20, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 20, 2026
danielhanchen and others added 4 commits September 20, 2026 07:12
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.
@shimmyshimmer

Copy link
Copy Markdown
Member

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 2400fffcd (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] (on the mirror)

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 2400fffcd8

View security finding report

Only the user who started this review can view the report in Codex.

No triage reaction was recorded on the mirror

Round 2 — reviewed mirror f3bc420dd (this PR's f3bc420dd)

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]*)";

P2 Badge Keep tracking angle destinations after an early >

When an angle destination gains text after an apparent closing bracket, Marked can backtrack and use a later > as the actual close, but this expression permanently stops at the first one. For example, streaming [g]: <a> and then extending it to [g]: <a> b> changes Marked's stored href from a to a> b, while markdownRenderKey remains document:[g]: <a>. The reference can therefore retain the earlier href instead of remounting with the value Marked now stores; the key matcher needs to account for Marked's backtracking rather than always terminating at the first >.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Right about marked, right about the key, and rejected on the consequence. Third round in this family, and it turns on the same mechanism as the previous two.

Confirmed the marked half rather than taking it, against both copies in the tree:

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})?`,

P2 Badge Remount when trailing text invalidates a definition

When a streamed definition grows from [g]: /guide to [g]: /guide trailing prose, Marked removes g from its definition map because the extra same-line text makes the whole definition invalid, but this regex continues returning the key document:[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 prose dropped

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&&...

children is 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 children does not. Streamed one character at a time through IncrementalMarkdownCache:

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 children change. 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. renderGeneration covers 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Studio: a link reference definition whose label spans lines is not held in the live tail

5 participants