findfamily: stamp own fixes with the hybrid clock so we can't lock ourselves out
- Commit
1b933be62eaf737e3fbc76694b1a67389a4b1635- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 17:34 UTC (14 days ago)
- Parents
1fab74d
Receivers now drop stale fixes per sender, but our own heartbeat still stamped wall time - a backwards clock correction would make a device's own fixes arrive stale against its own high-water everywhere. OwnFixStamps keeps a hybrid high-water (max(wall, last+1)) in device-protected storage (the pre-unlock publish path mints too), seeded at tracking start and written back per mint. Heartbeat, parting (shutdown/low-battery) and direct-boot publishes all funnel through publishLocation and now share the sequence; measuredAt stays the sensor's own time. Verified: findfamily suite passes incl. clock-backwards, restart-persistence and parting-after-heartbeat tests.
Diff
findfamily/src/main/java/com/vayunmathur/findfamily/data/OwnFixStamps.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/OwnFixStamps.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/OwnFixStamps.ktnew file mode 100644index 0000000000..e32005f93f--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/OwnFixStamps.kt@@ -0,0 +1,73 @@+package com.vayunmathur.findfamily.data++import android.content.Context+import com.vayunmathur.library.util.HybridStampGenerator+import kotlin.time.Instant++/**+ * Hybrid `reportedAt` stamps for this device's own location fixes.+ *+ * Receivers drop a fix whose stamp is not strictly newer than the sender's+ * stored high-water (see `domain/IngestSequencing`). Minting that stamp from+ * the raw wall clock therefore lets a device lock *itself* out: when its+ * clock is corrected backwards, every fix it sends arrives "stale" against+ * its own earlier high-water at each receiver until wall time catches up.+ * Minting through the library's hybrid rule — `max(wallNow, last + 1)` via+ * [HybridStampGenerator] — means stamps from this device never go backwards,+ * so the correction is invisible to receivers.+ *+ * One generator for the whole device (not per recipient): every peer tracks+ * the same sender, so one monotonic sequence is what they must all see. The+ * high-water is persisted per device under [KEY] in the device-protected+ * store ([DirectBootStore.store]) — not the credential-encrypted store —+ * because the pre-unlock publish path mints too, and a high-water it could+ * not read would restart the sequence below stamps already sent. Seeded on+ * start ([seedFromStore], from the tracking service) and lazily on first+ * mint; written back on every mint ([com.vayunmathur.library.util.DataStoreUtils.setLongIfGreater]),+ * so monotonicity survives process death and reboots.+ *+ * Only `reportedAt` is minted here. A fix's measured time (`timestamp`) is+ * the GPS fix's own time and is never rewritten: sequencing compares+ * `reportedAt` first, and parting reports deliberately carry a stale+ * measurement under a fresh send stamp.+ */+object OwnFixStamps {++ /** Device-protected DataStore key for the persisted own-fix high-water (epoch ms). */+ const val KEY = "ff_own_fix_reported_stamp"++ private var generator = HybridStampGenerator()++ @Volatile+ private var seeded = false++ /** The highest stamp minted so far in this process. */+ val last: Long+ get() = generator.last++ /** Seeds the in-process generator from the persisted high-water mark. */+ suspend fun seedFromStore(context: Context) {+ if (seeded) return+ seeded = true+ val persisted = DirectBootStore.store(context).getLongAwait(KEY) ?: 0L+ generator.observe(persisted)+ }++ /**+ * Mints the next own-fix `reportedAt`: strictly greater than every stamp+ * this device has minted before, even if the wall clock jumped backwards.+ * Persists the new high-water before returning.+ */+ suspend fun next(context: Context): Instant {+ seedFromStore(context)+ val stamp = generator.next()+ DirectBootStore.store(context).setLongIfGreater(KEY, stamp)+ return Instant.fromEpochMilliseconds(stamp)+ }++ /** Resets the in-process generator (tests only; the persisted mark is untouched). */+ internal fun resetForTesting(wallNow: () -> Long = { System.currentTimeMillis() }) {+ generator = HybridStampGenerator(wallNow = wallNow)+ seeded = false+ }+}
findfamily/src/main/java/com/vayunmathur/findfamily/platform/FinalLocationReporter.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FinalLocationReporter.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FinalLocationReporter.ktindex 8d6d13ec03..3ad194f21e 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FinalLocationReporter.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FinalLocationReporter.kt@@ -13,6 +13,7 @@ import com.vayunmathur.findfamily.data.Coord import com.vayunmathur.findfamily.data.DirectBootStore import com.vayunmathur.findfamily.data.LocationSource import com.vayunmathur.findfamily.data.LocationValue+import com.vayunmathur.findfamily.data.OwnFixStamps import com.vayunmathur.findfamily.network.Networking import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers@@ -239,7 +240,10 @@ object FinalLocationReporter { location.accuracy, measuredAt(location, now), battery,- reportedAt = now,+ // Hybrid stamp, not wall `now`: a parting report minted after a+ // backwards clock correction must still sort after every heartbeat+ // this device sent, or receivers drop it as stale (OwnFixStamps).+ reportedAt = OwnFixStamps.next(context), source = source, ) Log.status(TAG, "$source: reporting a fix ${now - value.timestamp} old to ${targets.size} peer(s)")
findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingDirectBoot.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingDirectBoot.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingDirectBoot.ktindex ce6ca9ea67..fd46da878e 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingDirectBoot.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingDirectBoot.kt@@ -16,6 +16,7 @@ import com.vayunmathur.findfamily.data.Coord import com.vayunmathur.findfamily.data.DirectBootStore import com.vayunmathur.findfamily.data.InboundSpool import com.vayunmathur.findfamily.data.LocationValue+import com.vayunmathur.findfamily.data.OwnFixStamps import com.vayunmathur.findfamily.platform.keepAliveTick import com.vayunmathur.findfamily.platform.refreshFixCeiling import com.vayunmathur.library.util.DataStoreUtils@@ -60,6 +61,7 @@ internal fun LocationTrackingService.startDirectBootTracking() { Log.status(LocationTrackingService.TAG_DIRECT_BOOT, "identity unavailable from the mirror; staying idle") return@launch }+ OwnFixStamps.seedFromStore(ctx) withContext(Dispatchers.Main) { registerSensors()@@ -162,6 +164,9 @@ internal suspend fun LocationTrackingService.publishDirectBoot(targets: List<Dir location.accuracy, Clock.System.now(), battery,+ // Pre-unlock fixes are own fixes too: hybrid reportedAt from the same+ // device-protected high-water the unlocked path uses (OwnFixStamps).+ reportedAt = OwnFixStamps.next(this@publishDirectBoot), ) val locSummary = "${location.latitude},${location.longitude} acc=${location.accuracy}" Log.dev(
findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingHeartbeat.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingHeartbeat.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingHeartbeat.ktindex f87fb3ec7b..64918561dd 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingHeartbeat.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingHeartbeat.kt@@ -7,6 +7,7 @@ import com.vayunmathur.library.log.Log import com.vayunmathur.findfamily.data.Coord import com.vayunmathur.findfamily.data.DirectBootStore import com.vayunmathur.findfamily.data.LocationValue+import com.vayunmathur.findfamily.data.OwnFixStamps import com.vayunmathur.findfamily.data.User import com.vayunmathur.findfamily.data.RequestStatus import com.vayunmathur.findfamily.data.havershine@@ -94,8 +95,12 @@ private suspend fun LocationTrackingService.upsertSelfLocation( // card read 0 forever, however fast they were actually moving. if (location.hasSpeed()) location.speed else 0f, location.accuracy,+ // timestamp (measuredAt) unchanged; only reportedAt is hybrid-stamped+ // (see OwnFixStamps) so a backwards clock correction cannot make this+ // heartbeat arrive stale against our own high-water at receivers. now,- bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY).toFloat()+ bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY).toFloat(),+ reportedAt = OwnFixStamps.next(this@upsertSelfLocation), ) Log.debug("FF-Heartbeat", "upsert local LocationValue for self") repository.upsertLocation(locationValue)
findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingService.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingService.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingService.ktindex 6d3d370082..56f96c7516 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingService.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingService.kt@@ -50,6 +50,7 @@ import com.vayunmathur.findfamily.data.DirectBootStore import com.vayunmathur.findfamily.data.FindFamilyRepository import com.vayunmathur.findfamily.data.LocationSource import com.vayunmathur.findfamily.data.LocationValue+import com.vayunmathur.findfamily.data.OwnFixStamps import com.vayunmathur.findfamily.data.RequestStatus import com.vayunmathur.findfamily.data.TemporaryLink import com.vayunmathur.findfamily.data.User@@ -399,6 +400,7 @@ class LocationTrackingService : Service(), SensorEventListener { DataStoreUtils.getInstance(this@LocationTrackingService), getString(R.string.me_label) )+ OwnFixStamps.seedFromStore(this@LocationTrackingService) // Hoist the UWB ranging session into this foreground service // so we can auto-accept incoming Find Nearby (UWB) requests
findfamily/src/test/java/com/vayunmathur/findfamily/data/OwnFixStampsTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/data/OwnFixStampsTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/data/OwnFixStampsTest.ktnew file mode 100644index 0000000000..fe0dc4d6de--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/data/OwnFixStampsTest.kt@@ -0,0 +1,70 @@+package com.vayunmathur.findfamily.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Own-fix hybrid stamps ([OwnFixStamps]): a backwards clock correction must+ * never make this device's fixes arrive stale against its own high-water at+ * receivers (see `domain/IngestSequencing`).+ */+@RunWith(AndroidJUnit4::class)+class OwnFixStampsTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @BeforeTest+ fun setup() = runBlocking {+ DirectBootStore.store(ctx).removeKeys(listOf(OwnFixStamps.KEY))+ }++ @Test+ fun clockBackwardsSequenceStillYieldsIncreasingReportedAt() = runBlocking {+ var wall = 1_700_000_000_000L+ OwnFixStamps.resetForTesting(wallNow = { wall })+ val first = OwnFixStamps.next(ctx)+ wall = 1_600_000_000_000L // clock corrected backwards by a day-ish+ val second = OwnFixStamps.next(ctx)+ val third = OwnFixStamps.next(ctx)+ assertEquals(1_700_000_000_000L, first.toEpochMilliseconds())+ assertTrue(second > first, "reportedAt regressed after backwards clock: $first -> $second")+ assertTrue(third > second, "reportedAt must keep increasing: $second -> $third")+ }++ @Test+ fun persistedHighWaterSurvivesRestart() = runBlocking {+ var wall = 1_700_000_000_000L+ OwnFixStamps.resetForTesting(wallNow = { wall })+ val before = OwnFixStamps.next(ctx)+ assertEquals(+ before.toEpochMilliseconds(),+ DirectBootStore.store(ctx).getLongAwait(OwnFixStamps.KEY),+ "mint must persist the high-water",+ )+ // Process death: fresh generator, wall now far behind the persisted mark.+ wall = 10L+ OwnFixStamps.resetForTesting(wallNow = { wall })+ val after = OwnFixStamps.next(ctx)+ assertTrue(after > before, "restart must resume past the persisted high-water: $before -> $after")+ }++ @Test+ fun partingReportStampsAfterHeartbeatStamps() = runBlocking {+ var wall = 1_700_000_000_000L+ OwnFixStamps.resetForTesting(wallNow = { wall })+ val heartbeat = OwnFixStamps.next(ctx) // heartbeat mint+ wall = 1_600_000_000_000L // clock corrected backwards before shutdown+ val parting = OwnFixStamps.next(ctx) // parting/shutdown mint+ assertTrue(+ parting > heartbeat,+ "parting reportedAt $parting must sort after heartbeat $heartbeat or receivers drop it as stale",+ )+ }+}