forge
Explore
Log in

Don't you dare go Hollow

🧮 refuse a mark on an exam that no longer exists

Browse files at this commit

bb774eba29a03316f6f13b07ed13ff0f1e3dab18Ahmet Kaan GümüşParent: 755f4ab
  • fix
    • 🧮 refuse a mark on an exam that no longer exists
Show full message
fix: 🧮 refuse a mark on an exam that no longer exists

ExamResult::write_mark gated on the exam being a draft, and read that
gate as `IF (SELECT VALUE draft FROM ONLY $exam)`. A deleted exam reads
NONE, NONE is falsy, so the gate passed and the mark landed cleanly on a
row that was already gone. The grade handler's pre-flight read cannot
close that — DELETE /exams/{id} takes no EXAM_LOCK while grading holds a
read lock, so a delete can land in the gap.

A missing exam now throws inside the same transaction and answers 404.
The handler already documented that status, so no doc surface moves.

Exam::delete's race test had to change with it. Its witness that the
delete landed inside the racer burst was "some marks survived" — exactly
the orphan this gate removes, so the witness was structurally
unsatisfiable and the test failed 3 of 3 runs against the real server.
It is #[ignore]d, so a green suite hid that.

The replacement witness is per-round: of six racing grades, a round where
between one and five were refused proves the delete landed between them.
That is stronger than what it replaces, which a clean no-overlap split
would also have satisfied. Measured two to four such rounds per twenty
across five runs, and it goes red when the beat is flattened so the
delete always lands first. What survives as an assertion rather than a
signal is that every round sweeps clean: a mark never outlives its exam.
src/domain/exam.rsmodified+36 -15
@@ -892,8 +892,14 @@ mod tests {
892892 /// The racer is a mark: [`ExamResult::grade`] claims the exam's own
893893 /// `result_count` (and the kind's reference) before writing, so it contends
894894 /// with the `DELETE $ex` and with the kind_ref decrement inside the same
895- /// transaction. The two stored counters assert the delete landed *inside*
896- /// the burst rather than before or after it.
895+ /// transaction. A round where *some* of the six grades 404 and the rest
896+ /// succeed is the witness that the delete landed inside the burst: the 404
897+ /// comes from `write_mark`'s existence gate, so it can only be answered by a
898+ /// grade that reached the store after the row was gone, and its siblings'
899+ /// success says the same burst also had grades that got there first. Stored
900+ /// state cannot say this any more — the gate is what stops a mark outliving
901+ /// its exam, so the sweep now finds nothing to leave behind in *every*
902+ /// round, which is asserted below as a fact rather than read as a signal.
897903 ///
898904 /// It does not prove the retry either: measured at 0 conflicts in 100 raced
899905 /// rounds, and green with
@@ -908,7 +914,7 @@ mod tests {
908914 use crate::domain::exam_result::{ExamResult, Mark};
909915 let (db, _serialized) = crate::database::init_test_server("exam_delete_race").await;
910916 let (mut delete_500, mut grade_500) = (0, 0);
911- let (mut marked, mut swept) = (0, 0);
917+ let (mut split, mut swept) = (0, 0);
912918 let (mut last_delete, mut last_grade) = (String::new(), String::new());
913919 for round in 0..20 {
914920 let exam = published(&db).await;
@@ -953,34 +959,49 @@ mod tests {
953959 delete_500 += 1;
954960 last_delete = format!("{drop_it:?}");
955961 }
962+ let mut refused = 0;
956963 for mark in marks {
957964 let mark = mark.await.unwrap();
958- if matches!(mark, Err(AppError::Db(_))) {
959- grade_500 += 1;
960- last_grade = format!("{mark:?}");
965+ match mark {
966+ // The existence gate: this grade reached the store after
967+ // the row was gone.
968+ Err(AppError::NotFound) => refused += 1,
969+ Err(AppError::Db(_)) => {
970+ grade_500 += 1;
971+ last_grade = format!("{mark:?}");
972+ }
973+ _ => {}
961974 }
962975 }
963- // Stored state, and *both* outcomes are needed: marks surviving
964- // means the grades ran past the cascade, no marks left means the
965- // cascade ran past the grades. Seeing only one of the two is a run
966- // where the delete never landed inside the burst at all.
976+ // Neither end of the burst: some grades beat the delete and some
977+ // lost to it, so the delete landed *between* them. A round that is
978+ // all-refused or all-through is one where it landed outside.
979+ if (1..6).contains(&refused) {
980+ split += 1;
981+ }
967982 if ExamResult::list_for_exam(exam.get_id(), &db)
968983 .await
969984 .unwrap()
970985 .is_empty()
971986 {
972987 swept += 1;
973- } else {
974- marked += 1;
975988 }
976989 }
977990 eprintln!(
978991 "Exam::delete raced: {delete_500}/20 delete 500s, {grade_500} grade 500s, \
979- {marked} rounds with marks left / {swept} swept"
992+ {split} rounds split by the delete / {swept} swept clean"
980993 );
981994 assert!(
982- marked > 0 && swept > 0,
983- "the delete never landed inside the burst ({marked} left / {swept} swept)"
995+ split > 0,
996+ "the delete never landed inside the burst (0/20 rounds split)"
997+ );
998+ // Not a race signal, an invariant: the gate refuses a mark for an exam
999+ // that is gone, so no round can leave one behind for the next reader.
1000+ assert_eq!(
1001+ swept,
1002+ 20,
1003+ "a mark outlived its exam in {} rounds",
1004+ 20 - swept
9841005 );
9851006 assert_eq!(
9861007 delete_500, 0,
src/domain/exam_result.rsmodified+104 -27
@@ -5,7 +5,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
55 use crate::constant::{
66 EXAM_RESULT_COUNT_FIELD, EXAM_RESULT_TABLE, KIND_REF_TABLE, REF_COUNT_FIELD,
77 };
8-use crate::database::Database;
8+use crate::database::{Database, transaction_with_retry};
99 use crate::domain::cap;
1010 use crate::domain::course::CourseId;
1111 use crate::domain::exam::ExamId;
@@ -242,33 +242,55 @@ impl ExamResult {
242242 mark,
243243 graded_by: graded_by.clone(),
244244 };
245- // The "not a draft" gate rides in the same transaction as the mark, the
246- // mirror of the re-draft gate on `Exam::update_if_unchanged`: between
247- // them, a mark and a re-draft racing each other can only ever leave one
248- // of the two applied, whichever process either ran in. The caller's
249- // pre-flight check answers the same 409 one round trip earlier.
245+ // The "exists" and "not a draft" gates ride in the same transaction as
246+ // the mark, the mirror of the re-draft gate on
247+ // `Exam::update_if_unchanged`: between them, a mark and a re-draft
248+ // racing each other can only ever leave one of the two applied,
249+ // whichever process either ran in. The existence gate is not
250+ // redundant with the draft one — a deleted exam reads NONE, which is
251+ // *falsy*, so the draft gate alone waved a mark onto an exam that no
252+ // longer existed. The caller's pre-flight check answers the same 409
253+ // one round trip earlier.
250254 // Whether the row was already there rides out of the transaction with
251255 // the mark: the answer decides if this grade owes the kind a reference,
252256 // and read anywhere else it would be a guess about a row two graders
253257 // may be writing at once.
254- let mut written = db
255- .query(
256- "BEGIN TRANSACTION;
258+ //
259+ // Re-sent while the store answers "conflict, retry": the gates read a
260+ // column an exam PATCH writes, so the two contend on one record by
261+ // design. Sound to re-send because the only write is an UPSERT on a
262+ // deterministic id — `key::sitting(exam, user, seq)` *is* the
263+ // `exam_result_exam_user_seq` unique tuple — so it can never answer
264+ // "already exists", the one thing a retry cannot fix.
265+ let (mut written, mut errors) = transaction_with_retry(
266+ db,
267+ "BEGIN TRANSACTION;
268+ IF (SELECT VALUE id FROM ONLY $exam) IS NONE { THROW 'exam_missing' };
257269 IF (SELECT VALUE draft FROM ONLY $exam) { THROW 'exam_draft' };
258270 LET $before = (SELECT VALUE id FROM ONLY $id);
259271 LET $after = (UPSERT $id CONTENT $result RETURN AFTER);
260272 RETURN { existed: $before != NONE, result: $after[0] };
261273 COMMIT TRANSACTION;",
262- )
263- .bind(("exam", exam.record()))
264- .bind(("id", result.id.record()))
265- .bind(("result", result))
266- .await?;
267- let mut errors = written.take_errors();
268- if errors
269- .values()
270- .any(|error| error.to_string().contains("exam_draft"))
271- {
274+ &[
275+ ("exam".into(), exam.record().into_value()),
276+ ("id".into(), result.id.record().into_value()),
277+ ("result".into(), result.into_value()),
278+ ],
279+ &["exam_missing", "exam_draft"],
280+ )
281+ .await?;
282+ // An aborted transaction errors every slot and only the THROW's own
283+ // slot names the marker, so a refusal is read by marker while a lost
284+ // round was already re-sent — never reported as a 500.
285+ let thrown = |marker: &str| {
286+ errors
287+ .values()
288+ .any(|error| error.to_string().contains(marker))
289+ };
290+ if thrown("exam_missing") {
291+ return Err(AppError::NotFound);
292+ }
293+ if thrown("exam_draft") {
272294 return Err(draft_error());
273295 }
274296 if let Some(error) = errors.drain().map(|(_, error)| error).next() {
@@ -348,8 +370,18 @@ impl ExamResult {
348370 // release them a second time, and on a kind another exam still grades
349371 // under, one release too many reads as one mark too few — a kind
350372 // wrongly free to leave the settings.
351- let mut result = db
352- .query(format!(
373+ //
374+ // Re-sent while the store answers "conflict, retry": the counters this
375+ // touches are the ones a concurrent grade claims, so a lost round is
376+ // routine and aborts having written nothing. `check()` cannot be used
377+ // to read the outcome — it takes the *lowest*-slot error, and an
378+ // aborted transaction's generic "not executed" sibling masked the real
379+ // conflict, the exact defect deleted from `Exam::delete`. No THROW of
380+ // its own, and only `DELETE`/`UPDATE` inside, so nothing here can
381+ // answer "already exists" and make a retry unsound.
382+ let (mut result, mut errors) = transaction_with_retry(
383+ db,
384+ &format!(
353385 "BEGIN TRANSACTION;
354386 LET $gone = (DELETE exam_result WHERE exam = $ex AND user = $usr RETURN BEFORE);
355387 IF array::len($gone) > 0 {{
@@ -360,12 +392,18 @@ impl ExamResult {
360392 }};
361393 RETURN $gone;
362394 COMMIT TRANSACTION;"
363- ))
364- .bind(("ex", exam.record()))
365- .bind(("usr", user.record()))
366- .bind(("kind", kind.to_string()))
367- .await?
368- .check()?;
395+ ),
396+ &[
397+ ("ex".into(), exam.record().into_value()),
398+ ("usr".into(), user.record().into_value()),
399+ ("kind".into(), kind.to_string().into_value()),
400+ ],
401+ &[],
402+ )
403+ .await?;
404+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
405+ return Err(error.into());
406+ }
369407 // `RETURN` is the last statement before `COMMIT`; its slot follows the
370408 // statement count, as in `Exam::delete`.
371409 let slot = result.num_statements().saturating_sub(2);
@@ -393,6 +431,17 @@ mod tests {
393431 let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA");
394432 let user = UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA");
395433 let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
434+ // The exam has to be real: a mark is refused on one that isn't.
435+ db.query(
436+ "CREATE $ex SET creator = $t, course = course:c, title = 't',
437+ description = '', kind = 'midterm'",
438+ )
439+ .bind(("ex", exam.record()))
440+ .bind(("t", teacher.record()))
441+ .await
442+ .unwrap()
443+ .check()
444+ .unwrap();
396445
397446 // Grade sitting #1, then a retake as sitting #2 — two rows, not one.
398447 ExamResult::grade(
@@ -455,4 +504,32 @@ mod tests {
455504 .is_empty()
456505 );
457506 }
507+
508+ /// A deleted exam reads NONE, and NONE is falsy — the draft gate alone let
509+ /// a mark land on an exam that no longer existed.
510+ #[tokio::test]
511+ async fn a_mark_is_refused_on_an_exam_that_no_longer_exists() {
512+ let db = init_mem().await.unwrap();
513+ let exam = ExamId::from_key("01TESTGONEEXAMAAAAAAAAAAAA");
514+ let user = UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA");
515+ let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
516+
517+ let refused = ExamResult::grade(
518+ &exam,
519+ &user,
520+ 1,
521+ Mark::try_new(40).unwrap(),
522+ &teacher,
523+ "midterm",
524+ &db,
525+ )
526+ .await;
527+ assert!(matches!(refused, Err(AppError::NotFound)), "{refused:?}");
528+ assert!(
529+ ExamResult::list_all_for_exam_user(&exam, &user, &db)
530+ .await
531+ .unwrap()
532+ .is_empty()
533+ );
534+ }
458535 }