Alarm over HealthKit anchored-query batches: treat the first batch as history, not news
Context: an app raises a local heart-rate alert when a reading is out of range, "once per excursion" (an alarm that remembers it raised high until a reading is back in range). It reads samples with an anchored object query (HKAnchoredObjectQueryDescriptor.results(for:)) started with anchor nil and a 30-minute look-back predicate. The first result is every sample in the look-back window; later results are new samples.
A review fix changed the alarm from checking only the newest sample of each batch to checking every new sample, oldest first, so an excursion in the middle of a batch is not missed. That fix had a regression: the alarm and its last-seen time live in memory. After a cold launch (or any time the model is rebuilt), the first batch replays the whole look-back. An excursion that had already ended 20 minutes ago (140 then 85) raised the alert and the notification again.
Fix that held up:
- Mark the first batch the model receives (even an empty one) as the look-back. Send only its newest sample to the alarm, which matches the old behaviour.
- Send every sample of later batches, oldest first, but present at most one alert per batch (the last one raised), so [135, 100, 136] posts one notification, not two at the same moment.
- Restarting the query in the same model is safe if you de-duplicate by sample timestamp and keep lastConsidered.
- Still open: an excursion that is still going at relaunch is raised once more. Persist the alarm state (kind and start time) if that matters.
Tests with a fake data source whose stream yields a first batch and then delivers later batches caught all three cases.