findfamily: drop stale fixes at ingest instead of just ignoring them
- Commit
da0c25243e80052da5c9d0187b6c83273e270e3e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 16:20 UTC (15 days ago)
- Parents
a1d44e5
Out-of-order fixes never overwrote the pin (the reader picks the newest), but stale arrivals were persisted into 7-day history and, worse, the batch enrichment - waypoints, battery, meta - ran on stale coordinates as if they were current. Ingest now folds per-sender high-water stamps (reportedAt, measuredAt, payloadHash - in seconds, matching Room's Instant storage): only strictly newer fixes persist and enrich; duplicates drop idempotently; equal-time payloads tie-break deterministically on payload bits, never arrival order. The existing future-clamp runs first. First fix from a sender always accepts; a clock-corrected sender gets no regression window (indistinguishable from stale replay - the real fix is sender-side hybrid stamping, noted as follow-up). Verified: findfamily full suite passes incl. 11 new sequencing tests (pure policy + Robolectric ingest).
Diff
findfamily/src/main/java/com/vayunmathur/findfamily/domain/IngestSequencing.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/IngestSequencing.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/IngestSequencing.ktnew file mode 100644index 0000000000..26b3eed235--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/IngestSequencing.kt@@ -0,0 +1,153 @@+package com.vayunmathur.findfamily.domain++import kotlin.time.Instant++/**+ * Per-sender monotonic acceptance for inbound location fixes (sync ingest).+ *+ * Pure policy by construction (the [NoShowPolicy] pattern): every input is a+ * primitive, an [Instant], or a [String]. The ingest boundary in+ * `platform/LocationTrackingInbound.kt` maps stored rows and wire fixes to+ * [FixStamp]s and applies [accepts].+ *+ * ## The hole this closes+ *+ * Storage was append-only with no ordering at all: `upsertLocations` inserted+ * every authenticated fix, and ordering existed only at read time+ * (`LocationValueDao.getLatest()` ranks on MAX(reportedAt)). That read-side+ * ranking kept the *map pin* mostly right, but the stale row was still+ * persisted, and the ingest batch itself was enriched as if it were the+ * present — waypoint/battery recomputation and `updateLocationMeta` ran on+ * the batch's contents, so a delayed or replayed older fix could move a+ * person's displayed place, battery state, and last-change time backwards+ * until the next genuine fix arrived. Nothing rejected the stale arrival.+ *+ * ## Rule+ *+ * A fix is stored only if its [FixStamp] is strictly newer than the stored+ * latest stamp *for that sender* (the per-sender high-water mark). Senders+ * are independent: one sender's high-water never gates another's, and a+ * sender with no stored fix is always accepted. Ordering is:+ *+ * 1. `reportedAt` — when the report was sent, device-stamped by the sender.+ * This (not measurement time) decides "newest", for the same reason+ * `getLatest()` ranks on it: shutdown/low-battery parting reports+ * deliberately carry a stale measured fix under a fresh send stamp.+ * 2. `measuredAt` — when the position was measured.+ * 3. `payloadHash` — a deterministic hash of the fix payload (see+ * [payloadHash]).+ *+ * ## Equal stamps and duplicates+ *+ * Two distinct fixes can share a millisecond (a pre-hybrid sender mints plain+ * wall stamps). The tie is broken by [payloadHash], never by arrival order,+ * so the accept/drop decision is a pure function of (candidate, stored) and+ * replays decide identically every time: the higher-hash payload is accepted,+ * the lower-hash one is dropped whenever it arrives. A true duplicate —+ * every field equal, so the whole stamp is equal — is not strictly newer and+ * is dropped, which makes redelivery idempotent: no second history row, no+ * re-fired enrichment. Within one batch the same fold applies in arrival+ * order against a running high-water, so a batch containing [new, old]+ * stores only the new fix; a fix that beats the batch's running high-water+ * only on this hash tiebreak *replaces* that batch entry rather than+ * appending a second same-second row. A win on time appends normally —+ * a batch's genuine progression stays in history.+ *+ * One residue is deliberately left alone: if a higher-hash fix arrives in a+ * *later batch* than an equal-stamp lower-hash fix, both rows exist in+ * history (history is append-only by design — the scrubber needs it), and+ * `getLatest()`'s MAX(reportedAt) tie between them is the pre-existing+ * reader behaviour. It self-resolves on the sender's next fix and is bounded+ * to same-second collisions.+ *+ * ## Granularity: one second, because that is what storage keeps+ *+ * Room persists `Instant` columns as epoch *seconds*+ * (`DefaultConverters.fromInstant`), so a stored high-water read back from+ * the database has one-second precision no matter what the sender stamped.+ * Stamps are therefore compared in epoch seconds on both sides: comparing a+ * full-precision candidate against a second-truncated stored stamp would+ * re-accept every duplicate whose sub-second part survived (the candidate+ * always looks newer). The cost is that two genuinely distinct fixes from+ * one sender inside the same second collapse onto the hash tiebreak — one+ * is stored, the other dropped. Fixes from a single sender are seconds to+ * minutes apart in every real flow (30 s heartbeat, keep-alive, parting+ * reports), so nothing observable is lost.+ *+ * ## Clock-corrected senders — no regression window (decided)+ *+ * A sender whose clock is corrected backwards will stamp below its stored+ * high-water and be dropped until its stamps pass the high-water again. We+ * deliberately do NOT accept a one-time regression to rescue that case:+ *+ * - At the receiver, a legitimate correction is indistinguishable from a+ * delayed duplicate or a replay — all three are "older than high-water".+ * A window any of them can consume reopens the hole this policy closes,+ * and the stale fix it admits becomes the person's displayed position+ * until the next genuine fix.+ * - The lockout is bounded. Anything this build (or any clamping build)+ * ingested was future-clamped to receiver-now + 5 min before storage, so+ * the stored high-water can sit at most ~5 min past the receiver's wall+ * clock: a corrected sender is accepted again within minutes, not days.+ * - The real fix is at the source: a sender minting stamps with the+ * library's hybrid rule ([com.vayunmathur.library.util.SyncStamp.next] —+ * `max(wallNow, last + 1)`) never stamps backwards at all, so the+ * situation cannot arise. This receiver policy is the backstop for+ * senders that predate hybrid stamps, and it favours never resurrecting+ * a stale position over briefly delaying a corrected one — in a+ * family-location app, showing where someone *was* as if it were current+ * is the worse failure.+ */+object IngestSequencing {++ /**+ * The ordering stamp of one fix: epoch *seconds* (the precision storage+ * keeps — see the granularity note above), compared lexicographically:+ * [reportedAtSec], then [measuredAtSec], then [payloadHash]. The ingest+ * boundary truncates sender stamps with `epochSeconds` when mapping.+ */+ data class FixStamp(+ val reportedAtSec: Long,+ val measuredAtSec: Long,+ val payloadHash: Int,+ ) : Comparable<FixStamp> {+ override fun compareTo(other: FixStamp): Int =+ compareValuesBy(this, other, { it.reportedAtSec }, { it.measuredAtSec }, { it.payloadHash })+ }++ /**+ * True when [candidate] must be stored over the sender's stored latest+ * stamp ([stored] null = first fix from this sender, always accepted).+ * Strictly-greater only: an equal stamp is a duplicate, not a newer fix.+ */+ fun accepts(candidate: FixStamp, stored: FixStamp?): Boolean =+ stored == null || candidate > stored++ /**+ * Deterministic payload hash for the equal-stamp tiebreak. Built only+ * from value bits (never identity or arrival state), so the same payload+ * hashes identically on every device and every replay. Collisions between+ * different payloads are acceptable: they degrade the tiebreak to+ * "duplicate", dropping one of two same-millisecond fixes, never to+ * accepting a stale one.+ */+ fun payloadHash(+ lat: Double,+ lon: Double,+ speed: Float,+ acc: Float,+ battery: Float,+ sourceName: String,+ ): Int {+ var hash = foldBits(lat.toBits())+ hash = 31 * hash + foldBits(lon.toBits())+ hash = 31 * hash + speed.toBits()+ hash = 31 * hash + acc.toBits()+ hash = 31 * hash + battery.toBits()+ hash = 31 * hash + sourceName.hashCode()+ return hash+ }++ /** Folds a 64-bit IEEE pattern to 32 bits (the `Double.hashCode` recipe). */+ private fun foldBits(bits: Long): Int = (bits xor (bits ushr 32)).toInt()+}
findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingInbound.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingInbound.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingInbound.ktindex e874a87045..16e04d1cc2 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingInbound.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingInbound.kt@@ -13,6 +13,7 @@ import com.vayunmathur.findfamily.data.User import com.vayunmathur.findfamily.data.UserKind import com.vayunmathur.findfamily.data.havershine import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.domain.IngestSequencing import com.vayunmathur.findfamily.domain.NoShowPolicy import com.vayunmathur.findfamily.domain.PairAuth import com.vayunmathur.findfamily.domain.UwbCancelReason@@ -170,6 +171,16 @@ private suspend fun LocationTrackingService.collectAuthenticatedFix( * `reportedAt` is clamped to receiver-now + [PairAuth.MAX_FUTURE_SKEW_SECONDS] * before it is stored. This device's own reports never pass through here — * they are stored via the heartbeat's single-row upsert with their true stamp.+ *+ * Per-sender sequencing (the sync-census leftover this clamp could not close):+ * clamping bounds how far a fix may claim into the future, but says nothing+ * about ordering — a delayed or replayed *older* fix was still stored, and+ * this batch was then enriched as if it were the present. After clamping,+ * each fix is folded against its sender's stored latest stamp (the per-sender+ * high-water, advanced within the batch as fixes are accepted) under+ * [IngestSequencing]: strictly newer is stored, anything else is dropped.+ * The clamp runs first so the high-water a fix must beat is the effective+ * (clamped) stamp, never the sender's raw claim. */ internal suspend fun LocationTrackingService.processIncomingLocations(incoming: List<LocationValue>) { // A category this build cannot interpret is dropped rather than stored. Marking it is not@@ -218,9 +229,53 @@ internal suspend fun LocationTrackingService.processIncomingLocations(incoming: // Snapshot the previous latest-per-user BEFORE persisting the new fixes, so the // battery-threshold and self-waypoint comparisons below still see the prior state- // rather than the fix we're about to store.+ // rather than the fix we're about to store. The same snapshot seeds the+ // per-sender high-water marks for sequencing. val latestMap = repository.latestLocationsOnce().associateBy { it.userid } + // Per-sender monotonic acceptance: fold the batch against each sender's+ // stored latest stamp, advancing the running high-water as fixes are+ // accepted, so a batch carrying [new, old] for one sender stores only the+ // new fix and a replayed batch stores nothing. Stale drops are logged at+ // debug with the count — there is no metrics seam in this app, so that+ // line is the observable. Only accepted fixes are persisted or enriched:+ // enriching a stale fix would re-run waypoint/battery state on where the+ // person *was*.+ val highWater = latestMap.mapValues { it.value.fixStamp() }.toMutableMap()+ val accepted = ArrayList<LocationValue>(locList.size)+ // Index of each sender's latest accepted entry *from this batch*, so a+ // fix that beats it only on the equal-stamp hash tiebreak replaces it+ // instead of appending a second same-second row (see IngestSequencing).+ // A win on time appends: batch history progression is kept.+ val batchLatestIndex = HashMap<Long, Int>()+ var staleDropped = 0+ for (fix in locList) {+ val stamp = fix.fixStamp()+ val stored = highWater[fix.userid]+ if (IngestSequencing.accepts(stamp, stored)) {+ val batchIndex = batchLatestIndex[fix.userid]+ if (batchIndex != null && stored != null &&+ stamp.reportedAtSec == stored.reportedAtSec && stamp.measuredAtSec == stored.measuredAtSec+ ) {+ accepted[batchIndex] = fix+ } else {+ batchLatestIndex[fix.userid] = accepted.size+ accepted += fix+ }+ highWater[fix.userid] = stamp+ } else {+ staleDropped+++ Log.debug(+ "FF-Heartbeat",+ "dropped stale fix from ${fix.userid.toULong()} " ++ "(reportedAtSec=${stamp.reportedAtSec} not newer than stored)"+ )+ }+ }+ if (staleDropped > 0) {+ Log.debug("FF-Heartbeat", "dropped $staleDropped stale fix(es) at ingest (per-sender sequencing)")+ }+ // Persist the raw fixes immediately, before any enrichment. Everything after this // (waypoint detection, reverse-geocoding via fetchAddress, notifications) is // best-effort: the geocoder is a slow network call, any of it can throw, and the@@ -229,18 +284,41 @@ internal suspend fun LocationTrackingService.processIncomingLocations(incoming: // enrichment step silently dropped the location, so getLatest() kept serving stale // fixes even across a force-stop. Writing here makes the fix durable no matter what // follows.- repository.upsertLocations(locList)- Log.dev("FF-Heartbeat", "upsertAll ${locList.size} locations done")+ if (accepted.isNotEmpty()) {+ repository.upsertLocations(accepted)+ Log.dev("FF-Heartbeat", "upsertAll ${accepted.size} locations done")+ } // Enrichment runs off the reader coroutine. Reverse-geocoding is a slow network // call, so doing it inline stalled every subsequent inbound frame until the // liveness timeout force-reconnected the socket. The mutex keeps batches // serialized, so entry/exit and low-battery alerts still fire once each.- serviceScope.launch {- enrichmentMutex.withLock { enrichIncomingLocations(locList, latestMap) }+ if (accepted.isNotEmpty()) {+ serviceScope.launch {+ enrichmentMutex.withLock { enrichIncomingLocations(accepted, latestMap) }+ } } } +/**+ * This fix's [IngestSequencing] ordering stamp (boundary mapping for the pure+ * policy). Truncated to epoch seconds — the precision Room persists — so a+ * candidate and a stored row read back from the database compare like with+ * like.+ */+private fun LocationValue.fixStamp(): IngestSequencing.FixStamp = IngestSequencing.FixStamp(+ reportedAtSec = reportedAt.epochSeconds,+ measuredAtSec = timestamp.epochSeconds,+ payloadHash = IngestSequencing.payloadHash(+ lat = coord.lat,+ lon = coord.lon,+ speed = speed,+ acc = acc,+ battery = battery,+ sourceName = source.name,+ ),+)+ /** * Best-effort follow-up to [processIncomingLocations]: recomputes waypoint * entry/exit, reverse-geocodes the display name, and raises the entry/exit and@@ -266,8 +344,12 @@ private suspend fun LocationTrackingService.enrichOneUser( ) { // Self never receives its own published location, so fall back to the latest // stored fix; otherwise "me" never gets its waypoint recomputed.+ // The batch pick uses the ingest ordering stamp, not raw measurement time:+ // a parting (shutdown/low-battery) report carries a deliberately stale fix+ // under the freshest reportedAt, and ranking on timestamp here would undo+ // the sequencing the batch just went through. val lastLoc = if (user.id == Networking.userid) latestMap[Networking.userid]- else locList.filter { it.userid == user.id }.maxByOrNull { it.timestamp }+ else locList.filter { it.userid == user.id }.maxWithOrNull(compareBy { it.fixStamp() }) lastLoc ?: return val lastSavedLoc = latestMap[user.id] maybeNotifyLowBattery(user, lastLoc, lastSavedLoc)
findfamily/src/test/java/com/vayunmathur/findfamily/domain/IngestSequencingTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/domain/IngestSequencingTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/IngestSequencingTest.ktnew file mode 100644index 0000000000..b48234af5e--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/IngestSequencingTest.kt@@ -0,0 +1,77 @@+package com.vayunmathur.findfamily.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+/**+ * Pure-JVM tests for [IngestSequencing] (per-sender monotonic acceptance).+ * No Android, no database — every case feeds stamps straight into the policy.+ */+class IngestSequencingTest {++ private val t0 = 1_786_570_000L+ private val t1 = 1_786_570_060L++ private fun stamp(+ reportedAtSec: Long,+ measuredAtSec: Long = reportedAtSec,+ hash: Int = 0,+ ) = IngestSequencing.FixStamp(reportedAtSec, measuredAtSec, hash)++ private fun hash(lat: Double) = IngestSequencing.payloadHash(+ lat = lat, lon = -0.12, speed = 0f, acc = 5f, battery = 90f, sourceName = "LIVE",+ )++ @Test+ fun firstFixFromASenderIsAccepted() {+ assertTrue(IngestSequencing.accepts(stamp(t0), stored = null))+ }++ @Test+ fun newerReportedAtWinsOlderIsDropped() {+ assertTrue(IngestSequencing.accepts(stamp(t1), stamp(t0)))+ assertFalse(IngestSequencing.accepts(stamp(t0), stamp(t1)))+ }++ @Test+ fun duplicateStampIsNotNewer() {+ // A redelivered fix reproduces its stamp exactly: accepting it again+ // would add a second history row and re-fire enrichment.+ assertFalse(IngestSequencing.accepts(stamp(t0, hash = 7), stamp(t0, hash = 7)))+ }++ @Test+ fun equalReportedAtFallsToMeasuredAtThenHash() {+ assertTrue(IngestSequencing.accepts(stamp(t0, measuredAtSec = t1), stamp(t0, measuredAtSec = t0)))+ assertTrue(IngestSequencing.accepts(stamp(t0, hash = 9), stamp(t0, hash = 3)))+ assertFalse(IngestSequencing.accepts(stamp(t0, hash = 3), stamp(t0, hash = 9)))+ }++ @Test+ fun hashTiebreakIsDeterministicInBothArrivalOrders() {+ // Two distinct fixes sharing a millisecond: whichever the payload+ // hash ranks higher must win regardless of the order they are folded.+ val a = stamp(t0, hash = hash(51.5))+ val b = stamp(t0, hash = hash(52.5))+ assertTrue(a.payloadHash != b.payloadHash)+ val winner = maxOf(a, b)+ // Fold in both orders against a running high-water, as ingest does.+ fun fold(first: IngestSequencing.FixStamp, second: IngestSequencing.FixStamp) =+ listOf(first, second).fold<IngestSequencing.FixStamp, IngestSequencing.FixStamp?>(null) { high, fix ->+ if (IngestSequencing.accepts(fix, high)) fix else high+ }+ assertEquals(winner, fold(a, b))+ assertEquals(winner, fold(b, a))+ }++ @Test+ fun payloadHashDependsOnlyOnPayload() {+ assertEquals(hash(51.5), hash(51.5))+ assertTrue(hash(51.5) != hash(51.6))+ assertTrue(+ IngestSequencing.payloadHash(51.5, -0.12, 0f, 5f, 90f, "LIVE") !=+ IngestSequencing.payloadHash(51.5, -0.12, 0f, 5f, 90f, "SHUTDOWN")+ )+ }+}
findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.ktindex 16fa4bcf41..fc7dc5d326 100644--- a/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt@@ -27,6 +27,7 @@ import com.vayunmathur.findfamily.data.LocationValue import com.vayunmathur.findfamily.data.RequestStatus import com.vayunmathur.findfamily.data.User import com.vayunmathur.findfamily.data.Waypoint+import com.vayunmathur.findfamily.domain.IngestSequencing import com.vayunmathur.findfamily.domain.UwbCancelReason import com.vayunmathur.findfamily.domain.UwbEnvelope import com.vayunmathur.findfamily.domain.UwbEnvelopeKind@@ -47,6 +48,9 @@ import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock+import kotlin.time.Duration.Companion.hours+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant @RunWith(AndroidJUnit4::class)@@ -115,8 +119,11 @@ class LocationTrackingInboundTest { // Wrong pair id: dropped. service.processIncomingFixes(listOf(InboundFix(fix(alice), "wrong-pair"))) assertEquals(1, repo.locationHistory(alice).first().size)- // Correct pair id: stored.- service.processIncomingFixes(listOf(InboundFix(fix(alice), "expected-pair")))+ // Correct pair id: stored. Stamped past the clamped future fix so it+ // is also newer under per-sender sequencing (a now-stamped fix here+ // would be stale against the clamped high-water and dropped — that+ // is the sequencing working, not the auth gate).+ service.processIncomingFixes(listOf(InboundFix(fix(alice, at = future + 1.hours), "expected-pair"))) assertEquals(2, repo.locationHistory(alice).first().size) // Ineligible sender (awaiting request): coordinates never stored. service.processIncomingFixes(listOf(InboundFix(fix(pending), null)))@@ -253,6 +260,102 @@ class LocationTrackingInboundTest { Unit } + @Test+ fun outOfOrderArrivalKeepsNewer() = runBlocking {+ val uid = repo.upsertUser(user("Alice"))+ val now = Clock.System.now()+ val newer = fix(uid, at = now - 1.minutes, coord = Coord(52.0, -0.12))+ val older = fix(uid, at = now - 2.minutes, coord = Coord(53.0, -0.12))+ // Across batches: the delayed older fix must not be stored at all.+ service.processIncomingLocations(listOf(newer))+ service.processIncomingLocations(listOf(older))+ var stored = repo.locationHistory(uid).first()+ assertEquals(1, stored.size)+ assertEquals(52.0, repo.latestLocationByUser.first()[uid]?.coord?.lat)+ // Within one batch: [new, old] folds to the new fix only.+ val other = repo.upsertUser(user("Other"))+ service.processIncomingLocations(listOf(+ fix(other, at = now - 1.minutes, coord = Coord(52.0, -0.12)),+ fix(other, at = now - 2.minutes, coord = Coord(53.0, -0.12)),+ ))+ stored = repo.locationHistory(other).first()+ assertEquals(1, stored.size)+ assertEquals(52.0, stored[0].coord.lat)+ Unit+ }++ @Test+ fun duplicateDeliveryIsIdempotent() = runBlocking {+ val uid = repo.upsertUser(user("Alice"))+ val at = Clock.System.now() - 1.minutes+ service.processIncomingLocations(listOf(fix(uid, at = at), fix(uid, at = at)))+ service.processIncomingLocations(listOf(fix(uid, at = at)))+ assertEquals(1, repo.locationHistory(uid).first().size)+ Unit+ }++ @Test+ fun sequencingIsPerSenderIndependent() = runBlocking {+ val alice = repo.upsertUser(user("Alice"))+ val bob = repo.upsertUser(user("Bob"))+ val now = Clock.System.now()+ service.processIncomingLocations(listOf(fix(alice, at = now - 1.minutes)))+ // Bob's first fix is older than Alice's latest: her high-water must+ // not gate him.+ service.processIncomingLocations(listOf(fix(bob, at = now - 1.hours)))+ assertEquals(1, repo.locationHistory(bob).first().size)+ // Alice's stale fix is dropped; Bob's next fix is unaffected.+ service.processIncomingLocations(listOf(+ fix(alice, at = now - 2.minutes),+ fix(bob, at = now - 30.seconds),+ ))+ assertEquals(1, repo.locationHistory(alice).first().size)+ assertEquals(2, repo.locationHistory(bob).first().size)+ Unit+ }++ @Test+ fun clockRegressionIsDroppedUntilSenderPassesHighWater() = runBlocking {+ // Documented decision (IngestSequencing): no regression window. A+ // sender whose clock jumps backwards is dropped until its stamps+ // pass the stored high-water, then accepted again.+ val uid = repo.upsertUser(user("Alice"))+ val now = Clock.System.now()+ service.processIncomingLocations(listOf(fix(uid, at = now - 1.minutes, coord = Coord(52.0, -0.12))))+ service.processIncomingLocations(listOf(fix(uid, at = now - 1.hours, coord = Coord(53.0, -0.12))))+ assertEquals(1, repo.locationHistory(uid).first().size)+ service.processIncomingLocations(listOf(fix(uid, at = now, coord = Coord(54.0, -0.12))))+ val stored = repo.locationHistory(uid).first()+ assertEquals(2, stored.size)+ assertEquals(54.0, repo.latestLocationByUser.first()[uid]?.coord?.lat)+ Unit+ }++ @Test+ fun equalStampTiebreakIsDeterministicAtIngest() = runBlocking {+ // Same reportedAt + measuredAt, different payloads: the payload-hash+ // winner is stored regardless of arrival order within the batch.+ val at = Clock.System.now() - 1.minutes+ fun hash(lat: Double) = IngestSequencing.payloadHash(lat, -0.12, 0f, 5f, 90f, "LIVE")+ val winnerLat = if (hash(51.5) > hash(52.5)) 51.5 else 52.5+ val first = repo.upsertUser(user("First"))+ val second = repo.upsertUser(user("Second"))+ service.processIncomingLocations(listOf(+ fix(first, at = at, coord = Coord(51.5, -0.12)),+ fix(first, at = at, coord = Coord(52.5, -0.12)),+ ))+ service.processIncomingLocations(listOf(+ fix(second, at = at, coord = Coord(52.5, -0.12)),+ fix(second, at = at, coord = Coord(51.5, -0.12)),+ ))+ for (uid in listOf(first, second)) {+ val stored = repo.locationHistory(uid).first()+ assertEquals(1, stored.size)+ assertEquals(winnerLat, stored[0].coord.lat)+ }+ Unit+ }+ @Test fun serviceStartWithoutPermissionStops() { val controller = Robolectric.buildService(LocationTrackingService::class.java)