Force both orders in delete-vs-write races
Browse files at this commit1a7d5c3e17ca031ea0705c6f638805e59616beafParent: 20e856a- test
- force both orders in delete-vs-write races
10 changed files +1419 -463
- src/db/attendance.rs +87 -23
- src/db/bank_question_image.rs +116 -31
- src/db/chatbot_thread.rs +105 -30
- src/db/course.rs +189 -79
- src/db/exam.rs +436 -134
- src/db/menu.rs +110 -48
- src/db/pool_question.rs +94 -35
- src/db/rag_thread.rs +90 -29
- src/db/session_attendance.rs +100 -29
- src/service/class_course.rs +92 -25
src/db/attendance.rsmodified+87 -23
| @@ -136,9 +136,13 @@ mod tests { | |||
| 136 | /// attendance rows and removes the row in one transaction, and a mark that | 136 | /// attendance rows and removes the row in one transaction, and a mark that |
| 137 | /// wrote into the gap was a bare upsert nothing would ever sweep again. | 137 | /// wrote into the gap was a bare upsert nothing would ever sweep again. |
| 138 | /// The mark now writes the event row too (its seats counter), so the two | 138 | /// The mark now writes the event row too (its seats counter), so the two |
| 139 | - /// transactions touch one row and Postgres refuses one of them; the barrier | 139 | + /// transactions touch one row and Postgres refuses one of them. |
| 140 | - /// releases both sides together so every interleaving gets its chance. | 140 | + /// |
| 141 | - /// Mutation-tested: turning the claim back into a read turns it red. | 141 | + /// Both orders are forced by awaiting one side to completion before the |
| 142 | + /// other starts. A barrier is a coin toss under load, and a run where the | ||
| 143 | + /// delete loses every overlapped round has still proved the invariant. | ||
| 144 | + /// Mutation-tested: turning the claim back into a read turns the | ||
| 145 | + /// write-first round red. | ||
| 142 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 146 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 143 | async fn a_mark_written_inside_a_delete_never_outlives_the_event() { | 147 | async fn a_mark_written_inside_a_delete_never_outlives_the_event() { |
| 144 | use crate::domain::event::{ | 148 | use crate::domain::event::{ |
| @@ -161,14 +165,10 @@ mod tests { | |||
| 161 | user | 165 | user |
| 162 | } | 166 | } |
| 163 | 167 | ||
| 164 | - let (db, _leases) = crate::database::init_test_db().await; | 168 | + async fn an_event(db: &Database, marker: &UserId) -> crate::domain::event::Event { |
| 165 | - let allowed: Vec<String> = Settings::defaults().get_attendance_statuses().to_vec(); | 169 | + crate::db::event::create( |
| 166 | - let marker = a_person(&db, "marker").await; | 170 | + db, |
| 167 | - let (mut swept, mut orphans) = (0, 0); | 171 | + marker, |
| 168 | - for round in 0..8 { | ||
| 169 | - let event = crate::db::event::create( | ||
| 170 | - &db, | ||
| 171 | - &marker, | ||
| 172 | EventTitle::try_new("gezi").unwrap(), | 172 | EventTitle::try_new("gezi").unwrap(), |
| 173 | EventDescription::try_new("").unwrap(), | 173 | EventDescription::try_new("").unwrap(), |
| 174 | EventAudience { | 174 | EventAudience { |
| @@ -182,11 +182,73 @@ mod tests { | |||
| 182 | None, | 182 | None, |
| 183 | ) | 183 | ) |
| 184 | .await | 184 | .await |
| 185 | - .unwrap(); | 185 | + .unwrap() |
| 186 | + } | ||
| 187 | + | ||
| 188 | + let (db, _leases) = crate::database::init_test_db().await; | ||
| 189 | + let allowed: Vec<String> = Settings::defaults().get_attendance_statuses().to_vec(); | ||
| 190 | + let marker = a_person(&db, "marker").await; | ||
| 191 | + | ||
| 192 | + // Delete-first: the event is gone before the mark starts. | ||
| 193 | + { | ||
| 194 | + let event = an_event(&db, &marker).await; | ||
| 195 | + let id = event.get_id().clone(); | ||
| 196 | + let dropped = crate::db::event::delete(&db, event).await; | ||
| 197 | + assert!( | ||
| 198 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 199 | + "delete-first: a delete must be answered, not 500: {dropped:?}" | ||
| 200 | + ); | ||
| 201 | + assert!( | ||
| 202 | + crate::db::event::read(&db, &id).await.unwrap().is_none(), | ||
| 203 | + "delete-first: the event is still there after delete: {dropped:?}" | ||
| 204 | + ); | ||
| 205 | + let student = a_person(&db, "df").await; | ||
| 206 | + let status = AttendanceStatus::try_new("present", &allowed).unwrap(); | ||
| 207 | + let marked = mark(&db, &id, &student, status, &marker).await; | ||
| 208 | + assert!( | ||
| 209 | + !matches!(marked, Err(AppError::Db(_))), | ||
| 210 | + "delete-first: a mark must be answered, not 500: {marked:?}" | ||
| 211 | + ); | ||
| 212 | + assert_eq!( | ||
| 213 | + list_for_event(&db, &id, None, 0).await.unwrap().0.len(), | ||
| 214 | + 0, | ||
| 215 | + "a mark outlived its event" | ||
| 216 | + ); | ||
| 217 | + } | ||
| 218 | + | ||
| 219 | + // Write-first: the mark lands, then the delete sweeps it. | ||
| 220 | + { | ||
| 221 | + let event = an_event(&db, &marker).await; | ||
| 222 | + let id = event.get_id().clone(); | ||
| 223 | + let student = a_person(&db, "wf").await; | ||
| 224 | + let status = AttendanceStatus::try_new("present", &allowed).unwrap(); | ||
| 225 | + let marked = mark(&db, &id, &student, status, &marker).await; | ||
| 226 | + assert!( | ||
| 227 | + marked.is_ok(), | ||
| 228 | + "write-first: the mark must land before the delete: {marked:?}" | ||
| 229 | + ); | ||
| 230 | + let dropped = crate::db::event::delete(&db, event).await; | ||
| 231 | + assert!( | ||
| 232 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 233 | + "write-first: a delete must be answered, not 500: {dropped:?}" | ||
| 234 | + ); | ||
| 235 | + assert!( | ||
| 236 | + crate::db::event::read(&db, &id).await.unwrap().is_none(), | ||
| 237 | + "write-first: the event is still there" | ||
| 238 | + ); | ||
| 239 | + assert_eq!( | ||
| 240 | + list_for_event(&db, &id, None, 0).await.unwrap().0.len(), | ||
| 241 | + 0, | ||
| 242 | + "a mark outlived its event" | ||
| 243 | + ); | ||
| 244 | + } | ||
| 245 | + | ||
| 246 | + // Overlapped rounds. Delete may lose every one of them. | ||
| 247 | + let mut swept = 0; | ||
| 248 | + for round in 0..4 { | ||
| 249 | + let event = an_event(&db, &marker).await; | ||
| 186 | let id = event.get_id().clone(); | 250 | let id = event.get_id().clone(); |
| 187 | 251 | ||
| 188 | - // Delete and mark released together: both write the event row, so | ||
| 189 | - // Postgres serializes them and refuses whichever lost. | ||
| 190 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | 252 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 191 | let drop_it = { | 253 | let drop_it = { |
| 192 | let (db, gate, event) = (db.clone(), gate.clone(), event); | 254 | let (db, gate, event) = (db.clone(), gate.clone(), event); |
| @@ -196,7 +258,7 @@ mod tests { | |||
| 196 | }) | 258 | }) |
| 197 | }; | 259 | }; |
| 198 | let marked = { | 260 | let marked = { |
| 199 | - let (db, id, marker, gate) = (db.clone(), id.clone(), marker, gate); | 261 | + let (db, id, marker, gate, allowed) = (db.clone(), id.clone(), marker, gate, allowed.clone()); |
| 200 | let student = a_person(&db, "student").await; | 262 | let student = a_person(&db, "student").await; |
| 201 | let status = AttendanceStatus::try_new("present", &allowed).unwrap(); | 263 | let status = AttendanceStatus::try_new("present", &allowed).unwrap(); |
| 202 | tokio::spawn(async move { | 264 | tokio::spawn(async move { |
| @@ -209,20 +271,22 @@ mod tests { | |||
| 209 | !matches!(marked, Err(AppError::Db(_))), | 271 | !matches!(marked, Err(AppError::Db(_))), |
| 210 | "round {round}: a raced mark must be answered, not 500: {marked:?}" | 272 | "round {round}: a raced mark must be answered, not 500: {marked:?}" |
| 211 | ); | 273 | ); |
| 274 | + assert!( | ||
| 275 | + !matches!(drop_it, Err(AppError::Db(_))), | ||
| 276 | + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" | ||
| 277 | + ); | ||
| 212 | 278 | ||
| 213 | - // Stored state is the whole verdict; a return value is not evidence. | ||
| 214 | if crate::db::event::read(&db, &id).await.unwrap().is_none() { | 279 | if crate::db::event::read(&db, &id).await.unwrap().is_none() { |
| 215 | swept += 1; | 280 | swept += 1; |
| 216 | - orphans += list_for_event(&db, &id, None, 0).await.unwrap().0.len(); | 281 | + assert_eq!( |
| 282 | + list_for_event(&db, &id, None, 0).await.unwrap().0.len(), | ||
| 283 | + 0, | ||
| 284 | + "round {round}: a mark outlived its event" | ||
| 285 | + ); | ||
| 217 | } else if drop_it.is_ok() { | 286 | } else if drop_it.is_ok() { |
| 218 | panic!("round {round}: the delete reported success but the event is still there"); | 287 | panic!("round {round}: the delete reported success but the event is still there"); |
| 219 | } | 288 | } |
| 220 | } | 289 | } |
| 221 | - eprintln!("Event::delete raced by a mark: {swept}/8 rounds deleted the event"); | 290 | + eprintln!("Event::delete raced by a mark: {swept}/4 concurrent rounds deleted the event"); |
| 222 | - assert!( | ||
| 223 | - swept > 0, | ||
| 224 | - "no round ever deleted the event, so the window was never reached" | ||
| 225 | - ); | ||
| 226 | - assert_eq!(orphans, 0, "a mark outlived its event"); | ||
| 227 | } | 291 | } |
| 228 | } | 292 | } |
src/db/bank_question_image.rsmodified+116 -31
| @@ -328,23 +328,116 @@ mod tests { | |||
| 328 | /// a blob stranded on disk. | 328 | /// a blob stranded on disk. |
| 329 | /// | 329 | /// |
| 330 | /// The upload writes the template row too (its `points`), so the two | 330 | /// The upload writes the template row too (its `points`), so the two |
| 331 | - /// transactions touch one row and Postgres refuses one of them; the | 331 | + /// transactions touch one row and Postgres refuses one of them. Both |
| 332 | - /// barrier releases both sides together so every interleaving gets its | 332 | + /// orders are forced by awaiting one side to completion before the other |
| 333 | - /// chance. | 333 | + /// starts. A barrier is a coin toss under load, and a run where the |
| 334 | + /// delete loses every overlapped round has still proved the invariant. | ||
| 334 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 335 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 335 | async fn an_image_written_inside_a_delete_window_never_outlives_its_template() { | 336 | async fn an_image_written_inside_a_delete_window_never_outlives_its_template() { |
| 336 | let (db, _leases) = crate::database::init_test_db().await; | 337 | let (db, _leases) = crate::database::init_test_db().await; |
| 337 | 338 | ||
| 338 | - let (mut swept, mut orphans, mut stranded) = (0, 0, 0); | 339 | + async fn upload( |
| 339 | - for round in 0..8 { | 340 | + db: &Database, |
| 341 | + question: &BankQuestionId, | ||
| 342 | + ) -> Result<(BankQuestionImage, Option<String>), AppError> { | ||
| 343 | + upsert(db, BankQuestionImage::new(question, None, png(), 3)).await | ||
| 344 | + } | ||
| 345 | + | ||
| 346 | + /// An image both sides report as committed must be in the list the | ||
| 347 | + /// delete hands back — that list is what the web layer unlinks from. | ||
| 348 | + fn stranded( | ||
| 349 | + child: &Result<(BankQuestionImage, Option<String>), AppError>, | ||
| 350 | + dropped: &Result<(crate::domain::bank_question::BankQuestion, Vec<BankQuestionImage>), AppError>, | ||
| 351 | + ) -> bool { | ||
| 352 | + if let (Ok((stored, _)), Ok((_, images))) = (child, dropped) { | ||
| 353 | + !images | ||
| 354 | + .iter() | ||
| 355 | + .any(|image| image.get_file() == stored.get_file()) | ||
| 356 | + } else { | ||
| 357 | + false | ||
| 358 | + } | ||
| 359 | + } | ||
| 360 | + | ||
| 361 | + // Delete-first: the template is gone before the upload starts. | ||
| 362 | + { | ||
| 363 | + let question = a_template(&db).await; | ||
| 364 | + let template = crate::db::bank_question::read(&db, &question) | ||
| 365 | + .await | ||
| 366 | + .unwrap() | ||
| 367 | + .unwrap(); | ||
| 368 | + let dropped = crate::db::bank_question::delete(&db, template).await; | ||
| 369 | + assert!( | ||
| 370 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 371 | + "delete-first: a delete must be answered, not 500: {dropped:?}" | ||
| 372 | + ); | ||
| 373 | + assert!( | ||
| 374 | + crate::db::bank_question::read(&db, &question) | ||
| 375 | + .await | ||
| 376 | + .unwrap() | ||
| 377 | + .is_none(), | ||
| 378 | + "delete-first: the template is still there after delete: {dropped:?}" | ||
| 379 | + ); | ||
| 380 | + let child = upload(&db, &question).await; | ||
| 381 | + assert!( | ||
| 382 | + !matches!(child, Err(AppError::Db(_))), | ||
| 383 | + "delete-first: an upload must be answered, not 500: {child:?}" | ||
| 384 | + ); | ||
| 385 | + assert_eq!( | ||
| 386 | + list_for_question(&db, &question).await.unwrap().len(), | ||
| 387 | + 0, | ||
| 388 | + "an image row outlived its template" | ||
| 389 | + ); | ||
| 390 | + assert!( | ||
| 391 | + !stranded(&child, &dropped), | ||
| 392 | + "an image committed inside the window was swept without being handed back, so its blob stays on disk" | ||
| 393 | + ); | ||
| 394 | + } | ||
| 395 | + | ||
| 396 | + // Write-first: the upload lands, then the delete sweeps it and must | ||
| 397 | + // hand the blob name back. | ||
| 398 | + { | ||
| 399 | + let question = a_template(&db).await; | ||
| 400 | + let template = crate::db::bank_question::read(&db, &question) | ||
| 401 | + .await | ||
| 402 | + .unwrap() | ||
| 403 | + .unwrap(); | ||
| 404 | + let child = upload(&db, &question).await; | ||
| 405 | + assert!( | ||
| 406 | + child.is_ok(), | ||
| 407 | + "write-first: the upload must land before the delete: {child:?}" | ||
| 408 | + ); | ||
| 409 | + let dropped = crate::db::bank_question::delete(&db, template).await; | ||
| 410 | + assert!( | ||
| 411 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 412 | + "write-first: a delete must be answered, not 500: {dropped:?}" | ||
| 413 | + ); | ||
| 414 | + assert!( | ||
| 415 | + crate::db::bank_question::read(&db, &question) | ||
| 416 | + .await | ||
| 417 | + .unwrap() | ||
| 418 | + .is_none(), | ||
| 419 | + "write-first: the template is still there" | ||
| 420 | + ); | ||
| 421 | + assert_eq!( | ||
| 422 | + list_for_question(&db, &question).await.unwrap().len(), | ||
| 423 | + 0, | ||
| 424 | + "an image row outlived its template" | ||
| 425 | + ); | ||
| 426 | + assert!( | ||
| 427 | + !stranded(&child, &dropped), | ||
| 428 | + "an image committed inside the window was swept without being handed back, so its blob stays on disk" | ||
| 429 | + ); | ||
| 430 | + } | ||
| 431 | + | ||
| 432 | + // Overlapped rounds. Delete may lose every one of them. | ||
| 433 | + let mut swept = 0; | ||
| 434 | + for round in 0..4 { | ||
| 340 | let question = a_template(&db).await; | 435 | let question = a_template(&db).await; |
| 341 | let template = crate::db::bank_question::read(&db, &question) | 436 | let template = crate::db::bank_question::read(&db, &question) |
| 342 | .await | 437 | .await |
| 343 | .unwrap() | 438 | .unwrap() |
| 344 | .unwrap(); | 439 | .unwrap(); |
| 345 | 440 | ||
| 346 | - // Delete and upload released together: both write the template row, | ||
| 347 | - // so Postgres serializes them and refuses whichever lost. | ||
| 348 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | 441 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 349 | let drop_it = { | 442 | let drop_it = { |
| 350 | let (db, gate, template) = (db.clone(), gate.clone(), template); | 443 | let (db, gate, template) = (db.clone(), gate.clone(), template); |
| @@ -357,50 +450,42 @@ mod tests { | |||
| 357 | let (db, question, gate) = (db.clone(), question.clone(), gate); | 450 | let (db, question, gate) = (db.clone(), question.clone(), gate); |
| 358 | tokio::spawn(async move { | 451 | tokio::spawn(async move { |
| 359 | gate.wait().await; | 452 | gate.wait().await; |
| 360 | - upsert(&db, BankQuestionImage::new(&question, None, png(), 3)).await | 453 | + upload(&db, &question).await |
| 361 | }) | 454 | }) |
| 362 | }; | 455 | }; |
| 363 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); | 456 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| 364 | - // A 404 for the upload is a correct answer; the only defect is | ||
| 365 | - // stored state. Neither side may 500 — they contend by design and a | ||
| 366 | - // lost round is re-sent, not reported. | ||
| 367 | assert!( | 457 | assert!( |
| 368 | !matches!(child, Err(AppError::Db(_))), | 458 | !matches!(child, Err(AppError::Db(_))), |
| 369 | "round {round}: a raced upload must be answered, not 500: {child:?}" | 459 | "round {round}: a raced upload must be answered, not 500: {child:?}" |
| 370 | ); | 460 | ); |
| 371 | assert!( | 461 | assert!( |
| 372 | !matches!(drop_it, Err(AppError::Db(_))), | 462 | !matches!(drop_it, Err(AppError::Db(_))), |
| 373 | - "round {round}: a raced delete must retry, not 500: {drop_it:?}" | 463 | + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" |
| 374 | ); | 464 | ); |
| 375 | 465 | ||
| 376 | - // Stored state is the whole verdict; a return value is not evidence. | ||
| 377 | if crate::db::bank_question::read(&db, &question) | 466 | if crate::db::bank_question::read(&db, &question) |
| 378 | .await | 467 | .await |
| 379 | .unwrap() | 468 | .unwrap() |
| 380 | .is_none() | 469 | .is_none() |
| 381 | { | 470 | { |
| 382 | swept += 1; | 471 | swept += 1; |
| 383 | - orphans += list_for_question(&db, &question).await.unwrap().len(); | 472 | + assert_eq!( |
| 384 | - if let (Ok((stored, _)), Ok((_, images))) = (&child, &drop_it) | 473 | + list_for_question(&db, &question).await.unwrap().len(), |
| 385 | - && !images | 474 | + 0, |
| 386 | - .iter() | 475 | + "round {round}: an image row outlived its template" |
| 387 | - .any(|image| image.get_file() == stored.get_file()) | 476 | + ); |
| 388 | - { | 477 | + assert!( |
| 389 | - stranded += 1; | 478 | + !stranded(&child, &drop_it), |
| 390 | - } | 479 | + "round {round}: an image committed inside the window was swept without being handed back" |
| 480 | + ); | ||
| 481 | + } else if drop_it.is_ok() { | ||
| 482 | + panic!( | ||
| 483 | + "round {round}: the delete reported success but the template is still there" | ||
| 484 | + ); | ||
| 391 | } | 485 | } |
| 392 | } | 486 | } |
| 393 | eprintln!( | 487 | eprintln!( |
| 394 | - "bank_question::delete raced by an upload: {swept}/8 rounds deleted the template" | 488 | + "bank_question::delete raced by an upload: {swept}/4 concurrent rounds deleted the template" |
| 395 | - ); | ||
| 396 | - assert!( | ||
| 397 | - swept > 0, | ||
| 398 | - "no round ever deleted the template, so the window was never reached" | ||
| 399 | - ); | ||
| 400 | - assert_eq!(orphans, 0, "an image row outlived its template"); | ||
| 401 | - assert_eq!( | ||
| 402 | - stranded, 0, | ||
| 403 | - "an image committed inside the window was swept without being handed back, so its blob stays on disk" | ||
| 404 | ); | 489 | ); |
| 405 | } | 490 | } |
| 406 | 491 | ||
src/db/chatbot_thread.rsmodified+105 -30
| @@ -385,17 +385,87 @@ mod tests { | |||
| 385 | /// The window the schema event used to force open is the thread row's own | 385 | /// The window the schema event used to force open is the thread row's own |
| 386 | /// lock now: a turn is written *through* the row ([`touch_and_write`]), | 386 | /// lock now: a turn is written *through* the row ([`touch_and_write`]), |
| 387 | /// so a turn racing the delete serializes on that row instead of | 387 | /// so a turn racing the delete serializes on that row instead of |
| 388 | - /// committing past the sweep. A barrier start lets both orders happen, | 388 | + /// committing past the sweep. Both orders are forced by awaiting one side |
| 389 | - /// and the invariant must hold in each. | 389 | + /// to completion before the other starts — a barrier is a coin toss under |
| 390 | + /// load, and a run where the delete loses every overlapped round has still | ||
| 391 | + /// proved the invariant. A few rounds still start together; those may all | ||
| 392 | + /// lose the delete, and that is not a failure. | ||
| 390 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 393 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 391 | async fn a_turn_written_inside_a_delete_never_outlives_the_thread() { | 394 | async fn a_turn_written_inside_a_delete_never_outlives_the_thread() { |
| 392 | - // One thread minted per round: the cap must cover every round, since | 395 | + // Forced rounds free their seat. Concurrent rounds may keep theirs, so |
| 393 | - // the rounds where the turn wins keep their thread (and its seat). | 396 | + // the cap covers every thread this test can leave standing. |
| 394 | - let (db, _leases) = a_user_capped_at(8).await; | 397 | + let (db, _leases) = a_user_capped_at(6).await; |
| 395 | - | ||
| 396 | let user = UserId::from_key(U); | 398 | let user = UserId::from_key(U); |
| 397 | - let (mut orphans, mut swept) = (0, 0); | 399 | + |
| 398 | - for round in 0..8 { | 400 | + async fn append( |
| 401 | + db: &Database, | ||
| 402 | + id: &ChatbotThreadId, | ||
| 403 | + user: &UserId, | ||
| 404 | + ) -> Result<(), AppError> { | ||
| 405 | + chatbot_message::append_user(db, id, user, ChatContent::try_new("selam").unwrap()) | ||
| 406 | + .await | ||
| 407 | + .map(|_| ()) | ||
| 408 | + } | ||
| 409 | + | ||
| 410 | + // Delete-first: the thread is gone before the turn starts. | ||
| 411 | + { | ||
| 412 | + let thread = create_capped(&db, &user, None).await.expect("thread"); | ||
| 413 | + let id = thread.get_id().clone(); | ||
| 414 | + let dropped = delete(&db, thread).await; | ||
| 415 | + assert!( | ||
| 416 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 417 | + "delete-first: a delete must be answered, not 500: {dropped:?}" | ||
| 418 | + ); | ||
| 419 | + assert!( | ||
| 420 | + read_for(&db, &id, &user).await.unwrap().is_none(), | ||
| 421 | + "delete-first: the thread is still there after delete: {dropped:?}" | ||
| 422 | + ); | ||
| 423 | + let turn = append(&db, &id, &user).await; | ||
| 424 | + assert!( | ||
| 425 | + !matches!(turn, Err(AppError::Db(_))), | ||
| 426 | + "delete-first: a turn must be answered, not 500: {turn:?}" | ||
| 427 | + ); | ||
| 428 | + assert_eq!( | ||
| 429 | + chatbot_message::list_for_thread(&db, &id, None, 0) | ||
| 430 | + .await | ||
| 431 | + .unwrap() | ||
| 432 | + .1, | ||
| 433 | + 0, | ||
| 434 | + "a turn outlived its thread" | ||
| 435 | + ); | ||
| 436 | + } | ||
| 437 | + | ||
| 438 | + // Write-first: the turn lands, then the delete sweeps it. | ||
| 439 | + { | ||
| 440 | + let thread = create_capped(&db, &user, None).await.expect("thread"); | ||
| 441 | + let id = thread.get_id().clone(); | ||
| 442 | + let turn = append(&db, &id, &user).await; | ||
| 443 | + assert!( | ||
| 444 | + turn.is_ok(), | ||
| 445 | + "write-first: the turn must land before the delete: {turn:?}" | ||
| 446 | + ); | ||
| 447 | + let dropped = delete(&db, thread).await; | ||
| 448 | + assert!( | ||
| 449 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 450 | + "write-first: a delete must be answered, not 500: {dropped:?}" | ||
| 451 | + ); | ||
| 452 | + assert!( | ||
| 453 | + read_for(&db, &id, &user).await.unwrap().is_none(), | ||
| 454 | + "write-first: the thread is still there" | ||
| 455 | + ); | ||
| 456 | + assert_eq!( | ||
| 457 | + chatbot_message::list_for_thread(&db, &id, None, 0) | ||
| 458 | + .await | ||
| 459 | + .unwrap() | ||
| 460 | + .1, | ||
| 461 | + 0, | ||
| 462 | + "a turn outlived its thread" | ||
| 463 | + ); | ||
| 464 | + } | ||
| 465 | + | ||
| 466 | + // Overlapped rounds. Delete may lose every one of them. | ||
| 467 | + let mut swept = 0; | ||
| 468 | + for round in 0..4 { | ||
| 399 | let thread = create_capped(&db, &user, None).await.expect("thread"); | 469 | let thread = create_capped(&db, &user, None).await.expect("thread"); |
| 400 | let id = thread.get_id().clone(); | 470 | let id = thread.get_id().clone(); |
| 401 | 471 | ||
| @@ -411,40 +481,45 @@ mod tests { | |||
| 411 | let (id, db, user, gate) = (id.clone(), db.clone(), user, gate); | 481 | let (id, db, user, gate) = (id.clone(), db.clone(), user, gate); |
| 412 | tokio::spawn(async move { | 482 | tokio::spawn(async move { |
| 413 | gate.wait().await; | 483 | gate.wait().await; |
| 414 | - chatbot_message::append_user( | 484 | + append(&db, &id, &user).await |
| 415 | - &db, | ||
| 416 | - &id, | ||
| 417 | - &user, | ||
| 418 | - ChatContent::try_new("selam").unwrap(), | ||
| 419 | - ) | ||
| 420 | - .await | ||
| 421 | - .map(|_| ()) | ||
| 422 | }) | 485 | }) |
| 423 | }; | 486 | }; |
| 424 | let (drop_it, turn) = (drop_it.await.unwrap(), turn.await.unwrap()); | 487 | let (drop_it, turn) = (drop_it.await.unwrap(), turn.await.unwrap()); |
| 425 | - // A 404 for the turn, or a NotFound for the delete, is a correct | ||
| 426 | - // answer — the only defect is stored state. | ||
| 427 | assert!( | 488 | assert!( |
| 428 | !matches!(turn, Err(AppError::Db(_))), | 489 | !matches!(turn, Err(AppError::Db(_))), |
| 429 | "round {round}: a raced turn must be answered, not 500: {turn:?}" | 490 | "round {round}: a raced turn must be answered, not 500: {turn:?}" |
| 430 | ); | 491 | ); |
| 431 | - | 492 | + // A lost round here is a 23503, not a missed sweep. The turn's |
| 432 | - // Stored state is the whole verdict; a return value is not evidence. | 493 | + // insert and this delete's `DELETE chatbot_message` do not share a |
| 433 | - if read_for(&db, &id, &user).await.unwrap().is_none() { | 494 | + // row lock, `chatbot_message.thread_id` is `ON DELETE NO ACTION`, |
| 495 | + // and [`delete`] does not retry that (`cascade = false`). The | ||
| 496 | + // thread is still there; nothing outlived a gone parent. Any other | ||
| 497 | + // database error is a 500. The forced rounds above are the ones | ||
| 498 | + // that require the delete itself to answer without one. | ||
| 499 | + let parent_gone = read_for(&db, &id, &user).await.unwrap().is_none(); | ||
| 500 | + if let Err(AppError::Db(err)) = &drop_it { | ||
| 501 | + let lost_the_gap = crate::database::foreign_key_violation(err) && !parent_gone; | ||
| 502 | + assert!( | ||
| 503 | + lost_the_gap, | ||
| 504 | + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" | ||
| 505 | + ); | ||
| 506 | + } | ||
| 507 | + if parent_gone { | ||
| 434 | swept += 1; | 508 | swept += 1; |
| 435 | - orphans += chatbot_message::list_for_thread(&db, &id, None, 0) | 509 | + assert_eq!( |
| 436 | - .await | 510 | + chatbot_message::list_for_thread(&db, &id, None, 0) |
| 437 | - .unwrap() | 511 | + .await |
| 438 | - .1; | 512 | + .unwrap() |
| 513 | + .1, | ||
| 514 | + 0, | ||
| 515 | + "round {round}: a turn outlived its thread" | ||
| 516 | + ); | ||
| 439 | } else if drop_it.is_ok() { | 517 | } else if drop_it.is_ok() { |
| 440 | panic!("round {round}: the delete reported success but the thread is still there"); | 518 | panic!("round {round}: the delete reported success but the thread is still there"); |
| 441 | } | 519 | } |
| 442 | } | 520 | } |
| 443 | - eprintln!("chatbot_thread::delete raced by a turn: {swept}/8 rounds deleted the thread"); | 521 | + eprintln!( |
| 444 | - assert!( | 522 | + "chatbot_thread::delete raced by a turn: {swept}/4 concurrent rounds deleted the thread" |
| 445 | - swept > 0, | ||
| 446 | - "no round ever deleted the thread, so the race never actually ran" | ||
| 447 | ); | 523 | ); |
| 448 | - assert_eq!(orphans, 0, "a turn outlived its thread"); | ||
| 449 | } | 524 | } |
| 450 | } | 525 | } |
src/db/course.rsmodified+189 -79
| @@ -717,13 +717,12 @@ pub(crate) async fn a_test_instance( | |||
| 717 | } | 717 | } |
| 718 | 718 | ||
| 719 | /// The race half of "a child of a course must not survive its deletion", run | 719 | /// The race half of "a child of a course must not survive its deletion", run |
| 720 | -/// for one child table: [`delete`] is held open by the schema and | 720 | +/// for one child table. |
| 721 | -/// `make` fires its create inside that window, eight rounds. | ||
| 722 | /// | 721 | /// |
| 723 | /// The harness lives here, beside the cascade being raced, and each child names | 722 | /// The harness lives here, beside the cascade being raced, and each child names |
| 724 | /// its own pin in its own module (`exam`, `course_session`, `subject`) — the | 723 | /// its own pin in its own module (`exam`, `course_session`, `subject`) — the |
| 725 | -/// loop, the window and the verdict are one fact about *this* delete, and three | 724 | +/// orders, the window and the verdict are one fact about *this* delete, and |
| 726 | -/// copies of it would drift into three different tests of three different | 725 | +/// three copies of it would drift into three different tests of three different |
| 727 | /// things. The sequential half — a create against a course that is already gone | 726 | /// things. The sequential half — a create against a course that is already gone |
| 728 | /// — is `tests/regress_course_child_orphans.rs`, which needs no server. | 727 | /// — is `tests/regress_course_child_orphans.rs`, which needs no server. |
| 729 | /// | 728 | /// |
| @@ -732,37 +731,111 @@ pub(crate) async fn a_test_instance( | |||
| 732 | /// hangs off an *instance* ([`crate::db::class_course`]) and reaches the course | 731 | /// hangs off an *instance* ([`crate::db::class_course`]) and reaches the course |
| 733 | /// through it. Either way it takes the course uuid as `$1`. | 732 | /// through it. Either way it takes the course uuid as `$1`. |
| 734 | /// | 733 | /// |
| 735 | -/// The window is opened by the database rather than by a lucky interleaving: | 734 | +/// Both orders are forced by awaiting one side to completion before the other |
| 736 | -/// Postgres puts the racing create and delete on the same rows (the FK claims | 735 | +/// starts. A barrier is a coin toss under load: whichever side is marginally |
| 737 | -/// and the cascade), so a barrier start covers every interleaving — and the | 736 | +/// faster takes every overlapped round, and requiring the delete to win one of |
| 738 | -/// child may never outlive the course in any of them. | 737 | +/// them fails a run that never let it. A few rounds still start together; those |
| 738 | +/// may all lose the delete, and that is not a failure. A rival that claims an | ||
| 739 | +/// instance (a session, an exam) makes the write-first delete a refusal — the | ||
| 740 | +/// course a class still teaches is not deletable — so that round asserts the | ||
| 741 | +/// refusal, not a sweep. The sweep is the delete-first round, and any round | ||
| 742 | +/// whose course is actually gone. | ||
| 739 | /// | 743 | /// |
| 740 | /// One child per round, for the reason the menu and `class_course` twins | 744 | /// One child per round, for the reason the menu and `class_course` twins |
| 741 | /// document: a second writer makes the delete lose and re-send, and the re-sent | 745 | /// document: a second writer makes the delete lose and re-send, and the re-sent |
| 742 | /// sweep clears the evidence. | 746 | /// sweep clears the evidence. |
| 743 | /// | 747 | /// |
| 744 | -/// Real server, and every caller is `#[ignore]`d for it: the subject *is* the | 748 | +/// Real server: the subject is the store's conflict detection, which an |
| 745 | -/// store's conflict detection, which `init_mem`'s embedded engine does not | 749 | +/// embedded engine does not have. |
| 746 | -/// have — it commits both sides and answers `Ok` to each, so this passes there | ||
| 747 | -/// on broken code. | ||
| 748 | #[cfg(test)] | 750 | #[cfg(test)] |
| 749 | pub(crate) async fn assert_no_child_outlives_a_course_delete( | 751 | pub(crate) async fn assert_no_child_outlives_a_course_delete( |
| 750 | table: &str, | 752 | table: &str, |
| 751 | orphan_count_sql: &str, | 753 | orphan_count_sql: &str, |
| 752 | make: fn(CourseId, Database) -> tokio::task::JoinHandle<Result<(), AppError>>, | 754 | make: fn(CourseId, Database) -> tokio::task::JoinHandle<Result<(), AppError>>, |
| 753 | ) { | 755 | ) { |
| 754 | - use sqlx::Row as _; | 756 | + |
| 757 | + async fn child_rows(db: &Database, sql: &str, course: &CourseId) -> usize { | ||
| 758 | + use sqlx::Row as _; | ||
| 759 | + sqlx::query(sqlx::AssertSqlSafe(sql.to_string())) | ||
| 760 | + .bind(course.uuid()) | ||
| 761 | + .fetch_one(db) | ||
| 762 | + .await | ||
| 763 | + .unwrap() | ||
| 764 | + .try_get::<i64, _>(0) | ||
| 765 | + .unwrap() as usize | ||
| 766 | + } | ||
| 755 | 767 | ||
| 756 | let (db, _leases) = crate::database::init_test_db().await; | 768 | let (db, _leases) = crate::database::init_test_db().await; |
| 757 | 769 | ||
| 758 | - let (mut swept, mut orphans) = (0, 0); | 770 | + // Delete-first: the course is gone before the child starts. |
| 759 | - for round in 0..8 { | 771 | + { |
| 772 | + let course = a_test_course(&db).await; | ||
| 773 | + let dropped = delete( | ||
| 774 | + &db, | ||
| 775 | + read(&db, &course) | ||
| 776 | + .await | ||
| 777 | + .unwrap() | ||
| 778 | + .expect("the course is there"), | ||
| 779 | + ) | ||
| 780 | + .await; | ||
| 781 | + assert!( | ||
| 782 | + matches!(dropped, Ok(true)), | ||
| 783 | + "{table} delete-first: an empty course must delete, not {dropped:?}" | ||
| 784 | + ); | ||
| 785 | + assert!( | ||
| 786 | + read(&db, &course).await.unwrap().is_none(), | ||
| 787 | + "{table} delete-first: the course is still there" | ||
| 788 | + ); | ||
| 789 | + let child = make(course.clone(), db.clone()).await.unwrap(); | ||
| 790 | + assert!( | ||
| 791 | + !matches!(child, Err(AppError::Db(_))), | ||
| 792 | + "{table} delete-first: a create must be answered, not 500: {child:?}" | ||
| 793 | + ); | ||
| 794 | + assert_eq!( | ||
| 795 | + child_rows(&db, orphan_count_sql, &course).await, | ||
| 796 | + 0, | ||
| 797 | + "{table}: a child outlived its course" | ||
| 798 | + ); | ||
| 799 | + } | ||
| 800 | + | ||
| 801 | + // Write-first: the child lands, then the delete. A rival that claimed an | ||
| 802 | + // instance makes this a refusal — the course stays, and that is correct. | ||
| 803 | + // A rival that did not (a subject) is swept: the course is gone and the | ||
| 804 | + // child count is 0. | ||
| 805 | + { | ||
| 806 | + let course = a_test_course(&db).await; | ||
| 807 | + let child = make(course.clone(), db.clone()).await.unwrap(); | ||
| 808 | + assert!( | ||
| 809 | + child.is_ok(), | ||
| 810 | + "{table} write-first: the child must land before the delete: {child:?}" | ||
| 811 | + ); | ||
| 812 | + let row = read(&db, &course).await.unwrap().expect( | ||
| 813 | + "{table} write-first: the course vanished before the delete", | ||
| 814 | + ); | ||
| 815 | + let dropped = delete(&db, row).await; | ||
| 816 | + assert!( | ||
| 817 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 818 | + "{table} write-first: a delete must be answered, not 500: {dropped:?}" | ||
| 819 | + ); | ||
| 820 | + let gone = read(&db, &course).await.unwrap().is_none(); | ||
| 821 | + if matches!(dropped, Ok(true)) && !gone { | ||
| 822 | + panic!( | ||
| 823 | + "{table} write-first: the delete reported success, the course is still there" | ||
| 824 | + ); | ||
| 825 | + } | ||
| 826 | + if gone { | ||
| 827 | + assert_eq!( | ||
| 828 | + child_rows(&db, orphan_count_sql, &course).await, | ||
| 829 | + 0, | ||
| 830 | + "{table}: a child outlived its course" | ||
| 831 | + ); | ||
| 832 | + } | ||
| 833 | + } | ||
| 834 | + | ||
| 835 | + // Overlapped rounds. Delete may lose every one of them. | ||
| 836 | + let mut swept = 0; | ||
| 837 | + for round in 0..4 { | ||
| 760 | let course = a_test_course(&db).await; | 838 | let course = a_test_course(&db).await; |
| 761 | - // The old engine needed a schema event to hold the delete's window | ||
| 762 | - // open; Postgres puts the racing create and delete on the same rows | ||
| 763 | - // (the FK claims and the cascade), so a barrier start covers every | ||
| 764 | - // interleaving — and the child may never outlive the course in any | ||
| 765 | - // of them. | ||
| 766 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | 839 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 767 | let drop_it = { | 840 | let drop_it = { |
| 768 | let (course, db, gate) = (course.clone(), db.clone(), gate.clone()); | 841 | 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( | |||
| 782 | let (course, db, gate) = (course.clone(), db.clone(), gate); | 855 | let (course, db, gate) = (course.clone(), db.clone(), gate); |
| 783 | tokio::spawn(async move { | 856 | tokio::spawn(async move { |
| 784 | gate.wait().await; | 857 | gate.wait().await; |
| 785 | - // The inner task joins here: a `Db` answer stays `Err`, only a | ||
| 786 | - // panic inside `make` (or the outer join) would panic. | ||
| 787 | make(course, db).await.unwrap() | 858 | make(course, db).await.unwrap() |
| 788 | }) | 859 | }) |
| 789 | } | 860 | } |
| 790 | .await | 861 | .await |
| 791 | .unwrap(); | 862 | .unwrap(); |
| 792 | let dropped = drop_it.await.unwrap(); | 863 | let dropped = drop_it.await.unwrap(); |
| 793 | - | ||
| 794 | - // A 404 for the create, or a refusal for the delete, is a correct | ||
| 795 | - // answer — the only defect is stored state. Nothing may 500. | ||
| 796 | assert!( | 864 | assert!( |
| 797 | !matches!(child, Err(AppError::Db(_))), | 865 | !matches!(child, Err(AppError::Db(_))), |
| 798 | "{table} round {round}: a raced create must be answered, not 500: {child:?}" | 866 | "{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( | |||
| 801 | !matches!(dropped, Err(AppError::Db(_))), | 869 | !matches!(dropped, Err(AppError::Db(_))), |
| 802 | "{table} round {round}: a raced delete must be answered, not 500: {dropped:?}" | 870 | "{table} round {round}: a raced delete must be answered, not 500: {dropped:?}" |
| 803 | ); | 871 | ); |
| 804 | - | ||
| 805 | - // Stored state is the whole verdict; a return value is not evidence. | ||
| 806 | if read(&db, &course).await.unwrap().is_none() { | 872 | if read(&db, &course).await.unwrap().is_none() { |
| 807 | swept += 1; | 873 | swept += 1; |
| 808 | - orphans += sqlx::query(sqlx::AssertSqlSafe(orphan_count_sql.to_string())) | 874 | + assert_eq!( |
| 809 | - .bind(course.uuid()) | 875 | + child_rows(&db, orphan_count_sql, &course).await, |
| 810 | - .fetch_one(&db) | 876 | + 0, |
| 811 | - .await | 877 | + "{table} round {round}: a child outlived its course" |
| 812 | - .unwrap() | 878 | + ); |
| 813 | - .try_get::<i64, _>(0) | ||
| 814 | - .unwrap() as usize; | ||
| 815 | } else if matches!(dropped, Ok(true)) { | 879 | } else if matches!(dropped, Ok(true)) { |
| 816 | - panic!("{table} round {round}: the delete reported success, the course is still there"); | 880 | + panic!( |
| 881 | + "{table} round {round}: the delete reported success, the course is still there" | ||
| 882 | + ); | ||
| 817 | } | 883 | } |
| 818 | } | 884 | } |
| 819 | - eprintln!("Course::delete raced by a {table} create: {swept}/8 rounds deleted the course"); | 885 | + eprintln!( |
| 820 | - assert!( | 886 | + "Course::delete raced by a {table} create: {swept}/4 concurrent rounds deleted the course" |
| 821 | - swept > 0, | ||
| 822 | - "{table}: no round ever deleted the course, so the race never actually ran" | ||
| 823 | ); | 887 | ); |
| 824 | - assert_eq!(orphans, 0, "{table}: a child outlived its course"); | ||
| 825 | } | 888 | } |
| 826 | 889 | ||
| 827 | #[cfg(test)] | 890 | #[cfg(test)] |
| @@ -975,16 +1038,12 @@ mod tests { | |||
| 975 | /// half of the verdict is the orphan check — an instance may never name a | 1038 | /// half of the verdict is the orphan check — an instance may never name a |
| 976 | /// course that is gone, whichever side of the race it was on. | 1039 | /// course that is gone, whichever side of the race it was on. |
| 977 | /// | 1040 | /// |
| 978 | - /// The rate is counted over the whole loop instead of asserted per round, | 1041 | + /// The 500s are counted over the overlapped rounds instead of asserted at |
| 979 | - /// because a per-round `assert!` aborts at the first hit and would report | 1042 | + /// the first hit, so a lost retry reports how often it happened. Those |
| 980 | - /// "1 of 1" for a bug the point of this test is to *quantify*. | 1043 | + /// rounds do not have to observe both verdicts: a 2ms head start is still |
| 981 | - /// | 1044 | + /// a coin toss under pool contention. Delete-first and attach-first below |
| 982 | - /// Each side gets a clear head start on every other round — 2ms is a | 1045 | + /// force the two orders by awaiting one side to completion. A delete that |
| 983 | - /// separation the several-statement rival cannot cross (the same spacing | 1046 | + /// reports success (`Ok(true)`) while the course remains is still a bug. |
| 984 | - /// [`crate::db::term`]'s race test settled on). Without it the two sides | ||
| 985 | - /// compete for the same course row and whichever one is marginally faster | ||
| 986 | - /// takes every round, leaving one half of the verdict (`swept > 0`, or | ||
| 987 | - /// `attached > 0`) a coin toss under load. | ||
| 988 | /// | 1047 | /// |
| 989 | /// Multi-threaded and on a real server: the current-thread runtime never | 1048 | /// Multi-threaded and on a real server: the current-thread runtime never |
| 990 | /// interleaves the two, and an embedded engine does not conflict-check | 1049 | /// interleaves the two, and an embedded engine does not conflict-check |
| @@ -999,27 +1058,84 @@ mod tests { | |||
| 999 | for seat in 0..6 { | 1058 | for seat in 0..6 { |
| 1000 | classes.push(a_class(&manager, &format!("9-{seat}"), &db).await); | 1059 | classes.push(a_class(&manager, &format!("9-{seat}"), &db).await); |
| 1001 | } | 1060 | } |
| 1002 | - let (mut delete_500, mut attach_500, mut attached, mut swept) = (0, 0, 0, 0); | 1061 | + |
| 1062 | + // Delete-first: the course is gone before any attach starts. | ||
| 1063 | + { | ||
| 1064 | + let course = a_course(&db).await; | ||
| 1065 | + let dropped = delete(&db, course.clone()).await; | ||
| 1066 | + assert!( | ||
| 1067 | + matches!(dropped, Ok(true)), | ||
| 1068 | + "delete-first: an empty course must delete, not {dropped:?}" | ||
| 1069 | + ); | ||
| 1070 | + assert!( | ||
| 1071 | + read(&db, course.get_id()).await.unwrap().is_none(), | ||
| 1072 | + "delete-first: the course is still there" | ||
| 1073 | + ); | ||
| 1074 | + for class in &classes { | ||
| 1075 | + let attached = crate::service::class_course::attach( | ||
| 1076 | + &db, | ||
| 1077 | + class.get_id(), | ||
| 1078 | + course.get_id(), | ||
| 1079 | + &manager, | ||
| 1080 | + ) | ||
| 1081 | + .await; | ||
| 1082 | + assert!( | ||
| 1083 | + !matches!(attached, Err(AppError::Db(_))), | ||
| 1084 | + "delete-first: an attach must be answered, not 500: {attached:?}" | ||
| 1085 | + ); | ||
| 1086 | + } | ||
| 1087 | + assert_eq!( | ||
| 1088 | + instance_rows(course.get_id(), &db).await, | ||
| 1089 | + 0, | ||
| 1090 | + "an instance outlived the course" | ||
| 1091 | + ); | ||
| 1092 | + } | ||
| 1093 | + | ||
| 1094 | + // Attach-first: the guard must refuse. The course stays; that is the | ||
| 1095 | + // verdict, not a missed sweep. | ||
| 1096 | + { | ||
| 1097 | + let course = a_course(&db).await; | ||
| 1098 | + for class in &classes { | ||
| 1099 | + let attached = crate::service::class_course::attach( | ||
| 1100 | + &db, | ||
| 1101 | + class.get_id(), | ||
| 1102 | + course.get_id(), | ||
| 1103 | + &manager, | ||
| 1104 | + ) | ||
| 1105 | + .await; | ||
| 1106 | + assert!( | ||
| 1107 | + attached.is_ok(), | ||
| 1108 | + "attach-first: the attach must land before the delete: {attached:?}" | ||
| 1109 | + ); | ||
| 1110 | + } | ||
| 1111 | + let dropped = delete(&db, course.clone()).await; | ||
| 1112 | + assert!( | ||
| 1113 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 1114 | + "attach-first: a delete must be answered, not 500: {dropped:?}" | ||
| 1115 | + ); | ||
| 1116 | + assert!( | ||
| 1117 | + matches!(dropped, Ok(false)), | ||
| 1118 | + "attach-first: a course a class still teaches must refuse, not {dropped:?}" | ||
| 1119 | + ); | ||
| 1120 | + assert!( | ||
| 1121 | + read(&db, course.get_id()).await.unwrap().is_some(), | ||
| 1122 | + "attach-first: the refused delete removed the course" | ||
| 1123 | + ); | ||
| 1124 | + assert!( | ||
| 1125 | + instance_rows(course.get_id(), &db).await > 0, | ||
| 1126 | + "attach-first: the landed instances are gone" | ||
| 1127 | + ); | ||
| 1128 | + } | ||
| 1129 | + | ||
| 1130 | + // Overlapped rounds keep the retry measurement. Delete may lose all | ||
| 1131 | + // of them. | ||
| 1132 | + let (mut delete_500, mut attach_500, mut swept) = (0, 0, 0); | ||
| 1003 | let (mut last_delete, mut last_attach) = (String::new(), String::new()); | 1133 | let (mut last_delete, mut last_attach) = (String::new(), String::new()); |
| 1004 | for round in 0..20 { | 1134 | for round in 0..20 { |
| 1005 | let course = a_course(&db).await; | 1135 | let course = a_course(&db).await; |
| 1006 | - | ||
| 1007 | - // Every other round the attaches are held back so the delete wins | ||
| 1008 | - // outright (the course goes, and nothing may survive it); the rest | ||
| 1009 | - // release the attaches first, which is the round where the guard | ||
| 1010 | - // has to read their claim and refuse the delete. | ||
| 1011 | - let clear = std::time::Duration::from_millis(2); | ||
| 1012 | - let (delete_beat, attach_beat) = if round % 2 == 0 { | ||
| 1013 | - (std::time::Duration::ZERO, clear) | ||
| 1014 | - } else { | ||
| 1015 | - (clear, std::time::Duration::ZERO) | ||
| 1016 | - }; | ||
| 1017 | let drop_it = { | 1136 | let drop_it = { |
| 1018 | let (course, db) = (course.clone(), db.clone()); | 1137 | let (course, db) = (course.clone(), db.clone()); |
| 1019 | - tokio::spawn(async move { | 1138 | + tokio::spawn(async move { delete(&db, course).await }) |
| 1020 | - tokio::time::sleep(delete_beat).await; | ||
| 1021 | - delete(&db, course).await | ||
| 1022 | - }) | ||
| 1023 | }; | 1139 | }; |
| 1024 | let joins: Vec<_> = classes | 1140 | let joins: Vec<_> = classes |
| 1025 | .iter() | 1141 | .iter() |
| @@ -1031,7 +1147,6 @@ mod tests { | |||
| 1031 | manager, | 1147 | manager, |
| 1032 | ); | 1148 | ); |
| 1033 | tokio::spawn(async move { | 1149 | tokio::spawn(async move { |
| 1034 | - tokio::time::sleep(attach_beat).await; | ||
| 1035 | crate::service::class_course::attach(&db, &class, &course, &mgr).await | 1150 | crate::service::class_course::attach(&db, &class, &course, &mgr).await |
| 1036 | }) | 1151 | }) |
| 1037 | }) | 1152 | }) |
| @@ -1048,14 +1163,14 @@ mod tests { | |||
| 1048 | last_attach = format!("{join:?}"); | 1163 | last_attach = format!("{join:?}"); |
| 1049 | } | 1164 | } |
| 1050 | } | 1165 | } |
| 1051 | - // Stored state, not the return values: an instance that landed is | ||
| 1052 | - // what the guard had to see, and one that outlived a deleted | ||
| 1053 | - // course is the defect this whole shape exists to catch. | ||
| 1054 | let live = instance_rows(course.get_id(), &db).await; | 1166 | let live = instance_rows(course.get_id(), &db).await; |
| 1055 | - if live > 0 { | 1167 | + let gone = read(&db, course.get_id()).await.unwrap().is_none(); |
| 1056 | - attached += 1; | 1168 | + if matches!(drop_it, Ok(true)) && !gone { |
| 1169 | + panic!( | ||
| 1170 | + "round {round}: the delete reported success, the course is still there" | ||
| 1171 | + ); | ||
| 1057 | } | 1172 | } |
| 1058 | - if read(&db, course.get_id()).await.unwrap().is_none() { | 1173 | + if gone { |
| 1059 | swept += 1; | 1174 | swept += 1; |
| 1060 | assert_eq!( | 1175 | assert_eq!( |
| 1061 | live, 0, | 1176 | live, 0, |
| @@ -1065,12 +1180,7 @@ mod tests { | |||
| 1065 | } | 1180 | } |
| 1066 | eprintln!( | 1181 | eprintln!( |
| 1067 | "Course::delete raced: {delete_500}/20 delete 500s, {attach_500} attach 500s, \ | 1182 | "Course::delete raced: {delete_500}/20 delete 500s, {attach_500} attach 500s, \ |
| 1068 | - {attached} rounds with an instance attached / {swept} rounds the course went" | 1183 | + {swept} rounds the course went" |
| 1069 | - ); | ||
| 1070 | - assert!( | ||
| 1071 | - attached > 0 && swept > 0, | ||
| 1072 | - "the sweep never crossed the window ({attached} attached / {swept} swept), \ | ||
| 1073 | - so at least one verdict was never exercised" | ||
| 1074 | ); | 1184 | ); |
| 1075 | assert_eq!( | 1185 | assert_eq!( |
| 1076 | delete_500, 0, | 1186 | delete_500, 0, |
src/db/exam.rsmodified+436 -134
| @@ -496,6 +496,7 @@ pub async fn update_if_unchanged( | |||
| 496 | /// What [`delete`] collects on its way through: the deleted row plus the | 496 | /// What [`delete`] collects on its way through: the deleted row plus the |
| 497 | /// blob keys of the image rows its cascade removed — exactly whose files | 497 | /// blob keys of the image rows its cascade removed — exactly whose files |
| 498 | /// the web layer may unlink. | 498 | /// the web layer may unlink. |
| 499 | +#[derive(Debug)] | ||
| 499 | pub struct Deleted { | 500 | pub struct Deleted { |
| 500 | pub exam: Exam, | 501 | pub exam: Exam, |
| 501 | pub question_image_files: Vec<String>, | 502 | pub question_image_files: Vec<String>, |
| @@ -1242,30 +1243,90 @@ mod tests { | |||
| 1242 | /// | 1243 | /// |
| 1243 | /// One child per round, deliberately — in the menu twin, two children in one | 1244 | /// One child per round, deliberately — in the menu twin, two children in one |
| 1244 | /// round hid the bug: the first writer made the delete lose and re-send, and | 1245 | /// round hid the bug: the first writer made the delete lose and re-send, and |
| 1245 | - /// the re-sent sweep removed the other's row. | 1246 | + /// the re-sent sweep removed the other's row. Both orders are forced by |
| 1247 | + /// awaiting one side to completion before the other starts. Overlapped | ||
| 1248 | + /// rounds may all lose the delete; that is not a failure. | ||
| 1246 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 1249 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1247 | async fn an_answer_written_inside_a_delete_never_outlives_the_exam() { | 1250 | async fn an_answer_written_inside_a_delete_never_outlives_the_exam() { |
| 1248 | use crate::db::exam_answer; | 1251 | use crate::db::exam_answer; |
| 1249 | let (db, _leases) = crate::database::init_test_db().await; | 1252 | let (db, _leases) = crate::database::init_test_db().await; |
| 1250 | 1253 | ||
| 1251 | - let (mut answers, mut swept) = (0, 0); | 1254 | + let student = a_person(&db, "student", "student").await; |
| 1252 | - for round in 0..8 { | 1255 | + |
| 1256 | + // Delete-first: the exam is gone before the save starts. | ||
| 1257 | + { | ||
| 1258 | + let exam = published(&db).await; | ||
| 1259 | + let question = question_on(&exam, &db).await; | ||
| 1260 | + let id = exam.get_id().clone(); | ||
| 1261 | + let pick = question.get_choices().unwrap()[1] | ||
| 1262 | + .get_id() | ||
| 1263 | + .as_str() | ||
| 1264 | + .to_string(); | ||
| 1265 | + let dropped = delete(&db, exam).await; | ||
| 1266 | + assert!( | ||
| 1267 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 1268 | + "delete-first: a delete must be answered, not 500: {dropped:?}" | ||
| 1269 | + ); | ||
| 1270 | + assert!( | ||
| 1271 | + read(&db, &id).await.unwrap().is_none(), | ||
| 1272 | + "delete-first: the exam is still there after delete: {dropped:?}" | ||
| 1273 | + ); | ||
| 1274 | + let child = exam_answer::save(&db, &question, &student, 1, Some(pick), None).await; | ||
| 1275 | + assert!( | ||
| 1276 | + !matches!(child, Err(AppError::Db(_))), | ||
| 1277 | + "delete-first: a save must be answered, not 500: {child:?}" | ||
| 1278 | + ); | ||
| 1279 | + assert_eq!( | ||
| 1280 | + exam_answer::list_for_exam(&db, &id).await.unwrap().len(), | ||
| 1281 | + 0, | ||
| 1282 | + "an answer outlived its exam" | ||
| 1283 | + ); | ||
| 1284 | + } | ||
| 1285 | + | ||
| 1286 | + // Write-first: the save lands, then the delete sweeps it. | ||
| 1287 | + { | ||
| 1288 | + let exam = published(&db).await; | ||
| 1289 | + let question = question_on(&exam, &db).await; | ||
| 1290 | + let id = exam.get_id().clone(); | ||
| 1291 | + let pick = question.get_choices().unwrap()[1] | ||
| 1292 | + .get_id() | ||
| 1293 | + .as_str() | ||
| 1294 | + .to_string(); | ||
| 1295 | + let child = exam_answer::save(&db, &question, &student, 1, Some(pick), None).await; | ||
| 1296 | + assert!( | ||
| 1297 | + child.is_ok(), | ||
| 1298 | + "write-first: the save must land before the delete: {child:?}" | ||
| 1299 | + ); | ||
| 1300 | + let dropped = delete(&db, exam).await; | ||
| 1301 | + assert!( | ||
| 1302 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 1303 | + "write-first: a delete must be answered, not 500: {dropped:?}" | ||
| 1304 | + ); | ||
| 1305 | + assert!( | ||
| 1306 | + read(&db, &id).await.unwrap().is_none(), | ||
| 1307 | + "write-first: the exam is still there" | ||
| 1308 | + ); | ||
| 1309 | + assert_eq!( | ||
| 1310 | + exam_answer::list_for_exam(&db, &id).await.unwrap().len(), | ||
| 1311 | + 0, | ||
| 1312 | + "an answer outlived its exam" | ||
| 1313 | + ); | ||
| 1314 | + } | ||
| 1315 | + | ||
| 1316 | + // Overlapped rounds. Delete may lose every one of them. | ||
| 1317 | + let mut swept = 0; | ||
| 1318 | + for round in 0..4 { | ||
| 1253 | let exam = published(&db).await; | 1319 | let exam = published(&db).await; |
| 1254 | let question = question_on(&exam, &db).await; | 1320 | let question = question_on(&exam, &db).await; |
| 1255 | let id = exam.get_id().clone(); | 1321 | let id = exam.get_id().clone(); |
| 1256 | - let student = a_person(&db, "student", "student").await; | ||
| 1257 | - // The stored choice ids are minted by the create, not the ones the | ||
| 1258 | - // spec asked for — an answer must name one of *those*. | ||
| 1259 | let pick = question.get_choices().unwrap()[1] | 1322 | let pick = question.get_choices().unwrap()[1] |
| 1260 | .get_id() | 1323 | .get_id() |
| 1261 | .as_str() | 1324 | .as_str() |
| 1262 | .to_string(); | 1325 | .to_string(); |
| 1263 | 1326 | ||
| 1264 | - // Delete and save released together: both write the exam row, so | ||
| 1265 | - // Postgres serializes them and refuses whichever lost. | ||
| 1266 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | 1327 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 1267 | let drop_it = { | 1328 | let drop_it = { |
| 1268 | - let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone()); | 1329 | + let (db, exam, gate) = (db.clone(), exam, gate.clone()); |
| 1269 | tokio::spawn(async move { | 1330 | tokio::spawn(async move { |
| 1270 | gate.wait().await; | 1331 | gate.wait().await; |
| 1271 | delete(&db, exam).await | 1332 | delete(&db, exam).await |
| @@ -1273,44 +1334,47 @@ mod tests { | |||
| 1273 | }; | 1334 | }; |
| 1274 | let child = { | 1335 | let child = { |
| 1275 | let (db, question, student, pick, gate) = | 1336 | let (db, question, student, pick, gate) = |
| 1276 | - (db.clone(), question.clone(), student, pick, gate); | 1337 | + (db.clone(), question, student, pick, gate); |
| 1277 | tokio::spawn(async move { | 1338 | tokio::spawn(async move { |
| 1278 | gate.wait().await; | 1339 | gate.wait().await; |
| 1279 | exam_answer::save(&db, &question, &student, 1, Some(pick), None).await | 1340 | exam_answer::save(&db, &question, &student, 1, Some(pick), None).await |
| 1280 | }) | 1341 | }) |
| 1281 | }; | 1342 | }; |
| 1282 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); | 1343 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| 1283 | - // A 404 for the save, or a refusal for the delete, is a correct | ||
| 1284 | - // answer — the only defect is stored state. | ||
| 1285 | assert!( | 1344 | assert!( |
| 1286 | !matches!(child, Err(AppError::Db(_))), | 1345 | !matches!(child, Err(AppError::Db(_))), |
| 1287 | "round {round}: a raced save must be answered, not 500: {child:?}" | 1346 | "round {round}: a raced save must be answered, not 500: {child:?}" |
| 1288 | ); | 1347 | ); |
| 1348 | + assert!( | ||
| 1349 | + !matches!(drop_it, Err(AppError::Db(_))), | ||
| 1350 | + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" | ||
| 1351 | + ); | ||
| 1289 | 1352 | ||
| 1290 | - // Stored state is the whole verdict; a return value is not evidence. | ||
| 1291 | if read(&db, &id).await.unwrap().is_none() { | 1353 | if read(&db, &id).await.unwrap().is_none() { |
| 1292 | swept += 1; | 1354 | swept += 1; |
| 1293 | - answers += exam_answer::list_for_exam(&db, &id).await.unwrap().len(); | 1355 | + assert_eq!( |
| 1356 | + exam_answer::list_for_exam(&db, &id).await.unwrap().len(), | ||
| 1357 | + 0, | ||
| 1358 | + "round {round}: an answer outlived its exam" | ||
| 1359 | + ); | ||
| 1294 | } else if drop_it.is_ok() { | 1360 | } else if drop_it.is_ok() { |
| 1295 | panic!("round {round}: the delete reported success but the exam is still there"); | 1361 | panic!("round {round}: the delete reported success but the exam is still there"); |
| 1296 | } | 1362 | } |
| 1297 | } | 1363 | } |
| 1298 | - eprintln!("Exam::delete raced by an answer save: {swept}/8 rounds deleted the exam"); | 1364 | + eprintln!("Exam::delete raced by an answer save: {swept}/4 concurrent rounds deleted the exam"); |
| 1299 | - assert!( | ||
| 1300 | - swept > 0, | ||
| 1301 | - "no round ever deleted the exam, so the window was never reached" | ||
| 1302 | - ); | ||
| 1303 | - assert_eq!(answers, 0, "an answer outlived its exam"); | ||
| 1304 | } | 1365 | } |
| 1305 | 1366 | ||
| 1306 | /// The same defect on the teacher's side of the sheet, and a worse one: a | 1367 | /// The same defect on the teacher's side of the sheet, and a worse one: a |
| 1307 | /// question written inside the delete window kept the reference it claimed | 1368 | /// question written inside the delete window kept the reference it claimed |
| 1308 | /// on its subject (the cascade's per-subject decrement counted only the | 1369 | /// on its subject (the cascade's per-subject decrement counted only the |
| 1309 | - /// rows it could see), and [`crate::db::subject::delete`] is | 1370 | + /// rows it could see), and [`crate::db::subject::delete`] is gated on that |
| 1310 | - /// gated on that count reading zero — a subject nobody could ever delete | 1371 | + /// count reading zero — a subject nobody could ever delete again, hanging |
| 1311 | - /// again, hanging off an exam nobody could ever see. The freeze gate is a | 1372 | + /// off an exam nobody could ever see. The freeze gate is a *read* of |
| 1312 | - /// *read* of `exam_attempt` and never survived this window; | 1373 | + /// `exam_attempt` and never survived this window; |
| 1313 | - /// [`crate::db::exam_attempt::write_unfrozen_with`] now writes the exam row too. | 1374 | + /// [`crate::db::exam_attempt::write_unfrozen_with`] now writes the exam row |
| 1375 | + /// too. Both orders are forced by awaiting one side to completion before | ||
| 1376 | + /// the other starts. Overlapped rounds may all lose the delete; that is | ||
| 1377 | + /// not a failure. | ||
| 1314 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 1378 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1315 | async fn a_question_written_inside_a_delete_never_outlives_the_exam() { | 1379 | async fn a_question_written_inside_a_delete_never_outlives_the_exam() { |
| 1316 | use crate::domain::exam_question::{ | 1380 | use crate::domain::exam_question::{ |
| @@ -1318,24 +1382,143 @@ mod tests { | |||
| 1318 | }; | 1382 | }; |
| 1319 | let (db, _leases) = crate::database::init_test_db().await; | 1383 | let (db, _leases) = crate::database::init_test_db().await; |
| 1320 | 1384 | ||
| 1321 | - let (mut questions, mut swept, mut stuck) = (0, 0, 0); | 1385 | + fn spec() -> QuestionSpec { |
| 1322 | - for round in 0..8 { | 1386 | + QuestionSpec::try_new( |
| 1323 | - let exam = published(&db).await; | 1387 | + QuestionKind::try_new("choice").unwrap(), |
| 1324 | - let id = exam.get_id().clone(); | 1388 | + Some(vec![ |
| 1325 | - let subject = crate::db::subject::create( | 1389 | + ChoiceInput { |
| 1326 | - &db, | 1390 | + id: Some("a".into()), |
| 1327 | - &crate::db::course::a_test_course(&db).await, | 1391 | + text: "5".into(), |
| 1392 | + }, | ||
| 1393 | + ChoiceInput { | ||
| 1394 | + id: Some("b".into()), | ||
| 1395 | + text: "6".into(), | ||
| 1396 | + }, | ||
| 1397 | + ]), | ||
| 1398 | + Some("b".into()), | ||
| 1399 | + &[], | ||
| 1400 | + ) | ||
| 1401 | + .unwrap() | ||
| 1402 | + } | ||
| 1403 | + | ||
| 1404 | + async fn ask( | ||
| 1405 | + db: &Database, | ||
| 1406 | + exam: &ExamId, | ||
| 1407 | + on: crate::domain::subject::SubjectId, | ||
| 1408 | + ) -> Result<crate::domain::exam_question::ExamQuestion, AppError> { | ||
| 1409 | + crate::db::exam_question::create( | ||
| 1410 | + db, | ||
| 1411 | + exam, | ||
| 1412 | + on, | ||
| 1413 | + QuestionText::try_new("3 + 3?").unwrap(), | ||
| 1414 | + QuestionPoints::try_new(5).unwrap(), | ||
| 1415 | + spec(), | ||
| 1416 | + ) | ||
| 1417 | + .await | ||
| 1418 | + } | ||
| 1419 | + | ||
| 1420 | + async fn subject_stuck(db: &Database, subject: &crate::domain::subject::Subject) -> bool { | ||
| 1421 | + crate::db::subject::delete( | ||
| 1422 | + db, | ||
| 1423 | + crate::db::subject::read(db, subject.get_id()) | ||
| 1424 | + .await | ||
| 1425 | + .unwrap() | ||
| 1426 | + .unwrap(), | ||
| 1427 | + ) | ||
| 1428 | + .await | ||
| 1429 | + .is_err() | ||
| 1430 | + } | ||
| 1431 | + | ||
| 1432 | + async fn a_subject(db: &Database) -> crate::domain::subject::Subject { | ||
| 1433 | + crate::db::subject::create( | ||
| 1434 | + db, | ||
| 1435 | + &crate::db::course::a_test_course(db).await, | ||
| 1328 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), | 1436 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), |
| 1329 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), | 1437 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), |
| 1330 | ) | 1438 | ) |
| 1331 | .await | 1439 | .await |
| 1332 | - .unwrap(); | 1440 | + .unwrap() |
| 1441 | + } | ||
| 1442 | + | ||
| 1443 | + // Delete-first: the exam is gone before the question write starts. | ||
| 1444 | + { | ||
| 1445 | + let exam = published(&db).await; | ||
| 1446 | + let id = exam.get_id().clone(); | ||
| 1447 | + let subject = a_subject(&db).await; | ||
| 1448 | + let dropped = delete(&db, exam).await; | ||
| 1449 | + assert!( | ||
| 1450 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 1451 | + "delete-first: a delete must be answered, not 500: {dropped:?}" | ||
| 1452 | + ); | ||
| 1453 | + assert!( | ||
| 1454 | + read(&db, &id).await.unwrap().is_none(), | ||
| 1455 | + "delete-first: the exam is still there after delete: {dropped:?}" | ||
| 1456 | + ); | ||
| 1457 | + let child = ask(&db, &id, *subject.get_id()).await; | ||
| 1458 | + assert!( | ||
| 1459 | + !matches!(child, Err(AppError::Db(_))), | ||
| 1460 | + "delete-first: a question write must be answered, not 500: {child:?}" | ||
| 1461 | + ); | ||
| 1462 | + assert_eq!( | ||
| 1463 | + crate::db::exam_question::list_for_exam(&db, &id, None, 0) | ||
| 1464 | + .await | ||
| 1465 | + .unwrap() | ||
| 1466 | + .0 | ||
| 1467 | + .len(), | ||
| 1468 | + 0, | ||
| 1469 | + "a question outlived its exam" | ||
| 1470 | + ); | ||
| 1471 | + assert!( | ||
| 1472 | + !subject_stuck(&db, &subject).await, | ||
| 1473 | + "an orphan question left its subject undeletable" | ||
| 1474 | + ); | ||
| 1475 | + } | ||
| 1476 | + | ||
| 1477 | + // Write-first: the question lands, then the delete sweeps it and frees | ||
| 1478 | + // the subject reference it claimed. | ||
| 1479 | + { | ||
| 1480 | + let exam = published(&db).await; | ||
| 1481 | + let id = exam.get_id().clone(); | ||
| 1482 | + let subject = a_subject(&db).await; | ||
| 1483 | + let child = ask(&db, &id, *subject.get_id()).await; | ||
| 1484 | + assert!( | ||
| 1485 | + child.is_ok(), | ||
| 1486 | + "write-first: the question must land before the delete: {child:?}" | ||
| 1487 | + ); | ||
| 1488 | + let dropped = delete(&db, exam).await; | ||
| 1489 | + assert!( | ||
| 1490 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 1491 | + "write-first: a delete must be answered, not 500: {dropped:?}" | ||
| 1492 | + ); | ||
| 1493 | + assert!( | ||
| 1494 | + read(&db, &id).await.unwrap().is_none(), | ||
| 1495 | + "write-first: the exam is still there" | ||
| 1496 | + ); | ||
| 1497 | + assert_eq!( | ||
| 1498 | + crate::db::exam_question::list_for_exam(&db, &id, None, 0) | ||
| 1499 | + .await | ||
| 1500 | + .unwrap() | ||
| 1501 | + .0 | ||
| 1502 | + .len(), | ||
| 1503 | + 0, | ||
| 1504 | + "a question outlived its exam" | ||
| 1505 | + ); | ||
| 1506 | + assert!( | ||
| 1507 | + !subject_stuck(&db, &subject).await, | ||
| 1508 | + "an orphan question left its subject undeletable" | ||
| 1509 | + ); | ||
| 1510 | + } | ||
| 1511 | + | ||
| 1512 | + // Overlapped rounds. Delete may lose every one of them. | ||
| 1513 | + let mut swept = 0; | ||
| 1514 | + for round in 0..4 { | ||
| 1515 | + let exam = published(&db).await; | ||
| 1516 | + let id = exam.get_id().clone(); | ||
| 1517 | + let subject = a_subject(&db).await; | ||
| 1333 | 1518 | ||
| 1334 | - // Delete and create released together: both write the exam row, so | ||
| 1335 | - // Postgres serializes them and refuses whichever lost. | ||
| 1336 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | 1519 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 1337 | let drop_it = { | 1520 | let drop_it = { |
| 1338 | - let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone()); | 1521 | + let (db, exam, gate) = (db.clone(), exam, gate.clone()); |
| 1339 | tokio::spawn(async move { | 1522 | tokio::spawn(async move { |
| 1340 | gate.wait().await; | 1523 | gate.wait().await; |
| 1341 | delete(&db, exam).await | 1524 | delete(&db, exam).await |
| @@ -1345,31 +1528,7 @@ mod tests { | |||
| 1345 | let (db, exam_id, on, gate) = (db.clone(), id.clone(), *subject.get_id(), gate); | 1528 | let (db, exam_id, on, gate) = (db.clone(), id.clone(), *subject.get_id(), gate); |
| 1346 | tokio::spawn(async move { | 1529 | tokio::spawn(async move { |
| 1347 | gate.wait().await; | 1530 | gate.wait().await; |
| 1348 | - let spec = QuestionSpec::try_new( | 1531 | + ask(&db, &exam_id, on).await |
| 1349 | - QuestionKind::try_new("choice").unwrap(), | ||
| 1350 | - Some(vec![ | ||
| 1351 | - ChoiceInput { | ||
| 1352 | - id: Some("a".into()), | ||
| 1353 | - text: "5".into(), | ||
| 1354 | - }, | ||
| 1355 | - ChoiceInput { | ||
| 1356 | - id: Some("b".into()), | ||
| 1357 | - text: "6".into(), | ||
| 1358 | - }, | ||
| 1359 | - ]), | ||
| 1360 | - Some("b".into()), | ||
| 1361 | - &[], | ||
| 1362 | - ) | ||
| 1363 | - .unwrap(); | ||
| 1364 | - crate::db::exam_question::create( | ||
| 1365 | - &db, | ||
| 1366 | - &exam_id, | ||
| 1367 | - on, | ||
| 1368 | - QuestionText::try_new("3 + 3?").unwrap(), | ||
| 1369 | - QuestionPoints::try_new(5).unwrap(), | ||
| 1370 | - spec, | ||
| 1371 | - ) | ||
| 1372 | - .await | ||
| 1373 | }) | 1532 | }) |
| 1374 | }; | 1533 | }; |
| 1375 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); | 1534 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| @@ -1377,63 +1536,135 @@ mod tests { | |||
| 1377 | !matches!(child, Err(AppError::Db(_))), | 1536 | !matches!(child, Err(AppError::Db(_))), |
| 1378 | "round {round}: a raced question write must be answered, not 500: {child:?}" | 1537 | "round {round}: a raced question write must be answered, not 500: {child:?}" |
| 1379 | ); | 1538 | ); |
| 1539 | + assert!( | ||
| 1540 | + !matches!(drop_it, Err(AppError::Db(_))), | ||
| 1541 | + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" | ||
| 1542 | + ); | ||
| 1380 | 1543 | ||
| 1381 | if read(&db, &id).await.unwrap().is_none() { | 1544 | if read(&db, &id).await.unwrap().is_none() { |
| 1382 | swept += 1; | 1545 | swept += 1; |
| 1383 | - questions += crate::db::exam_question::list_for_exam(&db, &id, None, 0) | 1546 | + assert_eq!( |
| 1384 | - .await | 1547 | + crate::db::exam_question::list_for_exam(&db, &id, None, 0) |
| 1385 | - .unwrap() | ||
| 1386 | - .0 | ||
| 1387 | - .len(); | ||
| 1388 | - // The subject has to be free again: a stranded reference is the | ||
| 1389 | - // half of this bug a row count alone would not catch. | ||
| 1390 | - if crate::db::subject::delete( | ||
| 1391 | - &db, | ||
| 1392 | - crate::db::subject::read(&db, subject.get_id()) | ||
| 1393 | .await | 1548 | .await |
| 1394 | .unwrap() | 1549 | .unwrap() |
| 1395 | - .unwrap(), | 1550 | + .0 |
| 1396 | - ) | 1551 | + .len(), |
| 1397 | - .await | 1552 | + 0, |
| 1398 | - .is_err() | 1553 | + "round {round}: a question outlived its exam" |
| 1399 | - { | 1554 | + ); |
| 1400 | - stuck += 1; | 1555 | + assert!( |
| 1401 | - } | 1556 | + !subject_stuck(&db, &subject).await, |
| 1557 | + "round {round}: an orphan question left its subject undeletable" | ||
| 1558 | + ); | ||
| 1402 | } else if drop_it.is_ok() { | 1559 | } else if drop_it.is_ok() { |
| 1403 | panic!("round {round}: the delete reported success but the exam is still there"); | 1560 | panic!("round {round}: the delete reported success but the exam is still there"); |
| 1404 | } | 1561 | } |
| 1405 | } | 1562 | } |
| 1406 | - eprintln!("Exam::delete raced by a question write: {swept}/8 rounds deleted the exam"); | 1563 | + eprintln!( |
| 1407 | - assert!( | 1564 | + "Exam::delete raced by a question write: {swept}/4 concurrent rounds deleted the exam" |
| 1408 | - swept > 0, | ||
| 1409 | - "no round ever deleted the exam, so the window was never reached" | ||
| 1410 | ); | 1565 | ); |
| 1411 | - assert_eq!(questions, 0, "a question outlived its exam"); | ||
| 1412 | - assert_eq!(stuck, 0, "an orphan question left its subject undeletable"); | ||
| 1413 | } | 1566 | } |
| 1414 | 1567 | ||
| 1415 | /// The student's half of the same picture problem: a drawing is a bare | 1568 | /// The student's half of the same picture problem: a drawing is a bare |
| 1416 | /// upsert — the exact pre-fix shape of [`crate::db::exam_answer::save`] — so it kept | 1569 | /// upsert — the exact pre-fix shape of [`crate::db::exam_answer::save`] — so it kept |
| 1417 | /// the hole the text answer just lost, blob and all. It now rides the same | 1570 | /// the hole the text answer just lost, blob and all. It now rides the same |
| 1418 | - /// exam-row write the answer does. | 1571 | + /// exam-row write the answer does. Both orders are forced by awaiting one |
| 1572 | + /// side to completion before the other starts. Overlapped rounds may all | ||
| 1573 | + /// lose the delete; that is not a failure. | ||
| 1419 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 1574 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1420 | async fn a_drawing_written_inside_a_delete_never_outlives_the_exam() { | 1575 | async fn a_drawing_written_inside_a_delete_never_outlives_the_exam() { |
| 1421 | use crate::domain::answer_image::AnswerImage; | 1576 | use crate::domain::answer_image::AnswerImage; |
| 1422 | use crate::domain::note_file::FileContentType; | 1577 | use crate::domain::note_file::FileContentType; |
| 1423 | let (db, _leases) = crate::database::init_test_db().await; | 1578 | let (db, _leases) = crate::database::init_test_db().await; |
| 1579 | + let student = a_person(&db, "student", "student").await; | ||
| 1580 | + | ||
| 1581 | + async fn draw( | ||
| 1582 | + db: &Database, | ||
| 1583 | + exam: &ExamId, | ||
| 1584 | + question: &crate::domain::exam_question::ExamQuestionId, | ||
| 1585 | + student: &UserId, | ||
| 1586 | + ) -> Result<(AnswerImage, Option<String>), AppError> { | ||
| 1587 | + let image = AnswerImage::new( | ||
| 1588 | + exam, | ||
| 1589 | + question, | ||
| 1590 | + student, | ||
| 1591 | + 1, | ||
| 1592 | + FileContentType::try_new("image/png").unwrap(), | ||
| 1593 | + 3, | ||
| 1594 | + ); | ||
| 1595 | + crate::db::answer_image::upsert(db, image).await | ||
| 1596 | + } | ||
| 1597 | + | ||
| 1598 | + // Delete-first: the exam is gone before the drawing starts. | ||
| 1599 | + { | ||
| 1600 | + let exam = published(&db).await; | ||
| 1601 | + let question = question_on(&exam, &db).await; | ||
| 1602 | + let id = exam.get_id().clone(); | ||
| 1603 | + let on = question.get_id().clone(); | ||
| 1604 | + let dropped = delete(&db, exam).await; | ||
| 1605 | + assert!( | ||
| 1606 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 1607 | + "delete-first: a delete must be answered, not 500: {dropped:?}" | ||
| 1608 | + ); | ||
| 1609 | + assert!( | ||
| 1610 | + read(&db, &id).await.unwrap().is_none(), | ||
| 1611 | + "delete-first: the exam is still there after delete: {dropped:?}" | ||
| 1612 | + ); | ||
| 1613 | + let child = draw(&db, &id, &on, &student).await; | ||
| 1614 | + assert!( | ||
| 1615 | + !matches!(child, Err(AppError::Db(_))), | ||
| 1616 | + "delete-first: a drawing write must be answered, not 500: {child:?}" | ||
| 1617 | + ); | ||
| 1618 | + assert_eq!( | ||
| 1619 | + crate::db::answer_image::list_for_exam(&db, &id) | ||
| 1620 | + .await | ||
| 1621 | + .unwrap() | ||
| 1622 | + .len(), | ||
| 1623 | + 0, | ||
| 1624 | + "a drawing outlived its exam" | ||
| 1625 | + ); | ||
| 1626 | + } | ||
| 1627 | + | ||
| 1628 | + // Write-first: the drawing lands, then the delete sweeps it. | ||
| 1629 | + { | ||
| 1630 | + let exam = published(&db).await; | ||
| 1631 | + let question = question_on(&exam, &db).await; | ||
| 1632 | + let id = exam.get_id().clone(); | ||
| 1633 | + let on = question.get_id().clone(); | ||
| 1634 | + let child = draw(&db, &id, &on, &student).await; | ||
| 1635 | + assert!( | ||
| 1636 | + child.is_ok(), | ||
| 1637 | + "write-first: the drawing must land before the delete: {child:?}" | ||
| 1638 | + ); | ||
| 1639 | + let dropped = delete(&db, exam).await; | ||
| 1640 | + assert!( | ||
| 1641 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 1642 | + "write-first: a delete must be answered, not 500: {dropped:?}" | ||
| 1643 | + ); | ||
| 1644 | + assert!( | ||
| 1645 | + read(&db, &id).await.unwrap().is_none(), | ||
| 1646 | + "write-first: the exam is still there" | ||
| 1647 | + ); | ||
| 1648 | + assert_eq!( | ||
| 1649 | + crate::db::answer_image::list_for_exam(&db, &id) | ||
| 1650 | + .await | ||
| 1651 | + .unwrap() | ||
| 1652 | + .len(), | ||
| 1653 | + 0, | ||
| 1654 | + "a drawing outlived its exam" | ||
| 1655 | + ); | ||
| 1656 | + } | ||
| 1424 | 1657 | ||
| 1425 | - let (mut drawings, mut swept) = (0, 0); | 1658 | + // Overlapped rounds. Delete may lose every one of them. |
| 1426 | - for round in 0..8 { | 1659 | + let mut swept = 0; |
| 1660 | + for round in 0..4 { | ||
| 1427 | let exam = published(&db).await; | 1661 | let exam = published(&db).await; |
| 1428 | let question = question_on(&exam, &db).await; | 1662 | let question = question_on(&exam, &db).await; |
| 1429 | let id = exam.get_id().clone(); | 1663 | let id = exam.get_id().clone(); |
| 1430 | - let student = a_person(&db, "student", "student").await; | ||
| 1431 | 1664 | ||
| 1432 | - // Delete and upsert released together: both write the exam row, so | ||
| 1433 | - // Postgres serializes them and refuses whichever lost. | ||
| 1434 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | 1665 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 1435 | let drop_it = { | 1666 | let drop_it = { |
| 1436 | - let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone()); | 1667 | + let (db, exam, gate) = (db.clone(), exam, gate.clone()); |
| 1437 | tokio::spawn(async move { | 1668 | tokio::spawn(async move { |
| 1438 | gate.wait().await; | 1669 | gate.wait().await; |
| 1439 | delete(&db, exam).await | 1670 | delete(&db, exam).await |
| @@ -1449,15 +1680,7 @@ mod tests { | |||
| 1449 | ); | 1680 | ); |
| 1450 | tokio::spawn(async move { | 1681 | tokio::spawn(async move { |
| 1451 | gate.wait().await; | 1682 | gate.wait().await; |
| 1452 | - let image = AnswerImage::new( | 1683 | + draw(&db, &exam_id, &on, &student).await |
| 1453 | - &exam_id, | ||
| 1454 | - &on, | ||
| 1455 | - &student, | ||
| 1456 | - 1, | ||
| 1457 | - FileContentType::try_new("image/png").unwrap(), | ||
| 1458 | - 3, | ||
| 1459 | - ); | ||
| 1460 | - crate::db::answer_image::upsert(&db, image).await | ||
| 1461 | }) | 1684 | }) |
| 1462 | }; | 1685 | }; |
| 1463 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); | 1686 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| @@ -1465,48 +1688,129 @@ mod tests { | |||
| 1465 | !matches!(child, Err(AppError::Db(_))), | 1688 | !matches!(child, Err(AppError::Db(_))), |
| 1466 | "round {round}: a raced drawing write must be answered, not 500: {child:?}" | 1689 | "round {round}: a raced drawing write must be answered, not 500: {child:?}" |
| 1467 | ); | 1690 | ); |
| 1691 | + assert!( | ||
| 1692 | + !matches!(drop_it, Err(AppError::Db(_))), | ||
| 1693 | + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" | ||
| 1694 | + ); | ||
| 1468 | 1695 | ||
| 1469 | if read(&db, &id).await.unwrap().is_none() { | 1696 | if read(&db, &id).await.unwrap().is_none() { |
| 1470 | swept += 1; | 1697 | swept += 1; |
| 1471 | - drawings += crate::db::answer_image::list_for_exam(&db, &id) | 1698 | + assert_eq!( |
| 1472 | - .await | 1699 | + crate::db::answer_image::list_for_exam(&db, &id) |
| 1473 | - .unwrap() | 1700 | + .await |
| 1474 | - .len(); | 1701 | + .unwrap() |
| 1702 | + .len(), | ||
| 1703 | + 0, | ||
| 1704 | + "round {round}: a drawing outlived its exam" | ||
| 1705 | + ); | ||
| 1475 | } else if drop_it.is_ok() { | 1706 | } else if drop_it.is_ok() { |
| 1476 | panic!("round {round}: the delete reported success but the exam is still there"); | 1707 | panic!("round {round}: the delete reported success but the exam is still there"); |
| 1477 | } | 1708 | } |
| 1478 | } | 1709 | } |
| 1479 | - eprintln!("Exam::delete raced by a drawing write: {swept}/8 rounds deleted the exam"); | 1710 | + eprintln!( |
| 1480 | - assert!( | 1711 | + "Exam::delete raced by a drawing write: {swept}/4 concurrent rounds deleted the exam" |
| 1481 | - swept > 0, | ||
| 1482 | - "no round ever deleted the exam, so the window was never reached" | ||
| 1483 | ); | 1712 | ); |
| 1484 | - assert_eq!(drawings, 0, "a drawing outlived its exam"); | ||
| 1485 | } | 1713 | } |
| 1486 | 1714 | ||
| 1487 | /// A picture is written through the same freeze gate as the question it | 1715 | /// A picture is written through the same freeze gate as the question it |
| 1488 | /// hangs on, so it had the same hole — and one the row count does not even | 1716 | /// hangs on, so it had the same hole — and one the row count does not even |
| 1489 | /// show: `delete_exam` collects the blob names to unlink *before* it calls | 1717 | /// show: `delete_exam` collects the blob names to unlink *before* it calls |
| 1490 | - /// [`crate::db::exam::delete`], so an image row landing after that snapshot strands | 1718 | + /// [`crate::db::exam::delete`], so an image row landing after that snapshot |
| 1491 | - /// its bytes on disk forever as well. It now rides the same exam-row write | 1719 | + /// strands its bytes on disk forever as well. It now rides the same |
| 1492 | - /// the question does. | 1720 | + /// exam-row write the question does. Both orders are forced by awaiting |
| 1721 | + /// one side to completion before the other starts. Overlapped rounds may | ||
| 1722 | + /// all lose the delete; that is not a failure. | ||
| 1493 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 1723 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1494 | async fn a_picture_written_inside_a_delete_never_outlives_the_exam() { | 1724 | async fn a_picture_written_inside_a_delete_never_outlives_the_exam() { |
| 1495 | use crate::domain::note_file::FileContentType; | 1725 | use crate::domain::note_file::FileContentType; |
| 1496 | use crate::domain::question_image::QuestionImage; | 1726 | use crate::domain::question_image::QuestionImage; |
| 1497 | let (db, _leases) = crate::database::init_test_db().await; | 1727 | let (db, _leases) = crate::database::init_test_db().await; |
| 1498 | 1728 | ||
| 1499 | - let (mut images, mut swept) = (0, 0); | 1729 | + async fn shoot( |
| 1500 | - for round in 0..8 { | 1730 | + db: &Database, |
| 1731 | + exam: &ExamId, | ||
| 1732 | + question: &crate::domain::exam_question::ExamQuestionId, | ||
| 1733 | + ) -> Result<(QuestionImage, Option<String>), AppError> { | ||
| 1734 | + let image = QuestionImage::new( | ||
| 1735 | + exam, | ||
| 1736 | + question, | ||
| 1737 | + None, | ||
| 1738 | + FileContentType::try_new("image/png").unwrap(), | ||
| 1739 | + 3, | ||
| 1740 | + ); | ||
| 1741 | + crate::db::question_image::upsert(db, image).await | ||
| 1742 | + } | ||
| 1743 | + | ||
| 1744 | + // Delete-first: the exam is gone before the picture starts. | ||
| 1745 | + { | ||
| 1746 | + let exam = published(&db).await; | ||
| 1747 | + let question = question_on(&exam, &db).await; | ||
| 1748 | + let id = exam.get_id().clone(); | ||
| 1749 | + let on = question.get_id().clone(); | ||
| 1750 | + let dropped = delete(&db, exam).await; | ||
| 1751 | + assert!( | ||
| 1752 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 1753 | + "delete-first: a delete must be answered, not 500: {dropped:?}" | ||
| 1754 | + ); | ||
| 1755 | + assert!( | ||
| 1756 | + read(&db, &id).await.unwrap().is_none(), | ||
| 1757 | + "delete-first: the exam is still there after delete: {dropped:?}" | ||
| 1758 | + ); | ||
| 1759 | + let child = shoot(&db, &id, &on).await; | ||
| 1760 | + assert!( | ||
| 1761 | + !matches!(child, Err(AppError::Db(_))), | ||
| 1762 | + "delete-first: a picture write must be answered, not 500: {child:?}" | ||
| 1763 | + ); | ||
| 1764 | + assert_eq!( | ||
| 1765 | + crate::db::question_image::list_for_exam(&db, &id) | ||
| 1766 | + .await | ||
| 1767 | + .unwrap() | ||
| 1768 | + .len(), | ||
| 1769 | + 0, | ||
| 1770 | + "a picture outlived its exam" | ||
| 1771 | + ); | ||
| 1772 | + } | ||
| 1773 | + | ||
| 1774 | + // Write-first: the picture lands, then the delete sweeps it. | ||
| 1775 | + { | ||
| 1776 | + let exam = published(&db).await; | ||
| 1777 | + let question = question_on(&exam, &db).await; | ||
| 1778 | + let id = exam.get_id().clone(); | ||
| 1779 | + let on = question.get_id().clone(); | ||
| 1780 | + let child = shoot(&db, &id, &on).await; | ||
| 1781 | + assert!( | ||
| 1782 | + child.is_ok(), | ||
| 1783 | + "write-first: the picture must land before the delete: {child:?}" | ||
| 1784 | + ); | ||
| 1785 | + let dropped = delete(&db, exam).await; | ||
| 1786 | + assert!( | ||
| 1787 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 1788 | + "write-first: a delete must be answered, not 500: {dropped:?}" | ||
| 1789 | + ); | ||
| 1790 | + assert!( | ||
| 1791 | + read(&db, &id).await.unwrap().is_none(), | ||
| 1792 | + "write-first: the exam is still there" | ||
| 1793 | + ); | ||
| 1794 | + assert_eq!( | ||
| 1795 | + crate::db::question_image::list_for_exam(&db, &id) | ||
| 1796 | + .await | ||
| 1797 | + .unwrap() | ||
| 1798 | + .len(), | ||
| 1799 | + 0, | ||
| 1800 | + "a picture outlived its exam" | ||
| 1801 | + ); | ||
| 1802 | + } | ||
| 1803 | + | ||
| 1804 | + // Overlapped rounds. Delete may lose every one of them. | ||
| 1805 | + let mut swept = 0; | ||
| 1806 | + for round in 0..4 { | ||
| 1501 | let exam = published(&db).await; | 1807 | let exam = published(&db).await; |
| 1502 | let question = question_on(&exam, &db).await; | 1808 | let question = question_on(&exam, &db).await; |
| 1503 | let id = exam.get_id().clone(); | 1809 | let id = exam.get_id().clone(); |
| 1504 | 1810 | ||
| 1505 | - // Delete and upsert released together: both write the exam row, so | ||
| 1506 | - // Postgres serializes them and refuses whichever lost. | ||
| 1507 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | 1811 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 1508 | let drop_it = { | 1812 | let drop_it = { |
| 1509 | - let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone()); | 1813 | + let (db, exam, gate) = (db.clone(), exam, gate.clone()); |
| 1510 | tokio::spawn(async move { | 1814 | tokio::spawn(async move { |
| 1511 | gate.wait().await; | 1815 | gate.wait().await; |
| 1512 | delete(&db, exam).await | 1816 | delete(&db, exam).await |
| @@ -1517,14 +1821,7 @@ mod tests { | |||
| 1517 | (db.clone(), id.clone(), question.get_id().clone(), gate); | 1821 | (db.clone(), id.clone(), question.get_id().clone(), gate); |
| 1518 | tokio::spawn(async move { | 1822 | tokio::spawn(async move { |
| 1519 | gate.wait().await; | 1823 | gate.wait().await; |
| 1520 | - let image = QuestionImage::new( | 1824 | + shoot(&db, &exam_id, &on).await |
| 1521 | - &exam_id, | ||
| 1522 | - &on, | ||
| 1523 | - None, | ||
| 1524 | - FileContentType::try_new("image/png").unwrap(), | ||
| 1525 | - 3, | ||
| 1526 | - ); | ||
| 1527 | - crate::db::question_image::upsert(&db, image).await | ||
| 1528 | }) | 1825 | }) |
| 1529 | }; | 1826 | }; |
| 1530 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); | 1827 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| @@ -1532,22 +1829,27 @@ mod tests { | |||
| 1532 | !matches!(child, Err(AppError::Db(_))), | 1829 | !matches!(child, Err(AppError::Db(_))), |
| 1533 | "round {round}: a raced picture write must be answered, not 500: {child:?}" | 1830 | "round {round}: a raced picture write must be answered, not 500: {child:?}" |
| 1534 | ); | 1831 | ); |
| 1832 | + assert!( | ||
| 1833 | + !matches!(drop_it, Err(AppError::Db(_))), | ||
| 1834 | + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" | ||
| 1835 | + ); | ||
| 1535 | 1836 | ||
| 1536 | if read(&db, &id).await.unwrap().is_none() { | 1837 | if read(&db, &id).await.unwrap().is_none() { |
| 1537 | swept += 1; | 1838 | swept += 1; |
| 1538 | - images += crate::db::question_image::list_for_exam(&db, &id) | 1839 | + assert_eq!( |
| 1539 | - .await | 1840 | + crate::db::question_image::list_for_exam(&db, &id) |
| 1540 | - .unwrap() | 1841 | + .await |
| 1541 | - .len(); | 1842 | + .unwrap() |
| 1843 | + .len(), | ||
| 1844 | + 0, | ||
| 1845 | + "round {round}: a picture outlived its exam" | ||
| 1846 | + ); | ||
| 1542 | } else if drop_it.is_ok() { | 1847 | } else if drop_it.is_ok() { |
| 1543 | panic!("round {round}: the delete reported success but the exam is still there"); | 1848 | panic!("round {round}: the delete reported success but the exam is still there"); |
| 1544 | } | 1849 | } |
| 1545 | } | 1850 | } |
| 1546 | - eprintln!("Exam::delete raced by a picture write: {swept}/8 rounds deleted the exam"); | 1851 | + eprintln!( |
| 1547 | - assert!( | 1852 | + "Exam::delete raced by a picture write: {swept}/4 concurrent rounds deleted the exam" |
| 1548 | - swept > 0, | ||
| 1549 | - "no round ever deleted the exam, so the window was never reached" | ||
| 1550 | ); | 1853 | ); |
| 1551 | - assert_eq!(images, 0, "a picture outlived its exam"); | ||
| 1552 | } | 1854 | } |
| 1553 | } | 1855 | } |
src/db/menu.rsmodified+110 -48
| @@ -517,20 +517,114 @@ mod tests { | |||
| 517 | /// The window the schema event used to force open is the menu row's own | 517 | /// The window the schema event used to force open is the menu row's own |
| 518 | /// lock now: every child write also writes the menu row, so a child racing | 518 | /// lock now: every child write also writes the menu row, so a child racing |
| 519 | /// the delete serializes on that row instead of committing into a range | 519 | /// the delete serializes on that row instead of committing into a range |
| 520 | - /// the sweep has already passed. A barrier start lets both orders happen; | 520 | + /// the sweep has already passed. Both orders are forced, for each child |
| 521 | - /// the invariant must hold in each. | 521 | + /// kind, by awaiting one side to completion before the other starts. A |
| 522 | + /// few rounds still start together; those may all lose the delete, and | ||
| 523 | + /// that is not a failure. | ||
| 522 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 524 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 523 | async fn a_child_written_inside_a_delete_never_outlives_the_menu() { | 525 | async fn a_child_written_inside_a_delete_never_outlives_the_menu() { |
| 524 | use crate::domain::menu_dish::DishDescription; | 526 | use crate::domain::menu_dish::DishDescription; |
| 525 | 527 | ||
| 526 | let (db, _leases) = school().await; | 528 | let (db, _leases) = school().await; |
| 527 | 529 | ||
| 528 | - let (mut dishes, mut marks, mut swept) = (0, 0, 0); | 530 | + async fn write_child(db: &Database, id: &MenuId, dish: bool) -> Result<(), AppError> { |
| 529 | - for round in 0..4 { | 531 | + if dish { |
| 530 | - let menu = publish(&format!("2026-09-{:02}", round + 1), &db) | 532 | + menu_dish::create( |
| 533 | + db, | ||
| 534 | + id, | ||
| 535 | + DishName::try_new("Pilav").unwrap(), | ||
| 536 | + None::<DishDescription>, | ||
| 537 | + DishPrice::try_new(1).unwrap(), | ||
| 538 | + DishTags::try_new(&[], &[]).unwrap(), | ||
| 539 | + 1_000, | ||
| 540 | + ) | ||
| 541 | + .await | ||
| 542 | + .map(|_| ()) | ||
| 543 | + } else { | ||
| 544 | + meal_attendance::mark( | ||
| 545 | + db, | ||
| 546 | + id, | ||
| 547 | + &UserId::from_key(TEACHER), | ||
| 548 | + MealAttendanceStatus::try_new("served").unwrap(), | ||
| 549 | + &UserId::from_key(TEACHER), | ||
| 550 | + ) | ||
| 531 | .await | 551 | .await |
| 532 | - .unwrap(); | 552 | + .map(|_| ()) |
| 553 | + } | ||
| 554 | + } | ||
| 555 | + | ||
| 556 | + async fn children(db: &Database, id: &MenuId) -> (usize, i64) { | ||
| 557 | + ( | ||
| 558 | + menu_dish::list_for_menu(db, id).await.unwrap().len(), | ||
| 559 | + meal_attendance::list_for_menu(db, id, None, 0) | ||
| 560 | + .await | ||
| 561 | + .unwrap() | ||
| 562 | + .1, | ||
| 563 | + ) | ||
| 564 | + } | ||
| 565 | + | ||
| 566 | + let mut day = 1u32; | ||
| 567 | + // One child kind per round, never both: whichever wrote first forces | ||
| 568 | + // the delete to re-send, and its second pass sweeps the other's row. | ||
| 569 | + for dish in [true, false] { | ||
| 570 | + let kind = if dish { "dish" } else { "mark" }; | ||
| 571 | + | ||
| 572 | + // Delete-first. | ||
| 573 | + { | ||
| 574 | + let menu = publish(&format!("2026-09-{day:02}"), &db).await.unwrap(); | ||
| 575 | + day += 1; | ||
| 576 | + let id = menu.get_id().clone(); | ||
| 577 | + let dropped = delete(&db, menu).await; | ||
| 578 | + assert!( | ||
| 579 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 580 | + "{kind} delete-first: a delete must be answered, not 500: {dropped:?}" | ||
| 581 | + ); | ||
| 582 | + assert!( | ||
| 583 | + read(&db, &id).await.unwrap().is_none(), | ||
| 584 | + "{kind} delete-first: the menu is still there after delete: {dropped:?}" | ||
| 585 | + ); | ||
| 586 | + let child = write_child(&db, &id, dish).await; | ||
| 587 | + assert!( | ||
| 588 | + !matches!(child, Err(AppError::Db(_))), | ||
| 589 | + "{kind} delete-first: a child write must be answered, not 500: {child:?}" | ||
| 590 | + ); | ||
| 591 | + let (dishes, marks) = children(&db, &id).await; | ||
| 592 | + assert_eq!(dishes, 0, "a dish outlived its menu"); | ||
| 593 | + assert_eq!(marks, 0, "a mark outlived its menu"); | ||
| 594 | + } | ||
| 595 | + | ||
| 596 | + // Write-first. | ||
| 597 | + { | ||
| 598 | + let menu = publish(&format!("2026-09-{day:02}"), &db).await.unwrap(); | ||
| 599 | + day += 1; | ||
| 600 | + let id = menu.get_id().clone(); | ||
| 601 | + let child = write_child(&db, &id, dish).await; | ||
| 602 | + assert!( | ||
| 603 | + child.is_ok(), | ||
| 604 | + "{kind} write-first: the child must land before the delete: {child:?}" | ||
| 605 | + ); | ||
| 606 | + let dropped = delete(&db, menu).await; | ||
| 607 | + assert!( | ||
| 608 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 609 | + "{kind} write-first: a delete must be answered, not 500: {dropped:?}" | ||
| 610 | + ); | ||
| 611 | + assert!( | ||
| 612 | + read(&db, &id).await.unwrap().is_none(), | ||
| 613 | + "{kind} write-first: the menu is still there" | ||
| 614 | + ); | ||
| 615 | + let (dishes, marks) = children(&db, &id).await; | ||
| 616 | + assert_eq!(dishes, 0, "a dish outlived its menu"); | ||
| 617 | + assert_eq!(marks, 0, "a mark outlived its menu"); | ||
| 618 | + } | ||
| 619 | + } | ||
| 620 | + | ||
| 621 | + // Overlapped rounds. Delete may lose every one of them. | ||
| 622 | + let mut swept = 0; | ||
| 623 | + for round in 0..4 { | ||
| 624 | + let menu = publish(&format!("2026-09-{day:02}"), &db).await.unwrap(); | ||
| 625 | + day += 1; | ||
| 533 | let id = menu.get_id().clone(); | 626 | let id = menu.get_id().clone(); |
| 627 | + let dish = round % 2 == 0; | ||
| 534 | 628 | ||
| 535 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | 629 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 536 | let drop_it = { | 630 | let drop_it = { |
| @@ -540,64 +634,32 @@ mod tests { | |||
| 540 | delete(&db, menu).await | 634 | delete(&db, menu).await |
| 541 | }) | 635 | }) |
| 542 | }; | 636 | }; |
| 543 | - // One child per round, never both: whichever wrote first forces the | ||
| 544 | - // delete to re-send, and its second pass sweeps the other's row — | ||
| 545 | - // which would mask exactly the defect this test exists to catch. | ||
| 546 | let child = { | 637 | let child = { |
| 547 | - let (id, db, dish, gate) = (id.clone(), db.clone(), round % 2 == 0, gate); | 638 | + let (id, db, gate) = (id.clone(), db.clone(), gate); |
| 548 | tokio::spawn(async move { | 639 | tokio::spawn(async move { |
| 549 | gate.wait().await; | 640 | gate.wait().await; |
| 550 | - if dish { | 641 | + write_child(&db, &id, dish).await |
| 551 | - menu_dish::create( | ||
| 552 | - &db, | ||
| 553 | - &id, | ||
| 554 | - DishName::try_new("Pilav").unwrap(), | ||
| 555 | - None::<DishDescription>, | ||
| 556 | - DishPrice::try_new(1).unwrap(), | ||
| 557 | - DishTags::try_new(&[], &[]).unwrap(), | ||
| 558 | - 1_000, | ||
| 559 | - ) | ||
| 560 | - .await | ||
| 561 | - .map(|_| ()) | ||
| 562 | - } else { | ||
| 563 | - meal_attendance::mark( | ||
| 564 | - &db, | ||
| 565 | - &id, | ||
| 566 | - &UserId::from_key(TEACHER), | ||
| 567 | - MealAttendanceStatus::try_new("served").unwrap(), | ||
| 568 | - &UserId::from_key(TEACHER), | ||
| 569 | - ) | ||
| 570 | - .await | ||
| 571 | - .map(|_| ()) | ||
| 572 | - } | ||
| 573 | }) | 642 | }) |
| 574 | }; | 643 | }; |
| 575 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); | 644 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| 576 | - // A 404 for the child, or a 409/NotFound for the delete, is a | ||
| 577 | - // correct answer — the only defect is stored state. | ||
| 578 | assert!( | 645 | assert!( |
| 579 | !matches!(child, Err(AppError::Db(_))), | 646 | !matches!(child, Err(AppError::Db(_))), |
| 580 | "round {round}: a raced child write must be answered, not 500: {child:?}" | 647 | "round {round}: a raced child write must be answered, not 500: {child:?}" |
| 581 | ); | 648 | ); |
| 649 | + assert!( | ||
| 650 | + !matches!(drop_it, Err(AppError::Db(_))), | ||
| 651 | + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" | ||
| 652 | + ); | ||
| 582 | 653 | ||
| 583 | - // Stored state is the whole verdict; a return value is not evidence. | ||
| 584 | if read(&db, &id).await.unwrap().is_none() { | 654 | if read(&db, &id).await.unwrap().is_none() { |
| 585 | swept += 1; | 655 | swept += 1; |
| 586 | - dishes += menu_dish::list_for_menu(&db, &id).await.unwrap().len(); | 656 | + let (dishes, marks) = children(&db, &id).await; |
| 587 | - marks += meal_attendance::list_for_menu(&db, &id, None, 0) | 657 | + assert_eq!(dishes, 0, "round {round}: a dish outlived its menu"); |
| 588 | - .await | 658 | + assert_eq!(marks, 0, "round {round}: a mark outlived its menu"); |
| 589 | - .unwrap() | ||
| 590 | - .1; | ||
| 591 | } else if drop_it.is_ok() { | 659 | } else if drop_it.is_ok() { |
| 592 | panic!("round {round}: the delete reported success but the menu is still there"); | 660 | panic!("round {round}: the delete reported success but the menu is still there"); |
| 593 | } | 661 | } |
| 594 | } | 662 | } |
| 595 | - eprintln!("Menu::delete raced by its children: {swept}/4 rounds deleted the menu"); | 663 | + eprintln!("Menu::delete raced by its children: {swept}/4 concurrent rounds deleted the menu"); |
| 596 | - assert!( | ||
| 597 | - swept > 0, | ||
| 598 | - "no round ever deleted the menu, so the window was never reached" | ||
| 599 | - ); | ||
| 600 | - assert_eq!(dishes, 0, "a dish outlived its menu"); | ||
| 601 | - assert_eq!(marks, 0, "a mark outlived its menu"); | ||
| 602 | } | 664 | } |
| 603 | } | 665 | } |
src/db/pool_question.rsmodified+94 -35
| @@ -266,6 +266,7 @@ pub async fn clear_image( | |||
| 266 | /// What [`delete`] took with the question: the rows ride back for their | 266 | /// What [`delete`] took with the question: the rows ride back for their |
| 267 | /// ids, and `image_files` is the caller's disk-GC list — the question's | 267 | /// ids, and `image_files` is the caller's disk-GC list — the question's |
| 268 | /// photo and every swept solution's. | 268 | /// photo and every swept solution's. |
| 269 | +#[derive(Debug)] | ||
| 269 | pub struct Deleted { | 270 | pub struct Deleted { |
| 270 | pub question: PoolQuestion, | 271 | pub question: PoolQuestion, |
| 271 | pub solutions: Vec<Solution>, | 272 | pub solutions: Vec<Solution>, |
| @@ -602,24 +603,93 @@ mod tests { | |||
| 602 | /// [`bump_question_and_write`] moves the question's own `asked_at` | 603 | /// [`bump_question_and_write`] moves the question's own `asked_at` |
| 603 | /// instead, so the two transactions touch one key and the store refuses | 604 | /// instead, so the two transactions touch one key and the store refuses |
| 604 | /// one of them. | 605 | /// one of them. |
| 605 | - /// | ||
| 606 | /// The offer writes the question row too (its `solution_count`), so the | 606 | /// The offer writes the question row too (its `solution_count`), so the |
| 607 | - /// two transactions touch one row and Postgres refuses one of them; the | 607 | + /// two transactions touch one row and Postgres refuses one of them. |
| 608 | - /// barrier releases both sides together so every interleaving gets its | 608 | + /// Both orders are forced by awaiting one side to completion before the |
| 609 | - /// chance. | 609 | + /// other starts. A barrier is a coin toss under load, and a run where the |
| 610 | + /// delete loses every overlapped round has still proved the invariant. | ||
| 610 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 611 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 611 | async fn a_solution_offered_inside_a_delete_never_outlives_its_question() { | 612 | async fn a_solution_offered_inside_a_delete_never_outlives_its_question() { |
| 612 | let (db, _leases) = database::init_test_db().await; | 613 | let (db, _leases) = database::init_test_db().await; |
| 613 | 614 | ||
| 614 | - let (mut solutions, mut swept, mut delete_500) = (0, 0, 0); | 615 | + async fn offer( |
| 615 | - for round in 0..8 { | 616 | + db: &Database, |
| 617 | + id: &PoolQuestionId, | ||
| 618 | + helper: &UserId, | ||
| 619 | + ) -> Result<Solution, AppError> { | ||
| 620 | + crate::db::solution::insert( | ||
| 621 | + db, | ||
| 622 | + Solution::new( | ||
| 623 | + id, | ||
| 624 | + helper, | ||
| 625 | + SolutionBody::try_new("Kismi integrasyon uygula.").unwrap(), | ||
| 626 | + ), | ||
| 627 | + ) | ||
| 628 | + .await | ||
| 629 | + } | ||
| 630 | + | ||
| 631 | + async fn solutions(db: &Database, id: &PoolQuestionId) -> usize { | ||
| 632 | + crate::db::solution::list_for(db, id, None, 0) | ||
| 633 | + .await | ||
| 634 | + .unwrap() | ||
| 635 | + .0 | ||
| 636 | + .len() | ||
| 637 | + } | ||
| 638 | + | ||
| 639 | + // Delete-first: the question is gone before the offer starts. | ||
| 640 | + { | ||
| 641 | + let asker = a_user(&db).await; | ||
| 642 | + let helper = a_user(&db).await; | ||
| 643 | + let q = insert(&db, question(&asker)).await.unwrap(); | ||
| 644 | + let id = *q.get_id(); | ||
| 645 | + let dropped = delete(&db, &id).await; | ||
| 646 | + assert!( | ||
| 647 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 648 | + "delete-first: a delete must be answered, not 500: {dropped:?}" | ||
| 649 | + ); | ||
| 650 | + assert!( | ||
| 651 | + read(&db, &id).await.unwrap().is_none(), | ||
| 652 | + "delete-first: the question is still there after delete: {dropped:?}" | ||
| 653 | + ); | ||
| 654 | + let child = offer(&db, &id, &helper).await; | ||
| 655 | + assert!( | ||
| 656 | + !matches!(child, Err(AppError::Db(_))), | ||
| 657 | + "delete-first: an offer must be answered, not 500: {child:?}" | ||
| 658 | + ); | ||
| 659 | + assert_eq!(solutions(&db, &id).await, 0, "a solution outlived its question"); | ||
| 660 | + } | ||
| 661 | + | ||
| 662 | + // Write-first: the offer lands, then the delete sweeps it. | ||
| 663 | + { | ||
| 664 | + let asker = a_user(&db).await; | ||
| 665 | + let helper = a_user(&db).await; | ||
| 666 | + let q = insert(&db, question(&asker)).await.unwrap(); | ||
| 667 | + let id = *q.get_id(); | ||
| 668 | + let child = offer(&db, &id, &helper).await; | ||
| 669 | + assert!( | ||
| 670 | + child.is_ok(), | ||
| 671 | + "write-first: the offer must land before the delete: {child:?}" | ||
| 672 | + ); | ||
| 673 | + let dropped = delete(&db, &id).await; | ||
| 674 | + assert!( | ||
| 675 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 676 | + "write-first: a delete must be answered, not 500: {dropped:?}" | ||
| 677 | + ); | ||
| 678 | + assert!( | ||
| 679 | + read(&db, &id).await.unwrap().is_none(), | ||
| 680 | + "write-first: the question is still there" | ||
| 681 | + ); | ||
| 682 | + assert_eq!(solutions(&db, &id).await, 0, "a solution outlived its question"); | ||
| 683 | + } | ||
| 684 | + | ||
| 685 | + // Overlapped rounds. Delete may lose every one of them. | ||
| 686 | + let mut swept = 0; | ||
| 687 | + for round in 0..4 { | ||
| 616 | let asker = a_user(&db).await; | 688 | let asker = a_user(&db).await; |
| 617 | let helper = a_user(&db).await; | 689 | let helper = a_user(&db).await; |
| 618 | let q = insert(&db, question(&asker)).await.unwrap(); | 690 | let q = insert(&db, question(&asker)).await.unwrap(); |
| 619 | let id = *q.get_id(); | 691 | let id = *q.get_id(); |
| 620 | 692 | ||
| 621 | - // Delete and offer released together: both write the question row, | ||
| 622 | - // so Postgres serializes them and refuses whichever lost. | ||
| 623 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | 693 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 624 | let drop_it = { | 694 | let drop_it = { |
| 625 | let (db, id, gate) = (db.clone(), id, gate.clone()); | 695 | let (db, id, gate) = (db.clone(), id, gate.clone()); |
| @@ -632,45 +702,34 @@ mod tests { | |||
| 632 | let (db, id, helper, gate) = (db.clone(), id, helper, gate); | 702 | let (db, id, helper, gate) = (db.clone(), id, helper, gate); |
| 633 | tokio::spawn(async move { | 703 | tokio::spawn(async move { |
| 634 | gate.wait().await; | 704 | gate.wait().await; |
| 635 | - crate::db::solution::insert( | 705 | + offer(&db, &id, &helper).await |
| 636 | - &db, | ||
| 637 | - Solution::new( | ||
| 638 | - &id, | ||
| 639 | - &helper, | ||
| 640 | - SolutionBody::try_new("Kismi integrasyon uygula.").unwrap(), | ||
| 641 | - ), | ||
| 642 | - ) | ||
| 643 | - .await | ||
| 644 | }) | 706 | }) |
| 645 | }; | 707 | }; |
| 646 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); | 708 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| 647 | - // A 404 for the offer is a correct answer; the only defect is | ||
| 648 | - // stored state. The delete must not 500 either — it contends with | ||
| 649 | - // the offer by design and a lost round is re-sent, not reported. | ||
| 650 | assert!( | 709 | assert!( |
| 651 | !matches!(child, Err(AppError::Db(_))), | 710 | !matches!(child, Err(AppError::Db(_))), |
| 652 | "round {round}: a raced offer must be answered, not 500: {child:?}" | 711 | "round {round}: a raced offer must be answered, not 500: {child:?}" |
| 653 | ); | 712 | ); |
| 654 | - if matches!(drop_it, Err(AppError::Db(_))) { | 713 | + assert!( |
| 655 | - delete_500 += 1; | 714 | + !matches!(drop_it, Err(AppError::Db(_))), |
| 656 | - } | 715 | + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" |
| 716 | + ); | ||
| 657 | 717 | ||
| 658 | - // Stored state is the whole verdict; a return value is not evidence. | ||
| 659 | if read(&db, &id).await.unwrap().is_none() { | 718 | if read(&db, &id).await.unwrap().is_none() { |
| 660 | swept += 1; | 719 | swept += 1; |
| 661 | - solutions += crate::db::solution::list_for(&db, &id, None, 0) | 720 | + assert_eq!( |
| 662 | - .await | 721 | + solutions(&db, &id).await, |
| 663 | - .unwrap() | 722 | + 0, |
| 664 | - .0 | 723 | + "round {round}: a solution outlived its question" |
| 665 | - .len(); | 724 | + ); |
| 725 | + } else if drop_it.is_ok() { | ||
| 726 | + panic!( | ||
| 727 | + "round {round}: the delete reported success but the question is still there" | ||
| 728 | + ); | ||
| 666 | } | 729 | } |
| 667 | } | 730 | } |
| 668 | - eprintln!("pool_question::delete raced by an offer: {swept}/8 rounds deleted the question"); | 731 | + eprintln!( |
| 669 | - assert!( | 732 | + "pool_question::delete raced by an offer: {swept}/4 concurrent rounds deleted the question" |
| 670 | - swept > 0, | ||
| 671 | - "no round ever deleted the question, so the window was never reached" | ||
| 672 | ); | 733 | ); |
| 673 | - assert_eq!(solutions, 0, "a solution outlived its question"); | ||
| 674 | - assert_eq!(delete_500, 0, "a raced delete must retry, not 500"); | ||
| 675 | } | 734 | } |
| 676 | } | 735 | } |
src/db/rag_thread.rsmodified+90 -29
| @@ -394,18 +394,84 @@ mod tests { | |||
| 394 | /// | 394 | /// |
| 395 | /// The window the schema event used to force open is the thread row's own | 395 | /// The window the schema event used to force open is the thread row's own |
| 396 | /// lock now: a turn is written *through* the row, so a turn racing the | 396 | /// lock now: a turn is written *through* the row, so a turn racing the |
| 397 | - /// delete serializes on that row instead of committing past the sweep. A | 397 | + /// delete serializes on that row instead of committing past the sweep. |
| 398 | - /// barrier start lets both orders happen, and the invariant must hold in | 398 | + /// Both orders are forced by awaiting one side to completion before the |
| 399 | - /// each. | 399 | + /// other starts — a barrier is a coin toss under load, and a run where |
| 400 | + /// the delete loses every overlapped round has still proved the invariant. | ||
| 401 | + /// A few rounds still start together; those may all lose the delete, and | ||
| 402 | + /// that is not a failure. | ||
| 400 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 403 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 401 | async fn a_turn_written_inside_a_delete_never_outlives_the_thread() { | 404 | async fn a_turn_written_inside_a_delete_never_outlives_the_thread() { |
| 402 | - // One thread minted per round: the cap must cover every round, since | 405 | + // Forced rounds free their seat. Concurrent rounds may keep theirs, so |
| 403 | - // the rounds where the turn wins keep their thread (and its seat). | 406 | + // the cap covers every thread this test can leave standing. |
| 404 | - let (db, _leases) = a_user_capped_at(8).await; | 407 | + let (db, _leases) = a_user_capped_at(6).await; |
| 405 | - | ||
| 406 | let user = UserId::from_key(U); | 408 | let user = UserId::from_key(U); |
| 407 | - let (mut orphans, mut swept) = (0, 0); | 409 | + |
| 408 | - for round in 0..8 { | 410 | + async fn append(db: &Database, id: &RagThreadId, user: &UserId) -> Result<(), AppError> { |
| 411 | + rag_message::append_user(db, id, user, RagContent::try_new("selam").unwrap()) | ||
| 412 | + .await | ||
| 413 | + .map(|_| ()) | ||
| 414 | + } | ||
| 415 | + | ||
| 416 | + // Delete-first: the thread is gone before the turn starts. | ||
| 417 | + { | ||
| 418 | + let thread = create_capped(&db, &user, None).await.expect("thread"); | ||
| 419 | + let id = thread.get_id().clone(); | ||
| 420 | + let dropped = delete(&db, thread).await; | ||
| 421 | + assert!( | ||
| 422 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 423 | + "delete-first: a delete must be answered, not 500: {dropped:?}" | ||
| 424 | + ); | ||
| 425 | + assert!( | ||
| 426 | + read_for(&db, &id, &user).await.unwrap().is_none(), | ||
| 427 | + "delete-first: the thread is still there after delete: {dropped:?}" | ||
| 428 | + ); | ||
| 429 | + let turn = append(&db, &id, &user).await; | ||
| 430 | + assert!( | ||
| 431 | + !matches!(turn, Err(AppError::Db(_))), | ||
| 432 | + "delete-first: a turn must be answered, not 500: {turn:?}" | ||
| 433 | + ); | ||
| 434 | + assert_eq!( | ||
| 435 | + rag_message::list_for_thread(&db, &id, None, 0) | ||
| 436 | + .await | ||
| 437 | + .unwrap() | ||
| 438 | + .1, | ||
| 439 | + 0, | ||
| 440 | + "a turn outlived its thread" | ||
| 441 | + ); | ||
| 442 | + } | ||
| 443 | + | ||
| 444 | + // Write-first: the turn lands, then the delete sweeps it. | ||
| 445 | + { | ||
| 446 | + let thread = create_capped(&db, &user, None).await.expect("thread"); | ||
| 447 | + let id = thread.get_id().clone(); | ||
| 448 | + let turn = append(&db, &id, &user).await; | ||
| 449 | + assert!( | ||
| 450 | + turn.is_ok(), | ||
| 451 | + "write-first: the turn must land before the delete: {turn:?}" | ||
| 452 | + ); | ||
| 453 | + let dropped = delete(&db, thread).await; | ||
| 454 | + assert!( | ||
| 455 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 456 | + "write-first: a delete must be answered, not 500: {dropped:?}" | ||
| 457 | + ); | ||
| 458 | + assert!( | ||
| 459 | + read_for(&db, &id, &user).await.unwrap().is_none(), | ||
| 460 | + "write-first: the thread is still there" | ||
| 461 | + ); | ||
| 462 | + assert_eq!( | ||
| 463 | + rag_message::list_for_thread(&db, &id, None, 0) | ||
| 464 | + .await | ||
| 465 | + .unwrap() | ||
| 466 | + .1, | ||
| 467 | + 0, | ||
| 468 | + "a turn outlived its thread" | ||
| 469 | + ); | ||
| 470 | + } | ||
| 471 | + | ||
| 472 | + // Overlapped rounds. Delete may lose every one of them. | ||
| 473 | + let mut swept = 0; | ||
| 474 | + for round in 0..4 { | ||
| 409 | let thread = create_capped(&db, &user, None).await.expect("thread"); | 475 | let thread = create_capped(&db, &user, None).await.expect("thread"); |
| 410 | let id = thread.get_id().clone(); | 476 | let id = thread.get_id().clone(); |
| 411 | 477 | ||
| @@ -421,40 +487,35 @@ mod tests { | |||
| 421 | let (id, db, user, gate) = (id.clone(), db.clone(), user, gate); | 487 | let (id, db, user, gate) = (id.clone(), db.clone(), user, gate); |
| 422 | tokio::spawn(async move { | 488 | tokio::spawn(async move { |
| 423 | gate.wait().await; | 489 | gate.wait().await; |
| 424 | - rag_message::append_user( | 490 | + append(&db, &id, &user).await |
| 425 | - &db, | ||
| 426 | - &id, | ||
| 427 | - &user, | ||
| 428 | - RagContent::try_new("selam").unwrap(), | ||
| 429 | - ) | ||
| 430 | - .await | ||
| 431 | - .map(|_| ()) | ||
| 432 | }) | 491 | }) |
| 433 | }; | 492 | }; |
| 434 | let (drop_it, turn) = (drop_it.await.unwrap(), turn.await.unwrap()); | 493 | let (drop_it, turn) = (drop_it.await.unwrap(), turn.await.unwrap()); |
| 435 | - // A 404 for the turn, or a NotFound for the delete, is a correct | ||
| 436 | - // answer — the only defect is stored state. | ||
| 437 | assert!( | 494 | assert!( |
| 438 | !matches!(turn, Err(AppError::Db(_))), | 495 | !matches!(turn, Err(AppError::Db(_))), |
| 439 | "round {round}: a raced turn must be answered, not 500: {turn:?}" | 496 | "round {round}: a raced turn must be answered, not 500: {turn:?}" |
| 440 | ); | 497 | ); |
| 498 | + assert!( | ||
| 499 | + !matches!(drop_it, Err(AppError::Db(_))), | ||
| 500 | + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" | ||
| 501 | + ); | ||
| 441 | 502 | ||
| 442 | - // Stored state is the whole verdict; a return value is not evidence. | ||
| 443 | if read_for(&db, &id, &user).await.unwrap().is_none() { | 503 | if read_for(&db, &id, &user).await.unwrap().is_none() { |
| 444 | swept += 1; | 504 | swept += 1; |
| 445 | - orphans += rag_message::list_for_thread(&db, &id, None, 0) | 505 | + assert_eq!( |
| 446 | - .await | 506 | + rag_message::list_for_thread(&db, &id, None, 0) |
| 447 | - .unwrap() | 507 | + .await |
| 448 | - .1; | 508 | + .unwrap() |
| 509 | + .1, | ||
| 510 | + 0, | ||
| 511 | + "round {round}: a turn outlived its thread" | ||
| 512 | + ); | ||
| 449 | } else if drop_it.is_ok() { | 513 | } else if drop_it.is_ok() { |
| 450 | panic!("round {round}: the delete reported success but the thread is still there"); | 514 | panic!("round {round}: the delete reported success but the thread is still there"); |
| 451 | } | 515 | } |
| 452 | } | 516 | } |
| 453 | - eprintln!("rag_thread::delete raced by a turn: {swept}/8 rounds deleted the thread"); | 517 | + eprintln!( |
| 454 | - assert!( | 518 | + "rag_thread::delete raced by a turn: {swept}/4 concurrent rounds deleted the thread" |
| 455 | - swept > 0, | ||
| 456 | - "no round ever deleted the thread, so the race never actually ran" | ||
| 457 | ); | 519 | ); |
| 458 | - assert_eq!(orphans, 0, "a turn outlived its thread"); | ||
| 459 | } | 520 | } |
| 460 | } | 521 | } |
src/db/session_attendance.rsmodified+100 -29
| @@ -644,41 +644,108 @@ mod tests { | |||
| 644 | 644 | ||
| 645 | /// The claim the existence gate cannot make by *reading*. The mark writes | 645 | /// The claim the existence gate cannot make by *reading*. The mark writes |
| 646 | /// the session row too (its attendance stamp), so the delete and the mark | 646 | /// the session row too (its attendance stamp), so the delete and the mark |
| 647 | - /// touch one row and Postgres refuses one of them; the barrier releases | 647 | + /// touch one row and Postgres refuses one of them. |
| 648 | - /// both sides together so every interleaving gets its chance. | ||
| 649 | /// | 648 | /// |
| 650 | /// The two flavors raced are the ones the credit branch never wrote for — a | 649 | /// The two flavors raced are the ones the credit branch never wrote for — a |
| 651 | /// lesson that has not begun, and a student with no row yet on a lesson | 650 | /// lesson that has not begun, and a student with no row yet on a lesson |
| 652 | - /// already counted. A re-mark of a row that *exists* was never in danger: | 651 | + /// already counted. Both orders are forced for each flavor by awaiting one |
| 653 | - /// the cascade and the upsert write that child's own key and collide there. | 652 | + /// side to completion before the other starts. A few rounds still start |
| 653 | + /// together; those may all lose the delete, and that is not a failure. | ||
| 654 | /// Mutation-tested: dropping the unconditional session-row write from | 654 | /// Mutation-tested: dropping the unconditional session-row write from |
| 655 | - /// `mark` turns it red. | 655 | + /// `mark` turns the write-first rounds red. |
| 656 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 656 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 657 | async fn a_mark_written_inside_a_delete_never_outlives_the_session() { | 657 | async fn a_mark_written_inside_a_delete_never_outlives_the_session() { |
| 658 | let (db, _leases) = crate::database::init_test_db().await; | 658 | let (db, _leases) = crate::database::init_test_db().await; |
| 659 | - | ||
| 660 | let teacher = a_teacher("t", &db).await; | 659 | let teacher = a_teacher("t", &db).await; |
| 661 | - let (mut swept, mut orphans) = (0, 0); | 660 | + |
| 662 | - for (round, already_counted) in [false, true, false, true, false, true, false, true] | 661 | + async fn session_for( |
| 663 | - .into_iter() | 662 | + db: &Database, |
| 664 | - .enumerate() | 663 | + teacher: &UserId, |
| 665 | - { | 664 | + already_counted: bool, |
| 666 | - let session = if already_counted { | 665 | + label: &str, |
| 667 | - // Counted by somebody else's mark, so this one credits nothing. | 666 | + ) -> CourseSession { |
| 668 | - let session = a_session(&teacher, &db).await; | 667 | + if already_counted { |
| 669 | - let first = a_student(&format!("f{round}"), &db).await; | 668 | + let session = a_session(teacher, db).await; |
| 670 | - mark(&db, &session, &first, status("present"), &teacher) | 669 | + let first = a_student(label, db).await; |
| 670 | + mark(db, &session, &first, status("present"), teacher) | ||
| 671 | .await | 671 | .await |
| 672 | .unwrap(); | 672 | .unwrap(); |
| 673 | session | 673 | session |
| 674 | } else { | 674 | } else { |
| 675 | - a_session_at(&teacher, Timestamp::now().as_millis() + 604_800_000, &db).await | 675 | + a_session_at(teacher, Timestamp::now().as_millis() + 604_800_000, db).await |
| 676 | - }; | 676 | + } |
| 677 | + } | ||
| 678 | + | ||
| 679 | + for (flavor, already_counted) in [("fresh", false), ("counted", true)] { | ||
| 680 | + // Delete-first. | ||
| 681 | + { | ||
| 682 | + let session = session_for(&db, &teacher, already_counted, &format!("df-{flavor}")) | ||
| 683 | + .await; | ||
| 684 | + let id = session.get_id().clone(); | ||
| 685 | + let ghost = session.clone(); | ||
| 686 | + let dropped = crate::db::course_session::delete(&db, session).await; | ||
| 687 | + assert!( | ||
| 688 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 689 | + "{flavor} delete-first: a delete must be answered, not 500: {dropped:?}" | ||
| 690 | + ); | ||
| 691 | + assert!( | ||
| 692 | + crate::db::course_session::read(&db, &id) | ||
| 693 | + .await | ||
| 694 | + .unwrap() | ||
| 695 | + .is_none(), | ||
| 696 | + "{flavor} delete-first: the session is still there after delete: {dropped:?}" | ||
| 697 | + ); | ||
| 698 | + let student = a_student(&format!("df-s-{flavor}"), &db).await; | ||
| 699 | + let marked = mark(&db, &ghost, &student, status("present"), &teacher).await; | ||
| 700 | + assert!( | ||
| 701 | + !matches!(marked, Err(AppError::Db(_))), | ||
| 702 | + "{flavor} delete-first: a mark must be answered, not 500: {marked:?}" | ||
| 703 | + ); | ||
| 704 | + assert_eq!( | ||
| 705 | + list_for_session(&db, &id, None, 0).await.unwrap().0.len(), | ||
| 706 | + 0, | ||
| 707 | + "a roll call outlived its session" | ||
| 708 | + ); | ||
| 709 | + } | ||
| 710 | + | ||
| 711 | + // Write-first. | ||
| 712 | + { | ||
| 713 | + let session = session_for(&db, &teacher, already_counted, &format!("wf-{flavor}")) | ||
| 714 | + .await; | ||
| 715 | + let id = session.get_id().clone(); | ||
| 716 | + let student = a_student(&format!("wf-s-{flavor}"), &db).await; | ||
| 717 | + let marked = mark(&db, &session, &student, status("present"), &teacher).await; | ||
| 718 | + assert!( | ||
| 719 | + marked.is_ok(), | ||
| 720 | + "{flavor} write-first: the mark must land before the delete: {marked:?}" | ||
| 721 | + ); | ||
| 722 | + let dropped = crate::db::course_session::delete(&db, session).await; | ||
| 723 | + assert!( | ||
| 724 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 725 | + "{flavor} write-first: a delete must be answered, not 500: {dropped:?}" | ||
| 726 | + ); | ||
| 727 | + assert!( | ||
| 728 | + crate::db::course_session::read(&db, &id) | ||
| 729 | + .await | ||
| 730 | + .unwrap() | ||
| 731 | + .is_none(), | ||
| 732 | + "{flavor} write-first: the session is still there" | ||
| 733 | + ); | ||
| 734 | + assert_eq!( | ||
| 735 | + list_for_session(&db, &id, None, 0).await.unwrap().0.len(), | ||
| 736 | + 0, | ||
| 737 | + "a roll call outlived its session" | ||
| 738 | + ); | ||
| 739 | + } | ||
| 740 | + } | ||
| 741 | + | ||
| 742 | + // Overlapped rounds. Delete may lose every one of them. | ||
| 743 | + let mut swept = 0; | ||
| 744 | + for (round, already_counted) in [false, true, false, true].into_iter().enumerate() { | ||
| 745 | + let session = session_for(&db, &teacher, already_counted, &format!("c{round}")).await; | ||
| 677 | let id = session.get_id().clone(); | 746 | let id = session.get_id().clone(); |
| 678 | let ghost = session.clone(); | 747 | let ghost = session.clone(); |
| 679 | 748 | ||
| 680 | - // Delete and mark released together: both write the session row, | ||
| 681 | - // so Postgres serializes them and refuses whichever lost. | ||
| 682 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | 749 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 683 | let drop_it = { | 750 | let drop_it = { |
| 684 | let (db, gate, session) = (db.clone(), gate.clone(), session); | 751 | let (db, gate, session) = (db.clone(), gate.clone(), session); |
| @@ -700,26 +767,30 @@ mod tests { | |||
| 700 | !matches!(marked, Err(AppError::Db(_))), | 767 | !matches!(marked, Err(AppError::Db(_))), |
| 701 | "round {round}: a raced mark must be answered, not 500: {marked:?}" | 768 | "round {round}: a raced mark must be answered, not 500: {marked:?}" |
| 702 | ); | 769 | ); |
| 770 | + assert!( | ||
| 771 | + !matches!(drop_it, Err(AppError::Db(_))), | ||
| 772 | + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" | ||
| 773 | + ); | ||
| 703 | 774 | ||
| 704 | - // Stored state is the whole verdict; a return value is not evidence. | ||
| 705 | if crate::db::course_session::read(&db, &id) | 775 | if crate::db::course_session::read(&db, &id) |
| 706 | .await | 776 | .await |
| 707 | .unwrap() | 777 | .unwrap() |
| 708 | .is_none() | 778 | .is_none() |
| 709 | { | 779 | { |
| 710 | swept += 1; | 780 | swept += 1; |
| 711 | - orphans += list_for_session(&db, &id, None, 0).await.unwrap().0.len(); | 781 | + assert_eq!( |
| 782 | + list_for_session(&db, &id, None, 0).await.unwrap().0.len(), | ||
| 783 | + 0, | ||
| 784 | + "round {round}: a roll call outlived its session" | ||
| 785 | + ); | ||
| 712 | } else if drop_it.is_ok() { | 786 | } else if drop_it.is_ok() { |
| 713 | - panic!("round {round}: the delete reported success but the session is still there"); | 787 | + panic!( |
| 788 | + "round {round}: the delete reported success but the session is still there" | ||
| 789 | + ); | ||
| 714 | } | 790 | } |
| 715 | } | 791 | } |
| 716 | eprintln!( | 792 | eprintln!( |
| 717 | - "CourseSession::delete raced by a roll call: {swept}/8 rounds deleted the session" | 793 | + "CourseSession::delete raced by a roll call: {swept}/4 concurrent rounds deleted the session" |
| 718 | - ); | ||
| 719 | - assert!( | ||
| 720 | - swept > 0, | ||
| 721 | - "no round ever deleted the session, so the window was never reached" | ||
| 722 | ); | 794 | ); |
| 723 | - assert_eq!(orphans, 0, "a roll call outlived its session"); | ||
| 724 | } | 795 | } |
| 725 | } | 796 | } |
src/service/class_course.rsmodified+92 -25
| @@ -588,11 +588,86 @@ mod tests { | |||
| 588 | /// still there lands on the very row `Course::delete`'s guard locks, so | 588 | /// still there lands on the very row `Course::delete`'s guard locks, so |
| 589 | /// whatever the interleaving, a link row and a deleted course can never | 589 | /// whatever the interleaving, a link row and a deleted course can never |
| 590 | /// both stand. | 590 | /// both stand. |
| 591 | + /// | ||
| 592 | + /// Both orders are forced. Delete-first awaits the delete, then the | ||
| 593 | + /// attach: the course is gone and no link may appear. Attach-first awaits | ||
| 594 | + /// the attach, then the delete: a course a class still teaches must | ||
| 595 | + /// refuse, not 500, and the course stays. A 2ms head start does not force | ||
| 596 | + /// that under pool contention. Overlapped rounds may all lose the delete; | ||
| 597 | + /// that is not a failure. | ||
| 591 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 598 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 592 | async fn a_class_course_link_never_outlives_the_course() { | 599 | async fn a_class_course_link_never_outlives_the_course() { |
| 593 | let (db, _leases) = crate::database::init_test_db().await; | 600 | let (db, _leases) = crate::database::init_test_db().await; |
| 594 | let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | 601 | let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; |
| 595 | - let (mut orphans, mut swept, mut miscounted) = (0, 0, 0); | 602 | + |
| 603 | + // Delete-first: nothing may attach to a course that is already gone. | ||
| 604 | + { | ||
| 605 | + let class = a_class("9-df", &db).await; | ||
| 606 | + let algebra = a_course("algebra-df", &db).await; | ||
| 607 | + let course = crate::db::course::read(&db, &algebra) | ||
| 608 | + .await | ||
| 609 | + .unwrap() | ||
| 610 | + .unwrap(); | ||
| 611 | + let dropped = crate::db::course::delete(&db, course).await; | ||
| 612 | + assert!( | ||
| 613 | + matches!(dropped, Ok(true)), | ||
| 614 | + "delete-first: an empty course must delete, not {dropped:?}" | ||
| 615 | + ); | ||
| 616 | + assert!( | ||
| 617 | + !course_exists(&algebra, &db).await, | ||
| 618 | + "delete-first: the course is still there" | ||
| 619 | + ); | ||
| 620 | + let child = attach(&db, &class, &algebra, &manager).await; | ||
| 621 | + assert!( | ||
| 622 | + !matches!(child, Err(AppError::Db(_))), | ||
| 623 | + "delete-first: an attach must be answered, not 500: {child:?}" | ||
| 624 | + ); | ||
| 625 | + assert!( | ||
| 626 | + !link_exists(&class, &algebra, &db).await, | ||
| 627 | + "a class_course link outlived its course" | ||
| 628 | + ); | ||
| 629 | + assert_eq!( | ||
| 630 | + counter("class_course_count", class.uuid(), &db).await, | ||
| 631 | + 0, | ||
| 632 | + "a class counts a course that is gone" | ||
| 633 | + ); | ||
| 634 | + } | ||
| 635 | + | ||
| 636 | + // Attach-first: the guard must refuse. Parent stays; that is the | ||
| 637 | + // verdict, not a missed sweep. | ||
| 638 | + { | ||
| 639 | + let class = a_class("9-wf", &db).await; | ||
| 640 | + let algebra = a_course("algebra-wf", &db).await; | ||
| 641 | + let course = crate::db::course::read(&db, &algebra) | ||
| 642 | + .await | ||
| 643 | + .unwrap() | ||
| 644 | + .unwrap(); | ||
| 645 | + let child = attach(&db, &class, &algebra, &manager).await; | ||
| 646 | + assert!( | ||
| 647 | + child.is_ok(), | ||
| 648 | + "attach-first: the attach must land before the delete: {child:?}" | ||
| 649 | + ); | ||
| 650 | + let dropped = crate::db::course::delete(&db, course).await; | ||
| 651 | + assert!( | ||
| 652 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 653 | + "attach-first: a delete must be answered, not 500: {dropped:?}" | ||
| 654 | + ); | ||
| 655 | + assert!( | ||
| 656 | + matches!(dropped, Ok(false)), | ||
| 657 | + "attach-first: a course a class still teaches must refuse, not {dropped:?}" | ||
| 658 | + ); | ||
| 659 | + assert!( | ||
| 660 | + course_exists(&algebra, &db).await, | ||
| 661 | + "attach-first: the refused delete removed the course" | ||
| 662 | + ); | ||
| 663 | + assert!( | ||
| 664 | + link_exists(&class, &algebra, &db).await, | ||
| 665 | + "attach-first: the landed link is gone" | ||
| 666 | + ); | ||
| 667 | + } | ||
| 668 | + | ||
| 669 | + // Overlapped rounds. Delete may lose every one of them. | ||
| 670 | + let mut swept = 0; | ||
| 596 | for round in 0..4 { | 671 | for round in 0..4 { |
| 597 | let class = a_class(&format!("9-{round}"), &db).await; | 672 | let class = a_class(&format!("9-{round}"), &db).await; |
| 598 | let algebra = a_course(&format!("algebra{round}"), &db).await; | 673 | let algebra = a_course(&format!("algebra{round}"), &db).await; |
| @@ -601,11 +676,9 @@ mod tests { | |||
| 601 | .unwrap() | 676 | .unwrap() |
| 602 | .unwrap(); | 677 | .unwrap(); |
| 603 | 678 | ||
| 604 | - // A barrier start covers every interleaving — the link row may | ||
| 605 | - // never outlive the course in any of them. | ||
| 606 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | 679 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 607 | let drop_it = { | 680 | let drop_it = { |
| 608 | - let (db, gate, course) = (db.clone(), gate.clone(), course.clone()); | 681 | + let (db, gate, course) = (db.clone(), gate.clone(), course); |
| 609 | tokio::spawn(async move { | 682 | tokio::spawn(async move { |
| 610 | gate.wait().await; | 683 | gate.wait().await; |
| 611 | crate::db::course::delete(&db, course).await | 684 | crate::db::course::delete(&db, course).await |
| @@ -616,42 +689,36 @@ mod tests { | |||
| 616 | (db.clone(), class.clone(), algebra.clone(), manager, gate); | 689 | (db.clone(), class.clone(), algebra.clone(), manager, gate); |
| 617 | tokio::spawn(async move { | 690 | tokio::spawn(async move { |
| 618 | gate.wait().await; | 691 | gate.wait().await; |
| 619 | - // Every other round the attach is held back a clear 2ms so | ||
| 620 | - // the delete wins outright (`swept > 0` below is a coin | ||
| 621 | - // toss without it): with the course counter claim live both | ||
| 622 | - // sides write the very row the guard reads, so whichever is | ||
| 623 | - // marginally faster otherwise takes every round under load. | ||
| 624 | - if round % 2 == 0 { | ||
| 625 | - tokio::time::sleep(std::time::Duration::from_millis(2)).await; | ||
| 626 | - } | ||
| 627 | attach(&db, &class, &algebra, &manager).await | 692 | attach(&db, &class, &algebra, &manager).await |
| 628 | }) | 693 | }) |
| 629 | }; | 694 | }; |
| 630 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); | 695 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| 631 | - // A 404 for the attach, or a refusal for the delete, is a correct | ||
| 632 | - // answer — the only defect is stored state. | ||
| 633 | assert!( | 696 | assert!( |
| 634 | !matches!(child, Err(AppError::Db(_))), | 697 | !matches!(child, Err(AppError::Db(_))), |
| 635 | "round {round}: a raced attach must be answered, not 500: {child:?}" | 698 | "round {round}: a raced attach must be answered, not 500: {child:?}" |
| 636 | ); | 699 | ); |
| 700 | + assert!( | ||
| 701 | + !matches!(drop_it, Err(AppError::Db(_))), | ||
| 702 | + "round {round}: a raced delete must be answered, not 500: {drop_it:?}" | ||
| 703 | + ); | ||
| 637 | 704 | ||
| 638 | - // Stored state is the whole verdict; a return value is not evidence. | ||
| 639 | if !course_exists(&algebra, &db).await { | 705 | if !course_exists(&algebra, &db).await { |
| 640 | swept += 1; | 706 | swept += 1; |
| 641 | - if link_exists(&class, &algebra, &db).await { | 707 | + assert!( |
| 642 | - orphans += 1; | 708 | + !link_exists(&class, &algebra, &db).await, |
| 643 | - } | 709 | + "round {round}: a class_course link outlived its course" |
| 644 | - miscounted += counter("class_course_count", class.uuid(), &db).await; | 710 | + ); |
| 711 | + assert_eq!( | ||
| 712 | + counter("class_course_count", class.uuid(), &db).await, | ||
| 713 | + 0, | ||
| 714 | + "round {round}: a class counts a course that is gone" | ||
| 715 | + ); | ||
| 645 | } else if matches!(drop_it, Ok(true)) { | 716 | } else if matches!(drop_it, Ok(true)) { |
| 646 | panic!("round {round}: the delete reported success but the course is still there"); | 717 | panic!("round {round}: the delete reported success but the course is still there"); |
| 647 | } | 718 | } |
| 648 | } | 719 | } |
| 649 | - eprintln!("Course::delete raced by an attach: {swept}/4 rounds deleted the course"); | 720 | + eprintln!( |
| 650 | - assert!( | 721 | + "Course::delete raced by an attach: {swept}/4 concurrent rounds deleted the course" |
| 651 | - swept > 0, | ||
| 652 | - "no round ever deleted the course, so the race never actually ran" | ||
| 653 | ); | 722 | ); |
| 654 | - assert_eq!(orphans, 0, "a class_course link outlived its course"); | ||
| 655 | - assert_eq!(miscounted, 0, "a class counts a course that is gone"); | ||
| 656 | } | 723 | } |
| 657 | } | 724 | } |