Skip to content

fix: guard Android BLE connectPeripheral against race condition (status=5) - #6067

Merged
mdmohsin7 merged 8 commits into
mainfrom
fix/android-ble-connect-race
Mar 27, 2026
Merged

mdmohsin7 merged 8 commits into
mainfrom
fix/android-ble-connect-race

Conversation

@mdmohsin7

Copy link
Copy Markdown
Member

Summary

  • Guard connectPeripheral and reconnectKnownPeripheral against re-entry using a connectingAddresses set — if a GATT connect is already in-flight for an address, skip the duplicate call
  • Tag every connectPeripheral invocation with its caller chain for log traceability (e.g. connectPeripheral(FgService/CompanionSvc.fallback): D3:6A:...)
  • Clear the connecting guard on onConnectionStateChange (both connected and disconnected) and disconnectPeripheral

Root cause: Three callers race into connectPeripheral within milliseconds during initial connection:

  1. Dart ensureConnection → connectPeripheral
  2. CompanionSvc.fallback (onCreate) → FgService.startService(shouldConnect=true) → connectPeripheral
  3. CompanionSvc.deviceAppeared → FgService.startService(shouldConnect=true) → connectPeripheral

Each call closed the in-flight GATT and opened a new one, corrupting the bond encryption handshake → status=5 (GATT_INSUFFICIENT_AUTHENTICATION) → native marks as non-retryable → connection fails.

Test plan

  • Fresh pair on Android — only one connectPeripheral call reaches GATT, others log "already in-flight, skipping"
  • Device goes out of range and back — reconnects cleanly
  • DFU update — disconnect, update, reconnect after reboot
  • Check logs for caller tags on each connectPeripheral invocation

🤖 Generated with Claude Code

Multiple callers (Dart ensureConnection, FgService, CompanionSvc) can
invoke connectPeripheral within milliseconds. Each call closed the
in-flight GATT and opened a new one, corrupting the encryption handshake
and causing status=5 (GATT_INSUFFICIENT_AUTHENTICATION) disconnects.

Add connectingAddresses set to track in-flight connects and skip
duplicate calls. Also add caller tags for log traceability.
Propagate caller identity from startService() through to
connectPeripheral() so logs show the full call chain
(e.g. FgService/CompanionSvc.fallback).
Tag handleDeviceAppeared and startForegroundServiceFallback with
distinct caller strings so logs identify which CompanionSvc path
triggered the connection attempt.
@greptile-apps

greptile-apps Bot commented Mar 26, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR addresses the Android BLE status=5 (GATT_INSUFFICIENT_AUTHENTICATION) failure by introducing a connectingAddresses set to prevent multiple callers (Dart, CompanionSvc.fallback, CompanionSvc.deviceAppeared) from racing into connectGatt simultaneously. It also adds cancelPendingReconnect() to the front of connectPeripheral and reconnectKnownPeripheral (resolving the previously-flagged pending-reconnect race), moves startRssiKeepAlive to onServicesDiscovered, and adds a new stale-bond removal path for auth-failure disconnects.\n\nKey findings:\n\n- disconnectAllPeripherals doesn't clear connectingAddresses — close() is called immediately after disconnect() (a known BLE anti-pattern), which can suppress onConnectionStateChange when the BLE stack is tearing down (e.g., Bluetooth OFF). Any address that was in-flight at that moment stays in connectingAddresses, causing the reconnectKnownPeripheral guard to silently skip reconnection when Bluetooth is re-enabled.\n- connectingAddresses.remove fires before the stale-GATT guard — a stale GATT callback can prematurely lift the in-flight guard for the real active GATT, creating a narrow but reproducible window where a duplicate connectPeripheral call races through before the active GATT's callback fires.\n- Auth-failure retry loop has no cap if removeBond (reflection) silently fails — if the hidden API returns false or throws, the bond is not removed and the device will loop: connect → status=5 → removeBond(no-op) → reconnect indefinitely.\n- The caller tagging across all call sites and the discoverServices queue-guard are clean improvements.

Confidence Score: 3/5

Not safe to merge as-is — two P1 logic issues in OmiBleManager.kt can cause silent reconnection failures after Bluetooth toggle or stale GATT events.

The PR correctly solves the primary race (multiple callers racing connectGatt) and addresses the previously-flagged pending-reconnect issue. However, two new P1 issues are introduced: (1) disconnectAllPeripherals not clearing connectingAddresses can permanently block reconnection after BT toggle, and (2) connectingAddresses.remove firing before the stale-GATT guard can prematurely lift the in-flight guard. Both are direct consequences of the new connectingAddresses set and affect core reconnection reliability.

OmiBleManager.kt — specifically disconnectAllPeripherals (missing connectingAddresses.clear()) and the ordering at the top of onConnectionStateChange.

Important Files Changed

Filename Overview
app/android/app/src/main/kotlin/com/friend/ios/OmiBleManager.kt Core change: adds connectingAddresses ConcurrentHashSet guard to block duplicate in-flight GATTs, adds cancelPendingReconnect() to connectPeripheral/reconnectKnownPeripheral, and introduces auth-failure (status=5) bond-removal+retry path. Two P1 issues: disconnectAllPeripherals doesn't clear connectingAddresses (may block reconnect after BT toggle), and connectingAddresses.remove fires before the stale-GATT guard (can prematurely lift the guard).
app/android/app/src/main/kotlin/com/friend/ios/OmiBleForegroundService.kt Adds caller parameter propagation through startService → onStartCommand → connectToDevice → connectPeripheral. Clean, no issues.
app/android/app/src/main/kotlin/com/friend/ios/BleCompanionService.kt Adds caller tags to startService calls for log traceability. No logic changes.
app/android/app/src/main/kotlin/com/friend/ios/BleHostApiImpl.kt Passes caller = "Dart" to connectPeripheral. Trivial, no issues.
app/android/app/src/main/kotlin/com/example/my_project/MainActivity.kt Updates comment and adds caller tag to startService call (no behavior change, shouldConnect remains false by default). Clean.

Comments Outside Diff (1)

  1. app/android/app/src/main/kotlin/com/friend/ios/OmiBleManager.kt, line 551-556 (link)

    connectingAddresses.remove fires before the stale-GATT guard

    connectingAddresses.remove(address) is called unconditionally at the very top of onConnectionStateChange, before the stale-GATT check two lines later.

    Consider this sequence:

    1. GATT-A is in-flight → connectingAddresses contains the address.
    2. An unrelated code path closes GATT-A and opens GATT-B (e.g., a Bluetooth stack reset stores GATT-B in connectedGatts).
    3. GATT-A's delayed onConnectionStateChange fires first: connectingAddresses.remove(address) runs immediately → address is now gone from the guard set.
    4. Before GATT-B's callback fires, a race caller invokes connectPeripheral → the guard check passes (address not in connectingAddresses) → GATT-C is created and stored in connectedGatts, overwriting GATT-B.
    5. GATT-A hits the stale check connectedGatts[address] !== gatt and returns early — but the damage is done.

    Moving the remove to after the stale-GATT guard ensures a stale callback cannot prematurely unlock the guard for the real in-flight GATT:

Reviews (4): Last reviewed commit: "fix: prevent double discoverServices, de..." | Re-trigger Greptile


fun connectPeripheral(address: String) {
/** Addresses with an in-flight GATT connect (between connectGatt and onConnectionStateChange). */
private val connectingAddresses = mutableSetOf<String>()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P0 connectingAddresses is not thread-safe

mutableSetOf<String>() returns a LinkedHashSet, which is not synchronized. This set is written from the main thread (in connectPeripheral, disconnectPeripheral, reconnectKnownPeripheral) but read and removed from a BLE binder thread (onConnectionStateChange). The class's own Javadoc says "GATT callbacks arrive on binder threads", and the rest of the file already uses ConcurrentHashMap.newKeySet<String>() for similar cross-thread sets (manuallyDisconnected, servicesDiscoveredFor).

A concurrent remove from the binder thread and add from the main thread can produce a ConcurrentModificationException, silent data loss, or missed visibility of the write — defeating the race guard entirely.

Suggested change
private val connectingAddresses = mutableSetOf<String>()
private val connectingAddresses = ConcurrentHashMap.newKeySet<String>()

onConnectionStateChange fires on a BLE binder thread while
connectPeripheral runs on the main thread. A plain LinkedHashSet
can produce ConcurrentModificationException or silent data loss.
@mdmohsin7

Copy link
Copy Markdown
Member Author

@greptile-apps re-review

Comment on lines 209 to 250
@@ -227,20 +230,29 @@ class OmiBleManager private constructor(private val application: Application) {
}
}

// Guard: skip if a GATT connect is already in-flight for this address.
// Multiple callers (Dart ensureConnection, FgService, CompanionSvc) can race here.
if (connectingAddresses.contains(addr)) {
Log.i(TAG, "connectPeripheral($caller): $addr connect already in-flight, skipping")
return
}

connectedGatts[addr]?.close()
connectedGatts.remove(addr)
servicesDiscoveredFor.remove(addr)

val adapter = bluetoothAdapter ?: return
val device = adapter.getRemoteDevice(addr)
Log.i(TAG, "connectPeripheral: $addr")
Log.i(TAG, "connectPeripheral($caller): $addr")
connectingAddresses.add(addr)
val gatt = device.connectGatt(application, false, gattCallback, BluetoothDevice.TRANSPORT_LE)
connectedGatts[addr] = gatt
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 connectPeripheral doesn't cancel in-flight pending reconnect

connectPeripheral correctly guards against a duplicate in-flight GATT via connectingAddresses, but it never calls cancelPendingReconnect(). After a retryable disconnect, onConnectionStateChange (1) removes the address from connectingAddresses and (2) schedules a pendingReconnectRunnable for 3 seconds. If Dart calls connectPeripheral within that 3-second window, the guard check passes (address is no longer in connectingAddresses), connectGatt is called, and then 3 seconds later the delayed runnable fires and calls connectGatt a second time — exactly the race this PR aims to eliminate.

The delayed runnable also directly writes to connectedGatts[address], overwriting the GATT handle created by connectPeripheral, leaving the manager with a stale entry.

The fix is to call cancelPendingReconnect() early in connectPeripheral (and in reconnectKnownPeripheral for the same reason):

fun connectPeripheral(address: String, caller: String = "unknown") {
    val addr = address.uppercase()
    appClosed = false
    manuallyDisconnected.remove(addr)
    reconnectRetryCount[addr] = 0
+   cancelPendingReconnect()
    // ... rest of the function
}

Same fix applies to reconnectKnownPeripheral at line 281.

After a retryable disconnect, a 3s delayed reconnect runnable is
scheduled. If Dart calls connectPeripheral within that window, the
delayed runnable would fire and call connectGatt a second time,
overwriting the GATT handle. Cancel it on entry to both
connectPeripheral and reconnectKnownPeripheral.
@mdmohsin7

Copy link
Copy Markdown
Member Author

@greptile-apps re-review

…atus=5

- Route public discoverServices() through GATT command queue so Dart's
  call serializes behind the native bonded-path discovery and skips via
  servicesDiscoveredFor check (eliminates double discoverServices that
  overwhelmed the Omi firmware during setup)
- Move startRssiKeepAlive from onConnectionStateChange(CONNECTED) to
  onServicesDiscovered to reduce BLE traffic during critical setup phase
- Handle GATT status=5 (INSUFFICIENT_AUTHENTICATION) by removing stale
  bond and retrying with autoConnect=true so re-pairing happens naturally
- Guard auto-reconnect runnables with connectingAddresses to prevent
  concurrent GATT creation from reconnect timer + connectPeripheral race
@mdmohsin7

Copy link
Copy Markdown
Member Author

@greptile-apps re-review

@mdmohsin7
mdmohsin7 merged commit 021208c into main Mar 27, 2026
3 checks passed
@mdmohsin7
mdmohsin7 deleted the fix/android-ble-connect-race branch March 27, 2026 13:16
Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
…us=5) (BasedHardware#6067)

## Summary

- Guard `connectPeripheral` and `reconnectKnownPeripheral` against
re-entry using a `connectingAddresses` set — if a GATT connect is
already in-flight for an address, skip the duplicate call
- Tag every `connectPeripheral` invocation with its caller chain for log
traceability (e.g. `connectPeripheral(FgService/CompanionSvc.fallback):
D3:6A:...`)
- Clear the connecting guard on `onConnectionStateChange` (both
connected and disconnected) and `disconnectPeripheral`

**Root cause:** Three callers race into `connectPeripheral` within
milliseconds during initial connection:
1. **Dart** `ensureConnection` → `connectPeripheral`
2. **CompanionSvc.fallback** (onCreate) →
`FgService.startService(shouldConnect=true)` → `connectPeripheral`
3. **CompanionSvc.deviceAppeared** →
`FgService.startService(shouldConnect=true)` → `connectPeripheral`

Each call closed the in-flight GATT and opened a new one, corrupting the
bond encryption handshake → `status=5`
(`GATT_INSUFFICIENT_AUTHENTICATION`) → native marks as non-retryable →
connection fails.

## Test plan
- [ ] Fresh pair on Android — only one `connectPeripheral` call reaches
GATT, others log "already in-flight, skipping"
- [ ] Device goes out of range and back — reconnects cleanly
- [ ] DFU update — disconnect, update, reconnect after reboot
- [ ] Check logs for caller tags on each connectPeripheral invocation

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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