Skip to main content

Duplicate resolve locks

Not released yet (comes after 1.7.0) A photo is often in two duplicate groups: an exact copy is in its exact group and in the visual group of the same picture. Duplicate.resolve (apps/backend/api/models/duplicate.py) keeps one photo and trashes the others, so two resolves of overlapping groups must never trash every copy between them. The model is verification/faces/DuplicateResolve.tla.

The locks​

resolve, dismiss and revert start with _lock, inside one transaction.atomic():

  1. the group's photos and the other photos of their stacks, select_for_update(no_key=True) in pk order;
  2. those stacks, in pk order;
  3. the group row, select_for_update();
  4. a second look. When a photo joined the group or one of the stacks meanwhile, the locks are given back and it starts over. With the group row held, no photo can join the group any more.

This is lock_stacks (api/models/stack_locks.py, see Manual stacks): a resolve or a revert takes photos out of the trash, and that may choose the cover of their stacks again. Up to 1.7.0 it asked for the stacks after it had the group, and could deadlock with a change of one of them.

The same order everywhere means two reviews never wait on each other in a circle. With the photos locked, resolve checks that the kept photo is still out of the trash (_is_live) and raises KeptPhotoInTrashError (a 409 kept_photo_in_trash from the view) otherwise. A second resolve of an overlapping group waits for the first to commit and then sees what it trashed.

The photo lock is FOR NO KEY UPDATE, not FOR UPDATE. It conflicts with itself, with the UPDATE that trashes a photo and with a DELETE, which is all the resolve needs. It does not conflict with the FOR KEY SHARE that PostgreSQL takes on a photo when a row referencing it is inserted (a Face, an album membership, a Duplicate.photos row), so a scan or an album edit never waits on a resolve, and the Tag and Person count refresh after the trash cannot deadlock against such an insert.

On SQLite select_for_update does nothing, and the BEGIN IMMEDIATE of atomic() (librephotos/settings/_sqlite.py) holds the one write lock for the whole resolve, so two resolves run one after the other.

Choosing the photo to keep​

DuplicateResolveView takes keep_photo_id or keep_photo_hash. Exact copies share a hash, so by hash it takes the lowest-pk photo of the group that is out of the trash and not removed, and only when there is none one in the trash, which the resolve then refuses.

Tests​

  • api/tests/duplicates/test_resolve_keeps_a_copy.py: resolving one after the other, the lock order, keeping by hash, the photo counts of the list and the detail.
  • api/tests/duplicates/test_resolve_concurrent_postgres.py: two threads resolve the exact and the visual group at once on PostgreSQL, the second held until the first holds its locks; it is skipped on SQLite and runs in the PostgreSQL job of test-backend.yml.