Make an attendance mark collide with its parent's delete
Browse files at this commit33b46b1cdb411eb570a40ee237830fd9a249b4e2Parent: 0251364- fix
- make an attendance mark collide with its parent's delete
4 changed files +486 -18
- src/domain/attendance.rs +145 -7
- src/domain/event.rs +24 -9
- src/domain/session_attendance.rs +109 -1
- tests/regress_attendance.rs +208 -1
src/domain/attendance.rsmodified+145 -7
| @@ -1,7 +1,7 @@ | |||
| 1 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 2 | 2 | ||
| 3 | -use crate::constant::ATTENDANCE_TABLE; | 3 | +use crate::constant::{ATTENDANCE_TABLE, REGISTRATION_COUNT_FIELD}; |
| 4 | -use crate::database::Database; | 4 | +use crate::database::{Database, transaction_with_retry}; |
| 5 | use crate::domain::event::EventId; | 5 | use crate::domain::event::EventId; |
| 6 | use crate::domain::page::PagedList; | 6 | use crate::domain::page::PagedList; |
| 7 | use crate::domain::user::UserId; | 7 | use crate::domain::user::UserId; |
| @@ -91,6 +91,25 @@ impl Attendance { | |||
| 91 | /// user), keyed by a deterministic composite id so this is a single atomic | 91 | /// user), keyed by a deterministic composite id so this is a single atomic |
| 92 | /// UPSERT — concurrent marks for the same pair can no longer both insert and | 92 | /// UPSERT — concurrent marks for the same pair can no longer both insert and |
| 93 | /// collide on the unique index (a 500); they converge on the one row. | 93 | /// collide on the unique index (a 500); they converge on the one row. |
| 94 | + /// | ||
| 95 | + /// The event's existence is proved *inside* the write, the twin of the gate | ||
| 96 | + /// in [`crate::domain::session_attendance::SessionAttendance::mark`]: the | ||
| 97 | + /// handler's event read sits several round trips in front of this, so a | ||
| 98 | + /// bare upsert left a mark on an event [`crate::domain::event::Event`]'s | ||
| 99 | + /// cascade (`DELETE attendance WHERE event = $ev`) had already swept — | ||
| 100 | + /// counted forever in `GET /attendance/{user}` on an event no page shows. | ||
| 101 | + /// Reading the event here would not have closed it either: SurrealDB 3.2.3 | ||
| 102 | + /// conflict-checks write sets, not read sets, so the proof has to *move* a | ||
| 103 | + /// value on the event row. It is the bump-and-restore of | ||
| 104 | + /// [`crate::domain::exam_answer::ExamAnswer::save`], on the counter the | ||
| 105 | + /// event already carries: matching nothing is the existence gate, writing | ||
| 106 | + /// the key the delete removes is the collision, and the restore is by | ||
| 107 | + /// captured value (`NONE` included) so no seat is spent or freed. | ||
| 108 | + /// | ||
| 109 | + /// Admissible for [`transaction_with_retry`]: no statement can answer | ||
| 110 | + /// "already exists" — the `UPSERT`'s composite id is bijective with the | ||
| 111 | + /// `attendance_event_user` unique tuple, so it resolves onto the row it | ||
| 112 | + /// names instead of colliding with it. | ||
| 94 | pub async fn mark( | 113 | pub async fn mark( |
| 95 | event: &EventId, | 114 | event: &EventId, |
| 96 | user: &UserId, | 115 | user: &UserId, |
| @@ -105,11 +124,45 @@ impl Attendance { | |||
| 105 | status, | 124 | status, |
| 106 | marked_by: marked_by.clone(), | 125 | marked_by: marked_by.clone(), |
| 107 | }; | 126 | }; |
| 108 | - let saved: Option<Attendance> = db | 127 | + let (mut result, mut errors) = transaction_with_retry( |
| 109 | - .upsert(attendance.id.record()) | 128 | + db, |
| 110 | - .content(attendance) | 129 | + &format!( |
| 111 | - .await?; | 130 | + "BEGIN TRANSACTION; |
| 112 | - saved.ok_or_else(|| AppError::Internal("failed to mark attendance".into())) | 131 | + LET $was = (SELECT VALUE {REGISTRATION_COUNT_FIELD} FROM ONLY $ev); |
| 132 | + LET $alive = (UPDATE $ev SET {REGISTRATION_COUNT_FIELD} = | ||
| 133 | + ({REGISTRATION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); | ||
| 134 | + IF array::len($alive) = 0 {{ THROW 'event_missing' }}; | ||
| 135 | + UPDATE $ev SET {REGISTRATION_COUNT_FIELD} = $was; | ||
| 136 | + LET $after = (UPSERT $id CONTENT $row RETURN AFTER); | ||
| 137 | + RETURN $after; | ||
| 138 | + COMMIT TRANSACTION;" | ||
| 139 | + ), | ||
| 140 | + &[ | ||
| 141 | + ("ev".into(), event.record().into_value()), | ||
| 142 | + ("id".into(), attendance.id.record().into_value()), | ||
| 143 | + ("row".into(), attendance.into_value()), | ||
| 144 | + ], | ||
| 145 | + &["event_missing"], | ||
| 146 | + ) | ||
| 147 | + .await?; | ||
| 148 | + // An aborted transaction errors every slot and only the THROW's own | ||
| 149 | + // slot names the marker. | ||
| 150 | + if errors | ||
| 151 | + .values() | ||
| 152 | + .any(|error| error.to_string().contains("event_missing")) | ||
| 153 | + { | ||
| 154 | + return Err(AppError::NotFound); | ||
| 155 | + } | ||
| 156 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 157 | + return Err(error.into()); | ||
| 158 | + } | ||
| 159 | + // The trailing `RETURN` is always the last statement before `COMMIT`. | ||
| 160 | + let slot = result.num_statements().saturating_sub(2); | ||
| 161 | + result | ||
| 162 | + .take::<Vec<Attendance>>(slot)? | ||
| 163 | + .into_iter() | ||
| 164 | + .next() | ||
| 165 | + .ok_or_else(|| AppError::Internal("failed to mark attendance".into())) | ||
| 113 | } | 166 | } |
| 114 | 167 | ||
| 115 | pub async fn list_for_event( | 168 | pub async fn list_for_event( |
| @@ -177,4 +230,89 @@ mod tests { | |||
| 177 | .collect(); | 230 | .collect(); |
| 178 | assert!(AttendanceStatus::try_new("online", &extended).is_ok()); | 231 | assert!(AttendanceStatus::try_new("online", &extended).is_ok()); |
| 179 | } | 232 | } |
| 233 | + | ||
| 234 | + /// The session twin's race, one table over | ||
| 235 | + /// ([`crate::domain::session_attendance::SessionAttendance`]): a | ||
| 236 | + /// `DEFINE EVENT` on `event` fires inside the delete's own transaction, and | ||
| 237 | + /// [`Event::delete`] sweeps its attendance rows before removing the row, so | ||
| 238 | + /// the `SLEEP` lands exactly between the sweep and the commit — the window | ||
| 239 | + /// where a bare upsert wrote a mark nothing would ever sweep again. | ||
| 240 | + /// | ||
| 241 | + /// Real server, and `#[ignore]`d for it: the subject is the store's | ||
| 242 | + /// conflict detection, which `init_mem`'s embedded engine does not have — | ||
| 243 | + /// it commits both writes and answers `Ok` to each, so this passes there on | ||
| 244 | + /// broken code. Mutation-tested: turning the claim back into a read | ||
| 245 | + /// (`SELECT VALUE id FROM $ev`) turns it red. | ||
| 246 | + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 247 | + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 248 | + async fn a_mark_written_inside_a_delete_never_outlives_the_event() { | ||
| 249 | + use crate::domain::event::{Event, EventAudience, EventDescription, EventTitle}; | ||
| 250 | + let (db, _serialized) = crate::database::init_test_server("event_attendance_race").await; | ||
| 251 | + db.query( | ||
| 252 | + "DEFINE EVENT hold_the_window ON TABLE event WHEN $event = 'DELETE' \ | ||
| 253 | + THEN { SLEEP 1s; };", | ||
| 254 | + ) | ||
| 255 | + .await | ||
| 256 | + .unwrap() | ||
| 257 | + .check() | ||
| 258 | + .unwrap(); | ||
| 259 | + | ||
| 260 | + let allowed: Vec<String> = crate::domain::settings::Settings::defaults() | ||
| 261 | + .get_attendance_statuses() | ||
| 262 | + .to_vec(); | ||
| 263 | + let marker = UserId::from_key("t"); | ||
| 264 | + let (mut swept, mut orphans) = (0, 0); | ||
| 265 | + for round in 0..4 { | ||
| 266 | + let event = Event::create( | ||
| 267 | + &marker, | ||
| 268 | + EventTitle::try_new("gezi").unwrap(), | ||
| 269 | + EventDescription::try_new("").unwrap(), | ||
| 270 | + EventAudience::School, | ||
| 271 | + None, | ||
| 272 | + None, | ||
| 273 | + &db, | ||
| 274 | + ) | ||
| 275 | + .await | ||
| 276 | + .unwrap(); | ||
| 277 | + let id = event.get_id().clone(); | ||
| 278 | + let drop_it = { | ||
| 279 | + let db = db.clone(); | ||
| 280 | + tokio::spawn(async move { event.delete(&db).await }) | ||
| 281 | + }; | ||
| 282 | + // The mark starts inside the held window: the sweep has run and the | ||
| 283 | + // event row is gone but uncommitted. | ||
| 284 | + tokio::time::sleep(std::time::Duration::from_millis(300)).await; | ||
| 285 | + let marked = { | ||
| 286 | + let (db, id, marker) = (db.clone(), id.clone(), marker.clone()); | ||
| 287 | + let student = UserId::from_key(&format!("s{round}")); | ||
| 288 | + let status = AttendanceStatus::try_new("present", &allowed).unwrap(); | ||
| 289 | + tokio::spawn( | ||
| 290 | + async move { Attendance::mark(&id, &student, status, &marker, &db).await }, | ||
| 291 | + ) | ||
| 292 | + }; | ||
| 293 | + let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap()); | ||
| 294 | + assert!( | ||
| 295 | + !matches!(marked, Err(AppError::Db(_))), | ||
| 296 | + "round {round}: a raced mark must be answered, not 500: {marked:?}" | ||
| 297 | + ); | ||
| 298 | + | ||
| 299 | + // Stored state is the whole verdict; a return value is not evidence. | ||
| 300 | + if Event::read(&id, &db).await.unwrap().is_none() { | ||
| 301 | + swept += 1; | ||
| 302 | + orphans += Attendance::list_for_event(&id, None, 0, &db) | ||
| 303 | + .await | ||
| 304 | + .unwrap() | ||
| 305 | + .0 | ||
| 306 | + .len(); | ||
| 307 | + } else if drop_it.is_ok() { | ||
| 308 | + panic!("round {round}: the delete reported success but the event is still there"); | ||
| 309 | + } | ||
| 310 | + } | ||
| 311 | + eprintln!("Event::delete raced by a mark: {swept}/4 rounds deleted the event"); | ||
| 312 | + assert!( | ||
| 313 | + swept > 0, | ||
| 314 | + "no round ever deleted the event, so the window was never reached" | ||
| 315 | + ); | ||
| 316 | + assert_eq!(orphans, 0, "a mark outlived its event"); | ||
| 317 | + } | ||
| 180 | } | 318 | } |
src/domain/event.rsmodified+24 -9
| @@ -3,7 +3,7 @@ | |||
| 3 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; | 3 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; |
| 4 | 4 | ||
| 5 | use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; | 5 | use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; |
| 6 | -use crate::database::Database; | 6 | +use crate::database::{Database, transaction_with_retry}; |
| 7 | use crate::domain::class_group::ClassGroupId; | 7 | use crate::domain::class_group::ClassGroupId; |
| 8 | use crate::domain::class_member::{ClassMember, ClassMemberId}; | 8 | use crate::domain::class_member::{ClassMember, ClassMemberId}; |
| 9 | use crate::domain::course::CourseId; | 9 | use crate::domain::course::CourseId; |
| @@ -315,21 +315,36 @@ impl Event { | |||
| 315 | /// registration or a mark that committed in between outlived its event — | 315 | /// registration or a mark that committed in between outlived its event — |
| 316 | /// an orphan no read path can ever reach and no delete can ever reclaim, | 316 | /// an orphan no read path can ever reach and no delete can ever reclaim, |
| 317 | /// since every one of them is keyed on the event that is now gone. | 317 | /// since every one of them is keyed on the event that is now gone. |
| 318 | + /// | ||
| 319 | + /// Re-sent while the store answers "conflict, retry", the way | ||
| 320 | + /// [`crate::domain::course_session::CourseSession::delete`] is: now that | ||
| 321 | + /// [`crate::domain::attendance::Attendance::mark`] writes the event row to | ||
| 322 | + /// prove it exists, a mark landing in this window really does contend for | ||
| 323 | + /// it — and without the retry the *delete* is the side that loses, turning | ||
| 324 | + /// a race the store resolved correctly into a 500 (measured 4 rounds in 4). | ||
| 325 | + /// Admissible: every statement is a `DELETE`, which can never answer | ||
| 326 | + /// "already exists", and a lost round wrote nothing. | ||
| 318 | pub async fn delete(self, db: &Database) -> Result<Event, AppError> { | 327 | pub async fn delete(self, db: &Database) -> Result<Event, AppError> { |
| 319 | - let mut result = db | 328 | + let (mut result, mut errors) = transaction_with_retry( |
| 320 | - .query( | 329 | + db, |
| 321 | - "BEGIN TRANSACTION; | 330 | + "BEGIN TRANSACTION; |
| 322 | DELETE attendance WHERE event = $ev; | 331 | DELETE attendance WHERE event = $ev; |
| 323 | DELETE registration WHERE event = $ev; | 332 | DELETE registration WHERE event = $ev; |
| 324 | LET $gone = (DELETE $ev RETURN BEFORE); | 333 | LET $gone = (DELETE $ev RETURN BEFORE); |
| 325 | RETURN $gone; | 334 | RETURN $gone; |
| 326 | COMMIT TRANSACTION;", | 335 | COMMIT TRANSACTION;", |
| 327 | - ) | 336 | + &[("ev".into(), self.id.record().into_value())], |
| 328 | - .bind(("ev", self.id.record())) | 337 | + // No THROW of its own — an unconditional cascade. |
| 329 | - .await? | 338 | + &[], |
| 330 | - .check()?; | 339 | + ) |
| 340 | + .await?; | ||
| 341 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 342 | + return Err(error.into()); | ||
| 343 | + } | ||
| 344 | + // Read through the trailing `RETURN`, never a hand-counted slot. | ||
| 345 | + let slot = result.num_statements().saturating_sub(2); | ||
| 331 | result | 346 | result |
| 332 | - .take::<Vec<Event>>(4)? | 347 | + .take::<Vec<Event>>(slot)? |
| 333 | .into_iter() | 348 | .into_iter() |
| 334 | .next() | 349 | .next() |
| 335 | .ok_or(AppError::NotFound) | 350 | .ok_or(AppError::NotFound) |
src/domain/session_attendance.rsmodified+109 -1
| @@ -111,6 +111,22 @@ impl SessionAttendance { | |||
| 111 | /// as `id` did — because the counter below needs that teacher anyway, and | 111 | /// as `id` did — because the counter below needs that teacher anyway, and |
| 112 | /// one read serves both. | 112 | /// one read serves both. |
| 113 | /// | 113 | /// |
| 114 | + /// A read is not a claim, though: SurrealDB 3.2.3 conflict-checks write | ||
| 115 | + /// sets, not read sets, so that gate alone only closes the *sequential* | ||
| 116 | + /// order (delete committed, then the mark arrives). To make the two really | ||
| 117 | + /// collide, this transaction also *writes* the session row, unconditionally | ||
| 118 | + /// — the bump-and-restore of [`crate::domain::exam_answer::ExamAnswer::save`] | ||
| 119 | + /// on the one column this write already owns, [`LESSON_COUNTED_AT_FIELD`]. | ||
| 120 | + /// Unconditional is the whole point: the credit branch below writes that | ||
| 121 | + /// column already, but it fires only for the first roll call of a lesson | ||
| 122 | + /// that has begun, so a future-dated sheet and every re-mark of a counted | ||
| 123 | + /// one touched nothing at all and committed happily beside | ||
| 124 | + /// `DELETE /sessions/{id}`. Re-stating the value verbatim would not do | ||
| 125 | + /// either — an `UPDATE` that leaves the document unchanged is elided and | ||
| 126 | + /// never enters the write set — hence bump first, then either stamp | ||
| 127 | + /// (credit branch) or put back exactly what was found, `NONE` included, so | ||
| 128 | + /// the row is byte-identical and the once-per-lesson rule is untouched. | ||
| 129 | + /// | ||
| 114 | /// Sound to re-send while the store answers "conflict, retry": the gate | 130 | /// Sound to re-send while the store answers "conflict, retry": the gate |
| 115 | /// reads the record a delete writes, so the two contend by design, and the | 131 | /// reads the record a delete writes, so the two contend by design, and the |
| 116 | /// UPSERT cannot legitimately answer "already exists" — its composite id is | 132 | /// UPSERT cannot legitimately answer "already exists" — its composite id is |
| @@ -200,10 +216,13 @@ impl SessionAttendance { | |||
| 200 | UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = | 216 | UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = |
| 201 | math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) + $delta, 0]) | 217 | math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) + $delta, 0]) |
| 202 | }}; | 218 | }}; |
| 219 | + UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = ({LESSON_COUNTED_AT_FIELD} ?? 0) + 1; | ||
| 203 | IF ($counted IS NONE) AND $begun {{ | 220 | IF ($counted IS NONE) AND $begun {{ |
| 204 | UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $stamp; | 221 | UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $stamp; |
| 205 | UPDATE $teacher SET {LESSONS_HELD_TOTAL_FIELD} = | 222 | UPDATE $teacher SET {LESSONS_HELD_TOTAL_FIELD} = |
| 206 | ({LESSONS_HELD_TOTAL_FIELD} ?? 0) + 1 | 223 | ({LESSONS_HELD_TOTAL_FIELD} ?? 0) + 1 |
| 224 | + }} ELSE {{ | ||
| 225 | + UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $counted | ||
| 207 | }}; | 226 | }}; |
| 208 | RETURN $after; | 227 | RETURN $after; |
| 209 | COMMIT TRANSACTION;" | 228 | COMMIT TRANSACTION;" |
| @@ -366,7 +385,7 @@ mod tests { | |||
| 366 | 385 | ||
| 367 | async fn a_session_at(teacher: &UserId, starts_at: i64, db: &Database) -> CourseSession { | 386 | async fn a_session_at(teacher: &UserId, starts_at: i64, db: &Database) -> CourseSession { |
| 368 | CourseSession::create( | 387 | CourseSession::create( |
| 369 | - &CourseId::from_key("c"), | 388 | + &crate::domain::course::a_test_course(db).await, |
| 370 | teacher, | 389 | teacher, |
| 371 | SessionTopic::try_new("limits").unwrap(), | 390 | SessionTopic::try_new("limits").unwrap(), |
| 372 | Timestamp::from_millis(starts_at), | 391 | Timestamp::from_millis(starts_at), |
| @@ -668,4 +687,93 @@ mod tests { | |||
| 668 | assert_eq!(attended(&student, &db).await, 0); | 687 | assert_eq!(attended(&student, &db).await, 0); |
| 669 | assert_eq!(held(&teacher, &db).await, 0, "a refused mark held a lesson"); | 688 | assert_eq!(held(&teacher, &db).await, 0, "a refused mark held a lesson"); |
| 670 | } | 689 | } |
| 690 | + | ||
| 691 | + /// The claim the existence gate cannot make by *reading*. A `DEFINE EVENT` | ||
| 692 | + /// on `course_session` fires inside the delete's own transaction, and | ||
| 693 | + /// [`CourseSession::delete`] sweeps its children before removing the row, | ||
| 694 | + /// so the `SLEEP` opens exactly the window a mark has to lose: the sheet is | ||
| 695 | + /// written after the sweep has run, and used to commit straight past it. | ||
| 696 | + /// | ||
| 697 | + /// The two flavors raced are the ones the credit branch never wrote for — a | ||
| 698 | + /// lesson that has not begun, and a student with no row yet on a lesson | ||
| 699 | + /// already counted. A re-mark of a row that *exists* was never in danger: | ||
| 700 | + /// the cascade and the upsert write that child's own key and collide there. | ||
| 701 | + /// | ||
| 702 | + /// Real server, and `#[ignore]`d for it: the subject is the store's | ||
| 703 | + /// conflict detection, which [`init_mem`]'s embedded engine does not have — | ||
| 704 | + /// it commits both writes and answers `Ok` to each, so this passes there on | ||
| 705 | + /// broken code. Mutation-tested: dropping the unconditional | ||
| 706 | + /// `UPDATE $sess` from `mark` turns it red. | ||
| 707 | + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 708 | + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 709 | + async fn a_mark_written_inside_a_delete_never_outlives_the_session() { | ||
| 710 | + let (db, _serialized) = crate::database::init_test_server("session_attendance_race").await; | ||
| 711 | + db.query( | ||
| 712 | + "DEFINE EVENT hold_the_window ON TABLE course_session WHEN $event = 'DELETE' \ | ||
| 713 | + THEN { SLEEP 1s; };", | ||
| 714 | + ) | ||
| 715 | + .await | ||
| 716 | + .unwrap() | ||
| 717 | + .check() | ||
| 718 | + .unwrap(); | ||
| 719 | + | ||
| 720 | + let teacher = a_teacher("t", &db).await; | ||
| 721 | + let (mut swept, mut orphans) = (0, 0); | ||
| 722 | + for (round, already_counted) in [false, true, false, true].into_iter().enumerate() { | ||
| 723 | + let session = if already_counted { | ||
| 724 | + // Counted by somebody else's mark, so this one credits nothing. | ||
| 725 | + let session = a_session(&teacher, &db).await; | ||
| 726 | + let first = a_student(&format!("f{round}"), &db).await; | ||
| 727 | + SessionAttendance::mark(&session, &first, status("present"), &teacher, &db) | ||
| 728 | + .await | ||
| 729 | + .unwrap(); | ||
| 730 | + session | ||
| 731 | + } else { | ||
| 732 | + a_session_at(&teacher, Timestamp::now().as_millis() + 604_800_000, &db).await | ||
| 733 | + }; | ||
| 734 | + let id = session.get_id().clone(); | ||
| 735 | + let ghost = session.clone(); | ||
| 736 | + let drop_it = { | ||
| 737 | + let db = db.clone(); | ||
| 738 | + tokio::spawn(async move { session.delete(&db).await }) | ||
| 739 | + }; | ||
| 740 | + // The mark starts inside the held window: the sweep has run and the | ||
| 741 | + // session row is gone but uncommitted — which is exactly what a | ||
| 742 | + // read of that session still believes. | ||
| 743 | + tokio::time::sleep(std::time::Duration::from_millis(300)).await; | ||
| 744 | + let marked = { | ||
| 745 | + let (db, teacher) = (db.clone(), teacher.clone()); | ||
| 746 | + let student = a_student(&format!("s{round}"), &db).await; | ||
| 747 | + tokio::spawn(async move { | ||
| 748 | + SessionAttendance::mark(&ghost, &student, status("present"), &teacher, &db) | ||
| 749 | + .await | ||
| 750 | + }) | ||
| 751 | + }; | ||
| 752 | + let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap()); | ||
| 753 | + assert!( | ||
| 754 | + !matches!(marked, Err(AppError::Db(_))), | ||
| 755 | + "round {round}: a raced mark must be answered, not 500: {marked:?}" | ||
| 756 | + ); | ||
| 757 | + | ||
| 758 | + // Stored state is the whole verdict; a return value is not evidence. | ||
| 759 | + if CourseSession::read(&id, &db).await.unwrap().is_none() { | ||
| 760 | + swept += 1; | ||
| 761 | + orphans += SessionAttendance::list_for_session(&id, None, 0, &db) | ||
| 762 | + .await | ||
| 763 | + .unwrap() | ||
| 764 | + .0 | ||
| 765 | + .len(); | ||
| 766 | + } else if drop_it.is_ok() { | ||
| 767 | + panic!("round {round}: the delete reported success but the session is still there"); | ||
| 768 | + } | ||
| 769 | + } | ||
| 770 | + eprintln!( | ||
| 771 | + "CourseSession::delete raced by a roll call: {swept}/4 rounds deleted the session" | ||
| 772 | + ); | ||
| 773 | + assert!( | ||
| 774 | + swept > 0, | ||
| 775 | + "no round ever deleted the session, so the window was never reached" | ||
| 776 | + ); | ||
| 777 | + assert_eq!(orphans, 0, "a roll call outlived its session"); | ||
| 778 | + } | ||
| 671 | } | 779 | } |
tests/regress_attendance.rsmodified+208 -1
| @@ -12,8 +12,10 @@ mod common; | |||
| 12 | 12 | ||
| 13 | use axum::http::StatusCode; | 13 | use axum::http::StatusCode; |
| 14 | use common::{app_and_db, create_course, create_session, enroll, login, login_as, me_id, send}; | 14 | use common::{app_and_db, create_course, create_session, enroll, login, login_as, me_id, send}; |
| 15 | -use hezarfen_backend::domain::attendance::AttendanceStatus; | 15 | +use hezarfen_backend::database::Database; |
| 16 | +use hezarfen_backend::domain::attendance::{Attendance, AttendanceStatus}; | ||
| 16 | use hezarfen_backend::domain::course_session::{CourseSession, CourseSessionId}; | 17 | use hezarfen_backend::domain::course_session::{CourseSession, CourseSessionId}; |
| 18 | +use hezarfen_backend::domain::event::EventId; | ||
| 17 | use hezarfen_backend::domain::session_attendance::SessionAttendance; | 19 | use hezarfen_backend::domain::session_attendance::SessionAttendance; |
| 18 | use hezarfen_backend::domain::settings::Settings; | 20 | use hezarfen_backend::domain::settings::Settings; |
| 19 | use hezarfen_backend::domain::timestamp::Timestamp; | 21 | use hezarfen_backend::domain::timestamp::Timestamp; |
| @@ -25,6 +27,43 @@ fn soon() -> i64 { | |||
| 25 | Timestamp::now().as_millis() + 3_600_000 | 27 | Timestamp::now().as_millis() + 3_600_000 |
| 26 | } | 28 | } |
| 27 | 29 | ||
| 30 | +/// Count writes to `table` from *inside* the writing transaction: a | ||
| 31 | +/// `DEFINE EVENT` on it fires within that write, so a parent row a mark never | ||
| 32 | +/// touches shows up here as a zero. That zero is the whole defect class — | ||
| 33 | +/// SurrealDB 3.2.3 conflict-checks write sets, not read sets, so a parent this | ||
| 34 | +/// transaction only *reads* is a parent whose concurrent delete it can never | ||
| 35 | +/// collide with, and the mark commits as an orphan. | ||
| 36 | +/// | ||
| 37 | +/// The collision itself is not testable on the in-memory engine (it commits | ||
| 38 | +/// both writes and answers `Ok` to each — see | ||
| 39 | +/// `crate::database::init_test_server`); the raced halves live beside the | ||
| 40 | +/// domain code, `#[ignore]`d. What runs here, always, is the precondition | ||
| 41 | +/// those races need: the parent is written at all. | ||
| 42 | +async fn watch_writes_to(table: &str, db: &Database) { | ||
| 43 | + db.query(format!( | ||
| 44 | + "DEFINE EVENT parent_touch ON TABLE {table} WHEN $event = 'UPDATE' THEN {{ | ||
| 45 | + UPSERT type::record('parent_write_probe', 'n') SET n = (n ?? 0) + 1; | ||
| 46 | + }}; | ||
| 47 | + UPSERT type::record('parent_write_probe', 'n') SET n = 0;" | ||
| 48 | + )) | ||
| 49 | + .await | ||
| 50 | + .unwrap() | ||
| 51 | + .check() | ||
| 52 | + .unwrap(); | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +/// How many parent writes the probe has seen so far. | ||
| 56 | +async fn writes_seen(db: &Database) -> i64 { | ||
| 57 | + db.query("SELECT VALUE n FROM parent_write_probe:n") | ||
| 58 | + .await | ||
| 59 | + .unwrap() | ||
| 60 | + .take::<Vec<i64>>(0) | ||
| 61 | + .unwrap() | ||
| 62 | + .first() | ||
| 63 | + .copied() | ||
| 64 | + .unwrap_or(0) | ||
| 65 | +} | ||
| 66 | + | ||
| 28 | /// A staff roll-call row is management's to write *and* to remove. The removal | 67 | /// A staff roll-call row is management's to write *and* to remove. The removal |
| 29 | /// gate used to ask "is the target the session's teacher?", which a teacher | 68 | /// gate used to ask "is the target the session's teacher?", which a teacher |
| 30 | /// reassignment falsifies: once the session moved to T2, the row T1 holds is no | 69 | /// 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() { | |||
| 132 | /// was unremovable, its only delete route 404ing on the vanished session while | 171 | /// was unremovable, its only delete route 404ing on the vanished session while |
| 133 | /// `GET /attendance/{user}` counted it forever. The existence gate now rides | 172 | /// `GET /attendance/{user}` counted it forever. The existence gate now rides |
| 134 | /// inside the write itself. | 173 | /// inside the write itself. |
| 174 | +/// | ||
| 175 | +/// This drives the *sequential* order only — the delete commits in full before | ||
| 176 | +/// the mark is sent — which a read-only gate already survives. What the | ||
| 177 | +/// concurrent order needs is next door: the mark must write the session row, or | ||
| 178 | +/// the two transactions share no key and both commit. | ||
| 135 | #[tokio::test] | 179 | #[tokio::test] |
| 136 | async fn a_mark_against_a_deleted_session_is_refused_and_stores_nothing() { | 180 | async fn a_mark_against_a_deleted_session_is_refused_and_stores_nothing() { |
| 137 | let (app, db) = app_and_db().await; | 181 | let (app, db) = app_and_db().await; |
| @@ -202,3 +246,166 @@ async fn a_mark_against_a_deleted_session_is_refused_and_stores_nothing() { | |||
| 202 | "no orphan row was written" | 246 | "no orphan row was written" |
| 203 | ); | 247 | ); |
| 204 | } | 248 | } |
| 249 | + | ||
| 250 | +/// A roll call must write its session row *every* time, not only when it also | ||
| 251 | +/// credits the lesson. The credit branch — first mark of a lesson that has | ||
| 252 | +/// begun — was the only writer, so the two cases it skips left the session row | ||
| 253 | +/// untouched and a concurrent `DELETE /sessions/{id}` had nothing to collide | ||
| 254 | +/// with: a sheet opened before the bell, and a student with no row yet on a | ||
| 255 | +/// lesson already counted. (A *re-mark* of a row that exists was never in | ||
| 256 | +/// danger — the delete's cascade and the upsert write that child's own key.) | ||
| 257 | +/// | ||
| 258 | +/// Both are driven through the real route, and the assertion is the probe's | ||
| 259 | +/// count, which goes to zero the moment the unconditional touch is dropped. | ||
| 260 | +#[tokio::test] | ||
| 261 | +async fn a_mark_writes_its_session_row_even_when_it_credits_nothing() { | ||
| 262 | + let (app, db) = app_and_db().await; | ||
| 263 | + let hoca = login_as(&app, &db, "hoca", "teacher").await; | ||
| 264 | + let ali = login(&app, "ali").await; | ||
| 265 | + let ali_id = me_id(&app, &ali).await; | ||
| 266 | + let veli = login(&app, "veli").await; | ||
| 267 | + let veli_id = me_id(&app, &veli).await; | ||
| 268 | + | ||
| 269 | + let course = create_course(&app, &hoca, "algebra").await; | ||
| 270 | + enroll(&app, &hoca, &course, &ali_id).await; | ||
| 271 | + enroll(&app, &hoca, &course, &veli_id).await; | ||
| 272 | + let session = create_session(&app, &hoca, &course, soon()).await; | ||
| 273 | + let mark_uri = format!("/sessions/{session}/attendance"); | ||
| 274 | + | ||
| 275 | + watch_writes_to("course_session", &db).await; | ||
| 276 | + | ||
| 277 | + // The lesson has not begun, so nothing is credited — and before the fix | ||
| 278 | + // nothing at all was written to the session. | ||
| 279 | + let before = writes_seen(&db).await; | ||
| 280 | + let res = send( | ||
| 281 | + &app, | ||
| 282 | + "POST", | ||
| 283 | + &mark_uri, | ||
| 284 | + Some(&hoca), | ||
| 285 | + Some(json!({ "status": "present", "user_id": ali_id })), | ||
| 286 | + ) | ||
| 287 | + .await; | ||
| 288 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 289 | + assert!( | ||
| 290 | + writes_seen(&db).await > before, | ||
| 291 | + "a mark on a future-dated lesson never touched its session" | ||
| 292 | + ); | ||
| 293 | + | ||
| 294 | + // The bell rings and the first roll call counts the lesson, stamping it. | ||
| 295 | + db.query("UPDATE $sess SET starts_at = 1") | ||
| 296 | + .bind(("sess", CourseSessionId::from_key(&session).record())) | ||
| 297 | + .await | ||
| 298 | + .unwrap() | ||
| 299 | + .check() | ||
| 300 | + .unwrap(); | ||
| 301 | + let res = send( | ||
| 302 | + &app, | ||
| 303 | + "POST", | ||
| 304 | + &mark_uri, | ||
| 305 | + Some(&hoca), | ||
| 306 | + Some(json!({ "status": "present", "user_id": ali_id })), | ||
| 307 | + ) | ||
| 308 | + .await; | ||
| 309 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 310 | + | ||
| 311 | + // The rest of the roster arrives on a lesson already counted: the credit | ||
| 312 | + // branch is closed for good, and it was the only writer. | ||
| 313 | + let before = writes_seen(&db).await; | ||
| 314 | + let res = send( | ||
| 315 | + &app, | ||
| 316 | + "POST", | ||
| 317 | + &mark_uri, | ||
| 318 | + Some(&hoca), | ||
| 319 | + Some(json!({ "status": "present", "user_id": veli_id })), | ||
| 320 | + ) | ||
| 321 | + .await; | ||
| 322 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 323 | + assert!( | ||
| 324 | + writes_seen(&db).await > before, | ||
| 325 | + "a mark on an already-counted lesson never touched its session" | ||
| 326 | + ); | ||
| 327 | + | ||
| 328 | + // That the touch is a bump-and-restore rather than a second credit is | ||
| 329 | + // `the_first_roll_call_counts_the_lesson_once`'s job, next to the SQL. | ||
| 330 | +} | ||
| 331 | + | ||
| 332 | +/// The twin, on event attendance, which had neither half: a bare upsert with no | ||
| 333 | +/// proof its event exists at all. A mark racing `DELETE /events/{id}`'s cascade | ||
| 334 | +/// (`DELETE attendance WHERE event = $ev`) was counted forever in the `events` | ||
| 335 | +/// tally of `GET /attendance/{user}`, on an event no page shows. | ||
| 336 | +/// | ||
| 337 | +/// Both halves are asserted here: the write on the event row (the collision, | ||
| 338 | +/// probed as above) and the existence gate (the sequential order, driven for | ||
| 339 | +/// real — a mark sent with an id whose event is gone). | ||
| 340 | +#[tokio::test] | ||
| 341 | +async fn an_event_mark_writes_its_event_and_is_refused_once_it_is_gone() { | ||
| 342 | + let (app, db) = app_and_db().await; | ||
| 343 | + let hoca = login_as(&app, &db, "hoca", "teacher").await; | ||
| 344 | + let hoca_ref = UserId::from_key(&me_id(&app, &hoca).await); | ||
| 345 | + let ali = login(&app, "ali").await; | ||
| 346 | + let ali_id = me_id(&app, &ali).await; | ||
| 347 | + let ali_ref = UserId::from_key(&ali_id); | ||
| 348 | + | ||
| 349 | + let res = send( | ||
| 350 | + &app, | ||
| 351 | + "POST", | ||
| 352 | + "/events", | ||
| 353 | + Some(&hoca), | ||
| 354 | + Some(json!({ "title": "Gezi", "audience": { "kind": "role", "role": "student" } })), | ||
| 355 | + ) | ||
| 356 | + .await; | ||
| 357 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 358 | + let event = common::id_of(&res.body); | ||
| 359 | + | ||
| 360 | + watch_writes_to("event", &db).await; | ||
| 361 | + let before = writes_seen(&db).await; | ||
| 362 | + let res = send( | ||
| 363 | + &app, | ||
| 364 | + "POST", | ||
| 365 | + &format!("/events/{event}/attendance"), | ||
| 366 | + Some(&hoca), | ||
| 367 | + Some(json!({ "status": "present", "user_id": ali_id })), | ||
| 368 | + ) | ||
| 369 | + .await; | ||
| 370 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 371 | + assert!( | ||
| 372 | + writes_seen(&db).await > before, | ||
| 373 | + "the mark never touched its event, so no delete can collide with it" | ||
| 374 | + ); | ||
| 375 | + | ||
| 376 | + // The event goes, cascade and all. | ||
| 377 | + let res = send( | ||
| 378 | + &app, | ||
| 379 | + "DELETE", | ||
| 380 | + &format!("/events/{event}"), | ||
| 381 | + Some(&hoca), | ||
| 382 | + None, | ||
| 383 | + ) | ||
| 384 | + .await; | ||
| 385 | + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); | ||
| 386 | + assert!( | ||
| 387 | + Attendance::list_for_user(&ali_ref, &db) | ||
| 388 | + .await | ||
| 389 | + .unwrap() | ||
| 390 | + .is_empty(), | ||
| 391 | + "the delete cascade removed the mark" | ||
| 392 | + ); | ||
| 393 | + | ||
| 394 | + // And the mark that arrives after it is refused rather than stored. | ||
| 395 | + let school = Settings::load(&db).await.unwrap(); | ||
| 396 | + let status = AttendanceStatus::try_new("present", school.get_attendance_statuses()).unwrap(); | ||
| 397 | + let marked = | ||
| 398 | + Attendance::mark(&EventId::from_key(&event), &ali_ref, status, &hoca_ref, &db).await; | ||
| 399 | + assert!( | ||
| 400 | + matches!(marked, Err(AppError::NotFound)), | ||
| 401 | + "a mark on a deleted event is a 404, got {marked:?}" | ||
| 402 | + ); | ||
| 403 | + // The stored state is the assertion — the return value is not trusted. | ||
| 404 | + assert!( | ||
| 405 | + Attendance::list_for_user(&ali_ref, &db) | ||
| 406 | + .await | ||
| 407 | + .unwrap() | ||
| 408 | + .is_empty(), | ||
| 409 | + "no orphan row was written" | ||
| 410 | + ); | ||
| 411 | +} | ||