Skip to content

Commit 298543f

Browse files
browstudio
andauthored
fix(mobile): report a push wake claim it stopped waiting for (#9931)
## What An Android push wake that runs out of time can leave a claim still running. If that claim then wins, the message is recorded as shown but was never returned. No later wake finds it, so the user is never told. This makes the wake report that case, and the native handler shows its generic notification for it. - `resolvePushWake` tracks the message each community is claiming. After the claim grace it sets `PushWakeResult.unreported` when a claim is still running for a message with something to show (a message whose body is empty would not be returned anyway). It is read in the same synchronous step as the claimed-message snapshot, so a claim that finishes before the snapshot is returned, and one that finishes after it is counted. - `PushWakeRunner` reports `unreported` when any pass does, because a message lost in one pass stays lost. - The channel payload carries `unreported`. The native handler posts the named notifications, and the generic notification beside them, silently when something already alerted. If the user already cleared the generic card this wake posted at 2 seconds, it stays cleared. The generic is marked as standing in for a lost message, so later wakes, which clear an unmarked generic as before, leave it until the user clears it. A later wake that re-posts the generic keeps the mark. - It stays separate from `incomplete`, which means a later wake retries. Folding the two would show the generic beside named notifications on every retryable partial wake. - `ShownMessageStore.claim` documents that a caller that stops waiting for a claim must report it. A claim that later returns false still costs one unnecessary generic notification, which is accepted. The realistic trigger is storage that stalls after the claim marker is created, during the watermark and prune I/O in `DirectoryShownMessageStore.claim` (a pre-existing finding from the review of the Android wake handler). The store's order is unchanged. The marker has to come first for atomicity, and this signal turns the stall into a generic notification instead of silence. ## Validation - The push-wake journey test's stalled-storage step now asserts `unreported`, and a stalled claim for a message with an empty body asserts it is not set. A wake cut short in the name lookup, outside any claim, asserts it is not set and still returns its messages. The runner step asserts that a message lost in one pass is still reported after a clean rerun. The channel payload test covers both values. - Forcing the signal off fails the stalled-storage step. - `WakeNotifierGenericTest` (instrumented) drives the generic notification against the real notification manager on a Pixel 9a: an unmarked card clears on a clean wake, a kept card survives clean wakes and a later 2-second re-post, and a card the user cleared before the result is not posted again. Each step waits for the state it expects, a re-post check waits for a newer post, and checks that nothing changed run after a barrier notification. Its two updates wait 700 ms first, so Android's update rate limit can't drop them on quick reruns (12 back-to-back runs passed). Removing the cleared-card check, or dropping the mark on re-post, fails it. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
1 parent 309f582 commit 298543f

11 files changed

Lines changed: 294 additions & 18 deletions

File tree

‎PLANS/ANDROID_PUSH.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,10 +83,10 @@ Decisions recorded as ADRs: [0004](../docs/adr/0004-push-gateway-hides-device-pl
8383

8484
**Mobile, Android native**
8585

86-
- A Firebase messaging service receives the wake. When the app is in the foreground (a native lifecycle check), it does nothing: the running app already shows new messages. Otherwise it starts a background Flutter engine running the wake-to-notification entrypoint and posts the result directly. The category is known only after the fetch, so no notification is posted before it. If nothing has been posted after about 2 s, it posts a generic "New activity" notification in a third "Other" category, which the real result replaces silently, and which is removed when the result is that there is nothing to show. A native watchdog finishes the work inside the platform's time limit even if Dart never answers.
86+
- A Firebase messaging service receives the wake. When the app is in the foreground (a native lifecycle check), it does nothing: the running app already shows new messages. Otherwise it starts a background Flutter engine running the wake-to-notification entrypoint and posts the result directly. The category is known only after the fetch, so no notification is posted before it. If nothing has been posted after about 2 s, it posts a generic "New activity" notification in a third "Other" category, which the real result replaces silently, and which is removed when the result is that there is nothing to show. When the result reports a message it claimed but could not return, the generic notification stays, beside the named notifications, and later wakes leave it. A native watchdog finishes the work inside the platform's time limit even if Dart never answers.
8787
- FCM token registration and rotation feed the same enrollment and endpoint-rotation flow iOS uses.
8888
- The app generates an Android Keystore key with the gateway's challenge and sends its attestation chain at enrollment.
89-
- Notification categories are "Direct messages", "Mentions" and "Other" (only the slow-fetch generic notification). Notifications use the platform's messaging style, grouped per conversation. A tap opens the conversation through the app's existing deep-link handling.
89+
- Notification categories are "Direct messages", "Mentions" and "Other" (only the generic notification, for a slow fetch or a message claimed but not returned). Notifications use the platform's messaging style, grouped per conversation. A tap opens the conversation through the app's existing deep-link handling.
9090
- The Android 13+ notification permission prompt appears at the same point iOS asks.
9191
- Firebase configuration is a build-time setting supplied by each distributor, never committed.
9292

‎docs/adr/0006-android-notifications-run-app-dart-code.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
On iOS, a native Swift notification service extension fetches and formats each notification. On Android, the push handler instead starts the app's Dart code in a background engine, without the UI, and that code fetches the message from the relay and builds the notification. This reuses the app's relay, sign-in and formatting code rather than porting the iOS extension to Kotlin. A prototype showed it fits Android's time limit for handling a push: on an emulator, the real text appeared about 0.1 s after a cold wake, and about 1 s with the CPU slowed 8x, against a budget of about 10 s.
44

5-
The handler posts the fetched notifications directly, because the category (and so the channel the user may have silenced) is known only after the fetch. If nothing is posted within about 2 s, it posts a generic notification in a separate "Other" category, which the real result replaces silently. A slow or failed fetch therefore still leaves a visible notification, and Android deprioritizes apps whose high-priority pushes show nothing. While the app is in the foreground the handler does nothing. Unlike the iOS extension, which can only rewrite the push it was handed, the handler posts every eligible unshown message it finds, grouped per conversation, so a wake means "sync now". The background path uses its own short network timeouts and a native watchdog, because the app's normal connect and sign-in timeouts are longer than the budget.
5+
The handler posts the fetched notifications directly, because the category (and so the channel the user may have silenced) is known only after the fetch. If nothing is posted within about 2 s, it posts a generic notification in a separate "Other" category, which the real result replaces silently. When the result reports a message it claimed but could not return, the generic notification stays, beside the named notifications, until the user clears it. A slow or failed fetch therefore still leaves a visible notification, and Android deprioritizes apps whose high-priority pushes show nothing. While the app is in the foreground the handler does nothing. Unlike the iOS extension, which can only rewrite the push it was handed, the handler posts every eligible unshown message it finds, grouped per conversation, so a wake means "sync now". The background path uses its own short network timeouts and a native watchdog, because the app's normal connect and sign-in timeouts are longer than the budget.
66

77
## Considered options
88

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
package xyz.block.buzz.mobile
2+
3+
import android.Manifest
4+
import android.os.Build
5+
import android.os.SystemClock
6+
import android.service.notification.StatusBarNotification
7+
import androidx.core.app.NotificationCompat
8+
import androidx.core.app.NotificationManagerCompat
9+
import androidx.test.ext.junit.runners.AndroidJUnit4
10+
import androidx.test.platform.app.InstrumentationRegistry
11+
import org.junit.After
12+
import org.junit.Before
13+
import org.junit.Test
14+
import org.junit.runner.RunWith
15+
import kotlin.test.assertEquals
16+
import kotlin.test.assertFalse
17+
import kotlin.test.assertTrue
18+
import kotlin.test.fail
19+
20+
/**
21+
* The generic notification against the real notification manager: a card
22+
* kept for a lost message survives later wakes, and one the user cleared
23+
* stays cleared.
24+
*/
25+
@RunWith(AndroidJUnit4::class)
26+
class WakeNotifierGenericTest {
27+
private val context = InstrumentationRegistry.getInstrumentation().targetContext
28+
private val manager = NotificationManagerCompat.from(context)
29+
private val notifier = WakeNotifier(context)
30+
31+
@Before fun setUp() {
32+
if (Build.VERSION.SDK_INT >= 33) {
33+
InstrumentationRegistry.getInstrumentation().uiAutomation
34+
.grantRuntimePermission(context.packageName, Manifest.permission.POST_NOTIFICATIONS)
35+
}
36+
notifier.createChannels()
37+
manager.cancelAll()
38+
}
39+
40+
@After fun tearDown() = manager.cancelAll()
41+
42+
@Test fun lostGenericJourney() {
43+
// A clean wake clears an unmarked generic, as before.
44+
notifier.postGeneric()
45+
awaitGeneric(Generic.SHOWING)
46+
notifier.cancelGeneric()
47+
awaitGeneric(Generic.NONE)
48+
49+
// The 2-second card is still up when the result reports a lost
50+
// message: it is kept, and later clean wakes leave it.
51+
notifier.postGeneric()
52+
val timerCard = awaitGeneric(Generic.SHOWING)
53+
paceUpdate()
54+
assertTrue(notifier.keepGeneric(shownThisWake = true, silent = true))
55+
awaitRepost(timerCard, Generic.LOST)
56+
notifier.cancelGeneric()
57+
drain()
58+
assertEquals(Generic.LOST, generic())
59+
60+
// A later wake's 2-second card re-posts it and keeps the mark.
61+
val kept = activeGeneric()!!
62+
paceUpdate()
63+
notifier.postGeneric()
64+
awaitRepost(kept, Generic.LOST)
65+
66+
// The user clears it.
67+
clearGeneric()
68+
awaitGeneric(Generic.NONE)
69+
70+
// The user clears the 2-second card before the result reports a lost
71+
// message: it is not posted again.
72+
notifier.postGeneric()
73+
awaitGeneric(Generic.SHOWING)
74+
clearGeneric()
75+
awaitGeneric(Generic.NONE)
76+
assertFalse(notifier.keepGeneric(shownThisWake = true, silent = true))
77+
drain()
78+
assertEquals(Generic.NONE, generic())
79+
80+
// Nothing posted this wake yet: the kept card is posted.
81+
assertTrue(notifier.keepGeneric(shownThisWake = false, silent = false))
82+
awaitGeneric(Generic.LOST)
83+
}
84+
85+
private enum class Generic { NONE, SHOWING, LOST }
86+
87+
// As a swipe or tap does: the platform cancels the card, not the handler.
88+
private fun clearGeneric() = manager.cancel("generic", 2)
89+
90+
// The notification service applies posts and cancels asynchronously, so
91+
// each step waits, within a bound, for the state it expects.
92+
private fun awaitGeneric(expected: Generic): StatusBarNotification? {
93+
await("generic $expected, was ${generic()}") { generic() == expected }
94+
return activeGeneric()
95+
}
96+
97+
// Waits for a new post of the card, so the state read is the re-post's
98+
// and not the record it replaced.
99+
private fun awaitRepost(previous: StatusBarNotification?, expected: Generic) {
100+
await("a re-post of the generic") {
101+
activeGeneric()?.let { it.postTime != previous?.postTime } == true
102+
}
103+
assertEquals(expected, generic())
104+
}
105+
106+
// Android silently drops an update to a showing card while the app
107+
// posts faster than max_notification_enqueue_rate (5 a second), and the
108+
// estimate carries over between runs. 700 ms with no post keeps the
109+
// rate under that, so quick reruns don't shed the test's updates.
110+
private fun paceUpdate() = SystemClock.sleep(700)
111+
112+
// Before asserting that nothing changed: a barrier card posted and
113+
// cancelled after the step is applied after it too.
114+
private fun drain() {
115+
manager.notify(
116+
"barrier",
117+
3,
118+
NotificationCompat.Builder(context, WakeNotifier.OTHER_CHANNEL)
119+
.setSmallIcon(android.R.drawable.stat_notify_chat)
120+
.build(),
121+
)
122+
await("the barrier card") { manager.activeNotifications.any { it.tag == "barrier" } }
123+
manager.cancel("barrier", 3)
124+
await("the barrier card to clear") { manager.activeNotifications.none { it.tag == "barrier" } }
125+
}
126+
127+
private fun await(what: String, condition: () -> Boolean) {
128+
val deadline = SystemClock.uptimeMillis() + 5_000
129+
while (!condition()) {
130+
if (SystemClock.uptimeMillis() > deadline) fail("timed out waiting for $what")
131+
Thread.sleep(20)
132+
}
133+
}
134+
135+
private fun activeGeneric(): StatusBarNotification? {
136+
val active = manager.activeNotifications.filter { it.tag == "generic" && it.id == 2 }
137+
assertTrue(active.size <= 1)
138+
return active.firstOrNull()
139+
}
140+
141+
private fun generic(): Generic {
142+
val card = activeGeneric() ?: return Generic.NONE
143+
return if (card.notification.extras.getBoolean("xyz.block.buzz.mobile.lost")) Generic.LOST else Generic.SHOWING
144+
}
145+
}

‎mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWake.kt‎

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,9 @@ import java.util.concurrent.TimeUnit
2727
*
2828
* If nothing has been posted after [GENERIC_AFTER_MS] the handler posts a
2929
* generic notification in the "Other" channel, which the result then replaces
30-
* silently, or removes when it finds nothing. A watchdog ends the work at
31-
* [WATCHDOG_MS] whatever Dart does, inside the time FCM gives a handler, and
30+
* silently, or removes when it finds nothing. It stays, beside any named ones,
31+
* when the result reports a message it lost track of. A watchdog ends the work
32+
* at [WATCHDOG_MS] whatever Dart does, inside the time FCM gives a handler, and
3233
* leaves the generic notification when no result came.
3334
*
3435
* One run exists per process. A wake that arrives while it runs is passed to
@@ -195,21 +196,27 @@ internal object PushWake {
195196
log("dart_result")
196197
val notifications = (map["notifications"] as List<*>).map { WakeNotification.fromDart(it) }
197198
answered = true
199+
if (notifications.isNotEmpty()) {
200+
notifier.postConversations(notifications, silent = genericShown)
201+
log("posted count=${notifications.size}")
202+
}
198203
when {
199-
notifications.isNotEmpty() -> {
200-
notifier.postConversations(notifications, silent = genericShown)
201-
log("posted count=${notifications.size}")
202-
removeGeneric()
204+
// A message claimed but never returned can't be named, and no
205+
// later wake finds it, so the generic notification stands in
206+
// for it, beside any named ones, until the user clears it.
207+
map["unreported"] == true -> {
208+
val silent = genericShown || notifications.isNotEmpty()
209+
if (notifier.keepGeneric(genericShown, silent)) genericShown = true
203210
}
204-
map["incomplete"] == true -> showGeneric()
211+
notifications.isEmpty() && map["incomplete"] == true -> showGeneric()
205212
else -> removeGeneric()
206213
}
207214
}
208215

209-
private fun showGeneric() {
216+
private fun showGeneric(silent: Boolean = false) {
210217
if (genericShown) return
211218
genericShown = true
212-
notifier.postGeneric()
219+
notifier.postGeneric(silent)
213220
}
214221

215222
/** Also clears the generic notification an earlier run left behind. */

‎mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWakeNotifications.kt‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import android.app.PendingIntent
44
import android.content.Context
55
import android.content.Intent
66
import android.net.Uri
7+
import android.os.Bundle
78
import androidx.core.app.NotificationChannelCompat
89
import androidx.core.app.NotificationCompat
910
import androidx.core.app.NotificationManagerCompat
@@ -103,6 +104,7 @@ internal class WakeNotifier(private val context: Context) {
103104
private const val GENERIC_ID = 2
104105
private const val GENERIC_TAG = "generic"
105106
private const val EVENT_ID_EXTRA = "eventId"
107+
private const val LOST_EXTRA = "xyz.block.buzz.mobile.lost"
106108

107109
private fun conversationTag(conversationId: String) = "conversation:$conversationId"
108110
}
@@ -185,7 +187,12 @@ internal class WakeNotifier(private val context: Context) {
185187
}
186188
}
187189

188-
fun postGeneric() {
190+
/**
191+
* [silent] posts it without alerting, beside notifications that did.
192+
* [lost] marks it as standing in for a message no wake can name, so
193+
* [cancelGeneric] leaves it. Re-posting a marked one keeps the mark.
194+
*/
195+
fun postGeneric(silent: Boolean = false, lost: Boolean = false) {
189196
val tap = PendingIntent.getActivity(
190197
context,
191198
GENERIC_ID,
@@ -200,11 +207,32 @@ internal class WakeNotifier(private val context: Context) {
200207
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
201208
.setAutoCancel(true)
202209
.setContentIntent(tap)
210+
.setSilent(silent)
211+
.addExtras(Bundle().apply { putBoolean(LOST_EXTRA, lost || genericLost()) })
203212
.build()
204213
AgeRestriction.unlessRestricted { manager.notify(GENERIC_TAG, GENERIC_ID, notification) }
205214
}
206215

207-
fun cancelGeneric() = manager.cancel(GENERIC_TAG, GENERIC_ID)
216+
/** Leaves a generic notification that stands in for a lost message. */
217+
fun cancelGeneric() {
218+
if (!genericLost()) manager.cancel(GENERIC_TAG, GENERIC_ID)
219+
}
220+
221+
/**
222+
* Posts the generic notification marked lost, so later wakes leave it. A
223+
* card this wake already showed ([shownThisWake]), and the user has since
224+
* cleared, stays cleared. Returns whether it is showing.
225+
*/
226+
fun keepGeneric(shownThisWake: Boolean, silent: Boolean): Boolean {
227+
if (shownThisWake && activeGeneric() == null) return false
228+
postGeneric(silent, lost = true)
229+
return true
230+
}
231+
232+
private fun genericLost(): Boolean = activeGeneric()?.notification?.extras?.getBoolean(LOST_EXTRA) == true
233+
234+
private fun activeGeneric() =
235+
manager.activeNotifications.firstOrNull { it.tag == GENERIC_TAG && it.id == GENERIC_ID }
208236

209237
private fun existingStyle(tag: String): NotificationCompat.MessagingStyle? =
210238
manager.activeNotifications

‎mobile/lib/shared/push/android_push_wake.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ Map<String, Object?> pushWakeChannelPayload(PushWakeResult result) => {
5252
},
5353
],
5454
'incomplete': result.incomplete,
55+
'unreported': result.unreported,
5556
};
5657

5758
/// Answers the native handler's wake requests from a [PushWakeRunner].

‎mobile/lib/shared/push/push_wake_resolver.dart‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@ class PushWakeResult {
131131
required this.notifications,
132132
this.failedCommunityIds = const [],
133133
this.interrupted = false,
134+
this.unreported = false,
134135
});
135136

136137
/// Every eligible unshown message, newest first, within the caps.
@@ -144,6 +145,12 @@ class PushWakeResult {
144145
/// say which communities it missed.
145146
final bool interrupted;
146147

148+
/// Whether a claim was still running when the wake stopped waiting for it.
149+
/// If it wins, its message is recorded as shown but was never returned, so
150+
/// no later wake finds it, and the caller shows its generic notification
151+
/// beside any others. Unlike [incomplete], a retry can't recover it.
152+
final bool unreported;
153+
147154
/// Whether the wake could not look everywhere. With no [notifications] the
148155
/// caller shows its generic notification, so the wake is never silent.
149156
bool get incomplete => interrupted || failedCommunityIds.isNotEmpty;
@@ -265,6 +272,13 @@ Future<PushWakeResult> resolvePushWake({
265272
await Future.wait(
266273
run.claims,
267274
).timeout(_claimGrace, onTimeout: () => const []);
275+
// Read with the claimed snapshot below, with no await between: a claim
276+
// that finishes after this point is not returned, so it is unreported.
277+
// A message with nothing to show would not be returned anyway. Its body
278+
// is formatted only here, so claims that answer in time never pay for it.
279+
final unreported = run.claiming.values.any(
280+
(event) => notificationBody(event.content).isNotEmpty,
281+
);
268282
for (final community in eligible) {
269283
if (!run.done.contains(community.id)) run.failed.add(community.id);
270284
}
@@ -276,6 +290,7 @@ Future<PushWakeResult> resolvePushWake({
276290
return PushWakeResult(
277291
notifications: capPushWakeNotifications(run.notifications),
278292
failedCommunityIds: run.failed.toSet().toList()..sort(),
293+
unreported: unreported,
279294
);
280295
} finally {
281296
timer.cancel();
@@ -295,6 +310,10 @@ class _WakeRun {
295310
final done = <String>{};
296311
final claims = <Future<void>>[];
297312

313+
/// The message each community is claiming now, until its claim answers.
314+
/// A community claims one message at a time.
315+
final claiming = <String, NostrEvent>{};
316+
298317
/// What each community running now has claimed so far, which is returned if
299318
/// the wake ends before the community does.
300319
final claimed = <String, List<PushWakeNotification>>{};
@@ -523,12 +542,19 @@ Future<void> _resolveCommunity(
523542
// A claim that fails (storage full, say) ends this community's run.
524543
// The messages claimed before it are returned, since they are already
525544
// recorded as shown, and the community is reported as incomplete.
545+
final bool won;
546+
run.claiming[community.id] = event;
526547
try {
527-
if (!await store.claim(community.id, event.id, createdAt)) continue;
548+
won = await store.claim(community.id, event.id, createdAt);
528549
} on Object {
529550
complete = false;
530551
break;
552+
} finally {
553+
// Nothing awaits between here and adding the message to `claimed`,
554+
// so a claim the wake has stopped waiting for is still counted.
555+
run.claiming.remove(community.id);
531556
}
557+
if (!won) continue;
532558
final body = notificationBody(event.content);
533559
// A message with no text (only markup) has nothing to show, but it is
534560
// recorded so it is not looked at again.

0 commit comments

Comments
 (0)