The bug the Simulator can't see: a Health save that only fails in your pocket
First Stride's phone-only runs reached Apple Health every time, unless the run finished on its own with the phone in a pocket. The Simulator can't reproduce that, so the boss became our test rig. About forty runs later we knew why: since iOS 26.4, HealthKit's final save comes back empty when the app is in the background, and the map goes missing with it.
The audio post ended on a warning: the bugs that hurt never show up in a unit test. You find them by doing the real thing, which is exactly what a simulator won't do for you. This is the longest case we've worked, and it took a lot of running. Most of it was done by the boss.
The reports came from more than one phone, and they all pointed at one state:
- iPhone only, ended early: saved to Apple Health, all stats present.
- iPhone with an Apple Watch: saved, all stats present.
- iPhone only, run plays out to Done on its own: in First Stride's History, missing from Apple Health.
Ending early and finishing naturally call the same save code. The difference isn't logic. It's where the phone is. You end a run early by tapping a button, so the app is on screen. A run that finishes on its own does it in your pocket, with the phone locked.
Suspect one: iOS put us to sleep mid-write
The obvious suspect came first. During a run, First Stride stays awake in the background by playing silence. When the run ends, the silence stops, and iOS is free to suspend the app. Saving a workout to HealthKit is a chain of async steps. If iOS freezes the app halfway through, the write never lands. The phone's direct save had no retry, so the run was simply gone.
The fix followed from the theory, in two layers:
private func savePhoneRunToHealth(_ a: RunAnchor) {
// 1. A persisted "this run still needs saving" record, flushed to disk
// NOW: a kill right after the finish is exactly when it has to survive.
pendingSaves.append(PendingSave(runID: a.runID, start: a.startDate, end: now))
persistPendingSaves()
// 2. Ask iOS for a background-task window so the write can finish.
var bg = UIBackgroundTaskIdentifier.invalid
bg = UIApplication.shared.beginBackgroundTask(withName: "saveRun") {
UIApplication.shared.endBackgroundTask(bg) // expired: iOS reclaimed us
}
health.logRun(start: a.start, end: .now) { ok in
if ok { markSaved(a.runID) } // reconcile will just drop the record
UIApplication.shared.endBackgroundTask(bg)
}
}On every launch and every return to the foreground, a reconcile pass looks for pending records whose run still isn't in Health and writes them from the record. It worked, in the sense that the missing runs started showing up. They just showed up empty.
The runs came back hollow
The rescued runs had the right duration and three blank tiles: no distance, no calories, no pace. The retry was faithfully writing everything it knew, and it didn't know much.
On a phone-only run, distance comes from the live GPS route collector, and the save consumes that collector. Calories and pace are both computed from distance. The pending record held a run ID and two timestamps. By the time a retry ran, the only source of distance was gone, and one missing number blanked three tiles. So the fix snapshots the distance at the finish, before the save consumes it:
struct PendingSave: Codable {
let runID: String; let start: Double; let end: Double
var backfilled = false
/// GPS metres, captured at finish BEFORE logRun consumes the collector.
/// OPTIONAL ON PURPOSE: records already on disk don't have this key.
var distanceMeters: Double? = nil
}That Optional is the most important character in the change. The records are decoded with try?. A new non-optional field would make every record written by the previous build fail to decode, and try? turns that failure into silence. The upgrade would have quietly deleted every save waiting to be rescued.
We considered the case closed. Runs were landing with their stats, a few minutes late and without a map, and the map felt like a detail. But we never found out why the first save failed, and a bug you don't understand tends to come back in another shape.
Enter the boss
The Simulator was no help: it never suspends a backgrounded app. A headless harness ran a workout to a natural finish in the background and saved perfectly, every time. On the Simulator, the path that fails in your pocket doesn't exist.
So we needed a real phone, a real run, and a way to read what happened afterwards. The boss volunteered for the first two. He laced up, we put a build with a trace on his phone, and we sent him out on ten runs.
The trace covers the whole save chain: whether the app was in the background, whether the phone was locked, whether the background task was granted or expired, and each HealthKit stage.
enum SaveLog {
static let log = Logger(subsystem: "com.gravexa.runwalk", category: "healthsave")
static func event(_ message: String) {
log.notice("[save] \(message, privacy: .public)")
}
}
SaveLog.event("direct-save begin appState=\(app.applicationState.rawValue) " +
"protectedData=\(app.isProtectedDataAvailable)")The rule for it is written at the top of the file: state only. Which stage ran, whether it worked, how many GPS points a route had. No distances, calories, coordinates or dates ever reach the log. Debugging a health app never needs the user's numbers, and booleans are enough to tell which link in the chain breaks.
Getting the log off the phone took longer than writing it. log stream --device-name no longer exists on current macOS, and devicectl device sysdiagnose stops on a consent prompt and exits having written nothing. What works is boring: the build also appends every event to a file in the app's own container, and one command copies it over the cable.
xcrun devicectl device copy from --device <id> \
--domain-type appDataContainer --domain-identifier com.gravexa.runwalk \
--source Documents/save-trace.log --destination .The ten runs produced one line that mattered, and one that mattered more because it wasn't there. finishWorkout, HealthKit's final commit, returned no workout. And BACKGROUND TASK EXPIRED never appeared. iOS hadn't suspended anything: the app was awake, inside its background window, when the save came back empty. Suspect one was innocent. The background task is harmless and we kept it, but it was never the missing piece.
The boss negotiates
Ten runs bought one clue, and the clue said we needed a lot more runs. Week 1, Day 1 is 30 minutes long. The boss did the math on twenty more of those and came back with terms: we could have all the runs we wanted, as long as we accelerated time 30x, so he wouldn't have to kill himself running all over town.
He had a point. The tempting version is a fake “Week 10” of tiny intervals, and we didn't do that. The schedule clamps weeks to 1 through 9, and a new week ripples into the 27-workout progress math, the workout picker and graduation, all one mistake away from shipping. Scaling seconds changes no structure at all:
#if DEBUG || SAVE_LAB
private static func debugScaled(_ intervals: [Interval]) -> [Interval] {
let divisor = UserDefaults.standard.integer(forKey: debugTimeScaleKey)
guard divisor > 1 else { return intervals }
return intervals.map { Interval($0.phase, max(1, $0.seconds / divisor)) }
}
#else
private static func debugScaled(_ intervals: [Interval]) -> [Interval] { intervals }
#endifSame intervals, same phases, same week and day, same program length. The SAVE_LAB flag builds a test-only TestFlight build with the 30x switch and the log file, for the boss's phone and never for App Review. A normal build compiles the identity function. It's phone-only by design: the phone and the Watch both derive the schedule from a shared start time, so speeding up just one of them desyncs a two-device run.
Same intervals, same phases, same program. Just less of the boss's afternoon.
Twenty-one for twenty-one
Boss mode turned the investigation into a couch sport. Start a run, lock the phone, wait a minute for the voice to say it's done, unlock, repeat. Apple Health now believes the boss worked through most of the nine-week program in a single day without breaking a sweat, which is technically accurate.
Out of 21 natural finishes with the phone locked, finishWorkout came back with no workout 21 times. The background task never expired once. None of the 21 reached Apple Health until the retry wrote them later, without a map.
This time we'd also fixed the oldest mistake in the file. The original save code read builder.finishWorkout { workout, _ in, and that _ was the error, thrown away. When we finally logged it, it was nil. HealthKit wasn't refusing the workout. It just wasn't answering.
Suspects interviewed and released along the way: iOS suspension, the background task, and the Done screen, which the boss asked about. The save starts at the finish, before Done ever appears.
What the documentation says
Apple documents this exact return. When finishWorkout hands back neither a workout nor an error, the finish succeeded, but "the workout sample is not available because the device is locked." By the book, all 21 runs were saved and just couldn't be shown to us.
They weren't saved. Health had nothing until the retry wrote them. We weren't alone, either: other developers have reported the same thing on Apple's forums since iOS 26.4. Apple's engineers couldn't reproduce it with their own code, and it's still there on iOS 27. On a current iPhone, a plain HKWorkoutBuilder that finishes in the background just doesn't save.
Plan B: borrow the Watch's engine
iOS 26 brought HKWorkoutSession to the iPhone. It's the engine Apple Watch workout apps have always run on, and a running session is how Apple expects a workout app to keep going with the screen locked. So every phone run now starts one, and the save commits through the session's own builder. Same metadata, same distance and energy samples, same route. The only thing that changed is who does the save.
// iOS 26+: every phone run gets a workout session, started in the foreground.
let session = try HKWorkoutSession(healthStore: store, configuration: config)
let builder = session.associatedWorkoutBuilder()
session.prepare()
session.startActivity(with: start)
builder.beginCollection(withStart: start) { _, _ in }
// The GPS route rides on the session's own builder, so finishWorkout owns it.
let routeBuilder = builder.seriesBuilder(for: .workoutRoute()) as? HKWorkoutRouteBuilderfinishWorkout still came back empty: no workout, no error. But this time the workouts were in Apple Health. Every single one.
The maps weren't. The boss had a theory: he hadn't moved, so there was nothing to map. Sadly for him, a phone sitting still in a living room still produces GPS jitter, 63 to 88 points per run, and the trace showed HealthKit had accepted every one of them, locked or not. The route rode on the session's builder exactly as documented, and the workout saved without it anyway. Another developer on Apple's forums hit the same missing route on iPhone, was told the route should just save, and got the same result.
One more clue: one run finished six seconds after the boss unlocked the phone, with the app still in the background, and came back just as empty. So it isn't only the lock. It's the app not being on screen.
The fix: trust, verify, and keep your own map
Three changes, all built on one idea: HealthKit did its job, it just won't tell us.
- Empty isn't failed. From the session, no workout and no error now means unconfirmed. A run that saved doesn't get a "couldn't save" warning.
- Look later, never while locked. The run is looked up in Health by its ID when the phone unlocks or the app opens. Never sooner: Health can't be read while locked, so an early lookup comes back empty, looks like a missing run, and the app would helpfully write a second copy.
- Keep your own copy of the map. At the finish, the app writes the route's points to its own container. If the run turns up in Health without a map, it builds a route from those points and attaches it. The points are deleted once the run is settled, and the run only counts as settled after the map step, so an app killed mid-attach tries again on the next launch.
session.finish(end: end, samples: samples, metadata: meta) { workout, error in
// Background finish on iOS 26.4+: nothing back, no error, saved anyway.
done(workout != nil ? .saved : error == nil ? .unconfirmed : .failed)
}
func reconcilePendingSaves() {
// Health can't be read while locked. An empty answer would look like a
// missing run, and we'd write a duplicate. Wait for the unlock.
guard UIApplication.shared.isProtectedDataAvailable else { return }
for p in pendingSaves {
health.findWorkout(runID: p.runID) { workout in
guard let workout else { return backfillIfOverdue(p) }
health.hasRoute(workout) { hasMap in
let points = hasMap ? [] : RouteStash.load(runID: p.runID)
guard !points.isEmpty else { return settle(p) }
health.attachRoute(points, to: workout) { ok in // a fresh HKWorkoutRouteBuilder
if ok { settle(p) } // otherwise: next launch
}
}
}
}
}Here's one locked finish from each stage, in the trace's own words:
A footnote for completeness: the Watch has a background mode called workout-processing, so we tried declaring it on the iPhone. App Store Connect rejected the upload within about a minute, because it isn't a valid iOS value. Fast feedback, at least.
Where it stands
On iOS 26.4 and later, a phone-only run that finishes in your pocket lands in Apple Health right away, with its duration, distance, calories and pace. The map appears when the phone is unlocked if the app is still running, or the next time the app opens, even if it was swiped away in between. Nobody gets a false alarm. If Apple fixes the regression, the session gets its workout back with its map, the app records it as saved, and the fallback never runs.
Here's what Health held at every stage of the saga:
Complete. The map is attached from the points kept on disk once the phone unlocks.
If you're hitting this
- Since iOS 26.4,
finishWorkoutcalled with the app in the background can return no workout and no error. From a plainHKWorkoutBuilder, nothing is saved. From an iPhoneHKWorkoutSession's builder, the workout is saved without its route. - Treat that empty return as unconfirmed, and find the workout later by an ID you put in its metadata.
- Don't look while
isProtectedDataAvailableis false. You'll find nothing and write a duplicate. - Keep your own copy of the route's
CLLocations, and attach them with a freshHKWorkoutRouteBuilderonce the workout turns up without one. workout-processingis a watchOS-only background mode. App Store Connect rejects it on iOS.- Test on a real phone, locked. The Simulator never suspends.
The lesson
- The Simulator is a different operating system for anything involving the app lifecycle. It never suspends a backgrounded app, so a clean Simulator run proves nothing about a bug that depends on background state.
- Build the way to read the log before you need it. Getting the trace off the phone took longer than writing it.
- A retry has to carry everything the first attempt had, and that includes the map. A recovery path that saves less than the original is the same bug, quieter.
- Log the reason, not just the result. Even when the reason turns out to be
nil, thatnilis the clue. - Trace state, not data. You can debug a health app thoroughly without a single health value in your logs.
- Make the test cheap enough to run twenty-one times. The 30x switch turned a ten-hour experiment into a coffee break. Credit to the boss for refusing to do it the hard way.
The fix that shipped first was right for the wrong reason. Ten real runs told us that. A couch, a locked phone and 30x told us the rest.