Repository navigation
fix: guard Android BLE connectPeripheral against race condition (status=5) - #6067
Conversation
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 SummaryThis PR addresses the Android BLE Confidence Score: 3/5Not safe to merge as-is — two P1 logic issues in The PR correctly solves the primary race (multiple callers racing
Important Files Changed
|
|
|
||
| fun connectPeripheral(address: String) { | ||
| /** Addresses with an in-flight GATT connect (between connectGatt and onConnectionStateChange). */ | ||
| private val connectingAddresses = mutableSetOf<String>() |
There was a problem hiding this comment.
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.
| 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.
|
@greptile-apps re-review |
| @@ -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 | |||
| } | |||
There was a problem hiding this comment.
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.
|
@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
|
@greptile-apps re-review |
…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)
Summary
connectPeripheralandreconnectKnownPeripheralagainst re-entry using aconnectingAddressesset — if a GATT connect is already in-flight for an address, skip the duplicate callconnectPeripheralinvocation with its caller chain for log traceability (e.g.connectPeripheral(FgService/CompanionSvc.fallback): D3:6A:...)onConnectionStateChange(both connected and disconnected) anddisconnectPeripheralRoot cause: Three callers race into
connectPeripheralwithin milliseconds during initial connection:ensureConnection→connectPeripheralFgService.startService(shouldConnect=true)→connectPeripheralFgService.startService(shouldConnect=true)→connectPeripheralEach 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
connectPeripheralcall reaches GATT, others log "already in-flight, skipping"🤖 Generated with Claude Code