Skip to content

fix(studio): widen the link reference probe to match the definition probe - #11375

Merged
danielhanchen merged 7 commits into
mainfrom
fix/9540-reference-label-cap
Sep 21, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
fix/9540-reference-label-cap

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 20, 2026 •

Copy link
Copy Markdown
Member

Closes #9540.

#9645 widened the link definition probe to CommonMark's 999 character label cap. The reference probe was left at 200, and a label only resolves when both ends of the pair carry it, so every label in 201..999 still failed at the reference end: the reply stayed on the blocks path and the reference rendered literally. That is the input class #9540 reports, so it was only partially fixed.

The change

LINK_REFERENCE_RE now admits exactly what LINK_DEFINITION_RE admits: the same character class, the same 999 cap, the same u flag.

Widening the regex on its own is a regression rather than a fix. The cap is the backtracking budget spent at every start position, and a run of [ supplies one start position per character. Over a 500k reply:

reference probe cost
narrow, as today 385ms
widened, tested over the whole reply 1743ms
widened, behind the windowed scan 7.7ms

So the widening comes with hasLinkReference, which bounds each candidate the way hasLinkDefinition bounds each ]:. Neither label admits a bare ], which pins a candidate on both sides: it opens after the last unescaped ] before the ][ seam and closes at the first unescaped one after it. A seam whose closing ] sits past the cap cannot match and is skipped without a test. Both cursors only advance, so the escape walks stay linear over the reply.

Behaviour

reference label before after
200 document document
201 blocks document
400 blocks document
999 blocks document
1000 blocks blocks

1000 stays on the blocks path because 999 is CommonMark's cap, not Marked's. Marked's def label is [^\]]+ with no cap and does register a longer one, but Marked only splits here, through streamdown's parseMarkdownIntoBlocks; the render is streamdown's remark pipeline, which is CommonMark-strict. Counting anchors through it, a 1000 character label resolves to 0 links even with the whole reply lexed as one document, so there is no link past 999 for the blocks path to lose.

Cost through the render path

Median per render of markdownRenderKey plus parseMarkdownIntoRenderableBlocks, the pair markdown-text.tsx calls, against main:

reply main this branch
50k prose with a reference 1.34ms 0.89ms
50k citations 6.61ms 3.58ms
50k markdown links 5.91ms 5.79ms
50k python 3.06ms 3.07ms
100k dense with [ 13.81ms 13.24ms
200k dense with ][ 37.13ms 36.74ms
200k of [a][b] pairs 41.46ms 41.68ms
500k of [ then a reference 199.49ms 191.65ms

The shapes carrying many brackets get cheaper because the scan reaches its answer without walking the reply.

One shape did regress and the first version of this description was wrong to say nothing did. A 200k reply of nothing but ][ went 1.16ms to 12.03ms, because the seam loop itself costs about 0.1us and that reply has 100,000 seams. It is back to 1.57ms now, by asking the cheaper definition probe first in documentProse: both are pure, so the conjunction is unchanged, but only the probe asked second is ever skipped, and the definition one refuses a reply with no ]: on its first indexOf.

Verification

  • hasLinkReference is the same predicate as the regex over the whole string: differential over 40,000 seeded inputs (seed 20260920) built from [, ], \, !, newlines, CRLF, astral characters and long filler runs, plus hand-picked boundary shapes at 999 and 1000 code points, escaped and unescaped ], and labels split across lines. No counterexample.
  • Full frontend suite: 8063 passed, 0 failed.
  • npm run typecheck and eslint clean.
  • Negative controls, both checked rather than assumed: the label test fails on main with a 201-character label did not reach the document path, and the cost test fails at 1508.3ms if the widened regex is kept but the scan removed.

Not in this change

A definition title that spans lines still stops the render key at the destination, so such a link keeps its old title until the message settles. It is cosmetic and self-correcting, and tightening it means capturing more than Marked stores, which remounts the subtree once per character. Worth its own change.


What it looks like

Two isolated Studio installs, BEFORE built from this PR's merge base 770f4a474 and AFTER from its head 788dae47c, driven through the same scripted reply: prose, a link reference whose label is 400 characters, then the definition last.

before and after

BEFORE prints the label, wrapping See [guide][the-complete-guide-to-streaming-markdown-rendering-in-unsloth-studio-...-in-u] for the full write-up. over six lines with no link in the message. AFTER reads See guide for the full write-up. on one line, with guide as the link.

Read off the rendered bubble rather than the markdown, since the source text is identical on both sides by construction:

fact before after
anchor_count 0 1
anchor_texts [] ['guide']
anchor_hrefs [] ['https://x.test/a']
literal_reference_visible true false
reply_chars 518 114

Both halves intercepted exactly one /v1/chat/completions, received the same 1954 SSE bytes, and show Streaming markdown has two halves that have to agree. above and That is the whole answer. below, which is what says the two sides were handed the same reply and only the rendering moved. The one other value that differs is the provider UUID each home creates for itself, which is not content.

…robe

A label only resolves when both ends of the pair carry it. The definition
probe was widened to Marked's 999 character cap, but the reference probe
was left at 200, so any label in 201..999 failed at the reference end and
the reply stayed on the blocks path with the reference rendered literally.

Widening the regex alone is a regression: the cap is the backtracking
budget at every start position, and a run of `[` supplies one per
character. Measured over a 500k reply, the widened regex costs 1743ms
against 385ms for the narrow one. Bound each `][` seam instead, the way
the definition side bounds each `]:`, and it costs 7.7ms.

Neither label admits a bare `]`, so a candidate is bounded on both sides:
it opens after the last unescaped `]` before the seam and closes at the
first one after it. Both cursors only advance, so the escape walks stay
linear over the reply.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 20, 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-21T08:50:16.057542Z 788dae4 Manual request
ℹ️ 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.

@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: 3ae704bac3

ℹ️ 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".

// the reference still literal (unslothai/unsloth#9540). Same class, same cap, same `u`.
const LINK_REFERENCE_RE =
/!?\[(?:\\.|[^\]\n\\]){1,200}\]\[(?:\\.|[^\]\n\\]){0,200}\]/;
/!?\[(?:\\[\s\S]|[^\]\\]){1,999}\]\[(?:\\[\s\S]|[^\]\\]){0,999}\]/u;

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 Keep the reference probe within a prose block

When bracket fragments are separated by a paragraph boundary, such as [foo\n\nbar][x], the widened character classes now match across the blank line. If the reply also contains any unrelated definition like [g]: /g, markdownRenderScope consequently selects document even though the Markdown renderer resolves no reference at all; any code fences in that reply then unnecessarily lose their per-block Copy/Download controls. Restrict multiline matching to text that can belong to one inline block rather than allowing \s\S/the negated class to cross arbitrary paragraph boundaries.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Reproduced, and the first half is right: [foo\n\nbar][x] with an unrelated [g]: /g does select document, and remark resolves 0 anchors there, so that reply is on the document path for nothing. CommonMark agrees on why: a label "can have at most 999 characters inside the square brackets" and may span lines, but not a blank line, since the blank line ends the paragraph holding it (https://spec.commonmark.org/0.31.2/#link-label).

Not taking it here, for two reasons.

The direction is the one this file deliberately buys. Saying document when blocks would have done costs that reply its per-block Copy and Download controls and nothing else, which is the tradeoff written above documentProse and the asymmetry tests/link-definition-oracle.test.ts is built around: it guards the expensive half exhaustively and leaves this half alone on purpose. Nothing renders wrongly and nothing is lost.

More to the point, the fix has to be symmetric or it is a regression. LINK_DEFINITION_RE carries the identical class and admits the identical blank-line-spanning label. A label only resolves when BOTH ends admit it, and the two ends having drifted apart is the entire bug this PR closes (#9540). Narrowing the reference end alone re-opens it in the other direction.

Two things worth recording against a symmetric follow-up. The class cannot simply lose \n: [foo\nbar][x] resolves to 1 anchor and must keep matching, which is #9633. And the variant with a matching definition, [foo\n\nbar][x] plus [x]: /x, already resolves to 1 anchor via the trailing shortcut reference, so the false positive also needs that group to be unresolvable, which narrows it further than the report suggests.

On cost, so it is not carried over as a reason it was not done: I measured the tempered form (?:(?!\n[ \t]*\n)(?:\\[\s\S]|[^\]\\])) and it is only 1.2x to 1.3x over the current class on a 500k whole-string test, and inside the windowed scan it runs on a ~6k slice where that is noise. It also behaves correctly, false on the blank-line case and true on the single-newline one. So the objection is scope and symmetry, not speed.

@danielhanchen

Copy link
Copy Markdown
Member Author

The Repo tests (CPU, rest) red here is stale, not something in this branch.

It fails on tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding for tests/security/test_desktop_release_resolver.py:124,132 and tests/security/test_release_desktop_integrity.py:911. Those three reads were given encoding = "utf-8" in #11372, which merged at 14:35 UTC as 7cc58b4. This run was created at 13:39 UTC, so its merge ref predates the fix and re-running it would reuse the same merge commit.

A rebase on current main clears it. Nothing to change in the PR for that check. The Frontend unit tests (Windows) failure is separate: it is the "Data settings deletion choices in Firefox" step, which is worth a look on its own.

pull Bot pushed a commit to y1024/unsloth that referenced this pull request Sep 20, 2026
…lothai#11386)

A pull_request run does not test the branch head. It tests refs/pull/N/merge,
a merge of the branch into the base as the base stood when the run was created.
GitHub does not rebuild that ref because the base later moved, and a re-run
replays the same merge commit, so a fix that lands on main after a run starts
stays invisible to that run until someone pushes to the branch.

That cost real time today. unslothai#11372 gave three test files encoding = "utf-8" and
merged at 14:35 UTC. Runs created at 13:39, 14:26 and 14:29 on unslothai#11375, unslothai#11357
and unslothai#11373 all went on failing tests/test_source_read_encoding.py on exactly
those three lines, and all three were first read as defects in branches that
had never touched the files.

Adds .github/actions/merge-ref-age, which asks the compare endpoint how far the
base branch has moved since this run's merge ref was built and prints a notice
if the answer is not zero. It is wired into the two studio-backend-ci.yml jobs
that run pytest, gated on failure(), so a green job never pays for it and it
stays quiet when the base has not moved.

It is advisory and cannot fail a job. A stale merge ref does not make a failure
untrue: the merge really does fail. Deciding otherwise for the reader would be
worse than the confusion it is fixing, so the script never exits non-zero and
never emits ::error::.

tests/studio/test_merge_ref_age_is_reported.py keeps both properties: every job
in that workflow running pytest carries the step under failure(), and the
action's script cannot fail the job it sits in. Each assertion was checked by
reverting it individually against a green baseline. The repo's own
test_workflow_guards_run_unfiltered caught the new guard missing from the
unfiltered job, so it is registered in workflow-trigger-lint.yml too.
@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed the reference probe in streaming-render-schedule.ts is still at 200 while the definition probe is at 999, so longer labels never resolve, and the windowed scan keeps the widened cap off the per-start-position cost. Will get this reviewed.

@danielhanchen danielhanchen self-assigned this Sep 21, 2026
…kahead is empty

The windowed scan added with the widened reference probe has two shapes where it
gives back nothing, and one of them is quadratic.

`unescapedClose` returning -1 means no unescaped `]` remains, but -1 is always
behind the next seam, so the cache never holds and every later `][` re-walks the
whole tail while advancing nothing. This is the cost `hasLinkDefinition` caches
its lookaheads to avoid, and its comment says so. `\][` repeated is the witness,
since every closer there is escaped:

| reply | narrow probe (main) | as merged | with this |
| --- | --- | --- | --- |
| 6k | 1.8ms | 26ms | - |
| 48k | 16ms | 1742ms | 1.1ms |
| 500k | 162ms | 196047ms | 2.6ms |

196 seconds on the render path, which runs per frame while a reply streams.

The second is the one the window exists to prevent, reintroduced inside it: the
window bounds the slice, not the start positions in it, so a window packed with
`[` whose reference label is past the cap pays the full widened budget at every
one of them. 500k of that shape costs 3225ms against 349ms for the narrow probe.
The reference label a match could use is a single candidate, because the `[`
before it restarts escape parity at the seam, so it is the text between the seam
and the first unescaped `]` and nothing else. Test it once per seam. The opener
is tracked forward for the same reason `lastIndexOf` is avoided next door, and
its skip runs first so a seam with no opener pays neither test.

Equivalence to the regex over the whole string is unchanged: 788,642 inputs, no
counterexample. Exhaustive over `a [ ] \ !` to length 8, 300,000 seeded from an
alphabet carrying astral code points, lone surrogates, CRLF and long backslash
runs, and boundary shapes built at 999 and 1000 repetitions rather than 999 and
1000 characters, escaped and unescaped closers, and backslash runs straddling
the computed slice start where slice-local parity can differ from the reply's.

Cost through the render path, median of 5, against the merge base:

| reply | main | as merged | with this |
| --- | --- | --- | --- |
| 100k dense with `[` | 133.52ms | 0.01ms | 0.01ms |
| 500k of `[` then a reference | 666.71ms | 12.05ms | 19.80ms |
| 200k dense with `][` | 1.16ms | 12.03ms | 10.02ms |
| 50k prose with a reference | 1.27ms | 1.43ms | 1.37ms |
| 50k citations | 16.57ms | 16.07ms | 16.60ms |

The `][` row does not reach the merge base and this does not close it: the seam
loop itself costs about 0.1us per seam, and a 200k reply of nothing but seams
has 100,000 of them. It is linear and 10ms absolute, so it stays, but it is a
regression against the narrow probe and the description should not have said
nothing regresses.
…er scope

`documentProse` needs both probes to agree, and both are pure, so the conjunction
does not care which is asked first. The cost does: only the probe asked SECOND is
ever skipped, and the two are not equally expensive to run. The reference scan
carries the window and the reference-label test, the definition scan carries
neither, and a reply dense with `][` that holds no definition at all is the shape
that separates them, because the definition probe refuses it on its first
`indexOf` while the reference probe walks every seam.

Median of 15 through `markdownRenderKey` plus `parseMarkdownIntoRenderableBlocks`:

| reply | reference first | definition first |
| --- | --- | --- |
| 200k dense with `][` | 10.42ms | 1.57ms |
| 500k of `[` then a reference | 20.50ms | 0.26ms |
| 500k packed `[` past the cap | 5.17ms | 0.27ms |
| 50k citations | 14.49ms | 13.59ms |
| 50k prose with a reference | 1.35ms | 1.16ms |
| 500k of `]: ` | 9.54ms | 10.32ms |
| 500k of `[]: ` | 16.86ms | 15.43ms |

The `]: ` row is the trade, and it is the whole of it: a reply carrying a
definition and no reference now pays the definition scan instead of being
refused by the reference one. Both dense-`]:` tests already bound that at 100ms
and it lands an order of magnitude inside them.

`200k dense with ][` is the row that matters, because it was the last shape still
above the merge base after the two scan fixes: 1.16ms there, 10.42ms before this,
1.57ms now. Routing is untouched, as it has to be for a reordered conjunction:
the 1386-cell base-versus-head enumeration is unchanged at 1009 identical, 377
newly reaching the document path, 0 reaching it less often.
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 21, 2026
…ked's

The new test justified its `blocks` assertion at 1000 with "999 is Marked's cap,
so a longer label is not a reference". Marked's `def` rule is
`/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/`, checked in
the installed marked 17.0.6 under streamdown and 16.4.2 at the top level, and its
label is `[^\]]+` with no cap at all. It resolves a 1000 and a 2000 character
label, checked by parsing both rather than read off the pattern.

999 is CommonMark's cap, and the definition probe alongside says so. The reason
both probes stop there is the one that probe gives: unbounded makes every `[` an
O(n) start position. So the line is pinning a residual, and it is a residual in
the direction this file calls the expensive one, since saying `blocks` for a
reply that needed one document splits the pair and leaves the reference literal.

Nothing changes in the assertion or the behaviour. It matters because a comment
that reads as a correctness boundary is a comment nobody revisits, and the whole
reason this PR exists is that the two ends of the same pair drifted apart while
each looked settled.
…broke on

`link-definition-oracle.test.ts` exists to catch the expensive error, a reply
sent down the blocks path when its reference only resolves in one piece. It
sweeps definition contexts, container prefixes, neutral blocks and line endings,
and every one of those cases uses the label `g`. Length is the one dimension the
probes actually bound, and the only one the oracle never varied, so a bound set
too small was invisible to the file written to catch exactly that. #9540 is that
bug, and #9645 moving the bound on one end while the other stayed at 200 was
invisible here for the same reason.

The new sweep is in scope for a length only when the rendered outcome really
differs between the two paths, the same gate the sweep above uses, plus an
assertion that at least one length was in scope so it cannot quietly stop testing
anything. It encodes no cap of its own.

On the merge base it fails and names them:

  label length 201, 201, 400, 400, 998, 998, 999, 999

1, 2, 199 and 200 pass there, which is the half of the pair that already worked.
1000, 1001 and 2000 drop out of scope on both sides rather than being excluded by
hand, and that is worth stating, because it is also the answer to what sits past
the cap.

Also corrects the note I added on the 1000 assertion. Marked's `def` label really
is `[^\]]+` with no cap, but Marked only SPLITS here, through streamdown's
`parseMarkdownIntoBlocks`. The render is streamdown's remark pipeline, which is
CommonMark-strict: counting anchors through it, a 1000-character label resolves
to 0 links even with the whole reply lexed as one document. So 999 is a real
boundary and not a bound we settled for, there is no link past it for the blocks
path to lose, and my earlier note describing a residual there was wrong.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 788dae47c8

ℹ️ 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 pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Repo tests (CPU, studio) is red here for something that is not in this branch, and it is red on main too.

Three assertions fail, all of them source-text contracts over frontend files this PR does not touch:

test asserts state on main
test_chat_response_details_ui_contract.py::test_response_model_badge_is_user_configurable_and_rendered_once_per_message className="min-w-0 flex-1" in reasoning.tsx the string is gone, 0 occurrences
test_chat_response_details_ui_contract.py::test_reasoning_keeps_streaming_height_cap_through_automatic_collapse streaming={isReasoningStreaming || retainStreamingHeight} the component now reads streaming={isStreaming || retainStreamingHeight}
test_desktop_reliability_frontend_contract.py::test_chat_sidebar_row_actions_visible_on_coarse_pointers [@media(pointer:coarse)]:pr-10 in the sidebar row block not present

Checked rather than inferred. All three pass on this branch at c2a0dd81d and all three fail on origin/main at 0054a64be, run locally in a clean worktree:

on this branch   3 passed
on origin/main   3 failed

The branch is based on 770f4a474 and changes four files, none of them reasoning.tsx or app-sidebar.tsx, so what the merge ref picks up is main's state, not this PR's. The last commits to touch reasoning.tsx are #11425, #11424, #11409 and #11395; the test was last touched long before any of them. It looks like a rename (isReasoningStreaming to isStreaming) and a couple of class changes landing without the contract tests that read those files being updated.

Not fixing it here: it is unrelated to this change, it affects every open PR equally, and which side is wrong is the UI author's call rather than something to settle inside a markdown-probe PR. Flagging it so the red on this PR is not read as this PR's.

Everything else is green, including the three cross-platform staging legs for this branch (ubuntu-latest, macos-15, windows-latest), each reporting # tests 43 # pass 43 # fail 0.

@danielhanchen
danielhanchen merged commit 949ce69 into main Sep 21, 2026
46 of 48 checks passed
@danielhanchen
danielhanchen deleted the fix/9540-reference-label-cap branch September 21, 2026 09:50
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…lothai#11386)

A pull_request run does not test the branch head. It tests refs/pull/N/merge,
a merge of the branch into the base as the base stood when the run was created.
GitHub does not rebuild that ref because the base later moved, and a re-run
replays the same merge commit, so a fix that lands on main after a run starts
stays invisible to that run until someone pushes to the branch.

That cost real time today. unslothai#11372 gave three test files encoding = "utf-8" and
merged at 14:35 UTC. Runs created at 13:39, 14:26 and 14:29 on unslothai#11375, unslothai#11357
and unslothai#11373 all went on failing tests/test_source_read_encoding.py on exactly
those three lines, and all three were first read as defects in branches that
had never touched the files.

Adds .github/actions/merge-ref-age, which asks the compare endpoint how far the
base branch has moved since this run's merge ref was built and prints a notice
if the answer is not zero. It is wired into the two studio-backend-ci.yml jobs
that run pytest, gated on failure(), so a green job never pays for it and it
stays quiet when the base has not moved.

It is advisory and cannot fail a job. A stale merge ref does not make a failure
untrue: the merge really does fail. Deciding otherwise for the reader would be
worse than the confusion it is fixing, so the script never exits non-zero and
never emits ::error::.

tests/studio/test_merge_ref_age_is_reported.py keeps both properties: every job
in that workflow running pytest carries the step under failure(), and the
action's script cannot fail the job it sits in. Each assertion was checked by
reverting it individually against a green baseline. The repo's own
test_workflow_guards_run_unfiltered caught the new guard missing from the
unfiltered job, so it is registered in workflow-trigger-lint.yml too.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…robe (unslothai#11375)

* fix(studio): widen the link reference probe to match the definition probe

A label only resolves when both ends of the pair carry it. The definition
probe was widened to Marked's 999 character cap, but the reference probe
was left at 200, so any label in 201..999 failed at the reference end and
the reply stayed on the blocks path with the reference rendered literally.

Widening the regex alone is a regression: the cap is the backtracking
budget at every start position, and a run of `[` supplies one per
character. Measured over a 500k reply, the widened regex costs 1743ms
against 385ms for the narrow one. Bound each `][` seam instead, the way
the definition side bounds each `]:`, and it costs 7.7ms.

Neither label admits a bare `]`, so a candidate is bounded on both sides:
it opens after the last unescaped `]` before the seam and closes at the
first one after it. Both cursors only advance, so the escape walks stay
linear over the reply.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix(studio): stop the reference scan rescanning the tail once its lookahead is empty

The windowed scan added with the widened reference probe has two shapes where it
gives back nothing, and one of them is quadratic.

`unescapedClose` returning -1 means no unescaped `]` remains, but -1 is always
behind the next seam, so the cache never holds and every later `][` re-walks the
whole tail while advancing nothing. This is the cost `hasLinkDefinition` caches
its lookaheads to avoid, and its comment says so. `\][` repeated is the witness,
since every closer there is escaped:

| reply | narrow probe (main) | as merged | with this |
| --- | --- | --- | --- |
| 6k | 1.8ms | 26ms | - |
| 48k | 16ms | 1742ms | 1.1ms |
| 500k | 162ms | 196047ms | 2.6ms |

196 seconds on the render path, which runs per frame while a reply streams.

The second is the one the window exists to prevent, reintroduced inside it: the
window bounds the slice, not the start positions in it, so a window packed with
`[` whose reference label is past the cap pays the full widened budget at every
one of them. 500k of that shape costs 3225ms against 349ms for the narrow probe.
The reference label a match could use is a single candidate, because the `[`
before it restarts escape parity at the seam, so it is the text between the seam
and the first unescaped `]` and nothing else. Test it once per seam. The opener
is tracked forward for the same reason `lastIndexOf` is avoided next door, and
its skip runs first so a seam with no opener pays neither test.

Equivalence to the regex over the whole string is unchanged: 788,642 inputs, no
counterexample. Exhaustive over `a [ ] \ !` to length 8, 300,000 seeded from an
alphabet carrying astral code points, lone surrogates, CRLF and long backslash
runs, and boundary shapes built at 999 and 1000 repetitions rather than 999 and
1000 characters, escaped and unescaped closers, and backslash runs straddling
the computed slice start where slice-local parity can differ from the reply's.

Cost through the render path, median of 5, against the merge base:

| reply | main | as merged | with this |
| --- | --- | --- | --- |
| 100k dense with `[` | 133.52ms | 0.01ms | 0.01ms |
| 500k of `[` then a reference | 666.71ms | 12.05ms | 19.80ms |
| 200k dense with `][` | 1.16ms | 12.03ms | 10.02ms |
| 50k prose with a reference | 1.27ms | 1.43ms | 1.37ms |
| 50k citations | 16.57ms | 16.07ms | 16.60ms |

The `][` row does not reach the merge base and this does not close it: the seam
loop itself costs about 0.1us per seam, and a 200k reply of nothing but seams
has 100,000 of them. It is linear and 10ms absolute, so it stays, but it is a
regression against the narrow probe and the description should not have said
nothing regresses.

* perf(studio): ask the cheaper link probe first when choosing the render scope

`documentProse` needs both probes to agree, and both are pure, so the conjunction
does not care which is asked first. The cost does: only the probe asked SECOND is
ever skipped, and the two are not equally expensive to run. The reference scan
carries the window and the reference-label test, the definition scan carries
neither, and a reply dense with `][` that holds no definition at all is the shape
that separates them, because the definition probe refuses it on its first
`indexOf` while the reference probe walks every seam.

Median of 15 through `markdownRenderKey` plus `parseMarkdownIntoRenderableBlocks`:

| reply | reference first | definition first |
| --- | --- | --- |
| 200k dense with `][` | 10.42ms | 1.57ms |
| 500k of `[` then a reference | 20.50ms | 0.26ms |
| 500k packed `[` past the cap | 5.17ms | 0.27ms |
| 50k citations | 14.49ms | 13.59ms |
| 50k prose with a reference | 1.35ms | 1.16ms |
| 500k of `]: ` | 9.54ms | 10.32ms |
| 500k of `[]: ` | 16.86ms | 15.43ms |

The `]: ` row is the trade, and it is the whole of it: a reply carrying a
definition and no reference now pays the definition scan instead of being
refused by the reference one. Both dense-`]:` tests already bound that at 100ms
and it lands an order of magnitude inside them.

`200k dense with ][` is the row that matters, because it was the last shape still
above the merge base after the two scan fixes: 1.16ms there, 10.42ms before this,
1.57ms now. Routing is untouched, as it has to be for a reordered conjunction:
the 1386-cell base-versus-head enumeration is unchanged at 1009 identical, 377
newly reaching the document path, 0 reaching it less often.

* docs(studio): say whose 999 the reference cap is, since it is not Marked's

The new test justified its `blocks` assertion at 1000 with "999 is Marked's cap,
so a longer label is not a reference". Marked's `def` rule is
`/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/`, checked in
the installed marked 17.0.6 under streamdown and 16.4.2 at the top level, and its
label is `[^\]]+` with no cap at all. It resolves a 1000 and a 2000 character
label, checked by parsing both rather than read off the pattern.

999 is CommonMark's cap, and the definition probe alongside says so. The reason
both probes stop there is the one that probe gives: unbounded makes every `[` an
O(n) start position. So the line is pinning a residual, and it is a residual in
the direction this file calls the expensive one, since saying `blocks` for a
reply that needed one document splits the pair and leaves the reference literal.

Nothing changes in the assertion or the behaviour. It matters because a comment
that reads as a correctness boundary is a comment nobody revisits, and the whole
reason this PR exists is that the two ends of the same pair drifted apart while
each looked settled.

* test(studio): sweep the oracle over label length, the dimension unslothai#9540 broke on

`link-definition-oracle.test.ts` exists to catch the expensive error, a reply
sent down the blocks path when its reference only resolves in one piece. It
sweeps definition contexts, container prefixes, neutral blocks and line endings,
and every one of those cases uses the label `g`. Length is the one dimension the
probes actually bound, and the only one the oracle never varied, so a bound set
too small was invisible to the file written to catch exactly that. unslothai#9540 is that
bug, and unslothai#9645 moving the bound on one end while the other stayed at 200 was
invisible here for the same reason.

The new sweep is in scope for a length only when the rendered outcome really
differs between the two paths, the same gate the sweep above uses, plus an
assertion that at least one length was in scope so it cannot quietly stop testing
anything. It encodes no cap of its own.

On the merge base it fails and names them:

  label length 201, 201, 400, 400, 998, 998, 999, 999

1, 2, 199 and 200 pass there, which is the half of the pair that already worked.
1000, 1001 and 2000 drop out of scope on both sides rather than being excluded by
hand, and that is worth stating, because it is also the answer to what sits past
the cap.

Also corrects the note I added on the 1000 assertion. Marked's `def` label really
is `[^\]]+` with no cap, but Marked only SPLITS here, through streamdown's
`parseMarkdownIntoBlocks`. The render is streamdown's remark pipeline, which is
CommonMark-strict: counting anchors through it, a 1000-character label resolves
to 0 links even with the whole reply lexed as one document. So 999 is a real
boundary and not a bound we settled for, there is no link past it for the blocks
path to lose, and my earlier note describing a residual there was wrong.

* Trim the comments this PR adds to the link probes and their tests

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit to apurv-1/unsloth that referenced this pull request Oct 5, 2026
… non-sticky

Resolve conflicts toward main: the link probe rewrites on main (unslothai#9645,
unslothai#11375) replace unslothai#10688's hunks, and the repaired-document scope does not
depend on them. A reference that remend closes early now renders as one
document, but only a source-level pair enters the sticky full-document
path, so a stream that abandons the reference returns to blocks.
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 with a label over 200 characters can be committed away, breaking the reference

1 participant