diff --git a/src/domain/chatbot_thread.rs b/src/domain/chatbot_thread.rs index bd2552b..409e2de 100644 --- a/src/domain/chatbot_thread.rs +++ b/src/domain/chatbot_thread.rs @@ -434,6 +434,77 @@ mod tests { ); } + /// The stamp moves **strictly upwards**, never to the clock — the property + /// the whole shape rests on, since an `UPDATE` that leaves the row + /// unchanged is elided, never reaches the store's write set, and so + /// collides with the racing delete not at all. + /// + /// The test above cannot see it: it compares one append against + /// `create_capped`, which costs a millisecond or so on its own, and a plain + /// `$now` clears that. Nor can a burst of appends — each is a transaction + /// of its own and takes about as long, so the clock has moved on by the + /// time the next one reads it. Timing cannot reach the window on demand. + /// + /// So the *state* the window produces is set up directly instead: a stamp + /// **ahead of the clock**, which is precisely what `math::max` leaves + /// behind (see [`touch_and_write`]) and therefore an ordinary row, not a + /// contrived one. From there the two rules are told apart with no race at + /// all — upwards keeps climbing off the stored value, the clock drags the + /// stamp back down to itself. The lead is a second, far more than two + /// writes can burn, and the guard below fails loudly rather than vacuously + /// on a machine that manages to burn it. + #[tokio::test] + async fn a_stamp_ahead_of_the_clock_still_climbs() { + use crate::domain::chatbot_message::{ChatContent, ChatbotMessage}; + + const LEAD: i64 = 1_000; + + let db = a_user_capped_at(1).await; + let user = UserId::from_key("u"); + let thread = ChatbotThread::create_capped(&user, None, &db) + .await + .expect("thread"); + + let parked = Timestamp::now().as_millis() + LEAD; + db.query("UPDATE $id SET updated_at = $parked") + .bind(("id", thread.get_id().record())) + .bind(("parked", parked)) + .await + .unwrap() + .check() + .unwrap(); + + for _ in 0..2 { + ChatbotMessage::append_user( + thread.get_id(), + &user, + ChatContent::try_new("selam").unwrap(), + &db, + ) + .await + .expect("append"); + } + let stamped = ChatbotThread::read_for(thread.get_id(), &user, &db) + .await + .expect("re-read") + .expect("still there") + .get_updated_at() + .as_millis(); + + assert!( + Timestamp::now().as_millis() < parked, + "the clock caught the {LEAD}ms lead up during two appends, so this \ + probe proves nothing" + ); + assert_eq!( + stamped, + parked + 2, + "two appends off a stamp of {parked} must leave {}: a stamp that \ + follows the clock instead is one an unchanged-row UPDATE elides", + parked + 2 + ); + } + /// No turn may survive the delete that swept its thread. An orphan is not /// litter: nothing sweeps `chatbot_message` afterwards, and both /// `GET /chatbot/threads/{id}/messages/{mid}` and its `/stream` answered diff --git a/tests/regress_course_delete.rs b/tests/regress_course_delete.rs new file mode 100644 index 0000000..b744184 --- /dev/null +++ b/tests/regress_course_delete.rs @@ -0,0 +1,130 @@ +//! A course delete must take every attempt under it with it — the same hole +//! `regress_exam_delete` pins one level down, and the same lease. +//! +//! `delete_course` cascades the course's exams *and their attempts*, and an +//! attempt is still the one exam child whose write cannot collide with that +//! sweep: its create rides `cap::claim_and_create` against the *student's* row, +//! which this cascade never touches. So the sweep and a start in flight can +//! both commit, and only `EXAM_LOCK.write()` keeps them apart. +//! +//! **Its own test binary on purpose.** `EXAM_LOCK` is process-wide, so this +//! test and `regress_exam_delete`'s share it across two unrelated databases +//! when they run in one binary: the neighbour holds the writer lease through +//! its own one-second window, the start here queues behind it, and the timeline +//! this test is built on stops holding. It was mutation-proven red alone and +//! green — on the *broken* code — beside that neighbour. Anything else added +//! here must not take `EXAM_LOCK` either. + +mod common; + +use axum::http::StatusCode; +use common::{app_and_db, create_exam_with, enroll, id_of, login_as, me_id, send, unenroll}; +use hezarfen_backend::domain::exam::ExamId; +use hezarfen_backend::domain::exam_attempt::ExamAttempt; +use serde_json::json; + +/// Reaching the window takes one move `regress_exam_delete` does not need, +/// because a course is refused while anyone is enrolled: the sitting has to +/// pass its enrollment gate and then lose that enrollment while it is still +/// being written. +/// +/// That also decides which side the window is opened on. It cannot be the +/// delete's, the way the exam test does it — by the time a course delete is +/// admitted the roster is empty, so a start fired into its window is answered +/// `403` by the enrollment gate and the test would pass on a missing lease. So +/// the *start* is held open instead: a `DEFINE EVENT` on `exam_attempt` fires +/// inside the create's own transaction, after every gate has been cleared, and +/// holds the start — and with it the writer lease — across the unenroll and the +/// delete that follow. That is exactly the pairing the lease exists to +/// serialize; without it the cascade sweeps attempts on a snapshot taken before +/// this one commits, and the sitting outlives both its exam and its course, +/// unreachable (every route to an attempt goes through its exam) with the +/// student's lifetime sitting counter up for good. +/// +/// The in-memory engine is enough, as it is next door: this asserts a *lock*, +/// not the store's conflict detection, and a mutex behaves the same on either +/// engine. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_attempt_started_inside_a_course_delete_never_outlives_it() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ogretmen_ders_sil", "teacher").await; + let student = login_as(&app, &db, "ogrenci_ders_sil", "student").await; + let student_id = me_id(&app, &student).await; + + // Hold the sitting's own write open for a full second, gates already + // passed, so the unenroll and the delete both land inside it. + db.query( + "DEFINE EVENT hold_the_start ON TABLE exam_attempt WHEN $event = 'CREATE' \ + THEN { SLEEP 1s; };", + ) + .await + .expect("define the window event") + .check() + .expect("check the window event"); + + let course = common::create_course(&app, &teacher, "Kimya").await; + enroll(&app, &teacher, &course, &student_id).await; + // `open` mode, as next door: an unscheduled exam answers the start with a + // 409 before it ever writes, and there would be no attempt to race. + let res = create_exam_with( + &app, + &teacher, + &course, + json!({ "title": "quiz", "kind": "midterm", "mode": "open" }), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "create exam"); + let exam = id_of(&res.body); + + let sit = { + let (app, student, exam) = (app.clone(), student.clone(), exam.clone()); + tokio::spawn(async move { + send( + &app, + "POST", + &format!("/exams/{exam}/attempt"), + Some(&student), + None, + ) + .await + }) + }; + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + // The enrollment goes while the sitting is mid-write — the only staging in + // which the delete is admitted at all. Without it this is a 409 and the + // race never happens. + unenroll(&app, &teacher, &course, &student_id).await; + let dropped = send( + &app, + "DELETE", + &format!("/courses/{course}"), + Some(&teacher), + None, + ) + .await; + let sat = sit.await.unwrap(); + + assert_eq!( + dropped.status, + StatusCode::NO_CONTENT, + "the delete must succeed: {:?}", + dropped.body + ); + // A 404 for the start is a correct answer too; the only defect is stored + // state. Nothing may 500 either way. + assert!( + sat.status == StatusCode::NOT_FOUND || sat.status.is_success(), + "a raced start must be answered, not {}: {:?}", + sat.status, + sat.body + ); + // Stored state is the whole verdict; a response code is not evidence. + assert_eq!( + ExamAttempt::list_for_exam(&ExamId::from_key(&exam), &db) + .await + .unwrap() + .len(), + 0, + "a sitting outlived the course it was sat under" + ); +}