State and sync
There's one database per install and one library folder. Published data comes in through one-way paths, and a desktop app linked to a server keeps the two installs in step through the sync paths below. This page lists each path, what it may change, and what it guarantees, including where the guarantees stop. Paths are relative to the repository root. Data model describes the tables.
Whose data is it
| Kind | Where | Owner | If lost |
|---|---|---|---|
| Original photos, RAWs, videos, XMP sidecars | The library (DATA_DIR), drives, trip folders | User | Gone. Back them up. |
.lifer recovery files | .lifer/ folders in the library and trip folders | User (written by Lifer) | Recreated as the library changes |
| User records | Database: captures, user_species, albums, trips, overlays, settings, accounts | User | Partly rebuildable from the library (below) |
| Catalog | Database: species, regions, checklists, vectors | Published | Downloaded again |
| Previews of the user's photos | APP_DATA_DIR/display, medium, thumb, video-preview | Cache | Regenerated from the originals when missing (apps/api/src/photos/routes.ts) |
| Reference photos, models, map, GPU runtime, downloads | APP_DATA_DIR/reference-*, models/, maps/, gpu-runtime/, catalog-downloads/ | Published | Downloaded again |
| Desktop database files and their password | app-data/postgres-data, app-data/postgres-password | User | Treat as the database. The password file is needed to open the data. |
The rule that keeps these apart: published data may be replaced at any time; user data is never written by a download. Catalog tables hold catalog rows only, and everything a user adds or changes about the catalog lives in separate per-user tables that no update path writes to (ADR 0005). The one place user data moves during an update is a species merge, which re-points it rather than discarding it (below).
First start: the catalog seed
A new database has no species. One code path fills it everywhere: seedCatalogIfEmpty in apps/api/src/species/catalogSeedUpdate.ts, started without waiting at the end of apps/api/src/index.ts. If species has no rows, it loads the bundled seed (the image's catalog-seed/, or the desktop installer's resources/catalog-seed/, which the desktop app passes in LIFER_BUNDLED_CATALOG_SEED_DIR), or downloads one if there's none. The seed is checked against the SHA-256 in catalog-manifest.json. Regions load first, in their own transaction, so onboarding can list countries, then everything else in one transaction. A failure leaves the catalog empty and is retried on the next start; Settings > Offline data can retry too.
The seed goes through the same tolerant load as a catalog update (below), so a migration that drops or adds a column never breaks first launch, and the catalog-seed-load CI job loads the published seed into a freshly migrated database to prove it. A table that is still empty skips the merge: its rows go straight in with FK checks and row triggers off (session_replication_role = replica, when the role may set it), its indexes and unreferenced keys are built after the insert, and it's analyzed. Region outlines are written with lz4 compression where the server supports it. Species search names are rebuilt in the background after the commit (ensureSpeciesSearchNames in species/search.ts); search uses a plain scan until then.
Limits:
- Restoring collection state from the library (
syncCollectionStateOnStartupinapps/api/src/lib/collectionState.ts) runs after the first-boot seed has finished, since it matches species by name. If none of the record's species are in the catalog (the seed failed, say), the restore isn't counted as tried, and the user's next session check (/auth/me) tries again.
Catalog updates
Settings > Offline data > Species catalog runs runCatalogUpdate (catalogSeedUpdate.ts):
- Fetch the manifest from
CATALOG_MANIFEST_URL, download the seed intoAPP_DATA_DIR/catalog-downloads/(resumable and retried with backoff bydownloadResumable, checked against the manifest's SHA-256), delete older downloads. - Apply it in one Postgres transaction, holding the reference-data advisory lock (
packages/core/src/lib/referenceDataLock.ts) so pack installs and vector installs wait:- Each table's data is streamed from the dump into a temporary table, then upserted into the real table on its primary key (
MERGE_TABLES). Nothing is truncated. Columns the install's schema doesn't have yet are dropped with a warning, so an older install can take a newer seed. - Local file paths are never overwritten. A photo the install fetched itself for a withheld species is kept.
- A region whose id changed upstream keeps its local id, matched by name and parent, so references to it survive.
- Checklist rows the seed no longer lists are deleted, only for regions and sea zones the seed covers. User additions are in other tables and aren't touched. A sea zone that disappears takes its catalog rows with it; user additions to a zone that comes back under the same name are moved to the new id.
- Species merges are applied (next section).
- The seed version is written to
install_settingslast, inside the transaction.
- Each table's data is streamed from the dump into a temporary table, then upserted into the real table on its primary key (
- After the commit: blocklisted photo files are deleted, XMP sidecars of photos moved by a merge are rewritten in the background, and species splits are resolved.
Guarantees and limits:
- All or nothing for the database. Any error, or the user cancelling, rolls back everything including the version. A crash before commit leaves the old catalog; the downloaded seed stays and is reused if its hash still matches.
- Species rows are never deleted by the merge itself, only by an explicit merge record. A species dropped upstream without one stays on the install.
- The seed overwrites catalog columns it carries. Enrichment such as descriptions and credits follows the published value; only the excluded path and withheld-photo columns are protected.
- Steps after the commit aren't transactional. If Lifer stops between the commit and them, the catalog is updated but some sidecars may still name the old species, and a deleted blocklisted photo file may linger. Splits are resolved again after every pack install; sidecars are rewritten at the photo's next change.
- Updating the gallery vectors is a separate step after the catalog, and its failure doesn't undo the catalog update.
Species merges and splits
When the pipeline merges two species, the seed carries species_merges (old id to survivor). applySpeciesMerges (packages/core/src/species/speciesMerges.ts) runs inside the catalog transaction:
- Follows chains of merges to the final survivor, ignoring pairs not present locally.
- Fills the survivor's empty columns from the old species, keeps the old common name as an alias and the old scientific name as a synonym.
- Copies the user's overlays (archived, hidden in a region, checklist additions, tier overrides) to the survivor where it has none.
- Folds the user's
user_speciesrows into one: collected beats seen, earliest first-collected date, best rating, the survivor's cover first. - Moves captures, unpaired RAWs and extra-species links to the survivor.
- Deletes the old species. Because captures and
user_speciesreference species with no cascade, a missed reference makes the delete fail and the whole update rolls back rather than losing user rows.
Splits are different: one species becomes several, and the right one depends on where each photo was taken. resolveSpeciesSplits (apps/api/src/species/speciesSplits.ts) runs after the commit, outside any transaction, because it moves files. A photo moves to a daughter species only when exactly one daughter is on the checklist where it was taken; otherwise it stays and the species card says the name changed. The user can choose to keep a photo on the parent (species_split_kept).
Region packs
A pack is one region's checklists and reference photos for one species group, published as a byte range inside a shard file listed in pack-index.json (ADR 0004).
Install (apps/api/src/offlinePacks/download.ts, apply.ts):
- Installs a newer catalog first, if there is one, and stops if that fails.
- Skips a pack whose
content_versionhasn't changed. - Fetches the pack's byte range into a temp file. Pack URLs must have the same origin as the index (
assertTrustedPackUrl); the response must be a 206 of exactly the requested range; the file must match the index's SHA-256. - Applies it in one transaction per pack: fills species photos and descriptions that are missing, upserts the region's checklist rows and removes those the pack no longer lists (user additions untouched), records the pack in
downloaded_packsand its species inpack_species. Photo files are copied before the rows that point at them. - After the commit, fetches the pack's reference photos from the photo store (below).
Species are matched to the catalog by scientific name and regions by name; a species the catalog lacks is skipped and logged. Cancelling a queue of packs keeps the ones already committed.
Remove (apps/api/src/offlinePacks/remove.ts), one transaction: deletes the pack's checklist rows; for species no other pack lists and no user has a user_species row for, clears their photo and description columns; deletes the pack record. Species rows, user additions and anything in a collection stay. Their photo files are only collected in the transaction and deleted after it commits, so a rollback leaves every file in place. A file some row still points at by then (another species sharing it, or a pack installed since) is kept. A file left behind by a failed delete or a crash before it is logged and harmless: reference photos are named by species id, so a reinstall overwrites it, and a fresh database relinks it (apps/api/src/species/relinkReferenceFiles.ts).
Offload provinces removes some provinces' checklist rows for a pack and keeps its photos; reinstalling the pack restores them. Offload several packs removes each pack in its own transaction, so it's not atomic across the batch.
The photo store and withheld photos
Reference photos are stored once each in shard files, with an index of [shard, offset, length, sha1] per photo (apps/api/src/offlinePacks/photoStore.ts). After a pack install, Lifer works out which photos are missing on disk, merges neighbouring ones into ranges of up to 32 MB, fetches them with retries, checks each photo's SHA-1, and writes each through a .part file and rename into APP_DATA_DIR/reference-*. Database paths are recorded only after the files are on disk. A photo that fails its check is skipped and retried next time; it never fails the pack.
Some catalog photos can't be redistributed under their license, so the pipeline leaves them out and marks the species photo_withheld (ADR 0010). apps/api/src/species/withheldPhotos.ts fetches those from iNaturalist on the install itself, for species on a downloaded pack's checklists: one at a time, two seconds apart, at most 2000 a day, stopping after repeated failures. It runs at startup and after each pack install, and can be turned off (fetch_withheld_photos in install_settings, Settings > Species and import > Species downloads > Download missing reference photos). These photos survive catalog updates and are removed with their pack.
A desktop app linked to a server
apps/api/src/sync/, driven by the desktop shell (apps/desktop/src-tauri/src/sync.rs). Once the window has signed in to a server, the server's page mints an API key with the sync scope (POST /auth/desktop-link) and the shell keeps it in <app data>/app-data/server-link.json with the server's instance id (GET /health, migration 148) and addresses (server_link.rs). The library on this computer keeps running alongside the server window, and its API does the work with that key. Species always go by scientific name; capture and photo ids are shared between the two installs.
The key carries sync, species.read, photos.read and photos.write (DESKTOP_LINK_SCOPES in auth/apiKeyRoutes.ts). photos.write is needed because a push uploads new photos through the ordinary import routes, so a sync key can do whatever a photos.write key can: add, edit, hide and trash the user's photos, plus revoke itself.
Trust model. The instance id the app checks at each address is public (GET /health needs no sign-in), so it picks the right server among the configured addresses but doesn't prove who answers. So POST /auth/desktop-link also returns a linkSecret, an HMAC of the key's id under a key the server keeps in install_settings (sync/linkProof.ts); the shell stores it beside the key. Before sending the key to an address, the app sends a random nonce to GET /api/sync/link/proof?keyId=&nonce= (public, rate limited, 404 for a missing or revoked key) and accepts the address only if the answer is the HMAC of proof:<nonce> under the secret (provesItself in sync/serverLink.ts, proves_itself in server_link.rs). A link without a secret is taken on its instance id. The key is also sent only over https, or over plain http to this computer or the local network: loopback, private and link-local ranges, 100.64.0.0/10 (Tailscale), single-label names and .local, .lan, .home.arpa and .internal names (keyMayGoTo in sync/serverLink.ts, is_secure_origin in security.rs for revokes). Any other plain-http address is skipped. On a home network anyone who can answer at the server's address can still take the key; use https if the network isn't yours. Redirects are refused on both sides, so the key never follows one.
- Packs (
sync/packs.ts): the packs only this computer has are started on the server by its own download; the ones only the server has are offered in a native dialog and downloaded here on a yes. Photos come from the pack store on both sides. - Push (
sync/push.ts, server sidesync/pushServer.ts): captures whoseupdated_atis pastpushed_at(migration 150; a mirrored capture is settled when taken, so only a later edit here makes it due, while a new local one is due until pushed), and species marks likewise, go toPOST /sync/push. The server finds each capture by the shared id, else by fingerprint among its live captures (the same photo imported on both sides, recorded here asremote_id); one it doesn't have is uploaded like any import (settings/uploadToServer.ts, with vectors computed here) and pushed again. Trashing here trashes there. A photo that can't be uploaded is logged, stays due, and fails the push job, so Settings shows it. Albums, trips and membership go in the same job (below). - Conflicts: the newest edit wins. Each pushed capture carries the server's
updated_atthis computer last had (remote_updated_at, migration 152). The server writes it only if its row hasn't changed since; otherwise it answersconflictwith its own copy, which the desktop takes at once. A push never brings a capture back from the server's trash unless the desktop had already seen the trashed copy (so restoring it here is the newer edit). A capture found only by fingerprint, with no version from the server, is a conflict too, and the server's copy wins. The pull never overwrites a capture imported here that has an edit not pushed yet; the next push settles it. - Mirror (
sync/mirror.ts, server sidesync/changes.ts):GET /sync/changespages the server's captures by(updated_at, id), trashed ones included, andGET /sync/user-speciessends every species mark. Rows land here withorigin = 'mirror'under the server's ids, with the thumbnail (and the medium copy, if chosen in Settings) underAPP_DATA_DIR, never the original. A capture the server trashed or purged is removed here if it's a mirrored row and moved to the trash here if it was imported here. Species marks the server no longer has are removed here, unless changed here and not pushed, or a live photo here still has that species. The cursor is ininstall_settings; linking to another server (sync_instance) drops the old mirror and makes everything here due for a push again. Changing the photo copy or deleting the local library clears the cursor, so the next pull walks everything again (files already here aren't fetched twice), and the saved cursor never moves past a capture whose file failed to download. Files are fetched before each page's transaction opens, six at a time. - The cursor and long transactions:
updated_atis stamped with the transaction's start time, so a long import could commit rows stamped before a cursor that already moved on./sync/changesserves only rows stamped before the oldest transaction still open on the server's database (pg_stat_activity), so every row it passes is committed. A long import or reimport on the server delays the mirror until it commits, and nothing is skipped. - Deletions (
sync_tombstones, migration 152): deleting a capture or a species mark outright records a tombstone, by the server's capture id or the species' scientific name, from a trigger. On the server they come back from/sync/changesaspurged, so a desktop that was offline through a trash and purge still drops the photo. On the desktop they're sent with the next push, deletions first: the server trashes those captures (unless they changed there since this computer's copy) and removes those marks (unless a live photo of the species remains). Deletes that sync makes itself setlifer.sync_applyand leave no tombstone, so nothing echoes. Server tombstones are kept; desktop ones are dropped once sent, and all of them when the link changes server. - Protocol 2 (
GET /healthreturnssyncProtocol: 2): beside captures and species marks,GET /sync/albums,/sync/trips,/sync/album-capturesand/sync/album-exclusionspage each entity by(updated_at, ref)under the same open-transaction hold, with deleted refs from the tombstones, andPOST /sync/pushtakes optionalalbums,trips,albumCaptures,albumExclusionsand matchingdeletedlists (sync/library.ts; the desktop side issync/libraryMirror.ts). Albums and trips carry the receiver's version they were based on and follow the capture rule: written only if unchanged since, elseconflictwith the receiver's copy, ornullwhen it was deleted there. Membership rows are sets: adds are idempotent, removals are tombstones, and each names the capture by the id the receiver knows it under. Cover photos apply only where that photo exists on the receiving side. A capture carries itstripId(optional on push, so an older desktop leaves it alone). The push sends trips and albums before captures and membership after them; the pull takes trips and albums, then captures, then membership. Species marks carryupdatedAt; a pushed mark with abaseUpdatedAtis written only if the server's mark hasn't changed since (remote_updated_at, migration 164), else the server's mark comes back inuserSpeciesConflictsand is taken here; a mark with no base (never mirrored) replaces the server's as before. A v1 desktop pushing to a v2 server keeps working for captures and marks. - A server that looks new (journey H): if the linked server's instance id differs from the one this install last synced with, the push and pull stop with
ServerChangedError,GET /sync/statusreportsserverChanged, and nothing is changed or deleted until the user confirms in Settings > Server (POST /sync/adopt). Confirming drops the old mirror and makes everything here due for a push. - Library tracking (migration 163): every table below has
updated_at(stamped on a real edit only, not onpushed_atorremote_updated_atupdates),pushed_atand, for albums and trips,remote_updated_at, and a delete writes a tombstone unlesslifer.sync_applyis on. Tracked:albums(album, ref the id),trips(trip),album_captures(album_capture, ref<album id>:<capture ref>),album_exclusions(album_exclusion, same ref),saved_spots(saved_spot),species_split_kept(species_split_kept, ref the capture ref; fed by/sync/species-split-keptand pushed asspeciesSplitKeptafter the captures it names),smart_tag_hidden_terms(smart_tag_hidden, ref the term id; fed by/sync/smart-tag-hiddenand pushed assmartTagHidden, desktops only). Ride on the capture's own stamp: tags,trip_id, extra species (capture_species) and smart tag decisions (smartTagsAcceptedandsmartTagsRejected, migration 208; a sender that leaves them out keeps the receiver's). Local only:trip_suggestion_dismissals,user_tier_overrides,user_archived_species, target lists, lists from iNaturalist and shared links. Smart tag suggestions (capture_smart_suggestions, migration 207) are derived from stored signals and never synced; each install works them out itself. Decisions about them sync: an accepted smart tag is an ordinary tag, a rejection and the hidden terms travel as above, and the undo batches (smart_tag_batches) stay local. A membership row deleted by its album or capture leaves no tombstone of its own, since the parent's covers it. Ids are uuids shared by both installs, so no natural key is needed. - Order: packs, then push, then pull, after every connection and every half hour; the shell restarts the local API first if it stopped, and stops between phases if the link was dropped. Recording a push, or taking the server's copy, doesn't count as a change (the touch triggers in migrations 150 and 152 skip bookkeeping-only updates), so nothing echoes.
- Deleting the local copy (
settings/deleteLocalLibrary.ts) is allowed once the library is linked and nothing is waiting to be pushed, deletions included. It deletes the user's captures anduser_speciesin one transaction, recording no tombstones (the server keeps everything), then the managed files and previews. The file deletion comes after the commit and isn't atomic.
Limits: the server must know every species the desktop has (a capture whose species the server's catalog lacks is counted and left for the next run); extra species (capture_species) don't sync yet; "newest" for a capture means newest relative to the version this computer last saw, never a comparison of the two computers' clocks; the two installs should run the same release.
Recovery files and reimport
Lifer keeps enough in the library to rebuild most of a collection without the database (ADR 0006):
- Species, rating and photo tags in each managed file or its XMP sidecar (Imports and metadata).
.lifer/collection-state.jsonat the library root: per user (by email), seen species, targets, archived and region-hidden species, tier overrides, checklist additions, and each species card's cover photo and crop, all by scientific name and region name or code, plus the install's downloaded pack ids. A card's cover is found again by its original file's content hash, else its path in the library, since Lifer writing tags into a managed file changes the hash; covers and crops come back at the end of a reimport (restoreCards), once the photos are back (apps/api/src/lib/collectionState.ts). Written two seconds after a change to any of them. A fresh install's setup reads it throughGET /library/existing(apps/api/src/library/routes.ts): it says the folder holds a library, pre-selects the countries and animal groups those packs covered, and finishes with a reimport..lifer/albums.jsonin photo folders: album membership by album name (apps/api/src/albums/albumIndex.ts)..lifer/index.jsonin trip destination folders: each imported file's species (apps/api/src/trips/tripIndex.ts).
These are written atomically (apps/api/src/lib/atomicWrite.ts: a temp file that's fsynced, renamed over the old one, then the folder fsynced, except on Windows), but the collection state is debounced, so a crash or power cut can lose the last few seconds of changes. They're a recovery aid, not a second database: the database always wins, and they're read only to fill an empty database.
Reimport (POST /api/library/reimport, apps/api/src/library/reimport.ts) walks the library or a chosen folder (skipping dot folders, the upload work folder and APP_DATA_DIR):
- A file whose hash is already known is left alone, or its path is repaired if it moved.
- A photo a culling app rejected (
apps/api/src/uploads/cullMarks.ts, read from the photo, its sidecar and a RAW twin with the same stem) is skipped, recovered hidden, or recovered as usual, as the request'scullMarkssays (skipby default). A skipped file is left untouched on disk and counted, not listed. - A known file the user left in place is moved into the library when the request has
organize(moveInIfLeftInPlace), so importing the same folder again with it on consolidates. - A new file's species comes from its keywords, then its file and folder names; an ambiguous or unknown file is listed for the user, not guessed. For an unknown one, its keywords and nearest non-layout folder are looked up on iNaturalist (
apps/api/src/library/unmatchedSuggestions.ts) and the result is attached as a suggestion;POST /api/library/reimport/assignimports the confirmed photos as that species, creating it as Other Taxa when the catalog lacks it. It's imported with its EXIF, rating, cull marks and the photo tags Lifer wrote into it, marked collected (unless recovered hidden), and added back to its albums by name. - RAW files attach to an existing JPEG capture with the same name stem and a capture time within one second.
- Before the walk, hand-added (Other Taxa) species listed in the library's record are re-created from iNaturalist, so their photos match.
- Finally the collection state is restored, if the database has none for that user. A chosen folder that is another Lifer library (
GET /api/library/inspect-folder) is merged instead: what its record holds that this install lacks is added, and its card covers apply only where the current cover isn't from this library. - Photos added this way get their CLIP, identification and scene vectors from the catch-up backfill (
catchUpPhotoBackfills), so search and shot kinds include them.
Trip scans separately read .lifer/index.json to restore the species of trip photos.
What can't be rebuilt from files: the account, sessions, API keys and share links; settings; trip records; RAW files with no JPEG; photos with no recognisable species; tags on photos Lifer doesn't manage (their files are never written); anything chosen in the database but never written to a file (for example a cover marker on an unmanaged photo). That's why the backup guide still asks for a database backup.
Desktop app connected to a server
In server mode the desktop window loads the server's own web app (apps/desktop/src-tauri/src/server_watch.rs, store.rs), and the app chooses between the server's local and public addresses by Wi-Fi network name, confirming the server's instance id at each. If no address answers, the app opens the computer's own library (use_local_while_offline in server_watch.rs), which holds the mirror of the server's collection described above when the app is linked; work done there is pushed when the server answers again. An app that isn't linked has no server collection to show.
Matching on this computer (apps/desktop/src-tauri/src/local_inference.rs, apps/api/src/species/localInferenceServer.ts): the app runs an inference-only copy of the API on loopback, with a per-launch bearer token, downloads the same model files the server uses (checked against the server's SHA-256), and sends the image vectors it computes along with each upload. The server accepts them only if they match its own image pipeline version, model versions and the uploaded file's SHA-256, and have the expected shape and norm (packages/core/src/species/clientVectors.ts); otherwise it computes its own. It doesn't recompute the vectors to compare, so this protects against version drift, not against a signed-in client sending wrong vectors for its own photos.
Backups
Lifer has no backup feature. The backup guide covers pg_dump of the database and copying the library, taken at about the same time. Because migrations are forward only (Database migrations), an older backup restores into a newer Lifer, but a database a newer Lifer has migrated can't be used by an older one. packages/data-pipeline/src/scripts/backup.ts is a maintainer convenience for the development database and library, not part of installs.