diff --git a/src/database.rs b/src/database.rs index 917e952..86f7dee 100644 --- a/src/database.rs +++ b/src/database.rs @@ -136,6 +136,75 @@ pub(crate) async fn write_with_retry( .unwrap_or_else(|| AppError::Internal("a guarded write never ran".into()))) } +/// Send one guarded `BEGIN…COMMIT` cascade, re-sending it while the store +/// answers "conflict, retry", and hand back both the response and the errors +/// drained off it. +/// +/// [`write_with_retry`]'s story, for the cascades that cannot be one statement: +/// the guard reads a column a rival writes, so the two contend on one record by +/// design, and a lost round aborts the transaction having written *nothing* — +/// which is what makes re-sending the whole of the recovery. +/// +/// Both halves come back because the caller needs both and `take_errors` +/// consumes: the response carries the result slots, and only the error map can +/// tell a deliberate `THROW` from a lost round. `refusals` are the caller's +/// `THROW` markers and they are matched *first* — a `THROW` is a decision, and +/// it outranks a conflict. Everything after that ordering is why this exists: +/// an aborted transaction errors *every* slot, and all but the failing one say +/// a generic "not executed", which is the consequence of the abort and never a +/// reason of its own. Picking one of those out of the unordered `HashMap` — or +/// taking the first via `check()` — retired a retryable round as a 500, measured +/// on `Course::delete` at 1-3 of 20 raced rounds. +/// +/// [`write_with_retry`]'s restriction carries over, and a cascade makes it +/// easier to trip: no statement inside may be able to answer "already exists", +/// because that is the other thing [`lost_the_race`] matches and re-sending it +/// would just fail the same way until the tries run out — turning a 409 into a +/// 500, which is the exact defect this exists to prevent. So `UPDATE` and +/// `DELETE`, and no `CREATE` and no write under a `UNIQUE` index anywhere in +/// the batch. The four cascades on it today are clear on both counts. +pub(crate) async fn transaction_with_retry( + db: &Database, + sql: &str, + bindings: &[(String, surrealdb::types::Value)], + refusals: &[&str], +) -> Result< + ( + surrealdb::IndexedResults, + std::collections::HashMap, + ), + AppError, +> { + let mut last = None; + for attempt in 0..CAP_WRITE_TRIES { + backoff(attempt).await; + let mut query = db.query(sql); + for (name, value) in bindings { + query = query.bind((name.clone(), value.clone())); + } + let mut result = match query.await { + Ok(result) => result, + Err(err) if lost_the_race(&err) => { + last = Some(err); + continue; + } + Err(err) => return Err(err.into()), + }; + let mut errors = result.take_errors(); + let refused = |error: &surrealdb::Error| { + let message = error.to_string(); + refusals.iter().any(|marker| message.contains(marker)) + }; + if errors.values().any(refused) || !errors.values().any(lost_the_race) { + return Ok((result, errors)); + } + last = errors.drain().map(|(_, error)| error).find(lost_the_race); + } + Err(last + .map(AppError::from) + .unwrap_or_else(|| AppError::Internal("a guarded cascade never ran".into()))) +} + /// Wait out one lost round. Exponential with jitter, because racers arrive in /// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them. /// Attempt zero waits not at all. @@ -194,8 +263,23 @@ pub async fn init_mem() -> Result { /// Every caller is `#[ignore]`d, so a machine with no server prints them as /// `ignored` rather than passing: this is not a test that may quietly skip. /// `HEZARFEN_TEST_DB` overrides the address; the credentials are `compose.yaml`'s. +/// +/// The guard handed back with the handle serializes these tests against each +/// other and must be held for the whole test — hence the tuple, which cannot be +/// forgotten the way a separate `lock()` line can. `cargo test -- --ignored` +/// runs them in parallel, and while each has a namespace to itself they all +/// burst against the *one* server: their beats are sub-millisecond, so a +/// sibling's burst pushes a delete clean out of the window it is meant to land +/// in (measured 4 runs in 4 at 3 of 6 failing their own "the race was reached" +/// guard). Serialized, the plain documented command works. +#[cfg(test)] +pub(crate) static RACE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + #[cfg(test)] -pub(crate) async fn init_test_server(scratch: &str) -> Database { +pub(crate) async fn init_test_server( + scratch: &str, +) -> (Database, tokio::sync::MutexGuard<'static, ()>) { + let serialized = RACE_LOCK.lock().await; let url = std::env::var("HEZARFEN_TEST_DB").unwrap_or_else(|_| "ws://127.0.0.1:8000".to_string()); let db = surrealdb::engine::any::connect(url.clone()) @@ -216,7 +300,7 @@ pub(crate) async fn init_test_server(scratch: &str) -> Database { db.use_ns(ns.clone()).use_db(ns).await.expect("scratch ns"); let db = std::sync::Arc::new(db); migrate(&db).await.expect("migrate the scratch namespace"); - db + (db, serialized) } /// Apply the schema + backfills. Idempotent — `init` runs it on every boot, diff --git a/src/domain/course.rs b/src/domain/course.rs index 07e5e41..ea80912 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -5,7 +5,7 @@ use crate::constant::{ COURSE_COUNT_FIELD, COURSE_TABLE, ENROLLMENT_COUNT_FIELD, MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN, REF_COUNT_FIELD, }; -use crate::database::Database; +use crate::database::{Database, transaction_with_retry}; use crate::domain::cap; use crate::domain::field_update::FieldUpdate; use crate::domain::page::PagedList; @@ -404,8 +404,7 @@ impl Course { /// the row gone (and is refused itself). `Err(NotFound)` /// keeps the answer a concurrent *delete* used to get. pub async fn delete(self, db: &Database) -> Result { - let mut result = db - .query(format!( + let sql = format!( "BEGIN TRANSACTION; LET $gone = (DELETE $course WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); IF array::len($gone) = 0 {{ THROW '{ROSTER_MARK}' }}; @@ -437,12 +436,17 @@ impl Course { DELETE homework WHERE course = $course; DELETE exam WHERE course = $course; COMMIT TRANSACTION;" - )) - .bind(("course", self.id.record())) - .await?; + ); // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the marker. - let mut errors = result.take_errors(); + // executed" — only the THROW's own slot names the marker, and a lost + // round is re-sent rather than reported (see [`transaction_with_retry`]). + let (_, mut errors) = transaction_with_retry( + db, + &sql, + &[("course".into(), self.id.record().into_value())], + &[ROSTER_MARK], + ) + .await?; if errors .values() .any(|error| error.to_string().contains(ROSTER_MARK)) @@ -677,4 +681,103 @@ mod tests { assert!(decoded.get_teachers().is_empty()); assert!(!decoded.is_assigned(&assigned)); } + + /// MEASUREMENT — the one race test that actually measures the retry, and + /// the only one of the four that does. The other three (subject, term, + /// exam) are status-code guards; each says so on itself. + /// + /// `Course::delete` is one `BEGIN…COMMIT` whose guard reads + /// `enrollment_count` off the very record a concurrent enroll increments, + /// so the two contend by design, and its cascade is long enough that a + /// rival's write lands mid-transaction. Losing that round writes nothing, + /// which is what makes re-sending it the recovery. Without + /// [`crate::database::transaction_with_retry`] a lost round comes out as a + /// 500: mutation-tested by cutting that retry loop to one attempt, which + /// turns this test red at 1-2 of 20 rounds (3 runs in 5 — the window is + /// real but narrow, so a single green run under the mutation means nothing). + /// + /// A refusal (`Ok(false)`) or an `Err(NotFound)` is *correct* here and + /// must not fail this test: the only defect is `AppError::Db`. + /// + /// The rate is counted over the whole loop instead of asserted per round, + /// because a per-round `assert!` aborts at the first hit and would report + /// "1 of 1" for a bug the point of this test is to *quantify*. + /// + /// Multi-threaded and on a real server for the reasons spelled out on + /// [`crate::domain::fee_plan_assignment`]'s pair of race tests: the + /// current-thread runtime never interleaves the two, and the embedded + /// engine does not conflict-check concurrent writes to one record at all. + #[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_an_enroll_never_answers_500() { + use crate::domain::enrollment::Enrollment; + let (db, _serialized) = crate::database::init_test_server("course_delete_race").await; + let (mut delete_500, mut enroll_500, mut enrolled) = (0, 0, 0); + let (mut last_delete, mut last_enroll) = (String::new(), String::new()); + for round in 0..20 { + let course = course_on(None, &db).await; + + // A *burst* of enrolls, and a delete held back by a sweeping beat. + // Released together the delete is one statement while an enroll + // spends two round trips reading before it claims, so it wins every + // round and the guard is never contended at all (measured: 0/20 + // seats placed). Six racers over a 0-3ms sweep put the single + // statement somewhere inside the counter writes instead. + let drop_it = { + let (course, db) = (course.clone(), db.clone()); + let beat = std::time::Duration::from_millis(round % 4); + tokio::spawn(async move { + tokio::time::sleep(beat).await; + course.delete(&db).await + }) + }; + let joins: Vec<_> = (0..6) + .map(|seat| { + let (id, db) = (course.get_id().clone(), db.clone()); + let student = UserId::from_key(&format!("stu{round}_{seat}")); + tokio::spawn(async move { + Enrollment::enroll(&id, &student, &UserId::from_key("mgr"), &db).await + }) + }) + .collect(); + let drop_it = drop_it.await.unwrap(); + if matches!(drop_it, Err(AppError::Db(_))) { + delete_500 += 1; + last_delete = format!("{drop_it:?}"); + } + for join in joins { + let join = join.await.unwrap(); + if matches!(join, Err(AppError::Db(_))) { + enroll_500 += 1; + last_enroll = format!("{join:?}"); + } + } + // Stored state, not the return values: a seat that landed is what + // the guard had to see. + if !Enrollment::list_for_course(course.get_id(), None, 0, &db) + .await + .unwrap() + .0 + .is_empty() + { + enrolled += 1; + } + } + eprintln!( + "Course::delete raced: {delete_500}/20 delete 500s, {enroll_500} enroll 500s, \ + {enrolled}/20 rounds with a seat placed" + ); + assert!( + enrolled > 0, + "no round ever placed an enrollment, so the delete guard was never contended" + ); + assert_eq!( + delete_500, 0, + "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}" + ); + assert_eq!( + enroll_500, 0, + "a raced enroll must retry, not 500: {enroll_500}/20 rounds, last {last_enroll}" + ); + } } diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 1e4cbe4..2f5af8a 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -4,7 +4,7 @@ use ulid::Ulid; use crate::constant::{ EXAM_TABLE, MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS, }; -use crate::database::Database; +use crate::database::{Database, transaction_with_retry}; use crate::domain::course::CourseId; use crate::domain::settings::ExamKindDef; use crate::domain::timestamp::Timestamp; @@ -598,9 +598,9 @@ impl Exam { /// each — which on a kind another exam still uses reads as one mark too /// few, and that is a kind wrongly free to leave the settings. pub async fn delete(self, db: &Database) -> Result { - let mut result = db - .query( - "BEGIN TRANSACTION; + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result WHERE exam = $ex GROUP BY kind) ?? []) { UPDATE type::record('kind_ref', $row.kind) SET count = @@ -621,10 +621,17 @@ impl Exam { LET $before = (DELETE $ex RETURN BEFORE); RETURN $before; COMMIT TRANSACTION;", - ) - .bind(("ex", self.id.record())) - .await? - .check()?; + &[("ex".into(), self.id.record().into_value())], + // No THROW of its own: an unconditional cascade, so the only error + // worth telling apart is a lost round, and `check()` — which took + // the *first* error in the batch — could not. It reported a + // sibling's "not executed" and made a retryable round a 500. + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } // The deleted row comes back through the transaction's trailing // `RETURN`, never a hand-counted slot: the old `take(8)` turned a // successful delete into a 404 the moment a cascade statement was @@ -870,4 +877,118 @@ mod tests { assert!(ExamSchedule::try_new(mode("sync"), at(2), at(2), None).is_err()); assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err()); } + + /// GUARD, not a retry measurement — read the last paragraph before + /// trusting this test with the retry. See + /// [`crate::domain::course::Course::delete`]'s race test for why the rate is + /// counted rather than asserted per round. + /// + /// This site has no `THROW` marker at all: it ends `.check()?`, which + /// returns the *first* error in the batch, and an aborted transaction + /// errors every slot — most of them with a generic "not executed". So a + /// genuine conflict can be masked by a sibling, and either way there is no + /// [`crate::database::lost_the_race`] check and no retry. + /// + /// 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. + /// + /// It does not prove the retry either: measured at 0 conflicts in 100 raced + /// rounds, and green with + /// [`crate::database::transaction_with_retry`]'s loop cut to a single + /// attempt — the grades serialize behind `cap`'s claim lock, so they mostly + /// queue rather than collide. So this guards the status codes and the + /// cascade (marks either survive whole or are swept whole, never a 500). + /// The retry is measured on [`crate::domain::course::Course::delete`]. + #[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_mark_never_answers_500() { + 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 last_delete, mut last_grade) = (String::new(), String::new()); + for round in 0..20 { + let exam = published(&db).await; + let kind = exam.get_kind().as_str().to_string(); + + // A burst of marks and a delete held back by a sweeping beat: this + // site has no guard to lose to, so a single racer released with it + // simply finishes on one side of it. Same recipe as + // [`crate::domain::course::Course::delete`]'s race test. + let drop_it = { + let (exam, db) = (exam.clone(), db.clone()); + // A wide sweep, not the 0-3ms the other three use: each grade + // takes two counter writes serialized behind `cap`'s claim + // lock, so the burst runs tens of milliseconds and a short beat + // always puts the delete in front of all six. + let beat = std::time::Duration::from_millis(round * 2); + tokio::spawn(async move { + tokio::time::sleep(beat).await; + exam.delete(&db).await + }) + }; + let marks: Vec<_> = (0..6) + .map(|seat| { + let (id, db, kind) = (exam.get_id().clone(), db.clone(), kind.clone()); + let student = UserId::from_key(&format!("stu{round}_{seat}")); + tokio::spawn(async move { + ExamResult::grade( + &id, + &student, + 1, + Mark::try_new(50).unwrap(), + &UserId::from_key("teacher"), + &kind, + &db, + ) + .await + }) + }) + .collect(); + let drop_it = drop_it.await.unwrap(); + if matches!(drop_it, Err(AppError::Db(_))) { + delete_500 += 1; + last_delete = format!("{drop_it:?}"); + } + for mark in marks { + let mark = mark.await.unwrap(); + if matches!(mark, 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. + 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" + ); + assert!( + marked > 0 && swept > 0, + "the delete never landed inside the burst ({marked} left / {swept} swept)" + ); + assert_eq!( + delete_500, 0, + "a raced delete must not 500: {delete_500}/20 rounds, last {last_delete}" + ); + assert_eq!( + grade_500, 0, + "a raced grade must retry, not 500: {grade_500}/20 rounds, last {last_grade}" + ); + } } diff --git a/src/domain/fee_plan_assignment.rs b/src/domain/fee_plan_assignment.rs index 1e701c4..adb0d8d 100644 --- a/src/domain/fee_plan_assignment.rs +++ b/src/domain/fee_plan_assignment.rs @@ -319,7 +319,7 @@ 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 an_edit_racing_an_assign_leaves_the_plan_and_the_money_agreeing() { - let db = crate::database::init_test_server("edit_race").await; + let (db, _serialized) = crate::database::init_test_server("edit_race").await; let mut reached = 0; for round in 0..20 { let manager = UserId::from_key("mgr1"); @@ -424,7 +424,7 @@ 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_an_assign_never_orphans_an_assignment() { - let db = crate::database::init_test_server("delete_race").await; + let (db, _serialized) = crate::database::init_test_server("delete_race").await; let (mut deleted_first, mut assigned_first) = (0, 0); for round in 0..20 { let hold_back_the_assign = round % 2 == 0; diff --git a/src/domain/subject.rs b/src/domain/subject.rs index 609119f..fb35d5b 100644 --- a/src/domain/subject.rs +++ b/src/domain/subject.rs @@ -1,7 +1,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN, SUBJECT_TABLE}; -use crate::database::Database; +use crate::database::{Database, transaction_with_retry}; use crate::domain::course::CourseId; use crate::domain::field_update::FieldUpdate; use crate::domain::monotonic_id::next_ulid; @@ -185,9 +185,9 @@ impl Subject { /// existence. Its cascade runs *after* the conditional delete, so a refused /// delete leaves every template's subject where it was. pub async fn delete(self, db: &Database) -> Result { - let mut result = db - .query( - "BEGIN TRANSACTION; + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; LET $held = (SELECT exam_question_count AS q, homework_count AS h FROM $sub); LET $before = (DELETE $sub WHERE (exam_question_count ?? 0) = 0 AND (homework_count ?? 0) = 0 @@ -200,12 +200,13 @@ impl Subject { UPDATE bank_question SET subject = NONE WHERE subject = $sub; RETURN $before; COMMIT TRANSACTION;", - ) - .bind(("sub", self.id.record())) - .await?; + &[("sub".into(), self.id.record().into_value())], + &["subject_missing", "subject_questions", "subject_homework"], + ) + .await?; // An aborted transaction errors every slot; only the THROW's own slot - // names the marker (the [`crate::domain::appointment_slot`] treatment). - let mut errors = result.take_errors(); + // names the marker (the [`crate::domain::appointment_slot`] treatment), + // and a lost round is re-sent rather than reported. let thrown = |marker: &str| { errors .values() @@ -267,4 +268,148 @@ mod tests { assert!(SubjectDescription::try_new("").is_ok()); assert!(SubjectDescription::try_new(&"x".repeat(2_001)).is_err()); } + + /// GUARD, not a retry measurement — read the last paragraph before + /// trusting this test with the retry. See + /// [`crate::domain::course::Course::delete`]'s race test for why the rate + /// is counted rather than asserted per round, and why this needs the real + /// server and a multi-threaded runtime. + /// + /// The racer is [`ExamQuestion::create`], which claims the subject's + /// question reference *before* it writes the row — a conditional write on + /// the same record the delete's `WHERE` reads. `Err(Conflict)` (still + /// referenced), `Err(NotFound)` and the claim's `Validation` miss are all + /// correct answers; only `AppError::Db` is the defect. What the two stored + /// counters below assert is that the sweep genuinely straddled the site: + /// some rounds the claims won, some rounds the delete did. + /// + /// What it does *not* prove is the retry. The 500 window here is the delete + /// passing its `WHERE` and then committing while a claim is in flight, and + /// this cascade is three statements long — measured at 0 conflicts in 100 + /// raced rounds, and the whole test stays green with + /// [`crate::database::transaction_with_retry`]'s loop cut to a single + /// attempt. Widening the sweep, staggering the burst and doubling it to 12 + /// racers all failed to open the window (they only move which side wins). + /// So this is a status-code-and-cascade guard: a raced delete answers 409 or + /// 404 and never 500, and a landed question survives it. The retry itself is + /// measured on [`crate::domain::course::Course::delete`], whose cascade is + /// long enough to lose a round (1-2 of 20, red under the same mutation). + #[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, + }; + let (db, _serialized) = crate::database::init_test_server("subject_delete_race").await; + let (mut delete_500, mut question_500) = (0, 0); + let (mut landed, mut wiped) = (0, 0); + let (mut last_delete, mut last_question) = (String::new(), String::new()); + for round in 0..20 { + let course = CourseId::generate(); + let exam = ExamId::generate(); + let subject = Subject::create( + &course, + SubjectName::try_new("Limits").unwrap(), + SubjectDescription::try_new("").unwrap(), + &db, + ) + .await + .unwrap(); + + let separated = round % 4 == 0; + let drop_it = { + let (subject, db) = (subject.clone(), db.clone()); + // One round in four holds the racers back by a clear 2ms so the + // delete wins outright: the sub-millisecond sweep alone leaves + // them ahead of it nearly every round (measured 20 to 0), and + // both counters below have to see a side. The other three keep + // the sub-ms beat, which is the only spacing that overlaps at + // all — a whole millisecond either way separates them. + let beat = if separated { + std::time::Duration::ZERO + } else { + std::time::Duration::from_micros(round * 53 % 300) + }; + tokio::spawn(async move { + tokio::time::sleep(beat).await; + subject.delete(&db).await + }) + }; + let asks: Vec<_> = (0..6) + .map(|_| { + let (id, db, exam) = (subject.get_id().clone(), db.clone(), exam.clone()); + let head_start = if separated { + std::time::Duration::from_millis(2) + } else { + std::time::Duration::from_micros(round * 37 % 300) + }; + tokio::spawn(async move { + tokio::time::sleep(head_start).await; + ExamQuestion::create( + &exam, + id, + QuestionText::try_new("why").unwrap(), + QuestionPoints::try_new(1).unwrap(), + QuestionSpec::try_new( + QuestionKind::try_new("text").unwrap(), + None, + None, + &[], + ) + .unwrap(), + &db, + ) + .await + }) + }) + .collect(); + let drop_it = drop_it.await.unwrap(); + if matches!(drop_it, Err(AppError::Db(_))) { + delete_500 += 1; + last_delete = format!("{drop_it:?}"); + } + for ask in asks { + let ask = ask.await.unwrap(); + if matches!(ask, Err(AppError::Db(_))) { + question_500 += 1; + last_question = format!("{ask:?}"); + } + } + // Stored state, and both sides are needed: a question landing means + // the claim beat the guard, the subject being gone means the delete + // did. Seeing only one is a run that never swept across the window. + if Subject::read(subject.get_id(), &db) + .await + .unwrap() + .is_none() + { + wiped += 1; + } + if !ExamQuestion::list_for_exam(&exam, None, 0, &db) + .await + .unwrap() + .0 + .is_empty() + { + landed += 1; + } + } + eprintln!( + "Subject::delete raced: {delete_500}/20 delete 500s, {question_500} question 500s, \ + {landed} rounds with a question landed / {wiped} wiped" + ); + assert!( + landed > 0 && wiped > 0, + "the sweep never crossed the window ({landed} landed / {wiped} wiped)" + ); + assert_eq!( + delete_500, 0, + "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}" + ); + assert_eq!( + question_500, 0, + "a raced question create must retry, not 500: {question_500}/20 rounds, last {last_question}" + ); + } } diff --git a/src/domain/term.rs b/src/domain/term.rs index 6c11bfa..5308ff5 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -10,7 +10,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; use crate::constant::{COURSE_COUNT_FIELD, MAX_TERM_NAME_LEN, TERM_TABLE}; -use crate::database::Database; +use crate::database::{Database, write_with_retry}; use crate::domain::field_update::FieldUpdate; use crate::domain::page::PagedList; use crate::domain::timestamp::{Timestamp, range_error}; @@ -144,14 +144,13 @@ impl Term { /// refused itself, with the same 400 the lookup gives). `Err(NotFound)` /// keeps the answer a concurrent *delete* used to get. pub async fn delete(self, db: &Database) -> Result { - let mut result = db - .query(format!( - "DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE" - )) - .bind(("term", self.id.record())) - .await? - .check()?; - if !result.take::>(0)?.is_empty() { + let sql = format!("DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE"); + // Through the retry, because the guard reads the very column a course + // create claims: a lost round writes nothing, and re-sending it is what + // keeps the answer the 404 or 409 it owes instead of a 500. + let gone: Vec = + write_with_retry(db, &sql, &[("term".into(), self.id.record().into_value())]).await?; + if !gone.is_empty() { return Ok(true); } // Still linked or already gone: the one statement cannot tell those @@ -204,4 +203,132 @@ mod tests { assert!(TermName::try_new(" ").is_err()); assert!(TermName::try_new(&"x".repeat(101)).is_err()); } + + /// GUARD, not a retry measurement — read the last paragraph before + /// trusting this test with the retry. See + /// [`crate::domain::course::Course::delete`]'s race test for why the rate is + /// counted rather than asserted per round. + /// + /// One conditional `DELETE … RETURN BEFORE` and a bare `.check()?`: no + /// transaction to abort, but also no [`crate::database::write_with_retry`], + /// which every other guarded single-statement write in the crate goes + /// through. A store answering "conflict, retry" therefore comes out as a + /// 500 instead of the 404 or 409 the request owes. + /// + /// The racer is [`crate::domain::course::Course::create`] against this + /// term: it claims `course_count` on the term row before it writes the + /// link, which is the same record and the same column the guard reads. Both + /// sides are swept across each other sub-millisecond, exactly as in + /// [`crate::domain::subject::Subject::delete`]'s race test — a whole + /// millisecond of head start on either side separates them completely, and + /// the counters below assert the sweep straddled the site rather than + /// landing on one side of it (it used to alternate on `round % 2` and score + /// an exact 10/10, i.e. no overlap at all). + /// + /// And like that test it does *not* prove the retry: this site is one + /// statement, so the window in which a conflict could reach + /// [`write_with_retry`] is a single round trip wide — measured at 0 + /// conflicts in 100 raced rounds, green with the retry loop cut to a single + /// attempt. A status-code guard, then: a raced delete answers 409 or 404 and + /// never 500, and a course that got linked survives it. The retry is + /// measured on [`crate::domain::course::Course::delete`]. + #[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_course_create_never_answers_500() { + use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; + use crate::domain::user::UserId; + let (db, _serialized) = crate::database::init_test_server("term_delete_race").await; + let (mut delete_500, mut create_500) = (0, 0); + let (mut linked, mut wiped) = (0, 0); + let (mut last_delete, mut last_create) = (String::new(), String::new()); + let at = Timestamp::from_millis; + for round in 0..20 { + let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db) + .await + .unwrap(); + + let separated = round % 4 == 0; + let drop_it = { + let (term, db) = (term.clone(), db.clone()); + // One round in four holds the racers back by a clear 2ms so the + // delete wins outright: the sub-millisecond sweep alone leaves + // them ahead of it nearly every round (measured 20 to 0), and + // both counters below have to see a side. The other three keep + // the sub-ms beat, which is the only spacing that overlaps at + // all — a whole millisecond either way separates them. + let beat = if separated { + std::time::Duration::ZERO + } else { + std::time::Duration::from_micros(round * 53 % 300) + }; + tokio::spawn(async move { + tokio::time::sleep(beat).await; + term.delete(&db).await + }) + }; + let makes: Vec<_> = (0..6) + .map(|_| { + let (id, db) = (term.get_id().clone(), db.clone()); + let head_start = if separated { + std::time::Duration::from_millis(2) + } else { + std::time::Duration::from_micros(round * 37 % 300) + }; + tokio::spawn(async move { + tokio::time::sleep(head_start).await; + Course::create( + &UserId::from_key("teacher"), + CourseTitle::try_new("algebra").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + Some(id), + None, + &db, + ) + .await + }) + }) + .collect(); + let drop_it = drop_it.await.unwrap(); + if matches!(drop_it, Err(AppError::Db(_))) { + delete_500 += 1; + last_delete = format!("{drop_it:?}"); + } + // Stored state, both sides: a linked course means the claim beat the + // guard, a gone term means the delete did. + let mut landed = false; + for make in makes { + let make = make.await.unwrap(); + if matches!(make, Err(AppError::Db(_))) { + create_500 += 1; + last_create = format!("{make:?}"); + } + if let Ok(course) = &make + && Course::read(course.get_id(), &db).await.unwrap().is_some() + { + landed = true; + } + } + linked += usize::from(landed); + if Term::read(term.get_id(), &db).await.unwrap().is_none() { + wiped += 1; + } + } + eprintln!( + "Term::delete raced: {delete_500}/20 delete 500s, {create_500} create 500s, \ + {linked} rounds with a course linked / {wiped} wiped" + ); + assert!( + linked > 0 && wiped > 0, + "the sweep never crossed the window ({linked} linked / {wiped} wiped)" + ); + assert_eq!( + delete_500, 0, + "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}" + ); + assert_eq!( + create_500, 0, + "a raced course create must retry, not 500: {create_500}/20 rounds, last {last_create}" + ); + } }