From 6bd04ec03cff0db2b56d10885b27d7d24ebe1a82 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:18:12 -0800 Subject: [PATCH 1/9] Lay out every view on the shared thread pool Each layout engine had a serial queue with no target. GCD gives such a queue a new thread when it has work, so a screen that replaces 20 documents at once held 20 layout threads. The engine queue now targets the global queue at the same QoS. Each engine stays serial, so the order of work for a view does not change. The engines share the pool that GCD keeps at about one thread for each core. The target is the global queue itself: through a concurrent queue of the package, a sync call from the main thread waits until the busy pool is free. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKit/Layout/LayoutEngine.swift | 5 +++- Sources/TranscriptKit/WorkQueue.swift | 27 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 Sources/TranscriptKit/WorkQueue.swift diff --git a/Sources/TranscriptKit/Layout/LayoutEngine.swift b/Sources/TranscriptKit/Layout/LayoutEngine.swift index 4cf780d..465babc 100644 --- a/Sources/TranscriptKit/Layout/LayoutEngine.swift +++ b/Sources/TranscriptKit/Layout/LayoutEngine.swift @@ -14,6 +14,9 @@ import QuartzCore /// The main thread lays out synchronously only when it cannot wait: the /// first layout, and a change of width or style. It does so through /// `queue.sync`, so the engine's state is only ever touched on its queue. +/// When the queue is idle, the main thread does that work itself and does +/// not wait for a thread. The queue shares its threads with the queues of +/// all other views and streams (see `WorkQueue`). /// /// While text is being appended, the engine also draws the end of the /// document into a surface (see `TailRenderer`), which travels with the @@ -76,7 +79,7 @@ final class LayoutEngine: @unchecked Sendable { } } - let queue = DispatchQueue(label: "TranscriptKit.layout", qos: .userInitiated) + let queue = WorkQueue.serial(label: "TranscriptKit.layout") /// Pictures for the documents' images, if the view was given a loader. let images = TranscriptImageStore() diff --git a/Sources/TranscriptKit/WorkQueue.swift b/Sources/TranscriptKit/WorkQueue.swift new file mode 100644 index 0000000..5acbbbb --- /dev/null +++ b/Sources/TranscriptKit/WorkQueue.swift @@ -0,0 +1,27 @@ +import Foundation + +/// The queues that parse and lay out text in the background. +/// +/// Each stream and each view has its own serial queue, so its work runs in +/// order. A serial queue without a target gets a new thread when it has +/// work, however many other queues are busy, so a screen that replaces many +/// documents at once can hold one thread for each. These queues target the +/// global queue instead, and share the pool that GCD keeps at about one +/// thread for each processor core. One view's long layout uses one thread +/// of the pool; the other views go on with the rest. +/// +/// The target is the global queue itself, not a concurrent queue of our +/// own: when the main thread calls `sync` on a queue with work waiting for a +/// thread of a busy pool, GCD gives that work a thread at once only when the +/// queue targets the global queue directly. Through a queue of our own, the +/// main thread waits until the pool is free. +/// +/// Work on these queues must not wait for work on another of them, as +/// `sync` does: a thread that waits does no work, and GCD then starts more +/// threads. +enum WorkQueue { + /// A serial queue for one stream or view, on the shared pool. + static func serial(label: String) -> DispatchQueue { + DispatchQueue(label: label, qos: .userInitiated, target: .global(qos: .userInitiated)) + } +} From 9881c5f28395019f1ab7cf9023484405c9e51989 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:18:12 -0800 Subject: [PATCH 2/9] Parse every stream on the shared thread pool The stream queue now targets the global queue, as the layout queues do. A screen with many streams does not hold a parse thread for each stream. TranscriptStream.flush() still calls sync on the stream queue from the main thread, and it does not wait for a busy pool. Co-Authored-By: Claude Opus 5.5 --- Sources/TranscriptKit/Stream/TranscriptStream.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/TranscriptKit/Stream/TranscriptStream.swift b/Sources/TranscriptKit/Stream/TranscriptStream.swift index 4124486..60033de 100644 --- a/Sources/TranscriptKit/Stream/TranscriptStream.swift +++ b/Sources/TranscriptKit/Stream/TranscriptStream.swift @@ -194,7 +194,7 @@ final class UnplacedHeightSignal { /// The parser and the attached sinks. `parser` is only touched on `queue`. final class StreamWorker: @unchecked Sendable { - let queue = DispatchQueue(label: "TranscriptKit.TranscriptStream", qos: .userInitiated) + let queue = WorkQueue.serial(label: "TranscriptKit.TranscriptStream") private var parser: MarkdownStreamParser private let lock = NSLock() From 6ea0ab0d9a3b7b8b6714b5c2f33b13ace771977d Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:18:12 -0800 Subject: [PATCH 3/9] Test the thread count of many layouts and parses at once The tests start the work of many engines and streams at the same moment. They count the work items that run at once and the threads that run them. They also check that a sync call from a thread outside the pool does not wait for the busy pool: relayout, measure, and the sync call that flush makes. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKitTests/SharedQueueTests.swift | 221 ++++++++++++++++++ 1 file changed, 221 insertions(+) create mode 100644 Tests/TranscriptKitTests/SharedQueueTests.swift diff --git a/Tests/TranscriptKitTests/SharedQueueTests.swift b/Tests/TranscriptKitTests/SharedQueueTests.swift new file mode 100644 index 0000000..520ba57 --- /dev/null +++ b/Tests/TranscriptKitTests/SharedQueueTests.swift @@ -0,0 +1,221 @@ +import Foundation +import Testing +@testable import TranscriptKit + +/// Counts the work items that run at the same time, and the threads they run on. +private final class Meter: @unchecked Sendable { + private let lock = NSLock() + private var running = 0 + private var maximum = 0 + private var seen: Set = [] + + var peak: Int { lock.withLock { maximum } } + var threads: Int { lock.withLock { seen.count } } + + func enter() { + lock.withLock { + running += 1 + maximum = max(maximum, running) + } + mark() + } + + func leave() { + lock.withLock { running -= 1 } + } + + func mark() { + var id: UInt64 = 0 + pthread_threadid_np(nil, &id) + _ = lock.withLock { seen.insert(id) } + } +} + +/// The threads of this process. Other tests that run at the same time add theirs. +private func processThreadCount() -> Int { + var threads: thread_act_array_t? + var count: mach_msg_type_number_t = 0 + guard task_threads(mach_task_self_, &threads, &count) == KERN_SUCCESS, let threads else { return 0 } + for index in 0...stride)) + return Int(count) +} + +private struct Measurement: CustomStringConvertible { + var queues: Int + /// Nil when the work does not mark where it starts and ends. + var peak: Int? + var threads: Int + var processThreadsBefore: Int + var processThreadsPeak: Int + + var description: String { + "\(queues) queues on \(cores) cores: " + (peak.map { "at most \($0) at once, " } ?? "") + + "on \(threads) threads; " + + "process threads \(processThreadsBefore) before, \(processThreadsPeak) at most" + } +} + +/// Suspends the queues, lets `enqueue` add work to each, and starts them all +/// at the same moment. `enqueue` gets the queue's index, and a closure to +/// call when its work is done. +private func measure(_ queues: [DispatchQueue], meter: Meter = Meter(), + enqueue: (Int, @escaping @Sendable () -> Void) -> Void) -> Measurement { + let group = DispatchGroup() + let before = processThreadCount() + for queue in queues { queue.suspend() } + for index in queues.indices { + group.enter() + enqueue(index) { group.leave() } + } + for queue in queues { queue.resume() } + var peakThreads = before + while group.wait(timeout: .now() + .milliseconds(2)) == .timedOut { + peakThreads = max(peakThreads, processThreadCount()) + } + return Measurement(queues: queues.count, peak: meter.peak > 0 ? meter.peak : nil, threads: meter.threads, + processThreadsBefore: before, processThreadsPeak: peakThreads) +} + +private func markdown(paragraphs: Int) -> String { + (0.. [LayoutEngine] { + let engines = (0.. TimeInterval { + let start = Date() + _ = DocumentLayout(document: longDocument, width: 200) + return Date().timeIntervalSince(start) +} + +@Suite(.serialized) +struct SharedQueueTests { + init() { + // Core Text loads its fonts the first time, and threads that wait for + // that make GCD add threads. + _ = timeOneLongLayout() + } + + /// The engines lay out through their own code path. The output handler + /// runs on the thread that made each layout. + @Test(arguments: [20, manyQueues]) + func enginesThatLayOutAtOnceShareThePool(_ count: Int) { + let engines = engines(count) + let meter = Meter() + let result = measure(engines.map(\.queue), meter: meter) { index, done in + engines[index].setOutputHandler { + meter.mark() + done() + } + engines[index].submit(.init(document: longDocument, source: 1, sequence: 1)) + } + print("Layout engines: \(result)") + for engine in engines { #expect(engine.backgroundLayoutCount == 1) } + } + + @Test func layoutsOnManyEngineQueuesRunAboutOnePerCore() throws { + let engines = engines(manyQueues) + let meter = Meter() + let result = measure(engines.map(\.queue), meter: meter) { index, done in + engines[index].queue.async { + meter.enter() + _ = DocumentLayout(document: longDocument, width: 200) + meter.leave() + done() + } + } + print("Layouts on engine queues: \(result)") + #expect(try #require(result.peak) <= bound) + } + + @Test func manyStreamsParseAboutOnePerCore() throws { + let workers = (0.. 0) + #expect(height > 0) + #expect(relayout < oneLongLayout) + #expect(measure < oneLongLayout) + for engine in busy { _ = engine.backgroundLayoutCount } + } + + /// `TranscriptStream.flush()` calls `sync` on the stream's queue, which + /// has a parse waiting for a thread while every thread of the pool is busy. + @Test func aFlushDoesNotWaitForTheBusyPool() { + let busy = engines(manyQueues) + let oneLongLayout = timeOneLongLayout() + let worker = StreamWorker(parser: MarkdownStreamParser()) + for engine in busy { engine.submit(.init(document: longDocument, source: 1, sequence: 1)) } + Thread.sleep(forTimeInterval: 0.02) + + worker.queue.async { _ = worker.apply("Some **text", finish: false) } + let start = Date() + let latest = worker.queue.sync { + _ = worker.apply("** here.", finish: true) + return worker.latest + } + let elapsed = Date().timeIntervalSince(start) + print("While \(busy.count) engines lay out: flush \(elapsed * 1000) ms; one long layout alone \(oneLongLayout * 1000) ms") + #expect(latest.isFinished) + #expect(latest.document.block(at: 0).text == "Some text here.") + #expect(elapsed < oneLongLayout) + for engine in busy { _ = engine.backgroundLayoutCount } + } +} From e9c5c594af32355796f130268c8af84e691317e5 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:18:12 -0800 Subject: [PATCH 4/9] Document the shared thread pool in the README Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 15e4433..1ebc117 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,9 @@ text streaming in at hundreds of characters a second doesn't make scrolling stut markup is held back for a character or two, so what is on screen almost never changes style or shrinks. - **Off the main thread.** Each frame's chunks are parsed on a background queue and laid out on another. Only the blocks that changed are laid out again, and the line being written is drawn on the layout queue into a surface. - The main thread installs the result and redraws what changed. + The main thread installs the result and redraws what changed. All streams and views share the system's pool of + threads, with about one thread for each processor core, so a screen that shows many texts at once does not start a + thread for each of them. - **One selectable document.** The whole text is one view with the system's selection handles, loupe and edit menu, and a selection can run from one block to the next: across headings, paragraphs, lists and code blocks. - **Markdown:** From e50a7f6811e96b5e237e1aa469f87f7ac1f979d8 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:42:08 -0800 Subject: [PATCH 5/9] Make the thread pool tests stable One burst of layouts can go above the bound: when a thread of the pool waits inside Core Text, GCD adds threads. The bound tests now take the run with the fewest items at once out of five runs. The sync tests call relayout, measure and the sync call of flush from a thread outside the pool at the QoS of the main thread. They compare the wait with the time that the busy engines take to finish. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKitTests/SharedQueueTests.swift | 150 +++++++++++------- 1 file changed, 93 insertions(+), 57 deletions(-) diff --git a/Tests/TranscriptKitTests/SharedQueueTests.swift b/Tests/TranscriptKitTests/SharedQueueTests.swift index 520ba57..d133023 100644 --- a/Tests/TranscriptKitTests/SharedQueueTests.swift +++ b/Tests/TranscriptKitTests/SharedQueueTests.swift @@ -90,25 +90,57 @@ private let longDocument = MarkdownStreamParser.document(from: longMarkdown, idP private var cores: Int { ProcessInfo.processInfo.activeProcessorCount } /// More queues than this run at once only if the queues get a thread each. -/// GCD adds a few threads to the pool when a thread waits, as Core Text -/// sometimes does. +/// GCD adds threads to the pool when a thread waits, as Core Text sometimes +/// does, so a single burst can go above it. private var bound: Int { cores + max(4, cores / 2) } /// Enough queues to make the bound show on any machine. private var manyQueues: Int { max(20, 3 * cores) } -/// Engines with a width and a long document each, as on a screen that -/// replaces its documents at once. +/// Engines with a width, as on a screen that shows many texts. private func engines(_ count: Int) -> [LayoutEngine] { let engines = (0.. TimeInterval { +/// Runs `measurement` a few times, and returns the run with the fewest items +/// at once. One run can go above the bound, but not every run. +private func fewestAtOnce(_ measurement: () -> Measurement) throws -> Measurement { + let runs = (0..<5).map { _ in measurement() } + let fewest = try #require(runs.min { ($0.peak ?? 0) < ($1.peak ?? 0) }) + print("Runs: \(runs.map { $0.peak ?? 0 }) at once; fewest: \(fewest)") + return fewest +} + +/// Gives every engine a long document to lay out in the background. Returns +/// a closure that waits until all of them are done, and returns how long they took. +private func startLongLayouts(on engines: [LayoutEngine]) -> () -> TimeInterval { + let group = DispatchGroup() + for engine in engines { + group.enter() + engine.setOutputHandler { group.leave() } + } let start = Date() - _ = DocumentLayout(document: longDocument, width: 200) - return Date().timeIntervalSince(start) + for engine in engines { engine.submit(.init(document: longDocument, source: 1, sequence: 1)) } + return { + group.wait() + return Date().timeIntervalSince(start) + } +} + +/// Runs `body` on a thread outside the pool, at the QoS of the main thread. +private func onInteractiveThread(_ body: @escaping @Sendable () -> T) -> T { + nonisolated(unsafe) var value: T? + let done = DispatchSemaphore(value: 0) + let thread = Thread { + value = body() + done.signal() + } + thread.qualityOfService = .userInteractive + thread.start() + done.wait() + return value! } @Suite(.serialized) @@ -116,13 +148,13 @@ struct SharedQueueTests { init() { // Core Text loads its fonts the first time, and threads that wait for // that make GCD add threads. - _ = timeOneLongLayout() + _ = DocumentLayout(document: longDocument, width: 200) } - /// The engines lay out through their own code path. The output handler - /// runs on the thread that made each layout. + /// A measurement: the engines lay out through their own code path, and + /// the output handler runs on the thread that made each layout. @Test(arguments: [20, manyQueues]) - func enginesThatLayOutAtOnceShareThePool(_ count: Int) { + func measureThreadsWhileEnginesLayOutAtOnce(_ count: Int) { let engines = engines(count) let meter = Meter() let result = measure(engines.map(\.queue), meter: meter) { index, done in @@ -138,33 +170,36 @@ struct SharedQueueTests { @Test func layoutsOnManyEngineQueuesRunAboutOnePerCore() throws { let engines = engines(manyQueues) - let meter = Meter() - let result = measure(engines.map(\.queue), meter: meter) { index, done in - engines[index].queue.async { - meter.enter() - _ = DocumentLayout(document: longDocument, width: 200) - meter.leave() - done() + let result = try fewestAtOnce { + let meter = Meter() + return measure(engines.map(\.queue), meter: meter) { index, done in + engines[index].queue.async { + meter.enter() + _ = DocumentLayout(document: longDocument, width: 200) + meter.leave() + done() + } } } - print("Layouts on engine queues: \(result)") #expect(try #require(result.peak) <= bound) } @Test func manyStreamsParseAboutOnePerCore() throws { - let workers = (0.. 0) + let (relayout, measure, height) = onInteractiveThread { + engine.submit(.init(document: MarkdownStreamParser.document(from: "Short text."), source: 1, sequence: 1)) + var start = Date() + let layout = engine.relayout(width: 180, style: TranscriptStyle()) + let relayout = Date().timeIntervalSince(start) + engine.submit(.init(document: MarkdownStreamParser.document(from: "Short text, longer."), source: 1, sequence: 2)) + start = Date() + _ = engine.measure(width: 150, style: TranscriptStyle()) + return (relayout, Date().timeIntervalSince(start), layout?.layout.height ?? 0) + } + let busyTime = waitForBusy() + print("While \(busy.count) engines lay out for \(busyTime * 1000) ms: relayout \(relayout * 1000) ms, " + + "measure \(measure * 1000) ms") #expect(height > 0) - #expect(relayout < oneLongLayout) - #expect(measure < oneLongLayout) - for engine in busy { _ = engine.backgroundLayoutCount } + #expect(relayout < busyTime / 4) + #expect(measure < busyTime / 4) } /// `TranscriptStream.flush()` calls `sync` on the stream's queue, which /// has a parse waiting for a thread while every thread of the pool is busy. @Test func aFlushDoesNotWaitForTheBusyPool() { let busy = engines(manyQueues) - let oneLongLayout = timeOneLongLayout() let worker = StreamWorker(parser: MarkdownStreamParser()) - for engine in busy { engine.submit(.init(document: longDocument, source: 1, sequence: 1)) } + let waitForBusy = startLongLayouts(on: busy) Thread.sleep(forTimeInterval: 0.02) - worker.queue.async { _ = worker.apply("Some **text", finish: false) } - let start = Date() - let latest = worker.queue.sync { - _ = worker.apply("** here.", finish: true) - return worker.latest + let (latest, elapsed) = onInteractiveThread { + worker.queue.async { _ = worker.apply("Some **text", finish: false) } + let start = Date() + let latest = worker.queue.sync { + _ = worker.apply("** here.", finish: true) + return worker.latest + } + return (latest, Date().timeIntervalSince(start)) } - let elapsed = Date().timeIntervalSince(start) - print("While \(busy.count) engines lay out: flush \(elapsed * 1000) ms; one long layout alone \(oneLongLayout * 1000) ms") + let busyTime = waitForBusy() + print("While \(busy.count) engines lay out for \(busyTime * 1000) ms: flush \(elapsed * 1000) ms") #expect(latest.isFinished) #expect(latest.document.block(at: 0).text == "Some text here.") - #expect(elapsed < oneLongLayout) - for engine in busy { _ = engine.backgroundLayoutCount } + #expect(elapsed < busyTime / 4) } } From 0f089141f5149022ceee63fa8bc424c5864013f3 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:19:19 -0800 Subject: [PATCH 6/9] Let short work go ahead of long layouts on the shared pool When more queues have work than the pool has threads, the queues wait in turn. A burst of long layouts then held back the parse of streamed text and the short layouts of other views for 300 to 700 ms. Short work now runs at the QoS of the main thread with .enforceQoS, so GCD gives it a thread at once. Short work is a parse of a short text, a short document, or a little text added to the end of the last layout. Long layouts stay at the lower QoS. The work of one view still runs in order. StreamWorker now has parse and applyNow, so that the tests call the code that TranscriptStream uses. The thread measurement test runs only with TRANSCRIPTKIT_TIMING, and the bound tests use shorter documents. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +- .../TranscriptKit/Layout/LayoutEngine.swift | 48 ++++++-- .../Stream/TranscriptStream.swift | 30 +++-- Sources/TranscriptKit/WorkQueue.swift | 32 ++++- .../TranscriptKitTests/SharedQueueTests.swift | 110 ++++++++++++++---- 5 files changed, 179 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index 1ebc117..3a0f38a 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,8 @@ text streaming in at hundreds of characters a second doesn't make scrolling stut blocks that changed are laid out again, and the line being written is drawn on the layout queue into a surface. The main thread installs the result and redraws what changed. All streams and views share the system's pool of threads, with about one thread for each processor core, so a screen that shows many texts at once does not start a - thread for each of them. + thread for each of them. Short work, such as the parse and layout of streamed text, goes ahead of the long layouts + of other views. - **One selectable document.** The whole text is one view with the system's selection handles, loupe and edit menu, and a selection can run from one block to the next: across headings, paragraphs, lists and code blocks. - **Markdown:** diff --git a/Sources/TranscriptKit/Layout/LayoutEngine.swift b/Sources/TranscriptKit/Layout/LayoutEngine.swift index 465babc..5e922e1 100644 --- a/Sources/TranscriptKit/Layout/LayoutEngine.swift +++ b/Sources/TranscriptKit/Layout/LayoutEngine.swift @@ -16,7 +16,9 @@ import QuartzCore /// `queue.sync`, so the engine's state is only ever touched on its queue. /// When the queue is idle, the main thread does that work itself and does /// not wait for a thread. The queue shares its threads with the queues of -/// all other views and streams (see `WorkQueue`). +/// all other views and streams (see `WorkQueue`). A drain of short work, +/// such as text added to the end, goes ahead of the long layouts of other +/// views. /// /// While text is being appended, the engine also draws the end of the /// document into a surface (see `TailRenderer`), which travels with the @@ -87,6 +89,11 @@ final class LayoutEngine: @unchecked Sendable { private let lock = NSLock() private var pending: Request? private var drainScheduled = false + /// The scheduled drain goes ahead of the long work of other views. + private var drainIsUrgent = false + /// The document of the newest layout, or of the one the queue makes + /// next. A document that only adds a little to it is short work. + private var laidOut = TranscriptDocument() /// Layouts are made at most this often: a document that arrives sooner /// waits, and is replaced by any newer one that arrives meanwhile. More /// than one layout per display frame would never be seen. @@ -213,6 +220,7 @@ final class LayoutEngine: @unchecked Sendable { pending = nil mailbox = nil onOutput = nil + laidOut = TranscriptDocument() } queue.async { self.base = nil @@ -231,7 +239,8 @@ final class LayoutEngine: @unchecked Sendable { @discardableResult func submit(_ request: Request) -> Bool { var accepted = true - let delay: CFTimeInterval? = lock.withLock { + let urgent = Self.isShortWork(request.document, after: lock.withLock { laidOut }) + let schedule: (delay: CFTimeInterval, urgent: Bool)? = lock.withLock { guard !isShutDown else { accepted = false; return nil } guard request.source >= currentSource else { return nil } if request.source > currentSource { @@ -241,20 +250,34 @@ final class LayoutEngine: @unchecked Sendable { guard request.sequence > lastSequence else { return nil } lastSequence = request.sequence pending = request - if drainScheduled { return nil } + // A drain that is not urgent can wait behind the work of other + // views, so short work schedules an urgent one of its own. The + // drain that runs first takes the request. + if drainScheduled, drainIsUrgent || !urgent { return nil } drainScheduled = true - return max(lastDrain + frameInterval - CACurrentMediaTime(), 0) + drainIsUrgent = urgent + return (max(lastDrain + frameInterval - CACurrentMediaTime(), 0), urgent) } - if let delay { - if delay > 0 { - queue.asyncAfter(deadline: .now() + delay) { self.drain() } - } else { - queue.async { self.drain() } - } + if let schedule { + WorkQueue.async(queue, urgent: schedule.urgent, after: schedule.delay) { self.drain() } } return accepted } + /// Whether laying out `document` takes about a millisecond or less: its + /// text is short, or it adds only a little text to the end of `laidOut`, + /// whose layout it reuses. An urgent drain keeps its QoS when a longer + /// document replaces the waiting one. + private static func isShortWork(_ document: TranscriptDocument, after laidOut: TranscriptDocument) -> Bool { + let length = document.utf16Count + if length <= WorkQueue.shortLength { return true } + // Documents that share no storage, as when the app parses each + // version itself, would compare every block. + guard laidOut.count > 0, length - laidOut.utf16Count <= WorkQueue.shortLength, + laidOut.count - document.knownSharedPrefix(with: laidOut) <= 2 else { return false } + return document.extends(laidOut) + } + private func takePending() -> Request? { lock.withLock { () -> Request? in defer { pending = nil } @@ -276,9 +299,11 @@ final class LayoutEngine: @unchecked Sendable { private func drain() { let next: Request? = lock.withLock { drainScheduled = false + drainIsUrgent = false guard let request = pending else { return nil } pending = nil lastDrain = CACurrentMediaTime() + if width > 0 { laidOut = request.document } return request } guard let request = next else { return } @@ -401,7 +426,7 @@ final class LayoutEngine: @unchecked Sendable { /// update that adds no text, for when updates have stopped. The tail /// stays in use. Any thread; the result comes like any other. func settleFinishedFades() { - queue.async { [self] in + WorkQueue.async(queue, urgent: true) { [self] in guard let layout = base, width > 0, layout.width == width else { return } let (fading, band) = updateFades(layout: layout, appendedTo: layout, tagsStarted: false) guard let band else { return } @@ -516,6 +541,7 @@ final class LayoutEngine: @unchecked Sendable { } lock.withLock { mailbox = nil + laidOut = latestDocument hiding = TagHiding(fadingFrom: kept) if kept == nil { fades.removeAll() } } diff --git a/Sources/TranscriptKit/Stream/TranscriptStream.swift b/Sources/TranscriptKit/Stream/TranscriptStream.swift index 60033de..975c635 100644 --- a/Sources/TranscriptKit/Stream/TranscriptStream.swift +++ b/Sources/TranscriptKit/Stream/TranscriptStream.swift @@ -86,13 +86,7 @@ public final class TranscriptStream { let finish = finishPending pending = "" finishPending = false - let worker = worker - // Waits for a job already running: the queue is serial. - let latest = worker.queue.sync { - _ = worker.apply(text, finish: finish) - return worker.latest - } - receive(latest) + receive(worker.applyNow(text, finish: finish)) } private func receive(_ update: StreamUpdate) { @@ -126,9 +120,7 @@ public final class TranscriptStream { pending = "" finishPending = false jobInFlight = true - let worker = worker - worker.queue.async { [weak self] in - let update = worker.apply(text, finish: finish) + worker.parse(text, finish: finish) { [weak self] update in DispatchQueue.main.async { MainActor.assumeIsolated { guard let self else { return } @@ -211,6 +203,24 @@ final class StreamWorker: @unchecked Sendable { lock.withLock { latestUpdate } } + /// Parses `text` on `queue`, then calls `done` there with the new + /// version, if any. A short text goes ahead of the long work of other + /// streams and views. + func parse(_ text: String, finish: Bool, then done: @escaping @Sendable (StreamUpdate?) -> Void) { + WorkQueue.async(queue, urgent: text.utf16.count <= WorkQueue.shortLength) { + done(self.apply(text, finish: finish)) + } + } + + /// Parses `text` now and returns the latest version. Waits for a parse + /// already on `queue`, as the queue is serial, but not for other queues. + func applyNow(_ text: String, finish: Bool) -> StreamUpdate { + queue.sync { + _ = apply(text, finish: finish) + return latest + } + } + /// Parses `text` and passes the new version to every sink. Runs on `queue`. func apply(_ text: String, finish: Bool) -> StreamUpdate? { dispatchPrecondition(condition: .onQueue(queue)) diff --git a/Sources/TranscriptKit/WorkQueue.swift b/Sources/TranscriptKit/WorkQueue.swift index 5acbbbb..10fbad0 100644 --- a/Sources/TranscriptKit/WorkQueue.swift +++ b/Sources/TranscriptKit/WorkQueue.swift @@ -8,20 +8,48 @@ import Foundation /// documents at once can hold one thread for each. These queues target the /// global queue instead, and share the pool that GCD keeps at about one /// thread for each processor core. One view's long layout uses one thread -/// of the pool; the other views go on with the rest. +/// of the pool. +/// +/// When more queues have work than the pool has threads, the queues wait in +/// turn, oldest first. Short work that a person waits to see, such as the +/// parse and layout of streamed text, does not wait in that line: `async` +/// with `urgent` gives it the QoS of the main thread with `.enforceQoS`, and +/// GCD gives work at that QoS a thread at once. Without `.enforceQoS`, the +/// QoS of the queue wins and the work waits. Long work stays at the lower +/// QoS. The work of one queue still runs in order: an urgent item raises +/// the QoS of the work queued before it on the same queue. /// /// The target is the global queue itself, not a concurrent queue of our /// own: when the main thread calls `sync` on a queue with work waiting for a /// thread of a busy pool, GCD gives that work a thread at once only when the /// queue targets the global queue directly. Through a queue of our own, the -/// main thread waits until the pool is free. +/// main thread and urgent work wait until the pool is free. A `sync` call +/// does not wait for the work of other queues, but it still waits for the +/// work that is already on its own queue. /// /// Work on these queues must not wait for work on another of them, as /// `sync` does: a thread that waits does no work, and GCD then starts more /// threads. enum WorkQueue { + /// Text up to this length, in UTF-16 units, takes about a millisecond + /// or less to parse or lay out. + static let shortLength = 2_000 + /// A serial queue for one stream or view, on the shared pool. static func serial(label: String) -> DispatchQueue { DispatchQueue(label: label, qos: .userInitiated, target: .global(qos: .userInitiated)) } + + /// Runs `work` on `queue` after `delay` seconds. Urgent work goes ahead + /// of the long work of other queues. + static func async(_ queue: DispatchQueue, urgent: Bool, after delay: TimeInterval = 0, + execute work: @escaping @Sendable () -> Void) { + let qos: DispatchQoS = urgent ? .userInteractive : .unspecified + let flags: DispatchWorkItemFlags = urgent ? .enforceQoS : [] + if delay > 0 { + queue.asyncAfter(deadline: .now() + delay, qos: qos, flags: flags, execute: work) + } else { + queue.async(qos: qos, flags: flags, execute: work) + } + } } diff --git a/Tests/TranscriptKitTests/SharedQueueTests.swift b/Tests/TranscriptKitTests/SharedQueueTests.swift index d133023..f601d26 100644 --- a/Tests/TranscriptKitTests/SharedQueueTests.swift +++ b/Tests/TranscriptKitTests/SharedQueueTests.swift @@ -86,6 +86,10 @@ private func markdown(paragraphs: Int) -> String { private let longMarkdown = markdown(paragraphs: 800) private let longDocument = MarkdownStreamParser.document(from: longMarkdown, idPrefix: "long") +/// Long enough that the work of many queues overlaps, for the bound tests. +private let mediumMarkdown = markdown(paragraphs: 300) +private let mediumDocument = MarkdownStreamParser.document(from: mediumMarkdown, idPrefix: "medium") +private let shortDocument = MarkdownStreamParser.document(from: "Short text.", idPrefix: "short") private var cores: Int { ProcessInfo.processInfo.activeProcessorCount } @@ -104,12 +108,12 @@ private func engines(_ count: Int) -> [LayoutEngine] { return engines } -/// Runs `measurement` a few times, and returns the run with the fewest items -/// at once. One run can go above the bound, but not every run. -private func fewestAtOnce(_ measurement: () -> Measurement) throws -> Measurement { +/// Runs `measurement` a few times, and returns the run with the lowest +/// `value`. One run can go above the bound, but not every run. +private func fewest(_ value: (Measurement) -> Int, _ measurement: () -> Measurement) throws -> Measurement { let runs = (0..<5).map { _ in measurement() } - let fewest = try #require(runs.min { ($0.peak ?? 0) < ($1.peak ?? 0) }) - print("Runs: \(runs.map { $0.peak ?? 0 }) at once; fewest: \(fewest)") + let fewest = try #require(runs.min { value($0) < value($1) }) + print("Runs: \(runs.map(value)); fewest: \(fewest)") return fewest } @@ -149,11 +153,12 @@ struct SharedQueueTests { // Core Text loads its fonts the first time, and threads that wait for // that make GCD add threads. _ = DocumentLayout(document: longDocument, width: 200) + _ = DocumentLayout(document: mediumDocument, width: 200) } /// A measurement: the engines lay out through their own code path, and /// the output handler runs on the thread that made each layout. - @Test(arguments: [20, manyQueues]) + @Test(.enabled(if: ProcessInfo.processInfo.environment["TRANSCRIPTKIT_TIMING"] != nil), arguments: [20, manyQueues]) func measureThreadsWhileEnginesLayOutAtOnce(_ count: Int) { let engines = engines(count) let meter = Meter() @@ -170,12 +175,12 @@ struct SharedQueueTests { @Test func layoutsOnManyEngineQueuesRunAboutOnePerCore() throws { let engines = engines(manyQueues) - let result = try fewestAtOnce { + let result = try fewest({ $0.peak ?? 0 }) { let meter = Meter() return measure(engines.map(\.queue), meter: meter) { index, done in engines[index].queue.async { meter.enter() - _ = DocumentLayout(document: longDocument, width: 200) + _ = DocumentLayout(document: mediumDocument, width: 200) meter.leave() done() } @@ -185,14 +190,14 @@ struct SharedQueueTests { } @Test func manyStreamsParseAboutOnePerCore() throws { - let result = try fewestAtOnce { + let result = try fewest({ $0.peak ?? 0 }) { let workers = (0.. Void = { name, start in + lock.withLock { waits[name] = Date().timeIntervalSince(start) } + done.leave() + } + let waitForBusy = startLongLayouts(on: busy) + Thread.sleep(forTimeInterval: 0.02) + + for _ in 0..<3 { done.enter() } + let start = Date() + worker.parse("Some **text** here.", finish: true) { _ in record("parse", start) } + short.setOutputHandler { record("short layout", start) } + short.submit(.init(document: shortDocument, source: 1, sequence: 1)) + growing.setOutputHandler { record("append layout", start) } + growing.submit(.init(document: grown, source: 1, sequence: 2)) + done.wait() + let busyTime = waitForBusy() + + let longest = try #require(waits.values.max()) + print("While \(busy.count) engines lay out for \(busyTime * 1000) ms: " + + waits.sorted { $0.key < $1.key }.map { "\($0.key) \($0.value * 1000) ms" }.joined(separator: ", ")) + #expect(waits.count == 3) + #expect(worker.latest.isFinished) + #expect(longest < busyTime / 10) + } + /// The main thread needs a layout now, as when the view gets a new width, - /// from an engine that has a short layout waiting for a thread while - /// every thread of the pool is busy. + /// from an engine that has work waiting for a thread while every thread + /// of the pool is busy. The work is not urgent, so only the `sync` call + /// can get it a thread at once. @Test func aSynchronousLayoutDoesNotWaitForTheBusyPool() throws { let busy = engines(manyQueues) let engine = LayoutEngine() + engine.submit(.init(document: shortDocument, source: 1, sequence: 1)) _ = engine.relayout(width: 200, style: TranscriptStyle()) let waitForBusy = startLongLayouts(on: busy) Thread.sleep(forTimeInterval: 0.02) let (relayout, measure, height) = onInteractiveThread { - engine.submit(.init(document: MarkdownStreamParser.document(from: "Short text."), source: 1, sequence: 1)) + engine.queue.async {} var start = Date() let layout = engine.relayout(width: 180, style: TranscriptStyle()) let relayout = Date().timeIntervalSince(start) - engine.submit(.init(document: MarkdownStreamParser.document(from: "Short text, longer."), source: 1, sequence: 2)) + engine.queue.async {} start = Date() _ = engine.measure(width: 150, style: TranscriptStyle()) return (relayout, Date().timeIntervalSince(start), layout?.layout.height ?? 0) @@ -231,8 +304,8 @@ struct SharedQueueTests { #expect(measure < busyTime / 4) } - /// `TranscriptStream.flush()` calls `sync` on the stream's queue, which - /// has a parse waiting for a thread while every thread of the pool is busy. + /// `TranscriptStream.flush()` waits for the stream's queue, which has a + /// parse waiting for a thread while every thread of the pool is busy. @Test func aFlushDoesNotWaitForTheBusyPool() { let busy = engines(manyQueues) let worker = StreamWorker(parser: MarkdownStreamParser()) @@ -242,10 +315,7 @@ struct SharedQueueTests { let (latest, elapsed) = onInteractiveThread { worker.queue.async { _ = worker.apply("Some **text", finish: false) } let start = Date() - let latest = worker.queue.sync { - _ = worker.apply("** here.", finish: true) - return worker.latest - } + let latest = worker.applyNow("** here.", finish: true) return (latest, Date().timeIntervalSince(start)) } let busyTime = waitForBusy() From 347fb55810ae4e787e4e0702cf4ae5a1ad8ec6a1 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:19:48 -0800 Subject: [PATCH 7/9] Add a benchmark mode that replaces many texts at once With -mode many, the benchmark app shows a stream and 20 texts. In each round, all texts get a new long document in the same main-thread turn, and the stream gets a short chunk. The app prints one MANY_RESULT line for each round: the peak thread count of the process, the time until the stream parses its chunk, the time until every text installs its layout, and the longest main-thread frame. Co-Authored-By: Claude Opus 5.5 --- Benchmark/TranscriptBench/BenchApp.swift | 11 ++ Benchmark/TranscriptBench/ManyTexts.swift | 159 ++++++++++++++++++++++ 2 files changed, 170 insertions(+) create mode 100644 Benchmark/TranscriptBench/ManyTexts.swift diff --git a/Benchmark/TranscriptBench/BenchApp.swift b/Benchmark/TranscriptBench/BenchApp.swift index 64e7adb..2731a13 100644 --- a/Benchmark/TranscriptBench/BenchApp.swift +++ b/Benchmark/TranscriptBench/BenchApp.swift @@ -15,6 +15,7 @@ import SwiftUI /// -hold 1 stay open after the run instead of exiting /// -noTail 1 TranscriptKit draws the growing end on the main thread, as before /// -mode scroll scroll through the history instead of streaming +/// -mode many replace the documents of many texts at once (see `ManyTextsModel`) /// -scrollSeconds how long to scroll (default 10) /// -scrollSpeed scrolling speed (default 3000) /// -corpus rich stream `Corpus.richSection` text instead of the default @@ -326,6 +327,16 @@ private extension WebRenderer { } struct BenchRoot: View { + var body: some View { + if UserDefaults.standard.string(forKey: "mode") == "many" { + ManyTextsRenderer() + } else { + BenchRendererRoot() + } + } +} + +struct BenchRendererRoot: View { @State private var model = BenchModel() var body: some View { diff --git a/Benchmark/TranscriptBench/ManyTexts.swift b/Benchmark/TranscriptBench/ManyTexts.swift new file mode 100644 index 0000000..6cb6173 --- /dev/null +++ b/Benchmark/TranscriptBench/ManyTexts.swift @@ -0,0 +1,159 @@ +import SwiftUI +@_spi(Diagnostics) import TranscriptKit + +/// `-mode many`: a page of many texts that all get a new long document in the +/// same main-thread turn, while a stream at the top of the page gets a short +/// chunk. Each round prints one `MANY_RESULT {json}` line, then the app exits. +/// +/// Launch arguments: +/// -views texts on the page (default 20) +/// -chars length of each new document (default 6000) +/// -rounds rounds, each with new documents (default 5) +@MainActor +@Observable +final class ManyTextsModel { + private(set) var documents: [TranscriptDocument] + @ObservationIgnored let stream = TranscriptStream(markdown: "The stream at the top of the page.") + @ObservationIgnored private let views: Int + @ObservationIgnored private let characters: Int + @ObservationIgnored private let rounds: Int + + init() { + let defaults = UserDefaults.standard + views = defaults.object(forKey: "views") != nil ? max(defaults.integer(forKey: "views"), 1) : 20 + characters = defaults.object(forKey: "chars") != nil ? defaults.integer(forKey: "chars") : 6000 + rounds = defaults.object(forKey: "rounds") != nil ? max(defaults.integer(forKey: "rounds"), 1) : 5 + documents = (0..= views + 1 { allInstalledMs = elapsed } + } + try? await Task.sleep(for: .milliseconds(500)) + let frames = monitor.stop() + let threadsPeak = sampler.stop() + + let result = ManyResult( + round: round, views: views, characters: characters, cores: ProcessInfo.processInfo.activeProcessorCount, + threadsBefore: threadsBefore, threadsPeak: threadsPeak, streamParseMs: parseMs, allInstalledMs: allInstalledMs, + installs: TranscriptDiagnostics.current.installs, worstFrameMs: frames.worstFrameMs, + droppedFrames: frames.droppedFrames, osVersion: UIDevice.current.systemVersion + ) + let json = String(data: try! JSONEncoder().encode(result), encoding: .utf8)! + print("MANY_RESULT \(json)") + fflush(stdout) + } +} + +struct ManyResult: Codable { + var round: Int + var views: Int + var characters: Int + var cores: Int + /// Threads of the process before the round, and the most during it. + var threadsBefore: Int + var threadsPeak: Int + /// From the new documents to the stream's parse of the short chunk on + /// the main thread. It includes the wait for the next display frame. + var streamParseMs: Double? + /// From the new documents until every text has installed a layout. + var allInstalledMs: Double? + var installs: Int + /// The longest main-thread frame of the round. + var worstFrameMs: Double + var droppedFrames: Int + var osVersion: String +} + +/// Samples the thread count of the process every 2 ms, on a thread of its +/// own, and keeps the highest. +final class ThreadSampler: @unchecked Sendable { + private let lock = NSLock() + private var peak = 0 + private var running = true + + func start() { + let thread = Thread { [self] in + while lock.withLock({ running }) { + let count = Self.count() + lock.withLock { peak = max(peak, count) } + usleep(2000) + } + } + thread.qualityOfService = .userInteractive + thread.start() + } + + func stop() -> Int { + lock.withLock { + running = false + return peak + } + } + + static func count() -> Int { + var threads: thread_act_array_t? + var count: mach_msg_type_number_t = 0 + guard task_threads(mach_task_self_, &threads, &count) == KERN_SUCCESS, let threads else { return 0 } + for index in 0...stride)) + return Int(count) + } +} + +private extension Duration { + var milliseconds: Double { + Double(components.seconds) * 1000 + Double(components.attoseconds) / 1e15 + } +} + +struct ManyTextsRenderer: View { + @State private var model = ManyTextsModel() + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 12) { + TranscriptText(stream: model.stream) + ForEach(model.documents.indices, id: \.self) { index in + TranscriptText(model.documents[index]) + } + } + .padding(16) + } + .task { await model.run() } + } +} From 46ecb3720f6f784c7735c8750f0b0cd4350afb92 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:29:20 -0800 Subject: [PATCH 8/9] Keep appends to lists urgent, and test the delayed drain A stream can leave two blocks outside the storage that its versions share, as at the end of a list. The check that an append is short now allows up to 8 such blocks, so that such appends stay urgent. The short work test now also covers an append that comes within a frame of the last layout. Its drain is scheduled with asyncAfter, and it keeps the higher QoS. The stream bound test uses the long text again, because the shorter text does not fail with no target. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKit/Layout/LayoutEngine.swift | 5 ++-- .../TranscriptKitTests/SharedQueueTests.swift | 29 ++++++++++++++----- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/Sources/TranscriptKit/Layout/LayoutEngine.swift b/Sources/TranscriptKit/Layout/LayoutEngine.swift index 5e922e1..c56316c 100644 --- a/Sources/TranscriptKit/Layout/LayoutEngine.swift +++ b/Sources/TranscriptKit/Layout/LayoutEngine.swift @@ -272,9 +272,10 @@ final class LayoutEngine: @unchecked Sendable { let length = document.utf16Count if length <= WorkQueue.shortLength { return true } // Documents that share no storage, as when the app parses each - // version itself, would compare every block. + // version itself, would compare every block. A stream shares all + // but its last block or two. guard laidOut.count > 0, length - laidOut.utf16Count <= WorkQueue.shortLength, - laidOut.count - document.knownSharedPrefix(with: laidOut) <= 2 else { return false } + laidOut.count - document.knownSharedPrefix(with: laidOut) <= 8 else { return false } return document.extends(laidOut) } diff --git a/Tests/TranscriptKitTests/SharedQueueTests.swift b/Tests/TranscriptKitTests/SharedQueueTests.swift index f601d26..88b524a 100644 --- a/Tests/TranscriptKitTests/SharedQueueTests.swift +++ b/Tests/TranscriptKitTests/SharedQueueTests.swift @@ -86,7 +86,7 @@ private func markdown(paragraphs: Int) -> String { private let longMarkdown = markdown(paragraphs: 800) private let longDocument = MarkdownStreamParser.document(from: longMarkdown, idPrefix: "long") -/// Long enough that the work of many queues overlaps, for the bound tests. +/// Long enough that the layouts of many queues overlap, for the bound test. private let mediumMarkdown = markdown(paragraphs: 300) private let mediumDocument = MarkdownStreamParser.document(from: mediumMarkdown, idPrefix: "medium") private let shortDocument = MarkdownStreamParser.document(from: "Short text.", idPrefix: "short") @@ -197,7 +197,7 @@ struct SharedQueueTests { let worker = workers[index] worker.queue.async { meter.enter() - _ = worker.apply(mediumMarkdown, finish: true) + _ = worker.apply(longMarkdown, finish: true) meter.leave() done() } @@ -232,19 +232,27 @@ struct SharedQueueTests { /// While every thread of the pool is busy with long layouts, short work /// that a person waits to see starts at once: the parse of a streamed /// chunk, a short document on another view, and text added to the end of - /// a long document on a third view. + /// a long document on a third view. On a fourth view, the append comes + /// within a frame of the last layout, so it waits for the frame first. @Test func shortWorkDoesNotWaitForTheBusyPool() throws { let busy = engines(manyQueues) let worker = StreamWorker(parser: MarkdownStreamParser()) let short = LayoutEngine() _ = short.relayout(width: 200, style: TranscriptStyle()) var parser = MarkdownStreamParser() - parser.append(longMarkdown) + parser.append(longMarkdown + "\n\n- One item\n- Two items") let growing = LayoutEngine() growing.submit(.init(document: parser.document, source: 1, sequence: 1)) _ = growing.relayout(width: 200, style: TranscriptStyle()) - parser.append("\n\nMore text at the end.") + parser.append("\n- Three items") let grown = parser.document + parser.append("\n\nMore text at the end.") + let grownMore = parser.document + let delayed = LayoutEngine() + delayed.setFramesPerSecond(30) + delayed.submit(.init(document: grown, source: 1, sequence: 1)) + _ = delayed.relayout(width: 200, style: TranscriptStyle()) + delayed.setOutputHandler { _ = delayed.takeOutput() } let lock = NSLock() nonisolated(unsafe) var waits: [String: TimeInterval] = [:] @@ -255,21 +263,26 @@ struct SharedQueueTests { } let waitForBusy = startLongLayouts(on: busy) Thread.sleep(forTimeInterval: 0.02) + delayed.submit(.init(document: grown, source: 2, sequence: 1)) + delayed.drainNow() - for _ in 0..<3 { done.enter() } + for _ in 0..<4 { done.enter() } let start = Date() worker.parse("Some **text** here.", finish: true) { _ in record("parse", start) } short.setOutputHandler { record("short layout", start) } short.submit(.init(document: shortDocument, source: 1, sequence: 1)) growing.setOutputHandler { record("append layout", start) } growing.submit(.init(document: grown, source: 1, sequence: 2)) + delayed.setOutputHandler { record("append within a frame", start) } + delayed.submit(.init(document: grownMore, source: 2, sequence: 2)) done.wait() let busyTime = waitForBusy() - let longest = try #require(waits.values.max()) + // The append within a frame waits for the frame of 1/30 s first. + let longest = try #require(waits.map { $0.key == "append within a frame" ? $0.value - 1.0 / 30 : $0.value }.max()) print("While \(busy.count) engines lay out for \(busyTime * 1000) ms: " + waits.sorted { $0.key < $1.key }.map { "\($0.key) \($0.value * 1000) ms" }.joined(separator: ", ")) - #expect(waits.count == 3) + #expect(waits.count == 4) #expect(worker.latest.isFinished) #expect(longest < busyTime / 10) } From eff2b5231bbde72c5110e16eec7205191c87a53f Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:31:25 -0800 Subject: [PATCH 9/9] Limit long layouts to one for each core, also when threads wait The shared pool did not limit the threads in the first burst after an app launched. On a phone with 6 cores, 20 views that got a long document at once used 12 to 23 busy threads in that burst, about one for each view. GCD starts a thread when a thread of the pool waits, for example while Core Text loads a font the first time. So each queue with waiting work could get a thread again. Long layout drains now go through WorkQueue.asyncLong. At most one long drain for each core runs at a time. The other drains wait outside their queues, oldest first, and do not ask GCD for a thread. A drain that waits keeps its place in the limit, so GCD has no work to start more threads for. No thread waits for the limit. Short drains, the drain that ends fades, and the sync calls do not go through the limit. A drain that waits there takes the newest request when it runs. When a sync call or a short drain took the request first, the drain finds nothing and ends. Each scheduled drain now has an ID, so that an older drain that runs late does not end the schedule of a newer one. Stream parses do not go through the limit, because a later flush must not parse its text before an earlier parse. On a Mac with 14 cores, in a cold test process without the font warm up, 20 engines used 20 threads in 5 of 5 runs before this change, and 14 threads in 9 of 10 runs (15 in 1) after it. With 42 queues of work that waits 50 ms, 42 ran at once before, and 14 after. Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +- .../TranscriptKit/Layout/LayoutEngine.swift | 28 +++++-- Sources/TranscriptKit/WorkQueue.swift | 74 +++++++++++++++++++ .../TranscriptKitTests/SharedQueueTests.swift | 64 +++++++++++++--- 4 files changed, 153 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 3a0f38a..3c7f2ea 100644 --- a/README.md +++ b/README.md @@ -13,9 +13,10 @@ text streaming in at hundreds of characters a second doesn't make scrolling stut - **Off the main thread.** Each frame's chunks are parsed on a background queue and laid out on another. Only the blocks that changed are laid out again, and the line being written is drawn on the layout queue into a surface. The main thread installs the result and redraws what changed. All streams and views share the system's pool of - threads, with about one thread for each processor core, so a screen that shows many texts at once does not start a - thread for each of them. Short work, such as the parse and layout of streamed text, goes ahead of the long layouts - of other views. + threads, with about one thread for each processor core. At most one long layout for each core runs at a time, also + when a layout waits, for example while a font loads the first time. So a screen that shows many texts at once does + not start a thread for each of them. Short work, such as the parse and layout of streamed text, goes ahead of the + long layouts of other views. - **One selectable document.** The whole text is one view with the system's selection handles, loupe and edit menu, and a selection can run from one block to the next: across headings, paragraphs, lists and code blocks. - **Markdown:** diff --git a/Sources/TranscriptKit/Layout/LayoutEngine.swift b/Sources/TranscriptKit/Layout/LayoutEngine.swift index c56316c..a7a30af 100644 --- a/Sources/TranscriptKit/Layout/LayoutEngine.swift +++ b/Sources/TranscriptKit/Layout/LayoutEngine.swift @@ -18,7 +18,8 @@ import QuartzCore /// not wait for a thread. The queue shares its threads with the queues of /// all other views and streams (see `WorkQueue`). A drain of short work, /// such as text added to the end, goes ahead of the long layouts of other -/// views. +/// views. A long drain waits for its turn among the long layouts of all +/// views; a `sync` call does not wait for that turn. /// /// While text is being appended, the engine also draws the end of the /// document into a surface (see `TailRenderer`), which travels with the @@ -91,6 +92,9 @@ final class LayoutEngine: @unchecked Sendable { private var drainScheduled = false /// The scheduled drain goes ahead of the long work of other views. private var drainIsUrgent = false + /// Identifies the scheduled drain. An older drain that runs later, as a + /// long drain can, leaves the schedule alone. + private var drainID = 0 /// The document of the newest layout, or of the one the queue makes /// next. A document that only adds a little to it is short work. private var laidOut = TranscriptDocument() @@ -240,7 +244,7 @@ final class LayoutEngine: @unchecked Sendable { func submit(_ request: Request) -> Bool { var accepted = true let urgent = Self.isShortWork(request.document, after: lock.withLock { laidOut }) - let schedule: (delay: CFTimeInterval, urgent: Bool)? = lock.withLock { + let schedule: (delay: CFTimeInterval, urgent: Bool, id: Int)? = lock.withLock { guard !isShutDown else { accepted = false; return nil } guard request.source >= currentSource else { return nil } if request.source > currentSource { @@ -256,10 +260,16 @@ final class LayoutEngine: @unchecked Sendable { if drainScheduled, drainIsUrgent || !urgent { return nil } drainScheduled = true drainIsUrgent = urgent - return (max(lastDrain + frameInterval - CACurrentMediaTime(), 0), urgent) + drainID += 1 + return (max(lastDrain + frameInterval - CACurrentMediaTime(), 0), urgent, drainID) } if let schedule { - WorkQueue.async(queue, urgent: schedule.urgent, after: schedule.delay) { self.drain() } + let id = schedule.id + if schedule.urgent { + WorkQueue.async(queue, urgent: true, after: schedule.delay) { self.drain(id) } + } else { + WorkQueue.asyncLong(queue, after: schedule.delay) { self.drain(id) } + } } return accepted } @@ -297,10 +307,14 @@ final class LayoutEngine: @unchecked Sendable { /// Lays out the newest waiting document. One that arrives while this /// works schedules its own drain, a frame after this one started. - private func drain() { + /// + /// - Parameter id: the drain's `drainID`, or nil to end the schedule. + private func drain(_ id: Int? = nil) { let next: Request? = lock.withLock { - drainScheduled = false - drainIsUrgent = false + if id == nil || id == drainID { + drainScheduled = false + drainIsUrgent = false + } guard let request = pending else { return nil } pending = nil lastDrain = CACurrentMediaTime() diff --git a/Sources/TranscriptKit/WorkQueue.swift b/Sources/TranscriptKit/WorkQueue.swift index 10fbad0..7825c5f 100644 --- a/Sources/TranscriptKit/WorkQueue.swift +++ b/Sources/TranscriptKit/WorkQueue.swift @@ -27,6 +27,14 @@ import Foundation /// does not wait for the work of other queues, but it still waits for the /// work that is already on its own queue. /// +/// GCD starts more threads when a thread of the pool waits, for example +/// while Core Text loads a font the first time. So the pool alone does not +/// limit the threads: in the first burst after launch, each queue can get a +/// thread again. `asyncLong` sets a hard limit for long layouts: at most one +/// for each core runs at a time. The other long work waits outside its queue +/// and does not ask GCD for a thread, so GCD has nothing to start threads +/// for. A long layout that waits keeps its place in the limit. +/// /// Work on these queues must not wait for work on another of them, as /// `sync` does: a thread that waits does no work, and GCD then starts more /// threads. @@ -40,6 +48,29 @@ enum WorkQueue { DispatchQueue(label: label, qos: .userInitiated, target: .global(qos: .userInitiated)) } + /// At most this many items of long work run at a time. + static let longWorkLimit = max(2, ProcessInfo.processInfo.activeProcessorCount) + + private static let longWork = Limit(count: longWorkLimit) + + /// Runs long `work` on `queue` after `delay` seconds, when fewer than + /// `longWorkLimit` items of long work run. Until then, the work waits + /// outside `queue`, oldest first, and holds no thread. + /// + /// A `sync` call on `queue` can run before work that waits for the + /// limit, so use this only for work that takes the newest state when it + /// runs, and that can find nothing to do. + static func asyncLong(_ queue: DispatchQueue, after delay: TimeInterval = 0, + execute work: @escaping @Sendable () -> Void) { + if delay > 0 { + DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + delay) { + longWork.run(work, on: queue) + } + } else { + longWork.run(work, on: queue) + } + } + /// Runs `work` on `queue` after `delay` seconds. Urgent work goes ahead /// of the long work of other queues. static func async(_ queue: DispatchQueue, urgent: Bool, after delay: TimeInterval = 0, @@ -53,3 +84,46 @@ enum WorkQueue { } } } + +/// Lets at most `count` work items run at a time, and keeps the others in +/// order until one ends. It never makes a thread wait. +private final class Limit: @unchecked Sendable { + private let count: Int + private let lock = NSLock() + private var running = 0 + private var waiting: [(work: @Sendable () -> Void, queue: DispatchQueue)] = [] + + init(count: Int) { + self.count = count + } + + func run(_ work: @escaping @Sendable () -> Void, on queue: DispatchQueue) { + let starts: Bool = lock.withLock { + guard running < count else { + waiting.append((work, queue)) + return false + } + running += 1 + return true + } + if starts { start(work, on: queue) } + } + + private func start(_ work: @escaping @Sendable () -> Void, on queue: DispatchQueue) { + queue.async { + work() + self.end() + } + } + + private func end() { + let item: (work: @Sendable () -> Void, queue: DispatchQueue)? = lock.withLock { + guard !waiting.isEmpty else { + running -= 1 + return nil + } + return waiting.removeFirst() + } + if let item { start(item.work, on: item.queue) } + } +} diff --git a/Tests/TranscriptKitTests/SharedQueueTests.swift b/Tests/TranscriptKitTests/SharedQueueTests.swift index 88b524a..1c2730e 100644 --- a/Tests/TranscriptKitTests/SharedQueueTests.swift +++ b/Tests/TranscriptKitTests/SharedQueueTests.swift @@ -173,20 +173,64 @@ struct SharedQueueTests { for engine in engines { #expect(engine.backgroundLayoutCount == 1) } } - @Test func layoutsOnManyEngineQueuesRunAboutOnePerCore() throws { - let engines = engines(manyQueues) - let result = try fewest({ $0.peak ?? 0 }) { - let meter = Meter() - return measure(engines.map(\.queue), meter: meter) { index, done in - engines[index].queue.async { - meter.enter() + /// Long layouts run at most one for each core at a time, also when they + /// wait, as Core Text does while it loads a font the first time. When + /// the threads of the pool wait, GCD starts a thread for each queue. + @Test(arguments: [false, true]) + func longWorkStaysWithinTheLimit(waits: Bool) throws { + let queues = (0..