Skip to content

fix(push): fetch notification metadata before FCM tears down the service - #100

Merged
Quick104 merged 1 commit into
mainfrom
t3code/fix-inconsistent-notification-metadata
Jul 25, 2026
Merged

Quick104 merged 1 commit into
mainfrom
t3code/fix-inconsistent-notification-metadata

Conversation

@Quick104

@Quick104 Quick104 commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Push notifications intermittently showed generic text ("Silo notification" / "Open Silo to view it.") instead of the real title, e.g. "Severance — S2E4 The Hidden Hallway".

Android registers in private_push mode, so the relay sends a content-free data payload carrying only silo_delivery_id. Every word of user-visible text comes from the GET /api/v1/notifications/{id} lookup the client makes on receipt — if that lookup doesn't complete, the notification degrades to the hardcoded fallback in PushNotificationPresenter.

Root cause

onMessageReceived only launched the lookup on a service-scoped coroutine and returned immediately:

serviceScope.launch { handler.handle(...) }   // returns instantly
...
override fun onDestroy() { serviceScope.cancel() }

FCM's EnhancedIntentService completes the wakeful intent (releasing the wake lock) and calls stopSelf() the instant the callback returns — verified against firebase-messaging-25.1.0 bytecode. onDestroy then cancelled the scope with the HTTP request still in flight.

The cancellation was invisible: safeApiCall catches Exception, and JVM CancellationException is one, so an aborted call came back as an ordinary NetworkError. Everything after the fetch is non-suspending, so the notification still posted — just with the generic strings. Whether the request beat stopSelf depended on connection warmth, cold-start, and whether the device was dozing, which is why it looked random.

onNewToken had the identical bug, silently dropping FCM token re-registration.

Fix

Run both callbacks inline. They execute on FCM's own intent-handling executor, never the main thread, so blocking there is the documented contract rather than a hazard.

  • PUSH_WORK_BUDGET_MS (8s) bounds each network call. That executor is single-threaded (FcmExecutors.newIntentHandleExecutor), so deliveries in a burst queue head-to-tail and each callback must give the thread back promptly. Set deliberately under the shared client's 10s connect timeout: a server we haven't connected to by then won't produce anything useful inside FCM's window either, and giving up early costs only generic text — while overrunning the window costs the whole notification.
  • withinPushBudget rethrows CancellationException ahead of its broad catch, matching the convention already used across the shared repositories and addressing review feedback on feat(push): handle relay silo_delivery_id and silo_mode data keys #71 that was never applied.

Verification

  • :androidApp:compileDebugKotlin and the full :androidApp:testDebugUnitTest suite pass.
  • Confirmed the FCM lifecycle claims by decompiling firebase-messaging-25.1.0: EnhancedIntentService calls WakeLockHolder.completeWakefulIntent then stopSelfResult on task completion; handleIntentOnMainThread is hardcoded false; the intent executor is newSingleThreadExecutor.
  • Confirmed by direct test that withTimeoutOrNull still returns null when its block swallows the cancellation, and that post-deadline suspend calls fail fast — so the budget is genuinely enforced through safeApiCall's broad catch.

Not folded in: safeApiCall swallowing CancellationException breaks structured concurrency for ~179 call sites app-wide and deserves its own change.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved push notification handling so inbox updates and badge counts remain current even when notification permission is denied.
    • Improved reliability when refreshing notification data after a direct notification lookup misses.
    • Added safeguards to prevent push notification and token-processing tasks from exceeding their available processing time.

…ice (#100)

Data-only pushes register in `private_push` mode, so the relay sends only
`silo_delivery_id` — every word of user-visible text comes from the
`GET /api/v1/notifications/{id}` lookup the client makes on receipt. When that
lookup didn't finish, the notification fell back to "Silo notification" /
"Open Silo to view it.", which is what users saw intermittently.

`onMessageReceived` only *launched* that lookup on a service-scoped coroutine
and returned. FCM's `EnhancedIntentService` completes the wakeful intent and
calls `stopSelf()` the instant the callback returns (verified against
firebase-messaging 25.1.0 bytecode), so `onDestroy` cancelled the scope
mid-request. The cancellation was invisible: `safeApiCall` catches `Exception`,
and JVM `CancellationException` is one, so the aborted call came back as a
plain `NetworkError`. Everything after the fetch is non-suspending, so the
notification still posted — just with the generic strings. Whether the request
beat `stopSelf` came down to connection warmth, which is why it looked random.

Run both callbacks inline instead. They execute on FCM's own intent-handling
executor, never the main thread, so blocking there is the documented contract.
`onNewToken` had the same bug and silently dropped token re-registration.

- `PUSH_WORK_BUDGET_MS` (8s) bounds each network call. That executor is
  single-threaded (`FcmExecutors.newIntentHandleExecutor`), so deliveries in a
  burst queue head-to-tail and a callback must give the thread back promptly.
  Deliberately under the shared client's 10s connect timeout: a server we
  haven't connected to by then can't help us inside the window either.
- `withinPushBudget` rethrows `CancellationException` ahead of its broad catch,
  matching the convention in the shared repositories and addressing review
  feedback on #71 that was never applied.

Follow-up, deliberately not folded in: `safeApiCall` swallowing
`CancellationException` breaks structured concurrency for ~179 call sites
app-wide and deserves its own change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Push notification handling now stays within the synchronous FCM callback boundary with an 8-second work budget. Notification-row lookup occurs before the notification permission check, and cache misses refresh the repository before retrying the lookup.

Changes

Push processing flow

Layer / File(s) Summary
Bounded FCM callback execution
androidApp/.../push/SiloFirebaseMessagingService.kt
Replaces service-scoped coroutine launches with runBlocking, adds timeout and cancellation handling, and bounds token registration with an 8-second budget.
Budgeted notification lookup
androidApp/.../push/PushNotificationPresenter.kt
Documents fetch-before-permission ordering and applies the push budget to repository refresh and cache-miss lookup.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant FCM
  participant SiloFirebaseMessagingService
  participant Handler
  participant PushNotificationPresenter
  participant NotificationsRepository

  FCM->>SiloFirebaseMessagingService: onMessageReceived
  SiloFirebaseMessagingService->>Handler: runBlocking handle
  Handler->>PushNotificationPresenter: present or sync
  PushNotificationPresenter->>NotificationsRepository: fetch cached row
  PushNotificationPresenter->>NotificationsRepository: refresh on miss
Loading

Possibly related PRs

Suggested reviewers: rxwatcher

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: fetching notification metadata before FCM service teardown.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch t3code/fix-inconsistent-notification-metadata

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
androidApp/src/androidMain/kotlin/org/siloserver/silo/android/push/SiloFirebaseMessagingService.kt (1)

100-113: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider logging on the failure/timeout paths.

DI resolution failure, handler.handle exceptions, and budget timeouts all fail silently today. Given the motivating bug for this PR was exactly this kind of hard-to-diagnose silent failure, a log line on each of these paths (missing handler/registrar, caught exception, timed-out budget) would materially help future triage without changing behavior.

Also applies to: 116-122

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/push/SiloFirebaseMessagingService.kt`
around lines 100 - 113, Update the Firebase message handling flow around
PushMessageHandler resolution and handler.handle so DI resolution failures,
caught handling exceptions, and budget timeouts each emit diagnostic log lines
before preserving the existing return or swallow behavior. Include relevant
exception details where available, and add equivalent logging for missing
handler/registrar paths without changing notification handling behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/push/SiloFirebaseMessagingService.kt`:
- Around line 100-113: Update the Firebase message handling flow around
PushMessageHandler resolution and handler.handle so DI resolution failures,
caught handling exceptions, and budget timeouts each emit diagnostic log lines
before preserving the existing return or swallow behavior. Include relevant
exception details where available, and add equivalent logging for missing
handler/registrar paths without changing notification handling behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cba4592a-1fd3-4e4f-8d20-a2f6d3e65c7c

📥 Commits

Reviewing files that changed from the base of the PR and between 27de43a and f895b32.

📒 Files selected for processing (2)
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/push/PushNotificationPresenter.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/push/SiloFirebaseMessagingService.kt

@Quick104
Quick104 merged commit 5047c4d into main Jul 25, 2026
1 of 2 checks passed
@Quick104
Quick104 deleted the t3code/fix-inconsistent-notification-metadata branch July 25, 2026 13:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant