music: adding a song to a playlist twice no longer stores it twice
- Commit
a9b8cbe0024fe1a17d6fca251f7a20aa8c84b100- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 01:35 UTC (5 days ago)
- Parents
0348658
Playlist membership is a set, but upsertMatching treated it as an append-only list: upserting a fresh id=0 row always inserted a second membership row, from both the phone 'Add to playlist' dialog and the Wear ADD_TO_PLAYLIST command. Consumers that map matching ids to songs in stored order then played/listed the track twice (Wear playlist page count inflated, Wear and assistant playback queues repeating the song), while phone/car screens masked it through toSet() — so surfaces disagreed about the same playlist. The repository now treats membership as a set: upsertMatching checks existence under a lock (concurrent phone+Wear adds cannot both pass) and returns -1 leaving the original row and its position untouched; upsertMatchings dedupes within the batch and against stored rows; reads dedupe first-occurrence-wins, so playlists already duplicated on disk read back as one membership without a migration. New tests cover double-add and legacy duplicates. Library scan, recents and lyrics were audited and cleared. Verified: targeted suites pass (Room 8/8, ViewModel playlist 3/3) and every other class passes in batches/individually; the single combined :music:testDevUnitTest invocation hangs in this shared tree across attempts and could not be attributed to this change (the new lock guards only check+insert, no nesting) — flagged here rather than claimed green. Lint errors are pre-existing on untouched files.
Diff
music/src/main/java/com/vayunmathur/music/data/MusicRepository.kt
diff --git a/music/src/main/java/com/vayunmathur/music/data/MusicRepository.kt b/music/src/main/java/com/vayunmathur/music/data/MusicRepository.ktindex f230e9b201..3c85a3b876 100644--- a/music/src/main/java/com/vayunmathur/music/data/MusicRepository.kt+++ b/music/src/main/java/com/vayunmathur/music/data/MusicRepository.kt@@ -210,7 +210,11 @@ class MusicRepository private constructor(context: Context) : _albumArtistMatchings.onStart { ensureLoaded() }, matchingDao.flow().onStart { emit(emptyList()) }, ) { derived, stored ->+ // Playlist membership is a set: legacy duplicate rows (written+ // before upsertMatching became idempotent) must not surface as+ // duplicate members. derived + stored.filter { it.type == TYPE_MUSIC_PLAYLIST }+ .distinctBy { Triple(it.leftID, it.rightID, it.type) } } // Music (tag cache only - the library itself is [music])@@ -236,12 +240,48 @@ class MusicRepository private constructor(context: Context) : } // Matching+ // Membership reads are deduplicated (first occurrence wins, so stored+ // order is preserved): a matching is a set membership, and rows written+ // before the idempotent upsert below may already be duplicated on disk. suspend fun getFromRight(rightId: Long, type: Int): List<Long> =- matchingDao.getFromRight(rightId, type)+ matchingDao.getFromRight(rightId, type).distinct() suspend fun getFromLeft(leftId: Long, type: Int): List<Long> =- matchingDao.getFromLeft(leftId, type)- suspend fun upsertMatching(value: ManyManyMatching): Long = matchingDao.upsert(value)- suspend fun upsertMatchings(values: List<ManyManyMatching>) = matchingDao.upsert(values)+ matchingDao.getFromLeft(leftId, type).distinct()++ private val matchingLock = Mutex()++ /**+ * Adds one membership row, or nothing if it already exists.+ *+ * [ManyManyMatching]'s primary key is an auto-generated row id with no+ * uniqueness on (leftID, rightID, type), so a plain upsert of a fresh+ * `ManyManyMatching(song, playlist, …)` always inserted a second row:+ * re-adding a song already in a playlist (phone dialog, or a repeated+ * Wear `ADD_TO_PLAYLIST` op) duplicated it in every consumer that maps+ * matching ids to songs in stored order — the Wear playlist page and+ * the assistant/Wear playlist playback queues played the song twice,+ * while phone screens masked it by filtering through a set. Guarded+ * here, the one writer every caller goes through, under a lock so two+ * concurrent adds of the same pair cannot both pass the check.+ *+ * Returns the new row id, or -1 when the membership already existed+ * (its original row, and so its playlist position, is left untouched).+ */+ suspend fun upsertMatching(value: ManyManyMatching): Long = matchingLock.withLock {+ if (matchingDao.getFromLeft(value.leftID, value.type).contains(value.rightID)) {+ -1L+ } else {+ matchingDao.upsert(value)+ }+ }++ suspend fun upsertMatchings(values: List<ManyManyMatching>) {+ matchingLock.withLock {+ val fresh = values.distinctBy { Triple(it.leftID, it.rightID, it.type) }+ .filterNot { matchingDao.getFromLeft(it.leftID, it.type).contains(it.rightID) }+ if (fresh.isNotEmpty()) matchingDao.upsert(fresh)+ }+ } suspend fun deleteMatch(left: Long, right: Long, type: Int) = matchingDao.deleteMatch(left, right, type) suspend fun deleteFromRight(rightId: Long, type: Int) =
music/src/test/java/com/vayunmathur/music/data/MusicRepositoryRoomTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/data/MusicRepositoryRoomTest.kt b/music/src/test/java/com/vayunmathur/music/data/MusicRepositoryRoomTest.ktindex df9a0eebdf..b05e1b8999 100644--- a/music/src/test/java/com/vayunmathur/music/data/MusicRepositoryRoomTest.kt+++ b/music/src/test/java/com/vayunmathur/music/data/MusicRepositoryRoomTest.kt@@ -102,6 +102,45 @@ class MusicRepositoryRoomTest { assertTrue(repo.getFromRight(50, TYPE_MUSIC_PLAYLIST).isEmpty()) } + @Test+ fun addingTheSameSongToAPlaylistTwiceStoresOneMembership() = runBlocking {+ // Regression: ManyManyMatching has an auto-generated PK and no+ // uniqueness on (leftID, rightID, type), so re-adding a song that is+ // already in the playlist (phone dialog, repeated Wear op) inserted+ // a second row and the Wear/assistant playlist queues, which map+ // matching ids to songs in stored order, played the song twice.+ repo.upsertMatching(ManyManyMatching(leftID = 1, rightID = 50, type = TYPE_MUSIC_PLAYLIST))+ repo.upsertMatching(ManyManyMatching(leftID = 1, rightID = 50, type = TYPE_MUSIC_PLAYLIST))+ repo.upsertMatchings(+ listOf(+ ManyManyMatching(leftID = 1, rightID = 50, type = TYPE_MUSIC_PLAYLIST),+ ManyManyMatching(leftID = 2, rightID = 50, type = TYPE_MUSIC_PLAYLIST),+ ManyManyMatching(leftID = 2, rightID = 50, type = TYPE_MUSIC_PLAYLIST),+ ),+ )+ assertEquals(listOf(1L, 2L), repo.getFromRight(50, TYPE_MUSIC_PLAYLIST))+ assertEquals(listOf(50L), repo.getFromLeft(1, TYPE_MUSIC_PLAYLIST))+ val merged = repo.matchings.first { merged -> merged.any { it.type == TYPE_MUSIC_PLAYLIST } }+ assertEquals(+ listOf(1L to 50L, 2L to 50L),+ merged.filter { it.type == TYPE_MUSIC_PLAYLIST }.map { it.leftID to it.rightID },+ )+ }++ @Test+ fun legacyDuplicateMatchingRowsReadBackAsOneMembership() = runBlocking {+ // Rows duplicated before the idempotent upsert, written straight+ // through the DAO the way the old code did, must not resurface.+ db.matchingDao().upsert(ManyManyMatching(leftID = 1, rightID = 50, type = TYPE_MUSIC_PLAYLIST))+ db.matchingDao().upsert(ManyManyMatching(leftID = 1, rightID = 50, type = TYPE_MUSIC_PLAYLIST))+ assertEquals(listOf(1L), repo.getFromRight(50, TYPE_MUSIC_PLAYLIST))+ val merged = repo.matchings.first { merged -> merged.any { it.type == TYPE_MUSIC_PLAYLIST } }+ assertEquals(+ listOf(1L to 50L),+ merged.filter { it.type == TYPE_MUSIC_PLAYLIST }.map { it.leftID to it.rightID },+ )+ }+ @Test fun matchingsFlowMergesDerivedPairsWithStoredPlaylistRowsOnly() = runBlocking { repo.refresh()
music/src/test/java/com/vayunmathur/music/platform/MusicViewModelPlaylistTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/platform/MusicViewModelPlaylistTest.kt b/music/src/test/java/com/vayunmathur/music/platform/MusicViewModelPlaylistTest.ktindex 96bb560bde..4118972083 100644--- a/music/src/test/java/com/vayunmathur/music/platform/MusicViewModelPlaylistTest.kt+++ b/music/src/test/java/com/vayunmathur/music/platform/MusicViewModelPlaylistTest.kt@@ -127,6 +127,22 @@ class MusicViewModelPlaylistTest { assertTrue(done, "delete completion callback must run") } + @Test+ fun addingTheSameTrackToAPlaylistTwiceKeepsOneMembership() {+ val vm = viewModel()+ vm.createPlaylist("Dupes") {}+ await("playlist created") { repo.getAllPlaylists().any { it.name == "Dupes" } }+ val playlist = runBlocking { repo.getAllPlaylists().first { it.name == "Dupes" } }+ // The Add-to-playlist dialog offers every playlist, including one+ // already containing the song; confirming it again must be a no-op.+ vm.addMusicToPlaylist(playlist.id, musicId = 1L)+ vm.addMusicToPlaylist(playlist.id, musicId = 1L)+ await("track added once") {+ repo.getFromRight(playlist.id, TYPE_MUSIC_PLAYLIST) == listOf(1L)+ }+ assertEquals(listOf(1L), runBlocking { repo.getFromRight(playlist.id, TYPE_MUSIC_PLAYLIST) })+ }+ @Test fun refreshLibraryPublishesTheFakeLibraryThroughTheViewModel() { val vm = viewModel()