Skip to content

Android peripheral: serialize notification value with the in-flight send (#403) - #404

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

fotiDim merged 1 commit into
mainfrom
fix/403-android-notification-race

Conversation

@fotiDim

@fotiDim fotiDim commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

What was wrong

On Android, updateCharacteristic wrote the shared BluetoothGattCharacteristic.value unconditionally, while drainNotifications also assigned it and called the deprecated 3-argument notifyCharacteristicChanged — and did both outside the pendingNotifications monitor (its in-flight check was outside too). drainNotifications runs from onNotificationSent on a binder thread, so a main-thread update could land between the drain's value assignment and its notify call. Below API 33 the payload is read from that shared characteristic, so a same-length payload was silently transmitted with the wrong content — corrupted notifications when a characteristic is updated faster than the stack drains.

What changed

  • drainNotifications(deviceAddress) now performs the in-flight check, the dequeue, the server lookup, the notificationsInFlight marker, the value assignment and the notify call inside a single synchronized(pendingNotifications) block. On failure the marker is removed and the payload goes back to the front of the queue, as before.
  • API 33+ uses the stateless 4-argument notifyCharacteristicChanged(device, characteristic, indicate, value) and treats only BluetoothStatusCodes.SUCCESS as sent; the deprecated 3-argument overload is kept for older releases.
  • updateCharacteristic resolves the subscribed devices before taking the pendingNotifications monitor (isSubscribed takes subscribedCharDevicesMap, and the descriptor and cleanup paths take those two monitors in the opposite order, so nesting them here would deadlock). It writes the static, readable value only when no target device is subscribed, instead of on every update.
  • CHANGELOG entry under Unreleased.

Tests

  • New queuedUpdateDoesNotOverwriteInFlightCharacteristicValue in android/src/test/.../PeripheralRegressionTest.kt: after a first update, a second update queued while the first is in flight must not touch characteristic.value; releasing the in-flight marker and re-running the drain sets the second chunk and notifies twice. The test fails against the previous code and passes now.
  • flutter analyze clean.
  • flutter test: 341 passed.
  • cd example/android && gradle :universal_ble:testDebugUnitTest (Gradle 9.3.1, Java 17): 132 passed.

Fixes #403

…end (#403)

* Android peripheral: one lock around the notification value and its send

Below API 33 notifyCharacteristicChanged takes the payload from the shared
BluetoothGattCharacteristic.value, and two threads wrote it.
updateCharacteristic set it unconditionally on the main thread, while
drainNotifications assigned the next queued payload and called
notifyCharacteristicChanged outside the pendingNotifications monitor — the
in-flight check was outside it too. Called from onNotificationSent on the binder
thread, a main-thread update could land between that assignment and the notify
call, so a payload of the same length was silently transmitted with the wrong
content: corrupted reports when a characteristic is updated faster than the
stack drains its notifications.

drainNotifications now does the in-flight check, the dequeue, the server
lookup, the in-flight marker, the value assignment and the notify call inside
one synchronized(pendingNotifications) block. API 33 and newer take the
stateless four-argument overload and treat only BluetoothStatusCodes.SUCCESS as
sent; the deprecated three-argument path stays for older releases. On failure
the marker is still removed and the payload pushed back to the front, so no
notification is dropped.

updateCharacteristic resolves the subscribed devices before taking that monitor,
because isSubscribed takes subscribedCharDevicesMap and the descriptor and
cleanup paths take those two monitors in the opposite order; nesting them the
other way would deadlock. The static, readable value is now written only when no
target device is subscribed, instead of on every update, so a queued update
cannot overwrite the value an in-flight notification is being sent from.

Verification: queuedUpdateDoesNotOverwriteInFlightCharacteristicValue added to
PeripheralRegressionTest (fails against the previous code, passes now); Android
unit tests 132 passed; flutter test 341 passed; flutter analyze clean.
@fotiDim
fotiDim force-pushed the fix/403-android-notification-race branch from 27b8f40 to 0287171 Compare November 26, 2026 20:40
fotiDim added a commit that referenced this pull request Nov 26, 2026
…) Darwin queue (#402)

Three independent causes made a bulk notification transfer slow (~15 KB/s):
the Darwin update was fire-and-forget, macOS negotiated latency=1, and the
Darwin pending queue removed elements with Array.removeFirst().

This also carries the #403 Android notification-race fix, aligned with
fix/403-android-notification-race (#404) so that #405 rebases cleanly once it
lands: the transmit critical section is the same code, and the only additions
here are the async settlement and completion aggregation.

* A completion contract for updateCharacteristicValue

`UniversalBlePeripheralChannel.updateCharacteristic` is now an async Pigeon
callback, so the Dart future completes when the notification is settled rather
than when it was handed to the plugin. Awaiting it between chunks is therefore
real backpressure, and a native failure reaches the caller.

Android completes on `onNotificationSent` (success on GATT_SUCCESS, failure
otherwise). Apple completes when CBPeripheralManager.updateValue returns true,
immediately or after peripheralManagerIsReady(toUpdateSubscribers). Windows
completes from the NotifyValueAsync completion handler. With several targets,
the call completes once all settle, reporting the first error; a call with no
subscriber still updates the readable value and completes immediately.

A queued update that can never be sent now fails with a descriptive error
instead of leaving the Dart future pending: clearPendingNotifications,
removeService/clearServices, central unsubscription, adapter reset, engine
disposal and device disconnect all settle what they discard. Each update is
settled exactly once.

* Apple: O(1) queue and connection latency

PeripheralNotificationQueue keeps a read head index over its storage instead of
shifting the tail per chunk; storage is compacted in batches and released when
drained. drain() reports each accepted element through onSent exactly once,
and removeAll()/removeAll(where:) return what they discarded so those callers
can be failed. Backpressure semantics are unchanged.

Add UniversalBlePeripheral.setDesiredConnectionLatency (Apple only), mapped to
CBPeripheralManager.setDesiredConnectionLatency(_:for:). It throws notFound for
an unknown central. initialValues still receives the last value on every
update: that assignment is O(1) and was not the quadratic cost.

* Android: settle from onNotificationSent, and the #403 race

Track the in-flight PendingNotification per client address rather than just a
busy marker, so onNotificationSent can complete the right update. Settlement
is posted to the main handler; no Dart callback runs on a binder thread or
under the pendingNotifications monitor. The settlement is queued before the
next packet is handed to the stack, so two updates for one client complete in
submission order.

Apply the #403 fix in the same path: updateCharacteristic only writes
characteristic.value when nobody is subscribed, and drainNotifications holds
the pendingNotifications monitor across the in-flight check, dequeue,
bookkeeping, value assignment and notifyCharacteristicChanged. API 33+ uses the
stateless four-argument call and treats BluetoothStatusCodes.SUCCESS as sent;
older releases keep the deprecated three-argument call. isSubscribed is
resolved before taking the pending monitor, since the descriptor-write and
disconnect paths take the two locks in the opposite order.

* Windows: reply from the completion handler

UpdateCharacteristic returns the Pigeon reply callback and completes it from
NotifyValueAsync.Completed (success) or a non-completed status (failure), and
from the synchronous catch as before. The callback is copied into the lambda
rather than moved, so the catch path still holds a valid std::function instead
of throwing std::bad_function_call. Failure logging is unchanged.

* Dart, docs and tests

Add the platform-interface default no-op, the iOS/macOS-only forwarding that
canonicalises the device id, the public API and the PeripheralConnectionLatency
export. Rewrite the updateCharacteristicValue and README completion semantics
to describe pacing bulk transfers by awaiting the future, and document the
latency setter. CHANGELOG records the behavioural change under Unreleased.

Tests: Android adds four cases for the completion contract (accepted packet is
not completed early, non-success status fails, the #403 queued update does not
overwrite the in-flight value, and clearPendingNotifications/reset fail what
they discard). The Apple helper covers onSent exactly once, blocked elements
not reported until resume, and removeAll returning removed elements. Dart adds
the Apple forwarding/no-op latency test and two channel tests proving the
future waits for the native settlement reply and surfaces its failure.

Generated files were rebuilt with Pigeon 29.0.12, the version origin/main's
files were generated with, so their diff is limited to the new enum, the
asyncCallback signature and setDesiredConnectionLatency plus the resulting
codec type-index renumbering.

Verification: flutter analyze clean, flutter test 344 passed, Android unit
tests 136 passed, the Apple native reliability checks pass, and the shared
Apple sources typecheck for macOS and iOS. Windows is compile-checked by CI; it
cannot be built on macOS.

(#402)
@fotiDim
fotiDim merged commit b025cf7 into main Nov 27, 2026
4 checks passed
@fotiDim
fotiDim deleted the fix/403-android-notification-race branch November 27, 2026 06:04
fotiDim added a commit that referenced this pull request Nov 27, 2026
…) Darwin queue (#402)

Three independent causes made a bulk notification transfer slow (~15 KB/s):
the Darwin update was fire-and-forget, macOS negotiated latency=1, and the
Darwin pending queue removed elements with Array.removeFirst().

This also carries the #403 Android notification-race fix, aligned with
fix/403-android-notification-race (#404) so that #405 rebases cleanly once it
lands: the transmit critical section is the same code, and the only additions
here are the async settlement and completion aggregation.

* A completion contract for updateCharacteristicValue

`UniversalBlePeripheralChannel.updateCharacteristic` is now an async Pigeon
callback, so the Dart future completes when the notification is settled rather
than when it was handed to the plugin. Awaiting it between chunks is therefore
real backpressure, and a native failure reaches the caller.

Android completes on `onNotificationSent` (success on GATT_SUCCESS, failure
otherwise). Apple completes when CBPeripheralManager.updateValue returns true,
immediately or after peripheralManagerIsReady(toUpdateSubscribers). Windows
completes from the NotifyValueAsync completion handler. With several targets,
the call completes once all settle, reporting the first error; a call with no
subscriber still updates the readable value and completes immediately.

A queued update that can never be sent now fails with a descriptive error
instead of leaving the Dart future pending: clearPendingNotifications,
removeService/clearServices, central unsubscription, adapter reset, engine
disposal and device disconnect all settle what they discard. Each update is
settled exactly once.

* Apple: O(1) queue and connection latency

PeripheralNotificationQueue keeps a read head index over its storage instead of
shifting the tail per chunk; storage is compacted in batches and released when
drained. drain() reports each accepted element through onSent exactly once,
and removeAll()/removeAll(where:) return what they discarded so those callers
can be failed. Backpressure semantics are unchanged.

Add UniversalBlePeripheral.setDesiredConnectionLatency (Apple only), mapped to
CBPeripheralManager.setDesiredConnectionLatency(_:for:). It throws notFound for
an unknown central. initialValues still receives the last value on every
update: that assignment is O(1) and was not the quadratic cost.

* Android: settle from onNotificationSent, and the #403 race

Track the in-flight PendingNotification per client address rather than just a
busy marker, so onNotificationSent can complete the right update. Settlement
is posted to the main handler; no Dart callback runs on a binder thread or
under the pendingNotifications monitor. The settlement is queued before the
next packet is handed to the stack, so two updates for one client complete in
submission order.

Apply the #403 fix in the same path: updateCharacteristic only writes
characteristic.value when nobody is subscribed, and drainNotifications holds
the pendingNotifications monitor across the in-flight check, dequeue,
bookkeeping, value assignment and notifyCharacteristicChanged. API 33+ uses the
stateless four-argument call and treats BluetoothStatusCodes.SUCCESS as sent;
older releases keep the deprecated three-argument call. isSubscribed is
resolved before taking the pending monitor, since the descriptor-write and
disconnect paths take the two locks in the opposite order.

* Windows: reply from the completion handler

UpdateCharacteristic returns the Pigeon reply callback and completes it from
NotifyValueAsync.Completed (success) or a non-completed status (failure), and
from the synchronous catch as before. The callback is copied into the lambda
rather than moved, so the catch path still holds a valid std::function instead
of throwing std::bad_function_call. Failure logging is unchanged.

* Dart, docs and tests

Add the platform-interface default no-op, the iOS/macOS-only forwarding that
canonicalises the device id, the public API and the PeripheralConnectionLatency
export. Rewrite the updateCharacteristicValue and README completion semantics
to describe pacing bulk transfers by awaiting the future, and document the
latency setter. CHANGELOG records the behavioural change under Unreleased.

Tests: Android adds four cases for the completion contract (accepted packet is
not completed early, non-success status fails, the #403 queued update does not
overwrite the in-flight value, and clearPendingNotifications/reset fail what
they discard). The Apple helper covers onSent exactly once, blocked elements
not reported until resume, and removeAll returning removed elements. Dart adds
the Apple forwarding/no-op latency test and two channel tests proving the
future waits for the native settlement reply and surfaces its failure.

Generated files were rebuilt with Pigeon 29.0.12, the version origin/main's
files were generated with, so their diff is limited to the new enum, the
asyncCallback signature and setDesiredConnectionLatency plus the resulting
codec type-index renumbering.

Verification: flutter analyze clean, flutter test 344 passed, Android unit
tests 136 passed, the Apple native reliability checks pass, and the shared
Apple sources typecheck for macOS and iOS. Windows is compile-checked by CI; it
cannot be built on macOS.

(#402)
fotiDim added a commit that referenced this pull request Nov 27, 2026
…) Darwin queue (#402) (#405)

Three independent causes made a bulk notification transfer slow (~15 KB/s):
the Darwin update was fire-and-forget, macOS negotiated latency=1, and the
Darwin pending queue removed elements with Array.removeFirst().

This also carries the #403 Android notification-race fix, aligned with
fix/403-android-notification-race (#404) so that #405 rebases cleanly once it
lands: the transmit critical section is the same code, and the only additions
here are the async settlement and completion aggregation.

* A completion contract for updateCharacteristicValue

`UniversalBlePeripheralChannel.updateCharacteristic` is now an async Pigeon
callback, so the Dart future completes when the notification is settled rather
than when it was handed to the plugin. Awaiting it between chunks is therefore
real backpressure, and a native failure reaches the caller.

Android completes on `onNotificationSent` (success on GATT_SUCCESS, failure
otherwise). Apple completes when CBPeripheralManager.updateValue returns true,
immediately or after peripheralManagerIsReady(toUpdateSubscribers). Windows
completes from the NotifyValueAsync completion handler. With several targets,
the call completes once all settle, reporting the first error; a call with no
subscriber still updates the readable value and completes immediately.

A queued update that can never be sent now fails with a descriptive error
instead of leaving the Dart future pending: clearPendingNotifications,
removeService/clearServices, central unsubscription, adapter reset, engine
disposal and device disconnect all settle what they discard. Each update is
settled exactly once.

* Apple: O(1) queue and connection latency

PeripheralNotificationQueue keeps a read head index over its storage instead of
shifting the tail per chunk; storage is compacted in batches and released when
drained. drain() reports each accepted element through onSent exactly once,
and removeAll()/removeAll(where:) return what they discarded so those callers
can be failed. Backpressure semantics are unchanged.

Add UniversalBlePeripheral.setDesiredConnectionLatency (Apple only), mapped to
CBPeripheralManager.setDesiredConnectionLatency(_:for:). It throws notFound for
an unknown central. initialValues still receives the last value on every
update: that assignment is O(1) and was not the quadratic cost.

* Android: settle from onNotificationSent, and the #403 race

Track the in-flight PendingNotification per client address rather than just a
busy marker, so onNotificationSent can complete the right update. Settlement
is posted to the main handler; no Dart callback runs on a binder thread or
under the pendingNotifications monitor. The settlement is queued before the
next packet is handed to the stack, so two updates for one client complete in
submission order.

Apply the #403 fix in the same path: updateCharacteristic only writes
characteristic.value when nobody is subscribed, and drainNotifications holds
the pendingNotifications monitor across the in-flight check, dequeue,
bookkeeping, value assignment and notifyCharacteristicChanged. API 33+ uses the
stateless four-argument call and treats BluetoothStatusCodes.SUCCESS as sent;
older releases keep the deprecated three-argument call. isSubscribed is
resolved before taking the pending monitor, since the descriptor-write and
disconnect paths take the two locks in the opposite order.

* Windows: reply from the completion handler

UpdateCharacteristic returns the Pigeon reply callback and completes it from
NotifyValueAsync.Completed (success) or a non-completed status (failure), and
from the synchronous catch as before. The callback is copied into the lambda
rather than moved, so the catch path still holds a valid std::function instead
of throwing std::bad_function_call. Failure logging is unchanged.

* Dart, docs and tests

Add the platform-interface default no-op, the iOS/macOS-only forwarding that
canonicalises the device id, the public API and the PeripheralConnectionLatency
export. Rewrite the updateCharacteristicValue and README completion semantics
to describe pacing bulk transfers by awaiting the future, and document the
latency setter. CHANGELOG records the behavioural change under Unreleased.

Tests: Android adds four cases for the completion contract (accepted packet is
not completed early, non-success status fails, the #403 queued update does not
overwrite the in-flight value, and clearPendingNotifications/reset fail what
they discard). The Apple helper covers onSent exactly once, blocked elements
not reported until resume, and removeAll returning removed elements. Dart adds
the Apple forwarding/no-op latency test and two channel tests proving the
future waits for the native settlement reply and surfaces its failure.

Generated files were rebuilt with Pigeon 29.0.12, the version origin/main's
files were generated with, so their diff is limited to the new enum, the
asyncCallback signature and setDesiredConnectionLatency plus the resulting
codec type-index renumbering.

Verification: flutter analyze clean, flutter test 344 passed, Android unit
tests 136 passed, the Apple native reliability checks pass, and the shared
Apple sources typecheck for macOS and iOS. Windows is compile-checked by CI; it
cannot be built on macOS.

(#402)
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.

[Bug]: (Android) Data corruption during rapid multi-chunk notifications

1 participant