Skip to content

invalidate following rows when tokenizer context changes - #18473

Merged
kevinushey merged 10 commits into
mainfrom
bugfix/ace-context-invalidation
Aug 10, 2026
Merged

kevinushey merged 10 commits into
mainfrom
bugfix/ace-context-invalidation

Conversation

@kevinushey

@kevinushey kevinushey commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

An edit that changes only tokenizer context data -- the nesting depth tracked for rainbow parentheses / rainbow fenced divs, the indent recorded for a YAML multiline string, chunk fence widths -- left stale syntax highlighting on every row below the edit. The Ace background tokenizer propagated invalidation to following rows only when a row's end state changed, and tokenizer contexts (an rstudio-ace extension) were invisible to that check.

In R / R Markdown / Quarto documents the bug is masked by an unrelated mechanism: modes with a code-model scope tree rebuild the scope tree after every edit, and that path (TokenIterator.tokenizeUpToRow) force-retokenizes every row from the edit point to the end of the document. Plain Markdown and YAML documents have no such rebuild and showed the stale highlighting indefinitely -- confirmed by inspecting the tokenizer caches: after inserting a fence at the top of a 160-row .md document with rainbow fenced divs enabled, 79 of 81 fence rows still held their old colors.

Changes

  • Updates the ace.js / ace-uncompressed.js builds with rstudio/rstudio-ace#13: BackgroundTokenizer.$tokenizeRow now snapshots the incoming context with structuredClone (so contexts can hold nested objects and arrays, and each row's stored context is an independent snapshot that in-place mutation by a highlight rule cannot corrupt), compares the newly-computed context against the stored one with a structural equality helper (key-order independent, never throws, depth-capped), and invalidates the following row when they differ, exactly as for a changed end state. Review hardening: non-plain objects (Date, Map, Set, RegExp, class instances) compare unequal rather than silently equal, the clone is skipped for missing and empty contexts (the common case for modes that never touch their context), and the helpers are unit-tested in the fork. The rebuilt artifact also drops a stray hand-patched comment left from the Source editor randomly becomes inoperable (dysfunctional text select, multi-line editing, & inputs appear in wrong tab)  #13605 investigation (now handled in the fork source).
  • Adds regression tests for both unmasked modes. YAML: re-indenting a multiline string's | opener changes only the recorded indent (the opener's end state is unchanged), and an off-screen content row must be re-highlighted. Plain Markdown (the symptom reported in edits can leave stale syntax highlighting below the edited line in Markdown and YAML documents #18472): an unclosed fenced div opener inserted at the top of a tall document deepens every following block, and an off-screen block's fence must take the next nesting-depth color (colors are depth-based since color fenced divs by nesting depth #18467) -- a positive assertion, where the YAML test's is an absence. Both tests pin exact token type/value pairs on both sides of the edit, assert the target row sits below the last rendered row before editing (the off-screen premise the tests' validity rests on -- rendered rows are incidentally re-tokenized by the fold gutter's getState() sweeps), and fail against the previous ace build while passing with this one.
  • Adopts the cloneContext / equalContexts helpers exported from ace/background_tokenizer in RCodeModel.$tokenizeUpToRow, whose parallel per-row cache had both halves of the same bug: a shallow Object.assign context copy (so a rule mutating a shared nested object retroactively corrupted the previous row's stored context) and an assumeGood short-circuit keyed only on the end state (so a context-only change stopped invalidation and following rows kept stale cached tokens, feeding indentation, folding, and the scope tree). Verified against the GWT testpage suite and a code-model e2e regression set.
  • Adopts the same helpers in TokenUtils.$tokenizeUpToRow (the parallel cache used by cpp_code_model.js, touched on main by fix C++ chunk indentation in R Markdown documents #18470), which had the identical shallow-copy and end-state-only-resume pair, and removes the comment there describing the limitation as shared with RCodeModel and the BackgroundTokenizer -- no longer true with this change.

The rebuilt artifact was diffed against the committed one before applying the fix to confirm a clean baseline, and again after, to confirm the artifact change is exactly the intended tokenizer change.

Merging note: after #18467 landed, the Markdown regression test was adapted to the depth-based color scheme (a closing fence at depth 0 no longer changes anything; the test now inserts an unclosed opener, which deepens -- and so recolors -- every following block). rstudio/rstudio-ace#13 should be merged into the ace fork alongside this PR so the committed artifacts and the fork source stay in sync.

Fixes #18472.

The Ace background tokenizer re-tokenizes the row following an edited
row only when the edited row's end state changes. Tokenizer contexts
(carrying e.g. rainbow paren / fenced div nesting depth, YAML
multiline-string indents, and chunk fence widths) also flow into
following rows, but context changes did not propagate invalidation,
so an edit that changed only context data left stale highlighting on
every row below. Modes with a code-model scope tree masked this by
force-retokenizing the document after every edit; plain Markdown and
YAML documents showed the stale highlighting indefinitely.

Updates the ace builds with rstudio/rstudio-ace#13, which compares
each row's newly-computed context against the stored one and
invalidates the following row when they differ. The rebuilt artifact
also drops a stray (hand-patched) comment left from the #13605
investigation.

Addresses #18472
@kevinushey kevinushey added this to the 2026.08 (Yellow Yarrow) milestone Aug 7, 2026
@posit-snyk-bot

posit-snyk-bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@github-actions

github-actions Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

7 test(s) failed

###################- 99% pass rate

Passed Failed Skipped Flaky
2049 7 369 6
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 2 0 8 0
✅ desktop-linux 507 0 90 1
✅ desktop-macos 511 0 86 2
❌ desktop-windows 513 7 82 2
✅ server-linux 494 0 95 1
✅ setup 22 0 8 0
View / download the full report

View report online -- opens in the browser, no download needed. Available for 14 days.

Download playwright-report.zip -- extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


All platforms - commit b9007b829a12580c5b072c1d7ce6c03a6a301e1b - Run #508

Updates the ace builds with the second commit of rstudio/rstudio-ace#13:
contexts are now deep-copied at the row boundary, so each row's stored
context is an independent snapshot that in-place mutation cannot
corrupt, and compared with a structural equality helper that is
key-order independent, never throws, and depth-caps recursion.
Updates the ace builds with the third commit of rstudio/rstudio-ace#13:
contexts are snapshotted with the platform deep clone, supporting nested
objects and arrays as context values.
@gtritchie

Copy link
Copy Markdown
Member

Code review findings

Actionable items from an automated multi-agent review.

No correctness defect was found in the fix itself. Invalidation chaining, the $worker loop, getState/getTokens convergence, and the interaction with $updateOnChange were all checked against the real context shapes produced by src/gwt/acesupport/acemode/*.js (max nesting depth 2, plain data, all structuredClone-safe). The deep clone also fixes a real aliasing bug the shallow Object.assign had: contexts[row-1].yaml and contexts[row].yaml were the same object, so yaml_highlight_rules.js:197 retroactively corrupted the previous row's stored context.

Important

  1. e2e/rstudio/tests/panes/editor/syntax-highlighting.test.ts:26 — 'syntax_highlight.md' is added to the afterEach cleanup list, but no test in the file creates a .md file. Dead entry. Either remove it, or land the markdown test it implies (see finding 2).

  2. Markdown / rainbow fenced divs is untested, and it is the symptom listed first in NEWS.md:19 and in edits can leave stale syntax highlighting below the edited line in Markdown and YAML documents #18472. The only new test covers context.yaml. context.fences (markdown_highlight_rules.js:213-217) fails differently — it is a monotonic counter, so inserting a ::: pair above an existing block shifts every following block's color while leaving end states identical, which is exactly the invalidation this PR restores. It also yields a positive assertion (fenced_div_N → fenced_div_N+1) rather than an absence. The existing Function after an empty div breaks source code blocks in Quarto document #14652 test at lines 53-91 is a template, but it uses .Rmd; a new test needs plain .md for the same reason the YAML test avoids a code-model mode.

  3. .../ace/ace-uncompressed.js:43152-43153 — exports.cloneContext / exports.equalContexts have no consumer anywhere in src/ or e2e/ (grepped .js/.ts/.java). Speculative API on a vendored file is the worst place to carry a local delta, since every future Ace update must re-apply it. Fix: keep the helpers module-private, or add the test that justifies the exports.

  4. src/gwt/acesupport/acemode/r_code_model.js:2174 — RCodeModel.$tokenizeUpToRow keeps its own parallel $contexts cache with both halves of the bug this PR fixes: Object.assign({}, this.$contexts[row - 1]) is still a shallow copy (so sweave_highlight_rules.js:78 and utils.js:149 mutate the previous row's stored context), and the assumeGood short-circuit at line 2189 still keys only on lineTokens.state === this.$endStates[row], ignoring context. Pre-existing, and it feeds indentation/folding/scope tree rather than highlighting, so it is not the edits can leave stale syntax highlighting below the edited line in Markdown and YAML documents #18472 symptom — but leaving the two implementations divergent is how this class of bug survives. Worth at least a follow-up issue.

Suggestions

  1. .../ace/ace-uncompressed.js:42986-43011 — equalContextValues reports any two Date, Map, Set, or RegExp values as equal, because Object.keys() on them returns []. Verified: equalContexts({d: new Date(1)}, {d: new Date(2)}) returns true. structuredClone preserves all four types, so a future rule storing one would get a silently missed invalidation — the exact bug this PR fixes, reintroduced. No current rule does this. Fix: bail out to false for non-plain objects, or document the plain-data-only contract.

  2. .../ace/ace-uncompressed.js:42984 — cloneContext runs once per row per tokenization, and for most modes the context is permanently {}. Measured: structuredClone({}) at 542 ns/op vs Object.assign({}, undefined) at 11 ns/op — ~50x on the dominant case, since cloneContext(undefined) still round-trips through structuredClone({}). An early return context ? structuredClone(context) : {}; removes the cost from that case for free.

  3. .../ace/ace-uncompressed.js:42984 — structuredClone throws DataCloneError on functions and symbols where Object.assign copied them silently, and it drops prototypes on class instances. An uncaught throw here kills highlighting entirely. No current rule stores such a value; worth a comment documenting that context must be structured-cloneable plain data.

  4. syntax-highlighting.test.ts:360-361 — the final assertion inspects only tokens[0] and only asserts what the row is not. Once the multiline string terminates, the leading indent of value34 may tokenize as its own text token while the remainder is still stale, so the assertion passes on a partial fix. The sibling tests in this file (lines 70-85, 118-124, 320-328) all pin exact {type, value} pairs; do the same here over tokens.map(t => t.type).

  5. syntax-highlighting.test.ts:339-341,351 — the test's validity rests on row 35 being below the last rendered row, so the fold gutter's incidental getState() sweeps don't retokenize it. That holds today only because the fixtures pin the window (desktop.fixture.ts:294 at 1024x645, server.fixture.ts:421 at 960x540). If either size changes, row 35 comes on-screen and the test passes against unfixed code, silently — the one way this test can go vacuous. Fix: raise the document to ~300 rows and target row 250, or assert lastVisibleRow < 35 before the edit.

  6. syntax-highlighting.test.ts:348 — new AceEditor(page, 'value39'). The page object's own docs (ace_editor.page.ts:26-38) prefer the empty marker for the active editor; the marker path is a DOM walk that can land on stale editors left after a tab close (test(e2e): expose active ace editor via automation bridge #17775 / test(e2e): use activeEditor bridge in autocomplete actions #17784). Only one tab is open here, so new AceEditor(page, '') is strictly safer.

  7. syntax-highlighting.test.ts:360 uses timeout: 15000, but the pre-assert at line 352 — which has to load and tokenize the file — uses the default. If anything is slow it is the first poll, not the second.

Worth confirming before merge

Given how much of the test's validity rests on the off-screen assumption (finding 9), confirm it is red on main and green on this branch in both Desktop and Server projects. If it passes on main in either mode, finding 9 is why.

@gtritchie gtritchie left a comment

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.

Feedback posted

Updates the ace builds with the latest rstudio/rstudio-ace#13: contexts
holding a Date, Map, Set, RegExp, or class instance now compare unequal
(Object.keys sees no content on them, so the structural comparison would
have reported any two as equal -- a silently missed invalidation), and
cloneContext skips the structuredClone for missing and empty contexts,
the common case for modes that never touch their context.
Review feedback: the rainbow fenced div symptom from #18472 was untested
(and the cleanup list already claimed a syntax_highlight.md file), the
yaml test's final assertion checked only the first token's type, its
off-screen premise was implicit, and the target-editor lookup went
through the marker DOM walk.

The new markdown test inserts a closing fence at the top of a tall plain
.md document and asserts an off-screen block's tokens cycle to the next
rainbow color -- a positive assertion, where the yaml test's is an
absence. Both context tests now pin exact token type/value pairs, assert
the target row sits below the last rendered row before editing (the
guard the tests' validity rests on), resolve the active editor directly,
and give the initial tokenization poll the same 15s budget as the
post-edit one. Both fail against the previous ace build and pass with
this one.

Addresses #18472.
Review feedback, folded in from the proposed follow-up:
RCodeModel.$tokenizeUpToRow kept both halves of the bug fixed for ace's
BackgroundTokenizer -- the shallow Object.assign copy let highlight
rules mutate the previous row's stored context through shared nested
objects, and the assumeGood short-circuit keyed only on the end state,
so a context-only change stopped invalidation and following rows kept
stale cached tokens (feeding indentation, folding, and the scope tree).
Use the cloneContext / equalContexts helpers exported from
ace/background_tokenizer, so both incremental caches share the same
snapshot and comparison semantics.

Addresses #18472.
@kevinushey

Copy link
Copy Markdown
Collaborator Author

Applied in 578d969, e5fa288, and c688184; the ace artifact was rebuilt from rstudio/rstudio-ace#13, which gained the source changes plus unit tests.

  • (5) equalContexts now treats non-plain objects (Date, Map, Set, RegExp, class instances) as unequal -- fail-safe: a spurious re-tokenization instead of a missed invalidation. Unit-tested in the fork.
  • (6) cloneContext returns a fresh {} without structuredClone for missing and empty contexts -- the dominant case is a permanently-empty (truthy) {}, so the nullish early-out alone wouldn't have helped it.
  • (7) The plain-data contract is documented in the fork source; the dryice build strips comments, so it can't live in the artifact.
  • (1, 2) Added the plain-.md rainbow fenced div test: a closing fence inserted at the top advances the color counter, so an off-screen block must cycle fenced_div_6 -> fenced_div_0 (positive assertion, wrap-around case). The syntax_highlight.md cleanup entry is now live. Note this encodes the current monotonic counter; if color fenced divs by nesting depth #18467 (depth-based colors) lands first, the edit needs to become an unclosed opener.
  • (8) Both context tests pin exact {type, value} pairs on both sides of the edit.
  • (9) Went with an explicit guard rather than a taller document: both tests assert editor.getLastVisibleRow() is above the target row before editing, so a viewport change fails loudly instead of passing vacuously.
  • (10, 11) Active-editor lookup and the 15s budget on the initial poll.
  • (4) Folded into this PR rather than a follow-up (c688184): RCodeModel.$tokenizeUpToRow now uses the cloneContext / equalContexts helpers exported from ace/background_tokenizer, so its cache gets the same deep-copy snapshots and its assumeGood short-circuit also keys on context equality. Verified against the GWT testpage suite (608/608: the autoindent/highlight harnesses drive this path) and a code-model e2e regression set (syntax-highlighting, code-folding, rename-in-scope, sweave, reformat: 23/23).
  • (3) The exports aren't speculative: the fork source documents them as shared semantics for RStudio's own incremental tokenization caches -- which is now literal, since (4) consumes them -- and the fork's unit tests exercise them as well.

Red/green re-confirmed on desktop with the final tests: against main's ace build both context tests fail with exactly the predicted stale tokens (the yaml row keeps its string token, the fence stays fenced_div_6); 15/15 pass with this branch. Server mode isn't runnable from this worktree (test:server-dev needs a configured build/), but the finding-9 guard rules out the vacuous pass there structurally (the server fixture's 960x540 window renders fewer rows than desktop's 1024x645), and CI runs this file in the server project.

kevinushey and others added 4 commits August 7, 2026 14:02
…validation

# Conflicts:
#	e2e/rstudio/tests/panes/editor/syntax-highlighting.test.ts
#	src/gwt/acesupport/acemode/r_code_model.js
TokenUtils.$tokenizeUpToRow (factored out on main in #18470) had the
same two defects this branch fixed in RCodeModel: a shallow context
copy, and an assumeGood resume keyed only on the end state. Adopt
cloneContext / equalContexts there too, and drop the now-stale comment
describing the limitation as shared with RCodeModel and the
BackgroundTokenizer.
@kevinushey
kevinushey merged commit 801df9f into main Aug 10, 2026
1 of 2 checks passed
@kevinushey
kevinushey deleted the bugfix/ace-context-invalidation branch August 10, 2026 20:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

edits can leave stale syntax highlighting below the edited line in Markdown and YAML documents

3 participants