From cfa2ba1f13cf9a8eb5f8b73c69aa914e58fe93a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 8 Sep 2026 05:53:51 +0300 Subject: [PATCH] =?UTF-8?q?the=20boot=20sweep=20reclaims=20only=20what=20i?= =?UTF-8?q?s=20older=20than=20the=20database:=20the=20store=20outlives=20a?= =?UTF-8?q?ny=20one=20copy=20of=20the=20database=20now=20that=20the=20byte?= =?UTF-8?q?s=20sit=20in=20a=20shared=20bucket,=20so=20an=20unknown=20objec?= =?UTF-8?q?t=20goes=20only=20when=20it=20is=20no=20newer=20than=20the=20ne?= =?UTF-8?q?west=20moment=20the=20rows=20know=20=E2=80=94=20a=20crash=20orp?= =?UTF-8?q?han=20ages=20past=20the=20next=20upload=20and=20goes=20on=20a?= =?UTF-8?q?=20later=20boot,=20while=20uploads=20a=20stale=20database=20nev?= =?UTF-8?q?er=20heard=20of=20are=20always=20newer=20and=20are=20kept=20and?= =?UTF-8?q?=20said=20out=20loud;=20an=20empty=20database=20reclaims=20noth?= =?UTF-8?q?ing.=20A=20database=20three=20days=20behind=20the=20bucket=20co?= =?UTF-8?q?st=20four=20real=20uploads=20tonight?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/in.toml | 6 ++ crates/in-core/src/store/blobs.rs | 46 +++++++-- crates/in-core/src/store/r2.rs | 17 +++- crates/in-core/src/store/turso_store.rs | 126 ++++++++++++++++++++---- crates/in-core/tests/store.rs | 93 +++++++++++++++-- 5 files changed, 249 insertions(+), 39 deletions(-) diff --git a/config/in.toml b/config/in.toml index 6c8d447..8fafe9b 100644 --- a/config/in.toml +++ b/config/in.toml @@ -67,6 +67,12 @@ client_secret = "in-dev-secret" # Absence is meaningful: no table, no bucket, local bytes. Nothing here is # ever completed into the file for you. # +# A bucket outlives any one copy of the database, so the boot sweep reclaims +# an object no row names only when it is older than the newest moment the +# database knows. Booting against a database that is behind the bucket keeps +# every newer object and says so, one log line each; an empty database +# deletes nothing at all. +# # Migrating an existing deployment's bytes into the bucket — database and # storage tree stay where they are; run once with the server stopped: # rclone copy /files ":s3,provider=Cloudflare,access_key_id=,secret_access_key=,region=auto,endpoint=https://.r2.cloudflarestorage.com:/files" diff --git a/crates/in-core/src/store/blobs.rs b/crates/in-core/src/store/blobs.rs index 77b4308..a3e6a68 100644 --- a/crates/in-core/src/store/blobs.rs +++ b/crates/in-core/src/store/blobs.rs @@ -18,6 +18,7 @@ use std::path::{Path, PathBuf}; +use time::OffsetDateTime; use ulid::Ulid; use super::FileSpan; @@ -76,10 +77,34 @@ pub trait Blobs: Send + Sync + 'static { /// not an error. async fn delete(&self, keys: &[&str]) -> Result<(), BlobError>; - /// The names under one directory of the key space (`"files"` or - /// `"thumbs"`), temp files included — the orphan sweep's eyes. A - /// listing is a walk of one directory, never of the whole tree. - async fn list(&self, dir: &str) -> Result, BlobError>; + /// What one directory of the key space (`"files"` or `"thumbs"`) holds, + /// temp files included — the orphan sweep's eyes, with the moment each + /// object last changed, because the sweep only reclaims what is older + /// than the newest row the database knows. A listing is a walk of one + /// directory, never of the whole tree. + async fn list_with_times(&self, dir: &str) -> Result, BlobError>; + + /// The names alone, for callers that do not weigh ages. + async fn list(&self, dir: &str) -> Result, BlobError> { + Ok(self + .list_with_times(dir) + .await? + .into_iter() + .map(|entry| entry.name) + .collect()) + } +} + +/// One object in a directory of the key space: its name, and when its bytes +/// last changed. `modified` is `None` when the backend will not say — an +/// object whose age is unknown is never reclaimed, because the sweep cannot +/// prove it predates the database. +#[derive(Debug, Clone)] +pub struct BlobEntry { + /// The name under the directory, the way a row would name it. + pub name: String, + /// When the object last changed, as the backend reports it. + pub modified: Option, } /// The blob tree on the local filesystem: `root/files/` and @@ -194,7 +219,7 @@ impl Blobs for LocalBlobs { Ok(()) } - async fn list(&self, dir: &str) -> Result, BlobError> { + async fn list_with_times(&self, dir: &str) -> Result, BlobError> { let entries = match std::fs::read_dir(self.root.join(dir)) { Ok(entries) => entries, // A half of the tree that does not exist yet lists empty: a @@ -202,7 +227,7 @@ impl Blobs for LocalBlobs { Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), Err(e) => return Err(e.into()), }; - let mut names = Vec::new(); + let mut out = Vec::new(); for entry in entries { let entry = entry?; // Files only: the sweep reads this as "what the tree holds", @@ -211,9 +236,14 @@ impl Blobs for LocalBlobs { continue; } if let Ok(name) = entry.file_name().into_string() { - names.push(name); + let modified = entry + .metadata() + .and_then(|meta| meta.modified()) + .ok() + .map(OffsetDateTime::from); + out.push(BlobEntry { name, modified }); } } - Ok(names) + Ok(out) } } diff --git a/crates/in-core/src/store/r2.rs b/crates/in-core/src/store/r2.rs index 5fd09d9..c7b8345 100644 --- a/crates/in-core/src/store/r2.rs +++ b/crates/in-core/src/store/r2.rs @@ -27,7 +27,7 @@ use object_store::{ }; use super::FileSpan; -use super::blobs::{BlobError, Blobs}; +use super::blobs::{BlobEntry, BlobError, Blobs}; /// The part size [`R2Blobs::adopt`] streams up in: 8 MiB, the chunk size the /// server fixes for uploads, so the staging side and the bucket side speak @@ -236,10 +236,10 @@ impl Blobs for R2Blobs { Ok(()) } - async fn list(&self, dir: &str) -> Result, BlobError> { + async fn list_with_times(&self, dir: &str) -> Result, BlobError> { let separator = format!("{dir}/"); let prefix = ObjectPath::from(separator.clone()); - let mut names = Vec::new(); + let mut out = Vec::new(); let mut listing = self.store.list(Some(&prefix)); while let Some(entry) = listing.next().await { let meta = entry?; @@ -247,8 +247,15 @@ impl Blobs for R2Blobs { // sweep compares these names against rows, and a nested name // that lost its directory would lie about what it names. let full = meta.location.to_string(); - names.push(full.strip_prefix(&separator).unwrap_or(&full).to_string()); + // `last_modified` is chrono's; the crate's own clock is `time`, + // and a unix second crosses between them without a dependency. + let modified = time::OffsetDateTime::from_unix_timestamp(meta.last_modified.timestamp()) + .ok(); + out.push(BlobEntry { + name: full.strip_prefix(&separator).unwrap_or(&full).to_string(), + modified, + }); } - Ok(names) + Ok(out) } } diff --git a/crates/in-core/src/store/turso_store.rs b/crates/in-core/src/store/turso_store.rs index 8fb3592..d57da13 100644 --- a/crates/in-core/src/store/turso_store.rs +++ b/crates/in-core/src/store/turso_store.rs @@ -220,6 +220,18 @@ impl TursoStore { /// whose file is gone is only said out loud and otherwise kept, because /// deleting the row would turn a lost file into a lost fact — the row is /// still what screens list, and a re-upload replaces it cleanly. + /// + /// The store outlives any one copy of the database now that the bytes + /// sit in a shared bucket, so an unknown object is reclaimed ONLY when + /// it is no newer than the newest moment the database knows (the latest + /// `file.created_at` / `file.updated_at` / `upload_session.created_at`); + /// anything newer is kept and said out loud. A crash orphan is older + /// than the next successful upload and goes on a later boot, while + /// uploads a stale database never heard of are always newer than its + /// newest row and are never touched — a database three days behind the + /// bucket once cost four real uploads here. An empty database knows no + /// moment at all, which is the stale case at its worst: it deletes + /// nothing. async fn sweep_orphan_files(&self) -> Result<()> { // The whole pass — the id reads and the directory walks — holds the // database's write lock. A writer lands a new file while holding @@ -244,39 +256,67 @@ impl TursoStore { "SELECT id FROM upload_session WHERE state = 'active'", ) .await?; + // The watermark: the newest moment any row carries. Read under the + // same lock as the ids, so a writer that commits mid-sweep either + // is in both sets or in neither. + let watermark = newest_known(&tx).await?; + let mut kept = 0usize; + // Whether an unknown object may be reclaimed: only one no newer + // than the database's newest moment. An age the backend will not + // report, and an empty database, both answer no. + let reclaimable = |modified: Option| match (watermark, modified) { + (Some(newest), Some(at)) => at <= newest, + _ => false, + }; for (dir, known, kind) in [ (FILES_DIR, &files, "file"), (THUMBS_DIR, &thumbs, "thumbnail"), ] { // One listing per half: the names the tree holds, temp files - // included — a `.tmp` is an orphan like any other. - let names: std::collections::HashSet = self + // included — a `.tmp` is an orphan like any other — each with + // the moment it last changed. + let entries = self .blobs - .list(dir) + .list_with_times(dir) .await - .map_err(|e| StoreError::Backend(e.to_string()))? - .into_iter() - .collect(); + .map_err(|e| StoreError::Backend(e.to_string()))?; + let names: std::collections::HashSet<&str> = + entries.iter().map(|entry| entry.name.as_str()).collect(); for id in known.iter() { - if !names.contains(id) { + if !names.contains(id.as_str()) { eprintln!("{kind} {id} names a file that is not there"); } } - for name in names { - if !known.contains(&name) { - if let Err(e) = self.blobs.delete(&[&format!("{dir}/{name}")]).await { - eprintln!("could not delete orphaned storage file {dir}/{name}: {e}"); - } + for entry in &entries { + if known.contains(&entry.name) { + continue; + } + if !reclaimable(entry.modified) { + kept += 1; + eprintln!( + "{kind} {} is newer than anything the database knows and was kept — \ + the database may be behind the store", + entry.name + ); + continue; + } + if let Err(e) = self.blobs.delete(&[&format!("{dir}/{}", entry.name)]).await { + eprintln!("could not delete orphaned storage file {dir}/{}: {e}", entry.name); } } } // A staged-chunk directory outlives its session only through a crash // between the session write and the first chunk, or a removed session - // row — either way nothing will ever finish it, so it goes. + // row — either way nothing will ever finish it, so it goes, under the + // same watermark rule and with the directory's own mtime as its age. let uploads = self.storage.join(UPLOADS_DIR); let entries = match std::fs::read_dir(&uploads) { Ok(entries) => entries, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + report_kept(kept); + tx.commit().await.map_err(backend)?; + return Ok(()); + } Err(e) => return Err(backend(e)), }; for entry in entries { @@ -285,17 +325,31 @@ impl TursoStore { if !path.is_dir() { continue; } - let named = entry - .file_name() - .to_str() - .is_some_and(|n| sessions.contains(n)); - if !named && let Err(e) = std::fs::remove_dir_all(&path) { + let name = entry.file_name().to_string_lossy().into_owned(); + if sessions.contains(&name) { + continue; + } + let modified = entry + .metadata() + .and_then(|meta| meta.modified()) + .ok() + .map(OffsetDateTime::from); + if !reclaimable(modified) { + kept += 1; + eprintln!( + "staged upload {name} is newer than anything the database knows and was kept — \ + the database may be behind the store" + ); + continue; + } + if let Err(e) = std::fs::remove_dir_all(&path) { eprintln!( "could not delete orphaned upload directory {}: {e}", path.display() ); } } + report_kept(kept); // Nothing was written through the transaction: it exists to hold // the write lock across the walk, and committing it ends the pass. tx.commit().await.map_err(backend)?; @@ -811,6 +865,40 @@ async fn known_ids(conn: &Connection, sql: &str) -> Result Result> { + let mut newest: Option = None; + for sql in [ + "SELECT MAX(created_at) FROM file", + "SELECT MAX(updated_at) FROM file", + "SELECT MAX(created_at) FROM upload_session", + ] { + let mut rows = conn.query(sql, ()).await.map_err(backend)?; + if let Some(row) = rows.next().await.map_err(backend)? + && let Some(raw) = row.get::>(0).map_err(backend)? + { + let at = parse_stamp(&raw)?; + if newest.is_none_or(|seen| at > seen) { + newest = Some(at); + } + } + } + Ok(newest) +} + +/// The one summary line a sweep that kept something owes the log; a sweep +/// that kept nothing says nothing. +fn report_kept(kept: usize) { + if kept > 0 { + eprintln!( + "boot sweep kept {kept} unknown object(s) newer than the database — \ + this database may be behind the store" + ); + } +} + /// A database sidecar (`in.db-wal`, `in.db-shm`): the file beside the main /// one, wearing the same name plus the suffix. fn sibling(path: &str, suffix: &str) -> std::path::PathBuf { diff --git a/crates/in-core/tests/store.rs b/crates/in-core/tests/store.rs index e241346..800ecf8 100644 --- a/crates/in-core/tests/store.rs +++ b/crates/in-core/tests/store.rs @@ -1095,19 +1095,95 @@ async fn search_finds_live_names_and_nothing_else() { assert!(scratch.store.search(&user.id, " ", 50).await.unwrap().files.is_empty()); } +/// Moves the database's watermark — the newest moment any row carries — to +/// `stamp`, so a test decides which side of it the planted junk falls on +/// rather than the clock. `insert_file` writes "now"; a far-future stamp +/// makes everything on disk older than the database, a far-past one makes +/// everything newer. +async fn restamp_files(scratch: &Scratch, stamp: &str) { + let conn = raw_conn(scratch).await; + conn.execute( + "UPDATE file SET created_at = ?1, updated_at = ?1", + turso::params![stamp], + ) + .await + .unwrap(); +} + #[tokio::test] async fn the_boot_sweep_deletes_files_no_row_names() { let mut scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + scratch.store.insert_file(&user.id, None, "kept", b"data").await.unwrap(); let stray = scratch.storage.join("files").join("stray"); std::fs::write(&stray, b"orphan").unwrap(); let ghost = scratch.storage.join("uploads").join("ghost"); std::fs::create_dir_all(&ghost).unwrap(); std::fs::write(ghost.join("0"), b"chunk").unwrap(); + // Both are older than what the database knows, which is the only case + // in which the sweep may reclaim them. + restamp_files(&scratch, "2099-01-01T00:00:00Z").await; scratch.reopen().await; assert!(!stray.exists()); assert!(!ghost.exists()); } +/// The incident this rule exists for: a database three days behind the +/// shared bucket deleted four real uploads. An object newer than the newest +/// row is an upload the database has not heard of yet, never an orphan. +#[tokio::test] +async fn the_boot_sweep_keeps_what_is_newer_than_the_database() { + let mut scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + scratch.store.insert_file(&user.id, None, "old", b"data").await.unwrap(); + // The database is behind the store: its rows are ancient, the objects + // beside them arrived since. + restamp_files(&scratch, "2000-01-01T00:00:00Z").await; + let unknown = scratch.storage.join("files").join("uploaded-elsewhere"); + std::fs::write(&unknown, b"a real upload").unwrap(); + let staged = scratch.storage.join("uploads").join("live-session"); + std::fs::create_dir_all(&staged).unwrap(); + scratch.reopen().await; + assert!(unknown.exists()); + assert!(staged.exists()); +} + +/// A fresh database against a populated bucket is the stale case at its +/// worst: it knows no moment at all, so it may reclaim nothing. +#[tokio::test] +async fn the_boot_sweep_keeps_everything_when_the_database_is_empty() { + let mut scratch = Scratch::open().await; + let stray = scratch.storage.join("files").join("stray"); + std::fs::create_dir_all(stray.parent().unwrap()).unwrap(); + std::fs::write(&stray, b"someone else's upload").unwrap(); + let ghost = scratch.storage.join("uploads").join("ghost"); + std::fs::create_dir_all(&ghost).unwrap(); + scratch.reopen().await; + assert!(stray.exists()); + assert!(ghost.exists()); +} + +/// Thumbnails follow the files' rule, both ways. +#[tokio::test] +async fn the_boot_sweep_weighs_thumbnails_by_the_same_watermark() { + let mut scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + scratch.store.insert_file(&user.id, None, "row", b"data").await.unwrap(); + let thumbs = scratch.storage.join("thumbs"); + std::fs::create_dir_all(&thumbs).unwrap(); + let old = thumbs.join("stale-thumb"); + std::fs::write(&old, b"orphan").unwrap(); + restamp_files(&scratch, "2099-01-01T00:00:00Z").await; + scratch.reopen().await; + assert!(!old.exists()); + + let new = thumbs.join("fresh-thumb"); + std::fs::write(&new, b"newer than the database").unwrap(); + restamp_files(&scratch, "2000-01-01T00:00:00Z").await; + scratch.reopen().await; + assert!(new.exists()); +} + #[tokio::test] async fn a_row_whose_file_is_missing_is_kept() { let mut scratch = Scratch::open().await; @@ -1174,7 +1250,7 @@ async fn the_sweep_waits_for_a_writer_instead_of_deleting_its_file() { "INSERT INTO file (id, owner_id, folder_id, name, mime, size_bytes, \ thumb_state, created_at, updated_at, deleted_at, download_count) \ VALUES ('midwrite', ?1, NULL, 'midwrite.txt', 'text/plain', 8, 'none', \ - '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', NULL, 0)", + '2099-01-01T00:00:00Z', '2099-01-01T00:00:00Z', NULL, 0)", turso::params![user.id.as_str()], ) .await @@ -1916,18 +1992,21 @@ async fn r2_purge_takes_the_key_and_the_bucket_forgets_it() { async fn r2_the_sweep_takes_orphans_and_leaves_known_keys() { let scratch = R2Scratch::open().await; let alice = alice(&scratch.store).await; - let file = scratch - .store - .insert_file(alice.id.as_str(), None, "kept.bin", b"kept bytes") - .await - .unwrap(); // A client-side PUT with no row behind it — the exact shape the boot - // sweep's orphan pass exists to clean. + // sweep's orphan pass exists to clean. It lands BEFORE the row below, + // which is what makes it older than the database's newest moment and so + // reclaimable; an object newer than that is an upload the database has + // not heard of and is kept. scratch .blobs .put("files/orphaned-by-crash", b"stray") .await .unwrap(); + let file = scratch + .store + .insert_file(alice.id.as_str(), None, "kept.bin", b"kept bytes") + .await + .unwrap(); // `boot_sweeps` runs the orphan sweep over the bucket, exactly as the // server does in its background task. scratch.store.boot_sweeps().await.unwrap();