Repository navigation
Studio: stop an unterminated code fence re-repairing itself on every chunk - #9517
Conversation
…chunk A fence that has opened and not yet closed lexes into a single block, so the incremental cache can never retain a prefix and its live tail grows with the fence. Repairing that tail is worse than linear: remend walks the whole string once per '[' looking for an unterminated link, and code is dense in brackets, so appending one chunk cost the length of the fence and a reply cost the square of it. Inside the fence there is nothing for those passes to find. Repair a bounded window of the fence body behind a synthetic opener and splice the untouched middle back, once a probe shows the head holds no marker the repair would have to close. A body carrying $$ or ~~, the two markers remend counts across a fence rather than skipping, keeps the whole-tail path, as does a tail with no line boundary to cut on. Measured in WebKitGTK 2.50.4 on a 90,000 character reply whose fence never closes: stream fps_p5 7.9 -> 35.7 and p95 frame gap 127 ms -> 28 ms, with a concurrent base-vs-base null moving 7.87 -> 7.94. The many-small-fence corpus, already healthy, is unchanged.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8e61d90465
ℹ️ 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".
| // than the window leaves no line boundary to cut on, which is the only place | ||
| // the splice can start without changing what the trailing repairs read. | ||
| function repairOpenFenceTail(tail: string, bodyStart: number): string | null { | ||
| const cut = tail.indexOf("\n", tail.length - OPEN_FENCE_REPAIR_WINDOW); |
There was a problem hiding this comment.
Preserve the preceding line when splicing fence repairs
When an open backtick fence contains a whitespace-only line longer than the 4,096-character window and the current streamed tail ends with -, --, =, or ==, this cut selects the newline after that long line and omits the line from the repair input. The synthetic nonblank fence head then causes remend's setext repair to append a zero-width space, whereas repairing the whole tail does not; this breaks the promised byte-identical result and can insert a hidden character into rendered or copied code. Retain the preceding line as well or fall back when it lies outside the window.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Genuine, reproduced exactly as described, and chasing it turned up a second independent divergence in the same code. Fixed in 68797ee.
The reported case, constructed to the description: an open backtick fence with a whitespace-only line longer than the 4,096 window and a tail ending in a setext run gives whole-tail " \n-" against spliced " \n-" plus a zero-width space. 60 divergences across blank lengths 4,095 to 20,000, three whitespace fillers and all four endings. Confirmed at remend's source: ln reads i.split("\n").at(-1), one line back only, and appends U+200B when that line is non-blank. The synthetic opener is never blank, so eliding a whitespace-only line flips the branch, and it lands inside the fence body that getCodeFence hands to the copy button.
The fixture gap was real: every generated piece was a short line, so no elided line ever exceeded the window.
The second family, which this item does not name, is a backtick, dollar or tilde in the elided middle. remend does not have one notion of being inside a fence but at least three that disagree: the escape-aware walk behind isWithinCodeBlock, the emphasis counters that toggle on a triple backtick without honouring an escape, and the inline-code repair that counts a regex. An escaped fence marker flips some and not others, so the opener cannot stand in for the elided text and a stray closer is appended.
Fixed with two more refusals in the existing style, so there are now four, all falling back to the whole-tail repair. Retaining the preceding line was considered and rejected: it addresses only the setext case, leaves the marker family standing, and a window bounded by an arbitrarily long preceding line is not bounded. The marker guard tracks the FIRST marker in the body, since a marker inside the window otherwise masks an earlier one in the middle.
Ten new cases, each confirmed failing on 8e61d90 and passing after. The randomized differential is widened with over-long lines: 0 divergences over four seeds, where the un-widened fixture missed both bugs and the minimal fix alone still leaves 57.
|
Confirmed this hits the path in studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts where repairTail still calls remend on the whole live tail on every chunk while a fence is open, and the frame-by-frame parity plus the substring-cost test cover the risky part. Will get this reviewed. |
…remend Two ways the window could elide something the repair reads. A preceding line longer than the window puts the cut on the newline that ends it, leaving the window holding the final line alone. remend's setext repair reads exactly one line back, and the opener standing in for the elided text is never blank, so a whitespace-only line elided that way turned a tail ending in -, --, = or == into one carrying a zero-width space that repairing the whole tail does not add, and that the copy button would put on the clipboard. A backtick, dollar or tilde inside the elided part is a character one of remend's fence notions counts. It has at least three and they disagree: the escape-aware walk behind isWithinCodeBlock, the emphasis counters that toggle on a triple backtick without honouring an escape, and the inline-code repair that counts the runs with a regex. An escaped fence or a four-backtick run flips some and not others, so the opener cannot stand in for it and a stray closer was appended. The scan now carries the FIRST such character in the body rather than the last, since one sitting in the window would otherwise mask an earlier one sitting in the elided middle. Both reproduce on the previous commit and are covered by ten new cases. The randomized differential grew lines longer than the window, whitespace-only and not, which is the gap that let both through: it is byte-identical to the whole-tail repair on every open-fence frame of five corpora and across four seeds of the widened adversarial set.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 68797ee125
ℹ️ 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".
| const probed = head + OPEN_FENCE_PROBE; | ||
| this.openFenceHeadInert = remend(probed) === probed; |
There was a problem hiding this comment.
Preserve inline-code parity when replacing the fence head
When a reply has an unmatched inline backtick before the opener and an escaped triple-backtick sequence inside the retained repair window (for example, `\n``` + more than 4,096 body characters + \n\```\n$), this probe declares the head inert before that later sequence is considered. The later sequence changes remend's global triple-fence parity and causes whole-tail repair to append a closing backtick for the unmatched head marker, but the synthetic head has discarded that marker, so the optimized render omits the backtick and is no longer byte-identical. Include the repair window in the inertness check or preserve the head's inline-code parity.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Genuine, and your diagnosis of where it lives is right: the defect is in the probe, not the cut. Fixed in 2fd6c5f.
Reproduced with head backtick-newline-newline, opener, and a window carrying an escaped triple-backtick run: whole-tail gives a trailing backtick the splice omits. The trailing content after the escaped run matters, so the run alone reads same, and dropping the unmatched inline backtick from the head also reads same, which confirms both dimensions are required.
On the direct question of whether the probe's verdict is head-only: yes, and that is what makes it unsound. The probe is remend(head + newline q newline), and remend's fence gate counts triple backticks over the whole string, so the probe fixes that parity at whatever the head gives. An escaped run later in the body flips it, the gate fires, and the head's dangling backtick gets closed by the whole-tail path only. No cut refusal can reach that, since the probe runs first.
The class is wider than reported. With a double-dollar window the divergence runs the OTHER way, the splice appending the delimiter where the whole tail does not, because the head's lone backtick moves the inline-code toggle.
Widening the probe to consider the window does not fix it, and I tested that rather than assuming: it still leaves 76 divergences, because the repair then still uses the synthetic head and the missing backtick is what moves the toggle. What works is making the probe's verdict true, so refusal 4 now covers the retained window as well as the elided middle. Structured sweep 304 to 0.
Worth recording why the earlier sweeps missed it. The fixture already contained unmatched inline backticks and escaped runs; what it never produced was the LAYOUT, head then opener then over 4,096 marker-free characters then an escaped run in the retained window. A random shuffle of six pieces essentially never assembles that order. A structured sweep over 4,500 combinations put the shipped code at 304 divergences on code the randomized sweep called clean.
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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 probe that lets one opener stand in for the real head reads the HEAD alone, and it runs before the cut is chosen. remend decides from the whole string, so text later in the body can flip a global parity the probe assumed and revive a marker it had cleared. An escaped triple-backtick run in the RETAINED window flips the global triple-run parity, so the whole-tail repair closes an unmatched inline backtick sitting before the opener while the spliced output, whose synthetic head never had one, does not. Display math there moves the maths parity the other way and the splice appends where the whole tail does not. Neither is reachable from a refusal on the cut, which is why the body-marker refusal now covers the retained window as well as the elided middle. Widening the probe instead does not work: probing the head against the real window still leaves 76 divergences in the structured sweep, because the repair goes on to use the synthetic head, whose missing backtick is what moves the inline-code toggle in the first place. Costs nothing on the five benchmark corpora, whose fast-path frame count is 2,077 with and without the wider guard. A fence body carrying a backtick, dollar or tilde anywhere now takes the whole-tail path. Found by a structured differential that emits the layout the splice depends on, head, opener, elided filler and retained window, rather than shuffling pieces and hoping the order lands there. The random generator had the ingredients and never assembled them: it reported 0 divergences on the same code the structured sweep puts at 304.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
UI idempotency, first and as a gate
This changes how a streamed reply is repaired before it is split into blocks, which is the highest-risk place in the app for a silent rendering difference, 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.
8,442 frames, zero differences, so nothing rendered changes. Nothing differs mid-stream either, not only at the end: the shortcut is not an approximation that converges, it returns the same bytes on every frame. The block splitter is not touched at all --
parseMarkdownIntoBlocksis called on the same string it was called on before.studiobench A/B parity digest, with its null.
--tier standard --reps 4 --ab pr9517 --engine chromium, base and treatment interleaved in one session against a byte-identical seeded thread, DOM digest at the close of each scripted action. The null control (base against base) ran in the same sweep and its measured variation replaces the declared unstable set.The finding
A streamed reply collapses while a code fence is open, and the cost scales with the characters accumulated inside that fence, not with how many elements are mounted.
The cleanest evidence for the axis is a window where the mounted element count is exactly constant at 760 while 11,479 characters stream in and rAF fps falls from 58.8 to 3.9. The node count is the same integer throughout,
code_blocksis still 0 andhighlight_spansis still 0, so nothing about the DOM and nothing about syntax highlighting can explain it. The work is upstream of both.Off-browser, feeding the streaming path chunk by chunk over a 90,000 character reply whose fence never closes,
IncrementalMarkdownCache.updatecosts 29,000 ms in total and per-update cost tracks the live tail exactly:committed_blocksnever moves and essentially all of the time isremend.The mechanism
Two things compound.
Nothing can be retained.
update()computesAn open fence lexes into a single block, so the repaired tail never has more than
ROLLBACK_BLOCKSblocks,candidateCountis 0 on every chunk, and the early return leaves before theSTALLED_TAIL_CHARACTERSbudget that exists for exactly this shape. The live tail therefore grows with the fence, without bound.Repairing that tail is quadratic.
repairTailcallsremend(this.tail). remend's link pass walks the whole string once per[to decide whether a link is unterminated, and itsisWithinCodeBlockprobe scans from index 0 each time. Bracketed content is what makes it quadratic, and code is dense in brackets:Inside an unterminated fence every one of those brackets is literal and every pass declines. The walk finds nothing and still costs the length of the fence, on every streamed chunk.
This is upstream of #8935, which made tokenization incremental. Nothing here is tokenized: the fence has not been recognised yet.
The fix
Repair a bounded window of the fence body behind a synthetic opener, and splice the untouched middle back in. An incremental scanner mirrors remend's own notion of an open fence (any
```run toggles it, wherever on the line it sits, a backslash escapes the backtick after it), carried across updates so a growing tail costs the characters that arrived rather than the characters it holds.The shortcut is only taken when it can be shown to return what repairing the whole tail returns. Four refusals fall back to the whole-tail path, and the last two are the interesting half of this pull request, because they are the reason the byte-identical claim is true rather than nearly true:
-,--,=or==into one carrying a zero-width space that repairing the whole tail does not add, and that the copy button would then put on the clipboard.``,$or~anywhere in the body**, retained window included, not only in what the cut elides. remend does not have one notion of "inside a fence"; it has at least three and they disagree.isWithinCodeBlockwalks the text and honours a backslash before a backtick, the emphasis counters toggle on` without honouring it, and the inline-code repair just counts `//g`. An escaped\```or a```` run flips some and not others, so the opener cannot stand in for the elided text and a stray closer was appended.A probe also checks that remend leaves the head alone before the head is elided. That probe is the reason refusal 4 has to cover the retained window too. It reads the head alone, and it runs before the cut is chosen, while remend decides from the whole string. An escaped
\```later in the body flips the global triple-run parity, so the whole-tail repair closes an unmatched inline backtick sitting before the opener while the spliced output, whose synthetic head never had one, does not; a$$there moves the maths parity the other way and the splice appends where the whole tail does not. No refusal on the cut can reach either, because the probe is upstream of the cut. Widening the probe instead does not work: probing the head against the real window still leaves 76 divergences, since the repair then goes on to use the synthetic head, whose missing backtick is what moves the inline-code toggle in the first place. Keeping the body free of all three characters is what makes the probe's verdict a property of the whole tail rather than of the head it was handed.Appending a chunk to an open fence then costs the window, not the fence.
What this narrows
Refusal 4 has a cost worth knowing before you hit it. A fence whose body carries a backtick, dollar or tilde anywhere at all loses the fast path for the rest of that fence and falls back to repairing the whole tail, at the original quadratic cost. In practice that means JavaScript or TypeScript with template literals, and shell with
$VAR. Python, Go, Rust, JSON, C and plain prose are unaffected.All five benchmark corpora are unaffected too: their fast-path frame count is 2,077 with the guard and 2,077 without it, so none of the numbers below pay for it. That is a fact about these corpora rather than a general reassurance, and a reply that is mostly shell or mostly TypeScript will not see the improvement.
This is a deliberate trade. The alternative was reproducing three mutually inconsistent fence conventions from a third-party library inside our own code, and three separate reviews each found a case where that reproduction was wrong. A refusal that is too broad costs speed on inputs we can name; a reproduction that is subtly wrong costs correctness on inputs nobody can enumerate.
Equivalence
The spliced repair is byte-identical to repairing the whole tail on every frame that takes it, across three independent fixtures.
Both sweeps matter, and the second is why the first is no longer quoted alone. The randomized generator shuffles pieces; it had every ingredient for the third bug (unmatched inline backticks in its head set, escaped fences and four-backtick runs in its piece set) and still reported 0 divergences on code the structured sweep puts at 304, because it never assembled them into the required layout. The structured sweep emits that layout directly -- head, opener, elided filler, retained window -- across 4,500 combinations, and is what a claim of byte-identity should rest on:
Each round of review widened the fixture, and each widening found the bug the previous fixture could not see: short lines only, then no over-long lines, then no assembled layout.
tests/streaming-open-fence-repair.test.tsasserts per-frame equality for an unterminated fence, a fence that closes and reopens, CRLF, a tilde fence, a nested longer fence,$$inside the body, a marker left open before the fence, eight setext cases across two whitespace fillers, two shrunk reproducers for a marker in the elided middle, and two for a marker in the retained window. Every one of those fails on the commit before its own fix. A~~case in the retained window is deliberately absent: it does not reproduce, and a case that passes on the broken code documents nothing while reading as coverage.Before and after, with the null
Real WebKitGTK 2.50.4 (
libwebkit2gtk-4.1via PyGObject, not Playwright WebKit),run_meta.platform.engine = webkitgtkderived from the page probe (X11 UA plus thewindow.webkit.messageHandlersbridge), not from the command line. 90,000 characters, field cadence, four concurrent uncapped arms, all on the guarded build (a87fafc0) against base (f01f6a0c).baseandnullare the same build, so their gap is the floor.A fence that never closes (
ls_never_closes):The shipped large-fence corpus (
mix_few_large):Smaller, and the reason is worth stating:
make_corpus_pair.pytruncates each prose run to an exact character budget (prose(per_p, rng)[:per_p]), which removes the trailing blank line and glues the next```onto the end of a prose line. A```that is not at the start of a line is an inline code span, not a fenced block, which is why that corpus reportscode_blocks: 0. Its fence is open for only part of the stream; the rest is a tail that stays uncommittable for a different reason. The gain there is the open-fence part.Control, many small fences (
mix_many_small), healthy today and required to stay healthy:Unchanged on every field.
Complexity, measured without a clock
tests/streaming-open-fence-repair.test.tscharges everysubstringprobe its receiver's length, which prices a repair at the length of what it was given, and so reads the same on a loaded CI box as on an idle one. Doubling the fence:2.05 per doubling is a per-chunk cost independent of the fence length. The test fails on
mainwith a 17.2x multiplier.