Skip to main content

Missing photos implementation

Overview​

The missing photos feature in LibrePhotos handles cases where photo files become unavailable on the file system while their metadata remains in the database. This document explains the architecture, implementation details, and how the system handles missing photos.

Architecture​

Data Models​

File Model​

Located in apps/backend/api/models/file.py, the File model represents individual files on disk:

class File(models.Model):
hash = models.CharField(primary_key=True, max_length=64)
path = models.TextField(blank=True, default="", unique=True)
type = models.PositiveIntegerField(choices=FILE_TYPES)
missing = models.BooleanField(default=False) # Tracks if file is missing
embedded_media = models.ManyToManyField("self", symmetrical=False)

Key fields:

  • hash: MD5 hash of file content + user ID (primary key)
  • path: Full file system path. It carries unique=True, which is load-bearing here: File.create looks a file up by path and reuses the existing row instead of creating a duplicate when a file reappears.
  • missing: Boolean flag indicating if the file cannot be found
  • type: File type (IMAGE, VIDEO, METADATA_FILE, RAW_FILE, UNKNOWN)

Photo Model​

Located in apps/backend/api/models/photo.py, the Photo model has relationships to files:

class Photo(models.Model):
# UUID primary key - enables flexible asset management
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

# Content hash for deduplication (MD5 of file content + user ID)
image_hash = models.CharField(max_length=64, db_index=True)

files = models.ManyToManyField(File) # All associated files
main_file = models.ForeignKey(
File,
related_name="main_photo",
on_delete=models.SET_NULL,
blank=False,
null=True,
)
# ... other fields

The primary key is the UUID id, not image_hash. image_hash is an indexed but non-unique CharField: the database declares no unique=True, unique_together, or UniqueConstraint on it. Uniqueness per user is a property of how the hash is built (MD5 of content + the user's id), not a constraint the database enforces. Always look photos up as Photo.objects.filter(image_hash=hash, owner=user) — never Photo.objects.get(pk=image_hash). A Photo's image_hash is not always its main_file.hash: File.path is unique, so two users whose scan directories overlap share one File row for a file both scan, hashed with the id of whoever scanned it first, and the scan gives each user's photo hash_for_owner(main_file.hash, user.id) (apps/backend/api/models/file.py). Compare a photo with its file by content_hash() (the MD5 part) only. Up to 1.3.0 the second user's photo took the first user's hash; migration 0175_salt_image_hashes_per_owner re-salts those and copies their thumbnails and face crops to the new names (#1957).

A photo is considered missing when:

  • files=None (no associated files), OR
  • main_file=None (no primary file reference), OR
  • its main_file is flagged missing and only sidecars (METADATA_FILE) are left in files

Query for missing photos, PhotoQuerySet.missing() in apps/backend/api/models/photo.py:

missing_photos = Photo.objects.owned_by(user).missing()

Both delete_missing_photos and the stats count use it, so the badge counts exactly what Remove missing photos removes. It tests the files with NOT EXISTS subqueries rather than a join, so each photo comes back once.

New in 1.7.0 Up to 1.6.0 the query was Q(files=None) | Q(main_file=None). A photo with a sidecar left beside its gone main file matched neither, so the first Remove missing photos only deleted the missing File rows, which set main_file to NULL, and the photo went on the second run.

Detection Mechanism​

_check_files() Method​

The Photo._check_files() method in apps/backend/api/models/photo.py is the core detection mechanism:

def _check_files(self):
for file in self.files.all():
if not file.path or not os.path.exists(file.path):
self.files.remove(file) # Remove from photo's file list
file.missing = True # Mark file as missing
file.save()
self.save()

This method:

  1. Iterates through all files associated with the photo
  2. Checks if the file path exists on the file system
  3. If missing, removes the file from the photo and sets file.missing = True
  4. Saves changes to the database

Note that it removes a vanished file from photo.files. When the vanished file is the main file, stand_in_for_main_file (apps/backend/api/photos/files.py) makes the best file still on disk the main file (select_main_file: an image, then a video, then a RAW), and sets video to match. Sidecars never stand in: a photo with nothing but sidecars left keeps main_file pointing at the vanished file, which is what makes it missing, and lets a reappearing file be relinked (see Relinking Process). New in 1.7.0 Up to 1.6.0 main_file was always left on the vanished file, so a RAW+JPEG photo whose JPEG was deleted lost its main file when the missing File rows were deleted, and the next Remove missing photos removed it with its RAW still on disk.

Stand-in for a gone main file​

New in 1.7.0 stand_in_for_main_file(photo) returns whether the main file changed; its save bumps last_modified, so detach_missing_files only saves last_modified itself when no stand-in was made. Details that matter:

  • The gone main file is read again (File.objects.filter(pk=photo.main_file_id, missing=True)): the caller may hold the File instance from before it was flagged.
  • The candidates come from a query (photo.files.exclude(type=METADATA_FILE).exclude(missing=True)), not photo.files.all(): the scan prefetches files, and the prefetched list still holds what was just removed.
  • Not released yet (comes after 1.7.0) A file that is the main file of another of the owner's photos never stands in (free_for_main): one file is the main file of at most one photo of a user (One photo per file).
  • The photo's edit follows the new main file (renditions.follow_main_file, apps/backend/api/editing/renditions.py), as rekey_replaced_file does for a file replaced in place. An edit is rendered from photo.main_file, so an image or RAW stand-in renders the edit again from it (render_again: a new version, a new preview and thumbnails, the rendition queued). A video cannot be edited, so a video stand-in forgets the edit (forget_edit: the default recipe, no history, the edit files removed once it commits, unless another photo with the same hash shows an edit). When the edit was shown and could not be rendered, or was forgotten, the thumbnails are made again from the new main file.

Every path that unlinks a gone file runs it:

  • detach_missing_files, used by the missing-file check (scan_missing_photos) and by the removal of reported paths (apps/backend/api/directory_watcher/removed_paths.py).
  • detach_deleted_files (apps/backend/nextcloud/directory_watcher.py), for the files the Nextcloud server no longer lists. It flags the file missing before it unlinks it from each photo, because the stand-in only replaces a main file that is flagged.
  • stand_in_for_gone_main_files(photos), for photos whose main file was flagged by a scan from before 1.7.0 and so is already out of files. It only visits the photos whose main file is missing and that still have a non-sidecar file that is not, one EXISTS subquery, so a library without such photos costs one query. scan_missing_photos runs it after detaching what the check found, and delete_missing_photos runs it before it picks the photos to remove.

When the main file comes back, the scan adopts it into the photo again (_adopt_files_into_photo in apps/backend/api/directory_watcher/file_handlers.py) and makes it the main file by FILE_TYPE_PRIORITY. That sets video from the new main file as well, so a Live Photo whose video stood in for its HEIC is a photo again, and the edit follows it the same way.

PhotoQuerySet.missing() tests the files with NOT EXISTS subqueries rather than joins, so each photo comes back once and Postgres hashes nothing in shared memory (#2868).

When is this called?

  • Only during the scan_missing_photos job (apps/backend/api/directory_watcher/scan_jobs.py). This is the sole production call site.

The inverse — clearing the missing flag when a file reappears — is handled independently by File.create in apps/backend/api/models/file.py, not by _check_files().

Jobs​

Scan Missing Photos Job​

Type: JOB_SCAN_MISSING_PHOTOS (job type 14)

Function: scan_missing_photos(user, job_id) in apps/backend/api/directory_watcher/scan_jobs.py

Purpose: Checks all photos owned by a user to detect missing files

Implementation:

def scan_missing_photos(user, job_id: UUID):
lrj = LongRunningJob.get_or_create_job(
user=user,
job_type=LongRunningJob.JOB_SCAN_MISSING_PHOTOS,
job_id=job_id,
)
try:
existing_photos = Photo.objects.filter(owner=user.id).order_by("image_hash")

paginator = Paginator(existing_photos, 5000)
lrj.update_progress(current=0, target=paginator.num_pages)
for page in range(1, paginator.num_pages + 1):
# Allow the job to be cancelled from the UI between pages
if is_job_cancelled(job_id):
logger.info("Scan missing photos job cancelled")
return
for existing_photo in paginator.page(page).object_list:
existing_photo._check_files()

update_scan_counter(job_id)
except Exception as e:
logger.exception("An error occurred: ")
lrj.fail(error=e)

Key features:

  • Processes photos in batches of 5,000 to manage memory.
  • Obtains the job via LongRunningJob.get_or_create_job() so an already-queued job row is reused and started rather than duplicated (job_id is unique).
  • Reports progress via lrj.update_progress(current, target), which persists the counters for UI feedback.
  • Polls is_job_cancelled(job_id) (apps/backend/api/directory_watcher/utils.py) once per page, so the job can be cancelled from the UI mid-run.
  • Any exception marks the job failed via lrj.fail(error=e).
  • Automatically triggered after full scans if not scanning specific files.
  • New in 1.7.0 After detaching, gives every photo whose main file is gone but which still has a file on disk a stand-in (stand_in_for_gone_main_files), including photos an older scan flagged.
  • Not released yet (comes after 1.7.0) Watches the mounts while it runs (MountWatch in apps/backend/api/directory_watcher/mount_watch.py). It reads the mounts at or below each library root (library_roots, resolved with realpath so a symlinked root finds its mounts, and spelled back as the root is stored). On Linux read_mount_table parses /proc/self/mountinfo: the mount point, major:minor, the file system type and the source after the - separator. Elsewhere it takes os.path.ismount and st_dev of the roots, their direct folders (listed once per job) and the remembered mount points; mapped drives and UNC shares on Windows are library roots themselves. The mounts seen before are the user's LibraryMount rows (migration 0264: owner, path, device, fs type, source, seen_at; unique per owner and path, written only through LibraryMount.objects.owned_by(user), so no User.save() can clobber them) plus those mounted when the job starts. MountWatch.check holds back a mount point seen before that is not mounted now; one whose identity changed (same_share: the same fs type and device, and no other source; an anonymous 0:NN device number can be reused, and a NAS can export its empty mount-point folder under the same source, so neither the device nor the source alone is trusted) until the tally finds more than half of the files known below it on the mount point's current device (known: files of photos added before LibraryMount.seen_at, the last time the mount was confirmed, left out the files below a nested mount, which are on that mount's own device; saw_on_disk(path, photo.added_on) counts them per device), which accepts the new identity; files imported from the mount-point folder while the share was down, or strays at known photos' paths, do not reach a majority. A mount point with no known file below it takes its new identity at once: no photo there can be flagged on a stale identity, and holding it would keep it held forever. A held identity change is reported with the old and the new identity: a normal scan with the share mounted recognises the same share, and a scan with the limit at 100% accepts another disk (also the only way when most known photos were deleted while the share was down). Remove missing photos and the watcher never learn an identity; and one that fails library_root_problem (cannot be read, or empty while photos are in it). A Docker bind mount of the host's mount-point folder, made while the host share was down, is in the table, but on another device and fs type, so it is held back. As a fallback for mounts the table does not show, the tally records the device (st_dev) of each folder in which it found a file on disk (saw_on_disk); a missing file whose folder had a device then, and whose nearest existing ancestor has another one now, is held back with that ancestor. Files are asked with files.on_disk (os.stat): only ENOENT and ENOTDIR mean gone; any other OSError (EIO, ESTALE, ENOTCONN, EACCES, and on Windows ERROR_BAD_NETPATH/ERROR_BAD_NET_NAME, winerror 53 and 67, which Python maps to ENOENT) leaves the file unknown, so it is never flagged (missing_files(..., unreadable=...), MountWatch.saw_unreadable). After the tally, leave_out_unmounted drops the held-back files from the tally, remember stores the mounts (those mounted now and trusted, with seen_at now, plus the remembered ones that are held back or gone, with their old identity and seen_at, unless the limit is 100%, so a scan with the limit off forgets a share that is gone), then too_many_missing decides as before (the floor of 100 photos and the limit). The first check after the update has nothing remembered, so a share already down behind a placeholder is learned as it is; only too_many_missing guards that one scan (the user guide asks to have every share mounted). _detach_missing asks missing_files(photo, among=...) again for each photo of a batch of 1000, then MountWatch.check for the batch, and detaches only what is not held back: the mount check comes after the file checks, so a share that drops while they run is seen. Each folder held back, each folder with files that could not be read, and each further library folder that unavailable_folders left out is listed in the job's errors (record_held_back, counted like a skipped directory, so the job is a partial failure, not a failed one); the user who started the job sees them on its page. In the desktop program on any drive (LIBRARY_ON_ANY_DRIVE), MountWatch.check also looks up the connected drives once (UnpluggedDrives in apps/backend/api/photos/allowed_folders.py), and holder holds back every file on a drive that is not among them, inside the library or not: a user who chose another folder and kept the photos of the old one has photos outside all library roots, whose mounts are neither read nor remembered. The limit at 100% turns this off too. Up to 1.7.0 the root was only checked at the start, so a share that dropped mid-tally, or a share mounted below the scan directory, got its files detached. Model: verification/scanning/ScanMissing.tla.

Delete Missing Photos Job​

Type: JOB_DELETE_MISSING_PHOTOS (job type 5)

Function: delete_missing_photos(user, job_id) in apps/backend/api/albums/auto_albums.py

Purpose: Permanently removes missing photos and their associated data from the database

Implementation:

def delete_missing_photos(user, job_id):
lrj = LongRunningJob.get_or_create_job(
user=user,
job_type=LongRunningJob.JOB_DELETE_MISSING_PHOTOS,
job_id=job_id,
)
try:
stand_in_for_gone_main_files(Photo.objects.owned_by(user))

missing_pks = list(
Photo.objects.owned_by(user).missing().values_list("pk", flat=True)
)
target = len(missing_pks)
lrj.update_progress(current=0, target=target)

# Delete in batches to bound peak memory. Album through-rows and Face
# rows are removed by DB cascade on Photo.delete(); only AlbumThing
# needs its photo_count / cover photos refreshed afterwards, because
# cascade bypasses its m2m_changed receiver.
affected_album_thing_ids: set[int] = set()
for start in range(0, target, _DELETE_MISSING_BATCH_SIZE):
batch_pks = missing_pks[start : start + _DELETE_MISSING_BATCH_SIZE]
batch_qs = Photo.objects.filter(pk__in=batch_pks)
affected_album_thing_ids.update(
AlbumThing.objects.filter(photos__in=batch_qs).values_list(
"id", flat=True
)
)
batch_qs.delete()
lrj.update_progress(current=start + len(batch_pks), target=target)

for album_thing in AlbumThing.objects.filter(id__in=affected_album_thing_ids):
album_thing.photo_count = album_thing.photos.filter(hidden=False).count()
album_thing.save(update_fields=["photo_count"])
album_thing.update_default_cover_photo()

owner_part = str(user.id)
File.objects.annotate(hash_length=Length("hash")).filter(
hash__endswith=owner_part,
hash_length=MD5_HEX_LENGTH + len(owner_part),
missing=True,
).delete()

lrj.complete()
except Exception as e:
logger.exception("An error occurred")
lrj.fail(error=e)

Notes on the implementation:

  • The missing-photo query is owned_by(user).missing(), so every branch of it is scoped to the requesting user.
  • A gone main file first gets a stand-in from the files still on disk (see Stand-in for a gone main file), so a photo flagged by an older scan is kept when its RAW is still there.
  • Photos are deleted in batches of _DELETE_MISSING_BATCH_SIZE (200) to bound peak memory.
  • Not released yet (comes after 1.7.0) Each batch is one transaction: it locks the batch's photo rows in pk order (select_for_update), asks owned_by(user).missing() again for the locked rows, and deletes only those. A scan that relinked a photo after the job listed it keeps it; up to 1.7.0 the batch was deleted by pk, so that photo was deleted and its file came back as a new photo on the next scan. On PostgreSQL the scan's link to the photo waits for the lock (its foreign key check takes a key-share lock on the photo row), and the second .missing() is a statement of its own, so it sees what the scan committed. On SQLite the transaction holds the write lock, so it never interleaves with a scan's write.
  • Not released yet (comes after 1.7.0) Before each batch's transaction, _gone_from_disk reads the photos still flagged missing, asks the disk for each one's main file and its exact copies (_back_on_disk, with files.on_disk: a photo whose main file or a copy of it is back is kept for the next scan to relink, and one whose file cannot be read is kept and reported), then MountWatch.check, and leaves out the photos whose main file is under a mount point that is held back. No disk is read inside the transaction: on SQLite it holds the write lock, and a stat on a hard NFS mount that dropped can block for minutes. The transaction asks only the database again (_lock_still_missing), so a photo that a scan relinked after the disk checks is kept. The photo_count and cover of the affected Thing albums and the Tag counts are refreshed in a finally, so a batch that fails leaves no stale counts for the batches already deleted. The final cleanup deletes only the missing File rows that are no main file of a photo left, so a photo held back keeps its main file. Folders held back are listed in the job's errors as <folder> looks unmounted; nothing was removed there, and the job completes. Up to 1.7.0 the job trusted the missing flag, so a photo flagged while its share was down, or whose file came back, was deleted.
  • Not released yet (comes after 1.7.0) POST /api/scan-files/ with removed_paths (removed_paths.plan_removal) asks the disk for each named file with files.on_disk, then MountWatch.check; a named file that cannot be read, or one under a mount point that is held back, makes the answer a 409 (library_unavailable) and nothing changes. The plan runs before the view's transaction, and detach_removed detaches only the files still attached to their photo when it runs.
  • The file cleanup filter uses str(user.id), because File.hash is md5 + str(user.id). Passing the User instance would stringify to the username and match nothing. The hash must also be exactly MD5_HEX_LENGTH (32) characters plus the id: New in 1.7.0 up to 1.6.0 the suffix match alone also deleted the missing File rows of every user whose id ends in the requester's (those of user 17 on a run of user 7).

What gets deleted:

  • Photo records from database
  • File records marked as missing
  • Associations with date-based albums
  • Associations with thing-based albums
  • Associations with place-based albums
  • Associations with user-created albums
  • Face detections linked to the photos
  • Thumbnail files on disk that no remaining photo uses

Album associations and face detections are removed by database cascade on Photo.delete() (Face.photo is on_delete=CASCADE), not by explicit per-photo loops. AlbumThing is the one exception: its photo_count and cover photos are maintained by an m2m_changed receiver that cascade bypasses, so affected AlbumThing ids are snapshotted per batch and refreshed afterwards.

Thumbnail file cleanup: Thumbnail rows are cascade-deleted with the Photo, and a post_delete receiver in apps/backend/api/models/thumbnail.py then removes their files from MEDIA_ROOT ($BASE_DATA/protected_media/):

  • thumbnails_big/ (.webp)
  • square_thumbnails/ (.webp, or .mp4 for video previews)
  • square_thumbnails_small/ (.webp, or .mp4 for video previews)

Thumbnail files are named by image_hash, not owned by one row, so the receiver only removes true orphans:

  • The deletion is deferred with transaction.on_commit, so a rolled-back delete keeps its files.
  • Inside that callback, the files are kept if any remaining Thumbnail row still points at them, or any Photo still has that image_hash (for example a photo that is still being scanned and has no Thumbnail row yet).
  • Otherwise delete_thumbnail_files(image_hash) removes them. It logs and skips an OSError (including PermissionError) per file, so a file that cannot be removed never fails the job.

The same receiver runs for every Thumbnail delete, including the daily removed-photo cleanup (api.photos.retention.cleanup_deleted_photos), which deletes the rows of photos removed more than 30 days ago. It never touches photos in the trash. New in 1.7.0 The 30 days count from Photo.removed_at, set by remove_photo; up to 1.6.0 they counted from last_modified, so any later write to the row restarted them. New in 1.4.0 The trash retention is a separate daily task (api.photos.retention.empty_expired_trash): when an admin sets TRASH_RETENTION_DAYS above 0, it deletes photos trashed longer ago than that, files included, through the same remove_photos as Delete permanently.

Not released yet (comes after 1.7.0) The retention passes its cutoff to remove_photos(..., trashed_before=cutoff), and remove_photo adds trashed_at <= cutoff to its conditional UPDATE. A photo the owner restored and moved to the trash again after the retention listed it has a later trashed_at, so it stays in the trash; up to 1.7.0 only in_trashcan was checked, and it was deleted at once.

Not released yet (comes after 1.7.0) trash_photos stamps trashed_at with the database's clock (Now()), and the trash listing (GET /api/days/?in_trashcan=true) answers snapshot_at, database_now() read just before the days. A select-all Delete permanently sends it back as trashed_before with expected_count: DeletePhotos counts only the query's photos with trashed_at <= trashed_before, answers 409 selection_changed (with the current count and a new snapshot_at) when the number differs, and passes the cutoff to remove_photos, so a photo trashed, or restored and trashed again, after the listing is left in the trash. Both sides use the database's clock, so the app servers' clocks do not matter. The model is verification/trash/PurgeSelectAll.tla.

Permanent deletion​

remove_photo (api/photos/files.py) first writes the journal of the files it may rename, then runs one transaction: it claims the journal rows, marks the photo removed, takes it out of its stacks and duplicate groups, unlinks its files and renames each file only it used to the staged path of its journal row, <path>.<32 hex>.librephotos-deleting. The renamed files and the journal rows are deleted once the transaction commits.

Not released yet (comes after 1.7.0) Changes in 1.8.0:

  • New primary. When the removed photo was the primary photo of a stack that keeps two photos or more, PhotoStack.auto_select_primary picks a new one among the members that are not removed and not in the trash, and among the ones in the trash only when no other is left. The timeline shows a stack only through its primary, so up to 1.7.0 the rest of the stack vanished from it.
  • Lock order. The photo's journal rows, its stack and duplicate group rows (select_for_update, by pk) and then its File rows are locked before the count of what is left in a group and the check whether another photo still uses a file. The order is always journal, photo, groups, files, so two removals never wait on each other in a circle. A photo in no stack takes no stack lock. Under PostgreSQL READ COMMITTED, the statement after a lock sees what the other removal committed, so two removals of the last photos of a stack dissolve it, and two removals of the photos sharing a file delete the file. SQLite takes the write lock when the transaction begins, so removals already ran one after another there.
  • Journal of staged files. A process killed during a removal leaves renamed files behind: before the commit the rows roll back but the file stays renamed, after it the delete never runs. Before its transaction, remove_photo commits one StagedDeletion row (migration 0261) per file of the photo: the original path and the staged path exactly as it renames them, the photo and file ids, a token for the attempt and staged_at, set by the database clock. Inside the transaction _claim_journal locks those rows and raises StagingNotJournaledError, which leaves the photo in the trash, when one is gone; a file that joined the photo after the journal was written raises it too, and so would a file linked to the photo twice, which the database rules out. A rollback puts the files back, never over a file that took the path meanwhile (that staged file keeps its row), and deletes the rows whose staged file is gone; a commit deletes the files, then the rows. No scan reads a staged file: the library walk (left_out in api/directory_watcher/utils.py), is_valid_media and get_or_create_file (which raises StagedForDeletionError) all refuse a name ending in .librephotos-deleting (is_staged_for_deletion in api/photos/paths.py), so uploads, the watcher, the Nextcloud import and single-file rescans skip it too.
  • Sweep. sweep_staged_deletions runs every 10 minutes in the workers (start_cleaning_service schedules it) and settles only rows whose 10-minute lease (STAGING_LEASE, from staged_at) has run out, one row per transaction: it locks the row with select_for_update(skip_locked=True), so a removal that is still running keeps its rows, then locks every File row with the journaled hash, the original path or the staged path, and reads the FileCopy rows of the hash or either path (_paths_in_use). A row at the staged path (a scan of an older version indexed the staged file) keeps the file where it is. A row at the original path means the removal rolled back, and the staged file goes back to its path, or next to it as <name> (restored).<ext> (then (restored 2) and so on, skipping names a file or a File/FileCopy row holds, is_taken) when a file took the path meanwhile. Rows with the same hash only at other paths are exact copies indexed after a committed delete: when one of them is on disk the staged file is deleted, so the deleted photo does not come back; when all of them are gone it is restored, since it is the last copy. A file nothing references is deleted: the removal committed. Then the journal row is deleted; a rename or delete that fails keeps the row for the next run. The paths come from the row, so nothing walks the library and nested library roots of different users settle like any other. On PostgreSQL the File row lock waits for a removal that deleted the row and has not ended, and a removal's own lock on the row waits for the sweep, so the sweep never puts back a file whose removal commits after it looked. On SQLite every sweep transaction holds the write lock, so it runs between removals.
  • Drive not connected. In the desktop program remove_photos asks LibraryDrives.away (see Library places) for every file of a photo first, and _stage_for_deletion asks again when a file is not there. A photo whose drive is away raises DriveAwayError: the removal rolls back, the photo stays in the trash and counts in Removal.drive_away (drive_away_count in the job result and in the answer of DELETE /api/photosedit/delete/). When the drive is pulled out between two renames, the renamed file cannot be put back. Its journal row stays, and the sweep waits until LibraryDrives.away answers that the drive is there, and puts the file back. On a drive that is not remembered, the files are compared with what LibrePhotos knows before they are deleted. The model is verification/trash/TrashDriveAway.tla.
  • Restore. In one transaction with the photos' update, restore_photos locks the stacks of the restored photos (select_for_update, after the photo rows, the order a removal takes them in) and picks a new primary (auto_select_primary) for each stack of the restored photos whose primary is still in the trash or removed, so restoring another photo of the stack brings the stack back to the timeline.

verification/trash/ holds the models of these steps.

API Endpoints​

Delete Missing Photos​

Endpoint: POST /api/deletemissingphotos

Implementation: DeleteMissingPhotosView in apps/backend/api/views/scan_triggers.py

class DeleteMissingPhotosView(APIView):
def post(self, request, format=None):
return self._delete_missing_photos(request, format)

@extend_schema(
deprecated=True,
description="Use POST method instead",
)
def get(self, request, format=None):
return self._delete_missing_photos(request, format)

def _delete_missing_photos(self, request, format=None):
try:
job_id = uuid.uuid4()
AsyncTask(delete_missing_photos, request.user, job_id).run()
return Response({"status": True, "job_id": job_id})
except BaseException:
logger.exception("An Error occurred")
return Response({"status": False})

Response:

{
"status": true,
"job_id": "550e8400-e29b-41d4-a716-446655440000"
}

The deletion runs as a background task (api.jobs.queue), so the 200 is returned as soon as the task is queued — not when the sweep finishes. Track progress on the LongRunningJob identified by the returned job_id and poll it rather than treating the response as completion.

Note: Also supports GET (deprecated) for backward compatibility; both methods delegate to the same _delete_missing_photos helper.

Photo Statistics​

Missing photo count is included in the user statistics API response.

Calculation: get_count_stats(user) in apps/backend/api/dataviz/stats.py

num_missing_photos = Photo.objects.owned_by(user).missing().count()

Returned in stats response as:

{
"num_photos": 1234,
"num_missing_photos": 5,
// ... other stats
}
Note

This count uses the same query as delete_missing_photos, PhotoQuerySet.missing(), so the badge and the run agree. Its subqueries are NOT EXISTS, so a photo with several File rows is counted once.

Hash-Based Relinking​

How It Works​

When files reappear in the scanned directories, LibrePhotos reconnects them to their existing photo metadata rather than creating duplicate photos. A File is identified by a content hash (File.hash is md5(content) + str(user.id), the primary key) and also carries a unique path, so a file that comes back is matched to the record it had before — even if it was renamed or moved within the scanned directories.

Hash Calculation: calculate_hash(user, path) in apps/backend/api/models/file.py

def calculate_hash(user, path):
hash_md5 = hashlib.md5()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(BUFFER_SIZE), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest() + str(user.id)
# ... error handling

Key points:

  • Hash is MD5 of file content + user ID
  • User ID ensures photos are scoped to individual users in multi-user setups
  • Buffer size of 65536 bytes for optimal performance

Relinking Process​

Relinking during a scan is driven by two independent pieces of the two-phase scan in apps/backend/api/directory_watcher/, not by a Photo.image_hash lookup:

  1. File.create (apps/backend/api/models/file.py) looks a record up by its unique path. If the existing record is flagged missing while the file is back on disk, it clears the flag:

    existing = File.objects.filter(path=path).first()
    if existing:
    if existing.missing and os.path.exists(path):
    existing.missing = False
    existing.save(update_fields=["missing"])
    return existing
  2. group_files_into_photo (apps/backend/api/directory_watcher/file_handlers.py) re-adopts the original Photo instead of creating a new one:

    existing_photo = Photo.objects.filter(
    Q(owner=user) & (Q(files__in=files) | Q(main_file__in=files))
    ).first()

    If a match is found, any files not already attached are added to it, and main_file is upgraded when a higher-priority variant appeared (per FILE_TYPE_PRIORITY). Only when no match exists is a new Photo created.

The Q(main_file__in=files) arm is the load-bearing part. A photo left with only sidecars keeps main_file pointing at its missing file, so matching on main_file is what stops a reappearing file from spawning a duplicate Photo with the same image_hash. A photo whose RAW stood in for a missing JPEG is matched through the RAW in files, and the reappearing JPEG takes main_file back by priority.

Note

create_new_image (apps/backend/api/directory_watcher/file_handlers.py) is the legacy single-file path, kept for uploads and the XMP-sidecar branch. It performs no image_hash lookup, no removed/in_trashcan restoration, and no _check_files() call — none of that relinking logic lives there any more. The behaviour above is exercised by apps/backend/api/tests/test_missing_file_reappearance.py.

Frontend Integration​

Photo Serializer​

File: apps/backend/api/serializers/photos.py

get_image_path builds the list of file paths for a photo:

def get_image_path(self, obj) -> list[str]:
try:
paths = []
for file in obj.files.all():
paths.append(file.path)
return paths
except Exception:
return ["Missing"]

Photo.files is a ManyToManyField(File), and _check_files() removes vanished files from that relation. A photo whose files have all gone missing therefore serializes image_path as an empty list []. The ["Missing"] value is only an error fallback for an unexpected exception — it is not the normal missing-photo signal.

The frontend detects the missing case by an empty array. VersionComponent.tsx and routes/_protected/photo.$id.tsx guard on photoDetail.image_path && photoDetail.image_path.length > 0, and MediaDisplay.tsx guards on !photoDetails?.image_path || !Array.isArray(photoDetails.image_path).

Video Error Handling​

File: apps/frontend/src/components/lightbox/VideoPlayer.tsx

MediaDisplay builds the media URL (/media/photos/<hash>.mp4 for videos, /media/embedded_media/<hash> for embedded media) and hands it to VideoPlayer. When the backend cannot serve the file, the <video> element's onError handler sets an error state and VideoPlayer renders a red alert over the still-available thumbnail poster, with a Retry button:

if (error) {
return (
<div style={{ backgroundImage: posterUrl ? `url(${posterUrl})` : undefined, /* ... */ }}>
<Alert color="red" title="Video Unavailable">
<Text size="sm">The video file could not be loaded. It may be missing, unsupported, or unavailable.</Text>
<Button variant="light" color="red" size="xs" mt="sm" onClick={handleRetry}>Retry</Button>
</Alert>
</div>
);
}

Settings UI​

The user-facing entry point for deleting missing photos is on the Library settings page (apps/frontend/src/components/settings/Library.tsx, reached via the /library route):

  • A red badge renders only when countStats.num_missing_photos > 0 (from useFetchCountStatsQuery, i.e. the same num_missing_photos stat described in Photo Statistics). The badge label comes from the settings.missingphotos translation key ("Missing Photos"), and it sits inside a Mantine HoverCard whose dropdown (settings.missingphotosdescription) explains the feature.
  • Clicking the badge opens a Modal titled settings.missingphotosbutton ("Remove missing photos") with Cancel / Confirm. Confirm calls deleteMissingPhotos.mutate() and then closes the modal.
  • The mutation lives in apps/frontend/src/api_client/photos/hooks/useDeleteMissingPhotosMutation.ts. It POSTs to /deletemissingphotos (the /api prefix comes from the fetch client base URL), validates the { status, job_id } response with zod, and on success invalidates the auto-albums, date-albums, recently-added, count-stats, and photo-month-count query keys — worth knowing which cached views go stale after a delete.
  • The same action is also exposed through the Spotlight command palette (apps/frontend/src/components/spotlight/useSpotlightActions.ts, action id action-delete-missing, label key spotlight.actions.deleteMissing). It fires the same mutation directly with no confirmation modal and is disabled when the worker queue cannot accept a job.

The English strings settings.missingphotos, settings.missingphotosbutton, and settings.missingphotosdescription live in apps/frontend/src/locales/en/translation.json; other locales come from Weblate.

Future Implementation​

Real-Time File System Monitoring​

Goal: Eliminate most missing photo cases through proactive file tracking

Planned features:

  1. File System Watchers

    • Implement inotify (Linux), FSEvents (macOS), or watchdog library
    • Monitor scanned directories for file changes in real-time
    • Trigger immediate updates instead of waiting for manual scans
  2. Move/Rename Detection

    • Detect when files are moved within scanned directories
    • Automatically update file paths in database
    • Preserve all metadata, ratings, and associations
  3. Immediate Relinking

    • Hash-based matching happens immediately when files appear
    • No manual scan required
    • Significantly reduced "missing photo" window
  4. Benefits

    • Near-instant UI updates when files change
    • Reduced database queries (no periodic scanning)
    • Better user experience with fewer missing photos
    • Lower system resource usage

Implementation Considerations​

  • Performance impact of continuous monitoring
  • Handling large directory trees efficiently
  • Network storage compatibility (NAS, SMB, NFS)
  • Docker container file system event propagation
  • Graceful degradation if monitoring unavailable

Known Issues and TODOs​

Current TODOs​

  1. Move delete_missing_photos function (autoalbum.py)
    • The function carries a # To-Do: This does not belong here comment.
    • It should be moved to a more appropriate module (e.g. photo_operations.py or similar).

Edge Cases​

  1. Symbolic links: May not be handled correctly in all cases
  2. Network storage timeouts: Slow network storage may cause false positives
  3. Permissions: Permission changes could make files appear missing
  4. Race conditions: Files changed during scan may cause inconsistencies

Code Organization​

Key Files​

  • Models:

    • apps/backend/api/models/file.py — File model (missing flag, unique path, calculate_hash)
    • apps/backend/api/models/photo.py — Photo model and _check_files() method
    • apps/backend/api/models/long_running_job.py — job type definitions
    • apps/backend/api/models/thumbnail.py — thumbnail records (cascade-deleted with the photo) and the post_delete receiver that removes orphaned thumbnail files
  • Business Logic:

    • apps/backend/api/directory_watcher/ — scanning and relinking (a package implementing the two-phase scan):
      • scan_jobs.py — scan_photos, scan_missing_photos
      • file_handlers.py — Phase 1 create_file_record, Phase 2 group_files_into_photo, legacy create_new_image
      • file_grouping.py — grouping key, select_main_file, FILE_TYPE_PRIORITY
      • processing_jobs.py, repair_jobs.py, utils.py
      • __init__.py re-exports the public names, so existing from api.directory_watcher import ... imports still work
    • apps/backend/api/albums/auto_albums.py — delete_missing_photos function
  • API Views:

    • apps/backend/api/views/scan_triggers.py — delete missing photos endpoint
    • apps/backend/api/views/photos.py — photo operations
  • Statistics:

    • apps/backend/api/dataviz/stats.py — count calculations including missing photos
  • Serializers:

    • apps/backend/api/serializers/photos.py — photo serialization (get_image_path)
  • Frontend:

    • apps/frontend/src/components/settings/Library.tsx — missing-photos badge and confirmation modal
    • apps/frontend/src/api_client/photos/hooks/useDeleteMissingPhotosMutation.ts — POST /deletemissingphotos and cache invalidation
    • apps/frontend/src/components/spotlight/useSpotlightActions.ts — Spotlight "Delete Missing Photos" action
    • apps/frontend/src/components/lightbox/VideoPlayer.tsx — video load-error UI
  • Tests:

    • apps/backend/api/tests/test_delete_missing_photos.py
    • apps/backend/api/tests/test_missing_file_reappearance.py

Testing Considerations​

When testing missing photos functionality:

  1. Setup: Create photos with valid files
  2. Trigger: Remove files from file system (outside LibrePhotos)
  3. Scan: Run scan_missing_photos job
  4. Verify: Check that photos marked as missing
  5. Restore: Add files back and rescan
  6. Verify relinking: Ensure photos automatically relink
  7. Delete: Test permanent deletion with delete_missing_photos

Automated tests​

The behaviour above is covered by two test modules; extend them when changing this code:

  • apps/backend/api/tests/test_delete_missing_photos.py — the delete_missing_photos sweep: per-user scoping of the Q(owner=user) & (Q(files=None) | Q(main_file=None)) filter, the hash__endswith=str(user.id) missing-file filter, LongRunningJob progress reporting, batched processing, cascade cleanup of album through-rows, the single AlbumThing.photo_count / cover-photo refresh, and the AsyncTask wrap on the view.
  • apps/backend/api/tests/test_missing_file_reappearance.py — clearing File.missing when a file returns to disk, and re-adoption of a reappearing file by its original Photo (no duplicate Photo created).

Run them from the backend app directory (normally inside the backend container — see Development Install):

cd apps/backend
python manage.py test api.tests.test_delete_missing_photos api.tests.test_missing_file_reappearance