Modern Apps git

← Modern-Apps.git

findfamily: spool the latest fix per recipient while the relay is down

Commit
ae62ec46af2bfde29800f4e463f11ce132fad10c
Author
Vayun Mathur <[email protected]>
When
2026-11-21 12:24 UTC (15 days ago)
Parents
1053877
Own-device fixes published to a dead socket were lost -
including the shutdown/low-battery final report. All publish
paths funnel through Networking.publishLocation, which now
records the outcome in a latest-only outbound spool mirroring
the inbound one: sealed ciphertext only, device-protected
fsynced storage, one slot per recipient, newer-reportedAt
wins, no queue growth. Every reconnect flushes after
subscribe; a send success is the ack and only superseded or
exactly-matching slots clear, so a newer fix spooled mid-flush
survives. UWB handshakes and outdated-peer publishes are
deliberately not spooled. No wire change - flush reuses the
existing PUB frame.

Verified: findfamily suite passes incl. 13 new spool tests
(store-level and real-crypto publish/flush round-trips).

Diff

findfamily/src/main/java/com/vayunmathur/findfamily/data/OutboundSpool.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/OutboundSpool.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/OutboundSpool.ktnew file mode 100644index 0000000000..5f3fe89d59--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/OutboundSpool.kt@@ -0,0 +1,211 @@+package com.vayunmathur.findfamily.data++import android.content.Context+import java.io.DataInputStream+import java.io.DataOutputStream+import java.io.EOFException+import java.io.File+import java.io.FileOutputStream+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext++/**+ * The latest unpublished outbound fix per recipient, held while the relay socket is down.+ *+ * Outbound counterpart of [InboundSpool]. When the socket is down, a publish used to fail+ * and the fix was gone: the heartbeat at least republishes on its next tick, but a parting+ * report (shutdown / low battery) is one-shot, and a still phone may not produce a newer+ * fix for a long time. This spool keeps the newest failed fix for each recipient so the+ * next (re)connect can deliver it before the next live publish.+ *+ * Mailbox-slot semantics, deliberately not a queue: each recipient holds exactly one fix,+ * the newest by `reportedAt`. A newer fix replaces the slot, an older one never displaces+ * it, and the file is bounded by the number of recipients rather than the length of the+ * outage. Staleness is the receiver's call (it ranks by `reportedAt`), so delivering the+ * latest-known position late is still truthful.+ *+ * Only sealed ciphertext is ever stored — the bytes [com.vayunmathur.findfamily.network.Networking]+ * would have put on the socket — in device-protected storage, mirroring [InboundSpool]:+ * holding the ciphertext here exposes nothing new (the keys live in the same storage),+ * nothing is decrypted or written in plaintext, and the pre-unlock publish path can spool+ * and flush too. A slot is cleared only when its exact payload is acked by a successful+ * socket send, or retired by a successful live publish of a newer-or-equal fix.+ *+ * Record format: `[u64 BE recipient][i64 BE reportedAtMs][u32 BE length][sealed payload]`.+ * Unlike [InboundSpool] the whole file is rewritten per mutation (temp file, fsync,+ * rename), because slots are replaced rather than appended; a torn or corrupt tail record+ * is ignored on read and every complete record before it is kept.+ */+object OutboundSpool {+    private const val FILE_NAME = "ff_outbound_spool.bin"++    /** Largest single sealed payload accepted; guards against reading a corrupt length. */+    private const val MAX_PAYLOAD_BYTES = 16 * 1024 * 1024++    /** recipient (u64) + reportedAtMs (i64) + length prefix (u32). */+    private const val RECORD_HEADER_BYTES = 20++    private val lock = Mutex()++    /** One spooled fix: the sealed [payload] for [recipient], ranked by [reportedAtMs]. */+    internal class Entry(val recipient: Long, val reportedAtMs: Long, val payload: ByteArray)++    private fun file(context: Context): File =+        File(context.createDeviceProtectedStorageContext().filesDir, FILE_NAME)++    /**+     * Make [payload] the spooled fix for [recipient], unless the slot already holds a+     * newer one (by [reportedAtMs]). Called when a publish fails because the socket is+     * down; the payload must already be sealed for this recipient.+     */+    suspend fun store(context: Context, recipient: Long, reportedAtMs: Long, payload: ByteArray) {+        if (payload.size > MAX_PAYLOAD_BYTES) return+        lock.withLock {+            withContext(Dispatchers.IO) {+                val f = file(context)+                val slots = readAll(f)+                val existing = slots[recipient]+                if (existing != null && reportedAtMs < existing.reportedAtMs) return@withContext+                slots[recipient] = Entry(recipient, reportedAtMs, payload)+                writeAll(f, slots)+            }+        }+    }++    /** The latest spooled payload per recipient, as a snapshot. */+    suspend fun pending(context: Context): Map<Long, ByteArray> = lock.withLock {+        withContext(Dispatchers.IO) {+            readAll(file(context)).mapValues { it.value.payload }+        }+    }++    /**+     * Clear [recipient]'s slot after a successful send, but only if the slot still holds+     * exactly [payload]: a newer fix spooled while this send was in flight must survive+     * the older fix's acknowledgement.+     */+    suspend fun ack(context: Context, recipient: Long, payload: ByteArray) {+        lock.withLock {+            withContext(Dispatchers.IO) {+                val f = file(context)+                val slots = readAll(f)+                val existing = slots[recipient] ?: return@withContext+                if (!existing.payload.contentEquals(payload)) return@withContext+                slots.remove(recipient)+                writeAll(f, slots)+            }+        }+    }++    /**+     * Retire [recipient]'s slot after a successful live publish, when the spooled fix is+     * no newer than the one just sent ([reportedAtMs]). A newer spooled fix is kept.+     */+    suspend fun clearSuperseded(context: Context, recipient: Long, reportedAtMs: Long) {+        lock.withLock {+            withContext(Dispatchers.IO) {+                val f = file(context)+                val slots = readAll(f)+                val existing = slots[recipient] ?: return@withContext+                if (existing.reportedAtMs > reportedAtMs) return@withContext+                slots.remove(recipient)+                writeAll(f, slots)+            }+        }+    }++    /**+     * Send every spooled fix, latest per recipient, oldest slot first. Each slot is+     * cleared only when [send] reports success for its exact payload (see [ack]); a+     * failed send leaves the slot for the next reconnect. The lock is not held while+     * sending, so publishes can keep spooling during a flush. Returns how many fixes+     * were delivered.+     */+    suspend fun flush(+        context: Context,+        send: suspend (recipient: Long, payload: ByteArray) -> Boolean,+    ): Int {+        val snapshot = lock.withLock {+            withContext(Dispatchers.IO) { readAll(file(context)).values.toList() }+        }+        var sent = 0+        for (entry in snapshot) {+            val ok = runCatching { send(entry.recipient, entry.payload) }.getOrDefault(false)+            if (ok) {+                ack(context, entry.recipient, entry.payload)+                sent+++            }+        }+        return sent+    }++    /** All complete records in [f], keyed by recipient; a corrupt or torn tail is ignored. */+    private fun readAll(f: File): LinkedHashMap<Long, Entry> {+        val out = LinkedHashMap<Long, Entry>()+        if (!f.exists()) return out+        DataInputStream(f.inputStream().buffered()).use { input ->+            while (true) {+                val entry = readNextRecord(input) ?: break+                val existing = out[entry.recipient]+                if (existing == null || entry.reportedAtMs >= existing.reportedAtMs) {+                    out[entry.recipient] = entry+                }+            }+        }+        return out+    }++    /** One complete record, or null at EOF, on a corrupt header, or on a torn final record. */+    private fun readNextRecord(input: DataInputStream): Entry? {+        val recipient: Long+        val reportedAtMs: Long+        val len: Int+        try {+            recipient = input.readLong()+            reportedAtMs = input.readLong()+            len = input.readInt()+        } catch (_: EOFException) {+            return null+        }+        if (len < 0 || len > MAX_PAYLOAD_BYTES) return null+        val buf = ByteArray(len)+        try {+            input.readFully(buf)+        } catch (_: EOFException) {+            return null // torn final record from a crash mid-write+        }+        return Entry(recipient, reportedAtMs, buf)+    }++    /** Rewrites the spool with [slots] (or deletes it when empty), fsynced, via tmp + rename. */+    private fun writeAll(f: File, slots: Map<Long, Entry>) {+        if (slots.isEmpty()) {+            f.delete()+            return+        }+        f.parentFile?.mkdirs()+        val tmp = File(f.parentFile, f.name + ".tmp")+        FileOutputStream(tmp).use { fos ->+            val out = DataOutputStream(fos)+            for (entry in slots.values) {+                out.writeLong(entry.recipient)+                out.writeLong(entry.reportedAtMs)+                out.writeInt(entry.payload.size)+                out.write(entry.payload)+            }+            out.flush()+            fos.fd.sync()+        }+        if (!tmp.renameTo(f)) {+            // Same-directory rename is atomic; this is only a fallback for filesystems+            // that refuse it, at the cost of the atomicity.+            tmp.copyTo(f, overwrite = true)+            tmp.delete()+        }+    }++    /** Header bytes preceding each payload on disk (for tests). */+    internal const val RECORD_OVERHEAD: Int = RECORD_HEADER_BYTES+}
findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.ktindex 4d8517315c..6a12c514f1 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.kt@@ -1,4 +1,5 @@ package com.vayunmathur.findfamily.network+import android.content.Context import com.vayunmathur.library.log.Log import com.vayunmathur.findfamily.data.LocationValue import com.vayunmathur.findfamily.data.TemporaryLink@@ -321,6 +322,19 @@ object Networking {         _liveConnectedFlow.value = connected     } +    /**+     * Application context the outbound spool persists under, bound by the tracking+     * service when it starts. Null before that (and in unit tests): failed publishes+     * then drop exactly as they did before the spool existed.+     */+    @Volatile+    internal var spoolContext: Context? = null++    /** Bind the application context [com.vayunmathur.findfamily.data.OutboundSpool] persists under. */+    fun bindSpoolContext(context: Context) {+        spoolContext = context.applicationContext+    }+     internal data class KeyResult(val status: Int, val bundle: ByteArray?)      /** Reads 8 big-endian bytes at [off] back into the original Long bit pattern. */@@ -372,6 +386,9 @@ object Networking {                         wsSession = this                         setLiveConnected(true)                         sendSubscribe()+                        // Latest unpublished fix per recipient goes out before the+                        // next heartbeat publish (see flushOutboundSpool).+                        Networking.flushOutboundSpool()                         backoff = BACKOFF_INITIAL_MS                         superviseConnection(connScope, outerScope, onLocations, onUwb, onRawMsg)                     }@@ -403,7 +420,7 @@ object Networking {     }      /** Send an already-encrypted payload to [recipient] over the socket. False if the socket is down. */-    private suspend fun sendLivePublish(recipient: Long, kind: String, raw: ByteArray): Boolean {+    internal suspend fun sendLivePublish(recipient: Long, kind: String, raw: ByteArray): Boolean {         val session = wsSession ?: return false         return runCatching {             val frame = ByteArray(PUB_FRAME_HEADER_LEN + raw.size)@@ -449,7 +466,9 @@ object Networking {     /**      * Publish location to a connected user over the socket. Returns false if the peer has no      * PQC bundle (outdated app — surface [PeerCrypto.NEEDS_UPDATE] via [peerCryptoStatus]) or-     * the socket is down (the next heartbeat retries once reconnected).+     * the socket is down. A socket-down failure is not lost: the sealed fix becomes the+     * recipient's spooled latest (see [recordPublishOutcome]) and flushes on reconnect.+     * A missing bundle is not spooled — there is nothing sendable for an outdated peer.      */     // Broad catch is deliberate: relay-socket boundary, same as [wsGetKey].     @Suppress("TooGenericExceptionCaught")@@ -461,7 +480,9 @@ object Networking {         }         return try {             val pairId = outboundPairIdFor(user)-            val ok = sendLivePublish(user.id, "location", sealLocation(location, bundle, pairId))+            val sealed = sealLocation(location, bundle, pairId)+            val ok = sendLivePublish(user.id, "location", sealed)+            recordPublishOutcome(user.id, location, sealed, ok)             Log.dev(TAG, "publishLocation PQC to ${user.id.toULong()} (${user.name}) ok=$ok")             ok         } catch (e: Exception) {@@ -478,7 +499,9 @@ object Networking {             val bundle = Base64.decode(link.pqcPublicKey)             // Anonymous link viewers prove nothing about identity and expect no auth:             // pair ID stays null so nothing link-specific is pinned or leaked.-            val ok = sendLivePublish(link.id, "location", sealLocation(location, bundle, pairId = null))+            val sealed = sealLocation(location, bundle, pairId = null)+            val ok = sendLivePublish(link.id, "location", sealed)+            recordPublishOutcome(link.id, location, sealed, ok)             Log.dev(TAG, "publishLocation PQC to temp link ${link.id} ok=$ok")             ok         } catch (e: Exception) {@@ -504,7 +527,9 @@ object Networking {         pairId: String? = null     ): Boolean {         return try {-            val ok = sendLivePublish(targetId, "location", sealLocation(location, Base64.decode(bundleB64), pairId))+            val sealed = sealLocation(location, Base64.decode(bundleB64), pairId)+            val ok = sendLivePublish(targetId, "location", sealed)+            recordPublishOutcome(targetId, location, sealed, ok)             Log.dev(TAG, "publishLocation PQC to ${targetId.toULong()} (direct boot) ok=$ok")             ok         } catch (e: Exception) {
findfamily/src/main/java/com/vayunmathur/findfamily/network/NetworkingLive.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/network/NetworkingLive.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/network/NetworkingLive.ktindex 4ed0171786..6a5cc4e54c 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/network/NetworkingLive.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/network/NetworkingLive.kt@@ -2,6 +2,7 @@ package com.vayunmathur.findfamily.network  import com.vayunmathur.library.log.Log import com.vayunmathur.findfamily.data.LocationValue+import com.vayunmathur.findfamily.data.OutboundSpool import com.vayunmathur.findfamily.data.LocationValueCompatible import com.vayunmathur.findfamily.domain.UwbEnvelope import com.vayunmathur.library.network.WebSocketClient@@ -205,6 +206,45 @@ private fun decryptLocationPqcBytes(raw: ByteArray): Triple<LocationValue, Strin     return Triple(compat.toLocationValue(), compat.senderPlatform, compat.pairId) } +/**+ * Records one location publish against the outbound spool (see [OutboundSpool]): a+ * failed send keeps the sealed fix as the recipient's latest unpublished one, and a+ * successful send retires any spooled fix it supersedes (no newer than [LocationValue.reportedAt]).+ * Only sealed payloads ever reach the spool, and the whole update is a no-op until the+ * tracking service binds a context — spooling must never fail a publish.+ */+internal suspend fun Networking.recordPublishOutcome(+    recipient: Long,+    fix: LocationValue,+    sealed: ByteArray,+    sent: Boolean,+) {+    val ctx = spoolContext ?: return+    runCatching {+        if (sent) {+            OutboundSpool.clearSuperseded(ctx, recipient, fix.reportedAt.toEpochMilliseconds())+        } else {+            OutboundSpool.store(ctx, recipient, fix.reportedAt.toEpochMilliseconds(), sealed)+        }+    }.onFailure { Log.status(TAG, "outbound spool update failed", it) }+}++/**+ * Delivers the latest spooled fix per recipient on (re)connect, right after the+ * SUBSCRIBE frame and before the next heartbeat publish, so peers see the newest+ * known position even if this device then goes still. Fixes whose resend fails stay+ * spooled for the next reconnect; slots are cleared only on a successful send.+ */+internal suspend fun Networking.flushOutboundSpool() {+    val ctx = spoolContext ?: return+    runCatching {+        val sent = OutboundSpool.flush(ctx) { recipient, payload ->+            sendLivePublish(recipient, "location", payload)+        }+        if (sent > 0) Log.dev(TAG, "flushed $sent spooled outbound fix(es) on reconnect")+    }.onFailure { Log.status(TAG, "outbound spool flush failed", it) }+}+ /** Reads a big-endian u16 at [off]. */ private fun readU16Be(src: ByteArray, off: Int): Int =     ((src[off].toInt() and Networking.INT_BYTE_MASK) shl Networking.BITS_PER_BYTE) or
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 aebc54585f..8d6d13ec03 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FinalLocationReporter.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FinalLocationReporter.kt@@ -44,7 +44,8 @@ import kotlin.time.Duration.Companion.seconds  *   where the phone demonstrably is not.  * - **It does not reconnect, look up keys, or touch the database.** Every one of those can block  *   for seconds. It publishes to peers whose keys are already cached, over a socket that is- *   already open, or it publishes nothing and says so in the log.+ *   already open; if the socket is down the sealed report is spooled instead (see+ *   [com.vayunmathur.findfamily.data.OutboundSpool]) and delivered on the next connect.  *  * Registration has to happen at runtime, from the running tracking service. Both halves of that  * were checked against the platform source in this tree:@@ -219,12 +220,11 @@ object FinalLocationReporter {             Log.status(TAG, "$source: identity not loaded, nothing to report as")             return         }-        if (!Networking.liveConnected) {-            // Reconnecting costs a TLS handshake we do not have time for, and on shutdown the-            // radios are going down anyway. Saying so beats silently sending nothing.-            Log.status(TAG, "$source: socket is down, dropping the report")-            return-        }+        // A down socket no longer drops the report: publishLocation spools the sealed+        // fix as each recipient's latest unpublished one (OutboundSpool) and it flushes+        // on the next connect — for a shutdown report, on the next boot. Reconnecting+        // here would still cost a TLS handshake we do not have time for, and on+        // shutdown the radios are going down anyway; spooling is one small file write.          val now = Clock.System.now()         val battery = runCatching {
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 343b5449cf..6d3d370082 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingService.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingService.kt@@ -314,6 +314,9 @@ class LocationTrackingService : Service(), SensorEventListener {      override fun onCreate() {         super.onCreate()+        // Every own-device publish path runs out of this service (heartbeat, pre-unlock,+        // parting reports), so it owns binding the outbound spool's storage context.+        Networking.bindSpoolContext(this)         setupNotificationChannels()         // Runtime registration is not a style choice: neither ACTION_SHUTDOWN nor         // ACTION_BATTERY_LOW reaches a manifest-declared receiver.
findfamily/src/test/java/com/vayunmathur/findfamily/data/OutboundSpoolTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/data/OutboundSpoolTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/data/OutboundSpoolTest.ktnew file mode 100644index 0000000000..bb3692ea14--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/data/OutboundSpoolTest.kt@@ -0,0 +1,135 @@+package com.vayunmathur.findfamily.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import java.io.File+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Latest-only outbound spool: fixes published while the relay socket is down must+ * survive (newest per recipient only), flush on reconnect, and clear on ack.+ */+@RunWith(AndroidJUnit4::class)+class OutboundSpoolTest {+    private val context: Context = ApplicationProvider.getApplicationContext()+    private val dir: File get() = context.createDeviceProtectedStorageContext().filesDir+    private val spool: File get() = File(dir, "ff_outbound_spool.bin")++    @BeforeTest+    fun clean() {+        dir.listFiles()?.filter { it.name.startsWith("ff_outbound_spool") }?.forEach { it.delete() }+    }++    @AfterTest+    fun tearDown() = clean()++    private fun payload(i: Int) = "sealed-fix-$i".encodeToByteArray()++    @Test+    fun fixSpooledWhileSocketDownIsRetained() = runBlocking {+        OutboundSpool.store(context, recipient = 42L, reportedAtMs = 1_000L, payload = payload(1))+        val pending = OutboundSpool.pending(context)+        assertEquals(1, pending.size)+        assertContentEquals(payload(1), pending[42L])+        assertTrue(spool.exists(), "spooled fix is persisted in device-protected storage")+    }++    @Test+    fun newerFixReplacesOlderForSameRecipient() = runBlocking {+        OutboundSpool.store(context, recipient = 42L, reportedAtMs = 1_000L, payload = payload(1))+        OutboundSpool.store(context, recipient = 42L, reportedAtMs = 2_000L, payload = payload(2))+        val pending = OutboundSpool.pending(context)+        assertEquals(1, pending.size, "mailbox slot: one fix per recipient, no queue growth")+        assertContentEquals(payload(2), pending[42L])+    }++    @Test+    fun olderFixDoesNotDisplaceNewerSpooledFix() = runBlocking {+        OutboundSpool.store(context, recipient = 42L, reportedAtMs = 2_000L, payload = payload(2))+        OutboundSpool.store(context, recipient = 42L, reportedAtMs = 1_000L, payload = payload(1))+        assertContentEquals(payload(2), OutboundSpool.pending(context)[42L])+    }++    @Test+    fun recipientsHaveIndependentSlots() = runBlocking {+        OutboundSpool.store(context, recipient = 42L, reportedAtMs = 1_000L, payload = payload(1))+        OutboundSpool.store(context, recipient = 43L, reportedAtMs = 1_000L, payload = payload(3))+        OutboundSpool.store(context, recipient = 42L, reportedAtMs = 2_000L, payload = payload(2))+        val pending = OutboundSpool.pending(context)+        assertEquals(2, pending.size)+        assertContentEquals(payload(2), pending[42L])+        assertContentEquals(payload(3), pending[43L])+    }++    @Test+    fun reconnectFlushDeliversLatestPerRecipientAndAckClears() = runBlocking {+        OutboundSpool.store(context, recipient = 42L, reportedAtMs = 1_000L, payload = payload(1))+        OutboundSpool.store(context, recipient = 42L, reportedAtMs = 2_000L, payload = payload(2))+        OutboundSpool.store(context, recipient = 43L, reportedAtMs = 1_500L, payload = payload(3))+        val delivered = mutableListOf<Pair<Long, ByteArray>>()+        val sent = OutboundSpool.flush(context) { recipient, payload ->+            delivered += recipient to payload+            true+        }+        assertEquals(2, sent)+        assertEquals(listOf(42L, 43L), delivered.map { it.first })+        assertContentEquals(payload(2), delivered[0].second)+        assertContentEquals(payload(3), delivered[1].second)+        assertTrue(OutboundSpool.pending(context).isEmpty(), "acked slots are cleared")+        assertFalse(spool.exists(), "spool file removed once every slot is acked")+    }++    @Test+    fun failedFlushKeepsEverySlotForNextReconnect() = runBlocking {+        OutboundSpool.store(context, recipient = 42L, reportedAtMs = 1_000L, payload = payload(1))+        val sent = OutboundSpool.flush(context) { _, _ -> false }+        assertEquals(0, sent)+        assertContentEquals(payload(1), OutboundSpool.pending(context)[42L])+    }++    @Test+    fun ackDoesNotClearNewerFixSpooledDuringFlush() = runBlocking {+        OutboundSpool.store(context, recipient = 42L, reportedAtMs = 1_000L, payload = payload(1))+        // While the flush of fix 1 is in flight, a newer fix fails and takes the slot.+        val sent = OutboundSpool.flush(context) { _, _ ->+            OutboundSpool.store(context, recipient = 42L, reportedAtMs = 2_000L, payload = payload(2))+            true+        }+        assertEquals(1, sent, "the in-flight fix was delivered")+        assertContentEquals(+            payload(2), OutboundSpool.pending(context)[42L],+            "the older fix's ack must not clear the newer spooled fix",+        )+    }++    @Test+    fun successfulLivePublishRetiresSupersededSpoolOnly() = runBlocking {+        OutboundSpool.store(context, recipient = 42L, reportedAtMs = 1_000L, payload = payload(1))+        OutboundSpool.clearSuperseded(context, recipient = 42L, reportedAtMs = 2_000L)+        assertTrue(OutboundSpool.pending(context).isEmpty(), "older spooled fix retired by newer live fix")++        OutboundSpool.store(context, recipient = 42L, reportedAtMs = 3_000L, payload = payload(3))+        OutboundSpool.clearSuperseded(context, recipient = 42L, reportedAtMs = 2_000L)+        assertContentEquals(+            payload(3), OutboundSpool.pending(context)[42L],+            "newer spooled fix survives an older live publish",+        )+    }++    @Test+    fun tornTailRecordIsIgnoredAndCompleteSlotsKept() = runBlocking {+        OutboundSpool.store(context, recipient = 42L, reportedAtMs = 1_000L, payload = payload(1))+        // Simulate a crash mid-write: a partial header promising more than was written.+        spool.appendBytes(byteArrayOf(0, 0, 0, 0, 0, 0, 0, 7))+        assertContentEquals(payload(1), OutboundSpool.pending(context)[42L])+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/util/NetworkingOutboundSpoolTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/NetworkingOutboundSpoolTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/NetworkingOutboundSpoolTest.ktnew file mode 100644index 0000000000..64a30dd88c--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/NetworkingOutboundSpoolTest.kt@@ -0,0 +1,191 @@+package com.vayunmathur.findfamily.util++import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.Coord+import com.vayunmathur.findfamily.data.LocationSource+import com.vayunmathur.findfamily.data.LocationValue+import com.vayunmathur.findfamily.data.OutboundSpool+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.data.TestFindFamilyRepository+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.network.InboundFix+import com.vayunmathur.findfamily.network.Networking+import com.vayunmathur.findfamily.network.dispatchLiveFrame+import com.vayunmathur.findfamily.network.flushOutboundSpool+import com.vayunmathur.library.network.WebSocketClient+import com.vayunmathur.library.network.WsSession+import com.vayunmathur.library.util.DataStoreUtils+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.File+import java.net.Socket+import kotlin.io.encoding.Base64+import kotlin.time.Instant+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Networking-level outbound spool: a location publish whose socket send fails is kept+ * (sealed) as the recipient's latest unpublished fix, flushed on reconnect, and cleared+ * once delivered. Uses the same in-memory [WsSession] harness as+ * [NetworkingLiveSessionTest]; the spool itself is asserted through [OutboundSpool] and+ * by decrypting payloads back through [dispatchLiveFrame].+ */+@RunWith(AndroidJUnit4::class)+class NetworkingOutboundSpoolTest {++    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private lateinit var repo: com.vayunmathur.findfamily.data.FindFamilyRepository+    private lateinit var out: ByteArrayOutputStream+    private lateinit var session: WsSession++    @BeforeTest+    fun setup() = runBlocking {+        repo = TestFindFamilyRepository.install(ctx)+        Networking.stopLive()+        Networking.init(repo, DataStoreUtils.getInstance(ctx), "Me")+        assertTrue(Networking.pqcReady, "PQC native library must load on the test host")+        Networking.bindSpoolContext(ctx)+        cleanSpool()+        out = ByteArrayOutputStream()+        session = fakeSession(out)+        Networking.wsSession = null+        Networking.repository = repo+    }++    @AfterTest+    fun tearDown() {+        Networking.wsSession = null+        cleanSpool()+    }++    private fun cleanSpool() {+        val dir = ctx.createDeviceProtectedStorageContext().filesDir+        dir.listFiles()?.filter { it.name.startsWith("ff_outbound_spool") }?.forEach { File(it.absolutePath).delete() }+    }++    private fun fakeSession(output: ByteArrayOutputStream): WsSession {+        val clientConstructor = WebSocketClient::class.java+            .getDeclaredConstructor(+                Socket::class.java, java.io.InputStream::class.java,+                java.io.OutputStream::class.java, Map::class.java, Map::class.java,+            ).apply { isAccessible = true }+        val client = clientConstructor.newInstance(+            Socket(), ByteArrayInputStream(ByteArray(0)), output,+            emptyMap<String, List<String>>(), emptyMap<String, String>(),+        )+        val sessionConstructor = WsSession::class.java+            .getDeclaredConstructor(WebSocketClient::class.java)+            .apply { isAccessible = true }+        return sessionConstructor.newInstance(client)+    }++    /** Unmasks the single client frame written to [out] and returns its payload. */+    private fun capturedPayload(): ByteArray {+        val frame = out.toByteArray()+        assertTrue(frame.size >= 6, "a masked client frame was written")+        var off = 2+        var len = frame[1].toInt() and 0x7f+        if (len == 126) {+            len = ((frame[off].toInt() and 0xff) shl 8) or (frame[off + 1].toInt() and 0xff)+            off += 2+        } else if (len == 127) {+            var wide = 0L+            for (i in 0 until 8) wide = (wide shl 8) or (frame[off + i].toLong() and 0xff)+            len = wide.toInt()+            off += 8+        }+        val mask = frame.copyOfRange(off, off + 4)+        off += 4+        return ByteArray(len) { i -> (frame[off + i].toInt() xor mask[i % 4].toInt()).toByte() }+    }++    private fun peer(id: Long): User {+        val bundle = Base64.encode(Networking.pqcIdentity.publicBundle)+        return User(+            name = "Peer", photo = null, locationName = "Home", sendingEnabled = true,+            requestStatus = RequestStatus.MUTUAL_CONNECTION,+            id = id, pqcEncryptionKey = bundle, outboundPairId = "pair-1",+        )+    }++    private fun fix(reportedAtMs: Long, battery: Float) = LocationValue(+        userid = Networking.userid, coord = Coord(12.5, -45.25), speed = 2f, acc = 5f,+        timestamp = Instant.fromEpochMilliseconds(reportedAtMs), battery = battery,+        reportedAt = Instant.fromEpochMilliseconds(reportedAtMs), source = LocationSource.LIVE,+    )++    /** Decrypts a sealed payload by feeding it back as an inbound MSG frame. */+    private fun decrypt(ciphertext: ByteArray): InboundFix {+        val delivered = mutableListOf<InboundFix>()+        runBlocking {+            dispatchLiveFrame(byteArrayOf(Networking.WS_OP_MSG, 0) + ciphertext, { delivered += it }, {})+        }+        assertEquals(1, delivered.size, "spooled payload must decrypt to exactly one fix")+        return delivered.single()+    }++    @Test+    fun publishWhileSocketDownSpoolsSealedFix() = runBlocking {+        val peer = peer(777L)+        repo.upsertUser(peer)+        assertFalse(Networking.publishLocation(fix(1_700_000_000_000L, battery = 63f), peer))+        val pending = OutboundSpool.pending(ctx)+        assertEquals(setOf(777L), pending.keys, "failed publish is spooled per recipient")+        val fix = decrypt(pending.getValue(777L))+        assertEquals(63f, fix.location.battery)+        assertEquals(Coord(12.5, -45.25), fix.location.coord)+        assertEquals("pair-1", fix.pairId, "spooled payload carries the pair ID, like a live send")+    }++    @Test+    fun newerPublishWhileDownReplacesSpooledFix() = runBlocking {+        val peer = peer(777L)+        repo.upsertUser(peer)+        assertFalse(Networking.publishLocation(fix(1_700_000_000_000L, battery = 63f), peer))+        assertFalse(Networking.publishLocation(fix(1_700_000_060_000L, battery = 64f), peer))+        val pending = OutboundSpool.pending(ctx)+        assertEquals(1, pending.size, "still one slot for the recipient")+        assertEquals(64f, decrypt(pending.getValue(777L)).location.battery)+    }++    @Test+    fun flushOnReconnectDeliversSpooledFixAndClears() = runBlocking {+        val peer = peer(777L)+        repo.upsertUser(peer)+        assertFalse(Networking.publishLocation(fix(1_700_000_000_000L, battery = 63f), peer))+        assertFalse(Networking.publishLocation(fix(1_700_000_060_000L, battery = 64f), peer))++        // Reconnect: the spool flushes before the next live fix, over the new socket.+        Networking.wsSession = session+        Networking.flushOutboundSpool()+        val frame = capturedPayload()+        assertEquals(0x02, frame[0].toInt(), "flushed frame is a PUB")+        assertEquals(777L, Networking.readU64Be(frame, 2))+        assertTrue(OutboundSpool.pending(ctx).isEmpty(), "delivered spool slot is cleared (ack)")+        assertEquals(64f, decrypt(frame.copyOfRange(10, frame.size)).location.battery)+    }++    @Test+    fun publishWhileConnectedLeavesNoSpool() = runBlocking {+        val peer = peer(777L)+        repo.upsertUser(peer)+        Networking.wsSession = session+        assertTrue(Networking.publishLocation(fix(1_700_000_000_000L, battery = 63f), peer))+        assertTrue(OutboundSpool.pending(ctx).isEmpty(), "connected publish behaviour unchanged")+        // A successful live publish also retires an older spooled fix for the recipient.+        Networking.wsSession = null+        assertFalse(Networking.publishLocation(fix(1_700_000_000_000L, battery = 63f), peer))+        Networking.wsSession = session+        out.reset()+        assertTrue(Networking.publishLocation(fix(1_700_000_060_000L, battery = 64f), peer))+        assertTrue(OutboundSpool.pending(ctx).isEmpty(), "newer live fix retires the spooled one")+    }+}