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() } + } +} diff --git a/README.md b/README.md index d21e681..6cdd9d2 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,11 @@ 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. 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 8beb8d0..99cca78 100644 --- a/Sources/TranscriptKit/Layout/LayoutEngine.swift +++ b/Sources/TranscriptKit/Layout/LayoutEngine.swift @@ -15,6 +15,12 @@ import QuartzCore /// first layout, a change of width or style, and a replaced document when /// the view's `replacementCrossfadeDuration` asks for it. 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`). A drain of short work, +/// such as text added to the end, goes ahead of the long layouts of other +/// 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 @@ -79,7 +85,7 @@ final class LayoutEngine: @unchecked Sendable { } } - let queue = DispatchQueue(label: "TranscriptKit.layout", qos: .userInitiated) + let queue = WorkQueue.serial(label: "TranscriptKit.layout") /// The work in flight: drains that are scheduled or running, a result /// that the view has not taken yet, and the image store's loads. let work: PendingWork @@ -98,6 +104,14 @@ final class LayoutEngine: @unchecked Sendable { /// `pending` waits for `relayout` on the main thread: a drain leaves it. private var pendingIsForMain = false 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() /// 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. @@ -241,6 +255,7 @@ final class LayoutEngine: @unchecked Sendable { pendingIsForMain = false mailbox = nil onOutput = nil + laidOut = TranscriptDocument() } queue.async { self.base = nil @@ -264,7 +279,8 @@ final class LayoutEngine: @unchecked Sendable { @discardableResult func submit(_ request: Request, schedulesLayout: Bool = true) -> 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, id: Int)? = lock.withLock { guard !isShutDown else { accepted = false; return nil } guard request.source >= currentSource else { return nil } if request.source > currentSource { @@ -275,21 +291,43 @@ final class LayoutEngine: @unchecked Sendable { lastSequence = request.sequence pending = request pendingIsForMain = !schedulesLayout - if drainScheduled || !schedulesLayout { return nil } + if !schedulesLayout { 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 + drainID += 1 + return (max(lastDrain + frameInterval - CACurrentMediaTime(), 0), urgent, drainID) } - if let delay { + if let schedule { + let id = schedule.id work.begin() - if delay > 0 { - queue.asyncAfter(deadline: .now() + delay) { self.drain(); self.work.end() } + if schedule.urgent { + WorkQueue.async(queue, urgent: true, after: schedule.delay) { self.drain(id); self.work.end() } } else { - queue.async { self.drain(); self.work.end() } + WorkQueue.asyncLong(queue, after: schedule.delay) { self.drain(id); self.work.end() } } } 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. 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) <= 8 else { return false } + return document.extends(laidOut) + } + private func takePending() -> Request? { lock.withLock { () -> Request? in defer { @@ -311,12 +349,18 @@ 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 + if id == nil || id == drainID { + drainScheduled = false + drainIsUrgent = false + } guard let request = pending, !pendingIsForMain else { return nil } pending = nil lastDrain = CACurrentMediaTime() + if width > 0 { laidOut = request.document } return request } guard let request = next else { return } @@ -441,7 +485,7 @@ final class LayoutEngine: @unchecked Sendable { /// stays in use. Any thread; the result comes like any other. func settleFinishedFades() { work.begin() - queue.async { [self] in + WorkQueue.async(queue, urgent: true) { [self] in defer { work.end() } guard let layout = base, width > 0, layout.width == width else { return } let (fading, band) = updateFades(layout: layout, appendedTo: layout, tagsStarted: false) @@ -565,6 +609,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 78ef97a..332b4b6 100644 --- a/Sources/TranscriptKit/Stream/TranscriptStream.swift +++ b/Sources/TranscriptKit/Stream/TranscriptStream.swift @@ -90,13 +90,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)) runIdleActions() } @@ -149,9 +143,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 } @@ -218,7 +210,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() @@ -235,6 +227,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 new file mode 100644 index 0000000..7825c5f --- /dev/null +++ b/Sources/TranscriptKit/WorkQueue.swift @@ -0,0 +1,129 @@ +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. +/// +/// 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 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. +/// +/// 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. +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)) + } + + /// 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, + 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) + } + } +} + +/// 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 new file mode 100644 index 0000000..1c2730e --- /dev/null +++ b/Tests/TranscriptKitTests/SharedQueueTests.swift @@ -0,0 +1,384 @@ +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.. Int, _ measurement: () -> Measurement) throws -> Measurement { + let runs = (0..<5).map { _ in measurement() } + let fewest = try #require(runs.min { value($0) < value($1) }) + print("Runs: \(runs.map(value)); 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() + 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) +struct SharedQueueTests { + init() { + // 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(.enabled(if: ProcessInfo.processInfo.environment["TRANSCRIPTKIT_TIMING"] != nil), arguments: [20, manyQueues]) + func measureThreadsWhileEnginesLayOutAtOnce(_ 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) } + } + + /// 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.. Void = { name, start in + lock.withLock { waits[name] = Date().timeIntervalSince(start) } + done.leave() + } + let waitForBusy = startLongLayouts(on: busy) + Thread.sleep(forTimeInterval: 0.02) + delayed.submit(.init(document: grown, source: 2, sequence: 1)) + delayed.drainNow() + + 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() + + // 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 == 4) + #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 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.queue.async {} + var start = Date() + let layout = engine.relayout(width: 180, style: TranscriptStyle()) + let relayout = Date().timeIntervalSince(start) + engine.queue.async {} + 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 < busyTime / 4) + #expect(measure < busyTime / 4) + } + + /// `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()) + let waitForBusy = startLongLayouts(on: busy) + Thread.sleep(forTimeInterval: 0.02) + + let (latest, elapsed) = onInteractiveThread { + worker.queue.async { _ = worker.apply("Some **text", finish: false) } + let start = Date() + let latest = worker.applyNow("** here.", finish: true) + return (latest, Date().timeIntervalSince(start)) + } + 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 < busyTime / 4) + } +}