Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238import Foundationimport ParcelCoreimport ParcelTestSupportimport Testing
@testable import ParcelEngine@testable import ParcelPlatform
@Suite("Write scheduling benchmarks", .serialized, .tags(.benchmark))@MainActorstruct WriteSchedulingBenchmarks { @Test func motionBatchMainActorOverhead() async throws { let executor = AppThreadExecutor(start: {}, stop: {}) defer { executor.shutdown() } let fixture = PerformanceFixture(count: 50, layout: .grid) @MainActor func run(jobs: Int) async throws -> Int { var checksum = 0 for index in 0..<jobs { let completed = try await withCheckedThrowingContinuation { continuation in executor.submit( run: { continuation.resume(returning: 1) }, cancel: { continuation.resume(throwing: AppThreadFailure.stopped) }) if index == 0 { checksum += reduce(fixture.state, .relayout).0.frames.count } } checksum += completed } return checksum } #expect(try await run(jobs: 1) == 51) try await WriteBenchmarkMeasurement.measureAsync("MotionBatchMainActorOverhead/before") { try await run(jobs: 20) } try await WriteBenchmarkMeasurement.measureAsync("MotionBatchMainActorOverhead/after") { try await run(jobs: 1) } }
#if !PARCEL_BENCH_CORE_ONLY @Test func animationScheduleAlreadyVerified200() throws { let fixture = PerformanceFixture(count: 200, layout: .grid) func run() throws -> BenchmarkObservation { let clock = HotPathClock() let engine = try ParcelEngine( world: HotPathWorld(), clock: clock, scheduler: HotPathScheduler(clock: clock), displayLink: { _ in HotPathEngineLink() }, announcer: HotPathAnnouncer(), log: HotPathLog(), initialState: fixture.state, reduceMotionSource: nil) engine.actualFrames = engine.snapshot.state.frames engine.targets = engine.snapshot.state.frames.mapValues { Rect(x: $0.minX + 1, y: $0.minY, width: $0.size.width, height: $0.size.height) } engine.planFrames() return BenchmarkObservation( checksum: engine.motionPlans.count + 1, proofMetrics: ["motion-plans": Double(engine.motionPlans.count)]) } let baseline = ProcessInfo.processInfo.environment["PARCEL_WRITE_BENCH_BASELINE"] == "1" #expect(try run().proofMetrics["motion-plans"] == (baseline ? 200 : 0)) try WriteBenchmarkMeasurement.measureShared("AnimationSchedule200/confirmed-frame", operation: run) }
@Test func settleReconcileEchoFilter() throws { let fixture = PerformanceFixture(count: 50, layout: .grid) let clock = HotPathClock() let engine = try ParcelEngine( world: HotPathWorld(), clock: clock, scheduler: HotPathScheduler(clock: clock), displayLink: { _ in HotPathEngineLink() }, announcer: HotPathAnnouncer(), log: HotPathLog(), initialState: fixture.state, reduceMotionSource: nil) let window = fixture.ids[0] let actual = try #require(fixture.state.frames[window]) let changed = Rect( x: actual.minX + 20, y: actual.minY, width: actual.size.width, height: actual.size.height) engine.actualFrames[window] = actual engine.rememberEcho(window, frame: actual, transaction: 1, generation: 1) for index in engine.echoes[window, default: []].indices { engine.echoes[window]?[index].completedAt = clock.now } #expect(engine.isEcho(window, frame: changed, origin: .unknown)) #expect(!engine.isEcho(window, frame: changed, origin: .reconciled)) for (name, origin) in [("before", FrameChangeOrigin.unknown), ("after", .reconciled)] { try WriteBenchmarkMeasurement.measureShared("SettleReconcileCost/echo-filter/\(name)") { let filtered = engine.isEcho(window, frame: changed, origin: origin) return BenchmarkObservation( checksum: filtered ? 2 : 1, proofMetrics: ["genuine-drift-discarded": filtered ? 1 : 0]) } } } #endif
@Test func immediateDrainDoesNotExpireDiscoveryDeadlines() { let scheduler = WriteBenchmarkScheduler() var fired: [String] = [] let deadline = scheduler.schedule(after: 1) { fired.append("deadline") } _ = scheduler.schedule(after: 0) { fired.append("turn") } scheduler.run() #expect(fired == ["turn"]) deadline.cancel() scheduler.run() #expect(fired == ["turn"]) #expect(scheduler.pending.isEmpty) }
@Test func settleReconcileCost() async throws { let backend = WriteBenchmarkBackend() let scheduler = WriteBenchmarkScheduler() let world = NativeEngineWorld(backend: backend, scheduler: scheduler) defer { world.stop() } try world.start { event in if case .failure(let failure) = event { Issue.record("Unexpected native benchmark failure: \(failure)") } } @MainActor func drain() async throws { let deadline = ContinuousClock.now.advanced(by: .seconds(5)) repeat { scheduler.run() if !world.hasPendingReconciliation { return } guard ContinuousClock.now < deadline else { throw BenchmarkFailure.measurement("settle reconciliation did not finish") } try Task.checkCancellation() await Task.yield() } while true } try await drain() let apps = Set(backend.apps.keys) try await WriteBenchmarkMeasurement.measureAsync("SettleReconcileCost/before") { let before = backend.apps.values.reduce(0) { $0 + $1.factsReads } world.reconcile(apps) try await drain() return backend.apps.values.reduce(0) { $0 + $1.factsReads } - before + 1 } let before = backend.apps.values.reduce(0) { $0 + $1.factsReads } world.reconcileFrames(apps) try await drain() #expect(backend.apps.values.reduce(0) { $0 + $1.factsReads } == before) try await WriteBenchmarkMeasurement.measureAsync("SettleReconcileCost/after") { world.reconcileFrames(apps) try await drain() return backend.visibleReads } }}
@MainActorprivate final class WriteBenchmarkCancellation: EngineCancellation { let deadline: Double var action: (@MainActor () -> Void)? init(deadline: Double, action: @escaping @MainActor () -> Void) { self.deadline = deadline self.action = action } func cancel() { action = nil }}
@MainActorprivate final class WriteBenchmarkScheduler: EngineScheduler { var pending: [WriteBenchmarkCancellation] = [] func schedule(after delay: Double, _ action: @escaping @MainActor () -> Void) -> any EngineCancellation { let work = WriteBenchmarkCancellation(deadline: max(0, delay), action: action) pending.append(work) return work } func run() { let ready = pending.filter { $0.deadline == 0 && $0.action != nil } pending.removeAll { $0.deadline == 0 || $0.action == nil } for work in ready { work.action?() } }}
@MainActorprivate final class WriteBenchmarkApplication: NativeEngineApplication { let snapshots: [NativeWindowSnapshot] let events: AsyncStream<AppThreadEvent> let continuation: AsyncStream<AppThreadEvent>.Continuation var factsReads = 0 init(_ snapshots: [NativeWindowSnapshot]) { self.snapshots = snapshots let stream = AsyncStream<AppThreadEvent>.makeStream() events = stream.stream continuation = stream.continuation } func windows() async throws -> [NativeWindowSnapshot] { factsReads += snapshots.count return snapshots } func frame(_ window: WindowID) async throws -> Rect { throw AppThreadFailure.windowNotFound(window.rawValue) } func focusedWindow() async throws -> WindowID? { nil } func write(_ frame: Rect, to window: WindowID) async throws -> Rect { throw AppThreadFailure.stopped } func writeFrames(_ frames: [EngineFrameWrite]) async throws -> EngineWriteReceipt { throw AppThreadFailure.stopped } func cancelFrameWrites(_ window: WindowID, throughGeneration: UInt64) async throws {} func finishShutdown() async throws {} func focus(_ window: WindowID) async throws { throw AppThreadFailure.stopped } func raise(_ window: WindowID) async throws { throw AppThreadFailure.stopped } func toggleFullscreen(_ window: WindowID) async throws { throw AppThreadFailure.stopped } func shutdown() { continuation.finish() }}
@MainActorprivate final class WriteBenchmarkBackend: NativeEngineBackend { let display = DisplayID(rawValue: "write-benchmark") let apps: [AppID: WriteBenchmarkApplication] var visibleReads = 0 init() { var applications: [AppID: WriteBenchmarkApplication] = [:] for pid in 1...5 { let app = AppID(pid: Int32(pid), bundleID: "org.example.write\(pid)") applications[app] = WriteBenchmarkApplication( (0..<6).map { index in let id = WindowID(rawValue: UInt32(pid * 10 + index)) return NativeWindowSnapshot( window: ManagedWindow(id: id, app: app), frame: Rect(x: Double(index * 100), y: 0, width: 100, height: 100)) }) } apps = applications } func start(receive: @escaping @MainActor (NativeEngineEvent) -> Void) throws {} func stop() {} func currentDisplays() throws -> [ParcelCore.Display] { [ParcelCore.Display(id: display, frame: Rect(x: 0, y: 0, width: 2000, height: 1000))] } func focusedApplication() -> AppID? { nil } func runningApplications() -> [NativeApplicationInfo] { apps.keys.map { NativeApplicationInfo(id: $0) } } func application(_ app: AppID) throws -> any NativeEngineApplication { guard let application = apps[app] else { throw AppThreadFailure.stopped } return application } func visibleWindows() async throws -> NativeVisibleWindows { visibleReads += 1 let windows = apps.values.flatMap(\.snapshots) return NativeVisibleWindows( frames: Dictionary(uniqueKeysWithValues: windows.map { ($0.window.id, $0.frame) }), owners: Dictionary(uniqueKeysWithValues: windows.map { ($0.window.id, $0.window.app.pid) })) } func currentSpaces(for displays: [DisplayID]) async throws -> NativeSpaceState { NativeSpaceState(spaces: [display: SpaceID(rawValue: 1)], suspended: []) }}