Skip to main content

Captions under concurrent writes

Not released yet (comes after 1.7.0)

PhotoCaption.captions_json holds a photo's captions under one key per writer:

KeyWriter
user_captionthe user's caption (edits.set_caption), the scan's description import (PhotoMetadata._import_description_to_caption) and Restore from file (edits.revert_all), all through PhotoCaption.apply_user_caption
im2txtthe caption job (processing_jobs.generate_caption_job) and Generate caption (GeneratePhotoCaption), through captioning.caption_photo -> PhotoCaption.store_generated_caption
openclip_vitb32the Things job (generate_tag_job), the upload's follow-up and the embedding run, through PhotoCaption.store_tags
imported_descriptionthe scan's description import, Restore from file and the write-back (photo_writer._remember_file_description)

The caption and Things jobs load the row, call their sidecar for seconds, and then store. Every writer goes through PhotoCaption.set_captions, which reads the row again with select_for_update() inside transaction.atomic(), changes only its own keys (a None value removes one), rebuilds the search captions from the result and writes captions_json with a queryset update(). On PostgreSQL READ COMMITTED a second writer waits for the first one's lock and then reads its commit; on SQLite the transaction is BEGIN IMMEDIATE, so it holds the write lock before it reads. The discard of a replaced picture's generated captions (generated_content._discard_generated_captions) and the write-back's _remember_file_description remove or set their keys the same way. The scan's description import decides under the same lock whether the file's description replaces the caption, so a caption typed while the scan reads the file is not replaced. set_captions returns the captions it read under the lock; edits.set_caption records the caption it replaced from them (PhotoCaption.replace_user_caption), so the edit history holds the caption that was really there, also when the scan imported one just before.

Up to 1.7.0 each writer saved the whole dict it had loaded: a caption typed, changed or cleared during a caption or Things job came back as it was when the job started, and a caption saved while a job stored its caption removed the generated one.

The tests are api/tests/metadata/test_caption_jobs_keep_concurrent_edits.py (each interleaving, forced in one connection) and api/tests/metadata/test_caption_lock_postgres.py (two connections, in the PostgreSQL CI step). The model is verification/metadata/RowLostUpdate.tla (CaptionFix, CaptionLock): without the row lock the re-read alone still loses a caption.