From 664bfee2e17de4a05f1e57cc3f34240a81db601a Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 13:23:49 -0400 Subject: [PATCH 01/22] Categorize profiling signposts and record synthetic engine traces --- Sources/ParcelAnimation/Animator.swift | 20 ++ .../ParcelAnimation/DisplayLinkDriver.swift | 19 ++ Sources/ParcelConfig/ConfigStore.swift | 16 ++ Sources/ParcelEngine/EngineEvents.swift | 2 + Sources/ParcelEngine/EngineInterfaces.swift | 2 + Sources/ParcelEngine/EngineMotion.swift | 15 ++ .../ParcelEngine/EngineSystemServices.swift | 38 +-- Sources/ParcelEngine/ParcelEngine.swift | 2 + Sources/ParcelPlatform/Displays.swift | 2 + .../ParcelPlatform/Input/HotKeyCenter.swift | 16 +- .../ParcelPlatform/Input/InputEventTap.swift | 23 ++ Sources/ParcelPlatform/ParcelPlatform.swift | 7 +- .../Spaces/NativeSpaceReader.swift | 4 + .../Tracing/ParcelSignposts.swift | 194 ++++++++++++++++ Sources/ParcelPlatform/WindowServer.swift | 13 +- .../ParcelUI/Overlays/OverlayController.swift | 12 +- .../CategorizedTraceTests.swift | 218 ++++++++++++++++++ 17 files changed, 575 insertions(+), 28 deletions(-) create mode 100644 Sources/ParcelPlatform/Tracing/ParcelSignposts.swift create mode 100644 Tests/ParcelEngineTests/CategorizedTraceTests.swift diff --git a/Sources/ParcelAnimation/Animator.swift b/Sources/ParcelAnimation/Animator.swift index 642c908f..9973db29 100644 --- a/Sources/ParcelAnimation/Animator.swift +++ b/Sources/ParcelAnimation/Animator.swift @@ -1,9 +1,12 @@ +import os + public struct Animator: Sendable { public private(set) var policy: MotionPolicy public private(set) var settings: MotionSettings public private(set) var timestamp: Double? public var isIdle: Bool { plans.isEmpty } public var activeWindowIDs: [MotionWindowID] { plans.keys.sorted() } + public var activeWindowCount: Int { plans.count } private var plans: [MotionWindowID: FramePlan] = [:] private var lastEmission: [MotionWindowID: Double] = [:] private var emissionCount: [MotionWindowID: Int] = [:] @@ -32,11 +35,28 @@ public struct Animator: Sendable { plans[identifier] = plan lastEmission[identifier] = nil emissionCount[identifier] = nil + let signposter = MotionSignposts.signposter + if signposter.isEnabled, plan.duration == 0, plan.request.surface == .window, + plan.request.metrics.isSlow(at: timestamp), + case .animate = policy.behavior(for: .window, level: settings.level) + { + let app = plan.request.appID.rawValue + let reason = plan.request.metrics.lastTimeout.map { timestamp - $0 < 5 } == true ? 2 : 1 + signposter.emitEvent("Snap", "app=\(app, privacy: .public) reason=\(reason, privacy: .public)") + } } self.timestamp = timestamp } public mutating func tick(at timestamp: Double) throws -> [MotionFrame] { + let signposter = MotionSignposts.signposter + let windows = plans.count + let interval = + signposter.isEnabled + ? signposter.beginInterval( + "Sample", id: signposter.makeSignpostID(), "windows=\(windows, privacy: .public)") + : nil + defer { if let interval { signposter.endInterval("Sample", interval) } } try validateTime(timestamp) self.timestamp = timestamp var frames: [MotionFrame] = [] diff --git a/Sources/ParcelAnimation/DisplayLinkDriver.swift b/Sources/ParcelAnimation/DisplayLinkDriver.swift index 356cd60d..3c897327 100644 --- a/Sources/ParcelAnimation/DisplayLinkDriver.swift +++ b/Sources/ParcelAnimation/DisplayLinkDriver.swift @@ -1,5 +1,11 @@ public import AppKit import QuartzCore +import os + +// Animation depends only on Core; matching lanes must not pull in Platform. +enum MotionSignposts { + static let signposter = OSSignposter(subsystem: "com.parcel", category: "Motion") +} @MainActor protocol DisplayLinkSource: AnyObject { @@ -115,6 +121,14 @@ public final class DisplayLinkDriver { private func tick(at timestamp: Double, generation: UInt64) { guard source.isRunning, sourceGeneration == generation else { return } + let signposter = MotionSignposts.signposter + let windows = animator.activeWindowCount + let interval = + signposter.isEnabled + ? signposter.beginInterval( + "Tick", id: signposter.makeSignpostID(), "windows=\(windows, privacy: .public)") + : nil + defer { if let interval { signposter.endInterval("Tick", interval) } } do { let frames = try animator.tick(at: timestamp) refreshSource() @@ -195,6 +209,11 @@ private final class ScreenDisplayLink: DisplayLinkSource { func tick(_ link: CADisplayLink) { guard link === self.link else { return } + let signposter = MotionSignposts.signposter + if signposter.isEnabled { + signposter.emitEvent( + "Display refresh", "interval=\(link.targetTimestamp - link.timestamp, privacy: .public)") + } callback?.tick(from: link, at: link.targetTimestamp) } } diff --git a/Sources/ParcelConfig/ConfigStore.swift b/Sources/ParcelConfig/ConfigStore.swift index 20576716..fead05d8 100644 --- a/Sources/ParcelConfig/ConfigStore.swift +++ b/Sources/ParcelConfig/ConfigStore.swift @@ -1,4 +1,5 @@ public import Foundation +import os public enum ConfigSource: Equatable, Sendable { case defaults @@ -23,6 +24,7 @@ public struct ConfigSnapshot: Sendable { } public actor ConfigStore { + private static let signposter = OSSignposter(subsystem: "com.parcel", category: "Config") public static var defaultFileURL: URL { FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent(".config/parcel/parcel.toml", isDirectory: false) @@ -65,6 +67,20 @@ public actor ConfigStore { @discardableResult public func reload() -> ConfigSnapshot { + let signposter = Self.signposter + let interval = signposter.isEnabled ? signposter.beginInterval("Reload", id: signposter.makeSignpostID()) : nil + defer { + if let interval { + let outcome: Int = + switch snapshot.loadState { + case .notLoaded: 0 + case .loaded: 1 + case .missingFileUsingDefaults: 2 + case .rejected: 3 + } + signposter.endInterval("Reload", interval, "outcome=\(outcome, privacy: .public)") + } + } let contents = ConfigFileContents.read(from: fileURL) previousContents = contents apply(contents) diff --git a/Sources/ParcelEngine/EngineEvents.swift b/Sources/ParcelEngine/EngineEvents.swift index a311cc96..48b0e64c 100644 --- a/Sources/ParcelEngine/EngineEvents.swift +++ b/Sources/ParcelEngine/EngineEvents.swift @@ -182,6 +182,8 @@ extension ParcelEngine { } snapNextPass = false execute(effects) + let publication = emissionTrace.beginIfEnabled(.publish, value: UInt64(subscribers.count), detail: revision) + defer { emissionTrace.endIfStarted(.publish, publication) } for subscriber in subscribers.values { subscriber.yield(snapshot) } } diff --git a/Sources/ParcelEngine/EngineInterfaces.swift b/Sources/ParcelEngine/EngineInterfaces.swift index 4fc61e64..6b50083d 100644 --- a/Sources/ParcelEngine/EngineInterfaces.swift +++ b/Sources/ParcelEngine/EngineInterfaces.swift @@ -253,6 +253,7 @@ public protocol EngineEventRecorder: AnyObject { public protocol EngineTraceSink: AnyObject { var isEnabled: Bool { get } nonisolated var detectionSource: (any DetectionTraceSource)? { get } + var emissionSink: (any ParcelTraceSink)? { get } func begin(_ stage: EngineTraceStage, transaction: UInt64) func end(_ stage: EngineTraceStage, transaction: UInt64) } @@ -260,6 +261,7 @@ public protocol EngineTraceSink: AnyObject { extension EngineTraceSink { public var isEnabled: Bool { true } public nonisolated var detectionSource: (any DetectionTraceSource)? { nil } + public var emissionSink: (any ParcelTraceSink)? { nil } } public struct EngineCommandResult: Sendable, Equatable { diff --git a/Sources/ParcelEngine/EngineMotion.swift b/Sources/ParcelEngine/EngineMotion.swift index 027cc07d..0b23f2a2 100644 --- a/Sources/ParcelEngine/EngineMotion.swift +++ b/Sources/ParcelEngine/EngineMotion.swift @@ -1,6 +1,7 @@ import Foundation import ParcelAnimation import ParcelCore +import ParcelPlatform extension ParcelEngine { func planFrames() { @@ -125,6 +126,12 @@ extension ParcelEngine { func tick(_ display: DisplayID, at timestamp: Double) { guard isRunning, !suspendedDisplays.contains(display) else { return } + let interval = + emissionTrace.emits(.tick) + ? emissionTrace.beginInterval( + .tick, value: UInt64(animators[display]?.activeWindowCount ?? 0), detail: 0) + : nil + defer { emissionTrace.endIfStarted(.tick, interval) } do { guard timestamp.isFinite else { throw MotionError.invalidTimestamp } engineTime = max(timestamp, animationTime) @@ -187,7 +194,15 @@ extension ParcelEngine { openWrites.insert(batch.identifier) trace.begin(.write, transaction: batch.identifier) } + let emissionTrace = emissionTrace + let writeInterval = emissionTrace.beginIfEnabled( + .write, value: UInt64(UInt32(bitPattern: batch.appID.rawValue)), detail: batch.identifier) world.write(writes, for: app) { [weak self] receipt in + if let writeInterval { + let outcome: UInt64 = + receipt.failures.isEmpty ? 0 : receipt.failures.contains(where: \.isTimeout) ? 2 : 1 + emissionTrace.endInterval(.write, writeInterval, value: outcome, detail: batch.identifier) + } guard let self, self.isRunning, self.lifetime == generation, self.activeBatches[batch.appID] == batch.identifier else { return } diff --git a/Sources/ParcelEngine/EngineSystemServices.swift b/Sources/ParcelEngine/EngineSystemServices.swift index 98eac467..5ff1f088 100644 --- a/Sources/ParcelEngine/EngineSystemServices.swift +++ b/Sources/ParcelEngine/EngineSystemServices.swift @@ -68,7 +68,10 @@ public final class ScreenEngineDisplayLink: NSObject, EngineDisplayLink { link = nil callback = nil } - fileprivate func tick(_ link: CADisplayLink) { callback?(link.targetTimestamp) } + fileprivate func tick(_ link: CADisplayLink) { + ParcelSignposts.displayRefresh(interval: link.targetTimestamp - link.timestamp) + callback?(link.targetTimestamp) + } isolated deinit { stop() } } @@ -121,7 +124,7 @@ public final class SystemEngineLog: EngineLogSink { @MainActor public final class SignpostEngineTrace: EngineTraceSink { - private let log = OSLog(subsystem: "com.parcel", category: .pointsOfInterest) + public let emissionSink: (any ParcelTraceSink)? = SignpostTraceSink.shared public let isEnabled: Bool public nonisolated let detectionSource: (any DetectionTraceSource)? public init(enabled: Bool = ProcessInfo.processInfo.environment["PARCEL_TRACE"] == "1") { @@ -129,28 +132,29 @@ public final class SignpostEngineTrace: EngineTraceSink { detectionSource = enabled ? SignpostDetectionTraceSource() : nil } public func begin(_ stage: EngineTraceStage, transaction: UInt64) { - guard isEnabled else { return } - os_signpost(.begin, log: log, name: stage.name, signpostID: OSSignpostID(transaction)) + // The emit-only writer owns receipt intervals, including when bookkeeping is disabled. + guard isEnabled, stage != .write else { return } + ParcelSignposts.beginTransaction(stage.signpost, identifier: transaction) } public func end(_ stage: EngineTraceStage, transaction: UInt64) { - guard isEnabled else { return } - os_signpost(.end, log: log, name: stage.name, signpostID: OSSignpostID(transaction)) + guard isEnabled, stage != .write else { return } + ParcelSignposts.endTransaction(stage.signpost, identifier: transaction) } } extension EngineTraceStage { - fileprivate var name: StaticString { + var signpost: ParcelTraceName { switch self { - case .eventToFirstWrite: "Event to first write" - case .eventToSettled: "Event to settled" - case .detect: "Detect" - case .apply: "Apply" - case .layout: "Layout" - case .diff: "Diff" - case .reduce: "Reduce" - case .plan: "Plan" - case .write: "Write" - case .settle: "Motion settle" + case .eventToFirstWrite: .eventToFirstWrite + case .eventToSettled: .eventToSettled + case .detect: .detect + case .apply: .apply + case .layout: .layout + case .diff: .diff + case .reduce: .reduce + case .plan: .plan + case .write: .write + case .settle: .settle } } } diff --git a/Sources/ParcelEngine/ParcelEngine.swift b/Sources/ParcelEngine/ParcelEngine.swift index 7edfab74..bca3d2e0 100644 --- a/Sources/ParcelEngine/ParcelEngine.swift +++ b/Sources/ParcelEngine/ParcelEngine.swift @@ -79,6 +79,7 @@ public final class ParcelEngine { let announcer: any EngineAnnouncer let log: any EngineLogSink let trace: (any EngineTraceSink)? + let emissionTrace: any ParcelTraceSink let recorder: (any EngineEventRecorder)? var traceCounter: UInt64 = 0 var turnTrace: UInt64? @@ -148,6 +149,7 @@ public final class ParcelEngine { self.log = log self.configSource = configSource self.trace = trace?.isEnabled == true ? trace : nil + self.emissionTrace = trace?.emissionSink ?? SignpostTraceSink.shared self.recorder = recorder self.reduceMotionSource = reduceMotionSource reduceMotion = reduceMotionSource?.isEnabled == true diff --git a/Sources/ParcelPlatform/Displays.swift b/Sources/ParcelPlatform/Displays.swift index fa1fdb2a..49654672 100644 --- a/Sources/ParcelPlatform/Displays.swift +++ b/Sources/ParcelPlatform/Displays.swift @@ -185,6 +185,8 @@ public final class Displays { private func publishChange() { guard !subscribers.isEmpty else { return } + let interval = ParcelSignposts.beginIfEnabled(.displayReconfigure) + defer { ParcelSignposts.endIfStarted(.displayReconfigure, interval) } do { let snapshot = try current() for continuation in subscribers.values { diff --git a/Sources/ParcelPlatform/Input/HotKeyCenter.swift b/Sources/ParcelPlatform/Input/HotKeyCenter.swift index 1994ac38..c4465786 100644 --- a/Sources/ParcelPlatform/Input/HotKeyCenter.swift +++ b/Sources/ParcelPlatform/Input/HotKeyCenter.swift @@ -23,6 +23,7 @@ public final class HotKeyCenter { private let backend: any HotKeyBackend private let onPress: @MainActor (HotKeyPress) -> Void + private let trace: any ParcelTraceSink private let onFailure: @MainActor (InputError) -> Void private let isEventTapInputAllowed: @MainActor () -> Bool private var bindings: [HotKey: Binding] = [:] @@ -46,6 +47,7 @@ public final class HotKeyCenter { init( backend: any HotKeyBackend, onPress: @escaping @MainActor (HotKeyPress) -> Void, onFailure: @escaping @MainActor (InputError) -> Void, + trace: any ParcelTraceSink = SignpostTraceSink.shared, isEventTapInputAllowed: @escaping @MainActor () -> Bool = { true }, scheduleRepeat: @escaping @MainActor (@escaping @MainActor () -> Void) -> (@MainActor () -> Void) = HotKeyCenter .systemRepeat @@ -53,6 +55,7 @@ public final class HotKeyCenter { self.scheduleRepeat = scheduleRepeat self.backend = backend self.onPress = onPress + self.trace = trace self.onFailure = onFailure self.isEventTapInputAllowed = isEventTapInputAllowed backend.onCarbonEvent = { [weak self] id, down in self?.carbonEvent(id: id, down: down) } @@ -189,6 +192,13 @@ public final class HotKeyCenter { return true } + private func dispatch(_ press: HotKeyPress) { + let interval = trace.beginIfEnabled( + .hotkeyDispatch, value: UInt64(press.hotKey.keyCode), detail: press.isRepeat ? 1 : 0) + defer { trace.endIfStarted(.hotkeyDispatch, interval) } + onPress(press) + } + private func carbonEvent(id: UInt32, down: Bool) { guard let binding = bindings.values.first(where: { $0.id == id }) else { return } let key = binding.registration.hotKey @@ -208,10 +218,10 @@ public final class HotKeyCenter { _ = self.carbonState.up(keyCode: key.keyCode) return } - self.onPress(HotKeyPress(hotKey: key, isRepeat: true)) + self.dispatch(HotKeyPress(hotKey: key, isRepeat: true)) } } - onPress(press) + dispatch(press) } else { _ = carbonState.up(keyCode: key.keyCode) repeats.removeValue(forKey: key)?() @@ -237,7 +247,7 @@ public final class HotKeyCenter { let result = tapState.down(key, isRepeat: event.getIntegerValueField(.keyboardEventAutorepeat) != 0) if let press = result.press { if !press.isRepeat { cancelRepeats() } - onPress(press) + dispatch(press) } return result.consume } diff --git a/Sources/ParcelPlatform/Input/InputEventTap.swift b/Sources/ParcelPlatform/Input/InputEventTap.swift index 614bd7f7..139221a8 100644 --- a/Sources/ParcelPlatform/Input/InputEventTap.swift +++ b/Sources/ParcelPlatform/Input/InputEventTap.swift @@ -1,5 +1,6 @@ import AppKit import ApplicationServices +import Darwin import Foundation @MainActor @@ -70,7 +71,29 @@ final class InputEventTap { port = nil } + static func dispatch( + _ type: CGEventType, _ event: CGEvent, trace: any ParcelTraceSink = SignpostTraceSink.shared, + handler: Handler + ) -> Bool { + let interval = trace.beginIfEnabled(.tapCallback, value: UInt64(type.rawValue), detail: event.timestamp) + var consumed = false + defer { trace.endIfStarted(.tapCallback, interval, value: consumed ? 1 : 0) } + if event.timestamp != 0, trace.emits(.inputLatency) { + let now = clock_gettime_nsec_np(CLOCK_UPTIME_RAW) + if now >= event.timestamp { + // Signposts start when emitted; the event clock preserves the queueing latency separately. + trace.event(.inputLatency, value: event.timestamp, detail: now - event.timestamp) + } + } + consumed = handler(type, event) + return consumed + } + func receive(_ type: CGEventType, _ event: CGEvent) -> Bool { + Self.dispatch(type, event) { type, event in handle(type, event) } + } + + private func handle(_ type: CGEventType, _ event: CGEvent) -> Bool { guard port != nil, permissionMonitor?.isTrusted == true else { return false } if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput { guard permissionMonitor?.checkPermission() == true else { return false } diff --git a/Sources/ParcelPlatform/ParcelPlatform.swift b/Sources/ParcelPlatform/ParcelPlatform.swift index 11bb1e0d..736c6cbe 100644 --- a/Sources/ParcelPlatform/ParcelPlatform.swift +++ b/Sources/ParcelPlatform/ParcelPlatform.swift @@ -80,16 +80,13 @@ public final class DetectionTrace: Sendable, Equatable { } public final class SignpostDetectionTraceSource: DetectionTraceSource { - private let signposter = OSSignposter(subsystem: "com.parcel", category: .pointsOfInterest) - public init() {} public func begin() -> DetectionTrace { let startedAt = DispatchTime.now().uptimeNanoseconds - let signposter = self.signposter - let interval = signposter.beginInterval("Detect", id: signposter.makeSignpostID()) + let interval = ParcelSignposts.beginIfEnabled(.detect) return DetectionTrace(startedAt: startedAt) { outcome in - signposter.endInterval("Detect", interval, "\(outcome.rawValue, privacy: .public)") + ParcelSignposts.endIfStarted(.detect, interval, value: outcome == .flushed ? 0 : 1) } } } diff --git a/Sources/ParcelPlatform/Spaces/NativeSpaceReader.swift b/Sources/ParcelPlatform/Spaces/NativeSpaceReader.swift index 81c75a0a..4d878d11 100644 --- a/Sources/ParcelPlatform/Spaces/NativeSpaceReader.swift +++ b/Sources/ParcelPlatform/Spaces/NativeSpaceReader.swift @@ -12,6 +12,8 @@ public struct NativeSpaceReader: SpaceReading { public func spaces(for window: CGWindowID) async throws -> [UInt64] { try await Task.detached { + let interval = ParcelSignposts.beginIfEnabled(.spaceRead, detail: 2) + defer { ParcelSignposts.endIfStarted(.spaceRead, interval) } let symbols = SpaceSymbols.shared let connection = try symbols.connection() let copy = try symbols.function("SLSCopySpacesForWindows", as: CopyWindowSpaces.self) @@ -39,6 +41,8 @@ public struct NativeSpaceReader: SpaceReading { } private static func readSnapshot() throws -> [NativeDisplaySpaces] { + let interval = ParcelSignposts.beginIfEnabled(.spaceRead, detail: 0) + defer { ParcelSignposts.endIfStarted(.spaceRead, interval) } let symbols = SpaceSymbols.shared let connection = try symbols.connection() let copy = try symbols.function("SLSCopyManagedDisplaySpaces", as: CopyDisplaySpaces.self) diff --git a/Sources/ParcelPlatform/Tracing/ParcelSignposts.swift b/Sources/ParcelPlatform/Tracing/ParcelSignposts.swift new file mode 100644 index 00000000..f5d3f9d2 --- /dev/null +++ b/Sources/ParcelPlatform/Tracing/ParcelSignposts.swift @@ -0,0 +1,194 @@ +import os + +public enum ParcelTraceCategory: String, CaseIterable, Sendable { + case engine = "Engine" + case input = "Input" + case motion = "Motion" + case overlay = "Overlay" + case platform = "Platform" + case config = "Config" + case pointsOfInterest = "PointsOfInterest" +} + +public enum ParcelTraceName: CaseIterable, Sendable { + case eventToFirstWrite, eventToSettled, detect, apply, layout, diff, reduce, plan, publish + case tapCallback, hotkeyDispatch, inputLatency + case tick, sample, write, settle, snap + case overlayUpdate, ghostRender + case windowListRead, spaceRead, displayReconfigure + case reload + + public var category: ParcelTraceCategory { + switch self { + case .eventToSettled: .pointsOfInterest + case .eventToFirstWrite, .detect, .apply, .layout, .diff, .reduce, .plan, .publish: .engine + case .tapCallback, .hotkeyDispatch, .inputLatency: .input + case .tick, .sample, .write, .settle, .snap: .motion + case .overlayUpdate, .ghostRender: .overlay + case .windowListRead, .spaceRead, .displayReconfigure: .platform + case .reload: .config + } + } + + public var name: StaticString { + switch self { + case .eventToFirstWrite: "Event to first write" + case .eventToSettled: "Event to settled" + case .detect: "Detect" + case .apply: "Apply" + case .layout: "Layout" + case .diff: "Diff" + case .reduce: "Reduce" + case .plan: "Plan" + case .publish: "Publish" + case .tapCallback: "Tap callback" + case .hotkeyDispatch: "Hotkey dispatch" + case .inputLatency: "Input latency" + case .tick: "Tick" + case .sample: "Sample" + case .write: "Write" + case .settle: "Motion settle" + case .snap: "Snap" + case .overlayUpdate: "Overlay update" + case .ghostRender: "Ghost render" + case .windowListRead: "Window list read" + case .spaceRead: "Space read" + case .displayReconfigure: "Display reconfigure" + case .reload: "Reload" + } + } +} + +public struct ParcelTraceInterval: Sendable { + public let identifier: UInt64 + fileprivate let state: OSSignpostIntervalState? + + public init(identifier: UInt64) { + self.identifier = identifier + state = nil + } + + fileprivate init(identifier: UInt64, state: OSSignpostIntervalState) { + self.identifier = identifier + self.state = state + } +} + +@MainActor +public protocol ParcelTraceSink: AnyObject { + func emits(_ name: ParcelTraceName) -> Bool + func beginInterval(_ name: ParcelTraceName, value: UInt64, detail: UInt64) -> ParcelTraceInterval + func endInterval(_ name: ParcelTraceName, _ interval: ParcelTraceInterval, value: UInt64, detail: UInt64) + func event(_ name: ParcelTraceName, value: UInt64, detail: UInt64) +} + +extension ParcelTraceSink { + public func beginIfEnabled(_ name: ParcelTraceName, value: UInt64 = 0, detail: UInt64 = 0) -> ParcelTraceInterval? { + guard emits(name) else { return nil } + return beginInterval(name, value: value, detail: detail) + } + + public func endIfStarted( + _ name: ParcelTraceName, _ interval: ParcelTraceInterval?, value: UInt64 = 0, detail: UInt64 = 0 + ) { + guard let interval else { return } + endInterval(name, interval, value: value, detail: detail) + } +} + +@MainActor +public final class SignpostTraceSink: ParcelTraceSink { + public static let shared = SignpostTraceSink() + public init() {} + public func emits(_ name: ParcelTraceName) -> Bool { ParcelSignposts.isEnabled(name) } + public func beginInterval(_ name: ParcelTraceName, value: UInt64, detail: UInt64) -> ParcelTraceInterval { + ParcelSignposts.begin(name, value: value, detail: detail) + } + public func endInterval(_ name: ParcelTraceName, _ interval: ParcelTraceInterval, value: UInt64, detail: UInt64) { + ParcelSignposts.endIfStarted(name, interval, value: value, detail: detail) + } + public func event(_ name: ParcelTraceName, value: UInt64, detail: UInt64) { + ParcelSignposts.event(name, value: value, detail: detail) + } +} + +public enum ParcelSignposts { + private struct Lane: Sendable { + let log: OSLog + let signposter: OSSignposter + init(_ category: ParcelTraceCategory) { + log = OSLog(subsystem: "com.parcel", category: category.rawValue) + signposter = OSSignposter(logHandle: log) + } + } + + private static let engine = Lane(.engine) + private static let input = Lane(.input) + private static let motion = Lane(.motion) + private static let overlay = Lane(.overlay) + private static let platform = Lane(.platform) + private static let config = Lane(.config) + private static let pointsOfInterest = Lane(.pointsOfInterest) + + private static func lane(_ category: ParcelTraceCategory) -> Lane { + switch category { + case .engine: engine + case .input: input + case .motion: motion + case .overlay: overlay + case .platform: platform + case .config: config + case .pointsOfInterest: pointsOfInterest + } + } + + public static func isEnabled(_ name: ParcelTraceName) -> Bool { lane(name.category).signposter.isEnabled } + + public static func beginIfEnabled( + _ name: ParcelTraceName, value: UInt64 = 0, detail: UInt64 = 0 + ) -> ParcelTraceInterval? { + guard isEnabled(name) else { return nil } + return begin(name, value: value, detail: detail) + } + + fileprivate static func begin(_ name: ParcelTraceName, value: UInt64, detail: UInt64) -> ParcelTraceInterval { + let signposter = lane(name.category).signposter + let id = signposter.makeSignpostID() + let state = signposter.beginInterval( + name.name, id: id, "value=\(value, privacy: .public) detail=\(detail, privacy: .public)") + return ParcelTraceInterval(identifier: id.rawValue, state: state) + } + + public static func endIfStarted( + _ name: ParcelTraceName, _ interval: ParcelTraceInterval?, value: UInt64 = 0, detail: UInt64 = 0 + ) { + guard let interval else { return } + guard let state = interval.state else { preconditionFailure("A native interval must have a native begin") } + lane(name.category).signposter.endInterval( + name.name, state, "value=\(value, privacy: .public) detail=\(detail, privacy: .public)") + } + + public static func event(_ name: ParcelTraceName, value: UInt64 = 0, detail: UInt64 = 0) { + let signposter = lane(name.category).signposter + guard signposter.isEnabled else { return } + signposter.emitEvent(name.name, "value=\(value, privacy: .public) detail=\(detail, privacy: .public)") + } + + public static func displayRefresh(interval: Double) { + let signposter = motion.signposter + guard signposter.isEnabled else { return } + signposter.emitEvent("Display refresh", "interval=\(interval, privacy: .public)") + } + + public static func beginTransaction(_ name: ParcelTraceName, identifier: UInt64) { + let lane = lane(name.category) + guard lane.signposter.isEnabled else { return } + os_signpost(.begin, log: lane.log, name: name.name, signpostID: OSSignpostID(identifier)) + } + + public static func endTransaction(_ name: ParcelTraceName, identifier: UInt64) { + let lane = lane(name.category) + guard lane.signposter.isEnabled else { return } + os_signpost(.end, log: lane.log, name: name.name, signpostID: OSSignpostID(identifier)) + } +} diff --git a/Sources/ParcelPlatform/WindowServer.swift b/Sources/ParcelPlatform/WindowServer.swift index 22cf45fe..509e0566 100644 --- a/Sources/ParcelPlatform/WindowServer.swift +++ b/Sources/ParcelPlatform/WindowServer.swift @@ -84,14 +84,23 @@ public struct WindowServer: Sendable { options: CGWindowListOption = .optionAll, relativeTo: CGWindowID = kCGNullWindowID ) throws -> [Window] { + let interval = ParcelSignposts.beginIfEnabled(.windowListRead) + var count: UInt64 = 0 + var outcome: UInt64 = 1 + defer { ParcelSignposts.endIfStarted(.windowListRead, interval, value: count, detail: outcome) } guard let records = CGWindowListCopyWindowInfo(options, relativeTo) else { throw ReadError.windowListUnavailable } guard CFGetTypeID(records) == CFArrayGetTypeID() else { throw ReadError.malformedWindowList } - return try Self.decodeWindows(records as NSArray) + let windows = try Self.decodeWindows(records as NSArray) + count = UInt64(windows.count) + outcome = 0 + return windows } public func displaySpaces() throws -> [DisplaySpaces] { + let interval = ParcelSignposts.beginIfEnabled(.spaceRead, detail: 0) + defer { ParcelSignposts.endIfStarted(.spaceRead, interval) } let symbols = RuntimeSymbols.shared guard let connectionPointer = symbols.mainConnection else { throw ReadError.symbolUnavailable("SLSMainConnectionID") @@ -109,6 +118,8 @@ public struct WindowServer: Sendable { } public func currentSpace(displayID: String) throws -> UInt64 { + let interval = ParcelSignposts.beginIfEnabled(.spaceRead, detail: 1) + defer { ParcelSignposts.endIfStarted(.spaceRead, interval) } guard !displayID.isEmpty else { throw ReadError.currentSpaceUnavailable(displayID: displayID) } diff --git a/Sources/ParcelUI/Overlays/OverlayController.swift b/Sources/ParcelUI/Overlays/OverlayController.swift index d0b44004..cdb516e8 100644 --- a/Sources/ParcelUI/Overlays/OverlayController.swift +++ b/Sources/ParcelUI/Overlays/OverlayController.swift @@ -26,6 +26,7 @@ public final class OverlayController { private var nativeProtectedWindows: [String: [OverlayWindow]] = [:] private let dimming: OverlayDimming private let onFailure: @MainActor (any Error) -> Void + private let orderPanels: Bool private var privacyRead: Task? private var privacyRevision: UInt64 = 0 private var nativeDimmingWindows: [OverlayWindow]? @@ -69,6 +70,7 @@ public final class OverlayController { brightness: (any OverlayBrightnessControlling)? = nil, color: @escaping @MainActor () -> NSColor = { .controlAccentColor }, notifications: OverlayNotifications, + orderPanels: Bool = true, onFailure: @escaping @MainActor (any Error) -> Void ) { self.configuration = configuration @@ -76,6 +78,7 @@ public final class OverlayController { self.accessibility = accessibility self.color = color self.onFailure = onFailure + self.orderPanels = orderPanels dimming = OverlayDimming(brightness: brightness ?? PlatformOverlayBrightness(), onFailure: onFailure) dimming.onChange = { [weak self] in self?.renderPrivacy() } dimming.launch(enabled: configuration.enabled && configuration.experimentalDimming) @@ -168,6 +171,8 @@ public final class OverlayController { } public func update(_ next: OverlaySnapshot) { + let interval = ParcelSignposts.beginIfEnabled(.overlayUpdate, value: UInt64(next.windows.count)) + defer { ParcelSignposts.endIfStarted(.overlayUpdate, interval) } if snapshot?.context != next.context { clearTransientLayers() dragTarget = nil @@ -326,7 +331,7 @@ public final class OverlayController { blurred: noPeek && focusModes.noPeekBlur && !solid && !clean, alreadyDimmedFrames: !solid && !clean && dimming.usesCompositor ? windows.filter { offsets[$0.id] == -Float(focusModes.noPeekLevel) }.map(\.focusFrame) : []) - if !privacy.isVisible { privacy.orderFrontRegardless() } + if orderPanels, !privacy.isVisible { privacy.orderFrontRegardless() } if clean { let backdrop = backdrops[id] @@ -337,7 +342,7 @@ public final class OverlayController { backdrop.update( display: panel.display, primaryDisplayHeight: primaryDisplayHeight, color: focusModes.cleanSpaceColor.backdropColor) - if !backdrop.isVisible { backdrop.orderFrontRegardless() } + if orderPanels, !backdrop.isVisible { backdrop.orderFrontRegardless() } } else { backdrops.removeValue(forKey: id)?.close() } @@ -500,6 +505,8 @@ public final class OverlayController { } private func renderGhosts(previous: OverlaySnapshot, next: OverlaySnapshot) { + let interval = ParcelSignposts.beginIfEnabled(.ghostRender, value: UInt64(next.windows.count)) + defer { ParcelSignposts.endIfStarted(.ghostRender, interval) } let old = Dictionary(uniqueKeysWithValues: previous.windows.map { ($0.id, $0) }) let visible = Set(next.windows.map(\.id)) for (display, tiles) in ghostLayers { @@ -575,6 +582,7 @@ public final class OverlayController { } private func refreshPanelVisibility() { + guard orderPanels else { return } for panel in panels.values { if panel.canvas.sublayers?.isEmpty == false { if !panel.isVisible { panel.orderFrontRegardless() } diff --git a/Tests/ParcelEngineTests/CategorizedTraceTests.swift b/Tests/ParcelEngineTests/CategorizedTraceTests.swift new file mode 100644 index 00000000..cf47332e --- /dev/null +++ b/Tests/ParcelEngineTests/CategorizedTraceTests.swift @@ -0,0 +1,218 @@ +import CoreGraphics +import ParcelAnimation +import ParcelCore +import Testing + +@testable import ParcelEngine +@testable import ParcelPlatform + +@MainActor +private final class RecordingTraceSink: EngineTraceSink, ParcelTraceSink { + enum Kind: Equatable { case begin, end, event } + struct Entry: Equatable { + let name: ParcelTraceName + let kind: Kind + let identifier: UInt64 + let value: UInt64 + let detail: UInt64 + } + + let isEnabled: Bool + var emissionsEnabled = true + var emissionSink: (any ParcelTraceSink)? { self } + private var nextIdentifier: UInt64 = 0 + var entries: [Entry] = [] + + init(bookkeeping: Bool = true) { isEnabled = bookkeeping } + func emits(_ name: ParcelTraceName) -> Bool { emissionsEnabled } + func beginInterval(_ name: ParcelTraceName, value: UInt64, detail: UInt64) -> ParcelTraceInterval { + nextIdentifier += 1 + entries.append(Entry(name: name, kind: .begin, identifier: nextIdentifier, value: value, detail: detail)) + return ParcelTraceInterval(identifier: nextIdentifier) + } + func endInterval(_ name: ParcelTraceName, _ interval: ParcelTraceInterval, value: UInt64, detail: UInt64) { + entries.append(Entry(name: name, kind: .end, identifier: interval.identifier, value: value, detail: detail)) + } + func event(_ name: ParcelTraceName, value: UInt64, detail: UInt64) { + entries.append(Entry(name: name, kind: .event, identifier: 0, value: value, detail: detail)) + } + func begin(_ stage: EngineTraceStage, transaction: UInt64) { + entries.append(Entry(name: stage.signpost, kind: .begin, identifier: transaction, value: 0, detail: 0)) + } + func end(_ stage: EngineTraceStage, transaction: UInt64) { + entries.append(Entry(name: stage.signpost, kind: .end, identifier: transaction, value: 0, detail: 0)) + } +} + +@MainActor +private final class TraceHotKeyBackend: HotKeyBackend { + var onCarbonEvent: (@MainActor (UInt32, Bool) -> Void)? + var onTapEvent: (@MainActor (CGEventType, CGEvent) -> Bool)? + var onFailure: (@MainActor (InputError) -> Void)? + func registerCarbon(_ key: HotKey, id: UInt32) throws -> Int32 { 0 } + func unregisterCarbon(id: UInt32) throws {} + func isPressed(_ key: HotKey) -> Bool? { false } + func startTap() throws {} + func stopTap() {} +} + +@MainActor +private struct CategorizedTraceHarness { + let clock = ManualEngineClock() + let scheduler: ManualEngineScheduler + let world: FakeEngineWorld + let links = FakeEngineLinks() + let trace: RecordingTraceSink + let engine: ParcelEngine + + init(bookkeeping: Bool = true, emissions: Bool = true) throws { + trace = RecordingTraceSink(bookkeeping: bookkeeping) + trace.emissionsEnabled = emissions + scheduler = ManualEngineScheduler(clock: clock) + world = FakeEngineWorld(clock: clock) + let links = links + engine = try ParcelEngine( + world: world, clock: clock, scheduler: scheduler, displayLink: { try links.make($0) }, + announcer: FakeEngineAnnouncer(), log: FakeEngineLog(), + configuration: engineConfiguration(glide: true), initialState: engineInitialState(), + trace: trace, reduceMotionSource: nil) + } + + func start() async throws { + try await engine.start() + try scheduler.runReady() + world.appear(engineWindow(1)) + world.appear(engineWindow(2)) + try scheduler.runReady() + clock.now += 2 + links.tickAll(at: clock.now) + try scheduler.runReady() + world.emit(.observed(.focusChanged(WindowID(rawValue: 1)))) + try scheduler.runReady() + trace.entries.removeAll() + } + + func tick(after interval: Double) throws { + clock.now += interval + links.tickAll(at: clock.now) + try scheduler.runReady() + } +} + +@Suite("Categorized tracing") +@MainActor +struct CategorizedTraceTests { + @Test func fixedNamesHaveSeparateHighFrequencyLanes() { + #expect(Set(ParcelTraceName.allCases.map(\.category)) == Set(ParcelTraceCategory.allCases)) + for name in [ParcelTraceName.tapCallback, .hotkeyDispatch, .inputLatency] { + #expect(name.category == .input) + } + for name in [ParcelTraceName.tick, .sample, .write, .settle, .snap] { + #expect(name.category == .motion) + } + #expect(ParcelTraceName.overlayUpdate.category == .overlay) + #expect(ParcelTraceName.ghostRender.category == .overlay) + #expect(ParcelTraceName.eventToSettled.category == .pointsOfInterest) + #expect(EngineTraceStage.reduce.signpost.category == .engine) + #expect(String(describing: EngineTraceStage.eventToFirstWrite.signpost.name) == "Event to first write") + #expect(String(describing: EngineTraceStage.settle.signpost.name) == "Motion settle") + } + + @Test func syntheticHotkeyTraversesTapReducerPlannerDriverAndWriterInOrder() async throws { + let harness = try CategorizedTraceHarness() + try await harness.start() + let backend = TraceHotKeyBackend() + let center = HotKeyCenter( + backend: backend, + onPress: { _ in harness.world.emit(.observed(.commandIssued(.swap(.right)))) }, + onFailure: { error in Issue.record("Unexpected input failure: \(error)") }, trace: harness.trace) + let key = HotKey(keyCode: 0, modifiers: .hyper) + #expect(try center.register(key).route == .eventTap) + let event = try #require(HotKeyPoster.events(for: key).first) + event.timestamp = 1_000_000 + let handler = try #require(backend.onTapEvent) + #expect(InputEventTap.dispatch(.keyDown, event, trace: harness.trace, handler: handler)) + try harness.scheduler.runReady() + let writesBeforeTick = harness.world.writes.count + try harness.tick(after: 1 / 120) + #expect(harness.world.writes.count > writesBeforeTick) + let entries = harness.trace.entries + let tap = try #require(entries.firstIndex { $0.name == .tapCallback && $0.kind == .begin }) + let hotkey = try #require(entries.firstIndex { $0.name == .hotkeyDispatch && $0.kind == .begin }) + let reduce = try #require(entries.firstIndex { $0.name == .reduce && $0.kind == .begin }) + let plan = try #require(entries.firstIndex { $0.name == .plan && $0.kind == .begin }) + let tick = try #require(entries.firstIndex { $0.name == .tick && $0.kind == .begin }) + let write = try #require(entries.firstIndex { $0.name == .write && $0.kind == .begin }) + #expect(tap < hotkey && hotkey < reduce && reduce < plan && plan < tick && tick < write) + #expect(entries[tap].value == UInt64(CGEventType.keyDown.rawValue)) + #expect(entries[tap].detail == event.timestamp) + #expect(entries[tick].value == 2) + #expect(entries.contains { $0.name == .inputLatency && $0.kind == .event && $0.value == event.timestamp }) + #expect(entries.contains { $0.name == .tapCallback && $0.kind == .end && $0.value == 1 }) + #expect(entries.contains { $0.name == .publish && $0.kind == .begin }) + try center.stop() + try harness.tick(after: 2) + await harness.engine.stop() + } + + @Test func emissionsDoNotRequireTransactionBookkeeping() async throws { + let harness = try CategorizedTraceHarness(bookkeeping: false) + try await harness.start() + #expect(harness.engine.trace == nil) + harness.world.emit(.observed(.commandIssued(.swap(.right)))) + try harness.scheduler.runReady() + try harness.tick(after: 1 / 120) + for name in [ParcelTraceName.publish, .tick, .write] { + #expect(harness.trace.entries.contains { $0.name == name && $0.kind == .begin }) + } + #expect(!harness.trace.entries.contains { $0.name == .reduce || $0.name == .plan }) + #expect(harness.engine.traced.isEmpty) + #expect(harness.engine.firstWriteTraces.isEmpty) + #expect(harness.engine.settlingTraces.isEmpty) + #expect(harness.engine.openWrites.isEmpty) + #expect(harness.engine.frameTransactions.isEmpty) + await harness.engine.stop() + } + + @Test func disabledEmissionPreservesInputAndReduceMotionBehavior() async throws { + let harness = try CategorizedTraceHarness(bookkeeping: false, emissions: false) + try await harness.start() + let event = try #require(CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true)) + var calls = 0 + #expect( + InputEventTap.dispatch(.keyDown, event, trace: harness.trace) { _, _ in + calls += 1 + return true + }) + #expect(calls == 1) + harness.world.emit(.observed(.commandIssued(.swap(.right)))) + try harness.scheduler.runReady() + harness.engine.setReduceMotion(true) + try harness.scheduler.runReady() + #expect(harness.engine.isIdle) + #expect(harness.links.runningCount == 0) + #expect(harness.trace.entries.isEmpty) + let write = try #require(harness.world.allWrites.last) + #expect(write.frame == harness.engine.snapshot.state.frames[write.window]) + await harness.engine.stop() + } + + @Test func writeIntervalsEndOnReceiptEvenAfterEngineStops() async throws { + let harness = try CategorizedTraceHarness(bookkeeping: false) + try await harness.start() + harness.world.deferWrites = true + harness.world.emit(.observed(.commandIssued(.swap(.right)))) + try harness.scheduler.runReady() + try harness.tick(after: 1 / 120) + let begin = try #require(harness.trace.entries.last { $0.name == .write && $0.kind == .begin }) + #expect( + !harness.trace.entries.contains { + $0.name == .write && $0.kind == .end && $0.identifier == begin.identifier + }) + await harness.engine.stop() + try harness.world.completeNextWrite() + #expect( + harness.trace.entries.filter { $0.name == .write && $0.kind == .end && $0.identifier == begin.identifier } + .count == 1) + } +} -- knotmirror 0.0.1 From 20f3e6477b4cef61b249dad358e3ec798ec072eb Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 13:26:56 -0400 Subject: [PATCH 02/22] Measure delivered frames, idle work, and long-run footprint --- Sources/FixtureApp/FrameRecorder.swift | 140 +++++++++ Sources/FixtureApp/main.swift | 84 +++++- .../FixtureFrameRecorderTests.swift | 97 ++++++ Tests/ParcelE2ETests/IdleBudgetTests.swift | 147 +++++++++ Tests/ParcelE2ETests/IdleWakeupTests.swift | 33 -- Tests/ParcelE2ETests/ParcelE2ETests.swift | 21 +- .../PerformanceMeasurementSupport.swift | 150 +++++++++ .../PerformanceMeasurementTests.swift | 88 ++++++ .../Smoothness/LatencyTests.swift | 11 + .../Smoothness/SmoothnessMetrics.swift | 127 ++++++++ .../Smoothness/SmoothnessMetricsTests.swift | 80 +++++ .../Smoothness/SmoothnessTests.swift | 284 ++++++++++++++++++ Tests/ParcelE2ETests/SoakTests.swift | 131 ++++++++ 13 files changed, 1352 insertions(+), 41 deletions(-) create mode 100644 Sources/FixtureApp/FrameRecorder.swift create mode 100644 Tests/ParcelE2ETests/FixtureFrameRecorderTests.swift create mode 100644 Tests/ParcelE2ETests/IdleBudgetTests.swift delete mode 100644 Tests/ParcelE2ETests/IdleWakeupTests.swift create mode 100644 Tests/ParcelE2ETests/PerformanceMeasurementSupport.swift create mode 100644 Tests/ParcelE2ETests/PerformanceMeasurementTests.swift create mode 100644 Tests/ParcelE2ETests/Smoothness/LatencyTests.swift create mode 100644 Tests/ParcelE2ETests/Smoothness/SmoothnessMetrics.swift create mode 100644 Tests/ParcelE2ETests/Smoothness/SmoothnessMetricsTests.swift create mode 100644 Tests/ParcelE2ETests/Smoothness/SmoothnessTests.swift create mode 100644 Tests/ParcelE2ETests/SoakTests.swift diff --git a/Sources/FixtureApp/FrameRecorder.swift b/Sources/FixtureApp/FrameRecorder.swift new file mode 100644 index 00000000..374fcae9 --- /dev/null +++ b/Sources/FixtureApp/FrameRecorder.swift @@ -0,0 +1,140 @@ +import AppKit +import Darwin +import QuartzCore +import os + +struct FrameRecord: Codable, Equatable { + enum Kind: String, Codable { case write, vsync, mark } + let timestampNanoseconds: UInt64 + let x: Double + let y: Double + let w: Double + let h: Double + let kind: Kind + var label: String? + var timestamp: Double? + var targetTimestamp: Double? + + private enum CodingKeys: String, CodingKey { + case timestampNanoseconds = "t_ns" + case x, y, w, h, kind, label, timestamp, targetTimestamp + } +} + +struct FrameRecording: Codable { + let window: Int + let records: [FrameRecord] + let refreshIntervalNanoseconds: UInt64 + let overflow: Bool + let clockSource: String + + private enum CodingKeys: String, CodingKey { + case window, records, overflow, clockSource + case refreshIntervalNanoseconds = "refreshInterval_ns" + } +} + +struct FrameRecordRing { + static let capacity = 4_096 + private var storage = [FrameRecord?](repeating: nil, count: capacity) + private var head = 0 + private(set) var count = 0 + private(set) var overflow = false + + mutating func append(_ record: FrameRecord) { + storage[(head + count) % Self.capacity] = record + if count == Self.capacity { + head = (head + 1) % Self.capacity + overflow = true + } else { + count += 1 + } + } + + var records: [FrameRecord] { + (0.. UInt64 { clock_gettime_nsec_np(CLOCK_UPTIME_RAW) } + + func start(window: NSWindow) throws { + guard !isRecording else { throw RecorderError(description: "Recording already active") } + let before = Double(Self.now()) + let media = CACurrentMediaTime() * 1_000_000_000 + let after = Double(Self.now()) + guard media.isFinite, media >= before - 100_000, media <= after + 100_000 else { + throw RecorderError(description: "Display and raw uptime clocks disagree by more than 100 microseconds") + } + ring = FrameRecordRing() + refreshInterval = 0 + self.window = window + isRecording = true + let link = window.displayLink(target: self, selector: #selector(tick(_:))) + self.link = link + link.add(to: .main, forMode: .common) + } + + func stop(index: Int) -> FrameRecording { + link?.invalidate() + link = nil + isRecording = false + window = nil + return FrameRecording( + window: index, records: ring.records, refreshIntervalNanoseconds: refreshInterval, + overflow: ring.overflow, clockSource: "CLOCK_UPTIME_RAW") + } + + func write(frame: NSRect) { + guard isRecording else { return } + append(frame: frame, kind: .write) + if signposter.isEnabled { signposter.emitEvent("Write") } + } + + @discardableResult + func mark(label: String, at timestamp: UInt64) throws -> UInt64 { + guard isRecording, let window else { throw RecorderError(description: "Mark needs an active recording") } + guard !label.isEmpty, label.utf8.count <= 128 else { + throw RecorderError(description: "Mark label must contain 1 through 128 UTF-8 bytes") + } + append(frame: window.frame, kind: .mark, at: timestamp, label: label) + return timestamp + } + + @objc private func tick(_ link: CADisplayLink) { + guard isRecording, link === self.link, let window else { return } + let interval = (link.targetTimestamp - link.timestamp) * 1_000_000_000 + if interval.isFinite, interval > 0 { refreshInterval = UInt64(interval.rounded()) } + append( + frame: window.frame, kind: .vsync, timestamp: link.timestamp, targetTimestamp: link.targetTimestamp) + } + + private func append( + frame: NSRect, kind: FrameRecord.Kind, at time: UInt64 = FrameRecorder.now(), label: String? = nil, + timestamp: Double? = nil, targetTimestamp: Double? = nil + ) { + ring.append( + FrameRecord( + timestampNanoseconds: time, x: frame.minX, y: frame.minY, w: frame.width, h: frame.height, kind: kind, + label: label, timestamp: timestamp, targetTimestamp: targetTimestamp)) + } +} + +private struct RecorderError: Error, CustomStringConvertible { + let description: String +} diff --git a/Sources/FixtureApp/main.swift b/Sources/FixtureApp/main.swift index 73f21c73..80b7ca50 100644 --- a/Sources/FixtureApp/main.swift +++ b/Sources/FixtureApp/main.swift @@ -102,6 +102,7 @@ private struct Control: Decodable { var width: Double? var height: Double? var slowResizeMilliseconds: Int? + var label: String? } private struct ResizeInterval: Encodable { @@ -132,6 +133,14 @@ private struct Reply: Encodable { let windows: [WindowState] let focusedWindow: Int? let error: String? + var recordings: [FrameRecording]? + var markNanoseconds: UInt64? + var overflow = false + + private enum CodingKeys: String, CodingKey { + case id, pid, windows, focusedWindow, error, recordings, overflow + case markNanoseconds = "mark_ns" + } } @MainActor @@ -144,6 +153,7 @@ private final class FixtureWindow: NSWindow { private(set) var clampedWrites = 0 private(set) var slowResizeIntervals: [ResizeInterval] = [] var recordsWrites = false + let frameRecorder = FrameRecorder() var fullscreenTransition = false override func setFrame(_ frameRect: NSRect, display flag: Bool) { @@ -167,6 +177,7 @@ private final class FixtureWindow: NSWindow { } } super.setFrame(requested, display: flag) + frameRecorder.write(frame: frame) } } @@ -178,11 +189,17 @@ private final class FixtureDelegate: NSObject, NSApplicationDelegate, NSWindowDe private var nextIndex = 1 private var inputSource: (any DispatchSourceRead)? private var input = Data() + private var recordingAllWindows = false + private var completedRecordings: [FrameRecording] = [] + private var replyRecordings: [FrameRecording]? + private var replyMark: UInt64? init(options: Options) { self.options = options } func applicationDidFinishLaunching(_ notification: Notification) { - for _ in 0.. FrameRecord { + FrameRecord(timestampNanoseconds: time, x: 0, y: 0, w: 100, h: 100, kind: .write) + } +} + +extension RealAppEndToEndTests { + @Suite struct FixtureFrameRecorderLiveTests { + @Test func controlsArmMarkDisarmAndRetainClosedWindows() async throws { + try await withSession { session in + let (fixture, _) = try await session.addFixture(arguments: [ + "--windows", "2", "--title", "Recorder Fixture", + ]) + _ = try await fixture.control(FixtureControl(action: "record-start", window: 1)) + await #expect(throws: E2EError.self) { + try await fixture.control(FixtureControl(action: "record-start")) + } + let marked = try await fixture.control(FixtureControl(action: "mark", label: "Stimulus")) + let timestamp = try #require(marked.markNanoseconds) + _ = try await fixture.control( + FixtureControl(action: "frame", window: 1, x: 100, y: 100, width: 600, height: 400)) + try await Task.sleep(for: .milliseconds(100)) + _ = try await fixture.control(FixtureControl(action: "close", window: 1)) + let stop = try await fixture.control(FixtureControl(action: "record-stop")) + let recording = try #require(stop.recordings?.first) + #expect(stop.recordings?.count == 1) + #expect(recording.window == 1) + #expect(!recording.overflow) + #expect( + recording.records.contains { + $0.kind == .mark && $0.timestampNanoseconds == timestamp && $0.label == "Stimulus" + }) + #expect(recording.records.contains { $0.kind == .write && $0.timestampNanoseconds >= timestamp }) + #expect(recording.records.contains { $0.kind == .vsync }) + #expect(recording.refreshIntervalNanoseconds > 0) + await #expect(throws: E2EError.self) { + try await fixture.control(FixtureControl(action: "mark", label: "Stopped")) + } + let stoppedAgain = try await fixture.control(FixtureControl(action: "record-stop")) + #expect(stoppedAgain.recordings?.isEmpty == true) + _ = try await fixture.control(FixtureControl(action: "record-start")) + let created = try await fixture.control(FixtureControl(action: "create", title: "Recorder New")) + let index = try #require(created.windows.map(\.index).max()) + _ = try await fixture.control( + FixtureControl(action: "frame", window: index, x: 100, y: 100, width: 500, height: 300)) + let all = try await fixture.control(FixtureControl(action: "record-stop")) + #expect( + all.recordings?.contains { $0.window == index && $0.records.contains { $0.kind == .write } } == true + ) + } + } + } +} diff --git a/Tests/ParcelE2ETests/IdleBudgetTests.swift b/Tests/ParcelE2ETests/IdleBudgetTests.swift new file mode 100644 index 00000000..6136da7d --- /dev/null +++ b/Tests/ParcelE2ETests/IdleBudgetTests.swift @@ -0,0 +1,147 @@ +import Foundation +import ParcelPlatform +import Testing + +struct IdlePhaseReport: Codable { + let phase: String + let skippedReason: String? + let settleSeconds: Int + let observedSeconds: Int + let counters: ProcessPerformanceCounters? + let failures: [String] + let diagnosticArtifacts: [String] +} + +extension RealAppEndToEndTests { + @Suite struct IdleBudgetTests { + @Test func idleInEveryLifecycleState() async throws { + try ProcessPerformanceCounters.verifyInstructionCounter() + try await withSession { session in + let (fixture, _) = try await session.addFixture(arguments: [ + "--windows", "2", "--title", "Idle Fixture", + ]) + try await session.startApp() + _ = try await session.settledWindows(for: fixture, count: 2) + var reports: [IdlePhaseReport] = [] + reports.append(try await measureIdlePhase("settled", session: session)) + _ = try await session.cli(["run", "--json", "e2e-settings-audit"]) + _ = try await fixture.control(FixtureControl(action: "focus", window: 1)) + try await waitUntil("fixture focus after settings close") { + try await session.windows(for: fixture).contains { $0.focused } + } + reports.append(try await measureIdlePhase("settings-closed-fixture-focused", session: session)) + _ = try await session.cli(["reload", "--json"]) + _ = try await session.settledWindows(for: fixture, count: 2) + reports.append(try await measureIdlePhase("config-reloaded", session: session)) + if let reason = try await idleSpacePhase(session: session, fixture: fixture) { + reports.append( + .init( + phase: "space-switched", skippedReason: reason, settleSeconds: 0, observedSeconds: 0, + counters: nil, failures: [], diagnosticArtifacts: [])) + try FileHandle.standardError.write(contentsOf: Data("Skipped idle Space phase: \(reason)\n".utf8)) + } else { + reports.append(try await measureIdlePhase("space-switched", session: session)) + } + try PerformanceArtifacts.write(reports, area: "idle", name: "phases-\(PerformanceArtifacts.host).json") + } + } + } +} + +@MainActor +private func measureIdlePhase(_ phase: String, session: E2ESession) async throws -> IdlePhaseReport { + let process = try #require(session.app) + try await Task.sleep(for: .seconds(5)) + let before = try ProcessPerformanceCounters.read(pid: process.processIdentifier) + let started = ContinuousClock.now + try await Task.sleep(for: .seconds(60)) + guard process.isRunning else { throw E2EError(description: "Parcel exited during idle phase \(phase)") } + let after = try ProcessPerformanceCounters.read(pid: process.processIdentifier) + let observedSeconds = Int(started.duration(to: .now).components.seconds) + let delta = try after.delta(from: before) + let failures = delta.idleBudgetFailures + let artifacts = failures.isEmpty ? [] : try await idleFailureArtifacts(phase: phase, session: session) + let report = IdlePhaseReport( + phase: phase, skippedReason: nil, settleSeconds: 5, + observedSeconds: observedSeconds, + counters: delta, failures: failures, diagnosticArtifacts: artifacts) + let url = try PerformanceArtifacts.write(report, area: "idle", name: "\(phase)-\(PerformanceArtifacts.host).json") + #expect(failures.isEmpty, "\(failures.joined(separator: "; ")); diagnostics: \(artifacts); counters: \(url.path)") + return report +} + +@MainActor +private func idleFailureArtifacts(phase: String, session: E2ESession) async throws -> [String] { + let pid = try #require(session.app).processIdentifier + let directory = try PerformanceArtifacts.directory("idle") + var artifacts: [String] = [] + for (name, executable, arguments) in [ + ("sample", "/usr/bin/sample", [String(pid), "5"]), + ("log", "/usr/bin/log", ["show", "--predicate", "subsystem == \"com.parcel\"", "--last", "70s"]), + ] { + let url = directory.appendingPathComponent("\(phase)-\(name)-\(PerformanceArtifacts.host).txt") + do { + let result = try await runProcess( + executable: URL(fileURLWithPath: executable), arguments: arguments, directory: directory, + timeout: .seconds(20)) + var output = Data("status=\(result.status)\n\(result.errors)\n".utf8) + output.append(result.output) + try output.write(to: url, options: .atomic) + if result.status != 0 { + Issue.record("Idle diagnostic \(name) failed: \(result.errors); artifact: \(url.path)") + } + } catch { + try Data("Diagnostic failed: \(error)\n".utf8).write(to: url, options: .atomic) + Issue.record("Idle diagnostic \(name): \(error)") + } + artifacts.append(url.path) + } + let appLog = directory.appendingPathComponent("\(phase)-app-\(PerformanceArtifacts.host).log") + try Data(contentsOf: session.directory.appendingPathComponent("app.log")).write(to: appLog, options: .atomic) + artifacts.append(appLog.path) + return artifacts +} + +@MainActor +private func idleSpacePhase(session: E2ESession, fixture: FixtureProcess) async throws -> String? { + guard ProcessInfo.processInfo.environment["PARCEL_IDLE_SPACE"] == "1" else { + return "Set PARCEL_IDLE_SPACE=1 to allow a native desktop round trip; no Space was changed." + } + if try await NativeSpaceReader().stageManagerEnabled() { return "Stage Manager is enabled." } + struct Space: Decodable { + let display: String + let active: Bool + let kind: String + let desktopNumber: Int? + private enum CodingKeys: String, CodingKey { + case display, active, kind + case desktopNumber = "desktop_number" + } + } + let windows = try await session.windows(for: fixture) + let workspace = try await session.workspace(for: windows) + let all: [Space] = try await session.query("spaces") + let spaces = all.filter { $0.display == workspace.id.display || $0.display == "Main" } + guard let original = spaces.first(where: \.active)?.desktopNumber, + let target = spaces.first(where: { !$0.active && $0.kind == "desktop" })?.desktopNumber + else { return "The fixture display needs a second numbered native desktop." } + let entries = try SymbolicHotKeys.read() + for number in [original, target] { + let shortcut = SymbolicHotKeys.spaceShortcut(.desktop(number), in: entries) + guard shortcut.isEnabled, shortcut.hotKey != nil else { + return "Enable the native shortcut for desktop \(number)." + } + } + do { + try await session.command("space-focus", String(target)) + try await session.command("space-focus", String(original)) + } catch { + do { try await session.command("space-focus", String(original)) } catch let restore { + throw E2EError(description: "Space switch failed: \(error); original desktop restore failed: \(restore)") + } + throw error + } + _ = try await session.settledWindows(for: fixture, count: 2) + _ = try await fixture.control(FixtureControl(action: "focus", window: 1)) + return nil +} diff --git a/Tests/ParcelE2ETests/IdleWakeupTests.swift b/Tests/ParcelE2ETests/IdleWakeupTests.swift deleted file mode 100644 index 16d83598..00000000 --- a/Tests/ParcelE2ETests/IdleWakeupTests.swift +++ /dev/null @@ -1,33 +0,0 @@ -import Darwin -import Foundation -import Testing - -extension RealAppEndToEndTests { - @Test func settledAppHasFewerThanOneInterruptWakeupPerSecond() async throws { - try await withSession { session in - let (fixture, _) = try await session.addFixture(arguments: ["--windows", "2", "--title", "Idle Fixture"]) - try await session.startApp() - _ = try await session.settledWindows(for: fixture, count: 2) - try await Task.sleep(for: .seconds(2)) - let process = try #require(session.app) - let before = try interruptWakeups(process.processIdentifier) - try await Task.sleep(for: .seconds(15)) - let after = try interruptWakeups(process.processIdentifier) - #expect(after >= before) - if after >= before { - #expect(after - before < 15) - } - } - } -} - -private func interruptWakeups(_ pid: pid_t) throws -> UInt64 { - var usage = rusage_info_v2() - let result = withUnsafeMutablePointer(to: &usage) { pointer in - pointer.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) { - proc_pid_rusage(pid, RUSAGE_INFO_V2, $0) - } - } - guard result == 0 else { throw E2EError(description: "Could not read process wakeups (errno \(errno))") } - return usage.ri_interrupt_wkups -} diff --git a/Tests/ParcelE2ETests/ParcelE2ETests.swift b/Tests/ParcelE2ETests/ParcelE2ETests.swift index 441ad041..f1aa2a6b 100644 --- a/Tests/ParcelE2ETests/ParcelE2ETests.swift +++ b/Tests/ParcelE2ETests/ParcelE2ETests.swift @@ -39,6 +39,14 @@ struct FixtureReply: Decodable { let windows: [FixtureWindowState] let focusedWindow: Int? let error: String? + var recordings: [MeasuredRecording]? + var markNanoseconds: UInt64? + var overflow: Bool? + + private enum CodingKeys: String, CodingKey { + case id, pid, windows, focusedWindow, error, recordings, overflow + case markNanoseconds = "mark_ns" + } } struct FixtureControl: Encodable { @@ -51,6 +59,7 @@ struct FixtureControl: Encodable { var width: Double? var height: Double? var slowResizeMilliseconds: Int? + var label: String? } struct AppConfig: Decodable { @@ -286,16 +295,21 @@ final class FixtureProcess { } func control(_ command: FixtureControl) async throws -> FixtureReply { + try await controlMeasured(command).reply + } + + func controlMeasured(_ command: FixtureControl) async throws -> (reply: FixtureReply, sentAt: UInt64) { guard process.isRunning else { throw E2EError(description: "FixtureApp exited before \(command.action)") } var data = try JSONEncoder().encode(command) data.append(10) + let sentAt = clock_gettime_nsec_np(CLOCK_UPTIME_RAW) try input.fileHandleForWriting.write(contentsOf: data) let reply = try await readReply() guard reply.id == command.id, reply.pid == process.processIdentifier else { throw E2EError(description: "FixtureApp returned a mismatched control acknowledgement") } if let error = reply.error { throw E2EError(description: "FixtureApp control rejected: \(error)") } - return reply + return (reply, sentAt) } func snapshot() async throws -> FixtureReply { try await control(FixtureControl(action: "snapshot")) } @@ -329,8 +343,8 @@ final class FixtureProcess { let count = Darwin.read(descriptor.fd, &bytes, bytes.count) guard count > 0 else { throw E2EError(description: "FixtureApp closed its control output") } pending.append(contentsOf: bytes.prefix(count)) - guard pending.count <= 65_536 else { - throw E2EError(description: "FixtureApp reply exceeded 65536 bytes") + guard pending.count <= 33_554_432 else { + throw E2EError(description: "FixtureApp reply exceeded 32 MiB") } } else { guard process.isRunning else { @@ -893,6 +907,7 @@ private enum E2EAvailability { ) return false } + try validatePerformanceScenarioSelection(environment: environment) var trusted = false try await withSession { session in try await session.startApp() diff --git a/Tests/ParcelE2ETests/PerformanceMeasurementSupport.swift b/Tests/ParcelE2ETests/PerformanceMeasurementSupport.swift new file mode 100644 index 00000000..c6244fb7 --- /dev/null +++ b/Tests/ParcelE2ETests/PerformanceMeasurementSupport.swift @@ -0,0 +1,150 @@ +import Darwin +import Foundation +import Testing +import os + +@testable import ParcelIPC + +struct PerformanceQuietState: Codable { + let eligible: Bool + let loadAverage: Double + let acPower: Bool + let thermalWarning: Bool + let maximumProcessCPU: Double + let lowPowerMode: Bool + let reasons: [String] + + static func load(environment: [String: String] = ProcessInfo.processInfo.environment) throws -> Self? { + guard let path = environment["PARCEL_BENCH_QUIET"] else { return nil } + return try JSONDecoder().decode(Self.self, from: Data(contentsOf: URL(fileURLWithPath: path))) + } +} + +enum PerformanceArtifacts { + static var host: String { + ProcessInfo.processInfo.hostName.map { $0.isLetter || $0.isNumber || $0 == "-" ? $0 : "-" } + .reduce(into: "") { $0.append($1) } + } + + static func directory(_ area: String) throws -> URL { + let root = + ProcessInfo.processInfo.environment["PARCEL_PERF_OUTPUT"].map { URL(fileURLWithPath: $0) } + ?? repositoryRoot().appendingPathComponent("build") + let directory = root.appendingPathComponent(area, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + return directory + } + + @discardableResult + static func write(_ value: Value, area: String, name: String) throws -> URL { + let url = try directory(area).appendingPathComponent(name) + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + try encoder.encode(value).write(to: url, options: .atomic) + return url + } +} + +struct TimedIPCResult { + let sentAt: UInt64 + let response: IPCResponse +} + +@MainActor +func measuredIPC(session: E2ESession, command: String, args: [String] = []) async throws -> TimedIPCResult { + let descriptor = try makeSocket() + let channel = SocketChannel(descriptor: descriptor) + do { + try await channel.connect(path: session.socketURL.path) + let request = IPCRequest(command: command, args: args) + let data = try IPCCodec.encode(request) + // Encode and connect before timing; process launch time is not command latency. + let sentAt = clock_gettime_nsec_np(CLOCK_UPTIME_RAW) + let count = data.withUnsafeBytes { bytes in + guard let base = bytes.baseAddress else { return 0 } + return Darwin.send(descriptor, base, bytes.count, 0) + } + guard count == data.count else { throw E2EError(description: "Measured IPC send was incomplete: \(errno)") } + let signposter = OSSignposter(subsystem: "com.parcel.e2e", category: "pointsOfInterest") + signposter.emitEvent("Stimulus", "sent_ns=\(sentAt, privacy: .public)") + let response = try await withThrowingTaskGroup(of: IPCResponse.self) { group in + group.addTask { + guard let line = try await channel.readLine() else { throw IPCTransportError.closed } + return try IPCCodec.decode(IPCResponse.self, from: line) + } + group.addTask { + try await Task.sleep(for: .seconds(10)) + await channel.close() + throw E2EError(description: "Measured IPC response timed out") + } + defer { group.cancelAll() } + guard let response = try await group.next() else { + throw E2EError(description: "Measured IPC response task ended without a result") + } + return response + } + await channel.close() + guard response.id == request.id, response.v == IPCProtocol.version, response.ok else { + throw E2EError(description: "Measured IPC rejected \(command): \(String(describing: response.error))") + } + return TimedIPCResult(sentAt: sentAt, response: response) + } catch { + await channel.close() + throw error + } +} + +struct ProcessPerformanceCounters: Codable, Equatable { + let cpuNanoseconds: UInt64 + let instructions: UInt64 + let interruptWakeups: UInt64 + let packageIdleWakeups: UInt64 + let physicalFootprint: UInt64 + + static func read(pid: pid_t) throws -> Self { + var usage = rusage_info_v4() + let result = withUnsafeMutablePointer(to: &usage) { pointer in + pointer.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) { + proc_pid_rusage(pid, RUSAGE_INFO_V4, $0) + } + } + guard result == 0 else { + throw E2EError(description: "Process counters unavailable for \(pid): errno \(errno)") + } + return Self( + cpuNanoseconds: usage.ri_user_time + usage.ri_system_time, instructions: usage.ri_instructions, + interruptWakeups: usage.ri_interrupt_wkups, packageIdleWakeups: usage.ri_pkg_idle_wkups, + physicalFootprint: usage.ri_phys_footprint) + } + + @inline(never) + static func verifyInstructionCounter() throws { + let before = try read(pid: getpid()) + var total: UInt64 = 0 + for value in 0..<100_000 { total &+= UInt64(value) &* 17 } + guard total == 84_999_150_000, try read(pid: getpid()).instructions > before.instructions else { + throw E2EError( + description: "Public retired-instruction counter unavailable; idle instructions cannot be gated") + } + } + + func delta(from previous: Self) throws -> Self { + guard cpuNanoseconds >= previous.cpuNanoseconds, instructions >= previous.instructions, + interruptWakeups >= previous.interruptWakeups, packageIdleWakeups >= previous.packageIdleWakeups + else { throw E2EError(description: "Process performance counters moved backwards") } + return Self( + cpuNanoseconds: cpuNanoseconds - previous.cpuNanoseconds, + instructions: instructions - previous.instructions, + interruptWakeups: interruptWakeups - previous.interruptWakeups, + packageIdleWakeups: packageIdleWakeups - previous.packageIdleWakeups, physicalFootprint: physicalFootprint) + } + + var idleBudgetFailures: [String] { + var failures: [String] = [] + if cpuNanoseconds >= 5_000_000 { failures.append("CPU time must be <5 ms: \(cpuNanoseconds) ns") } + if instructions >= 5_000_000 { failures.append("Instructions must be <5M: \(instructions)") } + if interruptWakeups > 2 { failures.append("Interrupt wakeups must be <=2: \(interruptWakeups)") } + if packageIdleWakeups > 2 { failures.append("Package idle wakeups must be <=2: \(packageIdleWakeups)") } + return failures + } +} diff --git a/Tests/ParcelE2ETests/PerformanceMeasurementTests.swift b/Tests/ParcelE2ETests/PerformanceMeasurementTests.swift new file mode 100644 index 00000000..d1c2724f --- /dev/null +++ b/Tests/ParcelE2ETests/PerformanceMeasurementTests.swift @@ -0,0 +1,88 @@ +import Darwin +import Foundation +import Testing + +@Suite struct PerformanceMeasurementTests { + @Test func idleBudgetsAreStrictAndCountersCannotMoveBackwards() throws { + let zero = counters() + #expect(zero.idleBudgetFailures.isEmpty) + #expect(counters(cpu: 4_999_999, instructions: 4_999_999, interrupt: 2, package: 2).idleBudgetFailures.isEmpty) + #expect(counters(cpu: 5_000_000).idleBudgetFailures.count == 1) + #expect(counters(instructions: 5_000_000).idleBudgetFailures.count == 1) + #expect(counters(interrupt: 3).idleBudgetFailures.count == 1) + #expect(counters(package: 3).idleBudgetFailures.count == 1) + #expect( + try counters(cpu: 10, instructions: 20, interrupt: 2, package: 1).delta(from: zero) + == counters(cpu: 10, instructions: 20, interrupt: 2, package: 1)) + #expect(throws: E2EError.self) { try zero.delta(from: counters(cpu: 1)) } + #expect(throws: E2EError.self) { try zero.delta(from: counters(instructions: 1)) } + #expect(throws: E2EError.self) { try zero.delta(from: counters(interrupt: 1)) } + #expect(throws: E2EError.self) { try zero.delta(from: counters(package: 1)) } + } + + @Test func publicInstructionCounterAdvancesForKnownWork() throws { + #if arch(arm64) + let before = try ProcessPerformanceCounters.read(pid: getpid()) + var total: UInt64 = 0 + for value in 0..<100_000 { total &+= UInt64(value) &* 17 } + #expect(total == 84_999_150_000) + let after = try ProcessPerformanceCounters.read(pid: getpid()) + #expect(after.instructions > before.instructions, "Public retired-instruction counters unavailable") + #endif + } + + @Test func tailFootprintSlopeUsesCommandSpacingAndRejectsMalformedSamples() throws { + let samples = (0..<20).map { FootprintSample(commands: $0 * 100, bytes: UInt64(1_000_000 + $0 * 400_000)) } + #expect(try footprintSlope(Array(samples.suffix(10))) == 4_000) + #expect( + try footprintSlope(samples.map { .init(commands: $0.commands, bytes: 10_000_000 - $0.bytes) }) == -4_000) + #expect(throws: E2EError.self) { try footprintSlope([]) } + #expect(throws: E2EError.self) { try footprintSlope([samples[0], samples[0]]) } + #expect(throws: E2EError.self) { try footprintSlope([samples[1], samples[0]]) } + #expect(soakBudgetFailures(finalBytes: 39_999_999, slope: 8_191).isEmpty) + #expect(soakBudgetFailures(finalBytes: 40_000_000, slope: 8_192).count == 2) + #expect(soakBudgetFailures(finalBytes: 1, slope: .nan).count == 1) + } + + @Test func quietEvidenceIsRequiredAndMalformedEvidenceIsNotIgnored() throws { + #expect(try PerformanceQuietState.load(environment: [:]) == nil) + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString) + let state = PerformanceQuietState( + eligible: true, loadAverage: 0.5, acPower: true, thermalWarning: false, maximumProcessCPU: 2, + lowPowerMode: false, reasons: []) + try JSONEncoder().encode(state).write(to: url) + defer { + do { try FileManager.default.removeItem(at: url) } catch { Issue.record(error) } + } + #expect(try PerformanceQuietState.load(environment: ["PARCEL_BENCH_QUIET": url.path])?.eligible == true) + try Data("not JSON".utf8).write(to: url) + #expect(throws: DecodingError.self) { + try PerformanceQuietState.load(environment: ["PARCEL_BENCH_QUIET": url.path]) + } + } + + @Test func exactScenarioSelectionRejectsTyposAndDoesNotMatchOtherScenarios() throws { + for scenario in LivePerformanceScenario.allCases { + #expect(try scenario.selected(environment: [:])) + for selected in LivePerformanceScenario.allCases { + #expect( + try scenario.selected(environment: ["PARCEL_SMOOTHNESS_SCENARIO": selected.rawValue]) + == (scenario == selected)) + } + } + #expect(throws: E2EError.self) { + try validatePerformanceScenarioSelection(environment: ["PARCEL_SMOOTHNESS_SCENARIO": "unknown"]) + } + #expect(throws: E2EError.self) { + try validatePerformanceScenarioSelection(environment: ["PARCEL_SMOOTHNESS_SCENARIO": ""]) + } + } + + private func counters(cpu: UInt64 = 0, instructions: UInt64 = 0, interrupt: UInt64 = 0, package: UInt64 = 0) + -> ProcessPerformanceCounters + { + .init( + cpuNanoseconds: cpu, instructions: instructions, interruptWakeups: interrupt, packageIdleWakeups: package, + physicalFootprint: 1_000) + } +} diff --git a/Tests/ParcelE2ETests/Smoothness/LatencyTests.swift b/Tests/ParcelE2ETests/Smoothness/LatencyTests.swift new file mode 100644 index 00000000..51990a0d --- /dev/null +++ b/Tests/ParcelE2ETests/Smoothness/LatencyTests.swift @@ -0,0 +1,11 @@ +import Testing + +extension RealAppEndToEndTests { + @Suite struct LatencyTests { + @Test(arguments: [LivePerformanceScenario.hotkey, .newWindow]) + func twentyRepeatedInputs(_ scenario: LivePerformanceScenario) async throws { + guard try scenario.selected() else { return } + _ = try await runPerformanceScenario(scenario) + } + } +} diff --git a/Tests/ParcelE2ETests/Smoothness/SmoothnessMetrics.swift b/Tests/ParcelE2ETests/Smoothness/SmoothnessMetrics.swift new file mode 100644 index 00000000..99f46805 --- /dev/null +++ b/Tests/ParcelE2ETests/Smoothness/SmoothnessMetrics.swift @@ -0,0 +1,127 @@ +import Foundation + +struct MeasuredFrame: Codable, Equatable { + enum Kind: String, Codable { case write, vsync, mark } + let timestampNanoseconds: UInt64 + let x: Double + let y: Double + let w: Double + let h: Double + let kind: Kind + var label: String? + var timestamp: Double? + var targetTimestamp: Double? + + private enum CodingKeys: String, CodingKey { + case timestampNanoseconds = "t_ns" + case x, y, w, h, kind, label, timestamp, targetTimestamp + } + + var components: [Double] { [x, y, w, h] } + func distance(to other: Self) -> Double { + zip(components, other.components).reduce(0) { $0 + pow($1.0 - $1.1, 2) }.squareRoot() + } +} + +struct MeasuredRecording: Codable { + let window: Int + let records: [MeasuredFrame] + let refreshIntervalNanoseconds: UInt64 + let overflow: Bool + let clockSource: String + + private enum CodingKeys: String, CodingKey { + case window, records, overflow, clockSource + case refreshIntervalNanoseconds = "refreshInterval_ns" + } +} + +struct SmoothnessMetrics: Codable { + let refreshIntervalNanoseconds: UInt64 + let refreshes: Int + let starvedRefreshes: Int + let dropRate: Double + let maxGapRefreshes: Double + let jank: Double + let inputToFirstMoveNanoseconds: UInt64 + let settle90Nanoseconds: UInt64 + let settleFinalNanoseconds: UInt64 + let overshootPoints: Double + let writesPerRefresh: Double + let maximumWritesPerRefresh: Int + + static func measure(_ recording: MeasuredRecording, stimulus: UInt64) throws -> Self { + guard !recording.overflow else { throw E2EError(description: "Fixture frame ring overflowed") } + guard recording.clockSource == "CLOCK_UPTIME_RAW" else { + throw E2EError(description: "Unsupported fixture timestamp source: \(recording.clockSource)") + } + let records = recording.records + guard records.allSatisfy({ $0.components.allSatisfy(\.isFinite) }), + zip(records, records.dropFirst()).allSatisfy({ $0.timestampNanoseconds <= $1.timestampNanoseconds }) + else { throw E2EError(description: "Nonfinite geometry or nonmonotonic recording") } + let interval = recording.refreshIntervalNanoseconds + guard interval > 0 else { throw E2EError(description: "No display refresh interval was recorded") } + let writes = records.filter { $0.kind == .write && $0.timestampNanoseconds >= stimulus } + guard let firstWrite = writes.first, let last = writes.last else { + throw E2EError(description: "No fixture frame write followed the stimulus") + } + let start = records.last { $0.kind == .mark && $0.timestampNanoseconds <= stimulus } ?? firstWrite + let moving = writes.filter { $0.distance(to: start) > 0.01 } + let first = moving.first ?? firstWrite + guard first.timestampNanoseconds >= stimulus else { throw E2EError(description: "Stimulus follows first move") } + let ticks = records.filter { $0.kind == .vsync } + guard ticks.count >= 2 else { throw E2EError(description: "Recording needs at least two display refreshes") } + let motionTicks = ticks.filter { + $0.timestampNanoseconds >= first.timestampNanoseconds + && $0.timestampNanoseconds <= last.timestampNanoseconds + } + var starved = 0 + var maximumWrites = 0 + var totalWrites = 0 + for tick in motionTicks { + let previous = + ticks.last { $0.timestampNanoseconds < tick.timestampNanoseconds }?.timestampNanoseconds + ?? first.timestampNanoseconds + let count = writes.filter { + $0.timestampNanoseconds > previous && $0.timestampNanoseconds <= tick.timestampNanoseconds + }.count + if count == 0 { starved += 1 } + maximumWrites = max(maximumWrites, count) + totalWrites += count + } + let gaps = zip(writes, writes.dropFirst()).map { + Double($1.timestampNanoseconds - $0.timestampNanoseconds) / Double(interval) + } + let delta = zip(start.components, last.components).map { $1 - $0 } + let squaredDistance = delta.reduce(0) { $0 + $1 * $1 } + func progress(_ frame: MeasuredFrame) -> Double { + guard squaredDistance > 0 else { return 1 } + return zip(zip(frame.components, start.components), delta).reduce(0) { + $0 + ($1.0.0 - $1.0.1) * $1.1 + } / squaredDistance + } + let ninety = writes.first { progress($0) >= 0.9 } ?? last + let overshoot = writes.map { max(0, progress($0) - 1) * squaredDistance.squareRoot() }.max() ?? 0 + return Self( + refreshIntervalNanoseconds: interval, refreshes: motionTicks.count, starvedRefreshes: starved, + dropRate: motionTicks.isEmpty ? 0 : Double(starved) / Double(motionTicks.count), + maxGapRefreshes: gaps.max() ?? 0, + jank: gaps.isEmpty ? 0 : Double(gaps.filter { $0 > 1.5 }.count) / Double(gaps.count), + inputToFirstMoveNanoseconds: first.timestampNanoseconds - stimulus, + settle90Nanoseconds: ninety.timestampNanoseconds - stimulus, + settleFinalNanoseconds: last.timestampNanoseconds - stimulus, overshootPoints: overshoot, + writesPerRefresh: motionTicks.isEmpty ? 0 : Double(totalWrites) / Double(motionTicks.count), + maximumWritesPerRefresh: maximumWrites) + } +} + +func measurementPercentile(_ values: [Double], _ percentile: Double) throws -> Double { + guard !values.isEmpty, values.allSatisfy(\.isFinite), (0...1).contains(percentile) else { + throw E2EError(description: "Percentile needs finite samples and a probability") + } + let sorted = values.sorted() + let rank = Double(sorted.count - 1) * percentile + let lower = Int(rank.rounded(.down)) + let upper = Int(rank.rounded(.up)) + return sorted[lower] + (sorted[upper] - sorted[lower]) * (rank - Double(lower)) +} diff --git a/Tests/ParcelE2ETests/Smoothness/SmoothnessMetricsTests.swift b/Tests/ParcelE2ETests/Smoothness/SmoothnessMetricsTests.swift new file mode 100644 index 00000000..f926ba9b --- /dev/null +++ b/Tests/ParcelE2ETests/Smoothness/SmoothnessMetricsTests.swift @@ -0,0 +1,80 @@ +import Foundation +import Testing + +@Suite struct SmoothnessMetricsTests { + @Test func syntheticTraceMeasuresStarvationJankAndSettling() throws { + let metrics = try SmoothnessMetrics.measure(trace(), stimulus: 0) + #expect(metrics.refreshes == 3) + #expect(metrics.starvedRefreshes == 1) + #expect(abs(metrics.dropRate - 1.0 / 3) < 1e-12) + #expect(metrics.maxGapRefreshes == 2) + #expect(metrics.jank == 0.5) + #expect(metrics.inputToFirstMoveNanoseconds == 10) + #expect(metrics.settle90Nanoseconds == 20) + #expect(metrics.settleFinalNanoseconds == 40) + #expect(metrics.overshootPoints == 0) + #expect(metrics.maximumWritesPerRefresh == 1) + } + + @Test func overshootAndWastedWritesAreVisible() throws { + let recording = MeasuredRecording( + window: 1, + records: [ + frame(0, 0, .mark), frame(5, 10, .vsync), frame(10, 120), frame(11, 120), + frame(15, 120, .vsync), frame(20, 100), frame(25, 100, .vsync), + ], + refreshIntervalNanoseconds: 10, overflow: false, clockSource: "CLOCK_UPTIME_RAW") + let metrics = try SmoothnessMetrics.measure(recording, stimulus: 0) + #expect(abs(metrics.overshootPoints - 20) < 1e-12) + #expect(metrics.maximumWritesPerRefresh == 2) + #expect(metrics.writesPerRefresh == 2) + } + + @Test func unchangedWriteIsNotFirstVisibleMove() throws { + let recording = MeasuredRecording( + window: 1, + records: [frame(0, 0, .mark), frame(5, 0, .vsync), frame(10, 0), frame(20, 100), frame(25, 100, .vsync)], + refreshIntervalNanoseconds: 10, overflow: false, clockSource: "CLOCK_UPTIME_RAW") + #expect(try SmoothnessMetrics.measure(recording, stimulus: 0).inputToFirstMoveNanoseconds == 20) + } + + @Test func malformedAndOverflowedTracesFailRatherThanReportZero() { + for recording in [ + trace(overflow: true), trace(interval: 0), trace(clock: "unknown"), + MeasuredRecording( + window: 1, records: [], refreshIntervalNanoseconds: 10, overflow: false, clockSource: "CLOCK_UPTIME_RAW" + ), + MeasuredRecording( + window: 1, records: [frame(20, 1), frame(10, 2)], refreshIntervalNanoseconds: 10, + overflow: false, clockSource: "CLOCK_UPTIME_RAW"), + MeasuredRecording( + window: 1, records: [frame(10, .nan)], refreshIntervalNanoseconds: 10, + overflow: false, clockSource: "CLOCK_UPTIME_RAW"), + ] { + #expect(throws: E2EError.self) { try SmoothnessMetrics.measure(recording, stimulus: 0) } + } + } + + @Test func percentilesUseEveryRepeatAndRejectEmptySamples() throws { + #expect(try measurementPercentile([0, 10, 20, 30], 0.5) == 15) + #expect(abs(try measurementPercentile([0, 10, 20, 30], 0.95) - 28.5) < 1e-12) + #expect(throws: E2EError.self) { try measurementPercentile([], 0.5) } + #expect(throws: E2EError.self) { try measurementPercentile([.infinity], 0.5) } + } + + private func trace(overflow: Bool = false, interval: UInt64 = 10, clock: String = "CLOCK_UPTIME_RAW") + -> MeasuredRecording + { + MeasuredRecording( + window: 1, + records: [ + frame(0, 0, .mark), frame(5, 0, .vsync), frame(10, 10), frame(15, 10, .vsync), + frame(20, 90), frame(25, 90, .vsync), frame(35, 90, .vsync), frame(40, 100), frame(45, 100, .vsync), + ], + refreshIntervalNanoseconds: interval, overflow: overflow, clockSource: clock) + } + + private func frame(_ time: UInt64, _ x: Double, _ kind: MeasuredFrame.Kind = .write) -> MeasuredFrame { + MeasuredFrame(timestampNanoseconds: time, x: x, y: 0, w: 100, h: 100, kind: kind) + } +} diff --git a/Tests/ParcelE2ETests/Smoothness/SmoothnessTests.swift b/Tests/ParcelE2ETests/Smoothness/SmoothnessTests.swift new file mode 100644 index 00000000..e252defd --- /dev/null +++ b/Tests/ParcelE2ETests/Smoothness/SmoothnessTests.swift @@ -0,0 +1,284 @@ +import Darwin +import Foundation +import ParcelCore +import Testing + +@testable import ParcelIPC + +enum LivePerformanceScenario: String, CaseIterable, Codable { + case swap = "swap-2-windows" + case layout10 = "layout-change-10" + case layout30 = "layout-change-30" + case hotkey = "hotkey-focus-move" + case slow = "slow-neighbour" + case newWindow = "new-window-to-tile" + + func selected(environment: [String: String] = ProcessInfo.processInfo.environment) throws -> Bool { + try validatePerformanceScenarioSelection(environment: environment) + return environment["PARCEL_SMOOTHNESS_SCENARIO"].map { $0 == rawValue } ?? true + } +} + +func validatePerformanceScenarioSelection(environment: [String: String]) throws { + if let value = environment["PARCEL_SMOOTHNESS_SCENARIO"], LivePerformanceScenario(rawValue: value) == nil { + throw E2EError(description: "Unknown PARCEL_SMOOTHNESS_SCENARIO: \(value)") + } +} + +struct SmoothnessRun: Codable { + struct Window: Codable { + let pid: Int32 + let recording: MeasuredRecording + let metrics: SmoothnessMetrics? + } + let iteration: Int + let stimulusNanoseconds: UInt64 + let stimulusSource: String + let windows: [Window] +} + +struct SmoothnessReport: Codable { + let schemaVersion: Int + let scenario: LivePerformanceScenario + let host: String + let quiet: PerformanceQuietState? + let gated: Bool + let recordingProxy: String + let runs: [SmoothnessRun] + let inputP50Nanoseconds: Double + let inputP95Nanoseconds: Double + let settleP50Nanoseconds: Double + let settleP95Nanoseconds: Double + let failures: [String] +} + +extension RealAppEndToEndTests { + @Suite struct SmoothnessTests { + @Test(arguments: [LivePerformanceScenario.swap, .layout10, .layout30, .slow]) + func twentyRepeatedCommands(_ scenario: LivePerformanceScenario) async throws { + guard try scenario.selected() else { return } + let baseline = scenario == .slow ? try await runPerformanceScenario(.swap) : nil + _ = try await runPerformanceScenario(scenario, baseline: baseline) + } + } +} + +@MainActor +@discardableResult +func runPerformanceScenario(_ scenario: LivePerformanceScenario, baseline: SmoothnessReport? = nil) async throws + -> SmoothnessReport +{ + let quiet = try PerformanceQuietState.load() + let gated = quiet?.eligible == true && scenario != .layout30 + var runs: [SmoothnessRun] = [] + var configuration = E2EConfiguration(layout: .side, ratio: 0.65, motion: true, transition: "glide") + if scenario == .layout10 || scenario == .layout30 { configuration.layout = .grid } + if scenario == .hotkey { configuration.layout = .accordion } + try await withSession(configuration: configuration) { session in + var fixtures: [(process: FixtureProcess, count: Int)] = [] + if scenario == .layout30 { + for index in 0..<3 { + let (fixture, _) = try await session.addFixture(arguments: [ + "--windows", "10", "--title", "Performance Group \(index)", + ]) + fixtures.append((fixture, 10)) + } + } else if scenario == .slow { + let (normal, _) = try await session.addFixture(arguments: [ + "--windows", "1", "--title", "Normal Performance", + ]) + let (slow, _) = try await session.addFixture(arguments: [ + "--windows", "1", "--title", "Slow Performance", "--slow-resize", "60", + ]) + fixtures = [(normal, 1), (slow, 1)] + } else { + let count = scenario == .layout10 ? 10 : (scenario == .newWindow ? 1 : 2) + let (fixture, _) = try await session.addFixture(arguments: [ + "--windows", String(count), "--title", "Performance Fixture", + ]) + fixtures = [(fixture, count)] + } + try await session.startApp() + for fixture in fixtures { _ = try await session.settledWindows(for: fixture.process, count: fixture.count) } + let firstFixture = try #require(fixtures.first?.process) + for iteration in 0..<20 { + _ = try await firstFixture.control(FixtureControl(action: "focus", window: 1)) + try await waitUntil("fixture focus before performance stimulus") { + try await session.windows(for: firstFixture).contains { $0.focused } + } + for fixture in fixtures { + _ = try await session.settledWindows(for: fixture.process, count: fixture.count) + _ = try await fixture.process.control(FixtureControl(action: "record-start")) + } + try await Task.sleep(for: .milliseconds(80)) + for fixture in fixtures { + _ = try await fixture.process.control(FixtureControl(action: "mark", label: "Stimulus")) + } + var createdIndex: Int? + let stimulus: UInt64 + let source: String + switch scenario { + case .newWindow: + let created = try await firstFixture.controlMeasured( + FixtureControl(action: "create", title: "Performance New")) + stimulus = created.sentAt + source = "fixture-control-send/CLOCK_UPTIME_RAW" + guard let index = created.reply.windows.map(\.index).max() else { + throw E2EError(description: "Fixture create returned no window") + } + createdIndex = index + case .hotkey: + let state = try await firstFixture.snapshot() + let window = try #require(state.windows.first { $0.index == 1 }) + let result = try await measuredIPC( + session: session, command: "run", args: ["e2e-key", String(window.number), "focus-right"]) + struct KeyResult: Decodable { + let accepted: Bool + let eventTimestampNanoseconds: UInt64 + private enum CodingKeys: String, CodingKey { + case accepted + case eventTimestampNanoseconds = "event_timestamp_ns" + } + } + let key = try JSONDecoder().decode(KeyResult.self, from: JSONEncoder().encode(result.response.result)) + guard key.accepted, key.eventTimestampNanoseconds >= result.sentAt, + key.eventTimestampNanoseconds <= clock_gettime_nsec_np(CLOCK_UPTIME_RAW) + else { throw E2EError(description: "CGEvent and raw uptime clocks disagree or hotkey was rejected") } + stimulus = key.eventTimestampNanoseconds + source = "CGEvent.timestamp" + case .layout10, .layout30: + stimulus = try await measuredIPC( + session: session, command: "run", args: [iteration.isMultiple(of: 2) ? "layout-bsp" : "layout-grid"] + ).sentAt + source = "IPC-send/CLOCK_UPTIME_RAW" + case .swap, .slow: + let windows = try await session.windows(for: firstFixture) + let all: [AppWindow] = try await session.query("windows") + let focused = try #require(windows.first { $0.focused }) + let target = try #require( + all.first { !$0.floating && $0.id != focused.id && $0.workspace == focused.workspace }) + let direction = + try #require(target.frame).minX > #require(focused.frame).minX ? "swap-right" : "swap-left" + stimulus = try await measuredIPC(session: session, command: "run", args: [direction]).sentAt + source = "IPC-send/CLOCK_UPTIME_RAW" + } + // Do not query Parcel or poll geometry while recording the command. + try await Task.sleep(for: .milliseconds(700)) + var raw: [SmoothnessRun.Window] = [] + for fixture in fixtures { + let stopped = try await fixture.process.control(FixtureControl(action: "record-stop")) + for recording in try #require(stopped.recordings) { + raw.append( + .init(pid: fixture.process.process.processIdentifier, recording: recording, metrics: nil)) + } + } + let rawURL = try PerformanceArtifacts.write( + SmoothnessRun( + iteration: iteration, stimulusNanoseconds: stimulus, stimulusSource: source, windows: raw), + area: "smoothness", name: "raw-\(scenario.rawValue)-\(PerformanceArtifacts.host)-\(iteration).json") + let captured = try raw.map { window -> SmoothnessRun.Window in + let recording = window.recording + guard !recording.overflow else { + throw E2EError(description: "Frame ring overflow in \(scenario.rawValue); raw: \(rawURL.path)") + } + let start = recording.records.last { $0.kind == .mark && $0.timestampNanoseconds <= stimulus } + let changed = recording.records.contains { frame in + frame.kind == .write && frame.timestampNanoseconds >= stimulus + && (start.map { frame.distance(to: $0) > 0.01 } ?? true) + } + let selected = scenario != .newWindow || recording.window == createdIndex + let normal = scenario != .slow || window.pid == firstFixture.process.processIdentifier + let metric = + changed && selected && normal ? try SmoothnessMetrics.measure(recording, stimulus: stimulus) : nil + return .init(pid: window.pid, recording: recording, metrics: metric) + } + guard captured.contains(where: { $0.metrics != nil }) else { + throw E2EError(description: "Scenario \(scenario.rawValue) delivered no measured frame changes") + } + runs.append( + .init(iteration: iteration, stimulusNanoseconds: stimulus, stimulusSource: source, windows: captured)) + if let createdIndex { + _ = try await session.settledWindows(for: firstFixture, count: 2) + _ = try await firstFixture.control(FixtureControl(action: "close", window: createdIndex)) + } + for fixture in fixtures { _ = try await session.settledWindows(for: fixture.process, count: fixture.count) } + } + } + let input = runs.compactMap { run in + run.windows.compactMap(\.metrics).map { Double($0.inputToFirstMoveNanoseconds) }.max() + } + let settle = runs.compactMap { run in + run.windows.compactMap(\.metrics).map { Double($0.settleFinalNanoseconds) }.max() + } + let input50 = try measurementPercentile(input, 0.5) + let input95 = try measurementPercentile(input, 0.95) + var failures = performanceBudgetFailures(scenario: scenario, runs: runs, input50: input50, input95: input95) + if scenario == .slow, let baseline, input50 > baseline.inputP50Nanoseconds + 2_000_000 { + failures.append("Normal neighbour p50 first move exceeds swap baseline by >2 ms") + } + let report = SmoothnessReport( + schemaVersion: 1, scenario: scenario, host: PerformanceArtifacts.host, quiet: quiet, gated: gated, + recordingProxy: "Fixture-delivered AX frames; compositor-side hitches are not measured", runs: runs, + inputP50Nanoseconds: input50, inputP95Nanoseconds: input95, + settleP50Nanoseconds: try measurementPercentile(settle, 0.5), + settleP95Nanoseconds: try measurementPercentile(settle, 0.95), failures: failures) + let url = try PerformanceArtifacts.write( + report, area: "smoothness", name: "\(scenario.rawValue)-\(PerformanceArtifacts.host).json") + try FileHandle.standardError.write( + contentsOf: Data( + "\(scenario.rawValue): 20 repeats, input p50/p95 \(input50 / 1e6)/\(input95 / 1e6) ms; \(gated ? "gated" : "report-only"), \(url.path)\n" + .utf8)) + if gated { #expect(failures.isEmpty, "\(failures.joined(separator: "; ")); raw artifact: \(url.path)") } + return report +} + +func performanceBudgetFailures( + scenario: LivePerformanceScenario, runs: [SmoothnessRun], input50: Double, input95: Double +) -> [String] { + let metrics = runs.flatMap { $0.windows.compactMap(\.metrics) } + var failures: [String] = [] + let interval = metrics.map { Double($0.refreshIntervalNanoseconds) }.max() ?? 0 + switch scenario { + case .swap, .slow: + if runs.contains(where: { $0.windows.compactMap(\.metrics).reduce(0) { $0 + $1.starvedRefreshes } > 1 }) { + failures.append("More than one starved refresh per swap") + } + if input50 > interval { failures.append("Input p50 exceeds one display frame") } + if input95 > interval * 2 { failures.append("Input p95 exceeds two display frames") } + if metrics.contains(where: { $0.settleFinalNanoseconds > 250_000_000 }) { + failures.append("Settle exceeds250 ms") + } + case .layout10: + let refreshes = metrics.reduce(0) { $0 + $1.refreshes } + let starved = metrics.reduce(0) { $0 + $1.starvedRefreshes } + if refreshes > 0, Double(starved) / Double(refreshes) > 0.02 { + failures.append("Starved refresh rate exceeds2%") + } + if metrics.contains(where: { $0.maxGapRefreshes > 2 }) { failures.append("Write gap exceeds two refreshes") } + case .layout30: + let refreshes = metrics.reduce(0) { $0 + $1.refreshes } + let starved = metrics.reduce(0) { $0 + $1.starvedRefreshes } + if refreshes > 0, Double(starved) / Double(refreshes) > 0.05 { + failures.append("Reported starved refresh rate exceeds5%") + } + case .hotkey: + if input50 > interval + 2_000_000 { + failures.append("Hotkey input p50 exceeds one frame plus2 ms write latency") + } + case .newWindow: + if input50 > 8_000_000 || input95 > 16_000_000 { + failures.append("New-window first-write p50/p95 exceeds8/16 ms") + } + let settles = metrics.map { Double($0.settleFinalNanoseconds) } + do { + if try measurementPercentile(settles, 0.5) > 20_000_000 || measurementPercentile(settles, 0.95) > 40_000_000 + { + failures.append("New-window tile p50/p95 exceeds20/40 ms") + } + } catch { failures.append("Invalid settle samples: \(error)") } + } + if metrics.contains(where: { $0.overshootPoints > 1 }) { + failures.append("Delivered frames overshoot target by >1 point") + } + return failures +} diff --git a/Tests/ParcelE2ETests/SoakTests.swift b/Tests/ParcelE2ETests/SoakTests.swift new file mode 100644 index 00000000..654b569a --- /dev/null +++ b/Tests/ParcelE2ETests/SoakTests.swift @@ -0,0 +1,131 @@ +import Foundation +import Testing + +struct FootprintSample: Codable, Equatable { + let commands: Int + let bytes: UInt64 +} + +struct SoakReport: Codable { + let schemaVersion: Int + let host: String + let windowCount: Int + let commands: Int + let sampleEveryCommands: Int + let samples: [FootprintSample] + let tailSlopeBytesPerCommand: Double + let finalFootprintBytes: UInt64 + let failures: [String] +} + +func footprintSlope(_ samples: [FootprintSample]) throws -> Double { + guard samples.count >= 2, zip(samples, samples.dropFirst()).allSatisfy({ $0.commands < $1.commands }) else { + throw E2EError(description: "Footprint regression needs ordered distinct command samples") + } + let count = Double(samples.count) + let meanX = samples.reduce(0) { $0 + Double($1.commands) } / count + let meanY = samples.reduce(0) { $0 + Double($1.bytes) } / count + let numerator = samples.reduce(0) { $0 + (Double($1.commands) - meanX) * (Double($1.bytes) - meanY) } + let denominator = samples.reduce(0) { $0 + pow(Double($1.commands) - meanX, 2) } + return numerator / denominator +} + +func soakBudgetFailures(finalBytes: UInt64, slope: Double) -> [String] { + var failures: [String] = [] + if finalBytes >= 40_000_000 { failures.append("Final physical footprint must be <40 MB: \(finalBytes) bytes") } + if !slope.isFinite || slope >= 8_192 { failures.append("Last10-sample slope must be <8 KiB/command: \(slope)") } + return failures +} + +extension RealAppEndToEndTests { + @Suite(.enabled(if: ProcessInfo.processInfo.environment["PARCEL_SOAK"] == "1")) + struct SoakTests { + @Test func thirtyWindowsTwoThousandCommands() async throws { + try await withSession(configuration: E2EConfiguration(layout: .grid)) { session in + let (fixture, _) = try await session.addFixture(arguments: [ + "--windows", "30", "--title", "Soak Fixture", + ]) + try await session.startApp() + _ = try await session.settledWindows(for: fixture, count: 30) + let process = try #require(session.app) + var samples = [ + FootprintSample( + commands: 0, + bytes: try ProcessPerformanceCounters.read(pid: process.processIdentifier).physicalFootprint) + ] + var transient: Int? + for command in 1...2_000 { + switch (command - 1) % 10 { + case 3: + let reply = try await fixture.control(FixtureControl(action: "create", title: "Soak Transient")) + guard let index = reply.windows.map(\.index).max() else { + throw E2EError(description: "Soak create returned no window") + } + transient = index + _ = try await session.settledWindows(for: fixture, count: 31) + case 4: + guard let index = transient else { + throw E2EError(description: "Soak lost its transient window") + } + _ = try await fixture.control(FixtureControl(action: "close", window: index)) + transient = nil + _ = try await session.settledWindows(for: fixture, count: 30) + default: + let names = [ + 0: "focus-right", 1: "swap-left", 2: "layout-bsp", 5: "focus-left", + 6: "swap-right", 7: "layout-grid", 8: "focus-down", 9: "focus-up", + ] + let name = try #require(names[(command - 1) % 10]) + let result = try await measuredIPC(session: session, command: "run", args: [name]) + struct Accepted: Decodable { let accepted: Bool } + let accepted = try JSONDecoder().decode( + Accepted.self, from: JSONEncoder().encode(result.response.result)) + guard accepted.accepted else { + throw E2EError(description: "Soak command \(name) was rejected") + } + } + if command.isMultiple(of: 100) { + _ = try await session.settledWindows(for: fixture, count: 30) + samples.append( + .init( + commands: command, + bytes: try ProcessPerformanceCounters.read(pid: process.processIdentifier) + .physicalFootprint)) + } + } + let final = try #require(samples.last).bytes + let slope = try footprintSlope(Array(samples.suffix(10))) + let failures = soakBudgetFailures(finalBytes: final, slope: slope) + let report = SoakReport( + schemaVersion: 1, host: PerformanceArtifacts.host, windowCount: 30, commands: 2_000, + sampleEveryCommands: 100, samples: samples, tailSlopeBytesPerCommand: slope, + finalFootprintBytes: final, failures: failures) + let url = try PerformanceArtifacts.write(report, area: "soak", name: "footprint.json") + #expect(failures.isEmpty, "\(failures.joined(separator: "; ")); artifact: \(url.path)") + try await awaitOwnedLeakInspection(session: session) + } + } + } +} + +@MainActor +private func awaitOwnedLeakInspection(session: E2ESession) async throws { + let environment = ProcessInfo.processInfo.environment + guard environment["PARCEL_LEAK_PID_FILE"] != nil || environment["PARCEL_LEAK_CONTINUE_FILE"] != nil else { return } + guard let pidPath = environment["PARCEL_LEAK_PID_FILE"], let continuePath = environment["PARCEL_LEAK_CONTINUE_FILE"] + else { + throw E2EError(description: "Leak inspection needs both PARCEL_LEAK_PID_FILE and PARCEL_LEAK_CONTINUE_FILE") + } + let process = try #require(session.app) + guard process.isRunning else { throw E2EError(description: "Harness-owned Parcel exited before leak inspection") } + guard !FileManager.default.fileExists(atPath: pidPath), !FileManager.default.fileExists(atPath: continuePath) else { + throw E2EError(description: "Leak handshake paths must be fresh; refusing stale PID or continuation") + } + try Data("\(process.processIdentifier)\n".utf8).write(to: URL(fileURLWithPath: pidPath), options: .atomic) + try await waitUntil("leak inspector continuation", timeout: .seconds(120)) { + guard process.isRunning else { + throw E2EError(description: "Harness-owned Parcel exited during leak inspection") + } + return FileManager.default.fileExists(atPath: continuePath) + } +} -- knotmirror 0.0.1 From 2839c31d2b74edfae036b6b77eb9bfacef107956 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 13:29:11 -0400 Subject: [PATCH 03/22] Gate benchmarks on verified instruction counts --- .github/workflows/ci.yml | 2 + Package.swift | 13 +- Scripts/bench-identity.py | 40 ++ Scripts/bench.sh | 23 +- Scripts/tests/bench.sh | 68 ++- .../BenchmarkAllocations.swift | 36 ++ .../BenchmarkBaselines.swift | 149 +++-- .../BenchmarkCounters.swift | 143 +++++ .../BenchmarkHarness.swift | 519 ++++++++++++------ .../BenchmarkRegressionProbeTests.swift | 56 ++ .../PerformanceBenchmarks.swift | 51 +- .../PerformanceBudgetTests.swift | 15 +- 12 files changed, 824 insertions(+), 291 deletions(-) create mode 100644 Scripts/bench-identity.py create mode 100644 Tests/ParcelPerformanceTests/BenchmarkAllocations.swift create mode 100644 Tests/ParcelPerformanceTests/BenchmarkCounters.swift create mode 100644 Tests/ParcelPerformanceTests/BenchmarkRegressionProbeTests.swift diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fc783e9f..d6e82355 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,6 +23,7 @@ jobs: timeout-minutes: 45 env: HOMEBREW_NO_AUTO_UPDATE: '1' + PARCEL_BENCH_SMOKE: '1' steps: - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 with: @@ -52,6 +53,7 @@ jobs: source Scripts/product.env unset "${PRODUCT_ENV_PREFIX}_E2E" "${PRODUCT_ENV_PREFIX}_E2E_PREFLIGHT_ONLY" printf '%s\n' 'Live-window e2e is disabled. CI requests neither Accessibility nor Screen Recording.' + printf '%s\n' 'Hosted CI runs benchmark smoke mode only; it does not certify performance budgets.' swift test for script in Scripts/tests/*.sh; do "$script"; done - name: Swift formatting and name checks diff --git a/Package.swift b/Package.swift index 85b2e319..bc42f62f 100644 --- a/Package.swift +++ b/Package.swift @@ -89,9 +89,18 @@ let package = Package( name: "ParcelPerformanceTests", dependencies: [ "ParcelCore", "ParcelConfig", "ParcelEngine", "ParcelIPC", "ParcelUI", "ParcelAnimation", - "ParcelTestSupport", + "ParcelPlatform", "ParcelTestSupport", ], - swiftSettings: strict), + exclude: ProcessInfo.processInfo.environment["PARCEL_BENCH_CORE_ONLY"] == "1" + ? [ + "HotPathBenchmarks.swift", "HotPathFixtures.swift", "HotPathNativeFixtures.swift", + "BenchmarkCatalog.swift", "HotPathBenchmarkTests.swift", "Fixtures", + ] : [], + resources: ProcessInfo.processInfo.environment["PARCEL_BENCH_CORE_ONLY"] == "1" + ? [] : [.copy("Fixtures")], + swiftSettings: strict + + (ProcessInfo.processInfo.environment["PARCEL_BENCH_CORE_ONLY"] == "1" + ? [.define("PARCEL_BENCH_CORE_ONLY")] : [])), .testTarget( name: "ParcelUITests", dependencies: ["ParcelUI", "ParcelConfig", "ParcelAnimation", "ParcelTestSupport"]), .testTarget(name: "ParcelIPCTests", dependencies: ["ParcelIPC", "ParcelEngine", "prcl"]), diff --git a/Scripts/bench-identity.py b/Scripts/bench-identity.py new file mode 100644 index 00000000..8bb6ad8f --- /dev/null +++ b/Scripts/bench-identity.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +import hashlib +import plistlib +import re +import subprocess +import sys +import uuid + + +def command(*args): + return subprocess.check_output(args, text=True).strip() + + +def identity(): + host = command("scutil", "--get", "LocalHostName") + model = command("sysctl", "-n", "hw.model") + cores = command("sysctl", "-n", "hw.ncpu") + records = plistlib.loads(subprocess.check_output( + ["ioreg", "-a", "-r", "-d", "1", "-c", "IOPlatformExpertDevice"])) + platform = str(uuid.UUID(records[0]["IOPlatformUUID"])).upper() + if not re.fullmatch(r"[A-Za-z0-9,._-]+", host) or not re.fullmatch(r"[A-Za-z0-9,._-]+", model): + raise ValueError("unsafe host or hardware model") + if not re.fullmatch(r"[1-9][0-9]*", cores): + raise ValueError("invalid CPU count") + digest = hashlib.sha256(platform.encode()).hexdigest()[:8] + return f"{host}-{digest}-{model}-{cores}.json" + + +def main(): + try: + print(identity()) + except (OSError, ValueError, KeyError, IndexError, TypeError, plistlib.InvalidFileException, + subprocess.CalledProcessError) as error: + print(f"Cannot determine benchmark host identity: {error}", file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/Scripts/bench.sh b/Scripts/bench.sh index 3ea4d9d6..061dc0f3 100755 --- a/Scripts/bench.sh +++ b/Scripts/bench.sh @@ -7,23 +7,28 @@ output=${2:-build/bench-results.json} baseline=${3:-} calibrate=${4:-0} case "$mode" in compare|record) ;; *) printf 'Choose compare or record.\n' >&2; exit 2 ;; esac -case "$calibrate" in 0|1) ;; *) printf 'BENCH_CALIBRATE must be 0 or 1.\n' >&2; exit 2 ;; esac -model=$(sysctl -n hw.model) -cores=$(sysctl -n hw.ncpu) -if [[ -z $model || $model == *[!a-zA-Z0-9,._-]* || -z $cores || $cores == *[!0-9]* || $cores == 0 ]]; then - printf 'Cannot determine a safe hardware model and CPU count.\n' >&2 +if [[ $calibrate != 0 ]]; then + printf 'Calibration scaling is no longer supported; retired instructions are the gate.\n' >&2 exit 2 fi -baseline=${baseline:-Benchmarks/baselines/$model-$cores.json} +identity=$(python3 -I Scripts/bench-identity.py) +baseline=${baseline:-Benchmarks/baselines/$identity} if [[ $mode == compare && ! -f $baseline ]]; then printf 'no baseline for this machine, run make bench-record on a quiet machine\nExpected: %s\n' "$baseline" >&2 exit 1 fi +quiet=build/bench-quiet.json +status=0 +Scripts/quiet-check.sh --output "$quiet" || status=$? +if [[ $status != 0 ]]; then + if [[ $status != 3 || $mode == record || ${BENCH_STRICT_QUIET:-0} == 1 ]]; then exit "$status"; fi + printf 'Host is not quiet: instruction gate only; CPU/time budgets are diagnostic.\n' +fi record=0 if [[ $mode == record ]]; then record=1 - printf 'Recording %s. Use a quiet machine and review the result before committing.\n' "$baseline" + printf 'Recording %s. Review the host conditions and results before committing.\n' "$baseline" fi -PARCEL_BENCH=1 PARCEL_BENCH_RECORD="$record" PARCEL_BENCH_OUTPUT="$output" \ - PARCEL_BENCH_BASELINE="$baseline" PARCEL_BENCH_CALIBRATE="$calibrate" \ +SWIFT_DETERMINISTIC_HASHING=1 PARCEL_BENCH=1 PARCEL_BENCH_RECORD="$record" PARCEL_BENCH_OUTPUT="$output" \ + PARCEL_BENCH_BASELINE="$baseline" PARCEL_BENCH_QUIET="$quiet" \ swift test -c release --no-parallel --filter PerformanceBenchmarks diff --git a/Scripts/tests/bench.sh b/Scripts/tests/bench.sh index b6727e8f..9084fb8c 100755 --- a/Scripts/tests/bench.sh +++ b/Scripts/tests/bench.sh @@ -1,71 +1,87 @@ #!/bin/bash set -euo pipefail - cd "$(dirname "$0")/../.." work=$(mktemp -d "${TMPDIR:-/tmp}/parcel benchmark tests.XXXXXX") trap 'rm -rf "$work"' EXIT mkdir -p "$work/project/Scripts" "$work/project/Benchmarks/baselines" "$work/bin" -cp Scripts/bench.sh "$work/project/Scripts/" +cp Scripts/bench.sh Scripts/bench-identity.py "$work/project/Scripts/" cp Makefile "$work/project/" cat > "$work/bin/sysctl" <<'MOCK' #!/bin/bash set -euo pipefail [[ ${TEST_SYSCTL_FAIL:-0} == 0 ]] || exit 7 case "$*" in - '-n hw.model') printf '%s\n' "${TEST_MODEL-Mac15,10}" ;; + '-n hw.model') printf '%s\n' "${TEST_MODEL-Mac}" ;; '-n hw.ncpu') printf '%s\n' "${TEST_CORES:-14}" ;; *) exit 2 ;; esac MOCK +cat > "$work/bin/scutil" <<'MOCK' +#!/bin/bash +printf '%s\n' "${TEST_HOST-test}" +MOCK +cat > "$work/bin/ioreg" <<'MOCK' +#!/bin/bash +printf 'IOPlatformUUID%s\n' "${TEST_UUID-00000000-0000-4000-8000-000000000001}" +MOCK +cat > "$work/project/Scripts/quiet-check.sh" <<'MOCK' +#!/bin/bash +set -euo pipefail +mkdir -p "$(dirname "$2")" +printf '{"eligible":true}\n' > "$2" +exit "${TEST_QUIET_STATUS:-0}" +MOCK cat > "$work/bin/swift" <<'MOCK' #!/bin/bash set -euo pipefail -printf '%s|%s|%s|%s|%s\n' "$*" "$PARCEL_BENCH_BASELINE" "$PARCEL_BENCH_OUTPUT" \ - "$PARCEL_BENCH_RECORD" "$PARCEL_BENCH_CALIBRATE" >> "$TEST_SWIFT_LOG" +printf '%s|%s|%s|%s|%s|%s\n' "$*" "$PARCEL_BENCH_BASELINE" "$PARCEL_BENCH_OUTPUT" \ + "$PARCEL_BENCH_RECORD" "$PARCEL_BENCH_QUIET" "$SWIFT_DETERMINISTIC_HASHING" >> "$TEST_SWIFT_LOG" exit "${TEST_SWIFT_STATUS:-0}" MOCK -chmod +x "$work/bin/"* +chmod +x "$work/bin/"* "$work/project/Scripts/quiet-check.sh" export PATH="$work/bin:$PATH" TEST_SWIFT_LOG="$work/swift.log" runner="$work/project/Scripts/bench.sh" +identity=$(python3 -I Scripts/bench-identity.py) count=0 check() { - if ! "$@"; then - printf 'Benchmark runner check failed: %s\n' "$*" >&2 - exit 1 - fi + if ! "$@"; then printf 'Benchmark runner check failed: %s\n' "$*" >&2; exit 1; fi count=$((count + 1)) } fails() { - if "$@" > "$work/failure.log" 2>&1; then - printf 'Expected a benchmark runner failure: %s\n' "$*" >&2 - return 1 - fi + if "$@" > "$work/failure.log" 2>&1; then printf 'Expected failure: %s\n' "$*" >&2; return 1; fi } check fails make -C "$work/project" bench check grep -Fq 'no baseline for this machine, run make bench-record on a quiet machine' "$work/failure.log" -check grep -Fq 'Benchmarks/baselines/Mac15,10-14.json' "$work/failure.log" +check grep -Fq "Benchmarks/baselines/$identity" "$work/failure.log" check test ! -e "$TEST_SWIFT_LOG" - -# A report for a different machine is never selected. -printf '{}\n' > "$work/project/Benchmarks/baselines/Mac16,1-10.json" +printf '{}\n' > "$work/project/Benchmarks/baselines/another-host-Mac-14.json" check fails "$runner" compare check test ! -e "$TEST_SWIFT_LOG" -printf '{}\n' > "$work/project/Benchmarks/baselines/Mac15,10-14.json" +printf '{}\n' > "$work/project/Benchmarks/baselines/$identity" check make -C "$work/project" bench -check grep -Fq 'test -c release --no-parallel --filter PerformanceBenchmarks|Benchmarks/baselines/Mac15,10-14.json|build/bench-results.json|0|0' "$TEST_SWIFT_LOG" -check make -C "$work/project" bench-record BENCH_OUTPUT='build/candidate file.json' BENCH_CALIBRATE=1 -check grep -Fq '|Benchmarks/baselines/Mac15,10-14.json|build/candidate file.json|1|1' "$TEST_SWIFT_LOG" +check grep -Fq "test -c release --no-parallel --filter PerformanceBenchmarks|Benchmarks/baselines/$identity|build/bench-results.json|0|build/bench-quiet.json|1" "$TEST_SWIFT_LOG" +check make -C "$work/project" bench-record BENCH_OUTPUT='build/candidate file.json' +check grep -Fq '|build/candidate file.json|1|' "$TEST_SWIFT_LOG" check make -C "$work/project" bench-record BENCH_BASELINE='custom baseline.json' -check grep -Fq '|custom baseline.json|build/bench-results.json|1|0' "$TEST_SWIFT_LOG" -check fails "$runner" compare 'build/out.json' 'missing explicit.json' -check grep -Fq 'missing explicit.json' "$work/failure.log" +check grep -Fq '|custom baseline.json|build/bench-results.json|1|' "$TEST_SWIFT_LOG" +check fails env TEST_QUIET_STATUS=3 "$runner" record +check fails env TEST_QUIET_STATUS=3 BENCH_STRICT_QUIET=1 "$runner" compare +check env TEST_QUIET_STATUS=3 "$runner" compare +check fails env TEST_QUIET_STATUS=2 "$runner" compare +check fails "$runner" compare build/out.json missing-explicit.json +check grep -Fq 'missing-explicit.json' "$work/failure.log" check fails env TEST_MODEL=../escape "$runner" record check fails env TEST_MODEL= "$runner" record +check fails env TEST_HOST=../escape "$runner" record +check fails env TEST_UUID=invalid "$runner" record check fails env TEST_CORES=0 "$runner" record check fails env TEST_CORES=invalid "$runner" record check fails env TEST_SYSCTL_FAIL=1 "$runner" record check fails "$runner" invalid -check fails "$runner" record build/out.json '' invalid +check fails "$runner" record build/out.json '' 1 check fails env TEST_SWIFT_STATUS=7 "$runner" compare check fails env TEST_SWIFT_STATUS=7 "$runner" record +other=$(TEST_HOST=another python3 -I Scripts/bench-identity.py) +check test "$identity" != "$other" +check fails make -C "$work/project" bench-remote printf 'Benchmark runner checks passed: %s\n' "$count" diff --git a/Tests/ParcelPerformanceTests/BenchmarkAllocations.swift b/Tests/ParcelPerformanceTests/BenchmarkAllocations.swift new file mode 100644 index 00000000..3d27dca7 --- /dev/null +++ b/Tests/ParcelPerformanceTests/BenchmarkAllocations.swift @@ -0,0 +1,36 @@ +import Darwin +import Testing + +struct BenchmarkAllocations { + let blocks: Int + let bytes: Int + + static func current() -> Self { + var statistics = malloc_statistics_t() + malloc_zone_statistics(nil, &statistics) + return Self(blocks: Int(statistics.blocks_in_use), bytes: Int(statistics.size_in_use)) + } + + func delta(from previous: Self, operations: Int) -> (blocks: Double, bytes: Double) { + precondition(operations > 0) + return ( + Double(blocks - previous.blocks) / Double(operations), Double(bytes - previous.bytes) / Double(operations) + ) + } +} + +@Suite("Retained allocation diagnostics") +struct BenchmarkAllocationTests { + @Test func deltasAreSignedAndNormalized() { + let delta = BenchmarkAllocations(blocks: 8, bytes: 100).delta( + from: BenchmarkAllocations(blocks: 10, bytes: 80), operations: 2) + #expect(delta.blocks == -1) + #expect(delta.bytes == 10) + } + + @Test func statisticsAreReadable() { + let value = BenchmarkAllocations.current() + #expect(value.blocks >= 0) + #expect(value.bytes >= 0) + } +} diff --git a/Tests/ParcelPerformanceTests/BenchmarkBaselines.swift b/Tests/ParcelPerformanceTests/BenchmarkBaselines.swift index b8a5c6ac..3a9e9cfe 100644 --- a/Tests/ParcelPerformanceTests/BenchmarkBaselines.swift +++ b/Tests/ParcelPerformanceTests/BenchmarkBaselines.swift @@ -1,48 +1,87 @@ +import CryptoKit import Foundation import ParcelTestSupport import Testing struct BenchmarkMachine: Equatable { + let hostKey: String let model: String let cores: Int - init(model: String, cores: Int) throws { + init(hostKey: String, model: String, cores: Int) throws { let safe = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,._-") - guard !model.isEmpty, model.unicodeScalars.allSatisfy(safe.contains), cores > 0 else { - throw BenchmarkFailure.measurement("machine identity") - } + guard !hostKey.isEmpty, !model.isEmpty, hostKey.unicodeScalars.allSatisfy(safe.contains), + model.unicodeScalars.allSatisfy(safe.contains), cores > 0 + else { throw BenchmarkFailure.measurement("machine identity") } + self.hostKey = hostKey self.model = model self.cores = cores } init(identity: String) throws { - let parts = identity.components(separatedBy: ";cores=") - guard parts.count == 2, let cores = Int(parts[1]) else { - throw BenchmarkFailure.measurement("machine identity") - } - try self.init(model: parts[0], cores: cores) + let parts = identity.components(separatedBy: ";") + guard parts.count == 3, parts[0].hasPrefix("host="), parts[1].hasPrefix("model="), + parts[2].hasPrefix("cores="), let cores = Int(parts[2].dropFirst(6)) + else { throw BenchmarkFailure.measurement("machine identity") } + try self.init(hostKey: String(parts[0].dropFirst(5)), model: String(parts[1].dropFirst(6)), cores: cores) } - var identity: String { "\(model);cores=\(cores)" } - var fileName: String { "\(model)-\(cores).json" } + var identity: String { "host=\(hostKey);model=\(model);cores=\(cores)" } + var fileName: String { "\(hostKey)-\(model)-\(cores).json" } - static func current() throws -> Self { + static func command(_ executable: String, _ arguments: [String]) throws -> String { let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/sbin/sysctl") - process.arguments = ["-n", "hw.model", "hw.ncpu"] + process.executableURL = URL(fileURLWithPath: executable) + process.arguments = arguments let output = Pipe() process.standardOutput = output + process.standardError = output try process.run() let data = output.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationStatus == 0, let text = String(data: data, encoding: .utf8) else { - throw BenchmarkFailure.measurement("machine identity") + throw BenchmarkFailure.measurement("host command failed: \(executable)") } - let parts = text.split(whereSeparator: \.isNewline) - guard parts.count == 2, let cores = Int(parts[1]) else { - throw BenchmarkFailure.measurement("machine identity") + return text.trimmingCharacters(in: .whitespacesAndNewlines) + } + + static func key(localHostName: String, platformUUID: String) throws -> String { + guard UUID(uuidString: platformUUID) != nil else { + throw BenchmarkFailure.measurement("platform UUID") } - return try Self(model: String(parts[0]), cores: cores) + let digest = SHA256.hash(data: Data(platformUUID.uppercased().utf8)) + let suffix = digest.prefix(4).map { String(format: "%02x", $0) }.joined() + let machine = try Self(hostKey: localHostName + "-" + suffix, model: "validation", cores: 1) + return machine.hostKey + } + + static func current() throws -> Self { + let host = try command("/usr/sbin/scutil", ["--get", "LocalHostName"]) + let data = Data(try command("/usr/sbin/ioreg", ["-a", "-r", "-d", "1", "-c", "IOPlatformExpertDevice"]).utf8) + struct RegistryRecord: Decodable { + let IOPlatformUUID: String + } + let records = try PropertyListDecoder().decode([RegistryRecord].self, from: data) + guard let uuid = records.first?.IOPlatformUUID, + let cores = Int(try command("/usr/sbin/sysctl", ["-n", "hw.ncpu"])) + else { throw BenchmarkFailure.measurement("hardware identity") } + return try Self( + hostKey: key(localHostName: host, platformUUID: uuid), + model: command("/usr/sbin/sysctl", ["-n", "hw.model"]), cores: cores) + } + + func host(source: BenchmarkCounterSource, quietURL: URL? = nil) throws -> BenchmarkHost { + let quiet = try quietURL.map { try JSONDecoder().decode(BenchmarkQuiet.self, from: Data(contentsOf: $0)) } + #if DEBUG + let configuration = "debug" + #else + let configuration = "release" + #endif + return try BenchmarkHost( + hostKey: hostKey, model: model, cores: cores, + osBuild: Self.command("/usr/sbin/sysctl", ["-n", "kern.osversion"]), + swiftVersion: Self.command("/usr/bin/env", ["swift", "--version"]), + buildConfiguration: configuration, counterSource: source, quiet: quiet) } } @@ -51,15 +90,16 @@ enum BenchmarkBaselines { .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() static let directory = repository.appendingPathComponent("Benchmarks/baselines", isDirectory: true) - static func url(for machine: BenchmarkMachine) -> URL { - directory.appendingPathComponent(machine.fileName) - } + static func url(for machine: BenchmarkMachine) -> URL { directory.appendingPathComponent(machine.fileName) } static func read(_ url: URL, caseNames: Set) throws -> BenchmarkReport { - guard FileManager.default.fileExists(atPath: url.path) else { - throw BenchmarkFailure.missingBaseline(url.path) + guard FileManager.default.fileExists(atPath: url.path) else { throw BenchmarkFailure.missingBaseline(url.path) } + let data = try Data(contentsOf: url) + struct Header: Decodable { let version: Int } + guard try JSONDecoder().decode(Header.self, from: data).version == BenchmarkReport.currentVersion else { + throw BenchmarkFailure.schema } - let report = try JSONDecoder().decode(BenchmarkReport.self, from: Data(contentsOf: url)) + let report = try JSONDecoder().decode(BenchmarkReport.self, from: data) try report.validate(caseNames: caseNames) return report } @@ -77,67 +117,54 @@ enum BenchmarkBaselines { extension AppKitTestSuite { @Suite("Checked-in benchmark baselines") struct BenchmarkBaselineFileTests { - @Test func everyCheckedInBaselineHasCurrentSchemaAndCompleteCoverage() throws { + @Test func checkedInBaselinesHaveHostIdentityAndCoverage() throws { let files = try FileManager.default.contentsOfDirectory( - at: BenchmarkBaselines.directory, includingPropertiesForKeys: nil) + at: BenchmarkBaselines.directory, + includingPropertiesForKeys: nil) for file in files where file.pathExtension == "json" { let report = try BenchmarkBaselines.read(file, caseNames: BenchmarkCases.names) let machine = try BenchmarkMachine(identity: report.machine) #expect(file.lastPathComponent == machine.fileName) #expect(report.results.allSatisfy { $0.samples == 15 }) - #expect(report.calibrationNanoseconds != nil) - for result in report.results { - #expect(result.metric == (result.name == "ipc-request-round-trip" ? .wall : .cpu)) - #expect(result.iterations == BenchmarkCases.iterations(for: result.name)) - } + #expect(report.host.buildConfiguration == "release") } - #expect( - !FileManager.default.fileExists( - atPath: BenchmarkBaselines.repository.appendingPathComponent( - "Tests/ParcelPerformanceTests/Baseline.json" - ).path)) } } } -@Suite("Benchmark baseline paths and isolated files") +@Suite("Benchmark baseline identity") struct BenchmarkBaselineTests { - @Test func machinePathsNeverFallBackToAnotherMachine() throws { - let first = try BenchmarkMachine(model: "Mac15,10", cores: 14) - let second = try BenchmarkMachine(model: "Mac16,1", cores: 10) - #expect(first.identity == "Mac15,10;cores=14") - #expect(BenchmarkBaselines.url(for: first).lastPathComponent == "Mac15,10-14.json") - #expect(BenchmarkBaselines.url(for: first) != BenchmarkBaselines.url(for: second)) + @Test func matchingModelsOnDifferentHostsHaveDifferentFiles() throws { + let first = try BenchmarkMachine(hostKey: "first-12345678", model: "Mac", cores: 14) + let second = try BenchmarkMachine(hostKey: "second-87654321", model: "Mac", cores: 14) + #expect(first.fileName != second.fileName) #expect(try BenchmarkMachine(identity: first.identity) == first) - #expect(throws: BenchmarkFailure.self) { try BenchmarkMachine(model: "../other", cores: 14) } - #expect(throws: BenchmarkFailure.self) { try BenchmarkMachine(model: "", cores: 14) } - #expect(throws: BenchmarkFailure.self) { try BenchmarkMachine(model: "Mac", cores: 0) } + #expect(throws: BenchmarkFailure.self) { try BenchmarkMachine(hostKey: "../other", model: "Mac", cores: 14) } + #expect(throws: BenchmarkFailure.self) { try BenchmarkMachine(hostKey: "test", model: "Mac", cores: 0) } #expect(throws: BenchmarkFailure.self) { try BenchmarkMachine(identity: "Mac;cores=oops") } } + @Test func UUIDHashIsStableAndOnlyEightHexDigitsAreExposed() throws { + let uuid = "00000000-0000-4000-8000-000000000001" + let first = try BenchmarkMachine.key(localHostName: "test", platformUUID: uuid) + #expect(first.count == 13) + #expect(try BenchmarkMachine.key(localHostName: "test", platformUUID: uuid.lowercased()) == first) + #expect(throws: BenchmarkFailure.self) { try BenchmarkMachine.key(localHostName: "test", platformUUID: "bad") } + } + @Test func baselineRoundTripAndMalformedFiles() throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent( "parcel-baseline-" + UUID().uuidString) - defer { - do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } - } + defer { do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } } let url = directory.appendingPathComponent("test.json") + let report = BenchmarkComparisonTests().report() #expect(throws: BenchmarkFailure.self) { try BenchmarkBaselines.read(url, caseNames: ["layout"]) } - let report = BenchmarkReport( - version: BenchmarkReport.currentVersion, machine: "Mac;cores=1", calibrationNanoseconds: 10, - results: [ - BenchmarkResult( - name: "layout", metric: .cpu, minimumNanoseconds: 10, medianNanoseconds: 12, - wallMedianNanoseconds: 15, p99Nanoseconds: 20, samples: 15, iterations: 10, checksum: 1) - ]) try BenchmarkBaselines.write(report, to: url, caseNames: ["layout"]) - let decoded = try BenchmarkBaselines.read(url, caseNames: ["layout"]) - #expect(decoded.results == report.results) - #expect(decoded.calibrationNanoseconds == 10) + #expect(try BenchmarkBaselines.read(url, caseNames: ["layout"]).results == report.results) #expect(throws: BenchmarkFailure.self) { try BenchmarkBaselines.read(url, caseNames: ["other"]) } try Data("not json".utf8).write(to: url) #expect(throws: DecodingError.self) { try BenchmarkBaselines.read(url, caseNames: ["layout"]) } - try Data("{\"version\":1,\"machine\":\"Mac\",\"results\":[]}".utf8).write(to: url) + try Data("{\"version\":4}".utf8).write(to: url) #expect(throws: BenchmarkFailure.self) { try BenchmarkBaselines.read(url, caseNames: ["layout"]) } } } diff --git a/Tests/ParcelPerformanceTests/BenchmarkCounters.swift b/Tests/ParcelPerformanceTests/BenchmarkCounters.swift new file mode 100644 index 00000000..7f37f0ad --- /dev/null +++ b/Tests/ParcelPerformanceTests/BenchmarkCounters.swift @@ -0,0 +1,143 @@ +import Darwin +import Foundation +import Testing + +@_silgen_name("thread_selfcounts") +private func threadSelfcounts(_ flavor: Int32, _ buffer: UnsafeMutableRawPointer, _ size: Int32) -> Int32 + +enum BenchmarkCounterSource: String, Codable { + case selfcounts, rusage + case cpuOnly = "cpu-only" + case smoke +} + +struct BenchmarkCounterReading: Equatable { + let instructions: UInt64 + let cycles: UInt64 + + func delta(from previous: Self) throws -> Self { + guard instructions >= previous.instructions, cycles >= previous.cycles else { + throw BenchmarkFailure.measurement("instruction counters moved backwards") + } + return Self(instructions: instructions - previous.instructions, cycles: cycles - previous.cycles) + } +} + +struct BenchmarkCounters { + let source: BenchmarkCounterSource + + func read() throws -> BenchmarkCounterReading? { + switch source { + case .selfcounts: return try Self.selfcounts() + case .rusage: return try Self.processRusage() + case .cpuOnly, .smoke: return nil + } + } + + static func selfcounts() throws -> BenchmarkCounterReading { + guard dlsym(UnsafeMutableRawPointer(bitPattern: -2), "thread_selfcounts") != nil else { + throw BenchmarkFailure.measurement("thread_selfcounts unavailable") + } + var counts: (UInt64, UInt64) = (0, 0) + let status = withUnsafeMutablePointer(to: &counts) { + threadSelfcounts(1, UnsafeMutableRawPointer($0), 16) + } + guard status == 0 else { throw BenchmarkFailure.measurement("thread_selfcounts failed: \(status)") } + return BenchmarkCounterReading(instructions: counts.0, cycles: counts.1) + } + + static func processRusage() throws -> BenchmarkCounterReading { + var usage = rusage_info_v4() + let status = withUnsafeMutablePointer(to: &usage) { + $0.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) { + proc_pid_rusage(getpid(), RUSAGE_INFO_V4, $0) + } + } + guard status == 0 else { throw BenchmarkFailure.measurement("process instruction counters unavailable") } + return BenchmarkCounterReading(instructions: usage.ri_instructions, cycles: usage.ri_cycles) + } + + @inline(never) + static func knownWork(seed: UInt64) -> UInt64 { + var value = seed + for _ in 0..<50_000 { value = (value &* 6_364_136_223_846_793_005 &+ 1) ^ (value >> 17) } + return value + } + + static func probe(read: () throws -> BenchmarkCounterReading) throws { + let before = try read() + guard before.instructions > 0 else { throw BenchmarkFailure.measurement("instruction counter is zero") } + let checksum = knownWork(seed: before.instructions) + let after = try read() + guard after.instructions > before.instructions, after.cycles >= before.cycles, checksum != 0 else { + throw BenchmarkFailure.measurement("instruction counter did not grow across known work") + } + } + + static func startup(full: Bool, hosted: Bool) -> Self { + do { + try probe(read: selfcounts) + return Self(source: full ? .selfcounts : .smoke) + } catch { + if hosted { + print("instruction counters unavailable: smoke mode only") + return Self(source: .smoke) + } + if String(describing: error).contains("zero") || String(describing: error).contains("did not grow") { + preconditionFailure(String(describing: error)) + } + do { + try probe(read: processRusage) + print("thread counters unavailable; explicitly using process rusage counters on serialized workloads") + return Self(source: full ? .rusage : .smoke) + } catch { + #if arch(x86_64) + if !String(describing: error).contains("zero") { + print("instruction counters unavailable on Intel: CPU-only gate requires a quiet host") + return Self(source: full ? .cpuOnly : .smoke) + } + #endif + preconditionFailure("Benchmark counter startup check failed: \(error)") + } + } + } +} + +@Suite("Instruction counter validation") +struct BenchmarkCounterTests { + @Test func zeroCounterIsRejected() { + #expect(throws: BenchmarkFailure.self) { + try BenchmarkCounters.probe { BenchmarkCounterReading(instructions: 0, cycles: 0) } + } + } + + @Test func stuckCounterIsRejected() { + #expect(throws: BenchmarkFailure.self) { + try BenchmarkCounters.probe { BenchmarkCounterReading(instructions: 10, cycles: 20) } + } + } + + @Test func increasingCounterIsAccepted() throws { + var value: UInt64 = 10 + try BenchmarkCounters.probe { + defer { value += 1 } + return BenchmarkCounterReading(instructions: value, cycles: value) + } + } + + @Test func failuresAndBackwardsCountersAreRejected() { + #expect(throws: BenchmarkFailure.self) { + try BenchmarkCounters.probe { throw BenchmarkFailure.measurement("unavailable") } + } + #expect(throws: BenchmarkFailure.self) { + try BenchmarkCounterReading(instructions: 1, cycles: 2).delta( + from: BenchmarkCounterReading(instructions: 2, cycles: 2)) + } + } + + @Test func deltaUsesBothCounters() throws { + let delta = try BenchmarkCounterReading(instructions: 50, cycles: 90).delta( + from: BenchmarkCounterReading(instructions: 20, cycles: 30)) + #expect(delta == BenchmarkCounterReading(instructions: 30, cycles: 60)) + } +} diff --git a/Tests/ParcelPerformanceTests/BenchmarkHarness.swift b/Tests/ParcelPerformanceTests/BenchmarkHarness.swift index 4458b985..eef3800a 100644 --- a/Tests/ParcelPerformanceTests/BenchmarkHarness.swift +++ b/Tests/ParcelPerformanceTests/BenchmarkHarness.swift @@ -22,6 +22,41 @@ struct BenchmarkObservation { let checksum: Int var nanoseconds: Double? = nil var cpuNanoseconds: Double? = nil + var instructions: Double? = nil + var cycles: Double? = nil + var proofMetrics: [String: Double] = [:] + var counterOperations: Int = 1 +} + +struct BenchmarkQuiet: Codable, Equatable { + let eligible: Bool + let loadAverage: Double + let acPower: Bool + let thermalWarning: Bool + let maximumProcessCPU: Double + let lowPowerMode: Bool + let reasons: [String] + + var verified: Bool { + eligible && loadAverage.isFinite && loadAverage >= 0 && loadAverage < 1.5 + && acPower && !thermalWarning && maximumProcessCPU.isFinite && maximumProcessCPU >= 0 + && maximumProcessCPU <= 10 && !lowPowerMode && reasons.isEmpty + } +} + +struct BenchmarkHost: Codable, Equatable { + let hostKey: String + let model: String + let cores: Int + let osBuild: String + let swiftVersion: String + let buildConfiguration: String + let counterSource: BenchmarkCounterSource + var quiet: BenchmarkQuiet? = nil + + var compatibilityKey: String { + "\(hostKey);\(model);cores=\(cores);os=\(osBuild);swift=\(swiftVersion);\(buildConfiguration);\(counterSource.rawValue)" + } } struct BenchmarkResult: Codable, Equatable { @@ -30,23 +65,38 @@ struct BenchmarkResult: Codable, Equatable { let minimumNanoseconds: Double let medianNanoseconds: Double let wallMedianNanoseconds: Double - let p99Nanoseconds: Double + let wallP99Nanoseconds: Double? + let cpuP99Nanoseconds: Double? + let instructionsP99: Double? let samples: Int let iterations: Int + let latencySamples: Int let checksum: Int + var instructionsPerOp: Double? = nil + var cyclesPerOp: Double? = nil + var counterSource: BenchmarkCounterSource = .smoke + var retainedBlocksPerOp: Double = 0 + var retainedBytesPerOp: Double = 0 + var proofMetrics: [String: Double] = [:] + var reportingOnly: Bool = false + var budget: String? = nil + var reason: String? = nil + var cpuBudgetNanoseconds: Double? = nil } struct BenchmarkReport: Codable { - static let currentVersion = 4 + static let currentVersion = 5 let version: Int let machine: String + let host: BenchmarkHost var calibrationNanoseconds: Double? = nil let results: [BenchmarkResult] func validate(caseNames: Set) throws { guard version == Self.currentVersion else { throw BenchmarkFailure.schema } - guard !machine.isEmpty, !caseNames.isEmpty, results.count == caseNames.count, - Set(results.map(\.name)) == caseNames + guard !machine.isEmpty, !host.hostKey.isEmpty, !host.model.isEmpty, host.cores > 0, + !host.osBuild.isEmpty, !host.swiftVersion.isEmpty, !host.buildConfiguration.isEmpty, + !caseNames.isEmpty, results.count == caseNames.count, Set(results.map(\.name)) == caseNames else { throw BenchmarkFailure.coverage } if let calibrationNanoseconds { guard calibrationNanoseconds.isFinite, calibrationNanoseconds > 0 else { @@ -57,43 +107,80 @@ struct BenchmarkReport: Codable { guard result.minimumNanoseconds.isFinite, result.minimumNanoseconds > 0, result.medianNanoseconds.isFinite, result.medianNanoseconds >= result.minimumNanoseconds, result.wallMedianNanoseconds.isFinite, result.wallMedianNanoseconds > 0, - result.p99Nanoseconds.isFinite, result.p99Nanoseconds > 0, - result.samples > 0, result.iterations > 0, result.checksum != 0 + result.samples > 0, result.iterations > 0, result.checksum != 0, + result.retainedBlocksPerOp.isFinite, result.retainedBytesPerOp.isFinite, + result.proofMetrics.values.allSatisfy(\.isFinite) else { throw BenchmarkFailure.measurement(result.name) } + let p99s = [result.wallP99Nanoseconds, result.cpuP99Nanoseconds, result.instructionsP99] + guard p99s.compactMap({ $0 }).allSatisfy({ $0.isFinite && $0 > 0 }), + result.latencySamples >= 1_000 || p99s.allSatisfy({ $0 == nil }) + else { throw BenchmarkFailure.measurement("p99 requires 1000 samples: \(result.name)") } + if result.metric == .cpu { + guard result.counterSource == host.counterSource else { + throw BenchmarkFailure.measurement("counter source: \(result.name)") + } + if host.counterSource == .selfcounts || host.counterSource == .rusage { + guard let instructions = result.instructionsPerOp, instructions.isFinite, instructions > 0, + let cycles = result.cyclesPerOp, cycles.isFinite, cycles >= 0 + else { throw BenchmarkFailure.measurement("instruction counters: \(result.name)") } + } else if result.instructionsPerOp != nil || result.cyclesPerOp != nil { + throw BenchmarkFailure.measurement("smoke/CPU-only counters must not contain placeholders") + } + } else if result.instructionsPerOp != nil || result.cyclesPerOp != nil { + throw BenchmarkFailure.measurement("thread instruction counts cannot measure async work") + } } } func regressions(against baseline: Self, scaleCalibration: Bool = false) throws -> [String] { guard version == Self.currentVersion, baseline.version == version else { throw BenchmarkFailure.schema } - guard machine == baseline.machine else { throw BenchmarkFailure.machine(baseline.machine, machine) } - let names = results.map(\.name) - let oldNames = baseline.results.map(\.name) - guard !names.isEmpty, Set(names).count == names.count, Set(oldNames).count == oldNames.count, - Set(names) == Set(oldNames) - else { throw BenchmarkFailure.coverage } - try validate(caseNames: Set(names)) - try baseline.validate(caseNames: Set(names)) - var calibrationScale = 1.0 - if scaleCalibration { - guard let current = calibrationNanoseconds, let reference = baseline.calibrationNanoseconds else { - throw BenchmarkFailure.measurement("calibration required for scaling") - } - calibrationScale = reference / current - guard calibrationScale.isFinite, calibrationScale > 0 else { - throw BenchmarkFailure.measurement("calibration scale") - } + guard machine == baseline.machine, host.compatibilityKey == baseline.host.compatibilityKey else { + throw BenchmarkFailure.machine(baseline.host.compatibilityKey, host.compatibilityKey) + } + let names = Set(results.map(\.name)) + try validate(caseNames: names) + try baseline.validate(caseNames: names) + guard !scaleCalibration else { + throw BenchmarkFailure.measurement("calibration scaling was removed; instruction counts are the gate") + } + guard host.counterSource != .smoke else { + throw BenchmarkFailure.measurement("smoke reports cannot certify performance") + } + if host.counterSource == .cpuOnly && (host.quiet?.verified != true || baseline.host.quiet?.verified != true) { + throw BenchmarkFailure.measurement("CPU-only gating requires verified quiet readings on both reports") } let old = Dictionary(uniqueKeysWithValues: baseline.results.map { ($0.name, $0) }) - return try results.compactMap { result in + var failures: [String] = [] + for result in results { guard let reference = old[result.name], result.metric == reference.metric, - result.samples == reference.samples, result.iterations == reference.iterations + result.samples == reference.samples, result.iterations == reference.iterations, + result.counterSource == reference.counterSource, result.reportingOnly == reference.reportingOnly else { throw BenchmarkFailure.measurement(result.name) } - let scale = result.metric == .cpu ? calibrationScale : 1 - let ratio = result.minimumNanoseconds / reference.minimumNanoseconds * scale - guard ratio.isFinite, ratio > 0 else { throw BenchmarkFailure.measurement(result.name) } - guard ratio > 1.2 else { return nil } - return "\(result.name): \(String(format: "%.1f", (ratio - 1) * 100))% slower" + guard result.checksum == reference.checksum else { + throw BenchmarkFailure.measurement("checksum changed: \(result.name)") + } + guard !result.reportingOnly else { continue } + if let current = result.instructionsPerOp, let previous = reference.instructionsPerOp, + current / previous > 1.03 + { + failures.append( + "\(result.name): instructions +\(String(format: "%.2f", (current / previous - 1) * 100))%") + } + if host.quiet?.verified == true, baseline.host.quiet?.verified == true, + result.minimumNanoseconds / reference.minimumNanoseconds > 1.25 + { + failures.append( + "\(result.name): quiet CPU/time +\(String(format: "%.2f", (result.minimumNanoseconds / reference.minimumNanoseconds - 1) * 100))%" + ) + } + if host.quiet?.verified == true, result.metric == .cpu, + let budget = result.cpuBudgetNanoseconds, result.minimumNanoseconds > budget + { + failures.append( + "\(result.name): release CPU budget exceeded (\(result.minimumNanoseconds) > \(budget) ns)") + } } + return failures } } @@ -106,21 +193,22 @@ enum BenchmarkFailure: Error, CustomStringConvertible { var description: String { switch self { - case .schema: "Unsupported benchmark schema." + case .schema: "Unsupported benchmark schema; deliberately re-record a v5 baseline." case .coverage: "Benchmark cases differ; review and deliberately record a new baseline." case .missingBaseline(let path): "no baseline for this machine, run make bench-record on a quiet machine\nExpected: \(path)" case .debugBuild: "Full benchmarks require a release build. Use make bench." case .machine(let expected, let actual): - "Baseline machine \(expected) differs from \(actual); record a machine-specific baseline explicitly." + "Baseline host/OS/toolchain/configuration/counters \(expected) differs from \(actual); re-record deliberately." case .measurement(let name): "Invalid or incompatible measurement for \(name)." - case .regression(let cases): "Performance regressed by more than 20%:\n" + cases.joined(separator: "\n") + case .regression(let cases): "Performance budget exceeded:\n" + cases.joined(separator: "\n") } } } struct BenchmarkHarness { let full: Bool + var counters = BenchmarkCounters(source: .smoke) var results: [BenchmarkResult] = [] private let clock = ContinuousClock() @@ -135,236 +223,313 @@ struct BenchmarkHarness { return sorted[max(0, Int((Double(sorted.count) * fraction).rounded(.up)) - 1)] } + private func reading() -> BenchmarkCounterReading? { + do { return try counters.read() } catch { preconditionFailure("Counter read failed: \(error)") } + } + + private func counterDelta(from before: BenchmarkCounterReading?) -> BenchmarkCounterReading? { + guard let before, let after = reading() else { return nil } + do { return try after.delta(from: before) } catch { preconditionFailure("Counter read failed: \(error)") } + } + @MainActor mutating func measure( - _ name: String, iterations: Int, operation: () throws -> BenchmarkObservation + _ name: String, iterations: Int, reportingOnly: Bool = false, budget: String? = nil, + reason: String? = nil, cpuBudgetNanoseconds: Double? = nil, latencySamples: Int = 1_000, + operation: () throws -> BenchmarkObservation ) rethrows { let count = full ? iterations : 2 - let samples = full ? 15 : 3 - var checksum = 0 - for _ in 0..<(full ? count : 1) { checksum &+= try operation().checksum } - var batches: [Double] = [] - var cpuBatches: [Double] = [] + let samples = full ? 15 : 1 + let reference = try operation() + for _ in 0..<3 { for _ in 0.. 0) + counterOperations += observation.counterOperations + precondition(observation.checksum == reference.checksum, "Unstable benchmark checksum: \(name)") + proofMetrics = observation.proofMetrics + if let value = observation.nanoseconds { + customWall += value + useWall = true } - if let nanoseconds = observation.cpuNanoseconds { - cpuMeasured += nanoseconds - customCPU = true + if let value = observation.cpuNanoseconds { + customCPU += value + useCPU = true + } + if let value = observation.instructions { + customInstructions += value + useInstructions = true + } + if let value = observation.cycles { + customCycles += value + useCycles = true } completed += 1 } } while full && BenchmarkCPUClock.elapsed(since: cpuStart) < 10_000_000 - batches.append((custom ? measured : Self.nanoseconds(start.duration(to: clock.now))) / Double(completed)) - cpuBatches.append( - (customCPU ? cpuMeasured : BenchmarkCPUClock.elapsed(since: cpuStart)) / Double(completed)) + let cpuElapsed = BenchmarkCPUClock.elapsed(since: cpuStart) + let wallElapsed = Self.nanoseconds(start.duration(to: clock.now)) + let counts = counterDelta(from: countersStart) + let retained = BenchmarkAllocations.current().delta(from: allocations, operations: counterOperations) + wall.append((useWall ? customWall : wallElapsed) / Double(completed)) + cpu.append((useCPU ? customCPU : cpuElapsed) / Double(completed)) + if let counts { + instructions.append( + useInstructions + ? customInstructions / Double(completed) + : Double(counts.instructions) / Double(counterOperations)) + cycles.append( + useCycles ? customCycles / Double(completed) : Double(counts.cycles) / Double(counterOperations)) + } + blocks.append(retained.blocks) + bytes.append(retained.bytes) } - var latencies: [Double] = [] - for _ in 0..<(full ? 129 : 3) { - let start = clock.now - let observation = try operation() - let elapsed = Self.nanoseconds(start.duration(to: clock.now)) - checksum &+= observation.checksum - latencies.append(observation.nanoseconds ?? elapsed) + var wallLatencies: [Double] = [] + var cpuLatencies: [Double] = [] + var instructionLatencies: [Double] = [] + if full { + for _ in 0..= 1_000 + ? Self.percentile(wallLatencies, fraction: 0.99) : nil, + cpuP99Nanoseconds: full && latencySamples >= 1_000 + ? Self.percentile(cpuLatencies, fraction: 0.99) : nil, + instructionsP99: instructionLatencies.count >= 1_000 + ? Self.percentile(instructionLatencies, fraction: 0.99) : nil, + samples: samples, iterations: count, latencySamples: wallLatencies.count, checksum: reference.checksum, + instructionsPerOp: instructions.isEmpty ? nil : Self.percentile(instructions, fraction: 0.5), + cyclesPerOp: cycles.isEmpty ? nil : Self.percentile(cycles, fraction: 0.5), + counterSource: counters.source, + retainedBlocksPerOp: Self.percentile(blocks, fraction: 0.5), + retainedBytesPerOp: Self.percentile(bytes, fraction: 0.5), + proofMetrics: proofMetrics, reportingOnly: reportingOnly, budget: budget, reason: reason, + cpuBudgetNanoseconds: cpuBudgetNanoseconds)) } @MainActor mutating func measureAsync( - _ name: String, iterations: Int, operation: () async throws -> BenchmarkObservation + _ name: String, iterations: Int, reportingOnly: Bool = false, budget: String? = nil, + reason: String? = nil, latencySamples: Int = 1_000, operation: () async throws -> BenchmarkObservation ) async rethrows { let count = full ? iterations : 2 - let samples = full ? 15 : 3 - var checksum = 0 - for _ in 0..<(full ? count : 1) { checksum &+= try await operation().checksum } + let samples = full ? 15 : 1 + let reference = try await operation() + for _ in 0..<3 { _ = try await operation() } var batches: [Double] = [] for _ in 0..= 1_000 ? Self.percentile(latencies, fraction: 0.99) : nil, + cpuP99Nanoseconds: nil, instructionsP99: nil, samples: samples, iterations: count, + latencySamples: latencies.count, checksum: reference.checksum, proofMetrics: reference.proofMetrics, + reportingOnly: reportingOnly, budget: budget, reason: reason)) } } @Suite("Benchmark comparison") struct BenchmarkComparisonTests { - private func report( - _ median: Double, name: String = "layout", machine: String = "test", minimum: Double? = nil, - metric: BenchmarkMetric = .cpu, calibration: Double? = nil + static let quiet = BenchmarkQuiet( + eligible: true, loadAverage: 0.5, acPower: true, thermalWarning: false, + maximumProcessCPU: 1, lowPowerMode: false, reasons: []) + static let host = BenchmarkHost( + hostKey: "test-12345678", model: "Mac", cores: 1, osBuild: "build", + swiftVersion: "Swift test", buildConfiguration: "release", counterSource: .selfcounts) + + func report( + _ instructions: Double = 100, cpu: Double = 100, quiet: Bool = false, + reportingOnly: Bool = false, checksum: Int = 1, host: BenchmarkHost = Self.host ) -> BenchmarkReport { - BenchmarkReport( - version: BenchmarkReport.currentVersion, machine: machine, calibrationNanoseconds: calibration, + var host = host + host.quiet = quiet ? Self.quiet : nil + return BenchmarkReport( + version: 5, machine: "test", host: host, results: [ BenchmarkResult( - name: name, metric: metric, minimumNanoseconds: minimum ?? median, medianNanoseconds: median, - wallMedianNanoseconds: median, - p99Nanoseconds: median, - samples: 15, iterations: 10, checksum: 1) + name: "layout", metric: .cpu, minimumNanoseconds: cpu, medianNanoseconds: cpu, + wallMedianNanoseconds: cpu, wallP99Nanoseconds: nil, cpuP99Nanoseconds: nil, instructionsP99: nil, + samples: 15, iterations: 10, latencySamples: 0, checksum: checksum, + instructionsPerOp: instructions, cyclesPerOp: instructions * 2, counterSource: .selfcounts, + reportingOnly: reportingOnly) ]) } - @Test func percentilesUseSortedNearestRank() { - #expect(BenchmarkHarness.percentile([9, 1, 5], fraction: 0.5) == 5) - #expect(BenchmarkHarness.percentile([9, 1, 5], fraction: 0.99) == 9) - #expect(BenchmarkHarness.percentile([9], fraction: 0) == 9) - #expect(BenchmarkHarness.nanoseconds(.milliseconds(1)) == 1_000_000) + @Test func instructionThresholdIsThreePercent() throws { + #expect(try report(103).regressions(against: report()).isEmpty) + #expect(try report(103.01).regressions(against: report()).count == 1) + #expect(try report(80).regressions(against: report()).isEmpty) } - @Test func thresholdIsStrictlyGreaterThanTwentyPercent() throws { - #expect(try report(120).regressions(against: report(100)).isEmpty) - #expect(try report(120.01).regressions(against: report(100)).count == 1) - #expect(try report(80).regressions(against: report(100)).isEmpty) + @Test func noisyCPUIsDiagnosticAndQuietCPUHasWiderGate() throws { + #expect(try report(cpu: 1000).regressions(against: report()).isEmpty) + #expect(try report(cpu: 125, quiet: true).regressions(against: report(quiet: true)).isEmpty) + #expect(try report(cpu: 125.01, quiet: true).regressions(against: report(quiet: true)).count == 1) } - @Test func missingCasesAndMachineChangesFailLoudly() { - #expect(throws: BenchmarkFailure.self) { try report(100, name: "diff").regressions(against: report(100)) } + @Test func reportingOnlyDoesNotGateButChecksumStillMustMatch() throws { + #expect(try report(1000, reportingOnly: true).regressions(against: report(reportingOnly: true)).isEmpty) #expect(throws: BenchmarkFailure.self) { - try report(100, machine: "other").regressions(against: report(100)) + try report(checksum: 2).regressions(against: report()) } } @Test(arguments: [0.0, -1.0, Double.nan, Double.infinity]) - func invalidMeasurementsAreRejected(_ value: Double) { - #expect(throws: BenchmarkFailure.self) { try report(value).regressions(against: report(100)) } - #expect(throws: BenchmarkFailure.self) { try report(100).regressions(against: report(value)) } - } - - @Test func samplingChangesAndEmptyReportsAreRejected() { - let baseline = report(100) - let altered = BenchmarkReport( - version: BenchmarkReport.currentVersion, machine: "test", - results: [ - BenchmarkResult( - name: "layout", metric: .cpu, minimumNanoseconds: 100, medianNanoseconds: 100, - wallMedianNanoseconds: 100, - p99Nanoseconds: 100, - samples: 14, iterations: 10, checksum: 1) - ]) - #expect(throws: BenchmarkFailure.self) { try altered.regressions(against: baseline) } - let empty = BenchmarkReport(version: BenchmarkReport.currentVersion, machine: "test", results: []) - #expect(throws: BenchmarkFailure.self) { try empty.regressions(against: empty) } + func invalidInstructionsFail(_ value: Double) { + #expect(throws: BenchmarkFailure.self) { try report(value).regressions(against: report()) } } - @Test func timingBasisChangesAreRejected() { - let baseline = report(100) - let changed = BenchmarkReport( - version: BenchmarkReport.currentVersion, machine: "test", - results: [ - BenchmarkResult( - name: "layout", metric: .wall, minimumNanoseconds: 100, medianNanoseconds: 100, - wallMedianNanoseconds: 100, p99Nanoseconds: 100, samples: 15, iterations: 10, checksum: 1) - ]) - #expect(throws: BenchmarkFailure.self) { try changed.regressions(against: baseline) } - let start = BenchmarkCPUClock.now() - #expect(BenchmarkCPUClock.elapsed(since: start) >= 0) - } - - @Test func gateUsesMinimumInsteadOfLoadedMedians() throws { - let baseline = report(100, minimum: 90) - #expect(try report(1_000, minimum: 90).regressions(against: baseline).isEmpty) - #expect(try report(1_000, minimum: 109).regressions(against: baseline).count == 1) - #expect(throws: BenchmarkFailure.self) { try report(100, minimum: 101).regressions(against: baseline) } - } - - @Test func calibrationScalingIsExplicitAndOnlyScalesCPU() throws { - let baseline = report(100, calibration: 100) - let slowed = report(150, calibration: 150) - #expect(try slowed.regressions(against: baseline).count == 1) - #expect(try slowed.regressions(against: baseline, scaleCalibration: true).isEmpty) - let wallBaseline = report(100, metric: .wall, calibration: 100) - let wallSlowed = report(150, metric: .wall, calibration: 150) - #expect(try wallSlowed.regressions(against: wallBaseline, scaleCalibration: true).count == 1) - #expect(throws: BenchmarkFailure.self) { - try report(100).regressions(against: baseline, scaleCalibration: true) - } - #expect(throws: BenchmarkFailure.self) { - try slowed.regressions(against: report(100), scaleCalibration: true) + @Test func hostOSCompilerAndCounterChangesRequireRebaseline() { + for host in [ + BenchmarkHost( + hostKey: "other", model: "Mac", cores: 1, osBuild: "build", swiftVersion: "Swift test", + buildConfiguration: "release", counterSource: .selfcounts), + BenchmarkHost( + hostKey: "test-12345678", model: "Mac", cores: 1, osBuild: "new", swiftVersion: "Swift test", + buildConfiguration: "release", counterSource: .selfcounts), + BenchmarkHost( + hostKey: "test-12345678", model: "Mac", cores: 1, osBuild: "build", swiftVersion: "new", + buildConfiguration: "release", counterSource: .selfcounts), + BenchmarkHost( + hostKey: "test-12345678", model: "Mac", cores: 1, osBuild: "build", swiftVersion: "Swift test", + buildConfiguration: "debug", counterSource: .selfcounts), + BenchmarkHost( + hostKey: "test-12345678", model: "Mac", cores: 1, osBuild: "build", swiftVersion: "Swift test", + buildConfiguration: "release", counterSource: .rusage), + ] { + #expect(throws: BenchmarkFailure.self) { try report(host: host).regressions(against: report()) } } } - @Test(arguments: [0.0, -1.0, Double.nan, Double.infinity]) - func invalidCalibrationIsRejected(_ value: Double) { - #expect(throws: BenchmarkFailure.self) { - try report(100, calibration: value).regressions(against: report(100)) - } - #expect(throws: BenchmarkFailure.self) { - try report(100).regressions(against: report(100, calibration: value)) - } + @Test func percentilesAreNearestRankAndRequireEnoughSamplesForP99() { + #expect(BenchmarkHarness.percentile([9, 1, 5], fraction: 0.5) == 5) + #expect(BenchmarkHarness.percentile([9, 1, 5], fraction: 0.99) == 9) + #expect(BenchmarkHarness.nanoseconds(.milliseconds(1)) == 1_000_000) + var value = report() + var result = value.results[0] + result = BenchmarkResult( + name: result.name, metric: .cpu, minimumNanoseconds: 100, medianNanoseconds: 100, + wallMedianNanoseconds: 100, wallP99Nanoseconds: 100, cpuP99Nanoseconds: nil, instructionsP99: nil, + samples: 15, iterations: 10, latencySamples: 129, checksum: 1, + instructionsPerOp: 100, cyclesPerOp: 100, counterSource: .selfcounts) + value = BenchmarkReport(version: 5, machine: "test", host: Self.host, results: [result]) + #expect(throws: BenchmarkFailure.self) { try value.validate(caseNames: ["layout"]) } } - @Test @MainActor func samplerKeepsCPUAndWallMetricsSeparate() throws { + @Test @MainActor func smokeSamplerSeparatesCPUAndWallAndOmitsP99() throws { var harness = BenchmarkHarness(full: false) harness.measure("custom", iterations: 10) { BenchmarkObservation(checksum: 1, nanoseconds: 100, cpuNanoseconds: 10) } let result = try #require(harness.results.first) - #expect(result.metric == .cpu) #expect(result.minimumNanoseconds == 10) - #expect(result.medianNanoseconds == 10) #expect(result.wallMedianNanoseconds == 100) - #expect(result.p99Nanoseconds == 100) - #expect(result.samples == 3) - #expect(result.iterations == 2) - #expect(result.checksum == 10) + #expect(result.wallP99Nanoseconds == nil) + #expect(result.instructionsPerOp == nil) + #expect(result.samples == 1) + #expect(result.checksum == 1) } - @Test @MainActor func asynchronousSamplerUsesWallTime() async throws { + @Test @MainActor func asyncSamplerDoesNotClaimThreadCounters() async throws { var harness = BenchmarkHarness(full: false) await harness.measureAsync("async", iterations: 10) { BenchmarkObservation(checksum: 1) } let result = try #require(harness.results.first) #expect(result.metric == .wall) - #expect(result.minimumNanoseconds > 0) - #expect(result.wallMedianNanoseconds == result.medianNanoseconds) - #expect(result.samples == 3) - #expect(result.checksum == 10) + #expect(result.instructionsPerOp == nil) + #expect(result.wallP99Nanoseconds == nil) } - @Test func duplicateCasesAndSchemaChangesAreRejected() { - let sample = report(100) + @Test func coverageSchemasAndCalibrationCannotChangeSilently() { + let original = report() + let empty = BenchmarkReport(version: 5, machine: "test", host: Self.host, results: []) let duplicate = BenchmarkReport( - version: BenchmarkReport.currentVersion, machine: "test", results: sample.results + sample.results) - #expect(throws: BenchmarkFailure.self) { try duplicate.regressions(against: sample) } - let version = BenchmarkReport( - version: BenchmarkReport.currentVersion + 1, machine: "test", results: sample.results) - #expect(throws: BenchmarkFailure.self) { try version.regressions(against: sample) } + version: 5, machine: "test", host: Self.host, + results: original.results + original.results) + let oldSchema = BenchmarkReport(version: 4, machine: "test", host: Self.host, results: original.results) + for changed in [empty, duplicate, oldSchema] { + #expect(throws: BenchmarkFailure.self) { try changed.regressions(against: original) } + } + #expect(throws: BenchmarkFailure.self) { + try original.regressions(against: original, scaleCalibration: true) + } + } + + @Test @MainActor func smokeReportCannotBeUsedAsABaseline() throws { + var harness = BenchmarkHarness(full: false) + harness.measure("smoke", iterations: 1) { BenchmarkObservation(checksum: 1) } + let host = BenchmarkHost( + hostKey: "test", model: "Mac", cores: 1, osBuild: "build", + swiftVersion: "Swift test", buildConfiguration: "debug", counterSource: .smoke) + let value = BenchmarkReport(version: 5, machine: "test", host: host, results: harness.results) + try value.validate(caseNames: ["smoke"]) + #expect(throws: BenchmarkFailure.self) { try value.regressions(against: value) } + } + + @Test func quietFlagCannotOverrideBadReadings() { + let fake = BenchmarkQuiet( + eligible: true, loadAverage: 10, acPower: true, thermalWarning: false, + maximumProcessCPU: 1, lowPowerMode: false, reasons: []) + #expect(!fake.verified) } } diff --git a/Tests/ParcelPerformanceTests/BenchmarkRegressionProbeTests.swift b/Tests/ParcelPerformanceTests/BenchmarkRegressionProbeTests.swift new file mode 100644 index 00000000..aa3cdbef --- /dev/null +++ b/Tests/ParcelPerformanceTests/BenchmarkRegressionProbeTests.swift @@ -0,0 +1,56 @@ +import Foundation +import ParcelCore +import Testing + +@Suite("Deliberate instruction regression proof", .serialized) +@MainActor +struct BenchmarkRegressionProbeTests { + @inline(never) + private func copiedChecksum(_ frames: [WindowID: Rect]) -> Int { + var copy = frames + if let first = frames.first { copy[first.key] = first.value } + return consume(copy) + } + + @Test func extraFrameCopiesFailTheInstructionGate() throws { + guard ProcessInfo.processInfo.environment["PARCEL_BENCH_REGRESSION_PROBE"] == "1" else { return } + #if DEBUG + throw BenchmarkFailure.debugBuild + #else + let counters = BenchmarkCounters.startup(full: true, hosted: false) + let machine = try BenchmarkMachine.current() + let host = try machine.host(source: counters.source) + let fixture = PerformanceFixture(count: 50, layout: .bsp) + var before = BenchmarkHarness(full: true, counters: counters) + var after = BenchmarkHarness(full: true, counters: counters) + before.measure("layout-diff/bsp/50", iterations: 40) { + let (next, effects) = reduce(fixture.state, .relayout) + return BenchmarkObservation(checksum: consume(next.frames) &+ effects.count) + } + after.measure("layout-diff/bsp/50", iterations: 40) { + let (next, effects) = reduce(fixture.state, .relayout) + let checksum = consume(next.frames) + for _ in 0..<16 { + precondition(copiedChecksum(next.frames) == checksum) + } + return BenchmarkObservation(checksum: checksum &+ effects.count) + } + let baseline = BenchmarkReport(version: 5, machine: machine.identity, host: host, results: before.results) + let candidate = BenchmarkReport(version: 5, machine: machine.identity, host: host, results: after.results) + let regressions = try candidate.regressions(against: baseline) + #expect(regressions.contains { $0.contains("instructions") }) + struct Proof: Encodable { + let before: BenchmarkReport + let after: BenchmarkReport + let regressions: [String] + } + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + let directory = BenchmarkBaselines.repository.appendingPathComponent("build") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try encoder.encode(Proof(before: baseline, after: candidate, regressions: regressions)) + .write(to: directory.appendingPathComponent("bench-regression-proof.json"), options: .atomic) + print("Instruction regression proof: \(regressions.joined(separator: "; "))") + #endif + } +} diff --git a/Tests/ParcelPerformanceTests/PerformanceBenchmarks.swift b/Tests/ParcelPerformanceTests/PerformanceBenchmarks.swift index f2d6f0d4..2f8d4381 100644 --- a/Tests/ParcelPerformanceTests/PerformanceBenchmarks.swift +++ b/Tests/ParcelPerformanceTests/PerformanceBenchmarks.swift @@ -15,26 +15,32 @@ extension AppKitTestSuite { struct PerformanceBenchmarks { @Test func headlessPaths() async throws { let environment = ProcessInfo.processInfo.environment - let full = environment["PARCEL_BENCH"] == "1" + let hosted = environment["GITHUB_ACTIONS"] == "true" || environment["PARCEL_BENCH_SMOKE"] == "1" + let full = environment["PARCEL_BENCH"] == "1" && !hosted + let counters = BenchmarkCounters.startup(full: full, hosted: hosted) + if hosted { print("Hosted CI: benchmark smoke mode only (no performance gate).") } if full && _isDebugAssertConfiguration() { throw BenchmarkFailure.debugBuild } - let machine = full ? try BenchmarkMachine.current() : nil + let machine = try BenchmarkMachine.current() + let host = try machine.host( + source: counters.source, + quietURL: environment["PARCEL_BENCH_QUIET"].map { URL(fileURLWithPath: $0) }) let baselineURL = environment["PARCEL_BENCH_BASELINE"].map { URL(fileURLWithPath: $0) } - ?? machine.map(BenchmarkBaselines.url) + ?? BenchmarkBaselines.url(for: machine) let recording = environment["PARCEL_BENCH_RECORD"] == "1" + let comparing = full && !recording && environment["PARCEL_BENCH_NO_COMPARE"] != "1" let baseline: BenchmarkReport? - if full && !recording { - guard let baselineURL else { throw BenchmarkFailure.measurement("baseline path") } + if comparing { baseline = try BenchmarkBaselines.read(baselineURL, caseNames: BenchmarkCases.names) - guard baseline?.machine == machine?.identity else { - throw BenchmarkFailure.machine(baseline?.machine ?? "missing", machine?.identity ?? "missing") + guard baseline?.machine == machine.identity else { + throw BenchmarkFailure.machine(baseline?.machine ?? "missing", machine.identity) } } else { baseline = nil } let previousPriority = full ? setPriority(.userInteractive) : nil defer { if let previousPriority { _ = setPriority(previousPriority) } } - var harness = BenchmarkHarness(full: full) + var harness = BenchmarkHarness(full: full, counters: counters) for count in [50, 200] { for layout in Layout.allCases { let fixture = PerformanceFixture(count: count, layout: layout) @@ -42,7 +48,8 @@ extension AppKitTestSuite { let name = "event-layout/\(layout.rawValue)/\(count)" try harness.measure(name, iterations: iterations) { try PerformanceWorkload.eventLayout( - state: fixture.state, event: .focusChanged(fixture.ids[count - 1]), name: name) + state: fixture.state, event: .focusChanged(fixture.ids[count - 1]), name: name, + counters: counters) } harness.measure("layout-diff/\(layout.rawValue)/\(count)", iterations: iterations) { let (next, effects) = reduce(fixture.state, .relayout) @@ -105,29 +112,40 @@ extension AppKitTestSuite { return BenchmarkObservation(checksum: configuration.rules.count) } try await socketRoundTrip(&harness) + #if !PARCEL_BENCH_CORE_ONLY + try await HotPathBenchmarks.run(&harness) + #endif #expect(harness.results.count == BenchmarkCases.names.count) #expect(Set(harness.results.map(\.name)) == BenchmarkCases.names) let report = BenchmarkReport( - version: BenchmarkReport.currentVersion, machine: machine?.identity ?? "smoke", + version: BenchmarkReport.currentVersion, machine: machine.identity, host: host, calibrationNanoseconds: BenchmarkCalibration.measure(), results: harness.results) try report.validate(caseNames: BenchmarkCases.names) - guard full else { return } if let output = environment["PARCEL_BENCH_OUTPUT"] { try BenchmarkBaselines.write(report, to: URL(fileURLWithPath: output), caseNames: BenchmarkCases.names) } + #if !PARCEL_BENCH_CORE_ONLY + try HotPathBenchmarks.writeCatalog() + #endif + guard full else { return } for result in report.results { print( "BENCH \(result.name): \(result.metric.rawValue) minimum \(String(format: "%.2f", result.minimumNanoseconds / 1000)) µs, " + "median \(String(format: "%.2f", result.medianNanoseconds / 1000)) µs, " + "wall median \(String(format: "%.2f", result.wallMedianNanoseconds / 1000)) µs, " - + "wall p99 \(String(format: "%.2f", result.p99Nanoseconds / 1000)) µs") + + "instructions \(result.instructionsPerOp.map { String(format: "%.0f", $0) } ?? "not measured") " + + "[\(result.reportingOnly ? "reporting-only" : "gating")] wall p99 " + + "\(result.wallP99Nanoseconds.map { String(format: "%.2f", $0 / 1000) } ?? "not sampled") µs") } if recording { - guard let baselineURL else { throw BenchmarkFailure.measurement("baseline path") } + guard host.quiet?.verified == true else { + throw BenchmarkFailure.measurement("baseline recording requires verified quiet-check readings") + } try BenchmarkBaselines.write(report, to: baselineURL, caseNames: BenchmarkCases.names) print("Recorded baseline: \(baselineURL.path)") return } + guard comparing else { return } guard let baseline else { throw BenchmarkFailure.measurement("baseline not loaded") } let regressions = try report.regressions( against: baseline, scaleCalibration: environment["PARCEL_BENCH_CALIBRATE"] == "1") @@ -238,7 +256,12 @@ struct PerformanceFixture { @inline(never) func consume(_ frames: [WindowID: Rect]) -> Int { - frames.count &+ Int(frames.values.first?.size.width ?? 0) + frames.reduce(frames.count) { checksum, element in + let frame = element.value + return checksum &+ Int(element.key.rawValue) &* 31 + &+ Int(frame.minX * 1000) &* 37 &+ Int(frame.minY * 1000) &* 41 + &+ Int(frame.size.width * 1000) &* 43 &+ Int(frame.size.height * 1000) &* 47 + } } private actor BenchmarkIPCHandler: IPCHandler { diff --git a/Tests/ParcelPerformanceTests/PerformanceBudgetTests.swift b/Tests/ParcelPerformanceTests/PerformanceBudgetTests.swift index be6466c4..b6410deb 100644 --- a/Tests/ParcelPerformanceTests/PerformanceBudgetTests.swift +++ b/Tests/ParcelPerformanceTests/PerformanceBudgetTests.swift @@ -18,6 +18,9 @@ enum BenchmarkCases { cases["snapshot-menu/6"] = 200 cases["config-parse-validate/500-rules"] = 3 cases["ipc-request-round-trip"] = 20 + #if !PARCEL_BENCH_CORE_ONLY + for (name, iterations) in BenchmarkCatalog.definitions { cases[name] = iterations } + #endif return cases } @@ -27,23 +30,31 @@ enum BenchmarkCases { } enum PerformanceWorkload { - static func eventLayout(state: State, event: Event, name: String) throws -> BenchmarkObservation { + static func eventLayout( + state: State, event: Event, name: String, + counters: BenchmarkCounters = BenchmarkCounters(source: .smoke) + ) throws -> BenchmarkObservation { + let countStart = try counters.read() let clock = ContinuousClock() let start = clock.now let cpuStart = BenchmarkCPUClock.now() var elapsed: Double? var cpuElapsed: Double? + var countEnd: BenchmarkCounterReading? let (next, effects) = reduce(state, [event]) { stage, phase in if stage == .layout && phase == .end { cpuElapsed = BenchmarkCPUClock.elapsed(since: cpuStart) elapsed = BenchmarkHarness.nanoseconds(start.duration(to: clock.now)) + do { countEnd = try counters.read() } catch { preconditionFailure("Counter read failed: \(error)") } } } guard let elapsed, let cpuElapsed else { throw BenchmarkFailure.measurement("layout stage not reached: \(name)") } + let delta = try countStart.flatMap { start in try countEnd.map { try $0.delta(from: start) } } return BenchmarkObservation( - checksum: consume(next.frames) &+ effects.count, nanoseconds: elapsed, cpuNanoseconds: cpuElapsed) + checksum: consume(next.frames) &+ effects.count, nanoseconds: elapsed, cpuNanoseconds: cpuElapsed, + instructions: delta.map { Double($0.instructions) }, cycles: delta.map { Double($0.cycles) }) } } -- knotmirror 0.0.1 From 3c607dc57061cbfaab97ceff1d1d40fc04efd7dd Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 13:29:20 -0400 Subject: [PATCH 04/22] Expose fixture stimulus time and guard idle waits --- Benchmarks/idle-waits.json | 19 ++++++ Sources/ParcelApp/AppIPCHandler.swift | 19 ++++-- Sources/ParcelApp/NativeAppRuntime.swift | 6 +- .../AppFixtureTimestampTests.swift | 20 ++++++ .../IdleTimerGuardTests.swift | 61 +++++++++++++++++++ 5 files changed, 117 insertions(+), 8 deletions(-) create mode 100644 Benchmarks/idle-waits.json create mode 100644 Tests/ParcelE2ETests/AppFixtureTimestampTests.swift create mode 100644 Tests/ParcelPerformanceTests/IdleTimerGuardTests.swift diff --git a/Benchmarks/idle-waits.json b/Benchmarks/idle-waits.json new file mode 100644 index 00000000..595933e1 --- /dev/null +++ b/Benchmarks/idle-waits.json @@ -0,0 +1,19 @@ +[ + {"path":"ParcelApp/AppFixtureMouseInput.swift","count":4,"why":"Harness-only gesture pacing and release safety; ends with the gesture."}, + {"path":"ParcelApp/AppIPCHandler.swift","count":2,"why":"Harness-only key and mouse release delays; end with input."}, + {"path":"ParcelApp/AppTourIntegration.swift","count":1,"why":"Explicit tour tidy confirmation; bounded deadline."}, + {"path":"ParcelConfig/ConfigFileWatcher.swift","count":1,"why":"File-event debounce; no wait until a file event arrives."}, + {"path":"ParcelConfig/ConfigStore.swift","count":1,"why":"Injected file-event debounce; cancels on watcher stop."}, + {"path":"ParcelEngine/EngineSpaces.swift","count":1,"why":"Explicit Space command waits for writes; bounded 750 ms."}, + {"path":"ParcelEngine/EngineSystemServices.swift","count":1,"why":"One-shot reactor deadline; cancelled when its work ends."}, + {"path":"ParcelEngine/NativeEngineBackend.swift","count":1,"why":"Explicit fullscreen command confirmation; bounded deadline."}, + {"path":"ParcelPlatform/AccessibilityTrustObserver.swift","count":1,"why":"One follow-up after a trust-change notification, not a poll."}, + {"path":"ParcelPlatform/AXElement.swift","count":1,"why":"One-shot AX watchdog; cancelled when the AX call finishes."}, + {"path":"ParcelPlatform/Permissions.swift","count":1,"why":"Explicit caller-requested grant wait before start, not a running-app idle poll."}, + {"path":"ParcelPlatform/Spaces/SpaceController.swift","count":1,"why":"Explicit Space command confirmation; bounded deadline."}, + {"path":"ParcelUI/Feedback/FeedbackController.swift","count":1,"why":"One-shot notice dismissal, cancelled when notice is replaced."}, + {"path":"ParcelUI/HoverBar/HoverBarController.swift","count":1,"why":"Pointer activity schedules a hover deadline; cancelled when hidden or stopped."}, + {"path":"ParcelUI/MenuBarController.swift","count":1,"why":"Ten-frame finite icon morph; exits when no frames remain."}, + {"path":"ParcelUI/Onboarding.swift","count":1,"why":"Finite onboarding motion; ends at its token duration."}, + {"path":"ParcelUI/Tour/TourView.swift","count":1,"why":"Finite tour motion; ends at its token duration."} +] diff --git a/Sources/ParcelApp/AppIPCHandler.swift b/Sources/ParcelApp/AppIPCHandler.swift index 8f09b6d7..874d6aaa 100644 --- a/Sources/ParcelApp/AppIPCHandler.swift +++ b/Sources/ParcelApp/AppIPCHandler.swift @@ -15,7 +15,7 @@ final class AppIPCHandler: IPCHandler { private var fixtureDragIsActive = false private var fixtureMouseInput: AppFixtureMouseInput? private let settingsAudit: (@MainActor () async throws -> JSONValue)? - private let fixtureKeyInput: (@MainActor (AppFixtureKeyInput) async throws -> Void)? + private let fixtureKeyInput: (@MainActor (AppFixtureKeyInput) async throws -> UInt64)? private let feedback: (@MainActor ([String]) async throws -> JSONValue)? private let secureInput: @MainActor () -> Bool private let tour: (@MainActor ([String]) async throws -> JSONValue)? @@ -24,7 +24,7 @@ final class AppIPCHandler: IPCHandler { init( services: EngineShellServices, configPath: String, settingsAudit: (@MainActor () async throws -> JSONValue)? = nil, - fixtureKeyInput: (@MainActor (AppFixtureKeyInput) async throws -> Void)? = nil, + fixtureKeyInput: (@MainActor (AppFixtureKeyInput) async throws -> UInt64)? = nil, feedback: (@MainActor ([String]) async throws -> JSONValue)? = nil, secureInput: @escaping @MainActor () -> Bool = { false }, tour: (@MainActor ([String]) async throws -> JSONValue)? = nil, @@ -98,8 +98,8 @@ final class AppIPCHandler: IPCHandler { _ = try runningEngine() fixtureDragIsActive = true defer { fixtureDragIsActive = false } - try await fixtureKeyInput(request) - return .object(["accepted": .bool(true)]) + let timestamp = try await fixtureKeyInput(request) + return try AppFixtureKeyInput.reply(timestamp: timestamp) } if command == "e2e-chip-middle-click" { let engine = try runningEngine() @@ -299,8 +299,15 @@ struct AppFixtureKeyInput { } } + static func reply(timestamp: UInt64) throws -> JSONValue { + guard let encodedTimestamp = Int64(exactly: timestamp), encodedTimestamp > 0 else { + throw AppFixtureDrag.rejected("Fixture keyboard stimulus timestamp is unavailable") + } + return .object(["accepted": .bool(true), "event_timestamp_ns": .integer(encodedTimestamp)]) + } + @MainActor - func post(state: State, activeBindings: [ConfigCommand: KeyChord]) async throws { + func post(state: State, activeBindings: [ConfigCommand: KeyChord]) async throws -> UInt64 { let pid = try targetPID(state: state) let chord = try chord(activeBindings: activeBindings) guard let application = NSRunningApplication(processIdentifier: pid) else { @@ -324,6 +331,7 @@ struct AppFixtureKeyInput { let events = try Self.events(chord: chord, pid: pid) let down = events[0] let up = events[1] + down.timestamp = clock_gettime_nsec_np(CLOCK_UPTIME_RAW) AppFixtureEventPosting.post(down) do { try await Task.sleep(for: .milliseconds(40)) } catch { AppFixtureEventPosting.post(up) @@ -333,6 +341,7 @@ struct AppFixtureKeyInput { guard !application.isTerminated, NSWorkspace.shared.frontmostApplication?.processIdentifier == pid else { throw AppFixtureDrag.rejected("FixtureApp lost focus or exited during synthetic keyboard input") } + return down.timestamp } } diff --git a/Sources/ParcelApp/NativeAppRuntime.swift b/Sources/ParcelApp/NativeAppRuntime.swift index 21ec5dd0..b9acf6be 100644 --- a/Sources/ParcelApp/NativeAppRuntime.swift +++ b/Sources/ParcelApp/NativeAppRuntime.swift @@ -264,7 +264,7 @@ final class NativeAppRuntime: AppRuntime { throw AppFixtureDrag.rejected( "Synthetic keyboard input is only available to the fixture-only e2e app") } - try await self.postFixtureKey(request) + return try await self.postFixtureKey(request) }, feedback: { [weak self] arguments in guard let feedback = self?.feedback else { throw AppText.failure("Parcel is shutting down.") } @@ -454,13 +454,13 @@ final class NativeAppRuntime: AppRuntime { feedback.controller.setSecureInput(secureInput.isEnabled, ownerName: secureInput.ownerName) } - private func postFixtureKey(_ request: AppFixtureKeyInput) async throws { + private func postFixtureKey(_ request: AppFixtureKeyInput) async throws -> UInt64 { guard let engine = services.engine, engine.isRunning, !services.isPaused, settings.onRecordedShortcut == nil else { throw AppFixtureDrag.rejected("Fixture keyboard input needs active tiling without shortcut capture") } _ = synchronizeMode() guard let effectiveShortcuts else { throw AppFixtureDrag.rejected("Fixture shortcuts are not registered") } - try await request.post(state: engine.snapshot.state, activeBindings: effectiveShortcuts) + return try await request.post(state: engine.snapshot.state, activeBindings: effectiveShortcuts) } static func hotkey(_ chord: KeyChord) -> HotKey { diff --git a/Tests/ParcelE2ETests/AppFixtureTimestampTests.swift b/Tests/ParcelE2ETests/AppFixtureTimestampTests.swift new file mode 100644 index 00000000..d8e3a954 --- /dev/null +++ b/Tests/ParcelE2ETests/AppFixtureTimestampTests.swift @@ -0,0 +1,20 @@ +import ParcelIPC +import Testing + +@testable import ParcelApp + +@Suite("Fixture keyboard stimulus timestamp") +struct AppFixtureTimestampTests { + @Test func acceptedReplyIncludesExactTimestamp() throws { + #expect( + try AppFixtureKeyInput.reply(timestamp: 123_456_789) + == .object([ + "accepted": .bool(true), "event_timestamp_ns": .integer(123_456_789), + ])) + } + + @Test(arguments: [UInt64(0), UInt64.max]) + func unavailableOrUnrepresentableTimestampFails(_ timestamp: UInt64) { + #expect(throws: IPCError.self) { try AppFixtureKeyInput.reply(timestamp: timestamp) } + } +} diff --git a/Tests/ParcelPerformanceTests/IdleTimerGuardTests.swift b/Tests/ParcelPerformanceTests/IdleTimerGuardTests.swift new file mode 100644 index 00000000..ef65fdeb --- /dev/null +++ b/Tests/ParcelPerformanceTests/IdleTimerGuardTests.swift @@ -0,0 +1,61 @@ +import Foundation +import Testing + +struct IdleWaitAllowance: Decodable { + let path: String + let count: Int + let why: String +} + +enum IdleTimerGuard { + static var waits: Regex { + /Timer\.scheduledTimer|DispatchSource\.makeTimerSource|Task\.sleep|asyncAfter/ + } + + static func validate(_ source: String, allowance: IdleWaitAllowance?) -> Bool { + let matches = source.matches(of: waits).count + guard matches > 0 else { return allowance == nil } + guard let allowance, allowance.count == matches, !allowance.why.isEmpty else { return false } + if source.contains("DispatchSource.makeTimerSource") { + guard !source.contains("flags: .strict"), source.contains("repeating: .never") else { return false } + } + return true + } +} + +@Suite("No unreviewed idle timers") +struct IdleTimerGuardTests { + @Test func everyWaitHasAnExplicitBoundedActivityReason() throws { + let repository = BenchmarkBaselines.repository + let allowances = try JSONDecoder().decode( + [IdleWaitAllowance].self, + from: Data(contentsOf: repository.appendingPathComponent("Benchmarks/idle-waits.json"))) + #expect(Set(allowances.map(\.path)).count == allowances.count) + let byPath = Dictionary(uniqueKeysWithValues: allowances.map { ($0.path, $0) }) + let sources = repository.appendingPathComponent("Sources") + let enumerator = try #require( + FileManager.default.enumerator( + at: sources, + includingPropertiesForKeys: nil)) + var used: Set = [] + for case let url as URL in enumerator where url.pathExtension == "swift" { + let path = String(url.path.dropFirst(sources.path.count + 1)) + let source = try String(contentsOf: url, encoding: .utf8) + #expect(IdleTimerGuard.validate(source, allowance: byPath[path]), "Unreviewed or changed wait: \(path)") + if byPath[path] != nil { used.insert(path) } + } + #expect(used == Set(byPath.keys), "Remove stale idle-wait allowances") + } + + @Test func newRepeatingOrStrictTimersAreRejected() { + #expect(!IdleTimerGuard.validate("Timer.scheduledTimer()", allowance: nil)) + let allowance = IdleWaitAllowance(path: "fixture", count: 1, why: "bounded") + #expect( + !IdleTimerGuard.validate( + "DispatchSource.makeTimerSource(flags: .strict); repeating: .never", allowance: allowance)) + #expect( + !IdleTimerGuard.validate("DispatchSource.makeTimerSource(); repeating: .seconds(1)", allowance: allowance)) + #expect(IdleTimerGuard.validate("DispatchSource.makeTimerSource(); repeating: .never", allowance: allowance)) + #expect(!IdleTimerGuard.validate("Task.sleep(); Task.sleep()", allowance: allowance)) + } +} -- knotmirror 0.0.1 From d7e1093f79c0b3ab2e16508df0f86fa7e05405dc Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 13:30:15 -0400 Subject: [PATCH 05/22] Measure hot paths with explicit budgets --- .../Overlays/StackChipController.swift | 17 +- .../BenchmarkCatalog.swift | 313 ++ .../Fixtures/windowlist-recorded.plist | 3369 +++++++++++++++++ .../HotPathBenchmarkTests.swift | 125 + .../HotPathBenchmarks.swift | 637 ++++ .../HotPathFixtures.swift | 568 +++ .../HotPathNativeFixtures.swift | 412 ++ 7 files changed, 5437 insertions(+), 4 deletions(-) create mode 100644 Tests/ParcelPerformanceTests/BenchmarkCatalog.swift create mode 100644 Tests/ParcelPerformanceTests/Fixtures/windowlist-recorded.plist create mode 100644 Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift create mode 100644 Tests/ParcelPerformanceTests/HotPathBenchmarks.swift create mode 100644 Tests/ParcelPerformanceTests/HotPathFixtures.swift create mode 100644 Tests/ParcelPerformanceTests/HotPathNativeFixtures.swift diff --git a/Sources/ParcelUI/Overlays/StackChipController.swift b/Sources/ParcelUI/Overlays/StackChipController.swift index 25bf57bb..d616ad23 100644 --- a/Sources/ParcelUI/Overlays/StackChipController.swift +++ b/Sources/ParcelUI/Overlays/StackChipController.swift @@ -4,17 +4,26 @@ public import ParcelCore @MainActor public final class StackChipController { - private var panels: [LearningPanel] = [] + private(set) var panels: [LearningPanel] = [] + private let orderPanels: Bool public private(set) var groups: [StackChipGroup] = [] private let focus: @MainActor (WindowID) -> Void private let close: @MainActor (WindowID) -> Void - public init( + public convenience init( focus: @escaping @MainActor (WindowID) -> Void, close: @escaping @MainActor (WindowID) -> Void + ) { + self.init(focus: focus, close: close, orderPanels: true) + } + + init( + focus: @escaping @MainActor (WindowID) -> Void, + close: @escaping @MainActor (WindowID) -> Void, orderPanels: Bool ) { self.focus = focus self.close = close + self.orderPanels = orderPanels } public func update(state: State, configuration: MotionConfiguration) { @@ -38,7 +47,7 @@ public final class StackChipController { } if !configuration.enabled { panel.contentView?.layer?.removeAllAnimations() } panel.place(group.frame) - panel.orderFront(nil) + if orderPanels { panel.orderFront(nil) } updated.append(panel) } for panel in remaining { panel.close() } @@ -47,7 +56,7 @@ public final class StackChipController { } public func focusChips() { - guard let panel = panels.first, let button = panel.contentView?.subviews.first else { return } + guard orderPanels, let panel = panels.first, let button = panel.contentView?.subviews.first else { return } NSApplication.shared.activate() panel.makeKeyAndOrderFront(nil) panel.makeFirstResponder(button) diff --git a/Tests/ParcelPerformanceTests/BenchmarkCatalog.swift b/Tests/ParcelPerformanceTests/BenchmarkCatalog.swift new file mode 100644 index 00000000..0838e1db --- /dev/null +++ b/Tests/ParcelPerformanceTests/BenchmarkCatalog.swift @@ -0,0 +1,313 @@ +import ParcelCore + +struct BenchmarkCatalogEntry: Codable, Equatable, Sendable { + enum Kind: String, Codable, Sendable { case headless, e2e, signpost } + enum Status: String, Codable, Sendable { case executable, unsupported } + let name: String + let kind: Kind + let status: Status + let iterations: Int + let budget: String + let reportingOnly: Bool + let reason: String? + + var cpuBudgetNanoseconds: Double? { + let count = Int(name.split(separator: "/").last ?? "") + if name.hasPrefix("reduce-layout/") { return 200_000 } + if name.hasPrefix("snapshot-publish/") { + return count == 10 ? 50_000 : count == 50 ? 200_000 : 800_000 + } + if name.hasPrefix("motion-tick/") { + return count == 1 ? 20_000 : count == 10 ? 100_000 : 300_000 + } + if name.hasPrefix("overlay-update/") { + return count == 1 ? 100_000 : count == 10 ? 300_000 : 800_000 + } + if name.hasPrefix("reduce.focusObservation.") { return 20_000 } + if name.hasPrefix("reduce.windowFrameEdited.tick.") || name.hasPrefix("reduce.tileEdgeResized.tick.") { + return name.hasSuffix("200") ? 2_000_000 : 500_000 + } + if name.hasPrefix("layout.arrange.") || name.hasPrefix("layout.edges.columns.") { return 500_000 } + switch name { + case "input-tap/keydown-hotkey": return 20_000 + case "input-tap/keydown-passthrough": return 5_000 + case "input-tap/mouse-moved": return 10_000 + case "motion-retarget/10": return 150_000 + case "overlay-frame/30": return 500_000 + case "window-list-read/decode-40": return 100_000 + case "window-list-read/decode-200": return 500_000 + case "WindowListDecode/200": return 300_000 + case "WatchdogBeginEnd": return 50 + case "reduce.batch.mixed8.50": return 2_000_000 + case "engine.snapshot.publish.1subs", "engine.snapshot.publish.4subs": return 50_000 + case "Overlay/HighlightUpdate/10-unchanged": return 50_000 + case "Overlay/HighlightUpdate/10-moved": return 300_000 + case "Overlay/Consume/50-windows": return 500_000 + case "Overlay/ThemeChange/10-windows": return 1_000_000 + case "MenuBar/IconRender": return 200_000 + case "Chips/Update/unchanged": return 20_000 + default: return nil + } + } +} + +enum BenchmarkCatalog { + private static let core = + "Core layout reuse, workspace indexing, adaptation and copy narrowing are pending; collect measurements without gating." + private static let motion = + "Motion coalescing, per-window rates and allocation fixes are pending; collect actual dispatch/sample counts without gating." + private static let platform = + "Native event and AX write fast paths are pending. Fake-backend method calls are measured, not inferred AX calls or actor hops." + private static let overlay = + "Persistent layers, render coalescing and shared palette fixes are pending; layer identity deltas count new reachable layers, not total mallocs." + + static let entries: [BenchmarkCatalogEntry] = { + var values: [BenchmarkCatalogEntry] = [] + func headless(_ name: String, _ budget: String, _ reason: String, iterations: Int = 10) { + values.append( + BenchmarkCatalogEntry( + name: name, kind: .headless, status: .executable, + iterations: iterations, budget: budget, reportingOnly: true, reason: reason)) + } + func deferred(_ name: String, _ kind: BenchmarkCatalogEntry.Kind, _ budget: String, _ reason: String) { + values.append( + BenchmarkCatalogEntry( + name: name, kind: kind, status: .unsupported, + iterations: 0, budget: budget, reportingOnly: true, reason: reason)) + } + for (variant, budget) in [ + ("keydown-hotkey", "20 us"), ("keydown-passthrough", "5 us"), ("mouse-moved", "10 us"), + ] { + headless( + "input-tap/\(variant)", "instructions +3%; release CPU <= \(budget)", + "Input callback dispatch runs with synthetic CGEvent and real handlers; event-tap scheduling and kernel delivery require live tracing.", + iterations: 100) + } + for count in [10, 50, 200] { + for kind in ["window-moved", "window-created", "focus"] { + let budget = + kind == "focus" + ? (count == 10 ? "0.2" : count == 50 ? "1" : "4") : (count == 10 ? "0.5" : count == 50 ? "2" : "8") + headless( + "ax-notify-to-decision/\(kind)/\(count)", "instructions +3%; release CPU <= \(budget) ms", platform, + iterations: 3) + } + headless( + "snapshot-publish/\(count)", + "instructions +3%; release CPU <= \(count == 10 ? 50 : count == 50 ? 200 : 800) us", core) + for workspaces in [1, 8] { + headless( + "reduce.focusObservation.\(count)x\(workspaces)ws", + "release CPU <= 20 us at 200 windows; linear 50->200 scaling", core) + } + for variant in ["windowFrameEdited", "tileEdgeResized"] { + headless("reduce.\(variant).tick.\(count)", "release CPU <= 0.5 ms at 50; <= 2 ms at 200", core) + } + } + for layout in Layout.allCases { + headless("reduce-layout/\(layout.rawValue)/10", "instructions +3%; release CPU <= 0.2 ms", core) + } + for count in [1, 10, 30] { + headless( + "motion-tick/\(count)", + "instructions +3%; mallocs/tick exact; release CPU/tick <= \(count == 1 ? 20 : count == 10 ? 100 : 300) us", + motion) + headless( + "overlay-update/\(count)", + "instructions +3%; release CPU <= \(count == 1 ? 100 : count == 10 ? 300 : 800) us", overlay) + } + headless("motion-retarget/10", "instructions +3%; release CPU <= 150 us", motion) + headless("overlay-frame/30", "instructions +3%; mallocs/frame exact; release CPU <= 500 us", overlay) + for count in [40, 200] { + headless( + "window-list-read/decode-\(count)", "instructions +3%; release CPU <= \(count == 40 ? 100 : 500) us", + "Integer decoding optimization pending; sanitized recorded geometry is selected/repeated to scale the corpus, with fixture parsing excluded." + ) + } + for variant in ["default", "500-rules"] { + headless( + "config-reload/\(variant)", "instructions +3%; release CPU <= \(variant == "default" ? 2 : 15) ms", + "Disk reload and AppliedConfiguration conversion run on ConfigStore's actor; async wall time is diagnostic, not a synchronous instruction gate.", + iterations: 1) + } + headless( + "motion-soak/30x10000", "retained bytes after stop within +/- 64 KiB; no idle display source", + "Retained malloc-zone bytes are process-wide diagnostics, not total allocations or a leak verdict; motion lifetime fixes pending.", + iterations: 1) + headless("CoalescerProMotionJitter", "exactly one dispatch per app per tick with +/- 3e-11 s jitter", motion) + headless( + "AXWriteFastPathCalls", "non-final <= 1 position call; final <= 5 AX calls", + "Burst writer not implemented. Real executeFrameWrite is driven by counting attribute access; frame getters count their two attribute reads." + ) + headless("EnhancedUIToggleCount", "two EnhancedUI sets per app per 24-frame burst", platform) + headless( + "EchoReadsDuringGlide", "zero frame reads per non-final frame; one per window after final", platform, + iterations: 1) + headless( + "PerWindowRateContinuity", "monotonic; >= 100 fps at 8.4 ms; no app-wide snap below 40 ms per window", + motion) + headless("NeighbourPhaseDivergence", "edge gap/overlap <= 4 pt; intersection area zero", motion) + headless("GhostTransition50", "second transition CA commit < 1 ms; zero new layers", overlay, iterations: 3) + headless("AnimationTick200", "release tick p99 < 0.1 ms", motion, iterations: 3) + headless("AnimationSchedule200", "release schedule p99 < 0.5 ms", motion, iterations: 3) + headless( + "FocusFastPath/50", "<= 2 AX calls; zero window-list reads; <= 1 main hop; CPU < 0.2 ms", platform, + iterations: 3) + headless( + "FocusLatencyWithHungApp", "app B focus applied < 2 ms while app A windows blocks 350 ms", platform, + iterations: 1) + headless( + "CreatedToWriteHops", "<= 2 hops; <= 4 AX calls; speculative placement zero hops", platform, iterations: 3) + headless( + "AppWriteBatch/20", "<= 8 AX calls/window; no O(N) lookup; one executor job", + "Real executeFrameWrite calls measured for 20 counting windows; production executor job and lookup instrumentation are absent, so no job/lookup count is fabricated." + ) + headless( + "FactsReadPerWindow", "<= 3 batched AX calls per window", + "WindowFactsReader.gather uses counting WindowFactsAccess; counts access methods, not hidden native IPC fan-out. Attribute batching is pending." + ) + headless( + "MoveStormCoalesce", "500 moves -> <= 1 pending/window; zero enumerations", + "Real NativeEngineWorld consumes 500 synthetic app events; frame reads measured. Worker pending-slot/enumeration hooks are absent; mailbox coalescing pending.", + iterations: 1) + headless("SpaceChangeTurn", "one Space read; only changed displays suspended", platform, iterations: 1) + headless( + "SettleReconcileCost", "5 apps x 6 windows: zero facts reads; <= 1 window-list read", platform, + iterations: 1) + headless("WindowListDecode/200", "release CPU < 0.3 ms", platform) + headless( + "WatchdogBeginEnd", "release CPU < 50 ns; zero timer allocations", + "Real AXCallWatchdog begin/end with native deadline timer; persistent worker timer optimization pending, timer allocations not inferred.", + iterations: 100) + for count in [50, 200] { + headless("reduce.batch.mixed8.\(count)", "release CPU <= 2 ms at 50; allocation bytes scale linearly", core) + headless("layout.edges.columns.\(count)", "release CPU <= 0.5 ms at 200; no crash", core, iterations: 3) + headless( + "engine.turn.wall.\(count)", "wall p99 <= 2 ms at 50; report only on noisy host", core, iterations: 3) + } + for layout in [Layout.columns, .rows, .accordion] { + headless( + "layout.arrange.\(layout.rawValue).200", "release CPU <= 0.5 ms; no recursion crash", core, + iterations: 3) + } + for subscribers in [1, 4] { + headless( + "engine.snapshot.publish.\(subscribers)subs", "release CPU <= 50 us; includes next-turn copy cost", core + ) + } + headless("Overlay/HighlightUpdate/10-unchanged", "CPU < 50 us; zero new layers", overlay) + headless("Overlay/HighlightUpdate/10-moved", "CPU < 300 us", overlay) + headless( + "Overlay/Consume/50-windows", "main-thread CPU < 0.5 ms; privacy reads <= 2 per glide second", overlay, + iterations: 3) + headless("Overlay/PrivacyBackdrop/update-8-cutouts", "unchanged < 30 us; changed < 200 us", overlay) + headless( + "Overlay/ThemeChange/10-windows", "CPU < 1 ms", + "Explicit appearance-context restyle measures existing update path; live palette invalidation/cache is pending.", + iterations: 3) + headless( + "MenuBar/IconRender", "image < 0.2 ms; cached repeat < 5 us", + "Real image(for:) is lazy; image is drawn into a bitmap so the workload actually rasterizes. Rendered-image caching pending." + ) + headless("Chips/Update/unchanged", "CPU < 20 us; zero orderFront calls", overlay) + + deferred( + "reduce.layoutCallsPerEvent", .headless, "one traverse/undoable event; zero/focus", + "Reducer stage trace does not observe layouts performed by undo preparation; requires a test-only LayoutEngine.traverse counter." + ) + deferred( + "undo.position.columns.200", .headless, "CPU <= 100 us", + "TileTree.undoPosition is fileprivate and cannot be isolated through @testable; needs a narrow internal accessor or traversal counter." + ) + deferred( + "MotionBatchMainActorOverhead", .signpost, "dispatch-to-receipt minus AppThread job < 0.2 ms", + "Write receipt does not expose measured AppThread job duration; fake duration subtraction would invent overhead." + ) + deferred( + "DisplayChangeLatency", .signpost, "reconfiguration completion to display publish < 60 ms", + "CGDisplay completion callback hook is pending; current debounce cannot simulate an absent callback honestly." + ) + deferred( + "window-list-read/live", .e2e, "none; report p50/p99/max", + "Live CGWindowList depends on the user's windows and WindowServer load; excluded from permission-free deterministic smoke." + ) + for (scenario, budget) in [ + ("swap-2-windows", "starved <= 1; first move p50 <= 1 frame, p95 <= 2 frames; settle <= 250 ms"), + ("layout-change-10", "starved <= 2%; max gap <= 2 refreshes"), + ("layout-change-30", "starved <= 5%; initially reporting only"), + ("hotkey-focus-move", "first move p50 <= 1 frame + write latency"), + ("slow-neighbour", "normal window starved <= 1; first move delta <= 2 ms"), + ("new-window-to-tile", "first write p50/p95 <= 8/16 ms; tiled <= 20/40 ms"), + ] { + deferred( + scenario, .e2e, budget, + "Requires opt-in FixtureApp frame/vsync recording and Parcel Accessibility grant; never launches live windows in headless smoke." + ) + } + for state in ["settled", "after-space-switch", "after-config-reload"] { + deferred( + "idle/\(state)", .e2e, "60 s: CPU < 5 ms; instructions < 5M; interrupt/package wakeups <= 2", + "Requires a separately launched granted Parcel process and a 60-second quiet window; not headless workload." + ) + } + deferred( + "soak/30x2000", .e2e, "footprint < 40 MB; tail slope < 8 KiB/command", + "Requires live fixture windows and process footprint samples; PARCEL_E2E=1 and PARCEL_SOAK=1 only.") + deferred( + "leaks/30-windows", .e2e, "zero leaks", + "Requires debug-only task inspection, stack logging and live process memgraph; not headless.") + deferred( + "Overlay/BorderLag", .signpost, "<= 1 frame of displacement; edge offset p95 <= 2 pt", + "Needs engine tick/confirmed AX geometry correlation and opt-in live capture; no window visibility in headless smoke." + ) + for (name, budget) in [ + ("overlay.render", "<= 1 render/display/frame"), ("motion.dispatch", "one dispatch/app/tick"), + ("ax.write", "one position call/non-final frame; report calls/per-window ms/final"), + ("ax.read.frame", "zero non-final echo reads; one final reconcile/window"), + ("ax.enhancedUI.toggle", "two toggles/app/burst"), ("motion.batch", "actor overhead < 0.2 ms"), + ("appthread.callback", "AX arrival starts detection interval"), + ("world.refresh", "apps progress independently; report AX calls"), + ("space.notify", "notification-to-placement interval"), ("space.read", "one read/change"), + ("space.retile", "destination placed before arrival"), ("display.change", "publish < 60 ms"), + ("appthread.speculativeWrite", "new-window first write < 8 ms p50"), + ("menu.render", "closed menu renders <= distinct layout changes"), + ] { + deferred( + name, .signpost, budget, + "Requires a live trace sink and native workload; production trace sites/counters are integrated separately." + ) + } + let traceLanes: [(String, [String])] = [ + ("pointsOfInterest", ["Command", "Event to settled"]), + ("Engine", ["Detect", "Apply", "Layout", "Diff", "Reduce", "Plan", "Publish", "Event to first write"]), + ("Input", ["Tap callback", "Hotkey dispatch"]), + ("Motion", ["Tick", "Write", "Settle", "Snap"]), + ("Overlay", ["Overlay update", "Ghost render"]), + ("Platform", ["Window list read", "Space read", "Display reconfigure"]), + ("Config", ["Reload"]), + ] + for (category, intervals) in traceLanes { + for interval in intervals { + deferred( + "trace/\(category)/\(interval)", .signpost, + "diagnostic interval; correlate with frame, decision and write budgets", + "Requires an attached live signpost recorder; excluded from deterministic headless baseline coverage." + ) + } + } + return values + }() + + static var names: Set { + Set(entries.filter { $0.kind == .headless && $0.status == .executable }.map(\.name)) + } + static var definitions: [String: Int] { + Dictionary(uniqueKeysWithValues: entries.filter { names.contains($0.name) }.map { ($0.name, $0.iterations) }) + } + static func definition(named name: String) -> BenchmarkCatalogEntry { + guard let entry = entries.first(where: { $0.name == name }) else { + preconditionFailure("Uncatalogued benchmark: \(name)") + } + return entry + } +} diff --git a/Tests/ParcelPerformanceTests/Fixtures/windowlist-recorded.plist b/Tests/ParcelPerformanceTests/Fixtures/windowlist-recorded.plist new file mode 100644 index 00000000..958df1ab --- /dev/null +++ b/Tests/ParcelPerformanceTests/Fixtures/windowlist-recorded.plist @@ -0,0 +1,3369 @@ + + + + + + kCGWindowBounds + + Height + 200 + Width + 200 + X + 656 + Y + 642 + + kCGWindowLayer + 2005 + kCGWindowNumber + 1 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 268 + Width + 460 + X + 755 + Y + 38 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 2 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 0.0 + Y + 482 + + kCGWindowLayer + 0 + kCGWindowNumber + 3 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 500 + Width + 500 + X + 0.0 + Y + 482 + + kCGWindowLayer + 0 + kCGWindowNumber + 4 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 886 + Width + 491 + X + 224 + Y + 38 + + kCGWindowLayer + 0 + kCGWindowNumber + 5 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 6 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 7 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 646 + Y + 559 + + kCGWindowLayer + 0 + kCGWindowNumber + 8 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 300 + Width + 300 + X + 755 + Y + 491 + + kCGWindowLayer + 3000 + kCGWindowNumber + 9 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 500 + Width + 500 + X + 0.0 + Y + 482 + + kCGWindowLayer + 0 + kCGWindowNumber + 10 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 721 + Width + 1378 + X + 83 + Y + 74 + + kCGWindowLayer + 0 + kCGWindowNumber + 11 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 48 + Width + 53 + X + 0.0 + Y + 982 + + kCGWindowLayer + 0 + kCGWindowNumber + 12 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 14 + Width + 596 + X + 0.0 + Y + 982 + + kCGWindowLayer + 0 + kCGWindowNumber + 13 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 719 + Width + 1433 + X + 17 + Y + 142 + + kCGWindowLayer + 0 + kCGWindowNumber + 14 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 14 + Width + 573 + X + 0.0 + Y + 982 + + kCGWindowLayer + 0 + kCGWindowNumber + 15 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 500 + Width + 500 + X + 0.0 + Y + 482 + + kCGWindowLayer + 0 + kCGWindowNumber + 16 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 0.0 + Width + 0.0 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 17 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 244 + Width + 667 + X + 799 + Y + 110 + + kCGWindowLayer + 101 + kCGWindowNumber + 18 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 244 + Width + 792 + X + 770 + Y + 81 + + kCGWindowLayer + 101 + kCGWindowNumber + 19 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 244 + Width + 667 + X + 741 + Y + 52 + + kCGWindowLayer + 101 + kCGWindowNumber + 20 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 177 + Width + 461 + X + 525 + Y + 216 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 21 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 500 + Width + 500 + X + 0.0 + Y + 482 + + kCGWindowLayer + 0 + kCGWindowNumber + 22 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 814 + Width + 1353 + X + 159 + Y + 112 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 23 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 24 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 25 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 26 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 0.0 + Width + 0.0 + X + 0.0 + Y + 982 + + kCGWindowLayer + 0 + kCGWindowNumber + 27 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 464 + Width + 920 + X + 43 + Y + 448 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 28 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 500 + Width + 500 + X + 0.0 + Y + 482 + + kCGWindowLayer + 0 + kCGWindowNumber + 29 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 886 + Width + 1512 + X + 0.0 + Y + 38 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 30 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 31 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 32 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 33 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 34 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 0.0 + Y + 928 + + kCGWindowLayer + 0 + kCGWindowNumber + 35 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 500 + Width + 500 + X + 0.0 + Y + 482 + + kCGWindowLayer + 0 + kCGWindowNumber + 36 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 778 + Width + 1512 + X + 0.0 + Y + 58 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 37 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 38 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 39 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 40 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 41 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 42 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 244 + Width + 667 + X + 712 + Y + 666 + + kCGWindowLayer + 101 + kCGWindowNumber + 43 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 244 + Width + 667 + X + 683 + Y + 637 + + kCGWindowLayer + 101 + kCGWindowNumber + 44 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 18 + Width + 94 + X + 760 + Y + 504 + + kCGWindowLayer + 103 + kCGWindowNumber + 45 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 0.0 + Y + 928 + + kCGWindowLayer + 0 + kCGWindowNumber + 46 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 500 + Width + 500 + X + 0.0 + Y + 482 + + kCGWindowLayer + 0 + kCGWindowNumber + 47 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 474 + Width + 750 + X + 328 + Y + 450 + + kCGWindowLayer + 8 + kCGWindowNumber + 48 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 37 + Width + 32 + X + 1150 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 25 + kCGWindowNumber + 49 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 37 + Width + 38 + X + 1036 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 25 + kCGWindowNumber + 50 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 37 + Width + 35 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 25 + kCGWindowNumber + 51 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 244 + Width + 667 + X + 567 + Y + 521 + + kCGWindowLayer + 101 + kCGWindowNumber + 52 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 669 + Width + 1029 + X + 310 + Y + 38 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 53 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 54 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 55 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 56 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 0.0 + Y + 482 + + kCGWindowLayer + 0 + kCGWindowNumber + 57 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 37 + Width + 32 + X + 1300 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 25 + kCGWindowNumber + 58 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 244 + Width + 667 + X + 538 + Y + 492 + + kCGWindowLayer + 101 + kCGWindowNumber + 59 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 24 + kCGWindowNumber + 60 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 0.0 + Y + 928 + + kCGWindowLayer + 0 + kCGWindowNumber + 61 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 24 + kCGWindowNumber + 62 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 63 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 560 + Y + 872 + + kCGWindowLayer + 0 + kCGWindowNumber + 64 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 0.0 + Y + 482 + + kCGWindowLayer + 0 + kCGWindowNumber + 65 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 66 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 67 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 68 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 743 + Width + 1218 + X + 54 + Y + 136 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 69 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 37 + Width + 34 + X + 1332 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 25 + kCGWindowNumber + 70 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + -2147483624 + kCGWindowNumber + 71 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + -2147483624 + kCGWindowNumber + 72 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 0.0 + Y + 928 + + kCGWindowLayer + 0 + kCGWindowNumber + 73 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 20 + kCGWindowNumber + 74 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 20 + kCGWindowNumber + 75 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 886 + Width + 715 + X + 0.0 + Y + 38 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 76 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 3003 + kCGWindowNumber + 77 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 0.0 + Y + 928 + + kCGWindowLayer + 0 + kCGWindowNumber + 78 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + -2147483626 + kCGWindowNumber + 79 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + -2147483624 + kCGWindowNumber + 80 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 0.0 + Width + 0.0 + X + 0.0 + Y + 982 + + kCGWindowLayer + 8 + kCGWindowNumber + 81 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 560 + Y + 872 + + kCGWindowLayer + 0 + kCGWindowNumber + 82 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 19 + Width + 55 + X + 1144 + Y + 190 + + kCGWindowLayer + 103 + kCGWindowNumber + 83 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 500 + Width + 500 + X + 0.0 + Y + 482 + + kCGWindowLayer + 0 + kCGWindowNumber + 84 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 85 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 86 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 87 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 88 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 552 + Width + 890 + X + 311 + Y + 136 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 89 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 37 + Width + 38 + X + 1074 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 25 + kCGWindowNumber + 90 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 244 + Width + 667 + X + 654 + Y + 608 + + kCGWindowLayer + 101 + kCGWindowNumber + 91 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 244 + Width + 667 + X + 625 + Y + 579 + + kCGWindowLayer + 101 + kCGWindowNumber + 92 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 93 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 0.0 + Width + 0.0 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 94 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 184 + Width + 422 + X + 545 + Y + 214 + + kCGWindowLayer + 0 + kCGWindowNumber + 95 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 500 + Width + 500 + X + 0.0 + Y + 482 + + kCGWindowLayer + 0 + kCGWindowNumber + 96 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 97 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 4000 + kCGWindowNumber + 98 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 244 + Width + 667 + X + 596 + Y + 550 + + kCGWindowLayer + 101 + kCGWindowNumber + 99 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 0.0 + Y + 482 + + kCGWindowLayer + 0 + kCGWindowNumber + 100 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 23 + kCGWindowNumber + 101 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 37 + Width + 38 + X + 1112 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 25 + kCGWindowNumber + 102 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 103 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 244 + Width + 667 + X + 509 + Y + 463 + + kCGWindowLayer + 101 + kCGWindowNumber + 104 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 0.0 + Y + 928 + + kCGWindowLayer + 0 + kCGWindowNumber + 105 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 37 + Width + 33 + X + 1121 + Y + 0.0 + + kCGWindowLayer + 25 + kCGWindowNumber + 106 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 24 + kCGWindowNumber + 107 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 743 + Width + 931 + X + 0.0 + Y + 38 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 108 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 945 + Width + 1512 + X + 0.0 + Y + 37 + + kCGWindowLayer + 0 + kCGWindowNumber + 109 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 578 + Width + 742 + X + 308 + Y + 285 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 110 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 0.0 + Y + 928 + + kCGWindowLayer + 0 + kCGWindowNumber + 111 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 112 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 113 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 114 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 459 + Width + 774 + X + 203 + Y + 50 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 115 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 116 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 117 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 37 + Width + 32 + X + 928 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 25 + kCGWindowNumber + 118 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 0.0 + Y + 928 + + kCGWindowLayer + 0 + kCGWindowNumber + 119 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 0.0 + Y + 928 + + kCGWindowLayer + 0 + kCGWindowNumber + 120 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 500 + Width + 500 + X + 0.0 + Y + 482 + + kCGWindowLayer + 0 + kCGWindowNumber + 121 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 52 + Width + 600 + X + 456 + Y + 197 + + kCGWindowLayer + 23 + kCGWindowNumber + 122 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 244 + Width + 667 + X + 480 + Y + 434 + + kCGWindowLayer + 101 + kCGWindowNumber + 123 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 244 + Width + 667 + X + 451 + Y + 405 + + kCGWindowLayer + 101 + kCGWindowNumber + 124 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 19 + Width + 191 + X + 285 + Y + 494 + + kCGWindowLayer + 103 + kCGWindowNumber + 125 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 37 + Width + 42 + X + 1220 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 25 + kCGWindowNumber + 126 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 37 + Width + 48 + X + 882 + Y + 0.0 + + kCGWindowLayer + 25 + kCGWindowNumber + 127 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 75 + Width + 198 + X + 100 + Y + 106 + + kCGWindowLayer + 103 + kCGWindowNumber + 128 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 56 + Width + 116 + X + 636 + Y + 708 + + kCGWindowLayer + 1000 + kCGWindowNumber + 129 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 37 + Width + 38 + X + 890 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 25 + kCGWindowNumber + 130 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 720 + Width + 720 + X + 516 + Y + 174 + + kCGWindowLayer + 3 + kCGWindowNumber + 131 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + -2147483603 + kCGWindowNumber + 132 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + -2147483622 + kCGWindowNumber + 133 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + -2147483624 + kCGWindowNumber + 134 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 44 + Width + 1512 + X + 0.0 + Y + 37 + + kCGWindowLayer + 0 + kCGWindowNumber + 135 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 431 + Width + 744 + X + 8 + Y + 46 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 136 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 359 + Width + 224 + X + 0.0 + Y + 607 + + kCGWindowLayer + 3 + kCGWindowNumber + 137 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 1000 + kCGWindowNumber + 138 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 96 + Width + 240 + X + 0.0 + Y + 886 + + kCGWindowLayer + 1000 + kCGWindowNumber + 139 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 240 + Width + 240 + X + 321 + Y + 420 + + kCGWindowLayer + 1000 + kCGWindowNumber + 140 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 3 + kCGWindowNumber + 141 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 37 + Width + 38 + X + 960 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 25 + kCGWindowNumber + 142 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 37 + Width + 38 + X + 1182 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 25 + kCGWindowNumber + 143 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 500 + Width + 500 + X + 0.0 + Y + 482 + + kCGWindowLayer + 0 + kCGWindowNumber + 144 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + -2147483625 + kCGWindowNumber + 145 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 37 + Width + 38 + X + 1262 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 25 + kCGWindowNumber + 146 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 692 + Width + 1092 + X + 42 + Y + 221 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 147 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 37 + Width + 148 + X + 1366 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 25 + kCGWindowNumber + 148 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 346 + Width + 480 + X + 1031 + Y + 517 + + kCGWindowLayer + 3 + kCGWindowNumber + 149 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 150 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 4000 + kCGWindowNumber + 151 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 37 + Width + 38 + X + 998 + Y + 0.0 + + kCGWindowIsOnscreen + + kCGWindowLayer + 25 + kCGWindowNumber + 152 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 153 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 23 + Width + 17 + X + 524 + Y + 750 + + kCGWindowLayer + 2147483630 + kCGWindowNumber + 154 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 54 + Width + 54 + X + 646 + Y + 559 + + kCGWindowLayer + 3 + kCGWindowNumber + 155 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 32 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + -2147483602 + kCGWindowNumber + 156 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 32 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + -2147483602 + kCGWindowNumber + 157 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 158 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 159 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 160 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 161 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 244 + Width + 667 + X + 422 + Y + 376 + + kCGWindowLayer + 101 + kCGWindowNumber + 162 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 24 + kCGWindowNumber + 163 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 982 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + -2147483622 + kCGWindowNumber + 164 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 888 + Width + 1105 + X + 88 + Y + 38 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 165 + kCGWindowOwnerPID + 5 + + + kCGWindowBounds + + Height + 945 + Width + 1512 + X + 0.0 + Y + 37 + + kCGWindowLayer + 0 + kCGWindowNumber + 166 + kCGWindowOwnerPID + 6 + + + kCGWindowBounds + + Height + 76 + Width + 302 + X + 100 + Y + 822 + + kCGWindowLayer + 2999 + kCGWindowNumber + 167 + kCGWindowOwnerPID + 7 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 168 + kCGWindowOwnerPID + 8 + + + kCGWindowBounds + + Height + 500 + Width + 500 + X + 0.0 + Y + 482 + + kCGWindowLayer + 0 + kCGWindowNumber + 169 + kCGWindowOwnerPID + 1 + + + kCGWindowBounds + + Height + 817 + Width + 630 + X + 441 + Y + 72 + + kCGWindowLayer + 3 + kCGWindowNumber + 170 + kCGWindowOwnerPID + 2 + + + kCGWindowBounds + + Height + 44 + Width + 1512 + X + 0.0 + Y + 37 + + kCGWindowLayer + 0 + kCGWindowNumber + 171 + kCGWindowOwnerPID + 3 + + + kCGWindowBounds + + Height + 37 + Width + 1512 + X + 0.0 + Y + 0.0 + + kCGWindowLayer + 0 + kCGWindowNumber + 172 + kCGWindowOwnerPID + 4 + + + kCGWindowBounds + + Height + 600 + Width + 950 + X + 143 + Y + 171 + + kCGWindowIsOnscreen + + kCGWindowLayer + 0 + kCGWindowNumber + 173 + kCGWindowOwnerPID + 5 + + + diff --git a/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift b/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift new file mode 100644 index 00000000..cc731f07 --- /dev/null +++ b/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift @@ -0,0 +1,125 @@ +import AppKit +import ParcelAnimation +import ParcelConfig +import ParcelCore +import ParcelTestSupport +import Testing + +@testable import ParcelEngine +@testable import ParcelPlatform +@testable import ParcelUI + +@Suite("Hot-path benchmark catalog") +struct HotPathCatalogTests { + @Test func namesAreUniqueAndOnlyExecutableHeadlessCasesNeedBaselines() { + let entries = BenchmarkCatalog.entries + #expect(Set(entries.map(\.name)).count == entries.count) + #expect(Set(BenchmarkCatalog.definitions.keys) == BenchmarkCatalog.names) + for entry in entries { + #expect(!entry.budget.isEmpty) + #expect(entry.reportingOnly) + #expect(entry.reason?.isEmpty == false) + if entry.status == .unsupported || entry.kind != .headless { + #expect(!BenchmarkCatalog.names.contains(entry.name)) + #expect(entry.iterations == 0) + } else { + #expect(BenchmarkCatalog.names.contains(entry.name)) + #expect(entry.iterations > 0) + } + } + } + + @Test(arguments: [40, 200]) func recordedWindowCorpusDecodesCompleteGeometry(_ count: Int) throws { + let windows = try RecordedWindowFixture(count: count).decode() + #expect(windows.count == count) + #expect(Set(windows.map(\.number)).count == count) + #expect(windows.allSatisfy { $0.bounds.width >= 0 && $0.bounds.height >= 0 }) + #expect(windows.allSatisfy { (1...8).contains($0.pid) }) + } + + @Test(arguments: [10, 50, 200], [1, 8]) + func workspaceFixturesPreserveUniqueMembershipAndInactiveGeometry(count: Int, workspaces: Int) throws { + let fixture = HotPathStateFixture(count: count, workspaces: workspaces) + #expect(fixture.state.windows.count == count) + #expect(fixture.state.workspaces.count == workspaces) + #expect(fixture.state.frames.count == count) + let members = fixture.state.workspaces.values.flatMap(\.order) + #expect(Set(members).count == count) + #expect(members.count == count) + let target = try #require(fixture.activeIDs.last) + let next = reduce(fixture.state, .focusChanged(target)).0 + #expect(next.focusedWindow == target) + for key in fixture.keys where !fixture.state.isActive(key) { + for id in try #require(fixture.state.workspaces[key]).order { + #expect(next.frames[id] == fixture.state.frames[id]) + } + } + } +} + +extension AppKitTestSuite { + @Suite("Hot-path benchmark proofs", .timeLimit(.minutes(10))) + @MainActor + struct HotPathBenchmarkTests { + @Test func executableCoverageUsesRealWorkloads() async throws { + var harness = BenchmarkHarness(full: false) + try await HotPathBenchmarks.run(&harness) + #expect(Set(harness.results.map(\.name)) == BenchmarkCatalog.names) + #expect(harness.results.count == BenchmarkCatalog.names.count) + #expect(harness.results.allSatisfy { $0.checksum != 0 }) + let jitter = try #require(harness.results.first { $0.name == "CoalescerProMotionJitter" }) + #expect(jitter.proofMetrics["ticks"] == 600) + #expect(try #require(jitter.proofMetrics["dispatches"]) > 0) + let decoded = try #require(harness.results.first { $0.name == "WindowListDecode/200" }) + #expect(decoded.proofMetrics["decoded-windows"] == 200) + let facts = try #require(harness.results.first { $0.name == "FactsReadPerWindow" }) + #expect(try #require(facts.proofMetrics["fact-access-method-reads"]) > 0) + let moved = try #require(harness.results.first { $0.name == "MoveStormCoalesce" }) + #expect(moved.proofMetrics["application-frame-reads"] == 500) + } + + @Test func offscreenControllersRenderWithoutOrderingPanels() throws { + let fixture = HotPathOverlayFixture(count: 10) + defer { fixture.stop() } + let update = try fixture.updatePair() + #expect(update.proofMetrics["ghost-tiles"] == 10) + #expect(update.proofMetrics["reachable-layers"].map { $0 > 0 } == true) + #expect(fixture.controller.panels.values.allSatisfy { !$0.isVisible }) + fixture.enablePrivacy() + _ = fixture.framePair() + #expect(fixture.controller.privacyPanels.values.allSatisfy { !$0.isVisible }) + #expect(fixture.controller.backdrops.values.allSatisfy { !$0.isVisible }) + let chips = StackChipController( + focus: { _ in Issue.record("Headless chips stole focus") }, close: { _ in }, orderPanels: false) + defer { chips.stop() } + chips.update(state: HotPathOverlayFixture.chipState(), configuration: MotionConfiguration()) + #expect(!chips.groups.isEmpty) + #expect(!chips.panels.isEmpty) + #expect(chips.panels.allSatisfy { !$0.isVisible }) + chips.focusChips() + #expect(chips.panels.allSatisfy { !$0.isVisible }) + } + + @Test func motionUsesTheDriverAndReleasesItsSource() throws { + let fixture = MotionTickFixture(count: 30) + let first = try fixture.run() + let second = try fixture.run() + #expect(first.checksum == second.checksum) + #expect(first.proofMetrics["sampled-frames"].map { $0 > 0 } == true) + #expect(first.proofMetrics["dispatched-batches"].map { $0 > 0 } == true) + #expect(fixture.source.starts > 0) + #expect(fixture.source.stops > 0) + #expect(!fixture.source.isRunning) + } + + @Test func frameAccessProofCountsAreReadFromTheFake() throws { + let single = try HotPathBenchmarks.frameWrites(windows: 1, ticks: 1) + let burst = try HotPathBenchmarks.frameWrites(windows: 1, ticks: 24) + #expect(single.proofMetrics["position-sets"] == 1) + #expect(single.proofMetrics["size-sets"] == 0) + #expect(single.proofMetrics["enhanced-ui-sets"] == 2) + #expect(burst.proofMetrics["position-sets"] == 24) + #expect(burst.proofMetrics["enhanced-ui-sets"] == 48) + } + } +} diff --git a/Tests/ParcelPerformanceTests/HotPathBenchmarks.swift b/Tests/ParcelPerformanceTests/HotPathBenchmarks.swift new file mode 100644 index 00000000..6115ba55 --- /dev/null +++ b/Tests/ParcelPerformanceTests/HotPathBenchmarks.swift @@ -0,0 +1,637 @@ +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) + try motionCases(&harness) + try inputCases(&harness) + try platformCases(&harness) + try overlayCases(&harness) + try await configCases(&harness) + try await nativeCases(&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), + ]) + } + + private static func motionCases(_ harness: inout BenchmarkHarness) throws { + 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() + observation.counterOperations = 30 + return observation + } + } + let soak = MotionTickFixture(count: 30) + try measure("motion-soak/30x10000", &harness, latencySamples: 0) { + let before = hotPathRetainedBytes() + var result = try soak.run(ticks: 10000) + result.counterOperations = 10000 + 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 cpu = BenchmarkCPUClock.now() + let start = ContinuousClock.now + let reversed = requests.map { request in + MotionRequest( + windowID: request.windowID, appID: request.appID, start: request.start, + target: request.start, screen: request.screen) + } + try animator.schedule(reversed, at: 100.075) + let wall = BenchmarkHarness.nanoseconds(start.duration(to: .now)) + let elapsed = BenchmarkCPUClock.elapsed(since: cpu) + 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, + 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: ["commands-enqueued": 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: ["commands-enqueued": 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..= workspaces && workspaces > 0) + let displays = (0..<(workspaces == 1 ? 1 : 2)).map { index in + ParcelCore.Display( + id: DisplayID(rawValue: "hot-path-\(index)"), + frame: Rect(x: Double(index) * 3840, width: 3840, height: 2160)) + } + keys = (0.. Int { + frames.keys.sorted().reduce(1) { result, id in + guard let frame = frames[id] else { preconditionFailure("Missing checksum frame") } + return result &+ Int(id.rawValue) &+ Int((frame.minX * 1000).rounded()) + &+ Int((frame.minY * 1000).rounded()) &+ Int((frame.size.width * 1000).rounded()) + &+ Int((frame.size.height * 1000).rounded()) + } +} + +struct RecordedWindowFixture { + private struct Record: Decodable { + struct Bounds: Decodable { + let x: Double + let y: Double + let width: Double + let height: Double + enum CodingKeys: String, CodingKey { + case x = "X" + case y = "Y" + case width = "Width" + case height = "Height" + } + } + let bounds: Bounds + let layer: Int32 + let onscreen: Bool? + enum CodingKeys: String, CodingKey { + case bounds = "kCGWindowBounds" + case layer = "kCGWindowLayer" + case onscreen = "kCGWindowIsOnscreen" + } + } + + let payload: NSArray + let count: Int + + init(count: Int) throws { + guard + let url = Bundle.module.url( + forResource: "windowlist-recorded", withExtension: "plist", subdirectory: "Fixtures") + else { + throw BenchmarkFailure.measurement("recorded window fixture resource") + } + let records = try PropertyListDecoder().decode([Record].self, from: Data(contentsOf: url)) + guard !records.isEmpty, count > 0 else { throw BenchmarkFailure.measurement("empty window recording") } + // Selection and repetition scale a captured geometry corpus without measuring fixture parsing. + payload = NSArray( + array: (0.. NSDictionary in + let record = records[index % records.count] + let bounds = NSDictionary(dictionary: [ + "X": record.bounds.x, "Y": record.bounds.y, + "Width": record.bounds.width, "Height": record.bounds.height, + ]) + let fields = NSMutableDictionary() + fields[kCGWindowNumber as String] = NSNumber(value: index + 1) + fields[kCGWindowOwnerPID as String] = NSNumber(value: index % 8 + 1) + fields[kCGWindowBounds as String] = bounds + fields[kCGWindowLayer as String] = NSNumber(value: record.layer) + if let onscreen = record.onscreen { fields[kCGWindowIsOnscreen as String] = NSNumber(value: onscreen) } + return fields + }) + self.count = count + } + + func decode() throws -> [WindowServer.Window] { try WindowServer.decodeWindows(payload) } +} + +@MainActor +final class HotPathDisplaySource: DisplayLinkSource { + private var callback: (@MainActor (Double) -> Void)? + var isRunning: Bool { callback != nil } + private(set) var starts = 0 + private(set) var stops = 0 + func start(tick: @escaping @MainActor (Double) -> Void) { + callback = tick + starts += 1 + } + func stop() { + if callback != nil { stops += 1 } + callback = nil + } + func tick(at timestamp: Double) { callback?(timestamp) } +} + +@MainActor +final class MotionTickFixture { + let requests: [MotionRequest] + let source = HotPathDisplaySource() + private var coalescer = FrameCoalescer() + private(set) var frames = 0 + private(set) var batches = 0 + private(set) var checksum = 1 + private var time = 100.0 + private(set) var failure: MotionError? + private lazy var driver = DisplayLinkDriver( + source: source, clock: { [unowned self] in time }, + onFrames: { [unowned self] in accept($0) }, onFailure: { [unowned self] in failure = $0 }) + + init(count: Int) { + requests = (0.. MotionRequest in + let x = Double(index) * 100 + let start = MotionRect(originX: x, originY: 100, width: 80, height: 100) + let target = MotionRect(originX: x + 40, originY: 200, width: 80, height: 100) + let screen = MotionRect(originX: 0, originY: 0, width: 24000, height: 2160) + return MotionRequest( + windowID: MotionWindowID(rawValue: UInt64(index + 1)), + appID: MotionAppID(rawValue: Int32(index % 3 + 1)), start: start, target: target, screen: screen) + } + } + + func run(ticks: Int = 30) throws -> BenchmarkObservation { + stop() + coalescer = FrameCoalescer() + frames = 0 + batches = 0 + checksum = 1 + failure = nil + time = 100 + try driver.schedule(requests, at: time) + let cpu = BenchmarkCPUClock.now() + let start = ContinuousClock.now + for tick in 1...ticks { + time = 100 + Double(tick) / 120 + if driver.animator.isIdle { try driver.schedule(requests, at: time) } + source.tick(at: time) + } + let wall = BenchmarkHarness.nanoseconds(start.duration(to: .now)) / Double(ticks) + let elapsedCPU = BenchmarkCPUClock.elapsed(since: cpu) / Double(ticks) + if let failure { throw failure } + guard frames > 0, batches > 0 else { throw BenchmarkFailure.measurement("motion tick did no work") } + let observation = BenchmarkObservation( + checksum: checksum, nanoseconds: wall, cpuNanoseconds: elapsedCPU, + proofMetrics: [ + "sampled-frames": Double(frames), "dispatched-batches": Double(batches), + "ticks": Double(ticks), "pending-frames-at-stop": Double(coalescer.pendingCount), + ]) + stop() + return observation + } + + func stop() { + driver.stop() + coalescer = FrameCoalescer() + } + + private func accept(_ frames: [MotionFrame]) { + do { + for frame in frames { + try coalescer.submit(frame) + self.frames += 1 + } + let ready = try coalescer.takeReady(at: time) + batches += ready.count + for batch in ready { + for frame in batch.frames { + checksum &+= + Int(frame.windowID.rawValue) &+ Int(frame.rect.originX.rounded()) + &+ Int(frame.rect.originY.rounded()) + } + try coalescer.complete(batch, duration: 0, at: time) + } + } catch let error as MotionError { failure = error } catch { + preconditionFailure("Unexpected motion fixture error: \(error)") + } + } +} + +final class CountingFrameAccess: FrameWriteAccess { + var value: CGRect + var enhanced = true + private(set) var attributeOperations = 0 + private(set) var enhancedSets = 0 + private(set) var positionSets = 0 + private(set) var sizeSets = 0 + init(_ frame: CGRect) { value = frame } + var frame: CGRect { + attributeOperations += 2 + return value + } + var size: CGSize { + attributeOperations += 1 + return value.size + } + var position: CGPoint { + attributeOperations += 1 + return value.origin + } + var enhancedUI: Bool { + attributeOperations += 1 + return enhanced + } + func setSize(_ size: CGSize) { + attributeOperations += 1 + sizeSets += 1 + value.size = size + } + func setPosition(_ position: CGPoint) { + attributeOperations += 1 + positionSets += 1 + value.origin = position + } + func setEnhancedUI(_ enabled: Bool) { + attributeOperations += 1 + enhancedSets += 1 + enhanced = enabled + } +} + +final class CountingFactsAccess: WindowFactsAccess { + private(set) var reads = 0 + func string(_ attribute: WindowStringFact) -> String { + reads += 1 + switch attribute { + case .role: return "AXWindow" + case .subrole: return "AXStandardWindow" + case .title: return "Document" + } + } + func button(_ attribute: WindowButtonFact) -> Bool { + reads += 1 + return true + } + func boolean(_ attribute: WindowBooleanFact) -> Bool { + reads += 1 + return false + } + func size(_ attribute: WindowSizeFact) -> Size { + reads += 1 + return Size(width: attribute == .minimum ? 4 : 10000, height: attribute == .minimum ? 4 : 10000) + } + func sizeSettable() -> Bool { + reads += 1 + return true + } + func parentRole() -> String { + reads += 1 + return "AXApplication" + } + func childRoles() -> [String?] { + reads += 1 + return [] + } +} + +@MainActor +final class HotPathKeyBackend: HotKeyBackend { + var onCarbonEvent: (@MainActor (UInt32, Bool) -> Void)? + var onTapEvent: (@MainActor (CGEventType, CGEvent) -> Bool)? + var onFailure: (@MainActor (InputError) -> Void)? + var carbonStatus: Int32 = 0 + func registerCarbon(_ key: HotKey, id: UInt32) -> Int32 { carbonStatus } + func unregisterCarbon(id: UInt32) {} + func isPressed(_ key: HotKey) -> Bool? { false } + func startTap() {} + func stopTap() {} +} + +@MainActor +func hotPathLayers(_ root: CALayer) -> [CALayer] { + var result = [root] + if let mask = root.mask { result += hotPathLayers(mask) } + for child in root.sublayers ?? [] { result += hotPathLayers(child) } + return result +} + +func hotPathRetainedBytes() -> Int { + var statistics = malloc_statistics_t() + malloc_zone_statistics(nil, &statistics) + return Int(statistics.size_in_use) +} + +@MainActor +final class HotPathOverlayFixture { + let display: OverlayDisplay + let controller: OverlayController + let snapshot: OverlaySnapshot + let moved: OverlaySnapshot + let state: State + private let root = CALayer() + private let canvas: OverlayHighlightCanvas + private let focus: OverlayTileLayer + private let privacy: PrivacyOverlayPanel + private let backdrop: CleanSpaceBackdrop + private var failure: (any Error)? + + init(count: Int) { + guard let screen = NSScreen.screens.first, + let number = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber, + let uuid = CGDisplayCreateUUIDFromDisplayID(number.uint32Value)?.takeRetainedValue() + else { + preconditionFailure( + "Headless overlay benchmarks require a window-server screen session, not an Accessibility grant") + } + let id = CFUUIDCreateString(nil, uuid) as String + let bounds = CGRect(x: screen.frame.minX, y: 0, width: screen.frame.width, height: screen.frame.height) + display = OverlayDisplay(id: id, frame: bounds, scale: screen.backingScaleFactor) + let columns = Int(ceil(sqrt(Double(count)))) + let rows = Int(ceil(Double(count) / Double(columns))) + let width = bounds.width / CGFloat(columns) + let height = bounds.height / CGFloat(rows) + let windows = (0.. BenchmarkObservation { + let old = layers() + controller.update(moved) + controller.update(snapshot) + if flush { CATransaction.flush() } + if let failure { throw failure } + guard controller.panels.values.allSatisfy({ !$0.isVisible }) else { + throw BenchmarkFailure.measurement("headless overlay ordered a panel") + } + let current = layers() + let retained = Set(old.map(ObjectIdentifier.init)) + let created = current.filter { !retained.contains(ObjectIdentifier($0)) }.count + withExtendedLifetime(old) {} + return BenchmarkObservation( + checksum: snapshot.windows.count + current.count + + controller.ghostLayers.values.reduce(0) { $0 + $1.count }, + proofMetrics: [ + "new-reachable-layers": Double(created), "reachable-layers": Double(current.count), + "ghost-tiles": Double(controller.ghostLayers.values.reduce(0) { $0 + $1.count }), "visible-panels": 0, + ]) + } + + func enablePrivacy() { + guard let key = state.activeWorkspace else { preconditionFailure("Missing overlay privacy workspace") } + controller.update( + OverlaySnapshot( + windows: snapshot.windows, focusedWindow: snapshot.focusedWindow, + context: snapshot.context, + privacyWorkspaces: [ + OverlayPrivacyWorkspace( + key: key, noPeek: true, cleanSpace: true, + focusedWindow: snapshot.focusedWindow) + ])) + } + + func framePair() -> BenchmarkObservation { + for window in moved.windows { + controller.observePrivacyFrame( + WindowFrame( + window: WindowID(rawValue: window.id), + frame: Rect( + x: window.frame.minX, y: window.frame.minY, width: window.frame.width, + height: window.frame.height))) + } + for window in snapshot.windows { + controller.observePrivacyFrame( + WindowFrame( + window: WindowID(rawValue: window.id), + frame: Rect( + x: window.frame.minX, y: window.frame.minY, width: window.frame.width, + height: window.frame.height))) + } + return BenchmarkObservation( + checksum: layers().count + snapshot.windows.count, + proofMetrics: ["observed-frame-updates": Double(snapshot.windows.count * 2)]) + } + + func highlight(moved changing: Bool) -> BenchmarkObservation { + let old = hotPathLayers(root) + let configuration = MotionConfiguration(highlight: .glow) + let target = changing ? moved : snapshot + canvas.update( + display: display, snapshot: target, configuration: configuration, + accessibility: OverlayAccessibility(), color: .systemBlue) + let style = OverlayHighlightStyle( + configuration: configuration, accessibility: OverlayAccessibility(), active: true) + focus.move( + to: display.localFrame(target.windows[0].frame), radius: 10, + motion: OverlayMotion( + configuration: MotionConfiguration(enabled: false), accessibility: OverlayAccessibility()), token: .pop) + focus.styleHighlight(style, color: .systemBlue, scale: display.scale) + if changing { + canvas.update( + display: display, snapshot: snapshot, configuration: configuration, + accessibility: OverlayAccessibility(), color: .systemBlue) + focus.move( + to: display.localFrame(snapshot.windows[0].frame), radius: 10, + motion: OverlayMotion( + configuration: MotionConfiguration(enabled: false), accessibility: OverlayAccessibility()), + token: .pop) + focus.styleHighlight(style, color: .systemBlue, scale: display.scale) + } + let current = hotPathLayers(root) + let previous = Set(old.map(ObjectIdentifier.init)) + let created = current.filter { !previous.contains(ObjectIdentifier($0)) }.count + withExtendedLifetime(old) {} + return BenchmarkObservation( + checksum: current.count + snapshot.windows.count, + proofMetrics: ["new-reachable-layers": Double(created), "reachable-layers": Double(current.count)]) + } + + func themePair() throws -> BenchmarkObservation { + guard let light = NSAppearance(named: .aqua), let dark = NSAppearance(named: .darkAqua) else { + throw BenchmarkFailure.measurement("appearance contexts unavailable") + } + for appearance in [dark, light] { + appearance.performAsCurrentDrawingAppearance { + controller.update(configuration: controller.configuration, accessibility: controller.accessibility) + } + } + return BenchmarkObservation(checksum: layers().count + 2, proofMetrics: ["appearance-restyles": 2]) + } + + func consumePair() -> BenchmarkObservation { + controller.consume(EngineSnapshot(revision: 1, state: state)) + controller.consume(EngineSnapshot(revision: 2, state: state)) + precondition(controller.panels.values.allSatisfy { !$0.isVisible }) + return BenchmarkObservation( + checksum: layers().count + state.windows.count + controller.privacyPanelCount, + proofMetrics: ["privacy-panels": Double(controller.privacyPanelCount), "visible-panels": 0]) + } + + func privacyPair() -> BenchmarkObservation { + let cutouts = Array(snapshot.windows.prefix(8)).map(\.frame) + let cpu = BenchmarkCPUClock.now() + privacy.update( + display: display, primaryDisplayHeight: display.frame.height, cutouts: cutouts, + color: .gray, opacity: 0.5, blurred: true) + backdrop.update(display: display, primaryDisplayHeight: display.frame.height, color: .gray) + let unchanged = BenchmarkCPUClock.elapsed(since: cpu) + let changedStart = BenchmarkCPUClock.now() + privacy.update( + display: display, primaryDisplayHeight: display.frame.height, + cutouts: cutouts.map { $0.offsetBy(dx: 1, dy: 1) }, color: .gray, opacity: 0.5, blurred: true) + backdrop.update(display: display, primaryDisplayHeight: display.frame.height, color: .gray) + let changed = BenchmarkCPUClock.elapsed(since: changedStart) + return BenchmarkObservation( + checksum: privacy.regions.count + privacy.tintRegions.count + cutouts.count, + proofMetrics: [ + "cutouts": Double(cutouts.count), "unchanged-cpu-ns": unchanged, "changed-cpu-ns": changed, + "visible-panels": privacy.isVisible || backdrop.isVisible ? 1 : 0, + ]) + } + + private func layers() -> [CALayer] { controller.panels.values.flatMap { hotPathLayers($0.canvas) } } + + static func chipState() -> State { + let fixture = HotPathStateFixture(count: 6) + var state = fixture.state + for key in state.workspaces.keys { state.workspaces[key]?.gaps = Gaps(inner: 24, outer: Insets(24)) } + state = reduce(state, .windowDropped(source: fixture.ids[0], target: fixture.ids[1], stacking: true)).0 + state.observedFrames = state.frames + precondition(!StackChips.groups(in: state).isEmpty, "Chip benchmark must have a real group") + return state + } +} diff --git a/Tests/ParcelPerformanceTests/HotPathNativeFixtures.swift b/Tests/ParcelPerformanceTests/HotPathNativeFixtures.swift new file mode 100644 index 00000000..73723e91 --- /dev/null +++ b/Tests/ParcelPerformanceTests/HotPathNativeFixtures.swift @@ -0,0 +1,412 @@ +import Foundation +import ParcelCore +import ParcelPlatform +import Testing + +@testable import ParcelEngine + +@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 + 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) + 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 } +} + +@MainActor +final class HotPathApplication: NativeEngineApplication { + let events: AsyncStream + private let continuation: AsyncStream.Continuation + var snapshots: [NativeWindowSnapshot] + var focused: WindowID? + var readDelay: Duration = .zero + private(set) var windowReads = 0 + private(set) var frameReads = 0 + private(set) var focusReads = 0 + private(set) var writes = 0 + var didBeginWindowRead: (@MainActor () -> Void)? + init(snapshots: [NativeWindowSnapshot]) { + self.snapshots = snapshots + focused = snapshots.first?.window.id + let pair = AsyncStream.makeStream() + events = pair.stream + continuation = pair.continuation + } + func emit(_ event: AppThreadEvent) { continuation.yield(event) } + func windows() async throws -> [NativeWindowSnapshot] { + windowReads += 1 + didBeginWindowRead?() + if readDelay > .zero { try await Task.sleep(for: readDelay) } + return snapshots + } + func frame(_ window: WindowID) async throws -> Rect { + frameReads += 1 + guard let snapshot = snapshots.first(where: { $0.window.id == window }) else { + throw EnginePlatformFailure.vanished(window) + } + return snapshot.frame + } + func focusedWindow() async throws -> WindowID? { + focusReads += 1 + return focused + } + func write(_ frame: Rect, to window: WindowID) async throws -> Rect { + writes += 1 + return frame + } + 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 } } + func toggleFullscreen(_ window: WindowID) async throws { + throw EnginePlatformFailure.operation(.focusUnchanged(window)) + } + func shutdown() { continuation.finish() } + func resetCounts() { + windowReads = 0 + frameReads = 0 + focusReads = 0 + writes = 0 + } +} + +@MainActor +final class HotPathNativeBackend: NativeEngineBackend { + let displays: [ParcelCore.Display] + var apps: [AppID: HotPathApplication] + var spaces: [DisplayID: SpaceID] + var frontmost: AppID? + 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 = state.activeSpaces + self.apps = apps + frontmost = state.windows[state.focusedWindow ?? WindowID(rawValue: 0)]?.app + } + func start(receive: @escaping @MainActor (NativeEngineEvent) -> Void) { self.receive = receive } + 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 + 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 currentSpaces(for displays: [DisplayID]) async throws -> NativeSpaceState { + spaceReads += 1 + return NativeSpaceState(spaces: spaces.filter { displays.contains($0.key) }, suspended: []) + } + func resetCounts() { + windowListReads = 0 + spaceReads = 0 + for app in apps.values { app.resetCounts() } + } +} + +@MainActor +final class HotPathNativeFixture { + let model: HotPathStateFixture + let clock = HotPathClock() + let scheduler: HotPathScheduler + let backend: HotPathNativeBackend + let world: NativeEngineWorld + private(set) var events: [EnginePlatformEvent] = [] + var state = State() + private(set) var suspended: Set = [] + private var failure: EnginePlatformFailure? + + 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) }) + world = NativeEngineWorld(backend: backend, scheduler: scheduler) + } + + func start() async throws { + 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 + case .failure(let error): failure = error + default: break + } + } + try await drain { self.state.windows.count == self.model.ids.count && self.scheduler.pendingCount == 0 } + resetCounts() + } + + func stop() { world.stop() } + func resetCounts() { + events.removeAll(keepingCapacity: true) + backend.resetCounts() + failure = nil + } + func drain(until predicate: @MainActor () -> Bool) async throws { + let deadline = ContinuousClock.now.advanced(by: .seconds(3)) + repeat { + scheduler.runReady() + await Task.yield() + if let failure { throw failure } + if predicate() { return } + } while ContinuousClock.now < deadline + throw BenchmarkFailure.measurement("native workload did not reach expected observation") + } + + 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 + app.emit(.focusedWindowChanged) + 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) async throws -> BenchmarkObservation { + let app = try firstApplication() + guard let snapshot = app.snapshots.first else { throw BenchmarkFailure.measurement("no native move target") } + resetCounts() + for _ in 0..= count + && self.events.filter { + if case .frameChanged = $0.untraced { return true } + return false + }.count >= count + } + return observation() + } + + func created(write: 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) + let added = NativeWindowSnapshot(window: window, frame: reference.frame) + app.snapshots.append(added) + resetCounts() + app.emit(.windowCreated(id.rawValue)) + try await drain { self.state.windows[id] != nil } + if write { + var completed = false + world.write([EngineFrameWrite(window: id, frame: reference.frame, transaction: 1)], for: window.app) { + receipt in + if let error = receipt.failures.first { self.failure = error } + completed = true + } + try await drain { completed } + } + let result = observation() + app.snapshots.removeAll { $0.window.id == 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 { + self.backend.windowListReads > 0 && self.backend.apps.values.allSatisfy { $0.windowReads > 0 } + && self.scheduler.pendingCount == 0 + } + 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.scheduler.pendingCount == 0 + } + var result = observation() + result.proofMetrics["suspended-display-count"] = Double(suspended.count) + result.proofMetrics["unchanged-display-suspended"] = + suspended.contains(backend.displays.last?.id ?? display.id) && backend.displays.count > 1 ? 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 + } + } + 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.reduce(0) { $0 + $1.frameReads } == self.model.ids.count * tick } + } + 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 + let start = ContinuousClock.now + second.emit(.focusedWindowChanged) + 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 }), + "application-focus-reads": Double(apps.reduce(0) { $0 + $1.focusReads }), + "window-list-reads": Double(backend.windowListReads), "space-reads": Double(backend.spaceReads), + "application-writes": Double(apps.reduce(0) { $0 + $1.writes }), + ]) + } +} + +@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 { + 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)") } + } +} -- knotmirror 0.0.1 From 0304f3c98627a1d83158e0de73f3c1aedb3bcaaf Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 13:33:38 -0400 Subject: [PATCH 06/22] Add tested performance measurement workflows --- Instruments/templates.json | 6 + Scripts/bench-ab-summary.py | 143 +++++++++ Scripts/bench-ab.sh | 48 +++ Scripts/bench-host-setup.sh | 57 ++++ Scripts/bench-remote.sh | 111 +++++++ Scripts/bundle.sh | 12 +- Scripts/idle-report.sh | 37 +++ Scripts/idle-summary.py | 119 ++++++++ Scripts/leaks.sh | 88 ++++++ Scripts/quiet-check.sh | 16 + Scripts/quiet-readings.py | 106 +++++++ Scripts/remote-sync.sh | 47 +++ Scripts/soak.sh | 9 + Scripts/test-e2e.sh | 11 +- Scripts/test-remote.sh | 19 +- Scripts/tests/bench-ab.sh | 4 + Scripts/tests/idle-summary.sh | 4 + Scripts/tests/measurement-e2e.sh | 4 + Scripts/tests/measurement-tests.py | 440 ++++++++++++++++++++++++++++ Scripts/tests/packaging.sh | 11 +- Scripts/tests/quiet-check.sh | 4 + Scripts/tests/remote-measurement.sh | 4 + Scripts/tests/trace-summary.sh | 4 + Scripts/trace-common.sh | 25 ++ Scripts/trace-e2e.sh | 48 +++ Scripts/trace-summary.py | 93 ++++++ Scripts/trace-templates.sh | 31 ++ Scripts/trace.sh | 43 +++ 28 files changed, 1521 insertions(+), 23 deletions(-) create mode 100644 Instruments/templates.json create mode 100644 Scripts/bench-ab-summary.py create mode 100755 Scripts/bench-ab.sh create mode 100755 Scripts/bench-host-setup.sh create mode 100755 Scripts/bench-remote.sh create mode 100755 Scripts/idle-report.sh create mode 100644 Scripts/idle-summary.py create mode 100755 Scripts/leaks.sh create mode 100755 Scripts/quiet-check.sh create mode 100644 Scripts/quiet-readings.py create mode 100755 Scripts/remote-sync.sh create mode 100755 Scripts/soak.sh create mode 100755 Scripts/tests/bench-ab.sh create mode 100755 Scripts/tests/idle-summary.sh create mode 100755 Scripts/tests/measurement-e2e.sh create mode 100644 Scripts/tests/measurement-tests.py create mode 100755 Scripts/tests/quiet-check.sh create mode 100755 Scripts/tests/remote-measurement.sh create mode 100755 Scripts/tests/trace-summary.sh create mode 100644 Scripts/trace-common.sh create mode 100755 Scripts/trace-e2e.sh create mode 100644 Scripts/trace-summary.py create mode 100755 Scripts/trace-templates.sh create mode 100755 Scripts/trace.sh diff --git a/Instruments/templates.json b/Instruments/templates.json new file mode 100644 index 00000000..af6e58ed --- /dev/null +++ b/Instruments/templates.json @@ -0,0 +1,6 @@ +{ + "smoothness": {"custom": "Parcel Smoothness.tracetemplate", "installed": "Animation Hitches"}, + "idle": {"custom": "Parcel Idle.tracetemplate", "installed": "Power Profiler"}, + "memory": {"custom": "Parcel Memory.tracetemplate", "installed": "Allocations"}, + "counters": {"custom": "Parcel Counters.tracetemplate", "installed": "CPU Counters"} +} diff --git a/Scripts/bench-ab-summary.py b/Scripts/bench-ab-summary.py new file mode 100644 index 00000000..b04395c4 --- /dev/null +++ b/Scripts/bench-ab-summary.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Compare five paired release runs; bootstrap paired minimum-CPU ratios.""" +import argparse +import json +import math +import os +from pathlib import Path +import random +import statistics +import sys + +HOST_FIELDS = ("hostKey", "model", "cores", "osBuild", "swiftVersion", "buildConfiguration", "counterSource") + + +def positive(value, label): + if isinstance(value, bool) or not isinstance(value, (float, int)) or not math.isfinite(value) or value <= 0: + raise ValueError(f"{label} must be positive and finite") + return value + + +def read(path): + report = json.loads(path.read_text()) + if report.get("version") != 5: + raise ValueError(f"{path}: A/B requires schema v5; rebuild both revisions with the measurement harness") + host = report.get("host") + if not isinstance(host, dict) or any(field not in host for field in HOST_FIELDS): + raise ValueError(f"{path}: host metadata is incomplete") + if any(not isinstance(host[field], str) or not host[field] for field in HOST_FIELDS if field != "cores") or isinstance(host["cores"], bool) or not isinstance(host["cores"], int) or host["cores"] <= 0: + raise ValueError(f"{path}: invalid host metadata") + if not isinstance(report.get("machine"), str) or not report["machine"]: + raise ValueError(f"{path}: machine identity is missing") + if host["buildConfiguration"] != "release" or host["counterSource"] not in ("selfcounts", "rusage", "cpu-only"): + raise ValueError(f"{path}: full release measurements are required, not smoke mode") + results = report.get("results") + if not isinstance(results, list) or not results: + raise ValueError(f"{path}: benchmark results are empty") + indexed = {} + for result in results: + name = result.get("name") + if not isinstance(name, str) or not name or name in indexed: + raise ValueError(f"{path}: duplicate or missing case name") + if result.get("metric") not in ("cpu", "wall") or not isinstance(result.get("reportingOnly"), bool): + raise ValueError(f"{path}: {name}: metric/reportingOnly missing or invalid") + positive(result.get("minimumNanoseconds"), f"{path}: {name}: minimumNanoseconds") + if result.get("instructionsPerOp") is not None: + positive(result["instructionsPerOp"], f"{path}: {name}: instructionsPerOp") + if result.get("counterSource") not in ("selfcounts", "rusage", "cpu-only", "smoke"): + raise ValueError(f"{path}: {name}: unrecognized counter source") + if result["metric"] == "cpu" and result["counterSource"] != "smoke" and result["counterSource"] != host["counterSource"]: + raise ValueError(f"{path}: {name}: CPU result counter source differs from host") + checksum = result.get("checksum") + if isinstance(checksum, bool) or not isinstance(checksum, int) or checksum == 0: + raise ValueError(f"{path}: {name}: checksum must be a nonzero integer") + indexed[name] = result + return report, indexed + + +def bootstrap(ratios, rng): + samples = sorted(statistics.median(rng.choices(ratios, k=len(ratios))) for _ in range(10_000)) + return [samples[249], samples[9749]] + + +def compare(base, head): + reports = [read(path) for pair in zip(base, head) for path in pair] + reference, names = reports[0] + identity = {field: reference["host"][field] for field in HOST_FIELDS} + for report, results in reports: + if report.get("machine") != reference.get("machine") or {field: report["host"][field] for field in HOST_FIELDS} != identity: + raise ValueError("host, OS, toolchain or counter source changed between A/B runs") + if set(results) != set(names): + raise ValueError("benchmark cases differ between A/B runs; use compatible measurement harnesses") + rng = random.Random(0) + output = [] + regressions = [] + for name in sorted(names): + entries = [results[name] for _, results in reports] + first = entries[0] + for result in entries: + if any(result.get(field) != first.get(field) for field in ("metric", "counterSource", "reportingOnly")): + raise ValueError(f"{name}: measurement metric, source or reporting policy changed") + reporting = first["reportingOnly"] or first["metric"] != "cpu" or first["counterSource"] == "smoke" + if not reporting and any(result["checksum"] != first["checksum"] for result in entries): + raise ValueError(f"{name}: checksum differs; a faster result must do the same work") + cpu = [entries[i + 1]["minimumNanoseconds"] / entries[i]["minimumNanoseconds"] for i in range(0, 10, 2)] + counts = [result.get("instructionsPerOp") for result in entries] + if any(value is None for value in counts) and not all(value is None for value in counts): + raise ValueError(f"{name}: instruction availability changed between runs") + if not reporting and first["counterSource"] != "cpu-only" and all(value is None for value in counts): + raise ValueError(f"{name}: instruction counter source reported without instruction readings") + instruction_ratio = None if counts[0] is None else statistics.median([counts[i + 1] / counts[i] for i in range(0, 10, 2)]) + ci = bootstrap(cpu, rng) + failures = [] + if not reporting: + if instruction_ratio is not None and instruction_ratio > 1.03: + failures.append("instructions exceed +3%") + if ci[0] > 1.05: + failures.append("95% bootstrap minimum-CPU lower bound exceeds +5%") + regressions.extend(f"{name}: {reason}" for reason in failures) + output.append(dict(name=name, metric=first["metric"], counterSource=first["counterSource"], + reportingOnly=reporting, gating=not reporting, + status="unsupported-counter" if first["counterSource"] == "smoke" and first["metric"] == "cpu" else "report-only" if reporting else "cpu-only" if instruction_ratio is None else "gated", + budget=first.get("budget"), reason=first.get("reason"), + instructionsRatio=instruction_ratio, minimumNanosecondsRatio=statistics.median(cpu), + minimumNanosecondsRatio95CI=ci, checksum=first["checksum"], failures=failures)) + return dict(version=1, host=reference["host"], + hostReadings={"base": [report["host"] for report, _ in reports[::2]], + "head": [report["host"] for report, _ in reports[1::2]]}, + rounds=5, bootstrapResamples=10_000, + bootstrapMethod="paired round ratios, median, percentile 95%", results=output, + regressions=regressions, passed=not regressions) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--base", action="append", type=Path, required=True) + parser.add_argument("--head", action="append", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--base-revision") + parser.add_argument("--head-revision") + args = parser.parse_args() + try: + if len(args.base) != 5 or len(args.head) != 5: + raise ValueError("exactly five paired A/B rounds are required") + summary = compare(args.base, args.head) + summary.update(baseRevision=args.base_revision, headRevision=args.head_revision, + measurementOverlay="working-tree Package.swift and Tests/ParcelPerformanceTests on base production sources", + caseScope="common-core" if os.environ.get("PARCEL_BENCH_CORE_ONLY") == "1" else "all-cases") + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(summary, indent=2, allow_nan=False) + "\n") + for case in summary["results"]: + instructions = "unavailable" if case["instructionsRatio"] is None else f"{(case['instructionsRatio'] - 1) * 100:+.2f}%" + lower, upper = case["minimumNanosecondsRatio95CI"] + print(f"{case['name']} [{case['status']}]: instructions {instructions}; minimum {case['metric']} ratio {case['minimumNanosecondsRatio']:.4f} (95% CI {lower:.4f}–{upper:.4f})") + for failure in summary["regressions"]: + print(f"REGRESSION {failure}", file=sys.stderr) + return 0 if summary["passed"] else 1 + except (OSError, ValueError, TypeError, KeyError) as error: + print(f"bench-ab: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/Scripts/bench-ab.sh b/Scripts/bench-ab.sh new file mode 100755 index 00000000..8fc8884d --- /dev/null +++ b/Scripts/bench-ab.sh @@ -0,0 +1,48 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/.." +if [[ $# -gt 2 || ${1:-main} == -* || -z ${1:-main} || + ( $# -eq 2 && $2 != --core-only && $2 != --all-cases ) ]]; then + printf 'Usage: %s [base-ref | BASE=base-ref] [--core-only|--all-cases]\n' "$0" >&2 + exit 2 +fi +export SWIFT_DETERMINISTIC_HASHING=1 +export PARCEL_BENCH_CORE_ONLY=1 +if [[ ${2:-} == --all-cases ]]; then export PARCEL_BENCH_CORE_ONLY=0; fi +base=${1:-${BASE:-main}} +base=${base#BASE=} +[[ -n $base && $base != -* ]] || { printf 'A base revision is required.\n' >&2; exit 2; } +base_revision=$(git merge-base HEAD "$base") +head_revision=$(git rev-parse HEAD) +mkdir -p build/bench-ab +session=$(mktemp -d "$PWD/build/bench-ab/run.XXXXXX") +mkdir -p "$session/base/source" "$session/head" +printf 'A/B base %s; head %s plus working-tree changes.\n' "$base_revision" "$head_revision" +printf 'Instrumentation overlay: working-tree Package.swift and Tests/ParcelPerformanceTests on base production sources.\n' +if [[ $PARCEL_BENCH_CORE_ONLY == 1 ]]; then + printf 'Explicit common-core scope: existing 44 cases; new production-hook-dependent cases excluded from both builds.\n' +else + printf 'All-cases scope: both revisions must support every production benchmark hook.\n' +fi +git archive "$base_revision" | tar -xf - -C "$session/base/source" +rm -rf "$session/base/source/Tests/ParcelPerformanceTests" +cp -R Tests/ParcelPerformanceTests "$session/base/source/Tests/ParcelPerformanceTests" +cp Package.swift "$session/base/source/Package.swift" +# Both binaries are built before any reading; base production sources stay at the merge base. +swift build --package-path "$session/base/source" --scratch-path "$session/base/build" -c release --build-tests -Xswiftc -enable-testing +swift build --package-path "$PWD" --scratch-path "$session/head/build" -c release --build-tests -Xswiftc -enable-testing +args=(--output "${BENCH_AB_OUTPUT:-build/bench-ab/summary.json}" --base-revision "$base_revision" --head-revision "$head_revision") +for round in 1 2 3 4 5; do + for variant in base head; do + source=$PWD + [[ $variant != base ]] || source="$session/base/source" + output="$session/$variant/round-$round.json" + printf 'A/B round %s/5: %s\n' "$round" "$variant" + PARCEL_BENCH=1 PARCEL_BENCH_NO_COMPARE=1 PARCEL_BENCH_RECORD=0 PARCEL_BENCH_OUTPUT="$output" \ + swift test --package-path "$source" --scratch-path "$session/$variant/build" \ + -c release --skip-build -Xswiftc -enable-testing --no-parallel --filter PerformanceBenchmarks + [[ -s $output ]] || { printf 'Benchmark runner did not write %s\n' "$output" >&2; exit 2; } + args+=("--$variant" "$output") + done +done +python3 -I Scripts/bench-ab-summary.py "${args[@]}" diff --git a/Scripts/bench-host-setup.sh b/Scripts/bench-host-setup.sh new file mode 100755 index 00000000..8695bea7 --- /dev/null +++ b/Scripts/bench-host-setup.sh @@ -0,0 +1,57 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/.." +source Scripts/remote-sync.sh +if [[ $# -lt 1 || $# -gt 2 ]]; then + printf 'Usage: %s [--dry-run|--check|--apply]\n' "$0" >&2 + exit 2 +fi +host=$1 +mode=${2:---dry-run} +remote_validate_host "$host" +case "$mode" in --dry-run|--check|--apply) ;; *) printf 'Unknown setup mode: %s\n' "$mode" >&2; exit 2 ;; esac +printf 'Bench host: %s; mode: %s\n' "$host" "$mode" +printf '%s\n' \ + 'Use a dedicated logged-in console user, AC power, and a deliberately selected Xcode/Swift toolchain.' \ + 'Proposed AC settings: sudo pmset -c sleep 0 displaysleep 0 powernap 0 lowpowermode 0' \ + 'Proposed backup exclusion: sudo tmutil addexclusion ~/parcel-ci' \ + 'Manual: put ~/parcel-ci in Spotlight Privacy (do not disable indexing on the whole boot volume).' \ + 'Manual: grant Accessibility to the remote build/Parcel.app, then run PARCEL_E2E_PREFLIGHT_ONLY=1 Scripts/test-e2e.sh.' \ + 'Optional manual sudoers policy: permit only /usr/bin/powermetrics and /usr/bin/leaks for this user; review it with visudo.' \ + 'No permission grants, toolchain selection, or sudoers changes are automated.' +[[ $mode != --dry-run ]] || exit 0 +# shellcheck disable=SC2029 +ssh "$host" "bash -s -- $mode" <<'REMOTE' +set -euo pipefail +mode=$1 +console_user=$(stat -f %Su /dev/console) +[[ $console_user == "$(id -un)" ]] || { printf 'Bench user is not the logged-in console user.\n' >&2; exit 2; } +sw_vers +xcode-select -p +swift --version +battery=$(pmset -g batt) +printf '%s\n' "$battery" +[[ $battery == *"Now drawing from 'AC Power'"* ]] || { printf 'AC power is required.\n' >&2; exit 2; } +pmset -g therm +if [[ $mode == --apply ]]; then + mkdir -p "$HOME/parcel-ci" + sudo pmset -c sleep 0 displaysleep 0 powernap 0 lowpowermode 0 + sudo tmutil addexclusion "$HOME/parcel-ci" +fi +settings=$(pmset -g custom) +printf '%s\n' "$settings" +printf '%s\n' "$settings" | python3 -I -c ' +import re,sys +s=re.search(r"^AC Power:\\s*\\n(.*?)(?=^\\S|\\Z)",sys.stdin.read(),re.M|re.S) +if s is None: sys.exit("Missing AC power settings") +values=dict(re.findall(r"^\\s*(\\w+)\\s+(\\d+)\\s*$",s[1],re.M)) +for key in ("sleep","displaysleep","powernap"): + if values.get(key)!="0": sys.exit("Unexpected AC setting: "+key) +modes=[values[key] for key in ("lowpowermode","powermode") if key in values] +if not modes or any(mode not in ("0","2") for mode in modes): sys.exit("Low Power Mode must be off") +' +exclusion=$(tmutil isexcluded "$HOME/parcel-ci") +printf '%s\n' "$exclusion" +[[ $exclusion == *'[Excluded]'* ]] || { printf 'Backup exclusion is not active.\n' >&2; exit 2; } +printf 'AC settings and backup exclusion verified; Accessibility and Spotlight remain manual preflight requirements.\n' +REMOTE diff --git a/Scripts/bench-remote.sh b/Scripts/bench-remote.sh new file mode 100755 index 00000000..dcb075f8 --- /dev/null +++ b/Scripts/bench-remote.sh @@ -0,0 +1,111 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/.." +source Scripts/remote-sync.sh +if [[ $# -lt 1 || $# -gt 3 ]]; then + printf 'Usage: %s [bench|bench-record|bench-ab|smoothness|idle|soak] [BASE=ref]\n' "$0" >&2 + exit 2 +fi +host=$1 +task=${2:-bench} +remote_validate_host "$host" +case "$task" in bench|bench-record|bench-ab|smoothness|idle|soak) ;; *) printf 'Unknown bench task: %s\n' "$task" >&2; exit 2 ;; esac +if [[ $# -eq 3 && ( $task != bench-ab || $3 != BASE=* ) ]]; then + printf 'BASE=ref is only accepted for bench-ab.\n' >&2 + exit 2 +fi +wait_value=${BENCH_WAIT:-15m} +if [[ ! $wait_value =~ ^([0-9]+)(s|m)?$ ]]; then + printf 'BENCH_WAIT must be an integer number of seconds or minutes (for example 15m).\n' >&2 + exit 2 +fi +wait_seconds=$((10#${BASH_REMATCH[1]})) +[[ ${BASH_REMATCH[2]:-} != m ]] || wait_seconds=$((wait_seconds * 60)) +base_revision= +if [[ $task == bench-ab ]]; then + base=${3:-BASE=${BASE:-main}} + base_revision=$(git merge-base HEAD "${base#BASE=}") +fi +remote_dir=$(remote_sync "$host") +if [[ $task == bench-ab ]]; then + bundle=$(mktemp "${TMPDIR:-/tmp}/parcel-bench-history.XXXXXX") + trap 'rm -f "$bundle"' EXIT + git bundle create "$bundle" HEAD + rsync -az "$bundle" "$host:parcel-ci/$remote_dir/measurement-history.bundle" +fi +stamp=$(date -u +%Y%m%dT%H%M%SZ) +destination="$PWD/build/remote/$host/$stamp" +mkdir -p "$destination" +# All inserted values are validated tokens; the script is sent verbatim, not shell-expanded. +status=0 +# shellcheck disable=SC2029 +ssh "$host" "bash -s -- $remote_dir $task $wait_seconds ${base_revision:-none}" <<'REMOTE' || status=$? +set -euo pipefail +cd "$HOME/parcel-ci/$1" +task=$2 +wait_seconds=$3 +base_revision=$4 +mkdir -p build +started=$SECONDS +while true; do + quiet_status=0 + Scripts/quiet-check.sh --output build/bench-quiet.json || quiet_status=$? + case "$quiet_status" in + 0) break ;; + 3) + if (( SECONDS - started >= wait_seconds )); then + printf 'Host did not become quiet before BENCH_WAIT expired.\n' >&2 + exit 3 + fi + remaining=$((wait_seconds - (SECONDS - started))) + delay=60 + (( remaining >= delay )) || delay=$remaining + sleep "$delay" + ;; + *) printf 'Quiet preflight failed with status %s; refusing measurement.\n' "$quiet_status" >&2; exit "$quiet_status" ;; + esac +done +if [[ $task == bench-ab ]]; then + git init --quiet + git fetch --quiet measurement-history.bundle HEAD:refs/heads/measurement-head + git symbolic-ref HEAD refs/heads/measurement-head + git reset --mixed --quiet HEAD + command=(Scripts/bench-ab.sh "$base_revision") +else + command=(make "$task") +fi +PARCEL_BENCH_QUIET="$PWD/build/bench-quiet.json" BENCH_STRICT_QUIET=1 \ + caffeinate -i -s nice -n -5 "${command[@]}" +REMOTE +# Readings and failure artifacts are retrieved even if the task terminates unsuccessfully. +# shellcheck disable=SC2029 +artifacts=$(ssh "$host" "cd ~/parcel-ci/$remote_dir && for path in build/bench-results.json build/bench-quiet.json build/bench-ab build/smoothness build/idle build/soak build/traces; do if [ -e \"\$path\" ]; then printf '%s\\n' \"\$path\"; fi; done") +while IFS= read -r artifact; do + [[ -n $artifact ]] || continue + case "$artifact" in build/bench-results.json|build/bench-quiet.json|build/bench-ab|build/smoothness|build/idle|build/soak|build/traces) ;; *) printf 'Unexpected artifact: %s\n' "$artifact" >&2; exit 2 ;; esac + rsync -az "$host:parcel-ci/$remote_dir/$artifact" "$destination/" +done <<< "$artifacts" +if (( status != 0 )); then + printf 'Remote task failed with status %s; artifacts: %s\n' "$status" "$destination" >&2 + exit "$status" +fi +case "$task" in + bench|bench-record) required=bench-results.json ;; + bench-ab) required=bench-ab/summary.json ;; + smoothness) required=smoothness ;; + idle) required=idle ;; + soak) required=soak ;; +esac +[[ -e $destination/$required ]] || { printf 'Required remote artifact missing: %s\n' "$required" >&2; exit 2; } +if [[ $task == bench-record ]]; then + # A fresh remote checkout can only produce this host's deliberate new baseline. + # shellcheck disable=SC2029 + baselines=$(ssh "$host" "cd ~/parcel-ci/$remote_dir && find Benchmarks/baselines -type f -name '*.json' -newer build/bench-quiet.json -print") + [[ -n $baselines ]] || { printf 'No newly recorded remote baseline found.\n' >&2; exit 2; } + while IFS= read -r baseline; do + [[ $baseline =~ ^Benchmarks/baselines/[A-Za-z0-9,._-]+\.json$ ]] || { printf 'Unexpected baseline path.\n' >&2; exit 2; } + rsync -az "$host:parcel-ci/$remote_dir/$baseline" "$baseline" + printf 'Retrieved baseline for review (not staged): %s\n' "$baseline" + done <<< "$baselines" +fi +printf 'Remote artifacts: %s\n' "$destination" diff --git a/Scripts/bundle.sh b/Scripts/bundle.sh index 2e1c78d1..fa90487d 100755 --- a/Scripts/bundle.sh +++ b/Scripts/bundle.sh @@ -5,11 +5,14 @@ cd "$(dirname "$0")/.." source Scripts/product.env source Scripts/version.sh source Scripts/packaging-paths.sh -if [[ $# -gt 1 || ( ${1:-debug} != debug && ${1:-debug} != release ) ]]; then - echo "Usage: $0 [debug|release]" >&2 +if [[ $# -gt 2 || ( ${1:-debug} != debug && ${1:-debug} != release ) || + ( $# -eq 2 && ( $1 != debug || $2 != --inspectable ) ) ]]; then + echo "Usage: $0 [debug|release] [--inspectable (debug only)]" >&2 exit 2 fi configuration=${1:-debug} +inspectable=0 +if [[ ${2:-} == --inspectable ]]; then inspectable=1; fi bundle_id=${PARCEL_BUNDLE_ID:-$PRODUCT_BUNDLE_ID} version=${PARCEL_VERSION-0.1.0} build_number=${PARCEL_BUILD_NUMBER-1} @@ -194,6 +197,11 @@ if grep -q '^TeamIdentifier=not set$' "$work/framework-signature.log"; then exit 1 fi /usr/libexec/PlistBuddy -c 'Add :com.apple.security.cs.disable-library-validation bool true' "$work/local.entitlements" > /dev/null +fi +if [[ $inspectable == 1 ]]; then + /usr/libexec/PlistBuddy -c 'Add :com.apple.security.get-task-allow bool true' "$work/local.entitlements" > /dev/null +fi +if [[ -f $work/local.entitlements ]]; then sign --entitlements "$work/local.entitlements" "$app" else sign "$app" diff --git a/Scripts/idle-report.sh b/Scripts/idle-report.sh new file mode 100755 index 00000000..99a6a639 --- /dev/null +++ b/Scripts/idle-report.sh @@ -0,0 +1,37 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/.." +if [[ $# -gt 1 || ( $# -eq 1 && ! $1 =~ ^[1-9][0-9]*$ ) ]]; then + printf 'Usage: %s [running-Parcel-pid]\n' "$0" >&2 + exit 2 +fi +pid=${1:-} +if [[ -z $pid ]]; then + pid=$(pgrep -x Parcel) || { printf 'No running Parcel; this report will not launch it.\n' >&2; exit 2; } +fi +[[ $pid =~ ^[1-9][0-9]*$ ]] || { printf 'Select one Parcel PID explicitly.\n' >&2; exit 2; } +process=$(ps -p "$pid" -o comm=) +[[ ${process##*/} == Parcel ]] || { printf 'PID is not Parcel.\n' >&2; exit 2; } +mkdir -p build/idle +output=$(mktemp -d "$PWD/build/idle/report.XXXXXX") +top_pid= +cleanup() { if [[ -n $top_pid ]]; then kill "$top_pid" 2>/dev/null || true; wait "$top_pid" 2>/dev/null || true; fi; } +trap cleanup EXIT +# Noninteractive sudo fails clearly; authorize the scoped tool before running this report. +top -l 61 -s 1 -pid "$pid" -stats pid,cpu,idlew,power > "$output/top.txt" 2> "$output/top.stderr" & +top_pid=$! +status=0 +# Report files intentionally belong to the invoking user, not root. +# shellcheck disable=SC2024 +sudo -n /usr/bin/powermetrics --samplers tasks --show-process-energy --show-process-wakeups -i 1000 -n 60 \ + > "$output/powermetrics.txt" 2> "$output/powermetrics.stderr" || status=$? +if (( status != 0 )); then + printf 'powermetrics failed (%s); inspect %s/powermetrics.stderr.\n' "$status" "$output" >&2 + exit "$status" +fi +wait "$top_pid" +top_pid= +kill -0 "$pid" || { printf 'Parcel exited during the report.\n' >&2; exit 2; } +python3 -I Scripts/idle-summary.py Parcel --pid "$pid" --powermetrics "$output/powermetrics.txt" \ + --top "$output/top.txt" --output "$output/summary.json" +printf 'Idle diagnostics (report-only): %s\n' "$output" diff --git a/Scripts/idle-summary.py b/Scripts/idle-summary.py new file mode 100644 index 00000000..3dad2520 --- /dev/null +++ b/Scripts/idle-summary.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Report task energy readings; unknown powermetrics formats fail explicitly.""" +import argparse +import json +import math +from pathlib import Path +import re +import statistics +import sys + + +def number(text): + value = float(text.rstrip("%")) + if not math.isfinite(value) or value < 0: + raise ValueError(f"invalid task reading: {text}") + return value + + +def reading(text): + if match := re.fullmatch(r"\(([^)]+)\)", text): + return [number(value.strip()) for value in match[1].split(",")] + return number(text) + + +def power_rows(content, name, pid): + rows = [] + columns = None + for line in content.splitlines(): + cells = re.split(r"\s{2,}|\t+", line.strip()) + if len(cells) >= 3 and cells[:2] in (["Name", "ID"], ["Name", "PID"]): + columns = cells + continue + if line.startswith("***"): + columns = None + if not columns or not cells or cells[0] != name: + continue + if len(cells) != len(columns): + raise ValueError("powermetrics task row does not match its header") + if not cells[1].isdigit(): + raise ValueError("powermetrics task ID is not numeric") + if pid is not None and int(cells[1]) != pid: + continue + row = {"pid": int(cells[1])} + for key, value in zip(columns[2:], cells[2:]): + row[key] = reading(value) + if not any(key in row for key in ("CPU ms/s", "CPU_ms/s")): + raise ValueError("powermetrics task table has no recognized CPU ms/s column") + rows.append(row) + if not rows: + raise ValueError(f"no task readings for {name}; unsupported format, missing permission or exited process") + if len({row["pid"] for row in rows}) != 1: + raise ValueError("multiple processes share that name; select --pid") + return rows + + +def top_rows(content, pid): + rows = [] + for sample in re.split(r"(?=^Processes:)", content, flags=re.M): + header = re.search(r"^\s*PID\s+%?CPU\s+IDLEW\s+POWER\s*$", sample, re.M) + if not header: + continue + found = False + for line in sample[header.end():].splitlines(): + if not line.strip(): + continue + row = re.fullmatch(r"\s*(\d+)\s+([0-9.]+)\s+(\d+)\s+([0-9.]+)\s*", line) + if not row: + raise ValueError(f"unrecognized top idle row: {line!r}") + if int(row[1]) == pid: + rows.append(dict(cpuPercent=number(row[2]), idleWakeups=int(row[3]), power=number(row[4]))) + found = True + if not found: + raise ValueError("target PID is absent from a top sample") + if len(rows) < 2: + raise ValueError("top needs at least two samples; its first sample is not an interval") + return rows[1:] + + +def summary(rows): + keys = sorted(set().union(*(row.keys() for row in rows)) - {"pid"}) + if any(any(key not in row for key in keys) for row in rows): + raise ValueError("task columns changed between samples") + def stats(values): + if any(isinstance(value, list) for value in values): + if not all(isinstance(value, list) and len(value) == len(values[0]) for value in values): + raise ValueError("task tuple format changed between samples") + return [stats([value[index] for value in values]) for index in range(len(values[0]))] + return dict(minimum=min(values), median=statistics.median(values), maximum=max(values)) + return {key: stats([row[key] for row in rows]) for key in keys} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("name") + parser.add_argument("--pid", type=int) + parser.add_argument("--powermetrics", type=Path) + parser.add_argument("--top", type=Path) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + try: + rows = power_rows(args.powermetrics.read_text() if args.powermetrics else sys.stdin.read(), args.name, args.pid) + pid = rows[0]["pid"] + top = top_rows(args.top.read_text(), pid) if args.top else None + result = dict(version=1, name=args.name, pid=pid, reportingOnly=True, + powermetrics=dict(samples=rows, summary=summary(rows)), + top=None if top is None else dict(samples=top, summary=summary(top))) + text = json.dumps(result, indent=2, allow_nan=False) + "\n" + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(text) + print(text, end="") + return 0 + except (OSError, ValueError) as error: + print(f"idle-summary: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/Scripts/leaks.sh b/Scripts/leaks.sh new file mode 100755 index 00000000..3e1ffef8 --- /dev/null +++ b/Scripts/leaks.sh @@ -0,0 +1,88 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/.." +[[ $# -eq 0 ]] || { printf 'Usage: %s\n' "$0" >&2; exit 2; } +process_status=0 +pgrep -x Parcel > /dev/null || process_status=$? +case "$process_status" in + 0) printf 'Quit your running Parcel first; leaks only inspects the soak harness-owned app.\n' >&2; exit 2 ;; + 1) ;; + *) printf 'Could not inspect running Parcel processes.\n' >&2; exit "$process_status" ;; +esac +mkdir -p build/leaks +work=$(mktemp -d "$PWD/build/leaks/run.XXXXXX") +runner_pid= +finish_runner() { + local deadline=$((SECONDS + 130)) + while kill -0 "$runner_pid" 2>/dev/null; do + if (( SECONDS >= deadline )); then + printf 'Harness failed to exit after continuation; terminating only the owned runner.\n' >&2 + kill -TERM "$runner_pid" 2>/dev/null || true + deadline=$((SECONDS + 5)) + while kill -0 "$runner_pid" 2>/dev/null && (( SECONDS < deadline )); do sleep 0.5; done + if kill -0 "$runner_pid" 2>/dev/null; then kill -KILL "$runner_pid" 2>/dev/null || true; fi + wait "$runner_pid" || true + return 2 + fi + sleep 0.5 + done + wait "$runner_pid" +} +cleanup() { + # Release the harness on tool failure as well as success; the harness owns app cleanup. + touch "$work/continue" + if [[ -n $runner_pid ]]; then finish_runner || true; fi +} +trap cleanup EXIT +wait_seconds=${PARCEL_LEAK_WAIT_SECONDS:-1800} +[[ $wait_seconds =~ ^[0-9]+$ ]] || { printf 'PARCEL_LEAK_WAIT_SECONDS must be nonnegative seconds.\n' >&2; exit 2; } +wait_seconds=$((10#$wait_seconds)) +MallocStackLogging=1 PARCEL_SOAK=1 PARCEL_E2E_INSPECTABLE=1 \ + PARCEL_E2E_FILTER='ParcelE2ETests.*SoakTests' \ + PARCEL_LEAK_PID_FILE="$work/pid" PARCEL_LEAK_CONTINUE_FILE="$work/continue" \ + Scripts/test-e2e.sh debug > "$work/soak.log" 2>&1 & +runner_pid=$! +started=$SECONDS +while [[ ! -s $work/pid ]]; do + if ! kill -0 "$runner_pid" 2>/dev/null; then + status=0 + wait "$runner_pid" || status=$? + runner_pid= + printf 'Soak exited before its leak handshake (status %s); inspect %s/soak.log.\n' "$status" "$work" >&2 + exit 2 + fi + if (( SECONDS - started >= wait_seconds )); then + printf 'Timed out waiting for the soak leak handshake; inspect %s/soak.log.\n' "$work" >&2 + exit 2 + fi + sleep 0.5 +done +[[ ! -L $work/pid ]] || { printf 'Leak PID file must not be a symlink.\n' >&2; exit 2; } +IFS= read -r pid < "$work/pid" +[[ $pid =~ ^[1-9][0-9]*$ ]] || { printf 'Invalid harness-owned PID.\n' >&2; exit 2; } +process=$(ps -p "$pid" -o comm=) +expected="$(pwd -P)/build/Parcel.app/Contents/MacOS/Parcel" +[[ $process == "$expected" ]] || { printf 'Handshake PID does not identify the harness bundle executable.\n' >&2; exit 2; } +codesign -d --entitlements :- build/Parcel.app > "$work/entitlements.plist" 2> "$work/codesign.stderr" +python3 -I -c 'import plistlib,sys; p=plistlib.load(open(sys.argv[1],"rb")); sys.exit(0 if p.get("com.apple.security.get-task-allow") is True else 2)' "$work/entitlements.plist" || { + printf 'Leak inspection requires the explicitly inspectable debug bundle.\n' >&2 + exit 2 +} +status=0 +# Report files intentionally belong to the invoking user, not root. +# shellcheck disable=SC2024 +sudo -n /usr/bin/leaks --outputGraph="$work/parcel.memgraph" "$pid" > "$work/leaks.txt" 2> "$work/leaks.stderr" || status=$? +touch "$work/continue" +soak_status=0 +finish_runner || soak_status=$? +runner_pid= +if (( status != 0 )); then + printf 'leaks failed or found leaks (status %s); inspect %s.\n' "$status" "$work" >&2 + exit "$status" +fi +if (( soak_status != 0 )); then + printf 'Soak failed (status %s); inspect %s/soak.log.\n' "$soak_status" "$work" >&2 + exit "$soak_status" +fi +[[ -f $work/parcel.memgraph ]] || { printf 'leaks did not write its requested memory graph.\n' >&2; exit 2; } +printf 'Harness-owned debug leak report: %s\n' "$work" diff --git a/Scripts/quiet-check.sh b/Scripts/quiet-check.sh new file mode 100755 index 00000000..28f910f3 --- /dev/null +++ b/Scripts/quiet-check.sh @@ -0,0 +1,16 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/.." +if [[ $# -ne 0 && ( $# -ne 2 || $1 != --output || -z $2 ) ]]; then + printf 'Usage: %s [--output readings.json]\n' "$0" >&2 + exit 2 +fi +work=$(mktemp -d "${TMPDIR:-/tmp}/parcel-quiet.XXXXXX") +trap 'rm -rf "$work"' EXIT +# Only the second sample covers the requested five-second interval. +top -l 2 -s 5 -stats pid,command,cpu > "$work/top" +pmset -g batt > "$work/battery" +pmset -g therm > "$work/thermal" +pmset -g custom > "$work/settings" +python3 -I Scripts/quiet-readings.py --top "$work/top" --battery "$work/battery" \ + --thermal "$work/thermal" --settings "$work/settings" "$@" diff --git a/Scripts/quiet-readings.py b/Scripts/quiet-readings.py new file mode 100644 index 00000000..f273a074 --- /dev/null +++ b/Scripts/quiet-readings.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Parse the final top sample and explicit pmset readings, without guessing.""" +import argparse +import json +import math +from pathlib import Path +import re +import sys + + +def parse(top, battery, thermal, settings): + samples = re.split(r"(?=^Processes:)", top, flags=re.M) + sample = samples[-1] + load = re.search(r"Load Avg:\s*([0-9]+(?:\.[0-9]+)?)", sample) + header = re.search(r"^\s*PID\s+COMMAND\s+%?CPU\s*$", sample, re.M) + if load is None or header is None: + raise ValueError("top output is missing load average or PID COMMAND CPU table") + cpus = [] + for line in sample[header.end():].splitlines(): + if not line.strip(): + continue + row = re.fullmatch(r"\s*\d+\s+.+?\s+([0-9]+(?:\.[0-9]+)?)%?\s*", line) + if row is None: + raise ValueError(f"unrecognized top process row: {line!r}") + cpus.append(float(row[1])) + if not cpus: + raise ValueError("top process table is empty") + source = re.search(r"Now drawing from '(AC Power|Battery Power)'", battery) + if source is None: + raise ValueError("pmset battery output has no recognized power source") + ac = source[1] == "AC Power" + warning = False + seen_thermal = seen_performance = False + for line in thermal.splitlines(): + if "No thermal warning level has been recorded" in line: + seen_thermal = True + elif "No performance warning level has been recorded" in line: + seen_performance = True + elif "No CPU power status has been recorded" in line: + pass + elif match := re.search(r"(Thermal|Performance)\s+(?:warning\s+)?level:\s*(\d+)", line, re.I): + warning |= int(match[2]) != 0 + if match[1].lower() == "thermal": + seen_thermal = True + else: + seen_performance = True + elif match := re.search(r"(CPU_Speed_Limit|CPU_Scheduler_Limit|CPU_Available_CPUs)\s*=\s*(\d+)", line): + if match[1] != "CPU_Available_CPUs": + seen_performance = True + warning |= int(match[2]) < 100 + elif re.search(r"warning|pressure", line, re.I): + raise ValueError(f"unrecognized thermal warning: {line!r}") + if not seen_thermal or not seen_performance: + raise ValueError("pmset thermal output does not establish thermal and performance status") + profile = "AC Power" if ac else "Battery Power" + section = re.search(rf"^{profile}:\s*\n(.*?)(?=^\S|\Z)", settings, re.M | re.S) + if section is None: + raise ValueError(f"pmset custom output has no {profile} profile") + modes = re.findall(r"^\s*(lowpowermode|powermode)\s+(\d+)\s*$", section[1], re.M) + if not modes: + raise ValueError("pmset custom output does not establish Low Power Mode") + low_power = False + for key, value in modes: + if (key == "lowpowermode" and value not in ("0", "1")) or (key == "powermode" and value not in ("0", "1", "2")): + raise ValueError(f"unknown {key}: {value}") + low_power |= value == "1" + load_average, maximum = float(load[1]), max(cpus) + if not all(math.isfinite(value) for value in (load_average, maximum)): + raise ValueError("non-finite top readings") + reasons = [] + if load_average >= 1.5: + reasons.append("1-minute load average must be below 1.5") + if not ac: + reasons.append("AC power is required") + if warning: + reasons.append("thermal or performance warning is active") + if maximum > 10: + reasons.append("a process exceeds 10% CPU in the final 5-second sample") + if low_power: + reasons.append("Low Power Mode must be off") + return dict(eligible=not reasons, loadAverage=load_average, acPower=ac, + thermalWarning=warning, maximumProcessCPU=maximum, + lowPowerMode=low_power, reasons=reasons) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ("top", "battery", "thermal", "settings"): + parser.add_argument(f"--{name}", type=Path, required=True) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + try: + readings = parse(*(getattr(args, name).read_text() for name in ("top", "battery", "thermal", "settings"))) + text = json.dumps(readings, indent=2, allow_nan=False) + "\n" + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(text) + print(text, end="") + return 0 if readings["eligible"] else 3 + except (OSError, ValueError) as error: + print(f"quiet-check: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/Scripts/remote-sync.sh b/Scripts/remote-sync.sh new file mode 100755 index 00000000..300c0ac7 --- /dev/null +++ b/Scripts/remote-sync.sh @@ -0,0 +1,47 @@ +#!/bin/bash + +remote_validate_host() { + if [[ ! ${1:-} =~ ^([A-Za-z0-9._-]+@)?[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then + printf 'A valid explicit SSH host is required.\n' >&2 + return 2 + fi +} + +remote_sync() { + local host=$1 files remote_dir + remote_validate_host "$host" || return + files=$(mktemp "${TMPDIR:-/tmp}/parcel-files.XXXXXX") || return + # Sending only tracked files keeps local secrets and unrelated work off the remote host. + if ! git ls-files -z > "$files.all"; then + rm -f "$files" "$files.all" + return 1 + fi + while IFS= read -r -d '' file; do + case "$file" in + .build/* | build/* | .pi/* | */.build/* | */build/*) continue ;; + esac + if [[ -e $file || -L $file ]]; then printf '%s\0' "$file" >> "$files"; fi + done < "$files.all" + if ! remote_dir=$(ssh "$host" 'mkdir -p ~/parcel-ci && cd ~/parcel-ci && mktemp -d run.XXXXXXXX'); then + rm -f "$files" "$files.all" + return 1 + fi + if [[ ! $remote_dir =~ ^run\.[A-Za-z0-9]+$ ]]; then + printf 'Unexpected remote directory: %s\n' "$remote_dir" >&2 + rm -f "$files" "$files.all" + return 1 + fi + if ! rsync -az --from0 --files-from="$files" ./ "$host:parcel-ci/$remote_dir/" >&2; then + rm -f "$files" "$files.all" + return 1 + fi + rm -f "$files" "$files.all" + printf '%s\n' "$remote_dir" +} + +if [[ ${BASH_SOURCE[0]} == "$0" ]]; then + set -euo pipefail + cd "$(dirname "$0")/.." + [[ $# -eq 1 ]] || { printf 'Usage: %s \n' "$0" >&2; exit 2; } + remote_sync "$1" +fi diff --git a/Scripts/soak.sh b/Scripts/soak.sh new file mode 100755 index 00000000..8bf544ed --- /dev/null +++ b/Scripts/soak.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/.." +if [[ $# -gt 1 || ( ${1:-debug} != debug && ${1:-debug} != release ) ]]; then + printf 'Usage: %s [debug|release]\n' "$0" >&2 + exit 2 +fi +PARCEL_SOAK=1 PARCEL_E2E_FILTER='ParcelE2ETests.*SoakTests' \ + Scripts/test-e2e.sh "${1:-debug}" diff --git a/Scripts/test-e2e.sh b/Scripts/test-e2e.sh index 9719647c..a0aea1aa 100755 --- a/Scripts/test-e2e.sh +++ b/Scripts/test-e2e.sh @@ -7,10 +7,15 @@ if [[ $# -gt 1 || ( ${1:-debug} != debug && ${1:-debug} != release ) ]]; then exit 2 fi configuration=${1:-debug} -Scripts/bundle.sh "$configuration" +bundle_args=("$configuration") +if [[ ${PARCEL_E2E_INSPECTABLE:-0} == 1 ]]; then + [[ $configuration == debug ]] || { printf 'Inspectable e2e bundles must be debug.\n' >&2; exit 2; } + bundle_args+=(--inspectable) +fi +Scripts/bundle.sh "${bundle_args[@]}" swift build --quiet -c "$configuration" --product FixtureApp bin_dir=$(swift build -c "$configuration" --show-bin-path) -PARCEL_E2E=1 \ +exec env PARCEL_E2E=1 \ PARCEL_APP_PATH="$PWD/build/Parcel.app" \ PARCEL_FIXTURE_PATH="$bin_dir/FixtureApp" \ - swift test --quiet -c "$configuration" --filter ParcelE2ETests + swift test --quiet -c "$configuration" --filter "${PARCEL_E2E_FILTER:-ParcelE2ETests}" diff --git a/Scripts/test-remote.sh b/Scripts/test-remote.sh index c37957f7..eab882e3 100755 --- a/Scripts/test-remote.sh +++ b/Scripts/test-remote.sh @@ -12,23 +12,8 @@ runner=Scripts/test.sh if [[ ${2:-} == --e2e ]]; then runner=Scripts/test-e2e.sh fi -files=$(mktemp "${TMPDIR:-/tmp}/parcel-files.XXXXXX") -trap 'rm -f "$files"' EXIT -# Sending only tracked files keeps local secrets and unrelated work off the remote Mac. -git ls-files -z | while IFS= read -r -d '' file; do - case "$file" in - .build/* | build/* | .pi/* | */.build/* | */build/*) continue ;; - esac - if [[ -e $file || -L $file ]]; then - printf '%s\0' "$file" >> "$files" - fi -done -remote_dir=$(ssh "$host" 'mkdir -p ~/parcel-ci && cd ~/parcel-ci && mktemp -d run.XXXXXXXX') -if [[ ! $remote_dir =~ ^run\.[A-Za-z0-9]+$ ]]; then - echo "Unexpected remote directory: $remote_dir" >&2 - exit 1 -fi -rsync -az --from0 --files-from="$files" ./ "$host:parcel-ci/$remote_dir/" +source Scripts/remote-sync.sh +remote_dir=$(remote_sync "$host") # The directory is validated above before it is inserted into the remote command. # shellcheck disable=SC2029 ssh "$host" "cd ~/parcel-ci/$remote_dir && $runner" diff --git a/Scripts/tests/bench-ab.sh b/Scripts/tests/bench-ab.sh new file mode 100755 index 00000000..8a25f724 --- /dev/null +++ b/Scripts/tests/bench-ab.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/../.." +python3 -I Scripts/tests/measurement-tests.py ABTests diff --git a/Scripts/tests/idle-summary.sh b/Scripts/tests/idle-summary.sh new file mode 100755 index 00000000..ac7e479d --- /dev/null +++ b/Scripts/tests/idle-summary.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/../.." +python3 -I Scripts/tests/measurement-tests.py IdleTests diff --git a/Scripts/tests/measurement-e2e.sh b/Scripts/tests/measurement-e2e.sh new file mode 100755 index 00000000..56fc8350 --- /dev/null +++ b/Scripts/tests/measurement-e2e.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/../.." +python3 -I Scripts/tests/measurement-tests.py E2ETests diff --git a/Scripts/tests/measurement-tests.py b/Scripts/tests/measurement-tests.py new file mode 100644 index 00000000..f7e7293d --- /dev/null +++ b/Scripts/tests/measurement-tests.py @@ -0,0 +1,440 @@ +#!/usr/bin/env python3 +import importlib.util +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +sys.dont_write_bytecode = True +ROOT = Path(__file__).resolve().parents[2] + + +def module(name): + spec = importlib.util.spec_from_file_location(name.replace("-", "_"), ROOT / "Scripts" / f"{name}.py") + loaded = importlib.util.module_from_spec(spec) + spec.loader.exec_module(loaded) + return loaded + + +QUIET = module("quiet-readings") +AB = module("bench-ab-summary") +TRACE = module("trace-summary") +IDLE = module("idle-summary") +TOP = """Processes: 3 total +Load Avg: 90.0, 4.0, 2.0 +PID COMMAND %CPU +1 busy 99.0 + +Processes: 3 total +Load Avg: 0.4, 0.5, 0.5 +PID COMMAND %CPU +1 launchd 0.0 +2 command with spaces 2.5 +""" +BATT = "Now drawing from 'AC Power'\n" +THERM = "Note: No thermal warning level has been recorded\nNote: No performance warning level has been recorded\nNote: No CPU power status has been recorded\n" +SETTINGS = "Battery Power:\n powermode 1\nAC Power:\n powermode 0\n sleep 0\n" +HOST = dict(hostKey="test-12345678", model="TestModel", cores=8, osBuild="test", swiftVersion="Swift test", buildConfiguration="release", counterSource="selfcounts") + + +def report(ratio=1, reporting=False, source="selfcounts", metric="cpu"): + host = dict(HOST, counterSource=source) + result = dict(name="layout/test/10", metric=metric, reportingOnly=reporting, + minimumNanoseconds=100 * ratio, instructionsPerOp=None if source == "cpu-only" or metric == "wall" else 1000 * ratio, + counterSource=source, checksum=17) + return dict(version=5, machine="host=test", host=host, results=[result]) + + +class ScriptTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="parcel measurement tests ") + self.work = Path(self.temp.name) + self.project = self.work / "project" + self.bin = self.work / "bin" + self.bin.mkdir() + (self.project / "Scripts").mkdir(parents=True) + (self.project / "Instruments").mkdir() + for file in (ROOT / "Scripts").iterdir(): + if file.is_file(): + shutil.copy2(file, self.project / "Scripts" / file.name) + shutil.copy2(ROOT / "Instruments/templates.json", self.project / "Instruments/templates.json") + self.env = dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", TEST_WORK=str(self.work)) + + def tearDown(self): + self.temp.cleanup() + + def mock(self, name, code): + path = self.bin / name + path.write_text("#!/usr/bin/env python3\n" + code) + path.chmod(0o755) + + def run_script(self, name, *args, expected=0): + result = subprocess.run(["bash", str(self.project / "Scripts" / name), *args], cwd=self.project, + env=self.env, text=True, capture_output=True, timeout=30) + self.assertEqual(result.returncode, expected, result.stdout + result.stderr) + return result + + def git(self, *args): + return subprocess.run(["git", *args], cwd=self.project, env=self.env, check=True, text=True, capture_output=True) + + def repository(self): + self.git("init", "-b", "main") + self.git("config", "user.name", "Script Test") + self.git("config", "user.email", "test@example.invalid") + self.git("add", ".") + self.git("commit", "-m", "Test fixture") + + +class QuietTests(ScriptTests): + def test_last_sample_and_ac_profile(self): + readings = QUIET.parse(TOP, BATT, THERM, SETTINGS) + self.assertTrue(readings["eligible"]) + self.assertEqual(readings["loadAverage"], 0.4) + self.assertEqual(readings["maximumProcessCPU"], 2.5) + self.assertFalse(readings["lowPowerMode"]) + + def test_each_refusal(self): + cases = [(TOP.replace("0.4,", "1.5,"), BATT, THERM, SETTINGS), + (TOP, BATT.replace("AC Power", "Battery Power"), THERM, SETTINGS), + (TOP, BATT, THERM.replace("No thermal warning level has been recorded", "Thermal warning level: 1"), SETTINGS), + (TOP.replace("2.5", "10.1"), BATT, THERM, SETTINGS), + (TOP, BATT, THERM, SETTINGS.replace("powermode 0", "lowpowermode 1"))] + for values in cases: + with self.subTest(values=values): + self.assertFalse(QUIET.parse(*values)["eligible"]) + + def test_numeric_performance_limits(self): + thermal = "Thermal level: 0\nCPU_Speed_Limit = 80\nCPU_Scheduler_Limit = 100\n" + self.assertTrue(QUIET.parse(TOP, BATT, thermal, SETTINGS)["thermalWarning"]) + + def test_unknown_readings_fail(self): + for values in [("garbage", BATT, THERM, SETTINGS), (TOP, "unknown", THERM, SETTINGS), + (TOP, BATT, "pressure unknown", SETTINGS), (TOP, BATT, THERM, "AC Power:\n sleep 0\n")]: + with self.subTest(values=values), self.assertRaises(ValueError): + QUIET.parse(*values) + + def test_wrapper_json_and_failures(self): + (self.work / "top").write_text(TOP) + for name, text in (("batt", BATT), ("therm", THERM), ("custom", SETTINGS)): + (self.work / name).write_text(text) + self.mock("top", 'import os,pathlib,sys\nassert sys.argv[1:] == ["-l","2","-s","5","-stats","pid,command,cpu"]\nsys.exit(7) if os.environ.get("FAIL_TOP") else print(pathlib.Path(os.environ["TEST_WORK"],"top").read_text(),end="")\n') + self.mock("pmset", 'import os,pathlib,sys\nprint(pathlib.Path(os.environ["TEST_WORK"],sys.argv[-1]).read_text(),end="")\n') + self.run_script("quiet-check.sh", "--output", "build/quiet.json") + self.assertEqual(json.loads((self.project / "build/quiet.json").read_text())["loadAverage"], 0.4) + (self.work / "top").write_text(TOP.replace("0.4,", "1.5,")) + self.run_script("quiet-check.sh", "--output", "build/busy.json", expected=3) + self.assertFalse(json.loads((self.project / "build/busy.json").read_text())["eligible"]) + self.env["FAIL_TOP"] = "1" + self.run_script("quiet-check.sh", expected=7) + + +class ABTests(ScriptTests): + def paired(self, base_report, head_report): + base, head = [], [] + for i in range(5): + for paths, value, label in ((base, base_report, "base"), (head, head_report, "head")): + path = self.work / f"{label}-{i}.json" + path.write_text(json.dumps(value)) + paths.append(path) + return AB.compare(base, head) + + def test_gates_and_report_only(self): + good = self.paired(report(), report(1.02)) + self.assertTrue(good["passed"]) + self.assertEqual(good["bootstrapResamples"], 10_000) + self.assertEqual(good["results"][0]["minimumNanosecondsRatio95CI"], [1.02, 1.02]) + instruction = report() + instruction["results"][0]["instructionsPerOp"] *= 1.031 + self.assertFalse(self.paired(report(), instruction)["passed"]) + self.assertFalse(self.paired(report(source="cpu-only"), report(1.06, source="cpu-only"))["passed"]) + self.assertTrue(self.paired(report(reporting=True), report(3, reporting=True))["passed"]) + self.assertTrue(self.paired(report(metric="wall"), report(3, metric="wall"))["passed"]) + wall_base, wall_head = report(metric="wall"), report(3, metric="wall") + for value in (wall_base, wall_head): value["results"][0]["counterSource"] = "smoke" + self.assertFalse(self.paired(wall_base, wall_head)["results"][0]["gating"]) + self.assertTrue(self.paired(report(), report(1.03))["passed"]) + + def test_incompatible_data(self): + for change in ("version", "host", "checksum", "coverage", "counter"): + bad = report() + if change == "version": bad["version"] = 4 + elif change == "host": bad["host"]["osBuild"] = "other" + elif change == "checksum": bad["results"][0]["checksum"] = 18 + elif change == "coverage": bad["results"][0]["name"] = "other" + elif change == "counter": bad["results"][0]["instructionsPerOp"] = None + with self.subTest(change=change), self.assertRaises(ValueError): + self.paired(report(), bad) + + def test_operational_overlay_and_alternation(self): + (self.project / "Tests/ParcelPerformanceTests").mkdir(parents=True) + (self.project / "Tests/ParcelPerformanceTests/harness.swift").write_text("base measurement") + (self.project / "Sources").mkdir() + (self.project / "Sources/production.swift").write_text("base production") + (self.project / "Package.swift").write_text("base manifest") + self.repository() + (self.project / "Tests/ParcelPerformanceTests/harness.swift").write_text("head measurement") + (self.project / "Package.swift").write_text("head manifest") + (self.work / "report.json").write_text(json.dumps(report())) + self.mock("swift", '''import json,os,pathlib,sys +w=pathlib.Path(os.environ["TEST_WORK"]) +with (w/"swift.log").open("a") as f: f.write(json.dumps(dict(args=sys.argv[1:],core=os.environ.get("PARCEL_BENCH_CORE_ONLY")))+"\\n") +if os.environ.get("FAIL_BUILD"): sys.exit(8) +assert os.environ["SWIFT_DETERMINISTIC_HASHING"]=="1" +if sys.argv[1]=="test": + assert os.environ["PARCEL_BENCH_NO_COMPARE"]=="1" + pathlib.Path(os.environ["PARCEL_BENCH_OUTPUT"]).write_text((w/"report.json").read_text()) +''') + self.run_script("bench-ab.sh", "main") + calls = [json.loads(line) for line in (self.work / "swift.log").read_text().splitlines()] + self.assertEqual([call["args"][0] for call in calls], ["build"] * 2 + ["test"] * 10) + self.assertTrue(all(call["core"] == "1" for call in calls)) + self.assertTrue(all("-enable-testing" in call["args"] for call in calls)) + for index, call in enumerate(calls[2:]): + scratch = call["args"][call["args"].index("--scratch-path") + 1] + self.assertIn("/base/" if index % 2 == 0 else "/head/", scratch) + self.assertIn("--skip-build", call["args"]) + base = Path(calls[0]["args"][calls[0]["args"].index("--package-path") + 1]) + self.assertEqual((base / "Sources/production.swift").read_text(), "base production") + self.assertEqual((base / "Tests/ParcelPerformanceTests/harness.swift").read_text(), "head measurement") + self.assertEqual((base / "Package.swift").read_text(), "head manifest") + summary = json.loads((self.project / "build/bench-ab/summary.json").read_text()) + self.assertEqual(summary["caseScope"], "common-core") + self.env["FAIL_BUILD"] = "1" + self.run_script("bench-ab.sh", "main", "--all-cases", expected=8) + + +class TraceTests(ScriptTests): + def xml(self, schemas, data): + toc = self.work / "toc.xml" + export = self.work / "data.xml" + toc.write_text('' + ''.join(f'' for name in schemas) + '') + export.write_text(data) + return TRACE.summarize(toc, export) + + def test_reference_rows_and_hitches(self): + data = '''namedurationsubsystemReduce1000000com.parcel3000000''' + summary = self.xml(["os-signpost-interval", "hitches"], data) + self.assertEqual(summary["intervals"]["Reduce"]["p50Nanoseconds"], 2000000) + self.assertEqual(summary["intervals"]["Reduce"]["p95Nanoseconds"], 3000000) + self.assertEqual(summary["hitchCount"], 2) + + def test_missing_is_not_zero_and_bad_refs_fail(self): + summary = self.xml([], "") + self.assertIsNone(summary["intervals"]) + self.assertIsNone(summary["hitchCount"]) + bad = 'nameduration1' + with self.assertRaises(ValueError): self.xml(["os-signpost-interval"], bad) + + def test_templates_and_attach_refusal(self): + self.run_script("trace-templates.sh", "--check", expected=2) + result = self.run_script("trace.sh", "smoothness", expected=2) + self.assertIn("Missing genuine custom template", result.stderr) + self.mock("xcrun", 'import sys\nassert sys.argv[1:]==["xctrace","list","templates"]\nprint("Animation Hitches")\n') + self.mock("pgrep", 'import sys\nsys.exit(1)\n') + result = self.run_script("trace.sh", "smoothness", "--installed-template", expected=2) + self.assertIn("NOT provide", result.stderr) + self.assertIn("will not launch", result.stderr) + self.run_script("trace.sh", "smoothness", "--launch", expected=2) + + + def test_trace_e2e_verdict_and_recorder_failures(self): + self.mock("pgrep", 'import sys\nsys.exit(1)\n') + self.mock("scutil", 'print("test-host")\n') + bundle = self.project / "Scripts/bundle.sh" + bundle.write_text('#!/bin/bash\nexit 0\n') + bundle.chmod(0o755) + binaries = self.work / "binaries" + runner = binaries / "ParcelPackageTests.xctest/Contents/MacOS/ParcelPackageTests" + runner.parent.mkdir(parents=True) + runner.write_text("test binary placeholder") + runner.chmod(0o755) + self.env["TEST_BINARIES"] = str(binaries) + self.mock("swift", 'import os,sys\nif "--show-bin-path" in sys.argv: print(os.environ["TEST_BINARIES"])\n') + self.mock("xcrun", '''import os,pathlib,sys +args=sys.argv[1:] +if args==["xctrace","list","templates"]: print("Animation Hitches"); sys.exit(0) +assert args[:2]==["xctrace","record"] +if os.environ.get("FAIL_TRACE"): sys.exit(7) +assert "--launch" in args and "--xunit-output" in args +assert "ParcelE2ETests.*(SmoothnessTests|LatencyTests)" in args +assert "PARCEL_SMOOTHNESS_SCENARIO=new-window-to-tile" in args +pathlib.Path(args[args.index("--output")+1]).mkdir(exist_ok=True) +if not os.environ.get("NO_VERDICT"): + verdict=os.environ.get("VERDICT", "") + pathlib.Path(args[args.index("--xunit-output")+1]).write_text(""+verdict+"") +''') + self.run_script("trace-e2e.sh", "new-window-to-tile", "--installed-template") + for key, value, status in (("VERDICT", "", 1), + ("VERDICT", "", 1), + ("NO_VERDICT", "1", 1), ("FAIL_TRACE", "1", 7)): + for artifact in (self.project / "build/traces").glob("*.xunit.xml"): + artifact.unlink() + self.env[key] = value + self.run_script("trace-e2e.sh", "new-window-to-tile", "--installed-template", expected=status) + self.env.pop(key) + + +class IdleTests(ScriptTests): + def test_actual_columns_and_second_top_sample(self): + power = '*** Running tasks ***\nName ID CPU ms/s Energy Impact\nParcel 42 0.5 0.1\nParcel 42 1.5 0.3\n' + rows = IDLE.power_rows(power, "Parcel", 42) + self.assertEqual(IDLE.summary(rows)["CPU ms/s"]["median"], 1) + tuple_rows = IDLE.power_rows('Name ID CPU ms/s Wakeups (Int, <2 ms)\nParcel 42 0.0 (1, 2)\n', "Parcel", 42) + self.assertEqual(IDLE.summary(tuple_rows)["Wakeups (Int, <2 ms)"][1]["maximum"], 2) + top = 'Processes: 1\nPID %CPU IDLEW POWER\n42 20.0 3 2.0\nProcesses: 1\nPID %CPU IDLEW POWER\n42 0.1 0 0.0\n' + self.assertEqual(IDLE.top_rows(top, 42), [dict(cpuPercent=0.1, idleWakeups=0, power=0)]) + with self.assertRaises(ValueError): IDLE.power_rows("unknown", "Parcel", 42) + with self.assertRaises(ValueError): IDLE.top_rows(top, 43) + + def test_wrapper_tool_failure_and_no_launch(self): + self.mock("pgrep", 'import sys\nsys.exit(1)\n') + self.run_script("idle-report.sh", expected=2) + self.mock("ps", 'print("/owned/Parcel")\n') + self.mock("top", 'print("mock top")\n') + self.mock("sudo", 'import sys\nsys.exit(9)\n') + self.run_script("idle-report.sh", "42", expected=9) + + +class E2ETests(ScriptTests): + def test_filter_passthrough_and_inspectable_scoping(self): + bundle = self.project / "Scripts/bundle.sh" + bundle.write_text('#!/bin/bash\nprintf "%s\\n" "$@" > "$TEST_WORK/bundle.args"\n') + bundle.chmod(0o755) + self.mock("swift", '''import json,os,pathlib,sys +w=pathlib.Path(os.environ["TEST_WORK"]) +if "--show-bin-path" in sys.argv: print(w/"binaries") +if sys.argv[1]=="test": (w/"test.args").write_text(json.dumps(sys.argv[1:])) +''') + self.env["PARCEL_E2E_FILTER"] = "ParcelE2ETests.*(Smoothness|Latency)" + self.run_script("test-e2e.sh") + args = json.loads((self.work / "test.args").read_text()) + self.assertEqual(args[-1], self.env["PARCEL_E2E_FILTER"]) + self.env["PARCEL_E2E_INSPECTABLE"] = "1" + self.run_script("test-e2e.sh", "debug") + self.assertEqual((self.work / "bundle.args").read_text(), "debug\n--inspectable\n") + self.run_script("test-e2e.sh", "release", expected=2) + # The real bundle parser rejects inspectable release before any build or signing. + shutil.copy2(ROOT / "Scripts/bundle.sh", bundle) + self.run_script("bundle.sh", "release", "--inspectable", expected=2) + + def test_leaks_owned_pid_success_and_failure_release(self): + runner = self.project / "Scripts/test-e2e.sh" + runner.write_text('''#!/bin/bash +set -eu +[[ $1 == debug && $MallocStackLogging == 1 && $PARCEL_E2E_INSPECTABLE == 1 ]] +printf '4242\\n' > "$PARCEL_LEAK_PID_FILE" +while [[ ! -f $PARCEL_LEAK_CONTINUE_FILE ]]; do sleep 0.01; done +exit "${FAIL_SOAK:-0}" +''') + runner.chmod(0o755) + self.mock("pgrep", 'import sys\nsys.exit(1)\n') + self.mock("ps", 'import os,pathlib\nprint(pathlib.Path.cwd()/"build/Parcel.app/Contents/MacOS/Parcel")\n') + self.mock("codesign", 'import plistlib,sys\nsys.stdout.buffer.write(plistlib.dumps({"com.apple.security.get-task-allow": True}))\n') + self.mock("sudo", '''import os,pathlib,sys +assert sys.argv[1:3]==["-n","/usr/bin/leaks"] +assert sys.argv[-1]=="4242" +if os.environ.get("FAIL_LEAKS"): sys.exit(1) +pathlib.Path(sys.argv[3].split("=",1)[1]).write_text("memgraph") +''') + self.run_script("leaks.sh") + self.env["FAIL_LEAKS"] = "1" + self.run_script("leaks.sh", expected=1) + self.assertTrue(all((path / "continue").exists() for path in (self.project / "build/leaks").iterdir())) + self.mock("ps", 'print("/user/Parcel")\n') + self.run_script("leaks.sh", expected=2) + self.mock("pgrep", 'print("999")\n') + self.run_script("leaks.sh", expected=2) + + +class RemoteTests(ScriptTests): + def setUp(self): + super().setUp() + self.remote = self.work / "remote-home" + self.remote.mkdir() + self.env["TEST_REMOTE_HOME"] = str(self.remote) + self.mock("ssh", '''import os,pathlib,subprocess,sys +host, command=sys.argv[1:] +assert host=="bench-test.local" +env=dict(os.environ,HOME=os.environ["TEST_REMOTE_HOME"]) +if command.startswith("bash -s --"): + sys.exit(subprocess.run(["bash","-c",command],env=env).returncode) +sys.exit(subprocess.run(["bash","-c",command],env=env).returncode) +''') + self.mock("rsync", '''import os,pathlib,shutil,sys +args=sys.argv[1:]; src,dst=args[-2:] +remote=pathlib.Path(os.environ["TEST_REMOTE_HOME"]) +def path(value): return remote/value.split(":",1)[1] if ":" in value else pathlib.Path(value) +s,d=path(src),path(dst) +if any(a.startswith("--files-from=") for a in args): + files=pathlib.Path(next(a.split("=",1)[1] for a in args if a.startswith("--files-from="))).read_bytes().split(b"\\0") + d.mkdir(parents=True,exist_ok=True) + for f in files: + if not f: continue + f=os.fsdecode(f); target=d/f; target.parent.mkdir(parents=True,exist_ok=True); shutil.copy2(s/f,target,follow_symlinks=False) +else: + if dst.endswith("/"): d.mkdir(parents=True,exist_ok=True); d=d/s.name + if s.is_dir(): shutil.copytree(s,d,dirs_exist_ok=True) + else: d.parent.mkdir(parents=True,exist_ok=True); shutil.copy2(s,d) +''') + self.mock("caffeinate", 'import os,sys\nassert sys.argv[1:3]==["-i","-s"]\nos.execvp(sys.argv[3],sys.argv[3:])\n') + self.mock("nice", 'import os,sys\nassert sys.argv[1:3]==["-n","-5"]\nos.execvp(sys.argv[3],sys.argv[3:])\n') + self.mock("make", '''import os,pathlib,sys,time +p=pathlib.Path.cwd(); (p/"build").mkdir(exist_ok=True) +if os.environ.get("FAIL_TASK"): sys.exit(8) +(p/"build/bench-results.json").write_text("{}") +if sys.argv[1]=="bench-record": + (p/"Benchmarks/baselines").mkdir(parents=True,exist_ok=True) + f=p/"Benchmarks/baselines/test-host-TestModel-8.json"; f.write_text("{}") + # Explicit mtime newer than quiet output, independent of filesystem timestamp resolution. + t=(p/"build/bench-quiet.json").stat().st_mtime+1; os.utime(f,(t,t)) +''') + quiet = self.project / "Scripts/quiet-check.sh" + quiet.write_text('''#!/bin/bash +mkdir -p build +printf '{"eligible":%s}\\n' "${QUIET_ELIGIBLE:-true}" > "$2" +exit "${QUIET_STATUS:-0}" +''') + quiet.chmod(0o755) + (self.project / "Benchmarks/baselines").mkdir(parents=True) + self.repository() + + def test_explicit_host_and_offline_setup(self): + self.run_script("bench-remote.sh", expected=2) + self.run_script("bench-remote.sh", "-bad", expected=2) + self.run_script("bench-remote.sh", "bench-test.local", "unknown", expected=2) + self.run_script("bench-remote.sh", "bench-test.local", "bench", "BASE=main", expected=2) + self.run_script("bench-host-setup.sh", "bench-test.local", "--dry-run") + self.assertFalse((self.remote / "parcel-ci").exists()) + + def test_remote_artifacts_and_baseline_unstaged(self): + self.run_script("bench-remote.sh", "bench-test.local", "bench-record") + self.assertTrue((self.project / "Benchmarks/baselines/test-host-TestModel-8.json").exists()) + self.assertNotIn("test-host", self.git("diff", "--cached", "--name-only").stdout) + outputs = list((self.project / "build/remote/bench-test.local").iterdir()) + self.assertTrue((outputs[0] / "bench-results.json").exists()) + self.assertTrue((outputs[0] / "bench-quiet.json").exists()) + self.assertFalse(any(path.name == ".git" for path in (self.remote / "parcel-ci").iterdir())) + + def test_quiet_failure_preserves_readings_and_task_failure(self): + self.env.update(BENCH_WAIT="0", QUIET_STATUS="3", QUIET_ELIGIBLE="false") + self.run_script("bench-remote.sh", "bench-test.local", expected=3) + self.assertTrue(list((self.project / "build/remote").rglob("bench-quiet.json"))) + self.env["QUIET_STATUS"] = "2" + self.run_script("bench-remote.sh", "bench-test.local", expected=2) + self.env.update(QUIET_STATUS="0", FAIL_TASK="1") + self.run_script("bench-remote.sh", "bench-test.local", expected=8) + + def test_factored_existing_runner(self): + script = self.project / "Scripts/test.sh" + script.write_text('#!/bin/bash\nprintf "remote test ran\\n"\n') + self.git("add", "Scripts/test.sh") + result = self.run_script("test-remote.sh", "bench-test.local") + self.assertIn("remote test ran", result.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/Scripts/tests/packaging.sh b/Scripts/tests/packaging.sh index 66828482..b0be4ff0 100755 --- a/Scripts/tests/packaging.sh +++ b/Scripts/tests/packaging.sh @@ -6,7 +6,7 @@ unset BASH_ENV work=$(mktemp -d "${TMPDIR:-/tmp}/parcel packaging.XXXXXX") trap 'rm -rf "$work"' EXIT mkdir -p "$work/project/Scripts" "$work/project/Resources" "$work/project/Sources" "$work/bin" "$work/products" "$work/probe/Sources/Probe/Resources/Probe.xcassets/Sample.imageset" -cp Scripts/product.env Scripts/version.sh Scripts/packaging-paths.sh Scripts/bundle-preflight.sh Scripts/check-binaries.py Scripts/strip-binary-paths.py Scripts/install-bundle.py Scripts/bundle.sh Scripts/update-metadata.py Scripts/check-bundle.sh Scripts/designated-requirement.sh Scripts/make-dev-cert.sh Scripts/test.sh Scripts/test-e2e.sh Scripts/test-remote.sh "$work/project/Scripts/" +cp Scripts/product.env Scripts/version.sh Scripts/packaging-paths.sh Scripts/bundle-preflight.sh Scripts/check-binaries.py Scripts/strip-binary-paths.py Scripts/install-bundle.py Scripts/bundle.sh Scripts/update-metadata.py Scripts/check-bundle.sh Scripts/designated-requirement.sh Scripts/make-dev-cert.sh Scripts/test.sh Scripts/test-e2e.sh Scripts/test-remote.sh Scripts/remote-sync.sh "$work/project/Scripts/" cp Resources/Info.plist "$work/project/Resources/" mkdir "$work/project/Packaging" cp Packaging/Sparkle-LICENSE "$work/project/Packaging/" @@ -207,6 +207,8 @@ check test -x "$app/Contents/MacOS/Parcel" check Scripts/check-bundle.sh --no-launch "$app" check Scripts/check-bundle.sh "$app" check test "$(library_validation_disabled)" = true +check app_entitlements +check fails /usr/libexec/PlistBuddy -c 'Print :com.apple.security.get-task-allow' "$work/app-entitlements.plist" check test -L "$app/Contents/Frameworks/Sparkle.framework/Sparkle" check test "$(/usr/libexec/PlistBuddy -c 'Print :ParcelUpdatesEnabled' "$plist")" = false check test "$(/usr/libexec/PlistBuddy -c 'Print :SUEnableAutomaticChecks' "$plist")" = false @@ -262,7 +264,14 @@ check fails Scripts/bundle.sh check grep -q 'Resource bundle already exists' "$work/failure.log" check codesign --verify --strict "$app" rmdir Resources/Probe_Probe.bundle +check Scripts/bundle.sh debug --inspectable > "$work/inspectable.log" 2>&1 +check app_entitlements +check test "$(/usr/libexec/PlistBuddy -c 'Print :com.apple.security.get-task-allow' "$work/app-entitlements.plist")" = true +check test "$(library_validation_disabled)" = true +check fails Scripts/bundle.sh release --inspectable check Scripts/bundle.sh release > "$work/release.log" 2>&1 +check app_entitlements +check fails /usr/libexec/PlistBuddy -c 'Print :com.apple.security.get-task-allow' "$work/app-entitlements.plist" check test "$(/usr/libexec/PlistBuddy -c 'Print :SUFeedURL' "$plist")" = "$PARCEL_APPCAST_URL" check test "$(/usr/libexec/PlistBuddy -c 'Print :SUPublicEDKey' "$plist")" = "$PARCEL_UPDATE_PUBLIC_KEY" check Scripts/check-bundle.sh --no-launch "$app" diff --git a/Scripts/tests/quiet-check.sh b/Scripts/tests/quiet-check.sh new file mode 100755 index 00000000..ed6a2c0b --- /dev/null +++ b/Scripts/tests/quiet-check.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/../.." +python3 -I Scripts/tests/measurement-tests.py QuietTests diff --git a/Scripts/tests/remote-measurement.sh b/Scripts/tests/remote-measurement.sh new file mode 100755 index 00000000..50839b55 --- /dev/null +++ b/Scripts/tests/remote-measurement.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/../.." +python3 -I Scripts/tests/measurement-tests.py RemoteTests diff --git a/Scripts/tests/trace-summary.sh b/Scripts/tests/trace-summary.sh new file mode 100755 index 00000000..7b94d74a --- /dev/null +++ b/Scripts/tests/trace-summary.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/../.." +python3 -I Scripts/tests/measurement-tests.py TraceTests diff --git a/Scripts/trace-common.sh b/Scripts/trace-common.sh new file mode 100644 index 00000000..df6c6bc0 --- /dev/null +++ b/Scripts/trace-common.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +trace_template() { + local mode=$1 installed=$2 file template available + file=$(python3 -I -c 'import json,sys; print(json.load(open(sys.argv[1]))[sys.argv[2]]["custom"])' Instruments/templates.json "$mode") || return + if [[ $installed == 0 ]]; then + [[ -f Instruments/$file ]] || { printf 'Missing genuine custom template: Instruments/%s. Export it from Instruments or explicitly select --installed-template (not equivalent).\n' "$file" >&2; return 2; } + printf '%s\n' "$PWD/Instruments/$file" + else + template=$(python3 -I -c 'import json,sys; print(json.load(open(sys.argv[1]))[sys.argv[2]]["installed"])' Instruments/templates.json "$mode") || return + available=$(xcrun xctrace list templates) || return + grep -Fxq "$template" <<< "$available" || { printf 'Required installed template is unavailable: %s\n' "$template" >&2; return 2; } + printf 'Custom template not selected: using installed "%s"; it does NOT provide the custom combined lanes or filters.\n' "$template" >&2 + printf '%s\n' "$template" + fi +} + +trace_output_path() { + local mode=$1 host stamp + host=$(scutil --get LocalHostName) || return + [[ $host =~ ^[A-Za-z0-9._-]+$ ]] || { printf 'Unsafe or empty host name.\n' >&2; return 2; } + stamp=$(date -u +%Y%m%dT%H%M%SZ) || return + mkdir -p build/traces + printf '%s/build/traces/%s-%s-%s.trace\n' "$PWD" "$mode" "$host" "$stamp" +} diff --git a/Scripts/trace-e2e.sh b/Scripts/trace-e2e.sh new file mode 100755 index 00000000..e7fb0073 --- /dev/null +++ b/Scripts/trace-e2e.sh @@ -0,0 +1,48 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/.." +source Scripts/trace-common.sh +usage() { printf 'Usage: %s [--seconds N] [--installed-template]\n' "$0" >&2; exit 2; } +[[ $# -ge 1 ]] || usage +scenario=$1 +shift +case "$scenario" in swap-2-windows|layout-change-10|layout-change-30|hotkey-focus-move|slow-neighbour|new-window-to-tile) ;; *) printf 'Unknown smoothness scenario: %s\n' "$scenario" >&2; exit 2 ;; esac +seconds=120 +installed=0 +while (( $# )); do + case "$1" in + --seconds) [[ $# -ge 2 && $2 =~ ^[1-9][0-9]*$ ]] || usage; seconds=$2; shift 2 ;; + --installed-template) installed=1; shift ;; + *) usage ;; + esac +done +template=$(trace_template smoothness "$installed") +process_status=0 +pgrep -x Parcel > /dev/null || process_status=$? +case "$process_status" in + 0) printf 'Quit your running Parcel first; trace-e2e only launches the harness-owned bundle.\n' >&2; exit 2 ;; + 1) ;; + *) printf 'Could not inspect running Parcel processes.\n' >&2; exit "$process_status" ;; +esac +configuration=${PARCEL_TRACE_CONFIGURATION:-release} +case "$configuration" in debug|release) ;; *) printf 'Trace configuration must be debug or release.\n' >&2; exit 2 ;; esac +Scripts/bundle.sh "$configuration" +swift build -c "$configuration" --product FixtureApp +swift build -c "$configuration" --build-tests -Xswiftc -enable-testing +bin_dir=$(swift build -c "$configuration" --show-bin-path) +runner="$bin_dir/ParcelPackageTests.xctest/Contents/MacOS/ParcelPackageTests" +[[ -x $runner ]] || { printf 'Swift Testing executable missing: %s\n' "$runner" >&2; exit 2; } +output=$(trace_output_path "e2e-$scenario") +xcrun xctrace record --template "$template" --time-limit "${seconds}s" --output "$output" \ + --target-stdout "${output%.trace}.test.log" \ + --env PARCEL_E2E=1 --env PARCEL_TRACE=1 \ + --env "PARCEL_APP_PATH=$PWD/build/Parcel.app" --env "PARCEL_FIXTURE_PATH=$bin_dir/FixtureApp" \ + --env "PARCEL_SMOOTHNESS_SCENARIO=$scenario" \ + --launch -- "$runner" --testing-library swift-testing --filter 'ParcelE2ETests.*(SmoothnessTests|LatencyTests)' \ + --xunit-output "${output%.trace}.xunit.xml" +[[ -d $output ]] || { printf 'Recorder succeeded without writing a trace.\n' >&2; exit 2; } +python3 -I -c 'import sys,xml.etree.ElementTree as E; r=E.parse(sys.argv[1]).getroot(); cases=[c for c in r.iter("testcase") if c.find("skipped") is None]; failures=list(r.iter("failure"))+list(r.iter("error")); sys.exit(0 if cases and not failures else 1)' "${output%.trace}.xunit.xml" || { + printf 'Scenario failed, did not run, or was terminated before its test verdict; inspect %s.\n' "${output%.trace}.test.log" >&2 + exit 1 +} +printf 'E2E trace: %s; test log: %s\n' "$output" "${output%.trace}.test.log" diff --git a/Scripts/trace-summary.py b/Scripts/trace-summary.py new file mode 100644 index 00000000..a4897629 --- /dev/null +++ b/Scripts/trace-summary.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Summarize xctrace XML; unavailable tables are null, never invented zeros.""" +import argparse +import json +import math +from pathlib import Path +import statistics +import sys +import xml.etree.ElementTree as ET + + +def summarize(toc_path, data_path): + toc, data = ET.parse(toc_path).getroot(), ET.parse(data_path).getroot() + schemas = {table.get("schema") for table in toc.iter("table")} + refs = {element.get("id"): element for element in data.iter() if element.get("id")} + + def text(element): + seen = set() + while element.get("ref"): + ref = element.get("ref") + if ref in seen or ref not in refs: + raise ValueError(f"unresolved or cyclic xctrace reference: {ref}") + seen.add(ref) + element = refs[ref] + return (element.text or element.get("fmt") or "").strip() + + intervals = {} + hitch_count = 0 if "hitches" in schemas else None + rows_seen = set() + for container in data.iter(): + schema = container.find("schema") + if schema is None: + continue + name = schema.get("name") or schema.get("schema") + columns = [(col.findtext("mnemonic") or col.get("mnemonic") or "") for col in schema.findall("col")] + if name not in ("os-signpost-interval", "hitches"): + continue + if name not in schemas: + raise ValueError(f"exported schema {name} is absent from the trace TOC") + for row in container.findall("row"): + if id(row) in rows_seen: + continue + rows_seen.add(id(row)) + if name == "hitches": + hitch_count += 1 + continue + values = list(row) + if len(values) != len(columns): + raise ValueError("xctrace row does not match its schema columns") + mapping = dict(zip(columns, values)) + name_key = next((key for key in ("name", "signpost-name", "os-signpost-name", "event-name") if key in mapping), None) + if name_key is None or "duration" not in mapping: + raise ValueError(f"unsupported signpost columns: {columns}") + subsystem_key = next((key for key in ("subsystem", "signpost-subsystem", "os-signpost-subsystem") if key in mapping), None) + if subsystem_key and not text(mapping[subsystem_key]).startswith(("com.parcel", "dev.parcel")): + continue + interval = text(mapping[name_key]) + duration = float(text(mapping["duration"])) + if not interval or not math.isfinite(duration) or duration < 0: + raise ValueError("invalid signpost name or duration; raw duration must be nanoseconds") + intervals.setdefault(interval, []).append(duration) + result = {} + for name, values in sorted(intervals.items()): + values.sort() + result[name] = dict(count=len(values), p50Nanoseconds=statistics.median(values), + p95Nanoseconds=values[math.ceil(len(values) * 0.95) - 1], maximumNanoseconds=max(values)) + return dict(version=1, intervals=result if "os-signpost-interval" in schemas else None, + intervalStatus="available" if "os-signpost-interval" in schemas else "missing os-signpost-interval table", + hitchCount=hitch_count, hitchStatus="available" if hitch_count is not None else "missing hitches table", + availableSchemas=sorted(value for value in schemas if value)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--toc", type=Path, required=True) + parser.add_argument("--data", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + try: + result = summarize(args.toc, args.data) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2, allow_nan=False) + "\n") + for name, stats in (result["intervals"] or {}).items(): + print(f"{name}: n={stats['count']} p50={stats['p50Nanoseconds'] / 1e6:.3f} ms p95={stats['p95Nanoseconds'] / 1e6:.3f} ms max={stats['maximumNanoseconds'] / 1e6:.3f} ms") + print(f"Signposts: {result['intervalStatus']}; hitches: {result['hitchCount'] if result['hitchCount'] is not None else 'unavailable'} ({result['hitchStatus']})") + return 0 + except (OSError, ValueError, ET.ParseError) as error: + print(f"trace-summary: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/Scripts/trace-templates.sh b/Scripts/trace-templates.sh new file mode 100755 index 00000000..230bc791 --- /dev/null +++ b/Scripts/trace-templates.sh @@ -0,0 +1,31 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/.." +if [[ $# -ne 1 || ( $1 != --check && $1 != --list ) ]]; then + printf 'Usage: %s --check|--list\n' "$0" >&2 + exit 2 +fi +if [[ $1 == --list ]]; then + xcrun xctrace list templates + exit +fi +mkdir -p build/traces/templates +status=0 +for mode in smoothness idle memory counters; do + file=$(python3 -I -c 'import json,sys; print(json.load(open(sys.argv[1]))[sys.argv[2]]["custom"])' Instruments/templates.json "$mode") + if [[ ! -f Instruments/$file ]]; then + printf 'Missing genuine Instruments-exported custom template: Instruments/%s\n' "$file" >&2 + status=2 + continue + fi + plutil -lint "Instruments/$file" + plutil -convert xml1 -o "build/traces/templates/$mode.plist.xml" "Instruments/$file" + if [[ -f Instruments/$mode.plist.xml ]]; then + diff -u "Instruments/$mode.plist.xml" "build/traces/templates/$mode.plist.xml" || status=1 + else + printf 'Missing review snapshot: Instruments/%s.plist.xml. Review the exported plist before saving a snapshot.\n' "$mode" >&2 + status=2 + fi +done +printf 'Plist checks do not prove recorder compatibility; custom templates must be exported and exercised in Instruments.\n' >&2 +exit "$status" diff --git a/Scripts/trace.sh b/Scripts/trace.sh new file mode 100755 index 00000000..d9e8079f --- /dev/null +++ b/Scripts/trace.sh @@ -0,0 +1,43 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/.." +source Scripts/trace-common.sh +usage() { printf 'Usage: %s smoothness|idle|memory|counters [--seconds N] [--attach] [--pid PID] [--installed-template]\n %s export \n' "$0" "$0" >&2; exit 2; } +[[ $# -ge 1 ]] || usage +mode=$1 +shift +if [[ $mode == export ]]; then + [[ $# -eq 1 && -d $1 && $1 == *.trace ]] || usage + trace=$(realpath "$1") + mkdir -p build/traces + output="$PWD/build/traces/$(basename "${trace%.trace}")" + xcrun xctrace export --input "$trace" --toc --output "$output.toc.xml" + xcrun xctrace export --input "$trace" --xpath '/trace-toc/run/data/table[@schema="os-signpost-interval" or @schema="hitches"]' --output "$output.data.xml" + python3 -I Scripts/trace-summary.py --toc "$output.toc.xml" --data "$output.data.xml" --output "$output.summary.json" + exit +fi +case "$mode" in smoothness|idle|memory|counters) ;; *) usage ;; esac +seconds=30 +installed=0 +pid= +while (( $# )); do + case "$1" in + --seconds) [[ $# -ge 2 && $2 =~ ^[1-9][0-9]*$ ]] || usage; seconds=$2; shift 2 ;; + --pid) [[ $# -ge 2 && $2 =~ ^[1-9][0-9]*$ ]] || usage; pid=$2; shift 2 ;; + --attach) shift ;; + --installed-template) installed=1; shift ;; + --launch) printf 'trace never launches or controls your app. Use trace-e2e.sh for a harness-owned launch.\n' >&2; exit 2 ;; + *) usage ;; + esac +done +template=$(trace_template "$mode" "$installed") +if [[ -z $pid ]]; then + pid=$(pgrep -x Parcel) || { printf 'No running Parcel to attach to. This script will not launch it.\n' >&2; exit 2; } + [[ $pid =~ ^[1-9][0-9]*$ ]] || { printf 'Multiple Parcel processes; select one with --pid.\n' >&2; exit 2; } +fi +process=$(ps -p "$pid" -o comm=) +[[ ${process##*/} == Parcel ]] || { printf 'PID does not identify Parcel.\n' >&2; exit 2; } +output=$(trace_output_path "$mode") +xcrun xctrace record --template "$template" --attach "$pid" --time-limit "${seconds}s" --output "$output" +[[ -d $output ]] || { printf 'Recorder succeeded without writing a trace.\n' >&2; exit 2; } +printf 'Trace: %s\n' "$output" -- knotmirror 0.0.1 From 254328b5c04af0806c97e910ad162152ebaeb6b9 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 13:33:38 -0400 Subject: [PATCH 07/22] Record measurement host approval and setup checklist --- Benchmarks/hosts.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Benchmarks/hosts.md diff --git a/Benchmarks/hosts.md b/Benchmarks/hosts.md new file mode 100644 index 00000000..b7d95a6a --- /dev/null +++ b/Benchmarks/hosts.md @@ -0,0 +1,30 @@ +# Measurement hosts + +No remote host is selected or approved by default. Pass an explicit SSH host to +`Scripts/bench-remote.sh` or `Scripts/bench-host-setup.sh`. Setup defaults to an +offline dry run; `--check` reads remote configuration and `--apply` changes only +the listed AC power settings and backup exclusion. No host was exercised while +implementing these scripts. + +Before measuring, use a dedicated console session, AC power, a matching Xcode +and Swift toolchain, and a quiet window. Add `~/parcel-ci` to Spotlight Privacy. +Grant Accessibility to the host's `build/Parcel.app` manually and verify with +`PARCEL_E2E_PREFLIGHT_ONLY=1 Scripts/test-e2e.sh`. Optional privileged energy and +leak tools need an explicitly reviewed sudo policy, not unrestricted sudo. + +Remote runs poll quietness for `BENCH_WAIT=15m`, record actual readings, and fail +with exit 3 if the host never qualifies. Build and tool failures are not quiet +failures and are not retried. Runs use `caffeinate -i -s` and `nice -n -5`; a +priority-setting failure is surfaced, never replaced with another scheduling +class. Retrieved reports live in `build/remote///`. Newly +recorded baselines return unstaged for deliberate review. + +| Role | Approved host | Last baseline | +|---|---|---| +| Primary instruction gate | Not selected | None | +| Intel CPU-only cross-check | Not selected | None | +| Live smoothness / idle / soak | Not selected | None | + +Record an approved host and dates here only after real preparation and runs. +Counter support, OS build, toolchain, host identity and quietness belong in each +report; hardware model alone is not a host identity. -- knotmirror 0.0.1 From 301308b35b7a4401e364921f6b6b2cf74318ec02 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 13:35:42 -0400 Subject: [PATCH 08/22] Wire measurement targets and document remaining evidence --- Benchmarks/MEASUREMENT.md | 37 +++++++ Benchmarks/README.md | 184 ++++++++++++++++++--------------- Benchmarks/RESULTS.md | 11 +- Benchmarks/baselines/README.md | 18 ++-- Makefile | 42 +++++++- 5 files changed, 193 insertions(+), 99 deletions(-) create mode 100644 Benchmarks/MEASUREMENT.md diff --git a/Benchmarks/MEASUREMENT.md b/Benchmarks/MEASUREMENT.md new file mode 100644 index 00000000..be649a10 --- /dev/null +++ b/Benchmarks/MEASUREMENT.md @@ -0,0 +1,37 @@ +# Measurement rollout — 2026-10-31 + +This package changes measurement and instrumentation, not tiling or motion policy. +New optimization proofs are reporting-only until their owning packages land. + +| Finding | Outcome | Evidence / remaining work | +|---|---|---| +| H1 | Implemented | v5 instruction +3% gate, startup known-work probe, explicit fallback/smoke modes, deliberate frame-copy regression probe. | +| H2 | Fixed | Host-keyed files and strict OS/compiler/configuration/counter compatibility; identity and mismatch tests. | +| H3 | Implemented, live unverified | Timestamped fixture ring and six 20-trial scenarios. Delivered frames are measured, not compositor pixels. Settle90 is diagnostic. | +| M1 | Partial | Categorized emit-only sites and actual synthetic tap→reduce→plan→tick→write test. Correlated Command span and genuine combined Instruments templates remain undone. Supported signposts cannot be backdated. Automatic watcher reloads lack the explicit Reload interval. | +| M2 | Partial | Steady tick, retarget, publication, offscreen overlay, layer-identity and retained-memory measurements. Malloc-zone deltas cannot prove total allocation calls, so exact mallocs/tick gating is not claimed. | +| M3 | Implemented, live unverified | 60-second CPU/instruction/interrupt/package-idle budgets, failure captures, static wait inventory. Native Space phase is opt-in; physical display reconfiguration is not automated. | +| M4 | Implemented, live unverified | 30-window/2,000-command footprint soak, tail slope, debug-only inspection entitlement and owned-PID leak graph handshake. No release inspection entitlement. | +| M5 | Fixed | Actual load/power/thermal/process/Low Power Mode readings, exit 3 refusal, parser tests; this busy host was refused. | +| L1 | Implemented | Five interleaved A/B rounds with identical v5 measurement overlay, instruction ratios and 10,000-resample CPU confidence intervals. Default common-core scope excludes hooks absent on older revisions. | +| L2 | Fixed | Distinct wall/CPU/instruction p99; omitted below 1,000 latency samples; no p99 regression gate. | +| L3 | Fixed | Performance e2e filters and dedicated make targets; unknown scenario selections fail before launch. | + +## Deliberately not installed or fabricated + +- No remote Mac was selected or contacted. Remote and host-preparation commands + require an explicit host. No nightly launch agent was installed. +- No quiet baseline was recorded. Preflight observed load **38.62** and maximum + sampled process CPU **84.5%** and refused with exit 3. +- Two headless proofs require genuine production hooks: layout traversal count and + isolated undo-position cost. Live/signpost probes remain external entries with + reasons. Unsupported entries never emit a fake successful baseline. +- Custom Instruments presets require genuine GUI exports. Default custom-template + recording fails clearly; explicit installed presets are labelled non-equivalent. +- No Screen Recording, compositor pixel validation, or SIP-dependent call was added. + +## Validation and measured evidence + +Final build/test counts and before/after instruction results are recorded here +after the validation runs finish. Raw local reports stay under `build/`, not in +host-independent checked-in baselines. diff --git a/Benchmarks/README.md b/Benchmarks/README.md index 87ee8426..d9467bd2 100644 --- a/Benchmarks/README.md +++ b/Benchmarks/README.md @@ -1,87 +1,101 @@ # Performance checks -`swift test` exercises every headless workload, validates every checked-in machine -baseline, and runs fixed CPU-budget regression tests. It launches no app and needs -neither Accessibility nor Screen Recording. - -## Machine baselines - -Run `make bench-record` on a quiet Mac. It writes -`Benchmarks/baselines/-.json` and `build/bench-results.json`. -Review the numbers, run `make bench`, then commit the baseline deliberately. -Recording replaces that machine's report; it never borrows another machine's data. -The old v1 baseline was invalid and has been removed. No replacement has been -recorded on this heavily loaded host. - -`make bench` exits nonzero if this machine has no baseline and tells you to run -`make bench-record` on a quiet machine. Missing cases, incompatible schemas, -sampling settings, timing bases, and machine identities also fail. Plain -`swift test` checks that every checked-in baseline parses and covers exactly the -same cases as smoke mode. Adding a layout or workload requires new baselines. -Keep the relative gate out of CI until a dedicated quiet runner has its own report. - -Both commands use release optimization and user-interactive main-thread priority, -restoring the previous priority afterwards. Each workload warms up, then runs 15 -batches of at least 10 ms. `iterations` is the minimum block count, not the exact -number of completed operations. Synchronous paths use **per-thread CPU time**; -IPC crosses threads and uses round-trip wall time. A regression over 20% in the -minimum batch cost fails. Medians and 129-sample wall p99 remain diagnostic. -CPU time excludes descheduling and other threads, but does not prove wall latency. - -A fixed arithmetic calibration is recorded in every report. Scaling CPU ratios -by it is opt-in with `BENCH_CALIBRATE=1`; IPC is never scaled. Leave it off unless -you deliberately want to normalize changes in host CPU speed. - -Use `BENCH_OUTPUT=build/candidate.json` for a different output path, or -`BENCH_BASELINE=/path/to/report.json` for an explicit baseline. Machine matching -still applies. Neither override silently selects another host's baseline. - -## Workloads and fixed budgets - -- Event through layout: focus observations with 50 and 200 windows, every layout. - The reducer callback captures the end of layout, excluding diff and effects. - A missing layout stage throws with the case name, never records zero. -- Layout plus diff: relayout with every frame changed, including reducer/effects. -- Compressed gaps: 200 windows on a small screen with an oversized gap, every - layout, exercising exact local minimum-size recurrence. -- Reducer throughput: a coalesced burst of 16 focus observations. -- Config: parse and validate 500 distinct rules. -- IPC: ping through the real Unix socket client/server, codec, and dispatch. -- Snapshot/menu: frame and mini-map/count-badge models for 6, 50, and 200 windows. -- Animation: plan and sample the first 120 Hz frame for 50 and 200 windows. - -Fixture construction, display adaptation, config source generation, and server -startup stay outside timed loops. Each workspace adapts to usable and full display -geometry before placement. Timed fixtures request `Int.max` so every layout really -places all requested windows. Regression tests also cover portrait, ultrawide, -compact, and distinct usable/full frames, with unlimited and capability-limited -caps. Checksums keep work observable to the optimizer. - -Traversal equivalence compares the same adapted tree against an independent, -uncached placement and minimum-size recurrence. It covers hidden stack minimums, -compressed gaps, conflicting minimums, mixed partitions, and invalid focus. - -The fixed 50-window targets are 1 ms through layout and 0.5 ms for layout plus -diff. Plain tests enforce CPU-work ceilings with 8× headroom and the minimum of -nine warmed samples, including debug builds. This catches large algorithmic -regressions without timing scheduler stalls. It does **not** certify the live p99 -targets; those still require quiet-machine measurements. - -## Live budgets and idle proof - -Headless timings cannot establish window-server detection, AX write latency, -visible settling, frame drops, resident memory, hangs, or 60-second CPU/wake-ups. -Use the opt-in e2e harness and Instruments. Quit your running app first; never -measure by moving your own windows. - -Enable `PARCEL_TRACE=1` for signposts. The pure reducer emits `apply`, `layout`, -and `diff` boundaries without clocks or logging. Engine tracing measures `detect` -from AX notification arrival through queued flush, plus `write`, `settle`, and -first-write/settled intervals. Disabled tracing has no reducer callbacks or -trace-only transaction metadata. - -Idle regressions exercise engine schedulers, display links, input permissions, -and platform notification/debounce/watchdog lifecycles with injected sources. -Trust changes are event-driven, with activation and wake as backstops, never a -repeating idle poll. Platform coverage and any remaining bounded post-activity -wake-ups are recorded in `RESULTS.md`. +`swift test` runs headless smoke workloads and fixed debug CPU ceilings. It launches +no app and requests neither Accessibility nor Screen Recording. Hosted CI prints +that it is smoke-only. A smoke report cannot pass a performance comparison. + +## Regression measurements + +`make bench-record` first requires a successful `quiet-check`, then deliberately +writes `Benchmarks/baselines/--.json`. The host is LocalHostName +plus eight SHA-256 digits of the platform UUID; the UUID itself is never recorded. +Review and commit a baseline deliberately. None has been recorded on this busy Mac. + +`make bench` compares the current host's baseline. Schema v5 rejects a different +host, macOS build, Swift version, build configuration, counter source, case set, +sampling configuration, or checksum. An OS/compiler upgrade requires re-recording, +not an automatic migration. Override paths with `BENCH_BASELINE` and `BENCH_OUTPUT`. + +Synchronous cases gate on median retired instructions per operation: **+3%** fails. +Per-thread counters are probed across known work before measurement; zero or stuck +counters crash locally. Public process counters are an explicitly announced +fallback. Intel without counters must use a quiet-verified CPU-only comparison. +Hosted guests with unavailable counters remain smoke-only and never record zeros. + +Three warm-up batches precede 15 batches of at least 10 ms. CPU and wall times, +cycles, proof counters, and retained malloc blocks/bytes are also recorded. CPU/time +regressions above **25%**, and absolute release CPU budgets, gate only when both +runs have verified quiet conditions. Wall/CPU/instruction p99 needs at least 1,000 +latency samples. Expensive soak/hung-app workloads omit p99 instead of labelling a +small sample as p99. Async work does not claim per-thread instruction counts. + +Malloc-zone statistics measure **retained** allocations, not total malloc calls. +They cannot establish an exact mallocs/tick gate. Layer-identity proof counters +measure newly reachable layers separately; Instruments is needed for total churn. +Calibration is diagnostic only; `BENCH_CALIBRATE=1` now fails explicitly. + +`make bench-ab BASE=main` builds the merge base and working tree before five +interleaved A/B rounds. Both use the same v5 instrumentation overlay and deterministic +hashing. The default common-core scope compares the existing 44 cases, so an older +base need not have new testing hooks. `Scripts/bench-ab.sh main --all-cases` includes +all compatible cases. The summary reports instruction ratios and a deterministic +10,000-resample CPU bootstrap interval. Instructions above +3%, or a CPU interval's +lower bound above 1.05, fail. Reporting-only cases never gate. + +## Workload catalog + +`build/bench-catalog.json` contains every new requested benchmark's name, budget, +execution kind, status, and reporting-only reason. Executable cases produce actual +measurements in `build/bench-results.json`. Cases awaiting another package's code +fix are reporting-only. Missing hooks or live-only probes are explicitly listed as +unsupported; they do not emit fake successful measurements. + +Fixtures cover 10/50/200 windows, multiple workspaces/displays, drag ticks, mixed +turns, snapshot subscribers, full motion ticks, retargeting, layers, config reload, +input handlers, and sanitized recorded window-list decoding. Synthetic backend +method counts are not described as measured AX calls or actor hops. + +## Live measurement targets + +Quit your running Parcel first. Only the harness-owned `build/Parcel.app` needs its +Accessibility grant; the runner needs neither Accessibility nor Screen Recording. + +- `make smoothness`: six fixture scenarios, 20 trials each, raw write/vsync JSON, + input latency, settling, starvation, gaps, jank, overshoot, and writes/refresh. + Quiet readings permit live gates; otherwise results are reporting-only. +- `make idle`: five-second settle, 60-second CPU/instruction/interrupt/package-idle + deltas across settled, focused/settings-closed, and config-reloaded states. + `PARCEL_IDLE_SPACE=1` adds a native Space roundtrip. Failure captures sample/logs. +- `make idle-report PID=...`: optional sudo power diagnostics for a running app. +- `make soak`: 30 fixture windows, 2,000 commands, footprint every 100 commands; + final <40 MB and last-ten-sample slope <8 KB/command. +- `make leaks`: explicitly inspectable debug bundle, stack logging, soak handshake, + and leak graph. Only the harness-owned PID is inspected. Release cannot request + the debug inspection entitlement. +- `make trace MODE=smoothness SECONDS=30`: attach to an existing app, never launch it. +- `make trace-e2e SCENARIO=swap-2-windows`: record a harness-owned scenario and retain + its test verdict. Export with `Scripts/trace.sh export `. + +Custom combined Instruments templates need genuine GUI exports. Missing templates +fail clearly; `TRACE_OPTIONS=--installed-template` explicitly selects a +non-equivalent installed preset. See `Instruments/README.md` for the missing lanes. +Emit-only trace sites use recorder `isEnabled`; transaction bookkeeping remains +behind `PARCEL_TRACE=1`. Input records the event timestamp numerically because the +supported signpost API cannot backdate an interval. + +## Host safety + +`make quiet-check` writes every condition to `build/bench-quiet.json`: load <1.5, +AC power, no thermal warning, no sampled process >10% CPU, Low Power Mode off. +It exits 3 with reasons when busy. Compare tolerates that only with counters; +`BENCH_STRICT_QUIET=1` makes quietness mandatory. + +`make bench-remote HOST= TASK=bench` requires an explicit host. +Nothing here selects or contacts another Mac automatically. Remote runs wait for +quietness, keep the host awake, copy artifacts back, and leave recorded baselines +unstaged. `Scripts/bench-host-setup.sh ` is dry-run unless `--apply` is explicit. +No nightly job is installed. `Benchmarks/hosts.md` lists the preparation checklist. + +`Benchmarks/idle-waits.json` documents every current bounded wait; unit tests reject +new unreviewed waits, repeating watchdogs, strict timers, and stale allowances. +It is a static guard, not proof that the live idle budget passes. diff --git a/Benchmarks/RESULTS.md b/Benchmarks/RESULTS.md index b3d3902d..de5c4cf6 100644 --- a/Benchmarks/RESULTS.md +++ b/Benchmarks/RESULTS.md @@ -6,12 +6,13 @@ There is no valid checked-in baseline yet. The v1 report was recorded before the layout hot-path fixes and sampler changes; it was removed, not migrated by changing its version. Final recording is deliberately deferred because this Mac is heavily loaded by other agents. Run `make bench-record` on a quiet machine, review its -hardware-keyed report, then run `make bench` before committing it. +host-keyed report, then run `make bench` before committing it. -The current v4 schema records per-thread CPU minima and medians, wall medians and -p99, and an arithmetic calibration. IPC uses wall time. The gate compares minima; -calibration scaling is explicit and optional. Plain tests validate any checked-in -report and enforce fixed 50-window CPU budgets with generous headroom. +Schema v5 gates synchronous work on retired instructions (+3%), with CPU/time +(+25%) only on verified quiet hosts. It records host, OS build, compiler, +configuration, counter source, retained malloc deltas, and proof counters. +P99 is absent below 1,000 samples. IPC remains wall-time-only. Hosted CI explicitly +runs smoke mode and cannot certify budgets. See `MEASUREMENT.md` for this rollout. ## Historical hot-path measurements diff --git a/Benchmarks/baselines/README.md b/Benchmarks/baselines/README.md index 3aaaa220..777d744e 100644 --- a/Benchmarks/baselines/README.md +++ b/Benchmarks/baselines/README.md @@ -1,10 +1,12 @@ -# Machine baselines +# Host baselines -No valid baseline is checked in yet. The old v1 report predated the hot-path fixes -and sampler changes; it was removed rather than relabeled. +No valid baseline is checked in yet. Older schemas are rejected, not relabelled. -On a quiet Mac, `make bench-record` writes `-.json` here. -Review it, run `make bench`, then commit it. Never borrow another machine's report. -Plain `swift test` validates every JSON report here against the current schema, -sampling settings, timing bases, hardware filename, and complete workload list. -A new layout or workload requires recording new baselines. +On a quiet Mac, `make bench-record` writes `--.json` here. +The host includes LocalHostName and eight SHA-256 digits of the platform UUID. +Review the v5 report, run `make bench`, then commit it deliberately. + +Reports record macOS build, Swift version, build configuration, counter source, +quiet conditions, and every executable case. Another host or an OS/compiler +upgrade needs an explicit new baseline. Plain tests validate all reports here. +Missing cases never silently borrow a different report. diff --git a/Makefile b/Makefile index 1878247f..3250bd5a 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ CONFIG ?= debug -.PHONY: build app check-app dmg release-dry-run run test test-serial e2e lint hooks format remote-test clean bench bench-record +.PHONY: build app check-app dmg release-dry-run run test test-serial e2e lint hooks format remote-test clean bench bench-record bench-ab bench-remote smoothness idle idle-report soak leaks trace trace-e2e quiet-check build: swift build @@ -40,6 +40,46 @@ bench: bench-record: Scripts/bench.sh record "$(BENCH_OUTPUT)" "$(BENCH_BASELINE)" "$(BENCH_CALIBRATE)" +BASE ?= main +TASK ?= bench +MODE ?= smoothness +SECONDS ?= 30 +SCENARIO ?= swap-2-windows +PERF_CONFIG ?= release +TRACE_OPTIONS ?= + +bench-ab: + Scripts/bench-ab.sh "$(BASE)" + +bench-remote: + @test -n "$(HOST)" || { printf 'Set HOST to the Mac you authorized.\n' >&2; exit 2; } + Scripts/bench-remote.sh "$(HOST)" "$(TASK)" $(if $(filter bench-ab,$(TASK)),"BASE=$(BASE)",) + +smoothness: + PARCEL_BENCH_QUIET=build/bench-quiet.json Scripts/quiet-check.sh --output build/bench-quiet.json || test $$? -eq 3 + PARCEL_BENCH_QUIET=build/bench-quiet.json PARCEL_E2E_FILTER='ParcelE2ETests.*(SmoothnessTests|LatencyTests)' Scripts/test-e2e.sh "$(PERF_CONFIG)" + +idle: + PARCEL_E2E_FILTER='ParcelE2ETests.*IdleBudgetTests' Scripts/test-e2e.sh "$(PERF_CONFIG)" + +idle-report: + Scripts/idle-report.sh $(if $(PID),"$(PID)",) + +soak: + Scripts/soak.sh "$(PERF_CONFIG)" + +leaks: + Scripts/leaks.sh + +trace: + Scripts/trace.sh "$(MODE)" --seconds "$(SECONDS)" $(TRACE_OPTIONS) + +trace-e2e: + Scripts/trace-e2e.sh "$(SCENARIO)" $(TRACE_OPTIONS) + +quiet-check: + Scripts/quiet-check.sh --output build/bench-quiet.json + lint: Scripts/lint.sh -- knotmirror 0.0.1 From e44e2db57e6a54360e9258bd79a30a8c936c7801 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 13:38:13 -0400 Subject: [PATCH 09/22] Map host identity wire keys explicitly --- Tests/ParcelPerformanceTests/BenchmarkBaselines.swift | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Tests/ParcelPerformanceTests/BenchmarkBaselines.swift b/Tests/ParcelPerformanceTests/BenchmarkBaselines.swift index 3a9e9cfe..82b82d09 100644 --- a/Tests/ParcelPerformanceTests/BenchmarkBaselines.swift +++ b/Tests/ParcelPerformanceTests/BenchmarkBaselines.swift @@ -59,10 +59,11 @@ struct BenchmarkMachine: Equatable { let host = try command("/usr/sbin/scutil", ["--get", "LocalHostName"]) let data = Data(try command("/usr/sbin/ioreg", ["-a", "-r", "-d", "1", "-c", "IOPlatformExpertDevice"]).utf8) struct RegistryRecord: Decodable { - let IOPlatformUUID: String + let platformUUID: String + enum CodingKeys: String, CodingKey { case platformUUID = "IOPlatformUUID" } } let records = try PropertyListDecoder().decode([RegistryRecord].self, from: data) - guard let uuid = records.first?.IOPlatformUUID, + guard let uuid = records.first?.platformUUID, let cores = Int(try command("/usr/sbin/sysctl", ["-n", "hw.ncpu"])) else { throw BenchmarkFailure.measurement("hardware identity") } return try Self( @@ -144,7 +145,7 @@ struct BenchmarkBaselineTests { #expect(throws: BenchmarkFailure.self) { try BenchmarkMachine(identity: "Mac;cores=oops") } } - @Test func UUIDHashIsStableAndOnlyEightHexDigitsAreExposed() throws { + @Test func uuidHashIsStableAndOnlyEightHexDigitsAreExposed() throws { let uuid = "00000000-0000-4000-8000-000000000001" let first = try BenchmarkMachine.key(localHostName: "test", platformUUID: uuid) #expect(first.count == 13) -- knotmirror 0.0.1 From c579d5c4226c24d0cb0154a6462197276d564ecb Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 13:39:29 -0400 Subject: [PATCH 10/22] Drain synthetic writes before asserting settled trace state --- .../CategorizedTraceTests.swift | 25 ++++++++++++++++--- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/Tests/ParcelEngineTests/CategorizedTraceTests.swift b/Tests/ParcelEngineTests/CategorizedTraceTests.swift index cf47332e..8262aff0 100644 --- a/Tests/ParcelEngineTests/CategorizedTraceTests.swift +++ b/Tests/ParcelEngineTests/CategorizedTraceTests.swift @@ -89,6 +89,8 @@ private struct CategorizedTraceHarness { try scheduler.runReady() world.emit(.observed(.focusChanged(WindowID(rawValue: 1)))) try scheduler.runReady() + try drainWrites() + try #require(engine.isIdle) trace.entries.removeAll() } @@ -97,6 +99,19 @@ private struct CategorizedTraceHarness { links.tickAll(at: clock.now) try scheduler.runReady() } + + func drainWrites() throws { + for _ in 0..<100 { + if world.pendingWriteCount > 0 { + try world.completeNextWrite() + } else if scheduler.pendingCount > 0 { + try scheduler.runNext() + } else { + return + } + } + throw HarnessError.schedulerDidNotQuiesce + } } @Suite("Categorized tracing") @@ -188,12 +203,14 @@ struct CategorizedTraceTests { harness.world.emit(.observed(.commandIssued(.swap(.right)))) try harness.scheduler.runReady() harness.engine.setReduceMotion(true) - try harness.scheduler.runReady() - #expect(harness.engine.isIdle) #expect(harness.links.runningCount == 0) + // Snapping stops the driver, but the final write can still wait for its app's slot. + try harness.drainWrites() + #expect(harness.engine.isIdle) #expect(harness.trace.entries.isEmpty) - let write = try #require(harness.world.allWrites.last) - #expect(write.frame == harness.engine.snapshot.state.frames[write.window]) + for (window, frame) in harness.engine.snapshot.state.frames { + #expect(harness.world.frames[window] == frame) + } await harness.engine.stop() } -- knotmirror 0.0.1 From 267c3b53bf7d7d47daa5ed9358b2eea4a7a9823f Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 13:46:29 -0400 Subject: [PATCH 11/22] Reset motion fixtures and align counter scopes --- .../BenchmarkCatalog.swift | 2 +- .../HotPathBenchmarkTests.swift | 7 +++++ .../HotPathBenchmarks.swift | 27 ++++++++++++++----- .../HotPathFixtures.swift | 27 +++++++++++++++---- 4 files changed, 50 insertions(+), 13 deletions(-) diff --git a/Tests/ParcelPerformanceTests/BenchmarkCatalog.swift b/Tests/ParcelPerformanceTests/BenchmarkCatalog.swift index 0838e1db..789b555e 100644 --- a/Tests/ParcelPerformanceTests/BenchmarkCatalog.swift +++ b/Tests/ParcelPerformanceTests/BenchmarkCatalog.swift @@ -80,7 +80,7 @@ enum BenchmarkCatalog { ] { headless( "input-tap/\(variant)", "instructions +3%; release CPU <= \(budget)", - "Input callback dispatch runs with synthetic CGEvent and real handlers; event-tap scheduling and kernel delivery require live tracing.", + "Synthetic CGEvent runs real handlers. Hotkey counts measure press callbacks, not engine enqueues; event-tap scheduling and kernel delivery require live tracing.", iterations: 100) } for count in [10, 50, 200] { diff --git a/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift b/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift index cc731f07..5b31dd7a 100644 --- a/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift +++ b/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift @@ -67,6 +67,9 @@ extension AppKitTestSuite { #expect(Set(harness.results.map(\.name)) == BenchmarkCatalog.names) #expect(harness.results.count == BenchmarkCatalog.names.count) #expect(harness.results.allSatisfy { $0.checksum != 0 }) + let hotkey = try #require(harness.results.first { $0.name == "input-tap/keydown-hotkey" }) + #expect(hotkey.proofMetrics["hotkey-press-callbacks"] == 1) + #expect(hotkey.proofMetrics["commands-enqueued"] == nil) let jitter = try #require(harness.results.first { $0.name == "CoalescerProMotionJitter" }) #expect(jitter.proofMetrics["ticks"] == 600) #expect(try #require(jitter.proofMetrics["dispatches"]) > 0) @@ -105,6 +108,10 @@ extension AppKitTestSuite { let first = try fixture.run() let second = try fixture.run() #expect(first.checksum == second.checksum) + #expect(first.instructions == nil) + #expect(first.cycles == nil) + #expect(second.instructions == nil) + #expect(second.cycles == nil) #expect(first.proofMetrics["sampled-frames"].map { $0 > 0 } == true) #expect(first.proofMetrics["dispatched-batches"].map { $0 > 0 } == true) #expect(fixture.source.starts > 0) diff --git a/Tests/ParcelPerformanceTests/HotPathBenchmarks.swift b/Tests/ParcelPerformanceTests/HotPathBenchmarks.swift index 6115ba55..0cc470eb 100644 --- a/Tests/ParcelPerformanceTests/HotPathBenchmarks.swift +++ b/Tests/ParcelPerformanceTests/HotPathBenchmarks.swift @@ -175,11 +175,12 @@ enum HotPathBenchmarks { } 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() + var observation = try fixture.run(counters: counters) observation.counterOperations = 30 return observation } @@ -187,7 +188,7 @@ enum HotPathBenchmarks { let soak = MotionTickFixture(count: 30) try measure("motion-soak/30x10000", &harness, latencySamples: 0) { let before = hotPathRetainedBytes() - var result = try soak.run(ticks: 10000) + var result = try soak.run(ticks: 10000, counters: counters) result.counterOperations = 10000 result.proofMetrics["retained-bytes-after-stop-delta"] = Double(hotPathRetainedBytes() - before) result.proofMetrics["display-source-running-after-stop"] = soak.source.isRunning ? 1 : 0 @@ -200,16 +201,25 @@ enum HotPathBenchmarks { var animator = Animator() try animator.schedule(requests, at: 100) _ = try animator.tick(at: 100.075) - let cpu = BenchmarkCPUClock.now() - let start = ContinuousClock.now 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 { @@ -220,6 +230,8 @@ enum HotPathBenchmarks { } 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, @@ -353,14 +365,14 @@ enum HotPathBenchmarks { guard consumed, presses == before + 1 else { throw BenchmarkFailure.measurement("hotkey did not dispatch") } return BenchmarkObservation( checksum: 1, - proofMetrics: ["commands-enqueued": Double(presses - before), "consumed": consumed ? 1 : 0]) + 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: ["commands-enqueued": 0, "consumed": 0]) + return BenchmarkObservation(checksum: 1, proofMetrics: ["hotkey-press-callbacks": 0, "consumed": 0]) } let fixture = HotPathStateFixture(count: 10) var mouse = MouseModel() @@ -468,13 +480,14 @@ enum HotPathBenchmarks { let file = directory.appendingPathComponent(variant + ".toml") try Data(source.utf8).write(to: file) let store = ConfigStore(fileURL: file) + let initialState = HotPathStateFixture(count: 10).state try await measureAsync("config-reload/\(variant)", &harness) { let snapshot = await store.reload() guard snapshot.loadState == .loaded, snapshot.diagnostics.isEmpty else { throw BenchmarkFailure.measurement("config reload rejected") } let applied = try AppliedConfiguration(snapshot.activeConfiguration) - var state = HotPathStateFixture(count: 10).state + var state = initialState applied.installLayoutDefaults(in: &state) for key in state.workspaces.keys { let display = state.displays[key.display] diff --git a/Tests/ParcelPerformanceTests/HotPathFixtures.swift b/Tests/ParcelPerformanceTests/HotPathFixtures.swift index 7cafaffe..9721b98d 100644 --- a/Tests/ParcelPerformanceTests/HotPathFixtures.swift +++ b/Tests/ParcelPerformanceTests/HotPathFixtures.swift @@ -160,9 +160,7 @@ final class MotionTickFixture { private(set) var checksum = 1 private var time = 100.0 private(set) var failure: MotionError? - private lazy var driver = DisplayLinkDriver( - source: source, clock: { [unowned self] in time }, - onFrames: { [unowned self] in accept($0) }, onFailure: { [unowned self] in failure = $0 }) + private var driver: DisplayLinkDriver? init(count: Int) { requests = (0.. MotionRequest in @@ -176,7 +174,9 @@ final class MotionTickFixture { } } - func run(ticks: Int = 30) throws -> BenchmarkObservation { + func run(ticks: Int = 30, counters: BenchmarkCounters = BenchmarkCounters(source: .smoke)) throws + -> BenchmarkObservation + { stop() coalescer = FrameCoalescer() frames = 0 @@ -184,20 +184,36 @@ final class MotionTickFixture { checksum = 1 failure = nil time = 100 + let driver = DisplayLinkDriver( + source: source, clock: { [unowned self] in time }, + onFrames: { [unowned self] in accept($0) }, onFailure: { [unowned self] in failure = $0 }) + self.driver = driver + defer { stop() } try driver.schedule(requests, at: time) let cpu = BenchmarkCPUClock.now() let start = ContinuousClock.now + let before = try counters.read() for tick in 1...ticks { time = 100 + Double(tick) / 120 if driver.animator.isIdle { try driver.schedule(requests, at: time) } source.tick(at: time) } + let after = try counters.read() let wall = BenchmarkHarness.nanoseconds(start.duration(to: .now)) / Double(ticks) let elapsedCPU = BenchmarkCPUClock.elapsed(since: cpu) / Double(ticks) + let measuredCounters: BenchmarkCounterReading? + if let before { + guard let after else { throw BenchmarkFailure.measurement("motion tick counters disappeared") } + measuredCounters = try after.delta(from: before) + } else { + measuredCounters = nil + } if let failure { throw failure } guard frames > 0, batches > 0 else { throw BenchmarkFailure.measurement("motion tick did no work") } let observation = BenchmarkObservation( checksum: checksum, nanoseconds: wall, cpuNanoseconds: elapsedCPU, + instructions: measuredCounters.map { Double($0.instructions) / Double(ticks) }, + cycles: measuredCounters.map { Double($0.cycles) / Double(ticks) }, proofMetrics: [ "sampled-frames": Double(frames), "dispatched-batches": Double(batches), "ticks": Double(ticks), "pending-frames-at-stop": Double(coalescer.pendingCount), @@ -207,7 +223,8 @@ final class MotionTickFixture { } func stop() { - driver.stop() + driver?.stop() + driver = nil coalescer = FrameCoalescer() } -- knotmirror 0.0.1 From 6f9638fa6cdc9858d0f36a747bee69dd382516c4 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 13:51:28 -0400 Subject: [PATCH 12/22] Launch traces through the verified SwiftPM test helper --- Scripts/name-allowlist.json | 6 ++++++ Scripts/tests/measurement-tests.py | 16 ++++++++++++++++ Scripts/trace-e2e.sh | 10 ++++++++-- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/Scripts/name-allowlist.json b/Scripts/name-allowlist.json index 761da407..d8f20772 100644 --- a/Scripts/name-allowlist.json +++ b/Scripts/name-allowlist.json @@ -120,6 +120,12 @@ "line_hash": "812cf3ab60072c2c6f76ede4f59af4ce29533ed0c037b425de119ad40ef847f7", "token_hash": "696b17ca4934cef3361f291676be1fa27859206523064ae9844fdf61a718171c", "reason": "Compiled animation continuity suite" + }, + { + "scope": "artifact", + "line_hash": "8bba385a931c355cc582ea298a43665667bcee8841f5d7ea901c990246268f34", + "token_hash": "696b17ca4934cef3361f291676be1fa27859206523064ae9844fdf61a718171c", + "reason": "Compiled fixture motion readback diagnostic" } ] } diff --git a/Scripts/tests/measurement-tests.py b/Scripts/tests/measurement-tests.py index f7e7293d..567333a6 100644 --- a/Scripts/tests/measurement-tests.py +++ b/Scripts/tests/measurement-tests.py @@ -253,11 +253,24 @@ class TraceTests(ScriptTests): runner.write_text("test binary placeholder") runner.chmod(0o755) self.env["TEST_BINARIES"] = str(binaries) + toolchain = self.work / "toolchain" + helper = toolchain / "libexec/swift/pm/swiftpm-testing-helper" + helper.parent.mkdir(parents=True) + (toolchain / "bin").mkdir() + helper.write_text("test helper placeholder") + helper.chmod(0o755) + self.env["TEST_TOOLCHAIN"] = str(toolchain) self.mock("swift", 'import os,sys\nif "--show-bin-path" in sys.argv: print(os.environ["TEST_BINARIES"])\n') self.mock("xcrun", '''import os,pathlib,sys args=sys.argv[1:] if args==["xctrace","list","templates"]: print("Animation Hitches"); sys.exit(0) +if args==["--find","swift"]: print(os.environ["TEST_TOOLCHAIN"]+"/bin/swift"); sys.exit(0) +if args==["--sdk","macosx","--show-sdk-platform-path"]: print("/test-platform"); sys.exit(0) assert args[:2]==["xctrace","record"] +assert "--test-bundle-path" in args and "--testing-library" in args +assert args[args.index("--launch")+2].endswith("swiftpm-testing-helper") +assert "DYLD_FRAMEWORK_PATH=/test-platform/Developer/Library/Frameworks" in args +assert "DYLD_LIBRARY_PATH=/test-platform/Developer/usr/lib" in args if os.environ.get("FAIL_TRACE"): sys.exit(7) assert "--launch" in args and "--xunit-output" in args assert "ParcelE2ETests.*(SmoothnessTests|LatencyTests)" in args @@ -276,6 +289,9 @@ if not os.environ.get("NO_VERDICT"): self.env[key] = value self.run_script("trace-e2e.sh", "new-window-to-tile", "--installed-template", expected=status) self.env.pop(key) + helper.unlink() + result = self.run_script("trace-e2e.sh", "new-window-to-tile", "--installed-template", expected=2) + self.assertIn("bundle-loading test helper missing", result.stderr) class IdleTests(ScriptTests): diff --git a/Scripts/trace-e2e.sh b/Scripts/trace-e2e.sh index e7fb0073..e4613d50 100755 --- a/Scripts/trace-e2e.sh +++ b/Scripts/trace-e2e.sh @@ -31,14 +31,20 @@ swift build -c "$configuration" --product FixtureApp swift build -c "$configuration" --build-tests -Xswiftc -enable-testing bin_dir=$(swift build -c "$configuration" --show-bin-path) runner="$bin_dir/ParcelPackageTests.xctest/Contents/MacOS/ParcelPackageTests" -[[ -x $runner ]] || { printf 'Swift Testing executable missing: %s\n' "$runner" >&2; exit 2; } +[[ -f $runner ]] || { printf 'Swift Testing bundle missing: %s\n' "$runner" >&2; exit 2; } +swift_path=$(xcrun --find swift) +helper="$(dirname "$swift_path")/../libexec/swift/pm/swiftpm-testing-helper" +[[ -x $helper ]] || { printf 'SwiftPM bundle-loading test helper missing: %s\n' "$helper" >&2; exit 2; } +platform=$(xcrun --sdk macosx --show-sdk-platform-path) output=$(trace_output_path "e2e-$scenario") xcrun xctrace record --template "$template" --time-limit "${seconds}s" --output "$output" \ --target-stdout "${output%.trace}.test.log" \ --env PARCEL_E2E=1 --env PARCEL_TRACE=1 \ --env "PARCEL_APP_PATH=$PWD/build/Parcel.app" --env "PARCEL_FIXTURE_PATH=$bin_dir/FixtureApp" \ --env "PARCEL_SMOOTHNESS_SCENARIO=$scenario" \ - --launch -- "$runner" --testing-library swift-testing --filter 'ParcelE2ETests.*(SmoothnessTests|LatencyTests)' \ + --env "DYLD_FRAMEWORK_PATH=$platform/Developer/Library/Frameworks" \ + --env "DYLD_LIBRARY_PATH=$platform/Developer/usr/lib" \ + --launch -- "$helper" --test-bundle-path "$runner" --testing-library swift-testing --filter 'ParcelE2ETests.*(SmoothnessTests|LatencyTests)' \ --xunit-output "${output%.trace}.xunit.xml" [[ -d $output ]] || { printf 'Recorder succeeded without writing a trace.\n' >&2; exit 2; } python3 -I -c 'import sys,xml.etree.ElementTree as E; r=E.parse(sys.argv[1]).getroot(); cases=[c for c in r.iter("testcase") if c.find("skipped") is None]; failures=list(r.iter("failure"))+list(r.iter("error")); sys.exit(0 if cases and not failures else 1)' "${output%.trace}.xunit.xml" || { -- knotmirror 0.0.1 From 3d66e5b5d405c841c5d82a5177f09f14b781c080 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 14:05:57 -0400 Subject: [PATCH 13/22] Record instruction evidence and live validation blockers --- Benchmarks/MEASUREMENT.md | 38 +++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/Benchmarks/MEASUREMENT.md b/Benchmarks/MEASUREMENT.md index be649a10..1279738e 100644 --- a/Benchmarks/MEASUREMENT.md +++ b/Benchmarks/MEASUREMENT.md @@ -32,6 +32,38 @@ New optimization proofs are reporting-only until their owning packages land. ## Validation and measured evidence -Final build/test counts and before/after instruction results are recorded here -after the validation runs finish. Raw local reports stay under `build/`, not in -host-independent checked-in baselines. +Debug and release production builds passed. Both parallel and non-parallel runs passed **2,660 tests +in 255 suites**; all **18 shell regression suites** passed. Strict formatting and +name checks passed. Direct Swift Testing bundle loading and xunit output were +verified with the selected Xcode helper (2 safe fixture timestamp tests). + +Five interleaved A/B rounds passed all **44 common-core cases**, with no instruction +or bootstrap CPU regressions. Both revisions used the same v5 measurement overlay. +The table gives the median of each revision's five instruction measurements; +small differences are measurement variation, not claimed algorithmic improvements. + +| Case | Base instructions/op | Head instructions/op | +|---|---:|---:| +| event-layout/grid/50 | 502,720 | 500,548 | +| layout-diff/bsp/50 | 447,249 | 445,181 | +| animation-plan-sample/200 | 974,202 | 974,171 | +| snapshot-menu/200 | 233,948 | 233,746 | + +Raw A/B evidence is `build/bench-ab/summary.json` and its per-round reports. The +catalog has **84 executable new headless cases**, plus **53 external/deferred +entries** (137 total). Pending code fixes remain reporting-only. The full release +report contains **128 cases**, with verified `selfcounts` and no zero placeholders. + +The deliberate `layout-diff/bsp/50` frame-copy probe measured **445,910 → 576,549 +instructions/op (+29.30%)** and was correctly rejected by the +3% gate. Its +checksum stayed identical. Evidence: `build/bench-regression-proof.json`. + +Live preflight stopped before Accessibility probing because release packaging +requires secure update metadata (`A secure HTTPS URL without credentials or a +fragment is required`). No replacement URL or grant was invented. Smoothness, +idle, soak and leak budgets therefore remain live-unverified. Optional standalone +`footprint` category exports are also not implemented. + +These measurements precede the final integration merge from main; the final build, +unit and static gates are rerun after that merge. No host-independent baseline is +fabricated. -- knotmirror 0.0.1 From 5e2784f231d95597b8f8132669abbeaa3729bb56 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 14:34:24 -0400 Subject: [PATCH 14/22] Record post-integration validation results --- Benchmarks/MEASUREMENT.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Benchmarks/MEASUREMENT.md b/Benchmarks/MEASUREMENT.md index 1279738e..9051cd8f 100644 --- a/Benchmarks/MEASUREMENT.md +++ b/Benchmarks/MEASUREMENT.md @@ -54,8 +54,8 @@ catalog has **84 executable new headless cases**, plus **53 external/deferred entries** (137 total). Pending code fixes remain reporting-only. The full release report contains **128 cases**, with verified `selfcounts` and no zero placeholders. -The deliberate `layout-diff/bsp/50` frame-copy probe measured **445,910 → 576,549 -instructions/op (+29.30%)** and was correctly rejected by the +3% gate. Its +The post-integration `layout-diff/bsp/50` frame-copy probe measured **447,472 → 578,081 +instructions/op (+29.19%)** and was correctly rejected by the +3% gate. Its checksum stayed identical. Evidence: `build/bench-regression-proof.json`. Live preflight stopped before Accessibility probing because release packaging @@ -64,6 +64,8 @@ fragment is required`). No replacement URL or grant was invented. Smoothness, idle, soak and leak budgets therefore remain live-unverified. Optional standalone `footprint` category exports are also not implemented. -These measurements precede the final integration merge from main; the final build, -unit and static gates are rerun after that merge. No host-independent baseline is -fabricated. +The interleaved A/B measurements precede integration from main. After integrating +layout-memory review fixes, both builds and both unit modes passed (**2,729 tests +in 256 suites**), and the 128-case release report and regression probe passed. +Static gates passed with no warnings. Later main updates are integrated and the +build/unit gates repeated before handoff. No host-independent baseline is fabricated. -- knotmirror 0.0.1 From d3d77872b009e6b253f204f1f0b509e95178b6b6 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 14:48:38 -0400 Subject: [PATCH 15/22] Adapt highlight probes and keep smoke workloads bounded --- Benchmarks/README.md | 3 +++ .../HotPathBenchmarkTests.swift | 9 +++++++++ Tests/ParcelPerformanceTests/HotPathBenchmarks.swift | 11 +++++++++-- Tests/ParcelPerformanceTests/HotPathFixtures.swift | 7 ++++--- 4 files changed, 25 insertions(+), 5 deletions(-) diff --git a/Benchmarks/README.md b/Benchmarks/README.md index d9467bd2..65ba7105 100644 --- a/Benchmarks/README.md +++ b/Benchmarks/README.md @@ -28,6 +28,9 @@ regressions above **25%**, and absolute release CPU budgets, gate only when both runs have verified quiet conditions. Wall/CPU/instruction p99 needs at least 1,000 latency samples. Expensive soak/hung-app workloads omit p99 instead of labelling a small sample as p99. Async work does not claim per-thread instruction counts. +Smoke runs use 30 soak ticks instead of 10,000 and yield between workload groups, +so headless checks do not monopolize the main actor during unrelated UI tests. +Actual tick counts remain in the proof metrics; full release runs keep 10,000. Malloc-zone statistics measure **retained** allocations, not total malloc calls. They cannot establish an exact mallocs/tick gate. Layer-identity proof counters diff --git a/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift b/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift index 5b31dd7a..e1b54cd8 100644 --- a/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift +++ b/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift @@ -103,6 +103,15 @@ extension AppKitTestSuite { #expect(chips.panels.allSatisfy { !$0.isVisible }) } + @Test func smokeSoakUsesABoundedTickCountAndReportsActualWork() throws { + #expect(HotPathBenchmarks.soakTicks(full: true) == 10000) + #expect(HotPathBenchmarks.soakTicks(full: false) == 30) + let fixture = MotionTickFixture(count: 30) + let result = try fixture.run(ticks: HotPathBenchmarks.soakTicks(full: false)) + #expect(result.proofMetrics["ticks"] == 30) + #expect(!fixture.source.isRunning) + } + @Test func motionUsesTheDriverAndReleasesItsSource() throws { let fixture = MotionTickFixture(count: 30) let first = try fixture.run() diff --git a/Tests/ParcelPerformanceTests/HotPathBenchmarks.swift b/Tests/ParcelPerformanceTests/HotPathBenchmarks.swift index 0cc470eb..05eda8dd 100644 --- a/Tests/ParcelPerformanceTests/HotPathBenchmarks.swift +++ b/Tests/ParcelPerformanceTests/HotPathBenchmarks.swift @@ -15,9 +15,13 @@ import Testing 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) try await configCases(&harness) try await nativeCases(&harness) @@ -174,6 +178,8 @@ enum HotPathBenchmarks { ]) } + 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] { @@ -186,10 +192,11 @@ enum HotPathBenchmarks { } } 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: 10000, counters: counters) - result.counterOperations = 10000 + 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 diff --git a/Tests/ParcelPerformanceTests/HotPathFixtures.swift b/Tests/ParcelPerformanceTests/HotPathFixtures.swift index 9721b98d..2aeb529c 100644 --- a/Tests/ParcelPerformanceTests/HotPathFixtures.swift +++ b/Tests/ParcelPerformanceTests/HotPathFixtures.swift @@ -499,8 +499,8 @@ final class HotPathOverlayFixture { let configuration = MotionConfiguration(highlight: .glow) let target = changing ? moved : snapshot canvas.update( - display: display, snapshot: target, configuration: configuration, - accessibility: OverlayAccessibility(), color: .systemBlue) + display: display, windows: target.windows, focusedWindow: target.focusedWindow, cutouts: target.windows, + configuration: configuration, accessibility: OverlayAccessibility(), color: .systemBlue) let style = OverlayHighlightStyle( configuration: configuration, accessibility: OverlayAccessibility(), active: true) focus.move( @@ -510,7 +510,8 @@ final class HotPathOverlayFixture { focus.styleHighlight(style, color: .systemBlue, scale: display.scale) if changing { canvas.update( - display: display, snapshot: snapshot, configuration: configuration, + display: display, windows: snapshot.windows, focusedWindow: snapshot.focusedWindow, + cutouts: snapshot.windows, configuration: configuration, accessibility: OverlayAccessibility(), color: .systemBlue) focus.move( to: display.localFrame(snapshot.windows[0].frame), radius: 10, -- knotmirror 0.0.1 From 6346d43f316be5898a491514d2d13cd2fd3c94e7 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 14:40:43 -0400 Subject: [PATCH 16/22] Keep idle mouse edits out of layout Only end a mouse gesture when a model or undo session exists. Idle mouse settings edits no longer enqueue a layout pass; active and unmanaged-pointer undo sessions still clean up. Signed-off-by: Vincent Taverna --- Sources/ParcelEngine/EngineMouse.swift | 1 + .../MouseIntegrationTests.swift | 18 ++++++++++++++- .../WorkspaceTransactionTests.swift | 22 ++++++++++++++++++- 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/Sources/ParcelEngine/EngineMouse.swift b/Sources/ParcelEngine/EngineMouse.swift index bea3dff2..317d54b7 100644 --- a/Sources/ParcelEngine/EngineMouse.swift +++ b/Sources/ParcelEngine/EngineMouse.swift @@ -30,6 +30,7 @@ extension ParcelEngine { public func cancelMouseGesture() { flushMouseTurn() + guard mouseModel.isActive || snapshot.state.undoGesture != nil else { return } applyMouse(mouseModel.cancel(state: snapshot.state, awaitingMouseUp: false) + [.event(.undoGestureEnded)]) } diff --git a/Tests/ParcelEngineTests/MouseIntegrationTests.swift b/Tests/ParcelEngineTests/MouseIntegrationTests.swift index 7a8508ce..f04e4024 100644 --- a/Tests/ParcelEngineTests/MouseIntegrationTests.swift +++ b/Tests/ParcelEngineTests/MouseIntegrationTests.swift @@ -2,10 +2,11 @@ import CoreGraphics import ParcelAnimation import ParcelConfig import ParcelCore -import ParcelEngine import ParcelPlatform import Testing +@testable import ParcelEngine + @Suite("Mouse monitor into engine") @MainActor struct MouseIntegrationTests { @@ -272,6 +273,21 @@ struct MouseIntegrationTests { await harness.engine.stop() } + @Test func cancellationEndsUndoSessionWithoutManagedWindow() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + let initial = harness.engine.snapshot.state + harness.engine.handleMouse(sample(.down, Point(x: -100, y: -100))) + #expect(!harness.engine.mouseModel.isActive) + #expect(harness.engine.snapshot.state.undoGesture != nil) + harness.engine.cancelMouseGesture() + #expect(harness.engine.snapshot.state.undoGesture == nil) + #expect(harness.engine.snapshot.state.workspaces == initial.workspaces) + #expect(harness.world.frames == initial.frames) + await harness.engine.stop() + } + @Test func invalidProgrammaticMouseConfigurationIsRejected() throws { for mouse in [ MouseConfiguration(swapModifiers: []), diff --git a/Tests/ParcelEngineTests/WorkspaceTransactionTests.swift b/Tests/ParcelEngineTests/WorkspaceTransactionTests.swift index ded57cd1..2e5124c6 100644 --- a/Tests/ParcelEngineTests/WorkspaceTransactionTests.swift +++ b/Tests/ParcelEngineTests/WorkspaceTransactionTests.swift @@ -8,7 +8,8 @@ import Testing @MainActor struct WorkspaceTransactionTests { @Test(arguments: [ - "login", "highlight", "width", "motion", "mouse", "hover", "accessibility", "privacy", "shortcuts", + "login", "highlight", "width", "motion", "mouse", "swap", "stack", "hover", "accessibility", "privacy", + "shortcuts", ]) func configurationOnlyEditDoesNotScheduleLayout(field: String) async throws { let harness = try EngineHarness() @@ -25,6 +26,8 @@ struct WorkspaceTransactionTests { case "width": config.motion.highlightWidth = 5 case "motion": config.motion.enabled.toggle() case "mouse": config.mouse.enabled.toggle() + case "swap": config.mouse.swapModifiers = .control + case "stack": config.mouse.stackModifiers = .shift case "hover": config.hoverBar.enabled.toggle() case "accessibility": config.accessibility.announceLayoutChanges.toggle() case "privacy": config.focusModes.noPeekLevel = 0.3 @@ -41,6 +44,23 @@ struct WorkspaceTransactionTests { await harness.engine.stop() } + @Test func idleMouseCancellationDoesNotScheduleLayout() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + let before = harness.engine.snapshot + let passes = harness.engine.layoutPassCount + let scheduled = harness.scheduler.scheduledCount + let writes = harness.world.allWrites.count + harness.engine.cancelMouseGesture() + #expect(harness.engine.snapshot == before) + #expect(harness.engine.layoutPassCount == passes) + #expect(harness.scheduler.scheduledCount == scheduled) + #expect(harness.world.allWrites.count == writes) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + @Test(arguments: [false, true]) func acceptsEngineClampedReadback(grid: Bool) async throws { let harness = try EngineHarness() -- knotmirror 0.0.1 From 2946f947b64c38188a949d7695c513b9ac6bade1 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 14:40:43 -0400 Subject: [PATCH 17/22] Align merged memory fixtures Populated memory fixtures now require the storage branch's 32-byte title salt. The blocker test must account for the destination directory it creates and verify neither fixture is removed. The notice test pinned obsolete generic copy; check the detailed recovery message with a deterministic error instead. Signed-off-by: Vincent Taverna --- Tests/ParcelAppTests/HighlightNoticeTests.swift | 8 ++++++-- .../ConfigurationMergeRegressionTests.swift | 5 +++-- Tests/ParcelPlatformTests/WorkspaceStateStoreTests.swift | 4 +++- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/Tests/ParcelAppTests/HighlightNoticeTests.swift b/Tests/ParcelAppTests/HighlightNoticeTests.swift index 86bad21e..de51d794 100644 --- a/Tests/ParcelAppTests/HighlightNoticeTests.swift +++ b/Tests/ParcelAppTests/HighlightNoticeTests.swift @@ -1,3 +1,4 @@ +import Foundation import ParcelEngine import Testing @@ -13,7 +14,8 @@ struct HighlightNoticeTests { #expect(notices.visible.count == 2) #expect( notices.visible.contains( - "Layout memory needs attention. Inspect or reset remembered layouts in Settings.")) + "Layout memory needs attention: Fixture notice failure. Review Layout settings; forgetting preserves unreadable files." + )) notices.clear(.workspaceMemory) #expect(notices.visible.count == 1) #expect(notices.counts[.highlights] == 1) @@ -33,4 +35,6 @@ struct HighlightNoticeTests { } } -private struct NoticeFailure: Error {} +private struct NoticeFailure: LocalizedError { + var errorDescription: String? { "Fixture notice failure" } +} diff --git a/Tests/ParcelEngineTests/ConfigurationMergeRegressionTests.swift b/Tests/ParcelEngineTests/ConfigurationMergeRegressionTests.swift index 77299cbc..84440b2f 100644 --- a/Tests/ParcelEngineTests/ConfigurationMergeRegressionTests.swift +++ b/Tests/ParcelEngineTests/ConfigurationMergeRegressionTests.swift @@ -31,7 +31,7 @@ struct ConfigurationMergeRegressionTests { try harness.scheduler.runReady() try harness.finishMotion() let before = harness.engine.snapshot - let memory = try WorkspaceMemory.capture(before.state) + let memory = try WorkspaceMemory.capture(before.state, titleSalt: Data(repeating: 7, count: 32)) harness.engine.pendingRestorationMemory = memory let passes = harness.engine.layoutPassCount let scheduled = harness.scheduler.scheduledCount @@ -58,7 +58,8 @@ struct ConfigurationMergeRegressionTests { try harness.add([3, 4], workspace: second) try harness.finishMotion() let before = harness.engine.snapshot.state - harness.engine.pendingRestorationMemory = try WorkspaceMemory.capture(before) + harness.engine.pendingRestorationMemory = try WorkspaceMemory.capture( + before, titleSalt: Data(repeating: 7, count: 32)) let passes = harness.engine.layoutPassCount var configuration = harness.engine.configuration var values = configuration.layout.global diff --git a/Tests/ParcelPlatformTests/WorkspaceStateStoreTests.swift b/Tests/ParcelPlatformTests/WorkspaceStateStoreTests.swift index 133a5e65..984adc44 100644 --- a/Tests/ParcelPlatformTests/WorkspaceStateStoreTests.swift +++ b/Tests/ParcelPlatformTests/WorkspaceStateStoreTests.swift @@ -590,13 +590,15 @@ import Testing #expect(throws: (any Error).self) { try blocked.save(memory()) } #expect(throws: (any Error).self) { try blocked.reset() } #expect(try String(contentsOf: blocker, encoding: .utf8) == "existing") + #expect(try FileManager.default.contentsOfDirectory(atPath: directory.path) == ["blocker"]) let destination = directory.appendingPathComponent("destination") try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: false) let directoryStore = WorkspaceStateStore(fileURL: destination) #expect(throws: (any Error).self) { try directoryStore.load() } #expect(throws: (any Error).self) { try directoryStore.save(memory()) } #expect(throws: (any Error).self) { try directoryStore.reset() } - #expect(try FileManager.default.contentsOfDirectory(atPath: directory.path) == ["blocker"]) + #expect(Set(try FileManager.default.contentsOfDirectory(atPath: directory.path)) == ["blocker", "destination"]) + #expect(try FileManager.default.contentsOfDirectory(atPath: destination.path).isEmpty) } @Test func symlinkStoreAndLockAreRejectedWithoutFollowingTheirTargets() throws { -- knotmirror 0.0.1 From 08e10c98bc6c38ab2ec69be5530b390db14b5433 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 14:40:55 -0400 Subject: [PATCH 18/22] Warn consistently for unknown settings Underscore spellings are unknown keys, not aliases. Like every other unknown setting, they warn while retaining valid configuration. Replace the older rejection expectations with canonical-only equivalence, located warnings, unchanged aliases, and preserved Settings source. Canonical validation errors still reject edits; align the schema and docs with that policy. Signed-off-by: Vincent Taverna --- Sources/ParcelConfig/ConfigJSONSchema.swift | 2 +- Sources/ParcelConfig/ConfigValidator.swift | 30 ++--- .../ParcelConfig.docc/ParcelConfig.md | 4 +- .../ParcelUI/ParcelUI.docc/ControlCenter.md | 2 +- .../CommandReviewRegressionTests.swift | 48 ++++++-- .../ConfigValidationTests.swift | 50 ++++++-- .../DashedConfigurationKeysTests.swift | 113 ++++++++++++------ .../MemoryConfigurationTests.swift | 29 ++++- .../HighlightSettingsTests.swift | 96 +++++++++++---- Tests/ParcelUITests/SettingsTests.swift | 32 +++-- docs/parcel.schema.json | 2 +- 11 files changed, 293 insertions(+), 115 deletions(-) diff --git a/Sources/ParcelConfig/ConfigJSONSchema.swift b/Sources/ParcelConfig/ConfigJSONSchema.swift index 25bf9d36..0542fd4d 100644 --- a/Sources/ParcelConfig/ConfigJSONSchema.swift +++ b/Sources/ParcelConfig/ConfigJSONSchema.swift @@ -180,7 +180,7 @@ public enum ConfigJSONSchema { "$id": .string(publishedURL), "title": .string("Parcel configuration, version 1"), "$comment": .string( - "This schema describes parsed TOML. Unknown settings are accepted with warnings by ConfigValidator, except recognized underscore spellings, which reject the configuration. " + "This schema describes parsed TOML. Unknown settings, including underscore spellings, are ignored with warnings by ConfigValidator; only dashed setting names are recognized. " + "ConfigValidator also checks the parcel-modifiers, parcel-key-chord, and parcel-mouse-modifiers formats, " + "nonempty and distinct resolved mouse modifier sets (including inherited defaults), " + "ICU expressions in parcel-title-regex, case-insensitive duplicate display UUIDs, " diff --git a/Sources/ParcelConfig/ConfigValidator.swift b/Sources/ParcelConfig/ConfigValidator.swift index 8f68c2f7..088dd251 100644 --- a/Sources/ParcelConfig/ConfigValidator.swift +++ b/Sources/ParcelConfig/ConfigValidator.swift @@ -856,24 +856,24 @@ extension Validation { guard let node = values[key] else { continue } let qualified = path.isEmpty ? key : "\(path).\(key)" let dashedKey = key.replacingOccurrences(of: "_", with: "-") + let suggestedKey: String? if dashedKey != key, allowed.contains(dashedKey) { - let suggestion = path.isEmpty ? dashedKey : "\(path).\(dashedKey)" - keyFailure( - node, - String( - localized: "Unknown key “\(qualified)”. Did you mean “\(suggestion)”?", - table: "Schema", bundle: .module - )) - continue + suggestedKey = dashedKey + } else { + let closest = allowed.sorted { + let lhs = Self.editDistance(key, $0) + let rhs = Self.editDistance(key, $1) + return lhs == rhs ? $0 < $1 : lhs < rhs + }.first + if let closest, Self.editDistance(key, closest) <= (key.count < 3 ? 1 : 2) { + suggestedKey = closest + } else { + suggestedKey = nil + } } - let closest = allowed.sorted { - let lhs = Self.editDistance(key, $0) - let rhs = Self.editDistance(key, $1) - return lhs == rhs ? $0 < $1 : lhs < rhs - }.first let message: String - if let closest, Self.editDistance(key, closest) <= (key.count < 3 ? 1 : 2) { - let suggestion = path.isEmpty ? closest : "\(path).\(closest)" + if let suggestedKey { + let suggestion = path.isEmpty ? suggestedKey : "\(path).\(suggestedKey)" message = String( localized: "Unknown key “\(qualified)”. Did you mean “\(suggestion)”?", table: "Schema", bundle: .module diff --git a/Sources/ParcelConfig/ParcelConfig.docc/ParcelConfig.md b/Sources/ParcelConfig/ParcelConfig.docc/ParcelConfig.md index dbcb9d9e..6d56dc66 100644 --- a/Sources/ParcelConfig/ParcelConfig.docc/ParcelConfig.md +++ b/Sources/ParcelConfig/ParcelConfig.docc/ParcelConfig.md @@ -180,8 +180,8 @@ use `startWatching(debounceInterval:)` for debounced filesystem updates. Call Invalid reads keep the last good configuration. Unknown keys warn; wrong types, bad ranges, unsupported versions, and conflicting shortcuts reject the edit. -Setting names use dashes. Underscore spellings reject the configuration rather -than silently leaving those preferences at their defaults. +Setting names use dashes. Underscore spellings are unknown keys: they warn with +a dashed-key suggestion and leave that preference unchanged. They are not aliases. ## Editor schema and strings diff --git a/Sources/ParcelUI/ParcelUI.docc/ControlCenter.md b/Sources/ParcelUI/ParcelUI.docc/ControlCenter.md index b7542418..c21748ab 100644 --- a/Sources/ParcelUI/ParcelUI.docc/ControlCenter.md +++ b/Sources/ParcelUI/ParcelUI.docc/ControlCenter.md @@ -8,7 +8,7 @@ The setup tour checks shortcuts and macOS window settings, offers open at login, Highlights use `motion.highlight = "none" | "active" | "all" | "glow"` and `motion.highlight-width = 2…6`. An explicit highlight style takes precedence over the legacy `focus-border` switch. Content is cut out of the highlight layer, and accessibility settings disable translucent glow. -Multiword motion keys use dashes: `focus-border`, `menu-bar-icon`, `drop-hints`, `experimental-dimming`, and `highlight-width`. Underscore spellings remain readable as deprecated aliases with a warning. If both spellings are present, the dashed key wins, but both values must be valid. Settings writes dashed keys and preserves existing aliases and comments. +Multiword motion keys use dashes: `focus-border`, `menu-bar-icon`, `drop-hints`, `experimental-dimming`, and `highlight-width`. Underscore spellings are unknown keys, not aliases: they warn and never change preferences. Settings writes dashed keys while preserving unknown settings and comments. When window controls supply their own Hover Focus item, leave `LayoutSnapshot.hoverFocus` nil to avoid duplicate switches. diff --git a/Tests/ParcelConfigTests/CommandReviewRegressionTests.swift b/Tests/ParcelConfigTests/CommandReviewRegressionTests.swift index b64fbe78..111222cd 100644 --- a/Tests/ParcelConfigTests/CommandReviewRegressionTests.swift +++ b/Tests/ParcelConfigTests/CommandReviewRegressionTests.swift @@ -49,7 +49,7 @@ struct ConfigCommandReviewRegressionTests { @Test(arguments: [ ("portrait_layout", "portrait-layout", "tree"), ("when_full", "when-full", "float"), ]) - func obsoleteLayoutKeysRejectWithSourceLocations( + func obsoleteLayoutKeysWarnWithSourceLocationsAndPreserveInheritance( oldKey: String, currentKey: String, oldValue: String ) throws { let id = try #require(UUID(uuidString: "A1B2C3D4-1234-5678-9ABC-0123456789AB")) @@ -58,12 +58,19 @@ struct ConfigCommandReviewRegressionTests { perDisplay ? "[layout]\ndefault = 'side'\nportrait-layout = 'columns'\nwindow-cap = 0\n" : "" let path = perDisplay ? "layout.displays.\"\(id.uuidString)\"" : "layout" + let baseline = ConfigValidator.validate(try TOMLDocument(parsing: "\(prefix)[\(path)]\n")) + #expect(baseline.diagnostics.isEmpty) + let expected = try #require(baseline.configuration) let document = try TOMLDocument(parsing: "\(prefix)[\(path)]\n \(oldKey) = '\(oldValue)'") let result = ConfigValidator.validate(document) - #expect(result.configuration == nil) + let configuration = try #require(result.configuration) + #expect(configuration == expected) + #expect(configuration.layout.values(for: id) == configuration.layout.global) #expect(result.diagnostics.count == 1) let diagnostic = try #require(result.diagnostics.first) - #expect(diagnostic.severity == .error) + #expect(diagnostic.severity == .warning) + let keyPath = perDisplay ? ["layout", "displays", id.uuidString, oldKey] : ["layout", oldKey] + #expect(diagnostic.location == document.node(forKey: keyPath)?.keyRange?.start) #expect(diagnostic.location.line == (perDisplay ? 6 : 2)) #expect(diagnostic.location.column == 3) #expect(diagnostic.message.contains("Unknown key “\(path).\(oldKey)”")) @@ -72,17 +79,38 @@ struct ConfigCommandReviewRegressionTests { } @Test(arguments: [("portrait_layout", "tree"), ("when_full", "float")], [false, true]) - func obsoleteKeysRejectAlongsideExplicitDashedKeys(obsoleteKey: (String, String), obsoleteFirst: Bool) throws { + func obsoleteKeysWarnWithoutOverridingExplicitDashedKeys(obsoleteKey: (String, String), obsoleteFirst: Bool) throws + { let (oldKey, oldValue) = obsoleteKey let id = try #require(UUID(uuidString: "A1B2C3D4-1234-5678-9ABC-0123456789AB")) - for path in ["layout", "layout.displays.\"\(id.uuidString)\""] { + for perDisplay in [false, true] { + let path = perDisplay ? "layout.displays.\"\(id.uuidString)\"" : "layout" let current = "default = 'side'\nportrait-layout = 'columns'\nwindow-cap = 100\nwhen-full = 'stack'" - let obsolete = "\(oldKey) = '\(oldValue)'" - let source = "[\(path)]\n" + (obsoleteFirst ? "\(obsolete)\n\(current)" : "\(current)\n\(obsolete)") - let result = ConfigValidator.validate(try TOMLDocument(parsing: source)) - #expect(result.configuration == nil) + let prefix = "[general]\nprefix = 'fn'\n[\(path)]\n" + let baseline = ConfigValidator.validate(try TOMLDocument(parsing: prefix + current)) + #expect(baseline.diagnostics.isEmpty) + let expected = try #require(baseline.configuration) + let obsolete = " \(oldKey) = '\(oldValue)'" + let source = prefix + (obsoleteFirst ? "\(obsolete)\n\(current)" : "\(current)\n\(obsolete)") + let document = try TOMLDocument(parsing: source) + let result = ConfigValidator.validate(document) + let configuration = try #require(result.configuration) + #expect(configuration == expected) + #expect(configuration.general.prefix == .fn) + #expect( + configuration.layout.values(for: id) + == LayoutValues(defaultLayout: .side, portraitLayout: .columns, windowCap: 100, whenFull: .stack)) + #expect(configuration.layout.global == (perDisplay ? LayoutValues() : configuration.layout.values(for: id))) #expect(result.diagnostics.count == 1) - #expect(result.diagnostics.first?.severity == .error) + let diagnostic = try #require(result.diagnostics.first) + #expect(diagnostic.severity == .warning) + let keyPath = perDisplay ? ["layout", "displays", id.uuidString, oldKey] : ["layout", oldKey] + #expect(diagnostic.location == document.node(forKey: keyPath)?.keyRange?.start) + #expect(diagnostic.location.column == 3) + #expect(diagnostic.message.contains("Unknown key “\(path).\(oldKey)”")) + #expect( + diagnostic.message.contains("Did you mean “\(path).\(oldKey.replacingOccurrences(of: "_", with: "-"))”") + ) } } diff --git a/Tests/ParcelConfigTests/ConfigValidationTests.swift b/Tests/ParcelConfigTests/ConfigValidationTests.swift index 7a6ad28a..9e83d19f 100644 --- a/Tests/ParcelConfigTests/ConfigValidationTests.swift +++ b/Tests/ParcelConfigTests/ConfigValidationTests.swift @@ -1054,14 +1054,20 @@ extension ConfigValidationTests { #expect(result.diagnostics.first?.severity == .warning) } - @Test func obsoleteKeyUsesKeyRangeAndRejectsConfiguration() throws { - let document = try TOMLDocument(parsing: "[general]\n launch_at_login = true") + @Test func obsoleteKeyWarnsAtKeyRangeAndRetainsConfiguration() throws { + let document = try TOMLDocument(parsing: "[general]\nprefix = 'fn'\n launch_at_login = true") let result = ConfigValidator.validate(document) - #expect(result.configuration == nil) + #expect(result.configuration == (try configuration("[general]\nprefix = 'fn'"))) + #expect(result.configuration?.general.launchAtLogin == false) + #expect(result.configuration?.general.prefix == .fn) + #expect(result.diagnostics.count == 1) let diagnostic = try #require(result.diagnostics.first) - #expect(diagnostic.severity == .error) + #expect(diagnostic.severity == .warning) #expect(diagnostic.location == document.root["general"]?["launch_at_login"]?.keyRange?.start) + #expect(diagnostic.location.line == 3) #expect(diagnostic.location.column == 3) + #expect(diagnostic.message.contains("Unknown key “general.launch_at_login”")) + #expect(diagnostic.message.contains("Did you mean “general.launch-at-login”")) } @Test func nearbyUnknownKeyGetsSuggestion() throws { @@ -1070,11 +1076,39 @@ extension ConfigValidationTests { #expect(result.diagnostics.first?.message.contains("Did you mean") == true) } - @Test func underscoreSpellingRejectsWithDashedKeySuggestion() throws { - let result = try validate("[layout]\nwindow_cap = 2") + @Test func underscoreSpellingWarnsWithDashedKeySuggestion() throws { + let document = try TOMLDocument(parsing: "[layout]\nratio = 0.6\nwindow_cap = 2") + let result = ConfigValidator.validate(document) + #expect(result.configuration == (try configuration("[layout]\nratio = 0.6"))) + #expect(result.configuration?.layout.global.windowCap == 3) + #expect(result.configuration?.layout.global.ratio == 0.6) + #expect(result.diagnostics.count == 1) + let diagnostic = try #require(result.diagnostics.first) + #expect(diagnostic.severity == .warning) + #expect(diagnostic.location == document.root["layout"]?["window_cap"]?.keyRange?.start) + #expect(diagnostic.location.line == 3) + #expect(diagnostic.location.column == 1) + #expect(diagnostic.message.contains("Unknown key “layout.window_cap”")) + #expect(diagnostic.message.contains("Did you mean “layout.window-cap”")) + } + + @Test(arguments: [false, true]) + func underscoreWarningsDoNotHideInvalidCanonicalValues(obsoleteFirst: Bool) throws { + let obsolete = " window_cap = 2" + let canonical = " window-cap = '2'" + let source = "[layout]\n" + (obsoleteFirst ? obsolete + "\n" + canonical : canonical + "\n" + obsolete) + let document = try TOMLDocument(parsing: source) + let result = ConfigValidator.validate(document) #expect(result.configuration == nil) - #expect(result.diagnostics.first?.severity == .error) - #expect(result.diagnostics.first?.message.contains("layout.window-cap") == true) + #expect(result.diagnostics.count == 2) + #expect(result.diagnostics.map(\.severity) == (obsoleteFirst ? [.warning, .error] : [.error, .warning])) + let warning = try #require(result.diagnostics.first { $0.severity == .warning }) + #expect(warning.location == document.root["layout"]?["window_cap"]?.keyRange?.start) + #expect(warning.message.contains("Did you mean “layout.window-cap”")) + let error = try #require(result.diagnostics.first { $0.severity == .error }) + #expect(error.location == document.root["layout"]?["window-cap"]?.range.start) + #expect(error.message.contains("layout.window-cap")) + #expect(error.message.contains("whole number")) } @Test func transposedLettersGetSuggestion() throws { diff --git a/Tests/ParcelConfigTests/DashedConfigurationKeysTests.swift b/Tests/ParcelConfigTests/DashedConfigurationKeysTests.swift index 264c794e..16e5ad7c 100644 --- a/Tests/ParcelConfigTests/DashedConfigurationKeysTests.swift +++ b/Tests/ParcelConfigTests/DashedConfigurationKeysTests.swift @@ -7,56 +7,91 @@ import Testing let table: String let key: String let value: String + let alternateValue: String } private static let settings = [ - Setting(table: "general", key: "launch-at-login", value: "true"), - Setting(table: "layout", key: "portrait-layout", value: "'columns'"), - Setting(table: "layout", key: "window-cap", value: "2"), - Setting(table: "layout", key: "when-full", value: "'float'"), - Setting(table: "memory", key: "restore-windows", value: "false"), - Setting(table: "motion", key: "focus-border", value: "false"), - Setting(table: "motion", key: "drop-hints", value: "false"), - Setting(table: "motion", key: "experimental-dimming", value: "true"), - Setting(table: "motion", key: "menu-bar-icon", value: "'logo'"), - Setting(table: "motion", key: "highlight-width", value: "5.5"), - Setting(table: "focus-modes", key: "no-peek-level", value: "0.7"), - Setting(table: "focus-modes", key: "no-peek-blur", value: "false"), - Setting(table: "focus-modes", key: "clean-space-color", value: "'stone'"), - Setting(table: "mouse", key: "swap-modifiers", value: "'ctrl'"), - Setting(table: "mouse", key: "stack-modifiers", value: "'shift'"), - Setting(table: "accessibility", key: "announce-layout-changes", value: "true"), - Setting(table: "keybindings", key: "focus-left", value: "false"), + Setting(table: "general", key: "launch-at-login", value: "true", alternateValue: "false"), + Setting(table: "layout", key: "portrait-layout", value: "'columns'", alternateValue: "'tree'"), + Setting(table: "layout", key: "window-cap", value: "2", alternateValue: "100"), + Setting(table: "layout", key: "when-full", value: "'float'", alternateValue: "'stack'"), + Setting(table: "memory", key: "restore-windows", value: "false", alternateValue: "true"), + Setting(table: "motion", key: "focus-border", value: "false", alternateValue: "true"), + Setting(table: "motion", key: "drop-hints", value: "false", alternateValue: "true"), + Setting(table: "motion", key: "experimental-dimming", value: "true", alternateValue: "false"), + Setting(table: "motion", key: "menu-bar-icon", value: "'logo'", alternateValue: "'minimap'"), + Setting(table: "motion", key: "highlight-width", value: "5.5", alternateValue: "2"), + Setting(table: "focus-modes", key: "no-peek-level", value: "0.7", alternateValue: "0.2"), + Setting(table: "focus-modes", key: "no-peek-blur", value: "false", alternateValue: "true"), + Setting(table: "focus-modes", key: "clean-space-color", value: "'stone'", alternateValue: "'mist'"), + Setting(table: "mouse", key: "swap-modifiers", value: "'ctrl'", alternateValue: "'shift'"), + Setting(table: "mouse", key: "stack-modifiers", value: "'shift'", alternateValue: "'ctrl'"), + Setting(table: "accessibility", key: "announce-layout-changes", value: "true", alternateValue: "false"), + Setting(table: "keybindings", key: "focus-left", value: "false", alternateValue: "'cmd-f20'"), ] @Test(arguments: settings, [0, 1, 2]) - private func obsoleteKeysRejectEvenBesideValidDashedKeys(setting: Setting, order: Int) throws { + private func obsoleteKeysWarnAndNeverOverrideDashedKeys(setting: Setting, order: Int) throws { let obsoleteKey = setting.key.replacingOccurrences(of: "-", with: "_") - let obsolete = " \(obsoleteKey) = \(setting.value)" let canonical = "\(setting.key) = \(setting.value)" - let assignments = order == 0 ? obsolete : order == 1 ? obsolete + "\n" + canonical : canonical + "\n" + obsolete - let document = try TOMLDocument(parsing: "[\(setting.table)]\n" + assignments) - let result = ConfigValidator.validate(document) - #expect(result.configuration == nil) - #expect(result.diagnostics.count == 1) - let diagnostic = try #require(result.diagnostics.first) - #expect(diagnostic.severity == .error) - #expect(diagnostic.location == document.root[setting.table]?[obsoleteKey]?.keyRange?.start) - #expect(diagnostic.message.contains("\(setting.table).\(obsoleteKey)")) - #expect(diagnostic.message.contains("\(setting.table).\(setting.key)")) + let prefix = "version = 1\n[hover-bar]\nenabled = false\n[\(setting.table)]\n" + let baseline = ConfigValidator.validate(try TOMLDocument(parsing: prefix + (order == 0 ? "" : canonical))) + #expect(baseline.diagnostics.isEmpty) + let expected = try #require(baseline.configuration) + for ignoredValue in [order == 0 ? setting.value : setting.alternateValue, "[]"] { + let obsolete = " \(obsoleteKey) = \(ignoredValue)" + let assignments = + order == 0 ? obsolete : order == 1 ? obsolete + "\n" + canonical : canonical + "\n" + obsolete + let source = prefix + assignments + let document = try TOMLDocument(parsing: source) + let result = ConfigValidator.validate(document) + #expect(try #require(result.configuration) == expected) + #expect(result.configuration?.hoverBar.enabled == false) + #expect(result.diagnostics.count == 1) + let diagnostic = try #require(result.diagnostics.first) + #expect(diagnostic.severity == .warning) + #expect(diagnostic.location == document.root[setting.table]?[obsoleteKey]?.keyRange?.start) + #expect(diagnostic.location.column == 3) + #expect(diagnostic.message.contains("Unknown key “\(setting.table).\(obsoleteKey)”")) + #expect(diagnostic.message.contains("Did you mean “\(setting.table).\(setting.key)”")) + #expect(document.render() == source) + } } - @Test(arguments: ["focus-modes", "hover-bar", "float-rules"]) - func obsoleteRootKeysRejectRatherThanIgnoringPreferences(key: String) throws { + @Test( + arguments: [ + ("focus-modes", "{ no-peek-level = 0.7 }", "{ no-peek-level = 0.2 }"), + ("hover-bar", "{ enabled = false }", "{ enabled = true }"), + ("float-rules", "[{ bundle-id = 'com.example.app' }]", "[{ role = 'AXDialog' }]"), + ], [0, 1, 2]) + func obsoleteRootKeysWarnAndNeverOverrideDashedKeys(setting: (String, String, String), order: Int) throws { + let (key, value, alternateValue) = setting let obsoleteKey = key.replacingOccurrences(of: "-", with: "_") - let document = try TOMLDocument(parsing: " \(obsoleteKey) = {}") - let result = ConfigValidator.validate(document) - #expect(result.configuration == nil) - #expect(result.diagnostics.count == 1) - let diagnostic = try #require(result.diagnostics.first) - #expect(diagnostic.severity == .error) - #expect(diagnostic.location == document.root[obsoleteKey]?.keyRange?.start) - #expect(diagnostic.message.contains("“\(key)”")) + let canonical = "\(key) = \(value)" + let otherPreferences = "\n[general]\nprefix = 'fn'\n[layout]\nratio = 0.6\n" + let baseline = ConfigValidator.validate( + try TOMLDocument(parsing: (order == 0 ? "" : canonical) + otherPreferences)) + #expect(baseline.diagnostics.isEmpty) + let expected = try #require(baseline.configuration) + for ignoredValue in [order == 0 ? value : alternateValue, "true"] { + let obsolete = " \(obsoleteKey) = \(ignoredValue)" + let assignments = + order == 0 ? obsolete : order == 1 ? obsolete + "\n" + canonical : canonical + "\n" + obsolete + let source = assignments + otherPreferences + let document = try TOMLDocument(parsing: source) + let result = ConfigValidator.validate(document) + #expect(try #require(result.configuration) == expected) + #expect(result.configuration?.general.prefix == .fn) + #expect(result.configuration?.layout.global.ratio == 0.6) + #expect(result.diagnostics.count == 1) + let diagnostic = try #require(result.diagnostics.first) + #expect(diagnostic.severity == .warning) + #expect(diagnostic.location == document.root[obsoleteKey]?.keyRange?.start) + #expect(diagnostic.location.column == 3) + #expect(diagnostic.message.contains("Unknown key “\(obsoleteKey)”")) + #expect(diagnostic.message.contains("Did you mean “\(key)”")) + #expect(document.render() == source) + } } @Test func dashedPreferencesRoundTripThroughDocumentEdits() throws { diff --git a/Tests/ParcelConfigTests/MemoryConfigurationTests.swift b/Tests/ParcelConfigTests/MemoryConfigurationTests.swift index ea329558..63ae11d6 100644 --- a/Tests/ParcelConfigTests/MemoryConfigurationTests.swift +++ b/Tests/ParcelConfigTests/MemoryConfigurationTests.swift @@ -29,18 +29,35 @@ struct MemoryConfigurationTests { @Test func unknownMemoryKeyIsVisible() throws { let result = ConfigValidator.validate(try TOMLDocument(parsing: "[memory]\nrestore-window = false\n")) + #expect(result.configuration == .defaults) #expect(result.diagnostics.count == 1) - #expect(result.diagnostics.first?.severity == .warning) + let diagnostic = try #require(result.diagnostics.first) + #expect(diagnostic.severity == .warning) + #expect(diagnostic.location.line == 2) + #expect(diagnostic.location.column == 1) + #expect(diagnostic.message.contains("Unknown key “memory.restore-window”")) + #expect(diagnostic.message.contains("Did you mean “memory.restore-windows”")) } - @Test func underscoreSpellingIsUnknownAndDoesNotChangeRestoration() throws { - let result = ConfigValidator.validate(try TOMLDocument(parsing: "[memory]\nrestore_windows = false\n")) + @Test(arguments: ["false", "'false'", "[]"]) + func underscoreSpellingIsUnknownAndDoesNotChangeRestoration(value: String) throws { + let source = "[general]\nprefix = 'fn'\n[memory]\nenabled = false\n" + let baseline = ConfigValidator.validate(try TOMLDocument(parsing: source)) + #expect(baseline.diagnostics.isEmpty) + let expected = try #require(baseline.configuration) + let document = try TOMLDocument(parsing: source + " restore_windows = \(value)\n") + let result = ConfigValidator.validate(document) let diagnostic = try #require(result.diagnostics.first) #expect(result.diagnostics.count == 1) #expect(diagnostic.severity == .warning) - #expect(diagnostic.location.line == 2) - #expect(diagnostic.message.contains("restore_windows")) - #expect(result.configuration?.memory.restoreWindows == true) + #expect(diagnostic.location == document.root["memory"]?["restore_windows"]?.keyRange?.start) + #expect(diagnostic.location.line == 5) + #expect(diagnostic.location.column == 3) + #expect(diagnostic.message.contains("Unknown key “memory.restore_windows”")) + #expect(diagnostic.message.contains("Did you mean “memory.restore-windows”")) + #expect(try #require(result.configuration) == expected) + #expect(result.configuration?.memory == MemoryConfiguration(enabled: false, restoreWindows: true)) + #expect(result.configuration?.general.prefix == .fn) } @Test func schemaMatchesMemoryDefaults() throws { diff --git a/Tests/ParcelUITests/HighlightSettingsTests.swift b/Tests/ParcelUITests/HighlightSettingsTests.swift index f8f41e58..7b64c492 100644 --- a/Tests/ParcelUITests/HighlightSettingsTests.swift +++ b/Tests/ParcelUITests/HighlightSettingsTests.swift @@ -79,29 +79,83 @@ import Testing } } - @Test(arguments: [ - "focus_border = true", - "menu_bar_icon = 'logo'", - "highlight_width = 4", - "drop_hints = true", - "experimental_dimming = false", - "focus-border = false\nfocus_border = 'true'", - "menu-bar-icon = 'logo'\nmenu_bar_icon = 'invalid'", - "highlight-width = 4\nhighlight_width = 99", - "drop-hints = true\ndrop_hints = 'false'", - "experimental-dimming = false\nexperimental_dimming = 'true'", - ]) - func underscoreMotionKeysBlockSaves(assignments: String) async throws { - let source = "[motion]\n" + assignments + "\n" - try await withModel(source: source) { model, file in - #expect(model.error != nil) - #expect(model.diagnostics.filter { $0.severity == .error }.count == 1) - #expect(model.diagnostics.allSatisfy { $0.severity == .error }) - await #expect(throws: SettingsFailure.self) { + @Test( + arguments: [ + ("focus_border", "false", "true", "'true'"), + ("menu_bar_icon", "'logo'", "'minimap'", "'invalid'"), + ("highlight_width", "4", "6", "99"), + ("drop_hints", "false", "true", "'false'"), + ("experimental_dimming", "true", "false", "'true'"), + ], [0, 1, 2]) + func underscoreMotionKeysWarnAndPreserveSourceThroughSaves(setting: (String, String, String, String), order: Int) + async throws + { + let (obsoleteKey, canonicalValue, alternateValue, invalidValue) = setting + let key = obsoleteKey.replacingOccurrences(of: "_", with: "-") + let prefix = "# Keep this\r\n[general]\r\nprefix = 'fn'\r\n[layout]\r\nratio = 0.6\r\n[motion]\r\n" + let canonical = "\(key) = \(canonicalValue) # canonical\r\n" + let canonicalSource = prefix + (order == 0 ? "" : canonical) + let baseline = ConfigValidator.validate(try TOMLDocument(parsing: canonicalSource)) + #expect(baseline.diagnostics.isEmpty) + let expected = try #require(baseline.configuration) + for ignoredValue in [order == 0 ? canonicalValue : alternateValue, invalidValue] { + let obsolete = " \(obsoleteKey) = \(ignoredValue) # obsolete\r\n" + let assignments = order == 0 ? obsolete : order == 1 ? obsolete + canonical : canonical + obsolete + let source = prefix + assignments + let document = try TOMLDocument(parsing: source) + let validation = ConfigValidator.validate(document) + #expect(try #require(validation.configuration) == expected) + #expect(try SettingsDocumentEditor.validate(document) == expected) + try await withModel(source: source) { model, file in + #expect(model.error == nil) + #expect(model.configuration == expected) + #expect(model.diagnostics == validation.diagnostics) + #expect(model.diagnostics.count == 1) + let diagnostic = try #require(model.diagnostics.first) + #expect(diagnostic.severity == .warning) + #expect(diagnostic.location == document.root["motion"]?[obsoleteKey]?.keyRange?.start) + #expect(diagnostic.location.column == 3) + #expect(diagnostic.message.contains("Unknown key “motion.\(obsoleteKey)”")) + #expect(diagnostic.message.contains("Did you mean “motion.\(key)”")) + let loaded = await model.store.snapshot + #expect(loaded.loadState == .loaded) + #expect(loaded.activeSource == .file(file)) + #expect(loaded.activeConfiguration == expected) + #expect(loaded.lastGoodDocument?.source == source) + try await model.setValue(.float(5), for: .motion(.highlightWidth)) + var expectedDocument = try TOMLDocument(parsing: canonicalSource) + try expectedDocument.setValue(.float(5), forKey: ["motion", "highlight-width"]) + let expectedAfterSave = try SettingsDocumentEditor.validate(expectedDocument) + #expect(model.error == nil) + #expect(model.configuration == expectedAfterSave) + #expect(model.configuration.motion.highlightWidth == 5) + #expect(model.configuration.general.prefix == .fn) + #expect(model.configuration.layout.global.ratio == 0.6) + let saved = try String(contentsOf: file, encoding: .utf8) + var expectedSource = document + try expectedSource.setValue(.float(5), forKey: ["motion", "highlight-width"]) + #expect(saved == expectedSource.render()) + #expect(saved.hasPrefix(prefix)) + #expect(saved.contains(obsolete)) + if order != 0, key != "highlight-width" { #expect(saved.contains(canonical)) } + let savedDocument = try TOMLDocument(parsing: saved) + #expect( + savedDocument.root["motion"]?[obsoleteKey]?.value == document.root["motion"]?[obsoleteKey]?.value) + #expect(savedDocument.root["motion"]?["highlight-width"]?.value == .float(5)) + let savedValidation = ConfigValidator.validate(savedDocument) + #expect(savedValidation.configuration == expectedAfterSave) + #expect(model.diagnostics == savedValidation.diagnostics) + #expect(model.diagnostics.count == 1) + #expect(model.diagnostics.first?.severity == .warning) + #expect( + model.diagnostics.first?.location == savedDocument.root["motion"]?[obsoleteKey]?.keyRange?.start) + let snapshot = await model.store.snapshot + #expect(snapshot.loadState == .loaded) + #expect(snapshot.activeSource == .file(file)) + #expect(snapshot.activeConfiguration == expectedAfterSave) + #expect(snapshot.lastGoodDocument?.source == saved) } - let saved = try String(contentsOf: file, encoding: .utf8) - #expect(saved == source) } } diff --git a/Tests/ParcelUITests/SettingsTests.swift b/Tests/ParcelUITests/SettingsTests.swift index 7a25002b..4bf240de 100644 --- a/Tests/ParcelUITests/SettingsTests.swift +++ b/Tests/ParcelUITests/SettingsTests.swift @@ -40,22 +40,32 @@ struct SettingsTests { } @Test(arguments: [ - "[memory]\nrestore_windows = true\n", + "[memory]\nrestore_windows = false\n", "[mouse]\nswap_modifiers = 'ctrl'\n", "[mouse]\nstack_modifiers = 'ctrl-shift'\n", - "[focus_modes]\nno-peek-level = 0.5\n", - "[focus-modes]\nno_peek_level = 0.5\n", - "[focus-modes]\nno_peek_blur = true\n", + "[focus_modes]\nno-peek-level = 0.7\n", + "[focus-modes]\nno_peek_level = 0.7\n", + "[focus-modes]\nno_peek_blur = false\n", "[focus-modes]\nclean_space_color = 'mist'\n", ]) - func underscoreKeysBlockUnrelatedEdits(source: String) async throws { - try await withSettings(source: source) { model, file async throws in - #expect(model.error != nil) - #expect(model.diagnostics.contains { $0.severity == .error }) - await #expect(throws: SettingsFailure.self) { - try await model.setValue(.float(0.6), for: .layout(.ratio)) - } + func underscoreKeysWarnWithoutApplyingAliasesOrBlockingUnrelatedEdits(source: String) async throws { + try await withSettings(source: source) { model, file in + #expect(model.error == nil) + #expect(!model.diagnostics.isEmpty) + #expect(model.diagnostics.allSatisfy { $0.severity == .warning }) + #expect(model.configuration == .defaults) #expect(try file.read() == source) + + try await model.setValue(.float(0.6), for: .layout(.ratio)) + var expected = ParcelConfiguration.defaults + expected.layout.global.ratio = 0.6 + #expect(model.configuration == expected) + #expect(model.error == nil) + #expect(!model.diagnostics.isEmpty) + #expect(model.diagnostics.allSatisfy { $0.severity == .warning }) + let saved = try file.read() + #expect(saved.contains(source)) + #expect(try SettingsDocumentEditor.validate(TOMLDocument(parsing: saved)) == expected) } } diff --git a/docs/parcel.schema.json b/docs/parcel.schema.json index a1aeb927..733aa3c2 100644 --- a/docs/parcel.schema.json +++ b/docs/parcel.schema.json @@ -1,5 +1,5 @@ { - "$comment" : "This schema describes parsed TOML. Unknown settings are accepted with warnings by ConfigValidator, except recognized underscore spellings, which reject the configuration. ConfigValidator also checks the parcel-modifiers, parcel-key-chord, and parcel-mouse-modifiers formats, nonempty and distinct resolved mouse modifier sets (including inherited defaults), ICU expressions in parcel-title-regex, case-insensitive duplicate display UUIDs, named mode targets and reserved names, and duplicate resolved shortcuts, including inherited defaults. Display overrides have no fixed defaults: omitted fields inherit the global layout.", + "$comment" : "This schema describes parsed TOML. Unknown settings, including underscore spellings, are ignored with warnings by ConfigValidator; only dashed setting names are recognized. ConfigValidator also checks the parcel-modifiers, parcel-key-chord, and parcel-mouse-modifiers formats, nonempty and distinct resolved mouse modifier sets (including inherited defaults), ICU expressions in parcel-title-regex, case-insensitive duplicate display UUIDs, named mode targets and reserved names, and duplicate resolved shortcuts, including inherited defaults. Display overrides have no fixed defaults: omitted fields inherit the global layout.", "$id" : "https://tangled.org/vinnymac.dev/parcel/raw/main/docs/parcel.schema.json", "$schema" : "https://json-schema.org/draft/2020-12/schema", "additionalProperties" : true, -- knotmirror 0.0.1 From 17684f7a867acd2936fdc553b271ae971e3f1a98 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 14:56:22 -0400 Subject: [PATCH 19/22] Track merged fixture waits and integration repairs --- Benchmarks/MEASUREMENT.md | 7 +++++++ Benchmarks/idle-waits.json | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Benchmarks/MEASUREMENT.md b/Benchmarks/MEASUREMENT.md index 9051cd8f..c387028f 100644 --- a/Benchmarks/MEASUREMENT.md +++ b/Benchmarks/MEASUREMENT.md @@ -29,6 +29,13 @@ New optimization proofs are reporting-only until their owning packages land. - Custom Instruments presets require genuine GUI exports. Default custom-template recording fails clearly; explicit installed presets are labelled non-equivalent. - No Screen Recording, compositor pixel validation, or SIP-dependent call was added. +- Final integration reused the existing menu repair commits `d9762ba`, `6d8cade`, + and `96ecdd3`: idle mouse cancellation guard, current memory salts/notices/blocker + fixtures, and consistent warnings for unknown config keys. Those changes were + required to make the merged main test suite pass, not new measurement designs. +- Smoke mode bounds the long motion soak to 30 ticks and yields between workload + groups. Full release measurements still use 10,000 ticks; proof metrics say which + ran. This prevents benchmark work from monopolizing UI tests' main actor. ## Validation and measured evidence diff --git a/Benchmarks/idle-waits.json b/Benchmarks/idle-waits.json index 595933e1..d8d76daf 100644 --- a/Benchmarks/idle-waits.json +++ b/Benchmarks/idle-waits.json @@ -1,7 +1,7 @@ [ {"path":"ParcelApp/AppFixtureMouseInput.swift","count":4,"why":"Harness-only gesture pacing and release safety; ends with the gesture."}, {"path":"ParcelApp/AppIPCHandler.swift","count":2,"why":"Harness-only key and mouse release delays; end with input."}, - {"path":"ParcelApp/AppTourIntegration.swift","count":1,"why":"Explicit tour tidy confirmation; bounded deadline."}, + {"path":"ParcelApp/NativeAppRuntime.swift","count":2,"why":"Fixture-only tour click pacing and completion confirmation; bounded five-second deadline."}, {"path":"ParcelConfig/ConfigFileWatcher.swift","count":1,"why":"File-event debounce; no wait until a file event arrives."}, {"path":"ParcelConfig/ConfigStore.swift","count":1,"why":"Injected file-event debounce; cancels on watcher stop."}, {"path":"ParcelEngine/EngineSpaces.swift","count":1,"why":"Explicit Space command waits for writes; bounded 750 ms."}, -- knotmirror 0.0.1 From d59236e66fc769af32e778bdf355a15d7dc302ec Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 15:19:02 -0400 Subject: [PATCH 20/22] Drain native benchmark observations through main dispatch --- .../HotPathBenchmarkTests.swift | 9 +++++++++ .../HotPathNativeFixtures.swift | 11 ++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift b/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift index e1b54cd8..c9d0fbaa 100644 --- a/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift +++ b/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift @@ -103,6 +103,15 @@ extension AppKitTestSuite { #expect(chips.panels.allSatisfy { !$0.isVisible }) } + @Test func nativeObservationGateServicesQueuedMainDispatchWork() async throws { + let fixture = HotPathNativeFixture(count: 10) + defer { fixture.stop() } + let target = WindowID(rawValue: 1) + DispatchQueue.main.async { fixture.state.focusedWindow = target } + try await fixture.drain { fixture.state.focusedWindow == target } + #expect(fixture.state.focusedWindow == target) + } + @Test func smokeSoakUsesABoundedTickCountAndReportsActualWork() throws { #expect(HotPathBenchmarks.soakTicks(full: true) == 10000) #expect(HotPathBenchmarks.soakTicks(full: false) == 30) diff --git a/Tests/ParcelPerformanceTests/HotPathNativeFixtures.swift b/Tests/ParcelPerformanceTests/HotPathNativeFixtures.swift index 73723e91..ed717c62 100644 --- a/Tests/ParcelPerformanceTests/HotPathNativeFixtures.swift +++ b/Tests/ParcelPerformanceTests/HotPathNativeFixtures.swift @@ -197,15 +197,20 @@ final class HotPathNativeFixture { backend.resetCounts() failure = nil } - func drain(until predicate: @MainActor () -> Bool) async throws { + func drain(label: String = #function, until predicate: @MainActor () -> Bool) async throws { let deadline = ContinuousClock.now.advanced(by: .seconds(3)) repeat { scheduler.runReady() - await Task.yield() + // A yield alone can resume before the dispatch callbacks that publish observations. + await withCheckedContinuation { (continuation: CheckedContinuation) in + DispatchQueue.main.async { continuation.resume() } + } if let failure { throw failure } if predicate() { return } } while ContinuousClock.now < deadline - throw BenchmarkFailure.measurement("native workload did not reach expected observation") + throw BenchmarkFailure.measurement( + "native \(label) did not reach expected observation; windows=\(state.windows.count), events=\(events.count), pending=\(scheduler.pendingCount)" + ) } func focus() async throws -> BenchmarkObservation { -- knotmirror 0.0.1 From aac74a25bc7cbb5b41d8362a05e34e47bb6b12e6 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 15:24:43 -0400 Subject: [PATCH 21/22] Keep progressing native workloads separate from stalls --- .../HotPathBenchmarkTests.swift | 12 +++++++++ .../HotPathNativeFixtures.swift | 26 +++++++++++++++++-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift b/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift index c9d0fbaa..fe2fb022 100644 --- a/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift +++ b/Tests/ParcelPerformanceTests/HotPathBenchmarkTests.swift @@ -103,6 +103,18 @@ extension AppKitTestSuite { #expect(chips.panels.allSatisfy { !$0.isVisible }) } + @Test func nativeDrainDistinguishesProgressFromAStallAndKeepsAnOverallBound() { + let start = ContinuousClock.now + var deadline = NativeDrainDeadline(now: start) + deadline.record(progress: 0, now: start) + #expect(!deadline.expired(at: start.advanced(by: .seconds(2)))) + deadline.record(progress: 451, now: start.advanced(by: .milliseconds(2900))) + #expect(!deadline.expired(at: start.advanced(by: .milliseconds(3100)))) + #expect(deadline.expired(at: start.advanced(by: .milliseconds(5900)))) + deadline.record(progress: 500, now: start.advanced(by: .milliseconds(29900))) + #expect(deadline.expired(at: start.advanced(by: .seconds(30)))) + } + @Test func nativeObservationGateServicesQueuedMainDispatchWork() async throws { let fixture = HotPathNativeFixture(count: 10) defer { fixture.stop() } diff --git a/Tests/ParcelPerformanceTests/HotPathNativeFixtures.swift b/Tests/ParcelPerformanceTests/HotPathNativeFixtures.swift index ed717c62..eeef79b3 100644 --- a/Tests/ParcelPerformanceTests/HotPathNativeFixtures.swift +++ b/Tests/ParcelPerformanceTests/HotPathNativeFixtures.swift @@ -144,6 +144,26 @@ final class HotPathNativeBackend: NativeEngineBackend { } } +struct NativeDrainDeadline { + private let maximum: ContinuousClock.Instant + private var stalled: ContinuousClock.Instant + private var progress = -1 + + init(now: ContinuousClock.Instant) { + maximum = now.advanced(by: .seconds(30)) + stalled = now.advanced(by: .seconds(3)) + } + + mutating func record(progress value: Int, now: ContinuousClock.Instant) { + if value != progress { + progress = value + stalled = now.advanced(by: .seconds(3)) + } + } + + func expired(at now: ContinuousClock.Instant) -> Bool { now >= maximum || now >= stalled } +} + @MainActor final class HotPathNativeFixture { let model: HotPathStateFixture @@ -198,7 +218,7 @@ final class HotPathNativeFixture { failure = nil } func drain(label: String = #function, until predicate: @MainActor () -> Bool) async throws { - let deadline = ContinuousClock.now.advanced(by: .seconds(3)) + var deadline = NativeDrainDeadline(now: .now) repeat { scheduler.runReady() // A yield alone can resume before the dispatch callbacks that publish observations. @@ -207,7 +227,9 @@ final class HotPathNativeFixture { } if let failure { throw failure } if predicate() { return } - } while ContinuousClock.now < deadline + let reads = backend.apps.values.reduce(0) { $0 + $1.frameReads + $1.windowReads } + deadline.record(progress: events.count + reads + backend.windowListReads + backend.spaceReads, now: .now) + } while !deadline.expired(at: .now) throw BenchmarkFailure.measurement( "native \(label) did not reach expected observation; windows=\(state.windows.count), events=\(events.count), pending=\(scheduler.pendingCount)" ) -- knotmirror 0.0.1 From b6e13881360c3417ac9444f00a76debe5ec0c48f Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 15:49:46 -0400 Subject: [PATCH 22/22] Finish validated measurement integration --- Benchmarks/MEASUREMENT.md | 24 +++++++++++++++--------- Scripts/bundle.sh | 1 - Scripts/tests/packaging.sh | 1 + 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/Benchmarks/MEASUREMENT.md b/Benchmarks/MEASUREMENT.md index c387028f..d54b102a 100644 --- a/Benchmarks/MEASUREMENT.md +++ b/Benchmarks/MEASUREMENT.md @@ -39,8 +39,8 @@ New optimization proofs are reporting-only until their owning packages land. ## Validation and measured evidence -Debug and release production builds passed. Both parallel and non-parallel runs passed **2,660 tests -in 255 suites**; all **18 shell regression suites** passed. Strict formatting and +Debug and release production builds passed. Both parallel and non-parallel final runs passed **2,808 tests +in 268 suites**; all **18 shell regression suites** passed. Strict formatting and name checks passed. Direct Swift Testing bundle loading and xunit output were verified with the selected Xcode helper (2 safe fixture timestamp tests). @@ -61,8 +61,8 @@ catalog has **84 executable new headless cases**, plus **53 external/deferred entries** (137 total). Pending code fixes remain reporting-only. The full release report contains **128 cases**, with verified `selfcounts` and no zero placeholders. -The post-integration `layout-diff/bsp/50` frame-copy probe measured **447,472 → 578,081 -instructions/op (+29.19%)** and was correctly rejected by the +3% gate. Its +The final `layout-diff/bsp/50` frame-copy probe measured **448,382 → 579,052 +instructions/op (+29.14%)** and was correctly rejected by the +3% gate. Its checksum stayed identical. Evidence: `build/bench-regression-proof.json`. Live preflight stopped before Accessibility probing because release packaging @@ -71,8 +71,14 @@ fragment is required`). No replacement URL or grant was invented. Smoothness, idle, soak and leak budgets therefore remain live-unverified. Optional standalone `footprint` category exports are also not implemented. -The interleaved A/B measurements precede integration from main. After integrating -layout-memory review fixes, both builds and both unit modes passed (**2,729 tests -in 256 suites**), and the 128-case release report and regression probe passed. -Static gates passed with no warnings. Later main updates are integrated and the -build/unit gates repeated before handoff. No host-independent baseline is fabricated. +The interleaved A/B measurements precede integration from main. Final validation +includes main `40b50dc` and the listed menu integration repairs: both builds, both +unit modes (**2,808 tests in 268 suites**), the 128-case release report, and the +regression probe passed. Static gates passed with no warnings. Every shell suite +passed; the final bundle-flag regression recheck passed 125 checks. The redundant +Swift 6 `ConciseMagicFile` flag was removed rather than suppressing its diagnostic. + +Native workload waits now service real main-dispatch callbacks, detect three seconds +without progress, and retain a 30-second overall bound. They do not mistake a +progressing 500-event burst on a loaded host for a broken observation path. These +liveness limits are not performance budgets. No host-independent baseline is fabricated. diff --git a/Scripts/bundle.sh b/Scripts/bundle.sh index fa90487d..268876e9 100755 --- a/Scripts/bundle.sh +++ b/Scripts/bundle.sh @@ -60,7 +60,6 @@ build_args=(--build-system swiftbuild -c "$configuration" -Xswiftc -file-prefix-map -Xswiftc "$checkout=." -Xswiftc -debug-prefix-map -Xswiftc "$checkout=." -Xswiftc -file-compilation-dir -Xswiftc . - -Xswiftc -enable-upcoming-feature -Xswiftc ConciseMagicFile -Xcc "-ffile-prefix-map=$checkout=." -Xcc "-fdebug-prefix-map=$checkout=.") # Multiple --arch options silently select the legacy build backend, which cannot build our resource plugin. # SwiftBuild's release default is universal; verify both slices below. diff --git a/Scripts/tests/packaging.sh b/Scripts/tests/packaging.sh index b0be4ff0..76b6a329 100755 --- a/Scripts/tests/packaging.sh +++ b/Scripts/tests/packaging.sh @@ -278,6 +278,7 @@ check Scripts/check-bundle.sh --no-launch "$app" check grep -q -- '--preserve-metadata=entitlements.*Downloader.xpc' "$TEST_CODESIGN_LOG" check grep -q 'build --build-system swiftbuild -c release .*--product ParcelApp E2E= BUNDLE=1' "$TEST_SWIFT_LOG" check fails grep -q -- '--arch' "$TEST_SWIFT_LOG" +check fails grep -q -- 'ConciseMagicFile' "$TEST_SWIFT_LOG" check grep -q 'ParcelApp -verify_arch arm64 x86_64' "$TEST_LIPO_LOG" check grep -q 'prcl -verify_arch arm64 x86_64' "$TEST_LIPO_LOG" check test "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$plist")" = dev.vinnymac.parcel -- knotmirror 0.0.1