forge
Explore
Log in

Don't you dare go Hollow

Stop image slots orphaning rows and blobs

Browse files at this commit

2eab9e2a5565991f772835c5368dc7a97ffa5c1bAhmet Kaan GümüşParent: 420deef
  • fix
    • stop image slots orphaning rows and blobs
Show full message
🖼️ fix: stop image slots orphaning rows and blobs

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.rsmodified+34 -9
@@ -68,6 +68,16 @@ pub struct AnswerImage {
68 size: i64,68 size: i64,
69 }69 }
70 70
71+/// What one [`AnswerImage::upsert`] transaction returns: the row it stored and
72+/// the blob name it replaced. Both are arrays because SurrealDB drops an object
73+/// key valued `NONE` on the way out, while an empty array survives — "nothing
74+/// was replaced" has to be readable, not missing.
75+#[derive(SurrealValue)]
76+struct UpsertOutcome {
77+ stored: Vec<AnswerImage>,
78+ replaced: Vec<String>,
79+}
80+
71 impl AnswerImage {81 impl AnswerImage {
72 /// Assemble a row (fresh blob name generated here) without persisting it.82 /// Assemble a row (fresh blob name generated here) without persisting it.
73 /// The caller writes the blob under [`Self::get_file`] first, then calls83 /// The caller writes the blob under [`Self::get_file`] first, then calls
@@ -115,7 +125,15 @@ impl AnswerImage {
115 125
116 /// Create or replace the student's drawing for the question — the126 /// Create or replace the student's drawing for the question — the
117 /// deterministic id makes this the whole "one drawing per student per127 /// deterministic id makes this the whole "one drawing per student per
118- /// question" story.128+ /// question" story — handing back what it stored plus the blob name it
129+ /// replaced, for the caller to take off disk.
130+ ///
131+ /// The replaced name is read *here*, inside this transaction, not by the
132+ /// caller in front of it: two uploads to one (question, user, seq) both
133+ /// write this row, so they contend and the loser re-reads the winner's blob
134+ /// name, where two pre-reads both saw the *old* blob and left the loser's
135+ /// fresh one on disk with nothing pointing at it. Same shape as
136+ /// [`crate::domain::question_image::QuestionImage::upsert`].
119 ///137 ///
120 /// `NotFound` = the exam is gone, and the drawing was *not* written. The138 /// `NotFound` = the exam is gone, and the drawing was *not* written. The
121 /// write moves the exam's mark counter and puts it straight back, in this139 /// write moves the exam's mark counter and puts it straight back, in this
@@ -141,7 +159,7 @@ impl AnswerImage {
141 /// `UPSERT`'s id is bijective with the (question, user, seq) triple this159 /// `UPSERT`'s id is bijective with the (question, user, seq) triple this
142 /// table keys — a lost round wrote nothing, and re-sending resolves onto160 /// table keys — a lost round wrote nothing, and re-sending resolves onto
143 /// the same row rather than colliding with it.161 /// the same row rather than colliding with it.
144- pub async fn upsert(self, db: &Database) -> Result<AnswerImage, AppError> {162+ pub async fn upsert(self, db: &Database) -> Result<(AnswerImage, Option<String>), AppError> {
145 // 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 operation163 // 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
146 let (exam, id) = (self.exam.record(), self.id.record());164 let (exam, id) = (self.exam.record(), self.id.record());
147 let (mut result, mut errors) = transaction_with_retry(165 let (mut result, mut errors) = transaction_with_retry(
@@ -153,8 +171,9 @@ impl AnswerImage {
153 ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id);171 ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id);
154 IF array::len($touched) = 0 {{ THROW 'no_exam' }};172 IF array::len($touched) = 0 {{ THROW 'no_exam' }};
155 UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = $was;173 UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = $was;
174+ LET $replaced = (SELECT VALUE file FROM $id);
156 LET $row = (UPSERT $id CONTENT $image RETURN AFTER);175 LET $row = (UPSERT $id CONTENT $image RETURN AFTER);
157- RETURN $row[0];176+ RETURN {{ stored: $row, replaced: $replaced }};
158 COMMIT TRANSACTION;"177 COMMIT TRANSACTION;"
159 ),178 ),
160 &[179 &[
@@ -180,11 +199,14 @@ impl AnswerImage {
180 // slot follows the statement count rather than a hand-kept number;199 // slot follows the statement count rather than a hand-kept number;
181 // `num_statements` counts BEGIN and COMMIT.200 // `num_statements` counts BEGIN and COMMIT.
182 let slot = result.num_statements().saturating_sub(2);201 let slot = result.num_statements().saturating_sub(2);
183- result202+ let failed = || AppError::Internal("failed to store answer image".into());
184- .take::<Vec<AnswerImage>>(slot)?203+ let outcome = result
204+ .take::<Vec<UpsertOutcome>>(slot)?
185 .into_iter()205 .into_iter()
186 .next()206 .next()
187- .ok_or_else(|| AppError::Internal("failed to store answer image".into()))207+ .ok_or_else(failed)?;
208+ let stored = outcome.stored.into_iter().next().ok_or_else(failed)?;
209+ Ok((stored, outcome.replaced.into_iter().next()))
188 }210 }
189 211
190 /// The student's drawing for one question in one sitting, if any.212 /// The student's drawing for one question in one sitting, if any.
@@ -318,16 +340,19 @@ mod tests {
318 let question = ExamQuestionId::generate();340 let question = ExamQuestionId::generate();
319 let user = student();341 let user = student();
320 342
321- let first = AnswerImage::new(&exam, &question, &user, 1, png(), 3)343+ let (first, retired) = AnswerImage::new(&exam, &question, &user, 1, png(), 3)
322 .upsert(&db)344 .upsert(&db)
323 .await345 .await
324 .unwrap();346 .unwrap();
325- let second = AnswerImage::new(&exam, &question, &user, 1, png(), 5)347+ assert_eq!(retired, None, "a first upload retires no blob");
348+ let (second, retired) = AnswerImage::new(&exam, &question, &user, 1, png(), 5)
326 .upsert(&db)349 .upsert(&db)
327 .await350 .await
328 .unwrap();351 .unwrap();
329- // Same (question, user, seq), same row — the replace swapped the blob.352+ // Same (question, user, seq), same row — the replace swapped the blob,
353+ // and the write itself names the blob the caller must unlink.
330 assert_ne!(first.get_file(), second.get_file());354 assert_ne!(first.get_file(), second.get_file());
355+ assert_eq!(retired.as_deref(), Some(first.get_file()));
331 let rows = AnswerImage::list_for_exam_user(&exam, &user, 1, &db)356 let rows = AnswerImage::list_for_exam_user(&exam, &user, 1, &db)
332 .await357 .await
333 .unwrap();358 .unwrap();
src/domain/bank_question.rsmodified+104 -42
@@ -14,7 +14,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
14 use crate::constant::{14 use crate::constant::{
15 BANK_QUESTION_TABLE, BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL, USAGE_COUNTS_SQL,15 BANK_QUESTION_TABLE, BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL, USAGE_COUNTS_SQL,
16 };16 };
17-use crate::database::Database;17+use crate::database::{Database, transaction_with_retry, write_with_retry};
18+use crate::domain::bank_question_image::BankQuestionImage;
18 use crate::domain::exam::ExamId;19 use crate::domain::exam::ExamId;
19 use crate::domain::exam_question::{20 use crate::domain::exam_question::{
20 Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,21 Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
@@ -74,6 +75,15 @@ struct UsageCount {
74 n: i64,75 n: i64,
75 }76 }
76 77
78+/// What one [`BankQuestion::delete`] transaction removed — the template (an
79+/// empty list once someone else deleted it first) and the image rows swept
80+/// with it.
81+#[derive(SurrealValue)]
82+struct DeleteOutcome {
83+ question: Vec<BankQuestion>,
84+ images: Vec<BankQuestionImage>,
85+}
86+
77 impl BankQuestionId {87 impl BankQuestionId {
78 /// A write-ordered id. `list` sorts `id DESC` to mean "newest first", and88 /// A write-ordered id. `list` sorts `id DESC` to mean "newest first", and
79 /// a random ULID is only millisecond-accurate — templates saved inside one89 /// a random ULID is only millisecond-accurate — templates saved inside one
@@ -395,6 +405,14 @@ impl BankQuestion {
395 /// the `SET` writes. `choices` is compared whole: its objects carry two405 /// the `SET` writes. `choices` is compared whole: its objects carry two
396 /// required string keys, so none is ever dropped for being `NONE` (the trap406 /// required string keys, so none is ever dropped for being `NONE` (the trap
397 /// [`crate::domain::settings::Settings::save_if_unchanged`] works around).407 /// [`crate::domain::settings::Settings::save_if_unchanged`] works around).
408+ ///
409+ /// Rides [`write_with_retry`] because an image write now moves this row too
410+ /// ([`crate::domain::bank_question_image::BankQuestionImage::upsert`]): an
411+ /// upload landing in the same instant makes the store answer "conflict,
412+ /// retry", and a bare `check()` would turn that into a 500 for an edit that
413+ /// only had to be re-sent. A lost round writes nothing, and the guard is
414+ /// re-evaluated on the next one, so a genuine stale merge still comes back
415+ /// as `None`. Admissible: an `UPDATE` can never answer "already exists".
398 pub async fn update_if_unchanged(416 pub async fn update_if_unchanged(
399 self,417 self,
400 subject: Option<SubjectId>,418 subject: Option<SubjectId>,
@@ -405,40 +423,60 @@ impl BankQuestion {
405 db: &Database,423 db: &Database,
406 ) -> Result<Option<BankQuestion>, AppError> {424 ) -> Result<Option<BankQuestion>, AppError> {
407 let (kind, choices, correct) = spec.into_parts();425 let (kind, choices, correct) = spec.into_parts();
408- let mut result = db426+ let rows: Vec<BankQuestion> = write_with_retry(
409- .query(427+ db,
410- "UPDATE $id SET subject = $subject, text = $text, points = $points,428+ "UPDATE $id SET subject = $subject, text = $text, points = $points,
411- kind = $kind, choices = $choices, correct = $correct,429+ kind = $kind, choices = $choices, correct = $correct,
412- visibility = $visibility430+ visibility = $visibility
413- WHERE subject = $was_subject AND text = $was_text431+ WHERE subject = $was_subject AND text = $was_text
414- AND points = $was_points AND kind = $was_kind432+ AND points = $was_points AND kind = $was_kind
415- AND choices = $was_choices AND correct = $was_correct433+ AND choices = $was_choices AND correct = $was_correct
416- AND visibility = $was_visibility434+ AND visibility = $was_visibility
417- RETURN AFTER",435+ RETURN AFTER",
418- )436+ &[
419- .bind(("was_subject", self.subject.clone().map(|s| s.record())))437+ (
420- .bind(("was_text", self.text.clone()))438+ "was_subject".into(),
421- .bind(("was_points", self.points))439+ self.subject.clone().map(|s| s.record()).into_value(),
422- .bind(("was_kind", self.kind.clone()))440+ ),
423- .bind(("was_choices", self.choices.clone()))441+ ("was_text".into(), self.text.clone().into_value()),
424- .bind(("was_correct", self.correct.clone()))442+ ("was_points".into(), self.points.into_value()),
425- .bind(("was_visibility", self.visibility.clone()))443+ ("was_kind".into(), self.kind.clone().into_value()),
426- .bind(("id", self.id.record()))444+ ("was_choices".into(), self.choices.clone().into_value()),
427- .bind(("subject", subject.map(|s| s.record())))445+ ("was_correct".into(), self.correct.clone().into_value()),
428- .bind(("text", text))446+ (
429- .bind(("points", points))447+ "was_visibility".into(),
430- .bind(("kind", kind))448+ self.visibility.clone().into_value(),
431- .bind(("choices", choices))449+ ),
432- .bind(("correct", correct))450+ ("id".into(), self.id.record().into_value()),
433- .bind(("visibility", visibility))451+ ("subject".into(), subject.map(|s| s.record()).into_value()),
434- .await?452+ ("text".into(), text.into_value()),
435- .check()?;453+ ("points".into(), points.into_value()),
436- Ok(result.take::<Vec<BankQuestion>>(0)?.into_iter().next())454+ ("kind".into(), kind.into_value()),
455+ ("choices".into(), choices.into_value()),
456+ ("correct".into(), correct.into_value()),
457+ ("visibility".into(), visibility.into_value()),
458+ ],
459+ )
460+ .await?;
461+ Ok(rows.into_iter().next())
437 }462 }
438 463
439 /// Delete the template and cascade-remove its bank images, so none points464 /// Delete the template and cascade-remove its bank images, so none points
440- /// at a missing template. Bank rows have no answers. The image *blobs* are465+ /// at a missing template. Bank rows have no answers. The image rows this
441- /// the web layer's to remove — it collects their names before calling this.466+ /// actually removed come back with it: the blobs are the web layer's to
467+ /// take off disk, but only for *these* rows — an upload that committed
468+ /// after the caller listed the template's images is swept here too, and a
469+ /// pre-read snapshot would strand its blob for good
470+ /// ([`crate::domain::note::Note::delete`]'s story, this domain over).
471+ ///
472+ /// Children first, in one transaction: as two queries, a failure between
473+ /// them left image rows swept under a template that survived, or (the other
474+ /// order) a template gone with its images still there. Rides the retry
475+ /// because an image write now moves this very row
476+ /// ([`crate::domain::bank_question_image::BankQuestionImage::upsert`]) — the
477+ /// two contend by design, and a lost round through a bare `check()` would be
478+ /// a 500 for a delete that only had to be re-sent. Admissible: no `UPDATE`
479+ /// or `DELETE` in here can answer "already exists".
442 ///480 ///
443 /// Exam questions tied to this template keep living: only their provenance481 /// Exam questions tied to this template keep living: only their provenance
444 /// links are cleared, field-scoped (never a whole-row save — the question482 /// links are cleared, field-scoped (never a whole-row save — the question
@@ -446,17 +484,41 @@ impl BankQuestion {
446 /// a template that no longer exists. *Both* directions point at a template,484 /// a template that no longer exists. *Both* directions point at a template,
447 /// so both are cleared: `from_bank` on the questions instantiated from it,485 /// so both are cleared: `from_bank` on the questions instantiated from it,
448 /// and `banked_as` on the question it was saved out of.486 /// and `banked_as` on the question it was saved out of.
449- pub async fn delete(self, db: &Database) -> Result<BankQuestion, AppError> {487+ pub async fn delete(
450- db.query(488+ self,
451- "DELETE bank_question_image WHERE bank_question = $b;489+ db: &Database,
490+ ) -> Result<(BankQuestion, Vec<BankQuestionImage>), AppError> {
491+ let (mut result, mut errors) = transaction_with_retry(
492+ db,
493+ "BEGIN TRANSACTION;
494+ LET $images = (DELETE bank_question_image WHERE bank_question = $b RETURN BEFORE);
452 UPDATE exam_question SET from_bank = NONE WHERE from_bank = $b;495 UPDATE exam_question SET from_bank = NONE WHERE from_bank = $b;
453- UPDATE exam_question SET banked_as = NONE WHERE banked_as = $b;",496+ UPDATE exam_question SET banked_as = NONE WHERE banked_as = $b;
497+ LET $gone = (DELETE $b RETURN BEFORE);
498+ RETURN { question: $gone, images: $images };
499+ COMMIT TRANSACTION;",
500+ &[("b".into(), self.id.record().into_value())],
501+ &[],
454 )502 )
455- .bind(("b", self.id.record()))503+ .await?;
456- .await?504+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
457- .check()?;505+ return Err(error.into());
458- let deleted: Option<BankQuestion> = db.delete(self.id.record()).await?;506+ }
459- deleted.ok_or(AppError::NotFound)507+ // The trailing `RETURN` is the last statement before `COMMIT`, so its
508+ // slot follows the statement count rather than a hand-kept number;
509+ // `num_statements` counts BEGIN and COMMIT.
510+ let slot = result.num_statements().saturating_sub(2);
511+ let outcome = result
512+ .take::<Vec<DeleteOutcome>>(slot)?
513+ .into_iter()
514+ .next()
515+ .ok_or_else(|| AppError::Internal("failed to delete bank question".into()))?;
516+ let question = outcome
517+ .question
518+ .into_iter()
519+ .next()
520+ .ok_or(AppError::NotFound)?;
521+ Ok((question, outcome.images))
460 }522 }
461 523
462 #[allow(clippy::too_many_arguments)]524 #[allow(clippy::too_many_arguments)]
@@ -784,7 +846,7 @@ mod tests {
784 // A real subject row: an exam question claims a reference on its846 // A real subject row: an exam question claims a reference on its
785 // subject, so a minted id it never wrote would be refused.847 // subject, so a minted id it never wrote would be refused.
786 let subject = crate::domain::subject::Subject::create(848 let subject = crate::domain::subject::Subject::create(
787- &crate::domain::course::CourseId::generate(),849+ &crate::domain::course::a_test_course(&db).await,
788 crate::domain::subject::SubjectName::try_new("topic").unwrap(),850 crate::domain::subject::SubjectName::try_new("topic").unwrap(),
789 crate::domain::subject::SubjectDescription::try_new("").unwrap(),851 crate::domain::subject::SubjectDescription::try_new("").unwrap(),
790 &db,852 &db,
src/domain/bank_question_image.rsmodified+291 -12
@@ -14,7 +14,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
14 use ulid::Ulid;14 use ulid::Ulid;
15 15
16 use crate::constant::BANK_QUESTION_IMAGE_TABLE;16 use crate::constant::BANK_QUESTION_IMAGE_TABLE;
17-use crate::database::Database;17+use crate::database::{Database, transaction_with_retry};
18 use crate::domain::bank_question::BankQuestionId;18 use crate::domain::bank_question::BankQuestionId;
19 use crate::domain::exam_question::ChoiceId;19 use crate::domain::exam_question::ChoiceId;
20 use crate::domain::key;20 use crate::domain::key;
@@ -59,6 +59,16 @@ pub struct BankQuestionImage {
59 size: i64,59 size: i64,
60 }60 }
61 61
62+/// What one [`BankQuestionImage::upsert`] transaction returns: the row it
63+/// stored and the blob name it replaced. Both are arrays because SurrealDB
64+/// drops an object key valued `NONE` on the way out, while an empty array
65+/// survives — "nothing was replaced" has to be readable, not missing.
66+#[derive(SurrealValue)]
67+struct UpsertOutcome {
68+ stored: Vec<BankQuestionImage>,
69+ replaced: Vec<String>,
70+}
71+
62 impl BankQuestionImage {72 impl BankQuestionImage {
63 /// Assemble a row (fresh blob name generated here) without persisting it.73 /// Assemble a row (fresh blob name generated here) without persisting it.
64 /// The caller writes the blob under [`Self::get_file`] first, then calls74 /// The caller writes the blob under [`Self::get_file`] first, then calls
@@ -99,12 +109,84 @@ impl BankQuestionImage {
99 self.size109 self.size
100 }110 }
101 111
102- /// Create or replace the slot's image row — the deterministic id makes112+ /// Create or replace the slot's image row — the deterministic id makes this
103- /// this the whole "one image per slot" story.113+ /// the whole "one image per slot" story — handing back what it stored plus
104- pub async fn upsert(self, db: &Database) -> Result<BankQuestionImage, AppError> {114+ /// the blob name it replaced, for the caller to take off disk.
115+ ///
116+ /// Both halves are the transaction's doing. The template's own `points` is
117+ /// moved and put straight back inside it, the way
118+ /// [`crate::domain::pool_question::bump_question_and_write`] moves
119+ /// `asked_at` (`created_at` is `READONLY`, so the move goes on the one other
120+ /// int column): that makes the template's *existence* part of this write.
121+ /// A bare `UPSERT` guarded by having read the template first does not
122+ /// survive its delete window — the read sees a row
123+ /// [`crate::domain::bank_question::BankQuestion::delete`] has removed but
124+ /// not committed, while that delete's image sweep ran on a snapshot
125+ /// predating this row, so both commit and the image outlives the template
126+ /// it hangs on. Nothing could ever read, delete, or sweep it afterwards:
127+ /// every image route goes through the template. Moving the value makes the
128+ /// two transactions touch one key, so the store refuses a side; writing the
129+ /// same value back would be elided and collide with nothing.
130+ ///
131+ /// The replaced blob name comes out of this same transaction rather than a
132+ /// read in front of it (the shape
133+ /// [`crate::domain::pool_question::PoolQuestion::set_image`] has): two
134+ /// uploads to one slot both write this row, so they contend and the loser
135+ /// re-reads the winner's blob name, where two pre-reads both saw the *old*
136+ /// blob and left the loser's fresh one orphaned on disk.
137+ ///
138+ /// Admissible for [`transaction_with_retry`]: the `UPSERT`'s id is
139+ /// deterministic per (question, slot) and the table carries no `UNIQUE`
140+ /// index, so the write always resolves onto the row its id names and can
141+ /// never answer "already exists".
142+ pub async fn upsert(
143+ self,
144+ db: &Database,
145+ ) -> Result<(BankQuestionImage, Option<String>), AppError> {
105 // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic146 // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic
106- let written: Option<BankQuestionImage> = db.upsert(self.id.record()).content(self).await?;147+ let (question, id) = (self.bank_question.record(), self.id.record());
107- written.ok_or_else(|| AppError::Internal("failed to store bank question image".into()))148+ let (mut result, mut errors) = transaction_with_retry(
149+ db,
150+ "BEGIN TRANSACTION;
151+ LET $was_points = (SELECT VALUE points FROM ONLY $b);
152+ LET $bumped = (UPDATE $b SET points = points + 1 RETURN VALUE id);
153+ IF array::len($bumped) = 0 { THROW 'no_question' };
154+ UPDATE $b SET points = $was_points;
155+ LET $replaced = (SELECT VALUE file FROM $id);
156+ LET $stored = (UPSERT $id CONTENT $image);
157+ RETURN { stored: $stored, replaced: $replaced };
158+ COMMIT TRANSACTION;",
159+ &[
160+ ("b".into(), question.into_value()),
161+ ("id".into(), id.into_value()),
162+ ("image".into(), self.into_value()),
163+ ],
164+ &["no_question"],
165+ )
166+ .await?;
167+ // An aborted transaction errors *every* slot, most with a generic "not
168+ // executed" — only the THROW's own slot names the reason.
169+ if errors
170+ .values()
171+ .any(|error| error.to_string().contains("no_question"))
172+ {
173+ return Err(AppError::NotFound);
174+ }
175+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
176+ return Err(error.into());
177+ }
178+ // The trailing `RETURN` is the last statement before `COMMIT`, so its
179+ // slot follows the statement count rather than a hand-kept number;
180+ // `num_statements` counts BEGIN and COMMIT.
181+ let slot = result.num_statements().saturating_sub(2);
182+ let failed = || AppError::Internal("failed to store bank question image".into());
183+ let outcome = result
184+ .take::<Vec<UpsertOutcome>>(slot)?
185+ .into_iter()
186+ .next()
187+ .ok_or_else(failed)?;
188+ let stored = outcome.stored.into_iter().next().ok_or_else(failed)?;
189+ Ok((stored, outcome.replaced.into_iter().next()))
108 }190 }
109 191
110 pub async fn read_slot(192 pub async fn read_slot(
@@ -183,12 +265,29 @@ impl BankQuestionImage {
183 #[cfg(test)]265 #[cfg(test)]
184 mod tests {266 mod tests {
185 use super::*;267 use super::*;
268+ use crate::domain::bank_question::BankQuestion;
186 use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec};269 use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec};
187 270
188 fn png() -> FileContentType {271 fn png() -> FileContentType {
189 FileContentType::try_new("image/png").unwrap()272 FileContentType::try_new("image/png").unwrap()
190 }273 }
191 274
275+ /// A real template row: an image write moves its `points` inside its own
276+ /// transaction, so a minted id nothing ever wrote is refused.
277+ async fn a_template(db: &Database) -> BankQuestionId {
278+ let id = BankQuestionId::generate();
279+ db.query(
280+ "CREATE $b SET owner = user:u, text = 'soru', kind = 'text', points = 5,
281+ visibility = 'private', created_at = 1",
282+ )
283+ .bind(("b", id.record()))
284+ .await
285+ .unwrap()
286+ .check()
287+ .unwrap();
288+ id
289+ }
290+
192 fn choice_ids() -> Vec<ChoiceId> {291 fn choice_ids() -> Vec<ChoiceId> {
193 QuestionSpec::try_new(292 QuestionSpec::try_new(
194 QuestionKind::try_new("choice").unwrap(),293 QuestionKind::try_new("choice").unwrap(),
@@ -235,18 +334,21 @@ mod tests {
235 #[tokio::test]334 #[tokio::test]
236 async fn upsert_replaces_per_slot() {335 async fn upsert_replaces_per_slot() {
237 let db = crate::database::init_mem().await.unwrap();336 let db = crate::database::init_mem().await.unwrap();
238- let question = BankQuestionId::generate();337+ let question = a_template(&db).await;
239 338
240- let first = BankQuestionImage::new(&question, None, png(), 3)339+ let (first, retired) = BankQuestionImage::new(&question, None, png(), 3)
241 .upsert(&db)340 .upsert(&db)
242 .await341 .await
243 .unwrap();342 .unwrap();
244- let second = BankQuestionImage::new(&question, None, png(), 5)343+ assert_eq!(retired, None, "a first upload retires no blob");
344+ let (second, retired) = BankQuestionImage::new(&question, None, png(), 5)
245 .upsert(&db)345 .upsert(&db)
246 .await346 .await
247 .unwrap();347 .unwrap();
248- // Same slot, same row — the replace swapped the blob pointer.348+ // Same slot, same row — the replace swapped the blob pointer, and the
349+ // write itself names the blob the caller must unlink.
249 assert_ne!(first.get_file(), second.get_file());350 assert_ne!(first.get_file(), second.get_file());
351+ assert_eq!(retired.as_deref(), Some(first.get_file()));
250 let rows = BankQuestionImage::list_for_question(&question, &db)352 let rows = BankQuestionImage::list_for_question(&question, &db)
251 .await353 .await
252 .unwrap();354 .unwrap();
@@ -259,7 +361,7 @@ mod tests {
259 #[tokio::test]361 #[tokio::test]
260 async fn only_the_dropped_options_lose_their_pictures() {362 async fn only_the_dropped_options_lose_their_pictures() {
261 let db = crate::database::init_mem().await.unwrap();363 let db = crate::database::init_mem().await.unwrap();
262- let question = BankQuestionId::generate();364+ let question = a_template(&db).await;
263 let ids = choice_ids();365 let ids = choice_ids();
264 BankQuestionImage::new(&question, None, png(), 1)366 BankQuestionImage::new(&question, None, png(), 1)
265 .upsert(&db)367 .upsert(&db)
@@ -288,7 +390,7 @@ mod tests {
288 #[tokio::test]390 #[tokio::test]
289 async fn an_empty_keep_set_clears_every_option_picture() {391 async fn an_empty_keep_set_clears_every_option_picture() {
290 let db = crate::database::init_mem().await.unwrap();392 let db = crate::database::init_mem().await.unwrap();
291- let question = BankQuestionId::generate();393+ let question = a_template(&db).await;
292 let ids = choice_ids();394 let ids = choice_ids();
293 BankQuestionImage::new(&question, None, png(), 1)395 BankQuestionImage::new(&question, None, png(), 1)
294 .upsert(&db)396 .upsert(&db)
@@ -313,4 +415,181 @@ mod tests {
313 assert_eq!(left.len(), 1);415 assert_eq!(left.len(), 1);
314 assert_eq!(left[0].get_slot(), None);416 assert_eq!(left[0].get_slot(), None);
315 }417 }
418+
419+ /// The [`crate::domain::pool_question::PoolQuestion`] defect, one domain
420+ /// over: an image written inside its template's delete window must not
421+ /// outlive it. Guarding the write by *reading* the template does not do it
422+ /// — the read sees a row [`BankQuestion::delete`] has removed but not
423+ /// committed, while its `DELETE bank_question_image WHERE bank_question =
424+ /// $b` ran on a snapshot predating this row, so both commit and the image
425+ /// is left pointing at a template that is gone. Nothing can reach it after
426+ /// that: every image route resolves the template first, no boot sweep
427+ /// visits this table, and its blob stays on disk for good. [`Self::upsert`]
428+ /// moves the template's own `points` instead, so the two transactions touch
429+ /// one key and the store refuses a side.
430+ ///
431+ /// The blob half is asserted through the list the delete hands back: that
432+ /// list — never a snapshot read before it — is what the web layer unlinks
433+ /// from, so an image that committed inside the window and is *not* in it is
434+ /// a blob stranded on disk.
435+ ///
436+ /// The window is opened by the schema, not by a lucky interleaving: a
437+ /// `DEFINE EVENT` on `bank_question` fires inside the delete's own
438+ /// transaction the instant the row goes.
439+ ///
440+ /// Real server, and `#[ignore]`d for it: the subject *is* the store's
441+ /// conflict detection, which `init_mem`'s embedded engine does not have —
442+ /// it commits both and answers `Ok` to each, so this passes there on broken
443+ /// code.
444+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
445+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
446+ async fn an_image_written_inside_a_delete_window_never_outlives_its_template() {
447+ let (db, _serialized) = crate::database::init_test_server("bank_image_race").await;
448+ db.query(
449+ "DEFINE EVENT hold_the_window ON TABLE bank_question WHEN $event = 'DELETE' \
450+ THEN { SLEEP 1s; };",
451+ )
452+ .await
453+ .unwrap()
454+ .check()
455+ .unwrap();
456+
457+ let (mut swept, mut orphans, mut stranded) = (0, 0, 0);
458+ for round in 0..4 {
459+ let question = a_template(&db).await;
460+ let template = BankQuestion::read(&question, &db).await.unwrap().unwrap();
461+
462+ let drop_it = {
463+ let db = db.clone();
464+ tokio::spawn(async move { template.delete(&db).await })
465+ };
466+ // The upload starts inside the held window — the template row is
467+ // gone but uncommitted, which is exactly what the handler's
468+ // ownership read believes.
469+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
470+ let child = {
471+ let (db, question) = (db.clone(), question.clone());
472+ tokio::spawn(async move {
473+ BankQuestionImage::new(&question, None, png(), 3)
474+ .upsert(&db)
475+ .await
476+ })
477+ };
478+ let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
479+ // A 404 for the upload is a correct answer; the only defect is
480+ // stored state. Neither side may 500 — they contend by design and a
481+ // lost round is re-sent, not reported.
482+ assert!(
483+ !matches!(child, Err(AppError::Db(_))),
484+ "round {round}: a raced upload must be answered, not 500: {child:?}"
485+ );
486+ assert!(
487+ !matches!(drop_it, Err(AppError::Db(_))),
488+ "round {round}: a raced delete must retry, not 500: {drop_it:?}"
489+ );
490+
491+ // Stored state is the whole verdict; a return value is not evidence.
492+ if BankQuestion::read(&question, &db).await.unwrap().is_none() {
493+ swept += 1;
494+ orphans += BankQuestionImage::list_for_question(&question, &db)
495+ .await
496+ .unwrap()
497+ .len();
498+ if let (Ok((stored, _)), Ok((_, images))) = (&child, &drop_it)
499+ && !images
500+ .iter()
501+ .any(|image| image.get_file() == stored.get_file())
502+ {
503+ stranded += 1;
504+ }
505+ }
506+ }
507+ eprintln!("BankQuestion::delete raced by an upload: {swept}/4 rounds deleted the template");
508+ assert!(
509+ swept > 0,
510+ "no round ever deleted the template, so the window was never reached"
511+ );
512+ assert_eq!(orphans, 0, "an image row outlived its template");
513+ assert_eq!(
514+ stranded, 0,
515+ "an image committed inside the window was swept without being handed back, so its blob stays on disk"
516+ );
517+ }
518+
519+ /// Two uploads to one slot must leave exactly one live blob and hand every
520+ /// other one back to be unlinked. Reading the slot's old blob name *before*
521+ /// the write gave both racers the same answer: both retired the same old
522+ /// blob, and the loser's fresh one stayed on disk with nothing naming it.
523+ /// [`Self::upsert`] reads it inside its own transaction instead, so the
524+ /// loser contends on the row it writes and re-reads the winner's name.
525+ ///
526+ /// The overlap is forced rather than hoped for: a `DEFINE EVENT` on this
527+ /// table holds the first write open inside its own transaction, so the
528+ /// second reads the slot before the first commits.
529+ ///
530+ /// Real server, and `#[ignore]`d for it, for the reason above: the embedded
531+ /// engine has no write-write conflict detection to make a loser re-read.
532+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
533+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
534+ async fn two_uploads_to_one_slot_leave_no_blob_unretired() {
535+ let (db, _serialized) = crate::database::init_test_server("bank_image_replace").await;
536+ db.query(
537+ "DEFINE EVENT hold_the_write ON TABLE bank_question_image WHEN true \
538+ THEN { SLEEP 300ms; };",
539+ )
540+ .await
541+ .unwrap()
542+ .check()
543+ .unwrap();
544+
545+ let mut unretired = 0;
546+ for round in 0..3 {
547+ let question = a_template(&db).await;
548+ // A first picture, so both racers have an old blob to retire.
549+ let (original, _) = BankQuestionImage::new(&question, None, png(), 1)
550+ .upsert(&db)
551+ .await
552+ .unwrap();
553+
554+ let mut writes = Vec::new();
555+ for size in [2, 3] {
556+ let (db, question) = (db.clone(), question.clone());
557+ writes.push(tokio::spawn(async move {
558+ BankQuestionImage::new(&question, None, png(), size)
559+ .upsert(&db)
560+ .await
561+ }));
562+ }
563+ let mut written = vec![original.get_file().to_string()];
564+ let mut retired = Vec::new();
565+ for write in writes {
566+ let (stored, replaced) = write.await.unwrap().unwrap_or_else(|err| {
567+ panic!("round {round}: a raced upload must not 500: {err:?}")
568+ });
569+ written.push(stored.get_file().to_string());
570+ retired.extend(replaced);
571+ }
572+
573+ // Stored state is the whole verdict: exactly one blob is live, and
574+ // every other one this round wrote must have been handed back —
575+ // once. A name written and never returned is a file on disk with
576+ // nothing pointing at it.
577+ let live = BankQuestionImage::read_slot(&question, None, &db)
578+ .await
579+ .unwrap()
580+ .unwrap();
581+ assert!(
582+ !retired.iter().any(|name| name == live.get_file()),
583+ "round {round}: the live row's own blob was retired"
584+ );
585+ unretired += written
586+ .iter()
587+ .filter(|name| *name != live.get_file() && !retired.contains(name))
588+ .count();
589+ }
590+ assert_eq!(
591+ unretired, 0,
592+ "a blob was written and never handed back to be unlinked — it stays on disk forever"
593+ );
594+ }
316 }595 }
src/domain/question_image.rsmodified+40 -11
@@ -61,6 +61,16 @@ pub struct QuestionImage {
61 size: i64,61 size: i64,
62 }62 }
63 63
64+/// What one [`QuestionImage::upsert`] transaction returns: the row it stored
65+/// and the blob name it replaced. Both are arrays because SurrealDB drops an
66+/// object key valued `NONE` on the way out, while an empty array survives —
67+/// "nothing was replaced" has to be readable, not missing.
68+#[derive(SurrealValue)]
69+struct UpsertOutcome {
70+ stored: Vec<QuestionImage>,
71+ replaced: Vec<String>,
72+}
73+
64 impl QuestionImage {74 impl QuestionImage {
65 /// Assemble a row (fresh blob name generated here) without persisting it.75 /// Assemble a row (fresh blob name generated here) without persisting it.
66 /// The caller writes the blob under [`Self::get_file`] first, then calls76 /// The caller writes the blob under [`Self::get_file`] first, then calls
@@ -104,15 +114,24 @@ impl QuestionImage {
104 }114 }
105 115
106 /// Create or replace the slot's image row — the deterministic id makes116 /// Create or replace the slot's image row — the deterministic id makes
107- /// this the whole "one image per slot" story. Refused once the exam has an117+ /// this the whole "one image per slot" story — handing back what it stored
108- /// attempt: pictures are part of the question, so they freeze with it, and118+ /// plus the blob name it replaced, for the caller to take off disk. Refused
109- /// the gate is in this transaction rather than in a lock the caller held.119+ /// once the exam has an attempt: pictures are part of the question, so they
110- pub async fn upsert(self, db: &Database) -> Result<QuestionImage, AppError> {120+ /// freeze with it, and the gate is in this transaction rather than in a lock
121+ /// the caller held.
122+ ///
123+ /// The replaced name is read *here*, not by the caller before it: two
124+ /// uploads to one slot both write this row, so they contend and the loser
125+ /// re-reads the winner's blob name, where two pre-reads both saw the *old*
126+ /// blob and left the loser's fresh one orphaned on disk.
127+ pub async fn upsert(self, db: &Database) -> Result<(QuestionImage, Option<String>), AppError> {
111 // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic128 // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic
112 let (exam, id) = (self.exam.clone(), self.id.record());129 let (exam, id) = (self.exam.clone(), self.id.record());
113 let mut result = ExamAttempt::write_unfrozen(130 let mut result = ExamAttempt::write_unfrozen(
114 &exam,131 &exam,
115- "UPSERT $id CONTENT $image;",132+ "LET $replaced = (SELECT VALUE file FROM $id);
133+ LET $stored = (UPSERT $id CONTENT $image);
134+ RETURN { stored: $stored, replaced: $replaced };",
116 vec![135 vec![
117 ("id".into(), id.into_value()),136 ("id".into(), id.into_value()),
118 ("image".into(), self.into_value()),137 ("image".into(), self.into_value()),
@@ -120,11 +139,18 @@ impl QuestionImage {
120 db,139 db,
121 )140 )
122 .await?;141 .await?;
123- result142+ // The trailing `RETURN` is the last statement before `COMMIT`, so its
124- .take::<Vec<QuestionImage>>(ExamAttempt::FROZEN_SLOT)?143+ // slot follows the statement count rather than a hand-kept number;
144+ // `num_statements` counts BEGIN and COMMIT.
145+ let slot = result.num_statements().saturating_sub(2);
146+ let failed = || AppError::Internal("failed to store question image".into());
147+ let outcome = result
148+ .take::<Vec<UpsertOutcome>>(slot)?
125 .into_iter()149 .into_iter()
126 .next()150 .next()
127- .ok_or_else(|| AppError::Internal("failed to store question image".into()))151+ .ok_or_else(failed)?;
152+ let stored = outcome.stored.into_iter().next().ok_or_else(failed)?;
153+ Ok((stored, outcome.replaced.into_iter().next()))
128 }154 }
129 155
130 pub async fn read_slot(156 pub async fn read_slot(
@@ -275,16 +301,19 @@ mod tests {
275 let question = ExamQuestionId::generate();301 let question = ExamQuestionId::generate();
276 let ids = choice_ids();302 let ids = choice_ids();
277 303
278- let first = QuestionImage::new(&exam, &question, None, png(), 3)304+ let (first, retired) = QuestionImage::new(&exam, &question, None, png(), 3)
279 .upsert(&db)305 .upsert(&db)
280 .await306 .await
281 .unwrap();307 .unwrap();
282- let second = QuestionImage::new(&exam, &question, None, png(), 5)308+ assert_eq!(retired, None, "a first upload retires no blob");
309+ let (second, retired) = QuestionImage::new(&exam, &question, None, png(), 5)
283 .upsert(&db)310 .upsert(&db)
284 .await311 .await
285 .unwrap();312 .unwrap();
286- // Same slot, same row — the replace swapped the blob pointer.313+ // Same slot, same row — the replace swapped the blob pointer, and the
314+ // write itself names the blob the caller must unlink.
287 assert_ne!(first.get_file(), second.get_file());315 assert_ne!(first.get_file(), second.get_file());
316+ assert_eq!(retired.as_deref(), Some(first.get_file()));
288 let rows = QuestionImage::list_for_question(&question, &db)317 let rows = QuestionImage::list_for_question(&question, &db)
289 .await318 .await
290 .unwrap();319 .unwrap();
src/web/bank_questions.rsmodified+11 -12
@@ -401,9 +401,12 @@ async fn owned_question(st: &AppState, user: &User, bid: &str) -> Result<BankQue
401 Ok(question)401 Ok(question)
402 }402 }
403 403
404-/// The bank-image write tail: the slot's current row names the blob to retire,404+/// The bank-image write tail: the UPSERT replaces the slot's row (the
405-/// the UPSERT replaces it (the deterministic per-slot id makes it a replace),405+/// deterministic per-slot id makes it a replace) and names the blob it retired
406-/// and [`store_blob`] owns the disk ordering.406+/// *from inside its own transaction*, and [`store_blob`] owns the disk
407+/// ordering. Reading the slot out here first instead would hand two uploads
408+/// racing on one slot the same old blob name, leaving the loser's fresh one on
409+/// disk with no row pointing at it.
407 pub(crate) async fn store_image(410 pub(crate) async fn store_image(
408 st: &AppState,411 st: &AppState,
409 question: &BankQuestionId,412 question: &BankQuestionId,
@@ -411,14 +414,9 @@ pub(crate) async fn store_image(
411 content_type: FileContentType,414 content_type: FileContentType,
412 data: &[u8],415 data: &[u8],
413 ) -> Result<BankQuestionImage, AppError> {416 ) -> Result<BankQuestionImage, AppError> {
414- let replaced = BankQuestionImage::read_slot(question, slot, &st.db).await?;
415 let image = BankQuestionImage::new(question, slot, content_type, data.len() as i64);417 let image = BankQuestionImage::new(question, slot, content_type, data.len() as i64);
416 let file = image.get_file().to_string();418 let file = image.get_file().to_string();
417- store_blob(st, &file, data, || async {419+ store_blob(st, &file, data, || async { image.upsert(&st.db).await }).await
418- let stored = image.upsert(&st.db).await?;
419- Ok((stored, replaced.map(|old| old.get_file().to_string())))
420- })
421- .await
422 }420 }
423 421
424 /// Add a template to the bank. Requires teacher+. `subject_id` is origin422 /// Add a template to the bank. Requires teacher+. `subject_id` is origin
@@ -729,9 +727,10 @@ async fn delete_question(
729 ) -> Result<StatusCode, AppError> {727 ) -> Result<StatusCode, AppError> {
730 let question = owned_question(&st, &user, &bid).await?;728 let question = owned_question(&st, &user, &bid).await?;
731 // Rows go first (the delete cascades the image rows), blobs after — a crash729 // Rows go first (the delete cascades the image rows), blobs after — a crash
732- // in between strands at worst an unreachable blob.730+ // in between strands at worst an unreachable blob. The blobs come from what
733- let images = BankQuestionImage::list_for_question(question.get_id(), &st.db).await?;731+ // the delete *swept*, never a list read before it: an upload that landed in
734- question.delete(&st.db).await?;732+ // between is swept too, and its blob would be stranded for good.
733+ let (_, images) = question.delete(&st.db).await?;
735 for image in &images {734 for image in &images {
736 remove_blob(&st.files_path, image.get_file()).await;735 remove_blob(&st.files_path, image.get_file()).await;
737 }736 }
src/web/exams/images.rsmodified+11 -17
@@ -119,9 +119,12 @@ pub(crate) async fn ensure_question_content_visible(
119 Ok(())119 Ok(())
120 }120 }
121 121
122-/// The image write tail, shared by both upload endpoints: the slot's current122+/// The image write tail, shared by both upload endpoints: the UPSERT replaces
123-/// row names the blob to retire, the UPSERT replaces it (the deterministic123+/// the slot's row (the deterministic per-slot id makes it a replace) and names
124-/// per-slot id makes it a replace), and [`store_blob`] owns the disk ordering.124+/// the blob it retired *from inside its own transaction*, and [`store_blob`]
125+/// owns the disk ordering. Reading the slot out here first instead would hand
126+/// two uploads racing on one slot the same old blob name, leaving the loser's
127+/// fresh one on disk with no row pointing at it.
125 pub(crate) async fn store_image(128 pub(crate) async fn store_image(
126 st: &AppState,129 st: &AppState,
127 exam: &Exam,130 exam: &Exam,
@@ -130,7 +133,6 @@ pub(crate) async fn store_image(
130 content_type: FileContentType,133 content_type: FileContentType,
131 data: &[u8],134 data: &[u8],
132 ) -> Result<QuestionImage, AppError> {135 ) -> Result<QuestionImage, AppError> {
133- let replaced = QuestionImage::read_slot(question.get_id(), slot, &st.db).await?;
134 let image = QuestionImage::new(136 let image = QuestionImage::new(
135 exam.get_id(),137 exam.get_id(),
136 question.get_id(),138 question.get_id(),
@@ -139,11 +141,7 @@ pub(crate) async fn store_image(
139 data.len() as i64,141 data.len() as i64,
140 );142 );
141 let file = image.get_file().to_string();143 let file = image.get_file().to_string();
142- store_blob(st, &file, data, || async {144+ store_blob(st, &file, data, || async { image.upsert(&st.db).await }).await
143- let stored = image.upsert(&st.db).await?;
144- Ok((stored, replaced.map(|old| old.get_file().to_string())))
145- })
146- .await
147 }145 }
148 146
149 /// The stored bytes, served inline via [`crate::web::serve_inline_blob`].147 /// The stored bytes, served inline via [`crate::web::serve_inline_blob`].
@@ -395,8 +393,9 @@ pub(crate) async fn delete_choice_image(
395 // content's own visibility (own sitting view / teacher grading view).393 // content's own visibility (own sitting view / teacher grading view).
396 394
397 /// The answer-image write tail, mirroring [`store_image`]: the deterministic395 /// The answer-image write tail, mirroring [`store_image`]: the deterministic
398-/// per-(question, user, seq) id makes the UPSERT a replace, and [`store_blob`]396+/// per-(question, user, seq) id makes the UPSERT a replace, the write names the
399-/// owns the disk ordering.397+/// blob it retired from inside its own transaction, and [`store_blob`] owns the
398+/// disk ordering.
400 pub(crate) async fn store_answer_image(399 pub(crate) async fn store_answer_image(
401 st: &AppState,400 st: &AppState,
402 exam: &Exam,401 exam: &Exam,
@@ -406,7 +405,6 @@ pub(crate) async fn store_answer_image(
406 content_type: FileContentType,405 content_type: FileContentType,
407 data: &[u8],406 data: &[u8],
408 ) -> Result<AnswerImage, AppError> {407 ) -> Result<AnswerImage, AppError> {
409- let replaced = AnswerImage::read(question.get_id(), user, seq, &st.db).await?;
410 let image = AnswerImage::new(408 let image = AnswerImage::new(
411 exam.get_id(),409 exam.get_id(),
412 question.get_id(),410 question.get_id(),
@@ -416,11 +414,7 @@ pub(crate) async fn store_answer_image(
416 data.len() as i64,414 data.len() as i64,
417 );415 );
418 let file = image.get_file().to_string();416 let file = image.get_file().to_string();
419- store_blob(st, &file, data, || async {417+ store_blob(st, &file, data, || async { image.upsert(&st.db).await }).await
420- let stored = image.upsert(&st.db).await?;
421- Ok((stored, replaced.map(|old| old.get_file().to_string())))
422- })
423- .await
424 }418 }
425 419
426 /// Attach (or replace) the caller's drawn answer to a question inside their420 /// Attach (or replace) the caller's drawn answer to a question inside their
tests/regress_bank_images.rsadded+206 -0
@@ -0,0 +1,206 @@
1+//! A bank template's images must never outlive the template, and every blob
2+//! must have a row pointing at it.
3+//!
4+//! `bank_question_image` was the one child in this domain whose write did not
5+//! touch its parent, and `BankQuestion::delete` the one cascade here that was
6+//! not a single transaction. Between them an upload that started before a
7+//! delete and landed after it left a row *and* a blob nothing could ever read,
8+//! delete, or sweep: every image route goes through the template, and no boot
9+//! sweep visits this table. The third hole was one round trip wide — the slot's
10+//! old blob name was read *before* the write, so two uploads to one slot both
11+//! retired the same old blob and one of the two fresh ones was left on disk
12+//! with nothing pointing at it.
13+//!
14+//! Stored state is the whole verdict here, on both sides: the row (is the
15+//! orphan there?) and the disk (is the blob still in `files_path`?). Each test
16+//! gets a blob directory of its own so a file count means something.
17+//!
18+//! These two need no server, so they run in CI by default. The *raced* halves
19+//! of the same three holes live beside the code they test, in
20+//! `bank_question_image`'s own test module, where `init_test_server` and
21+//! `RACE_LOCK` are in reach: the store's conflict detection is their subject,
22+//! and re-spelling the real bootstrap out here would be a hand-kept copy that
23+//! drifts silently the first time migration or router construction changes.
24+
25+mod common;
26+
27+use axum::Router;
28+use axum::http::StatusCode;
29+use common::{create_course, create_subject, id_of, login_as, send};
30+use hezarfen_backend::database::Database;
31+use hezarfen_backend::domain::bank_question::BankQuestionId;
32+use hezarfen_backend::domain::bank_question_image::BankQuestionImage;
33+use hezarfen_backend::domain::note_file::FileContentType;
34+use hezarfen_backend::error::AppError;
35+use hezarfen_backend::rate_limit::RateLimitConfig;
36+use hezarfen_backend::state::AppState;
37+use hezarfen_backend::{build_router, database};
38+use serde_json::json;
39+use tempfile::TempDir;
40+
41+const BOUNDARY: &str = "multipart/form-data; boundary=hezarfen-test-boundary";
42+
43+/// A router over a fresh in-memory database, with a blob directory nothing else
44+/// writes to — so `blobs()` counts this test's files and no one else's.
45+async fn mem_app() -> (Router, Database, TempDir) {
46+ let db = database::init_mem().await.expect("in-memory db");
47+ let files = tempfile::tempdir().expect("files tempdir");
48+ let app = build_router(AppState {
49+ db: db.clone(),
50+ files_path: files.path().to_path_buf(),
51+ cookie_secure: false,
52+ rate_limit: RateLimitConfig::unlimited(),
53+ chatbot_limit: Default::default(),
54+ exam_presence: Default::default(),
55+ board_hub: Default::default(),
56+ db_up: Default::default(),
57+ ai: None,
58+ });
59+ (app, db, files)
60+}
61+
62+/// Every blob file currently on disk, by name.
63+fn blobs(files: &TempDir) -> Vec<String> {
64+ let mut names: Vec<String> = std::fs::read_dir(files.path())
65+ .expect("read the blob dir")
66+ .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
67+ .collect();
68+ names.sort();
69+ names
70+}
71+
72+/// A template owned by `who`, under a fresh course + subject; returns its id.
73+async fn template(app: &Router, who: &str, name: &str) -> String {
74+ let course = create_course(app, who, &format!("Ders {name}")).await;
75+ let subject = create_subject(app, who, &course, name).await;
76+ let res = send(
77+ app,
78+ "POST",
79+ "/bank-questions",
80+ Some(who),
81+ Some(json!({ "subject_id": subject, "text": "soru", "kind": "text", "points": 3 })),
82+ )
83+ .await;
84+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
85+ id_of(&res.body)
86+}
87+
88+/// Upload an illustration onto the template; returns the status.
89+async fn upload(app: &Router, who: &str, bid: &str, bytes: &[u8]) -> StatusCode {
90+ let (status, _, _) = common::send_raw(
91+ app,
92+ "POST",
93+ &format!("/bank-questions/{bid}/image"),
94+ Some(who),
95+ Some(BOUNDARY),
96+ common::multipart_file("pic.png", "image/png", bytes),
97+ )
98+ .await;
99+ status
100+}
101+
102+fn png() -> FileContentType {
103+ FileContentType::try_new("image/png").unwrap()
104+}
105+
106+/// The template's existence is part of the image write itself, not a read in
107+/// front of it: writing a slot under a template that is gone is refused, and
108+/// stores nothing. Before the fix this was a bare `UPSERT` that cheerfully
109+/// created the row — a row no route could reach afterwards, since every image
110+/// endpoint resolves the template first, and no boot sweep touches this table.
111+///
112+/// Deterministic, no race needed: the parent is already gone. The *raced*
113+/// version of the same hole is
114+/// `an_upload_inside_a_delete_window_leaves_no_orphan_row_or_blob` below.
115+#[tokio::test]
116+async fn an_image_write_under_a_missing_template_is_refused() {
117+ let (app, db, _files) = mem_app().await;
118+ let teacher = login_as(&app, &db, "ogretmen_banka", "teacher").await;
119+ let bid = template(&app, &teacher, "optik").await;
120+
121+ let dropped = send(
122+ &app,
123+ "DELETE",
124+ &format!("/bank-questions/{bid}"),
125+ Some(&teacher),
126+ None,
127+ )
128+ .await;
129+ assert_eq!(dropped.status, StatusCode::NO_CONTENT);
130+
131+ let question = BankQuestionId::from_key(&bid);
132+ let refused = BankQuestionImage::new(&question, None, png(), 3)
133+ .upsert(&db)
134+ .await;
135+ assert!(
136+ matches!(refused, Err(AppError::NotFound)),
137+ "a slot write under a deleted template must be refused: {refused:?}"
138+ );
139+ // Stored state is the verdict — a refusal that still wrote the row would be
140+ // the very defect this pins.
141+ assert!(
142+ BankQuestionImage::list_for_question(&question, &db)
143+ .await
144+ .unwrap()
145+ .is_empty(),
146+ "the refused write left an orphan row"
147+ );
148+}
149+
150+/// The disk contract, end to end: a replace retires exactly the blob it
151+/// replaced (never the fresh one), and deleting the template takes the blobs of
152+/// the rows its cascade *swept* off disk with it.
153+#[tokio::test]
154+async fn a_replace_retires_one_blob_and_a_delete_takes_the_rest() {
155+ let (app, db, files) = mem_app().await;
156+ let teacher = login_as(&app, &db, "ogretmen_disk", "teacher").await;
157+ let bid = template(&app, &teacher, "akustik").await;
158+
159+ assert_eq!(
160+ upload(&app, &teacher, &bid, b"first").await,
161+ StatusCode::CREATED
162+ );
163+ assert_eq!(blobs(&files).len(), 1, "the first upload is on disk");
164+
165+ assert_eq!(
166+ upload(&app, &teacher, &bid, b"second").await,
167+ StatusCode::CREATED
168+ );
169+ let after = blobs(&files);
170+ assert_eq!(
171+ after.len(),
172+ 1,
173+ "a replace retires the blob it replaced: {after:?}"
174+ );
175+ let question = BankQuestionId::from_key(&bid);
176+ let rows = BankQuestionImage::list_for_question(&question, &db)
177+ .await
178+ .unwrap();
179+ assert_eq!(rows.len(), 1, "one row per slot");
180+ assert_eq!(
181+ after,
182+ vec![rows[0].get_file().to_string()],
183+ "the surviving blob is the one the row points at"
184+ );
185+
186+ let dropped = send(
187+ &app,
188+ "DELETE",
189+ &format!("/bank-questions/{bid}"),
190+ Some(&teacher),
191+ None,
192+ )
193+ .await;
194+ assert_eq!(dropped.status, StatusCode::NO_CONTENT);
195+ assert!(
196+ blobs(&files).is_empty(),
197+ "the delete left a blob behind: {:?}",
198+ blobs(&files)
199+ );
200+ assert!(
201+ BankQuestionImage::list_for_question(&question, &db)
202+ .await
203+ .unwrap()
204+ .is_empty()
205+ );
206+}