People: names and locks
Not released yet (comes after 1.7.0) A person is found by its name. get_or_create_person (apps/backend/api/models/person.py) looks one up by owner, kind and name and creates it when there is none; a face label (SetFacePersonLabel), a drawn face (AddFaceView), the face regions a scan reads (api/faces/photo_faces.py) and the clustering's "Unknown NNN" (api/faces/cluster_manager.py) all go through it. Django's get_or_create is a lookup, then an insert, then on IntegrityError a lookup again, so it is only safe with a unique constraint behind it. The model is verification/faces/PersonGetOrCreate.tla.
The constraint
unique_person_name_per_owner_and_kind on Person (cluster_owner, kind, name), for people with an owner. It is per user: two users may each have an "Anna". It is per kind: a named person and a cluster person may share a name, as the clustering's "Unknown NNN" never collides with a person someone named so. A person without an owner (a legacy row) is not covered.
Two callers that miss the lookup at once both insert; the second insert fails on the constraint and its get_or_create finds the first one's person. On PostgreSQL the second insert waits for the first one's transaction and fails once it commits; on SQLite the inserts run one after the other under BEGIN IMMEDIATE. Either way there is one person, and no later lookup raises MultipleObjectsReturned.
PATCH /api/persons/<id>/ with a newPersonName that another of the owner's people of the same kind has answers 400 with the code unique on newPersonName, as a taken group name does. The field validator (FreePersonName) checks first; a rename racing a create hits the constraint, which answers the same 400 and code, without the field. The rename saves only the changed columns (save(update_fields=...)).
Migration 0265
0265_unique_person_name merges the people a race already made, per owner, kind and name, before the constraint goes on, as Merge into does. The kept person is the one shared with someone, then the one with the most faces labelled as it, then the lowest id. It keeps its own name, cover, birth date, shares, share decisions, first-share date and sharing switches, and takes a cover or a birth date from the others only when it has none. It takes:
- their faces, labelled and suggested (
person,cluster_person,classification_person), and their clusters; - their groups;
- the "not this person" of their faces; a face labelled as the kept person drops its "not this person" of it.
The others' shares and share decisions go with them, as in Merge into: moving them would show the users they were shared with the kept person's photos, places and people, which its owner never shared with them. A share set only on one of the others has to be made again on the kept person.
Its face count is recomputed, and each merged person gets a tombstone (DeletionLog) for the sync clients. The tests are in apps/backend/api/tests/migrations/test_migration_0265_unique_person_name.py and apps/backend/api/tests/faces/test_person_unique_name.py.
Lock order
Not released yet (comes after 1.7.0) A merge, a face label, a training page, a clustering and a person delete all write people and faces at once. On PostgreSQL (READ COMMITTED) they take their row locks in one order, so none of them waits on another in a circle. The models are verification/faces/PersonLocks.tla and, for the transactions that also hold a photo, verification/faces/FaceLockOrder.tla. Setting who a person is shared with and deleting an account take their accounts first and then follow the same order; verification/sharing/AccountLocks.tla is their model.
- Photo rows, in pk order. A label, a training page, a clustering, a merge and a person delete lock none. A scan storing a photo's faces, a face drawn by the user, Deduplicate Faces, the turned-face repair and a replaced file lock the Photo row first, then the people, then the faces (
lock_people_and_facesandchange_faces_ofinapps/backend/api/faces/people.py). A label committed between reading the people and getting the faces makes them give those locks back and start again. A finished thumbnail goes from the Photo to its faces. A photo removal (journal, then Photo, then stacks, groups and File) and a duplicate resolve (Photo rows in pk order) touch people only through Django's collector, which clears a person's cover (a Person row) before it deletes the faces: Photo, then Person, then Face. A transaction that holds a person never waits for a photo: a default cover (Person._choose_cover) is picked among the faces whose photo nobody has locked, and a cover the user picks locks the photo before the person. When every photo it could come from is locked, the cover is picked right after the commit, in a transaction that takes the photo first (_choose_cover_later). - The user's clustering lock (
lock_clustering, the user'sUploadFollowupStaterow), before any Person row.record_face_labelruns once the labelling commits (transaction.on_commit), so no transaction holding people or faces waits for that row. - Person rows, in pk order. A transaction that writes a reference to a person (a label, a prediction, a restored label, a "not this person"), or recounts one, takes
Person.objects.filter(...).lock_for_update()(FOR NO KEY UPDATE) first, scoped to the requester's people where a request names them. A delete takeslock_for_delete()(FOR UPDATE) throughdelete_people(apps/backend/api/faces/people.py). - Face rows, in pk order (
select_for_update(no_key=True)), every face the transaction will write, before its first UPDATE:lock_faces_oflocks every face whoseperson,cluster_personorclassification_personis one of the people, and a cluster rebuild'slock_rebuilt_rowsalso the faces in the user's clusters and the faces it clusters, so a merge's suggestion UPDATEs, a rebuild's writes and Django's collector (which sets the faces toNULLin field order, not pk order) only touch rows already locked. - Counts and search captions. A label recounts after its commit; each recount takes its own person lock (
recount_people,refresh_person_face_counts).recount_peoplewrites a person's count and cover in one UPDATE, and a transaction calls it once, after its last face: PostgreSQL checks all foreign keys of a row again when a transaction updates it a second time, and for a person that is a share lock on the cover photo, taken while holding the person. A merge recounts inside its transaction, under the source and target locks it already holds, and rebuilds the search captions (PhotoSearchrows) there too: aPhotoSearchrow is the last lock in any of these transactions, and a caption write (PhotoCaption.set_captions: thePhotoCaptionrow, then thePhotoSearchrow) never waits for a person or a face. The face tags are written to the files after the commit, through the per-photo file claim (queued on commit for a merge). Tag locks are not part of these transactions.
FOR NO KEY UPDATE does not conflict with the FOR KEY SHARE that an insert or an FK check takes on the person it references, so a scan saving a new face of a person never waits on a label. FOR UPDATE does, which is why a delete takes it first and holds nothing else while it waits.
On SQLite select_for_update does nothing, and each of these transactions runs under BEGIN IMMEDIATE, one after the other.
What each writer does
- Label (
relabel_faces,apps/backend/api/faces/labels.py). One transaction locks the new person, then the faces, so the person a face had is the one it loses. Sending faces to unknown locks the faces' people instead and records "not this person" only for the people it locked. When the new person was merged away or deleted meanwhile,relabel_facesraisesPersonGoneError, and the label view names a new person of that name: a label names a person by name, so this is what labelling right after the merge gives too. The counts and covers are refreshed after the commit. - Merge (
merge_people,apps/backend/api/faces/merge.py). It locks the source and the target first, then every face referencing the source (lock_faces_of), and moves the faces it locked; a face labelled meanwhile keeps its new label. Before the delete, it takes the sourceFOR UPDATE, which waits for every statement still referencing it, locks the faces again, and moves the faces that got the source in the meantime, such as a scan's new face, to the target. A merge of a person deleted meanwhile is a404. Not released yet (comes after 1.7.0) A photo without a search row gets one after the commit, and a face is written once: both the new row and a second UPDATE would check the photo, and wait for a replaced file that waits for the people. These search rows are written in batches that lock the photos still there (index_missing_photos), so a photo deleted right after the merge is left out and the finished merge does not answer with an error. - Scan (
extract_faces,apps/backend/api/faces/photo_faces.py). One transaction saves everything a scan found on a photo, as described under Finding faces below. When a person the file names was merged away or deleted meanwhile, nothing is saved, the crops written are deleted, and the photo is read once more. - Deduplicate Faces and the turned-face repair (
apps/backend/api/faces/deduplicate.py,apps/backend/api/faces/turned_faces.py). They look for faces to delete without a lock and choose again from the locked rows, so a face the user labelled meanwhile is the one that stays. - Training (
store_predictions,apps/backend/api/faces/classify.py). Each page locks the people it predicts and leaves out the ones that are gone, then locks the page's faces, reads their labels and their "not this person" answers again, and writes. A face labelled or deleted meanwhile gets no suggestion, and a person the user rejected meanwhile is not suggested. A person deleted while training runs leaves those predictions empty instead of failing the job. - Clustering (
create_all_clusters). Under the clustering lock,lock_rebuilt_rowstakes the cluster peopleFOR UPDATE, then, in one pk-ordered statement, every face it will write: the faces in the user's clusters, the faces it clusters (for_recognition) and the faces referencing a cluster person. Only then dodelete_clustered_people,delete_clustersandwrite_clustersrun, so the collector'sNULLs and the new clusters touch rows already locked. A rebuild that planned before a newer one committed (the recorded watermark is above its own, and a face between the two exists) changes nothing.record_clusteringkeeps the greater watermark, so neither the watermark nor the clusters go back to an older plan. Cluster people are deleted throughdelete_people. - Person delete (
DELETE /api/persons/<id>/):delete_peoplelocks the peopleFOR UPDATE, then every face referencing them in pk order, then lets the collector run. - Sharing a person (
set_recipients,apps/backend/api/faces/person_shares.py). After the accounts it locks, on the first share, the photos the person is labelled on, then the person, and answers404when the person is gone. See The recipients of a person. - Account deletion (
prepare_user_deletion,apps/backend/api/accounts/deletion.py). After the accounts it locks the user's photos, the clustering lock and all their people. The faces of the user's unknown cluster are locked and moved to the one ofdeletedwhen there is one.
The tests are apps/backend/api/tests/faces/test_person_races.py (forced interleavings, on SQLite) and apps/backend/api/tests/faces/test_person_locks_postgres.py (two connections; each checks with pg_blocking_pids that the second writer waits for the first). apps/backend/api/tests/faces/test_face_races_postgres.py does the same for the transactions that hold a photo.
Finding faces
Not released yet (comes after 1.7.0) Finding the faces of a photo takes seconds, and the photo can change meanwhile: its file is replaced by another picture, it is rotated, cropped in the editor or reverted, another scan of it runs, or the admin picks another face model. A box is in the pixels of one thumbnail, so what was found is only stored while that thumbnail is still the one the photo shows. The model is verification/faces/FaceScan.tla.
extract_facesloads the photo and notes what it is about to read (picture_ofinapps/backend/api/faces/picture.py): the image hash, the main file, the thumbnail'srender_version,rendered_versionandrevision, and the face model. A photo whose thumbnails are being made is not read (render.is_being_rendered): the files on disk may then be newer than the database says. This ends when they are in place, or when the repair task has failed for the last time. A photo that cannot be rendered any more is read as its last thumbnail shows it.- The face service and the file's face regions are read, the crops are cut and encoded. No transaction is open and no row is locked.
_save_scanopens one short transaction.lock_picturelocks the Photo row and checks everything noted in step 1. Then the boxes the photo has are read again, so a face another scan saved meanwhile is not saved twice, and the faces, the names from the file andfaces_scanned_atare written together. Crop files are deleted when the transaction fails.- When the picture is no longer the one that was read, nothing is stored and the photo is read once more. When that happens twice,
faces_scanned_atis emptied, and the next Scan Faces takes the photo.
A Scan Faces job that read none of its photos, because all of them are being rendered, starts no clustering and no training (finish_face_scan).
Face regions are placed with the file's own orientation and the rotation LibrePhotos keeps, and a rotation written into the file moves from one to the other in two steps. Regions are therefore only stored while nobody holds the file claim (apps/backend/api/metadata/file_claim.py); the model is verification/faces/FaceRegions.tla.
A face's encoding (generate_face_encoding), a crop cut again (cut_crop), a face drawn by the user (AddFaceView) and the turned-face repair store through lock_picture as well. The drawn face is refused with a 409 and the code picture_changed when the picture is not the one the box was drawn on. The photo's details carry thumbnail_revision, and the client sends it back with the box (POST /api/addface/, optional): without it, only a change after the request arrived is noticed.
Boxes after a rotation
Not released yet (comes after 1.7.0) A rotation is stored at once and its thumbnails are made afterwards. Until they are in place, the faces stay where the old thumbnail has them, and Thumbnail.unrendered_turn keeps the turn they still need and the size of that thumbnail (apps/backend/api/thumbnails/face_turns.py). Several rotations add up in it. The transaction that puts a new big thumbnail in place turns the boxes and empties the field, for a photo without faces as well, so a turn is never applied to faces found after it. When the old thumbnail is gone from the disk and its size was not recorded, it is not guessed: thumbnails are not all as high as BIG_THUMBNAIL_HEIGHT (a photo turned by a quarter, a video). Boxes stay as they are when the picture is framed as before. After a rotation, the new thumbnail turned back has the old size. An edit saved or reverted then moves only the boxes whose place on the uncropped picture is kept (PhotoEdit.face_boxes). Face regions written to a file meanwhile are turned by it first, so the file gets them where the rotated picture has the faces. A face's crop is not cut again: it shows the face as it was found.