Modern Apps git

← Modern-Apps.git

wearlink: log conduit link failures and collapse duplicate contacts

Commit
f5d9ca400236652b6ff70188fe27c5b02af5fa48
Author
Vayun Mathur <[email protected]>
When
2026-12-04 22:02 UTC (1 day ago)
Parents
3108e1d
The Watch conduit RFCOMM handshake appeared to never complete between the Pixel 9 Pro XL and Pixel Watch 5: the phone cycled every bonded peripheral with 'read failed, socket might closed or timeout' while the watch showed a listening ModernApps WearLink server, yet no 'handshake failed' line ever appeared on either device.

Live diagnosis with temporary Log.status instrumentation (since removed) showed the main-tip handshake itself is sound: with current builds on both sides the watch dials the phone, both ends verify the cert-bound HELLO/HELLO_ACK (same signing cert hash on both), adopt the session within a second, and the link stays Connected (watch status screen confirms). What made the failure invisible and long-lived is that every other link state transition was silent: WearLinkNode.acceptLoop caught every listen/accept exception (SecurityException included) and retried every second with no log at all, a clean peer close ended readLoop with no log, and a successful adoption logged nothing, so neither failure nor success could be distinguished from a dead node in logcat. The phone also dials all ten bonded peripherals in sequence (several RFCOMM attempts take ~5 s each, and the watch fast-fails while its conduit is not yet listening), so phone-initiated reconnects are slow and depend on the watch dialling first.

Fix in WearLinkNode: log listen/accept failures with exception class and message, log 'connected to <peer>' on adoption, and log clean-EOF session ends like exceptional ones. Log.status is INFO and always emitted, and these are once-per-connection or once-per-failure events, so the next stall is diagnosable from logcat alone.

The same end-to-end run proved a second, user-visible defect: the contacts snapshot shipped duplicates to the watch. WearSnapshotBuilder.select documented 'duplicates collapsed' but only deduped by contact id; the same person arrives once as a device-provider row and once as a SIM row with different ids (measured live: 148 rows, 48 same-name/same-number duplicate groups). select now collapses by person identity (normalised name plus digit-normalised primary phone, or primary email), keeping the favourite/richest copy, before the existing favourite/A-Z sort and cap. A golden-protocol unit test pins the collapse (device + SIM copies, +1 prefix variant, merge to one row keeping the richer copy).

Verified: :library:wearlink:testDebugUnitTest and the contacts WearContactsProtocolTest (7 tests, including the new collapse test) pass; the only :contacts:testDevUnitTest failures are two Compose insert-or-edit tests that fail identically on the unmodified base. On device (Pixel 9 Pro XL + Pixel Watch 5) with these builds the conduit logs Connected on both sides, WearContactsSync publishes the snapshot, and WearLinkBridge on the watch receives the manifest and chunk with no 'not delivered' line.

Diff

contacts/src/test/java/com/vayunmathur/contacts/domain/WearContactsProtocolTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/domain/WearContactsProtocolTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/domain/WearContactsProtocolTest.ktindex 24c838895e..5d54b9cb80 100644--- a/contacts/src/test/java/com/vayunmathur/contacts/domain/WearContactsProtocolTest.kt+++ b/contacts/src/test/java/com/vayunmathur/contacts/domain/WearContactsProtocolTest.kt@@ -50,6 +50,19 @@ class WearContactsProtocolTest {         assertEquals(many.size, manifest.totalContacts)     } +    @Test+    fun `same person from two sources collapses to one snapshot row`() {+        // Device provider row and SIM row for one person: different ids,+        // same name and number (one carries the +1 country prefix).+        val device = WearContact(834L, "Ada Lovelace", listOf("4155550100"), listOf("[email protected]"))+        val sim = WearContact(1084L, "Ada Lovelace", listOf("+1 415 555 0100"))+        val other = WearContact(9L, "Grace Hopper", listOf("2025550199"))+        val selected = WearSnapshotBuilder.select(listOf(device, sim, other))+        assertEquals(2, selected.size)+        // The richer copy (with the email) survives the collapse.+        assertEquals(listOf("[email protected]"), selected.first { it.name == "Ada Lovelace" }.emails)+    }+     @Test     fun `per-contact lists and fields are capped`() {         val raw = WearContact(
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.ktindex ced6a07827..2f02a9113d 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.kt@@ -268,6 +268,7 @@ class WearLinkNode(                     runCatching { server.close() }                 }             } catch (expected: Exception) {+                Log.status(TAG, "listen/accept failed: ${expected::class.simpleName}: ${expected.message}")                 if (running) delay(1_000)             }         }@@ -371,6 +372,7 @@ class WearLinkNode(         }         activeSession = session         _state.value = WearLinkState.Connected(peerLabel)+        Log.status(TAG, "connected to $peerLabel")         scope.launch { readLoop(session, peerLabel) }         return true     }@@ -378,7 +380,11 @@ class WearLinkNode(     private fun readLoop(session: Session, peerLabel: String) {         try {             while (running && session.open) {-                val frame = FrameCodec.decode(session.socket.input) ?: break+                val frame = FrameCodec.decode(session.socket.input)+                if (frame == null) {+                    Log.status(TAG, "session ended: peer closed")+                    break+                }                 dispatch(session, frame)             }         } catch (expected: Exception) {
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/contacts/WearContactsProtocol.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/contacts/WearContactsProtocol.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/contacts/WearContactsProtocol.ktindex d0ecaf710b..f0a296d0f9 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/contacts/WearContactsProtocol.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/contacts/WearContactsProtocol.kt@@ -130,17 +130,45 @@ object WearSnapshotBuilder {      * (case-insensitive), ties by id. Blank-valued phones/emails are dropped,      * duplicates collapsed, every list and field capped per the protocol.      */-    fun select(contacts: List<WearContact>): List<WearContact> =-        contacts+    fun select(contacts: List<WearContact>): List<WearContact> {+        val normalised = contacts             .map { normalise(it) }             .filter { it.name.isNotBlank() || it.phones.isNotEmpty() || it.emails.isNotEmpty() }-            .distinctBy { it.id }+        // The same person arrives once per source (device provider row and+        // SIM row carry different ids), so id-only dedupe ships duplicates+        // to the watch. Collapse by person identity (normalised name plus+        // primary phone/email), keeping the favourite / richest copy.+        val deduped = normalised+            .sortedWith(+                compareByDescending<WearContact> { it.isFavorite }+                    .thenByDescending { it.phones.size + it.emails.size }+                    .thenBy { it.id },+            )+            .distinctBy { personKey(it) }+        return deduped             .sortedWith(                 compareByDescending<WearContact> { it.isFavorite }                     .thenBy { it.name.lowercase() }                     .thenBy { it.id },             )             .take(WearContactsProtocol.MAX_CONTACTS)+    }++    /** Identity of one person across contact sources: name + reachable handle. */+    private fun personKey(contact: WearContact): String {+        val phone = contact.phones.firstOrNull()+            ?.filter { it.isDigit() }+            ?.takeLast(10)+            .orEmpty()+        val handle = phone.ifEmpty {+            contact.emails.firstOrNull()?.lowercase().orEmpty()+        }+        return if (handle.isEmpty()) {+            "id:${contact.id}"+        } else {+            "${contact.name.lowercase()}|$handle"+        }+    }      /** Manifest for [selected] out of [totalContacts] contacts, in [chunkCount] chunks. */     fun manifest(