fix(export): refuse an export that cannot fit, and stop peaking at two generations
Nothing in export.rs ever asked whether the keepsake would fit. Both archives write
their media `Compression::Stored`, so each is essentially a byte-for-byte second copy
of the originals -- Gallery.zip always, and Memories.zip for every video and every
image at or under 5 MB. On the documented CX33 (80 GB, all three volumes on one
filesystem) the upload quota's fixed point leaves ~40 GB free, and a release spawns
BOTH halves concurrently against it.
The failure is not "the export failed", it is "the deliverable is stuck":
1. ENOSPC lands partway through a multi-GB write.
2. The epoch has already moved, so the job row is `failed` at the CURRENT
generation and readiness (epoch = event.export_epoch AND status = 'done') is
false -- GET /export/zip 404s.
3. The last good archive sits on disk, unreferenced and unreachable.
4. POST /host/export/rebuild, the only escape, re-arms the same doomed write.
Three changes.
Reclaim before building. `prune_stale_export_files` ran only after the new archive
was written, renamed and finalised. That reads as durability but buys nothing: the
moment `invalidate_and_arm` bumps the epoch the old archive is ALREADY unreachable,
so keeping it reserves gigabytes for a download nobody can perform -- and for a
takedown it is content someone explicitly asked to have removed. Peak usage is now
one generation. Narrower than the post-finalize prune on purpose: final archives
only, never a `.tmp` or a `viewer_tmp_` dir, since a superseded worker can still be
streaming into those and at build START is far more likely to be alive.
Preflight the space. SUM(original_size_bytes) over exactly `query_uploads`'
visibility filter, +10% for ZIP overhead, multiplied by the number of armed jobs --
without that multiplier each of the two concurrent halves independently sees "it
fits" and together they don't. Runs AFTER claim_job, not before as reported: bailing
before the claim leaves the row `pending` with no worker and no error, the
spinner-forever state `mark_failed`'s status guard exists to prevent. Fails open when
the mount can't be read, exactly as the upload quota does.
Show the host the reason. /export/status returned {status, progress_pct} and nothing
else, so the host dashboard could only render "fehlgeschlagen" next to the retry
button. The message was written to the row and surfaced solely in the ADMIN job list
-- a different screen, possibly a different person. It now travels with the status,
and only on a failure, so a message left on a since-succeeded row can't appear beside
a green "ist bereit".
Tests: 10 unit (the u128 clamp caught a real bug in the first draft -- saturating_mul
then /100 turns an overflow into a number ~100x too small, the one direction that
authorises the write being guarded against; the carried-forward archive must survive
its own older epoch in the filename), 4 DB-backed (the estimate is asserted against
the row set the archive actually contains, not against a restatement of the WHERE
clause, so the two queries cannot drift), 3 e2e over the four-hop plumbing.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -255,3 +255,85 @@ pub async fn downloadable(pool: &PgPool, event_id: Uuid, export_type: &str) -> O
|
||||
.expect("downloadable")
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Insert an upload of `size` bytes, optionally already soft-deleted.
|
||||
pub async fn seed_upload(
|
||||
pool: &PgPool,
|
||||
event_id: Uuid,
|
||||
user_id: Uuid,
|
||||
size: i64,
|
||||
deleted: bool,
|
||||
) -> Uuid {
|
||||
sqlx::query_scalar(
|
||||
"INSERT INTO upload (event_id, user_id, original_path, mime_type,
|
||||
original_size_bytes, deleted_at)
|
||||
VALUES ($1, $2, 'originals/x.jpg', 'image/jpeg', $3,
|
||||
CASE WHEN $4 THEN NOW() ELSE NULL END)
|
||||
RETURNING id",
|
||||
)
|
||||
.bind(event_id)
|
||||
.bind(user_id)
|
||||
.bind(size)
|
||||
.bind(deleted)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.expect("seed upload")
|
||||
}
|
||||
|
||||
/// Flip the moderation flags a ban sets.
|
||||
pub async fn set_user_moderation(pool: &PgPool, user_id: Uuid, banned: bool, hidden: bool) {
|
||||
sqlx::query("UPDATE \"user\" SET is_banned = $2, uploads_hidden = $3 WHERE id = $1")
|
||||
.bind(user_id)
|
||||
.bind(banned)
|
||||
.bind(hidden)
|
||||
.execute(pool)
|
||||
.await
|
||||
.expect("set moderation");
|
||||
}
|
||||
|
||||
/// SRC: `services/export.rs::query_uploads` — the visibility filter, verbatim, projected down to
|
||||
/// `(id, original_size_bytes)`. This is the row set that ACTUALLY lands in the archives.
|
||||
pub async fn export_visible_uploads(pool: &PgPool, event_id: Uuid) -> Vec<(Uuid, i64)> {
|
||||
sqlx::query_as(
|
||||
"SELECT u.id, u.original_size_bytes
|
||||
FROM upload u
|
||||
JOIN \"user\" usr ON usr.id = u.user_id
|
||||
WHERE u.event_id = $1 AND u.deleted_at IS NULL
|
||||
AND usr.uploads_hidden = FALSE AND usr.is_banned = FALSE
|
||||
GROUP BY u.id, usr.display_name
|
||||
ORDER BY u.created_at ASC",
|
||||
)
|
||||
.bind(event_id)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("export_visible_uploads")
|
||||
}
|
||||
|
||||
/// SRC: `services/export.rs::estimate_export_bytes` — verbatim.
|
||||
pub async fn estimate_export_bytes(pool: &PgPool, event_id: Uuid) -> i64 {
|
||||
let (bytes,): (i64,) = sqlx::query_as(
|
||||
"SELECT COALESCE(SUM(u.original_size_bytes), 0)::bigint
|
||||
FROM upload u
|
||||
JOIN \"user\" usr ON usr.id = u.user_id
|
||||
WHERE u.event_id = $1 AND u.deleted_at IS NULL
|
||||
AND usr.uploads_hidden = FALSE AND usr.is_banned = FALSE",
|
||||
)
|
||||
.bind(event_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.expect("estimate_export_bytes");
|
||||
bytes
|
||||
}
|
||||
|
||||
/// SRC: `services/export.rs::ensure_export_space` — the armed-job count, verbatim.
|
||||
pub async fn armed_job_count(pool: &PgPool, event_id: Uuid) -> i64 {
|
||||
let (n,): (i64,) = sqlx::query_as(
|
||||
"SELECT COUNT(*) FROM export_job
|
||||
WHERE event_id = $1 AND status IN ('pending', 'running')",
|
||||
)
|
||||
.bind(event_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.expect("armed_job_count");
|
||||
n
|
||||
}
|
||||
|
||||
154
backend/tests/export_preflight.rs
Normal file
154
backend/tests/export_preflight.rs
Normal file
@@ -0,0 +1,154 @@
|
||||
//! DB-backed tests for the export disk preflight.
|
||||
//!
|
||||
//! The keepsake used to be built with NO free-space check at all, and the failure that produced was
|
||||
//! not "the export failed" but "the deliverable is stuck and the escape hatch needs the space that
|
||||
//! isn't there":
|
||||
//!
|
||||
//! 1. A takedown bumps the epoch and re-arms both halves.
|
||||
//! 2. The ZIP hits ENOSPC partway through a multi-GB write.
|
||||
//! 3. The job row is now `failed` at the CURRENT epoch, so readiness
|
||||
//! (`epoch = event.export_epoch AND status = 'done'`) is false and `GET /export/zip` 404s —
|
||||
//! while the last good archive sits on disk, unreferenced and unreachable.
|
||||
//! 4. `POST /host/export/rebuild` re-arms the same doomed write.
|
||||
//!
|
||||
//! Two changes close it: reclaim the superseded generation BEFORE building (so peak usage is one
|
||||
//! generation, not two) and refuse up front with a number the host can act on.
|
||||
//!
|
||||
//! What these tests pin is the ESTIMATE — the part that decides. The arithmetic on top of it lives
|
||||
//! in `services/export.rs`'s unit tests; the filesystem selection lives in `is_superseded_archive`.
|
||||
//! The risk here is drift: if `query_uploads` ever gains or loses a visibility predicate and
|
||||
//! `estimate_export_bytes` doesn't, the preflight silently sizes the wrong gallery. So rather than
|
||||
//! restating the filter, these assert the estimate against the row set the archive actually
|
||||
//! contains.
|
||||
|
||||
mod common;
|
||||
|
||||
use common::*;
|
||||
use sqlx::PgPool;
|
||||
|
||||
/// The estimate must equal the sum over EXACTLY the rows `query_uploads` returns — computed from
|
||||
/// that row set, not from a restatement of its WHERE clause.
|
||||
///
|
||||
/// PREVENTS: the two queries drifting apart. An estimate that counts rows the archive skips is
|
||||
/// merely pessimistic; one that MISSES rows the archive writes under-reserves, which is the whole
|
||||
/// failure being guarded against.
|
||||
#[sqlx::test]
|
||||
async fn the_estimate_sums_exactly_the_rows_the_archive_will_contain(pool: PgPool) {
|
||||
let event_id = seed_event(&pool, "wedding").await;
|
||||
|
||||
let visible = seed_user(&pool, event_id, "Anna").await;
|
||||
let banned = seed_user(&pool, event_id, "Ben").await;
|
||||
let hidden = seed_user(&pool, event_id, "Cara").await;
|
||||
|
||||
seed_upload(&pool, event_id, visible, 1_000, false).await;
|
||||
seed_upload(&pool, event_id, visible, 2_500, false).await;
|
||||
// Each of these is excluded from the archive by a DIFFERENT predicate.
|
||||
seed_upload(&pool, event_id, visible, 9_000, true).await; // soft-deleted
|
||||
seed_upload(&pool, event_id, banned, 9_000, false).await; // uploader banned
|
||||
seed_upload(&pool, event_id, hidden, 9_000, false).await; // uploads hidden
|
||||
|
||||
set_user_moderation(&pool, banned, true, true).await;
|
||||
set_user_moderation(&pool, hidden, false, true).await;
|
||||
|
||||
let rows = export_visible_uploads(&pool, event_id).await;
|
||||
let expected: i64 = rows.iter().map(|(_, bytes)| bytes).sum();
|
||||
|
||||
assert_eq!(rows.len(), 2, "only Anna's two live uploads are archived");
|
||||
assert_eq!(
|
||||
estimate_export_bytes(&pool, event_id).await,
|
||||
expected,
|
||||
"the preflight must size the gallery the export will actually write"
|
||||
);
|
||||
assert_eq!(expected, 3_500);
|
||||
}
|
||||
|
||||
/// An event with nothing to archive estimates zero rather than NULL.
|
||||
///
|
||||
/// PREVENTS: `SUM()` over no rows returning NULL and the decode blowing up — which would abort the
|
||||
/// export with a type error instead of building an (entirely legitimate) empty keepsake.
|
||||
#[sqlx::test]
|
||||
async fn an_empty_gallery_estimates_zero_not_null(pool: PgPool) {
|
||||
let event_id = seed_event(&pool, "wedding").await;
|
||||
assert_eq!(estimate_export_bytes(&pool, event_id).await, 0);
|
||||
|
||||
// And with a user who has uploaded nothing.
|
||||
seed_user(&pool, event_id, "Anna").await;
|
||||
assert_eq!(estimate_export_bytes(&pool, event_id).await, 0);
|
||||
}
|
||||
|
||||
/// A release arms both halves, so the preflight sees a count of 2 and reserves for the pair.
|
||||
///
|
||||
/// PREVENTS: the concurrency under-reservation. `spawn_export_jobs` starts the ZIP and HTML workers
|
||||
/// at the same instant, and BOTH are gallery-sized (`Memories.zip` streams the original for every
|
||||
/// video and every image at or under 5 MB, all `Compression::Stored`). A worker reserving only for
|
||||
/// itself would see "it fits", its sibling would independently see the same, and together they
|
||||
/// would ENOSPC — which is why `required_free_bytes` multiplies by this count.
|
||||
#[sqlx::test]
|
||||
async fn a_release_arms_both_halves_so_the_preflight_reserves_for_two(pool: PgPool) {
|
||||
let event_id = seed_event(&pool, "wedding").await;
|
||||
let user = seed_user(&pool, event_id, "Anna").await;
|
||||
seed_upload(&pool, event_id, user, 1_000, false).await;
|
||||
|
||||
assert_eq!(
|
||||
armed_job_count(&pool, event_id).await,
|
||||
0,
|
||||
"nothing is armed before the release"
|
||||
);
|
||||
|
||||
let epoch = release_gallery(&pool, "wedding").await.expect("released");
|
||||
assert_eq!(
|
||||
armed_job_count(&pool, event_id).await,
|
||||
2,
|
||||
"a release arms zip AND html — both compete for the same disk"
|
||||
);
|
||||
|
||||
// A worker that has claimed its half is still competing; `running` must keep counting.
|
||||
assert!(claim_job(&pool, event_id, "zip", epoch).await);
|
||||
assert_eq!(
|
||||
armed_job_count(&pool, event_id).await,
|
||||
2,
|
||||
"claiming moves pending -> running, which must not drop out of the reservation"
|
||||
);
|
||||
|
||||
// Only a FINISHED half stops competing.
|
||||
assert!(finalize_job(&pool, event_id, "zip", epoch, "exports/Gallery.zip").await);
|
||||
assert_eq!(
|
||||
armed_job_count(&pool, event_id).await,
|
||||
1,
|
||||
"a done half no longer needs space reserved for it"
|
||||
);
|
||||
}
|
||||
|
||||
/// A ViewerOnly regeneration re-arms only the HTML half, so the preflight reserves for one.
|
||||
///
|
||||
/// PREVENTS: over-reservation refusing a rebuild that fits perfectly well. Moderating a comment
|
||||
/// carries the finished ZIP forward untouched; demanding room for a second copy of it would fail
|
||||
/// the one operation that needs no new gallery-sized write at all.
|
||||
#[sqlx::test]
|
||||
async fn a_viewer_only_regeneration_reserves_for_one_half(pool: PgPool) {
|
||||
let event_id = seed_event(&pool, "wedding").await;
|
||||
let user = seed_user(&pool, event_id, "Anna").await;
|
||||
seed_upload(&pool, event_id, user, 1_000, false).await;
|
||||
|
||||
let epoch = release_gallery(&pool, "wedding").await.expect("released");
|
||||
for t in ["zip", "html"] {
|
||||
assert!(claim_job(&pool, event_id, t, epoch).await);
|
||||
assert!(finalize_job(&pool, event_id, t, epoch, &format!("exports/{t}")).await);
|
||||
}
|
||||
assert_eq!(armed_job_count(&pool, event_id).await, 0);
|
||||
|
||||
// A moderated comment: bump the epoch, carry the ZIP forward, re-arm only the viewer.
|
||||
let (_, _, next) = bump_epoch(&pool, "wedding").await.expect("bumped");
|
||||
assert!(
|
||||
carry_zip_forward(&pool, event_id, next).await,
|
||||
"the finished ZIP is re-stamped, not rebuilt"
|
||||
);
|
||||
let mut conn = pool.acquire().await.expect("acquire");
|
||||
enqueue_types_at_epoch(&mut conn, event_id, next, &["html"]).await;
|
||||
|
||||
assert_eq!(
|
||||
armed_job_count(&pool, event_id).await,
|
||||
1,
|
||||
"only the viewer is being rebuilt, so only one archive's worth of space is needed"
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user