From 02bd8d5d20c15c88a1c6a89eb61fc9d45156f1b6 Mon Sep 17 00:00:00 2001 From: Anindra Date: Fri, 4 Dec 2026 00:17:50 +0530 Subject: [PATCH] fix(#604): a restore keeps its read state and blocklist, nudges expire MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The merge import added one unread per inserted message on top of the conversation's restored unread_count, so a thread with 80 read messages came back as 80 unread. Read state is one number per conversation, so RestoreUnread.toAdd() adds nothing to a conversation the backup inserted whole and at most the backup's unread count — never more than the messages the merge actually inserted — to one it merged into. The merge never read conversations.blocked, so a restored blocked sender landed in the Inbox while its blocklist row was copied. Both columns are carried now through an adaptive conversation SELECT, because blocking postdates soft delete and an older backup has neither column, and a blocked conversation the merge creates also reaches the blocklist. The in-process block cache is cleared after either import mode. The reply nudge had a lower age bound and no ceiling, so enabling it surfaced every old unanswered thread. Past a week the message is history; the policy and the row query share one constant. Tests: RestoreUnreadTest, LegacyBackupSchemaTest and ReplyNudgePolicyTest. Scripts test-restore-state.sh (12/12) and test-reply-nudge.sh (14/14) on emulator-5558. The Trash behaviour is unchanged. --- .../anindra/messages/data/ReplyNudgePolicy.kt | 17 +++- .../com/anindra/messages/data/Repository.kt | 82 ++++++++++++---- .../anindra/messages/data/RestoreUnread.kt | 29 ++++++ .../com/anindra/messages/data/SmsIeBackup.kt | 31 ++++++ .../messages/data/LegacyBackupSchemaTest.kt | 28 ++++++ .../messages/data/ReplyNudgePolicyTest.kt | 30 ++++++ .../messages/data/RestoreUnreadTest.kt | 97 +++++++++++++++++++ scripts | 2 +- 8 files changed, 296 insertions(+), 20 deletions(-) create mode 100644 app/src/main/java/com/anindra/messages/data/RestoreUnread.kt create mode 100644 app/src/test/java/com/anindra/messages/data/RestoreUnreadTest.kt diff --git a/app/src/main/java/com/anindra/messages/data/ReplyNudgePolicy.kt b/app/src/main/java/com/anindra/messages/data/ReplyNudgePolicy.kt index 61e8bc883..5c5884f62 100644 --- a/app/src/main/java/com/anindra/messages/data/ReplyNudgePolicy.kt +++ b/app/src/main/java/com/anindra/messages/data/ReplyNudgePolicy.kt @@ -37,6 +37,17 @@ object ReplyNudgePolicy { /** A nudge per conversation per day at most, even if the thread stays open. */ const val REPEAT_HOURS = 24L + /** + * Past this age the thread is history, not a reply still owed (#604). + * + * The rule above only says how long to wait before reminding, so without a + * ceiling every read-but-unanswered conversation ever — including one from + * three months ago — came due on the first run with the switch on. + */ + const val MAX_AGE_HOURS = 24 * 7 + + val MAX_AGE_MILLIS: Long = MAX_AGE_HOURS * HOUR_MILLIS + fun intervalMillis(hours: Int): Long = hours.coerceIn(1, 24 * 7).toLong() * HOUR_MILLIS @@ -45,7 +56,8 @@ object ReplyNudgePolicy { muted: Boolean, lastNudgedAt: Long, now: Long, - intervalMillis: Long + intervalMillis: Long, + maxAgeMillis: Long = MAX_AGE_MILLIS ): Boolean { // A thread whose newest message is ours is answered by definition. if (row.lastIsMine) return false @@ -55,6 +67,9 @@ object ReplyNudgePolicy { if (row.newest <= 0L) return false // Not old enough yet: the reply may still be on its way. if (now - row.newest < intervalMillis) return false + // Too old to be a reminder: the moment has passed, and a card for it is + // noise rather than a nudge. + if (now - row.newest > maxAgeMillis) return false if (lastNudgedAt > 0 && now - lastNudgedAt < REPEAT_HOURS * HOUR_MILLIS) return false return true } diff --git a/app/src/main/java/com/anindra/messages/data/Repository.kt b/app/src/main/java/com/anindra/messages/data/Repository.kt index d54c7e63b..22bdde5ba 100644 --- a/app/src/main/java/com/anindra/messages/data/Repository.kt +++ b/app/src/main/java/com/anindra/messages/data/Repository.kt @@ -2917,13 +2917,16 @@ class Repository(private val context: Context) { */ fun replyNudgeRowsBlocking(): List { val out = mutableListOf() + // The policy owns the age ceiling; this only keeps a long history from + // being loaded to reach it. + val oldest = System.currentTimeMillis() - ReplyNudgePolicy.MAX_AGE_MILLIS db.readableDatabase.rawQuery( """SELECT id,address,snippet,timestamp,last_is_me,unread_count,archived,blocked,deleted_at FROM conversations WHERE deleted_at=0 AND archived=0 AND blocked=0 - AND unread_count=0 AND last_is_me=0 + AND unread_count=0 AND last_is_me=0 AND timestamp>=? ORDER BY timestamp DESC""", - null + arrayOf(oldest.toString()) ).use { c -> while (c.moveToNext()) { out.add( @@ -3805,6 +3808,8 @@ class Repository(private val context: Context) { return ImportResult.Error("Failed to replace database file", attempts) } db = Db(context) + // The swapped file carries its own blocklist. + blockedCache.clear() // A restored backup should be fully visible: lift any // conversations that were in the trash when the backup was made, // and keep them out of the Archive for the same reason (#405). @@ -3986,16 +3991,29 @@ class Repository(private val context: Context) { val convoMap = HashMap() // Newest message per live conversation, refreshed only when merged rows are newer val newest = HashMap>() - // Restored incoming messages make the conversation unread (like a fresh receive) - val unreadBump = HashMap() + // Merging rows into a conversation already on this device must not + // make the whole thread unread again (#604); RestoreUnread decides + // how much of the backup's unread count is still genuinely new. + val restoredUnread = HashMap() + val createdConversations = HashSet() + val inboundAdded = HashMap() + // Blocked conversations restored before the blocklist table existed + // still have to show up on the Blocklist screen. + val restoredBlocks = ArrayList>() target.beginTransaction() try { - backup.rawQuery( - """SELECT id,address,name,snippet,timestamp,unread_count,last_is_me, - archived,pinned,draft,draft_date,deleted_at FROM conversations""", null - ).use { c -> + val conversationColumns = mutableSetOf() + backup.rawQuery("PRAGMA table_info(conversations)", null).use { columns -> + while (columns.moveToNext()) conversationColumns.add(columns.getString(1)) + } + val conversationQuery = LegacyBackupSchema.conversationsQuery(conversationColumns) + backup.rawQuery(conversationQuery, null).use { c -> while (c.moveToNext()) { val address = c.getString(1) + val blocked = c.getInt(LegacyBackupSchema.BLOCKED_INDEX) == 1 + val blockedAt = c.getLong(LegacyBackupSchema.BLOCKED_AT_INDEX) + .takeIf { it > 0 } ?: c.getLong(4) + var isNew = false val tId: Long = if (existing.contains(address)) { conflicts.count(Conflict.CONVERSATION_MERGED) @@ -4009,7 +4027,7 @@ class Repository(private val context: Context) { mergedId } else { existing.add(address) - target.insert( + val inserted = target.insert( "conversations", null, ContentValues().apply { put("address", address) @@ -4024,12 +4042,23 @@ class Repository(private val context: Context) { put("draft_date", c.getLong(10)) // 0: lift conversations trashed in the backup put("deleted_at", 0) + // Same: a restored blocked sender belongs + // under Spam & blocked, not in the inbox. + put("blocked", if (blocked) 1 else 0) + put("blocked_at", if (blocked) blockedAt else 0L) } ) + if (inserted > 0) isNew = true + inserted } } if (tId == -1L) continue convoMap[c.getLong(0)] = tId + restoredUnread[tId] = c.getInt(5) + if (isNew) { + createdConversations.add(tId) + if (blocked) restoredBlocks.add(address to blockedAt) + } } } @@ -4103,7 +4132,7 @@ class Repository(private val context: Context) { conflicts.count(Conflict.RECORD_UNREADABLE) } if (isMe == 0) { - unreadBump[tId] = (unreadBump[tId] ?: 0) + 1 + inboundAdded[tId] = (inboundAdded[tId] ?: 0) + 1 } val snippet = when (m.getString(5)) { "text" -> body @@ -4124,21 +4153,35 @@ class Repository(private val context: Context) { ) } - for ((tId, n) in unreadBump) { + for ((tId, incoming) in inboundAdded) { + val extra = RestoreUnread.toAdd( + conversationCreated = tId in createdConversations, + backupUnread = restoredUnread[tId] ?: 0, + incomingAdded = incoming + ) + if (extra <= 0) continue target.execSQL( "UPDATE conversations SET unread_count=unread_count+? WHERE id=?", - arrayOf(n, tId) + arrayOf(extra, tId) ) } - backup.rawQuery("SELECT number,timestamp FROM blocked_numbers", null).use { c -> - while (c.moveToNext()) { - target.execSQL( - "INSERT OR IGNORE INTO blocked_numbers(number,timestamp) VALUES(?,?)", - arrayOf(c.getString(0), c.getLong(1)) - ) + if (backupHasTable(backup, "blocked_numbers")) { + backup.rawQuery("SELECT number,timestamp FROM blocked_numbers", null).use { c -> + while (c.moveToNext()) { + target.execSQL( + "INSERT OR IGNORE INTO blocked_numbers(number,timestamp) VALUES(?,?)", + arrayOf(c.getString(0), c.getLong(1)) + ) + } } } + for ((address, at) in restoredBlocks) { + target.execSQL( + "INSERT OR IGNORE INTO blocked_numbers(number,timestamp) VALUES(?,?)", + arrayOf(address, at) + ) + } // conversation_notifications arrived after v8, so a backup from an // older build simply does not have the table. Per-conversation @@ -4178,6 +4221,9 @@ class Repository(private val context: Context) { target.endTransaction() } } + // Blocked numbers can arrive from the backup; a cached "not blocked" + // would let the next message from one of them through. + blockedCache.clear() return MergeReport(added, conflicts) } diff --git a/app/src/main/java/com/anindra/messages/data/RestoreUnread.kt b/app/src/main/java/com/anindra/messages/data/RestoreUnread.kt new file mode 100644 index 000000000..730685857 --- /dev/null +++ b/app/src/main/java/com/anindra/messages/data/RestoreUnread.kt @@ -0,0 +1,29 @@ +package com.anindra.messages.data + +/** + * How many unread messages a merge should add to a conversation it already had + * (#604). + * + * The database has no per-message read flag: read state lives in one number per + * conversation, `unread_count`, and the messages it covers are that thread's + * newest incoming ones. So a backup's read state is that number, and it must be + * carried — not re-derived by marking every restored message unread, which is + * what turned an 80-message thread into 80 unread after a restore. + */ +object RestoreUnread { + + /** + * @param conversationCreated the row was inserted from the backup, so it + * already carries the backup's `unread_count` verbatim and needs nothing + * added. + * @param backupUnread the conversation's `unread_count` in the backup. + * @param incomingAdded incoming messages this merge actually inserted; + * some of the backup's unread ones may already have been on this device. + * + * A merge can only add what the backup could still account for: at most its + * unread count, and at most the messages it actually inserted. + */ + fun toAdd(conversationCreated: Boolean, backupUnread: Int, incomingAdded: Int): Int = + if (conversationCreated) 0 + else minOf(backupUnread.coerceAtLeast(0), incomingAdded.coerceAtLeast(0)) +} diff --git a/app/src/main/java/com/anindra/messages/data/SmsIeBackup.kt b/app/src/main/java/com/anindra/messages/data/SmsIeBackup.kt index d5728bb5f..6e412e987 100644 --- a/app/src/main/java/com/anindra/messages/data/SmsIeBackup.kt +++ b/app/src/main/java/com/anindra/messages/data/SmsIeBackup.kt @@ -281,6 +281,33 @@ object LegacyBackupSchema { return "SELECT $select FROM messages $where ORDER BY timestamp" } + /** + * Absent in backups older than the blocklist. Blocking arrived after soft + * delete, so a backup can have `deleted_at` and still no `blocked` — the + * reason the same literal trick is needed for conversations. + */ + private val OPTIONAL_CONVERSATIONS = listOf("blocked" to "0", "blocked_at" to "0") + + /** Every conversation column the merge reads, before the optional tail. */ + private val REQUIRED_CONVERSATIONS = listOf( + "id", "address", "name", "snippet", "timestamp", "unread_count", + "last_is_me", "archived", "pinned", "draft", "draft_date", "deleted_at" + ) + + /** + * The conversation merge's SELECT, shaped the same way as [messagesQuery]: + * a missing optional column becomes a constant of the right type so the + * positional reads stay put. + */ + fun conversationsQuery(available: Set): String { + val select = (REQUIRED_CONVERSATIONS + OPTIONAL_CONVERSATIONS.map { it.first }) + .joinToString(",") { column -> + if (column in available) column + else OPTIONAL_CONVERSATIONS.first { it.first == column }.second + } + return "SELECT $select FROM conversations" + } + /** * Provider ids are meaningful only on the device that issued them. * @@ -301,4 +328,8 @@ object LegacyBackupSchema { const val LOCKED_INDEX = 9 const val SUB_ID_INDEX = 10 const val TRANSPORT_INDEX = 11 + + /** Same, for [conversationsQuery]. */ + const val BLOCKED_INDEX = 12 + const val BLOCKED_AT_INDEX = 13 } diff --git a/app/src/test/java/com/anindra/messages/data/LegacyBackupSchemaTest.kt b/app/src/test/java/com/anindra/messages/data/LegacyBackupSchemaTest.kt index f75b19a5d..f9ee0cf23 100644 --- a/app/src/test/java/com/anindra/messages/data/LegacyBackupSchemaTest.kt +++ b/app/src/test/java/com/anindra/messages/data/LegacyBackupSchemaTest.kt @@ -82,6 +82,34 @@ class LegacyBackupSchemaTest { } } + /** Conversations in a backup made before blocklisting existed: soft delete + * is there, `blocked` and `blocked_at` are not. */ + private val preBlockColumns = setOf( + "id", "address", "name", "snippet", "timestamp", "unread_count", + "last_is_me", "archived", "pinned", "draft", "draft_date", "deleted_at" + ) + + @Test + fun aPreBlocklistConversationsQueryUsesLiteralsAndKeepsItsShape() { + val q = LegacyBackupSchema.conversationsQuery(preBlockColumns) + assertFalse("must not select a column the file lacks: $q", "blocked" in q) + assertTrue("blocked falls back to 0: $q", q.endsWith(",0,0 FROM conversations")) + + fun select(cols: Set) = LegacyBackupSchema.conversationsQuery(cols) + .removePrefix("SELECT ").substringBefore(" FROM") + .split(",").map { it.trim() } + + val old = select(preBlockColumns) + val now = select(preBlockColumns + setOf("blocked", "blocked_at")) + assertEquals("column count must be stable", 14, old.size) + assertEquals(14, now.size) + assertEquals("deleted_at keeps index 11", "deleted_at", old[11]) + assertEquals("blocked lands at 12", "0", old[LegacyBackupSchema.BLOCKED_INDEX]) + assertEquals("blocked_at lands at 13", "0", old[LegacyBackupSchema.BLOCKED_AT_INDEX]) + assertEquals("blocked", now[LegacyBackupSchema.BLOCKED_INDEX]) + assertEquals("blocked_at", now[LegacyBackupSchema.BLOCKED_AT_INDEX]) + } + @Test fun theGeneratedQueryActuallyRunsAgainstARealOldBackup() { // The real file is the user's, not part of the repo, so this only runs diff --git a/app/src/test/java/com/anindra/messages/data/ReplyNudgePolicyTest.kt b/app/src/test/java/com/anindra/messages/data/ReplyNudgePolicyTest.kt index ea96cff6e..d5e02f696 100644 --- a/app/src/test/java/com/anindra/messages/data/ReplyNudgePolicyTest.kt +++ b/app/src/test/java/com/anindra/messages/data/ReplyNudgePolicyTest.kt @@ -57,6 +57,36 @@ class ReplyNudgePolicyTest { ) } + @Test + fun aThreadFromMonthsAgoIsHistoryNotAReminder() { + val day = ReplyNudgePolicy.intervalMillis(24) + assertTrue( + "a week is still a reply the user meant to send", + ReplyNudgePolicy.shouldNudge(row(newest = now - 6 * 24 * hour), false, 0, now, day) + ) + assertFalse( + "three months on, the message is history and a card for it is noise (#604)", + ReplyNudgePolicy.shouldNudge(row(newest = now - 90 * 24 * hour), false, 0, now, day) + ) + assertTrue( + "the ceiling is a week", + ReplyNudgePolicy.MAX_AGE_MILLIS == 7 * 24 * hour + ) + } + + @Test + fun theQueryUsesTheSameCeilingAsThePolicy() { + val repo = src("java/com/anindra/messages/data/Repository.kt") + assertTrue( + "the prefilter must take its age from the policy, or the two drift", + repo.contains("ReplyNudgePolicy.MAX_AGE_MILLIS") + ) + assertTrue( + "a conversation older than the ceiling cannot be a nudge candidate", + Regex("""timestamp>=\?""").containsMatchIn(repo) + ) + } + @Test fun anAnsweredThreadIsNeverNudged() { assertFalse( diff --git a/app/src/test/java/com/anindra/messages/data/RestoreUnreadTest.kt b/app/src/test/java/com/anindra/messages/data/RestoreUnreadTest.kt new file mode 100644 index 000000000..c99dfff03 --- /dev/null +++ b/app/src/test/java/com/anindra/messages/data/RestoreUnreadTest.kt @@ -0,0 +1,97 @@ +package com.anindra.messages.data + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File + +/** + * #604: a restore marked every message unread, so a thread with 80 messages + * came back as 80 unread and the badge counted work the user had already done. + * + * The database keeps read state in one number per conversation — `unread_count`, + * covering its newest incoming messages — so a merged backup can only add what + * that number still accounts for. A conversation inserted whole already carries + * the number and must add nothing. + */ +class RestoreUnreadTest { + + private val main: File by lazy { + generateSequence(File("").absoluteFile) { it.parentFile } + .map { File(it, "app/src/main") } + .firstOrNull { File(it, "java").isDirectory } + ?: error("app/src/main not found") + } + + private fun src(path: String) = File(main, path).readText() + + @Test + fun aFreshConversationAddsNothingOnTopOfItsRestoredCount() { + assertEquals( + "80 messages restored with unread_count 2 must stay 2, not become 82", + 0, + RestoreUnread.toAdd(conversationCreated = true, backupUnread = 2, incomingAdded = 80) + ) + assertEquals( + "a fully read thread restores fully read", + 0, + RestoreUnread.toAdd(conversationCreated = true, backupUnread = 0, incomingAdded = 80) + ) + } + + @Test + fun aMergedThreadOnlyGainsWhatTheBackupStillHeldUnread() { + assertEquals( + "three unread in the backup are three messages, not fifty", + 3, + RestoreUnread.toAdd(conversationCreated = false, backupUnread = 3, incomingAdded = 50) + ) + assertEquals( + "a read backup adds nothing to an existing unread count", + 0, + RestoreUnread.toAdd(conversationCreated = false, backupUnread = 0, incomingAdded = 50) + ) + assertEquals( + "no more than the messages this merge actually inserted", + 2, + RestoreUnread.toAdd(conversationCreated = false, backupUnread = 9, incomingAdded = 2) + ) + } + + @Test + fun nonsenseInputsCannotInventUnread() { + assertEquals(0, RestoreUnread.toAdd(false, backupUnread = -4, incomingAdded = 10)) + assertEquals(0, RestoreUnread.toAdd(false, backupUnread = 5, incomingAdded = -1)) + } + + @Test + fun theMergeCarriesReadStateAndBlockedSenders() { + val repo = src("java/com/anindra/messages/data/Repository.kt") + assertTrue( + "the unread decision has to be the one place the merge adds unread", + Regex("""RestoreUnread\.toAdd\([\s\S]{0,220}?conversationCreated = tId in createdConversations""") + .containsMatchIn(repo) + ) + assertFalse( + "bumping one unread per restored message is the bug this replaces", + repo.contains("unreadBump") + ) + assertTrue( + "a restored blocked conversation must stay blocked", + Regex("""put\("blocked", if \(blocked\) 1 else 0\)""").containsMatchIn(repo) + ) + assertTrue( + "and keep the moment it was blocked, for retention", + Regex("""put\("blocked_at", if \(blocked\) blockedAt else 0L\)""").containsMatchIn(repo) + ) + assertTrue( + "the columns are optional, because blocking postdates soft delete", + repo.contains("LegacyBackupSchema.conversationsQuery(conversationColumns)") + ) + assertTrue( + "a restored blocked sender has to reach the blocklist screen too", + Regex("""for \(\(address, at\) in restoredBlocks\)""").containsMatchIn(repo) + ) + } +} diff --git a/scripts b/scripts index a8eb2e37f..3559cf490 160000 --- a/scripts +++ b/scripts @@ -1 +1 @@ -Subproject commit a8eb2e37fb5a82afce3b646abc861062b508e5af +Subproject commit 3559cf49081631bb220d80be82c4fed3442d231e