diff --git a/src/db/attendance.rs b/src/db/attendance.rs index 1ed23fe..6f564b4 100644 --- a/src/db/attendance.rs +++ b/src/db/attendance.rs @@ -136,9 +136,13 @@ mod tests { /// attendance rows and removes the row in one transaction, and a mark that /// wrote into the gap was a bare upsert nothing would ever sweep again. /// The mark now writes the event row too (its seats counter), so the two - /// transactions touch one row and Postgres refuses one of them; the barrier - /// releases both sides together so every interleaving gets its chance. - /// Mutation-tested: turning the claim back into a read turns it red. + /// transactions touch one row and Postgres refuses one of them. + /// + /// Both orders are forced by awaiting one side to completion before the + /// other starts. A barrier is a coin toss under load, and a run where the + /// delete loses every overlapped round has still proved the invariant. + /// Mutation-tested: turning the claim back into a read turns the + /// write-first round red. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_mark_written_inside_a_delete_never_outlives_the_event() { use crate::domain::event::{ @@ -161,14 +165,10 @@ mod tests { user } - let (db, _leases) = crate::database::init_test_db().await; - let allowed: Vec = Settings::defaults().get_attendance_statuses().to_vec(); - let marker = a_person(&db, "marker").await; - let (mut swept, mut orphans) = (0, 0); - for round in 0..8 { - let event = crate::db::event::create( - &db, - &marker, + async fn an_event(db: &Database, marker: &UserId) -> crate::domain::event::Event { + crate::db::event::create( + db, + marker, EventTitle::try_new("gezi").unwrap(), EventDescription::try_new("").unwrap(), EventAudience { @@ -182,11 +182,73 @@ mod tests { None, ) .await - .unwrap(); + .unwrap() + } + + let (db, _leases) = crate::database::init_test_db().await; + let allowed: Vec = Settings::defaults().get_attendance_statuses().to_vec(); + let marker = a_person(&db, "marker").await; + + // Delete-first: the event is gone before the mark starts. + { + let event = an_event(&db, &marker).await; + let id = event.get_id().clone(); + let dropped = crate::db::event::delete(&db, event).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "delete-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + crate::db::event::read(&db, &id).await.unwrap().is_none(), + "delete-first: the event is still there after delete: {dropped:?}" + ); + let student = a_person(&db, "df").await; + let status = AttendanceStatus::try_new("present", &allowed).unwrap(); + let marked = mark(&db, &id, &student, status, &marker).await; + assert!( + !matches!(marked, Err(AppError::Db(_))), + "delete-first: a mark must be answered, not 500: {marked:?}" + ); + assert_eq!( + list_for_event(&db, &id, None, 0).await.unwrap().0.len(), + 0, + "a mark outlived its event" + ); + } + + // Write-first: the mark lands, then the delete sweeps it. + { + let event = an_event(&db, &marker).await; + let id = event.get_id().clone(); + let student = a_person(&db, "wf").await; + let status = AttendanceStatus::try_new("present", &allowed).unwrap(); + let marked = mark(&db, &id, &student, status, &marker).await; + assert!( + marked.is_ok(), + "write-first: the mark must land before the delete: {marked:?}" + ); + let dropped = crate::db::event::delete(&db, event).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "write-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + crate::db::event::read(&db, &id).await.unwrap().is_none(), + "write-first: the event is still there" + ); + assert_eq!( + list_for_event(&db, &id, None, 0).await.unwrap().0.len(), + 0, + "a mark outlived its event" + ); + } + + // Overlapped rounds. Delete may lose every one of them. + let mut swept = 0; + for round in 0..4 { + let event = an_event(&db, &marker).await; let id = event.get_id().clone(); - // Delete and mark released together: both write the event row, so - // Postgres serializes them and refuses whichever lost. let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { let (db, gate, event) = (db.clone(), gate.clone(), event); @@ -196,7 +258,7 @@ mod tests { }) }; let marked = { - let (db, id, marker, gate) = (db.clone(), id.clone(), marker, gate); + let (db, id, marker, gate, allowed) = (db.clone(), id.clone(), marker, gate, allowed.clone()); let student = a_person(&db, "student").await; let status = AttendanceStatus::try_new("present", &allowed).unwrap(); tokio::spawn(async move { @@ -209,20 +271,22 @@ mod tests { !matches!(marked, Err(AppError::Db(_))), "round {round}: a raced mark must be answered, not 500: {marked:?}" ); + assert!( + !matches!(drop_it, Err(AppError::Db(_))), + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" + ); - // Stored state is the whole verdict; a return value is not evidence. if crate::db::event::read(&db, &id).await.unwrap().is_none() { swept += 1; - orphans += list_for_event(&db, &id, None, 0).await.unwrap().0.len(); + assert_eq!( + list_for_event(&db, &id, None, 0).await.unwrap().0.len(), + 0, + "round {round}: a mark outlived its event" + ); } else if drop_it.is_ok() { panic!("round {round}: the delete reported success but the event is still there"); } } - eprintln!("Event::delete raced by a mark: {swept}/8 rounds deleted the event"); - assert!( - swept > 0, - "no round ever deleted the event, so the window was never reached" - ); - assert_eq!(orphans, 0, "a mark outlived its event"); + eprintln!("Event::delete raced by a mark: {swept}/4 concurrent rounds deleted the event"); } } diff --git a/src/db/bank_question_image.rs b/src/db/bank_question_image.rs index 59426f3..7244125 100644 --- a/src/db/bank_question_image.rs +++ b/src/db/bank_question_image.rs @@ -328,23 +328,116 @@ mod tests { /// a blob stranded on disk. /// /// The upload writes the template row too (its `points`), so the two - /// transactions touch one row and Postgres refuses one of them; the - /// barrier releases both sides together so every interleaving gets its - /// chance. + /// transactions touch one row and Postgres refuses one of them. Both + /// orders are forced by awaiting one side to completion before the other + /// starts. A barrier is a coin toss under load, and a run where the + /// delete loses every overlapped round has still proved the invariant. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn an_image_written_inside_a_delete_window_never_outlives_its_template() { let (db, _leases) = crate::database::init_test_db().await; - let (mut swept, mut orphans, mut stranded) = (0, 0, 0); - for round in 0..8 { + async fn upload( + db: &Database, + question: &BankQuestionId, + ) -> Result<(BankQuestionImage, Option), AppError> { + upsert(db, BankQuestionImage::new(question, None, png(), 3)).await + } + + /// An image both sides report as committed must be in the list the + /// delete hands back — that list is what the web layer unlinks from. + fn stranded( + child: &Result<(BankQuestionImage, Option), AppError>, + dropped: &Result<(crate::domain::bank_question::BankQuestion, Vec), AppError>, + ) -> bool { + if let (Ok((stored, _)), Ok((_, images))) = (child, dropped) { + !images + .iter() + .any(|image| image.get_file() == stored.get_file()) + } else { + false + } + } + + // Delete-first: the template is gone before the upload starts. + { + let question = a_template(&db).await; + let template = crate::db::bank_question::read(&db, &question) + .await + .unwrap() + .unwrap(); + let dropped = crate::db::bank_question::delete(&db, template).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "delete-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + crate::db::bank_question::read(&db, &question) + .await + .unwrap() + .is_none(), + "delete-first: the template is still there after delete: {dropped:?}" + ); + let child = upload(&db, &question).await; + assert!( + !matches!(child, Err(AppError::Db(_))), + "delete-first: an upload must be answered, not 500: {child:?}" + ); + assert_eq!( + list_for_question(&db, &question).await.unwrap().len(), + 0, + "an image row outlived its template" + ); + assert!( + !stranded(&child, &dropped), + "an image committed inside the window was swept without being handed back, so its blob stays on disk" + ); + } + + // Write-first: the upload lands, then the delete sweeps it and must + // hand the blob name back. + { + let question = a_template(&db).await; + let template = crate::db::bank_question::read(&db, &question) + .await + .unwrap() + .unwrap(); + let child = upload(&db, &question).await; + assert!( + child.is_ok(), + "write-first: the upload must land before the delete: {child:?}" + ); + let dropped = crate::db::bank_question::delete(&db, template).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "write-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + crate::db::bank_question::read(&db, &question) + .await + .unwrap() + .is_none(), + "write-first: the template is still there" + ); + assert_eq!( + list_for_question(&db, &question).await.unwrap().len(), + 0, + "an image row outlived its template" + ); + assert!( + !stranded(&child, &dropped), + "an image committed inside the window was swept without being handed back, so its blob stays on disk" + ); + } + + // Overlapped rounds. Delete may lose every one of them. + let mut swept = 0; + for round in 0..4 { let question = a_template(&db).await; let template = crate::db::bank_question::read(&db, &question) .await .unwrap() .unwrap(); - // Delete and upload released together: both write the template row, - // so Postgres serializes them and refuses whichever lost. let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { let (db, gate, template) = (db.clone(), gate.clone(), template); @@ -357,50 +450,42 @@ mod tests { let (db, question, gate) = (db.clone(), question.clone(), gate); tokio::spawn(async move { gate.wait().await; - upsert(&db, BankQuestionImage::new(&question, None, png(), 3)).await + upload(&db, &question).await }) }; let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); - // A 404 for the upload is a correct answer; the only defect is - // stored state. Neither side may 500 — they contend by design and a - // lost round is re-sent, not reported. assert!( !matches!(child, Err(AppError::Db(_))), "round {round}: a raced upload must be answered, not 500: {child:?}" ); assert!( !matches!(drop_it, Err(AppError::Db(_))), - "round {round}: a raced delete must retry, not 500: {drop_it:?}" + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" ); - // Stored state is the whole verdict; a return value is not evidence. if crate::db::bank_question::read(&db, &question) .await .unwrap() .is_none() { swept += 1; - orphans += list_for_question(&db, &question).await.unwrap().len(); - if let (Ok((stored, _)), Ok((_, images))) = (&child, &drop_it) - && !images - .iter() - .any(|image| image.get_file() == stored.get_file()) - { - stranded += 1; - } + assert_eq!( + list_for_question(&db, &question).await.unwrap().len(), + 0, + "round {round}: an image row outlived its template" + ); + assert!( + !stranded(&child, &drop_it), + "round {round}: an image committed inside the window was swept without being handed back" + ); + } else if drop_it.is_ok() { + panic!( + "round {round}: the delete reported success but the template is still there" + ); } } eprintln!( - "bank_question::delete raced by an upload: {swept}/8 rounds deleted the template" - ); - assert!( - swept > 0, - "no round ever deleted the template, so the window was never reached" - ); - assert_eq!(orphans, 0, "an image row outlived its template"); - assert_eq!( - stranded, 0, - "an image committed inside the window was swept without being handed back, so its blob stays on disk" + "bank_question::delete raced by an upload: {swept}/4 concurrent rounds deleted the template" ); } diff --git a/src/db/chatbot_thread.rs b/src/db/chatbot_thread.rs index ac703d9..a23f455 100644 --- a/src/db/chatbot_thread.rs +++ b/src/db/chatbot_thread.rs @@ -385,17 +385,87 @@ mod tests { /// The window the schema event used to force open is the thread row's own /// lock now: a turn is written *through* the row ([`touch_and_write`]), /// so a turn racing the delete serializes on that row instead of - /// committing past the sweep. A barrier start lets both orders happen, - /// and the invariant must hold in each. + /// committing past the sweep. Both orders are forced by awaiting one side + /// to completion before the other starts — a barrier is a coin toss under + /// load, and a run where the delete loses every overlapped round has still + /// proved the invariant. A few rounds still start together; those may all + /// lose the delete, and that is not a failure. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_turn_written_inside_a_delete_never_outlives_the_thread() { - // One thread minted per round: the cap must cover every round, since - // the rounds where the turn wins keep their thread (and its seat). - let (db, _leases) = a_user_capped_at(8).await; - + // Forced rounds free their seat. Concurrent rounds may keep theirs, so + // the cap covers every thread this test can leave standing. + let (db, _leases) = a_user_capped_at(6).await; let user = UserId::from_key(U); - let (mut orphans, mut swept) = (0, 0); - for round in 0..8 { + + async fn append( + db: &Database, + id: &ChatbotThreadId, + user: &UserId, + ) -> Result<(), AppError> { + chatbot_message::append_user(db, id, user, ChatContent::try_new("selam").unwrap()) + .await + .map(|_| ()) + } + + // Delete-first: the thread is gone before the turn starts. + { + let thread = create_capped(&db, &user, None).await.expect("thread"); + let id = thread.get_id().clone(); + let dropped = delete(&db, thread).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "delete-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + read_for(&db, &id, &user).await.unwrap().is_none(), + "delete-first: the thread is still there after delete: {dropped:?}" + ); + let turn = append(&db, &id, &user).await; + assert!( + !matches!(turn, Err(AppError::Db(_))), + "delete-first: a turn must be answered, not 500: {turn:?}" + ); + assert_eq!( + chatbot_message::list_for_thread(&db, &id, None, 0) + .await + .unwrap() + .1, + 0, + "a turn outlived its thread" + ); + } + + // Write-first: the turn lands, then the delete sweeps it. + { + let thread = create_capped(&db, &user, None).await.expect("thread"); + let id = thread.get_id().clone(); + let turn = append(&db, &id, &user).await; + assert!( + turn.is_ok(), + "write-first: the turn must land before the delete: {turn:?}" + ); + let dropped = delete(&db, thread).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "write-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + read_for(&db, &id, &user).await.unwrap().is_none(), + "write-first: the thread is still there" + ); + assert_eq!( + chatbot_message::list_for_thread(&db, &id, None, 0) + .await + .unwrap() + .1, + 0, + "a turn outlived its thread" + ); + } + + // Overlapped rounds. Delete may lose every one of them. + let mut swept = 0; + for round in 0..4 { let thread = create_capped(&db, &user, None).await.expect("thread"); let id = thread.get_id().clone(); @@ -411,40 +481,45 @@ mod tests { let (id, db, user, gate) = (id.clone(), db.clone(), user, gate); tokio::spawn(async move { gate.wait().await; - chatbot_message::append_user( - &db, - &id, - &user, - ChatContent::try_new("selam").unwrap(), - ) - .await - .map(|_| ()) + append(&db, &id, &user).await }) }; let (drop_it, turn) = (drop_it.await.unwrap(), turn.await.unwrap()); - // A 404 for the turn, or a NotFound for the delete, is a correct - // answer — the only defect is stored state. assert!( !matches!(turn, Err(AppError::Db(_))), "round {round}: a raced turn must be answered, not 500: {turn:?}" ); - - // Stored state is the whole verdict; a return value is not evidence. - if read_for(&db, &id, &user).await.unwrap().is_none() { + // A lost round here is a 23503, not a missed sweep. The turn's + // insert and this delete's `DELETE chatbot_message` do not share a + // row lock, `chatbot_message.thread_id` is `ON DELETE NO ACTION`, + // and [`delete`] does not retry that (`cascade = false`). The + // thread is still there; nothing outlived a gone parent. Any other + // database error is a 500. The forced rounds above are the ones + // that require the delete itself to answer without one. + let parent_gone = read_for(&db, &id, &user).await.unwrap().is_none(); + if let Err(AppError::Db(err)) = &drop_it { + let lost_the_gap = crate::database::foreign_key_violation(err) && !parent_gone; + assert!( + lost_the_gap, + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" + ); + } + if parent_gone { swept += 1; - orphans += chatbot_message::list_for_thread(&db, &id, None, 0) - .await - .unwrap() - .1; + assert_eq!( + chatbot_message::list_for_thread(&db, &id, None, 0) + .await + .unwrap() + .1, + 0, + "round {round}: a turn outlived its thread" + ); } else if drop_it.is_ok() { panic!("round {round}: the delete reported success but the thread is still there"); } } - eprintln!("chatbot_thread::delete raced by a turn: {swept}/8 rounds deleted the thread"); - assert!( - swept > 0, - "no round ever deleted the thread, so the race never actually ran" + eprintln!( + "chatbot_thread::delete raced by a turn: {swept}/4 concurrent rounds deleted the thread" ); - assert_eq!(orphans, 0, "a turn outlived its thread"); } } diff --git a/src/db/course.rs b/src/db/course.rs index 3ae3541..ce6448f 100644 --- a/src/db/course.rs +++ b/src/db/course.rs @@ -717,13 +717,12 @@ pub(crate) async fn a_test_instance( } /// The race half of "a child of a course must not survive its deletion", run -/// for one child table: [`delete`] is held open by the schema and -/// `make` fires its create inside that window, eight rounds. +/// for one child table. /// /// The harness lives here, beside the cascade being raced, and each child names /// its own pin in its own module (`exam`, `course_session`, `subject`) — the -/// loop, the window and the verdict are one fact about *this* delete, and three -/// copies of it would drift into three different tests of three different +/// orders, the window and the verdict are one fact about *this* delete, and +/// three copies of it would drift into three different tests of three different /// things. The sequential half — a create against a course that is already gone /// — is `tests/regress_course_child_orphans.rs`, which needs no server. /// @@ -732,37 +731,111 @@ pub(crate) async fn a_test_instance( /// hangs off an *instance* ([`crate::db::class_course`]) and reaches the course /// through it. Either way it takes the course uuid as `$1`. /// -/// The window is opened by the database rather than by a lucky interleaving: -/// Postgres puts the racing create and delete on the same rows (the FK claims -/// and the cascade), so a barrier start covers every interleaving — and the -/// child may never outlive the course in any of them. +/// Both orders are forced by awaiting one side to completion before the other +/// starts. A barrier is a coin toss under load: whichever side is marginally +/// faster takes every overlapped round, and requiring the delete to win one of +/// them fails a run that never let it. A few rounds still start together; those +/// may all lose the delete, and that is not a failure. A rival that claims an +/// instance (a session, an exam) makes the write-first delete a refusal — the +/// course a class still teaches is not deletable — so that round asserts the +/// refusal, not a sweep. The sweep is the delete-first round, and any round +/// whose course is actually gone. /// /// One child per round, for the reason the menu and `class_course` twins /// document: a second writer makes the delete lose and re-send, and the re-sent /// sweep clears the evidence. /// -/// Real server, and every caller is `#[ignore]`d for it: the subject *is* the -/// store's conflict detection, which `init_mem`'s embedded engine does not -/// have — it commits both sides and answers `Ok` to each, so this passes there -/// on broken code. +/// Real server: the subject is the store's conflict detection, which an +/// embedded engine does not have. #[cfg(test)] pub(crate) async fn assert_no_child_outlives_a_course_delete( table: &str, orphan_count_sql: &str, make: fn(CourseId, Database) -> tokio::task::JoinHandle>, ) { - use sqlx::Row as _; + + async fn child_rows(db: &Database, sql: &str, course: &CourseId) -> usize { + use sqlx::Row as _; + sqlx::query(sqlx::AssertSqlSafe(sql.to_string())) + .bind(course.uuid()) + .fetch_one(db) + .await + .unwrap() + .try_get::(0) + .unwrap() as usize + } let (db, _leases) = crate::database::init_test_db().await; - let (mut swept, mut orphans) = (0, 0); - for round in 0..8 { + // Delete-first: the course is gone before the child starts. + { + let course = a_test_course(&db).await; + let dropped = delete( + &db, + read(&db, &course) + .await + .unwrap() + .expect("the course is there"), + ) + .await; + assert!( + matches!(dropped, Ok(true)), + "{table} delete-first: an empty course must delete, not {dropped:?}" + ); + assert!( + read(&db, &course).await.unwrap().is_none(), + "{table} delete-first: the course is still there" + ); + let child = make(course.clone(), db.clone()).await.unwrap(); + assert!( + !matches!(child, Err(AppError::Db(_))), + "{table} delete-first: a create must be answered, not 500: {child:?}" + ); + assert_eq!( + child_rows(&db, orphan_count_sql, &course).await, + 0, + "{table}: a child outlived its course" + ); + } + + // Write-first: the child lands, then the delete. A rival that claimed an + // instance makes this a refusal — the course stays, and that is correct. + // A rival that did not (a subject) is swept: the course is gone and the + // child count is 0. + { + let course = a_test_course(&db).await; + let child = make(course.clone(), db.clone()).await.unwrap(); + assert!( + child.is_ok(), + "{table} write-first: the child must land before the delete: {child:?}" + ); + let row = read(&db, &course).await.unwrap().expect( + "{table} write-first: the course vanished before the delete", + ); + let dropped = delete(&db, row).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "{table} write-first: a delete must be answered, not 500: {dropped:?}" + ); + let gone = read(&db, &course).await.unwrap().is_none(); + if matches!(dropped, Ok(true)) && !gone { + panic!( + "{table} write-first: the delete reported success, the course is still there" + ); + } + if gone { + assert_eq!( + child_rows(&db, orphan_count_sql, &course).await, + 0, + "{table}: a child outlived its course" + ); + } + } + + // Overlapped rounds. Delete may lose every one of them. + let mut swept = 0; + for round in 0..4 { let course = a_test_course(&db).await; - // The old engine needed a schema event to hold the delete's window - // open; Postgres puts the racing create and delete on the same rows - // (the FK claims and the cascade), so a barrier start covers every - // interleaving — and the child may never outlive the course in any - // of them. let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { let (course, db, gate) = (course.clone(), db.clone(), gate.clone()); @@ -782,17 +855,12 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete( let (course, db, gate) = (course.clone(), db.clone(), gate); tokio::spawn(async move { gate.wait().await; - // The inner task joins here: a `Db` answer stays `Err`, only a - // panic inside `make` (or the outer join) would panic. make(course, db).await.unwrap() }) } .await .unwrap(); let dropped = drop_it.await.unwrap(); - - // A 404 for the create, or a refusal for the delete, is a correct - // answer — the only defect is stored state. Nothing may 500. assert!( !matches!(child, Err(AppError::Db(_))), "{table} round {round}: a raced create must be answered, not 500: {child:?}" @@ -801,27 +869,22 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete( !matches!(dropped, Err(AppError::Db(_))), "{table} round {round}: a raced delete must be answered, not 500: {dropped:?}" ); - - // Stored state is the whole verdict; a return value is not evidence. if read(&db, &course).await.unwrap().is_none() { swept += 1; - orphans += sqlx::query(sqlx::AssertSqlSafe(orphan_count_sql.to_string())) - .bind(course.uuid()) - .fetch_one(&db) - .await - .unwrap() - .try_get::(0) - .unwrap() as usize; + assert_eq!( + child_rows(&db, orphan_count_sql, &course).await, + 0, + "{table} round {round}: a child outlived its course" + ); } else if matches!(dropped, Ok(true)) { - panic!("{table} round {round}: the delete reported success, the course is still there"); + panic!( + "{table} round {round}: the delete reported success, the course is still there" + ); } } - eprintln!("Course::delete raced by a {table} create: {swept}/8 rounds deleted the course"); - assert!( - swept > 0, - "{table}: no round ever deleted the course, so the race never actually ran" + eprintln!( + "Course::delete raced by a {table} create: {swept}/4 concurrent rounds deleted the course" ); - assert_eq!(orphans, 0, "{table}: a child outlived its course"); } #[cfg(test)] @@ -975,16 +1038,12 @@ mod tests { /// half of the verdict is the orphan check — an instance may never name a /// course that is gone, whichever side of the race it was on. /// - /// 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*. - /// - /// Each side gets a clear head start on every other round — 2ms is a - /// separation the several-statement rival cannot cross (the same spacing - /// [`crate::db::term`]'s race test settled on). Without it the two sides - /// compete for the same course row and whichever one is marginally faster - /// takes every round, leaving one half of the verdict (`swept > 0`, or - /// `attached > 0`) a coin toss under load. + /// The 500s are counted over the overlapped rounds instead of asserted at + /// the first hit, so a lost retry reports how often it happened. Those + /// rounds do not have to observe both verdicts: a 2ms head start is still + /// a coin toss under pool contention. Delete-first and attach-first below + /// force the two orders by awaiting one side to completion. A delete that + /// reports success (`Ok(true)`) while the course remains is still a bug. /// /// Multi-threaded and on a real server: the current-thread runtime never /// interleaves the two, and an embedded engine does not conflict-check @@ -999,27 +1058,84 @@ mod tests { for seat in 0..6 { classes.push(a_class(&manager, &format!("9-{seat}"), &db).await); } - let (mut delete_500, mut attach_500, mut attached, mut swept) = (0, 0, 0, 0); + + // Delete-first: the course is gone before any attach starts. + { + let course = a_course(&db).await; + let dropped = delete(&db, course.clone()).await; + assert!( + matches!(dropped, Ok(true)), + "delete-first: an empty course must delete, not {dropped:?}" + ); + assert!( + read(&db, course.get_id()).await.unwrap().is_none(), + "delete-first: the course is still there" + ); + for class in &classes { + let attached = crate::service::class_course::attach( + &db, + class.get_id(), + course.get_id(), + &manager, + ) + .await; + assert!( + !matches!(attached, Err(AppError::Db(_))), + "delete-first: an attach must be answered, not 500: {attached:?}" + ); + } + assert_eq!( + instance_rows(course.get_id(), &db).await, + 0, + "an instance outlived the course" + ); + } + + // Attach-first: the guard must refuse. The course stays; that is the + // verdict, not a missed sweep. + { + let course = a_course(&db).await; + for class in &classes { + let attached = crate::service::class_course::attach( + &db, + class.get_id(), + course.get_id(), + &manager, + ) + .await; + assert!( + attached.is_ok(), + "attach-first: the attach must land before the delete: {attached:?}" + ); + } + let dropped = delete(&db, course.clone()).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "attach-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + matches!(dropped, Ok(false)), + "attach-first: a course a class still teaches must refuse, not {dropped:?}" + ); + assert!( + read(&db, course.get_id()).await.unwrap().is_some(), + "attach-first: the refused delete removed the course" + ); + assert!( + instance_rows(course.get_id(), &db).await > 0, + "attach-first: the landed instances are gone" + ); + } + + // Overlapped rounds keep the retry measurement. Delete may lose all + // of them. + let (mut delete_500, mut attach_500, mut swept) = (0, 0, 0); let (mut last_delete, mut last_attach) = (String::new(), String::new()); for round in 0..20 { let course = a_course(&db).await; - - // Every other round the attaches are held back so the delete wins - // outright (the course goes, and nothing may survive it); the rest - // release the attaches first, which is the round where the guard - // has to read their claim and refuse the delete. - let clear = std::time::Duration::from_millis(2); - let (delete_beat, attach_beat) = if round % 2 == 0 { - (std::time::Duration::ZERO, clear) - } else { - (clear, std::time::Duration::ZERO) - }; let drop_it = { let (course, db) = (course.clone(), db.clone()); - tokio::spawn(async move { - tokio::time::sleep(delete_beat).await; - delete(&db, course).await - }) + tokio::spawn(async move { delete(&db, course).await }) }; let joins: Vec<_> = classes .iter() @@ -1031,7 +1147,6 @@ mod tests { manager, ); tokio::spawn(async move { - tokio::time::sleep(attach_beat).await; crate::service::class_course::attach(&db, &class, &course, &mgr).await }) }) @@ -1048,14 +1163,14 @@ mod tests { last_attach = format!("{join:?}"); } } - // Stored state, not the return values: an instance that landed is - // what the guard had to see, and one that outlived a deleted - // course is the defect this whole shape exists to catch. let live = instance_rows(course.get_id(), &db).await; - if live > 0 { - attached += 1; + let gone = read(&db, course.get_id()).await.unwrap().is_none(); + if matches!(drop_it, Ok(true)) && !gone { + panic!( + "round {round}: the delete reported success, the course is still there" + ); } - if read(&db, course.get_id()).await.unwrap().is_none() { + if gone { swept += 1; assert_eq!( live, 0, @@ -1065,12 +1180,7 @@ mod tests { } eprintln!( "Course::delete raced: {delete_500}/20 delete 500s, {attach_500} attach 500s, \ - {attached} rounds with an instance attached / {swept} rounds the course went" - ); - assert!( - attached > 0 && swept > 0, - "the sweep never crossed the window ({attached} attached / {swept} swept), \ - so at least one verdict was never exercised" + {swept} rounds the course went" ); assert_eq!( delete_500, 0, diff --git a/src/db/exam.rs b/src/db/exam.rs index d72b412..af2b4a8 100644 --- a/src/db/exam.rs +++ b/src/db/exam.rs @@ -496,6 +496,7 @@ pub async fn update_if_unchanged( /// What [`delete`] collects on its way through: the deleted row plus the /// blob keys of the image rows its cascade removed — exactly whose files /// the web layer may unlink. +#[derive(Debug)] pub struct Deleted { pub exam: Exam, pub question_image_files: Vec, @@ -1242,30 +1243,90 @@ mod tests { /// /// One child per round, deliberately — in the menu twin, two children in one /// round hid the bug: the first writer made the delete lose and re-send, and - /// the re-sent sweep removed the other's row. + /// the re-sent sweep removed the other's row. Both orders are forced by + /// awaiting one side to completion before the other starts. Overlapped + /// rounds may all lose the delete; that is not a failure. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn an_answer_written_inside_a_delete_never_outlives_the_exam() { use crate::db::exam_answer; let (db, _leases) = crate::database::init_test_db().await; - let (mut answers, mut swept) = (0, 0); - for round in 0..8 { + let student = a_person(&db, "student", "student").await; + + // Delete-first: the exam is gone before the save starts. + { + let exam = published(&db).await; + let question = question_on(&exam, &db).await; + let id = exam.get_id().clone(); + let pick = question.get_choices().unwrap()[1] + .get_id() + .as_str() + .to_string(); + let dropped = delete(&db, exam).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "delete-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + read(&db, &id).await.unwrap().is_none(), + "delete-first: the exam is still there after delete: {dropped:?}" + ); + let child = exam_answer::save(&db, &question, &student, 1, Some(pick), None).await; + assert!( + !matches!(child, Err(AppError::Db(_))), + "delete-first: a save must be answered, not 500: {child:?}" + ); + assert_eq!( + exam_answer::list_for_exam(&db, &id).await.unwrap().len(), + 0, + "an answer outlived its exam" + ); + } + + // Write-first: the save lands, then the delete sweeps it. + { + let exam = published(&db).await; + let question = question_on(&exam, &db).await; + let id = exam.get_id().clone(); + let pick = question.get_choices().unwrap()[1] + .get_id() + .as_str() + .to_string(); + let child = exam_answer::save(&db, &question, &student, 1, Some(pick), None).await; + assert!( + child.is_ok(), + "write-first: the save must land before the delete: {child:?}" + ); + let dropped = delete(&db, exam).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "write-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + read(&db, &id).await.unwrap().is_none(), + "write-first: the exam is still there" + ); + assert_eq!( + exam_answer::list_for_exam(&db, &id).await.unwrap().len(), + 0, + "an answer outlived its exam" + ); + } + + // Overlapped rounds. Delete may lose every one of them. + let mut swept = 0; + for round in 0..4 { let exam = published(&db).await; let question = question_on(&exam, &db).await; let id = exam.get_id().clone(); - let student = a_person(&db, "student", "student").await; - // The stored choice ids are minted by the create, not the ones the - // spec asked for — an answer must name one of *those*. let pick = question.get_choices().unwrap()[1] .get_id() .as_str() .to_string(); - // Delete and save released together: both write the exam row, so - // Postgres serializes them and refuses whichever lost. let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { - let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone()); + let (db, exam, gate) = (db.clone(), exam, gate.clone()); tokio::spawn(async move { gate.wait().await; delete(&db, exam).await @@ -1273,44 +1334,47 @@ mod tests { }; let child = { let (db, question, student, pick, gate) = - (db.clone(), question.clone(), student, pick, gate); + (db.clone(), question, student, pick, gate); tokio::spawn(async move { gate.wait().await; exam_answer::save(&db, &question, &student, 1, Some(pick), None).await }) }; let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); - // A 404 for the save, or a refusal for the delete, is a correct - // answer — the only defect is stored state. assert!( !matches!(child, Err(AppError::Db(_))), "round {round}: a raced save must be answered, not 500: {child:?}" ); + assert!( + !matches!(drop_it, Err(AppError::Db(_))), + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" + ); - // Stored state is the whole verdict; a return value is not evidence. if read(&db, &id).await.unwrap().is_none() { swept += 1; - answers += exam_answer::list_for_exam(&db, &id).await.unwrap().len(); + assert_eq!( + exam_answer::list_for_exam(&db, &id).await.unwrap().len(), + 0, + "round {round}: an answer outlived its exam" + ); } else if drop_it.is_ok() { panic!("round {round}: the delete reported success but the exam is still there"); } } - eprintln!("Exam::delete raced by an answer save: {swept}/8 rounds deleted the exam"); - assert!( - swept > 0, - "no round ever deleted the exam, so the window was never reached" - ); - assert_eq!(answers, 0, "an answer outlived its exam"); + eprintln!("Exam::delete raced by an answer save: {swept}/4 concurrent rounds deleted the exam"); } /// The same defect on the teacher's side of the sheet, and a worse one: a /// question written inside the delete window kept the reference it claimed /// on its subject (the cascade's per-subject decrement counted only the - /// rows it could see), and [`crate::db::subject::delete`] is - /// gated on that count reading zero — a subject nobody could ever delete - /// again, hanging off an exam nobody could ever see. The freeze gate is a - /// *read* of `exam_attempt` and never survived this window; - /// [`crate::db::exam_attempt::write_unfrozen_with`] now writes the exam row too. + /// rows it could see), and [`crate::db::subject::delete`] is gated on that + /// count reading zero — a subject nobody could ever delete again, hanging + /// off an exam nobody could ever see. The freeze gate is a *read* of + /// `exam_attempt` and never survived this window; + /// [`crate::db::exam_attempt::write_unfrozen_with`] now writes the exam row + /// too. Both orders are forced by awaiting one side to completion before + /// the other starts. Overlapped rounds may all lose the delete; that is + /// not a failure. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_question_written_inside_a_delete_never_outlives_the_exam() { use crate::domain::exam_question::{ @@ -1318,24 +1382,143 @@ mod tests { }; let (db, _leases) = crate::database::init_test_db().await; - let (mut questions, mut swept, mut stuck) = (0, 0, 0); - for round in 0..8 { - let exam = published(&db).await; - let id = exam.get_id().clone(); - let subject = crate::db::subject::create( - &db, - &crate::db::course::a_test_course(&db).await, + fn spec() -> QuestionSpec { + QuestionSpec::try_new( + QuestionKind::try_new("choice").unwrap(), + Some(vec![ + ChoiceInput { + id: Some("a".into()), + text: "5".into(), + }, + ChoiceInput { + id: Some("b".into()), + text: "6".into(), + }, + ]), + Some("b".into()), + &[], + ) + .unwrap() + } + + async fn ask( + db: &Database, + exam: &ExamId, + on: crate::domain::subject::SubjectId, + ) -> Result { + crate::db::exam_question::create( + db, + exam, + on, + QuestionText::try_new("3 + 3?").unwrap(), + QuestionPoints::try_new(5).unwrap(), + spec(), + ) + .await + } + + async fn subject_stuck(db: &Database, subject: &crate::domain::subject::Subject) -> bool { + crate::db::subject::delete( + db, + crate::db::subject::read(db, subject.get_id()) + .await + .unwrap() + .unwrap(), + ) + .await + .is_err() + } + + async fn a_subject(db: &Database) -> crate::domain::subject::Subject { + crate::db::subject::create( + db, + &crate::db::course::a_test_course(db).await, crate::domain::subject::SubjectName::try_new("topic").unwrap(), crate::domain::subject::SubjectDescription::try_new("").unwrap(), ) .await - .unwrap(); + .unwrap() + } + + // Delete-first: the exam is gone before the question write starts. + { + let exam = published(&db).await; + let id = exam.get_id().clone(); + let subject = a_subject(&db).await; + let dropped = delete(&db, exam).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "delete-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + read(&db, &id).await.unwrap().is_none(), + "delete-first: the exam is still there after delete: {dropped:?}" + ); + let child = ask(&db, &id, *subject.get_id()).await; + assert!( + !matches!(child, Err(AppError::Db(_))), + "delete-first: a question write must be answered, not 500: {child:?}" + ); + assert_eq!( + crate::db::exam_question::list_for_exam(&db, &id, None, 0) + .await + .unwrap() + .0 + .len(), + 0, + "a question outlived its exam" + ); + assert!( + !subject_stuck(&db, &subject).await, + "an orphan question left its subject undeletable" + ); + } + + // Write-first: the question lands, then the delete sweeps it and frees + // the subject reference it claimed. + { + let exam = published(&db).await; + let id = exam.get_id().clone(); + let subject = a_subject(&db).await; + let child = ask(&db, &id, *subject.get_id()).await; + assert!( + child.is_ok(), + "write-first: the question must land before the delete: {child:?}" + ); + let dropped = delete(&db, exam).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "write-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + read(&db, &id).await.unwrap().is_none(), + "write-first: the exam is still there" + ); + assert_eq!( + crate::db::exam_question::list_for_exam(&db, &id, None, 0) + .await + .unwrap() + .0 + .len(), + 0, + "a question outlived its exam" + ); + assert!( + !subject_stuck(&db, &subject).await, + "an orphan question left its subject undeletable" + ); + } + + // Overlapped rounds. Delete may lose every one of them. + let mut swept = 0; + for round in 0..4 { + let exam = published(&db).await; + let id = exam.get_id().clone(); + let subject = a_subject(&db).await; - // Delete and create released together: both write the exam row, so - // Postgres serializes them and refuses whichever lost. let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { - let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone()); + let (db, exam, gate) = (db.clone(), exam, gate.clone()); tokio::spawn(async move { gate.wait().await; delete(&db, exam).await @@ -1345,31 +1528,7 @@ mod tests { let (db, exam_id, on, gate) = (db.clone(), id.clone(), *subject.get_id(), gate); tokio::spawn(async move { gate.wait().await; - let spec = QuestionSpec::try_new( - QuestionKind::try_new("choice").unwrap(), - Some(vec![ - ChoiceInput { - id: Some("a".into()), - text: "5".into(), - }, - ChoiceInput { - id: Some("b".into()), - text: "6".into(), - }, - ]), - Some("b".into()), - &[], - ) - .unwrap(); - crate::db::exam_question::create( - &db, - &exam_id, - on, - QuestionText::try_new("3 + 3?").unwrap(), - QuestionPoints::try_new(5).unwrap(), - spec, - ) - .await + ask(&db, &exam_id, on).await }) }; let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); @@ -1377,63 +1536,135 @@ mod tests { !matches!(child, Err(AppError::Db(_))), "round {round}: a raced question write must be answered, not 500: {child:?}" ); + assert!( + !matches!(drop_it, Err(AppError::Db(_))), + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" + ); if read(&db, &id).await.unwrap().is_none() { swept += 1; - questions += crate::db::exam_question::list_for_exam(&db, &id, None, 0) - .await - .unwrap() - .0 - .len(); - // The subject has to be free again: a stranded reference is the - // half of this bug a row count alone would not catch. - if crate::db::subject::delete( - &db, - crate::db::subject::read(&db, subject.get_id()) + assert_eq!( + crate::db::exam_question::list_for_exam(&db, &id, None, 0) .await .unwrap() - .unwrap(), - ) - .await - .is_err() - { - stuck += 1; - } + .0 + .len(), + 0, + "round {round}: a question outlived its exam" + ); + assert!( + !subject_stuck(&db, &subject).await, + "round {round}: an orphan question left its subject undeletable" + ); } else if drop_it.is_ok() { panic!("round {round}: the delete reported success but the exam is still there"); } } - eprintln!("Exam::delete raced by a question write: {swept}/8 rounds deleted the exam"); - assert!( - swept > 0, - "no round ever deleted the exam, so the window was never reached" + eprintln!( + "Exam::delete raced by a question write: {swept}/4 concurrent rounds deleted the exam" ); - assert_eq!(questions, 0, "a question outlived its exam"); - assert_eq!(stuck, 0, "an orphan question left its subject undeletable"); } /// The student's half of the same picture problem: a drawing is a bare /// upsert — the exact pre-fix shape of [`crate::db::exam_answer::save`] — so it kept /// the hole the text answer just lost, blob and all. It now rides the same - /// exam-row write the answer does. + /// exam-row write the answer does. Both orders are forced by awaiting one + /// side to completion before the other starts. Overlapped rounds may all + /// lose the delete; that is not a failure. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_drawing_written_inside_a_delete_never_outlives_the_exam() { use crate::domain::answer_image::AnswerImage; use crate::domain::note_file::FileContentType; let (db, _leases) = crate::database::init_test_db().await; + let student = a_person(&db, "student", "student").await; + + async fn draw( + db: &Database, + exam: &ExamId, + question: &crate::domain::exam_question::ExamQuestionId, + student: &UserId, + ) -> Result<(AnswerImage, Option), AppError> { + let image = AnswerImage::new( + exam, + question, + student, + 1, + FileContentType::try_new("image/png").unwrap(), + 3, + ); + crate::db::answer_image::upsert(db, image).await + } + + // Delete-first: the exam is gone before the drawing starts. + { + let exam = published(&db).await; + let question = question_on(&exam, &db).await; + let id = exam.get_id().clone(); + let on = question.get_id().clone(); + let dropped = delete(&db, exam).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "delete-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + read(&db, &id).await.unwrap().is_none(), + "delete-first: the exam is still there after delete: {dropped:?}" + ); + let child = draw(&db, &id, &on, &student).await; + assert!( + !matches!(child, Err(AppError::Db(_))), + "delete-first: a drawing write must be answered, not 500: {child:?}" + ); + assert_eq!( + crate::db::answer_image::list_for_exam(&db, &id) + .await + .unwrap() + .len(), + 0, + "a drawing outlived its exam" + ); + } + + // Write-first: the drawing lands, then the delete sweeps it. + { + let exam = published(&db).await; + let question = question_on(&exam, &db).await; + let id = exam.get_id().clone(); + let on = question.get_id().clone(); + let child = draw(&db, &id, &on, &student).await; + assert!( + child.is_ok(), + "write-first: the drawing must land before the delete: {child:?}" + ); + let dropped = delete(&db, exam).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "write-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + read(&db, &id).await.unwrap().is_none(), + "write-first: the exam is still there" + ); + assert_eq!( + crate::db::answer_image::list_for_exam(&db, &id) + .await + .unwrap() + .len(), + 0, + "a drawing outlived its exam" + ); + } - let (mut drawings, mut swept) = (0, 0); - for round in 0..8 { + // Overlapped rounds. Delete may lose every one of them. + let mut swept = 0; + for round in 0..4 { let exam = published(&db).await; let question = question_on(&exam, &db).await; let id = exam.get_id().clone(); - let student = a_person(&db, "student", "student").await; - // Delete and upsert released together: both write the exam row, so - // Postgres serializes them and refuses whichever lost. let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { - let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone()); + let (db, exam, gate) = (db.clone(), exam, gate.clone()); tokio::spawn(async move { gate.wait().await; delete(&db, exam).await @@ -1449,15 +1680,7 @@ mod tests { ); tokio::spawn(async move { gate.wait().await; - let image = AnswerImage::new( - &exam_id, - &on, - &student, - 1, - FileContentType::try_new("image/png").unwrap(), - 3, - ); - crate::db::answer_image::upsert(&db, image).await + draw(&db, &exam_id, &on, &student).await }) }; let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); @@ -1465,48 +1688,129 @@ mod tests { !matches!(child, Err(AppError::Db(_))), "round {round}: a raced drawing write must be answered, not 500: {child:?}" ); + assert!( + !matches!(drop_it, Err(AppError::Db(_))), + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" + ); if read(&db, &id).await.unwrap().is_none() { swept += 1; - drawings += crate::db::answer_image::list_for_exam(&db, &id) - .await - .unwrap() - .len(); + assert_eq!( + crate::db::answer_image::list_for_exam(&db, &id) + .await + .unwrap() + .len(), + 0, + "round {round}: a drawing outlived its exam" + ); } else if drop_it.is_ok() { panic!("round {round}: the delete reported success but the exam is still there"); } } - eprintln!("Exam::delete raced by a drawing write: {swept}/8 rounds deleted the exam"); - assert!( - swept > 0, - "no round ever deleted the exam, so the window was never reached" + eprintln!( + "Exam::delete raced by a drawing write: {swept}/4 concurrent rounds deleted the exam" ); - assert_eq!(drawings, 0, "a drawing outlived its exam"); } /// A picture is written through the same freeze gate as the question it /// hangs on, so it had the same hole — and one the row count does not even /// show: `delete_exam` collects the blob names to unlink *before* it calls - /// [`crate::db::exam::delete`], so an image row landing after that snapshot strands - /// its bytes on disk forever as well. It now rides the same exam-row write - /// the question does. + /// [`crate::db::exam::delete`], so an image row landing after that snapshot + /// strands its bytes on disk forever as well. It now rides the same + /// exam-row write the question does. Both orders are forced by awaiting + /// one side to completion before the other starts. Overlapped rounds may + /// all lose the delete; that is not a failure. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_picture_written_inside_a_delete_never_outlives_the_exam() { use crate::domain::note_file::FileContentType; use crate::domain::question_image::QuestionImage; let (db, _leases) = crate::database::init_test_db().await; - let (mut images, mut swept) = (0, 0); - for round in 0..8 { + async fn shoot( + db: &Database, + exam: &ExamId, + question: &crate::domain::exam_question::ExamQuestionId, + ) -> Result<(QuestionImage, Option), AppError> { + let image = QuestionImage::new( + exam, + question, + None, + FileContentType::try_new("image/png").unwrap(), + 3, + ); + crate::db::question_image::upsert(db, image).await + } + + // Delete-first: the exam is gone before the picture starts. + { + let exam = published(&db).await; + let question = question_on(&exam, &db).await; + let id = exam.get_id().clone(); + let on = question.get_id().clone(); + let dropped = delete(&db, exam).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "delete-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + read(&db, &id).await.unwrap().is_none(), + "delete-first: the exam is still there after delete: {dropped:?}" + ); + let child = shoot(&db, &id, &on).await; + assert!( + !matches!(child, Err(AppError::Db(_))), + "delete-first: a picture write must be answered, not 500: {child:?}" + ); + assert_eq!( + crate::db::question_image::list_for_exam(&db, &id) + .await + .unwrap() + .len(), + 0, + "a picture outlived its exam" + ); + } + + // Write-first: the picture lands, then the delete sweeps it. + { + let exam = published(&db).await; + let question = question_on(&exam, &db).await; + let id = exam.get_id().clone(); + let on = question.get_id().clone(); + let child = shoot(&db, &id, &on).await; + assert!( + child.is_ok(), + "write-first: the picture must land before the delete: {child:?}" + ); + let dropped = delete(&db, exam).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "write-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + read(&db, &id).await.unwrap().is_none(), + "write-first: the exam is still there" + ); + assert_eq!( + crate::db::question_image::list_for_exam(&db, &id) + .await + .unwrap() + .len(), + 0, + "a picture outlived its exam" + ); + } + + // Overlapped rounds. Delete may lose every one of them. + let mut swept = 0; + for round in 0..4 { let exam = published(&db).await; let question = question_on(&exam, &db).await; let id = exam.get_id().clone(); - // Delete and upsert released together: both write the exam row, so - // Postgres serializes them and refuses whichever lost. let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { - let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone()); + let (db, exam, gate) = (db.clone(), exam, gate.clone()); tokio::spawn(async move { gate.wait().await; delete(&db, exam).await @@ -1517,14 +1821,7 @@ mod tests { (db.clone(), id.clone(), question.get_id().clone(), gate); tokio::spawn(async move { gate.wait().await; - let image = QuestionImage::new( - &exam_id, - &on, - None, - FileContentType::try_new("image/png").unwrap(), - 3, - ); - crate::db::question_image::upsert(&db, image).await + shoot(&db, &exam_id, &on).await }) }; let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); @@ -1532,22 +1829,27 @@ mod tests { !matches!(child, Err(AppError::Db(_))), "round {round}: a raced picture write must be answered, not 500: {child:?}" ); + assert!( + !matches!(drop_it, Err(AppError::Db(_))), + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" + ); if read(&db, &id).await.unwrap().is_none() { swept += 1; - images += crate::db::question_image::list_for_exam(&db, &id) - .await - .unwrap() - .len(); + assert_eq!( + crate::db::question_image::list_for_exam(&db, &id) + .await + .unwrap() + .len(), + 0, + "round {round}: a picture outlived its exam" + ); } else if drop_it.is_ok() { panic!("round {round}: the delete reported success but the exam is still there"); } } - eprintln!("Exam::delete raced by a picture write: {swept}/8 rounds deleted the exam"); - assert!( - swept > 0, - "no round ever deleted the exam, so the window was never reached" + eprintln!( + "Exam::delete raced by a picture write: {swept}/4 concurrent rounds deleted the exam" ); - assert_eq!(images, 0, "a picture outlived its exam"); } } diff --git a/src/db/menu.rs b/src/db/menu.rs index d79aac4..010bc82 100644 --- a/src/db/menu.rs +++ b/src/db/menu.rs @@ -517,20 +517,114 @@ mod tests { /// The window the schema event used to force open is the menu row's own /// lock now: every child write also writes the menu row, so a child racing /// the delete serializes on that row instead of committing into a range - /// the sweep has already passed. A barrier start lets both orders happen; - /// the invariant must hold in each. + /// the sweep has already passed. Both orders are forced, for each child + /// kind, by awaiting one side to completion before the other starts. A + /// few rounds still start together; those may all lose the delete, and + /// that is not a failure. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_child_written_inside_a_delete_never_outlives_the_menu() { use crate::domain::menu_dish::DishDescription; let (db, _leases) = school().await; - let (mut dishes, mut marks, mut swept) = (0, 0, 0); - for round in 0..4 { - let menu = publish(&format!("2026-09-{:02}", round + 1), &db) + async fn write_child(db: &Database, id: &MenuId, dish: bool) -> Result<(), AppError> { + if dish { + menu_dish::create( + db, + id, + DishName::try_new("Pilav").unwrap(), + None::, + DishPrice::try_new(1).unwrap(), + DishTags::try_new(&[], &[]).unwrap(), + 1_000, + ) + .await + .map(|_| ()) + } else { + meal_attendance::mark( + db, + id, + &UserId::from_key(TEACHER), + MealAttendanceStatus::try_new("served").unwrap(), + &UserId::from_key(TEACHER), + ) .await - .unwrap(); + .map(|_| ()) + } + } + + async fn children(db: &Database, id: &MenuId) -> (usize, i64) { + ( + menu_dish::list_for_menu(db, id).await.unwrap().len(), + meal_attendance::list_for_menu(db, id, None, 0) + .await + .unwrap() + .1, + ) + } + + let mut day = 1u32; + // One child kind per round, never both: whichever wrote first forces + // the delete to re-send, and its second pass sweeps the other's row. + for dish in [true, false] { + let kind = if dish { "dish" } else { "mark" }; + + // Delete-first. + { + let menu = publish(&format!("2026-09-{day:02}"), &db).await.unwrap(); + day += 1; + let id = menu.get_id().clone(); + let dropped = delete(&db, menu).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "{kind} delete-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + read(&db, &id).await.unwrap().is_none(), + "{kind} delete-first: the menu is still there after delete: {dropped:?}" + ); + let child = write_child(&db, &id, dish).await; + assert!( + !matches!(child, Err(AppError::Db(_))), + "{kind} delete-first: a child write must be answered, not 500: {child:?}" + ); + let (dishes, marks) = children(&db, &id).await; + assert_eq!(dishes, 0, "a dish outlived its menu"); + assert_eq!(marks, 0, "a mark outlived its menu"); + } + + // Write-first. + { + let menu = publish(&format!("2026-09-{day:02}"), &db).await.unwrap(); + day += 1; + let id = menu.get_id().clone(); + let child = write_child(&db, &id, dish).await; + assert!( + child.is_ok(), + "{kind} write-first: the child must land before the delete: {child:?}" + ); + let dropped = delete(&db, menu).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "{kind} write-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + read(&db, &id).await.unwrap().is_none(), + "{kind} write-first: the menu is still there" + ); + let (dishes, marks) = children(&db, &id).await; + assert_eq!(dishes, 0, "a dish outlived its menu"); + assert_eq!(marks, 0, "a mark outlived its menu"); + } + } + + // Overlapped rounds. Delete may lose every one of them. + let mut swept = 0; + for round in 0..4 { + let menu = publish(&format!("2026-09-{day:02}"), &db).await.unwrap(); + day += 1; let id = menu.get_id().clone(); + let dish = round % 2 == 0; let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { @@ -540,64 +634,32 @@ mod tests { delete(&db, menu).await }) }; - // One child per round, never both: whichever wrote first forces the - // delete to re-send, and its second pass sweeps the other's row — - // which would mask exactly the defect this test exists to catch. let child = { - let (id, db, dish, gate) = (id.clone(), db.clone(), round % 2 == 0, gate); + let (id, db, gate) = (id.clone(), db.clone(), gate); tokio::spawn(async move { gate.wait().await; - if dish { - menu_dish::create( - &db, - &id, - DishName::try_new("Pilav").unwrap(), - None::, - DishPrice::try_new(1).unwrap(), - DishTags::try_new(&[], &[]).unwrap(), - 1_000, - ) - .await - .map(|_| ()) - } else { - meal_attendance::mark( - &db, - &id, - &UserId::from_key(TEACHER), - MealAttendanceStatus::try_new("served").unwrap(), - &UserId::from_key(TEACHER), - ) - .await - .map(|_| ()) - } + write_child(&db, &id, dish).await }) }; let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); - // A 404 for the child, or a 409/NotFound for the delete, is a - // correct answer — the only defect is stored state. assert!( !matches!(child, Err(AppError::Db(_))), "round {round}: a raced child write must be answered, not 500: {child:?}" ); + assert!( + !matches!(drop_it, Err(AppError::Db(_))), + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" + ); - // Stored state is the whole verdict; a return value is not evidence. if read(&db, &id).await.unwrap().is_none() { swept += 1; - dishes += menu_dish::list_for_menu(&db, &id).await.unwrap().len(); - marks += meal_attendance::list_for_menu(&db, &id, None, 0) - .await - .unwrap() - .1; + let (dishes, marks) = children(&db, &id).await; + assert_eq!(dishes, 0, "round {round}: a dish outlived its menu"); + assert_eq!(marks, 0, "round {round}: a mark outlived its menu"); } else if drop_it.is_ok() { panic!("round {round}: the delete reported success but the menu is still there"); } } - eprintln!("Menu::delete raced by its children: {swept}/4 rounds deleted the menu"); - assert!( - swept > 0, - "no round ever deleted the menu, so the window was never reached" - ); - assert_eq!(dishes, 0, "a dish outlived its menu"); - assert_eq!(marks, 0, "a mark outlived its menu"); + eprintln!("Menu::delete raced by its children: {swept}/4 concurrent rounds deleted the menu"); } } diff --git a/src/db/pool_question.rs b/src/db/pool_question.rs index a2edccf..05990cf 100644 --- a/src/db/pool_question.rs +++ b/src/db/pool_question.rs @@ -266,6 +266,7 @@ pub async fn clear_image( /// What [`delete`] took with the question: the rows ride back for their /// ids, and `image_files` is the caller's disk-GC list — the question's /// photo and every swept solution's. +#[derive(Debug)] pub struct Deleted { pub question: PoolQuestion, pub solutions: Vec, @@ -602,24 +603,93 @@ mod tests { /// [`bump_question_and_write`] moves the question's own `asked_at` /// instead, so the two transactions touch one key and the store refuses /// one of them. - /// /// The offer writes the question row too (its `solution_count`), so the - /// two transactions touch one row and Postgres refuses one of them; the - /// barrier releases both sides together so every interleaving gets its - /// chance. + /// two transactions touch one row and Postgres refuses one of them. + /// Both orders are forced by awaiting one side to completion before the + /// other starts. A barrier is a coin toss under load, and a run where the + /// delete loses every overlapped round has still proved the invariant. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_solution_offered_inside_a_delete_never_outlives_its_question() { let (db, _leases) = database::init_test_db().await; - let (mut solutions, mut swept, mut delete_500) = (0, 0, 0); - for round in 0..8 { + async fn offer( + db: &Database, + id: &PoolQuestionId, + helper: &UserId, + ) -> Result { + crate::db::solution::insert( + db, + Solution::new( + id, + helper, + SolutionBody::try_new("Kismi integrasyon uygula.").unwrap(), + ), + ) + .await + } + + async fn solutions(db: &Database, id: &PoolQuestionId) -> usize { + crate::db::solution::list_for(db, id, None, 0) + .await + .unwrap() + .0 + .len() + } + + // Delete-first: the question is gone before the offer starts. + { + let asker = a_user(&db).await; + let helper = a_user(&db).await; + let q = insert(&db, question(&asker)).await.unwrap(); + let id = *q.get_id(); + let dropped = delete(&db, &id).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "delete-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + read(&db, &id).await.unwrap().is_none(), + "delete-first: the question is still there after delete: {dropped:?}" + ); + let child = offer(&db, &id, &helper).await; + assert!( + !matches!(child, Err(AppError::Db(_))), + "delete-first: an offer must be answered, not 500: {child:?}" + ); + assert_eq!(solutions(&db, &id).await, 0, "a solution outlived its question"); + } + + // Write-first: the offer lands, then the delete sweeps it. + { + let asker = a_user(&db).await; + let helper = a_user(&db).await; + let q = insert(&db, question(&asker)).await.unwrap(); + let id = *q.get_id(); + let child = offer(&db, &id, &helper).await; + assert!( + child.is_ok(), + "write-first: the offer must land before the delete: {child:?}" + ); + let dropped = delete(&db, &id).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "write-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + read(&db, &id).await.unwrap().is_none(), + "write-first: the question is still there" + ); + assert_eq!(solutions(&db, &id).await, 0, "a solution outlived its question"); + } + + // Overlapped rounds. Delete may lose every one of them. + let mut swept = 0; + for round in 0..4 { let asker = a_user(&db).await; let helper = a_user(&db).await; let q = insert(&db, question(&asker)).await.unwrap(); let id = *q.get_id(); - // Delete and offer released together: both write the question row, - // so Postgres serializes them and refuses whichever lost. let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { let (db, id, gate) = (db.clone(), id, gate.clone()); @@ -632,45 +702,34 @@ mod tests { let (db, id, helper, gate) = (db.clone(), id, helper, gate); tokio::spawn(async move { gate.wait().await; - crate::db::solution::insert( - &db, - Solution::new( - &id, - &helper, - SolutionBody::try_new("Kismi integrasyon uygula.").unwrap(), - ), - ) - .await + offer(&db, &id, &helper).await }) }; let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); - // A 404 for the offer is a correct answer; the only defect is - // stored state. The delete must not 500 either — it contends with - // the offer by design and a lost round is re-sent, not reported. assert!( !matches!(child, Err(AppError::Db(_))), "round {round}: a raced offer must be answered, not 500: {child:?}" ); - if matches!(drop_it, Err(AppError::Db(_))) { - delete_500 += 1; - } + assert!( + !matches!(drop_it, Err(AppError::Db(_))), + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" + ); - // Stored state is the whole verdict; a return value is not evidence. if read(&db, &id).await.unwrap().is_none() { swept += 1; - solutions += crate::db::solution::list_for(&db, &id, None, 0) - .await - .unwrap() - .0 - .len(); + assert_eq!( + solutions(&db, &id).await, + 0, + "round {round}: a solution outlived its question" + ); + } else if drop_it.is_ok() { + panic!( + "round {round}: the delete reported success but the question is still there" + ); } } - eprintln!("pool_question::delete raced by an offer: {swept}/8 rounds deleted the question"); - assert!( - swept > 0, - "no round ever deleted the question, so the window was never reached" + eprintln!( + "pool_question::delete raced by an offer: {swept}/4 concurrent rounds deleted the question" ); - assert_eq!(solutions, 0, "a solution outlived its question"); - assert_eq!(delete_500, 0, "a raced delete must retry, not 500"); } } diff --git a/src/db/rag_thread.rs b/src/db/rag_thread.rs index e256b59..844b680 100644 --- a/src/db/rag_thread.rs +++ b/src/db/rag_thread.rs @@ -394,18 +394,84 @@ mod tests { /// /// The window the schema event used to force open is the thread row's own /// lock now: a turn is written *through* the row, so a turn racing the - /// delete serializes on that row instead of committing past the sweep. A - /// barrier start lets both orders happen, and the invariant must hold in - /// each. + /// delete serializes on that row instead of committing past the sweep. + /// Both orders are forced by awaiting one side to completion before the + /// other starts — a barrier is a coin toss under load, and a run where + /// the delete loses every overlapped round has still proved the invariant. + /// A few rounds still start together; those may all lose the delete, and + /// that is not a failure. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_turn_written_inside_a_delete_never_outlives_the_thread() { - // One thread minted per round: the cap must cover every round, since - // the rounds where the turn wins keep their thread (and its seat). - let (db, _leases) = a_user_capped_at(8).await; - + // Forced rounds free their seat. Concurrent rounds may keep theirs, so + // the cap covers every thread this test can leave standing. + let (db, _leases) = a_user_capped_at(6).await; let user = UserId::from_key(U); - let (mut orphans, mut swept) = (0, 0); - for round in 0..8 { + + async fn append(db: &Database, id: &RagThreadId, user: &UserId) -> Result<(), AppError> { + rag_message::append_user(db, id, user, RagContent::try_new("selam").unwrap()) + .await + .map(|_| ()) + } + + // Delete-first: the thread is gone before the turn starts. + { + let thread = create_capped(&db, &user, None).await.expect("thread"); + let id = thread.get_id().clone(); + let dropped = delete(&db, thread).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "delete-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + read_for(&db, &id, &user).await.unwrap().is_none(), + "delete-first: the thread is still there after delete: {dropped:?}" + ); + let turn = append(&db, &id, &user).await; + assert!( + !matches!(turn, Err(AppError::Db(_))), + "delete-first: a turn must be answered, not 500: {turn:?}" + ); + assert_eq!( + rag_message::list_for_thread(&db, &id, None, 0) + .await + .unwrap() + .1, + 0, + "a turn outlived its thread" + ); + } + + // Write-first: the turn lands, then the delete sweeps it. + { + let thread = create_capped(&db, &user, None).await.expect("thread"); + let id = thread.get_id().clone(); + let turn = append(&db, &id, &user).await; + assert!( + turn.is_ok(), + "write-first: the turn must land before the delete: {turn:?}" + ); + let dropped = delete(&db, thread).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "write-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + read_for(&db, &id, &user).await.unwrap().is_none(), + "write-first: the thread is still there" + ); + assert_eq!( + rag_message::list_for_thread(&db, &id, None, 0) + .await + .unwrap() + .1, + 0, + "a turn outlived its thread" + ); + } + + // Overlapped rounds. Delete may lose every one of them. + let mut swept = 0; + for round in 0..4 { let thread = create_capped(&db, &user, None).await.expect("thread"); let id = thread.get_id().clone(); @@ -421,40 +487,35 @@ mod tests { let (id, db, user, gate) = (id.clone(), db.clone(), user, gate); tokio::spawn(async move { gate.wait().await; - rag_message::append_user( - &db, - &id, - &user, - RagContent::try_new("selam").unwrap(), - ) - .await - .map(|_| ()) + append(&db, &id, &user).await }) }; let (drop_it, turn) = (drop_it.await.unwrap(), turn.await.unwrap()); - // A 404 for the turn, or a NotFound for the delete, is a correct - // answer — the only defect is stored state. assert!( !matches!(turn, Err(AppError::Db(_))), "round {round}: a raced turn must be answered, not 500: {turn:?}" ); + assert!( + !matches!(drop_it, Err(AppError::Db(_))), + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" + ); - // Stored state is the whole verdict; a return value is not evidence. if read_for(&db, &id, &user).await.unwrap().is_none() { swept += 1; - orphans += rag_message::list_for_thread(&db, &id, None, 0) - .await - .unwrap() - .1; + assert_eq!( + rag_message::list_for_thread(&db, &id, None, 0) + .await + .unwrap() + .1, + 0, + "round {round}: a turn outlived its thread" + ); } else if drop_it.is_ok() { panic!("round {round}: the delete reported success but the thread is still there"); } } - eprintln!("rag_thread::delete raced by a turn: {swept}/8 rounds deleted the thread"); - assert!( - swept > 0, - "no round ever deleted the thread, so the race never actually ran" + eprintln!( + "rag_thread::delete raced by a turn: {swept}/4 concurrent rounds deleted the thread" ); - assert_eq!(orphans, 0, "a turn outlived its thread"); } } diff --git a/src/db/session_attendance.rs b/src/db/session_attendance.rs index f32e8d5..13c3fc1 100644 --- a/src/db/session_attendance.rs +++ b/src/db/session_attendance.rs @@ -644,41 +644,108 @@ mod tests { /// The claim the existence gate cannot make by *reading*. The mark writes /// the session row too (its attendance stamp), so the delete and the mark - /// touch one row and Postgres refuses one of them; the barrier releases - /// both sides together so every interleaving gets its chance. + /// touch one row and Postgres refuses one of them. /// /// The two flavors raced are the ones the credit branch never wrote for — a /// lesson that has not begun, and a student with no row yet on a lesson - /// already counted. A re-mark of a row that *exists* was never in danger: - /// the cascade and the upsert write that child's own key and collide there. + /// already counted. Both orders are forced for each flavor by awaiting one + /// side to completion before the other starts. A few rounds still start + /// together; those may all lose the delete, and that is not a failure. /// Mutation-tested: dropping the unconditional session-row write from - /// `mark` turns it red. + /// `mark` turns the write-first rounds red. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_mark_written_inside_a_delete_never_outlives_the_session() { let (db, _leases) = crate::database::init_test_db().await; - let teacher = a_teacher("t", &db).await; - let (mut swept, mut orphans) = (0, 0); - for (round, already_counted) in [false, true, false, true, false, true, false, true] - .into_iter() - .enumerate() - { - let session = if already_counted { - // Counted by somebody else's mark, so this one credits nothing. - let session = a_session(&teacher, &db).await; - let first = a_student(&format!("f{round}"), &db).await; - mark(&db, &session, &first, status("present"), &teacher) + + async fn session_for( + db: &Database, + teacher: &UserId, + already_counted: bool, + label: &str, + ) -> CourseSession { + if already_counted { + let session = a_session(teacher, db).await; + let first = a_student(label, db).await; + mark(db, &session, &first, status("present"), teacher) .await .unwrap(); session } else { - a_session_at(&teacher, Timestamp::now().as_millis() + 604_800_000, &db).await - }; + a_session_at(teacher, Timestamp::now().as_millis() + 604_800_000, db).await + } + } + + for (flavor, already_counted) in [("fresh", false), ("counted", true)] { + // Delete-first. + { + let session = session_for(&db, &teacher, already_counted, &format!("df-{flavor}")) + .await; + let id = session.get_id().clone(); + let ghost = session.clone(); + let dropped = crate::db::course_session::delete(&db, session).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "{flavor} delete-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + crate::db::course_session::read(&db, &id) + .await + .unwrap() + .is_none(), + "{flavor} delete-first: the session is still there after delete: {dropped:?}" + ); + let student = a_student(&format!("df-s-{flavor}"), &db).await; + let marked = mark(&db, &ghost, &student, status("present"), &teacher).await; + assert!( + !matches!(marked, Err(AppError::Db(_))), + "{flavor} delete-first: a mark must be answered, not 500: {marked:?}" + ); + assert_eq!( + list_for_session(&db, &id, None, 0).await.unwrap().0.len(), + 0, + "a roll call outlived its session" + ); + } + + // Write-first. + { + let session = session_for(&db, &teacher, already_counted, &format!("wf-{flavor}")) + .await; + let id = session.get_id().clone(); + let student = a_student(&format!("wf-s-{flavor}"), &db).await; + let marked = mark(&db, &session, &student, status("present"), &teacher).await; + assert!( + marked.is_ok(), + "{flavor} write-first: the mark must land before the delete: {marked:?}" + ); + let dropped = crate::db::course_session::delete(&db, session).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "{flavor} write-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + crate::db::course_session::read(&db, &id) + .await + .unwrap() + .is_none(), + "{flavor} write-first: the session is still there" + ); + assert_eq!( + list_for_session(&db, &id, None, 0).await.unwrap().0.len(), + 0, + "a roll call outlived its session" + ); + } + } + + // Overlapped rounds. Delete may lose every one of them. + let mut swept = 0; + for (round, already_counted) in [false, true, false, true].into_iter().enumerate() { + let session = session_for(&db, &teacher, already_counted, &format!("c{round}")).await; let id = session.get_id().clone(); let ghost = session.clone(); - // Delete and mark released together: both write the session row, - // so Postgres serializes them and refuses whichever lost. let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { let (db, gate, session) = (db.clone(), gate.clone(), session); @@ -700,26 +767,30 @@ mod tests { !matches!(marked, Err(AppError::Db(_))), "round {round}: a raced mark must be answered, not 500: {marked:?}" ); + assert!( + !matches!(drop_it, Err(AppError::Db(_))), + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" + ); - // Stored state is the whole verdict; a return value is not evidence. if crate::db::course_session::read(&db, &id) .await .unwrap() .is_none() { swept += 1; - orphans += list_for_session(&db, &id, None, 0).await.unwrap().0.len(); + assert_eq!( + list_for_session(&db, &id, None, 0).await.unwrap().0.len(), + 0, + "round {round}: a roll call outlived its session" + ); } else if drop_it.is_ok() { - panic!("round {round}: the delete reported success but the session is still there"); + panic!( + "round {round}: the delete reported success but the session is still there" + ); } } eprintln!( - "CourseSession::delete raced by a roll call: {swept}/8 rounds deleted the session" - ); - assert!( - swept > 0, - "no round ever deleted the session, so the window was never reached" + "CourseSession::delete raced by a roll call: {swept}/4 concurrent rounds deleted the session" ); - assert_eq!(orphans, 0, "a roll call outlived its session"); } } diff --git a/src/service/class_course.rs b/src/service/class_course.rs index 635af25..2f2ced0 100644 --- a/src/service/class_course.rs +++ b/src/service/class_course.rs @@ -588,11 +588,86 @@ mod tests { /// still there lands on the very row `Course::delete`'s guard locks, so /// whatever the interleaving, a link row and a deleted course can never /// both stand. + /// + /// Both orders are forced. Delete-first awaits the delete, then the + /// attach: the course is gone and no link may appear. Attach-first awaits + /// the attach, then the delete: a course a class still teaches must + /// refuse, not 500, and the course stays. A 2ms head start does not force + /// that under pool contention. Overlapped rounds may all lose the delete; + /// that is not a failure. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_class_course_link_never_outlives_the_course() { let (db, _leases) = crate::database::init_test_db().await; let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; - let (mut orphans, mut swept, mut miscounted) = (0, 0, 0); + + // Delete-first: nothing may attach to a course that is already gone. + { + let class = a_class("9-df", &db).await; + let algebra = a_course("algebra-df", &db).await; + let course = crate::db::course::read(&db, &algebra) + .await + .unwrap() + .unwrap(); + let dropped = crate::db::course::delete(&db, course).await; + assert!( + matches!(dropped, Ok(true)), + "delete-first: an empty course must delete, not {dropped:?}" + ); + assert!( + !course_exists(&algebra, &db).await, + "delete-first: the course is still there" + ); + let child = attach(&db, &class, &algebra, &manager).await; + assert!( + !matches!(child, Err(AppError::Db(_))), + "delete-first: an attach must be answered, not 500: {child:?}" + ); + assert!( + !link_exists(&class, &algebra, &db).await, + "a class_course link outlived its course" + ); + assert_eq!( + counter("class_course_count", class.uuid(), &db).await, + 0, + "a class counts a course that is gone" + ); + } + + // Attach-first: the guard must refuse. Parent stays; that is the + // verdict, not a missed sweep. + { + let class = a_class("9-wf", &db).await; + let algebra = a_course("algebra-wf", &db).await; + let course = crate::db::course::read(&db, &algebra) + .await + .unwrap() + .unwrap(); + let child = attach(&db, &class, &algebra, &manager).await; + assert!( + child.is_ok(), + "attach-first: the attach must land before the delete: {child:?}" + ); + let dropped = crate::db::course::delete(&db, course).await; + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "attach-first: a delete must be answered, not 500: {dropped:?}" + ); + assert!( + matches!(dropped, Ok(false)), + "attach-first: a course a class still teaches must refuse, not {dropped:?}" + ); + assert!( + course_exists(&algebra, &db).await, + "attach-first: the refused delete removed the course" + ); + assert!( + link_exists(&class, &algebra, &db).await, + "attach-first: the landed link is gone" + ); + } + + // Overlapped rounds. Delete may lose every one of them. + let mut swept = 0; for round in 0..4 { let class = a_class(&format!("9-{round}"), &db).await; let algebra = a_course(&format!("algebra{round}"), &db).await; @@ -601,11 +676,9 @@ mod tests { .unwrap() .unwrap(); - // A barrier start covers every interleaving — the link row may - // never outlive the course in any of them. let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let drop_it = { - let (db, gate, course) = (db.clone(), gate.clone(), course.clone()); + let (db, gate, course) = (db.clone(), gate.clone(), course); tokio::spawn(async move { gate.wait().await; crate::db::course::delete(&db, course).await @@ -616,42 +689,36 @@ mod tests { (db.clone(), class.clone(), algebra.clone(), manager, gate); tokio::spawn(async move { gate.wait().await; - // Every other round the attach is held back a clear 2ms so - // the delete wins outright (`swept > 0` below is a coin - // toss without it): with the course counter claim live both - // sides write the very row the guard reads, so whichever is - // marginally faster otherwise takes every round under load. - if round % 2 == 0 { - tokio::time::sleep(std::time::Duration::from_millis(2)).await; - } attach(&db, &class, &algebra, &manager).await }) }; let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); - // A 404 for the attach, or a refusal for the delete, is a correct - // answer — the only defect is stored state. assert!( !matches!(child, Err(AppError::Db(_))), "round {round}: a raced attach must be answered, not 500: {child:?}" ); + assert!( + !matches!(drop_it, Err(AppError::Db(_))), + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" + ); - // Stored state is the whole verdict; a return value is not evidence. if !course_exists(&algebra, &db).await { swept += 1; - if link_exists(&class, &algebra, &db).await { - orphans += 1; - } - miscounted += counter("class_course_count", class.uuid(), &db).await; + assert!( + !link_exists(&class, &algebra, &db).await, + "round {round}: a class_course link outlived its course" + ); + assert_eq!( + counter("class_course_count", class.uuid(), &db).await, + 0, + "round {round}: a class counts a course that is gone" + ); } else if matches!(drop_it, Ok(true)) { panic!("round {round}: the delete reported success but the course is still there"); } } - eprintln!("Course::delete raced by an attach: {swept}/4 rounds deleted the course"); - assert!( - swept > 0, - "no round ever deleted the course, so the race never actually ran" + eprintln!( + "Course::delete raced by an attach: {swept}/4 concurrent rounds deleted the course" ); - assert_eq!(orphans, 0, "a class_course link outlived its course"); - assert_eq!(miscounted, 0, "a class counts a course that is gone"); } }