import Foundation @main struct SamplingIntervalChecks { @MainActor static func main() async throws { let suite = "kymo-interval-checks-" + UUID().uuidString let defaults = UserDefaults(suiteName: suite)! defer { defaults.removePersistentDomain(forName: suite) } let preferences = SamplingPreferences(defaults: defaults) precondition(preferences.panelMilliseconds == 2000 && preferences.backgroundMilliseconds == 30000 && !preferences.backgroundEnabled) for (input, expected) in [(Int.min, 500), (549, 500), (550, 600), (1501, 1500), (Int.max, 1_800_000)] { preferences.panelMilliseconds = input precondition(preferences.panelMilliseconds == expected) } preferences.backgroundMilliseconds = 1799900 let restored = SamplingPreferences(defaults: defaults) precondition(restored.panelMilliseconds == 1_800_000 && restored.backgroundMilliseconds == 1799900) precondition(restored.backgroundEnabled, "Existing explicit intervals retain background history") restored.backgroundEnabled = false precondition(!SamplingPreferences(defaults: defaults).backgroundEnabled, "Explicit opt-out overrides migration") defaults.set(Double.nan, forKey: "sampling.panelMilliseconds") defaults.set(true, forKey: "sampling.backgroundMilliseconds") let invalid = SamplingPreferences(defaults: defaults) precondition(invalid.panelMilliseconds == 2000 && invalid.backgroundMilliseconds == 30000 && !invalid.backgroundEnabled) preferences.backgroundEnabled = true preferences.panelMilliseconds = 500 preferences.backgroundMilliseconds = 1_800_000 let store = MetricsStore(sampling: preferences) store.setPanelVisible(true) try await until { store.snapshot.processes != nil } precondition(store.effectiveMilliseconds == 500) store.setPanelVisible(false) precondition(store.snapshot.processes == nil && store.effectiveMilliseconds == 1_800_000) try await Task.sleep(for: .milliseconds(200)) let hiddenDate = store.snapshot.date preferences.panelMilliseconds = 700 try await Task.sleep(for: .milliseconds(650)) precondition(store.snapshot.date == hiddenDate && store.snapshot.processes == nil) preferences.backgroundMilliseconds = 500 try await until { store.snapshot.date > hiddenDate } precondition(store.history.samples.last?.breakBefore == false) precondition(store.history.samples.last?.expectedInterval == 0.5) let first = store.snapshot.date try await until { store.snapshot.date > first } precondition(store.snapshot.date.timeIntervalSince(first) >= 0.45) store.togglePause() let paused = store.snapshot.date preferences.panelMilliseconds = 1_800_000 store.setPanelVisible(true) preferences.backgroundMilliseconds = 800 try await Task.sleep(for: .milliseconds(650)) precondition(store.isPaused && store.snapshot.date == paused) store.togglePause() try await until { store.snapshot.date > paused && store.snapshot.processes != nil } precondition(store.effectiveMilliseconds == 1_800_000) precondition(store.history.samples.last?.breakBefore == true) store.togglePause() let probe = DelayedProcessRead() let deferred = SystemSampler(processRead: { probe.read(&$0) }) await deferred.setProcessVisible(true) _ = await deferred.sample() await deferred.setProcessVisible(false) await deferred.setProcessVisible(true) let delivered = ProcessDelivery() _ = await deferred.sample(processUpdate: { _ in Task { await delivered.received() } }) let deadline = ContinuousClock.now.advanced(by: .seconds(4)) while !(await delivered.value) && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(20)) } let didDeliver = await delivered.value precondition(didDeliver, "Reopened process request must complete without another sample") precondition(probe.count >= 2 && probe.peak == 1) await deferred.setProcessVisible(false) let slowRead = DelayedProcessRead(delay: 0.5) let changing = SamplingPreferences(defaults: defaults) changing.panelMilliseconds = 500 changing.backgroundMilliseconds = 1_800_000 let changingStore = MetricsStore(sampling: changing, sampler: SystemSampler(processRead: { slowRead.read(&$0) })) changingStore.setPanelVisible(true) try await until { !changingStore.history.samples.isEmpty } precondition(changingStore.snapshot.processes == nil) let countBeforeChange = changingStore.history.samples.count changing.panelMilliseconds = 1_800_000 try await until { changingStore.snapshot.processes != nil } precondition(changingStore.history.samples.count == countBeforeChange, "Rate changes must preserve in-flight process delivery without an extra quick sample") changingStore.togglePause() let dormantPreferences = SamplingPreferences(defaults: defaults) dormantPreferences.backgroundEnabled = false dormantPreferences.panelMilliseconds = 500 let dormant = MetricsStore(sampling: dormantPreferences) try await Task.sleep(for: .milliseconds(650)) precondition(dormant.history.samples.isEmpty && dormant.snapshot.memory == nil, "Hidden without a consumer must not perform even an initial full sample") dormant.setPanelVisible(true) try await until { dormant.snapshot.processes != nil } dormant.setPanelVisible(false) let hiddenCount = dormant.history.samples.count try await Task.sleep(for: .milliseconds(650)) precondition(dormant.history.samples.count == hiddenCount && dormant.snapshot.processes == nil) dormantPreferences.backgroundEnabled = true dormantPreferences.backgroundMilliseconds = 500 try await until { dormant.history.samples.count > hiddenCount } dormantPreferences.backgroundEnabled = false let disabledCount = dormant.history.samples.count try await Task.sleep(for: .milliseconds(650)) precondition(dormant.history.samples.count == disabledCount) dormant.setPanelVisible(true) try await until { dormant.history.samples.count > disabledCount } precondition(dormant.history.samples.last?.breakBefore == true) dormant.togglePause() print("PASS: defaults, 100ms quantization/clamping, independent persistence, invalid defaults, active/background wake, pause precedence, slow-interval initial processes and history boundary") } @MainActor private static func until(_ predicate: () -> Bool) async throws { let deadline = ContinuousClock.now.advanced(by: .seconds(4)) while !predicate() && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(20)) } precondition(predicate(), "Timed out waiting for schedule update") } } private actor ProcessDelivery { private(set) var value = false func received() { value = true } } private final class DelayedProcessRead: @unchecked Sendable { private let lock = NSLock() private let delay: TimeInterval init(delay: TimeInterval = 0.2) { self.delay = delay } private var active = 0 private var reads = 0 private var maximum = 0 var count: Int { lock.lock(); defer { lock.unlock() }; return reads } var peak: Int { lock.lock(); defer { lock.unlock() }; return maximum } func read(_ monitor: inout ProcessMonitor) -> ProcessSnapshot { lock.lock(); active += 1; reads += 1; maximum = max(maximum, active); lock.unlock() defer { lock.lock(); active -= 1; lock.unlock() } Thread.sleep(forTimeInterval: delay) return monitor.sample() } }