forge
Explore
Log in

Don't you dare go Hollow

the boot sweep reclaims only what is older than the database: the store outlives any one copy of the database now that the bytes sit in a shared bucket, so an unknown object goes only when it is no newer than the newest moment the rows know — a crash orphan ages past the next upload and goes on a later boot, while uploads a stale database never heard of are always newer and are kept and said out loud; an empty database reclaims nothing. A database three days behind the bucket cost four real uploads tonight

Browse files at this commit

cfa2ba1f13cf9a8eb5f8b73c69aa914e58fe93a4Ahmet Kaan GümüşParent: 8ec00d2
config/in.tomlmodified+6 -0
@@ -67,6 +67,12 @@ client_secret = "in-dev-secret"
6767 # Absence is meaningful: no table, no bucket, local bytes. Nothing here is
6868 # ever completed into the file for you.
6969 #
70+# A bucket outlives any one copy of the database, so the boot sweep reclaims
71+# an object no row names only when it is older than the newest moment the
72+# database knows. Booting against a database that is behind the bucket keeps
73+# every newer object and says so, one log line each; an empty database
74+# deletes nothing at all.
75+#
7076 # Migrating an existing deployment's bytes into the bucket — database and
7177 # storage tree stay where they are; run once with the server stopped:
7278 # rclone copy <storage>/files ":s3,provider=Cloudflare,access_key_id=<key id>,secret_access_key=<secret>,region=auto,endpoint=https://<account_id>.r2.cloudflarestorage.com:<bucket>/files"
crates/in-core/src/store/blobs.rsmodified+38 -8
@@ -18,6 +18,7 @@
1818
1919 use std::path::{Path, PathBuf};
2020
21+use time::OffsetDateTime;
2122 use ulid::Ulid;
2223
2324 use super::FileSpan;
@@ -76,10 +77,34 @@ pub trait Blobs: Send + Sync + 'static {
7677 /// not an error.
7778 async fn delete(&self, keys: &[&str]) -> Result<(), BlobError>;
7879
79- /// The names under one directory of the key space (`"files"` or
80- /// `"thumbs"`), temp files included — the orphan sweep's eyes. A
81- /// listing is a walk of one directory, never of the whole tree.
82- async fn list(&self, dir: &str) -> Result<Vec<String>, BlobError>;
80+ /// What one directory of the key space (`"files"` or `"thumbs"`) holds,
81+ /// temp files included — the orphan sweep's eyes, with the moment each
82+ /// object last changed, because the sweep only reclaims what is older
83+ /// than the newest row the database knows. A listing is a walk of one
84+ /// directory, never of the whole tree.
85+ async fn list_with_times(&self, dir: &str) -> Result<Vec<BlobEntry>, BlobError>;
86+
87+ /// The names alone, for callers that do not weigh ages.
88+ async fn list(&self, dir: &str) -> Result<Vec<String>, BlobError> {
89+ Ok(self
90+ .list_with_times(dir)
91+ .await?
92+ .into_iter()
93+ .map(|entry| entry.name)
94+ .collect())
95+ }
96+}
97+
98+/// One object in a directory of the key space: its name, and when its bytes
99+/// last changed. `modified` is `None` when the backend will not say — an
100+/// object whose age is unknown is never reclaimed, because the sweep cannot
101+/// prove it predates the database.
102+#[derive(Debug, Clone)]
103+pub struct BlobEntry {
104+ /// The name under the directory, the way a row would name it.
105+ pub name: String,
106+ /// When the object last changed, as the backend reports it.
107+ pub modified: Option<OffsetDateTime>,
83108 }
84109
85110 /// The blob tree on the local filesystem: `root/files/<id>` and
@@ -194,7 +219,7 @@ impl Blobs for LocalBlobs {
194219 Ok(())
195220 }
196221
197- async fn list(&self, dir: &str) -> Result<Vec<String>, BlobError> {
222+ async fn list_with_times(&self, dir: &str) -> Result<Vec<BlobEntry>, BlobError> {
198223 let entries = match std::fs::read_dir(self.root.join(dir)) {
199224 Ok(entries) => entries,
200225 // A half of the tree that does not exist yet lists empty: a
@@ -202,7 +227,7 @@ impl Blobs for LocalBlobs {
202227 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
203228 Err(e) => return Err(e.into()),
204229 };
205- let mut names = Vec::new();
230+ let mut out = Vec::new();
206231 for entry in entries {
207232 let entry = entry?;
208233 // Files only: the sweep reads this as "what the tree holds",
@@ -211,9 +236,14 @@ impl Blobs for LocalBlobs {
211236 continue;
212237 }
213238 if let Ok(name) = entry.file_name().into_string() {
214- names.push(name);
239+ let modified = entry
240+ .metadata()
241+ .and_then(|meta| meta.modified())
242+ .ok()
243+ .map(OffsetDateTime::from);
244+ out.push(BlobEntry { name, modified });
215245 }
216246 }
217- Ok(names)
247+ Ok(out)
218248 }
219249 }
crates/in-core/src/store/r2.rsmodified+12 -5
@@ -27,7 +27,7 @@ use object_store::{
2727 };
2828
2929 use super::FileSpan;
30-use super::blobs::{BlobError, Blobs};
30+use super::blobs::{BlobEntry, BlobError, Blobs};
3131
3232 /// The part size [`R2Blobs::adopt`] streams up in: 8 MiB, the chunk size the
3333 /// server fixes for uploads, so the staging side and the bucket side speak
@@ -236,10 +236,10 @@ impl Blobs for R2Blobs {
236236 Ok(())
237237 }
238238
239- async fn list(&self, dir: &str) -> Result<Vec<String>, BlobError> {
239+ async fn list_with_times(&self, dir: &str) -> Result<Vec<BlobEntry>, BlobError> {
240240 let separator = format!("{dir}/");
241241 let prefix = ObjectPath::from(separator.clone());
242- let mut names = Vec::new();
242+ let mut out = Vec::new();
243243 let mut listing = self.store.list(Some(&prefix));
244244 while let Some(entry) = listing.next().await {
245245 let meta = entry?;
@@ -247,8 +247,15 @@ impl Blobs for R2Blobs {
247247 // sweep compares these names against rows, and a nested name
248248 // that lost its directory would lie about what it names.
249249 let full = meta.location.to_string();
250- names.push(full.strip_prefix(&separator).unwrap_or(&full).to_string());
250+ // `last_modified` is chrono's; the crate's own clock is `time`,
251+ // and a unix second crosses between them without a dependency.
252+ let modified = time::OffsetDateTime::from_unix_timestamp(meta.last_modified.timestamp())
253+ .ok();
254+ out.push(BlobEntry {
255+ name: full.strip_prefix(&separator).unwrap_or(&full).to_string(),
256+ modified,
257+ });
251258 }
252- Ok(names)
259+ Ok(out)
253260 }
254261 }
crates/in-core/src/store/turso_store.rsmodified+107 -19
@@ -220,6 +220,18 @@ impl TursoStore {
220220 /// whose file is gone is only said out loud and otherwise kept, because
221221 /// deleting the row would turn a lost file into a lost fact — the row is
222222 /// still what screens list, and a re-upload replaces it cleanly.
223+ ///
224+ /// The store outlives any one copy of the database now that the bytes
225+ /// sit in a shared bucket, so an unknown object is reclaimed ONLY when
226+ /// it is no newer than the newest moment the database knows (the latest
227+ /// `file.created_at` / `file.updated_at` / `upload_session.created_at`);
228+ /// anything newer is kept and said out loud. A crash orphan is older
229+ /// than the next successful upload and goes on a later boot, while
230+ /// uploads a stale database never heard of are always newer than its
231+ /// newest row and are never touched — a database three days behind the
232+ /// bucket once cost four real uploads here. An empty database knows no
233+ /// moment at all, which is the stale case at its worst: it deletes
234+ /// nothing.
223235 async fn sweep_orphan_files(&self) -> Result<()> {
224236 // The whole pass — the id reads and the directory walks — holds the
225237 // database's write lock. A writer lands a new file while holding
@@ -244,39 +256,67 @@ impl TursoStore {
244256 "SELECT id FROM upload_session WHERE state = 'active'",
245257 )
246258 .await?;
259+ // The watermark: the newest moment any row carries. Read under the
260+ // same lock as the ids, so a writer that commits mid-sweep either
261+ // is in both sets or in neither.
262+ let watermark = newest_known(&tx).await?;
263+ let mut kept = 0usize;
264+ // Whether an unknown object may be reclaimed: only one no newer
265+ // than the database's newest moment. An age the backend will not
266+ // report, and an empty database, both answer no.
267+ let reclaimable = |modified: Option<OffsetDateTime>| match (watermark, modified) {
268+ (Some(newest), Some(at)) => at <= newest,
269+ _ => false,
270+ };
247271 for (dir, known, kind) in [
248272 (FILES_DIR, &files, "file"),
249273 (THUMBS_DIR, &thumbs, "thumbnail"),
250274 ] {
251275 // One listing per half: the names the tree holds, temp files
252- // included — a `.tmp` is an orphan like any other.
253- let names: std::collections::HashSet<String> = self
276+ // included — a `.tmp` is an orphan like any other — each with
277+ // the moment it last changed.
278+ let entries = self
254279 .blobs
255- .list(dir)
280+ .list_with_times(dir)
256281 .await
257- .map_err(|e| StoreError::Backend(e.to_string()))?
258- .into_iter()
259- .collect();
282+ .map_err(|e| StoreError::Backend(e.to_string()))?;
283+ let names: std::collections::HashSet<&str> =
284+ entries.iter().map(|entry| entry.name.as_str()).collect();
260285 for id in known.iter() {
261- if !names.contains(id) {
286+ if !names.contains(id.as_str()) {
262287 eprintln!("{kind} {id} names a file that is not there");
263288 }
264289 }
265- for name in names {
266- if !known.contains(&name) {
267- if let Err(e) = self.blobs.delete(&[&format!("{dir}/{name}")]).await {
268- eprintln!("could not delete orphaned storage file {dir}/{name}: {e}");
269- }
290+ for entry in &entries {
291+ if known.contains(&entry.name) {
292+ continue;
293+ }
294+ if !reclaimable(entry.modified) {
295+ kept += 1;
296+ eprintln!(
297+ "{kind} {} is newer than anything the database knows and was kept — \
298+ the database may be behind the store",
299+ entry.name
300+ );
301+ continue;
302+ }
303+ if let Err(e) = self.blobs.delete(&[&format!("{dir}/{}", entry.name)]).await {
304+ eprintln!("could not delete orphaned storage file {dir}/{}: {e}", entry.name);
270305 }
271306 }
272307 }
273308 // A staged-chunk directory outlives its session only through a crash
274309 // between the session write and the first chunk, or a removed session
275- // row — either way nothing will ever finish it, so it goes.
310+ // row — either way nothing will ever finish it, so it goes, under the
311+ // same watermark rule and with the directory's own mtime as its age.
276312 let uploads = self.storage.join(UPLOADS_DIR);
277313 let entries = match std::fs::read_dir(&uploads) {
278314 Ok(entries) => entries,
279- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
315+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
316+ report_kept(kept);
317+ tx.commit().await.map_err(backend)?;
318+ return Ok(());
319+ }
280320 Err(e) => return Err(backend(e)),
281321 };
282322 for entry in entries {
@@ -285,17 +325,31 @@ impl TursoStore {
285325 if !path.is_dir() {
286326 continue;
287327 }
288- let named = entry
289- .file_name()
290- .to_str()
291- .is_some_and(|n| sessions.contains(n));
292- if !named && let Err(e) = std::fs::remove_dir_all(&path) {
328+ let name = entry.file_name().to_string_lossy().into_owned();
329+ if sessions.contains(&name) {
330+ continue;
331+ }
332+ let modified = entry
333+ .metadata()
334+ .and_then(|meta| meta.modified())
335+ .ok()
336+ .map(OffsetDateTime::from);
337+ if !reclaimable(modified) {
338+ kept += 1;
339+ eprintln!(
340+ "staged upload {name} is newer than anything the database knows and was kept — \
341+ the database may be behind the store"
342+ );
343+ continue;
344+ }
345+ if let Err(e) = std::fs::remove_dir_all(&path) {
293346 eprintln!(
294347 "could not delete orphaned upload directory {}: {e}",
295348 path.display()
296349 );
297350 }
298351 }
352+ report_kept(kept);
299353 // Nothing was written through the transaction: it exists to hold
300354 // the write lock across the walk, and committing it ends the pass.
301355 tx.commit().await.map_err(backend)?;
@@ -811,6 +865,40 @@ async fn known_ids(conn: &Connection, sql: &str) -> Result<std::collections::Has
811865 Ok(out)
812866 }
813867
868+/// The newest moment the database knows: the latest of the file rows'
869+/// stamps and the upload sessions'. `None` for a database with no rows at
870+/// all, which is what tells the sweep it may reclaim nothing.
871+async fn newest_known(conn: &Connection) -> Result<Option<OffsetDateTime>> {
872+ let mut newest: Option<OffsetDateTime> = None;
873+ for sql in [
874+ "SELECT MAX(created_at) FROM file",
875+ "SELECT MAX(updated_at) FROM file",
876+ "SELECT MAX(created_at) FROM upload_session",
877+ ] {
878+ let mut rows = conn.query(sql, ()).await.map_err(backend)?;
879+ if let Some(row) = rows.next().await.map_err(backend)?
880+ && let Some(raw) = row.get::<Option<String>>(0).map_err(backend)?
881+ {
882+ let at = parse_stamp(&raw)?;
883+ if newest.is_none_or(|seen| at > seen) {
884+ newest = Some(at);
885+ }
886+ }
887+ }
888+ Ok(newest)
889+}
890+
891+/// The one summary line a sweep that kept something owes the log; a sweep
892+/// that kept nothing says nothing.
893+fn report_kept(kept: usize) {
894+ if kept > 0 {
895+ eprintln!(
896+ "boot sweep kept {kept} unknown object(s) newer than the database — \
897+ this database may be behind the store"
898+ );
899+ }
900+}
901+
814902 /// A database sidecar (`in.db-wal`, `in.db-shm`): the file beside the main
815903 /// one, wearing the same name plus the suffix.
816904 fn sibling(path: &str, suffix: &str) -> std::path::PathBuf {
crates/in-core/tests/store.rsmodified+86 -7
@@ -1095,19 +1095,95 @@ async fn search_finds_live_names_and_nothing_else() {
10951095 assert!(scratch.store.search(&user.id, " ", 50).await.unwrap().files.is_empty());
10961096 }
10971097
1098+/// Moves the database's watermark — the newest moment any row carries — to
1099+/// `stamp`, so a test decides which side of it the planted junk falls on
1100+/// rather than the clock. `insert_file` writes "now"; a far-future stamp
1101+/// makes everything on disk older than the database, a far-past one makes
1102+/// everything newer.
1103+async fn restamp_files(scratch: &Scratch, stamp: &str) {
1104+ let conn = raw_conn(scratch).await;
1105+ conn.execute(
1106+ "UPDATE file SET created_at = ?1, updated_at = ?1",
1107+ turso::params![stamp],
1108+ )
1109+ .await
1110+ .unwrap();
1111+}
1112+
10981113 #[tokio::test]
10991114 async fn the_boot_sweep_deletes_files_no_row_names() {
11001115 let mut scratch = Scratch::open().await;
1116+ let user = alice(&scratch.store).await;
1117+ scratch.store.insert_file(&user.id, None, "kept", b"data").await.unwrap();
11011118 let stray = scratch.storage.join("files").join("stray");
11021119 std::fs::write(&stray, b"orphan").unwrap();
11031120 let ghost = scratch.storage.join("uploads").join("ghost");
11041121 std::fs::create_dir_all(&ghost).unwrap();
11051122 std::fs::write(ghost.join("0"), b"chunk").unwrap();
1123+ // Both are older than what the database knows, which is the only case
1124+ // in which the sweep may reclaim them.
1125+ restamp_files(&scratch, "2099-01-01T00:00:00Z").await;
11061126 scratch.reopen().await;
11071127 assert!(!stray.exists());
11081128 assert!(!ghost.exists());
11091129 }
11101130
1131+/// The incident this rule exists for: a database three days behind the
1132+/// shared bucket deleted four real uploads. An object newer than the newest
1133+/// row is an upload the database has not heard of yet, never an orphan.
1134+#[tokio::test]
1135+async fn the_boot_sweep_keeps_what_is_newer_than_the_database() {
1136+ let mut scratch = Scratch::open().await;
1137+ let user = alice(&scratch.store).await;
1138+ scratch.store.insert_file(&user.id, None, "old", b"data").await.unwrap();
1139+ // The database is behind the store: its rows are ancient, the objects
1140+ // beside them arrived since.
1141+ restamp_files(&scratch, "2000-01-01T00:00:00Z").await;
1142+ let unknown = scratch.storage.join("files").join("uploaded-elsewhere");
1143+ std::fs::write(&unknown, b"a real upload").unwrap();
1144+ let staged = scratch.storage.join("uploads").join("live-session");
1145+ std::fs::create_dir_all(&staged).unwrap();
1146+ scratch.reopen().await;
1147+ assert!(unknown.exists());
1148+ assert!(staged.exists());
1149+}
1150+
1151+/// A fresh database against a populated bucket is the stale case at its
1152+/// worst: it knows no moment at all, so it may reclaim nothing.
1153+#[tokio::test]
1154+async fn the_boot_sweep_keeps_everything_when_the_database_is_empty() {
1155+ let mut scratch = Scratch::open().await;
1156+ let stray = scratch.storage.join("files").join("stray");
1157+ std::fs::create_dir_all(stray.parent().unwrap()).unwrap();
1158+ std::fs::write(&stray, b"someone else's upload").unwrap();
1159+ let ghost = scratch.storage.join("uploads").join("ghost");
1160+ std::fs::create_dir_all(&ghost).unwrap();
1161+ scratch.reopen().await;
1162+ assert!(stray.exists());
1163+ assert!(ghost.exists());
1164+}
1165+
1166+/// Thumbnails follow the files' rule, both ways.
1167+#[tokio::test]
1168+async fn the_boot_sweep_weighs_thumbnails_by_the_same_watermark() {
1169+ let mut scratch = Scratch::open().await;
1170+ let user = alice(&scratch.store).await;
1171+ scratch.store.insert_file(&user.id, None, "row", b"data").await.unwrap();
1172+ let thumbs = scratch.storage.join("thumbs");
1173+ std::fs::create_dir_all(&thumbs).unwrap();
1174+ let old = thumbs.join("stale-thumb");
1175+ std::fs::write(&old, b"orphan").unwrap();
1176+ restamp_files(&scratch, "2099-01-01T00:00:00Z").await;
1177+ scratch.reopen().await;
1178+ assert!(!old.exists());
1179+
1180+ let new = thumbs.join("fresh-thumb");
1181+ std::fs::write(&new, b"newer than the database").unwrap();
1182+ restamp_files(&scratch, "2000-01-01T00:00:00Z").await;
1183+ scratch.reopen().await;
1184+ assert!(new.exists());
1185+}
1186+
11111187 #[tokio::test]
11121188 async fn a_row_whose_file_is_missing_is_kept() {
11131189 let mut scratch = Scratch::open().await;
@@ -1174,7 +1250,7 @@ async fn the_sweep_waits_for_a_writer_instead_of_deleting_its_file() {
11741250 "INSERT INTO file (id, owner_id, folder_id, name, mime, size_bytes, \
11751251 thumb_state, created_at, updated_at, deleted_at, download_count) \
11761252 VALUES ('midwrite', ?1, NULL, 'midwrite.txt', 'text/plain', 8, 'none', \
1177- '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', NULL, 0)",
1253+ '2099-01-01T00:00:00Z', '2099-01-01T00:00:00Z', NULL, 0)",
11781254 turso::params![user.id.as_str()],
11791255 )
11801256 .await
@@ -1916,18 +1992,21 @@ async fn r2_purge_takes_the_key_and_the_bucket_forgets_it() {
19161992 async fn r2_the_sweep_takes_orphans_and_leaves_known_keys() {
19171993 let scratch = R2Scratch::open().await;
19181994 let alice = alice(&scratch.store).await;
1919- let file = scratch
1920- .store
1921- .insert_file(alice.id.as_str(), None, "kept.bin", b"kept bytes")
1922- .await
1923- .unwrap();
19241995 // A client-side PUT with no row behind it — the exact shape the boot
1925- // sweep's orphan pass exists to clean.
1996+ // sweep's orphan pass exists to clean. It lands BEFORE the row below,
1997+ // which is what makes it older than the database's newest moment and so
1998+ // reclaimable; an object newer than that is an upload the database has
1999+ // not heard of and is kept.
19262000 scratch
19272001 .blobs
19282002 .put("files/orphaned-by-crash", b"stray")
19292003 .await
19302004 .unwrap();
2005+ let file = scratch
2006+ .store
2007+ .insert_file(alice.id.as_str(), None, "kept.bin", b"kept bytes")
2008+ .await
2009+ .unwrap();
19312010 // `boot_sweeps` runs the orphan sweep over the bucket, exactly as the
19322011 // server does in its background task.
19332012 scratch.store.boot_sweeps().await.unwrap();