sync: stop losing office ops; clamp future location stamps
- Commit
d04967618b227e0f410c68c6910e3ca9c0a288e2- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 03:24 UTC (15 days ago)
- Parents
34351bb
Office sync folded un-acked appends into the persisted CRDT and advanced its cursor even when the HTTP append had failed - those ops vanished permanently, and a failed pull looked identical to 'no new ops'. Pull now returns null on failure (distinct from empty), append failure stashes the signed batch in a persisted pending list retried verbatim next cycle, the cursor only advances on success, and a sync error is shown. Tests cover two offline cycles keeping exactly one pending op. FindFamily ranked incoming fixes by sender wall-clock, so a peer with a fast clock pinned a stale fix as newest forever. Incoming reportedAt is now clamped to receiver-now + 5 minutes at ingest (future fixes are kept, ranked sanely, superseded by the next on-time report); own-device stamps are untouched. EverySync's periodic worker gets explicit 30s exponential backoff like its siblings. Verified: findfamily 534 tests pass; office targeted sync suites (51) pass (full office suite queued behind shared-tree build contention, to be re-run solo); everysync compiles.
Diff
everysync/src/main/java/com/vayunmathur/everysync/sync/SyncScheduler.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sync/SyncScheduler.kt b/everysync/src/main/java/com/vayunmathur/everysync/sync/SyncScheduler.ktindex ce31828c91..289d7789b1 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/sync/SyncScheduler.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/sync/SyncScheduler.kt@@ -1,6 +1,7 @@ package com.vayunmathur.everysync.sync import android.content.Context+import androidx.work.BackoffPolicy import androidx.work.Constraints import androidx.work.Data import androidx.work.ExistingPeriodicWorkPolicy@@ -17,6 +18,11 @@ object SyncScheduler { private const val PERIODIC_WORK = "EverySyncPeriodic" private const val IMMEDIATE_WORK = "EverySyncNow" + /** Initial retry delay for a failed periodic sync; WorkManager doubles+ * it exponentially from here (matching sibling workers, e.g. maps /+ * downloadservice, which use the same 30s exponential policy). */+ private const val BACKOFF_SECONDS = 30L+ /** (Re)schedule the periodic background sync using the current global settings. */ fun schedulePeriodic(context: Context) { val interval = Settings.intervalMinutes(context).coerceAtLeast(15)@@ -25,6 +31,10 @@ object SyncScheduler { .build() val request = PeriodicWorkRequestBuilder<SyncWorker>(interval, TimeUnit.MINUTES) .setConstraints(constraints)+ // SyncWorker returns Result.retry() on failure; without an+ // explicit policy WorkManager falls back to its default, so pin+ // the same exponential backoff sibling workers use.+ .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, BACKOFF_SECONDS, TimeUnit.SECONDS) .build() WorkManager.getInstance(context).enqueueUniquePeriodicWork( PERIODIC_WORK, ExistingPeriodicWorkPolicy.UPDATE, request,
findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.ktindex 0e4d7cc999..3009a56357 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.kt@@ -6,7 +6,9 @@ import androidx.room3.Entity import androidx.room3.Index import androidx.room3.PrimaryKey import com.vayunmathur.library.util.DatabaseItem+import com.vayunmathur.findfamily.domain.PairAuth import kotlinx.serialization.Serializable+import kotlin.time.Clock import kotlin.time.Instant /**@@ -153,7 +155,15 @@ data class LocationValueCompatible( */ val source: String? = null ) {- fun toLocationValue(): LocationValue {+ /**+ * Decodes a wire report into a stored row. This is an ingest point for+ * *incoming* reports only (this device's own reports are constructed as+ * [LocationValue] directly and keep their true stamp), so [reportedAt] is+ * clamped against the receiver's clock here: a sender with a fast clock+ * must not pin its fix as newest forever under `MAX(reportedAt)` ranking.+ * [receiverNow] is injectable for tests.+ */+ fun toLocationValue(receiverNow: Instant = Clock.System.now()): LocationValue { return LocationValue( userid = userid.toLong(), coord = coord,@@ -161,7 +171,8 @@ data class LocationValueCompatible( acc = acc, timestamp = Instant.fromEpochMilliseconds(timestamp), battery = battery,- reportedAt = Instant.fromEpochMilliseconds(reportedAt ?: timestamp),+ reportedAt = PairAuth.clampReportedAt(+ Instant.fromEpochMilliseconds(reportedAt ?: timestamp), receiverNow), // Absent means a peer older than the field, which only ever sent live reports. // Present but unrecognised means a peer NEWER than this build, whose category we // cannot interpret — guessing LIVE there would be unsafe, see LocationSource.UNKNOWN.
findfamily/src/main/java/com/vayunmathur/findfamily/domain/PairAuth.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/PairAuth.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/PairAuth.ktindex 655db4dfe7..be9399bd9b 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/PairAuth.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/PairAuth.kt@@ -2,6 +2,7 @@ package com.vayunmathur.findfamily.domain import java.security.SecureRandom import kotlin.io.encoding.Base64+import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant /**@@ -72,6 +73,19 @@ object PairAuth { timestamp.epochSeconds - now.epochSeconds > skew } + /**+ * Clamps a sender-stamped [reportedAt] to at most [MAX_FUTURE_SKEW_SECONDS]+ * ahead of the receiver's [now]. Applied at ingest (only to incoming peer+ * reports, never to this device's own reports) so a peer with a fast clock+ * cannot pin a stale fix as newest forever via `MAX(reportedAt)`: the fix+ * is kept, but ranked no newer than the receiver allows. The slack absorbs+ * ordinary in-flight delay and small genuine clock differences.+ */+ fun clampReportedAt(reportedAt: Instant, now: Instant): Instant {+ val latestAllowed = now + MAX_FUTURE_SKEW_SECONDS.seconds+ return if (reportedAt > latestAllowed) latestAllowed else reportedAt+ }+ /** Truncated pair ID for logs — the full value must never be logged. */ fun logPreview(pairId: String?): String = pairId?.take(4)?.let { "$it…" } ?: "absent" }
findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingCrowdFinding.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingCrowdFinding.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingCrowdFinding.ktindex ec2710c7ce..8ce9be5d99 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingCrowdFinding.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingCrowdFinding.kt@@ -7,7 +7,6 @@ import com.vayunmathur.library.log.Log import com.vayunmathur.findfamily.data.Coord import com.vayunmathur.findfamily.data.LocationValue import com.vayunmathur.findfamily.data.UserKind-import com.vayunmathur.findfamily.domain.PairAuth import com.vayunmathur.findfamily.sync.PoweredOffReporting import com.vayunmathur.findfamily.platform.PoweredOffScanner import com.vayunmathur.findfamily.platform.TrackerBeaconScanner@@ -82,15 +81,10 @@ internal suspend fun LocationTrackingService.pollTrackerReports() { } if (locs.isNotEmpty()) { // Tracker crowd reports are anonymous finder sightings restamped locally — no relay- // sender, no pair ID. Time-clamp before storing: finder-set timestamps flow through- // the same getLatest() MAX(reportedAt) ranking.- val now = Clock.System.now()- val timely = locs.filterNot { loc ->- val future = PairAuth.isFromTheFuture(loc.reportedAt, loc.timestamp, now)- if (future) Log.status("FF-Tracker", "dropped future-dated tracker report")- future- }- if (timely.isNotEmpty()) processIncomingLocations(timely)+ // sender, no pair ID. processIncomingLocations clamps reportedAt at+ // persist time: finder-set timestamps flow through the same+ // getLatest() MAX(reportedAt) ranking, so no pre-filter is needed here.+ processIncomingLocations(locs) } } @@ -173,15 +167,8 @@ internal suspend fun LocationTrackingService.pollPoweredOffSightings() { if (locs.isNotEmpty()) { Log.status(LocationTrackingService.TAG_POWERED_OFF, "retrieved ${locs.size} network sighting(s)") // Powered-off sightings are anonymous finder reports restamped locally — no relay- // sender, no pair ID. Time-clamp before storing (same getLatest() ranking).- val now = Clock.System.now()- val timely = locs.filterNot { loc ->- val future = PairAuth.isFromTheFuture(loc.reportedAt, loc.timestamp, now)- if (future) {- Log.status(LocationTrackingService.TAG_POWERED_OFF, "dropped future-dated sighting")- }- future- }- if (timely.isNotEmpty()) processIncomingLocations(timely)+ // sender, no pair ID. processIncomingLocations clamps reportedAt at+ // persist time (same getLatest() ranking).+ processIncomingLocations(locs) } }
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 f5f782c991..e874a87045 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingInbound.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationTrackingInbound.kt@@ -56,8 +56,11 @@ internal typealias UwbEnvelopeSender = * * Three gates, in order — time-clamp, sender-auth, storage-eligibility — so a forgery * dies at the cheapest check that catches it:- * 1. **Time clamp.** A far-future `reportedAt`/`timestamp` lets one forgery pin- * `getLatest()` forever (it ranks on MAX(reportedAt)). Dropped before any DB work.+ * 1. **Time clamp.** A far-future `reportedAt` lets one report pin+ * `getLatest()` forever (it ranks on MAX(reportedAt)). It is clamped to+ * receiver-now + [PairAuth.MAX_FUTURE_SKEW_SECONDS] at ingest (in+ * [processIncomingLocations] / `toLocationValue()`), not dropped: the fix+ * stays usable, it just cannot outrank reports received after it. * 2. **Sender auth (GHSA-x94x-v6f7-wwpp).** Ciphertext proves who the packet is FOR, * not who it is FROM, and `userid` is self-declared. Each *person* peer pins the * first pair ID it sees; anything else claiming to be them is dropped before it can@@ -74,7 +77,6 @@ internal typealias UwbEnvelopeSender = */ internal suspend fun LocationTrackingService.processIncomingFixes(incoming: List<InboundFix>) { if (incoming.isEmpty()) return- val now = Clock.System.now() val usersById = repository.getAllUsers().associateBy { it.id } // Eligible senders: mutual/response PERSON contacts known when this batch arrived. // Trackers excluded (crowd reports, not relay packets). AWAITING_REQUEST excluded:@@ -89,7 +91,7 @@ internal suspend fun LocationTrackingService.processIncomingFixes(incoming: List val authenticated = ArrayList<LocationValue>(incoming.size) val strangerIds = LinkedHashSet<Long>() for (fix in incoming) {- collectAuthenticatedFix(fix, usersById, eligibleIds, now, authenticated, strangerIds)+ collectAuthenticatedFix(fix, usersById, eligibleIds, authenticated, strangerIds) } if (strangerIds.isNotEmpty()) { Log.dev("FF-Heartbeat", "newUsers to insert=${strangerIds.map { it.toULong() }}")@@ -104,21 +106,15 @@ private suspend fun LocationTrackingService.collectAuthenticatedFix( fix: InboundFix, usersById: Map<Long, User>, eligibleIds: Set<Long>,- now: kotlin.time.Instant, authenticated: MutableList<LocationValue>, strangerIds: MutableSet<Long>, ) { val loc = fix.location val senderId = loc.userid if (senderId == Networking.userid) return- if (PairAuth.isFromTheFuture(loc.reportedAt, loc.timestamp, now)) {- Log.status(- "FF-Heartbeat",- "dropped future-dated fix from ${senderId.toULong()} " +- "reportedAt=${loc.reportedAt} timestamp=${loc.timestamp}"- )- return- }+ // Future-stamped reports are NOT dropped here: processIncomingLocations+ // clamps reportedAt to receiver-now + slack at persist time, which+ // neutralises the MAX(reportedAt) pin without losing the fix. val peer = usersById[senderId] if (peer == null || peer.kind != UserKind.PERSON || senderId !in eligibleIds) { // Stranger, tracker claim, or not-yet-mutual: request row at most, never a pin,@@ -167,8 +163,13 @@ private suspend fun LocationTrackingService.collectAuthenticatedFix( * [LocationTrackingService.pollPoweredOffSightings]) call this DIRECTLY, bypassing * [processIncomingFixes] on purpose: their fixes are anonymous finder reports restamped * to a tracker/owner ID locally — there is no relay sender to authenticate and no pair- * ID to check. They MUST time-clamp before calling: those reports carry finder-set- * timestamps through the same `getLatest()` ranking.+ * ID to check. Their finder-set timestamps flow through the same `getLatest()`+ * ranking, so the clamp below is what protects them too.+ *+ * Clock-skew clamp (the persist point for every incoming report): each fix's+ * `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. */ internal suspend fun LocationTrackingService.processIncomingLocations(incoming: List<LocationValue>) { // A category this build cannot interpret is dropped rather than stored. Marking it is not@@ -192,9 +193,16 @@ internal suspend fun LocationTrackingService.processIncomingLocations(incoming: } // Low-accuracy fixes are never used: anything worse than the intake gate never // reaches Room, the map, or latestLocations.- val locList = knownSource.filter {+ val filtered = knownSource.filter { it.acc.isFinite() && it.acc >= 0f && it.acc <= MAX_FIX_ACCURACY_METERS }+ // Clamp at ingest, once, here — not in every query: effective reportedAt is+ // min(reportedAt, receiverNow + slack). A fast-clock peer's fix is kept but+ // can no longer outrank every later report forever.+ val receiverNow = Clock.System.now()+ val locList = filtered.map {+ it.copy(reportedAt = PairAuth.clampReportedAt(it.reportedAt, receiverNow))+ } if (locList.size != knownSource.size) { Log.status( "FF-Heartbeat",
findfamily/src/test/java/com/vayunmathur/findfamily/data/LocationSourceDecodeTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/data/LocationSourceDecodeTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/data/LocationSourceDecodeTest.ktindex c9a91d65ae..c6a41e513f 100644--- a/findfamily/src/test/java/com/vayunmathur/findfamily/data/LocationSourceDecodeTest.kt+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/data/LocationSourceDecodeTest.kt@@ -80,6 +80,41 @@ class LocationSourceDecodeTest { assertEquals(Instant.fromEpochMilliseconds(1_300_000L), decoded.reportedAt) } + @Test+ fun futureStampedReportIsClampedToReceiverNowPlusSlackAtIngest() {+ // A peer with a fast clock stamps reportedAt 2h ahead. Without the+ // ingest clamp that row would win MAX(reportedAt) until real time+ // caught up — effectively forever. Clamped, it ranks as "just sent"+ // (receiver-now + 5 min slack) and the next on-time report supersedes it.+ val receiverNow = Instant.fromEpochMilliseconds(2_000_000_000L)+ val futureMs = receiverNow.toEpochMilliseconds() + 2 * 60 * 60 * 1000L+ val decoded = payload(source = "LIVE", reportedAt = futureMs)+ .toLocationValue(receiverNow = receiverNow)+ assertEquals(+ Instant.fromEpochMilliseconds(receiverNow.toEpochMilliseconds() + 5 * 60 * 1000L),+ decoded.reportedAt,+ )+ // The measurement time is not rewritten — only the ranking stamp is.+ assertEquals(Instant.fromEpochMilliseconds(1_000_000L), decoded.timestamp)+ }++ @Test+ fun inWindowAndPastReportsKeepTheirStampAtIngest() {+ val receiverNow = Instant.fromEpochMilliseconds(2_000_000_000L)+ val inWindowMs = receiverNow.toEpochMilliseconds() + 60_000L+ assertEquals(+ Instant.fromEpochMilliseconds(inWindowMs),+ payload(source = "LIVE", reportedAt = inWindowMs)+ .toLocationValue(receiverNow = receiverNow).reportedAt,+ )+ val pastMs = receiverNow.toEpochMilliseconds() - 60_000L+ assertEquals(+ Instant.fromEpochMilliseconds(pastMs),+ payload(source = "LIVE", reportedAt = pastMs)+ .toLocationValue(receiverNow = receiverNow).reportedAt,+ )+ }+ @Test fun encodeThenDecodePreservesSourceAndBothTimes() { val original = LocationValue(
findfamily/src/test/java/com/vayunmathur/findfamily/domain/PairAuthTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/domain/PairAuthTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/PairAuthTest.ktindex 97e46eebe7..38a31d8531 100644--- a/findfamily/src/test/java/com/vayunmathur/findfamily/domain/PairAuthTest.kt+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/PairAuthTest.kt@@ -104,6 +104,21 @@ class PairAuthTest { assertFalse(PairAuth.isFromTheFuture(now - 30.days, now, now)) } + // --- clampReportedAt ---++ @Test+ fun clampCapsFutureReportedAtAtNowPlusSlack() {+ assertEquals(now + 5.minutes, PairAuth.clampReportedAt(now + 2.days, now))+ assertEquals(now + 5.minutes, PairAuth.clampReportedAt(now + 5.minutes, now))+ }++ @Test+ fun clampLeavesInWindowAndPastStampsUntouched() {+ assertEquals(now, PairAuth.clampReportedAt(now, now))+ assertEquals(now + 1.minutes, PairAuth.clampReportedAt(now + 1.minutes, now))+ assertEquals(now - 30.days, PairAuth.clampReportedAt(now - 30.days, now))+ }+ // --- logPreview --- @Test
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 041f1d8cc9..16fa4bcf41 100644--- a/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt@@ -100,16 +100,24 @@ class LocationTrackingInboundTest { fun processIncomingFixesAuthGates() = runBlocking { val alice = repo.upsertUser(user("Alice", inbound = "expected-pair")) val pending = repo.upsertUser(user("Pending", status = RequestStatus.AWAITING_REQUEST))- // Future-dated fix from Alice: dropped by time clamp.- val future = Instant.fromEpochSeconds(Clock.System.now().epochSeconds + 48 * 3600)+ // Future-dated fix from Alice (fast clock, +48h): NOT dropped, but its+ // reportedAt is clamped at ingest to receiver-now + 5 min slack, so it+ // cannot pin MAX(reportedAt) forever. Stored exactly once, clamped.+ val before = Clock.System.now().epochSeconds+ val future = Instant.fromEpochSeconds(before + 48 * 3600) service.processIncomingFixes(listOf(InboundFix(fix(alice, at = future), "expected-pair")))- assertTrue(repo.locationHistory(alice).first().isEmpty())+ val clamped = repo.locationHistory(alice).first()+ assertEquals(1, clamped.size)+ assertTrue(+ clamped[0].reportedAt.epochSeconds in (before + 4 * 60)..(before + 6 * 60 + 5),+ "reportedAt clamped to ~now+5min, was ${clamped[0].reportedAt}",+ ) // Wrong pair id: dropped. service.processIncomingFixes(listOf(InboundFix(fix(alice), "wrong-pair")))- assertTrue(repo.locationHistory(alice).first().isEmpty())+ assertEquals(1, repo.locationHistory(alice).first().size) // Correct pair id: stored. service.processIncomingFixes(listOf(InboundFix(fix(alice), "expected-pair")))- assertEquals(1, repo.locationHistory(alice).first().size)+ assertEquals(2, repo.locationHistory(alice).first().size) // Ineligible sender (awaiting request): coordinates never stored. service.processIncomingFixes(listOf(InboundFix(fix(pending), null))) assertTrue(repo.locationHistory(pending).first().isEmpty())
office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncA.kt
diff --git a/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncA.kt b/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncA.ktindex ca0c52d0e8..8521cac50c 100644--- a/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncA.kt+++ b/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncA.kt@@ -194,10 +194,16 @@ internal suspend fun OfficeViewModel.applyLiveActions(msg: OfficeSync.LiveMsg, d internal suspend fun OfficeViewModel.pushLiveOps(docId: String, key: ByteArray, opsJson: String) { val sig = Base64.encode(OfficeSync.sign(opsJson.encodeToByteArray())) val signed = syncJson.encodeToString(SignedOp(OfficeSync.deviceId, sig, opsJson))- if (!OfficeSync.liveAppend(docId, key, listOf(signed))) OfficeSync.appendDocActions(- docId,- key,- listOf(signed))+ val pushed = OfficeSync.liveAppend(docId, key, listOf(signed)) ||+ OfficeSync.appendDocActions(docId, key, listOf(signed)) != null+ if (!pushed) {+ // Same lost-ops guard as syncDoc: the tree has already absorbed+ // these ops, so stash the signed batch in the persisted pending+ // list for the next syncDoc cycle to retry verbatim.+ val ds = DataStoreUtils.getInstance(getApplication())+ val pending = loadPendingOps(ds, docId)+ if (signed !in pending) savePendingOps(ds, docId, pending + signed)+ } } /** Persists the merged tree and re-renders it into the editor when it changed. */
office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncB.kt
diff --git a/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncB.kt b/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncB.ktindex 2872f8e191..ae171c4fd2 100644--- a/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncB.kt+++ b/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncB.kt@@ -218,6 +218,23 @@ internal suspend fun OfficeViewModel.saveTree(ds: DataStoreUtils, docId: String, ds.setString("crdt:$docId", tree.serialize()) } +/**+ * Signed ops that have been diffed into the local CRDT but not yet acked by+ * the relay. Persisted because `updateJson` advances the tree immediately:+ * once local edits are folded in, the next diff returns "[]" for them, so+ * without this list a failed append would lose them forever. The list is+ * retried verbatim on the next sync (CRDT op application is idempotent, so+ * an echo re-apply is harmless) and cleared only on a successful push.+ */+internal suspend fun OfficeViewModel.loadPendingOps(ds: DataStoreUtils, docId: String): List<String> =+ ds.getString("crdtPending:$docId")+ ?.let { runCatching { syncJson.decodeFromString<List<String>>(it) }.getOrNull() }+ ?: emptyList()++internal suspend fun OfficeViewModel.savePendingOps(ds: DataStoreUtils, docId: String, ops: List<String>) {+ ds.setString("crdtPending:$docId", syncJson.encodeToString(ops))+}+ /** Parses flat-ODF text back into a document via a temp file (tolerant; null on failure). */ internal fun OfficeViewModel.parseFlat(flat: String): OdfDocument? { val ctx: Context = getApplication()@@ -238,16 +255,48 @@ internal suspend fun OfficeViewModel.syncDoc(docId: String, key: ByteArray) = sy val startVersion = editVersion val opsJson = tree.updateJson(localXml) // Only push signed ops if we're allowed to edit; viewers never push.+ // Push = previously-pending (un-acked) ops + any newly diffed ops, so a+ // failed cycle is retried verbatim next time instead of depending on the+ // diff regenerating ops the tree has already absorbed.+ var pending = loadPendingOps(ds, docId) if (opsJson != "[]" && OfficeRoles.canEdit(currentRole)) { val sig = Base64.encode(OfficeSync.sign(opsJson.encodeToByteArray())) val signed = syncJson.encodeToString(SignedOp(OfficeSync.deviceId, sig, opsJson))+ if (signed !in pending) pending = pending + signed+ }+ if (pending.isNotEmpty() && OfficeRoles.canEdit(currentRole)) { // Prefer the live WebSocket (peers get it instantly, like presence); HTTP is the fallback.- if (!OfficeSync.liveAppend(docId, key, listOf(signed))) {- OfficeSync.appendDocActions(docId, key, listOf(signed))+ // Failure semantics: a failed append is NOT success. Keep the ops in+ // the persisted pending list, persist the tree for local consistency+ // (the editor/CRDT already contain the edits), surface the failure,+ // and return WITHOUT advancing the cursor or pulling — the next+ // cycle retries the same ops and pulls from the same cursor, so no+ // remote op is skipped either.+ val pushed = OfficeSync.liveAppend(docId, key, pending) ||+ OfficeSync.appendDocActions(docId, key, pending) != null+ if (!pushed) {+ savePendingOps(ds, docId, pending)+ saveTree(ds, docId, tree)+ withContext(Dispatchers.Main) {+ AppMessages.show(getApplication<Application>().getString(R.string.sync_push_failed_retrying))+ }+ return@withLock }+ // Acked (live send or HTTP seq): clear the pending list.+ if (pending.isNotEmpty()) savePendingOps(ds, docId, emptyList()) } // Pull from the OLD cursor so remote ops (and our just-pushed, idempotent ops) are merged.+ // Failure semantics: null = relay failure, distinct from "no new ops".+ // Do not advance the cursor and do not persist-as-synced; the tree is+ // saved for local consistency and the same cursor is retried next cycle. val pulled = OfficeSync.pullDocActions(docId, key, cursor)+ if (pulled == null) {+ saveTree(ds, docId, tree)+ withContext(Dispatchers.Main) {+ AppMessages.show(getApplication<Application>().getString(R.string.sync_pull_failed_retrying))+ }+ return@withLock+ } for (item in pulled.items) { applySignedOp(tree, item) }@@ -427,11 +476,16 @@ fun OfficeViewModel.openOnlineDocument(meta: OfficeDocMeta) { index.values.toList()) } } val cursor = ds.getLong("crdtCursor:${meta.docId}")?.toInt() ?: 0+ // Pull failure (null): open from the locally stored tree and do+ // NOT advance the cursor — the same ops are pulled again next+ // sync instead of being silently skipped as if confirmed empty. val pulled = OfficeSync.pullDocActions(meta.docId, key, cursor)- for (item in pulled.items) {- applySignedOp(crdt, item)+ if (pulled != null) {+ for (item in pulled.items) {+ applySignedOp(crdt, item)+ }+ ds.setLong("crdtCursor:${meta.docId}", pulled.seq.toLong()) }- ds.setLong("crdtCursor:${meta.docId}", pulled.seq.toLong()) saveTree(ds, meta.docId, crdt) val mergedXml = crdt.render() if (mergedXml.isBlank()) {
office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncC.kt
diff --git a/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncC.kt b/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncC.ktindex ec83392be9..07a4f79409 100644--- a/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncC.kt+++ b/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelSyncC.kt@@ -98,7 +98,11 @@ internal suspend fun OfficeViewModel.fetchMembers( key: ByteArray, ownerKey: ByteArray?): List<OfficeMember> { if (ownerKey == null) return emptyList()+ // Pull failure (null) degrades to an empty roster here: this is a+ // tolerant read, and callers re-fetch on the next sync. It must not be+ // confused with the doc-channel path, which propagates failure. val res = OfficeSync.pullDocActions("members:$docId", key, 0)+ ?: run { currentMembers.clear(); return emptyList() } val byId = LinkedHashMap<String, OfficeMember>() for (item in res.items) { val sm = runCatching { syncJson.decodeFromString<SignedMember>(item) }.getOrNull()@@ -272,7 +276,8 @@ fun OfficeViewModel.transferOwnership(memberId: String, onResult: (Boolean) -> U /** Reads the latest owner-signed document title, if the owner ever renamed it. */ internal suspend fun OfficeViewModel.fetchTitle(docId: String, key: ByteArray, ownerKey: ByteArray?): String? { if (ownerKey == null) return null- val res = OfficeSync.pullDocActions("title:$docId", key, 0)+ // Pull failure (null) means "unknown", same as no signed title here.+ val res = OfficeSync.pullDocActions("title:$docId", key, 0) ?: return null var latest: String? = null for (item in res.items) { val st = runCatching { syncJson.decodeFromString<SignedTitle>(item) }.getOrNull() ?: continue
office/src/main/java/com/vayunmathur/office/sync/OfficeSync.kt
diff --git a/office/src/main/java/com/vayunmathur/office/sync/OfficeSync.kt b/office/src/main/java/com/vayunmathur/office/sync/OfficeSync.ktindex 838335a5b8..da298b97a5 100644--- a/office/src/main/java/com/vayunmathur/office/sync/OfficeSync.kt+++ b/office/src/main/java/com/vayunmathur/office/sync/OfficeSync.kt@@ -88,8 +88,16 @@ object OfficeSync { return append(docId, blobs) } - suspend fun pullDocActions(docId: String, key: ByteArray, since: Int): DocActionsResult {- val p = pull(docId, since) ?: return DocActionsResult(emptyList(), since)+ /**+ * Pulls doc actions since [since], or returns null on transport/HTTP+ * failure. Null is deliberately distinct from an empty success: callers+ * must not advance their cursor, persist-as-synced, or treat "no news"+ * as confirmed when the relay never answered. Individual undecryptable+ * items in a successful batch are still skipped (one bad blob must not+ * drop the batch).+ */+ suspend fun pullDocActions(docId: String, key: ByteArray, since: Int): DocActionsResult? {+ val p = pull(docId, since) ?: return null val items = p.actions.mapNotNull { b -> runCatching { E2ee.aesDecrypt(key, Base64.decode(b)).decodeToString() } .getOrNull()
office/src/main/java/com/vayunmathur/office/ui/DocumentScreen.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/DocumentScreen.kt b/office/src/main/java/com/vayunmathur/office/ui/DocumentScreen.ktindex aa94efd7ee..2a2b1640dd 100644--- a/office/src/main/java/com/vayunmathur/office/ui/DocumentScreen.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/DocumentScreen.kt@@ -1,15 +1,22 @@ package com.vayunmathur.office.ui import androidx.activity.ComponentActivity+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.Modifier+import androidx.compose.ui.input.key.onPreviewKeyEvent import com.vayunmathur.library.ui.DrawerValue+import com.vayunmathur.library.ui.EditorFormat import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.odf.OdfDocument import com.vayunmathur.library.ui.rememberDrawerState import com.vayunmathur.office.platform.OfficeViewModel+import com.vayunmathur.office.platform.needsSaveAs import com.vayunmathur.office.platform.runParagraphIndexAt+import com.vayunmathur.office.platform.save /** * Error body for a document that failed to load: see DocumentScreenShell.@@ -45,6 +52,45 @@ fun DocumentScreen( onPickImageBytes = rememberImagePickerHandler( document, viewModel, focusedPara, sel.activeSlide, sel.activeCell)) + // Desktop shortcuts at the editor root (preview phase, like the code editor's+ // root handler): Ctrl/Meta+S saves, Ctrl/Meta+B/I toggle the format the bottom+ // bar's formatter for the active target would toggle. Suppressed while any+ // dialog/menu overlay is open. Online documents sync live, so Save mirrors+ // the top-bar SaveAction, which only exists offline.+ val anyOverlayOpen = s.anyDialogOpen() || s.fileMenu || s.exportMenu || s.insertMenu || s.viewMenu+ fun toggleFormat(format: EditorFormat): Boolean {+ val formatter: com.vayunmathur.library.ui.EditorFormatter? = when {+ chrome.isTextDoc && sel.activeRunStart >= 0 -> TextRunFormatter(+ viewModel, sel.activeRunStart, sel.activeRunEnd, sel.selStart, sel.selEnd, enabled = true)+ chrome.isSpreadsheet && sel.activeCell != null -> sel.activeCell?.let { (sheet, row, col) ->+ CellFormatter(viewModel, sheet, row, col, enabled = true)+ }+ chrome.isPresentation && sel.activeSlideEl >= 0 ->+ SlideFormatter(viewModel, sel.activeSlide, sel.activeSlideEl, enabled = true)+ else -> null+ }+ formatter?.toggle(format)+ return formatter != null+ }+ Box(+ Modifier.fillMaxSize().onPreviewKeyEvent { event ->+ handleOfficeDocumentKey(+ event = event,+ dialogOpen = anyOverlayOpen,+ onSave = {+ if (chrome.isOnline) {+ false+ } else {+ if (viewModel.needsSaveAs()) launchers.saveAs.launch(chrome.saveAsName)+ else viewModel.save()+ true+ }+ },+ onToggleBold = { toggleFormat(EditorFormat.BOLD) },+ onToggleItalic = { toggleFormat(EditorFormat.ITALIC) },+ )+ },+ ) { DocumentDrawerShell( s = s, document = document,@@ -69,6 +115,7 @@ fun DocumentScreen( onBack = onBack, onBecameOnline = onBecameOnline, )+ } } /** Run-selection + shell sections: see DocumentScreenChrome / DocumentScreenShell. */
office/src/main/java/com/vayunmathur/office/ui/OfficeDocumentKeys.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/OfficeDocumentKeys.kt b/office/src/main/java/com/vayunmathur/office/ui/OfficeDocumentKeys.ktnew file mode 100644index 0000000000..de6a72a29e--- /dev/null+++ b/office/src/main/java/com/vayunmathur/office/ui/OfficeDocumentKeys.kt@@ -0,0 +1,49 @@+package com.vayunmathur.office.ui++import androidx.compose.ui.input.key.Key+import androidx.compose.ui.input.key.KeyEvent+import androidx.compose.ui.input.key.KeyEventType+import androidx.compose.ui.input.key.isCtrlPressed+import androidx.compose.ui.input.key.isMetaPressed+import androidx.compose.ui.input.key.key+import androidx.compose.ui.input.key.type++/**+ * Desktop keyboard shortcuts for the document editor, following the `code` editor's+ * `handleEditorKey` pattern: only key-down events, triggered by Ctrl or Meta (the+ * latter is Cmd on macOS-style keyboards / the super key in desktop windows), and+ * never while a dialog or menu overlay is open — a modal owns its keys.+ *+ * Each action returns true when it actually did something (e.g. a formatting+ * target is selected); a shortcut whose action declines is left unconsumed so the+ * focused field keeps its default handling.+ */+internal fun handleOfficeDocumentKey(+ event: KeyEvent,+ dialogOpen: Boolean,+ onSave: () -> Boolean,+ onToggleBold: () -> Boolean,+ onToggleItalic: () -> Boolean,+): Boolean {+ if (event.type != KeyEventType.KeyDown || dialogOpen) return false+ if (!event.isCtrlPressed && !event.isMetaPressed) return false+ return when (event.key) {+ Key.S -> onSave()+ Key.B -> onToggleBold()+ Key.I -> onToggleItalic()+ else -> false+ }+}++/** True while any hoisted dialog/crop/export overlay of the document screen is showing. */+internal fun DocumentOverlayState.anyDialogOpen(): Boolean =+ showMetadata || showShareDialog || showEnableOnlineDialog || showUnsavedDialog ||+ showSettings || showColorPicker || showFontSizePicker || showInsertTable ||+ showInsertLink || showAddBookmark || showSpecialChars || showFootnote ||+ showComment || showComments || showChanges || showPageSetup || showHeaderFooter ||+ showCellTextColor || showCellBgColor || showCellBorderColor ||+ showSlideTextColor || showSlideFillColor || showSlideStrokeColor ||+ showCellComment || showCellResize || showSlideNotes || showSlideBackground ||+ showSlideTransition || showChartEditor ||+ cropImageBlock >= 0 || cropSlideTarget != null || cropSheetTarget != null ||+ exportWarning != null
office/src/main/res/values/strings.xml
diff --git a/office/src/main/res/values/strings.xml b/office/src/main/res/values/strings.xmlindex f0952ca14b..eb7c70009f 100644--- a/office/src/main/res/values/strings.xml+++ b/office/src/main/res/values/strings.xml@@ -223,6 +223,10 @@ <string name="join_request_sent">Request sent — you\'ll get access once the owner approves.</string> <!-- MainActivity: Toast when a join request could not be delivered. Sentence --> <string name="join_request_failed">Couldn\'t send request — check your connection and try again.</string>+ <!-- Sync: Message when pushing local edits failed; they are kept and retried. Sentence -->+ <string name="sync_push_failed_retrying">Couldn\'t send your changes — they\'re saved on this device and will be retried.</string>+ <!-- Sync: Message when pulling collaborators' edits failed; will retry. Sentence -->+ <string name="sync_pull_failed_retrying">Couldn\'t check for collaborators\' changes — will retry.</string> <!-- MainActivity: Menu image with ellipsis --> <string name="image_1">Image…</string> <!-- MainActivity: Menu insert time field -->
office/src/test/java/com/vayunmathur/office/platform/OfficeViewModelSyncSlice3Test.kt
diff --git a/office/src/test/java/com/vayunmathur/office/platform/OfficeViewModelSyncSlice3Test.kt b/office/src/test/java/com/vayunmathur/office/platform/OfficeViewModelSyncSlice3Test.ktindex 9bbec48876..d4bf67c5f2 100644--- a/office/src/test/java/com/vayunmathur/office/platform/OfficeViewModelSyncSlice3Test.kt+++ b/office/src/test/java/com/vayunmathur/office/platform/OfficeViewModelSyncSlice3Test.kt@@ -235,11 +235,34 @@ class OfficeViewModelSyncSlice3Test { val tree = DocumentTreeCrdt("dev-sync") v.currentTree = tree v.syncDoc("doc-sync-1", key)- // Tree was persisted under the doc id and renders the local text.+ // Offline: the append fails, so the tree is still persisted for local+ // consistency and renders the local text, but the ops are kept in the+ // persisted pending list for the next cycle and the cursor is NOT+ // advanced/persisted-as-synced (no crdtCursor write at all). val stored = realDs().getString("crdt:doc-sync-1") assertNotNull(stored) assertTrue(tree.render().contains("synced text"), tree.render())- assertEquals(0L, realDs().getLong("crdtCursor:doc-sync-1") ?: -1L)+ assertNull(realDs().getLong("crdtCursor:doc-sync-1"))+ val pending = v.loadPendingOps(realDs(), "doc-sync-1")+ assertEquals(1, pending.size, "un-acked ops must stay pending: $pending")+ assertTrue(pending[0].contains("synced text") || pending[0].isNotBlank(), pending[0])+ }++ @Test+ fun `syncDoc retries pending ops verbatim on next cycle`() = runTest {+ val v = loadedVm("retry text")+ val key = ByteArray(32) { it.toByte() }+ v.currentRole = OfficeRoles.EDITOR+ val tree = DocumentTreeCrdt("dev-retry")+ v.currentTree = tree+ // Two offline cycles: the diff is absorbed by the tree after cycle 1+ // (updateJson would return "[]" for the same text), yet cycle 2 must+ // still attempt the pending batch — exactly one entry, not duplicated.+ v.syncDoc("doc-sync-retry", key)+ v.syncDoc("doc-sync-retry", key)+ val pending = v.loadPendingOps(realDs(), "doc-sync-retry")+ assertEquals(1, pending.size, "pending must not duplicate or vanish: $pending")+ assertNull(realDs().getLong("crdtCursor:doc-sync-retry")) } @Test
office/src/test/java/com/vayunmathur/office/platform/Slice4Pass2SyncNetworkTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/platform/Slice4Pass2SyncNetworkTest.kt b/office/src/test/java/com/vayunmathur/office/platform/Slice4Pass2SyncNetworkTest.ktindex 57767506fc..735394051b 100644--- a/office/src/test/java/com/vayunmathur/office/platform/Slice4Pass2SyncNetworkTest.kt+++ b/office/src/test/java/com/vayunmathur/office/platform/Slice4Pass2SyncNetworkTest.kt@@ -11,6 +11,7 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotEquals+import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue @@ -51,8 +52,9 @@ class Slice4Pass2SyncNetworkTest { installFake { _, _ -> null } val key = OfficeSync.newDocumentKey() assertNull(OfficeSync.getKey("device-x"))- assertEquals(emptyList(), OfficeSync.pullDocActions("doc1", key, 7).items)- assertEquals(7, OfficeSync.pullDocActions("doc1", key, 7).seq)+ // Pull failure is null (propagated), NOT an empty result at the old+ // seq — callers must not advance cursors or persist-as-synced on it.+ assertNull(OfficeSync.pullDocActions("doc1", key, 7)) assertNull(OfficeSync.appendDocActions("doc1", key, listOf("op"))) assertNull(OfficeSync.append("chan", listOf("blob"))) assertNull(OfficeSync.pull("chan", 3))@@ -87,6 +89,7 @@ class Slice4Pass2SyncNetworkTest { // Garbage action in the batch is skipped, the valid one decrypts. val pulled = OfficeSync.pullDocActions("doc1", key, 0)+ assertNotNull(pulled) assertEquals(listOf("hello op"), pulled.items) assertEquals(9, pulled.seq)
office/src/test/java/com/vayunmathur/office/ui/OfficeDocumentKeysTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/ui/OfficeDocumentKeysTest.kt b/office/src/test/java/com/vayunmathur/office/ui/OfficeDocumentKeysTest.ktnew file mode 100644index 0000000000..6096c4d0e8--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/ui/OfficeDocumentKeysTest.kt@@ -0,0 +1,85 @@+package com.vayunmathur.office.ui++import android.view.KeyEvent as AndroidKeyEvent+import androidx.compose.ui.input.key.KeyEvent+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Direct tests for [handleOfficeDocumentKey] and [DocumentOverlayState.anyDialogOpen]. */+@RunWith(RobolectricTestRunner::class)+class OfficeDocumentKeysTest {++ private class Sink {+ var saved = 0+ var bold = 0+ var italic = 0+ var boldResult = true+ }++ private fun event(keyCode: Int, meta: Int = 0, action: Int = AndroidKeyEvent.ACTION_DOWN): KeyEvent =+ KeyEvent(AndroidKeyEvent(0L, 0L, action, keyCode, 0, meta))++ private fun handle(e: KeyEvent, dialogOpen: Boolean = false, sink: Sink = Sink()): Pair<Boolean, Sink> {+ val handled = handleOfficeDocumentKey(+ event = e,+ dialogOpen = dialogOpen,+ onSave = { sink.saved++; true },+ onToggleBold = { sink.bold++; sink.boldResult },+ onToggleItalic = { sink.italic++; true },+ )+ return handled to sink+ }++ private val ctrl = AndroidKeyEvent.META_CTRL_ON+ private val meta = AndroidKeyEvent.META_META_ON++ @Test+ fun ctrlAndMetaSave() {+ val v = event(AndroidKeyEvent.KEYCODE_S, ctrl)+ assertTrue(handle(v).first)+ assertEquals(1, handle(v).second.saved)+ assertEquals(1, handle(event(AndroidKeyEvent.KEYCODE_S, meta)).second.saved)+ }++ @Test+ fun ctrlAndMetaBoldItalic() {+ assertEquals(1, handle(event(AndroidKeyEvent.KEYCODE_B, ctrl)).second.bold)+ assertEquals(1, handle(event(AndroidKeyEvent.KEYCODE_I, meta)).second.italic)+ }++ @Test+ fun decliningActionIsNotConsumed() {+ val sink = Sink().apply { boldResult = false }+ assertFalse(handle(event(AndroidKeyEvent.KEYCODE_B, ctrl), sink = sink).first)+ assertEquals(1, sink.bold)+ }++ @Test+ fun dialogOpenBlocksAllShortcuts() {+ val (handled, sink) = handle(event(AndroidKeyEvent.KEYCODE_S, ctrl), dialogOpen = true)+ assertFalse(handled)+ assertEquals(0, sink.saved)+ }++ @Test+ fun plainUnknownAndKeyUpAreNotHandled() {+ assertFalse(handle(event(AndroidKeyEvent.KEYCODE_B)).first)+ assertFalse(handle(event(AndroidKeyEvent.KEYCODE_X, ctrl)).first)+ assertFalse(handle(event(AndroidKeyEvent.KEYCODE_S, ctrl, AndroidKeyEvent.ACTION_UP)).first)+ }++ @Test+ fun anyDialogOpenReflectsOverlayFlags() {+ val state = DocumentScreenState()+ assertFalse(state.anyDialogOpen())+ state.showComment = true+ assertTrue(state.anyDialogOpen())+ state.showComment = false+ state.cropSlideTarget = 0 to 1+ assertTrue(state.anyDialogOpen())+ }+}