Thumbnails, ML results, the similarity index and archives under concurrent work
Rotation and its thumbnails
The web lightbox sends one POST /api/photosedit/rotate/ per click without waiting, so two turns of one photo can run at once. rotate_photo (api/metadata/photo_writer.py) turns an unedited photo in three steps:
- Turn.
_turnruns one shorttransaction.atomic(): it locks the PhotoEdit row (a photo whose edit is shown is turned inside its recipe byrotate_editinstead), locks the Photo row, composes the turn on thelocal_orientationit reads under the lock, saves it, swaps the shown size from the stored width and height, and requests a render (render.request_thumbnails). - Write-back. With media-file write-back on,
write_orientation_to_diskfolds the rotation into the file's own EXIF Orientation under the per-photo file claim.write_rotationreadslocal_orientationagain under the claim, and_adopt_written_orientationthen sets it, under the Photo and Thumbnail row locks, to what is left on top of the fold (render.local_orientation_after): 1 when nothing was turned meanwhile, the newer turn otherwise. The shown picture does not change. A fold that movedlocal_orientationrequests a render and renders the thumbnails itself; a Write Metadata job or a queued retry folds the same way. - Thumbnails.
render.rotate_thumbnailsrenders the thumbnails tothumbnails_staged/outside any transaction (stage_thumbnails), thenpublish_thumbnailslocks the Photo and Thumbnail rows and moves them into place only whilerender_versionis still the one they were rendered for; otherwise it drops them.rotate_photorenders in afinally, after the write-back, unless its fold already did.
Render requests, publishing and the repair task
Every change that needs new thumbnails of a photo goes through the same steps: a turn, a fold, a re-key, a rescan rebuild, a probe repair and an editor save (regenerate_thumbnails), and the first render of a photo the scan finds (generate_thumbnail, which requests nothing and only fills in missing files).
want_thumbnailsreads the photo'simage_hash, main file andlocal_orientationagain under the Photo row lock, so a render never starts from a hash or path that a re-key or a move has replaced.- A render request (
request_thumbnails, in the transaction of the change) movesThumbnail.render_versionand queuesrepair_thumbnails(photo_id, version)two minutes later, with a dedupe key per version. - A publish replaces the big thumbnail and the square together: if the second
os.replacefails (on Windows, while the file is being served), the first is put back from a hard link, the staged files go, andrendered_versionstays behind. Only a publish setsrendered_versionto the version it rendered and movesThumbnail.revision, the public part ofthumbnail_versionthat the grid puts in?v=. The first render moves the revision too when it shows something newer thanrendered_version(a photo turned while its thumbnail was missing). So?v=moves only with new bytes, never with the turn, and a browser never keeps an older picture under a newer?v=. - A publish dropped because
render_versionmoved needs no retry: whatever moved it renders after itself. - The repair task does nothing when
rendered_versionhas reached its version, and otherwise renders and publishes the photo as it is now. It covers a render that fails and a worker killed after the turn committed. The rotate view answers 200 once the turn is saved, even when its render failed. - Staged files of a photo go with its thumbnails (
delete_thumbnail_files); any older than an hour are swept before each render and by the dailycleanup_deleted_photos.
So no database lock is held while a thumbnail renders (on SQLite, no write lock for the whole render), the files change only after the change they show has committed, and nothing a failed or killed render leaves behind stays wrong.
Videos go the same way: ffmpeg writes the first frame and the clip to thumbnails_staged/, the still is resized there, and one publish replaces all of them. A video whose rebuild fails or is killed keeps the thumbnails it had until the repair task, which probes the file again, has made new ones. generate_thumbnail and the poster job (create_video_posters) render only what is missing, and their publish is dropped when a rebuild was requested meanwhile. A publish also stores the file names, so the Thumbnail row always names files of the photo's current image_hash. Up to 1.7.0 a video was rebuilt in place: a rescan, a probe repair and a replaced file could mix the pictures of two videos, and a move during a rebuild left the video without a thumbnail.
A replaced file and its photos
rekey_replaced_file (api/directory_watcher/file_handlers.py) runs when a scan finds other bytes in an indexed file. It compares the pictures first, outside any transaction, because that renders the file. _rekey then locks the PhotoEdit, Photo and File rows (_lock_holders) and looks up the photos of the file again: one attached meanwhile starts the transaction over, and nobody can join until it commits. Two users who scan the same folder share the File row, so this can be another user's photo.
Thumbnail.rendered_from is the File the thumbnails, and with them the perceptual hash, were made from. A publish sets it, unless it shows an edit, and a re-key moves it on with the File row. _shown_from picks the photos the verdict is for by it; for thumbnails of an older release, where it is empty, it picks those whose image_hash was taken from the file and that have it as main file. A photo named after its RAW and shown from its JPEG is not one of them, so a rating written into the RAW does not cost it its faces, as it did up to 1.7.0. Up to 1.7.0 only the image_hash counted. After a metadata write the picture is the same, the File row moves on to the new hash and the photo keeps its image_hash, so such a photo never followed its file again: a picture edited in another program after a rating had been written to the file kept its old thumbnails.
A photo can have a main file its thumbnails do not come from: the old main file is gone and another one stands in for it. Comparing the stand-in with the stored perceptual hash would call any metadata write a new picture and cost the photo its faces, things, text and edit. Such a photo (_shown_from_nothing_else) has its thumbnails made again and keeps everything else; from then on it is compared like any other. When the file its thumbnails come from is still one of its files (a RAW it was indexed from), a change of the main file changes nothing.
For a new picture the transaction also empties the Thumbnail row's file names, so no job reads the old thumbnail under the new hash, and requests the render, so a worker killed right after the commit loses nothing.
Files of a photo that is gone
Thumbnails, edit files, share copies and the cached transcode are named after Photo.image_hash, face crops after it and a number. Nothing on disk is ever deleted because the database does not know it: an empty or wrong database (a typo in DB_HOST, a restore that is still running) knows nothing. Instead, the transaction that removes the last row of a file records the removal in DerivedFileRemoval (api/photos/file_removal.py): remove_files_named_after for everything named after a hash, remove_file for one file, with its size and modification time. After the commit settle_removal deletes the files and then the record. replay_file_removals, scheduled every ten minutes, settles what a killed process left; a file that cannot be deleted is tried again the next day.
The same file can come back into the library under the same names at any moment, also between the commit and a replay, so every removal asks first:
_remove_unused_thumbnailsdeletes only what no photo and no Thumbnail row uses, and then asks again: a photo that took the hash while the files went gets a render request. A replay that finds the hash in use and the thumbnails missing requests one too._remove_unless_editedlocks the PhotoEdit and Photo rows with the hash and removes the edit files only when no edit is left.- A single file goes only when it is still the one that was recorded, and in a replay only when no Face or File row names it.
Files that releases before 1.8.0 left behind have no record and stay on disk.
Row lock order
Every transaction that writes these rows takes them in one order: PhotoEdit, then Photo, then File, then Thumbnail. That holds for _turn, the fold, publish_thumbnails and want_thumbnails, the editor's _store (it locks the Photo row right after the PhotoEdit row), the re-key of a changed file, the purge of removed photos (_delete_locked) and Remove missing photos (_lock_still_missing). The last three lock the PhotoEdit and Photo rows of every affected photo first (lock_edits_and_photos in api/photos/row_locks.py). A move records its new paths in the same order (record_new_paths), and the job that trashes photos outside the library locks the Photo rows only, without their keys (FOR NO KEY UPDATE). Taking them in another order deadlocks on PostgreSQL against one of these. A transaction that also locks accounts takes those before all of these.
Up to 1.7.0 nothing was locked: two clicks that loaded the photo before either saved lost a turn, a second click that arrived while the first rendered left the grid square a turn behind the big thumbnail, a rebuild that rendered in place could overwrite a rotation that completed meanwhile, and with media-file write-back each fold added the request's own copy of local_orientation to the file and reset it to 1, so two quick clicks folded one turn twice. The editor's save and the re-key of a changed file took their rows in opposite orders.
Upgrade jobs over every thumbnail
strip_thumbnail_metadata (api/thumbnails/metadata.py) and make_thumbhashes (api/thumbnails/placeholders.py) run while photos are turned and edited. Both read a file first and write later:
- The clean copy of a thumbnail is written next to it, ExifTool works on copies as well, and
_replace_if_unchangedmoves it over the file only while it holds the photo's row lock and the file is still the one that was read (inode, size and modification time).publish_thumbnailsholds the same lock. A thumbnail published meanwhile has no metadata to remove. The copy gets the mode and owner of the original, because the proxy that servesprotected_mediamay run as another user. - Video thumbnails are cleaned in batches, in a folder named
strip-metadata-…next to them. One that cannot be copied or replaced is reported, and the others go on.remove_abandoned_copiesremoves the folder of a killed run, at the next run and in the daily cleanup. - A placeholder is stored only where there is still none (
thumbnails_without_thumbhash().bulk_update).
Up to 1.7.0 the copy and the placeholder went over whatever was there, so a turn made during the upgrade could be undone in the grid. The model is verification/derived/ThumbnailCleanup.tla.
OCR text, search embeddings, captions, things and categories
The OCR job (_run_ocr_for_photo in api/directory_watcher/processing_jobs.py) and the search embedding job (store_clip_embeddings in api/search/embedding_jobs.py) load a photo, send its picture to a sidecar and store the answer. A rescan that finds a different picture in the file meanwhile gives the photo a new image_hash and drops its text and embedding in one transaction. The answer is stored only when the photo still has the image_hash it was loaded with:
-
OCR checks it in
transaction.atomic()with the Photo row locked (still_the_loaded_pictureinapi/photos/loaded_picture.py), then writes thePhotoOcrrow and the document category; -
the embedding is one conditional UPDATE on
pkand the loadedimage_hash(_store_embedding), and the Things of that run are filed in the same transaction (_store_results), so a re-key waits for both and then drops both. -
a generated caption (
caption_photo) and the things of a Find things run or an upload (generate_photo_tags), with the embedding of that run, are stored the same way: one transaction that locks the Photo row, compares theimage_hash, and writescaptions_json, the things' albums and the embedding together. Two runs for one photo wait for each other, so the albums are always the things ofcaptions_json. Photos of one user share albums, sorefresh_album_thing_photo_countslocks the album rows in primary key order, and an album gets its covers after the commit: an insert into the covers needs the other photo's row, which a re-key of that photo holds.
An answer for the replaced picture is dropped, and the photo is picked again by the next run because it has no text or embedding.
A category the user set (category_source="user") stays as they set it. _derive_is_document and Classify Media (_write_category_flags) write the flags with an UPDATE that skips such rows, so a correction made while the job ran is not overwritten by a value computed from the row it loaded before.
Up to 1.7.0 the text, embedding, generated caption and things of the old picture stuck to the new one for good, and OCR or Classify Media could overwrite a category the user set during the run.
Switching the OCR model
A request to the ocr service names the model to read with (model), and the service loads that bundle, dropping the one it had. PhotoOcr.engine is the model that was asked, and needs_ocr picks the photos whose text is not filed under the selected one. Before an answer is stored, the setting is read again under the Photo row lock: text of a model that is no longer selected is dropped, so it neither replaces the new model's text nor is stored after OCR was turned off. A job whose model is not on disk fails at once (ocr_model_exists), as the caption job does; a model that goes missing while a job runs is answered 424, which does not count as one of a photo's three attempts.
The recogniser reads each batch of text lines as wide as its longest line (line_width in service/ocr/ppocr/recognize.py, at most 3200 px). Up to 1.7.0 every line was squeezed to 320 px: letters went missing in lines of more than about 20 characters, and the larger the model, the more.
Up to 1.7.0 the service always ran PP-OCRv6 Small, whatever the admin had picked, and its text was filed under the picked model. Migration 0268 renames those rows to ppocrv6_small, so the next run reads them with the selected model, and gives the photos that were given up on their attempts back.
Similarity index rebuild
A rebuild of a user's similarity index is a session in the sidecar: the begin answers a rebuild_token, the pages carry it, and the last page commits. A newer begin supersedes the open rebuild, whose next page is answered 409 and which then stops. _send_rebuild (api/search/similarity.py) sends the begin with an empty page (_begin_rebuild) before it reads any photo. Every page a rebuild reads is read after its begin, so a rebuild that read before a new embedding was stored is superseded by the one that read after it.
Up to 1.7.0 the begin went with the first page, after that page was read: a rebuild that read page 1 before a new embedding could begin and commit after the rebuild that read it, and the new photo stayed out of the index until the next rebuild.
Deleting a user queues forget_similarity_index, which sends DELETE /build/ to the sidecar so that the user's vectors leave the disk. Up to 1.7.0 they stayed there.
Download archives
A download job (zip_photos_task in api/photos/zip_downloads.py) writes the archive to <name>.zip.part, renames it to <name>.zip and then schedules delete_zip_file a day later. Before each archive it removes the .part and .zip files in the zip folder that were not touched for a day (_remove_abandoned_zips). A worker killed between the rename and the schedule leaves an archive no delete is scheduled for, and the next archive build removes it. Up to 1.7.0 only .part files were removed and such an archive stayed for good.
ArchiveContents counts what the job found. A recorded file that is not on disk goes into missing_paths, and a photo without any recorded file counts as one missing file. The job completes with files_included and files_total, and as a partial failure with the missing paths when the two differ. A job that found no photo or video at all fails with reason: files_not_found and leaves no archive. GET /api/photos/download?job_id= answers these as files_included, files_total and files_not_found. The counts are written in the same UPDATE that ends the job, so a poll never sees a finished job without them. The reason is written in the same transaction as the failure.
With allow_single_file, POST /api/photos/download answers file instead of a job when the selection is one photo that has one file (only_file). The client then fetches the original from /media/photos/<hash>?original=1, under the rules that hold for every original. When that answers with an error, the web app starts the download once again without the flag: the proxy may not be allowed to read a file that the job can read, and the job says when the file is gone. A client that does not send the flag always gets an archive job. ?original=1 also skips the Convert every video before it plays conversion, for the owner only.
The web app decides who can open a link in one place, shareReach in components/sharing/shareReach.ts. Every dialog that shows a link uses it, through ShareReachNote or directly.
The models are verification/derived/RotateRegen.tla, VideoRebuild.tla, RekeyHolders.tla, RowLockOrder.tla, StaleEnrichment.tla, GeneratedCaptions.tla, ThingLocks.tla, OcrModelSwitch.tla, EmbeddingConversion.tla, SimilarityRebuild.tla, ZipArchive.tla and DownloadOutcome.tla, and verification/trash/DerivedFiles.tla and EditFiles.tla. The PostgreSQL tests api/tests/photos/test_rotate_races_postgres.py (a second click does not wait for a render; a rotation waits for an editor save, and for a re-key, instead of deadlocking) and api/tests/scanning/test_stale_enrichment_postgres.py run two connections in the PostgreSQL CI step.