Events, places, album comments and tags under concurrent edits
Event covers and titles
regenerate_event_titles and generate_event_albums (api/albums/auto_albums.py) load the Events at the start and write them while the owner can pick a cover (PATCH /api/albums/auto/{id}/). Every write names its columns:
AlbumAuto._generate_titlesavestitle_partsandtitle(update_fields, which also moveslast_modifiedfor the sync feed);- the Event run saves
timestamp,gps_latandgps_lononly when it changed them; _merge_albummoves the merged Event's favourite and cover with conditional UPDATEs: the cover only onto an Event without one, so the Event's own pick wins;AlbumAutoEditSerializer.updatesaves only the fields of the request.
Up to 1.7.0 these were full-row saves: the job wrote back the cover it loaded before the owner's pick, and a cover pick wrote back the title from before the job's new one.
A narrowed save of an Event deleted meanwhile fails instead of inserting the row again. The title job runs each Event in a savepoint (_unless_deleted): on ObjectNotUpdated or a DatabaseError it checks that the Event is gone and goes on with the next one. The Event job runs each group, finding or merging its Events included, in a transaction (_with_one_retry): when an Event it works on was deleted meanwhile (ObjectNotUpdated, AlbumAuto.DoesNotExist, or a deferred foreign key IntegrityError at the commit), the group runs once more from the current rows. _generate_title computes the title in a savepoint, so the fallback title can still be saved after a failed query on PostgreSQL.
Place membership
refresh_user_places (api/places/membership.py) runs in one transaction.atomic() block and first locks the owner's User row (_lock_owner, select_for_update(no_key=True): FOR NO KEY UPDATE on PostgreSQL, so rows that point at the user, such as a photo's tombstone, can still be inserted meanwhile), then reads the places, the positions and the links. On PostgreSQL two refreshes of one user run one after the other, and the second reads what the first committed; on SQLite the IMMEDIATE transaction does the same. A position change commits before its own refresh runs, so the refresh that runs last reads the new position. Up to 1.7.0 a full refresh that read an old position removed a photo another refresh had just put into the place, and two refreshes creating the same link failed with an IntegrityError.
Comment threads and photos leaving an album
A thread belongs to a photo in an album, and goes when the photo leaves it. members.take_out (behind remove_photos, take_out_contributions and the edit serializer's removedPhotos) locks the album row (lock_album) and removes the photos and their comments and likes in one transaction. add_comment and set_liked lock the same row in their transaction and check again that the album shows the photo (_hold_thread), answering 404 otherwise. So a comment either lands before the photo leaves, and is deleted with it, or is refused. The same lock serializes two likes of one user, so a double tap gives one like instead of a unique-constraint error (api/tests/albums/test_album_like_postgres.py, two connections, in the PostgreSQL CI step).
Tag merge, add, remove, rename and delete
TagViewSet._lock_tags (api/views/tags.py) locks the tags of the request (select_for_update, in primary key order) inside transaction.atomic() and answers 404 when one of them is gone. Every action then reads the tags' names again, so the keyword write-back (edits.tags_changed) gets the names the tags have under the lock, not the ones get_object() loaded before a rename. A merge locks both tags before it reads the merged tag's photos, so a photo added to that tag meanwhile either is read and moves over, or its add waits for the merge and then fails with a 404; two merges of the same two tags into each other run one after the other, and the second finds its tag gone. On SQLite the transaction is BEGIN IMMEDIATE, which serializes the same way. Up to 1.7.0 the merge was three autocommitted steps: an add during the merge lost its tag, and crossing merges deleted both tags.
A rename locks its tag and saves only the fields the request changed (save(update_fields=...)), so an add during the rename keeps its photo_count, and a rename of a tag a merge has just deleted is a 404 instead of the serializer's full save, which Django turned into an INSERT that brought the tag back empty. A delete locks its tag and reads its photos for the keyword write-back under the lock, so a photo added just before the delete gets the write-back too.
Tag photo counts
The m2m_changed receiver update_tag_photo_count (api/models/tag.py) locks the tags it counts first, in primary key order. On PostgreSQL, under READ COMMITTED, two adds to one tag at the same time each counted without the other's uncommitted link, and the last to save stored a count one too low. The second receiver now waits for the first add to commit, and its count, a new statement, sees the first add's link (api/tests/metadata/test_tag_count_postgres.py, two connections, in the PostgreSQL CI step). SQLite serializes the two transactions already. refresh_tag_photo_counts (trashing, hiding or deleting photos) locks its tags in primary key order too before its one UPDATE, so it cannot take two tags' locks in the opposite order to a merge.
User album covers
A user album's card (AlbumUserListSerializer.get_cover_photo, api/serializers/album_user.py) loads the picked cover through the album's vouched links to its owner's photos (cover_links in with_album_user_list_relations, as with_event_cover does for Events), so a cover the album no longer shows (hidden, trashed, removed or taken out) loads as nothing and the card falls back to its first shown photo. AlbumUserEditSerializer.update refuses a cover the album does not show after the request: a 400 on cover_photo before anything is written. Nothing clears cover_photo when the photo leaves, so a restored cover comes back. Up to 1.7.0 the card showed the stored cover whenever one was set, to the album's members too. The sync feed already left such a cover out for members (SyncUserAlbumsView).
Sharing and un-sharing photos
SetPhotosShared (api/views/photos.py, POST /api/photosedit/share/) writes the Photo.shared_to rows and the recipient's DeletionLog tombstones in one transaction.atomic() that first locks the selected photos in primary key order (select_for_update(no_key=True)). On PostgreSQL a share and an un-share of the same photo then run one after the other; on SQLite the transaction begins IMMEDIATE. Up to 1.7.0 every statement committed on its own, and a share whose tombstone delete ran after an un-share's tombstone left the photo un-shared with no tombstone, so the recipient's device kept it. The tombstones are scoped through DeletionLog.objects.owned_by(recipient), and an unknown target_user_id is a 404 instead of a server error. Tests: api/tests/sharing_and_public/test_photo_share_tombstone_order.py and, on PostgreSQL, test_photo_share_tombstone_postgres.py (the un-share waits for the share, pg_blocking_pids, and its tombstone stays).
The models are verification/organize/AutoAlbumCover.tla, PlaceMembership.tla, CommentThread.tla, TagMerge.tla, TagCount.tla, UserAlbumCover.tla and ShareTombstone.tla.
Manual stacks
Every request that changes a stack is one transaction that starts with lock_stacks (api/models/stack_locks.py):
- the rows of the photos it names and of every photo in its stacks, in the order of their ids;
- the rows of the stacks, in the order of their ids;
- a second look. When a photo joined one of the stacks meanwhile, the locks are given back and it starts over.
The photos named and the photos of the stacks come from one UNION. With an OR of two subqueries PostgreSQL read the whole photo table for every call (about 80 ms with 150,000 photos, 0.3 ms with the UNION), and a permanent delete calls it once for each photo.
Use it for any new code that puts photos into a stack, takes them out, or chooses a cover. The permanent delete of a photo, the repair that merges a RAW photo and the detection of bursts use it too. restore_photos uses it because a photo that comes back may become the cover of its stack, and Duplicate._lock because resolving or reverting a duplicate group restores photos. trash_photos locks its photos in the same order before it writes: a plain UPDATE locks rows in no order and deadlocks with a stack request. An account comes before its photos (see Sharing writes).
The models are verification/organize/StackChanges.tla (what can get lost) and StackLocks.tla (who waits for whom), and the tests api/tests/stacks/test_stack_races_postgres.py.