Repository navigation
Android peripheral: serialize notification value with the in-flight send (#403) - #404
Merged
Merged
Conversation
…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
force-pushed
the
fix/403-android-notification-race
branch
from
November 26, 2026 20:40
27b8f40 to
0287171
Compare
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
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What was wrong
On Android,
updateCharacteristicwrote the sharedBluetoothGattCharacteristic.valueunconditionally, whiledrainNotificationsalso assigned it and called the deprecated 3-argumentnotifyCharacteristicChanged— and did both outside thependingNotificationsmonitor (its in-flight check was outside too).drainNotificationsruns fromonNotificationSenton 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, thenotificationsInFlightmarker, the value assignment and the notify call inside a singlesynchronized(pendingNotifications)block. On failure the marker is removed and the payload goes back to the front of the queue, as before.notifyCharacteristicChanged(device, characteristic, indicate, value)and treats onlyBluetoothStatusCodes.SUCCESSas sent; the deprecated 3-argument overload is kept for older releases.updateCharacteristicresolves the subscribed devices before taking thependingNotificationsmonitor (isSubscribedtakessubscribedCharDevicesMap, 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.Unreleased.Tests
queuedUpdateDoesNotOverwriteInFlightCharacteristicValueinandroid/src/test/.../PeripheralRegressionTest.kt: after a first update, a second update queued while the first is in flight must not touchcharacteristic.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 analyzeclean.flutter test: 341 passed.cd example/android && gradle :universal_ble:testDebugUnitTest(Gradle 9.3.1, Java 17): 132 passed.Fixes #403