Skip to main content

capsule_library/library/
rebuild.rs

1//! Recovery-first rebuild of the SQLite index from the artifacts on disk.
2//!
3//! One sidecar shape is read here: the signed [`SidecarV1`] every write path emits
4//! (`write_asset_files`, behind [`import_asset`](crate::lifecycle::Workspace::import_asset)
5//! and every later metadata write). It carries the CRDT registers (`hidden`, `cull`,
6//! `stack_membership`, rating, tags), and it is the write path's own output, so a rebuild
7//! reconstructs exactly what the write path indexed.
8//!
9//! The retired unsigned pre-signed-path shape is **not** read: no reader of it remains. A
10//! rebuild holds no key material and cannot sign a sidecar, a manifest, or seal a blob, so a
11//! file that does not decode as the signed shape — that record included — is
12//! [probed](capsule_core::sidecar::shape), warned about, and skipped, rather than indexed as an
13//! asset the workspace cannot verify, export, or upload.
14//!
15//! What the signed shape restores:
16//!
17//! | state | source |
18//! |---|---|
19//! | `hidden` (gated Hidden view) | the `hidden` LWW register |
20//! | `rating` | the `rating` LWW register |
21//! | user tags (`asset_tags`) | the `tags_user` OR-set, replaced atomically with the row |
22//! | `caption`, `latitude`/`longitude` | the `caption` register; the effective GPS fix |
23//! | capture time | the effective capture timestamp (the user's correction, else as imported) |
24//! | trash (`is_deleted`/`deleted_at`) | the provenance chain's lifecycle actions |
25//! | `album_id` | the provenance chain head manifest |
26//! | stacks | the `stack_membership` LWW register |
27//! | `cull` | *not an index projection* — see below |
28//!
29//! Not restored: `cached_representations` (local cache state, re-scannable from disk and left
30//! untouched by a rebuild) and the media-derived columns (`chromahash`, `dominant_color`,
31//! `duration_ms`), which the write path leaves NULL too.
32//!
33//! The same per-asset path serves the open-time reconcile:
34//! [`reindex_sidecars`] indexes just the bundles `Workspace::open` found on disk with no
35//! `assets` row (an import interrupted between its durable bundle and its index commit).
36//!
37//! An **importer-formed** stack used to be the one thing the sidecar did not carry: an
38//! older `import_asset_with` recorded it as `assets.stack_id` / `is_stack_hidden` and wrote no
39//! `stack_membership` register, so it lived only in the index and a lost index lost it.
40//! The importer now writes the register, so an importer-formed stack is reconstructed from
41//! disk like any other. The preservation branch in [`signed_asset_row`] is therefore no longer
42//! load-bearing for anything this build writes — it stays as the **compatibility path** for
43//! libraries imported by that older importer, whose sidecars carry no register and whose
44//! placement is still index-only.
45//!
46//! `cull` needs nothing here: it has no column in `assets` and no query projects it. The
47//! culling views ([`Workspace::assets_by_cull`](crate::lifecycle::Workspace::assets_by_cull))
48//! read the register straight off the signed sidecars that `Workspace::open` restores, so a
49//! lost index costs it nothing. It is listed above so the absence is a recorded finding rather
50//! than an oversight.
51//!
52//! Nothing here verifies a signature: a rebuild holds no key material (a [`Library`] has no
53//! account), and these are the device's own local plaintext files — the same rule
54//! `Workspace::open`'s add-id sweep follows. Verification is `verify_asset`'s job, on open.
55
56use std::collections::HashMap;
57use std::fs;
58use std::path::{Path, PathBuf};
59
60use capsule_core::cbor;
61use capsule_core::crypto::provenance::{Action, ProvenanceRecord};
62use capsule_core::domain::StackType;
63use capsule_core::sidecar::shape;
64use capsule_core::sidecar::sidecar_v1::{SIDECAR_SCHEMA_V1, SidecarV1, StackMembership, StackRole};
65use uuid::Uuid;
66use walkdir::WalkDir;
67
68use crate::db::rows::{AssetRow, AssetStackRow, StackMemberRow};
69use crate::library::error::LibraryError;
70use crate::library::library::Library;
71
72/// A signed sidecar together with the directory it was found in (its provenance chain,
73/// which carries the album and the trash state, is that directory's sibling file).
74struct SignedOnDisk {
75    dir: PathBuf,
76    sidecar: SidecarV1,
77}
78
79/// The per-asset state that lives in the provenance chain rather than in the signed sidecar:
80/// the owning album, and whether the asset is currently in the trash.
81///
82/// [`Default`] is the honest answer for an asset whose chain could not be read — album
83/// unknown, not trashed — and it is always accompanied by a `warn`, because "not trashed"
84/// is the permissive answer and a reader after the fact must be able to see it was a guess.
85#[derive(Debug, Default)]
86struct ChainFacts {
87    album_id: Option<String>,
88    is_deleted: bool,
89    deleted_at: Option<i64>,
90}
91
92/// Rebuild the SQLite index from the sidecars on disk.
93///
94/// Every `{uuid}.cbor` under `media/` is decoded as the signed [`SidecarV1`] shape and upserted
95/// as an `assets` row together with its user tags (one transaction per asset); stacks are then
96/// reconstructed from the `stack_membership` registers.
97///
98/// A sidecar that does not decode as the signed shape — a torn or foreign file, or a retired
99/// unsigned pre-signed-path record — is warned about and skipped: a rebuild holds no keys and
100/// cannot admit it, and one unreadable file must not cost the whole library its index.
101#[tracing::instrument(skip_all, fields(root = %library.root.display()))]
102pub fn rebuild_index(library: &Library) -> Result<(), LibraryError> {
103    let media_dir = library.root.join("media");
104    if !media_dir.exists() {
105        tracing::info!("rebuild_index: no media directory; nothing to rebuild");
106        return Ok(());
107    }
108
109    let mut signed: Vec<SignedOnDisk> = Vec::new();
110    let mut skipped = 0usize;
111
112    for entry in WalkDir::new(&media_dir).into_iter().filter_map(Result::ok) {
113        let path = entry.path();
114        if !path.is_file() {
115            continue;
116        }
117        // The sidecar is exactly `{uuid}.cbor`. The sibling `{uuid}.provenance.cbor`,
118        // `{uuid}.receipts.cbor` and `{uuid}.attestations.cbor` logs are read through their own
119        // readers (or not at all) and must never be parsed as sidecars — the same filter
120        // `Workspace::open` applies.
121        let name = path.file_name().unwrap_or_default().to_string_lossy();
122        if !crate::library::paths::is_sidecar_file_name(&name) {
123            continue;
124        }
125
126        match decode_signed(path, &media_dir) {
127            Some(found) => signed.push(found),
128            None => skipped += 1,
129        }
130    }
131
132    let mut hidden = 0usize;
133    let mut trashed = 0usize;
134
135    for found in &signed {
136        let row = index_signed(library, found)?;
137        hidden += usize::from(row.is_hidden);
138        trashed += usize::from(row.is_deleted);
139    }
140
141    let signed_stacks = rebuild_signed_stacks(library, &signed);
142
143    tracing::info!(
144        signed = signed.len(),
145        skipped,
146        hidden,
147        trashed,
148        signed_stacks,
149        "rebuild_index: index rebuilt from on-disk sidecars"
150    );
151    Ok(())
152}
153
154/// Index the signed sidecars at `sidecars` — and only them — exactly as [`rebuild_index`]
155/// indexes each one: the `assets` row and its tags in one transaction, then any stack their
156/// `stack_membership` registers form. Returns the ids it indexed.
157///
158/// This is the open-time reconcile's write path: `Workspace::open` hands it the bundles it
159/// restored from disk that have no `assets` row, so a crash between an import's durable bundle
160/// and its index commit costs nothing once the library is opened again. A sidecar that does not
161/// decode is warned about and skipped, as in a full rebuild.
162#[tracing::instrument(skip_all, fields(root = %library.root.display(), sidecars = sidecars.len()))]
163pub(crate) fn reindex_sidecars(
164    library: &Library,
165    sidecars: &[PathBuf],
166) -> Result<Vec<Uuid>, LibraryError> {
167    let media_dir = library.root.join("media");
168    let signed: Vec<SignedOnDisk> = sidecars
169        .iter()
170        .filter_map(|path| decode_signed(path, &media_dir))
171        .collect();
172    for found in &signed {
173        let row = index_signed(library, found)?;
174        tracing::debug!(
175            asset_id = %row.uuid,
176            album_id = ?row.album_id,
177            is_deleted = row.is_deleted,
178            "reconcile: unindexed bundle indexed from its sidecar"
179        );
180    }
181    let stacks = rebuild_signed_stacks(library, &signed);
182    tracing::debug!(
183        indexed = signed.len(),
184        skipped = sidecars.len() - signed.len(),
185        stacks,
186        "reconcile: sidecars re-indexed"
187    );
188    Ok(signed.iter().map(|found| found.sidecar.uuid).collect())
189}
190
191/// Read and decode one `{uuid}.cbor` as the signed shape, warning (and returning `None`) when
192/// it is unreadable or any other shape.
193fn decode_signed(path: &Path, media_dir: &Path) -> Option<SignedOnDisk> {
194    let bytes = match fs::read(path) {
195        Ok(b) => b,
196        Err(e) => {
197            tracing::warn!(
198                sidecar = %path.display(),
199                error = %e,
200                "rebuild_index: unreadable sidecar file; skipping"
201            );
202            return None;
203        }
204    };
205    // The signed shape is the only one read: it is what every write path emits, and it is
206    // the only shape that carries the `hidden` register the default projections gate on.
207    match SidecarV1::from_canonical_slice(&bytes, SIDECAR_SCHEMA_V1) {
208        Ok(sidecar) => {
209            let dir = path.parent().unwrap_or(media_dir).to_path_buf();
210            tracing::debug!(
211                sidecar = %path.display(),
212                asset_id = %sidecar.uuid,
213                shape = "sidecar-v1-signed",
214                "rebuild_index: decoded sidecar"
215            );
216            Some(SignedOnDisk { dir, sidecar })
217        }
218        Err(signed_err) => {
219            tracing::warn!(
220                sidecar = %path.display(),
221                shape = ?shape::probe(&bytes),
222                error = %signed_err,
223                "rebuild_index: sidecar does not decode as the signed shape; skipping"
224            );
225            None
226        }
227    }
228}
229
230/// Upsert `found`'s `assets` row and replace its user tags, atomically, returning the row.
231fn index_signed(library: &Library, found: &SignedOnDisk) -> Result<AssetRow, LibraryError> {
232    let facts = chain_facts(&found.dir, &found.sidecar.uuid);
233    // The row already in the index, if any. A rebuild normally runs against a lost index
234    // and finds nothing here; when it is run against a live one (`capsule rebuild`), this
235    // is what keeps it from erasing the index-only stack placement described below.
236    let prior = library
237        .db
238        .find_by_uuid(&found.sidecar.uuid.to_string())
239        .ok()
240        .flatten();
241    let row = signed_asset_row(&found.sidecar, &facts, prior.as_ref());
242    let tags: Vec<String> = found.sidecar.tags_user.value().into_iter().collect();
243    tracing::trace!(
244        asset_id = %row.uuid,
245        album_id = ?row.album_id,
246        is_hidden = row.is_hidden,
247        is_deleted = row.is_deleted,
248        stack_id = ?row.stack_id,
249        tags = tags.len(),
250        "rebuild_index: upserting row and tags rebuilt from a signed sidecar"
251    );
252    let db = &library.db;
253    db.with_transaction(|| {
254        db.upsert_asset(&row)?;
255        db.replace_asset_tags(&row.uuid, &tags)
256    })?;
257    Ok(row)
258}
259
260// ── the signed shape ────────────────────────────────────────────────────────
261
262/// Read `{uuid}.provenance.cbor` and replay its lifecycle actions.
263///
264/// The chain — not the sidecar and not the old index — is the source of truth for the trash
265/// state (a `delete` moves an asset to trash, a later `trash-restore` brings it back) and for
266/// the owning album (the head manifest names it). Signatures are not checked here; see the
267/// module docs.
268fn chain_facts(dir: &Path, asset_id: &Uuid) -> ChainFacts {
269    let path = dir.join(format!("{}.provenance.cbor", asset_id.simple()));
270    let bytes = match fs::read(&path) {
271        Ok(b) => b,
272        Err(e) => {
273            tracing::warn!(
274                asset_id = %asset_id,
275                provenance = %path.display(),
276                error = %e,
277                "rebuild_index: no readable provenance chain; rebuilding this asset with an \
278                 unknown album and as NOT trashed"
279            );
280            return ChainFacts::default();
281        }
282    };
283    let records: Vec<ProvenanceRecord> = match cbor::from_slice(&bytes) {
284        Ok(r) => r,
285        Err(e) => {
286            tracing::warn!(
287                asset_id = %asset_id,
288                provenance = %path.display(),
289                error = %e,
290                "rebuild_index: undecodable provenance chain; rebuilding this asset with an \
291                 unknown album and as NOT trashed"
292            );
293            return ChainFacts::default();
294        }
295    };
296
297    let mut facts = ChainFacts::default();
298    for rec in &records {
299        match rec.manifest.core.action {
300            Action::Delete => {
301                facts.is_deleted = true;
302                facts.deleted_at = rfc3339_to_secs(&rec.manifest.core.timestamp);
303            }
304            Action::TrashRestore => {
305                facts.is_deleted = false;
306                facts.deleted_at = None;
307            }
308            _ => {}
309        }
310    }
311    facts.album_id = records
312        .last()
313        .map(|rec| rec.manifest.core.album_id.to_string());
314    tracing::debug!(
315        asset_id = %asset_id,
316        records = records.len(),
317        album_id = ?facts.album_id,
318        is_deleted = facts.is_deleted,
319        "rebuild_index: replayed provenance chain"
320    );
321    facts
322}
323
324/// Project a signed sidecar (plus its chain facts) onto an `assets` row.
325///
326/// This mirrors `lifecycle::asset_row_from_state`, which is what the write path indexes: the
327/// two must agree, or a rebuild would silently change what the views show. Media-derived
328/// columns (`chromahash`, `dominant_color`, `duration_ms`) stay NULL for the same reason they
329/// do there.
330fn signed_asset_row(s: &SidecarV1, facts: &ChainFacts, prior: Option<&AssetRow>) -> AssetRow {
331    // The timeline is dated by the user's correction when there is one, else the as-imported
332    // instant — the same rule the write path applies.
333    let capture = s.effective_capture_timestamp();
334    let capture_utc = rfc3339_to_secs(capture);
335    if capture_utc.is_none() {
336        tracing::warn!(
337            asset_id = %s.uuid,
338            capture_timestamp = %capture,
339            "rebuild_index: unparseable capture timestamp; indexing it as the epoch"
340        );
341    }
342    // Three cases, and the middle one is why this matches on `get()` rather than flattening
343    // through `and_then(Option::as_ref)`: a *stamped* `None` and a *never-written* register are
344    // different facts, and collapsing them resurrects placement the user deliberately removed.
345    // Mirrors `lifecycle::import::asset_row_from_state`, which is the write path's answer to the
346    // same question.
347    let register = s.stack_membership.get();
348    let (stack_id, is_stack_hidden) = match register {
349        // Stamped with a membership: project it. Every non-primary member is suppressed from the
350        // timeline, exactly as the write path arranges it.
351        Some(membership) => membership.as_ref().map_or((None, false), |m| {
352            // Stamped `None` — the asset left the stack. The register is authoritative and says
353            // so, so the columns are cleared rather than reconstructed from a stale index row.
354            (Some(m.stack_id.to_string()), m.role != StackRole::Primary)
355        }),
356        // No register on disk at all. Compatibility path only: every
357        // importer-formed stack this build writes carries the register, so reaching here means a
358        // **library imported by the older importer**, whose placement was written only to the
359        // index and lives nowhere else. Whatever the row already carries is then the only copy in existence, and a rebuild
360        // must not erase it.
361        None => prior.map_or((None, false), |p| (p.stack_id.clone(), p.is_stack_hidden)),
362    };
363    if register.is_none() && stack_id.is_some() {
364        tracing::debug!(
365            asset_id = %s.uuid,
366            stack_id = ?stack_id,
367            "rebuild_index: no stack_membership register on disk (asset written before the register existed); keeping \
368             the index-only stack placement the existing row carries"
369        );
370    }
371    AssetRow {
372        uuid: s.uuid.to_string(),
373        asset_type: if s.content_type.starts_with("video/") {
374            "video".to_string()
375        } else {
376            "photo".to_string()
377        },
378        capture_timestamp: capture_utc.unwrap_or(0),
379        capture_utc: Some(capture_utc.unwrap_or(0)),
380        capture_tz_source: None,
381        import_timestamp: rfc3339_to_secs(&s.import_timestamp).unwrap_or(0),
382        hash_sha256: s.hash.to_hex(),
383        width: s.dimensions.as_ref().map(|d| i64::from(d.width)),
384        height: s.dimensions.as_ref().map(|d| i64::from(d.height)),
385        duration_ms: None,
386        stack_id,
387        is_stack_hidden,
388        chromahash: None,
389        dominant_color: None,
390        album_id: facts.album_id.clone(),
391        rating: i64::from(s.rating.get().copied().unwrap_or(0)),
392        is_deleted: facts.is_deleted,
393        deleted_at: facts.deleted_at,
394        // The register this rebuild exists for: a never-written
395        // register means visible, the wire-absent default.
396        is_hidden: s.hidden.get().copied().unwrap_or(false),
397        // The caption register and the effective location (the user's edit over the
398        // as-imported fix), projected as the write path projects them.
399        caption: s.caption.get().filter(|c| !c.is_empty()).cloned(),
400        latitude: s.effective_gps().map(|g| g.lat),
401        longitude: s.effective_gps().map(|g| g.lon),
402    }
403}
404
405/// Reconstruct `asset_stacks` / `stack_members` from the signed `stack_membership` registers.
406/// Returns the number of stacks written.
407fn rebuild_signed_stacks(library: &Library, signed: &[SignedOnDisk]) -> usize {
408    // stack id → its members, as (asset uuid, membership).
409    let mut groups: HashMap<Uuid, Vec<(Uuid, StackMembership)>> = HashMap::new();
410    for found in signed {
411        if let Some(Some(membership)) = found.sidecar.stack_membership.get() {
412            groups
413                .entry(membership.stack_id)
414                .or_default()
415                .push((found.sidecar.uuid, membership.clone()));
416        }
417    }
418
419    let now = now_secs();
420    for (stack_id, members) in &mut groups {
421        // Deterministic order regardless of directory-walk order: declared index first,
422        // then asset id.
423        members.sort_by_key(|(uuid, m)| (m.member_index, *uuid));
424        let primary = members
425            .iter()
426            .find(|(_, m)| m.role == StackRole::Primary)
427            .or_else(|| members.first())
428            .map(|(uuid, _)| uuid.to_string());
429        let Some(primary) = primary else {
430            continue;
431        };
432        let stack_type = members
433            .first()
434            .map_or("custom", |(_, m)| stack_type_str(m.stack_type));
435
436        let stack_row = AssetStackRow {
437            id: stack_id.to_string(),
438            stack_type: stack_type.to_string(),
439            primary_asset_id: primary.clone(),
440            cover_asset_id: Some(primary.clone()),
441            is_collapsed: true,
442            // The register records the grouping, not how it came about, so a rebuilt stack
443            // makes no claim to have been auto-detected.
444            is_auto_generated: false,
445            created_at: now,
446            modified_at: now,
447        };
448        if let Err(e) = library.db.insert_stack(&stack_row) {
449            // Idempotent on rebuild: the row is already there from an earlier pass.
450            tracing::debug!(stack_id = %stack_id, error = %e, "rebuild_index: stack row already present");
451        }
452
453        for (i, (uuid, membership)) in members.iter().enumerate() {
454            let member_row = StackMemberRow {
455                // The member's declared index, as the importer numbers it, so a reconcile
456                // pass over part of a stack does not collide with the rows already there.
457                id: format!(
458                    "{stack_id}#{}",
459                    membership.member_index.map_or(i, |n| n as usize)
460                ),
461                stack_id: stack_id.to_string(),
462                asset_id: uuid.to_string(),
463                sequence_order: membership.member_index.map_or(i as i64, i64::from),
464                member_role: stack_role_str(membership.role).to_string(),
465                created_at: now,
466            };
467            if let Err(e) = library.db.insert_stack_member(&member_row) {
468                tracing::debug!(
469                    stack_id = %stack_id,
470                    asset_id = %uuid,
471                    error = %e,
472                    "rebuild_index: stack member row already present"
473                );
474            }
475        }
476        tracing::debug!(
477            stack_id = %stack_id,
478            members = members.len(),
479            primary_asset_id = %primary,
480            "rebuild_index: stack reconstructed from signed stack_membership registers"
481        );
482    }
483    groups.len()
484}
485
486// ── helpers ─────────────────────────────────────────────────────────────────
487
488fn rfc3339_to_secs(s: &str) -> Option<i64> {
489    s.parse::<jiff::Timestamp>()
490        .ok()
491        .map(|t: jiff::Timestamp| t.as_second())
492}
493
494/// The `stack_members.member_role` string for a signed membership's role.
495fn stack_role_str(r: StackRole) -> &'static str {
496    match r {
497        StackRole::Primary => "primary",
498        StackRole::Member => "member",
499        StackRole::Proxy => "proxy",
500    }
501}
502
503fn stack_type_str(st: StackType) -> &'static str {
504    match st {
505        StackType::RawJpeg => "raw_jpeg",
506        StackType::Burst => "burst",
507        StackType::LivePhoto => "live_photo",
508        StackType::Portrait => "portrait",
509        StackType::SmartSelection => "smart_selection",
510        StackType::HdrBracket => "hdr_bracket",
511        StackType::FocusStack => "focus_stack",
512        StackType::PixelShift => "pixel_shift",
513        StackType::Panorama => "panorama",
514        StackType::Proxy => "proxy",
515        StackType::Chaptered => "chaptered",
516        StackType::DualAudio => "dual_audio",
517        StackType::Custom => "custom",
518    }
519}
520
521fn now_secs() -> i64 {
522    std::time::SystemTime::now()
523        .duration_since(std::time::UNIX_EPOCH)
524        .unwrap_or_default()
525        .as_secs() as i64
526}
527
528// The contract these tests hold `rebuild_index` to:
529//
530// signed shape (`SidecarV1` — what every current write path emits)
531//   1. a hidden asset comes back hidden, and stays out of the default projections
532//   2. a visible asset comes back visible (the control: hiding is not the default)
533//   3. `stack_membership` comes back as `stack_id` + `is_stack_hidden` + stack rows
534//   3b. an index-only (importer-formed) placement is preserved, never overwritten with NULL
535//   4. the trash state and the owning album come back from the provenance chain
536//   5. a missing chain degrades to "album unknown, not trashed" rather than failing
537//   6. rebuilding twice changes nothing
538//   7. the `{uuid}.provenance.cbor` / `{uuid}.receipts.cbor` / `{uuid}.attestations.cbor`
539//      siblings are not sidecars, and a real attestation log survives the rebuild untouched
540//   8. `cull` needs no rebuild support — it is not an index projection (audit finding)
541//
542// the retired unsigned shape
543//   9. the two shapes are disjoint on the wire, so the probe cannot mis-route a file
544//   10. an unsigned sidecar is reported and not indexed; the signed asset beside it is
545#[cfg(test)]
546mod tests;