// 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.importCottonKitimportFoundation/// 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.publicenumCatchUpTask: 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.publicstaticfunc 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.publicenumSliceOutcome: 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.publicprotocolCatchUpScheduling: Sendable {func submit(_ task: CatchUpTask, notBefore: Date?) throws}/// What `sync.now { budgetMs }` answers, as far as a slice reads it.structSliceAnswer: Decodable, Equatable {let behind: Boollet moved: BoolprivateenumKeys: 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.iflet 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)) ?? 0let pulled = (try? fields.decode(Int.self, forKey: .pulled)) ?? 0 moved = pushed + pulled > 0 }}structSliceRequest: 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.structCompactRequest: 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).structCompactAnswer: Decodable {let owed: Boollet 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.finalclassTaskEnd: @unchecked Sendable {privatelet lock = NSLock()privatevar end: ((Bool) -> Void)?privatevar isExpired = falseinit(_ 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.endself.end = nilif expired { isExpired = true } lock.unlock() end?(success) }}@MainActorpublicfinalclassBackgroundCatchUp {publicstaticlet 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 staticlet 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 staticlet 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 staticlet 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.publictypealiasOpener = @MainActor @Sendable () async -> (any CottonCalling)?privatevar opener: Opener?privatevar 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 = falsepublicinit(opener: Opener? = nil, scheduler: (any CatchUpScheduling)? = nil) {self.opener = openerself.scheduler = scheduler }/// The app says how its core is opened. Once, at launch.publicfunc attach(opener: @escaping Opener) {self.opener = opener }publicfunc 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.publictypealiasExtra = @MainActor @Sendable (any CottonCalling) async -> Voidprivatevar extras: [Extra] = []publicfunc 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.privatefunc 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.publicfunc slice(budgetMs: Int = BackgroundCatchUp.wakeBudgetMs) async -> SliceOutcome {guardlet core = await opener?() else {return .failed("the core could not be opened in the background") }do {let answer: SliceAnswer = tryawait 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.ifReminderApps.keeps {let prefs = try? awaitCoreNotificationPreferences(core: core).read()iflet prefs { _ = awaitReminderPass(core: core, centre: SystemReminderCentre()) .run(timeZone: TimeZone.current.identifier, prefs: prefs, permission: awaitSystemNotificationAuthority().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.publicfunc 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. @discardableResultpublicfunc runRefresh(now: Date = Date()) async -> Bool { submit(.refresh, notBefore: now.addingTimeInterval(Self.refreshEvery))await runExtras()switchawait slice() {case .level:returntruecase .behind:// More than thirty seconds' worth: the long task is owed. submit(.processing, notBefore: nil)returntruecase .failed(let reason):Log.write("catch-up: the refresh slice did not run — \(reason)")returnfalse } }/// 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. @discardableResultpublicfunc runProcessing(expired: @Sendable () -> Bool) async -> Bool {await runExtras()whiletrue {switchawait slice() {case .level:ifawait !compactAway(expired: expired) { submit(.processing, notBefore: nil) }returntruecase .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)returnfalse }case .failed(let reason):Log.write("catch-up: a processing slice did not run — \(reason)") submit(.processing, notBefore: nil)returnfalse } } }/// 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.privatefunc compactAway(expired: @Sendable () -> Bool) async -> Bool {guard !expired() else { returnfalse }guardlet core = await opener?() else {Log.write("catch-up: the copy's compaction was not asked — the core could not be opened")returnfalse }// 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 { returnfalse } compacting = truedefer { compacting = false }do {let answer: CompactAnswer = tryawait core.call(CottonMethod.syncCompact, CompactRequest(budgetMs: Self.compactBudgetMs) )iflet took = answer.tookMs {Log.write("catch-up: the copy compacted in the processing task, in \(took) ms")returntrue }guard answer.owed else { returntrue }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")returnfalse } catch {Log.write("catch-up: the copy's compaction was not asked — \(error)")returnfalse } }/// 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 = 0while compacting, tries < 20 {iflet core = await opener?() {do { _ = tryawait 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 += 1if compacting { try? awaitTask.sleep(nanoseconds: 100_000_000) } } end.finish(false, expired: true) }privatefunc submit(_ task: CatchUpTask, notBefore: Date?) {guardlet 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)importBackgroundTasks/// The real scheduler.publicstructSystemCatchUpScheduler: CatchUpScheduling {publicinit() {}publicfunc submit(_ task: CatchUpTask, notBefore: Date?) throws {guardCatchUpTask.permitted().contains(task) else { return }switch task {case .refresh:let request = BGAppRefreshTaskRequest(identifier: task.rawValue) request.earliestBeginDate = notBeforetry 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 = notBeforetry BGTaskScheduler.shared.submit(request) } }}extensionBackgroundCatchUp {/// 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 staticfunc 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 inCatchUpTask.permitted() {let taken = BGTaskScheduler.shared.register(forTaskWithIdentifier: which.rawValue, using: nil) { task inlet end = TaskEnd { success in task.setTaskCompleted(success: success) }switch which {case .refresh: task.expirationHandler = { end.finish(false, expired: true) }Task { @MainActor in end.finish(awaitBackgroundCatchUp.shared.runRefresh()) }case .processing:// The compaction it may be waiting on is stopped before// the task is ended (`expire`). task.expirationHandler = { Task { @MainActor inawaitBackgroundCatchUp.shared.expire(end) } }Task { @MainActor inawaitBackgroundCatchUp.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