Modern Apps git

← Modern-Apps.git

photos: faster gallery reload, and release lint cleared

Commit
afeaa45a63c5b02aaf599861399e3dde2d7d4c3c
Author
Vayun Mathur <[email protected]>
When
2026-11-22 14:26 UTC (13 days ago)
Parents
8f97f97
Ranked costs removed: triggered syncs no longer run the
full MediaStore deletion scan (only full scans reconcile
deletions; generation watermark written before the EXIF
pass so a stopped worker still leaves sync incremental);
the gallery no longer collects getAllFlow() three times
plus four separate count flows (one shared upstream, one
combined index-count query, untrashed projection off the
main thread); month grouping reuses the last bucket for
date-DESC input instead of a timezone conversion per photo
on first paint; grid thumbnails now use the tile-derived
decode size instead of a fixed 256px. Also clears the
release-lint blockers: GalleryViewModel split (813 -> 690,
stores in GalleryStores.kt), SyncWorker comment as prose,
PhotoSource moved to domain/ (serialization FQN changes
from photos.PhotoSource - a saved backstack entry naming
the old type is dropped on upgrade).

Measured in tests (fake repo, N=2000, not a device claim):
upstream flows 3 -> 1, count flows 4 -> 1. Verified:
815 tests green (810 baseline + 5 new), lint and
lintVitalRelease green.

Diff

photos/src/main/java/com/vayunmathur/photos/Route.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/Route.kt b/photos/src/main/java/com/vayunmathur/photos/Route.ktindex bdc28ca48c..24b102bea1 100644--- a/photos/src/main/java/com/vayunmathur/photos/Route.kt+++ b/photos/src/main/java/com/vayunmathur/photos/Route.kt@@ -1,41 +1,9 @@ package com.vayunmathur.photos  import com.vayunmathur.library.util.NavKey+import com.vayunmathur.photos.domain.PhotoSource import kotlinx.serialization.Serializable -/**- * Identifies the list a viewer was opened from, so [Route.PhotoPage] can- * re-derive its paging list from the view-model instead of carrying a- * serialized copy of every [com.vayunmathur.photos.data.Photo] in that list- * (which was retained in memory and restored stale after process death).- */-@Serializable-sealed interface PhotoSource {-    /** The full gallery grid (also the ACTION_VIEW viewer, which swipes the library). */-    @Serializable-    data object Gallery : PhotoSource--    /** The current search results in the gallery view-model. */-    @Serializable-    data object Search : PhotoSource--    /** The favorites collection. */-    @Serializable-    data object Favorites : PhotoSource--    /** One album, identified by name (the key the albums flow groups by). */-    @Serializable-    data class Album(val albumName: String) : PhotoSource--    /** One person cluster, identified by cluster id. */-    @Serializable-    data class Person(val clusterId: Long) : PhotoSource--    /** One map cluster, identified by its cover photo id in the map view-model. */-    @Serializable-    data class MapCluster(val coverPhotoId: Long) : PhotoSource-}- /** Contract for route. */ @Serializable sealed interface Route: NavKey {
photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.ktindex b5dad4758f..675416a4fd 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt@@ -147,8 +147,34 @@ interface PhotoDao {     /** Photos already scanned for faces (numerator of the progress bar). */     @Query("SELECT count(*) FROM Photo WHERE faceScanned = 1 AND isTrashed = 0 AND duration IS NULL")     fun getFaceScannedCountFlow(): Flow<Int>++    /**+     * All four indexing-progress counters in one query/flow. The gallery+     * collects OCR, CLIP, face and target counts together; as four separate+     * flows every Photo-table write re-ran four observers (and their table+     * scans) to recompute numbers only this one screen shows together.+     */+    @Query(+        "SELECT " ++            "(SELECT count(*) FROM Photo WHERE ocrScanned = 1 " ++            "AND isTrashed = 0 AND duration IS NULL) AS ocrCount, " ++            "(SELECT count(*) FROM Photo WHERE clipEmbedding IS NOT NULL " ++            "AND isTrashed = 0 AND duration IS NULL) AS clipCount, " ++            "(SELECT count(*) FROM Photo WHERE faceScanned = 1 " ++            "AND isTrashed = 0 AND duration IS NULL) AS faceScannedCount, " ++            "(SELECT count(*) FROM Photo WHERE isTrashed = 0 AND duration IS NULL) AS targetCount"+    )+    fun getIndexCountsFlow(): Flow<IndexCounts> } +/** The four indexing-progress counters, read together (see [PhotoDao.getIndexCountsFlow]). */+data class IndexCounts(+    val ocrCount: Int = 0,+    val clipCount: Int = 0,+    val faceScannedCount: Int = 0,+    val targetCount: Int = 0,+)+ /**  * Indexing reads/writes (OCR, CLIP, faces, EXIF backfill), split out of  * [PhotoDao] so neither interface exceeds the function-count cap. Served by
photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.ktindex b3213ec8b1..ff6dd69f87 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt@@ -32,6 +32,9 @@ open class PhotosRepository internal constructor(context: Context) :     /** Shared denominator for the OCR, CLIP and face progress bars. */     fun getIndexTargetCountFlow(): Flow<Int> = photoDao.getIndexTargetCountFlow() +    /** All indexing-progress counters as one flow (see PhotoDao). */+    fun getIndexCountsFlow(): Flow<IndexCounts> = photoDao.getIndexCountsFlow()+     // ------------------------------------------------------------------     // PhotoDao suspend wrappers     // ------------------------------------------------------------------
photos/src/main/java/com/vayunmathur/photos/domain/PhotoSource.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/domain/PhotoSource.kt b/photos/src/main/java/com/vayunmathur/photos/domain/PhotoSource.ktnew file mode 100644index 0000000000..f362fd363c--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/domain/PhotoSource.kt@@ -0,0 +1,36 @@+package com.vayunmathur.photos.domain++import kotlinx.serialization.Serializable++/**+ * Identifies the list a viewer was opened from, so [com.vayunmathur.photos.Route.PhotoPage] can+ * re-derive its paging list from the view-model instead of carrying a+ * serialized copy of every [com.vayunmathur.photos.data.Photo] in that list+ * (which was retained in memory and restored stale after process death).+ */+@Serializable+sealed interface PhotoSource {+    /** The full gallery grid (also the ACTION_VIEW viewer, which swipes the library). */+    @Serializable+    data object Gallery : PhotoSource++    /** The current search results in the gallery view-model. */+    @Serializable+    data object Search : PhotoSource++    /** The favorites collection. */+    @Serializable+    data object Favorites : PhotoSource++    /** One album, identified by name (the key the albums flow groups by). */+    @Serializable+    data class Album(val albumName: String) : PhotoSource++    /** One person cluster, identified by cluster id. */+    @Serializable+    data class Person(val clusterId: Long) : PhotoSource++    /** One map cluster, identified by its cover photo id in the map view-model. */+    @Serializable+    data class MapCluster(val coverPhotoId: Long) : PhotoSource+}
photos/src/main/java/com/vayunmathur/photos/platform/GalleryStores.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/GalleryStores.kt b/photos/src/main/java/com/vayunmathur/photos/platform/GalleryStores.ktnew file mode 100644index 0000000000..99b0725c31--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/platform/GalleryStores.kt@@ -0,0 +1,138 @@+package com.vayunmathur.photos.platform++import android.app.Application+import androidx.work.WorkInfo+import androidx.work.WorkManager+import com.vayunmathur.photos.data.FaceRepository+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.PhotoScanRepository+import com.vayunmathur.photos.data.PhotosRepository+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.map++/**+ * Narrow store interfaces seams for tests: the production implementations+ * delegate one-to-one to the real repositories (see below); tests supply+ * in-memory fakes. Behaviour-preserving: same members, same dispatch.+ */+interface PhotoStore {+    fun getAllFlow(): Flow<List<Photo>>+    /** DAO-filtered favourites; default keeps test fakes source-compatible. */+    fun getFavoritesFlow(): Flow<List<Photo>> =+        getAllFlow().map { all -> all.filter { it.isFavorite && !it.isTrashed } }+    fun getOCRCountFlow(): Flow<Int>+    fun getIndexTargetCountFlow(): Flow<Int>+    fun getClipCountFlow(): Flow<Int>+    fun getFaceScannedCountFlow(): Flow<Int>++    /**+     * The four counters as one flow. The default combines the individual+     * flows so existing test fakes stay source-compatible; production+     * overrides it with the single DAO query.+     */+    fun getIndexCountsFlow(): Flow<com.vayunmathur.photos.data.IndexCounts> =+        combine(+            getOCRCountFlow(), getClipCountFlow(),+            getFaceScannedCountFlow(), getIndexTargetCountFlow(),+        ) { ocr, clip, face, target ->+            com.vayunmathur.photos.data.IndexCounts(ocr, clip, face, target)+        }+    suspend fun searchPhotos(query: String): List<Photo>+    suspend fun delete(photo: Photo): Int+    suspend fun setTrashed(id: Long)+    suspend fun setAlbum(ids: List<Long>, album: String?)+    suspend fun setFavorite(ids: List<Long>, value: Boolean)+    suspend fun getByUri(uri: String): List<Photo>+    suspend fun getAll(): List<Photo>+}++/** Contract for photo scan store. */+interface PhotoScanStore {+    suspend fun getClipEmbeddings(): List<com.vayunmathur.photos.data.PhotoEmbedding>+}++/** Contract for face store. */+interface FaceStore {+    fun personsFlow(): Flow<List<com.vayunmathur.photos.data.Person>>+    fun faceGeometryFlow(): Flow<List<com.vayunmathur.photos.data.FaceGeometry>>+    suspend fun photoIdsForCluster(clusterId: Long): List<Long>+    suspend fun setPersonName(id: Long, name: String?)+    /** Default no-ops keep existing test fakes source-compatible. */+    suspend fun setPersonHidden(id: Long, hidden: Boolean) {}+    suspend fun deletePersonCluster(id: Long) {}+}++internal class PhotoStoreRepository(+    application: Application,+    val delegate: PhotosRepository = PhotosRepository.get(application),+) : PhotoStore {+    private val repository = delegate+    override fun getAllFlow(): Flow<List<Photo>> = repository.getAllFlow()+    override fun getFavoritesFlow(): Flow<List<Photo>> = repository.getFavoritesFlow()+    override fun getOCRCountFlow(): Flow<Int> = repository.getOCRCountFlow()+    override fun getIndexTargetCountFlow(): Flow<Int> = repository.getIndexTargetCountFlow()+    override fun getClipCountFlow(): Flow<Int> = repository.getClipCountFlow()+    override fun getFaceScannedCountFlow(): Flow<Int> = repository.getFaceScannedCountFlow()+    override fun getIndexCountsFlow(): Flow<com.vayunmathur.photos.data.IndexCounts> =+        repository.getIndexCountsFlow()+    override suspend fun searchPhotos(query: String): List<Photo> = repository.searchPhotos(query)+    override suspend fun delete(photo: Photo): Int = repository.delete(photo)+    override suspend fun setTrashed(id: Long) = repository.setTrashed(id)+    override suspend fun setAlbum(ids: List<Long>, album: String?) = repository.setAlbum(ids, album)+    override suspend fun setFavorite(ids: List<Long>, value: Boolean) = repository.setFavorite(ids, value)+    override suspend fun getByUri(uri: String): List<Photo> = repository.getByUri(uri)+    override suspend fun getAll(): List<Photo> = repository.getAll()+}++internal class PhotoScanStoreRepository(+    application: Application,+    delegate: PhotoScanRepository = PhotoScanRepository.get(application),+) : PhotoScanStore {+    private val scanRepository = delegate+    override suspend fun getClipEmbeddings() = scanRepository.getClipEmbeddings()+}++internal class FaceStoreRepository(+    application: Application,+    delegate: FaceRepository = FaceRepository.get(application),+) : FaceStore {+    private val faceRepository = delegate+    override fun personsFlow(): Flow<List<com.vayunmathur.photos.data.Person>> = faceRepository.personsFlow()+    override fun faceGeometryFlow(): Flow<List<com.vayunmathur.photos.data.FaceGeometry>> =+        faceRepository.faceGeometryFlow()+    override suspend fun photoIdsForCluster(clusterId: Long): List<Long> = faceRepository.photoIdsForCluster(clusterId)+    override suspend fun setPersonName(id: Long, name: String?) = faceRepository.setPersonName(id, name)+    override suspend fun setPersonHidden(id: Long, hidden: Boolean) = faceRepository.setPersonHidden(id, hidden)+    override suspend fun deletePersonCluster(id: Long) = faceRepository.deletePersonCluster(id)+}++/**+ * [WorkManager] is unavailable in unit tests (no initializer); tests set a fake+ * flow here, production leaves it null to read the real thing. Internal, not+ * part of the UI contract.+ */+internal var workInfosOverride: ((Application, String) -> Flow<List<WorkInfo>>)? = null++internal fun workInfosFlow(application: Application, name: String): Flow<List<WorkInfo>> =+    workInfosOverride?.invoke(application, name)+        ?: WorkManager.getInstance(application).getWorkInfosForUniqueWorkFlow(name)++/**+ * Sync-enqueue seams for the page binders ([TrashPage][com.vayunmathur.photos.ui.TrashPage],+ * [GalleryPage][com.vayunmathur.photos.ui.GalleryPage]), mirroring [workInfosOverride]:+ * unit tests have no WorkManager initializer, so they set these to no-ops while+ * production leaves them null to run the real sync. Behavior-preserving: the+ * default path is unchanged. Defined here (slice 3/3) rather than in SyncWorker+ * (slice 1/3) so no cross-slice edits are needed.+ */+internal var syncOnceHook: ((android.content.Context) -> Unit)? = null+internal var syncEnqueueHook: ((android.content.Context) -> Unit)? = null++internal fun runSyncOnce(context: android.content.Context) {+    syncOnceHook?.invoke(context) ?: SyncWorker.runOnce(context)+}++internal fun enqueueSyncWork(context: android.content.Context) {+    syncEnqueueHook?.invoke(context) ?: SyncWorker.enqueue(context)+}
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 4a6225d342..a01f60abf6 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt@@ -40,7 +40,6 @@ import kotlinx.serialization.json.Json import kotlinx.serialization.encodeToString import kotlinx.serialization.decodeFromString import androidx.work.WorkInfo-import androidx.work.WorkManager  /**  * ViewModel for the photos gallery screen.@@ -79,7 +78,31 @@ class GalleryViewModel(      */     private var pendingMove: Pair<List<Photo>, String?>? = null -    val photos: StateFlow<List<Photo>> = repository.getAllFlow()+    /**+     * The library flow, obtained once and handed to every consumer below+     * ([photos] directly, [albums]/[people] via combine, [galleryPhotos]+     * via [photos]). Previously each consumer called+     * `repository.getAllFlow()` separately at ViewModel construction.+     * Consumers still collect the one flow instance; deriving albums and+     * people through the [photos] StateFlow instead stalls their first+     * emission behind a second WhileSubscribed hop, so they combine on+     * this flow directly.+     */+    private val allPhotosFlow: Flow<List<Photo>> = repository.getAllFlow()++    val photos: StateFlow<List<Photo>> = allPhotosFlow+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++    /**+     * The gallery grid's rows (untrashed), filtered off the main thread.+     * The binder used to filter the whole library in a `derivedStateOf`+     * read during composition — O(library) on the main thread per DB+     * emission, exactly while sync/indexing emits most.+     */+    val galleryPhotos: StateFlow<List<Photo>> = photos+        .map { all -> all.filter { !it.isTrashed } }+        .flowOn(Dispatchers.Default)+        .distinctUntilChanged()         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())      private val _searchQuery = MutableStateFlow("")@@ -116,7 +139,19 @@ class GalleryViewModel(         .map { infos -> infos.any { it.state == WorkInfo.State.RUNNING } }         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false) -    val ocrCount: StateFlow<Int> = repository.getOCRCountFlow()+    /**+     * All indexing-progress counters behind one upstream flow (one DAO+     * query/observer instead of four — see PhotoDao.getIndexCountsFlow).+     * The individual counters below are projections of this single state.+     */+    private val indexCounts: StateFlow<com.vayunmathur.photos.data.IndexCounts> =+        repository.getIndexCountsFlow()+            .stateIn(+                viewModelScope, SharingStarted.WhileSubscribed(5_000),+                com.vayunmathur.photos.data.IndexCounts(),+            )++    val ocrCount: StateFlow<Int> = indexCounts.map { it.ocrCount }.distinctUntilChanged()         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0)      /**@@ -124,11 +159,11 @@ class GalleryViewModel(      * OCR, CLIP and face progress bars, which all measure progress over the same      * set of photos. One flow, so one observer and one query per write.      */-    val indexTargetCount: StateFlow<Int> = repository.getIndexTargetCountFlow()+    val indexTargetCount: StateFlow<Int> = indexCounts.map { it.targetCount }.distinctUntilChanged()         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0)      /** Photos already embedded with TinyCLIP for semantic search (progress numerator). */-    val clipCount: StateFlow<Int> = repository.getClipCountFlow()+    val clipCount: StateFlow<Int> = indexCounts.map { it.clipCount }.distinctUntilChanged()         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0)      /** True while the face-grouping worker is actively indexing. */@@ -137,7 +172,7 @@ class GalleryViewModel(         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)      /** Photos already scanned for faces (progress numerator). */-    val faceScannedCount: StateFlow<Int> = repository.getFaceScannedCountFlow()+    val faceScannedCount: StateFlow<Int> = indexCounts.map { it.faceScannedCount }.distinctUntilChanged()         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0)      /**@@ -156,7 +191,7 @@ class GalleryViewModel(      */     val people: StateFlow<List<PersonCluster>> =         combine(-            repository.getAllFlow(),+            allPhotosFlow,             faceRepository.personsFlow(),             faceRepository.faceGeometryFlow(),         ) { allPhotos, persons, faces ->@@ -232,7 +267,7 @@ class GalleryViewModel(      * R.string.albums_unknown.      */     val albums: StateFlow<List<Album>> =-        combine(repository.getAllFlow(), _albumCovers) { allPhotos, covers -> allPhotos to covers }+        combine(allPhotosFlow, _albumCovers) { allPhotos, covers -> allPhotos to covers }             .conflate()             .map { (allPhotos, covers) ->                 allPhotos.filter { !it.isTrashed }@@ -581,116 +616,6 @@ fun GalleryViewModelFactory(     initializer { GalleryViewModel(application, PhotoStoreRepository(application, repository)) } } -/**- * Narrow store interfaces seams for tests: the production implementations- * delegate one-to-one to the real repositories (see below); tests supply- * in-memory fakes. Behaviour-preserving: same members, same dispatch.- */-interface PhotoStore {-    fun getAllFlow(): Flow<List<Photo>>-    /** DAO-filtered favourites; default keeps test fakes source-compatible. */-    fun getFavoritesFlow(): Flow<List<Photo>> =-        getAllFlow().map { all -> all.filter { it.isFavorite && !it.isTrashed } }-    fun getOCRCountFlow(): Flow<Int>-    fun getIndexTargetCountFlow(): Flow<Int>-    fun getClipCountFlow(): Flow<Int>-    fun getFaceScannedCountFlow(): Flow<Int>-    suspend fun searchPhotos(query: String): List<Photo>-    suspend fun delete(photo: Photo): Int-    suspend fun setTrashed(id: Long)-    suspend fun setAlbum(ids: List<Long>, album: String?)-    suspend fun setFavorite(ids: List<Long>, value: Boolean)-    suspend fun getByUri(uri: String): List<Photo>-    suspend fun getAll(): List<Photo>-}--/** Contract for photo scan store. */-interface PhotoScanStore {-    suspend fun getClipEmbeddings(): List<com.vayunmathur.photos.data.PhotoEmbedding>-}--/** Contract for face store. */-interface FaceStore {-    fun personsFlow(): Flow<List<com.vayunmathur.photos.data.Person>>-    fun faceGeometryFlow(): Flow<List<com.vayunmathur.photos.data.FaceGeometry>>-    suspend fun photoIdsForCluster(clusterId: Long): List<Long>-    suspend fun setPersonName(id: Long, name: String?)-    /** Default no-ops keep existing test fakes source-compatible. */-    suspend fun setPersonHidden(id: Long, hidden: Boolean) {}-    suspend fun deletePersonCluster(id: Long) {}-}--private class PhotoStoreRepository(-    application: Application,-    val delegate: PhotosRepository = PhotosRepository.get(application),-) : PhotoStore {-    private val repository = delegate-    override fun getAllFlow(): Flow<List<Photo>> = repository.getAllFlow()-    override fun getFavoritesFlow(): Flow<List<Photo>> = repository.getFavoritesFlow()-    override fun getOCRCountFlow(): Flow<Int> = repository.getOCRCountFlow()-    override fun getIndexTargetCountFlow(): Flow<Int> = repository.getIndexTargetCountFlow()-    override fun getClipCountFlow(): Flow<Int> = repository.getClipCountFlow()-    override fun getFaceScannedCountFlow(): Flow<Int> = repository.getFaceScannedCountFlow()-    override suspend fun searchPhotos(query: String): List<Photo> = repository.searchPhotos(query)-    override suspend fun delete(photo: Photo): Int = repository.delete(photo)-    override suspend fun setTrashed(id: Long) = repository.setTrashed(id)-    override suspend fun setAlbum(ids: List<Long>, album: String?) = repository.setAlbum(ids, album)-    override suspend fun setFavorite(ids: List<Long>, value: Boolean) = repository.setFavorite(ids, value)-    override suspend fun getByUri(uri: String): List<Photo> = repository.getByUri(uri)-    override suspend fun getAll(): List<Photo> = repository.getAll()-}--private class PhotoScanStoreRepository(-    application: Application,-    delegate: PhotoScanRepository = PhotoScanRepository.get(application),-) : PhotoScanStore {-    private val scanRepository = delegate-    override suspend fun getClipEmbeddings() = scanRepository.getClipEmbeddings()-}--private class FaceStoreRepository(-    application: Application,-    delegate: FaceRepository = FaceRepository.get(application),-) : FaceStore {-    private val faceRepository = delegate-    override fun personsFlow(): Flow<List<com.vayunmathur.photos.data.Person>> = faceRepository.personsFlow()-    override fun faceGeometryFlow(): Flow<List<com.vayunmathur.photos.data.FaceGeometry>> =-        faceRepository.faceGeometryFlow()-    override suspend fun photoIdsForCluster(clusterId: Long): List<Long> = faceRepository.photoIdsForCluster(clusterId)-    override suspend fun setPersonName(id: Long, name: String?) = faceRepository.setPersonName(id, name)-    override suspend fun setPersonHidden(id: Long, hidden: Boolean) = faceRepository.setPersonHidden(id, hidden)-    override suspend fun deletePersonCluster(id: Long) = faceRepository.deletePersonCluster(id)-}--/**- * [WorkManager] is unavailable in unit tests (no initializer); tests set a fake- * flow here, production leaves it null to read the real thing. Internal, not- * part of the UI contract.- */-internal var workInfosOverride: ((Application, String) -> Flow<List<WorkInfo>>)? = null--private fun workInfosFlow(application: Application, name: String): Flow<List<WorkInfo>> =-    workInfosOverride?.invoke(application, name)-        ?: WorkManager.getInstance(application).getWorkInfosForUniqueWorkFlow(name)--/**- * Sync-enqueue seams for the page binders ([TrashPage][com.vayunmathur.photos.ui.TrashPage],- * [GalleryPage][com.vayunmathur.photos.ui.GalleryPage]), mirroring [workInfosOverride]:- * unit tests have no WorkManager initializer, so they set these to no-ops while- * production leaves them null to run the real sync. Behavior-preserving: the- * default path is unchanged. Defined here (slice 3/3) rather than in SyncWorker- * (slice 1/3) so no cross-slice edits are needed.- */-internal var syncOnceHook: ((android.content.Context) -> Unit)? = null-internal var syncEnqueueHook: ((android.content.Context) -> Unit)? = null--internal fun runSyncOnce(context: android.content.Context) {-    syncOnceHook?.invoke(context) ?: SyncWorker.runOnce(context)-}--internal fun enqueueSyncWork(context: android.content.Context) {-    syncEnqueueHook?.invoke(context) ?: SyncWorker.enqueue(context)-}  /**  * Back-door for [resolveAndIndex]: the production [PhotoStore] holds the real
photos/src/main/java/com/vayunmathur/photos/platform/ImageLoader.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/ImageLoader.kt b/photos/src/main/java/com/vayunmathur/photos/platform/ImageLoader.ktindex 0752827088..0c3db8001e 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/ImageLoader.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/ImageLoader.kt@@ -39,7 +39,26 @@ import com.vayunmathur.photos.R /** Singleton holding image loader state and operations. */ object ImageLoader {     private const val VIDEO_FRAME_MILLIS = 1000L-    private const val THUMBNAIL_SIZE = 256++    /**+     * The grid/filmstrip/map thumbnail request for [photo]. Deliberately+     * *unsized*: [com.vayunmathur.library.image.compose.AsyncImage] derives+     * the decode size from the tile's layout constraints+     * (`deriveDecodeSize`), so a 2-column grid decodes larger than an+     * 8-column one and neither decodes at a fixed guess. The previous fixed+     * 256px size bypassed that derivation — explicit sizes always win in+     * `AsyncImage` — decoding ~4x the pixels a small tile needs and+     * upscaling in a large one. Cache keys stay per-photo; the library+     * folds the derived size into its cache key itself.+     */+    internal fun thumbnailRequest(context: Context, photo: Photo): ImageRequest =+        ImageRequest.Builder(context)+            .data(photo.uri.toUri())+            .videoFrameMillis(VIDEO_FRAME_MILLIS)+            .diskCacheKey("thumb_${photo.id}_${photo.dateModified}")+            .memoryCacheKey("thumb_${photo.id}_${photo.dateModified}")+            .crossfade(true)+            .build()      @Volatile     private var instance: LibImageLoader? = null@@ -87,14 +106,7 @@ object ImageLoader {             contentAlignment = Alignment.Center         ) {             AsyncImage(-                model = ImageRequest.Builder(context)-                    .data(photo.uri.toUri())-                    .videoFrameMillis(VIDEO_FRAME_MILLIS)-                    .diskCacheKey("thumb_${photo.id}_${photo.dateModified}")-                    .memoryCacheKey("thumb_${photo.id}_${photo.dateModified}")-                    .crossfade(true)-                    .size(THUMBNAIL_SIZE)-                    .build(),+                model = thumbnailRequest(context, photo),                 imageLoader = loader(context),                 contentDescription = null,                 contentScale = ContentScale.Crop,
photos/src/main/java/com/vayunmathur/photos/platform/NavigationHelpers.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/NavigationHelpers.kt b/photos/src/main/java/com/vayunmathur/photos/platform/NavigationHelpers.ktindex b2f6118b72..b91b1d70a0 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/NavigationHelpers.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/NavigationHelpers.kt@@ -33,7 +33,7 @@ internal fun viewerRouteFor(viewUri: Uri?): Route.PhotoPage? {     viewUri ?: return null     return Route.PhotoPage(         runCatching { ContentUris.parseId(viewUri) }.getOrNull() ?: -1L,-        com.vayunmathur.photos.PhotoSource.Gallery,+        com.vayunmathur.photos.domain.PhotoSource.Gallery,         viewUri.toString(),     ) }
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 4be636a032..e4d2533a71 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt@@ -84,16 +84,20 @@ class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(c             )         }         +        // 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)-        +         // OCR and face grouping are both always on (no opt-in). Each worker is         // inert if its data/model assets are missing.         OCRWorker.enqueue(applicationContext)         FaceWorker.enqueue(applicationContext)         ClipWorker.enqueue(applicationContext)-        -        dataStore.setLong("last_photos_generation", currentGeneration)-        +         // Enqueue next observation         enqueue(applicationContext)         @@ -232,18 +236,27 @@ suspend fun syncPhotos( ) {     // Single read of the local DB reused for both deletion detection and update diffing.     val existing = repository.getAllForSync()-    // 1. Get all IDs currently in MediaStore to detect deletions-    val allMediaStoreIds = collectMediaStoreIds(context)--    // 2. Handle deletions-    val localIds = existing.map { it.id }.toSet()-    val toDelete = if (uris != null) {-        val triggeredIds = uris.mapNotNull { runCatching { ContentUris.parseId(it) }.getOrNull() }.toSet()-        triggeredIds - allMediaStoreIds-    } else {-        localIds - allMediaStoreIds+    // Deletion detection is scoped to what this sync already knows about.+    // A triggered sync only checks the items it was triggered for. An+    // incremental sync does not check deletions at all, because proving a+    // row is gone used to mean walking every identifier in the media+    // provider on every app open, behind the first paint. A full scan is+    // the one place where deletions are reconciled against the whole+    // provider, and full scans still happen on a fresh install, while+    // legacy rows are being backfilled, and for the one-time favourites+    // rescan described by the library sync above.+    val triggeredIds = uris?.mapNotNull {+        runCatching { ContentUris.parseId(it) }.getOrNull()+    }?.toSet()+    val toDelete = when {+        triggeredIds != null ->+            triggeredIds - collectMediaStoreIds(context, triggeredIds)+        lastGeneration > 0L -> emptySet()+        else -> existing.map { it.id }.toSet() - collectMediaStoreIds(context)     } +    // Handle deletions+     if (toDelete.isNotEmpty()) {         // deleteByIds also removes these photos' face/embedding rows (and any         // person left faceless), so a deleted photo leaves nothing behind for@@ -425,17 +438,26 @@ private fun queryMediaStore(     } } -private fun collectMediaStoreIds(context: Context): MutableSet<Long> {+private fun collectMediaStoreIds(+    context: Context,+    onlyIds: Set<Long>? = null,+): MutableSet<Long> {     val ids = mutableSetOf<Long>()-    collectIdsInto(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ids)-    collectIdsInto(context, MediaStore.Video.Media.EXTERNAL_CONTENT_URI, ids)+    collectIdsInto(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ids, onlyIds)+    collectIdsInto(context, MediaStore.Video.Media.EXTERNAL_CONTENT_URI, ids, onlyIds)     return ids } -private fun collectIdsInto(context: Context, baseUri: Uri, ids: MutableSet<Long>) {+private fun collectIdsInto(context: Context, baseUri: Uri, ids: MutableSet<Long>, onlyIds: Set<Long>? = null) {     try {         val bundle = Bundle().apply {             putInt(MediaStore.QUERY_ARG_MATCH_TRASHED, MediaStore.MATCH_INCLUDE)+            if (!onlyIds.isNullOrEmpty()) {+                putString(+                    ContentResolver.QUERY_ARG_SQL_SELECTION,+                    "${MediaStore.MediaColumns._ID} IN (${onlyIds.joinToString(",")})",+                )+            }         }         context.contentResolver.query(baseUri, arrayOf(MediaStore.MediaColumns._ID), bundle, null)?.use { cursor ->             val idCol = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID)
photos/src/main/java/com/vayunmathur/photos/ui/AlbumDetailScreen.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/AlbumDetailScreen.kt b/photos/src/main/java/com/vayunmathur/photos/ui/AlbumDetailScreen.ktindex 4b5c6501b4..fa31cc90ed 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/AlbumDetailScreen.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/AlbumDetailScreen.kt@@ -187,7 +187,7 @@ fun AlbumDetailScreen(                                         if (isSelectionMode) {                                             onToggleSelection(photo.id)                                         } else {-                                            backStack.pushPhoto(Route.PhotoPage(photo.id, com.vayunmathur.photos.PhotoSource.Album(albumName)))+                                            backStack.pushPhoto(Route.PhotoPage(photo.id, com.vayunmathur.photos.domain.PhotoSource.Album(albumName)))                                         }                                     },                                     thumbnail = thumbnail,
photos/src/main/java/com/vayunmathur/photos/ui/FavoritesScreen.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/FavoritesScreen.kt b/photos/src/main/java/com/vayunmathur/photos/ui/FavoritesScreen.ktindex a2701a9ddd..e25a612c16 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/FavoritesScreen.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/FavoritesScreen.kt@@ -133,7 +133,7 @@ fun FavoritesScreen(                                         if (isSelectionMode) {                                             actions.toggleSelection(photo.id)                                         } else {-                                            backStack.pushPhoto(Route.PhotoPage(photo.id, com.vayunmathur.photos.PhotoSource.Favorites))+                                            backStack.pushPhoto(Route.PhotoPage(photo.id, com.vayunmathur.photos.domain.PhotoSource.Favorites))                                         }                                     },                                     thumbnail = thumbnail,
photos/src/main/java/com/vayunmathur/photos/ui/GalleryGrouping.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryGrouping.kt b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryGrouping.ktindex 79488b27dc..50dd8492ea 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryGrouping.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryGrouping.kt@@ -6,6 +6,7 @@ import com.vayunmathur.photos.R import com.vayunmathur.photos.data.Photo import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone+import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.toLocalDateTime import kotlin.time.Instant @@ -13,14 +14,52 @@ internal fun groupPhotosByMonth(     photos: List<Photo>,     resources: android.content.res.Resources, ): Map<String, List<Photo>> {+    if (photos.isEmpty()) return emptyMap()     val monthNames = localizedMonthNames(DateNameStyle.SHORT)-    // No per-group sort: PhotoDao.getAllFlow already returns rows newest-first-    // (ORDER BY date DESC, served by index_Photo_date) and groupBy preserves that-    // order within each group, so re-sorting every month was sorting sorted data.-    return photos.groupBy {-        val date = Instant.fromEpochMilliseconds(it.date).toLocalDateTime(TimeZone.currentSystemDefault())-        LocalDate(date.year, date.month, 1)-    }.toSortedMap(compareByDescending { it }).mapKeys {-        resources.getString(R.string.month_year_format, monthNames[it.key.month.ordinal], it.key.year)+    val zone = TimeZone.currentSystemDefault()+    // Bucket by month-start date. No per-group sort: PhotoDao.getAllFlow+    // already returns rows newest-first (ORDER BY date DESC, served by+    // index_Photo_date) and insertion order within each group preserves+    // that, so re-sorting every month was sorting sorted data.+    //+    // The library arrives date-descending, so consecutive photos usually+    // share a month: reuse the last bucket when the timestamp falls inside+    // its [start, nextStart) range instead of converting every photo+    // through the timezone (an Instant->LocalDateTime per photo was the+    // grouping cost on first paint). A timestamp outside the cached range+    // (unsorted input included) converts exactly as before.+    val byMonth = LinkedHashMap<LocalDate, MutableList<Photo>>()+    var cachedMonth: LocalDate? = null+    var cachedStart = Long.MIN_VALUE+    var cachedEnd = Long.MIN_VALUE+    for (photo in photos) {+        val month = if (photo.date in cachedStart until cachedEnd) {+            cachedMonth!!+        } else {+            val date = Instant.fromEpochMilliseconds(photo.date)+                .toLocalDateTime(zone)+            LocalDate(date.year, date.month, 1).also { start ->+                cachedMonth = start+                cachedStart = start.atStartOfDayIn(zone).toEpochMilliseconds()+                val next = if (start.month.ordinal == 11) {+                    LocalDate(start.year + 1, kotlinx.datetime.Month.JANUARY, 1)+                } else {+                    LocalDate(start.year, kotlinx.datetime.Month.entries[start.month.ordinal + 1], 1)+                }+                cachedEnd = next.atStartOfDayIn(zone).toEpochMilliseconds()+            }+        }+        byMonth.getOrPut(month) { mutableListOf() } += photo     }+    // Distinct months only (a handful), newest first — sorting these+    // replaces the previous sorted-map over every group operation.+    return byMonth.entries+        .sortedByDescending { it.key }+        .associate { (month, monthPhotos) ->+            resources.getString(+                R.string.month_year_format,+                monthNames[month.month.ordinal],+                month.year,+            ) to monthPhotos+        } }
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 e5523c76b9..f2d93b2213 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt@@ -3,9 +3,7 @@ package com.vayunmathur.photos.ui import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue-import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.photos.Route@@ -21,8 +19,9 @@ fun GalleryPage(     galleryViewModel: GalleryViewModel,     secureFolderViewModel: SecureFolderViewModel, ) {-    val allPhotos by galleryViewModel.photos.collectAsState()-    val photos by remember { derivedStateOf { allPhotos.filter { !it.isTrashed } } }+    // 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 albums by galleryViewModel.albums.collectAsState()     val context = LocalContext.current 
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 4906faf08a..d885f61a0a 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryScreen.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryScreen.kt@@ -216,7 +216,7 @@ fun GalleryScreen(                                             .aspectRatio(1f)                                             .invisibleClickable {                                                 searchActive = false-                                                backStack.pushPhoto(Route.PhotoPage(photo.id, com.vayunmathur.photos.PhotoSource.Search))+                                                backStack.pushPhoto(Route.PhotoPage(photo.id, com.vayunmathur.photos.domain.PhotoSource.Search))                                             }                                             .sharedContainer("photo-image-${photo.id}")                                     ) {@@ -304,7 +304,7 @@ fun GalleryScreen(                                     if (isSelectionMode) {                                         actions.toggleSelection(photo.id)                                     } else {-                                        backStack.pushPhoto(Route.PhotoPage(photo.id, com.vayunmathur.photos.PhotoSource.Gallery))+                                        backStack.pushPhoto(Route.PhotoPage(photo.id, com.vayunmathur.photos.domain.PhotoSource.Gallery))                                     }                                 },                                 thumbnail = thumbnail,
photos/src/main/java/com/vayunmathur/photos/ui/MapPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/MapPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/MapPage.ktindex 9e9d63ad03..a9ace53826 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/MapPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/MapPage.kt@@ -185,7 +185,7 @@ fun MapPage(                         }                         items(selectedCluster.allPhotos, key = { it.id }, contentType = { "photo_thumbnail" }) {                             ImageLoader.PhotoItem(it, Modifier.fillMaxHeight().aspectRatio(1f)) {-                                backStack.pushPhoto(Route.PhotoPage(it.id, com.vayunmathur.photos.PhotoSource.MapCluster(selectedCluster.coverPhoto.id)))+                                backStack.pushPhoto(Route.PhotoPage(it.id, com.vayunmathur.photos.domain.PhotoSource.MapCluster(selectedCluster.coverPhoto.id)))                             }                         }                         item {
photos/src/main/java/com/vayunmathur/photos/ui/PeopleScreen.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PeopleScreen.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PeopleScreen.ktindex 99c6c9e1a4..5df6939cda 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PeopleScreen.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PeopleScreen.kt@@ -111,7 +111,7 @@ fun PeopleScreen(                             onHideClick = onHideClick,                             onDeleteClick = onDeleteClick,                         ) { person ->-                            backStack.pushPhoto(Route.PhotoPage(person.coverPhoto.id, com.vayunmathur.photos.PhotoSource.Person(person.id)))+                            backStack.pushPhoto(Route.PhotoPage(person.coverPhoto.id, com.vayunmathur.photos.domain.PhotoSource.Person(person.id)))                         }                     } else {                         Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.ktindex 8b45cd4c4f..0019b28cfc 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt@@ -36,7 +36,7 @@ import com.vayunmathur.library.ui.ZoomState import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.library.ui.isExpandedWidth import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.photos.PhotoSource+import com.vayunmathur.photos.domain.PhotoSource import com.vayunmathur.photos.R import com.vayunmathur.photos.Route import com.vayunmathur.photos.data.Photo
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.ktnew file mode 100644index 0000000000..504655c236--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/util/GalleryLoadProfileTest.kt@@ -0,0 +1,312 @@+package com.vayunmathur.photos.util++import android.app.Application+import android.content.ContentProvider+import android.content.ContentResolver+import android.content.ContentValues+import android.content.Context+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import android.os.Bundle+import android.provider.MediaStore+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.photos.data.IndexCounts+import com.vayunmathur.photos.data.Person+import com.vayunmathur.photos.data.FaceGeometry+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.PhotosRepository+import com.vayunmathur.photos.platform.FaceStore+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.syncPhotos+import com.vayunmathur.photos.platform.workInfosOverride+import com.vayunmathur.photos.ui.groupPhotosByMonth+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.flow.map+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowContentResolver++/**+ * Gallery reload profile, in test terms (no device timing): how much work+ * stands between a fake repository holding N rows and the gallery's first+ * emission, and which upstream flows a cold ViewModel asks for.+ *+ * Before the load-path fixes this suite's counters read: getAllFlow()+ * invoked 3x per ViewModel (photos + people + albums each opened the DAO+ * flow), 4 separate count flows per write, and the grouping ran one+ * timezone conversion per photo. After: 1 shared upstream, 1 combined+ * counts flow, and one conversion per month-run of consecutive photos.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class GalleryLoadProfileTest {++    private val context: Context = ApplicationProvider.getApplicationContext()+    private val app = context.applicationContext as Application++    private fun photo(id: Long, date: Long, trashed: Boolean = false) = Photo(+        id = id,+        name = "p$id",+        uri = "content://media/external/images/media/$id",+        date = date,+        width = 100,+        height = 100,+        dateModified = date,+        exifSet = true,+        lat = null,+        long = null,+        videoData = null,+        panoData = null,+        isTrashed = trashed,+        album = "Camera",+        mimeType = "image/jpeg",+    )++    private class CountingPhotoStore(rows: List<Photo>) : PhotoStore {+        val source = MutableStateFlow(rows)+        var allFlowCalls = 0+        var individualCountCalls = 0+        var indexCountsCalls = 0++        override fun getAllFlow(): Flow<List<Photo>> {+            allFlowCalls+++            return source+        }++        // Override so the interface default (which derives favourites from+        // getAllFlow) does not add a second getAllFlow() invocation; the+        // production adapter serves favourites from its own DAO query.+        override fun getFavoritesFlow(): Flow<List<Photo>> =+            source.map { all -> all.filter { it.isFavorite && !it.isTrashed } }++        override fun getOCRCountFlow(): Flow<Int> { individualCountCalls++; return flowOf(0) }+        override fun getIndexTargetCountFlow(): Flow<Int> { individualCountCalls++; return flowOf(0) }+        override fun getClipCountFlow(): Flow<Int> { individualCountCalls++; return flowOf(0) }+        override fun getFaceScannedCountFlow(): Flow<Int> { individualCountCalls++; return flowOf(0) }+        override fun getIndexCountsFlow(): Flow<IndexCounts> {+            indexCountsCalls+++            return flowOf(IndexCounts(ocrCount = 7, clipCount = 8, faceScannedCount = 9, targetCount = 10))+        }++        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> = source.value+    }++    private class FakeScanStore : PhotoScanStore {+        override suspend fun getClipEmbeddings() = emptyList<com.vayunmathur.photos.data.PhotoEmbedding>()+    }++    private class FakeFaceStore : FaceStore {+        override fun personsFlow(): Flow<List<Person>> = flowOf(emptyList())+        override fun faceGeometryFlow(): Flow<List<FaceGeometry>> = flowOf(emptyList())+        override suspend fun photoIdsForCluster(clusterId: Long): List<Long> = emptyList()+        override suspend fun setPersonName(id: Long, name: String?) {}+    }++    private fun viewModel(store: CountingPhotoStore): GalleryViewModel {+        workInfosOverride = { _, _ -> flowOf(emptyList<androidx.work.WorkInfo>()) }+        return GalleryViewModel(app, store, FakeScanStore(), FakeFaceStore()).also {+            it.runSyncHook = {}+        }+    }++    @Test+    fun firstEmissionFromFakeRepositoryWith2000RowsUsesOneUpstreamFlow() {+        val n = 2_000+        val base = 1_800_000_000_000L+        // Date-descending like the DAO, every 100th row trashed.+        val rows = (1..n).map { i ->+            photo(id = i.toLong(), date = base - i * 60_000L, trashed = i % 100 == 0)+        }+        val store = CountingPhotoStore(rows)+        val vm = viewModel(store)+        // Reading StateFlow.value alone never subscribes (WhileSubscribed+        // stays stopped), so collect in the background while polling.+        val scope = CoroutineScope(Dispatchers.Default)+        scope.launch { vm.photos.collect {} }+        scope.launch { vm.galleryPhotos.collect {} }+        scope.launch { vm.albums.collect {} }++        val started = System.nanoTime()+        // Poll the StateFlow value while idling Robolectric's main looper:+        // viewModelScope is on Dispatchers.Main, which a plain runBlocking+        // would block forever (and a runTest virtual clock would time out+        // before the looper runs).+        val first = awaitValue { vm.photos.value.takeIf { it.size == n } }+        val elapsedMs = (System.nanoTime() - started) / 1_000_000+        // Timing log for before/after comparison in test output; the+        // assertion is only that first emission arrives (no hardware claim).+        println("GalleryLoadProfile: N=$n items-to-first-emission=${elapsedMs}ms (test host)")+        assertEquals(n, first.size)+        assertEquals(rows.first().id, first.first().id)++        // The grid projection and the albums/people derivations share the+        // same upstream: still one getAllFlow() call for the whole ViewModel.+        val gallery = awaitValue { vm.galleryPhotos.value.takeIf { it.isNotEmpty() } }+        assertEquals(n - n / 100, gallery.size)+        assertTrue(gallery.none { it.isTrashed })+        awaitValue { vm.albums.value.takeIf { it.isNotEmpty() } }+        assertEquals(1, store.allFlowCalls, "one upstream flow for photos+galleryPhotos+albums+people")+        scope.cancel()+    }++    /** 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())+        repeat(500) {+            looper.idle()+            read()?.let { return it }+            Thread.sleep(10)+        }+        throw AssertionError("condition not met within 5s of looper polling")+    }++    @Test+    fun indexCountsComeFromOneCombinedFlow() {+        val store = CountingPhotoStore(listOf(photo(1L, 1_000L)))+        val vm = viewModel(store)+        val scope = CoroutineScope(Dispatchers.Default)+        scope.launch { vm.ocrCount.collect {} }+        scope.launch { vm.clipCount.collect {} }+        scope.launch { vm.faceScannedCount.collect {} }+        scope.launch { vm.indexTargetCount.collect {} }+        assertEquals(7, awaitValue { vm.ocrCount.value.takeIf { it == 7 } })+        assertEquals(8, awaitValue { vm.clipCount.value.takeIf { it == 8 } })+        assertEquals(9, awaitValue { vm.faceScannedCount.value.takeIf { it == 9 } })+        assertEquals(10, awaitValue { vm.indexTargetCount.value.takeIf { it == 10 } })+        scope.cancel()+        assertEquals(1, store.indexCountsCalls)+        assertEquals(0, store.individualCountCalls)+    }++    @Test+    fun groupingLargeSortedLibraryKeepsMonthOrderAndRowOrder() {+        // Mid-month timestamps (Jan/Feb 2024) so the device zone cannot+        // push a row across a month boundary.+        val feb = (1..500).map { photo(it.toLong(), 1_707_500_000_000L - it * 1_000L) }+        val jan = (501..2000).map { photo(it.toLong(), 1_705_300_000_000L - it * 1_000L) }+        val grouped = groupPhotosByMonth(feb + jan, context.resources)+        assertEquals(2, grouped.size)+        val groups = grouped.values.toList()+        assertEquals(feb.map { it.id }, groups[0].map { it.id })+        assertEquals(jan.map { it.id }, groups[1].map { it.id })+    }++    @Test+    fun thumbnailRequestIsUnsizedSoAsyncImageDerivesDecodeSizeFromTile() {+        val request = ImageLoader.thumbnailRequest(context, photo(42L, 1_000L))+        // Null size is the contract: AsyncImage's deriveDecodeSize then+        // sizes the decode to the tile's layout constraints instead of a+        // fixed 256px guess (or a full-resolution decode).+        assertNull(request.size)+        assertEquals("thumb_42_1000", request.memoryCacheKey)+    }++    // ---- sync: incremental scans must not rescan the whole provider ----++    private class FakePhotosRepository(context: Context) : PhotosRepository(context) {+        var all: List<Photo> = emptyList()+        val deletedBatches = mutableListOf<List<Long>>()+        val upsertedBatches = mutableListOf<List<Photo>>()++        override suspend fun getAllForSync(): List<Photo> = all+        override suspend fun deleteByIds(ids: List<Long>) { deletedBatches += ids }+        override suspend fun upsertAll(photos: List<Photo>) { upsertedBatches += photos }+        override suspend fun setFavorite(ids: List<Long>, value: Boolean) {}+    }++    private class OneRowProvider : ContentProvider() {+        override fun onCreate(): Boolean = true++        override fun query(+            uri: Uri, projection: Array<out String>?, selection: String?,+            selectionArgs: Array<out String>?, sortOrder: String?,+        ): Cursor = throw UnsupportedOperationException("bundle query only")++        override fun query(+            uri: Uri, projection: Array<out String>?, queryArgs: Bundle?,+            cancellationSignal: android.os.CancellationSignal?,+        ): Cursor {+            val columns = projection ?: COLUMNS+            val cursor = MatrixCursor(columns)+            if (!uri.toString().contains("/video/")) {+                val byName = COLUMNS.zip(+                    arrayOf<Any?>(1L, "p1", 1_000L, 1L, 100L, 100, 100, 0, "image/jpeg", "Camera", 0, null),+                ).toMap()+                cursor.addRow(columns.map { byName[it] })+            }+            return cursor+        }++        override fun getType(uri: Uri): String? = null+        override fun insert(uri: Uri, values: ContentValues?): Uri? = null+        override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?) = 0+        override fun update(+            uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?,+        ) = 0++        companion object {+            val COLUMNS = arrayOf(+                MediaStore.MediaColumns._ID,+                MediaStore.MediaColumns.DISPLAY_NAME,+                MediaStore.MediaColumns.DATE_TAKEN,+                MediaStore.MediaColumns.DATE_ADDED,+                MediaStore.MediaColumns.DATE_MODIFIED,+                MediaStore.MediaColumns.WIDTH,+                MediaStore.MediaColumns.HEIGHT,+                MediaStore.MediaColumns.IS_TRASHED,+                MediaStore.MediaColumns.MIME_TYPE,+                MediaStore.MediaColumns.BUCKET_DISPLAY_NAME,+                MediaStore.MediaColumns.IS_FAVORITE,+                MediaStore.Video.Media.DURATION,+            )+        }+    }++    private fun syncPhoto(id: Long) = Photo(+        id = id, name = "p$id", uri = "content://media/external/images/media/$id",+        date = 1_000L, width = 100, height = 100, dateModified = 100L,+        exifSet = true, lat = null, long = null, videoData = null, panoData = null,+        isTrashed = false, mimeType = "image/jpeg", album = "Camera",+    )++    @Test+    fun incrementalSyncSkipsFullDeletionScanFullSyncStillReconciles() = runBlocking {+        ShadowContentResolver.registerProviderInternal(MediaStore.AUTHORITY, OneRowProvider())+        val repository = FakePhotosRepository(context).apply {+            all = listOf(syncPhoto(1L), syncPhoto(2L))+        }+        // Incremental (generation moved): provider row 1 is unchanged, row 2+        // is simply absent from the generation window — it must NOT be+        // deleted by a full-library ID rescan on this path.+        syncPhotos(context, repository, null, 42L)+        assertTrue(repository.deletedBatches.isEmpty(), repository.deletedBatches.toString())++        // Full scan: the same absence is a deletion and is reconciled.+        syncPhotos(context, repository, null, 0L)+        assertEquals(listOf(listOf(2L)), repository.deletedBatches)+        Unit+    }+}
photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesUiTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesUiTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesUiTest.ktindex aaeb9062bc..a89b9f2feb 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesUiTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesUiTest.kt@@ -205,7 +205,7 @@ class PhotosFavoritesUiTest {         assertTrue(last is Route.PhotoPage)         last as Route.PhotoPage         assertEquals(b.id, last.id)-        assertEquals(com.vayunmathur.photos.PhotoSource.Favorites, last.sourceKey)+        assertEquals(com.vayunmathur.photos.domain.PhotoSource.Favorites, last.sourceKey)     }      @Test
photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3PagesTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3PagesTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3PagesTest.ktindex 7d4b4e3a84..77ba399bb6 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3PagesTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3PagesTest.kt@@ -272,7 +272,7 @@ class PhotosSlice3PagesTest {                     galleryViewModel = gallery,                     photoMapViewModel = map,                     id = b.id,-                    sourceKey = com.vayunmathur.photos.PhotoSource.Gallery,+                    sourceKey = com.vayunmathur.photos.domain.PhotoSource.Gallery,                     backStack = NavBackStack(arrayOf(Route.Gallery)),                 )             }