// What wakes the reconciler. // // The pure diff has its own suite (`AlarmReconcilerTests`); this one is about // the shell around it, and specifically about the two things the 4e review // found wrong with it. // // The previous hook watched the whole query cache and reconciled on any // `"updated"` / `"added"`, so an alarm that ARRIVED — by // sync, from a tool, from another device — reached the operating system at // once. The first cut of this model reconciled only after a write made on the // Alarms screen, which left every other path waiting for the next foreground. // And when a request arrived mid-pass it was DROPPED, which that hook could // afford because its cache subscription would fire again; nothing re-fires // here. import CottonKit import Foundation import XCTest @testable import CottonUI /// Counts `read.alarms` and answers an empty list, which is a legitimate answer /// (the person has no alarms) rather than a refusal. private actor CountingCore: CottonCalling { private var reads = 0 /// How long a read takes. Zero everywhere but the mid-pass case, which /// needs a pass that is genuinely still in flight when the next request /// arrives — otherwise the case passes whether the request was remembered /// or dropped. private let readTakes: Duration init(readTakes: Duration = .zero) { self.readTakes = readTakes } var readCount: Int { reads } func callRaw(_ method: String, requestJSON: String) async throws -> String { if method == CottonMethod.readAlarms { reads += 1 if readTakes != .zero { try? await Task.sleep(for: readTakes) } } return #"{"ok":true,"data":{"alarms":[]}}"# } func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {} func close() async {} } /// A device that holds nothing and accepts everything. The diff over an empty /// desired set and an empty actual set is empty, so these cases are about WHEN /// a pass runs, not about what it does. private struct SilentDevice: AlarmDevice, AlarmAuthorizer, Sendable { func alarmKitIds() async -> [String]? { [] } func scheduleAlarmKit(_ schedule: AlarmSchedule) async -> Bool { true } func cancelAlarmKit(id: String) async -> Bool { true } func notificationKeys() async -> [String]? { [] } func scheduleFallback(_ schedule: AlarmSchedule, now: Date) async -> Bool { true } func cancelFallback(keys: [String]) async {} func alarmKitAvailable() -> Bool { false } func alarmKitAuthorization() async -> AlarmAuthorization { .unavailable } func requestAlarmKitAuthorization() async -> AlarmAuthorization { .unavailable } func notificationAuthorization() async -> AlarmAuthorization { .authorized } } private struct AlarmsOn: AlarmPreferences, Sendable { var alarmsEnabled: Bool { true } } @MainActor final class AlarmSyncModelTests: XCTestCase { /// A store of its own, so a test never reads or writes the simulator's /// shared defaults — and never sees another case's ledger. private func store(_ name: String) -> AlarmLedgerStore { let defaults = UserDefaults(suiteName: name)! defaults.removePersistentDomain(forName: name) return AlarmLedgerStore(defaults: defaults) } private func model(_ core: CountingCore, _ name: String) -> AlarmSyncModel { AlarmSyncModel( core: core, device: SilentDevice(), authorizer: SilentDevice(), preferences: AlarmsOn(), ledgerStore: store(name) ) } // ── Waiting ────────────────────────────────────────────────────────── // // The debounce is 400 ms, so every case here waits. It waits by POLLING to // a deadline rather than sleeping a fixed span: this suite shares a Mac // with other builds, and a fixed sleep tuned to an idle machine is a test // that goes red when somebody else is compiling. A poll that reaches its // answer early is also faster in the ordinary case. /// Wait until the core has been read `count` times, or the deadline passes. /// Answers the count either way, so the assertion — not this helper — is /// what fails, with its own sentence. private func reads(_ core: CountingCore, reaching count: Int) async -> Int { let deadline = Date().addingTimeInterval(20) while Date() < deadline { let seen = await core.readCount if seen >= count { return seen } try? await Task.sleep(for: .milliseconds(25)) } return await core.readCount } /// Wait long enough that a pass this model was going to run has run. /// /// Used only by the cases asserting that NOTHING happens, where there is no /// event to poll for — and by the ones asserting a burst collapsed to one /// pass, which have to outlast a second debounce to mean anything. Generous /// on purpose: waiting too long here costs seconds, waiting too little /// costs a false green. private func settle() async { try? await Task.sleep(for: .milliseconds(1500)) } func testAnInboundFoldNamingTheAlarmsTableRunsAPass() async { let core = CountingCore() let alarms = model(core, "cotton.tests.alarms.fold") alarms.receive(.data(tables: ["cotton_alarms"], origin: "pull")) let count = await reads(core, reaching: 1) XCTAssertEqual( count, 1, "an alarm arriving by sync must reach the operating system now, not at the next foreground" ) } func testAFoldThatNamesOtherTablesRunsNothing() async { let core = CountingCore() let alarms = model(core, "cotton.tests.alarms.other") alarms.receive(.data(tables: ["cotton_todos", "cotton_notes"], origin: "pull")) await settle() let count = await core.readCount XCTAssertEqual(count, 0, "only the alarms table wakes this model") } func testAnEventThatIsNotAFoldRunsNothing() async { let core = CountingCore() let alarms = model(core, "cotton.tests.alarms.cycle") alarms.receive(.cycle(pushed: 1, pulled: 2, behind: 0, pending: 0, lastPullAt: nil)) await settle() let count = await core.readCount XCTAssertEqual(count, 0) } func testTwoFoldsInOneBurstReconcileOnce() async { // The debounce's whole job: a screen that wrote three rows, or a fold // that carried three, reconciles once. let core = CountingCore() let alarms = model(core, "cotton.tests.alarms.burst") alarms.receive(.data(tables: ["cotton_alarms"], origin: "pull")) alarms.receive(.data(tables: ["cotton_alarms"], origin: "pull")) alarms.receive(.data(tables: ["cotton_alarms"], origin: "write")) _ = await reads(core, reaching: 1) // A second pass, if the debounce failed to collapse the burst, would be // scheduled by now — so outlast it before believing the one. await settle() let count = await core.readCount XCTAssertEqual(count, 1, "three requests inside one debounce window are one pass") } func testARequestThatArrivesDuringAPassIsNotLost() async { // The pass in flight read its desired set BEFORE this write landed, so // dropping the request outright loses it until the next foreground. // // The read is deliberately SLOW here: the fold arrives 400 ms later // (the debounce) while the first pass is still inside its read, which // is the only arrangement that tells "remembered" apart from "dropped". // Dropped would leave this at one read. // Three seconds, not the debounce's four hundred milliseconds: the // second request has to arrive while this read is still in flight, and // the margin is what keeps that true on a Mac that is also compiling. let core = CountingCore(readTakes: .seconds(3)) let alarms = model(core, "cotton.tests.alarms.midpass") let first = Task { await alarms.run() } alarms.receive(.data(tables: ["cotton_alarms"], origin: "write")) await first.value let count = await reads(core, reaching: 2) XCTAssertEqual( count, 2, "the pass that was running could not have seen the row that arrived during it" ) } }