import Foundation import ParcelCore import Synchronization import Testing @testable import ParcelEngine @testable import ParcelPlatform @MainActor final class HotPathClock: EngineClock { var now = 100.0 } @MainActor final class HotPathScheduledWork: EngineCancellation { let due: Double var action: (@MainActor () -> Void)? init(due: Double, action: @escaping @MainActor () -> Void) { self.due = due self.action = action } func cancel() { action = nil } } @MainActor final class HotPathScheduler: EngineScheduler { let clock: HotPathClock private var work: [HotPathScheduledWork] = [] private(set) var scheduled = 0 var onSchedule: (@MainActor () -> Void)? init(clock: HotPathClock) { self.clock = clock } func schedule(after delay: Double, _ action: @escaping @MainActor () -> Void) -> any EngineCancellation { let item = HotPathScheduledWork(due: clock.now + delay, action: action) scheduled += 1 work.append(item) onSchedule?() return item } func runReady() { let ready = work.filter { $0.due <= clock.now } work.removeAll { $0.due <= clock.now || $0.action == nil } for item in ready { let action = item.action item.action = nil action?() } } var pendingCount: Int { work.filter { $0.action != nil }.count } } enum HotPathMotionReadPolicy: String, CaseIterable { case eager case deferred } enum HotPathMotionCadence: String, CaseIterable { case burst case paced var eventsPerTurn: Int { self == .burst ? 25 : 1 } } @MainActor final class HotPathApplication: NativeEngineApplication { let events: AsyncStream private let continuation: AsyncStream.Continuation var snapshots: [NativeWindowSnapshot] var focused: WindowID? var readDelay: Duration = .zero var motionReadPolicy: HotPathMotionReadPolicy = .deferred var newWindowTarget: (@Sendable (AppThreadCreatedWindow) -> CGRect?)? private var motionMailbox = AppThreadMotionMailbox() private let applicationAccess = CountingFrameAccess(.zero) private var frameAccess: [WindowID: CountingFrameAccess] private(set) var windowReads = 0 private(set) var frameReads = 0 private(set) var callbackFrameReads = 0 private(set) var focusReads = 0 private(set) var writes = 0 private(set) var speculativeWrites = 0 private(set) var factReads = 0 private var attributeOperationsAtReset = 0 private var frameMethodReadsAtReset = 0 var didBeginWindowRead: (@MainActor () -> Void)? var beforeWindowRead: (@MainActor () async -> Void)? var onProgress: (@MainActor () -> Void)? init(snapshots: [NativeWindowSnapshot]) { self.snapshots = snapshots frameAccess = Dictionary( uniqueKeysWithValues: snapshots.map { ($0.window.id, CountingFrameAccess($0.frame.cgRect)) }) focused = snapshots.first?.window.id let pair = AsyncStream.makeStream() events = pair.stream continuation = pair.continuation } var motionIsIdle: Bool { motionMailbox.inFlightCount == 0 && motionMailbox.pendingCount == 0 } var syntheticFrameAttributeOperations: Int { attributeOperations - attributeOperationsAtReset } var syntheticFrameMethodReads: Int { frameMethodReads - frameMethodReadsAtReset } private var frameMethodReads: Int { frameAccess.values.reduce(0) { $0 + $1.frameReads } } private var attributeOperations: Int { applicationAccess.attributeOperations + frameAccess.values.reduce(0) { $0 + $1.attributeOperations } } func emit(_ event: AppThreadEvent) { if let pending = motionMailbox.flushBefore(event) { deliver(pending) } let offered = motionReadPolicy == .eager ? materialize(event) : event if let ready = motionMailbox.offer(offered) { deliver(ready) } } private func materialize(_ event: AppThreadEvent) -> AppThreadEvent { AppThreadMotionMailbox.materialize(event) { raw in self.callbackFrameReads += 1 return try self.access(WindowID(rawValue: raw)).frame } } private func deliver(_ event: AppThreadEvent) { continuation.yield(materialize(event)) } func acknowledgeMotion(_ window: UInt32) { if let event = motionMailbox.acknowledge(window) { deliver(event) } onProgress?() } func setFrame(_ frame: Rect, for window: WindowID) throws { guard let index = snapshots.firstIndex(where: { $0.window.id == window }) else { throw EnginePlatformFailure.vanished(window) } snapshots[index].frame = frame try access(window).value = frame.cgRect } func emitCreated(_ window: ManagedWindow, frame: Rect, speculate: Bool) throws -> Rect { snapshots.append(NativeWindowSnapshot(window: window, frame: frame)) frameAccess[window.id] = CountingFrameAccess(frame.cgRect) let source = CountingFactsAccess() let facts = try WindowFactsReader.gather( source: source, context: WindowFactsContext(bundleID: window.app.bundleID, activationPolicy: .regular)) factReads += source.reads callbackFrameReads += 1 let created = AppThreadCreatedWindow( windowID: window.id.rawValue, facts: facts, frame: try access(window.id).frame, isOnScreen: true) let placed = try AppThreadSpeculativePlacement.place( created, speculate: speculate, assistiveTechnology: AssistiveTechnology(voiceOver: false, switchControl: false), read: newWindowTarget ) { target in self.speculativeWrites += 1 self.writes += 1 return try executeFrameWrite( target, window: self.access(window.id), application: self.applicationAccess, assistiveTechnology: AssistiveTechnology(voiceOver: false, switchControl: false)) } try setFrame(Rect(placed.frame), for: window.id) emit(.windowCreatedWithFacts(placed)) return Rect(placed.frame) } private func access(_ window: WindowID) throws -> CountingFrameAccess { guard let access = frameAccess[window] else { throw EnginePlatformFailure.vanished(window) } return access } func windows() async throws -> [NativeWindowSnapshot] { windowReads += 1 didBeginWindowRead?() onProgress?() if let beforeWindowRead { await beforeWindowRead() } if readDelay > .zero { try await Task.sleep(for: readDelay) } return snapshots } func frame(_ window: WindowID) async throws -> Rect { frameReads += 1 return Rect(try access(window).frame) } func focusedWindow() async throws -> WindowID? { focusReads += 1 return focused } func emitFocus() { focusReads += 1 emit(.focusedWindowRead(focused?.rawValue)) } func write(_ frame: Rect, to window: WindowID) async throws -> Rect { writes += 1 try setFrame(frame, for: window) return frame } func writeFrames(_ frames: [EngineFrameWrite]) async throws -> EngineWriteReceipt { writes += frames.count for frame in frames { try setFrame(frame.frame, for: frame.window) } return EngineWriteReceipt( frames: frames.filter(\.isFinal).map { WindowFrame(window: $0.window, frame: $0.frame) }, duration: 0, writtenWindowCount: frames.count) } func cancelFrameWrites(_ window: WindowID, throughGeneration: UInt64) async throws {} func finishShutdown() async throws {} func focus(_ window: WindowID) async throws { focused = window } func raise(_ window: WindowID) async throws {} func close(_ window: WindowID) async throws { snapshots.removeAll { $0.window.id == window } frameAccess.removeValue(forKey: window) } func toggleFullscreen(_ window: WindowID) async throws { throw EnginePlatformFailure.operation(.focusUnchanged(window)) } func shutdown() { continuation.finish() } func resetCounts() { windowReads = 0 frameReads = 0 callbackFrameReads = 0 focusReads = 0 writes = 0 speculativeWrites = 0 factReads = 0 attributeOperationsAtReset = attributeOperations frameMethodReadsAtReset = frameMethodReads } } @MainActor final class HotPathNativeBackend: NativeEngineBackend { let displays: [ParcelCore.Display] var apps: [AppID: HotPathApplication] var spaces: [DisplayID: SpaceID] var frontmost: AppID? var beforeVisibleRead: (@MainActor () async -> Void)? private(set) var windowListReads = 0 private(set) var spaceReads = 0 private var receive: (@MainActor (NativeEngineEvent) -> Void)? init(state: State, apps: [AppID: HotPathApplication]) { displays = state.displays.values.sorted { $0.id < $1.id } spaces = Dictionary( uniqueKeysWithValues: displays.enumerated().map { index, display in (display.id, SpaceID(rawValue: UInt64(index * 100 + 1))) }) self.apps = apps frontmost = state.windows[state.focusedWindow ?? WindowID(rawValue: 0)]?.app } func start(receive: @escaping @MainActor (NativeEngineEvent) -> Void) { self.receive = receive } func setNewWindowTarget(_ target: @escaping @Sendable (AppThreadCreatedWindow) -> CGRect?) { for app in apps.values { app.newWindowTarget = target } } func stop() { receive = nil } func emit(_ event: NativeEngineEvent) { receive?(event) } func currentDisplays() -> [ParcelCore.Display] { displays } func focusedApplication() -> AppID? { frontmost } func runningApplications() -> [NativeApplicationInfo] { apps.keys.sorted { $0.pid < $1.pid }.map { NativeApplicationInfo(id: $0) } } func application(_ app: AppID) throws -> any NativeEngineApplication { guard let application = apps[app] else { throw EnginePlatformFailure.appUnavailable(app) } return application } func visibleWindows() async throws -> NativeVisibleWindows { windowListReads += 1 if let beforeVisibleRead { await beforeVisibleRead() } let snapshots = apps.values.flatMap(\.snapshots) return NativeVisibleWindows( frames: Dictionary(uniqueKeysWithValues: snapshots.map { ($0.window.id, $0.frame) }), owners: Dictionary(uniqueKeysWithValues: snapshots.map { ($0.window.id, $0.window.app.pid) })) } func nativeSpaces() -> [NativeDisplaySpaces] { displays.compactMap { display in guard let space = spaces[display.id] else { return nil } return NativeDisplaySpaces( displayID: display.id.rawValue, currentSpace: space.rawValue, spaces: [NativeSpace(id: space.rawValue, kind: .desktop, desktopNumber: Int(space.rawValue))]) } } func currentSpaces(for displays: [DisplayID]) async throws -> NativeSpaceState { spaceReads += 1 return NativeSpaceState( spaces: spaces.filter { displays.contains($0.key) }, suspended: [], snapshot: nativeSpaces()) } func resetCounts() { windowListReads = 0 spaceReads = 0 for app in apps.values { app.resetCounts() } } } final class HotPathSpaceReader: SpaceReading, Sendable { let backend: HotPathNativeBackend private let counter = Mutex(0) init(backend: HotPathNativeBackend) { self.backend = backend } var reads: Int { counter.withLock { $0 } } func reset() { counter.withLock { $0 = 0 } } func snapshot() async throws -> [NativeDisplaySpaces] { counter.withLock { $0 += 1 } return await backend.nativeSpaces() } func spaces(for window: UInt32) async throws -> [UInt64] { [] } func stageManagerEnabled() async throws -> Bool { false } } @MainActor final class HotPathNativeFixture { let model: HotPathStateFixture let clock = HotPathClock() let scheduler: HotPathScheduler let backend: HotPathNativeBackend let world: NativeEngineWorld let spaceReader: HotPathSpaceReader private(set) var events: [EnginePlatformEvent] = [] var state = State() private(set) var suspended: Set = [] private var suspensionHistory: [Set] = [] private var failure: EnginePlatformFailure? private struct DrainWaiter { let id: UUID let predicate: @MainActor () -> Bool let continuation: CheckedContinuation } private var scheduledAtReset = 0 private var drainWaiter: DrainWaiter? private var progressScheduled = false private var started = false var onDrainWaiting: (@MainActor () -> Void)? var onReconciliationCheck: (@MainActor (Bool) -> Void)? init(count: Int, workspaces: Int = 1, applications: Int = 5) { model = HotPathStateFixture(count: count, workspaces: workspaces) var snapshots: [AppID: [NativeWindowSnapshot]] = [:] for (index, id) in model.ids.enumerated() { guard var window = model.state.windows[id], let frame = model.state.frames[id] else { preconditionFailure("Incomplete native fixture") } window.app = AppID(pid: Int32(index % applications + 1), bundleID: "org.example.fixture") snapshots[window.app, default: []].append(NativeWindowSnapshot(window: window, frame: frame)) } scheduler = HotPathScheduler(clock: clock) backend = HotPathNativeBackend( state: model.state, apps: snapshots.mapValues { HotPathApplication(snapshots: $0) }) spaceReader = HotPathSpaceReader(backend: backend) world = NativeEngineWorld( backend: backend, scheduler: scheduler, spaceController: SpaceController(reader: spaceReader)) scheduler.onSchedule = { [weak self] in self?.signalProgress() } for app in backend.apps.values { app.onProgress = { [weak self] in self?.signalProgress() } } world.onWindowObservation = { [weak self] _ in self?.signalProgress() } world.onReconciliationIdle = { [weak self] in self?.signalProgress() } } func start() async throws { precondition(!started, "Native fixture is already started") try world.start { [unowned self] event in events.append(event) switch event.untraced { case .observed(let observation): state = reduce(state, observation).0 case .frameChanged(let id, let frame, let resized, _): state = reduce( state, resized ? .windowResizedByUser(id, frame: frame) : .windowMovedByUser(id, frame: frame) ).0 case .suspendedDisplaysChanged(let displays): suspended = displays suspensionHistory.append(displays) case .failure(let error): failure = error default: break } signalProgress() } started = true do { try await drain { self.state.windows.count == self.model.ids.count && !self.world.hasPendingReconciliation } world.updatePlacementState(state, classifier: WindowClassifier(), allowsSpeculation: true) resetCounts() } catch { stop() throw error } } func stop() { started = false world.stop() finishDrain(throwing: BenchmarkFailure.measurement("native fixture stopped with pending work")) } func resetCounts() { events.removeAll(keepingCapacity: true) backend.resetCounts() spaceReader.reset() suspensionHistory.removeAll(keepingCapacity: true) scheduledAtReset = scheduler.scheduled failure = nil } func drain(until predicate: @escaping @MainActor () -> Bool) async throws { precondition(drainWaiter == nil, "Native fixture operations must run in sequence") try Task.checkCancellation() guard started else { throw BenchmarkFailure.measurement("native fixture is stopped") } if let failure { throw failure } if predicate() { return } let id = UUID() try await withTaskCancellationHandler { try Task.checkCancellation() try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in guard !Task.isCancelled else { continuation.resume(throwing: CancellationError()) return } drainWaiter = DrainWaiter(id: id, predicate: predicate, continuation: continuation) onDrainWaiting?() scheduler.runReady() signalProgress() } } onCancel: { Task { @MainActor [weak self] in guard let self, self.drainWaiter?.id == id else { return } self.finishDrain(throwing: CancellationError()) } } } private func finishDrain(throwing error: any Error) { let continuation = drainWaiter?.continuation drainWaiter = nil continuation?.resume(throwing: error) } private func signalProgress() { guard drainWaiter != nil, !progressScheduled else { return } progressScheduled = true // Check after the delivery job finishes, including its deferred acknowledgement. DispatchQueue.main.async { [weak self] in guard let self else { return } self.progressScheduled = false guard let waiter = self.drainWaiter else { return } self.scheduler.runReady() if let failure = self.failure { self.finishDrain(throwing: failure) } else if waiter.predicate() { self.drainWaiter = nil waiter.continuation.resume() } } } func focus() async throws -> BenchmarkObservation { let app = try firstApplication() guard let target = app.snapshots.last?.window.id else { throw BenchmarkFailure.measurement("no native focus target") } resetCounts() app.focused = target backend.frontmost = app.snapshots.first?.window.app app.emitFocus() try await drain { self.events.contains { if case .observed(.focusChanged(let id)) = $0.untraced { return id == target } return false } } return observation() } func moved( count: Int = 1, cadence: HotPathMotionCadence = .burst, readPolicy: HotPathMotionReadPolicy = .deferred ) async throws -> BenchmarkObservation { precondition(count > 0) let app = try firstApplication() guard let snapshot = app.snapshots.first else { throw BenchmarkFailure.measurement("no native move target") } resetCounts() app.motionReadPolicy = readPolicy defer { app.motionReadPolicy = .deferred } var consumerTurns = 0 for index in 1...count { let frame = Rect( x: snapshot.frame.minX + Double(index), y: snapshot.frame.minY, width: snapshot.frame.size.width, height: snapshot.frame.size.height) try app.setFrame(frame, for: snapshot.window.id) app.emit(.windowMoved(snapshot.window.id.rawValue, origin: .unattributed)) if index.isMultiple(of: cadence.eventsPerTurn) || index == count { consumerTurns += 1 try await drain { self.state.observedFrames[snapshot.window.id] == frame && app.motionIsIdle } } } var result = observation() result.proofMetrics["motion-notifications"] = Double(count) result.proofMetrics["consumer-turns"] = Double(consumerTurns) result.proofMetrics["events-per-consumer-turn"] = Double(cadence.eventsPerTurn) result.proofMetrics["final-frame-delivered"] = 1 return result } func created(speculate: Bool = false) async throws -> BenchmarkObservation { let app = try firstApplication() guard let reference = app.snapshots.first else { throw BenchmarkFailure.measurement("no native create target") } let id = WindowID(rawValue: 10001) let window = ManagedWindow( id: id, app: reference.window.app, title: reference.window.title, minimumSize: reference.window.minimumSize) world.updatePlacementState(state, classifier: WindowClassifier(), allowsSpeculation: true) resetCounts() let initial = Rect(x: 100, y: 100, width: 800, height: 600) let callbackFrame = try app.emitCreated(window, frame: initial, speculate: speculate) let writesBeforeDelivery = app.speculativeWrites try await drain { self.state.windows[id] != nil && !self.world.hasPendingReconciliation } var result = observation() result.proofMetrics["writes-before-engine-delivery"] = Double(writesBeforeDelivery) result.proofMetrics["callback-frame-matches-layout"] = state.frames[id] == callbackFrame ? 1 : 0 result.proofMetrics["created-window-admitted"] = 1 try await app.close(id) app.emit(.windowDestroyed(id.rawValue)) try await drain { self.state.windows[id] == nil } return result } func reconcile() async throws -> BenchmarkObservation { resetCounts() world.reconcile(Set(backend.apps.keys)) try await drain { let complete = self.backend.windowListReads > 0 && self.backend.apps.values.allSatisfy { $0.windowReads > 0 } && self.scheduler.pendingCount == 0 && !self.world.hasPendingReconciliation self.onReconciliationCheck?(complete) return complete } return observation() } func changeSpace() async throws -> BenchmarkObservation { guard let display = backend.displays.first else { throw BenchmarkFailure.measurement("no native display") } let old = backend.spaces[display.id] ?? SpaceID(rawValue: 1) let new = SpaceID(rawValue: old.rawValue == 1 ? 2 : 1) resetCounts() backend.spaces[display.id] = new backend.emit(.spaceChanged) try await drain { self.state.activeSpaces[display.id] == new && self.backend.spaceReads > 0 && !self.world.hasPendingReconciliation } var result = observation() result.proofMetrics["suspended-display-count"] = Double(suspensionHistory.map(\.count).max() ?? 0) result.proofMetrics["unchanged-display-suspended"] = backend.displays.count > 1 && suspensionHistory.contains { $0.contains(backend.displays.last?.id ?? display.id) } ? 1 : 0 return result } func echoFrames() async throws -> BenchmarkObservation { resetCounts() for tick in 1...24 { var receipts = 0 for (id, app) in backend.apps { let writes = app.snapshots.map { snapshot in EngineFrameWrite(window: snapshot.window.id, frame: snapshot.frame, transaction: UInt64(tick)) } world.write(writes, for: id) { receipt in if let error = receipt.failures.first { self.failure = error } receipts += 1 self.signalProgress() } } try await drain { receipts == self.backend.apps.count } for app in backend.apps.values { for snapshot in app.snapshots { app.emit(.windowMoved(snapshot.window.id.rawValue, origin: .unattributed)) } } try await drain { self.backend.apps.values.allSatisfy(\.motionIsIdle) } } return observation() } func hungFocus() async throws -> BenchmarkObservation { let apps = backend.apps.sorted { $0.key.pid < $1.key.pid } guard apps.count >= 2, let target = apps[1].value.focused else { throw BenchmarkFailure.measurement("hung focus needs two apps") } let first = apps[0].value let second = apps[1].value resetCounts() var begun = false first.readDelay = .milliseconds(350) first.didBeginWindowRead = { begun = true } first.emit(.windowTitleChanged(first.snapshots[0].window.id.rawValue)) try await drain { begun } backend.frontmost = apps[1].key backend.emit(.activated(NativeApplicationInfo(id: apps[1].key))) let start = ContinuousClock.now second.emitFocus() try await drain { self.events.contains { if case .observed(.focusChanged(let id)) = $0.untraced { return id == target } return false } } let latency = BenchmarkHarness.nanoseconds(start.duration(to: .now)) first.readDelay = .zero first.didBeginWindowRead = nil var result = observation() result.proofMetrics["other-app-focus-wall-ns"] = latency return result } private func firstApplication() throws -> HotPathApplication { guard let app = backend.apps.min(by: { $0.key.pid < $1.key.pid })?.value else { throw BenchmarkFailure.measurement("no native application") } return app } private func observation() -> BenchmarkObservation { let apps = backend.apps.values return BenchmarkObservation( checksum: state.windows.keys.reduce(1) { $0 + Int($1.rawValue) }, proofMetrics: [ "application-window-reads": Double(apps.reduce(0) { $0 + $1.windowReads }), "application-frame-reads": Double(apps.reduce(0) { $0 + $1.frameReads }), "callback-frame-reads": Double(apps.reduce(0) { $0 + $1.callbackFrameReads }), "synthetic-frame-method-reads": Double(apps.reduce(0) { $0 + $1.syntheticFrameMethodReads }), "synthetic-frame-attribute-operations": Double( apps.reduce(0) { $0 + $1.syntheticFrameAttributeOperations }), "fact-access-method-reads": Double(apps.reduce(0) { $0 + $1.factReads }), "speculative-writes": Double(apps.reduce(0) { $0 + $1.speculativeWrites }), "application-focus-reads": Double(apps.reduce(0) { $0 + $1.focusReads }), "window-list-reads": Double(backend.windowListReads), "space-reads": Double(backend.spaceReads + spaceReader.reads), "application-writes": Double(apps.reduce(0) { $0 + $1.writes }), "scheduled-world-turns": Double(scheduler.scheduled - scheduledAtReset), "frame-observations": Double( events.filter { if case .frameChanged = $0.untraced { return true } return false }.count), ]) } } @MainActor final class HotPathWorld: EngineWindowWorld { private(set) var writes = 0 func start(receive: @escaping @MainActor (EnginePlatformEvent) -> Void) {} func stop() {} func write( _ frames: [EngineFrameWrite], for app: AppID, completion: @escaping @MainActor (EngineWriteReceipt) -> Void ) { writes += frames.count completion( EngineWriteReceipt(frames: frames.map { WindowFrame(window: $0.window, frame: $0.frame) }, duration: 0)) } func focus(_ window: WindowID, completion: @escaping @MainActor (EnginePlatformFailure?) -> Void) { completion(nil) } func raise(_ window: WindowID, completion: @escaping @MainActor (EnginePlatformFailure?) -> Void) { completion(nil) } func close(_ window: WindowID) async throws {} func toggleFullscreen(_ window: WindowID) async throws {} func reconcile(_ apps: Set) {} } @MainActor final class HotPathEngineLink: EngineDisplayLink { let frameRate = 120.0 private var tick: (@MainActor (Double) -> Void)? var isRunning: Bool { tick != nil } func start(tick: @escaping @MainActor (Double) -> Void) { self.tick = tick } func stop() { tick = nil } } @MainActor final class HotPathAnnouncer: EngineAnnouncer { func announce(_ announcement: Announcement) {} } @MainActor final class HotPathLog: EngineLogSink { func record(_ diagnostic: EngineDiagnostic) { if case .platform(let failure) = diagnostic { Issue.record("Headless engine failed: \(failure)") } } }