Repository navigation
fix(connection): release callers merged into an attempt that ends - #105
Conversation
A caller merged into a connect or disconnect attempt waited on the owner's task with neither its own timeout nor its token, and nothing completed that task when the owner gave up. The owner now ends its attempt, a merged caller is bounded by its own timeout and token, and the owner's cleanup leaves a later attempt's state alone.
ConnectAsync and DisconnectAsync join an attempt in progress; the remarks state what such a call returns or throws and that its own timeout and token bound only its wait.
There was a problem hiding this comment.
🟡 Changes recommended
A critical ownership-transition race can erase a retry task and leave callers waiting indefinitely, while merged callers’ finite timeouts do not cover the subsequent refresh.
2 open issues
What changed in this PR
This PR addresses shared connection-attempt hangs in the platform-independent Core layer, releasing joined callers when an owner abandons an attempt and adding caller-specific timeout and cancellation handling.
Changes:
- Completes abandoned attempt tasks and adds ownership checks during cleanup.
- Adds bounded waits for joined callers, connection-state validation, and connection-failure normalization.
- Documents joining behavior without changing public API signatures.
| File | Description |
|---|---|
Bluetooth.Core.Scanning/BaseBluetoothRemoteDevice.Connection.cs |
Updates shared-attempt waiting, completion, and cleanup for connect/disconnect operations. |
Bluetooth.Abstractions.Scanning/IBluetoothRemoteDevice.Connection.cs |
Adds XML documentation for joined calls, cancellation, timeouts, and failures. |
Review effort: Balanced
Deciding whether to join or own an attempt, and releasing it, are now each one step, so a released caller's retry cannot be erased and two simultaneous callers cannot both own. A joined connect's refresh of the connection state gets what is left of the caller's timeout.
There was a problem hiding this comment.
🟡 Changes recommended
Connection and disconnection attempt updates synchronously notify subscribers while holding _attemptGate, creating a critical cross-thread deadlock risk before timeout-aware waits begin.
1 open issue
2 resolved since last review
Review effort: Balanced
ConnectionTcs and DisconnectionTcs were bindable properties, so assigning one inside _attemptGate raised PropertyChanged synchronously and ran subscribers while the gate was held. A subscriber that blocks on another thread entering ConnectAsync or DisconnectAsync then waits for a gate its own thread holds, before the caller reaches its timeout-aware wait. Both attempt references are now plain fields read and written with Volatile. They are private and nothing observes them through PropertyChanged; IsConnecting and IsDisconnecting stay the observable state and are still written outside the gate.
There was a problem hiding this comment.
🔵 Needs a closer look
Shared connection lifecycle changes lack hardware validation for Apple/Android cancellation-before-disconnect behavior, and the external fake-native harness does not establish delayed-callback or retry behavior.
No open issues 🎉
1 resolved since last review
Review effort: Balanced


Summary
A
ConnectAsyncorDisconnectAsynccall that arrives while another call's attempt is in progress joins that attempt, and waited on the owner's task with neither its own timeout nor its token. When the owner timed out or was cancelled, nothing completed that task, so the joined call never returned.The owner now ends its own attempt when it gives up, a joined call is bounded by its own
timeoutandcancellationToken, and the decision to join or own an attempt, like its release, is one atomic step.Refs #59 (item 6).
Why
On
main, in the cases below the joined call stays pending for ever:finallyclearsConnectionTcs/DisconnectionTcswithout completing it;ConnectAsyncreturned normally while the device was not connected.Change
ConnectAsync/DisconnectAsynckeep a reference to their own attempt. When the owner leaves through a timeout, cancellation or failure, it completes that attempt withDeviceFailedToConnectException/DeviceFailedToDisconnectException(the owner's exception inside). For a connect this happens after the native cancel, so the disconnection callback that cancel raises is still absorbed by the pending attempt and not reported as an unexpected disconnection.Task.WaitAsync(timeout, token).TimeoutExceptionandOperationCanceledExceptionmean what they mean for any call; giving up does not cancel the attempt it joined.WaitBetterAsyncis not used here because it ignores the token when no timeout is given (Plugin.BaseTypeExtensions#62).ConnectAsyncchecksIsConnectedafter the wait, like the owner, and normalizes an opaque failure toDeviceFailedToConnectExceptionlike the owner does.RunContinuationsAsynchronously, so a joined call released by the owner does not run its own code inside the owner's cleanup._attemptGate, the same idea as_stopGatein the scanner), and only the attempt fields are touched under it. The owner releases only the attempt that is still its own, so a joined call released by the owner can start the next attempt at once without the owner's cleanup erasing it (found by Copilot's first review).IsConnecting/IsDisconnectingare re-synced from the registered attempt outside the lock, until the two agree. This also means two callers entering at the same instant can no longer both own an attempt.ConnectAsync's refresh of the connection state after the wait gets what is left of the caller's timeout (and its token), and a refresh that overruns throwsTimeoutException; giving up still does not cancel the owner's attempt (Copilot's first review).ConnectAsync/DisconnectAsyncsay what joining means.Change Type
refa)Affected Areas
Bluetooth.Maui)Behavior And Compatibility
No signature changes. Only calls that join an attempt in progress behave differently:
ConnectAsyncwhose attempt fails now throwsDeviceFailedToConnectException(the native exception inside), as the owner always did, instead of the raw native exception;ConnectAsyncno longer returns normally while the device is not connected.A call that starts an attempt (the owner) behaves as before, except for the two internal points above (asynchronous continuations, and the cleanup that leaves another attempt's state alone).
Platform Notes
Core only, no platform file changes. Whether a platform's native cancel of a pending connect raises a disconnection callback varies; the change is written to be correct either way (both cases are in the harness below).
Tests
Validation notes:
The repository has no test project, so there are no automated tests in this PR. A throwaway console (not in the PR) subclasses
BaseBluetoothRemoteDevicewith a fake native layer on a Mac; no hardware is involved. Same harness,mainagainst this branch:mainConnectAsynctimes out (300 ms), joined caller has no timeoutDeviceFailedToConnectException(theTimeoutExceptioninside) after 258 msConnectAsyncis cancelled by its token, joined caller has noneDeviceFailedToConnectException(cancellation inside) after 194 msDisconnectAsynctimes out or is cancelled, joined caller has noneDeviceFailedToDisconnectExceptionafter about 250 msTimeoutExceptionafter 201 ms; the owner still times out at 2 s and no native disconnect was issued by the joined caller giving upOperationCanceledExceptionafter 200 msConnectAsyncIsConnectedisfalseDeviceFailedToConnectExceptionConnectAsyncis joinedInvalidOperationExceptionDeviceFailedToConnectException(native exception inside), like the ownerUnexpectedDisconnection, one native disconnect), unobserved task exceptions after a GCIsConnecting/IsDisconnectingclear after every roundConnectAsynccalls entering at the same instant (a start gate), both bounded, 400 roundsDisconnectAsynccalls entering at the same instant, 400 rounds on the branch, 80 onmain(it waits out each hung round)ConnectAsync, owner succeeds at 50 ms, the connection state refresh then stalls: caller with a 300 ms timeout; caller with a token cancelled at 250 msmainnever refreshes in a joined callTimeoutExceptionafter 301 ms;OperationCanceledExceptionafter 251 ms; the owner's attempt is unaffected and finishes once the refresh is releasedExcept in the simultaneous-entry rows, the joined caller starts after the owner has claimed the attempt.
The harness can be run on request; it is about 400 lines and lives outside the repo.
Documentation
Logging / Diagnostics
Risks And Follow-ups
Risk level:
Medium because it changes the shared connect/disconnect path every platform goes through, with hardware validation on none of them. The gate is held only for a field read and write, never across an
await, an event or a flag write.Known limitations or deferred follow-ups:
StartScanningAsyncandStartBroadcastingAsync, together with the same unbounded merge for a second concurrent start; not part of this PR.WaitBetterAsync, the "Addition to 5" on Connect/disconnect robustness: pre-existing timeout, double-reporting, and hang issues #59). The joined call now honours its token, so the two differ until that is fixed.Checklist
type (scope): short imperativeand is <= 72 chars