import AppKit import Foundation import ParcelAnimation import ParcelConfig import ParcelCore import QuartzCore import Testing @testable import ParcelAnimation @testable import ParcelEngine @testable import ParcelPlatform @testable import ParcelUI @MainActor enum HotPathBenchmarks { static func run(_ harness: inout BenchmarkHarness) async throws { try reducerCases(&harness) await Task.yield() try motionCases(&harness) await Task.yield() try inputCases(&harness) await Task.yield() try platformCases(&harness) await Task.yield() try overlayCases(&harness) let tabView = TabViewRenderingFixture() try measure("TabView/CanvasAndCardRaster/12", &harness, latencySamples: 100) { try tabView.render().observation } try await configCases(&harness) try await nativeCases(&harness) try await DisplayEventBenchmarks.run(&harness) try await engineCases(&harness) } static func writeCatalog() throws { let directory = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() .deletingLastPathComponent().appendingPathComponent("build", isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] try encoder.encode(BenchmarkCatalog.entries).write( to: directory.appendingPathComponent("bench-catalog.json"), options: .atomic) } private static func measure( _ name: String, _ harness: inout BenchmarkHarness, latencySamples: Int = 1000, operation: () throws -> BenchmarkObservation ) rethrows { let entry = BenchmarkCatalog.definition(named: name) try harness.measure( name, iterations: entry.iterations, reportingOnly: entry.reportingOnly, budget: entry.budget, reason: entry.reason, cpuBudgetNanoseconds: entry.cpuBudgetNanoseconds, latencySamples: latencySamples, operation: operation) } private static func measureAsync( _ name: String, _ harness: inout BenchmarkHarness, latencySamples: Int = 1000, operation: () async throws -> BenchmarkObservation ) async rethrows { let entry = BenchmarkCatalog.definition(named: name) try await harness.measureAsync( name, iterations: entry.iterations, reportingOnly: entry.reportingOnly, budget: entry.budget, reason: entry.reason, latencySamples: latencySamples, operation: operation) } private static func reducerCases(_ harness: inout BenchmarkHarness) throws { for count in [10, 50, 200] { for workspaces in [1, 8] { let fixture = HotPathStateFixture(count: count, workspaces: workspaces) guard let target = fixture.activeIDs.last else { throw BenchmarkFailure.measurement("active focus fixture") } measure("reduce.focusObservation.\(count)x\(workspaces)ws", &harness) { let (next, effects) = reduce(fixture.state, .focusChanged(target)) return reduced(next, effects: effects.count) } } let fixture = HotPathStateFixture(count: count) guard let original = fixture.state.frames[fixture.ids[0]], let edge = fixture.state.tileEdges.first else { throw BenchmarkFailure.measurement("interactive fixture geometry") } let drag = Rect( x: original.minX, y: original.minY, width: original.size.width + 8, height: original.size.height) let previousTick = reduce(fixture.state, .windowFrameEdited(fixture.ids[0], frame: drag)).0 measure("reduce.windowFrameEdited.tick.\(count)", &harness) { let (next, effects) = reduce( previousTick, .windowFrameEdited( fixture.ids[0], frame: Rect(x: drag.minX, y: drag.minY, width: drag.size.width + 4, height: drag.size.height))) return reduced(next, effects: effects.count) } measure("reduce.tileEdgeResized.tick.\(count)", &harness) { let (next, effects) = reduce(fixture.state, .tileEdgeResized(edge, delta: 8)) return reduced(next, effects: effects.count) } let pair = (0..<3).map { _ in AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) } defer { for item in pair { item.continuation.finish() } } measure("snapshot-publish/\(count)", &harness) { let snapshot = EngineSnapshot(revision: 1, state: fixture.state) var yields = 0 for item in pair { switch item.continuation.yield(snapshot) { case .enqueued, .dropped: yields += 1 case .terminated: preconditionFailure("Benchmark snapshot subscriber terminated") @unknown default: preconditionFailure("Unknown stream yield result") } } return BenchmarkObservation( checksum: hotPathChecksum(snapshot.state.frames) + snapshot.tiles.count + yields, proofMetrics: ["subscriber-yields": Double(yields), "snapshot-tiles": Double(snapshot.tiles.count)]) } } for layout in Layout.allCases { let fixture = HotPathStateFixture(count: 10, layout: layout) measure("reduce-layout/\(layout.rawValue)/10", &harness) { let (next, effects) = reduce(fixture.state, .commandIssued(.retile)) return reduced(next, effects: effects.count) } } for count in [50, 200] { let fixture = HotPathStateFixture(count: count) guard let frame = fixture.state.frames[fixture.ids[0]] else { throw BenchmarkFailure.measurement("batch frame") } let burst: [Event] = [ .focusChanged(fixture.ids[1]), .windowMovedByUser(fixture.ids[0], frame: frame), .windowFrameEdited( fixture.ids[0], frame: Rect(x: frame.minX, y: frame.minY, width: frame.size.width + 8, height: frame.size.height)), .focusChanged(fixture.ids[2]), .windowResizedByUser(fixture.ids[1], frame: frame), .commandIssued(.nudgeRatio(0.01)), .focusChanged(fixture.ids[0]), .relayout, ] measure("reduce.batch.mixed8.\(count)", &harness) { let before = hotPathRetainedBytes() let (next, effects) = reduce(fixture.state, burst) var result = reduced(next, effects: effects.reduce(0) { $0 + $1.count }) result.proofMetrics["retained-bytes-delta"] = Double(hotPathRetainedBytes() - before) result.proofMetrics["events-in-batch"] = Double(burst.count) return result } let columns = HotPathStateFixture(count: count, layout: .columns) guard let workspace = columns.state.workspaces[columns.keys[0]], let display = columns.state.displays[columns.keys[0].display] else { throw BenchmarkFailure.measurement("column edge fixture") } measure("layout.edges.columns.\(count)", &harness) { let edges = LayoutEngine.edges(workspace, in: display.frame, windows: columns.state.windows) return BenchmarkObservation( checksum: edges.reduce(1) { $0 + $1.path.count + $1.affectedWindows.count + Int($1.position.rounded()) }, proofMetrics: [ "edges": Double(edges.count), "max-path-depth": Double(edges.map { $0.path.count }.max() ?? 0), ]) } } for layout in [Layout.columns, .rows, .accordion] { let fixture = HotPathStateFixture(count: 200, layout: layout) guard let workspace = fixture.state.workspaces[fixture.keys[0]], let display = fixture.state.displays[fixture.keys[0].display] else { throw BenchmarkFailure.measurement("linear layout fixture") } measure("layout.arrange.\(layout.rawValue).200", &harness) { let layout = LayoutEngine.arrange(workspace, in: display.frame, windows: fixture.state.windows) return BenchmarkObservation( checksum: hotPathChecksum(layout.frames) + layout.visibleWindows.count, proofMetrics: ["arranged-frames": Double(layout.frames.count)]) } } } private static func reduced(_ state: State, effects: Int) -> BenchmarkObservation { BenchmarkObservation( checksum: hotPathChecksum(state.frames) + effects + Int(state.focusedWindow?.rawValue ?? 0), proofMetrics: [ "windows": Double(state.windows.count), "effects": Double(effects), "undo-entries": Double( state.undoHistory.map { history in history.windows.reduce(0) { $0 + history.count(for: $1) } } ?? 0), ]) } static func soakTicks(full: Bool) -> Int { full ? 10000 : 30 } private static func motionCases(_ harness: inout BenchmarkHarness) throws { let counters = harness.counters for count in [1, 10, 30, 200] { let fixture = MotionTickFixture(count: count) let name = count == 200 ? "AnimationTick200" : "motion-tick/\(count)" try measure(name, &harness) { var observation = try fixture.run(counters: counters) observation.counterOperations = 30 return observation } } let soak = MotionTickFixture(count: 30) let ticks = soakTicks(full: harness.full) try measure("motion-soak/30x10000", &harness, latencySamples: 0) { let before = hotPathRetainedBytes() var result = try soak.run(ticks: ticks, counters: counters) result.counterOperations = ticks result.proofMetrics["retained-bytes-after-stop-delta"] = Double(hotPathRetainedBytes() - before) result.proofMetrics["display-source-running-after-stop"] = soak.source.isRunning ? 1 : 0 return result } for count in [10, 200] { let requests = MotionTickFixture(count: count).requests let name = count == 10 ? "motion-retarget/10" : "AnimationSchedule200" try measure(name, &harness) { var animator = Animator() try animator.schedule(requests, at: 100) _ = try animator.tick(at: 100.075) let reversed = requests.map { request in MotionRequest( windowID: request.windowID, appID: request.appID, start: request.start, target: request.start, screen: request.screen) } let cpu = BenchmarkCPUClock.now() let start = ContinuousClock.now let before = try counters.read() try animator.schedule(reversed, at: 100.075) let after = try counters.read() let wall = BenchmarkHarness.nanoseconds(start.duration(to: .now)) let elapsed = BenchmarkCPUClock.elapsed(since: cpu) let measuredCounters: BenchmarkCounterReading? if let before { guard let after else { throw BenchmarkFailure.measurement("retarget counters disappeared") } measuredCounters = try after.delta(from: before) } else { measuredCounters = nil } var checksum = 1 var inheritedSpeed = 0.0 for request in requests { if let sample = try animator.presentation(for: request.windowID, at: 100.075) { checksum += Int(sample.frame.rect.originX.rounded()) + Int(sample.frame.windowID.rawValue) inheritedSpeed += abs(sample.velocity.horizontal) } } return BenchmarkObservation( checksum: checksum, nanoseconds: wall, cpuNanoseconds: elapsed, instructions: measuredCounters.map { Double($0.instructions) }, cycles: measuredCounters.map { Double($0.cycles) }, proofMetrics: [ "retargeted-windows": Double(animator.activeWindowIDs.count), "inherited-speed-sum": inheritedSpeed, ]) } } try measure("CoalescerProMotionJitter", &harness) { try jitter() } try measure("PerWindowRateContinuity", &harness) { var rates: [Double] = [] var snaps = 0 for windows in 1...8 { for microseconds in stride(from: 8000, through: 8600, by: 100) { var metrics = AppWriteMetrics() try metrics.record(duration: Double(microseconds * windows) / 1_000_000, at: 100) rates.append(metrics.frameRate()) if metrics.shouldSnap(at: 100) { snaps += 1 } } } return BenchmarkObservation( checksum: 1 + rates.reduce(0) { $0 + Int($1.rounded()) } + snaps, proofMetrics: [ "rate-at-8.4ms": rates[4], "app-wide-snap-cases": Double(snaps), "minimum-rate": rates.min() ?? 0, "rate-samples": Double(rates.count), ]) } try measure("NeighbourPhaseDivergence", &harness) { try neighbourReplay() } } static func jitter() throws -> BenchmarkObservation { var coalescer = FrameCoalescer() var dispatches = 0 let window = MotionWindowID(rawValue: 1) let app = MotionAppID(rawValue: 1) for tick in 0..<600 { let timestamp = 100000 + Double(tick) / 120 + (tick % 2 == 0 ? -3e-11 : 3e-11) let request = MotionRequest( windowID: window, appID: app, start: MotionRect(originX: 0, originY: 0, width: 100, height: 100), target: MotionRect(originX: 100, originY: 0, width: 100, height: 100), screen: MotionRect(originX: 0, originY: 0, width: 1000, height: 1000)) let plan = try FramePlanner.plan(request, at: timestamp - 0.01) try coalescer.submit(try plan.sample(at: timestamp).frame) let ready = try coalescer.takeReady(at: timestamp) dispatches += ready.count for batch in ready { try coalescer.complete(batch, duration: 0, at: timestamp) } } return BenchmarkObservation( checksum: dispatches + 1, proofMetrics: ["ticks": 600, "dispatches": Double(dispatches), "skipped-ticks": Double(600 - dispatches)]) } private static func neighbourReplay() throws -> BenchmarkObservation { var animator = Animator() var coalescer = FrameCoalescer() let screen = MotionRect(originX: 0, originY: 0, width: 1000, height: 1000) let requests: [MotionRequest] = (0..<2).map { index -> MotionRequest in let x = Double(index) * 100 let start = MotionRect(originX: x, originY: 100, width: 100, height: 100) let target = MotionRect(originX: x + 100, originY: 100, width: 100, height: 100) return MotionRequest( windowID: MotionWindowID(rawValue: UInt64(index + 1)), appID: MotionAppID(rawValue: Int32(index + 1)), start: start, target: target, screen: screen) } try animator.schedule(requests, at: 100) var delivered: [MotionWindowID: MotionRect] = Dictionary( uniqueKeysWithValues: requests.map { ($0.windowID, $0.start) }) var inflight: [(batch: FrameBatch, due: Double)] = [] var maximum = 0.0 var overlap = 0.0 var writes = 0 for tick in 1...60 { let time = 100 + Double(tick) / 120 let ready = inflight.filter { $0.due <= time } inflight.removeAll { $0.due <= time } for pending in ready { for frame in pending.batch.frames { delivered[frame.windowID] = frame.rect writes += 1 } try coalescer.complete(pending.batch, duration: pending.due - pending.batch.dispatchedAt, at: time) } for frame in try animator.tick(at: time) { try coalescer.submit(frame) } for batch in try coalescer.takeReady(at: time) { inflight.append((batch, time + (batch.appID.rawValue == 1 ? 0.002 : 0.020))) } guard let left = delivered[requests[0].windowID], let right = delivered[requests[1].windowID] else { throw BenchmarkFailure.measurement("missing neighbour frame") } maximum = max(maximum, abs(left.maxX - right.originX)) overlap = max(overlap, max(0, left.maxX - right.originX) * 100) } return BenchmarkObservation( checksum: writes + Int(maximum.rounded()) + Int(overlap.rounded()) + 1, proofMetrics: [ "maximum-edge-divergence-points": maximum, "maximum-overlap-area": overlap, "delivered-frames": Double(writes), ]) } private static func inputCases(_ harness: inout BenchmarkHarness) throws { let backend = HotPathKeyBackend() var presses = 0 let center = HotKeyCenter( backend: backend, onPress: { _ in presses += 1 }, onFailure: { Issue.record("Input benchmark failure: \($0)") }) guard let chord = ParcelConfiguration.defaults.keybindings[.focusRight] else { throw BenchmarkFailure.measurement("default synthetic hotkey") } let key = HotKey(keyCode: chord.keyCode, modifiers: .init(rawValue: UInt32(chord.modifiers.rawValue))) // Force the event-tap route without changing the configured default chord. backend.carbonStatus = -1 _ = try center.register(key) defer { do { try center.stop() } catch { Issue.record(error) } } guard let handler = backend.onTapEvent else { throw BenchmarkFailure.measurement("synthetic hotkey handler") } guard let down = CGEvent(keyboardEventSource: nil, virtualKey: key.keyCode, keyDown: true), let up = CGEvent(keyboardEventSource: nil, virtualKey: key.keyCode, keyDown: false), let passthrough = CGEvent(keyboardEventSource: nil, virtualKey: key.keyCode, keyDown: true), let move = CGEvent( mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: CGPoint(x: 20, y: 20), mouseButton: .left) else { throw BenchmarkFailure.measurement("synthetic CGEvent creation") } down.flags = key.modifiers.eventFlags up.flags = key.modifiers.eventFlags passthrough.flags = [] try measure("input-tap/keydown-hotkey", &harness) { let before = presses let consumed = InputEventTap.dispatch(.keyDown, down, handler: handler) _ = InputEventTap.dispatch(.keyUp, up, handler: handler) guard consumed, presses == before + 1 else { throw BenchmarkFailure.measurement("hotkey did not dispatch") } return BenchmarkObservation( checksum: 1, proofMetrics: ["hotkey-press-callbacks": Double(presses - before), "consumed": consumed ? 1 : 0]) } try measure("input-tap/keydown-passthrough", &harness) { let before = presses let consumed = InputEventTap.dispatch(.keyDown, passthrough, handler: handler) center.resetPressedState() guard !consumed, presses == before else { throw BenchmarkFailure.measurement("passthrough consumed") } return BenchmarkObservation(checksum: 1, proofMetrics: ["hotkey-press-callbacks": 0, "consumed": 0]) } let fixture = HotPathStateFixture(count: 10) var mouse = MouseModel() var locations = CGPoint.zero measure("input-tap/mouse-moved", &harness) { var effects: [MouseEffect] = [] let consumed = InputEventTap.dispatch(.mouseMoved, move) { _, event in locations = event.location effects = mouse.reduce( DragSample(kind: .dragged, location: event.location, timestamp: 100), state: fixture.state, configuration: ParcelConfiguration.defaults.mouse) return false } return BenchmarkObservation( checksum: 1 + Int(locations.x + locations.y) + effects.count, proofMetrics: ["mouse-effects": Double(effects.count), "consumed": consumed ? 1 : 0]) } } private static func platformCases(_ harness: inout BenchmarkHarness) throws { for count in [40, 200] { let fixture = try RecordedWindowFixture(count: count) for name in count == 200 ? ["window-list-read/decode-200", "WindowListDecode/200"] : ["window-list-read/decode-40"] { try measure(name, &harness) { let windows = try fixture.decode() return BenchmarkObservation( checksum: windows.reduce(1) { $0 + Int($1.number) + Int($1.bounds.width.rounded()) + Int($1.layer) }, proofMetrics: ["decoded-windows": Double(windows.count)]) } } } for (name, windows, ticks) in [ ("AXWriteFastPathCalls", 1, 2), ("EnhancedUIToggleCount", 1, 24), ("AppWriteBatch/20", 20, 1), ] { try measure(name, &harness) { try frameWrites(windows: windows, ticks: ticks) } } try measure("FactsReadPerWindow", &harness) { let source = CountingFactsAccess() let facts = try WindowFactsReader.gather( source: source, context: WindowFactsContext(bundleID: "org.example.fixture", activationPolicy: .regular)) return BenchmarkObservation( checksum: source.reads + (facts.isResizable == true ? 1 : 0), proofMetrics: ["fact-access-method-reads": Double(source.reads)]) } let watchdog = AXCallWatchdog(deadline: 1, overdue: { Issue.record("Benchmark watchdog unexpectedly expired") }) defer { watchdog.stop() } measure("WatchdogBeginEnd", &harness) { let token = watchdog.begin() watchdog.end(token) return BenchmarkObservation(checksum: 1) } } static func frameWrites(windows: Int, ticks: Int) throws -> BenchmarkObservation { let application = CountingFrameAccess(.zero) var calls = 0 var positions = 0 var sizes = 0 var nonFinal = 0 var final = 0 for _ in 0.. before else { throw BenchmarkFailure.measurement("engine turn not flushed") } return BenchmarkObservation( checksum: hotPathChecksum(engine.snapshot.state.frames) + streams.count, proofMetrics: [ "subscriber-count": Double(streams.count), "windows": Double(engine.snapshot.state.windows.count), ]) } withExtendedLifetime(streams) {} await engine.stop() } } private static func overlayCases(_ harness: inout BenchmarkHarness) throws { for count in [1, 10, 30] { let fixture = HotPathOverlayFixture(count: count) defer { fixture.stop() } try measure("overlay-update/\(count)", &harness) { try fixture.updatePair() } } let frame = HotPathOverlayFixture(count: 30) defer { frame.stop() } frame.enablePrivacy() measure("overlay-frame/30", &harness) { frame.framePair() } let ghost = HotPathOverlayFixture(count: 50) defer { ghost.stop() } try measure("GhostTransition50", &harness) { try ghost.updatePair(flush: true) } let highlight = HotPathOverlayFixture(count: 10) defer { highlight.stop() } measure("Overlay/HighlightUpdate/10-unchanged", &harness) { highlight.highlight(moved: false) } measure("Overlay/HighlightUpdate/10-moved", &harness) { highlight.highlight(moved: true) } try measure("Overlay/ThemeChange/10-windows", &harness) { try highlight.themePair() } let consume = HotPathOverlayFixture(count: 50) defer { consume.stop() } measure("Overlay/Consume/50-windows", &harness) { consume.consumePair() } measure("Overlay/PrivacyBackdrop/update-8-cutouts", &harness) { highlight.privacyPair() } let chips = StackChipController(focus: { _ in }, close: { _ in }, orderPanels: false) let chipState = HotPathOverlayFixture.chipState() chips.update(state: chipState, configuration: MotionConfiguration(enabled: false)) defer { chips.stop() } measure("Chips/Update/unchanged", &harness) { chips.update(state: chipState, configuration: MotionConfiguration(enabled: false)) precondition(chips.panels.allSatisfy { !$0.isVisible }) return BenchmarkObservation( checksum: chips.groups.count + chips.groups.reduce(0) { $0 + $1.chips.count }, proofMetrics: [ "chip-groups": Double(chips.groups.count), "visible-panels": Double(chips.panels.filter(\.isVisible).count), ]) } let renderer = try MenuIconRenderer() let fixture = HotPathStateFixture(count: 10) let layout = LayoutSnapshot( layout: .grid, bounds: CGRect(x: 0, y: 0, width: 3840, height: 2160), tiles: fixture.ids.map { id in guard let rectangle = fixture.state.frames[id] else { preconditionFailure("Missing icon fixture frame") } return LayoutTile( id: UInt64(id.rawValue), frame: CGRect( x: rectangle.minX, y: rectangle.minY, width: rectangle.size.width, height: rectangle.size.height ), isFocused: id == fixture.ids[0]) }) let icon = MenuIcon(snapshot: layout, style: .minimap) try measure("MenuBar/IconRender", &harness) { guard let bitmap = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: 36, pixelsHigh: 36, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0), let context = NSGraphicsContext(bitmapImageRep: bitmap) else { throw UIResourceError.renderingFailed } NSGraphicsContext.saveGraphicsState() defer { NSGraphicsContext.restoreGraphicsState() } NSGraphicsContext.current = context context.cgContext.scaleBy(x: 2, y: 2) renderer.image(for: icon).draw(in: CGRect(x: 0, y: 0, width: 18, height: 18)) guard let bytes = bitmap.bitmapData else { throw UIResourceError.renderingFailed } let checksum = (0..