From bb774eba29a03316f6f13b07ed13ff0f1e3dab18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 31 Jul 2026 04:17:16 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=A7=AE=20refuse=20a=20mark=20on=20?= =?UTF-8?q?an=20exam=20that=20no=20longer=20exists?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.rs | 51 ++++++++++----- src/domain/exam_result.rs | 131 ++++++++++++++++++++++++++++++-------- 2 files changed, 140 insertions(+), 42 deletions(-) diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 39636ff..bee3280 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -892,8 +892,14 @@ mod tests { /// The racer is a mark: [`ExamResult::grade`] claims the exam's own /// `result_count` (and the kind's reference) before writing, so it contends /// with the `DELETE $ex` and with the kind_ref decrement inside the same - /// transaction. The two stored counters assert the delete landed *inside* - /// the burst rather than before or after it. + /// transaction. A round where *some* of the six grades 404 and the rest + /// succeed is the witness that the delete landed inside the burst: the 404 + /// comes from `write_mark`'s existence gate, so it can only be answered by a + /// grade that reached the store after the row was gone, and its siblings' + /// success says the same burst also had grades that got there first. Stored + /// state cannot say this any more — the gate is what stops a mark outliving + /// its exam, so the sweep now finds nothing to leave behind in *every* + /// round, which is asserted below as a fact rather than read as a signal. /// /// It does not prove the retry either: measured at 0 conflicts in 100 raced /// rounds, and green with @@ -908,7 +914,7 @@ mod tests { use crate::domain::exam_result::{ExamResult, Mark}; let (db, _serialized) = crate::database::init_test_server("exam_delete_race").await; let (mut delete_500, mut grade_500) = (0, 0); - let (mut marked, mut swept) = (0, 0); + let (mut split, mut swept) = (0, 0); let (mut last_delete, mut last_grade) = (String::new(), String::new()); for round in 0..20 { let exam = published(&db).await; @@ -953,34 +959,49 @@ mod tests { delete_500 += 1; last_delete = format!("{drop_it:?}"); } + let mut refused = 0; for mark in marks { let mark = mark.await.unwrap(); - if matches!(mark, Err(AppError::Db(_))) { - grade_500 += 1; - last_grade = format!("{mark:?}"); + match mark { + // The existence gate: this grade reached the store after + // the row was gone. + Err(AppError::NotFound) => refused += 1, + Err(AppError::Db(_)) => { + grade_500 += 1; + last_grade = format!("{mark:?}"); + } + _ => {} } } - // Stored state, and *both* outcomes are needed: marks surviving - // means the grades ran past the cascade, no marks left means the - // cascade ran past the grades. Seeing only one of the two is a run - // where the delete never landed inside the burst at all. + // Neither end of the burst: some grades beat the delete and some + // lost to it, so the delete landed *between* them. A round that is + // all-refused or all-through is one where it landed outside. + if (1..6).contains(&refused) { + split += 1; + } if ExamResult::list_for_exam(exam.get_id(), &db) .await .unwrap() .is_empty() { swept += 1; - } else { - marked += 1; } } eprintln!( "Exam::delete raced: {delete_500}/20 delete 500s, {grade_500} grade 500s, \ - {marked} rounds with marks left / {swept} swept" + {split} rounds split by the delete / {swept} swept clean" ); assert!( - marked > 0 && swept > 0, - "the delete never landed inside the burst ({marked} left / {swept} swept)" + split > 0, + "the delete never landed inside the burst (0/20 rounds split)" + ); + // Not a race signal, an invariant: the gate refuses a mark for an exam + // that is gone, so no round can leave one behind for the next reader. + assert_eq!( + swept, + 20, + "a mark outlived its exam in {} rounds", + 20 - swept ); assert_eq!( delete_500, 0, diff --git a/src/domain/exam_result.rs b/src/domain/exam_result.rs index f0f54c4..df5f20f 100644 --- a/src/domain/exam_result.rs +++ b/src/domain/exam_result.rs @@ -5,7 +5,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ EXAM_RESULT_COUNT_FIELD, EXAM_RESULT_TABLE, KIND_REF_TABLE, REF_COUNT_FIELD, }; -use crate::database::Database; +use crate::database::{Database, transaction_with_retry}; use crate::domain::cap; use crate::domain::course::CourseId; use crate::domain::exam::ExamId; @@ -242,33 +242,55 @@ impl ExamResult { mark, graded_by: graded_by.clone(), }; - // The "not a draft" gate rides in the same transaction as the mark, the - // mirror of the re-draft gate on `Exam::update_if_unchanged`: between - // them, a mark and a re-draft racing each other can only ever leave one - // of the two applied, whichever process either ran in. The caller's - // pre-flight check answers the same 409 one round trip earlier. + // The "exists" and "not a draft" gates ride in the same transaction as + // the mark, the mirror of the re-draft gate on + // `Exam::update_if_unchanged`: between them, a mark and a re-draft + // racing each other can only ever leave one of the two applied, + // whichever process either ran in. The existence gate is not + // redundant with the draft one — a deleted exam reads NONE, which is + // *falsy*, so the draft gate alone waved a mark onto an exam that no + // longer existed. The caller's pre-flight check answers the same 409 + // one round trip earlier. // Whether the row was already there rides out of the transaction with // the mark: the answer decides if this grade owes the kind a reference, // and read anywhere else it would be a guess about a row two graders // may be writing at once. - let mut written = db - .query( - "BEGIN TRANSACTION; + // + // Re-sent while the store answers "conflict, retry": the gates read a + // column an exam PATCH writes, so the two contend on one record by + // design. Sound to re-send because the only write is an UPSERT on a + // deterministic id — `key::sitting(exam, user, seq)` *is* the + // `exam_result_exam_user_seq` unique tuple — so it can never answer + // "already exists", the one thing a retry cannot fix. + let (mut written, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + IF (SELECT VALUE id FROM ONLY $exam) IS NONE { THROW 'exam_missing' }; IF (SELECT VALUE draft FROM ONLY $exam) { THROW 'exam_draft' }; LET $before = (SELECT VALUE id FROM ONLY $id); LET $after = (UPSERT $id CONTENT $result RETURN AFTER); RETURN { existed: $before != NONE, result: $after[0] }; COMMIT TRANSACTION;", - ) - .bind(("exam", exam.record())) - .bind(("id", result.id.record())) - .bind(("result", result)) - .await?; - let mut errors = written.take_errors(); - if errors - .values() - .any(|error| error.to_string().contains("exam_draft")) - { + &[ + ("exam".into(), exam.record().into_value()), + ("id".into(), result.id.record().into_value()), + ("result".into(), result.into_value()), + ], + &["exam_missing", "exam_draft"], + ) + .await?; + // An aborted transaction errors every slot and only the THROW's own + // slot names the marker, so a refusal is read by marker while a lost + // round was already re-sent — never reported as a 500. + let thrown = |marker: &str| { + errors + .values() + .any(|error| error.to_string().contains(marker)) + }; + if thrown("exam_missing") { + return Err(AppError::NotFound); + } + if thrown("exam_draft") { return Err(draft_error()); } if let Some(error) = errors.drain().map(|(_, error)| error).next() { @@ -348,8 +370,18 @@ impl ExamResult { // release them a second time, and on a kind another exam still grades // under, one release too many reads as one mark too few — a kind // wrongly free to leave the settings. - let mut result = db - .query(format!( + // + // Re-sent while the store answers "conflict, retry": the counters this + // touches are the ones a concurrent grade claims, so a lost round is + // routine and aborts having written nothing. `check()` cannot be used + // to read the outcome — it takes the *lowest*-slot error, and an + // aborted transaction's generic "not executed" sibling masked the real + // conflict, the exact defect deleted from `Exam::delete`. No THROW of + // its own, and only `DELETE`/`UPDATE` inside, so nothing here can + // answer "already exists" and make a retry unsound. + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( "BEGIN TRANSACTION; LET $gone = (DELETE exam_result WHERE exam = $ex AND user = $usr RETURN BEFORE); IF array::len($gone) > 0 {{ @@ -360,12 +392,18 @@ impl ExamResult { }}; RETURN $gone; COMMIT TRANSACTION;" - )) - .bind(("ex", exam.record())) - .bind(("usr", user.record())) - .bind(("kind", kind.to_string())) - .await? - .check()?; + ), + &[ + ("ex".into(), exam.record().into_value()), + ("usr".into(), user.record().into_value()), + ("kind".into(), kind.to_string().into_value()), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } // `RETURN` is the last statement before `COMMIT`; its slot follows the // statement count, as in `Exam::delete`. let slot = result.num_statements().saturating_sub(2); @@ -393,6 +431,17 @@ mod tests { let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA"); let user = UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"); let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + // The exam has to be real: a mark is refused on one that isn't. + db.query( + "CREATE $ex SET creator = $t, course = course:c, title = 't', + description = '', kind = 'midterm'", + ) + .bind(("ex", exam.record())) + .bind(("t", teacher.record())) + .await + .unwrap() + .check() + .unwrap(); // Grade sitting #1, then a retake as sitting #2 — two rows, not one. ExamResult::grade( @@ -455,4 +504,32 @@ mod tests { .is_empty() ); } + + /// A deleted exam reads NONE, and NONE is falsy — the draft gate alone let + /// a mark land on an exam that no longer existed. + #[tokio::test] + async fn a_mark_is_refused_on_an_exam_that_no_longer_exists() { + let db = init_mem().await.unwrap(); + let exam = ExamId::from_key("01TESTGONEEXAMAAAAAAAAAAAA"); + let user = UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"); + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + + let refused = ExamResult::grade( + &exam, + &user, + 1, + Mark::try_new(40).unwrap(), + &teacher, + "midterm", + &db, + ) + .await; + assert!(matches!(refused, Err(AppError::NotFound)), "{refused:?}"); + assert!( + ExamResult::list_all_for_exam_user(&exam, &user, &db) + .await + .unwrap() + .is_empty() + ); + } }