// The phone catches up while the app is in the background. // // Until 11 Oct 2026 nothing synced a phone that was not open: no background // task was registered anywhere, and a 34,000-row mail backfill reached the // phone only while somebody was looking at it. This is the phone's half of the // answer: two tasks iOS runs when it chooses, and one way to spend the time // they are given. // // • REFRESH (`BGAppRefreshTask`) — the short periodic slice, about thirty // seconds, asked for again every time it runs. // • PROCESSING (`BGProcessingTask`) — minutes, when the phone is charging // and has a network: the one that finishes a backfill overnight. // // Both run THE SAME THING: `sync.now { budgetMs }`, the core's time-boxed // slice. A slice stops between pages when its time is gone, and every page it // fetched is already in the file with its cursor — so a slice interrupted at // any point has lost nothing, and thirty of them through a day add up // (`cotton-client/src/sync/time_box.rs`, guarded in `slice_tests.rs`). // // THE HONEST LIMIT, which no code here can move: iOS decides when a task runs // and whether it runs at all — it learns from how the phone is used, and a // phone in Low Power Mode or with Background App Refresh switched off is given // nothing. A phone that is behind is normally level within hours without // being opened; a large backfill may still finish only when it is. // // THE PROCESSING TASK ALSO COMPACTS. After a trim the core owes the copy one // whole compaction (VACUUM, `phone/trim.rs`), which it runs only while the app // is away and only when the time fits the file: a 300 to 550 MB copy needs a // minute or two, more than a trip to the back gives. So once the slices are // level the processing task asks `sync.compact { budgetMs }`, which answers // only when the compaction is done, and iOS saying the time is up stops it // with `sync.compact { stop: true }` (SQLite takes the rewrite back, nothing // is lost) BEFORE the task is ended, never leaving a suspended app halfway // through rewriting its file. // // This file decides nothing about WHAT is behind. It asks the core, and the // core's answer — `behind` — is the only thing that schedules more work. import CottonKit import Foundation /// The two tasks, by the identifiers iOS knows them under. /// /// THE SAME STRINGS as `BGTaskSchedulerPermittedIdentifiers` in `project.yml`: /// iOS refuses to register or to schedule an identifier the Info.plist does /// not permit, and it refuses by raising — `ios-project-spec.test.ts` holds /// the two lists to each other. public enum CatchUpTask: String, CaseIterable, Sendable { case refresh = "com.cottondb.catchup.refresh" case processing = "com.cottondb.catchup.processing" /// The background mode iOS asks of each task. var mode: String { self == .refresh ? "fetch" : "processing" } /// The tasks this app's plist permits and has the mode for: all of them /// in Cotton, none in an app that runs nothing in the background. public static func permitted(_ info: [String: Any] = Bundle.main.infoDictionary ?? [:]) -> [CatchUpTask] { let ids = info["BGTaskSchedulerPermittedIdentifiers"] as? [String] ?? [] let modes = info["UIBackgroundModes"] as? [String] ?? [] return allCases.filter { ids.contains($0.rawValue) && modes.contains($0.mode) } } } /// What one slice came to. public enum SliceOutcome: Equatable, Sendable { /// Nothing more is waiting. case level /// More is waiting. `moved` is whether this slice landed anything: a /// slice that is behind and moved nothing is not catching up, and asking /// it again at once would spend a battery on no row. case behind(moved: Bool) /// The core could not be asked, or refused. The sentence is for the log. case failed(String) } /// Asks iOS for a task. A protocol so the rules below are tested without a /// phone: the simulator has no scheduler at all. public protocol CatchUpScheduling: Sendable { func submit(_ task: CatchUpTask, notBefore: Date?) throws } /// What `sync.now { budgetMs }` answers, as far as a slice reads it. struct SliceAnswer: Decodable, Equatable { let behind: Bool let moved: Bool private enum Keys: String, CodingKey { case behind, pushed, pulled } init(from decoder: any Decoder) throws { let fields = try decoder.container(keyedBy: Keys.self) // A phone with no Mac yet answers the number 0 where a pass answers a // boolean (`ClientController::no_server_yet`); both are read. if let flag = try? fields.decode(Bool.self, forKey: .behind) { behind = flag } else { behind = ((try? fields.decode(Int.self, forKey: .behind)) ?? 0) != 0 } let pushed = (try? fields.decode(Int.self, forKey: .pushed)) ?? 0 let pulled = (try? fields.decode(Int.self, forKey: .pulled)) ?? 0 moved = pushed + pulled > 0 } } struct SliceRequest: Encodable { let budgetMs: Int } /// `sync.compact { budgetMs }` runs the copy's compaction now, or /// `{ stop: true }` stops one running. An absent field is not sent. struct CompactRequest: Encodable { var budgetMs: Int? var stop: Bool? } /// What `sync.compact { budgetMs }` answers, as far as the task reads it: /// whether the copy still owes its compaction, and how long it took when it /// ran (`owed` with no `tookMs`: it was stopped, or the time was too short). struct CompactAnswer: Decodable { let owed: Bool let tookMs: Int? } /// Ends a task ONCE, from whichever of its two ends comes first: the work /// finishing, or iOS saying the time is up. A task ended twice is a crash, /// and one never ended is an app iOS stops trusting with background time. final class TaskEnd: @unchecked Sendable { private let lock = NSLock() private var end: ((Bool) -> Void)? private var isExpired = false init(_ end: @escaping (Bool) -> Void) { self.end = end } var expired: Bool { lock.lock() defer { lock.unlock() } return isExpired } /// iOS said the time is up. Marked at once, so the run sees it at its next /// step, while the task is still being stopped. func markExpired() { lock.lock() isExpired = true lock.unlock() } func finish(_ success: Bool, expired: Bool = false) { lock.lock() let end = self.end self.end = nil if expired { isExpired = true } lock.unlock() end?(success) } } @MainActor public final class BackgroundCatchUp { public static let shared = BackgroundCatchUp() /// What a refresh, and a wake, hands the core. iOS gives such a launch /// about thirty seconds; the slice stops clean inside twenty-five. public nonisolated static let wakeBudgetMs = 25_000 /// How soon the next refresh may run. iOS treats it as "not before" and /// decides the rest; asking for less than this is asking to be ignored. public nonisolated static let refreshEvery: TimeInterval = 15 * 60 /// What the processing task hands the compaction: the most the core takes. /// iOS does not say how long a processing task has, so the limit is its /// expiry handler, which stops the compaction (`expire`). public nonisolated static let compactBudgetMs = 1_800_000 /// Opens the core — or hands back the one the window already opened. Nil /// when it cannot be opened now: a phone not unlocked since it restarted /// cannot read its key, and a slice there is a slice that waits. public typealias Opener = @MainActor @Sendable () async -> (any CottonCalling)? private var opener: Opener? private var scheduler: (any CatchUpScheduling)? /// Whether a processing task is waiting on the copy's compaction now: /// what an expiry must stop before the task is ended. private(set) var compacting = false public init(opener: Opener? = nil, scheduler: (any CatchUpScheduling)? = nil) { self.opener = opener self.scheduler = scheduler } /// The app says how its core is opened. Once, at launch. public func attach(opener: @escaping Opener) { self.opener = opener } public func use(scheduler: any CatchUpScheduling) { self.scheduler = scheduler } /// Work an app does in the same wake, before the slice: Post's round of This phone fetches. Once, at launch. public typealias Extra = @MainActor @Sendable (any CottonCalling) async -> Void private var extras: [Extra] = [] public func also(_ work: @escaping Extra) { extras.append(work) } /// The app's own work for this wake, each in turn; a core that cannot be opened does none. private func runExtras() async { guard !extras.isEmpty, let core = await opener?() else { return } for work in extras { await work(core) } } // ── One slice ──────────────────────────────────────────────────────── /// Ask the core for one time-boxed slice. /// /// NO "a slice is already running" here. A flag set across an `await` stays /// set when iOS freezes the process inside it, and every later wake was /// refused by it. Two slices at once are the core's to order: a second /// joins the pass in flight, and a pass the loop stopped waiting for is /// cut and waited for inside the new slice's budget. public func slice(budgetMs: Int = BackgroundCatchUp.wakeBudgetMs) async -> SliceOutcome { guard let core = await opener?() else { return .failed("the core could not be opened in the background") } do { let answer: SliceAnswer = try await core.call( CottonMethod.syncNow, SliceRequest(budgetMs: budgetMs) ) // Then the reminder pass on what the slice brought: an event added or moved on another device alerts // with Days closed (as Android's background sync runs it). Standalone, on the core this slice opened: a // background launch may have no screen, and so no notifications model. if ReminderApps.keeps { let prefs = try? await CoreNotificationPreferences(core: core).read() if let prefs { _ = await ReminderPass(core: core, centre: SystemReminderCentre()) .run(timeZone: TimeZone.current.identifier, prefs: prefs, permission: await SystemNotificationAuthority().read(), others: nil) } } return answer.behind ? .behind(moved: answer.moved) : .level } catch { return .failed(String(describing: error)) } } // ── What is asked of iOS, and when ─────────────────────────────────── /// The app left the front: ask for both tasks. /// /// BOTH, whether or not this phone knows it is behind — what is behind is /// the Mac's to know and the core's to ask, and a processing task on a /// phone that is level costs one round trip while it charges. public func appWentAway(now: Date = Date()) { submit(.refresh, notBefore: now.addingTimeInterval(Self.refreshEvery)) submit(.processing, notBefore: nil) } /// The refresh task ran — or a wake arrived: one slice. /// /// The next refresh is asked for FIRST. iOS runs a refresh once per /// request, and a slice that is killed must not be the last one. @discardableResult public func runRefresh(now: Date = Date()) async -> Bool { submit(.refresh, notBefore: now.addingTimeInterval(Self.refreshEvery)) await runExtras() switch await slice() { case .level: return true case .behind: // More than thirty seconds' worth: the long task is owed. submit(.processing, notBefore: nil) return true case .failed(let reason): Log.write("catch-up: the refresh slice did not run — \(reason)") return false } } /// The processing task ran: slice after slice until this phone is level, /// a slice moves nothing, or iOS says the time is up. /// /// `expired` is asked BETWEEN slices. A slice in flight when the time /// goes is not waited for — the task is ended by its expiry handler, and /// the slice has lost nothing wherever the process is frozen. /// /// Then, level or moving nothing, the copy's compaction it may owe /// (`compactAway`). A copy that still owes it, its compaction stopped by /// the time running out, asks for the task again. @discardableResult public func runProcessing(expired: @Sendable () -> Bool) async -> Bool { await runExtras() while true { switch await slice() { case .level: if await !compactAway(expired: expired) { submit(.processing, notBefore: nil) } return true case .behind(let moved): if expired() { // Still owed. iOS runs it again when it next can. submit(.processing, notBefore: nil) return moved } if !moved { // Still owed, and asked again whatever the compaction does. _ = await compactAway(expired: expired) submit(.processing, notBefore: nil) return false } case .failed(let reason): Log.write("catch-up: a processing slice did not run — \(reason)") submit(.processing, notBefore: nil) return false } } } /// The processing task from its start to its one end. Once iOS has said /// the time is up, the end is the expiry's (`expire`): it ends the task /// only after the compaction has answered, and as expired. func processingTask(_ end: TaskEnd) async { let success = await runProcessing(expired: { end.expired }) if !end.expired { end.finish(success) } } // ── The compaction ─────────────────────────────────────────────────── /// The copy's one whole compaction, if it owes one: `sync.compact /// { budgetMs }`, answered when it is done. Answers false when the copy /// still owes it (stopped by the time running out, or not asked), so the /// task is asked for again; true when it ran or nothing was owed. private func compactAway(expired: @Sendable () -> Bool) async -> Bool { guard !expired() else { return false } guard let core = await opener?() else { Log.write("catch-up: the copy's compaction was not asked — the core could not be opened") return false } // Asked again after the wait above: an expiry that came meanwhile saw // nothing to stop, and the task may already be ended. guard !expired() else { return false } compacting = true defer { compacting = false } do { let answer: CompactAnswer = try await core.call( CottonMethod.syncCompact, CompactRequest(budgetMs: Self.compactBudgetMs) ) if let took = answer.tookMs { Log.write("catch-up: the copy compacted in the processing task, in \(took) ms") return true } guard answer.owed else { return true } Log.write(expired() ? "catch-up: iOS's time ran out and the copy's compaction stopped; the processing task is asked again" : "catch-up: the copy's compaction did not run; the processing task is asked again") return false } catch { Log.write("catch-up: the copy's compaction was not asked — \(error)") return false } } /// iOS says the processing task's time is up. A compaction it is waiting /// on is stopped FIRST (`sync.compact { stop: true }`; SQLite takes the /// rewrite back) and waited for, and only then is the task ended, once: a /// task ended mid-rewrite is an app suspended holding its file. /// /// The stop is said again until the compaction has answered: a stop that /// reached the core before the compaction began would stop nothing. Two /// seconds at most, then the task is ended whatever is running. func expire(_ end: TaskEnd) async { end.markExpired() var tries = 0 while compacting, tries < 20 { if let core = await opener?() { do { _ = try await core.callJSON(CottonMethod.syncCompact, CompactRequest(stop: true)) if tries == 0 { Log.write("catch-up: iOS's time ran out; the copy's compaction is stopped") } } catch { Log.write("catch-up: the compaction could not be stopped — \(error)") } } tries += 1 if compacting { try? await Task.sleep(nanoseconds: 100_000_000) } } end.finish(false, expired: true) } private func submit(_ task: CatchUpTask, notBefore: Date?) { guard let scheduler else { return } do { try scheduler.submit(task, notBefore: notBefore) } catch { // Background App Refresh is off, or this is a simulator. Said // once per ask and nothing else: the app still syncs when open. Log.write("catch-up: iOS did not take \(task.rawValue) — \(error)") } } } #if os(iOS) && canImport(BackgroundTasks) import BackgroundTasks /// The real scheduler. public struct SystemCatchUpScheduler: CatchUpScheduling { public init() {} public func submit(_ task: CatchUpTask, notBefore: Date?) throws { guard CatchUpTask.permitted().contains(task) else { return } switch task { case .refresh: let request = BGAppRefreshTaskRequest(identifier: task.rawValue) request.earliestBeginDate = notBefore try BGTaskScheduler.shared.submit(request) case .processing: let request = BGProcessingTaskRequest(identifier: task.rawValue) // "When charging and on a network" — the conditions under which // iOS gives minutes rather than seconds, and the ones under which // a backfill costs the person nothing they would notice. request.requiresNetworkConnectivity = true request.requiresExternalPower = true request.earliestBeginDate = notBefore try BGTaskScheduler.shared.submit(request) } } } extension BackgroundCatchUp { /// Tell iOS what runs for each identifier. /// /// **BEFORE `didFinishLaunching` RETURNS, and nowhere else.** iOS raises /// on a handler registered later, and on one registered twice. A launch /// in the background — the app was not running when the task came due — /// passes through the same delegate, which is why this is called there /// and not from a view. public nonisolated static func registerTasks() { // An app that runs nothing in the background (Words, Days: no `fetch` // or `processing` mode, no permitted identifiers, 22 Nov 2026) registers // nothing: iOS may raise on an identifier its plist does not permit. for which in CatchUpTask.permitted() { let taken = BGTaskScheduler.shared.register(forTaskWithIdentifier: which.rawValue, using: nil) { task in let end = TaskEnd { success in task.setTaskCompleted(success: success) } switch which { case .refresh: task.expirationHandler = { end.finish(false, expired: true) } Task { @MainActor in end.finish(await BackgroundCatchUp.shared.runRefresh()) } case .processing: // The compaction it may be waiting on is stopped before // the task is ended (`expire`). task.expirationHandler = { Task { @MainActor in await BackgroundCatchUp.shared.expire(end) } } Task { @MainActor in await BackgroundCatchUp.shared.processingTask(end) } } } if !taken { // The identifier is not in the Info.plist's permitted list. Log.write("catch-up: iOS did not register \(which.rawValue)") } } } } #endif