diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index a40e96f..897e629 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -770,8 +770,17 @@ mod tests { let used_once = template("once").await.unwrap(); let unused = template("never").await.unwrap(); - let exam = ExamId::generate(); - let other_exam = ExamId::generate(); + // Real exam rows: instantiating a template moves the exam's counter + // (what keeps a question from outliving its exam), so a minted id + // nothing wrote is a 404. + let exam = crate::domain::exam::published_exam(&db) + .await + .get_id() + .clone(); + let other_exam = crate::domain::exam::published_exam(&db) + .await + .get_id() + .clone(); // 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( diff --git a/src/domain/exam.rs b/src/domain/exam.rs index b9e3c68..cfc4dcc 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -666,31 +666,38 @@ impl Exam { } } +/// An unscheduled published exam — the minimum any test that writes a *child* +/// of an exam needs, in any module: every such write moves the exam row (see +/// [`ExamAttempt::write_unfrozen_with`](crate::domain::exam_attempt::ExamAttempt) +/// and [`crate::domain::exam_answer::ExamAnswer::save`]), so a minted id whose +/// row was never created is a 404 rather than a silent orphan. +#[cfg(test)] +pub(crate) async fn published_exam(db: &Database) -> Exam { + let allowed: Vec = crate::domain::settings::Settings::defaults() + .get_exam_kinds() + .to_vec(); + Exam::create( + &UserId::generate(), + &CourseId::generate(), + ExamTitle::try_new("midterm").unwrap(), + ExamDescription::try_new("").unwrap(), + ExamKind::try_new("midterm", &allowed).unwrap(), + ExamSchedule::try_new(None, None, None, None).unwrap(), + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + false, + db, + ) + .await + .unwrap() +} + #[cfg(test)] mod tests { use super::*; - /// An unscheduled published exam, the minimum this file's write tests need. - async fn published(db: &Database) -> Exam { - let allowed: Vec = crate::domain::settings::Settings::defaults() - .get_exam_kinds() - .to_vec(); - Exam::create( - &UserId::generate(), - &CourseId::generate(), - ExamTitle::try_new("midterm").unwrap(), - ExamDescription::try_new("").unwrap(), - ExamKind::try_new("midterm", &allowed).unwrap(), - ExamSchedule::try_new(None, None, None, None).unwrap(), - ExamAttemptLimit::try_new(1).unwrap(), - true, - false, - false, - db, - ) - .await - .unwrap() - } + use crate::domain::exam::published_exam as published; fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) { ( @@ -1166,4 +1173,185 @@ mod tests { ); assert_eq!(answers, 0, "an answer outlived its exam"); } + + /// The same defect on the teacher's side of the sheet, and a worse one: a + /// question written inside the delete window kept the reference it claimed + /// on its subject (the cascade's per-subject decrement counted only the + /// rows it could see), and [`crate::domain::subject::Subject::delete`] is + /// gated on that count reading zero — a subject nobody could ever delete + /// again, hanging off an exam nobody could ever see. The freeze gate is a + /// *read* of `exam_attempt` and never survived this window; + /// [`ExamAttempt::write_unfrozen_with`] now writes the exam row too. + /// + /// Same seam, same `#[ignore]`, same reason as the answer twin above: the + /// subject *is* the store's conflict detection, which the in-memory engine + /// does not have. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_question_written_inside_a_delete_never_outlives_the_exam() { + use crate::domain::exam_question::{ + ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, + }; + use crate::domain::subject::Subject; + let (db, _serialized) = crate::database::init_test_server("exam_question_race").await; + db.query( + "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let (mut questions, mut swept, mut stuck) = (0, 0, 0); + for round in 0..4 { + let exam = published(&db).await; + let id = exam.get_id().clone(); + let subject = Subject::create( + &CourseId::generate(), + crate::domain::subject::SubjectName::try_new("topic").unwrap(), + crate::domain::subject::SubjectDescription::try_new("").unwrap(), + &db, + ) + .await + .unwrap(); + + let drop_it = { + let db = db.clone(); + tokio::spawn(async move { exam.delete(&db).await }) + }; + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let child = { + let (db, exam_id, on) = (db.clone(), id.clone(), subject.get_id().clone()); + tokio::spawn(async move { + let spec = QuestionSpec::try_new( + QuestionKind::try_new("choice").unwrap(), + Some(vec![ + ChoiceInput { + id: Some("a".into()), + text: "5".into(), + }, + ChoiceInput { + id: Some("b".into()), + text: "6".into(), + }, + ]), + Some("b".into()), + &[], + ) + .unwrap(); + ExamQuestion::create( + &exam_id, + on, + QuestionText::try_new("3 + 3?").unwrap(), + QuestionPoints::try_new(5).unwrap(), + spec, + &db, + ) + .await + }) + }; + let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); + assert!( + !matches!(child, Err(AppError::Db(_))), + "round {round}: a raced question write must be answered, not 500: {child:?}" + ); + + if Exam::read(&id, &db).await.unwrap().is_none() { + swept += 1; + questions += ExamQuestion::list_for_exam(&id, None, 0, &db) + .await + .unwrap() + .0 + .len(); + // The subject has to be free again: a stranded reference is the + // half of this bug a row count alone would not catch. + if Subject::read(subject.get_id(), &db) + .await + .unwrap() + .unwrap() + .delete(&db) + .await + .is_err() + { + stuck += 1; + } + } else if drop_it.is_ok() { + panic!("round {round}: the delete reported success but the exam is still there"); + } + } + eprintln!("Exam::delete raced by a question write: {swept}/4 rounds deleted the exam"); + assert!( + swept > 0, + "no round ever deleted the exam, so the window was never reached" + ); + assert_eq!(questions, 0, "a question outlived its exam"); + assert_eq!(stuck, 0, "an orphan question left its subject undeletable"); + } + + /// A picture is written through the same freeze gate as the question it + /// hangs on, so it had the same hole — and one the row count does not even + /// show: `delete_exam` collects the blob names to unlink *before* it calls + /// [`Exam::delete`], so an image row landing after that snapshot strands + /// its bytes on disk forever as well. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_picture_written_inside_a_delete_never_outlives_the_exam() { + use crate::domain::note_file::FileContentType; + use crate::domain::question_image::QuestionImage; + let (db, _serialized) = crate::database::init_test_server("question_image_race").await; + db.query( + "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let (mut images, mut swept) = (0, 0); + for round in 0..4 { + let exam = published(&db).await; + let question = question_on(&exam, &db).await; + let id = exam.get_id().clone(); + + let drop_it = { + let db = db.clone(); + tokio::spawn(async move { exam.delete(&db).await }) + }; + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let child = { + let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone()); + tokio::spawn(async move { + QuestionImage::new( + &exam_id, + &on, + None, + FileContentType::try_new("image/png").unwrap(), + 3, + ) + .upsert(&db) + .await + }) + }; + let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); + assert!( + !matches!(child, Err(AppError::Db(_))), + "round {round}: a raced picture write must be answered, not 500: {child:?}" + ); + + if Exam::read(&id, &db).await.unwrap().is_none() { + swept += 1; + images += QuestionImage::list_for_exam(&id, &db).await.unwrap().len(); + } else if drop_it.is_ok() { + panic!("round {round}: the delete reported success but the exam is still there"); + } + } + eprintln!("Exam::delete raced by a picture write: {swept}/4 rounds deleted the exam"); + assert!( + swept > 0, + "no round ever deleted the exam, so the window was never reached" + ); + assert_eq!(images, 0, "a picture outlived its exam"); + } } diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs index 3e05ebd..61eb52a 100644 --- a/src/domain/exam_attempt.rs +++ b/src/domain/exam_attempt.rs @@ -1,6 +1,6 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{EXAM_ATTEMPT_TABLE, EXAM_SAT_TOTAL_FIELD}; +use crate::constant::{EXAM_ATTEMPT_TABLE, EXAM_RESULT_COUNT_FIELD, EXAM_SAT_TOTAL_FIELD}; use crate::database::{Database, transaction_with_retry}; use crate::domain::exam::Exam; use crate::domain::exam::ExamId; @@ -14,6 +14,10 @@ use crate::error::AppError; /// the two refused. const FROZEN_MARK: &str = "questions_frozen"; +/// The `THROW` marker the exam-existence touch aborts with — the exam row this +/// write hangs off is gone, so the write is a 404 and nothing lands. +const GONE_MARK: &str = "no_exam"; + pub(crate) fn frozen_error() -> AppError { AppError::Conflict("cannot change questions after attempts have started") } @@ -361,7 +365,34 @@ impl ExamAttempt { /// all once `exam` has an attempt — the freeze gate, made atomic with the /// write it guards instead of merely preceding it. `freeze_exam` is bound /// here; the caller binds the rest and reads its own results from - /// [`Self::FROZEN_SLOT`] onwards (`BEGIN` and the `IF` take a slot each). + /// [`Self::FROZEN_SLOT`] onwards. + /// + /// The same transaction *writes* the exam row — bumping its mark counter + /// and putting it straight back — which is what ties every child written + /// through here to its exam. The freeze gate only *reads* `exam_attempt`, + /// and a read does not survive [`Exam::delete`](crate::domain::exam::Exam::delete)'s + /// window: a question or picture landing after that delete removed the exam + /// but before it committed reads a row that is still there, while the + /// cascade's `DELETE exam_question WHERE exam = $ex` ran on a snapshot + /// predating this insert — so both commit and the child outlives the exam, + /// with neither caller told anything. Writing a key the delete also writes + /// makes the two collide and the store refuses one side. It is the shape + /// [`crate::domain::exam_answer::ExamAnswer::save`] and + /// [`crate::domain::menu::bump_menu_and_write`] already use. + /// + /// An orphan here is not merely untidy: an `exam_question` that outlives + /// its exam keeps the reference it claimed on its subject (the cascade's + /// per-subject decrement counted the rows it could see), and + /// [`crate::domain::subject::Subject::delete`] is gated on that count + /// reading zero — a subject nobody can ever delete again. + /// + /// The bump is restored *by captured value*, `NONE` included, so the row is + /// byte-identical afterwards: the boot backfill still finds the rows it + /// keys on (`WHERE result_count = NONE`) and a teacher's PATCH, which pins + /// that counter, is not refused because somebody added a question. Writing + /// the same value back would not do — an `UPDATE` that leaves the document + /// unchanged is elided and never reaches the store's write set, so it + /// collides with nothing. /// /// This replaces a process-wide `EXAM_LOCK.write()` held across the check /// and the write. That lock ordered the two requests but still read the @@ -420,12 +451,18 @@ impl ExamAttempt { "BEGIN TRANSACTION; IF array::len((SELECT VALUE id FROM exam_attempt \ WHERE exam = $freeze_exam LIMIT 1)) > 0 {{ THROW '{FROZEN_MARK}' }}; + LET $was_results = \ + (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $freeze_exam); + LET $touched = (UPDATE $freeze_exam SET {EXAM_RESULT_COUNT_FIELD} = \ + ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); + IF array::len($touched) = 0 {{ THROW '{GONE_MARK}' }}; + UPDATE $freeze_exam SET {EXAM_RESULT_COUNT_FIELD} = $was_results; {statements} COMMIT TRANSACTION;" ); let mut bound = vec![("freeze_exam".into(), exam.record().into_value())]; bound.extend(bindings); - let mut marks = vec![FROZEN_MARK]; + let mut marks = vec![FROZEN_MARK, GONE_MARK]; marks.extend(refusals.iter().map(|(marker, _)| *marker)); let (result, mut errors) = transaction_with_retry(db, &sql, &bound, &marks).await?; let thrown = |marker: &str| { @@ -436,6 +473,12 @@ impl ExamAttempt { if thrown(FROZEN_MARK) { return Err(frozen_error()); } + // The exam is gone: the same 404 every one of these writes' handlers + // answers a missing exam with, and it outranks the callers' own gates + // for the freeze's reason — there is nothing left to refuse *about*. + if thrown(GONE_MARK) { + return Err(AppError::NotFound); + } for (marker, refusal) in refusals { if thrown(marker) { return Err(refusal); @@ -447,8 +490,10 @@ impl ExamAttempt { } } - /// The first slot a [`Self::write_unfrozen`] caller's own statements land in. - pub(crate) const FROZEN_SLOT: usize = 2; + /// The first slot a [`Self::write_unfrozen`] caller's own statements land + /// in: `BEGIN`, the freeze `IF`, and the exam touch's two `LET`s, `IF` and + /// restoring `UPDATE` take one each. + pub(crate) const FROZEN_SLOT: usize = 6; /// Whether anyone has started this exam — the gate that freezes `mode` /// edits once an attempt exists. diff --git a/src/domain/question_image.rs b/src/domain/question_image.rs index 68c20e7..e0c78eb 100644 --- a/src/domain/question_image.rs +++ b/src/domain/question_image.rs @@ -229,6 +229,16 @@ mod tests { use super::*; use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec}; + /// A real exam row: an image write moves its exam's counter (that is what + /// keeps a picture from outliving its exam), so a minted id nothing wrote + /// is a 404. + async fn exam_row(db: &Database) -> ExamId { + crate::domain::exam::published_exam(db) + .await + .get_id() + .clone() + } + fn png() -> FileContentType { FileContentType::try_new("image/png").unwrap() } @@ -261,7 +271,7 @@ mod tests { #[tokio::test] async fn upsert_replaces_per_slot() { let db = crate::database::init_mem().await.unwrap(); - let exam = ExamId::generate(); + let exam = exam_row(&db).await; let question = ExamQuestionId::generate(); let ids = choice_ids(); @@ -311,7 +321,7 @@ mod tests { #[tokio::test] async fn only_the_dropped_options_lose_their_pictures() { let db = crate::database::init_mem().await.unwrap(); - let exam = ExamId::generate(); + let exam = exam_row(&db).await; let question = ExamQuestionId::generate(); let ids = choice_ids(); QuestionImage::new(&exam, &question, None, png(), 1) @@ -361,7 +371,7 @@ mod tests { #[tokio::test] async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() { let db = crate::database::init_mem().await.unwrap(); - let exam = ExamId::generate(); + let exam = exam_row(&db).await; let question = ExamQuestionId::generate(); let ids = choice_ids(); QuestionImage::new(&exam, &question, None, png(), 1) @@ -391,8 +401,8 @@ mod tests { #[tokio::test] async fn exam_listing_scopes_by_exam() { let db = crate::database::init_mem().await.unwrap(); - let exam_a = ExamId::generate(); - let exam_b = ExamId::generate(); + let exam_a = exam_row(&db).await; + let exam_b = exam_row(&db).await; QuestionImage::new(&exam_a, &ExamQuestionId::generate(), None, png(), 1) .upsert(&db) .await diff --git a/src/domain/subject.rs b/src/domain/subject.rs index fb35d5b..51d8886 100644 --- a/src/domain/subject.rs +++ b/src/domain/subject.rs @@ -297,7 +297,6 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_delete_racing_a_question_never_answers_500() { - use crate::domain::exam::ExamId; use crate::domain::exam_question::{ ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, }; @@ -307,7 +306,13 @@ mod tests { let (mut last_delete, mut last_question) = (String::new(), String::new()); for round in 0..20 { let course = CourseId::generate(); - let exam = ExamId::generate(); + // A real exam row per round: a question write moves its exam's + // counter, so a minted id nothing wrote is a 404 and no round would + // reach the subject race this test is about. + let exam = crate::domain::exam::published_exam(&db) + .await + .get_id() + .clone(); let subject = Subject::create( &course, SubjectName::try_new("Limits").unwrap(),