photos: fix gallery never importing after a triggered sync
- Commit
0e2d54511a05347cd1795cfed4f42b612839c556- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-22 22:34 UTC (13 days ago)
- Parents
304fed6
Owner phone showed an empty gallery. Root cause: the speed change moved the MediaStore generation watermark write ahead of the EXIF pass and let content-triggered syncs advance it - a triggered sync imports only its URIs yet raised the watermark past every other pending photo, and later incremental syncs filter GENERATION_MODIFIED > watermark, so those photos were skipped permanently. The watermark again advances only after the EXIF pass and only for generation-complete (untriggered) syncs. A one-time full recovery scan heals already-poisoned installs on the next sync (no data clear). Also the owner loading rule: the gallery now shows a loading indicator until first emission instead of a fake-empty state; genuinely empty stays the empty state. The ViewModel flow, combined counts query and PhotoSource move were audited over real Room and cleared. Verified: 412 tests green incl. new real-repo emission pins.
Diff
photos/src/main/java/com/vayunmathur/photos/platform/GalleryUiContract.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/GalleryUiContract.kt b/photos/src/main/java/com/vayunmathur/photos/platform/GalleryUiContract.ktindex 196693fc80..fd0f86b446 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/GalleryUiContract.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/GalleryUiContract.kt@@ -19,6 +19,14 @@ import com.vayunmathur.photos.data.Photo /** Everything the gallery grid draws. */ data class GalleryUiState( val photos: List<Photo> = emptyList(),+ /**+ * True while the first library emission is still in flight. An empty+ * [photos] list is only a genuine empty library when this is false;+ * while true the screen shows a loading indicator, never the empty+ * state. Defaults false so previews/tests that hand rows (or a+ * deliberate empty) directly render them as loaded.+ */+ val isLoading: Boolean = false, val selectedIds: Set<Long> = emptySet(), val isRefreshing: Boolean = false, val searchQuery: String = "",
photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt b/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.ktindex a01f60abf6..46290ba6b6 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt@@ -32,6 +32,7 @@ import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch@@ -90,7 +91,22 @@ class GalleryViewModel( */ private val allPhotosFlow: Flow<List<Photo>> = repository.getAllFlow() + /**+ * True until the library flow's first emission, false forever after.+ *+ * [photos]/[galleryPhotos] start at `emptyList()` (their StateFlow+ * initial value), which is indistinguishable from a genuinely empty+ * library — so the binder reads this flag to show a loading indicator+ * instead of a fake-empty grid while the first Room emission is in+ * flight. It is only ever cleared, never re-set: once rows (or a+ * genuine empty) have been seen, a WhileSubscribed restart replays+ * the retained value and must not flash loading again.+ */+ private val _galleryLoading = MutableStateFlow(true)+ val galleryLoading: StateFlow<Boolean> = _galleryLoading.asStateFlow()+ val photos: StateFlow<List<Photo>> = allPhotosFlow+ .onEach { _galleryLoading.value = false } .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) /**
photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt b/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.ktindex e4d2533a71..a95a36bcc6 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt@@ -81,14 +81,9 @@ class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(c syncLibrary( applicationContext, repository, lastGeneration, needsMimeBackfill, DataStoreOneTimeFlag(dataStore, FAVORITES_RESCAN_DONE_KEY),+ DataStoreOneTimeFlag(dataStore, GENERATION_RECOVERY_DONE_KEY), ) }- - // Watermark before the EXIF pass: that pass can run for a long time- // over a backlogged library, and if the worker is stopped during it- // the next sync must still start from this generation instead of- // re-walking every change since the previous one.- dataStore.setLong("last_photos_generation", currentGeneration) setExifData(scanRepository, applicationContext) @@ -98,6 +93,22 @@ class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(c FaceWorker.enqueue(applicationContext) ClipWorker.enqueue(applicationContext) + // Generation watermark, written LAST and only by a generation-complete+ // sync (see generationWatermarkAfter): a triggered sync imports only+ // its own URIs, so advancing the watermark from one permanently skips+ // every other change at or below the current generation — the+ // incremental selection is GENERATION_MODIFIED > watermark, and an+ // unchanged file never moves again. afeaa45a6 also moved this write+ // ahead of the EXIF pass, which removed the one recovery window the+ // old placement had: a worker stopped during that long pass used to+ // leave the watermark untouched, so the next sync re-walked the+ // generation. If this worker is stopped before this line, the next+ // sync simply re-walks from the old watermark (idempotent upserts),+ // which is the safe failure direction.+ generationWatermarkAfter(triggeredUris.isNotEmpty(), currentGeneration)?.let {+ dataStore.setLong("last_photos_generation", it)+ }+ // Enqueue next observation enqueue(applicationContext) @@ -209,11 +220,45 @@ private class DataStoreOneTimeFlag( */ internal const val FAVORITES_RESCAN_DONE_KEY = "favorites_rescan_done" +/**+ * Set once the one-time full rescan that repairs a possibly-poisoned+ * generation watermark has run. Between afeaa45a6 and the watermark fix, a+ * triggered sync (or a worker stopped during the EXIF pass after afeaa45a6+ * moved the watermark ahead of it) could persist a watermark past changes+ * no sync ever imported, and every later incremental sync then skipped+ * them forever (`GENERATION_MODIFIED > watermark` never matches an+ * unchanged file again). One full pass — whose selection is not+ * generation-bounded — re-imports anything the provider still has, after+ * which incremental sync is trustworthy again.+ */+internal const val GENERATION_RECOVERY_DONE_KEY = "generation_recovery_done"++/** A flag that reads as already set; the default for callers that owe no recovery scan. */+private object AlreadySetFlag : OneTimeFlag {+ override suspend fun isSet(): Boolean = true+ override suspend fun set() {}+}++/**+ * The generation watermark a completed [SyncWorker] run may persist, or+ * null to leave the stored watermark untouched.+ *+ * Only an untriggered (generation-complete: full or incremental over the+ * whole provider) sync may advance it. A triggered sync imports only its+ * triggered URIs, so it proves nothing about any other change at or below+ * [currentGeneration]; advancing from one permanently skips those changes+ * (see the call site in [SyncWorker.doWork]).+ */+internal fun generationWatermarkAfter(triggered: Boolean, currentGeneration: Long): Long? =+ if (triggered) null else currentGeneration+ /** * The untriggered library sync: incremental from [lastGeneration], unless a- * full scan is owed — rows still missing their mimeType, or the one-time- * favourites rescan behind [favoritesRescan] has not run yet. The flag is set- * only after a full scan completed, so it runs exactly once.+ * full scan is owed — rows still missing their mimeType, the one-time+ * favourites rescan behind [favoritesRescan] has not run yet, or the+ * one-time generation-watermark recovery behind [generationRecovery] has+ * not run yet. Each flag is set only after a full scan completed, so each+ * runs exactly once. */ internal suspend fun syncLibrary( context: Context,@@ -221,11 +266,14 @@ internal suspend fun syncLibrary( lastGeneration: Long, needsMimeBackfill: Boolean, favoritesRescan: OneTimeFlag,+ generationRecovery: OneTimeFlag = AlreadySetFlag, ) { val needsFavoritesRescan = !favoritesRescan.isSet()- val fullScan = needsMimeBackfill || needsFavoritesRescan+ val needsGenerationRecovery = !generationRecovery.isSet()+ val fullScan = needsMimeBackfill || needsFavoritesRescan || needsGenerationRecovery syncPhotos(context, repository, null, if (fullScan) 0L else lastGeneration) if (needsFavoritesRescan) favoritesRescan.set()+ if (needsGenerationRecovery) generationRecovery.set() } suspend fun syncPhotos(
photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.ktindex f2d93b2213..933a23dcde 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt@@ -22,6 +22,7 @@ fun GalleryPage( // Untrashed rows projected off the main thread in the ViewModel // (galleryPhotos); filtering here used to run O(library) in composition. val photos by galleryViewModel.galleryPhotos.collectAsState()+ val isLoading by galleryViewModel.galleryLoading.collectAsState() val albums by galleryViewModel.albums.collectAsState() val context = LocalContext.current @@ -52,6 +53,7 @@ fun GalleryPage( backStack = backStack, state = GalleryUiState( photos = photos,+ isLoading = isLoading, selectedIds = selectedIds, isRefreshing = isRefreshing, searchQuery = searchQuery,
photos/src/main/java/com/vayunmathur/photos/ui/GalleryScreen.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryScreen.kt b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryScreen.ktindex d885f61a0a..3940c58ad4 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryScreen.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryScreen.kt@@ -23,6 +23,7 @@ import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.LoadingIndicator import com.vayunmathur.library.ui.adaptiveGridCells import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.IconButton@@ -274,7 +275,17 @@ fun GalleryScreen( .padding(paddingValues) .pinchToZoomColumns({ columnCount }, { columnCount = it }) ) {- if (state.photos.isEmpty() && !state.isRefreshing) {+ if (state.isLoading) {+ // First library emission still in flight: a wait, not an+ // empty library (same shape as the vault viewer / secure+ // folder binders: full-size box, centred indicator).+ Box(+ modifier = Modifier.fillMaxSize(),+ contentAlignment = androidx.compose.ui.Alignment.Center,+ ) {+ LoadingIndicator()+ }+ } else if (state.photos.isEmpty() && !state.isRefreshing) { EmptyState( title = stringResource(R.string.gallery_empty_title), message = stringResource(R.string.gallery_empty_message),
photos/src/test/java/com/vayunmathur/photos/util/GalleryLoadProfileTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/GalleryLoadProfileTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/GalleryLoadProfileTest.ktindex 504655c236..c59456613a 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/GalleryLoadProfileTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/GalleryLoadProfileTest.kt@@ -21,6 +21,9 @@ import com.vayunmathur.photos.platform.GalleryViewModel import com.vayunmathur.photos.platform.ImageLoader import com.vayunmathur.photos.platform.PhotoScanStore import com.vayunmathur.photos.platform.PhotoStore+import com.vayunmathur.photos.platform.OneTimeFlag+import com.vayunmathur.photos.platform.generationWatermarkAfter+import com.vayunmathur.photos.platform.syncLibrary import com.vayunmathur.photos.platform.syncPhotos import com.vayunmathur.photos.platform.workInfosOverride import com.vayunmathur.photos.ui.groupPhotosByMonth@@ -125,7 +128,29 @@ class GalleryLoadProfileTest { override suspend fun setPersonName(id: Long, name: String?) {} } - private fun viewModel(store: CountingPhotoStore): GalleryViewModel {+ /** A store whose library flow emits nothing until [gate] completes. */+ private class GatedPhotoStore(+ private val gate: kotlinx.coroutines.CompletableDeferred<List<Photo>>,+ ) : PhotoStore {+ override fun getAllFlow(): Flow<List<Photo>> =+ kotlinx.coroutines.flow.flow { emit(gate.await()) }+ override fun getFavoritesFlow(): Flow<List<Photo>> =+ kotlinx.coroutines.flow.flow { emit(gate.await().filter { it.isFavorite && !it.isTrashed }) }+ override fun getOCRCountFlow(): Flow<Int> = flowOf(0)+ override fun getIndexTargetCountFlow(): Flow<Int> = flowOf(0)+ override fun getClipCountFlow(): Flow<Int> = flowOf(0)+ override fun getFaceScannedCountFlow(): Flow<Int> = flowOf(0)+ override fun getIndexCountsFlow(): Flow<IndexCounts> = flowOf(IndexCounts())+ override suspend fun searchPhotos(query: String): List<Photo> = emptyList()+ override suspend fun delete(photo: Photo): Int = 0+ override suspend fun setTrashed(id: Long) {}+ override suspend fun setAlbum(ids: List<Long>, album: String?) {}+ override suspend fun setFavorite(ids: List<Long>, value: Boolean) {}+ override suspend fun getByUri(uri: String): List<Photo> = emptyList()+ override suspend fun getAll(): List<Photo> = emptyList()+ }++ private fun viewModel(store: PhotoStore): GalleryViewModel { workInfosOverride = { _, _ -> flowOf(emptyList<androidx.work.WorkInfo>()) } return GalleryViewModel(app, store, FakeScanStore(), FakeFaceStore()).also { it.runSyncHook = {}@@ -172,6 +197,60 @@ class GalleryLoadProfileTest { scope.cancel() } + @Test+ fun galleryPhotosEmitUserVisibleItemsAndLoadingTransitionsToContent() {+ val gate = kotlinx.coroutines.CompletableDeferred<List<Photo>>()+ val vm = viewModel(GatedPhotoStore(gate))+ val scope = CoroutineScope(Dispatchers.Default)+ // The device path: the binder collects galleryPhotos (+ loading),+ // not the raw photos flow, so collect exactly those two.+ scope.launch { vm.galleryPhotos.collect {} }+ scope.launch { vm.galleryLoading.collect {} }++ // Before the first upstream emission the user-visible rows are the+ // StateFlow initial empty list, and the model must say "loading" —+ // not collapse into a genuine empty library.+ assertTrue(vm.galleryPhotos.value.isEmpty())+ assertEquals(true, awaitValue { vm.galleryLoading.value.takeIf { it } })++ gate.complete(+ listOf(+ photo(3L, 3_000L),+ photo(2L, 2_000L, trashed = true),+ photo(1L, 1_000L),+ )+ )+ val visible = awaitValue { vm.galleryPhotos.value.takeIf { it.size == 2 } }+ assertEquals(listOf(3L, 1L), visible.map { it.id })+ assertEquals(false, awaitValue { vm.galleryLoading.value.takeIf { !it } })+ scope.cancel()+ }++ @Test+ fun galleryLoadingClearsOnGenuinelyEmptyFirstEmission() {+ val gate = kotlinx.coroutines.CompletableDeferred<List<Photo>>()+ val vm = viewModel(GatedPhotoStore(gate))+ val scope = CoroutineScope(Dispatchers.Default)+ scope.launch { vm.galleryPhotos.collect {} }+ scope.launch { vm.galleryLoading.collect {} }+ assertEquals(true, awaitValue { vm.galleryLoading.value.takeIf { it } })+ gate.complete(emptyList())+ // An emitted empty library is a real empty (the screen may now show+ // its empty state): loading cleared even though rows stayed empty.+ assertEquals(false, awaitValue { vm.galleryLoading.value.takeIf { !it } })+ assertTrue(vm.galleryPhotos.value.isEmpty())+ scope.cancel()+ }++ @Test+ fun triggeredSyncNeverAdvancesGenerationWatermark() {+ // A triggered sync imports only its URIs; the watermark may only move+ // after a generation-complete sync, else every other change at or+ // below that generation is skipped by all later incremental syncs.+ assertNull(generationWatermarkAfter(triggered = true, currentGeneration = 99L))+ assertEquals(99L, generationWatermarkAfter(triggered = false, currentGeneration = 99L))+ }+ /** Idles the paused main looper until [read] yields a value (bounded, real time). */ private fun <T> awaitValue(read: () -> T?): T { val looper = org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper())@@ -309,4 +388,33 @@ class GalleryLoadProfileTest { assertEquals(listOf(listOf(2L)), repository.deletedBatches) Unit }++ private class FakeFlag(initial: Boolean) : OneTimeFlag {+ var value = initial+ override suspend fun isSet(): Boolean = value+ override suspend fun set() { value = true }+ }++ @Test+ fun generationRecoveryForcesOneFullScanThenReturnsToIncremental() = runBlocking {+ ShadowContentResolver.registerProviderInternal(MediaStore.AUTHORITY, OneRowProvider())+ val repository = FakePhotosRepository(context).apply {+ all = listOf(syncPhoto(1L), syncPhoto(2L))+ }+ val favoritesDone = FakeFlag(initial = true)+ val recovery = FakeFlag(initial = false)++ // Despite a moved generation (42), the owed recovery pass is a full+ // scan: row 2's absence is reconciled (a poisoned watermark's missed+ // cohort is re-walked by the un-bounded selection) and the flag set.+ syncLibrary(context, repository, 42L, false, favoritesDone, recovery)+ assertEquals(listOf(listOf(2L)), repository.deletedBatches)+ assertTrue(recovery.value)++ // Recovery runs once: the next library sync is incremental again.+ repository.deletedBatches.clear()+ syncLibrary(context, repository, 42L, false, favoritesDone, recovery)+ assertTrue(repository.deletedBatches.isEmpty(), repository.deletedBatches.toString())+ Unit+ } }
photos/src/test/java/com/vayunmathur/photos/util/GalleryViewModelRealRepoTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/GalleryViewModelRealRepoTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/GalleryViewModelRealRepoTest.ktindex 1a19e53b0f..033f3e9cce 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/GalleryViewModelRealRepoTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/GalleryViewModelRealRepoTest.kt@@ -78,6 +78,8 @@ class GalleryViewModelRealRepoTest { CoroutineScope(Dispatchers.Default).launch { vm.faceScannedCount.collect {} }, CoroutineScope(Dispatchers.Default).launch { vm.searchResults.collect {} }, CoroutineScope(Dispatchers.Default).launch { vm.photos.collect {} },+ CoroutineScope(Dispatchers.Default).launch { vm.galleryPhotos.collect {} },+ CoroutineScope(Dispatchers.Default).launch { vm.galleryLoading.collect {} }, CoroutineScope(Dispatchers.Default).launch { vm.albums.collect {} }, CoroutineScope(Dispatchers.Default).launch { vm.people.collect {} }, CoroutineScope(Dispatchers.Default).launch { vm.favorites.collect {} },@@ -98,6 +100,11 @@ class GalleryViewModelRealRepoTest { // The photos flow is the raw library order (newest first, trash included); // trash/album filtering happens in the grouping projections below. await("photos loaded") { vm.photos.value.map { it.name } == listOf("trashed-one", "beach", "mountain", "city") }+ // The user-visible grid projection (what GalleryPage collects) over+ // the real Room flow: untrashed rows, newest first, and loading+ // cleared by the first real emission.+ await("gallery photos loaded") { vm.galleryPhotos.value.map { it.name } == listOf("beach", "mountain", "city") }+ await("gallery loading cleared") { !vm.galleryLoading.value } await("albums grouped") { vm.albums.value.map { it.name } == listOf("Camera", "Trips") } val camera = vm.albums.value.first { it.name == "Camera" } assertEquals("beach", camera.coverPhoto.name)
photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3ScreensTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3ScreensTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3ScreensTest.ktindex 65e5cdfa0d..c311f40131 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3ScreensTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3ScreensTest.kt@@ -121,6 +121,21 @@ class PhotosSlice3ScreensTest { composeRule.onNodeWithText(str(R.string.search_placeholder)).assertIsDisplayed() } + @Test+ fun galleryLoadingShowsIndicatorNeverEmptyState() {+ setGallery(GalleryUiState(isLoading = true))+ // While the first library emission is in flight the fake-empty state+ // must not render; the loading indicator takes its place instead.+ composeRule.onNodeWithText(str(R.string.gallery_empty_title)).assertDoesNotExist()+ composeRule.onNodeWithText(str(R.string.search_placeholder)).assertIsDisplayed()+ }++ @Test+ fun galleryLoadedEmptyShowsEmptyState() {+ setGallery(GalleryUiState(isLoading = false))+ composeRule.onNodeWithText(str(R.string.gallery_empty_title)).assertIsDisplayed()+ }+ @Test fun galleryGridGroupsPhotosByMonth() { val a = photo("jan-a", 1_705_320_000_000L)