Accurate distances toggle, Approx. distance markers, and Closest-mode speedup

Distance confidence
- Every distance surface takes the figure AND its "Approx." marker from one
  FuelStore.stationDistanceDisplay call (station rows, detail sheet, widget,
  Live Activity, watch, Siri), so a surface can never mark one figure approximate
  while showing a routed one. Radius filters and Closest ordering test that same
  displayed distance, so no row can read a distance outside the radius that
  filtered it (the reported "14.6 mi inside a 10-mile list").

Accurate distances (Settings -> Distances, default off)
- Off: the browse layer serves the straight line, marked Approx., for every row,
  so two installs agree to the metre and the app makes no route requests at all.
- On: routed distances for the whole search area, unmarked, served only from a
  COMPLETE set anchored within 600 m — a partial fill reverts every row at once
  rather than mixing road and straight-line bases.
- Best Value maths sits deliberately outside the toggle: it keeps using measured
  road routes and its own confidence marking, so money figures never move with
  the switch.
- Fills run only while the toggle is on and the app is frontmost; capacity raised
  to 600 stations per pass; completeness tolerates pins Apple Maps has no route
  for, which otherwise left an area permanently incomplete and the whole list
  stuck on estimates.

Performance (the reported slowdown switching to Closest / launching with it)
- FuelStore.accurateDistancesEnabled was a UserDefaults(suiteName:) read per
  call: a synchronous cfprefsd round-trip measured at ~1.9 us, ~200k calls per
  Closest sort. Memoised, with the setter keeping it in step.
- Both keyed sorts decorate their keys — one distance per station, carried as an
  index instead of copying whole stations into the decorated array — and the
  comparison baseline plus per-station journeys now come from ONE pass instead of
  two full scans per tab. The Stations tab also reuses its single sorted list for
  the count and the TOP badge instead of sorting the country three times.
- Measured on iPhone SE (7,914-station Closest pool): sort 36.6 ms -> 17.1 ms per
  list, Cheapest 6 ms, Best Value 11 ms.
- DEBUG probes: FB_PERF list timing, FB_PERF_BENCH toggle-read benchmark, and
  FB_DIST_FOCUS now reports the served value, marker and mode (and re-prints when
  a fill lands). FB_ACCURATE_DISTANCES / FB_SORT_MODE env forms for devices, where
  devicectl eats a leading-dash argument.

Tests: 198, 0 failures. Device and simulator Debug builds green.
This commit is contained in:
FuelBoard Contributor
2026-10-13 18:01:45 +01:00
parent e0a997ecb0
commit 2a2823c180
21 changed files with 1009 additions and 131 deletions
+67 -11
View File
@@ -7,19 +7,26 @@
// here, not in the widget. The widget/Live Activity just read the cache.
//
// Throttling: recompute at most every `throttleMinutes`, or when the user has
// moved `moveThresholdMeters` from where the cache was built. Bounded to the
// `candidatesPerPass` nearest stations so a pass stays a handful of route calls.
// moved `moveThresholdMeters` from where the cache was built. In
// "Accurate distances" mode a pass routes the WHOLE search area (up to
// `fillCapacity` stations) so the browse layer can serve routed distances for
// every row at once; the mode must also be ON for any pass to run at all.
import Foundation
import MapKit
import UIKit
import WidgetKit
enum RoadDistanceService {
/// Upper bound on stations routed per pass, so a pass stays a bounded set of
/// route calls. Worth-the-Drive now asks for outward AND return routes, so
/// this must stay conservative; a larger value can make first launch feel
/// unresponsive while MapKit drains dozens of route requests.
static let candidatesPerPass = 12
/// Upper bound on stations routed per pass. Accurate-distances mode routes the
/// whole search area in ONE pass, because a 12-per-pass budget could never
/// make a list fully routed — that is exactly why two devices (and two
/// radii) disagreed about the same station. Capped so a pathological dataset
/// can't turn one pass into thousands of route requests; a capped pass stays
/// incomplete, and the browse layer keeps showing straight-line + "Approx."
/// until a later pass finishes the job. Measured on device: ~3.2 route calls
/// per second, so 600 stations (1,200 calls) is ~6 min at the very worst.
static let fillCapacity = 600
/// How many Worth-the-Drive candidates may claim slots in a pass. Those
/// rows are ranked by NET SAVING and are typically FURTHER out than the
/// nearest stations — routing only the nearest stations (the old behaviour)
@@ -46,6 +53,14 @@ enum RoadDistanceService {
lat: Double,
lng: Double,
prioritising priorityStations: [FuelStation] = []) async {
// "Accurate distances" OFF (the default) means the browse layer never
// serves a routed value, so any routing would be pure cost with nothing
// visible to show for it: no pass, no requests, no widget reloads.
guard FuelStore.accurateDistancesEnabled else { return }
// Only fill while the app is on screen. The browse layer is the only
// consumer, so a background fill would spend radio and battery routing a
// position nothing is displaying — worst case, a long drive.
guard await appIsActive() else { return }
guard await refreshGate.begin() else { return }
defer { Task { await refreshGate.end() } }
@@ -79,7 +94,7 @@ enum RoadDistanceService {
var candidates: [FuelStation] = []
var seen = Set<String>()
func consider(_ station: FuelStation) {
guard candidates.count < candidatesPerPass else { return }
guard candidates.count < fillCapacity else { return }
guard station.distanceKM(to: lat, lng2: lng) <= maxRadiusKM else { return }
guard seen.insert(station.id).inserted else { return }
guard !FuelStore.hasRoadDistance(for: station, userLat: lat, userLng: lng) else { return }
@@ -88,19 +103,23 @@ enum RoadDistanceService {
for station in priorityStations.prefix(priorityCandidates) { consider(station) }
let nearest = stations.sorted { $0.distanceKM(to: lat, lng2: lng) < $1.distanceKM(to: lat, lng2: lng) }
for station in nearest {
if candidates.count >= candidatesPerPass { break }
if candidates.count >= fillCapacity { break }
consider(station)
}
guard !candidates.isEmpty else { return }
let passStart = Date()
let origin = CLLocationCoordinate2D(latitude: lat, longitude: lng)
var entries: [String: CachedRoadDistance] = originCompatible ? (existing?.entries ?? [:]) : [:]
var routedCount = 0
for station in candidates {
let dest = CLLocationCoordinate2D(latitude: station.lat, longitude: station.lng)
async let outward = roadMeters(from: origin, to: dest)
async let back = roadMeters(from: dest, to: origin)
if let meters = await outward {
routedCount += 1
// Store the exact pin that was routed so the display layer can
// refuse to serve this value if the station later appears with
// a different coordinate (corrected pin / other data source).
@@ -115,13 +134,50 @@ enum RoadDistanceService {
return
}
FuelStore.saveRoadDistances(sourceLat: lat, sourceLng: lng, entries: entries)
// Wake the widgets so the new road distances surface immediately.
// A pass is complete when nothing in the search area is left UNRESOLVED:
// every station either has a route from this anchor, or was attempted in
// THIS pass and Apple Maps returned none. A few pins genuinely have no
// route (offshore, deleted forecourt, bad snapshot) and one of those must
// never leave the area permanently incomplete — that would pin the whole
// list on straight-line estimates forever. Those stations show their
// straight line, marked Approx., and the radius filter uses that same
// distance, so nothing is ever out of step with what a row displays.
let attempted = Set(candidates.map(\.id))
let capped = candidates.count >= fillCapacity
let unresolved = capped || stations.contains { station in
station.distanceKM(to: lat, lng2: lng) <= maxRadiusKM
&& !FuelStore.hasRoadDistance(for: station, userLat: lat, userLng: lng)
&& !attempted.contains(station.id)
}
FuelStore.saveRoadDistances(sourceLat: lat, sourceLng: lng, entries: entries,
complete: !unresolved)
#if DEBUG
// `FB-ROUTE` prints what a pass actually cost (stations, route calls,
// wall-clock, unroutable pins, whether the set is now complete) — the
// evidence for any "how taxing is routing?" answer, and how a bigger pass
// gets scaled from measurement instead of guesswork.
print("FB-ROUTE pass stations=\(candidates.count) calls=\(candidates.count * 2) "
+ "elapsed=\(String(format: "%.2f", Date().timeIntervalSince(passStart)))s "
+ "cached=\(entries.count) failed=\(candidates.count - routedCount) "
+ "complete=\(!unresolved)")
#endif
// Wake the widgets so the new road distances surface immediately, and
// tell the app so its rows re-read the distance they are showing.
WidgetCenter.shared.reloadAllTimelines()
await MainActor.run {
NotificationCenter.default.post(name: .fuelBoardRoadDistancesUpdated, object: nil)
}
}
private static let refreshGate = RoadDistanceRefreshGate()
/// Accurate mode fills only while the app is on screen: the browse layer is
/// the only consumer of routed distances, so a background fill would spend
/// radio and battery routing a position nothing is looking at.
private static func appIsActive() async -> Bool {
await MainActor.run { UIApplication.shared.applicationState == .active }
}
/// Driving distance (metres) between two coordinates via Apple Maps routing.
private static func roadMeters(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) async -> Double? {
let request = MKDirections.Request()