From 02b1ff8c850aec25a011e99802f1bb326b265dc8 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 01:25:10 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=93=9D=20stop=20an=20answer=20from?= =?UTF-8?q?=20outliving=20its=20exam?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Saving an answer only read the exam it belonged to, and a delete sweeps answers in its own transaction — so a save landing inside that window wrote a row the sweep had already passed, and both sides reported success. The same shape as the attendance mark, one domain over; measured 4 of 4 raced rounds against a real server. The save now writes the exam row itself, so the two collide and the store refuses one. It has to move a value to do that: SurrealDB drops an update that leaves the document unchanged, so setting the counter to itself never enters the write set and never conflicts — it is bumped and put back inside the one transaction instead. No new column, since a whole-row save would strip one at the next edit. Editing an exam now rides the retry too. The answer touch makes that row hot, and a lost round through the old bare query was a 500. --- src/domain/exam.rs | 203 +++++++++++++++++++++++++++++++++----- src/domain/exam_answer.rs | 159 ++++++++++++++++++++++++++++- 2 files changed, 332 insertions(+), 30 deletions(-) diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 3f7af04..b9e3c68 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -524,9 +524,21 @@ impl Exam { self.draft = draft; // whole-row-save-ok: the WHERE below pins every column this replaces to // the caller's snapshot, so no concurrent write can be reverted - let mut result = db - .query( - "BEGIN TRANSACTION; + // + // Sent through the retry loop, not a bare `query`: this row now has a + // hot writer. Every answer save touches it to tie itself to the exam + // ([`crate::domain::exam_answer::ExamAnswer::save`]), so a teacher + // flipping `allow_rejoin` mid-exam can lose a round to a student + // typing — and a lost round is a re-send, never the 500 a bare `?` on + // the conflict would have answered. Re-sending is sound because the + // statement is a compare-and-set: the second pass carries the same + // pinned snapshot, so it lands only if the row is still what the caller + // read, and a rival that really moved it is refused as it was before. + // Admissible for the loop — an `UPDATE`, an `IF`/`THROW` and a `SELECT` + // can never answer "already exists". + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; IF $redraft AND ( array::len((SELECT VALUE id FROM exam_attempt WHERE exam = $id LIMIT 1)) > 0 OR array::len((SELECT VALUE id FROM exam_result WHERE exam = $id LIMIT 1)) > 0 @@ -543,31 +555,37 @@ impl Exam { AND (result_count ?? 0) = $was_results RETURN AFTER; COMMIT TRANSACTION;", - ) - .bind(("redraft", redraft)) - .bind(("id", self.id.record())) - .bind(("was_title", was.0)) - .bind(("was_description", was.1)) - .bind(("was_kind", was.2)) - .bind(("was_mode", was.3)) - .bind(("was_starts", was.4)) - .bind(("was_ends", was.5)) - .bind(("was_duration", was.6)) - .bind(("was_max_attempts", was.7)) - .bind(("was_allow_rejoin", was.8)) - .bind(("was_allow_review", was.9)) - .bind(("was_draft", was.10)) - // The mark counter is pinned like every other column this write - // replaces, and for a sharper reason: a grade increments it, so - // pinning it is what makes "this exam had no marks" — the gate the - // handler refuses a kind change on — true at *write* time and not - // merely at read time. A mark landing in between refuses the save. - .bind(("was_results", self.result_count.unwrap_or(0))) - .bind(("new", self)) - .await?; + &[ + ("redraft".into(), redraft.into_value()), + ("id".into(), self.id.record().into_value()), + ("was_title".into(), was.0.into_value()), + ("was_description".into(), was.1.into_value()), + ("was_kind".into(), was.2.into_value()), + ("was_mode".into(), was.3.into_value()), + ("was_starts".into(), was.4.into_value()), + ("was_ends".into(), was.5.into_value()), + ("was_duration".into(), was.6.into_value()), + ("was_max_attempts".into(), was.7.into_value()), + ("was_allow_rejoin".into(), was.8.into_value()), + ("was_allow_review".into(), was.9.into_value()), + ("was_draft".into(), was.10.into_value()), + // The mark counter is pinned like every other column this write + // replaces, and for a sharper reason: a grade increments it, so + // pinning it is what makes "this exam had no marks" — the gate + // the handler refuses a kind change on — true at *write* time + // and not merely at read time. A mark landing in between + // refuses the save. + ( + "was_results".into(), + self.result_count.unwrap_or(0).into_value(), + ), + ("new".into(), self.into_value()), + ], + &["exam_redraft"], + ) + .await?; // An aborted transaction errors every slot; only the THROW's names the // marker (the [`ExamAttempt::write_unfrozen`] treatment). - let mut errors = result.take_errors(); if errors .values() .any(|error| error.to_string().contains("exam_redraft")) @@ -1015,4 +1033,137 @@ mod tests { "a raced grade must retry, not 500: {grade_500}/20 rounds, last {last_grade}" ); } + + /// One choice question on `exam`, with a real subject row behind it — a + /// question claims a reference on its subject and is refused without one. + async fn question_on(exam: &Exam, db: &Database) -> crate::domain::exam_question::ExamQuestion { + use crate::domain::exam_question::{ + ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, + }; + 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(); + let subject = crate::domain::subject::Subject::create( + &CourseId::generate(), + crate::domain::subject::SubjectName::try_new("topic").unwrap(), + crate::domain::subject::SubjectDescription::try_new("").unwrap(), + db, + ) + .await + .unwrap(); + ExamQuestion::create( + exam.get_id(), + subject.get_id().clone(), + QuestionText::try_new("3 + 3?").unwrap(), + QuestionPoints::try_new(5).unwrap(), + spec, + db, + ) + .await + .unwrap() + } + + /// The `Menu::delete` defect, one domain over: a student's answer must not + /// outlive the exam it belongs to. Guarding the save by *reading* the exam + /// would not do it — the read sees a row [`Exam::delete`] has removed but + /// not committed, while its `DELETE exam_answer WHERE exam = $ex` swept a + /// snapshot predating the save, so both commit and the answer is left + /// pointing at an exam that is gone. [`ExamAnswer::save`] writes the exam + /// row instead (its `result_count`, back unchanged), so the two transactions + /// touch one key and the store refuses one of them. + /// + /// The window is opened by the database, not by a lucky interleaving: a + /// `DEFINE EVENT` on `exam` fires *inside* the delete's own transaction the + /// instant the row goes, so the `SLEEP` lands exactly between the delete and + /// its cascade every time. Nothing in `src/` knows about it; the seam is the + /// schema. + /// + /// One child per round, deliberately — in the menu twin, two children in one + /// round hid the bug: the first writer made the delete lose and re-send, and + /// the re-sent sweep removed the other's row. + /// + /// 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 writes and answers `Ok` to each, so this passes there on + /// broken code. Mutation-tested: putting the bare + /// `db.upsert(id).content(answer)` back turns it red (the exact output is in + /// the commit that added it). + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn an_answer_written_inside_a_delete_never_outlives_the_exam() { + use crate::domain::exam_answer::ExamAnswer; + let (db, _serialized) = crate::database::init_test_server("exam_answer_race").await; + // Hold the delete open for a full second after the row is gone, while + // its cascade still has to run. + db.query( + "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let (mut answers, 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 student = UserId::from_key(&format!("stu{round}")); + // The stored choice ids are minted by the create, not the ones the + // spec asked for — an answer must name one of *those*. + let pick = question.get_choices().unwrap()[1] + .get_id() + .as_str() + .to_string(); + + let drop_it = { + let db = db.clone(); + tokio::spawn(async move { exam.delete(&db).await }) + }; + // The save starts inside the held window — the exam row is gone but + // uncommitted, which is exactly what an exam read believes. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let child = { + let (db, question, student) = (db.clone(), question.clone(), student.clone()); + tokio::spawn(async move { + ExamAnswer::save(&question, &student, 1, Some(pick), None, &db).await + }) + }; + let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); + // A 404 for the save, or a NotFound for the delete, is a correct + // answer — the only defect is stored state. + assert!( + !matches!(child, Err(AppError::Db(_))), + "round {round}: a raced save must be answered, not 500: {child:?}" + ); + + // Stored state is the whole verdict; a return value is not evidence. + if Exam::read(&id, &db).await.unwrap().is_none() { + swept += 1; + answers += ExamAnswer::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 an answer save: {swept}/4 rounds deleted the exam"); + assert!( + swept > 0, + "no round ever deleted the exam, so the window was never reached" + ); + assert_eq!(answers, 0, "an answer outlived its exam"); + } } diff --git a/src/domain/exam_answer.rs b/src/domain/exam_answer.rs index dcaa0bb..299c48c 100644 --- a/src/domain/exam_answer.rs +++ b/src/domain/exam_answer.rs @@ -1,7 +1,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{EXAM_ANSWER_TABLE, MAX_ANSWER_TEXT_LEN}; -use crate::database::Database; +use crate::constant::{EXAM_ANSWER_TABLE, EXAM_RESULT_COUNT_FIELD, MAX_ANSWER_TEXT_LEN}; +use crate::database::{Database, transaction_with_retry}; use crate::domain::exam::ExamId; use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId}; use crate::domain::key; @@ -171,8 +171,82 @@ impl ExamAnswer { text, updated_at: Timestamp::now(), }; - let saved: Option = db.upsert(answer.id.record()).content(answer).await?; - saved.ok_or_else(|| AppError::Internal("failed to save exam answer".into())) + // The save writes the *exam row* as well as the answer, in one + // transaction, and that is what ties the answer's fate to its exam: + // reading the exam does not survive [`crate::domain::exam::Exam::delete`]'s + // window — a save landing after its `DELETE exam_answer WHERE exam = $ex` + // but before the commit reads an exam that is still there (uncommitted) + // while the sweep ran on a snapshot predating this row, so both commit + // and the answer outlives the exam (measured 4 of 4 raced rounds). + // Writing the key the delete removes makes the two collide, and the + // store refuses one of them. It is the shape + // [`crate::domain::menu::bump_menu_and_write`] uses, and the one a mark + // already uses on this very row + // ([`crate::domain::exam_result::ExamResult::grade`]). + // + // The bump-and-restore is not a flourish, it is the whole instrument. + // The exam carries no revision to bump and must not grow one — its save + // is a whole-row `CONTENT` write, so a column this struct did not know + // about would be wiped by the next PATCH — so this touches the one + // counter it already has and puts it back. Writing the *same* value is + // not enough: an `UPDATE` that leaves the document unchanged is elided + // and never reaches the store's write set, which the race test proved + // (green on the raced delete, red the moment the value moves for real). + // The restore is 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`), the PATCH's + // `(result_count ?? 0) = $was_results` still passes, and no teacher's + // edit is refused because a student typed. Both statements are inside + // the transaction, so a crash between them cannot leave the counter up. + // No `cap::counter_lock` either: no counter moves here, and the hottest + // write path in the app should not queue behind one. + // + // Admissible for `transaction_with_retry`: the `UPDATE`s, `SELECT`, + // `IF`/`THROW` and `RETURN` can never answer "already exists", and the + // `UPSERT`'s id is bijective with the (question, user, seq) triple + // `exam_answer` keys — a lost round wrote nothing, and re-sending + // resolves onto the same row rather than colliding with it. + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $was = (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $ex); + LET $touched = (UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = \ + ({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 $row = (UPSERT $id CONTENT $answer RETURN AFTER); + RETURN $row[0]; + COMMIT TRANSACTION;" + ), + &[ + ("ex".into(), answer.exam.record().into_value()), + ("id".into(), answer.id.record().into_value()), + ("answer".into(), answer.into_value()), + ], + &["no_exam"], + ) + .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_exam")) + { + 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 (the + // `Exam::delete` treatment); `num_statements` counts BEGIN and COMMIT. + let slot = result.num_statements().saturating_sub(2); + result + .take::>(slot)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to save exam answer".into())) } /// One student's stored answer for a question in sitting `seq`, if any. @@ -415,4 +489,81 @@ mod tests { let text = text_question(&exam, 10); assert_eq!(answer(&text, &user, None).is_correct(&text), None); } + + /// The bite test for the exam-row touch in [`ExamAnswer::save`]: it exists + /// to collide with [`crate::domain::exam::Exam::delete`], so it must leave + /// the counter it borrows exactly where it found it — absent stays absent + /// (the boot backfill keys on `result_count = NONE`), and a real count is + /// not moved by a student typing. The race half is + /// `domain::exam::tests::an_answer_written_inside_a_delete_never_outlives_the_exam`, + /// which needs a real server; this half is the arithmetic and runs anywhere. + #[tokio::test] + async fn a_save_puts_the_exams_mark_counter_back_exactly() { + use crate::domain::exam::{ + Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, + }; + let db = crate::database::init_mem().await.unwrap(); + let kinds = crate::domain::settings::Settings::defaults() + .get_exam_kinds() + .to_vec(); + let exam = Exam::create( + &student(), + &crate::domain::course::CourseId::generate(), + ExamTitle::try_new("quiz").unwrap(), + ExamDescription::try_new("").unwrap(), + ExamKind::try_new("quiz", &kinds).unwrap(), + ExamSchedule::try_new(None, None, None, None).unwrap(), + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + false, + &db, + ) + .await + .unwrap(); + let stored = async |db: &Database| -> Option { + let mut result = db + .query("SELECT VALUE result_count FROM ONLY $ex") + .bind(("ex", exam.get_id().record())) + .await + .unwrap() + .check() + .unwrap(); + result.take::>(0).unwrap() + }; + let question = choice_question(exam.get_id(), 10, 1); + let pick = choice_id(&question, 1).as_str().to_string(); + + // A fresh exam carries no counter at all, and must still not after a save. + assert_eq!(stored(&db).await, None, "the fixture must start absent"); + ExamAnswer::save(&question, &student(), 1, Some(pick.clone()), None, &db) + .await + .unwrap(); + assert_eq!( + stored(&db).await, + None, + "the touch left the counter set — the backfill keys on NONE" + ); + + // …and a counter that marks have moved is put back at its own value. + db.query("UPDATE $ex SET result_count = 7") + .bind(("ex", exam.get_id().record())) + .await + .unwrap() + .check() + .unwrap(); + ExamAnswer::save(&question, &student(), 2, Some(pick), None, &db) + .await + .unwrap(); + assert_eq!(stored(&db).await, Some(7), "the touch moved a real count"); + + // The gate that makes the touch worth having: no exam, no answer. + let orphan = choice_question(&ExamId::from_key("01NOSUCHEXAMAAAAAAAAAAAAAA"), 10, 0); + let pick = choice_id(&orphan, 0).as_str().to_string(); + let refused = ExamAnswer::save(&orphan, &student(), 1, Some(pick), None, &db).await; + assert!( + matches!(refused, Err(AppError::NotFound)), + "a save into a missing exam must 404, got {refused:?}" + ); + } }