forge
Explore
Log in

Don't you dare go Hollow

πŸ“ stop an answer from outliving its exam

Browse files at this commit

02b1ff8c850aec25a011e99802f1bb326b265dc8Ahmet Kaan GümüşParent: 84c873c
  • fix
    • πŸ“ stop an answer from outliving its exam
Show full message
fix: πŸ“ stop an answer from outliving its exam

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.rsmodified+177 -26
@@ -524,9 +524,21 @@ impl Exam {
524 self.draft = draft;524 self.draft = draft;
525 // whole-row-save-ok: the WHERE below pins every column this replaces to525 // whole-row-save-ok: the WHERE below pins every column this replaces to
526 // the caller's snapshot, so no concurrent write can be reverted526 // the caller's snapshot, so no concurrent write can be reverted
527- let mut result = db527+ //
528- .query(528+ // Sent through the retry loop, not a bare `query`: this row now has a
529- "BEGIN TRANSACTION;529+ // hot writer. Every answer save touches it to tie itself to the exam
530+ // ([`crate::domain::exam_answer::ExamAnswer::save`]), so a teacher
531+ // flipping `allow_rejoin` mid-exam can lose a round to a student
532+ // typing β€” and a lost round is a re-send, never the 500 a bare `?` on
533+ // the conflict would have answered. Re-sending is sound because the
534+ // statement is a compare-and-set: the second pass carries the same
535+ // pinned snapshot, so it lands only if the row is still what the caller
536+ // read, and a rival that really moved it is refused as it was before.
537+ // Admissible for the loop β€” an `UPDATE`, an `IF`/`THROW` and a `SELECT`
538+ // can never answer "already exists".
539+ let (mut result, mut errors) = transaction_with_retry(
540+ db,
541+ "BEGIN TRANSACTION;
530 IF $redraft AND (542 IF $redraft AND (
531 array::len((SELECT VALUE id FROM exam_attempt WHERE exam = $id LIMIT 1)) > 0543 array::len((SELECT VALUE id FROM exam_attempt WHERE exam = $id LIMIT 1)) > 0
532 OR array::len((SELECT VALUE id FROM exam_result WHERE exam = $id LIMIT 1)) > 0544 OR array::len((SELECT VALUE id FROM exam_result WHERE exam = $id LIMIT 1)) > 0
@@ -543,31 +555,37 @@ impl Exam {
543 AND (result_count ?? 0) = $was_results555 AND (result_count ?? 0) = $was_results
544 RETURN AFTER;556 RETURN AFTER;
545 COMMIT TRANSACTION;",557 COMMIT TRANSACTION;",
546- )558+ &[
547- .bind(("redraft", redraft))559+ ("redraft".into(), redraft.into_value()),
548- .bind(("id", self.id.record()))560+ ("id".into(), self.id.record().into_value()),
549- .bind(("was_title", was.0))561+ ("was_title".into(), was.0.into_value()),
550- .bind(("was_description", was.1))562+ ("was_description".into(), was.1.into_value()),
551- .bind(("was_kind", was.2))563+ ("was_kind".into(), was.2.into_value()),
552- .bind(("was_mode", was.3))564+ ("was_mode".into(), was.3.into_value()),
553- .bind(("was_starts", was.4))565+ ("was_starts".into(), was.4.into_value()),
554- .bind(("was_ends", was.5))566+ ("was_ends".into(), was.5.into_value()),
555- .bind(("was_duration", was.6))567+ ("was_duration".into(), was.6.into_value()),
556- .bind(("was_max_attempts", was.7))568+ ("was_max_attempts".into(), was.7.into_value()),
557- .bind(("was_allow_rejoin", was.8))569+ ("was_allow_rejoin".into(), was.8.into_value()),
558- .bind(("was_allow_review", was.9))570+ ("was_allow_review".into(), was.9.into_value()),
559- .bind(("was_draft", was.10))571+ ("was_draft".into(), was.10.into_value()),
560- // The mark counter is pinned like every other column this write572+ // The mark counter is pinned like every other column this write
561- // replaces, and for a sharper reason: a grade increments it, so573+ // replaces, and for a sharper reason: a grade increments it, so
562- // pinning it is what makes "this exam had no marks" β€” the gate the574+ // pinning it is what makes "this exam had no marks" β€” the gate
563- // handler refuses a kind change on β€” true at *write* time and not575+ // the handler refuses a kind change on β€” true at *write* time
564- // merely at read time. A mark landing in between refuses the save.576+ // and not merely at read time. A mark landing in between
565- .bind(("was_results", self.result_count.unwrap_or(0)))577+ // refuses the save.
566- .bind(("new", self))578+ (
567- .await?;579+ "was_results".into(),
580+ self.result_count.unwrap_or(0).into_value(),
581+ ),
582+ ("new".into(), self.into_value()),
583+ ],
584+ &["exam_redraft"],
585+ )
586+ .await?;
568 // An aborted transaction errors every slot; only the THROW's names the587 // An aborted transaction errors every slot; only the THROW's names the
569 // marker (the [`ExamAttempt::write_unfrozen`] treatment).588 // marker (the [`ExamAttempt::write_unfrozen`] treatment).
570- let mut errors = result.take_errors();
571 if errors589 if errors
572 .values()590 .values()
573 .any(|error| error.to_string().contains("exam_redraft"))591 .any(|error| error.to_string().contains("exam_redraft"))
@@ -1015,4 +1033,137 @@ mod tests {
1015 "a raced grade must retry, not 500: {grade_500}/20 rounds, last {last_grade}"1033 "a raced grade must retry, not 500: {grade_500}/20 rounds, last {last_grade}"
1016 );1034 );
1017 }1035 }
1036+
1037+ /// One choice question on `exam`, with a real subject row behind it β€” a
1038+ /// question claims a reference on its subject and is refused without one.
1039+ async fn question_on(exam: &Exam, db: &Database) -> crate::domain::exam_question::ExamQuestion {
1040+ use crate::domain::exam_question::{
1041+ ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
1042+ };
1043+ let spec = QuestionSpec::try_new(
1044+ QuestionKind::try_new("choice").unwrap(),
1045+ Some(vec![
1046+ ChoiceInput {
1047+ id: Some("a".into()),
1048+ text: "5".into(),
1049+ },
1050+ ChoiceInput {
1051+ id: Some("b".into()),
1052+ text: "6".into(),
1053+ },
1054+ ]),
1055+ Some("b".into()),
1056+ &[],
1057+ )
1058+ .unwrap();
1059+ let subject = crate::domain::subject::Subject::create(
1060+ &CourseId::generate(),
1061+ crate::domain::subject::SubjectName::try_new("topic").unwrap(),
1062+ crate::domain::subject::SubjectDescription::try_new("").unwrap(),
1063+ db,
1064+ )
1065+ .await
1066+ .unwrap();
1067+ ExamQuestion::create(
1068+ exam.get_id(),
1069+ subject.get_id().clone(),
1070+ QuestionText::try_new("3 + 3?").unwrap(),
1071+ QuestionPoints::try_new(5).unwrap(),
1072+ spec,
1073+ db,
1074+ )
1075+ .await
1076+ .unwrap()
1077+ }
1078+
1079+ /// The `Menu::delete` defect, one domain over: a student's answer must not
1080+ /// outlive the exam it belongs to. Guarding the save by *reading* the exam
1081+ /// would not do it β€” the read sees a row [`Exam::delete`] has removed but
1082+ /// not committed, while its `DELETE exam_answer WHERE exam = $ex` swept a
1083+ /// snapshot predating the save, so both commit and the answer is left
1084+ /// pointing at an exam that is gone. [`ExamAnswer::save`] writes the exam
1085+ /// row instead (its `result_count`, back unchanged), so the two transactions
1086+ /// touch one key and the store refuses one of them.
1087+ ///
1088+ /// The window is opened by the database, not by a lucky interleaving: a
1089+ /// `DEFINE EVENT` on `exam` fires *inside* the delete's own transaction the
1090+ /// instant the row goes, so the `SLEEP` lands exactly between the delete and
1091+ /// its cascade every time. Nothing in `src/` knows about it; the seam is the
1092+ /// schema.
1093+ ///
1094+ /// One child per round, deliberately β€” in the menu twin, two children in one
1095+ /// round hid the bug: the first writer made the delete lose and re-send, and
1096+ /// the re-sent sweep removed the other's row.
1097+ ///
1098+ /// Real server, and `#[ignore]`d for it: the subject *is* the store's
1099+ /// conflict detection, which `init_mem`'s embedded engine does not have β€” it
1100+ /// commits both writes and answers `Ok` to each, so this passes there on
1101+ /// broken code. Mutation-tested: putting the bare
1102+ /// `db.upsert(id).content(answer)` back turns it red (the exact output is in
1103+ /// the commit that added it).
1104+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1105+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1106+ async fn an_answer_written_inside_a_delete_never_outlives_the_exam() {
1107+ use crate::domain::exam_answer::ExamAnswer;
1108+ let (db, _serialized) = crate::database::init_test_server("exam_answer_race").await;
1109+ // Hold the delete open for a full second after the row is gone, while
1110+ // its cascade still has to run.
1111+ db.query(
1112+ "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1113+ THEN { SLEEP 1s; };",
1114+ )
1115+ .await
1116+ .unwrap()
1117+ .check()
1118+ .unwrap();
1119+
1120+ let (mut answers, mut swept) = (0, 0);
1121+ for round in 0..4 {
1122+ let exam = published(&db).await;
1123+ let question = question_on(&exam, &db).await;
1124+ let id = exam.get_id().clone();
1125+ let student = UserId::from_key(&format!("stu{round}"));
1126+ // The stored choice ids are minted by the create, not the ones the
1127+ // spec asked for β€” an answer must name one of *those*.
1128+ let pick = question.get_choices().unwrap()[1]
1129+ .get_id()
1130+ .as_str()
1131+ .to_string();
1132+
1133+ let drop_it = {
1134+ let db = db.clone();
1135+ tokio::spawn(async move { exam.delete(&db).await })
1136+ };
1137+ // The save starts inside the held window β€” the exam row is gone but
1138+ // uncommitted, which is exactly what an exam read believes.
1139+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1140+ let child = {
1141+ let (db, question, student) = (db.clone(), question.clone(), student.clone());
1142+ tokio::spawn(async move {
1143+ ExamAnswer::save(&question, &student, 1, Some(pick), None, &db).await
1144+ })
1145+ };
1146+ let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1147+ // A 404 for the save, or a NotFound for the delete, is a correct
1148+ // answer β€” the only defect is stored state.
1149+ assert!(
1150+ !matches!(child, Err(AppError::Db(_))),
1151+ "round {round}: a raced save must be answered, not 500: {child:?}"
1152+ );
1153+
1154+ // Stored state is the whole verdict; a return value is not evidence.
1155+ if Exam::read(&id, &db).await.unwrap().is_none() {
1156+ swept += 1;
1157+ answers += ExamAnswer::list_for_exam(&id, &db).await.unwrap().len();
1158+ } else if drop_it.is_ok() {
1159+ panic!("round {round}: the delete reported success but the exam is still there");
1160+ }
1161+ }
1162+ eprintln!("Exam::delete raced by an answer save: {swept}/4 rounds deleted the exam");
1163+ assert!(
1164+ swept > 0,
1165+ "no round ever deleted the exam, so the window was never reached"
1166+ );
1167+ assert_eq!(answers, 0, "an answer outlived its exam");
1168+ }
1018 }1169 }
src/domain/exam_answer.rsmodified+155 -4
@@ -1,7 +1,7 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3-use crate::constant::{EXAM_ANSWER_TABLE, MAX_ANSWER_TEXT_LEN};3+use crate::constant::{EXAM_ANSWER_TABLE, EXAM_RESULT_COUNT_FIELD, MAX_ANSWER_TEXT_LEN};
4-use crate::database::Database;4+use crate::database::{Database, transaction_with_retry};
5 use crate::domain::exam::ExamId;5 use crate::domain::exam::ExamId;
6 use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId};6 use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId};
7 use crate::domain::key;7 use crate::domain::key;
@@ -171,8 +171,82 @@ impl ExamAnswer {
171 text,171 text,
172 updated_at: Timestamp::now(),172 updated_at: Timestamp::now(),
173 };173 };
174- let saved: Option<ExamAnswer> = db.upsert(answer.id.record()).content(answer).await?;174+ // The save writes the *exam row* as well as the answer, in one
175- saved.ok_or_else(|| AppError::Internal("failed to save exam answer".into()))175+ // transaction, and that is what ties the answer's fate to its exam:
176+ // reading the exam does not survive [`crate::domain::exam::Exam::delete`]'s
177+ // window β€” a save landing after its `DELETE exam_answer WHERE exam = $ex`
178+ // but before the commit reads an exam that is still there (uncommitted)
179+ // while the sweep ran on a snapshot predating this row, so both commit
180+ // and the answer outlives the exam (measured 4 of 4 raced rounds).
181+ // Writing the key the delete removes makes the two collide, and the
182+ // store refuses one of them. It is the shape
183+ // [`crate::domain::menu::bump_menu_and_write`] uses, and the one a mark
184+ // already uses on this very row
185+ // ([`crate::domain::exam_result::ExamResult::grade`]).
186+ //
187+ // The bump-and-restore is not a flourish, it is the whole instrument.
188+ // The exam carries no revision to bump and must not grow one β€” its save
189+ // is a whole-row `CONTENT` write, so a column this struct did not know
190+ // about would be wiped by the next PATCH β€” so this touches the one
191+ // counter it already has and puts it back. Writing the *same* value is
192+ // not enough: an `UPDATE` that leaves the document unchanged is elided
193+ // and never reaches the store's write set, which the race test proved
194+ // (green on the raced delete, red the moment the value moves for real).
195+ // The restore is by captured value, `NONE` included, so the row is
196+ // byte-identical afterwards: the boot backfill still finds the rows it
197+ // keys on (`WHERE result_count = NONE`), the PATCH's
198+ // `(result_count ?? 0) = $was_results` still passes, and no teacher's
199+ // edit is refused because a student typed. Both statements are inside
200+ // the transaction, so a crash between them cannot leave the counter up.
201+ // No `cap::counter_lock` either: no counter moves here, and the hottest
202+ // write path in the app should not queue behind one.
203+ //
204+ // Admissible for `transaction_with_retry`: the `UPDATE`s, `SELECT`,
205+ // `IF`/`THROW` and `RETURN` can never answer "already exists", and the
206+ // `UPSERT`'s id is bijective with the (question, user, seq) triple
207+ // `exam_answer` keys β€” a lost round wrote nothing, and re-sending
208+ // resolves onto the same row rather than colliding with it.
209+ let (mut result, mut errors) = transaction_with_retry(
210+ db,
211+ &format!(
212+ "BEGIN TRANSACTION;
213+ LET $was = (SELECT VALUE {EXAM_RESULT_COUNT_FIELD} FROM ONLY $ex);
214+ LET $touched = (UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = \
215+ ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id);
216+ IF array::len($touched) = 0 {{ THROW 'no_exam' }};
217+ UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = $was;
218+ LET $row = (UPSERT $id CONTENT $answer RETURN AFTER);
219+ RETURN $row[0];
220+ COMMIT TRANSACTION;"
221+ ),
222+ &[
223+ ("ex".into(), answer.exam.record().into_value()),
224+ ("id".into(), answer.id.record().into_value()),
225+ ("answer".into(), answer.into_value()),
226+ ],
227+ &["no_exam"],
228+ )
229+ .await?;
230+ // An aborted transaction errors *every* slot, most with a generic "not
231+ // executed" β€” only the THROW's own slot names the reason.
232+ if errors
233+ .values()
234+ .any(|error| error.to_string().contains("no_exam"))
235+ {
236+ return Err(AppError::NotFound);
237+ }
238+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
239+ return Err(error.into());
240+ }
241+ // The trailing `RETURN` is the last statement before `COMMIT`, so its
242+ // slot follows the statement count rather than a hand-kept number (the
243+ // `Exam::delete` treatment); `num_statements` counts BEGIN and COMMIT.
244+ let slot = result.num_statements().saturating_sub(2);
245+ result
246+ .take::<Vec<ExamAnswer>>(slot)?
247+ .into_iter()
248+ .next()
249+ .ok_or_else(|| AppError::Internal("failed to save exam answer".into()))
176 }250 }
177 251
178 /// One student's stored answer for a question in sitting `seq`, if any.252 /// One student's stored answer for a question in sitting `seq`, if any.
@@ -415,4 +489,81 @@ mod tests {
415 let text = text_question(&exam, 10);489 let text = text_question(&exam, 10);
416 assert_eq!(answer(&text, &user, None).is_correct(&text), None);490 assert_eq!(answer(&text, &user, None).is_correct(&text), None);
417 }491 }
492+
493+ /// The bite test for the exam-row touch in [`ExamAnswer::save`]: it exists
494+ /// to collide with [`crate::domain::exam::Exam::delete`], so it must leave
495+ /// the counter it borrows exactly where it found it β€” absent stays absent
496+ /// (the boot backfill keys on `result_count = NONE`), and a real count is
497+ /// not moved by a student typing. The race half is
498+ /// `domain::exam::tests::an_answer_written_inside_a_delete_never_outlives_the_exam`,
499+ /// which needs a real server; this half is the arithmetic and runs anywhere.
500+ #[tokio::test]
501+ async fn a_save_puts_the_exams_mark_counter_back_exactly() {
502+ use crate::domain::exam::{
503+ Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,
504+ };
505+ let db = crate::database::init_mem().await.unwrap();
506+ let kinds = crate::domain::settings::Settings::defaults()
507+ .get_exam_kinds()
508+ .to_vec();
509+ let exam = Exam::create(
510+ &student(),
511+ &crate::domain::course::CourseId::generate(),
512+ ExamTitle::try_new("quiz").unwrap(),
513+ ExamDescription::try_new("").unwrap(),
514+ ExamKind::try_new("quiz", &kinds).unwrap(),
515+ ExamSchedule::try_new(None, None, None, None).unwrap(),
516+ ExamAttemptLimit::try_new(1).unwrap(),
517+ true,
518+ false,
519+ false,
520+ &db,
521+ )
522+ .await
523+ .unwrap();
524+ let stored = async |db: &Database| -> Option<i64> {
525+ let mut result = db
526+ .query("SELECT VALUE result_count FROM ONLY $ex")
527+ .bind(("ex", exam.get_id().record()))
528+ .await
529+ .unwrap()
530+ .check()
531+ .unwrap();
532+ result.take::<Option<i64>>(0).unwrap()
533+ };
534+ let question = choice_question(exam.get_id(), 10, 1);
535+ let pick = choice_id(&question, 1).as_str().to_string();
536+
537+ // A fresh exam carries no counter at all, and must still not after a save.
538+ assert_eq!(stored(&db).await, None, "the fixture must start absent");
539+ ExamAnswer::save(&question, &student(), 1, Some(pick.clone()), None, &db)
540+ .await
541+ .unwrap();
542+ assert_eq!(
543+ stored(&db).await,
544+ None,
545+ "the touch left the counter set β€” the backfill keys on NONE"
546+ );
547+
548+ // …and a counter that marks have moved is put back at its own value.
549+ db.query("UPDATE $ex SET result_count = 7")
550+ .bind(("ex", exam.get_id().record()))
551+ .await
552+ .unwrap()
553+ .check()
554+ .unwrap();
555+ ExamAnswer::save(&question, &student(), 2, Some(pick), None, &db)
556+ .await
557+ .unwrap();
558+ assert_eq!(stored(&db).await, Some(7), "the touch moved a real count");
559+
560+ // The gate that makes the touch worth having: no exam, no answer.
561+ let orphan = choice_question(&ExamId::from_key("01NOSUCHEXAMAAAAAAAAAAAAAA"), 10, 0);
562+ let pick = choice_id(&orphan, 0).as_str().to_string();
563+ let refused = ExamAnswer::save(&orphan, &student(), 1, Some(pick), None, &db).await;
564+ assert!(
565+ matches!(refused, Err(AppError::NotFound)),
566+ "a save into a missing exam must 404, got {refused:?}"
567+ );
568+ }
418 }569 }