Why CKSyncEngine doesn’t fetch when your app comes back, and how to make it

Published by malhal on

I was testing sync between two simulators with CKSyncEngine. I’d edit a record on one, then on the other I’d deactivate the app and activate it again. The change never arrived. Quitting and relaunching the app fetched it straight away. Calling fetchChanges() myself when the app became active didn’t help either: it returned almost immediately and fetched nothing.

The post CKSyncEngine fetchChanges() does nothing covers a related problem. There, an engine created after the app was already active never fetched on launch. I opened CloudKit in Hopper to find out exactly when the engine fetches by itself, and why fetchChanges() doesn’t. This is what I found, and a debug-only fix.

When the engine fetches by itself

Apart from pushes, the engine fetches on one event: UIApplicationWillEnterForegroundNotification. It starts observing it in its initializer (except in daemons). When the notification arrives, it logs:

<engine> received appForegroundNotificationName notification

Then it checks a private property, lastForegroundTriggeredFetchDate. Decompiled, the check looks like this:

if let last = lastForegroundTriggeredFetchDate,
   Date.now < last + Double.random(in: 55..<77) {
    return    // too soon: no fetch, nothing logged
}
lastForegroundTriggeredFetchDate = .now
// logs "<engine> will perform fetch on application foreground"
try await Task.sleep(for: .seconds(0.5))
// fetches, in an activity named "engine/fetch-on-foreground"

That explains three things:

  1. Deactivating and activating the app isn’t a foreground. Pulling down Control Center or Notification Center, or opening the app switcher and going back, only makes the app inactive and active again. willEnterForeground is only posted when the app comes back from the background. To test the engine’s own fetch, send the app to the background (⇧⌘H in the simulator) and then reopen it.
  2. Foreground fetches are throttled. After one, the engine ignores the notification for a random 55 to 77 seconds. If you switch back and forth while testing, most switches do nothing, and nothing is logged to say so.
  3. A cold launch doesn’t count. iOS doesn’t post willEnterForeground on launch, and the date is only kept in memory, starting as nil. The engine fetches when it starts (as long as it’s created before the app is active; see the lilback.com post), and the first return from the background after that always fetches.

Push notifications are what normally bring changes in while the app is running. They’re much less reliable on simulators, so in testing, the foreground fetch is often all you get.

Why fetchChanges() doesn’t help

lastForegroundTriggeredFetchDate has nothing to do with fetchChanges(). Only the notification handler reads it; otherwise it’s only set to nil in the initializer and destroyed in deinit.

What stops fetchChanges() is a different flag in the engine’s state: needsToFetchDatabaseChanges. The engine only asks the server for database changes (which zones have changed) when that flag is set, and it sets it itself on a push or a foreground fetch. Without it, fetchChanges() only fetches zones the engine already knows have changed, which is usually none, so it returns at once.

CloudKit has a method that sets the flag on request, but it isn’t public:

// CloudKit.CKSyncEngine.setNeedsToFetchChanges() -> ()
// $s8CloudKit12CKSyncEngineC22setNeedsToFetchChangesyyF

It logs <engine> manually setting needsToFetchDatabaseChanges and then calls setNeedsToFetchDatabaseChanges: on the engine’s Objective-C CKSyncEngineState. The symbol is exported, but it’s not in the SDK’s CloudKit.swiftinterface, so it’s SPI: you can’t call it from Swift normally. The Objective-C CKSyncEngine has a matching -setNeedsToFetchChanges, but the Swift CKSyncEngine isn’t an Objective-C class, so there’s no selector to send.

The fix, for debug builds

Look the method up with dlsym and call it on the engine. A Swift method takes self in the same register (x20 on arm64) that a closure takes its captured context in. So a closure made of the method’s address and the engine calls the method on the engine:

#if DEBUG
import CloudKit
import Darwin

extension CKSyncEngine {
    /// Fetches changes now, including asking the server which zones changed, ignoring the engine's own
    /// foreground throttle. For testing only: it calls CloudKit SPI.
    func forceFetchChanges() async throws {
        Self.setNeedsToFetchChanges?(self)
        try await fetchChanges()
    }

    /// CloudKit's SPI `CKSyncEngine.setNeedsToFetchChanges()`, or nil if it's gone.
    private static let setNeedsToFetchChanges: (@Sendable (CKSyncEngine) -> Void)? = {
        let defaultHandle = UnsafeMutableRawPointer(bitPattern: -2)    // RTLD_DEFAULT: every loaded image
        guard let method = dlsym(defaultHandle, "$s8CloudKit12CKSyncEngineC22setNeedsToFetchChangesyyF") else {
            return nil
        }
        return { engine in
            // A Swift method takes self in the register a closure takes its context in.
            let call = unsafeBitCast((method, engine), to: (() -> Void).self)
            call()
        }
    }()
}
#endif

Then call it when the scene becomes active:

.onChange(of: scenePhase) { _, newPhase in
    #if DEBUG
    if newPhase == .active {
        Task {
            try? await syncEngine.forceFetchChanges()
        }
    }
    #endif
}

To check it’s working, filter Console on the CloudKit subsystem. You should see manually setting needsToFetchDatabaseChanges, followed by your delegate’s .willFetchChanges and .fetchedRecordZoneChanges events.

Caveats

  • Keep it out of release builds. It calls a private method by its mangled name. App Review may reject it, and any OS update can rename or remove the method. If the method is gone, dlsym returns nil and you just get a plain fetchChanges(). If its signature changes, the call will probably crash.
  • The bit cast relies on the arm64 Swift calling convention (no pointer authentication on function pointers, which is true for third-party apps and the simulator). I’ve only tried it in the simulator.
  • Release builds should rely on pushes. If you need a fetch on activation in production, the lilback.com post’s approach of keeping your own database change token and calling CKDatabase.databaseChanges(since:) uses only public API.

I’d like setNeedsToFetchChanges(), or a fetch option that asks the server for database changes, to be public API. If you hit this too, a feedback report saying so would help.

Categories: CloudKit