forge
Explore
Log in

Don't you dare go Hollow

🔁 retry a guarded cascade that loses a write race

Browse files at this commit

616a66b490a1a4546ccd07158fbd9fd19a95989dAhmet Kaan GümüşParent: ac70cc0
  • fix
    • 🔁 retry a guarded cascade that loses a write race
Show full message
fix: 🔁 retry a guarded cascade that loses a write race

A BEGIN/COMMIT delete that lost a write conflict answered 500 instead of
the refusal or retry it owed. An aborted transaction errors *every* slot,
and all but the failing one say a generic "not executed" — the consequence
of the abort, never a reason of its own. Picking one of those out of the
unordered HashMap from take_errors, or taking the first via check(),
retired a retryable round as a database error. Measured on Course::delete
at 1-3 of 20 raced rounds against a real server.

transaction_with_retry is write_with_retry's story for the cascades that
cannot be one statement: it matches the caller's THROW markers first, since
a THROW is a decision and outranks a conflict, then re-sends while any slot
reports a lost round. It hands back both the response and the drained
errors because take_errors consumes and the caller needs the slots as well
as the map.

Course, Subject and Exam route through it; Exam also loses the check() that
was masking the conflict behind a sibling slot. Term needed none of it — it
is a single statement, so the existing write_with_retry was the whole fix.

Four ignored race tests come with it. Only the course one discriminates,
proven by cutting the retry loop to a single attempt and watching it go
red; the other three guard their handlers' status codes and say so on
themselves rather than implying a measurement they do not make. They share
a lock so the documented invocation works.
src/database.rsmodified+86 -2
@@ -136,6 +136,75 @@ pub(crate) async fn write_with_retry<T: surrealdb::types::SurrealValue>(
136 .unwrap_or_else(|| AppError::Internal("a guarded write never ran".into())))136 .unwrap_or_else(|| AppError::Internal("a guarded write never ran".into())))
137 }137 }
138 138
139+/// Send one guarded `BEGIN…COMMIT` cascade, re-sending it while the store
140+/// answers "conflict, retry", and hand back both the response and the errors
141+/// drained off it.
142+///
143+/// [`write_with_retry`]'s story, for the cascades that cannot be one statement:
144+/// the guard reads a column a rival writes, so the two contend on one record by
145+/// design, and a lost round aborts the transaction having written *nothing* —
146+/// which is what makes re-sending the whole of the recovery.
147+///
148+/// Both halves come back because the caller needs both and `take_errors`
149+/// consumes: the response carries the result slots, and only the error map can
150+/// tell a deliberate `THROW` from a lost round. `refusals` are the caller's
151+/// `THROW` markers and they are matched *first* — a `THROW` is a decision, and
152+/// it outranks a conflict. Everything after that ordering is why this exists:
153+/// an aborted transaction errors *every* slot, and all but the failing one say
154+/// a generic "not executed", which is the consequence of the abort and never a
155+/// reason of its own. Picking one of those out of the unordered `HashMap` — or
156+/// taking the first via `check()` — retired a retryable round as a 500, measured
157+/// on `Course::delete` at 1-3 of 20 raced rounds.
158+///
159+/// [`write_with_retry`]'s restriction carries over, and a cascade makes it
160+/// easier to trip: no statement inside may be able to answer "already exists",
161+/// because that is the other thing [`lost_the_race`] matches and re-sending it
162+/// would just fail the same way until the tries run out — turning a 409 into a
163+/// 500, which is the exact defect this exists to prevent. So `UPDATE` and
164+/// `DELETE`, and no `CREATE` and no write under a `UNIQUE` index anywhere in
165+/// the batch. The four cascades on it today are clear on both counts.
166+pub(crate) async fn transaction_with_retry(
167+ db: &Database,
168+ sql: &str,
169+ bindings: &[(String, surrealdb::types::Value)],
170+ refusals: &[&str],
171+) -> Result<
172+ (
173+ surrealdb::IndexedResults,
174+ std::collections::HashMap<usize, surrealdb::Error>,
175+ ),
176+ AppError,
177+> {
178+ let mut last = None;
179+ for attempt in 0..CAP_WRITE_TRIES {
180+ backoff(attempt).await;
181+ let mut query = db.query(sql);
182+ for (name, value) in bindings {
183+ query = query.bind((name.clone(), value.clone()));
184+ }
185+ let mut result = match query.await {
186+ Ok(result) => result,
187+ Err(err) if lost_the_race(&err) => {
188+ last = Some(err);
189+ continue;
190+ }
191+ Err(err) => return Err(err.into()),
192+ };
193+ let mut errors = result.take_errors();
194+ let refused = |error: &surrealdb::Error| {
195+ let message = error.to_string();
196+ refusals.iter().any(|marker| message.contains(marker))
197+ };
198+ if errors.values().any(refused) || !errors.values().any(lost_the_race) {
199+ return Ok((result, errors));
200+ }
201+ last = errors.drain().map(|(_, error)| error).find(lost_the_race);
202+ }
203+ Err(last
204+ .map(AppError::from)
205+ .unwrap_or_else(|| AppError::Internal("a guarded cascade never ran".into())))
206+}
207+
139 /// Wait out one lost round. Exponential with jitter, because racers arrive in208 /// Wait out one lost round. Exponential with jitter, because racers arrive in
140 /// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them.209 /// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them.
141 /// Attempt zero waits not at all.210 /// Attempt zero waits not at all.
@@ -194,8 +263,23 @@ pub async fn init_mem() -> Result<Database, AppError> {
194 /// Every caller is `#[ignore]`d, so a machine with no server prints them as263 /// Every caller is `#[ignore]`d, so a machine with no server prints them as
195 /// `ignored` rather than passing: this is not a test that may quietly skip.264 /// `ignored` rather than passing: this is not a test that may quietly skip.
196 /// `HEZARFEN_TEST_DB` overrides the address; the credentials are `compose.yaml`'s.265 /// `HEZARFEN_TEST_DB` overrides the address; the credentials are `compose.yaml`'s.
266+///
267+/// The guard handed back with the handle serializes these tests against each
268+/// other and must be held for the whole test — hence the tuple, which cannot be
269+/// forgotten the way a separate `lock()` line can. `cargo test -- --ignored`
270+/// runs them in parallel, and while each has a namespace to itself they all
271+/// burst against the *one* server: their beats are sub-millisecond, so a
272+/// sibling's burst pushes a delete clean out of the window it is meant to land
273+/// in (measured 4 runs in 4 at 3 of 6 failing their own "the race was reached"
274+/// guard). Serialized, the plain documented command works.
275+#[cfg(test)]
276+pub(crate) static RACE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
277+
197 #[cfg(test)]278 #[cfg(test)]
198-pub(crate) async fn init_test_server(scratch: &str) -> Database {279+pub(crate) async fn init_test_server(
280+ scratch: &str,
281+) -> (Database, tokio::sync::MutexGuard<'static, ()>) {
282+ let serialized = RACE_LOCK.lock().await;
199 let url =283 let url =
200 std::env::var("HEZARFEN_TEST_DB").unwrap_or_else(|_| "ws://127.0.0.1:8000".to_string());284 std::env::var("HEZARFEN_TEST_DB").unwrap_or_else(|_| "ws://127.0.0.1:8000".to_string());
201 let db = surrealdb::engine::any::connect(url.clone())285 let db = surrealdb::engine::any::connect(url.clone())
@@ -216,7 +300,7 @@ pub(crate) async fn init_test_server(scratch: &str) -> Database {
216 db.use_ns(ns.clone()).use_db(ns).await.expect("scratch ns");300 db.use_ns(ns.clone()).use_db(ns).await.expect("scratch ns");
217 let db = std::sync::Arc::new(db);301 let db = std::sync::Arc::new(db);
218 migrate(&db).await.expect("migrate the scratch namespace");302 migrate(&db).await.expect("migrate the scratch namespace");
219- db303+ (db, serialized)
220 }304 }
221 305
222 /// Apply the schema + backfills. Idempotent — `init` runs it on every boot,306 /// Apply the schema + backfills. Idempotent — `init` runs it on every boot,
src/domain/course.rsmodified+111 -8
@@ -5,7 +5,7 @@ use crate::constant::{
5 COURSE_COUNT_FIELD, COURSE_TABLE, ENROLLMENT_COUNT_FIELD, MAX_COURSE_DESCRIPTION_LEN,5 COURSE_COUNT_FIELD, COURSE_TABLE, ENROLLMENT_COUNT_FIELD, MAX_COURSE_DESCRIPTION_LEN,
6 MAX_COURSE_TITLE_LEN, REF_COUNT_FIELD,6 MAX_COURSE_TITLE_LEN, REF_COUNT_FIELD,
7 };7 };
8-use crate::database::Database;8+use crate::database::{Database, transaction_with_retry};
9 use crate::domain::cap;9 use crate::domain::cap;
10 use crate::domain::field_update::FieldUpdate;10 use crate::domain::field_update::FieldUpdate;
11 use crate::domain::page::PagedList;11 use crate::domain::page::PagedList;
@@ -404,8 +404,7 @@ impl Course {
404 /// the row gone (and is refused itself). `Err(NotFound)`404 /// the row gone (and is refused itself). `Err(NotFound)`
405 /// keeps the answer a concurrent *delete* used to get.405 /// keeps the answer a concurrent *delete* used to get.
406 pub async fn delete(self, db: &Database) -> Result<bool, AppError> {406 pub async fn delete(self, db: &Database) -> Result<bool, AppError> {
407- let mut result = db407+ let sql = format!(
408- .query(format!(
409 "BEGIN TRANSACTION;408 "BEGIN TRANSACTION;
410 LET $gone = (DELETE $course WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE);409 LET $gone = (DELETE $course WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE);
411 IF array::len($gone) = 0 {{ THROW '{ROSTER_MARK}' }};410 IF array::len($gone) = 0 {{ THROW '{ROSTER_MARK}' }};
@@ -437,12 +436,17 @@ impl Course {
437 DELETE homework WHERE course = $course;436 DELETE homework WHERE course = $course;
438 DELETE exam WHERE course = $course;437 DELETE exam WHERE course = $course;
439 COMMIT TRANSACTION;"438 COMMIT TRANSACTION;"
440- ))439+ );
441- .bind(("course", self.id.record()))
442- .await?;
443 // An aborted transaction errors *every* slot, most with a generic "not440 // An aborted transaction errors *every* slot, most with a generic "not
444- // executed" — only the THROW's own slot names the marker.441+ // executed" — only the THROW's own slot names the marker, and a lost
445- let mut errors = result.take_errors();442+ // round is re-sent rather than reported (see [`transaction_with_retry`]).
443+ let (_, mut errors) = transaction_with_retry(
444+ db,
445+ &sql,
446+ &[("course".into(), self.id.record().into_value())],
447+ &[ROSTER_MARK],
448+ )
449+ .await?;
446 if errors450 if errors
447 .values()451 .values()
448 .any(|error| error.to_string().contains(ROSTER_MARK))452 .any(|error| error.to_string().contains(ROSTER_MARK))
@@ -677,4 +681,103 @@ mod tests {
677 assert!(decoded.get_teachers().is_empty());681 assert!(decoded.get_teachers().is_empty());
678 assert!(!decoded.is_assigned(&assigned));682 assert!(!decoded.is_assigned(&assigned));
679 }683 }
684+
685+ /// MEASUREMENT — the one race test that actually measures the retry, and
686+ /// the only one of the four that does. The other three (subject, term,
687+ /// exam) are status-code guards; each says so on itself.
688+ ///
689+ /// `Course::delete` is one `BEGIN…COMMIT` whose guard reads
690+ /// `enrollment_count` off the very record a concurrent enroll increments,
691+ /// so the two contend by design, and its cascade is long enough that a
692+ /// rival's write lands mid-transaction. Losing that round writes nothing,
693+ /// which is what makes re-sending it the recovery. Without
694+ /// [`crate::database::transaction_with_retry`] a lost round comes out as a
695+ /// 500: mutation-tested by cutting that retry loop to one attempt, which
696+ /// turns this test red at 1-2 of 20 rounds (3 runs in 5 — the window is
697+ /// real but narrow, so a single green run under the mutation means nothing).
698+ ///
699+ /// A refusal (`Ok(false)`) or an `Err(NotFound)` is *correct* here and
700+ /// must not fail this test: the only defect is `AppError::Db`.
701+ ///
702+ /// The rate is counted over the whole loop instead of asserted per round,
703+ /// because a per-round `assert!` aborts at the first hit and would report
704+ /// "1 of 1" for a bug the point of this test is to *quantify*.
705+ ///
706+ /// Multi-threaded and on a real server for the reasons spelled out on
707+ /// [`crate::domain::fee_plan_assignment`]'s pair of race tests: the
708+ /// current-thread runtime never interleaves the two, and the embedded
709+ /// engine does not conflict-check concurrent writes to one record at all.
710+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
711+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
712+ async fn a_delete_racing_an_enroll_never_answers_500() {
713+ use crate::domain::enrollment::Enrollment;
714+ let (db, _serialized) = crate::database::init_test_server("course_delete_race").await;
715+ let (mut delete_500, mut enroll_500, mut enrolled) = (0, 0, 0);
716+ let (mut last_delete, mut last_enroll) = (String::new(), String::new());
717+ for round in 0..20 {
718+ let course = course_on(None, &db).await;
719+
720+ // A *burst* of enrolls, and a delete held back by a sweeping beat.
721+ // Released together the delete is one statement while an enroll
722+ // spends two round trips reading before it claims, so it wins every
723+ // round and the guard is never contended at all (measured: 0/20
724+ // seats placed). Six racers over a 0-3ms sweep put the single
725+ // statement somewhere inside the counter writes instead.
726+ let drop_it = {
727+ let (course, db) = (course.clone(), db.clone());
728+ let beat = std::time::Duration::from_millis(round % 4);
729+ tokio::spawn(async move {
730+ tokio::time::sleep(beat).await;
731+ course.delete(&db).await
732+ })
733+ };
734+ let joins: Vec<_> = (0..6)
735+ .map(|seat| {
736+ let (id, db) = (course.get_id().clone(), db.clone());
737+ let student = UserId::from_key(&format!("stu{round}_{seat}"));
738+ tokio::spawn(async move {
739+ Enrollment::enroll(&id, &student, &UserId::from_key("mgr"), &db).await
740+ })
741+ })
742+ .collect();
743+ let drop_it = drop_it.await.unwrap();
744+ if matches!(drop_it, Err(AppError::Db(_))) {
745+ delete_500 += 1;
746+ last_delete = format!("{drop_it:?}");
747+ }
748+ for join in joins {
749+ let join = join.await.unwrap();
750+ if matches!(join, Err(AppError::Db(_))) {
751+ enroll_500 += 1;
752+ last_enroll = format!("{join:?}");
753+ }
754+ }
755+ // Stored state, not the return values: a seat that landed is what
756+ // the guard had to see.
757+ if !Enrollment::list_for_course(course.get_id(), None, 0, &db)
758+ .await
759+ .unwrap()
760+ .0
761+ .is_empty()
762+ {
763+ enrolled += 1;
764+ }
765+ }
766+ eprintln!(
767+ "Course::delete raced: {delete_500}/20 delete 500s, {enroll_500} enroll 500s, \
768+ {enrolled}/20 rounds with a seat placed"
769+ );
770+ assert!(
771+ enrolled > 0,
772+ "no round ever placed an enrollment, so the delete guard was never contended"
773+ );
774+ assert_eq!(
775+ delete_500, 0,
776+ "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}"
777+ );
778+ assert_eq!(
779+ enroll_500, 0,
780+ "a raced enroll must retry, not 500: {enroll_500}/20 rounds, last {last_enroll}"
781+ );
782+ }
680 }783 }
src/domain/exam.rsmodified+129 -8
@@ -4,7 +4,7 @@ use ulid::Ulid;
4 use crate::constant::{4 use crate::constant::{
5 EXAM_TABLE, MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS,5 EXAM_TABLE, MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS,
6 };6 };
7-use crate::database::Database;7+use crate::database::{Database, transaction_with_retry};
8 use crate::domain::course::CourseId;8 use crate::domain::course::CourseId;
9 use crate::domain::settings::ExamKindDef;9 use crate::domain::settings::ExamKindDef;
10 use crate::domain::timestamp::Timestamp;10 use crate::domain::timestamp::Timestamp;
@@ -598,9 +598,9 @@ impl Exam {
598 /// each — which on a kind another exam still uses reads as one mark too598 /// each — which on a kind another exam still uses reads as one mark too
599 /// few, and that is a kind wrongly free to leave the settings.599 /// few, and that is a kind wrongly free to leave the settings.
600 pub async fn delete(self, db: &Database) -> Result<Exam, AppError> {600 pub async fn delete(self, db: &Database) -> Result<Exam, AppError> {
601- let mut result = db601+ let (mut result, mut errors) = transaction_with_retry(
602- .query(602+ db,
603- "BEGIN TRANSACTION;603+ "BEGIN TRANSACTION;
604 FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result604 FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result
605 WHERE exam = $ex GROUP BY kind) ?? []) {605 WHERE exam = $ex GROUP BY kind) ?? []) {
606 UPDATE type::record('kind_ref', $row.kind) SET count =606 UPDATE type::record('kind_ref', $row.kind) SET count =
@@ -621,10 +621,17 @@ impl Exam {
621 LET $before = (DELETE $ex RETURN BEFORE);621 LET $before = (DELETE $ex RETURN BEFORE);
622 RETURN $before;622 RETURN $before;
623 COMMIT TRANSACTION;",623 COMMIT TRANSACTION;",
624- )624+ &[("ex".into(), self.id.record().into_value())],
625- .bind(("ex", self.id.record()))625+ // No THROW of its own: an unconditional cascade, so the only error
626- .await?626+ // worth telling apart is a lost round, and `check()` — which took
627- .check()?;627+ // the *first* error in the batch — could not. It reported a
628+ // sibling's "not executed" and made a retryable round a 500.
629+ &[],
630+ )
631+ .await?;
632+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
633+ return Err(error.into());
634+ }
628 // The deleted row comes back through the transaction's trailing635 // The deleted row comes back through the transaction's trailing
629 // `RETURN`, never a hand-counted slot: the old `take(8)` turned a636 // `RETURN`, never a hand-counted slot: the old `take(8)` turned a
630 // successful delete into a 404 the moment a cascade statement was637 // successful delete into a 404 the moment a cascade statement was
@@ -870,4 +877,118 @@ mod tests {
870 assert!(ExamSchedule::try_new(mode("sync"), at(2), at(2), None).is_err());877 assert!(ExamSchedule::try_new(mode("sync"), at(2), at(2), None).is_err());
871 assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err());878 assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err());
872 }879 }
880+
881+ /// GUARD, not a retry measurement — read the last paragraph before
882+ /// trusting this test with the retry. See
883+ /// [`crate::domain::course::Course::delete`]'s race test for why the rate is
884+ /// counted rather than asserted per round.
885+ ///
886+ /// This site has no `THROW` marker at all: it ends `.check()?`, which
887+ /// returns the *first* error in the batch, and an aborted transaction
888+ /// errors every slot — most of them with a generic "not executed". So a
889+ /// genuine conflict can be masked by a sibling, and either way there is no
890+ /// [`crate::database::lost_the_race`] check and no retry.
891+ ///
892+ /// The racer is a mark: [`ExamResult::grade`] claims the exam's own
893+ /// `result_count` (and the kind's reference) before writing, so it contends
894+ /// 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.
897+ ///
898+ /// It does not prove the retry either: measured at 0 conflicts in 100 raced
899+ /// rounds, and green with
900+ /// [`crate::database::transaction_with_retry`]'s loop cut to a single
901+ /// attempt — the grades serialize behind `cap`'s claim lock, so they mostly
902+ /// queue rather than collide. So this guards the status codes and the
903+ /// cascade (marks either survive whole or are swept whole, never a 500).
904+ /// The retry is measured on [`crate::domain::course::Course::delete`].
905+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
906+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
907+ async fn a_delete_racing_a_mark_never_answers_500() {
908+ use crate::domain::exam_result::{ExamResult, Mark};
909+ let (db, _serialized) = crate::database::init_test_server("exam_delete_race").await;
910+ let (mut delete_500, mut grade_500) = (0, 0);
911+ let (mut marked, mut swept) = (0, 0);
912+ let (mut last_delete, mut last_grade) = (String::new(), String::new());
913+ for round in 0..20 {
914+ let exam = published(&db).await;
915+ let kind = exam.get_kind().as_str().to_string();
916+
917+ // A burst of marks and a delete held back by a sweeping beat: this
918+ // site has no guard to lose to, so a single racer released with it
919+ // simply finishes on one side of it. Same recipe as
920+ // [`crate::domain::course::Course::delete`]'s race test.
921+ let drop_it = {
922+ let (exam, db) = (exam.clone(), db.clone());
923+ // A wide sweep, not the 0-3ms the other three use: each grade
924+ // takes two counter writes serialized behind `cap`'s claim
925+ // lock, so the burst runs tens of milliseconds and a short beat
926+ // always puts the delete in front of all six.
927+ let beat = std::time::Duration::from_millis(round * 2);
928+ tokio::spawn(async move {
929+ tokio::time::sleep(beat).await;
930+ exam.delete(&db).await
931+ })
932+ };
933+ let marks: Vec<_> = (0..6)
934+ .map(|seat| {
935+ let (id, db, kind) = (exam.get_id().clone(), db.clone(), kind.clone());
936+ let student = UserId::from_key(&format!("stu{round}_{seat}"));
937+ tokio::spawn(async move {
938+ ExamResult::grade(
939+ &id,
940+ &student,
941+ 1,
942+ Mark::try_new(50).unwrap(),
943+ &UserId::from_key("teacher"),
944+ &kind,
945+ &db,
946+ )
947+ .await
948+ })
949+ })
950+ .collect();
951+ let drop_it = drop_it.await.unwrap();
952+ if matches!(drop_it, Err(AppError::Db(_))) {
953+ delete_500 += 1;
954+ last_delete = format!("{drop_it:?}");
955+ }
956+ for mark in marks {
957+ let mark = mark.await.unwrap();
958+ if matches!(mark, Err(AppError::Db(_))) {
959+ grade_500 += 1;
960+ last_grade = format!("{mark:?}");
961+ }
962+ }
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.
967+ if ExamResult::list_for_exam(exam.get_id(), &db)
968+ .await
969+ .unwrap()
970+ .is_empty()
971+ {
972+ swept += 1;
973+ } else {
974+ marked += 1;
975+ }
976+ }
977+ eprintln!(
978+ "Exam::delete raced: {delete_500}/20 delete 500s, {grade_500} grade 500s, \
979+ {marked} rounds with marks left / {swept} swept"
980+ );
981+ assert!(
982+ marked > 0 && swept > 0,
983+ "the delete never landed inside the burst ({marked} left / {swept} swept)"
984+ );
985+ assert_eq!(
986+ delete_500, 0,
987+ "a raced delete must not 500: {delete_500}/20 rounds, last {last_delete}"
988+ );
989+ assert_eq!(
990+ grade_500, 0,
991+ "a raced grade must retry, not 500: {grade_500}/20 rounds, last {last_grade}"
992+ );
993+ }
873 }994 }
src/domain/fee_plan_assignment.rsmodified+2 -2
@@ -319,7 +319,7 @@ mod tests {
319 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]319 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
320 #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]320 #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
321 async fn an_edit_racing_an_assign_leaves_the_plan_and_the_money_agreeing() {321 async fn an_edit_racing_an_assign_leaves_the_plan_and_the_money_agreeing() {
322- let db = crate::database::init_test_server("edit_race").await;322+ let (db, _serialized) = crate::database::init_test_server("edit_race").await;
323 let mut reached = 0;323 let mut reached = 0;
324 for round in 0..20 {324 for round in 0..20 {
325 let manager = UserId::from_key("mgr1");325 let manager = UserId::from_key("mgr1");
@@ -424,7 +424,7 @@ mod tests {
424 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]424 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
425 #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]425 #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
426 async fn a_delete_racing_an_assign_never_orphans_an_assignment() {426 async fn a_delete_racing_an_assign_never_orphans_an_assignment() {
427- let db = crate::database::init_test_server("delete_race").await;427+ let (db, _serialized) = crate::database::init_test_server("delete_race").await;
428 let (mut deleted_first, mut assigned_first) = (0, 0);428 let (mut deleted_first, mut assigned_first) = (0, 0);
429 for round in 0..20 {429 for round in 0..20 {
430 let hold_back_the_assign = round % 2 == 0;430 let hold_back_the_assign = round % 2 == 0;
src/domain/subject.rsmodified+154 -9
@@ -1,7 +1,7 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3 use crate::constant::{MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN, SUBJECT_TABLE};3 use crate::constant::{MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN, SUBJECT_TABLE};
4-use crate::database::Database;4+use crate::database::{Database, transaction_with_retry};
5 use crate::domain::course::CourseId;5 use crate::domain::course::CourseId;
6 use crate::domain::field_update::FieldUpdate;6 use crate::domain::field_update::FieldUpdate;
7 use crate::domain::monotonic_id::next_ulid;7 use crate::domain::monotonic_id::next_ulid;
@@ -185,9 +185,9 @@ impl Subject {
185 /// existence. Its cascade runs *after* the conditional delete, so a refused185 /// existence. Its cascade runs *after* the conditional delete, so a refused
186 /// delete leaves every template's subject where it was.186 /// delete leaves every template's subject where it was.
187 pub async fn delete(self, db: &Database) -> Result<Subject, AppError> {187 pub async fn delete(self, db: &Database) -> Result<Subject, AppError> {
188- let mut result = db188+ let (mut result, mut errors) = transaction_with_retry(
189- .query(189+ db,
190- "BEGIN TRANSACTION;190+ "BEGIN TRANSACTION;
191 LET $held = (SELECT exam_question_count AS q, homework_count AS h FROM $sub);191 LET $held = (SELECT exam_question_count AS q, homework_count AS h FROM $sub);
192 LET $before = (DELETE $sub192 LET $before = (DELETE $sub
193 WHERE (exam_question_count ?? 0) = 0 AND (homework_count ?? 0) = 0193 WHERE (exam_question_count ?? 0) = 0 AND (homework_count ?? 0) = 0
@@ -200,12 +200,13 @@ impl Subject {
200 UPDATE bank_question SET subject = NONE WHERE subject = $sub;200 UPDATE bank_question SET subject = NONE WHERE subject = $sub;
201 RETURN $before;201 RETURN $before;
202 COMMIT TRANSACTION;",202 COMMIT TRANSACTION;",
203- )203+ &[("sub".into(), self.id.record().into_value())],
204- .bind(("sub", self.id.record()))204+ &["subject_missing", "subject_questions", "subject_homework"],
205- .await?;205+ )
206+ .await?;
206 // An aborted transaction errors every slot; only the THROW's own slot207 // An aborted transaction errors every slot; only the THROW's own slot
207- // names the marker (the [`crate::domain::appointment_slot`] treatment).208+ // names the marker (the [`crate::domain::appointment_slot`] treatment),
208- let mut errors = result.take_errors();209+ // and a lost round is re-sent rather than reported.
209 let thrown = |marker: &str| {210 let thrown = |marker: &str| {
210 errors211 errors
211 .values()212 .values()
@@ -267,4 +268,148 @@ mod tests {
267 assert!(SubjectDescription::try_new("").is_ok());268 assert!(SubjectDescription::try_new("").is_ok());
268 assert!(SubjectDescription::try_new(&"x".repeat(2_001)).is_err());269 assert!(SubjectDescription::try_new(&"x".repeat(2_001)).is_err());
269 }270 }
271+
272+ /// GUARD, not a retry measurement — read the last paragraph before
273+ /// trusting this test with the retry. See
274+ /// [`crate::domain::course::Course::delete`]'s race test for why the rate
275+ /// is counted rather than asserted per round, and why this needs the real
276+ /// server and a multi-threaded runtime.
277+ ///
278+ /// The racer is [`ExamQuestion::create`], which claims the subject's
279+ /// question reference *before* it writes the row — a conditional write on
280+ /// the same record the delete's `WHERE` reads. `Err(Conflict)` (still
281+ /// referenced), `Err(NotFound)` and the claim's `Validation` miss are all
282+ /// correct answers; only `AppError::Db` is the defect. What the two stored
283+ /// counters below assert is that the sweep genuinely straddled the site:
284+ /// some rounds the claims won, some rounds the delete did.
285+ ///
286+ /// What it does *not* prove is the retry. The 500 window here is the delete
287+ /// passing its `WHERE` and then committing while a claim is in flight, and
288+ /// this cascade is three statements long — measured at 0 conflicts in 100
289+ /// raced rounds, and the whole test stays green with
290+ /// [`crate::database::transaction_with_retry`]'s loop cut to a single
291+ /// attempt. Widening the sweep, staggering the burst and doubling it to 12
292+ /// racers all failed to open the window (they only move which side wins).
293+ /// So this is a status-code-and-cascade guard: a raced delete answers 409 or
294+ /// 404 and never 500, and a landed question survives it. The retry itself is
295+ /// measured on [`crate::domain::course::Course::delete`], whose cascade is
296+ /// long enough to lose a round (1-2 of 20, red under the same mutation).
297+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
298+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
299+ async fn a_delete_racing_a_question_never_answers_500() {
300+ use crate::domain::exam::ExamId;
301+ use crate::domain::exam_question::{
302+ ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
303+ };
304+ let (db, _serialized) = crate::database::init_test_server("subject_delete_race").await;
305+ let (mut delete_500, mut question_500) = (0, 0);
306+ let (mut landed, mut wiped) = (0, 0);
307+ let (mut last_delete, mut last_question) = (String::new(), String::new());
308+ for round in 0..20 {
309+ let course = CourseId::generate();
310+ let exam = ExamId::generate();
311+ let subject = Subject::create(
312+ &course,
313+ SubjectName::try_new("Limits").unwrap(),
314+ SubjectDescription::try_new("").unwrap(),
315+ &db,
316+ )
317+ .await
318+ .unwrap();
319+
320+ let separated = round % 4 == 0;
321+ let drop_it = {
322+ let (subject, db) = (subject.clone(), db.clone());
323+ // One round in four holds the racers back by a clear 2ms so the
324+ // delete wins outright: the sub-millisecond sweep alone leaves
325+ // them ahead of it nearly every round (measured 20 to 0), and
326+ // both counters below have to see a side. The other three keep
327+ // the sub-ms beat, which is the only spacing that overlaps at
328+ // all — a whole millisecond either way separates them.
329+ let beat = if separated {
330+ std::time::Duration::ZERO
331+ } else {
332+ std::time::Duration::from_micros(round * 53 % 300)
333+ };
334+ tokio::spawn(async move {
335+ tokio::time::sleep(beat).await;
336+ subject.delete(&db).await
337+ })
338+ };
339+ let asks: Vec<_> = (0..6)
340+ .map(|_| {
341+ let (id, db, exam) = (subject.get_id().clone(), db.clone(), exam.clone());
342+ let head_start = if separated {
343+ std::time::Duration::from_millis(2)
344+ } else {
345+ std::time::Duration::from_micros(round * 37 % 300)
346+ };
347+ tokio::spawn(async move {
348+ tokio::time::sleep(head_start).await;
349+ ExamQuestion::create(
350+ &exam,
351+ id,
352+ QuestionText::try_new("why").unwrap(),
353+ QuestionPoints::try_new(1).unwrap(),
354+ QuestionSpec::try_new(
355+ QuestionKind::try_new("text").unwrap(),
356+ None,
357+ None,
358+ &[],
359+ )
360+ .unwrap(),
361+ &db,
362+ )
363+ .await
364+ })
365+ })
366+ .collect();
367+ let drop_it = drop_it.await.unwrap();
368+ if matches!(drop_it, Err(AppError::Db(_))) {
369+ delete_500 += 1;
370+ last_delete = format!("{drop_it:?}");
371+ }
372+ for ask in asks {
373+ let ask = ask.await.unwrap();
374+ if matches!(ask, Err(AppError::Db(_))) {
375+ question_500 += 1;
376+ last_question = format!("{ask:?}");
377+ }
378+ }
379+ // Stored state, and both sides are needed: a question landing means
380+ // the claim beat the guard, the subject being gone means the delete
381+ // did. Seeing only one is a run that never swept across the window.
382+ if Subject::read(subject.get_id(), &db)
383+ .await
384+ .unwrap()
385+ .is_none()
386+ {
387+ wiped += 1;
388+ }
389+ if !ExamQuestion::list_for_exam(&exam, None, 0, &db)
390+ .await
391+ .unwrap()
392+ .0
393+ .is_empty()
394+ {
395+ landed += 1;
396+ }
397+ }
398+ eprintln!(
399+ "Subject::delete raced: {delete_500}/20 delete 500s, {question_500} question 500s, \
400+ {landed} rounds with a question landed / {wiped} wiped"
401+ );
402+ assert!(
403+ landed > 0 && wiped > 0,
404+ "the sweep never crossed the window ({landed} landed / {wiped} wiped)"
405+ );
406+ assert_eq!(
407+ delete_500, 0,
408+ "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}"
409+ );
410+ assert_eq!(
411+ question_500, 0,
412+ "a raced question create must retry, not 500: {question_500}/20 rounds, last {last_question}"
413+ );
414+ }
270 }415 }
src/domain/term.rsmodified+136 -9
@@ -10,7 +10,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
10 use ulid::Ulid;10 use ulid::Ulid;
11 11
12 use crate::constant::{COURSE_COUNT_FIELD, MAX_TERM_NAME_LEN, TERM_TABLE};12 use crate::constant::{COURSE_COUNT_FIELD, MAX_TERM_NAME_LEN, TERM_TABLE};
13-use crate::database::Database;13+use crate::database::{Database, write_with_retry};
14 use crate::domain::field_update::FieldUpdate;14 use crate::domain::field_update::FieldUpdate;
15 use crate::domain::page::PagedList;15 use crate::domain::page::PagedList;
16 use crate::domain::timestamp::{Timestamp, range_error};16 use crate::domain::timestamp::{Timestamp, range_error};
@@ -144,14 +144,13 @@ impl Term {
144 /// refused itself, with the same 400 the lookup gives). `Err(NotFound)`144 /// refused itself, with the same 400 the lookup gives). `Err(NotFound)`
145 /// keeps the answer a concurrent *delete* used to get.145 /// keeps the answer a concurrent *delete* used to get.
146 pub async fn delete(self, db: &Database) -> Result<bool, AppError> {146 pub async fn delete(self, db: &Database) -> Result<bool, AppError> {
147- let mut result = db147+ let sql = format!("DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE");
148- .query(format!(148+ // Through the retry, because the guard reads the very column a course
149- "DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE"149+ // create claims: a lost round writes nothing, and re-sending it is what
150- ))150+ // keeps the answer the 404 or 409 it owes instead of a 500.
151- .bind(("term", self.id.record()))151+ let gone: Vec<Term> =
152- .await?152+ write_with_retry(db, &sql, &[("term".into(), self.id.record().into_value())]).await?;
153- .check()?;153+ if !gone.is_empty() {
154- if !result.take::<Vec<Term>>(0)?.is_empty() {
155 return Ok(true);154 return Ok(true);
156 }155 }
157 // Still linked or already gone: the one statement cannot tell those156 // Still linked or already gone: the one statement cannot tell those
@@ -204,4 +203,132 @@ mod tests {
204 assert!(TermName::try_new(" ").is_err());203 assert!(TermName::try_new(" ").is_err());
205 assert!(TermName::try_new(&"x".repeat(101)).is_err());204 assert!(TermName::try_new(&"x".repeat(101)).is_err());
206 }205 }
206+
207+ /// GUARD, not a retry measurement — read the last paragraph before
208+ /// trusting this test with the retry. See
209+ /// [`crate::domain::course::Course::delete`]'s race test for why the rate is
210+ /// counted rather than asserted per round.
211+ ///
212+ /// One conditional `DELETE … RETURN BEFORE` and a bare `.check()?`: no
213+ /// transaction to abort, but also no [`crate::database::write_with_retry`],
214+ /// which every other guarded single-statement write in the crate goes
215+ /// through. A store answering "conflict, retry" therefore comes out as a
216+ /// 500 instead of the 404 or 409 the request owes.
217+ ///
218+ /// The racer is [`crate::domain::course::Course::create`] against this
219+ /// term: it claims `course_count` on the term row before it writes the
220+ /// link, which is the same record and the same column the guard reads. Both
221+ /// sides are swept across each other sub-millisecond, exactly as in
222+ /// [`crate::domain::subject::Subject::delete`]'s race test — a whole
223+ /// millisecond of head start on either side separates them completely, and
224+ /// the counters below assert the sweep straddled the site rather than
225+ /// landing on one side of it (it used to alternate on `round % 2` and score
226+ /// an exact 10/10, i.e. no overlap at all).
227+ ///
228+ /// And like that test it does *not* prove the retry: this site is one
229+ /// statement, so the window in which a conflict could reach
230+ /// [`write_with_retry`] is a single round trip wide — measured at 0
231+ /// conflicts in 100 raced rounds, green with the retry loop cut to a single
232+ /// attempt. A status-code guard, then: a raced delete answers 409 or 404 and
233+ /// never 500, and a course that got linked survives it. The retry is
234+ /// measured on [`crate::domain::course::Course::delete`].
235+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
236+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
237+ async fn a_delete_racing_a_course_create_never_answers_500() {
238+ use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle};
239+ use crate::domain::user::UserId;
240+ let (db, _serialized) = crate::database::init_test_server("term_delete_race").await;
241+ let (mut delete_500, mut create_500) = (0, 0);
242+ let (mut linked, mut wiped) = (0, 0);
243+ let (mut last_delete, mut last_create) = (String::new(), String::new());
244+ let at = Timestamp::from_millis;
245+ for round in 0..20 {
246+ let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db)
247+ .await
248+ .unwrap();
249+
250+ let separated = round % 4 == 0;
251+ let drop_it = {
252+ let (term, db) = (term.clone(), db.clone());
253+ // One round in four holds the racers back by a clear 2ms so the
254+ // delete wins outright: the sub-millisecond sweep alone leaves
255+ // them ahead of it nearly every round (measured 20 to 0), and
256+ // both counters below have to see a side. The other three keep
257+ // the sub-ms beat, which is the only spacing that overlaps at
258+ // all — a whole millisecond either way separates them.
259+ let beat = if separated {
260+ std::time::Duration::ZERO
261+ } else {
262+ std::time::Duration::from_micros(round * 53 % 300)
263+ };
264+ tokio::spawn(async move {
265+ tokio::time::sleep(beat).await;
266+ term.delete(&db).await
267+ })
268+ };
269+ let makes: Vec<_> = (0..6)
270+ .map(|_| {
271+ let (id, db) = (term.get_id().clone(), db.clone());
272+ let head_start = if separated {
273+ std::time::Duration::from_millis(2)
274+ } else {
275+ std::time::Duration::from_micros(round * 37 % 300)
276+ };
277+ tokio::spawn(async move {
278+ tokio::time::sleep(head_start).await;
279+ Course::create(
280+ &UserId::from_key("teacher"),
281+ CourseTitle::try_new("algebra").unwrap(),
282+ CourseDescription::try_new("").unwrap(),
283+ CourseKind::course(),
284+ Some(id),
285+ None,
286+ &db,
287+ )
288+ .await
289+ })
290+ })
291+ .collect();
292+ let drop_it = drop_it.await.unwrap();
293+ if matches!(drop_it, Err(AppError::Db(_))) {
294+ delete_500 += 1;
295+ last_delete = format!("{drop_it:?}");
296+ }
297+ // Stored state, both sides: a linked course means the claim beat the
298+ // guard, a gone term means the delete did.
299+ let mut landed = false;
300+ for make in makes {
301+ let make = make.await.unwrap();
302+ if matches!(make, Err(AppError::Db(_))) {
303+ create_500 += 1;
304+ last_create = format!("{make:?}");
305+ }
306+ if let Ok(course) = &make
307+ && Course::read(course.get_id(), &db).await.unwrap().is_some()
308+ {
309+ landed = true;
310+ }
311+ }
312+ linked += usize::from(landed);
313+ if Term::read(term.get_id(), &db).await.unwrap().is_none() {
314+ wiped += 1;
315+ }
316+ }
317+ eprintln!(
318+ "Term::delete raced: {delete_500}/20 delete 500s, {create_500} create 500s, \
319+ {linked} rounds with a course linked / {wiped} wiped"
320+ );
321+ assert!(
322+ linked > 0 && wiped > 0,
323+ "the sweep never crossed the window ({linked} linked / {wiped} wiped)"
324+ );
325+ assert_eq!(
326+ delete_500, 0,
327+ "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}"
328+ );
329+ assert_eq!(
330+ create_500, 0,
331+ "a raced course create must retry, not 500: {create_500}/20 rounds, last {last_create}"
332+ );
333+ }
207 }334 }