One photo per file
A user has at most one photo per main file. The scan builds photos in two phases (apps/backend/api/directory_watcher/file_handlers.py): create_file_record makes the File row of each path, and group_files_into_photo finds or makes the photo of a file group. File rows are keyed by content hash, so two exact copies in one folder (IMG_1.jpg and IMG_1 (1).jpg) are two file groups with one File row, and two workers can group them at the same time.
Finding or making the photo
_photo_for_group takes the rows in the order every other locker takes them, the photo before the File:
- It looks for the photo without a lock (
_group_photo): one whose main file is the group's, then one holding any of the group's media files as its main file or a variant, then one with the same image hash that is not removed. Sidecars are left out of the match, because byte-identical XMPs of two photos share oneFilerow. A photo whose main file is the group's wins, so a RAW uploaded before its JPEG does not make a second photo of the JPEG; the repair job merges the rest. The image hash finds the user's own copy of bytes whoseFilerow carries another user's salt (a path that user scanned first). - In the transaction it locks that photo's row when there is one (
_lock_photo_row,select_for_update(no_key=True)), then theFilerow of the group's main file (_lock_file_row, the same lock). - It looks again. When the answer moved (a removal committed, another task inserted the photo), it lets the locks go and starts over, up to
GROUP_LOOKUP_ATTEMPTS(3) times, then fails the group withGroupLookupMovedError. Three or more exact copies scanned at the same moment could move the answer that often; the group then fails cleanly and the next scan groups it. - It adopts the files into that photo (
_adopt_files_into_photo), or inserts a new photo with its main file set and adds its files (_insert_photo).
The order matters on PostgreSQL. A permanent delete (remove_photo, apps/backend/api/photos/files.py) updates the photo row (_mark_removed) and then locks its File rows (_unlink_files), and the removal of missing photos and the duplicate resolve also lock photos first. A scan that locked the File row first and then wrote the photo (adopting a RAW+JPEG pair moves the main file to the JPEG) deadlocked with an Empty Trash of that photo, and PostgreSQL failed the scan's group with deadlock detected.
A second task for the same file waits on the lock and then finds the first task's photo. On PostgreSQL the lock is a row lock and the lookup is a statement after it, so under READ COMMITTED it sees what the first task committed. On SQLite select_for_update does nothing, and the transaction is IMMEDIATE, so it holds the write lock from its start and the two never interleave. A worker killed inside the transaction leaves nothing behind: the insert and the file links roll back together, and the retried task starts over. The edit of a photo whose main file changed follows it (renditions.follow_main_file) after the transaction, so no render runs under the lock.
create_new_image (uploads, Nextcloud) does the same for one file in _photo_for_file: under the File lock, an existing photo of the file is returned instead of a second one. It writes no existing photo, so it needs no photo lock.
The unique constraint one_photo_per_main_file on Photo (owner, main_file) backs the lock. It leaves out photos marked shares_main_file, which only the account deleted has: two deleted users can have had a photo of the same file, and each stays as it was. Both functions catch an IntegrityError once and run again, which then finds the other writer's photo. The writers that move a main file without the lock skip a file that is the main file of another of the owner's photos (free_for_main in apps/backend/api/photos/files.py): the stand-in for a gone main file and the repair of RAW-only photos pass over it, and POST /api/photos/{image_hash}/main-file/ answers 409 main_file_of_another_photo.
Up to 1.7.0 the lookups, the insert, files.add and the main-file save were separate statements in autocommit. Two tasks could both find nothing and each insert a photo, and a kill after the insert left a photo without a main file, which missing() lists and nothing showed. A retried task found that photo by its image hash and adopted the file without setting the main file. _adopt_files_into_photo now sets the main file of a photo that has none (and is not removed), so such a photo is repaired the next time its file is scanned.
Two File rows for the same bytes (a path another user scanned first, and the user's own copy) are two locks, so two tasks for them are not serialized; that case needs two users scanning overlapping folders and stays as before.
The migration
0263_one_photo_per_main_file merges the photos that share a main file, as 0159 did for repeated Nextcloud scans, and 0272_photo_shares_main_file adds the constraint. The photos of deleted are not merged, since they can come from different users and a merged photo would show one user's caption and people to those the other shared with; 0272 marks all but one photo of each file instead. Development versions added the constraint in 0263, so 0272 drops it first. Development installs that already ran the earlier version of 0263 keep the photos of deleted it merged, with the shares of both. The kept photo is the one not in the trash, then the one with a pending move (PendingMove, a move a kill cut short), then the one with an edit, then the one with the most metadata edits, then the oldest, then the lowest id. It keeps its own values and takes the highest rating (when that changes its rating, rating_edits moves on, so the hourly write-back writes it to the file of an owner who writes metadata to files), public if any copy was public, every album, event, tag, Thing, share, like, stack and duplicate group link, the one-to-one rows it lacks (edit, caption, OCR text, public link; when both were edited, the dropped photo's edit is dropped), the pending move of a dropped photo when it has none (PendingMove, so the move sweep still finishes or puts back its staged files) and the faces (a face at the box of one of its own is dropped, the labelled one winning). Counts are recomputed, a stack or duplicate group left with one photo is removed, and each dropped photo gets a tombstone for the sync clients. Two pending moves in one group are never merged: both photos share the main file, so both moves carry a row with the same source and different destinations, and the sweep plans a move by its sources. The migration then stops before it changes anything, naming the photos, and asks the admin to start the previous version once (its move sweep finishes the moves at start) and upgrade again. Pending moves only exist since 1.8.0, so an upgrade from 1.7.0 never meets this.
One link per file
photo.files.add(file) does not look first whether the photo has the file: nothing listens to m2m_changed of Photo.files, so Django sends INSERT ... ON CONFLICT DO NOTHING and leaves the rest to the unique index on api_photo_files (photo_id, file_id). Up to 1.7.0 no PostgreSQL database had that index, nor the one on api_photo_shared_to (photo_id, user_id), new installs included: the migration that made the photo's UUID its primary key gave the link tables a new photo_id column, and the index went with the old one. SQLite databases always had both. So a file added again was linked again, even by one task after the other: create_new_image for a sidecar read twice, or _attach_embedded_motion_video.
A second link is more than a line too many. The permanent delete writes one journal row per link and expects one per path, so remove_photo refuses a photo with a repeated link (StagingNotJournaledError) each time, and the photo would stay in the trash for good.
0273_photo_link_unique_indexes adds both indexes where they are missing. Each table has a transaction of its own:
- It locks the table (
ACCESS EXCLUSIVE), so it waits for a worker of the old version that has just added a link, and no link comes in until the index is there. It holds no other lock then, so it cannot deadlock. - It deletes the repeated links and keeps the oldest of each.
- It creates the index.
It also makes photo_id NOT NULL in seven link tables (PHOTO_LINKS in the migration), as the models and every SQLite database have it; a link without a photo belonged to nothing and is deleted. With 500,000 links and 5,000 repeated ones in each of the two tables it takes about 6 seconds on PostgreSQL 16. A table that has its index is skipped, so it can run again after a stop, and going back drops the indexes, not the NOT NULL. While both versions run, a web process of 1.7.0 that shares the same photo with the same person twice at the same moment gets an IntegrityError for the second one; since 1.8.0 the second request waits for the photos and finds the share.
The database is compared with the models in CI, see The schema.
Tests and model
apps/backend/api/tests/scanning/test_one_photo_per_file.py: a second task between the lookup and the insert, a photo inserted meanwhile, a kill after the insert, a photo left without a main file, the constraint,create_new_imagefor an exact copy, and the stand-in and repair skipping another photo's main file.apps/backend/api/tests/scanning/test_group_files_lock_postgres.py: on PostgreSQL, a second task blocks on theFilerow (pg_blocking_pids) and takes the first task's photo, and a rescan of a trashed RAW+JPEG photo during its permanent delete waits for the delete instead of deadlocking with it.apps/backend/api/tests/migrations/test_migration_0263_one_photo_per_main_file.py: the merge, andtest_migration_0272_photo_shares_main_file.pythe marks.apps/backend/api/tests/migrations/test_migration_0273_photo_link_unique_indexes.py: the repeated links, a second run, the way back, and a photo the trash cleanup failed on and then deletes.apps/backend/api/tests/photos/test_photo_links_postgres.py: the same sidecar, motion clip and share added on two connections at once, and a link added while0273runs.verification/scanning/PhotoLinks.tla: two writers and the migration; without the index a photo ends with two links, and the migration that locks after its delete fails.verification/scanning/GroupLockOrder.tla: the photo-first order passes; theFile-first order deadlocks, and the photo-first order without the second lookup adopts into a removed photo.verification/scanning/GroupRace.tla: the configurations of the current code pass; the code before the fix failsOnePhotoPerFileandNoStuckPhoto, and the lock and the adopt fix each fail without the other.