Skip to main content

mira_core/
offload.rs

1//! Copy a sealed block to an object store before retention unlinks it.
2//!
3//! The whole module is one idea. A block directory's name already carries its
4//! own time range, node and sequence (section 3.2), so a flat namespace of
5//! those names *is* the catalog: [`Target::list`] is one call to the store's
6//! own list API and nothing here writes an index, a manifest or a marker
7//! beside the blocks. There is no second thing to keep consistent, which is
8//! what principle 4 asks for — kill the process mid-sweep and the only state
9//! is what the store lists, which is the same answer before and after.
10//!
11//! Four limits, all deliberate:
12//!
13//! * Only sealed, immutable blocks already past the retention cutoff are
14//!   uploaded. The hot path does not reach this module and the upload happens
15//!   on the retention worker's `spawn_blocking` thread, once a minute.
16//! * An offloaded block is never mapped. [`Target::pull`] copies it back into
17//!   the data directory and the read path opens it there, so section 9's
18//!   refusal to `mmap` a networked filesystem holds unchanged: this is a read
19//!   of bytes, not a mapping of them.
20//! * A block is deleted locally only after its copy is visible in the store
21//!   under its final name. The direction of the failure is fixed — a crash
22//!   leaves two copies, never zero.
23//! * `file://` is the only scheme implemented. See [`Target::parse`].
24
25use std::fs::{self, File};
26use std::io;
27use std::path::{Path, PathBuf};
28
29use crate::block::{self, BlockRef};
30use crate::error::{Error, IoContext, Result};
31
32/// Where offloaded blocks go. Parsed from `--offload`.
33#[derive(Debug, Clone)]
34pub struct Target {
35    root: PathBuf,
36}
37
38impl Target {
39    /// Parse an offload URI.
40    ///
41    /// Everything after `file://` is the path, so `file:///srv/cold` is
42    /// absolute and `file://./cold` is relative to the working directory.
43    /// There is no host field; a mounted bucket, an NFS export or a second
44    /// local volume are all the same thing to this module.
45    ///
46    /// `s3://` is not implemented, and the error says so rather than failing
47    /// later with something vaguer. The reason is the dependency budget the
48    /// README states as a product property: this tree has no HTTP client, no
49    /// HMAC/SHA implementation and no XML parser, and SigV4 signing plus
50    /// `ListObjectsV2` response parsing needs all three. That is not an
51    /// argument that it should never exist — it is the number whoever adds it
52    /// has to be willing to move, stated where they will hit it.
53    pub fn parse(uri: &str) -> Result<Target> {
54        match uri.strip_prefix("file://") {
55            Some(p) if !p.is_empty() => Ok(Target {
56                root: PathBuf::from(p),
57            }),
58            _ => Err(Error::OffloadScheme { uri: uri.into() }),
59        }
60    }
61
62    /// Every block the store holds for `signal`, oldest first.
63    ///
64    /// This is [`block::scan`] against the store's root and nothing else: the
65    /// same `readdir` that rebuilds the local catalog at boot rebuilds the
66    /// remote one, because the two namespaces are the same namespace. If this
67    /// function needed anything the local one does not, the naming scheme
68    /// would not be carrying its weight.
69    pub fn list(&self, signal: &str) -> Result<Vec<BlockRef>> {
70        block::scan(&self.root, signal)
71    }
72
73    /// Copy one local block into the store. `false` if it was already there.
74    ///
75    /// Staged under `.tmp` and renamed, for the reason [`block::publish`]
76    /// stages: the store's list API is the catalog, so a half-copied block
77    /// visible under its final name is a catalog entry that does not open.
78    ///
79    /// "Already there" is checked against the bytes, not only the name,
80    /// because `false` is what licenses the caller to unlink the local copy —
81    /// `block::expire_with` on the retention sweep, the operator deleting a
82    /// drained replica's volume on `mira offload push` exiting 0. A replica
83    /// re-created on a fresh volume keeps its node id and restarts its
84    /// sequence, so it reissues `(node, seq)` pairs the store may still hold,
85    /// and a name taken by somebody else's rows is the one case where "already
86    /// archived" is a lie with a volume behind it.
87    pub fn push(&self, signal: &str, b: &BlockRef) -> Result<bool> {
88        let Some((partition, name)) = split(&b.dir) else {
89            return Ok(false);
90        };
91        let dest_dir = self.root.join(signal).join(partition);
92        let dest = dest_dir.join(name);
93        if dest.exists() {
94            return match differs(&b.dir, &dest)? {
95                None => Ok(false),
96                Some(why) => Err(Error::OffloadCollision { dest, why }),
97            };
98        }
99        copy_block(
100            &b.dir,
101            &self.root,
102            &dest_dir,
103            &dest,
104            &format!("{signal}-{name}"),
105        )
106    }
107
108    /// Copy one offloaded block back into a local data directory. `false` if
109    /// it was already there.
110    ///
111    /// `node` only names the staging directory, so that a restore killed
112    /// half-way leaves a directory [`block::sweep_staging`] already knows how
113    /// to clear at the next start.
114    ///
115    /// It lands under [`block::name_covering_no_log`] rather than the name the
116    /// store holds, because the log the stored name refers to is the one on the
117    /// volume this block is being rescued *from*.
118    pub fn pull(&self, signal: &str, b: &BlockRef, data_dir: &Path, node: u32) -> Result<bool> {
119        let Some((partition, name)) = split(&b.dir) else {
120            return Ok(false);
121        };
122        let name = block::name_covering_no_log(name);
123        let dest_dir = data_dir.join(signal).join(partition);
124        let dest = dest_dir.join(&name);
125        if dest.exists() {
126            return Ok(false);
127        }
128        let staging = format!("{signal}-{node:08x}-restore-{name}");
129        copy_block(&b.dir, data_dir, &dest_dir, &dest, &staging)
130    }
131}
132
133/// Why two copies of one block name are not the same block, or `None`.
134///
135/// Names and sizes, not content. A block is sealed and immutable, its files
136/// are written once and the store's copy came from `copy_files` — so a byte
137/// that differs under a name and a length that both match has no writer in
138/// this design. Reading both sides to compare them would put the block's whole
139/// size through the retention sweep once a minute for every block already in
140/// the store, to rule out a case nothing can produce.
141///
142/// The same `is_file` filter as [`copy_files`], which walks past directories:
143/// a stray one beside the tables is not part of the block and was never
144/// copied, so counting it would report a mismatch against the store's faithful
145/// copy of it.
146fn differs(src: &Path, dest: &Path) -> Result<Option<String>> {
147    let (mut ours, mut theirs) = (sizes(src)?, sizes(dest)?);
148    // Names only, when one side has gone cold and the other has not: `compact`
149    // ZSTD-encodes every table in place and drops the marker beside them, so no
150    // size on either side is a size on the other. That is not an edge case — it
151    // happens to every block a sweep pushed while it was still inside its own
152    // hour, so comparing sizes across the boundary fails the *steady state*: an
153    // error on every subsequent sweep, and retention unable to expire the block
154    // it had already archived.
155    //
156    // ponytail: the name set is what is left, and it does not discriminate a
157    // reissued `(node, seq)` — two blocks of the same signal have the same
158    // table names. Narrower than the check it replaces, and only on the
159    // handful of blocks mid-boundary; the fix is an identity in the block
160    // rather than one derived from its bytes, which is a format change.
161    let marker = |v: &[(String, u64)]| v.iter().any(|(n, _)| n == block::COLD_MARKER);
162    let across = marker(&ours) != marker(&theirs);
163    if across {
164        ours.retain(|(n, _)| n != block::COLD_MARKER);
165        theirs.retain(|(n, _)| n != block::COLD_MARKER);
166    }
167    for (name, len) in &ours {
168        match theirs.iter().find(|(n, _)| n == name) {
169            None => return Ok(Some(format!("{name} is missing from it"))),
170            Some((_, there)) if !across && there != len => {
171                return Ok(Some(format!("{name} is {there} bytes there, {len} here")));
172            }
173            Some(_) => {}
174        }
175    }
176    let extra = theirs
177        .iter()
178        .find(|(n, _)| !ours.iter().any(|(o, _)| o == n));
179    Ok(extra.map(|(n, _)| format!("it holds {n}, which this block does not")))
180}
181
182/// `(file name, length)` for the regular files directly in `dir`, sorted.
183fn sizes(dir: &Path) -> Result<Vec<(String, u64)>> {
184    let mut out = Vec::new();
185    for entry in fs::read_dir(dir).ctx(dir)? {
186        let entry = entry.ctx(dir)?;
187        let meta = entry.metadata().ctx(entry.path())?;
188        if meta.is_file() {
189            out.push((entry.file_name().to_string_lossy().into_owned(), meta.len()));
190        }
191    }
192    out.sort();
193    Ok(out)
194}
195
196/// `(partition, block name)` out of `…/<signal>/p=<hour>/<block>`.
197fn split(dir: &Path) -> Option<(&std::ffi::OsStr, &str)> {
198    let name = dir.file_name()?.to_str()?;
199    let partition = dir.parent()?.file_name()?;
200    Some((partition, name))
201}
202
203/// Stage a whole block directory into `root/.tmp`, then rename it into place.
204fn copy_block(
205    src: &Path,
206    root: &Path,
207    dest_dir: &Path,
208    dest: &Path,
209    staging_name: &str,
210) -> Result<bool> {
211    let staging = root.join(".tmp");
212    // The pid, because two replicas sharing a volume both see this block in
213    // their own sweep and both will try to copy it. `publish` solves the same
214    // collision by putting the content's identity in the staging name; here
215    // the content's identity is already in `staging_name` and what has to be
216    // distinguished is the two *copiers* of identical bytes.
217    let tmp = staging.join(format!("{staging_name}-{}", std::process::id()));
218    fs::create_dir_all(&staging).ctx(&staging)?;
219    // Unlike `publish`, clearing a leftover here is unambiguous: the source is
220    // an immutable sealed block and the destination name is derived from it, so
221    // a directory left by a killed copy of *this* block can only hold a prefix
222    // of the bytes about to be written again.
223    if let Err(e) = fs::remove_dir_all(&tmp)
224        && e.kind() != io::ErrorKind::NotFound
225    {
226        return Err(e).ctx(tmp);
227    }
228    fs::create_dir(&tmp).ctx(&tmp)?;
229
230    let copied = copy_files(src, &tmp).and_then(|()| {
231        fsync_dir(&tmp)?;
232        fs::create_dir_all(dest_dir).ctx(dest_dir)?;
233        match fs::rename(&tmp, dest) {
234            Ok(()) => {}
235            // The other replica won the race described above and put the same
236            // immutable bytes there first. `rename` onto a non-empty directory
237            // is `ENOTEMPTY`, which is the same outcome as the `exists` check
238            // at the top of `push` and is not a failure of this sweep.
239            Err(_) if dest.exists() => return Ok(false),
240            Err(e) => return Err(e).ctx(dest),
241        }
242        fsync_dir(dest_dir)?;
243        Ok(true)
244    });
245
246    // Unconditional: on success the rename took it, on `Ok(false)` the bytes
247    // are already there under someone else's copy, and on error it is a
248    // prefix. Leaving it costs a whole block of store until the next
249    // `sweep_staging`, and this is one `rmdir` on a directory that is usually
250    // already gone.
251    let _ = fs::remove_dir_all(&tmp);
252    copied
253}
254
255fn copy_files(src: &Path, dst: &Path) -> Result<()> {
256    for entry in fs::read_dir(src).ctx(src)? {
257        let entry = entry.ctx(src)?;
258        let from = entry.path();
259        // A block directory is flat: `<table>.arrow` files, the sidecars and
260        // the `cold` marker. Anything else in there is not part of the block
261        // and copying it would put bytes in the store that no reader opens.
262        // `DirEntry::file_name` rather than `Path::file_name` because the first
263        // cannot fail and the second returns an `Option` nothing can produce.
264        if from.is_file() {
265            copy_file(&from, &dst.join(entry.file_name()))?;
266        }
267    }
268    Ok(())
269}
270
271/// Copy one file's bytes, giving the destination a current modification time.
272///
273/// Deliberately not `fs::copy`. On macOS that is `fcopyfile(COPYFILE_ALL)`,
274/// which carries the source's `mtime` across to the copy — so a restore lands
275/// a two-month-old stamp on bytes written seconds ago. Retention keys on the
276/// `max_ts` in the directory name, so nothing here changes either way; what
277/// changes is every reader *outside* this process that treats `(len, mtime)` as
278/// a path's identity, because a restore is precisely the case where a path's
279/// contents change. Writing the bytes rather than cloning the file makes the
280/// timestamp current as a consequence of the write, with no call anyone has to
281/// remember. `offload_restore_stamps_current_mtime` fails if this becomes
282/// `fs::copy`.
283fn copy_file(from: &Path, to: &Path) -> Result<()> {
284    let mut r = File::open(from).ctx(from)?;
285    let mut w = File::create(to).ctx(to)?;
286    io::copy(&mut r, &mut w).ctx(to)?;
287    // The local copy is about to be unlinked, so this one is the only one.
288    crate::sync_all(&w).ctx(to)
289}
290
291fn fsync_dir(path: &Path) -> Result<()> {
292    crate::sync_all(&File::open(path).ctx(path)?).ctx(path)
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use std::time::{Duration, SystemTime};
299
300    fn block(root: &Path, signal: &str, min_ts: i64, seq: u64, body: &[u8]) -> PathBuf {
301        let dir = root
302            .join(signal)
303            .join(format!("p={}", min_ts / 3_600_000_000_000))
304            .join(format!(
305                "{min_ts:020}-{:020}-{:08x}-{seq:012}-{:020}",
306                min_ts + 1,
307                7,
308                0
309            ));
310        fs::create_dir_all(&dir).unwrap();
311        fs::write(dir.join("logs.arrow"), body).unwrap();
312        fs::write(dir.join("attr.idx"), b"sidecar").unwrap();
313        dir
314    }
315
316    #[test]
317    fn only_file_scheme_is_implemented() {
318        assert!(Target::parse("file:///srv/cold").is_ok());
319        let e = Target::parse("s3://bucket/prefix").unwrap_err().to_string();
320        // The message has to name the scheme that was asked for and the one
321        // that works, because the operator reading it typed the first.
322        assert!(
323            e.contains("s3://bucket/prefix") && e.contains("file://"),
324            "{e}"
325        );
326        assert!(Target::parse("file://").is_err());
327    }
328
329    #[test]
330    fn push_list_pull_round_trips() {
331        let tmp = tempdir("rt");
332        let (local, store) = (tmp.join("data"), tmp.join("cold"));
333        let dir = block(&local, "logs", 7_200_000_000_000, 1, b"hello");
334        let t = Target::parse(&format!("file://{}", store.display())).unwrap();
335
336        // A block directory is flat, so anything with children in it belongs to
337        // something else — a half-written compaction, an editor's backup dir.
338        // It is walked past rather than recursed into, because the copy's cost
339        // is the block's size and nothing here bounds what a stray directory
340        // holds. Mutation check: recurse and this shows up in the store.
341        fs::create_dir(dir.join("not-a-table")).unwrap();
342        fs::write(dir.join("not-a-table").join("junk"), b"x").unwrap();
343
344        let b = block::scan(&local, "logs").unwrap().remove(0);
345        assert!(t.push("logs", &b).unwrap());
346        // Idempotent: the second sweep sees it and does not copy it again.
347        assert!(!t.push("logs", &b).unwrap());
348
349        // The catalog is the store's own listing, with no index written.
350        let listed = t.list("logs").unwrap();
351        assert_eq!(listed.len(), 1);
352        assert_eq!(listed[0].min_ts, b.min_ts);
353        assert_eq!(listed[0].seq, b.seq);
354        assert_eq!(listed[0].node, b.node);
355        assert!(!store.join(".tmp").join("logs-x").exists());
356        assert!(
357            !listed[0].dir.join("not-a-table").exists(),
358            "a directory inside the block was copied into the store"
359        );
360
361        fs::remove_dir_all(&dir).unwrap();
362        assert!(t.pull("logs", &listed[0], &local, 7).unwrap());
363        assert_eq!(fs::read(dir.join("logs.arrow")).unwrap(), b"hello");
364        // Sidecars ride along: they are optional to the reader, but a block
365        // that comes back without them comes back slower.
366        assert_eq!(fs::read(dir.join("attr.idx")).unwrap(), b"sidecar");
367        assert_eq!(block::scan(&local, "logs").unwrap(), vec![b]);
368        assert!(!t.pull("logs", &listed[0], &local, 7).unwrap());
369    }
370
371    /// A restored block describes a log that no longer exists.
372    ///
373    /// `wal_hi` is a position in the log of the volume that *wrote* the block,
374    /// and a restore lands it beside a log that starts at sequence 0 — a
375    /// re-created pod, a new claim. [`block::wal_watermarks`] takes the maximum
376    /// over the names it finds and filters only by node, and `node` is a hash
377    /// of `--node`, which the operator keeps stable across exactly this. So the
378    /// fresh log is handed a watermark thousands of sequences ahead of itself,
379    /// and the next replay skips every frame under it: acked data, dropped
380    /// silently, in the one situation the log exists for.
381    ///
382    /// `publish` states the rule this rests on — too high is the dangerous
383    /// direction, too low only costs a re-ingest.
384    #[test]
385    fn a_restored_block_claims_no_progress_in_the_log_it_lands_beside() {
386        let tmp = tempdir("restore-watermark");
387        let (old, store, fresh) = (tmp.join("old"), tmp.join("cold"), tmp.join("fresh"));
388        let dir = old.join("logs").join("p=2").join(format!(
389            "{:020}-{:020}-{:08x}-{:012}-{:020}",
390            7_200_000_000_000u64, 7_200_000_000_001u64, 7, 1, 5000
391        ));
392        fs::create_dir_all(&dir).unwrap();
393        fs::write(dir.join("logs.arrow"), b"hello").unwrap();
394
395        let t = Target::parse(&format!("file://{}", store.display())).unwrap();
396        let b = block::scan(&old, "logs").unwrap().remove(0);
397        assert_eq!(b.wal_hi, 5000);
398        assert!(t.push("logs", &b).unwrap());
399        assert!(
400            t.pull("logs", &t.list("logs").unwrap()[0], &fresh, 7)
401                .unwrap()
402        );
403
404        assert_eq!(
405            block::wal_watermarks(&fresh, 7).unwrap(),
406            [0, 0, 0],
407            "a fresh log at sequence 0 was told 5000 of its frames are already published"
408        );
409        // Still one block, still readable: only the claim about the log moved.
410        let landed = block::scan(&fresh, "logs").unwrap();
411        assert_eq!(landed.len(), 1);
412        assert_eq!(
413            fs::read(landed[0].dir.join("logs.arrow")).unwrap(),
414            b"hello"
415        );
416    }
417
418    /// A copy killed half-way leaves nothing in the catalog, and the next
419    /// sweep still lands the block.
420    ///
421    /// This is the whole reason `copy_block` stages and renames instead of
422    /// writing into the final name: the store's listing *is* the catalog, so a
423    /// directory holding two of a block's eight tables under its real name is
424    /// not a slow upload, it is a catalog entry that does not open. Mutation
425    /// check: copy straight into `dest` and the first assertion here fails.
426    #[test]
427    fn a_killed_copy_is_not_in_the_listing_and_does_not_block_the_retry() {
428        let tmp = tempdir("killed");
429        let (local, store) = (tmp.join("data"), tmp.join("cold"));
430        block(&local, "logs", 7_200_000_000_000, 1, b"hello");
431        let t = Target::parse(&format!("file://{}", store.display())).unwrap();
432        let b = block::scan(&local, "logs").unwrap().remove(0);
433
434        // What a kill mid-copy leaves behind, built by hand because there is
435        // no seam to fail the real one through: the staging directory this
436        // push would use, holding a prefix of the block.
437        let name = b.dir.file_name().unwrap().to_str().unwrap();
438        let half = store
439            .join(".tmp")
440            .join(format!("logs-{name}-{}", std::process::id()));
441        fs::create_dir_all(&half).unwrap();
442        fs::write(half.join("logs.arrow"), b"hel").unwrap();
443        assert!(t.list("logs").unwrap().is_empty(), "staging is not catalog");
444
445        assert!(t.push("logs", &b).unwrap());
446        let listed = t.list("logs").unwrap();
447        assert_eq!(listed.len(), 1);
448        // The whole block, not the three bytes the dead copy had written.
449        assert_eq!(
450            fs::read(listed[0].dir.join("logs.arrow")).unwrap(),
451            b"hello"
452        );
453    }
454
455    /// Three failure shapes a round trip cannot produce, and `copy_block` has
456    /// to tell apart: a block whose directory cannot be named, a staging path
457    /// that is not a directory, and another replica landing the same immutable
458    /// bytes first. The third is the one worth the test — read as a failure it
459    /// would keep a block that is already safely in the store.
460    #[test]
461    fn a_copy_that_cannot_land_says_which_way_it_failed() {
462        let tmp = tempdir("fail");
463        let (local, store) = (tmp.join("data"), tmp.join("cold"));
464        block(&local, "logs", 7_200_000_000_000, 1, b"hello");
465        let t = Target::parse(&format!("file://{}", store.display())).unwrap();
466        let b = block::scan(&local, "logs").unwrap().remove(0);
467        let name = b.dir.file_name().unwrap().to_str().unwrap().to_string();
468        let staged = store
469            .join(".tmp")
470            .join(format!("logs-{name}-{}", std::process::id()));
471
472        // A `BlockRef` with no partition above it has no address in the store.
473        // `scan` cannot produce one; it is skipped rather than copied to a
474        // name that would not list.
475        let orphan = block::BlockRef {
476            dir: PathBuf::from("loose"),
477            ..b
478        };
479        assert!(!t.push("logs", &orphan).unwrap());
480        assert!(!t.pull("logs", &orphan, &local, 7).unwrap());
481
482        // Staging occupied by a *file*. Clearing a leftover directory is
483        // unambiguous and silent; this is not a leftover, so it is an error
484        // rather than something to delete.
485        fs::create_dir_all(staged.parent().unwrap()).unwrap();
486        fs::write(&staged, b"not a directory").unwrap();
487        assert!(t.push("logs", &b).is_err());
488        assert!(t.list("logs").unwrap().is_empty());
489        fs::remove_file(&staged).unwrap();
490
491        // The race the staging name's pid exists for: the other replica
492        // renamed first, so `rename` gets `ENOTEMPTY` after this copy's
493        // `exists` check already passed. Called through `copy_block` because
494        // `push` returns at that check and never reaches the race.
495        let (partition, name) = split(&b.dir).unwrap();
496        let dest_dir = store.join("logs").join(partition);
497        let dest = dest_dir.join(name);
498        fs::create_dir_all(&dest).unwrap();
499        fs::write(dest.join("logs.arrow"), b"theirs").unwrap();
500        let staging = format!("logs-{name}");
501        assert!(!copy_block(&b.dir, &store, &dest_dir, &dest, &staging).unwrap());
502        // Theirs, untouched — and the copy this call made is not left behind
503        // in `.tmp` holding a second copy of the block.
504        assert_eq!(fs::read(dest.join("logs.arrow")).unwrap(), b"theirs");
505        assert!(!staged.exists());
506    }
507
508    /// "Already there" is what licenses the unlink, so it has to be decided
509    /// from the bytes and not from the name.
510    ///
511    /// A replica re-created on a fresh volume keeps its node id and restarts
512    /// its sequence — `offload_cmd`'s own doc says it "reissues `(node, seq)`
513    /// pairs that are still alive wherever they were copied" — so a second
514    /// drain of the same ordinal can find the first drain's archive under the
515    /// name the new block wants. Decided by name, that block is reported
516    /// `present`, `mira offload push` exits 0, and the operator deletes a
517    /// volume whose rows are in no store: the name in the catalog belongs to
518    /// somebody else's bytes.
519    ///
520    /// Mutation check: drop the comparison and `push` returns `Ok(false)` for
521    /// every case below.
522    #[test]
523    fn a_name_in_the_store_over_other_bytes_is_not_a_block_that_was_pushed() {
524        let tmp = tempdir("collide");
525        let (local, store) = (tmp.join("data"), tmp.join("cold"));
526        block(&local, "logs", 7_200_000_000_000, 1, b"hello");
527        let t = Target::parse(&format!("file://{}", store.display())).unwrap();
528        let b = block::scan(&local, "logs").unwrap().remove(0);
529        assert!(t.push("logs", &b).unwrap());
530        let there = t.list("logs").unwrap().remove(0).dir;
531
532        // Same names, different bytes. This is the collision itself.
533        fs::write(there.join("logs.arrow"), b"someone else's rows").unwrap();
534        let e = t.push("logs", &b).unwrap_err().to_string();
535        assert!(
536            e.contains("logs.arrow") && e.contains(&*there.to_string_lossy()),
537            "{e}"
538        );
539
540        // A short copy under the final name, which staging is supposed to make
541        // impossible and a store nobody else writes to would never hold.
542        fs::write(there.join("logs.arrow"), b"hello").unwrap();
543        fs::remove_file(there.join("attr.idx")).unwrap();
544        assert!(t.push("logs", &b).is_err());
545
546        // And a file the local block does not have. Restored to equality, the
547        // push goes back to the idempotent `false` the sweep runs on.
548        fs::write(there.join("attr.idx"), b"sidecar").unwrap();
549        assert!(!t.push("logs", &b).unwrap());
550        fs::write(there.join("stray"), b"x").unwrap();
551        assert!(t.push("logs", &b).is_err());
552    }
553
554    /// The same block on the two sides of the cold boundary is the same block.
555    ///
556    /// `compact` ZSTD-encodes every table in place and drops a `cold` marker
557    /// beside them, so a block pushed while hot and swept again after it aged
558    /// out of its hour has the same table names and none of the same sizes.
559    /// Compared byte-for-byte that reads as somebody else's rows under this
560    /// block's name: `push` raises `OffloadCollision`, `mira offload push`
561    /// exits non-zero, and the operator will not delete a drained replica's
562    /// volume — whose blocks are, in fact, already archived.
563    ///
564    /// Mutation check: compare sizes across the boundary too, and every
565    /// assertion below turns into an error.
566    #[test]
567    fn a_block_that_went_cold_after_it_was_pushed_is_still_that_block() {
568        let tmp = tempdir("cold");
569        let (local, store) = (tmp.join("data"), tmp.join("cold"));
570        let dir = block(&local, "logs", 7_200_000_000_000, 1, b"hello");
571        let t = Target::parse(&format!("file://{}", store.display())).unwrap();
572        let b = block::scan(&local, "logs").unwrap().remove(0);
573        assert!(t.push("logs", &b).unwrap());
574
575        // What `compact_block` leaves behind: smaller tables, plus the marker.
576        fs::write(dir.join("logs.arrow"), b"zstd").unwrap();
577        fs::write(dir.join("cold"), b"").unwrap();
578        assert!(!t.push("logs", &b).unwrap());
579
580        // And the other direction, which is what a restore then a re-drain
581        // does: the store holds the cold copy, the local one is hot again.
582        let there = t.list("logs").unwrap().remove(0).dir;
583        fs::write(there.join("logs.arrow"), b"zstd").unwrap();
584        fs::write(there.join("cold"), b"").unwrap();
585        fs::remove_file(dir.join("cold")).unwrap();
586        fs::write(dir.join("logs.arrow"), b"hello").unwrap();
587        assert!(!t.push("logs", &b).unwrap());
588
589        // Still a collision when the *names* disagree. Compression cannot add
590        // or drop a table, so this is the check that survives the boundary.
591        fs::remove_file(there.join("attr.idx")).unwrap();
592        assert!(t.push("logs", &b).is_err());
593    }
594
595    /// The invariant [section
596    /// 6.1](https://miradb.dev/architecture/retention/#61-offload-a-copy-before-the-unlink)
597    /// states: a restore rewrites what is at a path, so the path's `mtime` has
598    /// to say the bytes are new.
599    ///
600    /// Mutation check: implement `copy_file` with `fs::copy` on macOS, or add
601    /// any explicit `utimensat` that replays the source timestamp, and the
602    /// restored file keeps 1990 and this fails.
603    #[test]
604    fn offload_restore_stamps_current_mtime() {
605        let tmp = tempdir("mtime");
606        let (local, store) = (tmp.join("data"), tmp.join("cold"));
607        let dir = block(&local, "logs", 7_200_000_000_000, 1, b"hello");
608        let t = Target::parse(&format!("file://{}", store.display())).unwrap();
609        let b = block::scan(&local, "logs").unwrap().remove(0);
610        t.push("logs", &b).unwrap();
611        fs::remove_dir_all(&dir).unwrap();
612
613        // 1990, so the assertion cannot pass by the copy happening to be quick.
614        let listed = t.list("logs").unwrap();
615        set_mtime(&listed[0].dir.join("logs.arrow"), 631_152_000);
616        t.pull("logs", &listed[0], &local, 7).unwrap();
617
618        let age = SystemTime::now()
619            .duration_since(
620                fs::metadata(dir.join("logs.arrow"))
621                    .unwrap()
622                    .modified()
623                    .unwrap(),
624            )
625            .expect("restored mtime is in the past");
626        assert!(
627            age < Duration::from_secs(60),
628            "restored mtime is stale: {age:?}"
629        );
630    }
631
632    fn set_mtime(path: &Path, secs: i64) {
633        let times = [
634            libc::timeval {
635                tv_sec: secs as libc::time_t,
636                tv_usec: 0,
637            },
638            libc::timeval {
639                tv_sec: secs as libc::time_t,
640                tv_usec: 0,
641            },
642        ];
643        let c = std::ffi::CString::new(path.to_str().unwrap()).unwrap();
644        // SAFETY: `c` is a live NUL-terminated string and `times` is a live
645        // array of exactly the two `timeval`s `utimes` reads. Both outlive the
646        // call, which writes through neither pointer.
647        assert_eq!(unsafe { libc::utimes(c.as_ptr(), times.as_ptr()) }, 0);
648    }
649
650    fn tempdir(tag: &str) -> PathBuf {
651        let p = std::env::temp_dir().join(format!("mira-offload-{tag}-{}", std::process::id()));
652        let _ = fs::remove_dir_all(&p);
653        fs::create_dir_all(&p).unwrap();
654        p
655    }
656}