commit 0c23512a95341ce64dbd90ab341e721b1331a311
parent 9cfb22ca72e45815a9476075315da1cc2bc754e2
Author: Michael Camilleri <[email protected]>
Date: Tue, 20 Oct 2026 16:11:13 +0900
End a location search early only on a recent fix
A report could be saved with a location from minutes earlier and
somewhere else. Core Location often opens a search with a cached fix,
and the capture ended as soon as any fix was within 50 metres, whatever
its age. Captures finishing in 0.2 seconds were seen. Holding an
'Always' session since a344a0a keeps cached fixes on hand more often,
which made this more likely.
This commit moves the choice of fix into FixChoice. Only a recent fix —
at most 30 seconds old, or from an update marked stationary — ends the
search early. An older fix is kept as a fallback in case nothing recent
arrives within the budget, and any recent fix beats it, however
accurate. The event log now records how old each capture's fix was, and
whether it had to fall back to an older one.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Notes/Design.md | | | 10 | +++++++--- |
| M | Shared/Capture/ContextCapture.swift | | | 59 | +++++++++++++++++++++++++++++++++++++++++++++++++---------- |
| M | Tests/Unit/ContextCaptureTests.swift | | | 68 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
3 files changed, 124 insertions(+), 13 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -639,9 +639,13 @@ denied provider leaves its section `nil`. It never blocks saving the report. ### Location -`CLLocationUpdate.liveUpdates()`, taking the first fix within an accuracy -threshold (50 m), then falling back to the best fix within the budget, less -3 seconds kept for looking up the address. Authorisation is asked for when +`CLLocationUpdate.liveUpdates()`, taking the first recent fix within an +accuracy threshold (50 m), then falling back to the best fix within the +budget, less 3 seconds kept for looking up the address. A fix counts as +recent if it's at most 30 seconds old or the update says the device is +stationary. Core Location often starts with a cached fix, which can be +accurate but minutes old and somewhere else, so an older fix never ends the +search early: it's kept as a fallback, and any recent fix beats it. Authorisation is asked for when the app is first opened (see [Notification actions](#notification-actions)); holding a `CLServiceSession` would otherwise ask for 'While Using' the first time a survey opens. Capture starts
diff --git a/Shared/Capture/ContextCapture.swift b/Shared/Capture/ContextCapture.swift
@@ -26,7 +26,8 @@ struct ContextCapture: Sendable {
/// The whole capture's budget.
var budget: Duration = .seconds(10)
- /// A fix at least this accurate, in metres, ends the search early.
+ /// A recent fix at least this accurate, in metres, ends the search
+ /// early.
var goodAccuracy: CLLocationAccuracy = 50
/// Time kept back from the location search for looking up the address
/// and the weather, which both start once there's a fix.
@@ -140,12 +141,12 @@ struct ContextCapture: Sendable {
return answer ?? false
}
- /// The first fix within `goodAccuracy`, or the best one received within
- /// `limit`.
+ /// The first recent fix within `goodAccuracy`, or the best one received
+ /// within `limit` (see `FixChoice`).
private func bestFix(within limit: Duration) async -> CLLocation? {
await withTaskGroup(of: CLLocation??.self) { group in
group.addTask {
- var best: CLLocation?
+ var choice = FixChoice(goodAccuracy: goodAccuracy)
var updates = 0
var last: CLLocationUpdate?
do {
@@ -157,21 +158,23 @@ struct ContextCapture: Sendable {
{
break
}
- if let location = update.location, location.horizontalAccuracy >= 0,
- location.horizontalAccuracy < best?.horizontalAccuracy ?? .infinity
+ if let location = update.location,
+ choice.consider(location, stationary: update.stationary)
{
- best = location
+ break
}
- if let best, best.horizontalAccuracy <= goodAccuracy { break }
if Task.isCancelled { break }
}
} catch {
Self.log.error("Location updates failed: \(error)")
}
- if best == nil {
+ if let best = choice.best {
+ let age = Date.now.timeIntervalSince(best.timestamp)
+ Self.log.info("Best fix was \(Int(age.rounded()))s old\(choice.isRecent ? "" : ", none recent")")
+ } else {
Self.logUnfixed(updates: updates, last: last)
}
- return .some(best)
+ return .some(choice.best)
}
group.addTask {
try? await Task.sleep(for: limit)
@@ -192,6 +195,42 @@ struct ContextCapture: Sendable {
}
}
+ /// Picks a location search's fix as updates arrive.
+ ///
+ /// Core Location's first update is often a cached fix, which can be
+ /// minutes old and somewhere else, but accurate enough to end the search
+ /// on accuracy alone. So only a recent fix ends it early; an older one is
+ /// kept in case nothing recent arrives in time. A recent fix beats an
+ /// older one whatever their accuracy, and between two of the same kind
+ /// the more accurate wins. An update marked stationary counts as recent:
+ /// the device hasn't moved since its fix, and Core Location pauses
+ /// updates until it does.
+ struct FixChoice {
+ /// A recent fix at least this accurate, in metres, ends the search.
+ var goodAccuracy: CLLocationAccuracy
+ /// How old a fix can be, in seconds, and still count as recent.
+ var recentAge: TimeInterval = 30
+ private(set) var best: CLLocation?
+ private(set) var isRecent = false
+
+ /// Takes in a fix, and says whether the search can stop.
+ mutating func consider(_ location: CLLocation, stationary: Bool = false, now: Date = .now) -> Bool {
+ guard location.horizontalAccuracy >= 0 else { return false }
+ let recent = stationary || now.timeIntervalSince(location.timestamp) <= recentAge
+ let isBetter =
+ if let best {
+ recent != isRecent ? recent : location.horizontalAccuracy < best.horizontalAccuracy
+ } else {
+ true
+ }
+ if isBetter {
+ best = location
+ isRecent = recent
+ }
+ return isRecent && best.map { $0.horizontalAccuracy <= goodAccuracy } == true
+ }
+ }
+
/// Records why a search ended without a fix: the last update's
/// diagnostics say whether Core Location held updates back.
private static func logUnfixed(updates: Int, last: CLLocationUpdate?) {
diff --git a/Tests/Unit/ContextCaptureTests.swift b/Tests/Unit/ContextCaptureTests.swift
@@ -61,6 +61,74 @@ struct ContextCaptureTests {
#expect(ContextCapture.localLanguage(ofRegion: "CN") == "zh-Hans")
}
+ // MARK: Choosing a fix
+
+ private static let now = Date(timeIntervalSince1970: 10_000)
+
+ private static func fix(accuracy: CLLocationAccuracy, age: TimeInterval) -> CLLocation {
+ CLLocation(
+ coordinate: CLLocationCoordinate2D(latitude: 35.7, longitude: 139.58),
+ altitude: 0, horizontalAccuracy: accuracy, verticalAccuracy: -1,
+ timestamp: now.addingTimeInterval(-age))
+ }
+
+ @Test("A recent, accurate fix ends the search")
+ func recentAccurateFix() {
+ var choice = ContextCapture.FixChoice(goodAccuracy: 50)
+ let ended = choice.consider(Self.fix(accuracy: 10, age: 5), now: Self.now)
+ #expect(ended)
+ #expect(choice.isRecent)
+ }
+
+ @Test("An old fix doesn't end the search however accurate, but is kept")
+ func oldFixKept() {
+ var choice = ContextCapture.FixChoice(goodAccuracy: 50)
+ let old = Self.fix(accuracy: 5, age: 600)
+ let ended = choice.consider(old, now: Self.now)
+ #expect(!ended)
+ #expect(choice.best === old)
+ #expect(!choice.isRecent)
+ }
+
+ @Test("A recent fix beats an older, more accurate one")
+ func recentBeatsOld() {
+ var choice = ContextCapture.FixChoice(goodAccuracy: 50)
+ _ = choice.consider(Self.fix(accuracy: 5, age: 600), now: Self.now)
+ let recent = Self.fix(accuracy: 200, age: 1)
+ let endedOnRecent = choice.consider(recent, now: Self.now)
+ #expect(!endedOnRecent)
+ #expect(choice.best === recent)
+ // An older fix doesn't take its place again.
+ let endedOnOld = choice.consider(Self.fix(accuracy: 3, age: 300), now: Self.now)
+ #expect(!endedOnOld)
+ #expect(choice.best === recent)
+ }
+
+ @Test("Between recent fixes the more accurate wins")
+ func moreAccurateWins() {
+ var choice = ContextCapture.FixChoice(goodAccuracy: 50)
+ _ = choice.consider(Self.fix(accuracy: 200, age: 2), now: Self.now)
+ let better = Self.fix(accuracy: 80, age: 1)
+ _ = choice.consider(better, now: Self.now)
+ _ = choice.consider(Self.fix(accuracy: 120, age: 0), now: Self.now)
+ #expect(choice.best === better)
+ }
+
+ @Test("An old fix from a stationary update counts as recent")
+ func stationaryIsRecent() {
+ var choice = ContextCapture.FixChoice(goodAccuracy: 50)
+ let ended = choice.consider(Self.fix(accuracy: 10, age: 600), stationary: true, now: Self.now)
+ #expect(ended)
+ }
+
+ @Test("A fix with invalid accuracy is ignored")
+ func invalidFixIgnored() {
+ var choice = ContextCapture.FixChoice(goodAccuracy: 50)
+ let ended = choice.consider(Self.fix(accuracy: -1, age: 0), now: Self.now)
+ #expect(!ended)
+ #expect(choice.best == nil)
+ }
+
@Test("A timeout gives up with nil, and a quick result comes through")
func timeout() async {
let slow = await withTimeout(.milliseconds(50)) { () async -> Int? in