From 2eab9e2a5565991f772835c5368dc7a97ffa5c1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 5 Aug 2026 21:05:08 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=96=BC=EF=B8=8F=20fix:=20stop=20image=20s?= =?UTF-8?q?lots=20orphaning=20rows=20and=20blobs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit bank_question_image was the only child in its domain whose write moved nothing on its parent, and BankQuestion::delete was two round trips rather than one transaction. An upload whose body was still streaming when the template was deleted left a metadata row and a blob that no route could read or remove. Three more of one shape: store_image read the slot's current row to learn which blob to retire and then upserted, so two concurrent uploads both retired the same old blob and stranded the loser's new one. Fixed on the bank, exam-question and answer-image paths alike by reading the replaced name inside the write's own transaction — the shape PoolQuestion::set_image already used. delete_question no longer unlinks blobs from a pre-read snapshot; the delete returns the rows it actually swept, as Note::delete does. BankQuestion::update_if_unchanged moves to write_with_retry: the image upsert now writes the template row, so a raced PATCH would otherwise have started answering 500. --- src/domain/answer_image.rs | 43 ++++- src/domain/bank_question.rs | 146 +++++++++----- src/domain/bank_question_image.rs | 303 ++++++++++++++++++++++++++++-- src/domain/question_image.rs | 51 +++-- src/web/bank_questions.rs | 23 ++- src/web/exams/images.rs | 28 ++- tests/regress_bank_images.rs | 206 ++++++++++++++++++++ 7 files changed, 697 insertions(+), 103 deletions(-) create mode 100644 tests/regress_bank_images.rs diff --git a/src/domain/answer_image.rs b/src/domain/answer_image.rs index dfdc1f5..dbcc8ef 100644 --- a/src/domain/answer_image.rs +++ b/src/domain/answer_image.rs @@ -68,6 +68,16 @@ pub struct AnswerImage { size: i64, } +/// What one [`AnswerImage::upsert`] transaction returns: the row it stored and +/// the blob name it replaced. Both are arrays because SurrealDB drops an object +/// key valued `NONE` on the way out, while an empty array survives — "nothing +/// was replaced" has to be readable, not missing. +#[derive(SurrealValue)] +struct UpsertOutcome { + stored: Vec, + replaced: Vec, +} + impl AnswerImage { /// Assemble a row (fresh blob name generated here) without persisting it. /// The caller writes the blob under [`Self::get_file`] first, then calls @@ -115,7 +125,15 @@ impl AnswerImage { /// Create or replace the student's drawing for the question — the /// deterministic id makes this the whole "one drawing per student per - /// question" story. + /// question" story — handing back what it stored plus the blob name it + /// replaced, for the caller to take off disk. + /// + /// The replaced name is read *here*, inside this transaction, not by the + /// caller in front of it: two uploads to one (question, user, seq) both + /// write this row, so they contend and the loser re-reads the winner's blob + /// name, where two pre-reads both saw the *old* blob and left the loser's + /// fresh one on disk with nothing pointing at it. Same shape as + /// [`crate::domain::question_image::QuestionImage::upsert`]. /// /// `NotFound` = the exam is gone, and the drawing was *not* written. The /// write moves the exam's mark counter and puts it straight back, in this @@ -141,7 +159,7 @@ impl AnswerImage { /// `UPSERT`'s id is bijective with the (question, user, seq) triple this /// table keys — a lost round wrote nothing, and re-sending resolves onto /// the same row rather than colliding with it. - pub async fn upsert(self, db: &Database) -> Result { + pub async fn upsert(self, db: &Database) -> Result<(AnswerImage, Option), AppError> { // whole-row-save-ok: self is built in place from the request, never read back, and the (question, user, seq) id is deterministic — replacing the row *is* the operation let (exam, id) = (self.exam.record(), self.id.record()); let (mut result, mut errors) = transaction_with_retry( @@ -153,8 +171,9 @@ impl AnswerImage { ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); IF array::len($touched) = 0 {{ THROW 'no_exam' }}; UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = $was; + LET $replaced = (SELECT VALUE file FROM $id); LET $row = (UPSERT $id CONTENT $image RETURN AFTER); - RETURN $row[0]; + RETURN {{ stored: $row, replaced: $replaced }}; COMMIT TRANSACTION;" ), &[ @@ -180,11 +199,14 @@ impl AnswerImage { // slot follows the statement count rather than a hand-kept number; // `num_statements` counts BEGIN and COMMIT. let slot = result.num_statements().saturating_sub(2); - result - .take::>(slot)? + let failed = || AppError::Internal("failed to store answer image".into()); + let outcome = result + .take::>(slot)? .into_iter() .next() - .ok_or_else(|| AppError::Internal("failed to store answer image".into())) + .ok_or_else(failed)?; + let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; + Ok((stored, outcome.replaced.into_iter().next())) } /// The student's drawing for one question in one sitting, if any. @@ -318,16 +340,19 @@ mod tests { let question = ExamQuestionId::generate(); let user = student(); - let first = AnswerImage::new(&exam, &question, &user, 1, png(), 3) + let (first, retired) = AnswerImage::new(&exam, &question, &user, 1, png(), 3) .upsert(&db) .await .unwrap(); - let second = AnswerImage::new(&exam, &question, &user, 1, png(), 5) + assert_eq!(retired, None, "a first upload retires no blob"); + let (second, retired) = AnswerImage::new(&exam, &question, &user, 1, png(), 5) .upsert(&db) .await .unwrap(); - // Same (question, user, seq), same row — the replace swapped the blob. + // Same (question, user, seq), same row — the replace swapped the blob, + // and the write itself names the blob the caller must unlink. assert_ne!(first.get_file(), second.get_file()); + assert_eq!(retired.as_deref(), Some(first.get_file())); let rows = AnswerImage::list_for_exam_user(&exam, &user, 1, &db) .await .unwrap(); diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index 897e629..4fd24a1 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -14,7 +14,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ BANK_QUESTION_TABLE, BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL, USAGE_COUNTS_SQL, }; -use crate::database::Database; +use crate::database::{Database, transaction_with_retry, write_with_retry}; +use crate::domain::bank_question_image::BankQuestionImage; use crate::domain::exam::ExamId; use crate::domain::exam_question::{ Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, @@ -74,6 +75,15 @@ struct UsageCount { n: i64, } +/// What one [`BankQuestion::delete`] transaction removed — the template (an +/// empty list once someone else deleted it first) and the image rows swept +/// with it. +#[derive(SurrealValue)] +struct DeleteOutcome { + question: Vec, + images: Vec, +} + impl BankQuestionId { /// A write-ordered id. `list` sorts `id DESC` to mean "newest first", and /// a random ULID is only millisecond-accurate — templates saved inside one @@ -395,6 +405,14 @@ impl BankQuestion { /// the `SET` writes. `choices` is compared whole: its objects carry two /// required string keys, so none is ever dropped for being `NONE` (the trap /// [`crate::domain::settings::Settings::save_if_unchanged`] works around). + /// + /// Rides [`write_with_retry`] because an image write now moves this row too + /// ([`crate::domain::bank_question_image::BankQuestionImage::upsert`]): an + /// upload landing in the same instant makes the store answer "conflict, + /// retry", and a bare `check()` would turn that into a 500 for an edit that + /// only had to be re-sent. A lost round writes nothing, and the guard is + /// re-evaluated on the next one, so a genuine stale merge still comes back + /// as `None`. Admissible: an `UPDATE` can never answer "already exists". pub async fn update_if_unchanged( self, subject: Option, @@ -405,40 +423,60 @@ impl BankQuestion { db: &Database, ) -> Result, AppError> { let (kind, choices, correct) = spec.into_parts(); - let mut result = db - .query( - "UPDATE $id SET subject = $subject, text = $text, points = $points, - kind = $kind, choices = $choices, correct = $correct, - visibility = $visibility - WHERE subject = $was_subject AND text = $was_text - AND points = $was_points AND kind = $was_kind - AND choices = $was_choices AND correct = $was_correct - AND visibility = $was_visibility - RETURN AFTER", - ) - .bind(("was_subject", self.subject.clone().map(|s| s.record()))) - .bind(("was_text", self.text.clone())) - .bind(("was_points", self.points)) - .bind(("was_kind", self.kind.clone())) - .bind(("was_choices", self.choices.clone())) - .bind(("was_correct", self.correct.clone())) - .bind(("was_visibility", self.visibility.clone())) - .bind(("id", self.id.record())) - .bind(("subject", subject.map(|s| s.record()))) - .bind(("text", text)) - .bind(("points", points)) - .bind(("kind", kind)) - .bind(("choices", choices)) - .bind(("correct", correct)) - .bind(("visibility", visibility)) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + let rows: Vec = write_with_retry( + db, + "UPDATE $id SET subject = $subject, text = $text, points = $points, + kind = $kind, choices = $choices, correct = $correct, + visibility = $visibility + WHERE subject = $was_subject AND text = $was_text + AND points = $was_points AND kind = $was_kind + AND choices = $was_choices AND correct = $was_correct + AND visibility = $was_visibility + RETURN AFTER", + &[ + ( + "was_subject".into(), + self.subject.clone().map(|s| s.record()).into_value(), + ), + ("was_text".into(), self.text.clone().into_value()), + ("was_points".into(), self.points.into_value()), + ("was_kind".into(), self.kind.clone().into_value()), + ("was_choices".into(), self.choices.clone().into_value()), + ("was_correct".into(), self.correct.clone().into_value()), + ( + "was_visibility".into(), + self.visibility.clone().into_value(), + ), + ("id".into(), self.id.record().into_value()), + ("subject".into(), subject.map(|s| s.record()).into_value()), + ("text".into(), text.into_value()), + ("points".into(), points.into_value()), + ("kind".into(), kind.into_value()), + ("choices".into(), choices.into_value()), + ("correct".into(), correct.into_value()), + ("visibility".into(), visibility.into_value()), + ], + ) + .await?; + Ok(rows.into_iter().next()) } /// Delete the template and cascade-remove its bank images, so none points - /// at a missing template. Bank rows have no answers. The image *blobs* are - /// the web layer's to remove — it collects their names before calling this. + /// at a missing template. Bank rows have no answers. The image rows this + /// actually removed come back with it: the blobs are the web layer's to + /// take off disk, but only for *these* rows — an upload that committed + /// after the caller listed the template's images is swept here too, and a + /// pre-read snapshot would strand its blob for good + /// ([`crate::domain::note::Note::delete`]'s story, this domain over). + /// + /// Children first, in one transaction: as two queries, a failure between + /// them left image rows swept under a template that survived, or (the other + /// order) a template gone with its images still there. Rides the retry + /// because an image write now moves this very row + /// ([`crate::domain::bank_question_image::BankQuestionImage::upsert`]) — the + /// two contend by design, and a lost round through a bare `check()` would be + /// a 500 for a delete that only had to be re-sent. Admissible: no `UPDATE` + /// or `DELETE` in here can answer "already exists". /// /// Exam questions tied to this template keep living: only their provenance /// links are cleared, field-scoped (never a whole-row save — the question @@ -446,17 +484,41 @@ impl BankQuestion { /// a template that no longer exists. *Both* directions point at a template, /// so both are cleared: `from_bank` on the questions instantiated from it, /// and `banked_as` on the question it was saved out of. - pub async fn delete(self, db: &Database) -> Result { - db.query( - "DELETE bank_question_image WHERE bank_question = $b; + pub async fn delete( + self, + db: &Database, + ) -> Result<(BankQuestion, Vec), AppError> { + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + LET $images = (DELETE bank_question_image WHERE bank_question = $b RETURN BEFORE); UPDATE exam_question SET from_bank = NONE WHERE from_bank = $b; - UPDATE exam_question SET banked_as = NONE WHERE banked_as = $b;", + UPDATE exam_question SET banked_as = NONE WHERE banked_as = $b; + LET $gone = (DELETE $b RETURN BEFORE); + RETURN { question: $gone, images: $images }; + COMMIT TRANSACTION;", + &[("b".into(), self.id.record().into_value())], + &[], ) - .bind(("b", self.id.record())) - .await? - .check()?; - let deleted: Option = db.delete(self.id.record()).await?; - deleted.ok_or(AppError::NotFound) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is the last statement before `COMMIT`, so its + // slot follows the statement count rather than a hand-kept number; + // `num_statements` counts BEGIN and COMMIT. + let slot = result.num_statements().saturating_sub(2); + let outcome = result + .take::>(slot)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to delete bank question".into()))?; + let question = outcome + .question + .into_iter() + .next() + .ok_or(AppError::NotFound)?; + Ok((question, outcome.images)) } #[allow(clippy::too_many_arguments)] @@ -784,7 +846,7 @@ mod tests { // A real subject row: an exam question claims a reference on its // subject, so a minted id it never wrote would be refused. let subject = crate::domain::subject::Subject::create( - &crate::domain::course::CourseId::generate(), + &crate::domain::course::a_test_course(&db).await, crate::domain::subject::SubjectName::try_new("topic").unwrap(), crate::domain::subject::SubjectDescription::try_new("").unwrap(), &db, diff --git a/src/domain/bank_question_image.rs b/src/domain/bank_question_image.rs index f81ba99..3a6cc14 100644 --- a/src/domain/bank_question_image.rs +++ b/src/domain/bank_question_image.rs @@ -14,7 +14,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; use crate::constant::BANK_QUESTION_IMAGE_TABLE; -use crate::database::Database; +use crate::database::{Database, transaction_with_retry}; use crate::domain::bank_question::BankQuestionId; use crate::domain::exam_question::ChoiceId; use crate::domain::key; @@ -59,6 +59,16 @@ pub struct BankQuestionImage { size: i64, } +/// What one [`BankQuestionImage::upsert`] transaction returns: the row it +/// stored and the blob name it replaced. Both are arrays because SurrealDB +/// drops an object key valued `NONE` on the way out, while an empty array +/// survives — "nothing was replaced" has to be readable, not missing. +#[derive(SurrealValue)] +struct UpsertOutcome { + stored: Vec, + replaced: Vec, +} + impl BankQuestionImage { /// Assemble a row (fresh blob name generated here) without persisting it. /// The caller writes the blob under [`Self::get_file`] first, then calls @@ -99,12 +109,84 @@ impl BankQuestionImage { self.size } - /// Create or replace the slot's image row — the deterministic id makes - /// this the whole "one image per slot" story. - pub async fn upsert(self, db: &Database) -> Result { + /// Create or replace the slot's image row — the deterministic id makes this + /// the whole "one image per slot" story — handing back what it stored plus + /// the blob name it replaced, for the caller to take off disk. + /// + /// Both halves are the transaction's doing. The template's own `points` is + /// moved and put straight back inside it, the way + /// [`crate::domain::pool_question::bump_question_and_write`] moves + /// `asked_at` (`created_at` is `READONLY`, so the move goes on the one other + /// int column): that makes the template's *existence* part of this write. + /// A bare `UPSERT` guarded by having read the template first does not + /// survive its delete window — the read sees a row + /// [`crate::domain::bank_question::BankQuestion::delete`] has removed but + /// not committed, while that delete's image sweep ran on a snapshot + /// predating this row, so both commit and the image outlives the template + /// it hangs on. Nothing could ever read, delete, or sweep it afterwards: + /// every image route goes through the template. Moving the value makes the + /// two transactions touch one key, so the store refuses a side; writing the + /// same value back would be elided and collide with nothing. + /// + /// The replaced blob name comes out of this same transaction rather than a + /// read in front of it (the shape + /// [`crate::domain::pool_question::PoolQuestion::set_image`] has): two + /// uploads to one slot both write this row, so they contend and the loser + /// re-reads the winner's blob name, where two pre-reads both saw the *old* + /// blob and left the loser's fresh one orphaned on disk. + /// + /// Admissible for [`transaction_with_retry`]: the `UPSERT`'s id is + /// deterministic per (question, slot) and the table carries no `UNIQUE` + /// index, so the write always resolves onto the row its id names and can + /// never answer "already exists". + pub async fn upsert( + self, + db: &Database, + ) -> Result<(BankQuestionImage, Option), AppError> { // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic - let written: Option = db.upsert(self.id.record()).content(self).await?; - written.ok_or_else(|| AppError::Internal("failed to store bank question image".into())) + let (question, id) = (self.bank_question.record(), self.id.record()); + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + LET $was_points = (SELECT VALUE points FROM ONLY $b); + LET $bumped = (UPDATE $b SET points = points + 1 RETURN VALUE id); + IF array::len($bumped) = 0 { THROW 'no_question' }; + UPDATE $b SET points = $was_points; + LET $replaced = (SELECT VALUE file FROM $id); + LET $stored = (UPSERT $id CONTENT $image); + RETURN { stored: $stored, replaced: $replaced }; + COMMIT TRANSACTION;", + &[ + ("b".into(), question.into_value()), + ("id".into(), id.into_value()), + ("image".into(), self.into_value()), + ], + &["no_question"], + ) + .await?; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the reason. + if errors + .values() + .any(|error| error.to_string().contains("no_question")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is the last statement before `COMMIT`, so its + // slot follows the statement count rather than a hand-kept number; + // `num_statements` counts BEGIN and COMMIT. + let slot = result.num_statements().saturating_sub(2); + let failed = || AppError::Internal("failed to store bank question image".into()); + let outcome = result + .take::>(slot)? + .into_iter() + .next() + .ok_or_else(failed)?; + let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; + Ok((stored, outcome.replaced.into_iter().next())) } pub async fn read_slot( @@ -183,12 +265,29 @@ impl BankQuestionImage { #[cfg(test)] mod tests { use super::*; + use crate::domain::bank_question::BankQuestion; use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec}; fn png() -> FileContentType { FileContentType::try_new("image/png").unwrap() } + /// A real template row: an image write moves its `points` inside its own + /// transaction, so a minted id nothing ever wrote is refused. + async fn a_template(db: &Database) -> BankQuestionId { + let id = BankQuestionId::generate(); + db.query( + "CREATE $b SET owner = user:u, text = 'soru', kind = 'text', points = 5, + visibility = 'private', created_at = 1", + ) + .bind(("b", id.record())) + .await + .unwrap() + .check() + .unwrap(); + id + } + fn choice_ids() -> Vec { QuestionSpec::try_new( QuestionKind::try_new("choice").unwrap(), @@ -235,18 +334,21 @@ mod tests { #[tokio::test] async fn upsert_replaces_per_slot() { let db = crate::database::init_mem().await.unwrap(); - let question = BankQuestionId::generate(); + let question = a_template(&db).await; - let first = BankQuestionImage::new(&question, None, png(), 3) + let (first, retired) = BankQuestionImage::new(&question, None, png(), 3) .upsert(&db) .await .unwrap(); - let second = BankQuestionImage::new(&question, None, png(), 5) + assert_eq!(retired, None, "a first upload retires no blob"); + let (second, retired) = BankQuestionImage::new(&question, None, png(), 5) .upsert(&db) .await .unwrap(); - // Same slot, same row — the replace swapped the blob pointer. + // Same slot, same row — the replace swapped the blob pointer, and the + // write itself names the blob the caller must unlink. assert_ne!(first.get_file(), second.get_file()); + assert_eq!(retired.as_deref(), Some(first.get_file())); let rows = BankQuestionImage::list_for_question(&question, &db) .await .unwrap(); @@ -259,7 +361,7 @@ mod tests { #[tokio::test] async fn only_the_dropped_options_lose_their_pictures() { let db = crate::database::init_mem().await.unwrap(); - let question = BankQuestionId::generate(); + let question = a_template(&db).await; let ids = choice_ids(); BankQuestionImage::new(&question, None, png(), 1) .upsert(&db) @@ -288,7 +390,7 @@ mod tests { #[tokio::test] async fn an_empty_keep_set_clears_every_option_picture() { let db = crate::database::init_mem().await.unwrap(); - let question = BankQuestionId::generate(); + let question = a_template(&db).await; let ids = choice_ids(); BankQuestionImage::new(&question, None, png(), 1) .upsert(&db) @@ -313,4 +415,181 @@ mod tests { assert_eq!(left.len(), 1); assert_eq!(left[0].get_slot(), None); } + + /// The [`crate::domain::pool_question::PoolQuestion`] defect, one domain + /// over: an image written inside its template's delete window must not + /// outlive it. Guarding the write by *reading* the template does not do it + /// — the read sees a row [`BankQuestion::delete`] has removed but not + /// committed, while its `DELETE bank_question_image WHERE bank_question = + /// $b` ran on a snapshot predating this row, so both commit and the image + /// is left pointing at a template that is gone. Nothing can reach it after + /// that: every image route resolves the template first, no boot sweep + /// visits this table, and its blob stays on disk for good. [`Self::upsert`] + /// moves the template's own `points` instead, so the two transactions touch + /// one key and the store refuses a side. + /// + /// The blob half is asserted through the list the delete hands back: that + /// list — never a snapshot read before it — is what the web layer unlinks + /// from, so an image that committed inside the window and is *not* in it is + /// a blob stranded on disk. + /// + /// The window is opened by the schema, not by a lucky interleaving: a + /// `DEFINE EVENT` on `bank_question` fires inside the delete's own + /// transaction the instant the row goes. + /// + /// Real server, and `#[ignore]`d for it: the subject *is* the store's + /// conflict detection, which `init_mem`'s embedded engine does not have — + /// it commits both and answers `Ok` to each, so this passes there on broken + /// code. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn an_image_written_inside_a_delete_window_never_outlives_its_template() { + let (db, _serialized) = crate::database::init_test_server("bank_image_race").await; + db.query( + "DEFINE EVENT hold_the_window ON TABLE bank_question WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let (mut swept, mut orphans, mut stranded) = (0, 0, 0); + for round in 0..4 { + let question = a_template(&db).await; + let template = BankQuestion::read(&question, &db).await.unwrap().unwrap(); + + let drop_it = { + let db = db.clone(); + tokio::spawn(async move { template.delete(&db).await }) + }; + // The upload starts inside the held window — the template row is + // gone but uncommitted, which is exactly what the handler's + // ownership read believes. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let child = { + let (db, question) = (db.clone(), question.clone()); + tokio::spawn(async move { + BankQuestionImage::new(&question, None, png(), 3) + .upsert(&db) + .await + }) + }; + let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); + // A 404 for the upload is a correct answer; the only defect is + // stored state. Neither side may 500 — they contend by design and a + // lost round is re-sent, not reported. + assert!( + !matches!(child, Err(AppError::Db(_))), + "round {round}: a raced upload must be answered, not 500: {child:?}" + ); + assert!( + !matches!(drop_it, Err(AppError::Db(_))), + "round {round}: a raced delete must retry, not 500: {drop_it:?}" + ); + + // Stored state is the whole verdict; a return value is not evidence. + if BankQuestion::read(&question, &db).await.unwrap().is_none() { + swept += 1; + orphans += BankQuestionImage::list_for_question(&question, &db) + .await + .unwrap() + .len(); + if let (Ok((stored, _)), Ok((_, images))) = (&child, &drop_it) + && !images + .iter() + .any(|image| image.get_file() == stored.get_file()) + { + stranded += 1; + } + } + } + eprintln!("BankQuestion::delete raced by an upload: {swept}/4 rounds deleted the template"); + assert!( + swept > 0, + "no round ever deleted the template, so the window was never reached" + ); + assert_eq!(orphans, 0, "an image row outlived its template"); + assert_eq!( + stranded, 0, + "an image committed inside the window was swept without being handed back, so its blob stays on disk" + ); + } + + /// Two uploads to one slot must leave exactly one live blob and hand every + /// other one back to be unlinked. Reading the slot's old blob name *before* + /// the write gave both racers the same answer: both retired the same old + /// blob, and the loser's fresh one stayed on disk with nothing naming it. + /// [`Self::upsert`] reads it inside its own transaction instead, so the + /// loser contends on the row it writes and re-reads the winner's name. + /// + /// The overlap is forced rather than hoped for: a `DEFINE EVENT` on this + /// table holds the first write open inside its own transaction, so the + /// second reads the slot before the first commits. + /// + /// Real server, and `#[ignore]`d for it, for the reason above: the embedded + /// engine has no write-write conflict detection to make a loser re-read. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn two_uploads_to_one_slot_leave_no_blob_unretired() { + let (db, _serialized) = crate::database::init_test_server("bank_image_replace").await; + db.query( + "DEFINE EVENT hold_the_write ON TABLE bank_question_image WHEN true \ + THEN { SLEEP 300ms; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let mut unretired = 0; + for round in 0..3 { + let question = a_template(&db).await; + // A first picture, so both racers have an old blob to retire. + let (original, _) = BankQuestionImage::new(&question, None, png(), 1) + .upsert(&db) + .await + .unwrap(); + + let mut writes = Vec::new(); + for size in [2, 3] { + let (db, question) = (db.clone(), question.clone()); + writes.push(tokio::spawn(async move { + BankQuestionImage::new(&question, None, png(), size) + .upsert(&db) + .await + })); + } + let mut written = vec![original.get_file().to_string()]; + let mut retired = Vec::new(); + for write in writes { + let (stored, replaced) = write.await.unwrap().unwrap_or_else(|err| { + panic!("round {round}: a raced upload must not 500: {err:?}") + }); + written.push(stored.get_file().to_string()); + retired.extend(replaced); + } + + // Stored state is the whole verdict: exactly one blob is live, and + // every other one this round wrote must have been handed back — + // once. A name written and never returned is a file on disk with + // nothing pointing at it. + let live = BankQuestionImage::read_slot(&question, None, &db) + .await + .unwrap() + .unwrap(); + assert!( + !retired.iter().any(|name| name == live.get_file()), + "round {round}: the live row's own blob was retired" + ); + unretired += written + .iter() + .filter(|name| *name != live.get_file() && !retired.contains(name)) + .count(); + } + assert_eq!( + unretired, 0, + "a blob was written and never handed back to be unlinked — it stays on disk forever" + ); + } } diff --git a/src/domain/question_image.rs b/src/domain/question_image.rs index e0c78eb..dee6e2a 100644 --- a/src/domain/question_image.rs +++ b/src/domain/question_image.rs @@ -61,6 +61,16 @@ pub struct QuestionImage { size: i64, } +/// What one [`QuestionImage::upsert`] transaction returns: the row it stored +/// and the blob name it replaced. Both are arrays because SurrealDB drops an +/// object key valued `NONE` on the way out, while an empty array survives — +/// "nothing was replaced" has to be readable, not missing. +#[derive(SurrealValue)] +struct UpsertOutcome { + stored: Vec, + replaced: Vec, +} + impl QuestionImage { /// Assemble a row (fresh blob name generated here) without persisting it. /// The caller writes the blob under [`Self::get_file`] first, then calls @@ -104,15 +114,24 @@ impl QuestionImage { } /// Create or replace the slot's image row — the deterministic id makes - /// this the whole "one image per slot" story. Refused once the exam has an - /// attempt: pictures are part of the question, so they freeze with it, and - /// the gate is in this transaction rather than in a lock the caller held. - pub async fn upsert(self, db: &Database) -> Result { + /// this the whole "one image per slot" story — handing back what it stored + /// plus the blob name it replaced, for the caller to take off disk. Refused + /// once the exam has an attempt: pictures are part of the question, so they + /// freeze with it, and the gate is in this transaction rather than in a lock + /// the caller held. + /// + /// The replaced name is read *here*, not by the caller before it: two + /// uploads to one slot both write this row, so they contend and the loser + /// re-reads the winner's blob name, where two pre-reads both saw the *old* + /// blob and left the loser's fresh one orphaned on disk. + pub async fn upsert(self, db: &Database) -> Result<(QuestionImage, Option), AppError> { // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic let (exam, id) = (self.exam.clone(), self.id.record()); let mut result = ExamAttempt::write_unfrozen( &exam, - "UPSERT $id CONTENT $image;", + "LET $replaced = (SELECT VALUE file FROM $id); + LET $stored = (UPSERT $id CONTENT $image); + RETURN { stored: $stored, replaced: $replaced };", vec![ ("id".into(), id.into_value()), ("image".into(), self.into_value()), @@ -120,11 +139,18 @@ impl QuestionImage { db, ) .await?; - result - .take::>(ExamAttempt::FROZEN_SLOT)? + // The trailing `RETURN` is the last statement before `COMMIT`, so its + // slot follows the statement count rather than a hand-kept number; + // `num_statements` counts BEGIN and COMMIT. + let slot = result.num_statements().saturating_sub(2); + let failed = || AppError::Internal("failed to store question image".into()); + let outcome = result + .take::>(slot)? .into_iter() .next() - .ok_or_else(|| AppError::Internal("failed to store question image".into())) + .ok_or_else(failed)?; + let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; + Ok((stored, outcome.replaced.into_iter().next())) } pub async fn read_slot( @@ -275,16 +301,19 @@ mod tests { let question = ExamQuestionId::generate(); let ids = choice_ids(); - let first = QuestionImage::new(&exam, &question, None, png(), 3) + let (first, retired) = QuestionImage::new(&exam, &question, None, png(), 3) .upsert(&db) .await .unwrap(); - let second = QuestionImage::new(&exam, &question, None, png(), 5) + assert_eq!(retired, None, "a first upload retires no blob"); + let (second, retired) = QuestionImage::new(&exam, &question, None, png(), 5) .upsert(&db) .await .unwrap(); - // Same slot, same row — the replace swapped the blob pointer. + // Same slot, same row — the replace swapped the blob pointer, and the + // write itself names the blob the caller must unlink. assert_ne!(first.get_file(), second.get_file()); + assert_eq!(retired.as_deref(), Some(first.get_file())); let rows = QuestionImage::list_for_question(&question, &db) .await .unwrap(); diff --git a/src/web/bank_questions.rs b/src/web/bank_questions.rs index 1830cc4..bb83457 100644 --- a/src/web/bank_questions.rs +++ b/src/web/bank_questions.rs @@ -401,9 +401,12 @@ async fn owned_question(st: &AppState, user: &User, bid: &str) -> Result Result { - let replaced = BankQuestionImage::read_slot(question, slot, &st.db).await?; let image = BankQuestionImage::new(question, slot, content_type, data.len() as i64); let file = image.get_file().to_string(); - store_blob(st, &file, data, || async { - let stored = image.upsert(&st.db).await?; - Ok((stored, replaced.map(|old| old.get_file().to_string()))) - }) - .await + store_blob(st, &file, data, || async { image.upsert(&st.db).await }).await } /// Add a template to the bank. Requires teacher+. `subject_id` is origin @@ -729,9 +727,10 @@ async fn delete_question( ) -> Result { let question = owned_question(&st, &user, &bid).await?; // Rows go first (the delete cascades the image rows), blobs after — a crash - // in between strands at worst an unreachable blob. - let images = BankQuestionImage::list_for_question(question.get_id(), &st.db).await?; - question.delete(&st.db).await?; + // in between strands at worst an unreachable blob. The blobs come from what + // the delete *swept*, never a list read before it: an upload that landed in + // between is swept too, and its blob would be stranded for good. + let (_, images) = question.delete(&st.db).await?; for image in &images { remove_blob(&st.files_path, image.get_file()).await; } diff --git a/src/web/exams/images.rs b/src/web/exams/images.rs index 7b8d1d1..6e70e9c 100644 --- a/src/web/exams/images.rs +++ b/src/web/exams/images.rs @@ -119,9 +119,12 @@ pub(crate) async fn ensure_question_content_visible( Ok(()) } -/// The image write tail, shared by both upload endpoints: the slot's current -/// row names the blob to retire, the UPSERT replaces it (the deterministic -/// per-slot id makes it a replace), and [`store_blob`] owns the disk ordering. +/// The image write tail, shared by both upload endpoints: the UPSERT replaces +/// the slot's row (the deterministic per-slot id makes it a replace) and names +/// the blob it retired *from inside its own transaction*, and [`store_blob`] +/// owns the disk ordering. Reading the slot out here first instead would hand +/// two uploads racing on one slot the same old blob name, leaving the loser's +/// fresh one on disk with no row pointing at it. pub(crate) async fn store_image( st: &AppState, exam: &Exam, @@ -130,7 +133,6 @@ pub(crate) async fn store_image( content_type: FileContentType, data: &[u8], ) -> Result { - let replaced = QuestionImage::read_slot(question.get_id(), slot, &st.db).await?; let image = QuestionImage::new( exam.get_id(), question.get_id(), @@ -139,11 +141,7 @@ pub(crate) async fn store_image( data.len() as i64, ); let file = image.get_file().to_string(); - store_blob(st, &file, data, || async { - let stored = image.upsert(&st.db).await?; - Ok((stored, replaced.map(|old| old.get_file().to_string()))) - }) - .await + store_blob(st, &file, data, || async { image.upsert(&st.db).await }).await } /// The stored bytes, served inline via [`crate::web::serve_inline_blob`]. @@ -395,8 +393,9 @@ pub(crate) async fn delete_choice_image( // content's own visibility (own sitting view / teacher grading view). /// The answer-image write tail, mirroring [`store_image`]: the deterministic -/// per-(question, user, seq) id makes the UPSERT a replace, and [`store_blob`] -/// owns the disk ordering. +/// per-(question, user, seq) id makes the UPSERT a replace, the write names the +/// blob it retired from inside its own transaction, and [`store_blob`] owns the +/// disk ordering. pub(crate) async fn store_answer_image( st: &AppState, exam: &Exam, @@ -406,7 +405,6 @@ pub(crate) async fn store_answer_image( content_type: FileContentType, data: &[u8], ) -> Result { - let replaced = AnswerImage::read(question.get_id(), user, seq, &st.db).await?; let image = AnswerImage::new( exam.get_id(), question.get_id(), @@ -416,11 +414,7 @@ pub(crate) async fn store_answer_image( data.len() as i64, ); let file = image.get_file().to_string(); - store_blob(st, &file, data, || async { - let stored = image.upsert(&st.db).await?; - Ok((stored, replaced.map(|old| old.get_file().to_string()))) - }) - .await + store_blob(st, &file, data, || async { image.upsert(&st.db).await }).await } /// Attach (or replace) the caller's drawn answer to a question inside their diff --git a/tests/regress_bank_images.rs b/tests/regress_bank_images.rs new file mode 100644 index 0000000..1608dee --- /dev/null +++ b/tests/regress_bank_images.rs @@ -0,0 +1,206 @@ +//! A bank template's images must never outlive the template, and every blob +//! must have a row pointing at it. +//! +//! `bank_question_image` was the one child in this domain whose write did not +//! touch its parent, and `BankQuestion::delete` the one cascade here that was +//! not a single transaction. Between them an upload that started before a +//! delete and landed after it left a row *and* a blob nothing could ever read, +//! delete, or sweep: every image route goes through the template, and no boot +//! sweep visits this table. The third hole was one round trip wide — the slot's +//! old blob name was read *before* the write, so two uploads to one slot both +//! retired the same old blob and one of the two fresh ones was left on disk +//! with nothing pointing at it. +//! +//! Stored state is the whole verdict here, on both sides: the row (is the +//! orphan there?) and the disk (is the blob still in `files_path`?). Each test +//! gets a blob directory of its own so a file count means something. +//! +//! These two need no server, so they run in CI by default. The *raced* halves +//! of the same three holes live beside the code they test, in +//! `bank_question_image`'s own test module, where `init_test_server` and +//! `RACE_LOCK` are in reach: the store's conflict detection is their subject, +//! and re-spelling the real bootstrap out here would be a hand-kept copy that +//! drifts silently the first time migration or router construction changes. + +mod common; + +use axum::Router; +use axum::http::StatusCode; +use common::{create_course, create_subject, id_of, login_as, send}; +use hezarfen_backend::database::Database; +use hezarfen_backend::domain::bank_question::BankQuestionId; +use hezarfen_backend::domain::bank_question_image::BankQuestionImage; +use hezarfen_backend::domain::note_file::FileContentType; +use hezarfen_backend::error::AppError; +use hezarfen_backend::rate_limit::RateLimitConfig; +use hezarfen_backend::state::AppState; +use hezarfen_backend::{build_router, database}; +use serde_json::json; +use tempfile::TempDir; + +const BOUNDARY: &str = "multipart/form-data; boundary=hezarfen-test-boundary"; + +/// A router over a fresh in-memory database, with a blob directory nothing else +/// writes to — so `blobs()` counts this test's files and no one else's. +async fn mem_app() -> (Router, Database, TempDir) { + let db = database::init_mem().await.expect("in-memory db"); + let files = tempfile::tempdir().expect("files tempdir"); + let app = build_router(AppState { + db: db.clone(), + files_path: files.path().to_path_buf(), + cookie_secure: false, + rate_limit: RateLimitConfig::unlimited(), + chatbot_limit: Default::default(), + exam_presence: Default::default(), + board_hub: Default::default(), + db_up: Default::default(), + ai: None, + }); + (app, db, files) +} + +/// Every blob file currently on disk, by name. +fn blobs(files: &TempDir) -> Vec { + let mut names: Vec = std::fs::read_dir(files.path()) + .expect("read the blob dir") + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names +} + +/// A template owned by `who`, under a fresh course + subject; returns its id. +async fn template(app: &Router, who: &str, name: &str) -> String { + let course = create_course(app, who, &format!("Ders {name}")).await; + let subject = create_subject(app, who, &course, name).await; + let res = send( + app, + "POST", + "/bank-questions", + Some(who), + Some(json!({ "subject_id": subject, "text": "soru", "kind": "text", "points": 3 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + id_of(&res.body) +} + +/// Upload an illustration onto the template; returns the status. +async fn upload(app: &Router, who: &str, bid: &str, bytes: &[u8]) -> StatusCode { + let (status, _, _) = common::send_raw( + app, + "POST", + &format!("/bank-questions/{bid}/image"), + Some(who), + Some(BOUNDARY), + common::multipart_file("pic.png", "image/png", bytes), + ) + .await; + status +} + +fn png() -> FileContentType { + FileContentType::try_new("image/png").unwrap() +} + +/// The template's existence is part of the image write itself, not a read in +/// front of it: writing a slot under a template that is gone is refused, and +/// stores nothing. Before the fix this was a bare `UPSERT` that cheerfully +/// created the row — a row no route could reach afterwards, since every image +/// endpoint resolves the template first, and no boot sweep touches this table. +/// +/// Deterministic, no race needed: the parent is already gone. The *raced* +/// version of the same hole is +/// `an_upload_inside_a_delete_window_leaves_no_orphan_row_or_blob` below. +#[tokio::test] +async fn an_image_write_under_a_missing_template_is_refused() { + let (app, db, _files) = mem_app().await; + let teacher = login_as(&app, &db, "ogretmen_banka", "teacher").await; + let bid = template(&app, &teacher, "optik").await; + + let dropped = send( + &app, + "DELETE", + &format!("/bank-questions/{bid}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(dropped.status, StatusCode::NO_CONTENT); + + let question = BankQuestionId::from_key(&bid); + let refused = BankQuestionImage::new(&question, None, png(), 3) + .upsert(&db) + .await; + assert!( + matches!(refused, Err(AppError::NotFound)), + "a slot write under a deleted template must be refused: {refused:?}" + ); + // Stored state is the verdict — a refusal that still wrote the row would be + // the very defect this pins. + assert!( + BankQuestionImage::list_for_question(&question, &db) + .await + .unwrap() + .is_empty(), + "the refused write left an orphan row" + ); +} + +/// The disk contract, end to end: a replace retires exactly the blob it +/// replaced (never the fresh one), and deleting the template takes the blobs of +/// the rows its cascade *swept* off disk with it. +#[tokio::test] +async fn a_replace_retires_one_blob_and_a_delete_takes_the_rest() { + let (app, db, files) = mem_app().await; + let teacher = login_as(&app, &db, "ogretmen_disk", "teacher").await; + let bid = template(&app, &teacher, "akustik").await; + + assert_eq!( + upload(&app, &teacher, &bid, b"first").await, + StatusCode::CREATED + ); + assert_eq!(blobs(&files).len(), 1, "the first upload is on disk"); + + assert_eq!( + upload(&app, &teacher, &bid, b"second").await, + StatusCode::CREATED + ); + let after = blobs(&files); + assert_eq!( + after.len(), + 1, + "a replace retires the blob it replaced: {after:?}" + ); + let question = BankQuestionId::from_key(&bid); + let rows = BankQuestionImage::list_for_question(&question, &db) + .await + .unwrap(); + assert_eq!(rows.len(), 1, "one row per slot"); + assert_eq!( + after, + vec![rows[0].get_file().to_string()], + "the surviving blob is the one the row points at" + ); + + let dropped = send( + &app, + "DELETE", + &format!("/bank-questions/{bid}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(dropped.status, StatusCode::NO_CONTENT); + assert!( + blobs(&files).is_empty(), + "the delete left a blob behind: {:?}", + blobs(&files) + ); + assert!( + BankQuestionImage::list_for_question(&question, &db) + .await + .unwrap() + .is_empty() + ); +}