Skip to content

fix(connection): release callers merged into an attempt that ends - #105

Merged
framinosona merged 4 commits into
mainfrom
framinosona/merged-connect-callers
Nov 17, 2026
Merged

framinosona merged 4 commits into
mainfrom
framinosona/merged-connect-callers

Conversation

@framinosona

@framinosona framinosona commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

Summary

A ConnectAsync or DisconnectAsync call 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 timeout and cancellationToken, 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:

  • the owner times out or is cancelled: the owner's finally clears ConnectionTcs/DisconnectionTcs without completing it;
  • the joined call passes its own timeout or token: both are ignored, it only ever waits for the owner;
  • on platforms whose native cancel of a pending connect raises a disconnection callback, that callback completes the pending attempt successfully, so a joined ConnectAsync returned normally while the device was not connected.

Change

  • ConnectAsync/DisconnectAsync keep a reference to their own attempt. When the owner leaves through a timeout, cancellation or failure, it completes that attempt with DeviceFailedToConnectException/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.
  • A joined call waits with Task.WaitAsync(timeout, token). TimeoutException and OperationCanceledException mean what they mean for any call; giving up does not cancel the attempt it joined. WaitBetterAsync is not used here because it ignores the token when no timeout is given (Plugin.BaseTypeExtensions#62).
  • A joined ConnectAsync checks IsConnected after the wait, like the owner, and normalizes an opaque failure to DeviceFailedToConnectException like the owner does.
  • Both attempt tasks use RunContinuationsAsynchronously, so a joined call released by the owner does not run its own code inside the owner's cleanup.
  • Joining or owning an attempt, and releasing it, are each one step under a small gate (_attemptGate, the same idea as _stopGate in 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/IsDisconnecting are 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.
  • A joined 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 throws TimeoutException; giving up still does not cancel the owner's attempt (Copilot's first review).
  • XML remarks on ConnectAsync/DisconnectAsync say what joining means.

Change Type

  • Feature
  • Bug fix
  • Refactor (refa)
  • Docs only
  • CI/build/tooling

Affected Areas

  • Abstractions (XML docs only)
  • Core
  • Platform: Android
  • Platform: iOS/macOS
  • Platform: Windows
  • Platform: DotNetCore fallback
  • Facade (Bluetooth.Maui)
  • Documentation

Behavior And Compatibility

  • Public API changed
  • Exception behavior changed
  • DI registration behavior changed
  • Capability matrix impact
  • No externally visible behavior change

No signature changes. Only calls that join an attempt in progress behave differently:

  • they return or throw when the owner gives up, or when their own timeout or token fires, instead of waiting for ever;
  • a joined ConnectAsync whose attempt fails now throws DeviceFailedToConnectException (the native exception inside), as the owner always did, instead of the raw native exception;
  • a joined ConnectAsync no 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

  • Unit tests added/updated
  • Integration/smoke tests added/updated
  • Manual platform validation performed
  • Not applicable (explain)

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 BaseBluetoothRemoteDevice with a fake native layer on a Mac; no hardware is involved. Same harness, main against this branch:

    A joined caller, while the owner... main This PR
    ConnectAsync times out (300 ms), joined caller has no timeout still pending after 3 s throws DeviceFailedToConnectException (the TimeoutException inside) after 258 ms
    ConnectAsync is cancelled by its token, joined caller has none still pending after 3 s throws DeviceFailedToConnectException (cancellation inside) after 194 ms
    DisconnectAsync times out or is cancelled, joined caller has none still pending after 3 s throws DeviceFailedToDisconnectException after about 250 ms
    joined caller passes its own 200 ms timeout (owner has 2 s), connect and disconnect ignored, still pending after 1.5 s TimeoutException after 201 ms; the owner still times out at 2 s and no native disconnect was issued by the joined caller giving up
    joined caller is cancelled after 200 ms (no timeout), connect and disconnect still pending after 1.5 s OperationCanceledException after 200 ms
    three joined callers, owner times out, connect and disconnect all three still pending after 3 s all three released after about 250 ms
    owner gives up and its native cleanup raises a disconnection callback, joined ConnectAsync returns normally after 249 ms while IsConnected is false throws DeviceFailedToConnectException
    native failure reported while a ConnectAsync is joined joined caller gets the raw InvalidOperationException DeviceFailedToConnectException (native exception inside), like the owner
    owner succeeds / fails normally, a new attempt after an abandoned one, owner gives up with nobody joined (cleanup callback still absorbed: 0 UnexpectedDisconnection, one native disconnect), unobserved task exceptions after a GC pass pass
    randomized: 400 rounds, 1 to 3 joined callers with random timeouts and tokens, the platform completing, failing or staying silent, connect and disconnect alternating 186 rounds with a call still pending after 1.5 s 0 rounds with a pending call; 0 unexpected exception types; IsConnecting/IsDisconnecting clear after every round
    two ConnectAsync calls entering at the same instant (a start gate), both bounded, 400 rounds 37 rounds with two native connects (both callers owned an attempt); a caller still pending after 2 s in 363 rounds 0 rounds with two native connects; both finish and the device is idle in every round
    two DisconnectAsync calls entering at the same instant, 400 rounds on the branch, 80 on main (it waits out each hung round) 3 of 80 rounds with two native disconnects; a call still pending in 77 of 80 0 of 400 with two native disconnects
    joined 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 ms no counterpart: main never refreshes in a joined call TimeoutException after 301 ms; OperationCanceledException after 251 ms; the owner's attempt is unaffected and finishes once the refresh is released
    total 27 of the first 44 checks pass; 0 of the 3 simultaneous-entry checks 51 of 51 pass

    Except 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

  • Docs updated in same PR
  • Capability claims verified against implementation
  • Links validated
  • Not applicable (explain)

Logging / Diagnostics

  • New logs added
  • EventId range validated
  • No logging changes

Risks And Follow-ups

Risk level:

  • Low
  • Medium
  • High

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:

  • The same read-then-write owner decision exists in StartScanningAsync and StartBroadcastingAsync, together with the same unbounded merge for a second concurrent start; not part of this PR.
  • An owner that passes a token but no timeout still cannot be cancelled while it waits for the native callback (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.
  • Not run on Android, iOS or Windows hardware.

Checklist

  • I reviewed Docs/Best-Practices/Contribution-DoD.md
  • Commit header follows type (scope): short imperative and is <= 72 chars
  • Commit type is one of: feat, fix, refa, perf, docs, ci, chore, test, build
  • Commit body is 1-2 factual sentences (what/why), no emojis, refs, or co-authors
  • If architectural behavior changed, an ADR was added or updated under Docs/Architecture/ADR

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.
Copilot AI balanced review requested due to automatic review settings November 10, 2026 12:04

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.
Copilot AI balanced review requested due to automatic review settings November 10, 2026 12:52

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.
Copilot AI balanced review requested due to automatic review settings November 16, 2026 14:20

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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

@framinosona
framinosona merged commit d5a6dc3 into main Nov 17, 2026
10 checks passed
@framinosona
framinosona deleted the framinosona/merged-connect-callers branch November 17, 2026 16:28
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.

2 participants