Skip to content

Peripheral: notification backpressure on Android/Apple/Windows, O(1) Darwin queue (#402) - #405

Merged
fotiDim merged 1 commit into
mainfrom
fix/402-peripheral-backpressure
Nov 27, 2026
Merged

fotiDim merged 1 commit into
mainfrom
fix/402-peripheral-backpressure

Conversation

@fotiDim

@fotiDim fotiDim commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

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.

Root cause Fix
Darwin updateCharacteristic was fire-and-forget: it appended to an unbounded pendingNotifications array and returned void, so updateCharacteristicValue completed before anything was transmitted. updateCharacteristic is an @asyncCallback now 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 negotiated latency = 1. New UniversalBlePeripheral.setDesiredConnectionLatency(deviceId, PeripheralConnectionLatency.low/medium/high), Apple-only and mapped to CoreBluetooth.
PeripheralNotificationQueue.drain used Array.removeFirst(), O(N) per chunk and O(N²) over a transfer, on the main queue. The queue is a head-indexed O(1) FIFO, compacted in batches and released when drained.

Stacked on #404

This branch carries the #403 Android notification-race fix, but it is not on
main yet
: it comes from fix/403-android-notification-race (#404, now at
0287171). The shared Android notification path is byte-for-byte #404's final
version; the only differences in
android/src/main/kotlin/com/navideck/universal_ble/UniversalBlePeripheralPlugin.kt
are 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.updateCharacteristic replies when the
notification is settled, so awaiting updateCharacteristicValue is real
backpressure and native failures reach Dart:

  • Android replies from onNotificationSent — success on
    GATT_SUCCESS, failure on any other status.
  • Apple replies when CBPeripheralManager.updateValue returns true,
    immediately or later from peripheralManagerIsReady(toUpdateSubscribers:).
  • Windows replies from the NotifyValueAsync.Completed handler, failing on
    a 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, engine
disposal and device disconnect all settle what they discard, exactly once.
Every characteristic.value write 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 elements removeAll() /
removeAll(where:) discard so their futures can be failed. initialValues
still 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 PendingNotification is 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 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, and dispose() no longer
sweeps away the settlements its own reset just posted. The #403 transmit
critical section is unchanged: in-flight check, dequeue,
characteristic.value assignment and notifyCharacteristicChanged under one
monitor; API 33+ stateless four-argument call with
BluetoothStatusCodes.SUCCESS; the no-subscriber write also under that monitor;
isSubscribed resolved outside it.

Windows. UpdateCharacteristic returns the Pigeon reply callback and
completes 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 were
generated with, so there is no generator-version churn. The generated diff
contains only the new PeripheralConnectionLatency enum (which shifts the codec
type indices), the @asyncCallback signature of updateCharacteristic, and
UniversalBleDarwinPeripheralChannel.setDesiredConnectionLatency:

File +/−
lib/src/universal_ble.g.dart +99 −54
UniversalBle.g.kt +120 −61
UniversalBle.g.swift +115 −60
windows/src/generated/universal_ble.g.cpp +106 −61
windows/src/generated/universal_ble.g.h +26 −3

pubspec.yaml/pubspec.lock are unchanged.

Tests

  • flutter analyze — clean.
  • flutter test — 344 passed. Includes the Apple forwarding/no-op latency test
    and two channel tests proving the future waits for the native settlement reply
    and surfaces its failure.
  • Android :universal_ble:testDebugUnitTest — 136 passed. New cases cover: the
    callback is not invoked while notifyCharacteristicChanged accepts the write
    and completes after onNotificationSent succeeds; a non-success status fails
    it; 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 for
    onSent exactly-once reporting, blocked elements not being reported until
    resume, and removeAll returning removed elements.
  • bash .github/scripts/typecheck_apple.sh — the shared Apple sources typecheck
    for 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/main 8979822, so the #400 Windows service-denial
discovery work is preserved.

Fixes #402

@fotiDim
fotiDim force-pushed the fix/402-peripheral-backpressure branch from 3f8883f to 29ba648 Compare November 26, 2026 20:51
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
fotiDim force-pushed the fix/402-peripheral-backpressure branch from 29ba648 to 946698a Compare November 27, 2026 06:08
@fotiDim
fotiDim merged commit 937ee2e into main Nov 27, 2026
4 checks passed
@fotiDim
fotiDim deleted the fix/402-peripheral-backpressure branch November 27, 2026 06:09
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]: Slow bulk notifications on Darwin due to missing backpressure and O(N²) PeripheralNotificationQueue

1 participant