From 33b46b1cdb411eb570a40ee237830fd9a249b4e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 5 Aug 2026 21:04:51 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=8B=20fix:=20make=20an=20attendance=20?= =?UTF-8?q?mark=20collide=20with=20its=20parent's=20delete?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SessionAttendance::mark proved its session by reading it; the only write to that row was conditional and never fired for a future-dated lesson or for a new student on an already-counted one. f12af3a closed only the sequential order, and the regression test drove exactly that order, so it passed over the live hole. The parent touch is now unconditional. Attendance::mark had no event-existence gate at all — a bare upsert. It now claims the event row, which is both the gate and the collision. Event::delete moves to transaction_with_retry: once the mark claims the event row, the delete is the side that loses and would otherwise 500. Real-server measurement: read-only gate 4/4 orphans, write claim 0/4. --- src/domain/attendance.rs | 152 ++++++++++++++++++++-- src/domain/event.rs | 33 +++-- src/domain/session_attendance.rs | 110 +++++++++++++++- tests/regress_attendance.rs | 209 ++++++++++++++++++++++++++++++- 4 files changed, 486 insertions(+), 18 deletions(-) diff --git a/src/domain/attendance.rs b/src/domain/attendance.rs index 161d3f3..efcc410 100644 --- a/src/domain/attendance.rs +++ b/src/domain/attendance.rs @@ -1,7 +1,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::ATTENDANCE_TABLE; -use crate::database::Database; +use crate::constant::{ATTENDANCE_TABLE, REGISTRATION_COUNT_FIELD}; +use crate::database::{Database, transaction_with_retry}; use crate::domain::event::EventId; use crate::domain::page::PagedList; use crate::domain::user::UserId; @@ -91,6 +91,25 @@ impl Attendance { /// user), keyed by a deterministic composite id so this is a single atomic /// UPSERT — concurrent marks for the same pair can no longer both insert and /// collide on the unique index (a 500); they converge on the one row. + /// + /// The event's existence is proved *inside* the write, the twin of the gate + /// in [`crate::domain::session_attendance::SessionAttendance::mark`]: the + /// handler's event read sits several round trips in front of this, so a + /// bare upsert left a mark on an event [`crate::domain::event::Event`]'s + /// cascade (`DELETE attendance WHERE event = $ev`) had already swept — + /// counted forever in `GET /attendance/{user}` on an event no page shows. + /// Reading the event here would not have closed it either: SurrealDB 3.2.3 + /// conflict-checks write sets, not read sets, so the proof has to *move* a + /// value on the event row. It is the bump-and-restore of + /// [`crate::domain::exam_answer::ExamAnswer::save`], on the counter the + /// event already carries: matching nothing is the existence gate, writing + /// the key the delete removes is the collision, and the restore is by + /// captured value (`NONE` included) so no seat is spent or freed. + /// + /// Admissible for [`transaction_with_retry`]: no statement can answer + /// "already exists" — the `UPSERT`'s composite id is bijective with the + /// `attendance_event_user` unique tuple, so it resolves onto the row it + /// names instead of colliding with it. pub async fn mark( event: &EventId, user: &UserId, @@ -105,11 +124,45 @@ impl Attendance { status, marked_by: marked_by.clone(), }; - let saved: Option = db - .upsert(attendance.id.record()) - .content(attendance) - .await?; - saved.ok_or_else(|| AppError::Internal("failed to mark attendance".into())) + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $was = (SELECT VALUE {REGISTRATION_COUNT_FIELD} FROM ONLY $ev); + LET $alive = (UPDATE $ev SET {REGISTRATION_COUNT_FIELD} = + ({REGISTRATION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); + IF array::len($alive) = 0 {{ THROW 'event_missing' }}; + UPDATE $ev SET {REGISTRATION_COUNT_FIELD} = $was; + LET $after = (UPSERT $id CONTENT $row RETURN AFTER); + RETURN $after; + COMMIT TRANSACTION;" + ), + &[ + ("ev".into(), event.record().into_value()), + ("id".into(), attendance.id.record().into_value()), + ("row".into(), attendance.into_value()), + ], + &["event_missing"], + ) + .await?; + // An aborted transaction errors every slot and only the THROW's own + // slot names the marker. + if errors + .values() + .any(|error| error.to_string().contains("event_missing")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is always the last statement before `COMMIT`. + let slot = result.num_statements().saturating_sub(2); + result + .take::>(slot)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to mark attendance".into())) } pub async fn list_for_event( @@ -177,4 +230,89 @@ mod tests { .collect(); assert!(AttendanceStatus::try_new("online", &extended).is_ok()); } + + /// The session twin's race, one table over + /// ([`crate::domain::session_attendance::SessionAttendance`]): a + /// `DEFINE EVENT` on `event` fires inside the delete's own transaction, and + /// [`Event::delete`] sweeps its attendance rows before removing the row, so + /// the `SLEEP` lands exactly between the sweep and the commit — the window + /// where a bare upsert wrote a mark nothing would ever sweep again. + /// + /// Real server, and `#[ignore]`d for it: the subject is the store's + /// conflict detection, which `init_mem`'s embedded engine does not have — + /// it commits both writes and answers `Ok` to each, so this passes there on + /// broken code. Mutation-tested: turning the claim back into a read + /// (`SELECT VALUE id FROM $ev`) turns it red. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_mark_written_inside_a_delete_never_outlives_the_event() { + use crate::domain::event::{Event, EventAudience, EventDescription, EventTitle}; + let (db, _serialized) = crate::database::init_test_server("event_attendance_race").await; + db.query( + "DEFINE EVENT hold_the_window ON TABLE event WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let allowed: Vec = crate::domain::settings::Settings::defaults() + .get_attendance_statuses() + .to_vec(); + let marker = UserId::from_key("t"); + let (mut swept, mut orphans) = (0, 0); + for round in 0..4 { + let event = Event::create( + &marker, + EventTitle::try_new("gezi").unwrap(), + EventDescription::try_new("").unwrap(), + EventAudience::School, + None, + None, + &db, + ) + .await + .unwrap(); + let id = event.get_id().clone(); + let drop_it = { + let db = db.clone(); + tokio::spawn(async move { event.delete(&db).await }) + }; + // The mark starts inside the held window: the sweep has run and the + // event row is gone but uncommitted. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let marked = { + let (db, id, marker) = (db.clone(), id.clone(), marker.clone()); + let student = UserId::from_key(&format!("s{round}")); + let status = AttendanceStatus::try_new("present", &allowed).unwrap(); + tokio::spawn( + async move { Attendance::mark(&id, &student, status, &marker, &db).await }, + ) + }; + let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap()); + assert!( + !matches!(marked, Err(AppError::Db(_))), + "round {round}: a raced mark must be answered, not 500: {marked:?}" + ); + + // Stored state is the whole verdict; a return value is not evidence. + if Event::read(&id, &db).await.unwrap().is_none() { + swept += 1; + orphans += Attendance::list_for_event(&id, None, 0, &db) + .await + .unwrap() + .0 + .len(); + } 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}/4 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"); + } } diff --git a/src/domain/event.rs b/src/domain/event.rs index 2dc6e09..df4cbd7 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -3,7 +3,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; -use crate::database::Database; +use crate::database::{Database, transaction_with_retry}; use crate::domain::class_group::ClassGroupId; use crate::domain::class_member::{ClassMember, ClassMemberId}; use crate::domain::course::CourseId; @@ -315,21 +315,36 @@ impl Event { /// registration or a mark that committed in between outlived its event — /// an orphan no read path can ever reach and no delete can ever reclaim, /// since every one of them is keyed on the event that is now gone. + /// + /// Re-sent while the store answers "conflict, retry", the way + /// [`crate::domain::course_session::CourseSession::delete`] is: now that + /// [`crate::domain::attendance::Attendance::mark`] writes the event row to + /// prove it exists, a mark landing in this window really does contend for + /// it — and without the retry the *delete* is the side that loses, turning + /// a race the store resolved correctly into a 500 (measured 4 rounds in 4). + /// Admissible: every statement is a `DELETE`, which can never answer + /// "already exists", and a lost round wrote nothing. pub async fn delete(self, db: &Database) -> Result { - let mut result = db - .query( - "BEGIN TRANSACTION; + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; DELETE attendance WHERE event = $ev; DELETE registration WHERE event = $ev; LET $gone = (DELETE $ev RETURN BEFORE); RETURN $gone; COMMIT TRANSACTION;", - ) - .bind(("ev", self.id.record())) - .await? - .check()?; + &[("ev".into(), self.id.record().into_value())], + // No THROW of its own — an unconditional cascade. + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Read through the trailing `RETURN`, never a hand-counted slot. + let slot = result.num_statements().saturating_sub(2); result - .take::>(4)? + .take::>(slot)? .into_iter() .next() .ok_or(AppError::NotFound) diff --git a/src/domain/session_attendance.rs b/src/domain/session_attendance.rs index e05f026..73818cf 100644 --- a/src/domain/session_attendance.rs +++ b/src/domain/session_attendance.rs @@ -111,6 +111,22 @@ impl SessionAttendance { /// as `id` did — because the counter below needs that teacher anyway, and /// one read serves both. /// + /// A read is not a claim, though: SurrealDB 3.2.3 conflict-checks write + /// sets, not read sets, so that gate alone only closes the *sequential* + /// order (delete committed, then the mark arrives). To make the two really + /// collide, this transaction also *writes* the session row, unconditionally + /// — the bump-and-restore of [`crate::domain::exam_answer::ExamAnswer::save`] + /// on the one column this write already owns, [`LESSON_COUNTED_AT_FIELD`]. + /// Unconditional is the whole point: the credit branch below writes that + /// column already, but it fires only for the first roll call of a lesson + /// that has begun, so a future-dated sheet and every re-mark of a counted + /// one touched nothing at all and committed happily beside + /// `DELETE /sessions/{id}`. Re-stating the value verbatim would not do + /// either — an `UPDATE` that leaves the document unchanged is elided and + /// never enters the write set — hence bump first, then either stamp + /// (credit branch) or put back exactly what was found, `NONE` included, so + /// the row is byte-identical and the once-per-lesson rule is untouched. + /// /// Sound to re-send while the store answers "conflict, retry": the gate /// reads the record a delete writes, so the two contend by design, and the /// UPSERT cannot legitimately answer "already exists" — its composite id is @@ -200,10 +216,13 @@ impl SessionAttendance { UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) + $delta, 0]) }}; + UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = ({LESSON_COUNTED_AT_FIELD} ?? 0) + 1; IF ($counted IS NONE) AND $begun {{ UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $stamp; UPDATE $teacher SET {LESSONS_HELD_TOTAL_FIELD} = ({LESSONS_HELD_TOTAL_FIELD} ?? 0) + 1 + }} ELSE {{ + UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $counted }}; RETURN $after; COMMIT TRANSACTION;" @@ -366,7 +385,7 @@ mod tests { async fn a_session_at(teacher: &UserId, starts_at: i64, db: &Database) -> CourseSession { CourseSession::create( - &CourseId::from_key("c"), + &crate::domain::course::a_test_course(db).await, teacher, SessionTopic::try_new("limits").unwrap(), Timestamp::from_millis(starts_at), @@ -668,4 +687,93 @@ mod tests { assert_eq!(attended(&student, &db).await, 0); assert_eq!(held(&teacher, &db).await, 0, "a refused mark held a lesson"); } + + /// The claim the existence gate cannot make by *reading*. A `DEFINE EVENT` + /// on `course_session` fires inside the delete's own transaction, and + /// [`CourseSession::delete`] sweeps its children before removing the row, + /// so the `SLEEP` opens exactly the window a mark has to lose: the sheet is + /// written after the sweep has run, and used to commit straight past it. + /// + /// 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. + /// + /// Real server, and `#[ignore]`d for it: the subject is the store's + /// conflict detection, which [`init_mem`]'s embedded engine does not have — + /// it commits both writes and answers `Ok` to each, so this passes there on + /// broken code. Mutation-tested: dropping the unconditional + /// `UPDATE $sess` from `mark` turns it red. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_mark_written_inside_a_delete_never_outlives_the_session() { + let (db, _serialized) = crate::database::init_test_server("session_attendance_race").await; + db.query( + "DEFINE EVENT hold_the_window ON TABLE course_session WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let teacher = a_teacher("t", &db).await; + let (mut swept, mut orphans) = (0, 0); + for (round, already_counted) in [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; + SessionAttendance::mark(&session, &first, status("present"), &teacher, &db) + .await + .unwrap(); + session + } else { + a_session_at(&teacher, Timestamp::now().as_millis() + 604_800_000, &db).await + }; + let id = session.get_id().clone(); + let ghost = session.clone(); + let drop_it = { + let db = db.clone(); + tokio::spawn(async move { session.delete(&db).await }) + }; + // The mark starts inside the held window: the sweep has run and the + // session row is gone but uncommitted — which is exactly what a + // read of that session still believes. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let marked = { + let (db, teacher) = (db.clone(), teacher.clone()); + let student = a_student(&format!("s{round}"), &db).await; + tokio::spawn(async move { + SessionAttendance::mark(&ghost, &student, status("present"), &teacher, &db) + .await + }) + }; + let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap()); + assert!( + !matches!(marked, Err(AppError::Db(_))), + "round {round}: a raced mark must be answered, not 500: {marked:?}" + ); + + // Stored state is the whole verdict; a return value is not evidence. + if CourseSession::read(&id, &db).await.unwrap().is_none() { + swept += 1; + orphans += SessionAttendance::list_for_session(&id, None, 0, &db) + .await + .unwrap() + .0 + .len(); + } else if drop_it.is_ok() { + panic!("round {round}: the delete reported success but the session is still there"); + } + } + eprintln!( + "CourseSession::delete raced by a roll call: {swept}/4 rounds deleted the session" + ); + assert!( + swept > 0, + "no round ever deleted the session, so the window was never reached" + ); + assert_eq!(orphans, 0, "a roll call outlived its session"); + } } diff --git a/tests/regress_attendance.rs b/tests/regress_attendance.rs index e08d497..8144b9e 100644 --- a/tests/regress_attendance.rs +++ b/tests/regress_attendance.rs @@ -12,8 +12,10 @@ mod common; use axum::http::StatusCode; use common::{app_and_db, create_course, create_session, enroll, login, login_as, me_id, send}; -use hezarfen_backend::domain::attendance::AttendanceStatus; +use hezarfen_backend::database::Database; +use hezarfen_backend::domain::attendance::{Attendance, AttendanceStatus}; use hezarfen_backend::domain::course_session::{CourseSession, CourseSessionId}; +use hezarfen_backend::domain::event::EventId; use hezarfen_backend::domain::session_attendance::SessionAttendance; use hezarfen_backend::domain::settings::Settings; use hezarfen_backend::domain::timestamp::Timestamp; @@ -25,6 +27,43 @@ fn soon() -> i64 { Timestamp::now().as_millis() + 3_600_000 } +/// Count writes to `table` from *inside* the writing transaction: a +/// `DEFINE EVENT` on it fires within that write, so a parent row a mark never +/// touches shows up here as a zero. That zero is the whole defect class — +/// SurrealDB 3.2.3 conflict-checks write sets, not read sets, so a parent this +/// transaction only *reads* is a parent whose concurrent delete it can never +/// collide with, and the mark commits as an orphan. +/// +/// The collision itself is not testable on the in-memory engine (it commits +/// both writes and answers `Ok` to each — see +/// `crate::database::init_test_server`); the raced halves live beside the +/// domain code, `#[ignore]`d. What runs here, always, is the precondition +/// those races need: the parent is written at all. +async fn watch_writes_to(table: &str, db: &Database) { + db.query(format!( + "DEFINE EVENT parent_touch ON TABLE {table} WHEN $event = 'UPDATE' THEN {{ + UPSERT type::record('parent_write_probe', 'n') SET n = (n ?? 0) + 1; + }}; + UPSERT type::record('parent_write_probe', 'n') SET n = 0;" + )) + .await + .unwrap() + .check() + .unwrap(); +} + +/// How many parent writes the probe has seen so far. +async fn writes_seen(db: &Database) -> i64 { + db.query("SELECT VALUE n FROM parent_write_probe:n") + .await + .unwrap() + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap_or(0) +} + /// A staff roll-call row is management's to write *and* to remove. The removal /// gate used to ask "is the target the session's teacher?", which a teacher /// reassignment falsifies: once the session moved to T2, the row T1 holds is no @@ -132,6 +171,11 @@ async fn reassigning_the_teacher_does_not_unlock_the_old_teachers_staff_row() { /// was unremovable, its only delete route 404ing on the vanished session while /// `GET /attendance/{user}` counted it forever. The existence gate now rides /// inside the write itself. +/// +/// This drives the *sequential* order only — the delete commits in full before +/// the mark is sent — which a read-only gate already survives. What the +/// concurrent order needs is next door: the mark must write the session row, or +/// the two transactions share no key and both commit. #[tokio::test] async fn a_mark_against_a_deleted_session_is_refused_and_stores_nothing() { let (app, db) = app_and_db().await; @@ -202,3 +246,166 @@ async fn a_mark_against_a_deleted_session_is_refused_and_stores_nothing() { "no orphan row was written" ); } + +/// A roll call must write its session row *every* time, not only when it also +/// credits the lesson. The credit branch — first mark of a lesson that has +/// begun — was the only writer, so the two cases it skips left the session row +/// untouched and a concurrent `DELETE /sessions/{id}` had nothing to collide +/// with: a sheet opened before the bell, 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 delete's cascade and the upsert write that child's own key.) +/// +/// Both are driven through the real route, and the assertion is the probe's +/// count, which goes to zero the moment the unconditional touch is dropped. +#[tokio::test] +async fn a_mark_writes_its_session_row_even_when_it_credits_nothing() { + let (app, db) = app_and_db().await; + let hoca = login_as(&app, &db, "hoca", "teacher").await; + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + let veli = login(&app, "veli").await; + let veli_id = me_id(&app, &veli).await; + + let course = create_course(&app, &hoca, "algebra").await; + enroll(&app, &hoca, &course, &ali_id).await; + enroll(&app, &hoca, &course, &veli_id).await; + let session = create_session(&app, &hoca, &course, soon()).await; + let mark_uri = format!("/sessions/{session}/attendance"); + + watch_writes_to("course_session", &db).await; + + // The lesson has not begun, so nothing is credited — and before the fix + // nothing at all was written to the session. + let before = writes_seen(&db).await; + let res = send( + &app, + "POST", + &mark_uri, + Some(&hoca), + Some(json!({ "status": "present", "user_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert!( + writes_seen(&db).await > before, + "a mark on a future-dated lesson never touched its session" + ); + + // The bell rings and the first roll call counts the lesson, stamping it. + db.query("UPDATE $sess SET starts_at = 1") + .bind(("sess", CourseSessionId::from_key(&session).record())) + .await + .unwrap() + .check() + .unwrap(); + let res = send( + &app, + "POST", + &mark_uri, + Some(&hoca), + Some(json!({ "status": "present", "user_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // The rest of the roster arrives on a lesson already counted: the credit + // branch is closed for good, and it was the only writer. + let before = writes_seen(&db).await; + let res = send( + &app, + "POST", + &mark_uri, + Some(&hoca), + Some(json!({ "status": "present", "user_id": veli_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert!( + writes_seen(&db).await > before, + "a mark on an already-counted lesson never touched its session" + ); + + // That the touch is a bump-and-restore rather than a second credit is + // `the_first_roll_call_counts_the_lesson_once`'s job, next to the SQL. +} + +/// The twin, on event attendance, which had neither half: a bare upsert with no +/// proof its event exists at all. A mark racing `DELETE /events/{id}`'s cascade +/// (`DELETE attendance WHERE event = $ev`) was counted forever in the `events` +/// tally of `GET /attendance/{user}`, on an event no page shows. +/// +/// Both halves are asserted here: the write on the event row (the collision, +/// probed as above) and the existence gate (the sequential order, driven for +/// real — a mark sent with an id whose event is gone). +#[tokio::test] +async fn an_event_mark_writes_its_event_and_is_refused_once_it_is_gone() { + let (app, db) = app_and_db().await; + let hoca = login_as(&app, &db, "hoca", "teacher").await; + let hoca_ref = UserId::from_key(&me_id(&app, &hoca).await); + let ali = login(&app, "ali").await; + let ali_id = me_id(&app, &ali).await; + let ali_ref = UserId::from_key(&ali_id); + + let res = send( + &app, + "POST", + "/events", + Some(&hoca), + Some(json!({ "title": "Gezi", "audience": { "kind": "role", "role": "student" } })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let event = common::id_of(&res.body); + + watch_writes_to("event", &db).await; + let before = writes_seen(&db).await; + let res = send( + &app, + "POST", + &format!("/events/{event}/attendance"), + Some(&hoca), + Some(json!({ "status": "present", "user_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert!( + writes_seen(&db).await > before, + "the mark never touched its event, so no delete can collide with it" + ); + + // The event goes, cascade and all. + let res = send( + &app, + "DELETE", + &format!("/events/{event}"), + Some(&hoca), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + assert!( + Attendance::list_for_user(&ali_ref, &db) + .await + .unwrap() + .is_empty(), + "the delete cascade removed the mark" + ); + + // And the mark that arrives after it is refused rather than stored. + let school = Settings::load(&db).await.unwrap(); + let status = AttendanceStatus::try_new("present", school.get_attendance_statuses()).unwrap(); + let marked = + Attendance::mark(&EventId::from_key(&event), &ali_ref, status, &hoca_ref, &db).await; + assert!( + matches!(marked, Err(AppError::NotFound)), + "a mark on a deleted event is a 404, got {marked:?}" + ); + // The stored state is the assertion — the return value is not trusted. + assert!( + Attendance::list_for_user(&ali_ref, &db) + .await + .unwrap() + .is_empty(), + "no orphan row was written" + ); +}