Skip to content

Android peripheral: retry a notification the stack refused - #407

Merged
fotiDim merged 1 commit into
mainfrom
fix/android-notification-retry-scheduling
Nov 27, 2026
Merged

fotiDim merged 1 commit into
mainfrom
fix/android-notification-retry-scheduling

Conversation

@fotiDim

@fotiDim fotiDim commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

The gap

#402/#405 made updateCharacteristicValue complete on onNotificationSent. Since then, drainNotifications handles a refused send (notifyCharacteristicChanged returns false) by pushing the payload back to the front of pendingNotifications and removing the in-flight marker — and scheduling nothing else. The marker was absent before the send, so there is no packet whose onNotificationSent would ever retry it. The queued update waits for an unrelated updateCharacteristic for the same client, and every later update queues behind it. A payload enqueued in the narrow window between the isSubscribed check in updateCharacteristic and the enqueue (a CCCD unsubscribe can land in between) could likewise be sent after a resubscription.

This cannot corrupt a chunk — the #403 critical section is unchanged — but it stalls the client's notification path.

The fix

Android only, UniversalBlePeripheralPlugin:

  • A refused send schedules a retry for that client on the existing main Handler. At most one runnable exists per address: further refusals coalesce into it instead of posting another.
  • Backoff is 10 ms, doubled per consecutive refusal, capped at 500 ms. The attempt counter stops at the ceiling (7, i.e. a shift distance of at most 6), so it cannot overflow into a negative shift after billions of refusals; a successful send clears it, so state is one small int per client and does not grow.
  • The retry re-checks the subscription outside the pendingNotifications monitor — isSubscribed takes subscribedCharDevicesMap, and the descriptor/cleanup paths take the two monitors in the opposite order, so nesting them would deadlock. If the client has unsubscribed, the queued payloads of the characteristic at the head of its queue are dropped with dropNotifications(includeInFlight = false) and settled with the same IllegalStateException("Central unsubscribed") as the existing unsubscribe path. The client's other characteristics still drain. This ends the retry loop.
    • A client that resubscribes before the first retry fires (10 ms) is treated as still wanting the update, like any queued payload. That is deliberate: the subscription check is a point-in-time re-check, not a subscription generation. The window is narrow and resubscription revives delivery of a payload that was queued while subscribed.
  • Settlement stays on settleNotifications (posts to the handler); no Dart callback runs on a binder thread and no new lock nesting is introduced.
  • Disconnect/cleanConnection, resetPeripheralState, removeService, clearServices, clearPendingNotifications and the CCCD unsubscribe path cancel a retry the queue no longer needs (handler.removeCallbacks plus map cleanup), and a runnable that still fires against torn-down state is a harmless no-op. removeService cancels only when nothing else of the client is queued, so another service's refused payload keeps its retry.
  • The onNotificationSent flow is untouched: the marker is still cleared only by the callback on a successful send, so an accepted packet is never settled early, and a retried packet is settled exactly once (the refusal leaves no in-flight marker for the callback to find).
  • drainNotifications finding gattServer == null re-queues without a retry. That branch is unreachable through the public paths (the server is only nulled by resetPeripheralState, which empties the queue and cancels its retries first; every enqueue path calls requireGattServer), and scheduling a retry there would poll a server that is still null. It now says so in a comment instead.

Tests

PeripheralRegressionTest gained a captured postDelayed helper (runnables are run manually, never with real delays) and nine cases:

  • a refused send schedules exactly one retry; the Dart callback stays pending; running the retry with the stack now accepting sends the payload and the onNotificationSent success settles it;
  • three queued updates for one client produce one runnable, not three;
  • the delays are exactly 10/20/40/80/160/320/500/500 ms and only the latest runnable is live;
  • a client that unsubscribes before the retry has its payload dropped with "Central unsubscribed", no second notifyCharacteristicChanged, and no send after resubscribing;
  • dropping the unsubscribed characteristic does not stop the client's other characteristic from draining, and the backoff keeps counting across the drop (20 ms next, not 10 ms);
  • disconnect cancels the runnable, fails the queue, and a runnable run afterwards sends nothing;
  • removeService keeps the retry while another service's payload is still queued, then cancels it when that one is removed too;
  • reset cancels the runnable and the existing cleanup fails the queued callback;
  • clearPendingNotifications(lowercaseId) cancels the retry and clears its backoff.

Determinism: the handler is a Mockito mock, settlements run inline, and no test sleeps or bounds a clock. Cleanup: the plugin (and its retry maps) is per-test and discarded; the mocked handler never holds a real runnable, and @AfterTest restores the global characteristic/subscription caches the tests seed.

Negative check: with the production file reverted to origin/main and only the two new field declarations kept (so the reflective seeding works and the assertions run), all nine cases fail — e.g. The refusal schedules exactly one retry ==> expected: <1> but was: <0>.

Tests run: flutter analyze clean, flutter test 344 passed, Android :universal_ble:testDebugUnitTest 145 passed (142 before, 3 new).

Residual risk

A packet the stack accepts but never reports through onNotificationSent is not detectable: there is no refusal to retry from, and inventing a native timeout would guess at how long a link may legitimately take. That case still needs a disconnect or adapter reset, as before. The payload queued in the isSubscribed-to-enqueue window is re-checked only when its send is refused; when the stack accepts it, it is transmitted immediately (to a client that has just unsubscribed at the ATT level, which drops it), and the retry is what prevents it from lingering across a resubscription.

fotiDim added a commit that referenced this pull request Nov 27, 2026
drainNotifications pushes a refused payload (notifyCharacteristicChanged
returns false) back to the front of pendingNotifications and removes the
in-flight marker. Nothing then schedules another drain: the marker was absent
before the send, so there is no packet whose onNotificationSent would retry it.
The queued update therefore waits for an unrelated updateCharacteristic for the
same client, and every later update queues behind it. A payload enqueued in the
window between the isSubscribed check in updateCharacteristic and the enqueue (a
CCCD unsubscribe can land in between) could likewise be transmitted stale after
a resubscription.

A refusal now schedules a retry for that client on the existing main Handler.
At most one runnable exists per address, so further refusals coalesce into it.
The delay is 10 ms, doubled per consecutive refusal and capped at 500 ms; a
successful send clears the attempt count, leaving at most one int map entry per
device. The runnable re-checks the subscription outside the pendingNotifications
monitor, because isSubscribed takes subscribedCharDevicesMap and the
descriptor/cleanup paths take the two monitors in the opposite order. When the
client has unsubscribed, the queued payloads of the characteristic at the head
of its queue are dropped with dropNotifications(includeInFlight = false) and
settled with "Central unsubscribed", which ends the retry loop, and the client's
other characteristics still drain. Settlements still go through
settleNotifications, so no Dart callback runs on a binder thread. Disconnect,
adapter reset, removeService/clearServices, clearPendingNotifications and the
CCCD unsubscribe path cancel a retry that is no longer needed, and the
onNotificationSent flow that settles a successful send is unchanged.

Tests (PeripheralRegressionTest) add a captured postDelayed helper that runs
retries manually, never with real delays, and cover: one retry for a refusal
that succeeds when it runs, one retry for several queued updates, the
10/20/40/80/160/320/500/500 ms backoff, the unsubscribe drop with a failed
callback and no resend after resubscribing, reset and clearPendingNotifications
cancelling the runnable and failing the queue, and the attempt state cleared by
a successful send. The first test fails against the unfixed production file
("The refusal schedules exactly one retry ==> expected: <1> but was: <0>").

Verification: flutter analyze clean, flutter test 344 passed, Android unit tests
142 passed.
@fotiDim
fotiDim force-pushed the fix/android-notification-retry-scheduling branch from 34f1851 to 694ce56 Compare November 27, 2026 06:14
fotiDim added a commit that referenced this pull request Nov 27, 2026
drainNotifications pushes a refused payload (notifyCharacteristicChanged
returns false) back to the front of pendingNotifications and removes the
in-flight marker. Nothing then schedules another drain: the marker was absent
before the send, so there is no packet whose onNotificationSent would retry it.
The queued update therefore waits for an unrelated updateCharacteristic for the
same client, and every later update queues behind it. A payload enqueued in the
window between the isSubscribed check in updateCharacteristic and the enqueue (a
CCCD unsubscribe can land in between) could likewise be transmitted stale after
a resubscription.

A refusal now schedules a retry for that client on the existing main Handler.
At most one runnable exists per address, so further refusals coalesce into it.
The delay is 10 ms, doubled per consecutive refusal and capped at 500 ms; the
attempt counter stops at the ceiling so the shift distance stays in range, and a
successful send clears it, leaving at most one int map entry per device. The
runnable re-checks the subscription outside the pendingNotifications monitor,
because isSubscribed takes subscribedCharDevicesMap and the descriptor/cleanup
paths take the two monitors in the opposite order. When the client has
unsubscribed, the queued payloads of the characteristic at the head of its queue
are dropped with dropNotifications(includeInFlight = false) and settled with
"Central unsubscribed", which ends the retry loop, and the client's other
characteristics still drain. A client that resubscribes before the retry fires
is treated as still wanting the update, like any queued payload. Settlements
still go through settleNotifications, so no Dart callback runs on a binder
thread. Disconnect, adapter reset, removeService/clearServices,
clearPendingNotifications and the CCCD unsubscribe path cancel a retry that is
no longer needed, and the onNotificationSent flow that settles a successful send
is unchanged. The queued payload a drain finds with no server is unreachable
through the public paths and now says so instead of scheduling a retry against a
server that is still null.

Tests (PeripheralRegressionTest) add a captured postDelayed helper that runs
retries manually, never with real delays, and cover: one retry for a refusal
that succeeds when it runs, one retry for several queued updates, the
10/20/40/80/160/320/500/500 ms backoff, the unsubscribe drop with a failed
callback and no resend after resubscribing, dropping the unsubscribed
characteristic while the client's other characteristic keeps draining,
disconnect/removeService/reset/clearPendingNotifications cancelling the runnable
and failing the queue, removeService keeping a retry that another service's
payload still needs, and the attempt state cleared by a successful send. The
retry cases fail against the unfixed production file ("The refusal schedules
exactly one retry ==> expected: <1> but was: <0>").

Verification: flutter analyze clean, flutter test 344 passed, Android unit tests
145 passed (142 before).
@fotiDim
fotiDim force-pushed the fix/android-notification-retry-scheduling branch from 694ce56 to 7902569 Compare November 27, 2026 06:22
fotiDim added a commit that referenced this pull request Nov 27, 2026
drainNotifications pushes a refused payload (notifyCharacteristicChanged
returns false) back to the front of pendingNotifications and removes the
in-flight marker. Nothing then schedules another drain: the marker was absent
before the send, so there is no packet whose onNotificationSent would retry it.
The queued update therefore waits for an unrelated updateCharacteristic for the
same client, and every later update queues behind it. A payload enqueued in the
window between the isSubscribed check in updateCharacteristic and the enqueue (a
CCCD unsubscribe can land in between) could likewise be transmitted stale after
a resubscription.

A refusal now schedules a retry for that client on the existing main Handler.
At most one runnable exists per address, so further refusals coalesce into it.
The delay is 10 ms, doubled per consecutive refusal and capped at 500 ms; the
attempt counter stops at the ceiling so the shift distance stays in range, and a
successful send clears it, leaving at most one int map entry per device. The
runnable re-checks the subscription outside the pendingNotifications monitor,
because isSubscribed takes subscribedCharDevicesMap and the descriptor/cleanup
paths take the two monitors in the opposite order. When the client has
unsubscribed, the queued payloads of the characteristic at the head of its queue
are dropped with dropNotifications(includeInFlight = false) and settled with
"Central unsubscribed", which ends the retry loop, and the client's other
characteristics still drain. A client that resubscribes before the retry fires
is treated as still wanting the update, like any queued payload. Settlements
still go through settleNotifications, so no Dart callback runs on a binder
thread. Disconnect, adapter reset, removeService/clearServices,
clearPendingNotifications and the CCCD unsubscribe path cancel a retry that is
no longer needed, and the onNotificationSent flow that settles a successful send
is unchanged. The queued payload a drain finds with no server is unreachable
through the public paths and now says so instead of scheduling a retry against a
server that is still null.

Tests (PeripheralRegressionTest) add a captured postDelayed helper that runs
retries manually, never with real delays, and cover: one retry for a refusal
that succeeds when it runs, one retry for several queued updates, the
10/20/40/80/160/320/500/500 ms backoff, the unsubscribe drop with a failed
callback and no resend after resubscribing, dropping the unsubscribed
characteristic while the client's other characteristic keeps draining,
disconnect/removeService/reset/clearPendingNotifications cancelling the runnable
and failing the queue, removeService keeping a retry that another service's
payload still needs, and the attempt state cleared by a successful send. The
retry cases fail against the unfixed production file ("The refusal schedules
exactly one retry ==> expected: <1> but was: <0>").

Verification: flutter analyze clean, flutter test 344 passed, Android unit tests
145 passed (142 before).
@fotiDim
fotiDim force-pushed the fix/android-notification-retry-scheduling branch from 7902569 to 15b522c Compare November 27, 2026 06:24
drainNotifications pushes a refused payload (notifyCharacteristicChanged
returns false) back to the front of pendingNotifications and removes the
in-flight marker. Nothing then schedules another drain: the marker was absent
before the send, so there is no packet whose onNotificationSent would retry it.
The queued update therefore waits for an unrelated updateCharacteristic for the
same client, and every later update queues behind it. A payload enqueued in the
window between the isSubscribed check in updateCharacteristic and the enqueue (a
CCCD unsubscribe can land in between) could likewise be transmitted stale after
a resubscription.

A refusal now schedules a retry for that client on the existing main Handler.
At most one runnable exists per address, so further refusals coalesce into it.
The delay is 10 ms, doubled per consecutive refusal and capped at 500 ms; the
attempt counter stops at the ceiling so the shift distance stays in range, and a
successful send clears it, leaving at most one int map entry per device. The
runnable re-checks the subscription outside the pendingNotifications monitor,
because isSubscribed takes subscribedCharDevicesMap and the descriptor/cleanup
paths take the two monitors in the opposite order. When the client has
unsubscribed, the queued payloads of the characteristic at the head of its queue
are dropped with dropNotifications(includeInFlight = false) and settled with
"Central unsubscribed", which ends the retry loop, and the client's other
characteristics still drain. A client that resubscribes before the retry fires
is treated as still wanting the update, like any queued payload. Settlements
still go through settleNotifications, so no Dart callback runs on a binder
thread. Disconnect, adapter reset, removeService/clearServices,
clearPendingNotifications and the CCCD unsubscribe path cancel a retry that is
no longer needed, and the onNotificationSent flow that settles a successful send
is unchanged. The queued payload a drain finds with no server is unreachable
through the public paths and now says so instead of scheduling a retry against a
server that is still null.

Tests (PeripheralRegressionTest) add a captured postDelayed helper that runs
retries manually, never with real delays, and cover: one retry for a refusal
that succeeds when it runs, one retry for several queued updates, the
10/20/40/80/160/320/500/500 ms backoff, the unsubscribe drop with a failed
callback and no resend after resubscribing, dropping the unsubscribed
characteristic while the client's other characteristic keeps draining,
disconnect/removeService/reset/clearPendingNotifications cancelling the runnable
and failing the queue, removeService keeping a retry that another service's
payload still needs, and the attempt state cleared by a successful send. The
retry cases fail against the unfixed production file ("The refusal schedules
exactly one retry ==> expected: <1> but was: <0>").

Verification: flutter analyze clean, flutter test 344 passed, Android unit tests
145 passed (142 before).
@fotiDim
fotiDim force-pushed the fix/android-notification-retry-scheduling branch from 15b522c to 7642bb2 Compare November 27, 2026 06:26
@fotiDim
fotiDim merged commit 2d0b364 into main Nov 27, 2026
4 checks passed
@fotiDim
fotiDim deleted the fix/android-notification-retry-scheduling branch November 27, 2026 06:36
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