🧪 pin the two fixes no mutation could reach
Browse files at this commit12f2280e63d8ca29122df9a2175e20cdaba26b64Parent: 2e0b57a- test
- 🧪 pin the two fixes no mutation could reach
2 changed files +201 -0
- src/domain/chatbot_thread.rs +71 -0
- tests/regress_course_delete.rs +130 -0
src/domain/chatbot_thread.rsmodified+71 -0
| @@ -434,6 +434,77 @@ mod tests { | |||
| 434 | ); | 434 | ); |
| 435 | } | 435 | } |
| 436 | 436 | ||
| 437 | + /// The stamp moves **strictly upwards**, never to the clock — the property | ||
| 438 | + /// the whole shape rests on, since an `UPDATE` that leaves the row | ||
| 439 | + /// unchanged is elided, never reaches the store's write set, and so | ||
| 440 | + /// collides with the racing delete not at all. | ||
| 441 | + /// | ||
| 442 | + /// The test above cannot see it: it compares one append against | ||
| 443 | + /// `create_capped`, which costs a millisecond or so on its own, and a plain | ||
| 444 | + /// `$now` clears that. Nor can a burst of appends — each is a transaction | ||
| 445 | + /// of its own and takes about as long, so the clock has moved on by the | ||
| 446 | + /// time the next one reads it. Timing cannot reach the window on demand. | ||
| 447 | + /// | ||
| 448 | + /// So the *state* the window produces is set up directly instead: a stamp | ||
| 449 | + /// **ahead of the clock**, which is precisely what `math::max` leaves | ||
| 450 | + /// behind (see [`touch_and_write`]) and therefore an ordinary row, not a | ||
| 451 | + /// contrived one. From there the two rules are told apart with no race at | ||
| 452 | + /// all — upwards keeps climbing off the stored value, the clock drags the | ||
| 453 | + /// stamp back down to itself. The lead is a second, far more than two | ||
| 454 | + /// writes can burn, and the guard below fails loudly rather than vacuously | ||
| 455 | + /// on a machine that manages to burn it. | ||
| 456 | + #[tokio::test] | ||
| 457 | + async fn a_stamp_ahead_of_the_clock_still_climbs() { | ||
| 458 | + use crate::domain::chatbot_message::{ChatContent, ChatbotMessage}; | ||
| 459 | + | ||
| 460 | + const LEAD: i64 = 1_000; | ||
| 461 | + | ||
| 462 | + let db = a_user_capped_at(1).await; | ||
| 463 | + let user = UserId::from_key("u"); | ||
| 464 | + let thread = ChatbotThread::create_capped(&user, None, &db) | ||
| 465 | + .await | ||
| 466 | + .expect("thread"); | ||
| 467 | + | ||
| 468 | + let parked = Timestamp::now().as_millis() + LEAD; | ||
| 469 | + db.query("UPDATE $id SET updated_at = $parked") | ||
| 470 | + .bind(("id", thread.get_id().record())) | ||
| 471 | + .bind(("parked", parked)) | ||
| 472 | + .await | ||
| 473 | + .unwrap() | ||
| 474 | + .check() | ||
| 475 | + .unwrap(); | ||
| 476 | + | ||
| 477 | + for _ in 0..2 { | ||
| 478 | + ChatbotMessage::append_user( | ||
| 479 | + thread.get_id(), | ||
| 480 | + &user, | ||
| 481 | + ChatContent::try_new("selam").unwrap(), | ||
| 482 | + &db, | ||
| 483 | + ) | ||
| 484 | + .await | ||
| 485 | + .expect("append"); | ||
| 486 | + } | ||
| 487 | + let stamped = ChatbotThread::read_for(thread.get_id(), &user, &db) | ||
| 488 | + .await | ||
| 489 | + .expect("re-read") | ||
| 490 | + .expect("still there") | ||
| 491 | + .get_updated_at() | ||
| 492 | + .as_millis(); | ||
| 493 | + | ||
| 494 | + assert!( | ||
| 495 | + Timestamp::now().as_millis() < parked, | ||
| 496 | + "the clock caught the {LEAD}ms lead up during two appends, so this \ | ||
| 497 | + probe proves nothing" | ||
| 498 | + ); | ||
| 499 | + assert_eq!( | ||
| 500 | + stamped, | ||
| 501 | + parked + 2, | ||
| 502 | + "two appends off a stamp of {parked} must leave {}: a stamp that \ | ||
| 503 | + follows the clock instead is one an unchanged-row UPDATE elides", | ||
| 504 | + parked + 2 | ||
| 505 | + ); | ||
| 506 | + } | ||
| 507 | + | ||
| 437 | /// No turn may survive the delete that swept its thread. An orphan is not | 508 | /// No turn may survive the delete that swept its thread. An orphan is not |
| 438 | /// litter: nothing sweeps `chatbot_message` afterwards, and both | 509 | /// litter: nothing sweeps `chatbot_message` afterwards, and both |
| 439 | /// `GET /chatbot/threads/{id}/messages/{mid}` and its `/stream` answered | 510 | /// `GET /chatbot/threads/{id}/messages/{mid}` and its `/stream` answered |
tests/regress_course_delete.rsadded+130 -0
| @@ -0,0 +1,130 @@ | |||
| 1 | +//! A course delete must take every attempt under it with it — the same hole | ||
| 2 | +//! `regress_exam_delete` pins one level down, and the same lease. | ||
| 3 | +//! | ||
| 4 | +//! `delete_course` cascades the course's exams *and their attempts*, and an | ||
| 5 | +//! attempt is still the one exam child whose write cannot collide with that | ||
| 6 | +//! sweep: its create rides `cap::claim_and_create` against the *student's* row, | ||
| 7 | +//! which this cascade never touches. So the sweep and a start in flight can | ||
| 8 | +//! both commit, and only `EXAM_LOCK.write()` keeps them apart. | ||
| 9 | +//! | ||
| 10 | +//! **Its own test binary on purpose.** `EXAM_LOCK` is process-wide, so this | ||
| 11 | +//! test and `regress_exam_delete`'s share it across two unrelated databases | ||
| 12 | +//! when they run in one binary: the neighbour holds the writer lease through | ||
| 13 | +//! its own one-second window, the start here queues behind it, and the timeline | ||
| 14 | +//! this test is built on stops holding. It was mutation-proven red alone and | ||
| 15 | +//! green — on the *broken* code — beside that neighbour. Anything else added | ||
| 16 | +//! here must not take `EXAM_LOCK` either. | ||
| 17 | + | ||
| 18 | +mod common; | ||
| 19 | + | ||
| 20 | +use axum::http::StatusCode; | ||
| 21 | +use common::{app_and_db, create_exam_with, enroll, id_of, login_as, me_id, send, unenroll}; | ||
| 22 | +use hezarfen_backend::domain::exam::ExamId; | ||
| 23 | +use hezarfen_backend::domain::exam_attempt::ExamAttempt; | ||
| 24 | +use serde_json::json; | ||
| 25 | + | ||
| 26 | +/// Reaching the window takes one move `regress_exam_delete` does not need, | ||
| 27 | +/// because a course is refused while anyone is enrolled: the sitting has to | ||
| 28 | +/// pass its enrollment gate and then lose that enrollment while it is still | ||
| 29 | +/// being written. | ||
| 30 | +/// | ||
| 31 | +/// That also decides which side the window is opened on. It cannot be the | ||
| 32 | +/// delete's, the way the exam test does it — by the time a course delete is | ||
| 33 | +/// admitted the roster is empty, so a start fired into its window is answered | ||
| 34 | +/// `403` by the enrollment gate and the test would pass on a missing lease. So | ||
| 35 | +/// the *start* is held open instead: a `DEFINE EVENT` on `exam_attempt` fires | ||
| 36 | +/// inside the create's own transaction, after every gate has been cleared, and | ||
| 37 | +/// holds the start — and with it the writer lease — across the unenroll and the | ||
| 38 | +/// delete that follow. That is exactly the pairing the lease exists to | ||
| 39 | +/// serialize; without it the cascade sweeps attempts on a snapshot taken before | ||
| 40 | +/// this one commits, and the sitting outlives both its exam and its course, | ||
| 41 | +/// unreachable (every route to an attempt goes through its exam) with the | ||
| 42 | +/// student's lifetime sitting counter up for good. | ||
| 43 | +/// | ||
| 44 | +/// The in-memory engine is enough, as it is next door: this asserts a *lock*, | ||
| 45 | +/// not the store's conflict detection, and a mutex behaves the same on either | ||
| 46 | +/// engine. | ||
| 47 | +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 48 | +async fn an_attempt_started_inside_a_course_delete_never_outlives_it() { | ||
| 49 | + let (app, db) = app_and_db().await; | ||
| 50 | + let teacher = login_as(&app, &db, "ogretmen_ders_sil", "teacher").await; | ||
| 51 | + let student = login_as(&app, &db, "ogrenci_ders_sil", "student").await; | ||
| 52 | + let student_id = me_id(&app, &student).await; | ||
| 53 | + | ||
| 54 | + // Hold the sitting's own write open for a full second, gates already | ||
| 55 | + // passed, so the unenroll and the delete both land inside it. | ||
| 56 | + db.query( | ||
| 57 | + "DEFINE EVENT hold_the_start ON TABLE exam_attempt WHEN $event = 'CREATE' \ | ||
| 58 | + THEN { SLEEP 1s; };", | ||
| 59 | + ) | ||
| 60 | + .await | ||
| 61 | + .expect("define the window event") | ||
| 62 | + .check() | ||
| 63 | + .expect("check the window event"); | ||
| 64 | + | ||
| 65 | + let course = common::create_course(&app, &teacher, "Kimya").await; | ||
| 66 | + enroll(&app, &teacher, &course, &student_id).await; | ||
| 67 | + // `open` mode, as next door: an unscheduled exam answers the start with a | ||
| 68 | + // 409 before it ever writes, and there would be no attempt to race. | ||
| 69 | + let res = create_exam_with( | ||
| 70 | + &app, | ||
| 71 | + &teacher, | ||
| 72 | + &course, | ||
| 73 | + json!({ "title": "quiz", "kind": "midterm", "mode": "open" }), | ||
| 74 | + ) | ||
| 75 | + .await; | ||
| 76 | + assert_eq!(res.status, StatusCode::CREATED, "create exam"); | ||
| 77 | + let exam = id_of(&res.body); | ||
| 78 | + | ||
| 79 | + let sit = { | ||
| 80 | + let (app, student, exam) = (app.clone(), student.clone(), exam.clone()); | ||
| 81 | + tokio::spawn(async move { | ||
| 82 | + send( | ||
| 83 | + &app, | ||
| 84 | + "POST", | ||
| 85 | + &format!("/exams/{exam}/attempt"), | ||
| 86 | + Some(&student), | ||
| 87 | + None, | ||
| 88 | + ) | ||
| 89 | + .await | ||
| 90 | + }) | ||
| 91 | + }; | ||
| 92 | + tokio::time::sleep(std::time::Duration::from_millis(300)).await; | ||
| 93 | + // The enrollment goes while the sitting is mid-write — the only staging in | ||
| 94 | + // which the delete is admitted at all. Without it this is a 409 and the | ||
| 95 | + // race never happens. | ||
| 96 | + unenroll(&app, &teacher, &course, &student_id).await; | ||
| 97 | + let dropped = send( | ||
| 98 | + &app, | ||
| 99 | + "DELETE", | ||
| 100 | + &format!("/courses/{course}"), | ||
| 101 | + Some(&teacher), | ||
| 102 | + None, | ||
| 103 | + ) | ||
| 104 | + .await; | ||
| 105 | + let sat = sit.await.unwrap(); | ||
| 106 | + | ||
| 107 | + assert_eq!( | ||
| 108 | + dropped.status, | ||
| 109 | + StatusCode::NO_CONTENT, | ||
| 110 | + "the delete must succeed: {:?}", | ||
| 111 | + dropped.body | ||
| 112 | + ); | ||
| 113 | + // A 404 for the start is a correct answer too; the only defect is stored | ||
| 114 | + // state. Nothing may 500 either way. | ||
| 115 | + assert!( | ||
| 116 | + sat.status == StatusCode::NOT_FOUND || sat.status.is_success(), | ||
| 117 | + "a raced start must be answered, not {}: {:?}", | ||
| 118 | + sat.status, | ||
| 119 | + sat.body | ||
| 120 | + ); | ||
| 121 | + // Stored state is the whole verdict; a response code is not evidence. | ||
| 122 | + assert_eq!( | ||
| 123 | + ExamAttempt::list_for_exam(&ExamId::from_key(&exam), &db) | ||
| 124 | + .await | ||
| 125 | + .unwrap() | ||
| 126 | + .len(), | ||
| 127 | + 0, | ||
| 128 | + "a sitting outlived the course it was sat under" | ||
| 129 | + ); | ||
| 130 | +} | ||