import ParcelCore import ParcelPlatform /// A window identifies the sample, not the app-wide failure being counted. private struct EngineFailureLogKey: Equatable { enum Cause: Equatable { case appUnavailable case accessibility(AXPlatformError) case appThread(AppThreadFailure) case observerRegistration(notification: String, code: Int32) case observerRemoval(notification: String, code: Int32) case windowNotFound case activationRefused case timedOut } let app: AppID let cause: Cause init?(_ failure: EnginePlatformFailure) { switch failure { case .appUnavailable(let app): self.app = app cause = .appUnavailable case .accessibility(let app, _, let error): self.app = app cause = .accessibility(error) case .appThread(let app, let error): self.app = app switch error { case .observerRegistration(let notification, _, let code): cause = .observerRegistration(notification: notification, code: code) case .observerRemoval(let notification, _, let code): cause = .observerRemoval(notification: notification, code: code) case .windowNotFound: cause = .windowNotFound default: cause = .appThread(error) } case .operation(.activationRefused(let app)): self.app = app cause = .activationRefused case .timedOut(let app): self.app = app cause = .timedOut case .operation, .unexpected, .vanished, .permissionLost, .correctiveWriteLimit: return nil } } } @MainActor final class EngineFailureLogAggregation { private struct Entry { let key: EngineFailureLogKey var sample: String var total: UInt64 = 1 var pending: UInt64 = 0 var deadline: Double var lastOccurrence: UInt64 } private let clock: any EngineClock private let scheduler: any EngineScheduler private let interval: Double private let maximumCauses: Int private let output: @MainActor (String) -> Void // Equatable typed causes avoid string identities and stay scoped to apps, not windows. private var entries: [Entry] = [] private var occurrence: UInt64 = 0 private var wake: (any EngineCancellation)? private var wakeDeadline: Double? private var wakeGeneration: UInt64 = 0 init( clock: any EngineClock, scheduler: any EngineScheduler, interval: Double, maximumCauses: Int = 256, output: @escaping @MainActor (String) -> Void ) { precondition(interval.isFinite && interval > 0) precondition(maximumCauses > 0) self.clock = clock self.scheduler = scheduler self.interval = interval self.maximumCauses = maximumCauses self.output = output } func record(_ diagnostic: EngineDiagnostic) { guard case .platform(let failure) = diagnostic, let key = EngineFailureLogKey(failure) else { output(String(describing: diagnostic)) return } let now = clock.now precondition(now.isFinite) let sample = String(describing: diagnostic) occurrence += 1 if let index = entries.firstIndex(where: { $0.key == key }) { entries[index].sample = sample entries[index].total += 1 entries[index].pending += 1 entries[index].lastOccurrence = occurrence if now >= entries[index].deadline { emitPending(at: index, now: now) } } else { if entries.count == maximumCauses, let oldest = entries.indices.min(by: { entries[$0].lastOccurrence < entries[$1].lastOccurrence }) { if entries[oldest].pending > 0 { emitPending(at: oldest, now: now) } entries.remove(at: oldest) } entries.append(Entry(key: key, sample: sample, deadline: now + interval, lastOccurrence: occurrence)) output("\(sample) [count=1 total=1]") } schedulePending() } func forgetFailures(for app: AppID) { let now = clock.now precondition(now.isFinite) for index in entries.indices where entries[index].key.app == app && entries[index].pending > 0 { emitPending(at: index, now: now) } entries.removeAll { $0.key.app == app } schedulePending() } // Totals belong to a retained cause lifetime; summing emitted counts also covers evicted lifetimes. func totalCount(for failure: EnginePlatformFailure) -> UInt64? { guard let key = EngineFailureLogKey(failure) else { return nil } return entries.first(where: { $0.key == key })?.total } func flush() { cancelWake() let now = clock.now precondition(now.isFinite) for index in entries.indices where entries[index].pending > 0 { emitPending(at: index, now: now) } } private func emitPending(at index: Int, now: Double) { let entry = entries[index] entries[index].pending = 0 entries[index].deadline = now + interval output("\(entry.sample) [count=\(entry.pending) total=\(entry.total)]") } private func schedulePending() { let deadline = entries.lazy.filter { $0.pending > 0 }.map(\.deadline).min() guard deadline != wakeDeadline else { return } cancelWake() guard let deadline else { return } wakeDeadline = deadline let generation = wakeGeneration wake = scheduler.schedule(after: max(0, deadline - clock.now)) { [weak self] in guard let self, self.wakeGeneration == generation else { return } self.wake = nil self.wakeDeadline = nil let now = self.clock.now precondition(now.isFinite) for index in self.entries.indices where self.entries[index].pending > 0 && self.entries[index].deadline <= now { self.emitPending(at: index, now: now) } self.schedulePending() } } private func cancelWake() { wakeGeneration += 1 wake?.cancel() wake = nil wakeDeadline = nil } isolated deinit { flush() } }