musikr: batch cache writes to reduce fsync overhead on cold scan (#1365)

Replace per-song Room inserts with chunked bulk inserts (500 songs per
transaction). Reduces ~3000 individual fsync calls to ~6 on a full
cold scan, cutting write time from seconds to milliseconds on typical
eMMC/UFS storage. Adds writeAll() to MutableCache with a default
fallback for external implementors, and unit tests for the chunking
behaviour.
This commit is contained in:
shapeshed
2026-08-29 14:19:10 -06:00
committed by GitHub
parent 5bd1efe61d
commit 4546cda499
6 changed files with 183 additions and 33 deletions
@@ -35,6 +35,10 @@ class WriteOnlyMutableCache(private val inner: MutableCache) : MutableCache {
inner.write(cachedFile)
}
override suspend fun writeAll(cachedFiles: List<CachedFile>) {
inner.writeAll(cachedFiles)
}
override suspend fun cleanup(excluding: List<CachedFile>) {
inner.cleanup(excluding)
}
+15
View File
@@ -62,6 +62,21 @@ interface MutableCache : Cache {
*/
suspend fun write(cachedFile: CachedFile)
/**
* Write a batch of [CachedFile]s to the cache.
*
* Prefer this over multiple [write] calls when writing many entries at once, as implementations
* can use bulk-insert strategies to reduce transaction overhead.
*
* The default implementation falls back to calling [write] for each item individually. Override
* for a more efficient implementation.
*
* @param cachedFiles the [CachedFile]s to write to the cache
*/
suspend fun writeAll(cachedFiles: List<CachedFile>) {
cachedFiles.forEach { write(it) }
}
/**
* Cleanup the cache by removing all [CachedFile]s that are not in the provided [excluding]
* list.
@@ -63,6 +63,9 @@ internal interface CacheReadDao {
internal interface CacheWriteDao {
@Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun updateSong(data: CachedFileData)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun updateSongs(data: List<CachedFileData>)
@Transaction
suspend fun deleteExcludingUris(uris: Set<String>) {
val delete = selectAllUris().toSet() - uris
+46 -32
View File
@@ -104,6 +104,8 @@ class DBCache private constructor(private val readDao: CacheReadDao) : Cache {
fun from(context: Context) = from(CacheDatabase.from(context))
internal fun from(db: CacheDatabase) = DBCache(db.readDao())
internal fun from(readDao: CacheReadDao) = DBCache(readDao)
}
}
@@ -118,38 +120,13 @@ private constructor(private val inner: DBCache, private val writeDao: CacheWrite
override suspend fun read(file: File) = inner.read(file)
override suspend fun write(cachedFile: CachedFile) {
val dbSong =
CachedFileData(
uri = cachedFile.file.uri,
modifiedMs = cachedFile.file.modifiedMs,
addedMs = cachedFile.addedMs,
mimeType = cachedFile.audio?.properties?.mimeType,
durationMs = cachedFile.audio?.properties?.durationMs,
bitrateKbps = cachedFile.audio?.properties?.bitrateKbps,
sampleRateHz = cachedFile.audio?.properties?.sampleRateHz,
musicBrainzId = cachedFile.audio?.tags?.musicBrainzId,
name = cachedFile.audio?.tags?.name,
sortName = cachedFile.audio?.tags?.sortName,
track = cachedFile.audio?.tags?.track,
disc = cachedFile.audio?.tags?.disc,
subtitle = cachedFile.audio?.tags?.subtitle,
date = cachedFile.audio?.tags?.date,
albumMusicBrainzId = cachedFile.audio?.tags?.albumMusicBrainzId,
albumName = cachedFile.audio?.tags?.albumName,
albumSortName = cachedFile.audio?.tags?.albumSortName,
releaseTypes = cachedFile.audio?.tags?.releaseTypes,
artistMusicBrainzIds = cachedFile.audio?.tags?.artistMusicBrainzIds,
artistNames = cachedFile.audio?.tags?.artistNames,
artistSortNames = cachedFile.audio?.tags?.artistSortNames,
albumArtistMusicBrainzIds = cachedFile.audio?.tags?.albumArtistMusicBrainzIds,
albumArtistNames = cachedFile.audio?.tags?.albumArtistNames,
albumArtistSortNames = cachedFile.audio?.tags?.albumArtistSortNames,
genreNames = cachedFile.audio?.tags?.genreNames,
replayGainTrackAdjustment = cachedFile.audio?.tags?.replayGainTrackAdjustment,
replayGainAlbumAdjustment = cachedFile.audio?.tags?.replayGainAlbumAdjustment,
coverId = cachedFile.audio?.coverId,
)
writeDao.updateSong(dbSong)
writeDao.updateSong(cachedFile.toDbData())
}
override suspend fun writeAll(cachedFiles: List<CachedFile>) {
for (chunk in cachedFiles.chunked(BATCH_SIZE)) {
writeDao.updateSongs(chunk.map { it.toDbData() })
}
}
override suspend fun cleanup(excluding: List<CachedFile>) {
@@ -170,5 +147,42 @@ private constructor(private val inner: DBCache, private val writeDao: CacheWrite
val db = CacheDatabase.from(context)
return MutableDBCache(DBCache.from(db), db.writeDao())
}
internal fun from(inner: DBCache, writeDao: CacheWriteDao) =
MutableDBCache(inner, writeDao)
private const val BATCH_SIZE = 500
}
}
private fun CachedFile.toDbData() =
CachedFileData(
uri = file.uri,
modifiedMs = file.modifiedMs,
addedMs = addedMs,
mimeType = audio?.properties?.mimeType,
durationMs = audio?.properties?.durationMs,
bitrateKbps = audio?.properties?.bitrateKbps,
sampleRateHz = audio?.properties?.sampleRateHz,
musicBrainzId = audio?.tags?.musicBrainzId,
name = audio?.tags?.name,
sortName = audio?.tags?.sortName,
track = audio?.tags?.track,
disc = audio?.tags?.disc,
subtitle = audio?.tags?.subtitle,
date = audio?.tags?.date,
albumMusicBrainzId = audio?.tags?.albumMusicBrainzId,
albumName = audio?.tags?.albumName,
albumSortName = audio?.tags?.albumSortName,
releaseTypes = audio?.tags?.releaseTypes,
artistMusicBrainzIds = audio?.tags?.artistMusicBrainzIds,
artistNames = audio?.tags?.artistNames,
artistSortNames = audio?.tags?.artistSortNames,
albumArtistMusicBrainzIds = audio?.tags?.albumArtistMusicBrainzIds,
albumArtistNames = audio?.tags?.albumArtistNames,
albumArtistSortNames = audio?.tags?.albumArtistSortNames,
genreNames = audio?.tags?.genreNames,
replayGainTrackAdjustment = audio?.tags?.replayGainTrackAdjustment,
replayGainAlbumAdjustment = audio?.tags?.replayGainAlbumAdjustment,
coverId = audio?.coverId,
)
@@ -122,12 +122,17 @@ private class ExtractStepImpl(
val finalizedTask =
scope.tryAsyncWith(extracted, Dispatchers.IO) {
val exclude = mutableListOf<CachedFile>()
val pending = mutableListOf<CachedFile>()
for (item in parsed) {
val result =
when (item) {
is Finalized -> item
is NeedsCaching -> {
cache.write(item.rawSong.toCachedFile())
pending.add(item.rawSong.toCachedFile())
if (pending.size >= CACHE_BATCH_SIZE) {
cache.writeAll(pending.toList())
pending.clear()
}
Finalized(item.rawSong)
}
}
@@ -136,6 +141,9 @@ private class ExtractStepImpl(
}
it.send(result.extracted)
}
if (pending.isNotEmpty()) {
cache.writeAll(pending)
}
cache.cleanup(exclude)
}
@@ -158,5 +166,6 @@ private class ExtractStepImpl(
private companion object {
const val PARALLELISM = 8
const val CACHE_BATCH_SIZE = 500
}
}
@@ -0,0 +1,105 @@
/*
* Copyright (c) 2025 Auxio Project
* MutableDBCacheWriteAllTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.cache.db
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.Runs
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test
import org.oxycblt.musikr.cache.CachedFile
import org.oxycblt.musikr.fs.File
class MutableDBCacheWriteAllTest {
private val mockReadDao = mockk<CacheReadDao>(relaxed = true)
private val mockWriteDao = mockk<CacheWriteDao>(relaxed = true)
private val dbCache = DBCache.from(mockReadDao)
private val cache = MutableDBCache.from(dbCache, mockWriteDao)
@Test
fun writeAll_emptyList_doesNotCallDao() = runTest {
cache.writeAll(emptyList())
coVerify(exactly = 0) { mockWriteDao.updateSongs(any()) }
}
@Test
fun writeAll_fewerThanBatchSize_oneInsert() = runTest {
coEvery { mockWriteDao.updateSongs(any()) } just Runs
cache.writeAll(makeCachedFiles(100))
coVerify(exactly = 1) { mockWriteDao.updateSongs(any()) }
}
@Test
fun writeAll_exactlyBatchSize_oneInsert() = runTest {
coEvery { mockWriteDao.updateSongs(any()) } just Runs
cache.writeAll(makeCachedFiles(500))
coVerify(exactly = 1) { mockWriteDao.updateSongs(any()) }
}
@Test
fun writeAll_overBatchSize_multipleInserts() = runTest {
coEvery { mockWriteDao.updateSongs(any()) } just Runs
cache.writeAll(makeCachedFiles(1100))
coVerify(exactly = 3) { mockWriteDao.updateSongs(any()) }
}
@Test
fun writeAll_chunkSizes_matchBatchBoundaries() = runTest {
val capturedChunks = mutableListOf<List<CachedFileData>>()
coEvery { mockWriteDao.updateSongs(capture(capturedChunks)) } just Runs
cache.writeAll(makeCachedFiles(1100))
assertEquals(3, capturedChunks.size)
assertEquals(500, capturedChunks[0].size)
assertEquals(500, capturedChunks[1].size)
assertEquals(100, capturedChunks[2].size)
}
@Test
fun writeAll_remainder_isFlushedInFinalChunk() = runTest {
val capturedChunks = mutableListOf<List<CachedFileData>>()
coEvery { mockWriteDao.updateSongs(capture(capturedChunks)) } just Runs
cache.writeAll(makeCachedFiles(501))
assertEquals(2, capturedChunks.size)
assertEquals(500, capturedChunks[0].size)
assertEquals(1, capturedChunks[1].size)
}
private fun makeCachedFiles(count: Int): List<CachedFile> =
(1..count).map { n ->
val file = mockk<File>(relaxed = true)
every { file.uri } returns mockk(relaxed = true)
every { file.modifiedMs } returns n.toLong()
CachedFile(file = file, audio = null, addedMs = n.toLong())
}
}