Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

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

Hugh Scott9cf76c17085a
diff --git a/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
index 1a83a2e3952..4e4083ba89d 100644
--- a/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
+++ b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
@@ -50,13 +50,84 @@ 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;
+
+// Odd backslash run: `[a\]b]:` keeps its escaped `]` in the label, `[a]b]:` does not.
+function isEscaped(text: string, index: number): boolean {
+ let slashes = 0;
+ for (let i = index - 1; i >= 0 && text[i] === "\\"; i -= 1) {
+ slashes += 1;
+ }
+ return slashes % 2 === 1;
+}
+// Same predicate as the regex over the whole reply (it has no anchor or lookaround), scanned from
+// the rare `]:` rather than from every `[` (unslothai/unsloth#10529). Two bounds keep each
+// terminator cheap: a match opens with `[`, and its label admits no bare `]`, so the window starts
+// after the last unescaped one. Both cursors only advance and their lookaheads are CACHED --
+// re-asking `indexOf` past -1 rescans the tail while advancing nothing, measured slower than no
+// skip at all (282ms -> 881ms), and `lastIndexOf` is unbounded backwards. Per 500k reply:
+// `]: ` 289ms -> 3.6ms, `[]: ` 338ms -> 7.1ms.
+function hasLinkDefinition(text: string): boolean {
+ let bracket = text.indexOf("[");
+ let nextBracket = bracket < 0 ? -1 : text.indexOf("[", bracket + 1);
+ let close = -1;
+ let nextClose = text.indexOf("]");
+ for (let end = text.indexOf("]:"); end >= 0; end = text.indexOf("]:", end + 1)) {
+ while (nextBracket >= 0 && nextBracket <= end) {
+ bracket = nextBracket;
+ nextBracket = text.indexOf("[", bracket + 1);
+ }
+ while (nextClose >= 0 && nextClose < end) {
+ close = nextClose;
+ nextClose = text.indexOf("]", close + 1);
+ }
+ let start = end < LINK_DEFINITION_WINDOW ? 0 : end - LINK_DEFINITION_WINDOW;
+ if (close > start && !isEscaped(text, close)) {
+ start = close + 1;
+ }
+ // `start`, not `bracket`: the class admits `[` inside a label, so the last one can fail where
+ // an earlier matches (`[a[]:` matches from 0, not 2). Skip test only.
+ 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})?`,
+ `g${LINK_DEFINITION_LINE_RE.flags}`,
+);
// The two block shapes whose body is literal code: an opening fence, and an indent that
// reaches column four -- four spaces, or a tab, which advances to the same column.
const CODE_BLOCK_RE = /^(?: {0,3}(?:`{3,}|~{3,})|(?: {4,}| {0,3}\t)[ \t]*[^ \t\r\n])/;
@@ -112,13 +183,20 @@ function blocksOf(markdown: string): readonly string[] {
// `document` when blocks would have done only costs that reply its per-code-block Copy and
// Download controls -- which is what this path did for EVERY reply containing a `]:` substring
// before. See tests/link-definition-oracle.test.ts, which pins the first case exhaustively.
+// Normalised because `\r` counts against `{1,999}` and the `\n` it replaces does
+// not, so the scope would otherwise follow the reply's line ending. NOT for
+// `blocksOf`, whose one memo slot is shared with `parseMarkdownIntoRenderableBlocks`:
+// a normalised copy misses it and costs a CRLF reply two splits per render.
function documentProse(markdown: string): string | null {
- if (!LINK_REFERENCE_RE.test(markdown) || !LINK_DEFINITION_RE.test(markdown)) {
+ const normalized = normalizeLineEndings(markdown);
+ if (!LINK_REFERENCE_RE.test(normalized) || !hasLinkDefinition(normalized)) {
return null;
}
- const prose = blocksOf(markdown)
- .filter((block) => !isCodeBlock(block))
- .join("\n");
+ const prose = normalizeLineEndings(
+ blocksOf(markdown)
+ .filter((block) => !isCodeBlock(block))
+ .join("\n"),
+ );
return LINK_DEFINITION_LINE_RE.test(prose) && LINK_REFERENCE_RE.test(prose)
? prose
: null;
@@ -133,10 +211,7 @@ export function markdownRenderKey(markdown: string): string {
if (prose === null) {
return "blocks";
}
- return `document:${prose
- .split("\n")
- .filter((line) => LINK_DEFINITION_LINE_RE.test(line))
- .join("\n")}`;
+ return `document:${(prose.match(LINK_DEFINITION_KEY_RE) ?? []).join("\n")}`;
}
export function parseMarkdownIntoRenderableBlocks(markdown: string): string[] {
@@ -231,7 +306,7 @@ const createRepairParity = (
// and shown as a literal line. Keeping every definition in the live tail makes the two lexes agree.
// Marked reads a fenced block as code, so those do not count.
function updateLinkDefinitionParity(parity: RepairParity, text: string): void {
- if (!FENCED_CODE_BLOCK_RE.test(text) && LINK_DEFINITION_RE.test(text)) {
+ if (!FENCED_CODE_BLOCK_RE.test(text) && hasLinkDefinition(text)) {
parity.linkDefinition = true;
}
}
diff --git a/studio/frontend/tests/streaming-render-schedule.test.ts b/studio/frontend/tests/streaming-render-schedule.test.ts
index 41cb07cb63d..5a77d4b6dfe 100644
--- a/studio/frontend/tests/streaming-render-schedule.test.ts
+++ b/studio/frontend/tests/streaming-render-schedule.test.ts
@@ -100,6 +100,17 @@ const MARKDOWN_CASES = [
`\`\`\`md\n[x]: https://e.test\n\`\`\`\n\n${paragraphs(12)}[x]: https://e.test\n\nq\n\n`,
// A label may contain an escaped bracket, and Marked registers it.
`[foo\\]bar]: /url\n\n${paragraphs(12)}[foo\\]bar]: /url\n\nq\n\n`,
+ // Every label to CommonMark's 999 is registered, so one past 200 must be held.
+ `[${"x".repeat(250)}]: /url\n\n${paragraphs(12)}[${"x".repeat(250)}]: /url\n\nq\n\n`,
+ `[${"x".repeat(999)}]: /url\n\n${paragraphs(12)}[${"x".repeat(999)}]: /url\n\nq\n\n`,
+ // Label whitespace is normalised: `[foo\nbar]` registers as `foo bar`.
+ `[foo\nbar]: /url\n\n${paragraphs(12)}[foo\nbar]: /url\n\nq\n\n`,
+ `[foo\n${"y".repeat(300)}]: /url\n\n${paragraphs(12)}[foo\n${"y".repeat(300)}]: /url\n\nq\n\n`,
+ // 1040 UTF-16 units, 520 code points: the bound must count the latter. Also
+ // cuts surrogate pairs in half while streaming.
+ `[${"πŸ˜€".repeat(520)}]: /url\n\n${paragraphs(12)}[${"πŸ˜€".repeat(520)}]: /url\n\nq\n\n`,
+ // Registers as `foo\ bar`, so the escape must admit a line ending; `.` cannot.
+ `[foo\\\nbar]: /url\n\n${paragraphs(12)}[foo\\\nbar]: /url\n\nq\n\n`,
// Retained-prefix contexts that nothing else reaches: a balanced single
// underscore, one first seen inside inline code, and an underscore that
// precedes the first bold marker.
@@ -306,7 +317,8 @@ test("the block split is shared per reply without leaking between replies", () =
// their calls through it, so the only thing keeping that honest is that the slot is keyed
// on the exact reply text: a miss recomputes, it never answers for the wrong reply.
const plain = "Message A.\n\n```ts\nconst a = grid[r][c];\n```\n";
- const withReference = "Message B, see [guide][g].\n\n```py\nprint('b')\n```\n\n[g]: /guide\n";
+ const withReference =
+ "Message B, see [guide][g].\n\n```py\nprint('b')\n```\n\n[g]: /guide\n";
const other = "Message C.\n\n```js\nconst c = 1;\n```\n";
for (const reply of [plain, withReference, other, withReference, plain]) {
@@ -361,6 +373,230 @@ test("link references and definitions stay in one rendered document", () => {
);
});
+// Everything Marked stores must move the key as it arrives, or the reference keeps
+// the stale link. Every line ending, because the key reads un-normalised text.
+test("a definition that spans lines still moves the render key", () => {
+ const labels = ["foo", "x".repeat(250), "foo\nbar", "foo\\\nbar"];
+
+ for (const newline of ["\n", "\r\n", "\r"]) {
+ const eol = (text: string) => text.replaceAll("\n", newline);
+ const usage = eol(`Before [reference][foo bar].\n\n${paragraphs(20)}`);
+
+ // A container marker is stripped before storing, so label, destination and
+ // title each have to be found behind one.
+ for (const label of labels) {
+ for (const [container, indent] of [
+ ["", " "],
+ ["> ", "> "],
+ ["- ", " "],
+ ] as const) {
+ for (const separator of [" ", `\n${indent}`]) {
+ const opened = `${usage}${eol(`${container}[${label}]:${separator}`)}`;
+ const destined = `${opened}https://example.com/reference`;
+ const titled = `${destined}${eol(`\n${indent}"reference"`)}`;
+ const shape = JSON.stringify(
+ eol(`${container}[${label}]:${separator}`),
+ );
+
+ assert.equal(markdownRenderScope(destined), "document", shape);
+ assert.notEqual(
+ markdownRenderKey(opened),
+ markdownRenderKey(destined),
+ `render key did not move for the destination of ${shape}`,
+ );
+ assert.notEqual(
+ markdownRenderKey(destined),
+ markdownRenderKey(titled),
+ `render key did not move for the title of ${shape}`,
+ );
+ }
+ }
+ }
+ }
+});
+
+// The other half of that contract: text the key captures that marked does NOT
+// store remounts the whole subtree once per character of it. A definition in a
+// container keeps its continuation in the same block, so these reach the key
+// suffix where prose after a plain definition does not.
+test("prose after a definition does not move the render key", () => {
+ const tails = [
+ "ordinary prose that follows on the next line",
+ // Opens like a title and never closes: marked stores none until one does.
+ '"a quoted sentence that keeps going',
+ "'a quoted sentence that keeps going",
+ "(a parenthetical that keeps going",
+ ];
+
+ for (const [container, indent] of [
+ ["", ""],
+ ["> ", "> "],
+ ["- ", " "],
+ ["1. ", " "],
+ ] as const) {
+ for (const definition of [
+ `${container}[g]: /guide`,
+ `${container}[g]: /guide "settled"`,
+ `${container}[g]:\n${indent}/guide`,
+ ]) {
+ for (const tail of tails) {
+ const settled = `See [g][g].\n\n${definition}`;
+ const key = markdownRenderKey(settled);
+ const shape = JSON.stringify(`${definition}⏎${tail}`);
+
+ // A key that moves at ANY prefix is a remount, so sweep, not endpoints.
+ for (let index = 1; index <= tail.length; index += 1) {
+ const separator = definition.includes("\n") ? " " : `\n${indent}`;
+ assert.equal(
+ markdownRenderKey(`${settled}${separator}${tail.slice(0, index)}`),
+ key,
+ `render key moved for prose after ${shape} at prefix ${index}`,
+ );
+ }
+ }
+ }
+ }
+});
+
+// marked stores the space in `[g]: <https://x.test/a b>`, so the key must follow
+// an angle destination to its `>` or it settles on the first word and freezes.
+test("an angle-bracketed destination keeps moving the render key", () => {
+ const usage = "See [guide][g].\n\n";
+ const streamed = [
+ "[g]: <https://x.test/a",
+ "[g]: <https://x.test/a ",
+ "[g]: <https://x.test/a b",
+ "[g]: <https://x.test/a b>",
+ '[g]: <https://x.test/a b> "settled"',
+ ];
+
+ let previous = markdownRenderKey(`${usage}[g]: `);
+ for (const step of streamed) {
+ const key = markdownRenderKey(usage + step);
+ assert.notEqual(key, previous, `render key did not move for ${step}`);
+ previous = key;
+ }
+
+ // `>` closes the ANGLE form only: marked keeps it in `[g]: https://x.test/a>b`.
+ let bareStep = markdownRenderKey(`${usage}[g]: `);
+ for (const step of ["https://x.test/a", "https://x.test/a>", "https://x.test/a>b"]) {
+ const key = markdownRenderKey(`${usage}[g]: ${step}`);
+ assert.notEqual(key, bareStep, `render key did not move for ${step}`);
+ bareStep = key;
+ }
+
+ // Padding after the destination does not stop Marked storing a next-line title.
+ for (const [container, indent] of [
+ ["", " "],
+ ["> ", "> "],
+ ] as const) {
+ const destined = `${usage}${container}[g]: /url `;
+ assert.notEqual(
+ markdownRenderKey(destined),
+ markdownRenderKey(`${destined}\n${indent}"title"`),
+ `render key did not move for a padded title behind ${JSON.stringify(container)}`,
+ );
+ }
+
+ // Bare still stops at whitespace, which is what keeps prose out of the key.
+ const bare = markdownRenderKey(`${usage}[g]: https://x.test/ab`);
+ assert.equal(
+ markdownRenderKey(`${usage}[g]: https://x.test/ab\nordinary prose follows`),
+ bare,
+ );
+});
+
+// The window back from each `]:` has to hold the widest label: 999 escapes each
+// followed by an astral code point. Sized in code points it cuts the opening `[`
+// off these. The padding is what forces the window to be the thing under test.
+test("the widest label is still found far into a reply", () => {
+ const padding = "ordinary prose. ".repeat(400);
+ for (const filler of ["z", "\u{1F600}", "\\z", "\\\u{1F600}"]) {
+ const reply = `See [guide][g].\n\n${padding}\n\n[${filler.repeat(999)}]: /url`;
+ assert.equal(
+ markdownRenderScope(reply),
+ "document",
+ `a 999-repetition label of ${JSON.stringify(filler)} was not found`,
+ );
+ }
+});
+
+// Every `[` used to be a start position that ran to the bound before it could
+// fail, so one long line dense with `[` cost half a second per render. A wall-clock
+// budget, not a ratio against a plain reply of the same length: marked's own block
+// split is itself far dearer over 100,000 `[` than over 100,000 `x`, so a ratio
+// would measure marked rather than this probe.
+test("a bracket-dense reply does not stall the scan", () => {
+ const reply = `See [guide][g].\n\n${"[".repeat(100_000)}\n\n[g]: /guide`;
+ for (let run = 0; run < 3; run += 1) markdownRenderScope(reply);
+ const samples = [];
+ for (let run = 0; run < 5; run += 1) {
+ const started = performance.now();
+ markdownRenderScope(reply);
+ samples.push(performance.now() - started);
+ }
+ const median = samples.sort((a, b) => a - b)[2];
+ assert.ok(median < 150, `scope took ${median.toFixed(1)}ms on a 100k bracket-dense reply`);
+});
+
+// Scope decides what is committed, so it cannot follow the reply's line ending.
+// This label is 999 normalised, 1000 raw under CRLF.
+test("the render scope does not depend on the reply's line ending", () => {
+ const label = `foo${" ".repeat(995)}`;
+ const usage = `Before [reference][foo].\n\n${paragraphs(20)}`;
+
+ const source = `${usage}[${label}\n]: https://example.com/reference`;
+ for (const newline of ["\n", "\r\n", "\r"]) {
+ assert.equal(
+ markdownRenderScope(source.replaceAll("\n", newline)),
+ "document",
+ JSON.stringify(newline),
+ );
+ }
+});
+
+test("extended definitions keep their scope and key outside code blocks", () => {
+ const labels = [
+ "x".repeat(250),
+ "x".repeat(999),
+ "foo\nbar",
+ "foo\\\nbar",
+ "πŸ˜€".repeat(520),
+ ];
+ const usage = "See [guide][g].\n\n";
+
+ for (const label of labels) {
+ for (const prefix of ["", "> ", "- ", "1. ", "- > "]) {
+ for (const newline of ["\n", "\r\n", "\r"]) {
+ const eol = (text: string) => text.replaceAll("\n", newline);
+ const definition = `${prefix}[${label}]: /guide`;
+ const reply = eol(`${usage}${definition}`);
+ assert.equal(markdownRenderScope(reply), "document", reply);
+ assert.notEqual(
+ markdownRenderKey(reply),
+ markdownRenderKey(`${reply}-changed`),
+ );
+ assert.deepEqual(parseMarkdownIntoRenderableBlocks(reply), [reply]);
+ }
+ }
+
+ const fenced = `\`\`\`md\n[${label}]: /code\n\`\`\``;
+ const indented = `[${label}]: /code`
+ .split("\n")
+ .map((line) => ` ${line}`)
+ .join("\n");
+ for (const code of [fenced, indented]) {
+ assert.equal(markdownRenderScope(`${usage}${code}`), "blocks", code);
+ const real = `${usage}[g]: /guide`;
+ assert.equal(
+ markdownRenderKey(`${real}\n\n${code}`),
+ markdownRenderKey(real),
+ code,
+ );
+ }
+ }
+});
+
test("a transient marker imbalance can recover incremental parsing", () => {
const cache = new IncrementalMarkdownCache();
const unbalanced = `Match *.py files here.\n\n${paragraphs(20)}`;
@@ -619,3 +855,45 @@ test("a fenced block larger than the budget keeps retaining", () => {
parseMarkdownIntoBlocks(remend(input)),
);
});
+
+// The window skip is sound only because a match opens with `[` and its label holds no bare `]`.
+// Two ways it could be wrong, both pinned: the LAST `[` is not the only candidate, and the
+// lookahead must not rescan once it has run out.
+test("a `]:` whose window holds no `[` is skipped without changing the answer", () => {
+ // `[a[]:` matches from 0 (label `a[`), not from the last `[` (empty label): a skip clamped to
+ // the last one reports false.
+ assert.equal(markdownRenderScope(`See [x][a[].\n\n${paragraphs(12)}[a[]: /url\n`), "document");
+ // Nothing to open a definition with, at any distance.
+ assert.equal(markdownRenderScope(`See [x][y].\n\n${"]: ".repeat(2000)}`), "blocks");
+});
+
+test("a reply dense with `]:` and no definition does not pay per occurrence", () => {
+ // Not linearity: unskipped this is linear too, with the 2999-char window as its constant. The
+ // gap is the constant's SIZE, ~80x (289ms vs 3.6ms at 500k), on a path markdownRenderKey runs
+ // every render. Absolute and loose so a 10x slower runner still separates ~36ms from ~2900ms.
+ const dense = `See [guide][g].\n\n${"]: ".repeat(166666)}`;
+ for (let i = 0; i < 3; i += 1) markdownRenderScope(dense + " ");
+ const runs: number[] = [];
+ for (let i = 0; i < 5; i += 1) {
+ const t0 = performance.now();
+ markdownRenderScope(dense + " ".repeat(i));
+ runs.push(performance.now() - t0);
+ }
+ const median = runs.sort((a, b) => a - b)[2]!;
+ assert.ok(median < 100,
+ `500k of \`]:\` cost ${median.toFixed(1)}ms; the per-occurrence window scan is back`);
+
+ // A `[` in the window is not enough: `[]: ` keeps one in every window while never opening a
+ // definition, so unbounded each occurrence still slices ~3000 chars. 338ms against 7ms.
+ const invalid = `See [guide][g].\n\n${"[]: ".repeat(125000)}`;
+ for (let i = 0; i < 3; i += 1) markdownRenderScope(invalid + " ");
+ const invalidRuns: number[] = [];
+ for (let i = 0; i < 5; i += 1) {
+ const t0 = performance.now();
+ markdownRenderScope(invalid + " ".repeat(i));
+ invalidRuns.push(performance.now() - t0);
+ }
+ const invalidMedian = invalidRuns.sort((a, b) => a - b)[2]!;
+ assert.ok(invalidMedian < 100,
+ `500k of \`[]:\` cost ${invalidMedian.toFixed(1)}ms; invalid candidates are being rescanned`);
+});