Repository navigation
Peripheral: notification backpressure on Android/Apple/Windows, O(1) Darwin queue (#402) - #405
Merged
Merged
Conversation
fotiDim
force-pushed
the
fix/402-peripheral-backpressure
branch
from
November 26, 2026 20:51
3f8883f to
29ba648
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)
…) 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
force-pushed
the
fix/402-peripheral-backpressure
branch
from
November 27, 2026 06:08
29ba648 to
946698a
Compare
This was referenced Nov 27, 2026
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.
Summary
Bulk peripheral notifications were limited to roughly 15 KB/s on Darwin. The
issue names three independent causes, and this branch fixes all three, plus the
cross-platform contract change the first one requires.
updateCharacteristicwas fire-and-forget: it appended to an unboundedpendingNotificationsarray and returnedvoid, soupdateCharacteristicValuecompleted before anything was transmitted.updateCharacteristicis an@asyncCallbacknow and completes when every target central's notification is settled. Queued updates that are discarded fail their Dart future instead of leaking.CBPeripheralManager.setDesiredConnectionLatency(_:for:)was never called or exposed, so macOS negotiatedlatency = 1.UniversalBlePeripheral.setDesiredConnectionLatency(deviceId, PeripheralConnectionLatency.low/medium/high), Apple-only and mapped to CoreBluetooth.PeripheralNotificationQueue.drainusedArray.removeFirst(), O(N) per chunk and O(N²) over a transfer, on the main queue.Stacked on #404
This branch carries the #403 Android notification-race fix, but it is not on
mainyet: it comes fromfix/403-android-notification-race(#404, now at0287171). The shared Android notification path is byte-for-byte #404's finalversion; the only differences in
android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePeripheralPlugin.ktare the #402 async settlement and completion aggregation, so this branch rebases
cleanly once #404 lands. Its #403 regression test is adapted to the completion
callbacks and still asserts that a queued update does not overwrite the value
of the packet in flight.
#404 should merge first.
The new completion contract
UniversalBlePeripheralChannel.updateCharacteristicreplies when thenotification is settled, so awaiting
updateCharacteristicValueis realbackpressure and native failures reach Dart:
onNotificationSent— success onGATT_SUCCESS, failure on any other status.CBPeripheralManager.updateValuereturnstrue,immediately or later from
peripheralManagerIsReady(toUpdateSubscribers:).NotifyValueAsync.Completedhandler, failing ona non-completed status.
With several targeted centrals the call completes once all of them settle,
reporting the first error. With no subscriber it updates the readable value and
completes immediately, so static characteristics behave as before.
A queued update that can never be sent now fails with a descriptive error
rather than leaving the future pending:
clearPendingNotifications,removeService/clearServices, central unsubscription, adapter reset, enginedisposal and device disconnect all settle what they discard, exactly once.
Every
characteristic.valuewrite stays ordered with the transmit.This is a behavioural change (awaiting now waits for delivery), not a signature
break: the Dart parameter list is unchanged.
Platform notes
Apple. The queue keeps a read head index, reports each accepted element
exactly once through
onSent, and returns the elementsremoveAll()/removeAll(where:)discard so their futures can be failed.initialValuesstill receives the last value on every update — that assignment is O(1) and was
not the quadratic cost. Everything remains on the main queue.
Android. The in-flight
PendingNotificationis tracked per client address(not just a set), settlement is posted to the main handler, and no Dart callback
runs on a binder thread or under the
pendingNotificationsmonitor. Thesettlement is queued before the next packet is handed to the stack, so two
updates for one client complete in submission order, and
dispose()no longersweeps away the settlements its own reset just posted. The #403 transmit
critical section is unchanged: in-flight check, dequeue,
characteristic.valueassignment andnotifyCharacteristicChangedunder onemonitor; API 33+ stateless four-argument call with
BluetoothStatusCodes.SUCCESS; the no-subscriber write also under that monitor;isSubscribedresolved outside it.Windows.
UpdateCharacteristicreturns the Pigeon reply callback andcompletes it exactly once from the async completion handler or the synchronous
catch. The callback is copied into the lambda, not moved, so the catch path
still has a valid
std::function. Failure logging is unchanged.Generated files
Rebuilt with Pigeon 29.0.12, the version
origin/main's files weregenerated with, so there is no generator-version churn. The generated diff
contains only the new
PeripheralConnectionLatencyenum (which shifts the codectype indices), the
@asyncCallbacksignature ofupdateCharacteristic, andUniversalBleDarwinPeripheralChannel.setDesiredConnectionLatency:lib/src/universal_ble.g.dartUniversalBle.g.ktUniversalBle.g.swiftwindows/src/generated/universal_ble.g.cppwindows/src/generated/universal_ble.g.hpubspec.yaml/pubspec.lockare unchanged.Tests
flutter analyze— clean.flutter test— 344 passed. Includes the Apple forwarding/no-op latency testand two channel tests proving the future waits for the native settlement reply
and surfaces its failure.
:universal_ble:testDebugUnitTest— 136 passed. New cases cover: thecallback is not invoked while
notifyCharacteristicChangedaccepts the writeand completes after
onNotificationSentsucceeds; a non-success status failsit; the [Bug]: (Android) Data corruption during rapid multi-chunk notifications #403 queued update does not overwrite the in-flight value; and
clearPendingNotifications/ adapter reset fail what they discard.bash darwin/test/run_peripheral_reliability_tests.sh— passes. Extended foronSentexactly-once reporting, blocked elements not being reported untilresume, andremoveAllreturning removed elements.bash .github/scripts/typecheck_apple.sh— the shared Apple sources typecheckfor macOS and iOS.
Windows is not built locally (no Windows toolchain on macOS); it is
compile-checked by the CI Windows job.
Rebased onto
origin/main8979822, so the #400 Windows service-denialdiscovery work is preserved.
Fixes #402