Skip to content

Peripheral: document and test the updateCharacteristicValue timeout contract - #406

Merged
fotiDim merged 2 commits into
mainfrom
docs/peripheral-update-timeout
Nov 27, 2026
Merged

fotiDim merged 2 commits into
mainfrom
docs/peripheral-update-timeout

Conversation

@fotiDim

@fotiDim fotiDim commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #405 (issue #402). That PR made UniversalBlePeripheral.updateCharacteristicValue complete when the native platform settles the notification. Its review left a residual risk: the async native reply has no timeout, so a stack that reports neither onNotificationSent nor peripheralManagerIsReady leaves the future pending. Is a timeout on the Dart side enough?

Yes, as the caller-facing guarantee. This PR documents that contract and locks it down with tests; it does not change production behaviour.

Why the Dart timeout is sufficient for callers

updateCharacteristicValue is dispatched through BleCommandQueue.queueCommand, so it inherits the peripheral queue timeout: 10 s by default, overridable with UniversalBlePeripheral.timeout, disabled with null.

  • QueueType.perDevice/global (Android, Web, Linux; or explicit): the queue item awaits closure().timeout(...), completes the caller's future with a TimeoutException, and its onComplete runs the next queued command. The bound starts when the item runs, so time spent waiting behind earlier commands is not counted.
  • QueueType.none (Apple, Windows): the returned future is wrapped directly with .timeout(...) at submission.

So the caller gets an answer once the command runs, and a timed-out command does not wedge later work.

Why a native timeout is unsafe

  • Android's onNotificationSent(device, status) carries no packet identity. notificationsInFlight is keyed by client address and settles whatever is marked for that client. A native watchdog that cleared the marker and re-sent could not distinguish a lost callback from a slow link: it could mark a later packet complete early (double send, out-of-order notifications) or drop a packet the stack actually sent.
  • Apple's peripheralManagerIsReady(toUpdateSubscribers:) is already the documented readiness signal, and CBPeripheralManager.updateValue returns acceptance. A watchdog on top would have no additional identity to match against.
  • From the native side, a stack that never settles a notification is indistinguishable from one that is still sending. Guessing converts a slow link into duplicated or reordered data.

The reliable teardown paths are the existing ones: a central disconnecting and the adapter-reset path settle every pending update.

Recovery guidance

Await the failure, then call clearPendingNotifications(deviceId) to discard what is still waiting — the Dart queue, plus the platform's pending queue on Android and Apple. A packet already handed to the OS cannot be recalled, and work still queued natively may yet be delivered. The call cannot withdraw a packet already in flight: Android keeps its in-flight marker until onNotificationSent, so later updates for that client still wait behind the timed-out packet, and Windows has no plugin-owned queue at all. If the link itself is wedged, have the central disconnect or reset the adapter (Bluetooth off/on), which fails every pending update; clearServices() also settles all pending updates if re-registering the services is acceptable.

Residual gap: no remote acknowledgement is implied. The timeout tells the caller to stop waiting, not that the peer received or missed a packet. Applications that need delivery guarantees must implement an application-level acknowledgement.

Evidence

New tests in test/ble_peripheral_command_queue_test.dart use a fake peripheral platform whose updateCharacteristicValue never completes:

  1. a 50 ms global timeout fails UniversalBlePeripheral.updateCharacteristicValue with TimeoutException in QueueType.perDevice;
  2. a command queued behind the timed-out one still executes, so the queue is not wedged;
  3. the same timeout bounds the directly wrapped QueueType.none path used on Apple/Windows;
  4. UniversalBlePeripheral.timeout = null disables the timeout (a command released after the previously configured 50 ms succeeds).

The timeouts only need "eventually times out", with no upper bound on the passing path, so a slow runner cannot flake them. UniversalBlePeripheral.timeout is static state; tearDown restores the 10 s default, and setUp reconfigures it for each test.

flutter analyze clean, flutter test 348/348 passing, this test file passing under flutter test --platform chrome, and the Android plugin unit tests (:universal_ble:testDebugUnitTest) pass.

Files: lib/src/universal_ble_peripheral.dart (API contract), README.md (timeout and recovery contract, why no native watchdog), test/ble_peripheral_command_queue_test.dart (four regression tests).

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.
…isticValue

The README and the dartdoc said the update future is bounded by the
peripheral command timeout, but in QueueType.global and QueueType.perDevice
the timeout starts only when the queue item runs: Queue._QueuedFuture.execute
wraps closure() in .timeout() at that point, so time spent waiting behind
earlier commands is not counted. QueueType.none, the QueueType.auto default on
Apple and Windows, bounds the call as submitted. Say which one applies.

The recovery advice also overclaimed clearPendingNotifications. On Android it
drops the queued notifications and keeps the in-flight marker until
onNotificationSent arrives (dropNotifications(includeInFlight = false), as
asserted by clearPendingNotificationsFailsQueuedUpdatesButKeepsTheOneInFlight),
so later updates for that client still wait behind the packet that timed out.
Windows has no plugin-owned queue: ClearPendingNotifications returns without
touching anything, so an operation already running cannot be cancelled. Spell
out what the call discards and what it cannot recall.

List UniversalBlePeripheral.timeout in the README Timeout section, which only
covered UniversalBle.timeout, and cross-link the notification caveats.

Also explain why the "does not wedge the queue" test releases its gate after
the second submission: the fake reads the field when the platform call starts,
so the first update keeps the never-completing completer.

Verification: flutter analyze clean, flutter test 348 passed, and this test
file also passes under flutter test --platform chrome.
@fotiDim
fotiDim merged commit a2f343f into main Nov 27, 2026
4 checks passed
@fotiDim
fotiDim deleted the docs/peripheral-update-timeout branch November 27, 2026 06:23
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