Skip to main content

vcon_server/
store.rs

1//! One tenant's vCons: a sealed object per kept version and a catalog row
2//! for it. The catalog is the truth: a version exists once its row is
3//! committed, and an object with no row is garbage. Every rule is here;
4//! the catalog and the objects are reached through the backend traits.
5
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8#[cfg(test)]
9use std::sync::{Mutex, MutexGuard};
10
11#[cfg(test)]
12use crate::backend::local::LocalConn;
13
14use uuid::Uuid;
15use vcon::read::Inspection;
16
17use crate::audit::{self, Action, Actor, Entry};
18use crate::backend::local::{Durability, LocalCatalog, LocalObjects};
19use crate::backend::{
20    Catalog, CatalogTx, CommitError, NewVersion, ObjectError, Objects, Packed, Packs,
21};
22use crate::catalog;
23use crate::clock::{Clock, nanos};
24use crate::envelope::{self, Context, Key, WrapLimit};
25use crate::fs::Fs;
26use crate::ids::{KeyId, TenantId, VersionId};
27use crate::retention::Retention;
28use crate::reveal::Part;
29use pending::Writers;
30
31mod backup;
32#[cfg(test)]
33mod clock_reading_tests;
34mod compact;
35mod examine;
36mod export;
37mod group;
38#[cfg(test)]
39mod group_tests;
40mod legal;
41mod list;
42pub(crate) mod manifest;
43#[cfg(test)]
44mod manifest_grace_tests;
45#[cfg(test)]
46mod pack_pending_tests;
47pub(crate) mod packed;
48pub(crate) mod packer;
49pub(crate) mod pending;
50mod purge;
51#[cfg(test)]
52mod read_race_tests;
53mod rekey;
54mod rewrite;
55#[cfg(test)]
56mod statement_tests;
57#[cfg(test)]
58mod sync_tests;
59
60pub use backup::{BackupError, Copied, TRIES};
61pub use examine::{Examination, ExamineError};
62pub use export::KeptVersion;
63pub use legal::{Legal, VersionInfo};
64pub use list::{Cursor, ListQuery, Listed, Listing};
65pub use purge::{Kept, PurgeReport, due};
66
67/// Who is calling, for the audit record.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub struct Caller {
70    pub key: KeyId,
71}
72
73/// What `create` did.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum Created {
76    /// Stored as a new vCon.
77    New(VersionId),
78    /// The same bytes were already current; nothing was written.
79    Same(VersionId),
80}
81
82/// A version as `get` returns it.
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct Stored {
85    pub version: VersionId,
86    pub form: vcon::Form,
87    /// Whether the body is gzipped, as it arrived.
88    pub gzip: bool,
89    /// The body exactly as it arrived.
90    pub body: Vec<u8>,
91}
92
93/// What a tenant's Store keeps, as removal checks it.
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub struct Counts {
96    /// Versions kept, hidden ones included.
97    pub versions: u64,
98    /// Uuids under a legal hold.
99    pub held: u64,
100}
101
102/// Why a Store call was refused or failed.
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub enum StoreError {
105    Conflict,
106    Gone,
107    NotFound,
108    NotDeleted,
109    PreconditionFailed,
110    Immutable,
111    /// The tenant key is at its wrap limit and must be rotated.
112    LimitReached,
113    /// A row's object file is missing or does not open.
114    Damaged,
115    /// The audit record could not be written, so nothing was done.
116    AuditFailed,
117    Io,
118}
119
120/// Why a tenant's Store did not open: kept apart so a key that does not
121/// open its catalog is never confused with files this process may not use.
122#[derive(Debug)]
123pub enum OpenError {
124    /// The catalog does not open under the tenant's catalog key.
125    WrongKey,
126    /// This process may not use `path`, a file or directory the Store
127    /// needs; `error` is the system's.
128    Access {
129        path: PathBuf,
130        error: std::io::Error,
131    },
132    /// Anything else.
133    Store(StoreError),
134}
135
136impl From<OpenError> for StoreError {
137    /// How the Store's callers see a Store that did not open.
138    fn from(_: OpenError) -> StoreError {
139        StoreError::Io
140    }
141}
142
143impl From<StoreError> for OpenError {
144    fn from(e: StoreError) -> OpenError {
145        OpenError::Store(e)
146    }
147}
148
149impl From<catalog::CatalogError> for OpenError {
150    fn from(e: catalog::CatalogError) -> OpenError {
151        match e {
152            catalog::CatalogError::WrongKey => OpenError::WrongKey,
153            catalog::CatalogError::Access { path, error } => OpenError::Access { path, error },
154            _ => OpenError::Store(StoreError::Io),
155        }
156    }
157}
158
159/// A catalog transaction.
160type Tx<'a> = Box<dyn CatalogTx + 'a>;
161
162/// One tenant's vCons.
163pub struct Store {
164    tenant: TenantId,
165    tenant_key: Key,
166    catalog: Box<dyn Catalog>,
167    objects: Arc<dyn Objects>,
168    /// The pack files of packed versions; None where the storage keeps
169    /// none.
170    packs: Option<Arc<dyn Packs>>,
171    /// The footers of the pack files read.
172    footers: packed::Footers,
173    /// The filesystem a backup is written to.
174    fs: Arc<dyn Fs>,
175    clock: Arc<dyn Clock>,
176    /// The reads waiting to record themselves, committed together.
177    group: group::Group,
178    /// The local objects directory, for tests that look at its files.
179    #[cfg(test)]
180    objects_dir: PathBuf,
181    #[cfg(test)]
182    hooks: tests::Hooks,
183}
184
185impl Store {
186    /// Opens the tenant's local catalog under its catalog key, making it
187    /// if new, then runs start-up recovery.
188    pub fn open(
189        dir: &Path,
190        tenant: TenantId,
191        tenant_key: Key,
192        fs: Arc<dyn Fs>,
193        clock: Arc<dyn Clock>,
194    ) -> Result<Store, OpenError> {
195        // Every process that runs recovery holds the catalog alone: a
196        // server or a command that runs alone (datadir.rs).
197        let store = Store::open_as(dir, tenant, tenant_key, fs, clock, Durability::Group)?;
198        store.recover(Writers::None)?;
199        Ok(store)
200    }
201
202    /// Opens the store as a command running beside a server does: without
203    /// start-up recovery, which would take the server's writes in progress
204    /// for a crash's leftovers, and syncing what it reads (Durability).
205    pub fn open_beside(
206        dir: &Path,
207        tenant: TenantId,
208        tenant_key: Key,
209        fs: Arc<dyn Fs>,
210        clock: Arc<dyn Clock>,
211    ) -> Result<Store, OpenError> {
212        Store::open_as(dir, tenant, tenant_key, fs, clock, Durability::Beside)
213    }
214
215    /// Opens the store without start-up recovery, its catalog made durable
216    /// as `durability` says.
217    pub(crate) fn open_as(
218        dir: &Path,
219        tenant: TenantId,
220        tenant_key: Key,
221        fs: Arc<dyn Fs>,
222        clock: Arc<dyn Clock>,
223        durability: Durability,
224    ) -> Result<Store, OpenError> {
225        let catalog_key = envelope::catalog_key(&tenant_key).map_err(|_| StoreError::Io)?;
226        let catalog =
227            LocalCatalog::open(&dir.join("catalog.sqlite"), catalog_key, &*fs, durability)?;
228        let objects = dir.join("objects");
229        fs.create_dir_all(&objects).map_err(|_| StoreError::Io)?;
230        // Each version is written into objects/, so it must be writable too.
231        catalog::may_use(&objects, libc::W_OK | libc::X_OK)?;
232        // A new directory survives a crash only once the directory that
233        // holds it is synced; without this a crash could take the objects
234        // directory, synced files and all, while the catalog keeps its rows.
235        fs.sync_dir(dir).map_err(|_| StoreError::Io)?;
236        #[cfg_attr(
237            not(test),
238            allow(unused_mut, reason = "only tests set the objects directory after")
239        )]
240        let mut store = Store::with_backends(
241            tenant,
242            tenant_key,
243            Box::new(catalog),
244            Arc::new(LocalObjects::new(objects.clone(), fs.clone())),
245            None,
246            fs,
247            clock,
248        );
249        #[cfg(test)]
250        {
251            store.objects_dir = objects;
252        }
253        Ok(store)
254    }
255
256    /// A Store over the given catalog, objects and pack files; with
257    /// `recover`, start-up recovery runs, assuming the writers it names.
258    #[cfg(feature = "s3")]
259    #[expect(
260        clippy::too_many_arguments,
261        reason = "each backend is its own argument"
262    )]
263    pub(crate) fn open_on(
264        tenant: TenantId,
265        tenant_key: Key,
266        catalog: Box<dyn Catalog>,
267        objects: Arc<dyn Objects>,
268        packs: Option<Arc<dyn Packs>>,
269        fs: Arc<dyn Fs>,
270        clock: Arc<dyn Clock>,
271        recover: Option<Writers>,
272    ) -> Result<Store, OpenError> {
273        let store = Store::with_backends(tenant, tenant_key, catalog, objects, packs, fs, clock);
274        if let Some(writers) = recover {
275            // Writers::None for a process that holds the catalog alone
276            // (the data directory's lock, or a command alone on a
277            // database); Writers::Maybe for a server among several.
278            store.recover(writers)?;
279        }
280        Ok(store)
281    }
282
283    /// A Store over the given catalog, objects and pack files, opened as
284    /// `open_beside` opens one: without start-up recovery.
285    pub(crate) fn with_backends(
286        tenant: TenantId,
287        tenant_key: Key,
288        catalog: Box<dyn Catalog>,
289        objects: Arc<dyn Objects>,
290        packs: Option<Arc<dyn Packs>>,
291        fs: Arc<dyn Fs>,
292        clock: Arc<dyn Clock>,
293    ) -> Store {
294        Store {
295            tenant,
296            tenant_key,
297            catalog,
298            objects,
299            packs,
300            footers: packed::Footers::new(packed::FOOTERS),
301            fs,
302            clock,
303            group: group::Group::default(),
304            #[cfg(test)]
305            objects_dir: PathBuf::new(),
306            #[cfg(test)]
307            hooks: tests::Hooks::default(),
308        }
309    }
310
311    /// The catalog's clock in `tx` ([`CatalogTx::clock_now`]), `host`
312    /// being this process's.
313    fn catalog_now(&self, tx: &mut dyn CatalogTx, host: i64) -> Result<i64, StoreError> {
314        let now = tx.clock_now(host)?;
315        #[cfg(test)]
316        let now = {
317            let mut steps = self.hooks.clock_steps.lock().expect("hook");
318            if steps.is_empty() {
319                now
320            } else {
321                now + steps.remove(0)
322            }
323        };
324        Ok(now)
325    }
326
327    /// The time in `tx` by the catalog's clock: what the transaction
328    /// writes as a time, and judges a time another server wrote by. On a
329    /// database it is the database's clock, so the host clocks of the
330    /// servers on it do not matter; on a data directory, this process's.
331    pub(crate) fn now_in(&self, tx: &mut dyn CatalogTx) -> Result<i64, StoreError> {
332        self.catalog_now(tx, nanos(self.clock.now()))
333    }
334
335    /// Start-up recovery: the catalog recovers itself, and temporary
336    /// objects, objects with no row and pack files with no row are
337    /// removed, unless a write is under way for them (store/pending.rs),
338    /// and how many is logged. A name that is not a version id, with or
339    /// without `.tmp`, or not a pack file's, is not ours and is left alone.
340    ///
341    /// The order is what keeps a write under way safe. A pending row no
342    /// write can still be under way for is deleted first, so that write's
343    /// last transaction refuses to add its row. The objects and the pack
344    /// files are listed next, and the rows read after: a write adds its
345    /// pending row before it puts its object or its file, so every one
346    /// listed has its pending row or its own row in that read.
347    pub(crate) fn recover(&self, writers: Writers) -> Result<(), StoreError> {
348        self.catalog.recover()?;
349        let host = nanos(self.clock.now());
350        let now = {
351            let mut tx = self.catalog.immediate()?;
352            let now = self.catalog_now(tx.as_mut(), host)?;
353            for (version, started_at) in tx.pending()? {
354                if !pending::under_way(writers, started_at, now) {
355                    tx.drop_pending(version)?;
356                }
357            }
358            for (file, started_at) in tx.pending_files()? {
359                if !pending::under_way(writers, started_at, now) {
360                    tx.drop_pending_file(file)?;
361                }
362            }
363            commit(tx)?;
364            now
365        };
366        let names = self.objects.list().map_err(io)?;
367        let pack_names = match &self.packs {
368            Some(packs) => packs.list().map_err(io)?,
369            None => Vec::new(),
370        };
371        // Nothing is removed on what the read saw until it is durable.
372        let (places, files, writing, putting) = self.read(|tx| {
373            let places: std::collections::HashMap<VersionId, bool> = tx
374                .places()?
375                .into_iter()
376                .map(|(version, place)| (version, names_its_object(&place)))
377                .collect();
378            let files: std::collections::HashSet<_> = tx.pack_files()?.into_iter().collect();
379            let writing: std::collections::HashSet<VersionId> = tx
380                .pending()?
381                .into_iter()
382                .filter(|(_, started_at)| pending::under_way(writers, *started_at, now))
383                .map(|(version, _)| version)
384                .collect();
385            let putting: std::collections::HashSet<crate::ids::FileId> = tx
386                .pending_files()?
387                .into_iter()
388                .filter(|(_, started_at)| pending::under_way(writers, *started_at, now))
389                .map(|(file, _)| file)
390                .collect();
391            Ok((places, files, writing, putting))
392        })?;
393        #[cfg(test)]
394        {
395            let hook = self.hooks.after_snapshot.lock().expect("hook").take();
396            if let Some(hook) = hook {
397                hook(self);
398            }
399        }
400        let mut removed: u64 = 0;
401        for name in names {
402            let (id, temporary) = match name.strip_suffix(".tmp") {
403                Some(id) => (id, true),
404                None => (name.as_str(), false),
405            };
406            let Some(version) = VersionId::parse(id) else {
407                continue;
408            };
409            let named = places.get(&version).copied().unwrap_or(false);
410            if pending::leftover(named, temporary, writing.contains(&version)) {
411                self.objects.remove_name(&name).map_err(io)?;
412                removed += 1;
413            }
414        }
415        if let Some(packs) = &self.packs {
416            let mut unnamed: u64 = 0;
417            // A file a rewrite wrote but did not record is removed below; a
418            // purge whose file side was cut off is finished after.
419            for name in pack_names {
420                let Some((_, file)) = packed::parse_name(&name) else {
421                    continue;
422                };
423                if pending::leftover(files.contains(&file), false, putting.contains(&file)) {
424                    packs.remove(&name).map_err(io)?;
425                    unnamed += 1;
426                }
427            }
428            if unnamed > 0 {
429                tracing::info!(
430                    removed = unnamed,
431                    "start-up recovery removed pack files that no catalog row names"
432                );
433            }
434        }
435        self.finish_purges()?;
436        self.publish()?;
437        if removed > 0 {
438            self.objects.sync().map_err(io)?;
439            // A count only, as the purge sweep logs, never a tenant or a
440            // name.
441            tracing::info!(
442                removed,
443                "start-up recovery removed objects that no catalog row names"
444            );
445        }
446        Ok(())
447    }
448
449    /// Stores a new vCon. The uuid's state is checked before anything is
450    /// sealed, the body is written in the order below, and the
451    /// commit checks the state again, so of two racing writers one wins
452    /// and the other's object is removed.
453    pub fn create(
454        &self,
455        who: &Caller,
456        found: &Inspection,
457        body: &[u8],
458    ) -> Result<Created, StoreError> {
459        let uuid = found.uuid;
460        let entry = |status, version| Entry {
461            actor: Actor::Key(who.key),
462            action: Action::Create,
463            target: Some(uuid.to_string()),
464            version,
465            status,
466        };
467        let key_id = self.tenant_key.id();
468        let version = VersionId::generate();
469        {
470            let mut tx = self.catalog.immediate()?;
471            let refused = match state(&mut tx, uuid)? {
472                State::Gone => Some((410, None, StoreError::Gone)),
473                State::Live(current) => match self.read_version(&mut tx, uuid, current) {
474                    Ok(stored) if stored == body => {
475                        self.record(&mut tx, &entry(200, Some(current)))?;
476                        commit(tx)?;
477                        return Ok(Created::Same(current));
478                    }
479                    Ok(_) => Some((409, None, StoreError::Conflict)),
480                    Err(StoreError::Damaged) => Some((500, Some(current), StoreError::Damaged)),
481                    Err(e) => return Err(e),
482                },
483                State::Absent if envelope::wrap_limit(tx.wraps(key_id)?) == WrapLimit::Refuse => {
484                    Some((503, None, StoreError::LimitReached))
485                }
486                // The wrap is counted before it is made, so every wrap is
487                // counted once whether this write wins or loses. The
488                // pending row marks the object as a write under way until
489                // its row is added (store/pending.rs).
490                State::Absent => {
491                    tx.add_wrap(key_id)?;
492                    tx.add_pending(version, nanos(self.clock.now()))?;
493                    None
494                }
495            };
496            if let Some((status, version, error)) = refused {
497                self.record(&mut tx, &entry(status, version))?;
498                commit(tx)?;
499                return Err(error);
500            }
501            commit(tx)?;
502        }
503
504        let wrapped = self.write_version(uuid, version, body)?;
505        self.pause();
506
507        let unknown = std::cell::Cell::new(false);
508        let committed = (|| {
509            let mut tx = self.catalog.immediate()?;
510            let mine = tx.drop_pending(version)?;
511            match state(&mut tx, uuid)? {
512                State::Absent => {}
513                lost => {
514                    let (status, error) = match lost {
515                        State::Gone => (410, StoreError::Gone),
516                        _ => (409, StoreError::Conflict),
517                    };
518                    self.record(&mut tx, &entry(status, None))?;
519                    commit(tx)?;
520                    return Err(error);
521                }
522            }
523            if !mine {
524                // Recovery took the write for a leftover and removed its
525                // object: a row now would name nothing.
526                self.record(&mut tx, &entry(500, None))?;
527                commit(tx)?;
528                return Err(StoreError::Io);
529            }
530            // The version's time, and the uuid's first: the list keeps
531            // its place by it through replace, delete and restore.
532            let stored_at = self.now_in(tx.as_mut())?;
533            tx.insert_version(&NewVersion {
534                version,
535                uuid,
536                form: form_name(found.form),
537                gzip: found.gzip,
538                size: i64::try_from(body.len()).map_err(io)?,
539                stored_at,
540                key: key_id,
541                wrapped: &wrapped,
542            })?;
543            tx.insert_vcon(uuid, version, stored_at)?;
544            self.record(&mut tx, &entry(201, Some(version)))?;
545            kept(tx.commit(), &unknown)?;
546            Ok(Created::New(version))
547        })();
548        self.drop_unless_kept(committed.is_err(), unknown.get(), version);
549        #[cfg(test)]
550        if committed.is_ok() {
551            self.forced_pack();
552        }
553        committed
554    }
555
556    /// Reads the current version of `uuid`. The body is decrypted whole,
557    /// then one transaction checks that the version is still current and
558    /// commits the audit record; only then is the body returned. If the
559    /// version changed meanwhile, the read starts again.
560    pub fn get(&self, who: &Caller, uuid: Uuid) -> Result<Stored, StoreError> {
561        self.read_as(who, uuid, Action::Read)
562    }
563
564    /// Reads the current version of `uuid` as [`Store::get`] does, for a
565    /// caller about to show `part` of it: the same answer, recorded under
566    /// the reveal action of that part.
567    pub fn reveal(&self, who: &Caller, uuid: Uuid, part: Part) -> Result<Stored, StoreError> {
568        self.read_as(who, uuid, Action::Reveal(part))
569    }
570
571    /// Reads the current version of `uuid` as [`Store::get`] does, for a
572    /// caller that answers its masked view: the same body, recorded as
573    /// `read_masked`.
574    pub fn read_masked(&self, who: &Caller, uuid: Uuid) -> Result<Stored, StoreError> {
575        self.read_as(who, uuid, Action::ReadMasked)
576    }
577
578    /// The read behind `get`, `reveal` and `read_masked`: every outcome is recorded as
579    /// `action`.
580    fn read_as(&self, who: &Caller, uuid: Uuid, action: Action) -> Result<Stored, StoreError> {
581        loop {
582            // The first step only reads, and takes no write lock (on
583            // PostgreSQL, no lock on the tenant): the last step checks
584            // again under the lock, and records the read or its refusal.
585            let found = self.read(|tx| {
586                Ok(match state(tx, uuid)? {
587                    State::Live(version) => {
588                        #[cfg(test)]
589                        {
590                            let hook = self.hooks.in_first_step.lock().expect("hook").clone();
591                            if let Some(hook) = hook {
592                                hook();
593                            }
594                        }
595                        Some((version, version_row(tx, version)))
596                    }
597                    State::Gone | State::Absent => None,
598                })
599            })?;
600            let (version, opened, place) = match found {
601                Some((version, row)) => {
602                    let place = row.as_ref().ok().and_then(|r| r.place.clone());
603                    #[cfg(test)]
604                    {
605                        let hook = self.hooks.before_read.lock().expect("hook").take();
606                        if let Some(hook) = hook {
607                            hook();
608                        }
609                    }
610                    let opened = row.and_then(|row| {
611                        let body = self.open_version(uuid, version, &row)?;
612                        Ok(Stored {
613                            version,
614                            form: row.form,
615                            gzip: row.gzip,
616                            body,
617                        })
618                    });
619                    (Some(version), Some(opened), place)
620                }
621                None => (None, None, None),
622            };
623            self.pause();
624            #[cfg(test)]
625            {
626                let hook = self.hooks.before_confirm.lock().expect("hook").clone();
627                if let Some(hook) = hook {
628                    hook();
629                }
630            }
631            let read = group::Confirm {
632                key: who.key,
633                action,
634                uuid,
635                version,
636                opened: opened.as_ref().is_some_and(Result::is_ok),
637                place,
638            };
639            match self.group.confirm(self, read)? {
640                // The last step answers only a read that read a version, so
641                // `opened` holds that version's outcome; without one (no
642                // such step answers so) the read would start again.
643                group::Confirmed::Answer => match opened {
644                    Some(opened) => return opened,
645                    None => continue,
646                },
647                group::Confirmed::Again => continue,
648                group::Confirmed::Refused(error) => return Err(error),
649            }
650        }
651    }
652
653    /// Replaces the current version of `found.uuid`, if it is `if_match`
654    /// and neither signed nor encrypted. The caller has checked that the
655    /// body's uuid is the one asked for. The old version is hidden, and
656    /// kept for legal reads until it is purged. As in `create`, the state
657    /// is checked before sealing and again at the commit, so of two racing
658    /// replaces one wins and the other's object is removed.
659    pub fn replace(
660        &self,
661        who: &Caller,
662        if_match: VersionId,
663        found: &Inspection,
664        body: &[u8],
665    ) -> Result<VersionId, StoreError> {
666        let uuid = found.uuid;
667        let entry = |status, version| Entry {
668            actor: Actor::Key(who.key),
669            action: Action::Replace,
670            target: Some(uuid.to_string()),
671            version,
672            status,
673        };
674        let key_id = self.tenant_key.id();
675        let version = VersionId::generate();
676        // Why the state does not allow this replace, if it does not.
677        let refusal = |tx: &mut Tx| -> Result<Option<(u16, StoreError)>, StoreError> {
678            Ok(match state(tx, uuid)? {
679                State::Absent => Some((404, StoreError::NotFound)),
680                State::Gone => Some((410, StoreError::Gone)),
681                State::Live(current) if version_row(tx, current)?.form != vcon::Form::Unsigned => {
682                    Some((409, StoreError::Immutable))
683                }
684                State::Live(current) if current != if_match => {
685                    Some((412, StoreError::PreconditionFailed))
686                }
687                State::Live(_) => None,
688            })
689        };
690        {
691            let mut tx = self.catalog.immediate()?;
692            let refused = match refusal(&mut tx)? {
693                None if envelope::wrap_limit(tx.wraps(key_id)?) == WrapLimit::Refuse => {
694                    Some((503, StoreError::LimitReached))
695                }
696                other => other,
697            };
698            if let Some((status, error)) = refused {
699                self.record(&mut tx, &entry(status, None))?;
700                commit(tx)?;
701                return Err(error);
702            }
703            tx.add_wrap(key_id)?;
704            tx.add_pending(version, nanos(self.clock.now()))?;
705            commit(tx)?;
706        }
707
708        let wrapped = self.write_version(uuid, version, body)?;
709        self.pause();
710
711        let unknown = std::cell::Cell::new(false);
712        let committed = (|| {
713            let mut tx = self.catalog.immediate()?;
714            let mine = tx.drop_pending(version)?;
715            if let Some((status, error)) = refusal(&mut tx)? {
716                self.record(&mut tx, &entry(status, None))?;
717                commit(tx)?;
718                return Err(error);
719            }
720            if !mine {
721                // As in `create`: recovery removed the object.
722                self.record(&mut tx, &entry(500, None))?;
723                commit(tx)?;
724                return Err(StoreError::Io);
725            }
726            let now = self.now_in(tx.as_mut())?;
727            tx.insert_version(&NewVersion {
728                version,
729                uuid,
730                form: form_name(found.form),
731                gzip: found.gzip,
732                size: i64::try_from(body.len()).map_err(io)?,
733                stored_at: now,
734                key: key_id,
735                wrapped: &wrapped,
736            })?;
737            tx.hide_version(if_match, now)?;
738            tx.set_current(uuid, version)?;
739            self.record(&mut tx, &entry(200, Some(version)))?;
740            kept(tx.commit(), &unknown)?;
741            Ok(version)
742        })();
743        self.drop_unless_kept(committed.is_err(), unknown.get(), version);
744        #[cfg(test)]
745        if committed.is_ok() {
746            self.forced_pack();
747        }
748        committed
749    }
750
751    /// Deletes `uuid`: one transaction marks it deleted, empties its
752    /// current version and hides every kept version, with the audit
753    /// record. Its versions stay for legal reads until they are purged;
754    /// any already as old as `retention` is purged at once, so a zero
755    /// period erases the vCon inside the request.
756    /// Deleting a deleted or purged uuid succeeds again. A legal hold does
757    /// not stop a delete, only a purge.
758    pub fn delete(&self, who: &Caller, uuid: Uuid, retention: Retention) -> Result<(), StoreError> {
759        let entry = |status| Entry {
760            actor: Actor::Key(who.key),
761            action: Action::Delete,
762            target: Some(uuid.to_string()),
763            version: None,
764            status,
765        };
766        {
767            let mut tx = self.catalog.immediate()?;
768            let outcome = match state(&mut tx, uuid)? {
769                State::Absent => Err(StoreError::NotFound),
770                State::Gone => Ok(()),
771                State::Live(_) => {
772                    tx.mark_deleted(uuid, nanos(self.clock.now()))?;
773                    Ok(())
774                }
775            };
776            let status = if outcome.is_ok() { 204 } else { 404 };
777            self.record(&mut tx, &entry(status))?;
778            commit(tx)?;
779            outcome?;
780        }
781        // A version already as old as `retention` is erased now, not at
782        // the next sweep.
783        self.purge_hidden(Actor::Key(who.key), retention, Some(uuid))?;
784        Ok(())
785    }
786
787    /// Every version whose object is missing, or, for a packed version,
788    /// whose pack file is missing or not the length its row says. Such a
789    /// version answers 500 when read; it is reported, never dropped.
790    pub fn check(&self) -> Result<Vec<VersionId>, StoreError> {
791        let versions = self.read(|tx| tx.places())?;
792        let present: std::collections::BTreeSet<String> =
793            self.objects.list().map_err(io)?.into_iter().collect();
794        let mut whole = std::collections::HashMap::new();
795        let mut missing = Vec::new();
796        for (version, place) in versions {
797            let kept = match place {
798                Err(_) => false,
799                Ok(None) => present.contains(&version.to_string()),
800                Ok(Some(packed)) => match whole.get(&packed.file) {
801                    Some(&kept) => kept,
802                    None => {
803                        let kept = match &self.packs {
804                            None => false,
805                            Some(packs) => {
806                                let name = crate::backend::pack::name(&packed.date, packed.file);
807                                packs.size(&name).map_err(io)? == Some(packed.bytes)
808                            }
809                        };
810                        whole.insert(packed.file, kept);
811                        kept
812                    }
813                },
814            };
815            if !kept {
816                missing.push(version);
817            }
818        }
819        Ok(missing)
820    }
821
822    /// Seals `body` as a new version of `uuid` under a new data key, wraps
823    /// that key under the tenant key, and writes the object as `version`.
824    /// Returns the wrapped key.
825    fn write_version(
826        &self,
827        uuid: Uuid,
828        version: VersionId,
829        body: &[u8],
830    ) -> Result<Vec<u8>, StoreError> {
831        let ctx = Context::Version {
832            tenant: self.tenant,
833            uuid,
834            version,
835        };
836        let data_key = Key::generate().map_err(|_| StoreError::Io)?;
837        let blob = envelope::seal(&data_key, &ctx, body);
838        let wrapped = envelope::wrap(&self.tenant_key, &ctx, &data_key);
839        self.objects.put(version, &blob).map_err(io)?;
840        Ok(wrapped)
841    }
842
843    /// Removes a new version's object when the write failed and its rows
844    /// were surely not kept. After a commit whose outcome is unknown the
845    /// object stays: its rows may be kept, and a row without its object is
846    /// damage, while an object without a row is a leftover that start-up
847    /// recovery removes.
848    fn drop_unless_kept(&self, failed: bool, unknown: bool, version: VersionId) {
849        if failed && !unknown {
850            // Best effort: start-up recovery removes any object left over.
851            let _ = self.objects.remove(version);
852        }
853    }
854
855    /// In tests, runs the hook set for the gap between work done outside
856    /// the catalog lock and the transaction that confirms it.
857    fn pause(&self) {
858        #[cfg(test)]
859        {
860            let hook = self.hooks.between.lock().expect("hook").take();
861            if let Some(hook) = hook {
862                hook();
863            }
864        }
865    }
866
867    /// The plaintext of a stored version. A missing row or object, or one
868    /// that does not open, is damage; a read the storage fails is Io.
869    fn read_version(
870        &self,
871        tx: &mut Tx,
872        uuid: Uuid,
873        version: VersionId,
874    ) -> Result<Vec<u8>, StoreError> {
875        self.read_or_why(tx, uuid, version)
876            .map_err(Unopened::into_store)
877    }
878
879    /// `read_version`, keeping a storage failure as the storage's error.
880    fn read_or_why(
881        &self,
882        tx: &mut Tx,
883        uuid: Uuid,
884        version: VersionId,
885    ) -> Result<Vec<u8>, Unopened> {
886        let row = version_row(tx, version)?;
887        self.open_or_why(uuid, version, &row)
888    }
889
890    /// Opens a version's sealed blob, from its object or its pack file,
891    /// with its wrapped data key.
892    fn open_version(
893        &self,
894        uuid: Uuid,
895        version: VersionId,
896        row: &VersionRow,
897    ) -> Result<Vec<u8>, StoreError> {
898        self.open_or_why(uuid, version, row)
899            .map_err(Unopened::into_store)
900    }
901
902    /// `open_version`, keeping a storage failure as the storage's error,
903    /// for `examine`, which reports its kind.
904    fn open_or_why(
905        &self,
906        uuid: Uuid,
907        version: VersionId,
908        row: &VersionRow,
909    ) -> Result<Vec<u8>, Unopened> {
910        let ctx = Context::Version {
911            tenant: self.tenant,
912            uuid,
913            version,
914        };
915        let data_key =
916            envelope::unwrap(&self.tenant_key, &ctx, &row.wrapped).map_err(key_failed)?;
917        let blob = match self.sealed_blob(version, row.place.as_ref()) {
918            Ok(blob) => blob,
919            Err(packed::Unread::Object(ObjectError::Io(e))) => return Err(Unopened::Storage(e)),
920            Err(other) => return Err(Unopened::Store(other.into_store())),
921        };
922        Ok(envelope::open(&data_key, &ctx, &blob).map_err(|_| StoreError::Damaged)?)
923    }
924
925    /// How many versions are packed into pack files: once there are any,
926    /// the storage must keep Parquet storage on, since nothing turns them
927    /// back into objects.
928    pub fn packed_versions(&self) -> Result<u64, StoreError> {
929        self.read(|tx| tx.count_packed())
930    }
931
932    /// Waits until every commit this Store made is durable and answers
933    /// whether it is (Io: a sync failed, and a commit may be lost). For a
934    /// caller that closes an idle store: it calls this, begins nothing
935    /// more, and drops the Store. Dropping without it stays safe: every
936    /// commit has already waited for its own sync.
937    pub fn close(&self) -> Result<(), StoreError> {
938        self.catalog.close()
939    }
940
941    /// How many versions the Store keeps and how many uuids are held.
942    pub fn counts(&self) -> Result<Counts, StoreError> {
943        self.read(|tx| {
944            Ok(Counts {
945                versions: tx.count_versions()?,
946                held: tx.count_held()?,
947            })
948        })
949    }
950
951    /// Runs `read` in a snapshot and ends it (CatalogTx::end): what it
952    /// returns is given back only once every commit it may have seen is
953    /// durable, so nothing answered or done after it rests on a commit that
954    /// may be lost. A failed end overrides the result.
955    pub(crate) fn read<T>(
956        &self,
957        read: impl FnOnce(&mut Tx<'_>) -> Result<T, StoreError>,
958    ) -> Result<T, StoreError> {
959        let mut tx = self.catalog.snapshot()?;
960        let out = read(&mut tx);
961        tx.end()?;
962        out
963    }
964
965    /// Writes the tenant's log after `since` as JSON lines, oldest first.
966    /// Not recorded: reading the log changes nothing.
967    pub fn export(
968        &self,
969        since: Option<i64>,
970        out: &mut dyn std::io::Write,
971    ) -> Result<(), audit::AuditError> {
972        self.catalog.export(since.unwrap_or(0), out)
973    }
974
975    /// A page of the tenant's log as JSON lines, the lines `export` writes
976    /// for the same records. The read is recorded as audit_read in the same
977    /// log and transaction, after the page is read, so a page never holds
978    /// its own record.
979    pub fn audit_page(
980        &self,
981        who: &Caller,
982        query: &audit::AuditQuery,
983    ) -> Result<Vec<u8>, StoreError> {
984        let mut tx = self.catalog.immediate()?;
985        let mut out = Vec::new();
986        let read = tx.audit_lines(query.after, Some(query.limit), &mut out);
987        self.record(
988            &mut tx,
989            &Entry {
990                actor: Actor::Key(who.key),
991                action: Action::AuditRead,
992                target: None,
993                version: None,
994                status: if read.is_ok() { 200 } else { 500 },
995            },
996        )?;
997        commit(tx)?;
998        read.map(|()| out).map_err(io)
999    }
1000
1001    /// Records, in a transaction of its own, an action on the tenant taken
1002    /// elsewhere, such as a change to its retention period.
1003    pub fn log(&self, entry: &Entry) -> Result<(), StoreError> {
1004        let mut tx = self.catalog.immediate()?;
1005        self.record(&mut tx, entry)?;
1006        commit(tx)
1007    }
1008
1009    #[cfg(test)]
1010    pub(crate) fn break_audit(&self) {
1011        self.conn()
1012            .execute_batch(
1013                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
1014                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
1015            )
1016            .expect("trigger");
1017    }
1018
1019    /// For tests: after every write that adds a version, a pack run with
1020    /// `plan`, so each version is packed before the next step. Pack
1021    /// storage is S3's, so only an S3 build's harnesses call it.
1022    #[cfg(all(test, feature = "s3"))]
1023    pub(crate) fn pack_after_every_write(&mut self, plan: packer::PackPlan) {
1024        *self.hooks.pack_always.lock().expect("hook") = Some(plan);
1025    }
1026
1027    #[cfg(test)]
1028    fn forced_pack(&self) {
1029        let plan = *self.hooks.pack_always.lock().expect("hook");
1030        if let Some(plan) = plan {
1031            self.pack(&plan).expect("the forced pack run");
1032        }
1033    }
1034
1035    /// In tests, sets the hook every read runs after its first step and
1036    /// before its last; None removes it. The live PostgreSQL read tests
1037    /// use it.
1038    #[cfg(all(test, feature = "postgres", feature = "backend-tests"))]
1039    pub(crate) fn on_last_step(&self, hook: Option<Arc<dyn Fn() + Send + Sync>>) {
1040        *self.hooks.before_confirm.lock().expect("hook") = hook;
1041    }
1042
1043    /// In tests, sets the hook every read runs in its first step, after it
1044    /// finds the vCon's current version and before it reads that
1045    /// version's row; None removes it.
1046    #[cfg(all(test, feature = "postgres", feature = "backend-tests"))]
1047    pub(crate) fn in_first_step(&self, hook: Option<Arc<dyn Fn() + Send + Sync>>) {
1048        *self.hooks.in_first_step.lock().expect("hook") = hook;
1049    }
1050
1051    /// In tests, sets the hook the next read runs once, after its first
1052    /// step and before it opens the version's body.
1053    #[cfg(all(test, feature = "postgres", feature = "backend-tests"))]
1054    pub(crate) fn once_before_open(&self, hook: Box<dyn FnOnce() + Send>) {
1055        *self.hooks.before_read.lock().expect("hook") = Some(hook);
1056    }
1057
1058    /// Sets the hook a write runs once, between its object and its last
1059    /// transaction.
1060    #[cfg(test)]
1061    pub(crate) fn on_between(&self, hook: Box<dyn FnOnce() + Send>) {
1062        *self.hooks.between.lock().expect("hook") = Some(hook);
1063    }
1064
1065    /// The catalog's pending rows, for tests.
1066    #[cfg(test)]
1067    pub(crate) fn pending_writes(&self) -> Result<Vec<(VersionId, i64)>, StoreError> {
1068        self.read(|tx| tx.pending())
1069    }
1070
1071    #[cfg(test)]
1072    pub(crate) fn on_backup_copied(&self, hook: tests::BackupHook) {
1073        *self.hooks.copied.lock().expect("hook") = Some(hook);
1074    }
1075
1076    #[cfg(test)]
1077    pub(crate) fn conn_for_test(&self) -> MutexGuard<'_, LocalConn> {
1078        self.conn()
1079    }
1080
1081    #[cfg(test)]
1082    pub(crate) fn records(&self) -> Vec<serde_json::Value> {
1083        crate::audit::testing::exported(&self.conn(), None)
1084    }
1085
1086    /// Counts, in a transaction of its own, an event the tenant's log
1087    /// keeps one record per minute for, such as a failed check of one of
1088    /// its keys.
1089    pub fn count(&self, entry: &Entry) -> Result<(), StoreError> {
1090        let mut tx = self.catalog.immediate()?;
1091        tx.count(entry, self.clock.now())
1092            .map_err(|_| StoreError::AuditFailed)?;
1093        commit(tx)
1094    }
1095
1096    /// Writes an audit record in `tx`; if it cannot, nothing is done.
1097    /// The time given is this process's clock, which a data directory's
1098    /// log keeps; a database's log writes the transaction's reading of
1099    /// its own clock instead, in the statement, so the record costs no
1100    /// reading of its own: a purge's record is judged against the time
1101    /// the tenant's key was rotated, which another server may have
1102    /// written.
1103    fn record(&self, tx: &mut Tx, entry: &Entry) -> Result<(), StoreError> {
1104        tx.record(entry, self.clock.now())
1105            .map_err(|_| StoreError::AuditFailed)
1106    }
1107
1108    /// The local catalog's connection, for tests.
1109    #[cfg(test)]
1110    fn conn(&self) -> MutexGuard<'_, LocalConn> {
1111        self.catalog.local_conn()
1112    }
1113}
1114
1115enum State {
1116    Absent,
1117    Live(VersionId),
1118    Gone,
1119}
1120
1121/// A uuid's state: purged or deleted is Gone. A row that is neither
1122/// deleted nor current is damage.
1123fn state(tx: &mut Tx, uuid: Uuid) -> Result<State, StoreError> {
1124    if tx.tombstoned(uuid)? {
1125        return Ok(State::Gone);
1126    }
1127    match tx.vcon_row(uuid)? {
1128        None => Ok(State::Absent),
1129        Some(row) if row.deleted_at.is_some() => Ok(State::Gone),
1130        Some(row) => row.current.map(State::Live).ok_or(StoreError::Damaged),
1131    }
1132}
1133
1134/// Whether a version row, with `place` as its place, names the version's
1135/// object: unless the row says the version is packed. A row whose place is
1136/// broken names its object, which is kept, since damage is reported and
1137/// never removed.
1138fn names_its_object(place: &Result<Option<Packed>, StoreError>) -> bool {
1139    !matches!(place, Ok(Some(_)))
1140}
1141
1142struct VersionRow {
1143    form: vcon::Form,
1144    gzip: bool,
1145    wrapped: Vec<u8>,
1146    place: Option<Packed>,
1147}
1148
1149/// A version's row; one missing, or with a form this build does not
1150/// know, is damage.
1151fn version_row(tx: &mut Tx, version: VersionId) -> Result<VersionRow, StoreError> {
1152    let row = tx.version_row(version)?.ok_or(StoreError::Damaged)?;
1153    let form = match row.form.as_str() {
1154        "unsigned" => vcon::Form::Unsigned,
1155        "signed" => vcon::Form::Signed,
1156        "encrypted" => vcon::Form::Encrypted,
1157        _ => return Err(StoreError::Damaged),
1158    };
1159    Ok(VersionRow {
1160        form,
1161        gzip: row.gzip,
1162        wrapped: row.wrapped,
1163        place: row.place,
1164    })
1165}
1166
1167fn commit(tx: Tx) -> Result<(), StoreError> {
1168    tx.commit().map_err(io)
1169}
1170
1171/// The commit that adds a version's rows: an error is Io, and one whose
1172/// outcome is unknown is noted in `unknown`, since its rows may be kept.
1173fn kept(
1174    outcome: Result<(), CommitError>,
1175    unknown: &std::cell::Cell<bool>,
1176) -> Result<(), StoreError> {
1177    outcome.map_err(|e| {
1178        unknown.set(e == CommitError::Unknown);
1179        StoreError::Io
1180    })
1181}
1182
1183/// A wrapped data key that did not open: damage if it does not open under
1184/// the tenant key, and Io if its memory could not be locked.
1185fn key_failed(e: envelope::KeyError) -> StoreError {
1186    match e {
1187        envelope::KeyError::Damaged => StoreError::Damaged,
1188        _ => StoreError::Io,
1189    }
1190}
1191
1192/// A read of the object a version row names that failed: an object the
1193/// storage does not hold is damage; any other failure (a disk error, a
1194/// refused key, no answer in time) says nothing about the stored data, so
1195/// it is Io and is logged by its kind. Its text is not logged: a service's
1196/// message may name the object's key.
1197fn read_failed(e: ObjectError) -> StoreError {
1198    match e {
1199        ObjectError::Missing => StoreError::Damaged,
1200        ObjectError::Io(e) => {
1201            storage_failed(&e);
1202            StoreError::Io
1203        }
1204    }
1205}
1206
1207/// Logs a read the storage failed by the error's kind and system error
1208/// number only: its text is not logged, since a service's message may name
1209/// the object's key.
1210fn storage_failed(e: &std::io::Error) {
1211    tracing::warn!(
1212        kind = %e.kind(),
1213        os_error = e.raw_os_error(),
1214        "a stored version's object could not be read"
1215    );
1216}
1217
1218/// Why a version's blob did not open: as a read answers it, or a failure
1219/// of the storage itself, kept so `examine` can report its kind.
1220#[derive(Debug)]
1221enum Unopened {
1222    Store(StoreError),
1223    Storage(std::io::Error),
1224}
1225
1226impl Unopened {
1227    /// How a read answers: a storage failure is logged by its kind and is
1228    /// Io, as `read_failed` has it.
1229    fn into_store(self) -> StoreError {
1230        match self {
1231            Unopened::Store(e) => e,
1232            Unopened::Storage(e) => read_failed(ObjectError::Io(e)),
1233        }
1234    }
1235}
1236
1237impl From<StoreError> for Unopened {
1238    fn from(e: StoreError) -> Unopened {
1239        Unopened::Store(e)
1240    }
1241}
1242
1243fn io<E>(_: E) -> StoreError {
1244    StoreError::Io
1245}
1246
1247/// The name the catalog stores for `form`.
1248fn form_name(form: vcon::Form) -> &'static str {
1249    form.as_str()
1250}
1251
1252impl From<ObjectError> for StoreError {
1253    fn from(_: ObjectError) -> StoreError {
1254        StoreError::Io
1255    }
1256}
1257
1258#[cfg(test)]
1259pub(crate) mod testing {
1260    use std::collections::BTreeSet;
1261
1262    use vcon::Form;
1263    use vcon::read::{Inspection, Limits, inspect};
1264
1265    /// An unsigned vCon with this uuid, and what `inspect` makes of it.
1266    pub(crate) fn vcon(uuid: &str, subject: &str) -> (Inspection, Vec<u8>) {
1267        let body = format!(
1268            r#"{{"uuid": "{uuid}", "created_at": "2026-10-23T12:00:00Z", "subject": "{subject}", "parties": []}}"#
1269        )
1270        .into_bytes();
1271        let found =
1272            inspect(&body, None, &Limits::new(1 << 20), &BTreeSet::new()).expect("a valid vCon");
1273        assert_eq!(found.form, Form::Unsigned);
1274        (found, body)
1275    }
1276}
1277
1278#[cfg(test)]
1279pub(crate) mod tests {
1280    use std::collections::BTreeSet;
1281
1282    use serde_json::Value;
1283    use time::macros::datetime;
1284    use vcon::read::{Limits, inspect};
1285
1286    use super::testing::vcon;
1287    use super::*;
1288    use crate::audit::testing::exported;
1289
1290    /// Each version is written into objects/: a Store that may not write
1291    /// there does not open, and says so with the path and the system's
1292    /// error, as it does for its catalog.
1293    #[test]
1294    fn an_objects_directory_the_process_may_not_write_is_named() {
1295        use std::os::unix::fs::PermissionsExt;
1296        let f = fixture();
1297        let objects = f.dir.path().join("objects");
1298        let mode = |m| {
1299            std::fs::set_permissions(&objects, std::fs::Permissions::from_mode(m)).expect("chmod")
1300        };
1301        mode(0o500);
1302        let refused = f.open_or_why();
1303        mode(0o700);
1304        match refused {
1305            Err(OpenError::Access { path, error }) => {
1306                assert_eq!(path, objects);
1307                assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1308            }
1309            other => panic!("{:?}", other.map(|_| "opened")),
1310        }
1311        assert!(f.open_or_why().is_ok(), "opens once allowed");
1312    }
1313    use crate::catalog::testing::columns_taking_null;
1314    use crate::clock::ManualClock;
1315    use rusqlite::{Connection, params};
1316
1317    use crate::catalog;
1318    use crate::fs::{CrashFs, Op};
1319
1320    const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
1321
1322    /// What a backup runs at each try, after it copies the catalog.
1323    pub(crate) type BackupHook = Box<dyn FnMut(&Store) + Send>;
1324
1325    /// What a hook that runs once inside the Store is given: the Store.
1326    pub(crate) type StoreHook = Box<dyn FnOnce(&Store) + Send>;
1327
1328    /// Test-only points where a test can step in.
1329    #[derive(Default)]
1330    pub(super) struct Hooks {
1331        /// Runs once, between work done outside the catalog lock (a
1332        /// write's files, a read's decryption) and the transaction that
1333        /// confirms it.
1334        pub(super) between: Mutex<Option<Box<dyn FnOnce() + Send>>>,
1335        /// Runs at each try of a backup, after the catalog is copied and
1336        /// before its versions' files are.
1337        pub(super) copied: Mutex<Option<BackupHook>>,
1338        /// Runs once, in a read, between the transaction that finds the
1339        /// version's place and the read of its blob.
1340        pub(super) before_read: Mutex<Option<Box<dyn FnOnce() + Send>>>,
1341        /// A pack run after every write that adds a version.
1342        pub(super) pack_always: Mutex<Option<super::packer::PackPlan>>,
1343        /// Runs in every read, after its body is read and before it joins
1344        /// the queue for its last step.
1345        pub(super) before_confirm: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
1346        /// Runs in every read's first step, between the read of the
1347        /// vCon's current version and the read of that version's row.
1348        pub(super) in_first_step: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
1349        /// Runs once, in recovery, after it reads the catalog's rows and
1350        /// before it removes anything.
1351        pub(super) after_snapshot: Mutex<Option<StoreHook>>,
1352        /// Nanoseconds added to the next readings of the catalog's clock
1353        /// ([`Store::now_in`], recovery's too), one per reading, in order:
1354        /// time passing on the clock, which no test can make a database's
1355        /// clock do.
1356        pub(super) clock_steps: Mutex<Vec<i64>>,
1357    }
1358
1359    impl Store {
1360        /// Adds `steps` to the next readings of the catalog's clock, one
1361        /// per reading, in order ([`Hooks::clock_steps`]).
1362        pub(crate) fn step_clock(&self, steps: Vec<i64>) {
1363            *self.hooks.clock_steps.lock().expect("hook") = steps;
1364        }
1365    }
1366
1367    pub(crate) struct Fixture {
1368        pub(crate) dir: tempfile::TempDir,
1369        pub(crate) fs: Arc<CrashFs>,
1370        pub(crate) clock: Arc<ManualClock>,
1371        /// The tenant key, wrapped under `master`, so a test can open the
1372        /// store again with the same key.
1373        master: Key,
1374        wrapped: Vec<u8>,
1375        pub(crate) store: Store,
1376        pub(crate) caller: Caller,
1377        /// The pack storage the Store is opened with, as an S3 store is;
1378        /// None, as a local one is.
1379        pub(crate) packs: Option<Arc<dyn Packs>>,
1380    }
1381
1382    pub(super) const TENANT: TenantId = TenantId([0x11; 16]);
1383
1384    impl Fixture {
1385        pub(super) fn open(&self) -> Result<Store, StoreError> {
1386            self.open_or_why().map_err(StoreError::from)
1387        }
1388
1389        /// `open`, saying why a Store that did not open did not.
1390        pub(super) fn open_or_why(&self) -> Result<Store, OpenError> {
1391            let ctx = Context::Tenant { tenant: TENANT };
1392            let tenant_key = envelope::unwrap(&self.master, &ctx, &self.wrapped).expect("unwraps");
1393            // As `Store::open` does, with the fixture's pack storage given
1394            // before recovery runs.
1395            let mut store = Store::open_beside(
1396                self.dir.path(),
1397                TENANT,
1398                tenant_key,
1399                self.fs.clone(),
1400                self.clock.clone(),
1401            )?;
1402            store.packs = self.packs.clone();
1403            store.recover(super::pending::Writers::None)?;
1404            Ok(store)
1405        }
1406
1407        /// The tenant key the Store was made under.
1408        pub(crate) fn tenant_key(&self) -> Key {
1409            let ctx = Context::Tenant { tenant: TENANT };
1410            envelope::unwrap(&self.master, &ctx, &self.wrapped).expect("unwraps")
1411        }
1412
1413        pub(crate) fn tenant(&self) -> TenantId {
1414            TENANT
1415        }
1416
1417        /// The directory of the Store's object files.
1418        pub(crate) fn store_objects_dir(&self) -> PathBuf {
1419            self.store.objects_dir.clone()
1420        }
1421
1422        /// A second Store on the same catalog and objects, opened as a
1423        /// command beside a server opens one: for a test that must hand a
1424        /// Store to another thread.
1425        pub(crate) fn open_beside_store(&self) -> Store {
1426            self.open_beside().expect("opens beside")
1427        }
1428
1429        /// Opens the store again as a command beside a server would.
1430        fn open_beside(&self) -> Result<Store, StoreError> {
1431            let ctx = Context::Tenant { tenant: TENANT };
1432            let tenant_key = envelope::unwrap(&self.master, &ctx, &self.wrapped).expect("unwraps");
1433            Store::open_beside(
1434                self.dir.path(),
1435                TENANT,
1436                tenant_key,
1437                self.fs.clone(),
1438                self.clock.clone(),
1439            )
1440            .map_err(StoreError::from)
1441        }
1442
1443        /// Closes the store and opens it again, as a restart would.
1444        pub(super) fn reopen(&mut self) {
1445            let placeholder = self.open().expect("opens");
1446            drop(std::mem::replace(&mut self.store, placeholder));
1447            self.store = self.open().expect("reopens");
1448        }
1449    }
1450
1451    pub(crate) fn fixture() -> Fixture {
1452        let dir = tempfile::tempdir().expect("temp dir");
1453        let fs = Arc::new(CrashFs::new(dir.path()));
1454        let clock = Arc::new(ManualClock::at(datetime!(2026-10-23 12:00 UTC)));
1455        let master = Key::generate().expect("master key");
1456        let tenant_key = Key::generate().expect("tenant key");
1457        let wrapped = envelope::wrap(&master, &Context::Tenant { tenant: TENANT }, &tenant_key);
1458        let store =
1459            Store::open(dir.path(), TENANT, tenant_key, fs.clone(), clock.clone()).expect("opens");
1460        let caller = Caller {
1461            key: Key::generate().expect("caller key").id(),
1462        };
1463        Fixture {
1464            dir,
1465            fs,
1466            clock,
1467            master,
1468            wrapped,
1469            store,
1470            caller,
1471            packs: None,
1472        }
1473    }
1474
1475    fn audit_log(store: &Store) -> Vec<Value> {
1476        exported(&store.conn(), None)
1477    }
1478
1479    fn count(store: &Store, sql: &str) -> i64 {
1480        store.conn().query_row(sql, [], |r| r.get(0)).expect(sql)
1481    }
1482
1483    fn wraps(store: &Store) -> i64 {
1484        store
1485            .conn()
1486            .query_row("SELECT coalesce(sum(wraps), 0) FROM key_use", [], |r| {
1487                r.get(0)
1488            })
1489            .expect("wraps")
1490    }
1491
1492    /// The body the store holds for `version`, opened as `get` will.
1493    fn stored_body(f: &Fixture, uuid: Uuid, version: VersionId) -> Vec<u8> {
1494        let wrapped: Vec<u8> = f
1495            .store
1496            .conn()
1497            .query_row(
1498                "SELECT wrapped_key FROM version WHERE version = ?1",
1499                [version.0],
1500                |r| r.get(0),
1501            )
1502            .expect("row");
1503        let ctx = Context::Version {
1504            tenant: f.store.tenant,
1505            uuid,
1506            version,
1507        };
1508        let data_key = envelope::unwrap(&f.store.tenant_key, &ctx, &wrapped).expect("unwraps");
1509        let blob =
1510            f.fs.read(&f.store.objects_dir.join(version.to_string()))
1511                .expect("file");
1512        envelope::open(&data_key, &ctx, &blob).expect("opens")
1513    }
1514
1515    fn audit_page(f: &Fixture, after: i64, limit: u32) -> Result<Vec<u8>, StoreError> {
1516        f.store
1517            .audit_page(&f.caller, &audit::AuditQuery { after, limit })
1518    }
1519
1520    fn export_text(store: &Store, since: Option<i64>) -> Vec<u8> {
1521        let mut out = Vec::new();
1522        store.export(since, &mut out).expect("export");
1523        out
1524    }
1525
1526    #[test]
1527    fn an_audit_page_is_export_s_lines_and_records_its_read_after_them() {
1528        let f = fixture();
1529        for n in 0..3 {
1530            let (found, body) = vcon(&format!("01a07da8-c2bb-83e5-b9a2-27900000000{n}"), "x");
1531            f.store.create(&f.caller, &found, &body).expect("stored");
1532        }
1533        let before = export_text(&f.store, None);
1534        assert_eq!(audit_page(&f, 0, 1000), Ok(before.clone()));
1535        let read = audit_log(&f.store);
1536        assert_eq!(read.len(), 4, "three creates and the read");
1537        assert_eq!(read[3]["action"], "audit_read");
1538        assert_eq!(read[3]["actor"], f.caller.key.to_string());
1539        assert_eq!(read[3]["status"], 200);
1540        assert_eq!(read[3]["seq"], 4);
1541        assert_eq!(read[3]["target"], Value::Null);
1542        // A page of two from seq 1: the second and third creates.
1543        let lines: Vec<&[u8]> = before.split_inclusive(|b| *b == b'\n').collect();
1544        assert_eq!(audit_page(&f, 1, 2), Ok(lines[1..3].concat()));
1545        // Past the end: nothing but the earlier reads' records.
1546        let tail = audit_page(&f, 4, 1000).expect("a page");
1547        assert_eq!(tail, export_text(&f.store, Some(4))[..tail.len()]);
1548        assert_eq!(String::from_utf8(tail).expect("UTF-8").lines().count(), 1);
1549    }
1550
1551    /// A record that cannot be read back (a status past any HTTP status)
1552    /// fails the page, and the read is still recorded, as 500.
1553    #[test]
1554    fn an_audit_page_that_cannot_be_read_is_a_failure_and_recorded() {
1555        let f = fixture();
1556        f.store
1557            .conn_for_test()
1558            .execute(
1559                "INSERT INTO audit (at, actor, action, status, count)
1560                 VALUES ('2026-10-23T12:00:00Z', 'cli', 'read', 70000, 1)",
1561                [],
1562            )
1563            .expect("damaged");
1564        assert_eq!(audit_page(&f, 0, 10), Err(StoreError::Io));
1565        let mut recorded = Vec::new();
1566        f.store.export(Some(1), &mut recorded).expect("export");
1567        let recorded: Value = serde_json::from_slice(&recorded).expect("one record");
1568        assert_eq!(recorded["action"], "audit_read");
1569        assert_eq!(recorded["status"], 500);
1570    }
1571
1572    #[test]
1573    fn an_audit_page_whose_record_fails_is_refused() {
1574        let f = fixture();
1575        f.store.break_audit();
1576        assert_eq!(audit_page(&f, 0, 10), Err(StoreError::AuditFailed));
1577    }
1578
1579    /// The tenant catalog's WAL, whose syncs the crash filesystem logs.
1580    pub(super) fn wal(f: &Fixture) -> std::path::PathBuf {
1581        f.dir.path().join("catalog.sqlite-wal")
1582    }
1583
1584    /// Since log entry `ops`, a refused or unchanged request wrote no file:
1585    /// the one entry is the sync of the commit holding its audit record,
1586    /// made before the answer was returned.
1587    fn only_its_record_synced(f: &Fixture, ops: usize) {
1588        assert_eq!(
1589            f.fs.log()[ops..],
1590            [Op::SyncData(wal(f))],
1591            "no file written; the record's commit synced before the answer"
1592        );
1593    }
1594
1595    #[test]
1596    fn a_new_vcon_is_written_in_order_and_recorded() {
1597        let f = fixture();
1598        let (found, body) = vcon(UUID, "first");
1599        let ops = f.fs.log().len();
1600        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1601            panic!("a new vCon")
1602        };
1603        let (tmp, done) = (
1604            f.store.objects_dir.join(format!("{version}.tmp")),
1605            f.store.objects_dir.join(version.to_string()),
1606        );
1607        assert_eq!(
1608            f.fs.log()[ops..],
1609            [
1610                // The pending row's commit is durable before the object is
1611                // written, so recovery never takes the object for a leftover.
1612                Op::SyncData(wal(&f)),
1613                Op::Write(tmp.clone()),
1614                Op::SyncFile(tmp.clone()),
1615                Op::Rename(tmp, done),
1616                Op::SyncDir(f.store.objects_dir.clone()),
1617                // The version's row and its record: synced before the answer.
1618                Op::SyncData(wal(&f)),
1619            ],
1620            "every change and sync of a create, in order"
1621        );
1622        assert_eq!(
1623            f.fs.log().len() - ops,
1624            WRITE_STEPS,
1625            "the steps a cut can hit"
1626        );
1627        assert_eq!(stored_body(&f, found.uuid, version), body);
1628        assert_eq!(
1629            count(
1630                &f.store,
1631                "SELECT count(*) FROM version WHERE hidden_at IS NULL"
1632            ),
1633            1
1634        );
1635        let current: Vec<u8> = f
1636            .store
1637            .conn()
1638            .query_row(
1639                "SELECT current FROM vcon WHERE uuid = ?1",
1640                [found.uuid.as_bytes()],
1641                |r| r.get(0),
1642            )
1643            .expect("vcon row");
1644        assert_eq!(current, version.0);
1645        assert_eq!(wraps(&f.store), 1, "one data key wrapped");
1646        let log = audit_log(&f.store);
1647        assert_eq!(log.len(), 1);
1648        assert_eq!(log[0]["action"], "create");
1649        assert_eq!(log[0]["actor"], f.caller.key.to_string());
1650        assert_eq!(log[0]["target"], UUID);
1651        assert_eq!(log[0]["version"], version.to_string());
1652        assert_eq!(log[0]["status"], 201);
1653    }
1654
1655    #[test]
1656    fn a_replace_is_written_in_order_and_synced() {
1657        let f = fixture();
1658        let (found, old) = stored(&f, "first");
1659        let (_, newer) = vcon(UUID, "second");
1660        let ops = f.fs.log().len();
1661        let version = f
1662            .store
1663            .replace(&f.caller, old, &found, &newer)
1664            .expect("replaced");
1665        let (tmp, done) = (
1666            f.store.objects_dir.join(format!("{version}.tmp")),
1667            f.store.objects_dir.join(version.to_string()),
1668        );
1669        assert_eq!(
1670            f.fs.log()[ops..],
1671            [
1672                Op::SyncData(wal(&f)),
1673                Op::Write(tmp.clone()),
1674                Op::SyncFile(tmp.clone()),
1675                Op::Rename(tmp, done),
1676                Op::SyncDir(f.store.objects_dir.clone()),
1677                Op::SyncData(wal(&f)),
1678            ],
1679            "every change and sync of a replace, in order"
1680        );
1681        assert_eq!(
1682            f.fs.log().len() - ops,
1683            REPLACE_STEPS,
1684            "the steps a cut can hit"
1685        );
1686    }
1687
1688    #[test]
1689    fn the_same_body_again_is_same_and_writes_nothing() {
1690        let f = fixture();
1691        let (found, body) = vcon(UUID, "first");
1692        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1693            panic!("a new vCon")
1694        };
1695        let ops = f.fs.log().len();
1696        assert_eq!(
1697            f.store.create(&f.caller, &found, &body),
1698            Ok(Created::Same(version))
1699        );
1700        only_its_record_synced(&f, ops);
1701        assert_eq!(count(&f.store, "SELECT count(*) FROM version"), 1);
1702        assert_eq!(wraps(&f.store), 1, "nothing wrapped");
1703        let log = audit_log(&f.store);
1704        assert_eq!(
1705            (log[1]["status"].clone(), log[1]["version"].clone()),
1706            (200.into(), version.to_string().into())
1707        );
1708    }
1709
1710    #[test]
1711    fn another_body_for_a_stored_uuid_is_a_conflict_and_writes_nothing() {
1712        let f = fixture();
1713        let (found, body) = vcon(UUID, "first");
1714        f.store.create(&f.caller, &found, &body).expect("stored");
1715        let ops = f.fs.log().len();
1716        // The same length as the first body, so only the bytes differ.
1717        let (found, other) = vcon(UUID, "other");
1718        assert_eq!(
1719            f.store.create(&f.caller, &found, &other),
1720            Err(StoreError::Conflict)
1721        );
1722        only_its_record_synced(&f, ops);
1723        assert_eq!(wraps(&f.store), 1, "nothing wrapped");
1724        assert_eq!(audit_log(&f.store)[1]["status"], 409);
1725    }
1726
1727    #[test]
1728    fn a_deleted_or_purged_uuid_is_gone_and_writes_nothing() {
1729        for sql in [
1730            "INSERT INTO vcon (uuid, current, deleted_at) VALUES (?1, NULL, 1)",
1731            "INSERT INTO tombstone (uuid, purged_at) VALUES (?1, 1)",
1732        ] {
1733            let f = fixture();
1734            let (found, body) = vcon(UUID, "first");
1735            f.store
1736                .conn()
1737                .execute(sql, [found.uuid.as_bytes()])
1738                .expect(sql);
1739            let ops = f.fs.log().len();
1740            assert_eq!(
1741                f.store.create(&f.caller, &found, &body),
1742                Err(StoreError::Gone),
1743                "{sql}"
1744            );
1745            only_its_record_synced(&f, ops);
1746            assert_eq!(wraps(&f.store), 0, "nothing wrapped");
1747            assert_eq!(audit_log(&f.store)[0]["status"], 410);
1748        }
1749    }
1750
1751    #[test]
1752    fn counts_include_hidden_versions_and_held_uuids() {
1753        let f = fixture();
1754        let none = Counts {
1755            versions: 0,
1756            held: 0,
1757        };
1758        assert_eq!(f.store.counts(), Ok(none));
1759        let (found, old) = stored(&f, "first");
1760        let (_, newer) = vcon(UUID, "second");
1761        f.store
1762            .replace(&f.caller, old, &found, &newer)
1763            .expect("replaced");
1764        f.store
1765            .delete(&f.caller, found.uuid, Retention::Years(7))
1766            .expect("deleted");
1767        let (other, body) = vcon("01a07da8-c2bb-83e5-b9a2-279e0d16bc47", "other");
1768        f.store.create(&f.caller, &other, &body).expect("stored");
1769        assert_eq!(
1770            f.store.counts(),
1771            Ok(Counts {
1772                versions: 3,
1773                held: 0
1774            }),
1775            "two hidden versions and a live one"
1776        );
1777        f.store
1778            .conn()
1779            .execute(
1780                "UPDATE vcon SET hold = 1 WHERE uuid = ?1",
1781                [found.uuid.as_bytes()],
1782            )
1783            .expect("a hold");
1784        assert_eq!(f.store.counts().map(|c| c.held), Ok(1));
1785    }
1786
1787    #[test]
1788    fn a_negative_wrap_count_is_damage_and_stores_nothing() {
1789        let f = fixture();
1790        f.store
1791            .conn()
1792            .execute(
1793                "INSERT INTO key_use (tenant_key_id, wraps) VALUES (?1, -1)",
1794                [f.store.tenant_key.id().bytes()],
1795            )
1796            .expect("a damaged count");
1797        let (found, body) = vcon(UUID, "first");
1798        let ops = f.fs.log().len();
1799        assert_eq!(
1800            f.store.create(&f.caller, &found, &body),
1801            Err(StoreError::Io)
1802        );
1803        assert_eq!(f.fs.log().len(), ops, "no file written");
1804    }
1805
1806    #[test]
1807    fn a_tenant_key_at_its_wrap_limit_refuses_new_vcons() {
1808        let f = fixture();
1809        f.store
1810            .conn()
1811            .execute(
1812                "INSERT INTO key_use (tenant_key_id, wraps) VALUES (?1, ?2)",
1813                params![f.store.tenant_key.id().bytes(), 1_i64 << 32],
1814            )
1815            .expect("at the limit");
1816        let (found, body) = vcon(UUID, "first");
1817        let ops = f.fs.log().len();
1818        assert_eq!(
1819            f.store.create(&f.caller, &found, &body),
1820            Err(StoreError::LimitReached)
1821        );
1822        only_its_record_synced(&f, ops);
1823        assert_eq!(audit_log(&f.store)[0]["status"], 503);
1824    }
1825
1826    #[test]
1827    fn a_missing_current_file_is_damage_not_a_conflict() {
1828        let f = fixture();
1829        let (found, body) = vcon(UUID, "first");
1830        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1831            panic!("a new vCon")
1832        };
1833        f.fs.remove(&f.store.objects_dir.join(version.to_string()))
1834            .expect("remove");
1835        assert_eq!(
1836            f.store.create(&f.caller, &found, &body),
1837            Err(StoreError::Damaged)
1838        );
1839        assert_eq!(audit_log(&f.store)[1]["status"], 500);
1840    }
1841
1842    #[test]
1843    fn a_racing_create_that_loses_gets_a_conflict_and_leaves_no_file() {
1844        let f = Arc::new(fixture());
1845        let (found, body) = vcon(UUID, "first");
1846        let winner = f.clone();
1847        *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
1848            let (found, other) = vcon(UUID, "second");
1849            assert!(matches!(
1850                winner.store.create(&winner.caller, &found, &other),
1851                Ok(Created::New(_))
1852            ));
1853        }));
1854        assert_eq!(
1855            f.store.create(&f.caller, &found, &body),
1856            Err(StoreError::Conflict)
1857        );
1858        assert_eq!(
1859            count(&f.store, "SELECT count(*) FROM version"),
1860            1,
1861            "only the winner"
1862        );
1863        assert_eq!(
1864            f.fs.list(&f.store.objects_dir).expect("list").len(),
1865            1,
1866            "the loser's file is gone"
1867        );
1868        assert_eq!(wraps(&f.store), 2, "both wraps are counted");
1869        let statuses: Vec<_> = audit_log(&f.store)
1870            .iter()
1871            .map(|r| r["status"].clone())
1872            .collect();
1873        assert_eq!(statuses, [201, 409]);
1874    }
1875
1876    #[test]
1877    fn a_create_whose_audit_record_fails_leaves_no_row_and_no_file() {
1878        let f = fixture();
1879        // Every audit insert now fails, as a full disk or a broken log would.
1880        f.store
1881            .conn()
1882            .execute_batch(
1883                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
1884                 BEGIN SELECT RAISE(ABORT, 'audit fails'); END;",
1885            )
1886            .expect("trigger");
1887        let (found, body) = vcon(UUID, "first");
1888        assert_eq!(
1889            f.store.create(&f.caller, &found, &body),
1890            Err(StoreError::AuditFailed)
1891        );
1892        assert_eq!(count(&f.store, "SELECT count(*) FROM version"), 0);
1893        assert_eq!(count(&f.store, "SELECT count(*) FROM vcon"), 0);
1894        assert_eq!(
1895            f.fs.list(&f.store.objects_dir).expect("list"),
1896            Vec::<std::ffi::OsString>::new()
1897        );
1898    }
1899
1900    #[test]
1901    fn a_create_whose_commit_outcome_is_unknown_keeps_its_object() {
1902        let f = fixture();
1903        let (found, body) = vcon(UUID, "first");
1904        // The wrap count commits first; the second commit, which adds the
1905        // rows, is kept and then reported as failed, as a lost connection
1906        // reports a commit the database made.
1907        f.store.catalog.fail_commit(2, CommitError::Unknown);
1908        assert_eq!(
1909            f.store.create(&f.caller, &found, &body),
1910            Err(StoreError::Io),
1911            "a_create_whose_commit_outcome_is_unknown_keeps_its_object: f.store.create(&f.caller, &found, &body)"
1912        );
1913        let stored = f
1914            .store
1915            .get(&f.caller, found.uuid)
1916            .expect("the kept row reads");
1917        assert_eq!(
1918            stored.body, body,
1919            "a_create_whose_commit_outcome_is_unknown_keeps_its_object: stored.body"
1920        );
1921        assert_eq!(f.store.check(), Ok(Vec::new()), "no row without its object");
1922        drop(f.open().expect("reopens"));
1923        assert_eq!(
1924            f.store.get(&f.caller, found.uuid).map(|s| s.body),
1925            Ok(body),
1926            "recovery keeps an object a row names"
1927        );
1928    }
1929
1930    #[test]
1931    fn a_replace_whose_commit_outcome_is_unknown_keeps_its_object() {
1932        let f = fixture();
1933        let (found, body) = vcon(UUID, "first");
1934        let Ok(Created::New(first)) = f.store.create(&f.caller, &found, &body) else {
1935            panic!("a new vCon")
1936        };
1937        let (found, second) = vcon(UUID, "second");
1938        f.store.catalog.fail_commit(2, CommitError::Unknown);
1939        assert_eq!(
1940            f.store.replace(&f.caller, first, &found, &second),
1941            Err(StoreError::Io),
1942            "a_replace_whose_commit_outcome_is_unknown_keeps_its_object: f.store.replace(&f.caller, first, &found, &second)"
1943        );
1944        let stored = f
1945            .store
1946            .get(&f.caller, found.uuid)
1947            .expect("the kept row reads");
1948        assert_eq!(
1949            stored.body, second,
1950            "a_replace_whose_commit_outcome_is_unknown_keeps_its_object: stored.body"
1951        );
1952        assert_eq!(f.store.check(), Ok(Vec::new()), "no row without its object");
1953    }
1954
1955    #[test]
1956    fn a_create_whose_commit_rolls_back_leaves_no_object() {
1957        let f = fixture();
1958        let (found, body) = vcon(UUID, "first");
1959        f.store.catalog.fail_commit(2, CommitError::RolledBack);
1960        assert_eq!(
1961            f.store.create(&f.caller, &found, &body),
1962            Err(StoreError::Io),
1963            "a_create_whose_commit_rolls_back_leaves_no_object: f.store.create(&f.caller, &found, &body)"
1964        );
1965        assert_eq!(
1966            count(&f.store, "SELECT count(*) FROM version"),
1967            0,
1968            "a_create_whose_commit_rolls_back_leaves_no_object: count(&f.store, \"SELECT count(*) FROM version\")"
1969        );
1970        assert_eq!(
1971            f.fs.list(&f.store.objects_dir).expect("list"),
1972            Vec::<std::ffi::OsString>::new(),
1973            "a_create_whose_commit_rolls_back_leaves_no_object: f.fs.list(&f.store.objects_dir).expect(\"list\")"
1974        );
1975    }
1976
1977    fn get_entry_status(f: &Fixture) -> Value {
1978        audit_log(&f.store).last().expect("a record")["status"].clone()
1979    }
1980
1981    #[test]
1982    fn a_stored_vcon_reads_back_byte_for_byte_and_is_recorded() {
1983        let f = fixture();
1984        let (found, body) = vcon(UUID, "first");
1985        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1986            panic!("a new vCon")
1987        };
1988        let stored = f.store.get(&f.caller, found.uuid).expect("reads");
1989        assert_eq!(
1990            stored,
1991            Stored {
1992                version,
1993                form: vcon::Form::Unsigned,
1994                gzip: false,
1995                body
1996            }
1997        );
1998        let log = audit_log(&f.store);
1999        let read = log.last().expect("a record");
2000        assert_eq!(read["action"], "read");
2001        assert_eq!(read["status"], 200);
2002        assert_eq!(read["version"], version.to_string());
2003        assert_eq!(read["target"], UUID);
2004    }
2005
2006    #[test]
2007    fn a_uuid_never_stored_is_not_found() {
2008        let f = fixture();
2009        let (found, _) = vcon(UUID, "first");
2010        assert_eq!(
2011            f.store.get(&f.caller, found.uuid),
2012            Err(StoreError::NotFound)
2013        );
2014        assert_eq!(get_entry_status(&f), 404);
2015    }
2016
2017    #[test]
2018    fn a_deleted_or_purged_uuid_is_gone() {
2019        for sql in [
2020            "UPDATE vcon SET current = NULL, deleted_at = 1 WHERE uuid = ?1",
2021            "DELETE FROM vcon WHERE uuid = ?1; INSERT INTO tombstone (uuid, purged_at) VALUES (?1, 1)",
2022        ] {
2023            let f = fixture();
2024            let (found, body) = vcon(UUID, "first");
2025            f.store.create(&f.caller, &found, &body).expect("stored");
2026            for statement in sql.split("; ") {
2027                f.store
2028                    .conn()
2029                    .execute(statement, [found.uuid.as_bytes()])
2030                    .expect(statement);
2031            }
2032            assert_eq!(
2033                f.store.get(&f.caller, found.uuid),
2034                Err(StoreError::Gone),
2035                "{sql}"
2036            );
2037            assert_eq!(get_entry_status(&f), 410);
2038        }
2039    }
2040
2041    #[test]
2042    fn a_missing_or_damaged_file_is_a_500_never_an_empty_body() {
2043        let f = fixture();
2044        let (found, body) = vcon(UUID, "first");
2045        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
2046            panic!("a new vCon")
2047        };
2048        let file = f.store.objects_dir.join(version.to_string());
2049        let blob = f.fs.read(&file).expect("file");
2050        f.fs.remove(&file).expect("remove");
2051        assert_eq!(
2052            f.store.get(&f.caller, found.uuid),
2053            Err(StoreError::Damaged),
2054            "missing"
2055        );
2056        assert_eq!(get_entry_status(&f), 500);
2057        let mut bad = blob.clone();
2058        let last = bad.len() - 1;
2059        bad[last] ^= 1;
2060        f.fs.write_new(&file, &bad).expect("write");
2061        assert_eq!(
2062            f.store.get(&f.caller, found.uuid),
2063            Err(StoreError::Damaged),
2064            "tampered"
2065        );
2066    }
2067
2068    /// Makes the failure a read gives.
2069    pub(super) type Fail = fn() -> ObjectError;
2070
2071    /// Objects whose every read fails as `fail` makes the failure, and
2072    /// whose other calls reach `inner`.
2073    pub(super) struct ReadsFail {
2074        pub(super) inner: Arc<dyn Objects>,
2075        pub(super) fail: Fail,
2076    }
2077
2078    impl Objects for ReadsFail {
2079        fn put(&self, version: VersionId, blob: &[u8]) -> Result<(), ObjectError> {
2080            self.inner.put(version, blob)
2081        }
2082
2083        fn get(&self, _: VersionId) -> Result<Vec<u8>, ObjectError> {
2084            Err((self.fail)())
2085        }
2086
2087        fn remove(&self, version: VersionId) -> Result<(), ObjectError> {
2088            self.inner.remove(version)
2089        }
2090
2091        fn list(&self) -> Result<Vec<String>, ObjectError> {
2092            self.inner.list()
2093        }
2094
2095        fn remove_name(&self, name: &str) -> Result<(), ObjectError> {
2096            self.inner.remove_name(name)
2097        }
2098
2099        fn sync(&self) -> Result<(), ObjectError> {
2100            self.inner.sync()
2101        }
2102    }
2103
2104    /// Objects that are read as stored, and a listing that fails.
2105    struct ListFails {
2106        inner: Arc<dyn Objects>,
2107        fail: Fail,
2108    }
2109
2110    impl Objects for ListFails {
2111        fn put(&self, version: VersionId, blob: &[u8]) -> Result<(), ObjectError> {
2112            self.inner.put(version, blob)
2113        }
2114
2115        fn get(&self, version: VersionId) -> Result<Vec<u8>, ObjectError> {
2116            self.inner.get(version)
2117        }
2118
2119        fn remove(&self, version: VersionId) -> Result<(), ObjectError> {
2120            self.inner.remove(version)
2121        }
2122
2123        fn list(&self) -> Result<Vec<String>, ObjectError> {
2124            Err((self.fail)())
2125        }
2126
2127        fn remove_name(&self, name: &str) -> Result<(), ObjectError> {
2128            self.inner.remove_name(name)
2129        }
2130
2131        fn sync(&self) -> Result<(), ObjectError> {
2132            self.inner.sync()
2133        }
2134    }
2135
2136    /// A listing of the objects that the storage fails is the storage's
2137    /// failure, with its kind, as a read's is; a listing that says no
2138    /// object has the name, which no listing means, is a failed
2139    /// examination, not a storage error.
2140    #[test]
2141    fn a_listing_the_storage_fails_is_reported_with_its_kind() {
2142        let cases: [(Fail, ExamineError); 2] = [
2143            (
2144                || storage_failed(std::io::ErrorKind::PermissionDenied),
2145                ExamineError::Objects {
2146                    kind: std::io::ErrorKind::PermissionDenied,
2147                    os_error: None,
2148                },
2149            ),
2150            (
2151                || ObjectError::Missing,
2152                ExamineError::Failed(StoreError::Io),
2153            ),
2154        ];
2155        for (fail, expected) in cases {
2156            let mut f = fixture();
2157            let (found, body) = vcon(UUID, "first");
2158            f.store.create(&f.caller, &found, &body).expect("stored");
2159            f.store.objects = Arc::new(ListFails {
2160                inner: f.store.objects.clone(),
2161                fail,
2162            });
2163            assert_eq!(
2164                f.store
2165                    .examine(
2166                        Retention::Years(7),
2167                        datetime!(2026-10-23 12:00 UTC),
2168                        datetime!(2026-10-23 12:00 UTC),
2169                    )
2170                    .err(),
2171                Some(expected),
2172                "examine fails with the listing's failure"
2173            );
2174        }
2175    }
2176
2177    /// A storage failure, of the kind the system or the S3 backend gives.
2178    fn storage_failed(kind: std::io::ErrorKind) -> ObjectError {
2179        ObjectError::Io(std::io::Error::from(kind))
2180    }
2181
2182    /// Only an object the storage says is not there is damage: a read the
2183    /// storage fails (a disk error, a refused key, no answer in time) is
2184    /// a failure of the server, in every read that opens a version.
2185    #[test]
2186    fn a_read_the_storage_fails_is_io_and_only_a_missing_object_is_damage() {
2187        let cases: [(Fail, StoreError, &str); 5] = [
2188            (|| ObjectError::Missing, StoreError::Damaged, "missing"),
2189            (
2190                || ObjectError::Io(std::io::Error::from_raw_os_error(libc::EIO)),
2191                StoreError::Io,
2192                "EIO",
2193            ),
2194            (
2195                || storage_failed(std::io::ErrorKind::PermissionDenied),
2196                StoreError::Io,
2197                "permission denied",
2198            ),
2199            (
2200                || storage_failed(std::io::ErrorKind::ConnectionRefused),
2201                StoreError::Io,
2202                "connection refused",
2203            ),
2204            (
2205                || storage_failed(std::io::ErrorKind::TimedOut),
2206                StoreError::Io,
2207                "timed out",
2208            ),
2209        ];
2210        for (fail, expected, why) in cases {
2211            let mut f = fixture();
2212            let (found, body) = vcon(UUID, "first");
2213            let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
2214                panic!("a new vCon")
2215            };
2216            f.store.objects = Arc::new(ReadsFail {
2217                inner: f.store.objects.clone(),
2218                fail,
2219            });
2220            assert_eq!(
2221                f.store.get(&f.caller, found.uuid),
2222                Err(expected),
2223                "{why}: get"
2224            );
2225            assert_eq!(get_entry_status(&f), 500, "{why}: get is recorded");
2226            assert_eq!(
2227                f.store.create(&f.caller, &found, &body),
2228                Err(expected),
2229                "{why}: create of the same body"
2230            );
2231            for asked in [None, Some(version)] {
2232                assert_eq!(
2233                    f.store.legal_get(&f.caller, found.uuid, asked).err(),
2234                    Some(expected),
2235                    "{why}: legal_get {asked:?}"
2236                );
2237            }
2238            let examined = f.store.examine(
2239                Retention::Years(7),
2240                datetime!(2026-10-23 12:00 UTC),
2241                datetime!(2026-10-23 12:00 UTC),
2242            );
2243            match expected {
2244                StoreError::Damaged => assert_eq!(
2245                    examined.map(|e| e.damaged),
2246                    Ok(vec![version]),
2247                    "{why}: examine lists the version"
2248                ),
2249                _ => {
2250                    let ObjectError::Io(failed) = fail() else {
2251                        panic!("{why}: a storage failure")
2252                    };
2253                    assert_eq!(
2254                        examined.err(),
2255                        Some(ExamineError::Objects {
2256                            kind: failed.kind(),
2257                            os_error: failed.raw_os_error(),
2258                        }),
2259                        "{why}: examine fails with the storage's error kind, listing nothing as damaged"
2260                    );
2261                }
2262            }
2263        }
2264    }
2265
2266    /// Collects what the log writes.
2267    #[derive(Clone, Default)]
2268    pub(super) struct Capture(pub(super) Arc<Mutex<Vec<u8>>>);
2269
2270    impl std::io::Write for Capture {
2271        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
2272            self.0.lock().expect("lock").extend_from_slice(bytes);
2273            Ok(bytes.len())
2274        }
2275
2276        fn flush(&mut self) -> std::io::Result<()> {
2277            Ok(())
2278        }
2279    }
2280
2281    impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Capture {
2282        type Writer = Capture;
2283
2284        fn make_writer(&'a self) -> Capture {
2285            self.clone()
2286        }
2287    }
2288
2289    /// The text of a storage failure that names the object's key and a
2290    /// credential, as a service's message might.
2291    const LEAKY: &str = "tenants/1111/objects/0e0e AKIAIOSFODNN7EXAMPLE wJalrXUtnFEMI";
2292
2293    /// A failed read is logged with the failure's kind, and nothing of its
2294    /// text, the tenant, the uuid or the version, which may name an
2295    /// object's key or a credential.
2296    #[test]
2297    fn a_failed_read_is_logged_by_its_kind_only() {
2298        let mut f = fixture();
2299        let (found, body) = vcon(UUID, "first");
2300        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
2301            panic!("a new vCon")
2302        };
2303        f.store.objects = Arc::new(ReadsFail {
2304            inner: f.store.objects.clone(),
2305            fail: || {
2306                ObjectError::Io(std::io::Error::new(
2307                    std::io::ErrorKind::PermissionDenied,
2308                    LEAKY,
2309                ))
2310            },
2311        });
2312        let capture = Capture::default();
2313        let subscriber = tracing_subscriber::fmt()
2314            .with_writer(capture.clone())
2315            .with_ansi(false)
2316            .log_internal_errors(false)
2317            .finish();
2318        let read =
2319            tracing::subscriber::with_default(subscriber, || f.store.get(&f.caller, found.uuid));
2320        assert_eq!(read, Err(StoreError::Io), "the read fails as Io");
2321        let log = String::from_utf8(capture.0.lock().expect("lock").clone()).expect("UTF-8");
2322        assert!(log.contains("WARN"), "a warning: {log}");
2323        assert!(
2324            log.contains("kind=permission denied"),
2325            "the kind is logged: {log}"
2326        );
2327        // Each value is named by what it is, so a failure prints no value.
2328        let version = version.to_string();
2329        let tenant = TENANT.to_string();
2330        for (what, value) in [
2331            ("the error's text", LEAKY),
2332            ("the object's key", "tenants/1111"),
2333            ("the access key id", "AKIAIOSFODNN7EXAMPLE"),
2334            ("the secret key", "wJalrXUtnFEMI"),
2335            ("the uuid", UUID),
2336            ("the version id", version.as_str()),
2337            ("the tenant id", tenant.as_str()),
2338        ] {
2339            assert!(!log.contains(value), "{what} is logged");
2340        }
2341
2342        // A file's failure carries the system's error number too.
2343        f.store.objects = Arc::new(ReadsFail {
2344            inner: f.store.objects.clone(),
2345            fail: || ObjectError::Io(std::io::Error::from_raw_os_error(libc::EIO)),
2346        });
2347        let capture = Capture::default();
2348        let subscriber = tracing_subscriber::fmt()
2349            .with_writer(capture.clone())
2350            .with_ansi(false)
2351            .log_internal_errors(false)
2352            .finish();
2353        tracing::subscriber::with_default(subscriber, || f.store.get(&f.caller, found.uuid))
2354            .expect_err("fails");
2355        let log = String::from_utf8(capture.0.lock().expect("lock").clone()).expect("UTF-8");
2356        assert!(
2357            log.contains(&format!("os_error={}", libc::EIO)),
2358            "the error number is logged: {log}"
2359        );
2360    }
2361
2362    /// A data key that does not open is damage; a key page the system will
2363    /// not lock is a failure of the server, not of the stored data.
2364    #[test]
2365    fn only_a_wrapped_key_that_does_not_open_is_damage() {
2366        assert_eq!(
2367            key_failed(envelope::KeyError::Damaged),
2368            StoreError::Damaged,
2369            "a key that does not open"
2370        );
2371        assert_eq!(
2372            key_failed(envelope::KeyError::Memory(
2373                std::io::Error::from_raw_os_error(libc::ENOMEM)
2374            )),
2375            StoreError::Io,
2376            "a key page that cannot be locked"
2377        );
2378    }
2379
2380    #[test]
2381    fn a_read_racing_a_delete_never_returns_the_body() {
2382        let f = Arc::new(fixture());
2383        let (found, body) = vcon(UUID, "first");
2384        f.store.create(&f.caller, &found, &body).expect("stored");
2385        let deleter = f.clone();
2386        *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2387            deleter
2388                .store
2389                .conn()
2390                .execute(
2391                    "UPDATE vcon SET current = NULL, deleted_at = 1 WHERE uuid = ?1",
2392                    [found.uuid.as_bytes()],
2393                )
2394                .expect("delete");
2395        }));
2396        assert_eq!(f.store.get(&f.caller, found.uuid), Err(StoreError::Gone));
2397        assert_eq!(get_entry_status(&f), 410);
2398    }
2399
2400    #[test]
2401    fn a_read_racing_a_new_version_starts_again_and_returns_the_new_one() {
2402        let f = Arc::new(fixture());
2403        let (found, body) = vcon(UUID, "first");
2404        f.store.create(&f.caller, &found, &body).expect("stored");
2405        let (_, newer) = vcon(UUID, "newer");
2406        let version = VersionId::generate();
2407        let wrapped = f
2408            .store
2409            .write_version(found.uuid, version, &newer)
2410            .expect("written");
2411        let writer = f.clone();
2412        *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2413            let conn = writer.store.conn();
2414            conn.execute(
2415                "INSERT INTO version
2416                     (version, uuid, form, gzip, size, stored_at, tenant_key_id, wrapped_key)
2417                 VALUES (?1, ?2, 'unsigned', 0, 0, 0, ?3, ?4)",
2418                params![
2419                    version.0,
2420                    found.uuid.as_bytes(),
2421                    writer.store.tenant_key.id().bytes(),
2422                    wrapped
2423                ],
2424            )
2425            .expect("new version");
2426            conn.execute(
2427                "UPDATE vcon SET current = ?1 WHERE uuid = ?2",
2428                params![version.0, found.uuid.as_bytes()],
2429            )
2430            .expect("made current");
2431        }));
2432        let stored = f.store.get(&f.caller, found.uuid).expect("reads");
2433        assert_eq!((stored.version, stored.body), (version, newer));
2434        let reads = audit_log(&f.store)
2435            .iter()
2436            .filter(|r| r["action"] == "read")
2437            .count();
2438        assert_eq!(reads, 1, "one record for the one request");
2439    }
2440
2441    #[test]
2442    fn every_form_and_the_gzip_flag_read_back_as_stored() {
2443        use base64::Engine;
2444        use std::io::Write;
2445        let f = fixture();
2446        let uuids = [
2447            "01a07da8-c2bb-83e5-b9a2-279e0d16bc01",
2448            "01a07da8-c2bb-83e5-b9a2-279e0d16bc02",
2449            "01a07da8-c2bb-83e5-b9a2-279e0d16bc03",
2450        ];
2451        let (_, unsigned) = vcon(uuids[0], "plain");
2452        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
2453        gz.write_all(&unsigned).expect("gzip");
2454        let gzipped = gz.finish().expect("gzip");
2455        let (_, inner) = vcon(uuids[1], "signed");
2456        let signed = format!(
2457            r#"{{"payload": "{}", "signatures": [{{"header": {{}}}}]}}"#,
2458            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(inner)
2459        )
2460        .into_bytes();
2461        let encrypted = format!(
2462            r#"{{"unprotected": {{"uuid": "{}"}}, "ciphertext": "x", "recipients": []}}"#,
2463            uuids[2]
2464        )
2465        .into_bytes();
2466        let cases = [
2467            (gzipped, vcon::Form::Unsigned, true),
2468            (signed, vcon::Form::Signed, false),
2469            (encrypted, vcon::Form::Encrypted, false),
2470        ];
2471        for (body, form, gzip) in cases {
2472            let found = inspect(&body, None, &Limits::new(1 << 20), &BTreeSet::new())
2473                .expect("a valid vCon");
2474            assert_eq!((found.form, found.gzip), (form, gzip));
2475            f.store.create(&f.caller, &found, &body).expect("stored");
2476            let stored = f.store.get(&f.caller, found.uuid).expect("reads");
2477            assert_eq!((stored.form, stored.gzip, stored.body), (form, gzip, body));
2478        }
2479    }
2480
2481    /// Stores `subject` under UUID and returns its version.
2482    fn stored(f: &Fixture, subject: &str) -> (Inspection, VersionId) {
2483        let (found, body) = vcon(UUID, subject);
2484        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
2485            panic!("a new vCon")
2486        };
2487        (found, version)
2488    }
2489
2490    #[test]
2491    fn a_replace_makes_a_new_current_version_and_hides_the_old_one() {
2492        let f = fixture();
2493        let (found, old) = stored(&f, "first");
2494        let (_, newer) = vcon(UUID, "second");
2495        let version = f
2496            .store
2497            .replace(&f.caller, old, &found, &newer)
2498            .expect("replaced");
2499        assert_ne!(version, old);
2500        let stored = f.store.get(&f.caller, found.uuid).expect("reads");
2501        assert_eq!((stored.version, stored.body), (version, newer));
2502        let hidden: Option<i64> = f
2503            .store
2504            .conn()
2505            .query_row(
2506                "SELECT hidden_at FROM version WHERE version = ?1",
2507                [old.0],
2508                |r| r.get(0),
2509            )
2510            .expect("the old row is kept");
2511        assert_eq!(
2512            hidden,
2513            Some(crate::clock::nanos(datetime!(2026-10-23 12:00 UTC))),
2514            "the old version is hidden at the replace's time"
2515        );
2516        assert!(
2517            f.fs.read(&f.store.objects_dir.join(old.to_string()))
2518                .is_ok(),
2519            "its file is kept"
2520        );
2521        let record = audit_log(&f.store)
2522            .into_iter()
2523            .find(|r| r["action"] == "replace")
2524            .expect("a replace record");
2525        assert_eq!(
2526            (record["status"].clone(), record["version"].clone()),
2527            (200.into(), version.to_string().into())
2528        );
2529    }
2530
2531    #[test]
2532    fn a_replace_of_a_missing_or_gone_uuid_is_refused() {
2533        let f = fixture();
2534        let (found, body) = vcon(UUID, "first");
2535        let any = VersionId([7; 16]);
2536        assert_eq!(
2537            f.store.replace(&f.caller, any, &found, &body),
2538            Err(StoreError::NotFound)
2539        );
2540        assert_eq!(get_entry_status(&f), 404);
2541        let (found, old) = stored(&f, "first");
2542        f.store
2543            .conn()
2544            .execute(
2545                "UPDATE vcon SET current = NULL, deleted_at = 1 WHERE uuid = ?1",
2546                [found.uuid.as_bytes()],
2547            )
2548            .expect("delete");
2549        assert_eq!(
2550            f.store.replace(&f.caller, old, &found, &body),
2551            Err(StoreError::Gone)
2552        );
2553        assert_eq!(get_entry_status(&f), 410);
2554    }
2555
2556    #[test]
2557    fn a_stale_if_match_is_refused_and_writes_nothing() {
2558        let f = fixture();
2559        let (found, _) = stored(&f, "first");
2560        let ops = f.fs.log().len();
2561        let (_, newer) = vcon(UUID, "second");
2562        assert_eq!(
2563            f.store
2564                .replace(&f.caller, VersionId([7; 16]), &found, &newer),
2565            Err(StoreError::PreconditionFailed)
2566        );
2567        only_its_record_synced(&f, ops);
2568        assert_eq!(wraps(&f.store), 1, "nothing wrapped");
2569        assert_eq!(get_entry_status(&f), 412);
2570    }
2571
2572    #[test]
2573    fn a_signed_or_encrypted_current_version_is_immutable() {
2574        use base64::Engine;
2575        let f = fixture();
2576        let (found, old) = stored(&f, "first");
2577        let (_, inner) = vcon(UUID, "signed");
2578        let signed = format!(
2579            r#"{{"payload": "{}", "signatures": [{{"header": {{}}}}]}}"#,
2580            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(inner)
2581        )
2582        .into_bytes();
2583        let signed_found =
2584            inspect(&signed, None, &Limits::new(1 << 20), &BTreeSet::new()).expect("a signed vCon");
2585        let version = f
2586            .store
2587            .replace(&f.caller, old, &signed_found, &signed)
2588            .expect("an unsigned vCon may be replaced by a signed one");
2589        let (_, newer) = vcon(UUID, "second");
2590        let ops = f.fs.log().len();
2591        assert_eq!(
2592            f.store.replace(&f.caller, version, &found, &newer),
2593            Err(StoreError::Immutable)
2594        );
2595        only_its_record_synced(&f, ops);
2596        assert_eq!(get_entry_status(&f), 409);
2597
2598        let g = fixture();
2599        let encrypted = format!(
2600            r#"{{"unprotected": {{"uuid": "{UUID}"}}, "ciphertext": "x", "recipients": []}}"#
2601        )
2602        .into_bytes();
2603        let enc_found = inspect(&encrypted, None, &Limits::new(1 << 20), &BTreeSet::new())
2604            .expect("an encrypted vCon");
2605        let Ok(Created::New(enc_version)) = g.store.create(&g.caller, &enc_found, &encrypted)
2606        else {
2607            panic!("stored")
2608        };
2609        assert_eq!(
2610            g.store.replace(&g.caller, enc_version, &found, &newer),
2611            Err(StoreError::Immutable)
2612        );
2613    }
2614
2615    #[test]
2616    fn a_replace_at_the_wrap_limit_is_refused() {
2617        let f = fixture();
2618        let (found, old) = stored(&f, "first");
2619        f.store
2620            .conn()
2621            .execute("UPDATE key_use SET wraps = ?1", [1_i64 << 32])
2622            .expect("at the limit");
2623        let (_, newer) = vcon(UUID, "second");
2624        assert_eq!(
2625            f.store.replace(&f.caller, old, &found, &newer),
2626            Err(StoreError::LimitReached)
2627        );
2628        assert_eq!(get_entry_status(&f), 503);
2629    }
2630
2631    #[test]
2632    fn of_two_replaces_racing_on_one_version_the_second_to_commit_loses() {
2633        let f = Arc::new(fixture());
2634        let (found, old) = stored(&f, "first");
2635        let winner = f.clone();
2636        let racer = found;
2637        *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2638            let (_, body) = vcon(UUID, "winner");
2639            winner
2640                .store
2641                .replace(&winner.caller, old, &racer, &body)
2642                .expect("wins");
2643        }));
2644        let (_, body) = vcon(UUID, "loser");
2645        assert_eq!(
2646            f.store.replace(&f.caller, old, &found, &body),
2647            Err(StoreError::PreconditionFailed)
2648        );
2649        assert_eq!(
2650            f.fs.list(&f.store.objects_dir).expect("list").len(),
2651            2,
2652            "first and winner only"
2653        );
2654        assert_eq!(wraps(&f.store), 3, "every wrap counted");
2655        assert_eq!(get_entry_status(&f), 412);
2656    }
2657
2658    #[test]
2659    fn two_threads_replacing_with_the_same_if_match_one_wins() {
2660        let f = Arc::new(fixture());
2661        let (_, old) = stored(&f, "first");
2662        let threads: Vec<_> = ["one", "two"]
2663            .into_iter()
2664            .map(|subject| {
2665                let f = f.clone();
2666                std::thread::spawn(move || {
2667                    let (found, body) = vcon(UUID, subject);
2668                    f.store.replace(&f.caller, old, &found, &body)
2669                })
2670            })
2671            .collect();
2672        let results: Vec<_> = threads
2673            .into_iter()
2674            .map(|t| t.join().expect("thread"))
2675            .collect();
2676        assert_eq!(
2677            results.iter().filter(|r| r.is_ok()).count(),
2678            1,
2679            "{results:?}"
2680        );
2681        assert!(
2682            results.contains(&Err(StoreError::PreconditionFailed)),
2683            "{results:?}"
2684        );
2685    }
2686
2687    #[test]
2688    fn a_replace_whose_audit_record_fails_changes_nothing() {
2689        let f = fixture();
2690        let (found, old) = stored(&f, "first");
2691        f.store
2692            .conn()
2693            .execute_batch(
2694                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
2695                 BEGIN SELECT RAISE(ABORT, 'audit fails'); END;",
2696            )
2697            .expect("trigger");
2698        let (_, newer) = vcon(UUID, "second");
2699        assert_eq!(
2700            f.store.replace(&f.caller, old, &found, &newer),
2701            Err(StoreError::AuditFailed)
2702        );
2703        f.store
2704            .conn()
2705            .execute_batch("DROP TRIGGER no_audit")
2706            .expect("drop trigger");
2707        assert_eq!(
2708            f.store.get(&f.caller, found.uuid).expect("reads").version,
2709            old
2710        );
2711        assert_eq!(
2712            f.fs.list(&f.store.objects_dir).expect("list").len(),
2713            1,
2714            "only the first file"
2715        );
2716    }
2717
2718    fn hidden_versions(f: &Fixture) -> i64 {
2719        count(
2720            &f.store,
2721            "SELECT count(*) FROM version WHERE hidden_at IS NOT NULL",
2722        )
2723    }
2724
2725    #[test]
2726    fn a_deleted_uuid_answers_gone_and_keeps_its_versions_hidden() {
2727        let f = fixture();
2728        let (found, old) = stored(&f, "first");
2729        let (_, newer) = vcon(UUID, "second");
2730        f.clock.set(datetime!(2026-10-23 13:00 UTC));
2731        let current = f
2732            .store
2733            .replace(&f.caller, old, &found, &newer)
2734            .expect("replaced");
2735        f.clock.set(datetime!(2026-10-23 14:00 UTC));
2736        assert_eq!(
2737            f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2738            Ok(())
2739        );
2740        let record = audit_log(&f.store).pop().expect("a record");
2741        assert_eq!(
2742            (record["action"].clone(), record["status"].clone()),
2743            ("delete".into(), 204.into())
2744        );
2745        let hidden_at = |version: VersionId| -> i64 {
2746            f.store
2747                .conn()
2748                .query_row(
2749                    "SELECT hidden_at FROM version WHERE version = ?1",
2750                    [version.0],
2751                    |r| r.get(0),
2752                )
2753                .expect("hidden")
2754        };
2755        assert_eq!(
2756            hidden_at(old),
2757            nanos(datetime!(2026-10-23 13:00 UTC)),
2758            "hidden by the replace"
2759        );
2760        assert_eq!(
2761            hidden_at(current),
2762            nanos(datetime!(2026-10-23 14:00 UTC)),
2763            "hidden by the delete"
2764        );
2765        assert_eq!(f.store.get(&f.caller, found.uuid), Err(StoreError::Gone));
2766        let (_, body) = vcon(UUID, "third");
2767        assert_eq!(
2768            f.store.create(&f.caller, &found, &body),
2769            Err(StoreError::Gone)
2770        );
2771        assert_eq!(hidden_versions(&f), 2, "both versions hidden");
2772        assert_eq!(
2773            f.fs.list(&f.store.objects_dir).expect("list").len(),
2774            2,
2775            "files kept for legal reads"
2776        );
2777        let (current, deleted_at): (Option<Vec<u8>>, Option<i64>) = f
2778            .store
2779            .conn()
2780            .query_row(
2781                "SELECT current, deleted_at FROM vcon WHERE uuid = ?1",
2782                [found.uuid.as_bytes()],
2783                |r| Ok((r.get(0)?, r.get(1)?)),
2784            )
2785            .expect("row");
2786        assert_eq!(current, None);
2787        assert_eq!(deleted_at, Some(nanos(datetime!(2026-10-23 14:00 UTC))));
2788    }
2789
2790    #[test]
2791    fn deleting_a_deleted_or_purged_uuid_succeeds_again() {
2792        let f = fixture();
2793        let (found, _) = stored(&f, "first");
2794        f.store
2795            .delete(&f.caller, found.uuid, Retention::Years(7))
2796            .expect("deleted");
2797        assert_eq!(
2798            f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2799            Ok(())
2800        );
2801        assert_eq!(get_entry_status(&f), 204);
2802        let g = fixture();
2803        g.store
2804            .conn()
2805            .execute(
2806                "INSERT INTO tombstone (uuid, purged_at) VALUES (?1, 1)",
2807                [found.uuid.as_bytes()],
2808            )
2809            .expect("purged");
2810        assert_eq!(
2811            g.store.delete(&g.caller, found.uuid, Retention::Years(7)),
2812            Ok(())
2813        );
2814        assert_eq!(get_entry_status(&g), 204);
2815    }
2816
2817    #[test]
2818    fn deleting_a_uuid_never_stored_is_not_found() {
2819        let f = fixture();
2820        let (found, _) = vcon(UUID, "first");
2821        assert_eq!(
2822            f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2823            Err(StoreError::NotFound)
2824        );
2825        assert_eq!(get_entry_status(&f), 404);
2826    }
2827
2828    #[test]
2829    fn a_hold_does_not_stop_a_delete() {
2830        let f = fixture();
2831        let (found, _) = stored(&f, "first");
2832        f.store
2833            .conn()
2834            .execute(
2835                "UPDATE vcon SET hold = 1 WHERE uuid = ?1",
2836                [found.uuid.as_bytes()],
2837            )
2838            .expect("hold");
2839        assert_eq!(
2840            f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2841            Ok(())
2842        );
2843        assert_eq!(f.store.get(&f.caller, found.uuid), Err(StoreError::Gone));
2844    }
2845
2846    #[test]
2847    fn a_delete_whose_audit_record_fails_changes_nothing() {
2848        let f = fixture();
2849        let (found, version) = stored(&f, "first");
2850        f.store
2851            .conn()
2852            .execute_batch(
2853                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
2854                 BEGIN SELECT RAISE(ABORT, 'audit fails'); END;",
2855            )
2856            .expect("trigger");
2857        assert_eq!(
2858            f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2859            Err(StoreError::AuditFailed)
2860        );
2861        f.store
2862            .conn()
2863            .execute_batch("DROP TRIGGER no_audit")
2864            .expect("drop trigger");
2865        assert_eq!(
2866            f.store
2867                .get(&f.caller, found.uuid)
2868                .expect("still live")
2869                .version,
2870            version
2871        );
2872        assert_eq!(hidden_versions(&f), 0);
2873    }
2874
2875    #[test]
2876    fn only_the_optional_catalog_columns_may_be_empty() {
2877        let f = fixture();
2878        let conn = f.store.conn();
2879        let tables: [(&str, &[(&str, &str)]); 8] = [
2880            (
2881                "vcon",
2882                &[
2883                    ("uuid", "x'01'"),
2884                    ("current", "x'02'"),
2885                    ("deleted_at", "1"),
2886                    ("hold", "0"),
2887                ],
2888            ),
2889            (
2890                "version",
2891                &[
2892                    ("version", "x'02'"),
2893                    ("uuid", "x'01'"),
2894                    ("form", "'unsigned'"),
2895                    ("gzip", "0"),
2896                    ("size", "1"),
2897                    ("stored_at", "1"),
2898                    ("hidden_at", "1"),
2899                    ("tenant_key_id", "x'03'"),
2900                    ("wrapped_key", "x'04'"),
2901                    ("place_file", "x'05'"),
2902                    ("place_group", "0"),
2903                    ("place_row", "0"),
2904                ],
2905            ),
2906            (
2907                "parquet_file",
2908                &[
2909                    ("file_id", "x'05'"),
2910                    ("date", "'2026-10-23'"),
2911                    ("rows", "1"),
2912                    ("live_rows", "1"),
2913                    ("bytes", "1"),
2914                    ("created_at", "1"),
2915                    ("unnamed_at", "1"),
2916                ],
2917            ),
2918            ("purge_pending", &[("file_id", "x'05'")]),
2919            ("manifest", &[("seq", "1"), ("published_at", "1")]),
2920            ("tombstone", &[("uuid", "x'01'"), ("purged_at", "1")]),
2921            ("key_use", &[("tenant_key_id", "x'03'"), ("wraps", "1")]),
2922            (
2923                "audit",
2924                &[
2925                    ("at", "'2026-10-23T12:00Z'"),
2926                    ("actor", "'cli'"),
2927                    ("action", "'create'"),
2928                    ("target", "'x'"),
2929                    ("version", "'y'"),
2930                    ("status", "201"),
2931                    ("count", "1"),
2932                ],
2933            ),
2934        ];
2935        let may_be_empty: Vec<String> = tables
2936            .iter()
2937            .flat_map(|(table, row)| columns_taking_null(&conn, table, row))
2938            .collect();
2939        assert_eq!(
2940            may_be_empty,
2941            [
2942                "vcon.current",
2943                "vcon.deleted_at",
2944                "version.hidden_at",
2945                "version.place_file",
2946                "version.place_group",
2947                "version.place_row",
2948                "parquet_file.unnamed_at",
2949                // A rowid: NULL takes the next number, never a used one.
2950                "manifest.seq",
2951                "manifest.published_at",
2952                "audit.target",
2953                "audit.version",
2954                // A record that answers no request has no status.
2955                "audit.status"
2956            ]
2957        );
2958    }
2959
2960    #[test]
2961    fn a_new_stores_objects_directory_survives_a_crash() {
2962        let f = fixture();
2963        f.fs.crash();
2964        assert_eq!(
2965            f.fs.list(f.dir.path()).expect("list"),
2966            [std::ffi::OsString::from("objects")]
2967        );
2968    }
2969
2970    #[test]
2971    fn opening_removes_temporary_and_orphaned_files_and_nothing_else() {
2972        let mut f = fixture();
2973        let (found, version) = stored(&f, "first");
2974        let orphan = VersionId([0x0e; 16]);
2975        let objects = f.store.objects_dir.clone();
2976        for name in [
2977            format!("{orphan}"),
2978            format!("{orphan}.tmp"),
2979            format!("{version}.tmp"),
2980            "notes.txt".to_owned(),
2981        ] {
2982            f.fs.write_new(&objects.join(name), b"x").expect("write");
2983        }
2984        f.reopen();
2985        let names: Vec<String> =
2986            f.fs.list(&objects)
2987                .expect("list")
2988                .into_iter()
2989                .map(|n| n.to_string_lossy().into_owned())
2990                .collect();
2991        assert_eq!(names, [version.to_string(), "notes.txt".to_owned()]);
2992        assert_eq!(
2993            f.store
2994                .get(&f.caller, found.uuid)
2995                .expect("still reads")
2996                .version,
2997            version
2998        );
2999        let log = f.fs.log();
3000        let last_removal = log
3001            .iter()
3002            .rposition(|op| matches!(op, Op::Remove(_)))
3003            .expect("files were removed");
3004        assert!(
3005            log[last_removal..].contains(&Op::SyncDir(objects)),
3006            "the removals are synced"
3007        );
3008    }
3009
3010    /// A command beside a running server must not take the server's
3011    /// writes in progress for a crash's leftovers.
3012    #[test]
3013    fn opening_beside_a_server_removes_nothing() {
3014        let f = fixture();
3015        let (found, version) = stored(&f, "first");
3016        let orphan = VersionId([0x0e; 16]);
3017        let objects = f.store.objects_dir.clone();
3018        let mut written = vec![version.to_string()];
3019        for name in [
3020            format!("{orphan}"),
3021            format!("{orphan}.tmp"),
3022            format!("{version}.tmp"),
3023        ] {
3024            f.fs.write_new(&objects.join(&name), b"x").expect("write");
3025            written.push(name);
3026        }
3027        written.sort();
3028        let ops = f.fs.log().len();
3029        let beside = f.open_beside().expect("opens beside");
3030        let mut names: Vec<String> =
3031            f.fs.list(&objects)
3032                .expect("list")
3033                .into_iter()
3034                .map(|n| n.to_string_lossy().into_owned())
3035                .collect();
3036        names.sort();
3037        assert_eq!(names, written);
3038        assert!(
3039            !f.fs.log()[ops..]
3040                .iter()
3041                .any(|op| matches!(op, Op::Remove(_))),
3042            "nothing removed"
3043        );
3044        assert_eq!(
3045            beside.get(&f.caller, found.uuid).expect("reads").version,
3046            version
3047        );
3048    }
3049
3050    #[test]
3051    fn opening_checkpoints_the_wal_with_truncation() {
3052        let mut f = fixture();
3053        stored(&f, "first");
3054        let wal = f.dir.path().join("catalog.sqlite-wal");
3055        assert!(
3056            std::fs::metadata(&wal).expect("a WAL").len() > 0,
3057            "the WAL holds the write"
3058        );
3059        f.reopen();
3060        assert_eq!(std::fs::metadata(&wal).expect("a WAL").len(), 0);
3061    }
3062
3063    #[test]
3064    fn check_reports_a_version_whose_file_is_missing() {
3065        let f = fixture();
3066        let (_, version) = stored(&f, "first");
3067        assert_eq!(f.store.check(), Ok(vec![]));
3068        f.fs.remove(&f.store.objects_dir.join(version.to_string()))
3069            .expect("remove");
3070        assert_eq!(f.store.check(), Ok(vec![version]));
3071    }
3072
3073    #[test]
3074    fn opening_refuses_while_a_reader_stops_the_wal_from_being_truncated() {
3075        let f = fixture();
3076        stored(&f, "first");
3077        let ctx = Context::Tenant { tenant: TENANT };
3078        let tenant_key = envelope::unwrap(&f.master, &ctx, &f.wrapped).expect("unwraps");
3079        let catalog_key = envelope::catalog_key(&tenant_key).expect("catalog key");
3080        let mut reader = catalog::open(&f.dir.path().join("catalog.sqlite"), &catalog_key, "")
3081            .expect("a second connection");
3082        let read = reader.transaction().expect("read transaction");
3083        let _: i64 = read
3084            .query_row("SELECT count(*) FROM vcon", [], |r| r.get(0))
3085            .expect("a read holds a snapshot");
3086        assert!(matches!(f.open(), Err(StoreError::Io)));
3087        drop(read);
3088        assert!(f.open().is_ok(), "opens once the reader is done");
3089    }
3090
3091    /// The filesystem steps a create makes when nothing fails (pinned by
3092    /// a_new_vcon_is_written_in_order_and_recorded): the pending row's
3093    /// sync, write, sync, rename, sync the directory, the final commit's
3094    /// sync.
3095    const WRITE_STEPS: usize = 6;
3096
3097    /// The same for a replace (pinned by
3098    /// a_replace_is_written_in_order_and_synced).
3099    const REPLACE_STEPS: usize = 6;
3100
3101    /// After a restart, no row lacks its file and every file has a row.
3102    fn assert_whole(f: &Fixture, step: usize) {
3103        assert_eq!(
3104            f.store.check(),
3105            Ok(vec![]),
3106            "a row without its file at step {step}"
3107        );
3108        for name in f.fs.list(&f.store.objects_dir).expect("list") {
3109            let name = name.to_string_lossy().into_owned();
3110            let version = VersionId::parse(&name)
3111                .unwrap_or_else(|| panic!("{name} left over at step {step}"));
3112            let rows = count(
3113                &f.store,
3114                &format!("SELECT count(*) FROM version WHERE hex(version) = upper('{version}')"),
3115            );
3116            assert_eq!(rows, 1, "{name} has no row at step {step}");
3117        }
3118    }
3119
3120    /// A second connection to the store's catalog, outside the store, on
3121    /// which a test makes a trigger that every connection then meets (a
3122    /// TEMP trigger would hold only for this one).
3123    pub(super) fn second_connection(f: &Fixture) -> Connection {
3124        let ctx = Context::Tenant { tenant: TENANT };
3125        let tenant_key = envelope::unwrap(&f.master, &ctx, &f.wrapped).expect("unwraps");
3126        let catalog_key = envelope::catalog_key(&tenant_key).expect("catalog key");
3127        catalog::open(&f.dir.path().join("catalog.sqlite"), &catalog_key, "")
3128            .expect("second connection")
3129    }
3130
3131    fn die_before_commit(f: &Fixture) {
3132        let other = second_connection(f);
3133        let fs = f.fs.clone();
3134        *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
3135            fs.fail_from(0);
3136            other
3137                .execute_batch(
3138                    "CREATE TRIGGER dead BEFORE INSERT ON audit
3139                     BEGIN SELECT RAISE(ABORT, 'the process has died'); END;",
3140                )
3141                .expect("trigger");
3142        }));
3143    }
3144
3145    pub(super) fn restart(f: &mut Fixture) {
3146        f.fs.crash();
3147        f.store
3148            .conn()
3149            .execute_batch("DROP TRIGGER IF EXISTS dead")
3150            .expect("drop trigger");
3151        f.reopen();
3152    }
3153
3154    /// The log a write makes from a fresh fixture when nothing fails.
3155    fn uncut_log(write: impl Fn(&Fixture)) -> Vec<Op> {
3156        let f = fixture();
3157        let ops = f.fs.log().len();
3158        write(&f);
3159        f.fs.log()[ops..].to_vec()
3160    }
3161
3162    /// A cut at a WAL sync is a failed fdatasync: the request is refused
3163    /// with Io (its commit's outcome is unknown) and the catalog is
3164    /// poisoned. With the filesystem working again, a read is still
3165    /// refused: nothing is answered until the catalog is reopened.
3166    fn assert_poisoned_at_a_sync(
3167        f: &Fixture,
3168        uncut: &[Op],
3169        step: usize,
3170        result: Result<(), StoreError>,
3171    ) {
3172        if !matches!(uncut.get(step), Some(Op::SyncData(_))) {
3173            return;
3174        }
3175        assert_eq!(result, Err(StoreError::Io), "step {step}: a failed sync");
3176        f.fs.revive();
3177        assert_eq!(
3178            f.store
3179                .get(&f.caller, Uuid::parse_str(UUID).expect("uuid"))
3180                .map(|_| ()),
3181            Err(StoreError::Io),
3182            "step {step}: poisoned until the catalog is reopened"
3183        );
3184    }
3185
3186    #[test]
3187    fn a_create_cut_off_at_any_step_leaves_no_vcon_or_the_whole_vcon() {
3188        let (found, body) = vcon(UUID, "first");
3189        let uncut = uncut_log(|f| {
3190            f.store.create(&f.caller, &found, &body).expect("created");
3191        });
3192        assert_eq!(
3193            uncut.len(),
3194            WRITE_STEPS,
3195            "every step of a create: {uncut:?}"
3196        );
3197        for step in 0..=WRITE_STEPS {
3198            let mut f = fixture();
3199            f.fs.fail_from(f.fs.log().len() + step);
3200            let result = f.store.create(&f.caller, &found, &body);
3201            assert_eq!(
3202                result.is_ok(),
3203                step == WRITE_STEPS,
3204                "step {step}: {result:?}"
3205            );
3206            assert_poisoned_at_a_sync(&f, &uncut, step, result.map(|_| ()));
3207            restart(&mut f);
3208            match f.store.get(&f.caller, found.uuid) {
3209                Ok(stored) => assert_eq!(stored.body, body, "step {step}"),
3210                Err(StoreError::NotFound) => {
3211                    assert!(result.is_err(), "acknowledged, then lost, at step {step}")
3212                }
3213                other => panic!("half a vCon at step {step}: {other:?}"),
3214            }
3215            assert_whole(&f, step);
3216        }
3217    }
3218
3219    #[test]
3220    fn a_create_cut_off_between_its_file_and_its_commit_leaves_nothing() {
3221        let mut f = fixture();
3222        let (found, body) = vcon(UUID, "first");
3223        die_before_commit(&f);
3224        assert!(f.store.create(&f.caller, &found, &body).is_err());
3225        restart(&mut f);
3226        assert_eq!(
3227            f.store.get(&f.caller, found.uuid),
3228            Err(StoreError::NotFound)
3229        );
3230        assert_whole(&f, WRITE_STEPS);
3231    }
3232
3233    #[test]
3234    fn a_replace_cut_off_at_any_step_leaves_the_old_version_or_the_new() {
3235        let (found, old_body) = vcon(UUID, "first");
3236        let (_, new_body) = vcon(UUID, "second");
3237        let uncut = {
3238            let f = fixture();
3239            let Ok(Created::New(old)) = f.store.create(&f.caller, &found, &old_body) else {
3240                panic!("stored")
3241            };
3242            let ops = f.fs.log().len();
3243            f.store
3244                .replace(&f.caller, old, &found, &new_body)
3245                .expect("replaced");
3246            f.fs.log()[ops..].to_vec()
3247        };
3248        assert_eq!(
3249            uncut.len(),
3250            REPLACE_STEPS,
3251            "every step of a replace: {uncut:?}"
3252        );
3253        let last_sync = uncut
3254            .iter()
3255            .rposition(|op| matches!(op, Op::SyncData(_)))
3256            .expect("the final commit syncs");
3257        for step in 0..=REPLACE_STEPS {
3258            let mut f = fixture();
3259            let Ok(Created::New(old)) = f.store.create(&f.caller, &found, &old_body) else {
3260                panic!("stored")
3261            };
3262            f.fs.fail_from(f.fs.log().len() + step);
3263            let result = f.store.replace(&f.caller, old, &found, &new_body);
3264            assert_eq!(
3265                result.is_ok(),
3266                step == REPLACE_STEPS,
3267                "step {step}: {result:?}"
3268            );
3269            assert_poisoned_at_a_sync(&f, &uncut, step, result.map(|_| ()));
3270            restart(&mut f);
3271            let stored = f
3272                .store
3273                .get(&f.caller, found.uuid)
3274                .unwrap_or_else(|e| panic!("step {step}: {e:?}"));
3275            match result {
3276                Ok(new) => assert_eq!(
3277                    (stored.version, stored.body),
3278                    (new, new_body.clone()),
3279                    "step {step}"
3280                ),
3281                // The final commit's sync failed: its frames were written,
3282                // so whether it is kept is unknown, and the refusal says
3283                // so; either whole version is right.
3284                Err(_) if step == last_sync && stored.version != old => {
3285                    assert_eq!(stored.body, new_body, "step {step}: the new version whole")
3286                }
3287                Err(_) => assert_eq!(
3288                    (stored.version, stored.body),
3289                    (old, old_body.clone()),
3290                    "step {step}"
3291                ),
3292            }
3293            assert_whole(&f, step);
3294        }
3295    }
3296
3297    #[test]
3298    fn a_replace_cut_off_between_its_file_and_its_commit_keeps_the_old_version() {
3299        let mut f = fixture();
3300        let (found, old) = stored(&f, "first");
3301        let (_, newer) = vcon(UUID, "second");
3302        die_before_commit(&f);
3303        assert!(f.store.replace(&f.caller, old, &found, &newer).is_err());
3304        restart(&mut f);
3305        assert_eq!(
3306            f.store.get(&f.caller, found.uuid).expect("reads").version,
3307            old
3308        );
3309        assert_eq!(hidden_versions(&f), 0);
3310        assert_whole(&f, WRITE_STEPS);
3311    }
3312
3313    #[test]
3314    fn a_delete_cut_off_before_its_commit_leaves_the_vcon_live() {
3315        let mut f = fixture();
3316        let (found, version) = stored(&f, "first");
3317        let other = second_connection(&f);
3318        other
3319            .execute_batch(
3320                "CREATE TRIGGER dead BEFORE INSERT ON audit
3321                 BEGIN SELECT RAISE(ABORT, 'the process has died'); END;",
3322            )
3323            .expect("trigger");
3324        assert!(
3325            f.store
3326                .delete(&f.caller, found.uuid, Retention::Years(7))
3327                .is_err()
3328        );
3329        drop(other);
3330        restart(&mut f);
3331        assert_eq!(
3332            f.store
3333                .get(&f.caller, found.uuid)
3334                .expect("still live")
3335                .version,
3336            version
3337        );
3338        assert_eq!(hidden_versions(&f), 0);
3339    }
3340
3341    /// The record of the last request, without its seq and time.
3342    fn last_record(f: &Fixture) -> (String, Value, Value, Value) {
3343        let log = audit_log(&f.store);
3344        let last = log.last().expect("a record");
3345        (
3346            last["action"].as_str().expect("an action").to_owned(),
3347            last["status"].clone(),
3348            last["version"].clone(),
3349            last["target"].clone(),
3350        )
3351    }
3352
3353    #[test]
3354    fn a_reveal_reads_what_a_read_does_and_is_recorded_under_its_part() {
3355        let f = fixture();
3356        let (found, body) = vcon(UUID, "first");
3357        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
3358            panic!("a new vCon")
3359        };
3360        let read = f.store.get(&f.caller, found.uuid).expect("reads");
3361        for part in Part::ALL {
3362            let revealed = f.store.reveal(&f.caller, found.uuid, part).expect("reads");
3363            assert_eq!(revealed, read, "{part:?}");
3364            assert_eq!(
3365                last_record(&f),
3366                (
3367                    format!("reveal_{}", part.name()),
3368                    200.into(),
3369                    version.to_string().into(),
3370                    UUID.into()
3371                ),
3372                "{part:?}"
3373            );
3374        }
3375    }
3376
3377    #[test]
3378    fn a_reveal_of_a_uuid_never_stored_is_not_found_and_recorded_as_the_reveal() {
3379        let f = fixture();
3380        let (found, _) = vcon(UUID, "first");
3381        assert_eq!(
3382            f.store.reveal(&f.caller, found.uuid, Part::Dialog),
3383            Err(StoreError::NotFound),
3384            "the answer"
3385        );
3386        assert_eq!(
3387            last_record(&f),
3388            (
3389                "reveal_dialog".to_owned(),
3390                404.into(),
3391                Value::Null,
3392                UUID.into()
3393            ),
3394            "the record"
3395        );
3396    }
3397
3398    #[test]
3399    fn a_reveal_of_a_deleted_vcon_is_gone_and_recorded_as_the_reveal() {
3400        let f = fixture();
3401        let (found, body) = vcon(UUID, "first");
3402        f.store.create(&f.caller, &found, &body).expect("stored");
3403        f.store
3404            .delete(&f.caller, found.uuid, Retention::Years(7))
3405            .expect("deleted");
3406        assert_eq!(
3407            f.store.reveal(&f.caller, found.uuid, Part::Parties),
3408            Err(StoreError::Gone),
3409            "the answer"
3410        );
3411        assert_eq!(
3412            last_record(&f),
3413            (
3414                "reveal_parties".to_owned(),
3415                410.into(),
3416                Value::Null,
3417                UUID.into()
3418            ),
3419            "the record"
3420        );
3421    }
3422
3423    #[test]
3424    fn a_reveal_of_a_version_whose_file_is_missing_is_damage_recorded_as_the_reveal() {
3425        let f = fixture();
3426        let (found, body) = vcon(UUID, "first");
3427        let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
3428            panic!("a new vCon")
3429        };
3430        f.fs.remove(&f.store.objects_dir.join(version.to_string()))
3431            .expect("remove");
3432        assert_eq!(
3433            f.store.reveal(&f.caller, found.uuid, Part::All),
3434            Err(StoreError::Damaged),
3435            "the answer"
3436        );
3437        assert_eq!(
3438            last_record(&f),
3439            (
3440                "reveal_all".to_owned(),
3441                500.into(),
3442                version.to_string().into(),
3443                UUID.into()
3444            ),
3445            "the record"
3446        );
3447    }
3448
3449    /// The marker changes one record's action: the reads before and after
3450    /// a reveal are recorded as the reads they are.
3451    #[test]
3452    fn a_read_before_and_after_a_reveal_is_still_recorded_as_a_read() {
3453        let f = fixture();
3454        let (found, body) = vcon(UUID, "first");
3455        f.store.create(&f.caller, &found, &body).expect("stored");
3456        f.store.get(&f.caller, found.uuid).expect("reads");
3457        f.store
3458            .reveal(&f.caller, found.uuid, Part::Subject)
3459            .expect("reads");
3460        f.store.get(&f.caller, found.uuid).expect("reads");
3461        let actions: Vec<String> = audit_log(&f.store)
3462            .iter()
3463            .map(|r| r["action"].as_str().expect("an action").to_owned())
3464            .collect();
3465        assert_eq!(
3466            actions,
3467            ["create", "read", "reveal_subject", "read"],
3468            "the record"
3469        );
3470    }
3471}