Modern Apps git

← Modern-Apps.git

photos: MediaStore sync no longer wipes OCR/CLIP indexing

Commit
46d78c7c0d92e0ccdc3c34c9aefa8416d9abc76c
Author
Vayun Mathur <[email protected]>
When
2026-11-30 19:12 UTC (5 days ago)
Parents
3686d09
When any synced field of an already-indexed photo changed (album
move, edit in another app, DATE_MODIFIED bump), sync rebuilt the
row from a projection that deliberately omits clipEmbedding,
ocrText and ocrBoxes — then upserted it, writing NULLs over the
stored indexing. Because the wiped row kept ocrScanned=true and
the OCR worker only scans ocrScanned=0, the text (and its FTS
index) was never rescanned: photo search silently lost the photo
forever. The favourite-only and EXIF paths already avoid exactly
this with column-targeted writes; the general sync path missed it.

Known rows now go through PhotoDao.updateSyncFields, an UPDATE of
only the MediaStore-owned columns; new rows still insert via
upsertAll. EXIF/pano, face, OCR and CLIP state are never written by
sync. New real-DB regression test failed pre-fix (ocrText became
null) and passes now. Verified: :photos:testDevUnitTest 411 tests,
0 failures; lint errors are pre-existing on untouched files.

Diff

photos/AGENTS.md
diff --git a/photos/AGENTS.md b/photos/AGENTS.mdindex ef4025e51d..29545817a1 100644--- a/photos/AGENTS.md+++ b/photos/AGENTS.md@@ -24,6 +24,7 @@ _Install: ./install photos (dev by default)._ - `ACTION_VIEW` from another app (e.g. the camera) makes that one photo the stack root with no gallery beneath; in-app back handling must not swallow the system predictive-back gesture there - `MaFragmentActivity` (not `MaActivity`) — biometric + fragment-hosting requirement - Widget code is flat in `widget/` (widget + receiver in one file); ViewModels/ML/compositing live in `platform/`, pure helpers in `domain/`+- MediaStore sync writes already-known rows by column (`PhotoDao.updateSyncFields`), never as rebuilt-row upserts: the sync projection excludes the OCR/CLIP payload columns, so an upsert of a changed row would null its OCR text/geometry and CLIP embedding while leaving the scanned flags set  ## Key files ### Root — entry + inline navigation
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 675416a4fd..3181372479 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt@@ -95,6 +95,57 @@ interface PhotoDao {     @Query("UPDATE Photo SET isFavorite = :value WHERE id IN (:ids)")     suspend fun setFavorite(ids: List<Long>, value: Boolean) +    /**+     * Apply the MediaStore-owned columns of an already-known row by column.+     * Deliberately not an upsert of the rebuilt [Photo]: the sync projection+     * ([getAllForSync]) has no clipEmbedding/ocrText/ocrBoxes, so upserting+     * its rows wrote NULL over a changed photo's OCR text/geometry and CLIP+     * embedding — while leaving ocrScanned set, so the text was never+     * rescanned and silently left search. Columns the sync does not own+     * (EXIF/pano, face/OCR/CLIP scan state and payloads) are untouched.+     */+    @Query(+        "UPDATE Photo SET name = :name, uri = :uri, date = :date, width = :width, " ++            "height = :height, dateModified = :dateModified, duration = :duration, " ++            "isTrashed = :isTrashed, mimeType = :mimeType, album = :album, " ++            "isFavorite = :isFavorite WHERE id = :id"+    )+    suspend fun updateSyncFieldValues(+        id: Long,+        name: String,+        uri: String,+        date: Long,+        width: Int,+        height: Int,+        dateModified: Long,+        duration: Long?,+        isTrashed: Boolean,+        mimeType: String?,+        album: String?,+        isFavorite: Boolean,+    )++    /** Batched form of [updateSyncFieldValues] (one transaction per sync write). */+    @Transaction+    suspend fun updateSyncFields(photos: List<Photo>) {+        for (photo in photos) {+            updateSyncFieldValues(+                id = photo.id,+                name = photo.name,+                uri = photo.uri,+                date = photo.date,+                width = photo.width,+                height = photo.height,+                dateModified = photo.dateModified,+                duration = photo.videoData?.duration,+                isTrashed = photo.isTrashed,+                mimeType = photo.mimeType,+                album = photo.album,+                isFavorite = photo.isFavorite,+            )+        }+    }+     @Query(         "SELECT Photo.* FROM Photo JOIN PhotoFts ON PhotoFts.rowid = Photo.id " +             "WHERE Photo.isTrashed = 0 AND PhotoFts MATCH :match ORDER BY Photo.date DESC"
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 ff6dd69f87..97bf667a5d 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt@@ -41,6 +41,9 @@ open class PhotosRepository internal constructor(context: Context) :     open suspend fun getAll(): List<Photo> = photoDao.getAll()     suspend fun getByUri(uri: String): List<Photo> = photoDao.getByUri(uri)     open suspend fun upsertAll(photos: List<Photo>) = photoDao.upsertAll(photos)++    /** Column-targeted MediaStore sync update for known rows (see [PhotoDao.updateSyncFields]). */+    open suspend fun updateSyncFields(photos: List<Photo>) = photoDao.updateSyncFields(photos)     open suspend fun delete(value: Photo): Int {         var deleted = 0         db.withWriteTransaction {
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 c26b9a7cbe..0edc92c476 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt@@ -389,7 +389,14 @@ suspend fun syncPhotos(     )      if (newOrUpdatedPhotos.isNotEmpty()) {-        repository.upsertAll(newOrUpdatedPhotos)+        // New rows are inserted whole. Already-known rows are written by+        // column only: the rebuilt Photo carries no clipEmbedding/ocrText/+        // ocrBoxes (the sync projection excludes those blobs), so upserting+        // it wiped a changed photo's indexing — OCR text permanently, since+        // ocrScanned stayed set and the OCR worker never rescanned it.+        val (updates, inserts) = newOrUpdatedPhotos.partition { it.id in existingPhotos }+        if (inserts.isNotEmpty()) repository.upsertAll(inserts)+        if (updates.isNotEmpty()) repository.updateSyncFields(updates)     }     // Favourite-only diffs (a toggle here or in another gallery app) are written     // by column: an upsert of the row rebuilt above would drop its CLIP
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 0267b3c9dd..3cd8d6279e 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/GalleryLoadProfileTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/GalleryLoadProfileTest.kt@@ -436,6 +436,9 @@ class GalleryLoadProfileTest {         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 }+        // Known-row sync writes are column-targeted in production; record+        // them with the inserts so assertions see every row the sync wrote.+        override suspend fun updateSyncFields(photos: List<Photo>) { upsertedBatches += photos }         override suspend fun setFavorite(ids: List<Long>, value: Boolean) {}     } 
photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesSyncTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesSyncTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesSyncTest.ktindex 46fe976e08..89d933b92a 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesSyncTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesSyncTest.kt@@ -51,6 +51,11 @@ class PhotosFavoritesSyncTest {         override suspend fun upsertAll(photos: List<Photo>) {             upsertedBatches += photos         }+        // Known-row sync writes are column-targeted in production; record+        // them with the inserts so assertions see every row the sync wrote.+        override suspend fun updateSyncFields(photos: List<Photo>) {+            upsertedBatches += photos+        }         override suspend fun setFavorite(ids: List<Long>, value: Boolean) {             favoriteWrites += ids to value         }
photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1SyncTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1SyncTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1SyncTest.ktindex ba8b109fd0..6c4cbe726e 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1SyncTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1SyncTest.kt@@ -56,6 +56,11 @@ class PhotosSlice1SyncTest {         override suspend fun upsertAll(photos: List<Photo>) {             upsertedBatches += photos         }+        // Known-row sync writes are column-targeted in production; record+        // them with the inserts so assertions see every row the sync wrote.+        override suspend fun updateSyncFields(photos: List<Photo>) {+            upsertedBatches += photos+        }     }      private class FakeScanRepository(context: Context) : PhotoScanRepository(context) {
photos/src/test/java/com/vayunmathur/photos/util/SyncWorkersRealRepoTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/SyncWorkersRealRepoTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/SyncWorkersRealRepoTest.ktindex e8587d6405..20ff8a94b1 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/SyncWorkersRealRepoTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/SyncWorkersRealRepoTest.kt@@ -26,6 +26,7 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import kotlin.test.BeforeTest import kotlin.test.Test+import kotlin.test.assertContentEquals import kotlin.test.assertEquals import kotlin.test.assertTrue @@ -252,6 +253,45 @@ class SyncWorkersRealRepoTest {         Unit     } +    @Test fun syncAlbumChangePreservesOcrAndClipIndexing() = runBlocking {+        // Photo 501 is already indexed: OCR text/geometry and a CLIP embedding+        // are stored, and both scanned flags are set. The provider row differs+        // only in its bucket ("Camera" vs the seeded "OldAlbum") — the change+        // this app's own album move, an edit in another app, or a trash toggle+        // produces on the next sync.+        installed.photos.upsertAll(listOf(+            Photo(+                id = 501L, name = "beach.jpg",+                uri = "content://media/external/images/media/501",+                date = 1_700_000_000_000L, width = 0, height = 0,+                dateModified = 1_700_000_000L, exifSet = true, lat = 10.0, long = 20.0,+                videoData = null, panoData = null, isTrashed = false,+                faceScanned = true, ocrText = "hello sign", ocrScanned = true,+                clipEmbedding = byteArrayOf(1, 2, 3), clipScanned = true,+                mimeType = "image/jpeg", ocrBoxes = "{\"lines\":[]}",+                album = "OldAlbum", isFavorite = true,+            ),+        ))+        syncPhotos(context, installed.photos, null, 0L)+        val after = installed.photos.getAll().first { it.id == 501L }+        // The MediaStore change is applied...+        assertEquals("Camera", after.album)+        // ...without wiping the indexing the row already had. Before the fix+        // the rebuilt-row upsert stored ocrText/ocrBoxes/clipEmbedding as+        // null (and clipScanned as false) while ocrScanned stayed true, so+        // OCR search text was lost permanently (never rescanned) and the+        // CLIP embedding had to be recomputed.+        assertEquals("hello sign", after.ocrText)+        assertEquals("{\"lines\":[]}", after.ocrBoxes)+        assertTrue(after.ocrScanned)+        assertContentEquals(byteArrayOf(1, 2, 3), after.clipEmbedding)+        assertTrue(after.clipScanned)+        assertTrue(after.faceScanned)+        assertEquals(10.0, after.lat)+        assertEquals(20.0, after.long)+        Unit+    }+     @Test fun coolDownBetweenBatchesOnlyPausesOnBatchBoundaries() = runBlocking {         val started = System.currentTimeMillis()         coolDownBetweenBatches(1, "test")