Skip to content

perf(editor): parse edits off the main thread without copying the document #4535

Done

Description

@datlechin

Problem

In the 1.9M-character file, tree-sitter applyEdits took 164 ms of main-queue time over about 420 keys (Time Profiler, typing-1900k). Below 1,000,000 units every small edit is parsed synchronously on the main thread with no bound on how long the parse takes. Above it, every key copies the whole document on the main thread for the background parse. A typed character is drawn uncoloured first and restyled after the parse lands, which is a second layout and draw per key. On an unwrapped line, that restyle typesets the whole line again.

Cause

  • shouldExecuteAsync sends an edit through execSync on the caller, the main thread, when the edit is 1,024 units or less and the document is 1,000,000 units or less (apple/Packages/TableProEditor/Sources/TableProEditorKit/TreeSitter/TreeSitterClient.swift:80-83, :172-175, :208-221).
  • calculateNewState loops parser.parse until it returns a tree. On the main-thread path Task.isCancelled is always false, so the 50 ms parserTimeout bounds nothing (apple/Packages/TableProEditor/Sources/TableProEditorKit/TreeSitter/LanguageLayer.swift:147-160). An edit that opens a quote or a comment re-lexes everything after it.
  • On the main thread, the read block makes an NSString substring, a String and a UTF-16 Data for every 4 KB chunk tree-sitter reads (apple/Packages/TableProEditor/Sources/TableProEditorKit/Extensions/TextView+/TextView+createReadBlock.swift:57-71).
  • Above 1,000,000 units, each key calls createTextSnapshot(), which copies the whole document into a ContiguousArray<UInt16> on the main thread (TreeSitterClient.swift:228, TextView+createReadBlock.swift:38-48).
  • Queued tasks poll for their turn with a 10 ms Task.sleep (apple/Packages/TableProEditor/Sources/TableProEditorKit/TreeSitter/TreeSitterExecutor.swift:104-113, TreeSitterClient.swift:109).
  • The background parse works on a copy of the state (apple/Packages/TableProEditor/Sources/TableProEditorKit/TreeSitter/TreeSitterClient+Edit.swift:20), but the result is swapped in with DispatchQueue.waitMainIfNot (TreeSitterClient+Edit.swift:60-66). The swap, and the release of the old state's trees, run on the main thread while the background task waits.
  • When the queue is busy, the highlight query's .access task only dispatches the query to the main thread and returns, so the query and its predicate reads still run on main (TreeSitterClient.swift:296-303).
  • Restyle has a fast path only for wrapped lines: TextLine.restyle returns nil unless lineFragments.count > 1 (apple/Packages/TableProEditor/Sources/TableProTextEngine/TextLine/TextLine.swift:83). restyleLayout then marks the line for a full typeset (apple/Packages/TableProEditor/Sources/TableProTextEngine/TextLayoutManager/TextLayoutManager+Invalidation.swift:41-59). A full typeset copies the whole line (TextLine.swift:64, apple/Packages/TableProEditor/Sources/TableProTextEngine/TextLine/Typesetter/Typesetter.swift:164, :239) and shapes all of it with CTTypesetterCreateWithAttributedString (Typesetter.swift:168). With wrapping off, a one-line dump of 10^5 to 10^6 characters is shaped again on every colour write.

Overlaps #4442: JV3 there covers restyling a long line without typesetting it again. The single-fragment restyle below is that same change; the parse pipeline is new.

Change

  • One background pipeline owns the parser and trees: a serial executor (an actor or a serial queue) replaces the lock and the 10 ms polling.
  • The main thread sends only the InputEdit list and an O(1) immutable snapshot. Build the snapshot from a persistent structure (swift-collections' rope, already a dependency of TableProEditorKit) or copy-on-write pages, and give tree-sitter UTF-16 chunk pointers without making a String or Data per chunk.
  • No unbounded parse on the main thread. If same-frame colour is wanted, try the parse on main with a small timeoutMicros budget and, when it does not finish, resume the same parse off main (tree-sitter resumes a timed-out parse when called again with the same tree).
  • Run highlight queries off main against a tree copy and the same snapshot; post only the resulting ranges to main. Swap the parsed state in without blocking the parse thread on main, and release old trees off main. Bound restyles with Tree.changedRanges.
  • Add a restyle path for single-fragment lines: rebuild the line's runs from the existing break instead of typesetting it again (coordinate with JV3 in perf(json): cell popover, long-line restyle and harness items left from #4427 #4442).

Measure

  • os_signpost intervals around applyEdits, createTextSnapshot and queryHighlightsForRange, tagged with the thread. After the change, no TSParser frames on the main thread in typing-1900k, against 164 ms of applyEdits today. In a document over 1,000,000 units the parse runs in a background task, so the main-queue applyEdits time in the trace is most likely the state swap and the old trees' release; the signposts settle it.
  • Hangs instrument: type ' at the top of a 900 KB script, before and after.
  • Count Core Animation commits and Typesetter.typeset calls per key in the 1.9M file, with wrapping on and off.

Part of the performance plan.

Activity

  1. added
    enhancement
    platform-macos
    on Nov 25, 2026
  2. datlechin commented on Nov 25, 2026

    @datlechin
    MemberAuthor

    #4585 ships the parse pipeline from this issue: rope snapshot, chunk reads, bounded main parse resumed off main, lock-based commit off main, continuation wakeups instead of 10 ms polling, busy-queue queries off main, signposts, and changed ranges against the edited old tree.

    Left:

    • The single-fragment restyle (rebuild an unwrapped line's runs instead of typesetting it again) is the same change as JV3 in perf(json): cell popover, long-line restyle and harness items left from #4427 #4442, so it stays there rather than landing twice.
    • SwiftTreeSitter still copies each chunk into its own Input buffer. Removing that copy needs a SwiftTreeSitter API that wraps a raw TSTree (its Tree initializer is internal).
    • The Typesetter-call and Core Animation commit counts per key were not taken: they need the app under Instruments, which this pass did not run.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementplatform-macos

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions