❓ stop a solution from outliving its pool question
Browse files at this commit226334a84bd0abfbccdff4ab3681dca4f95d1931Parent: f8b854c- fix
- ❓ stop a solution from outliving its pool question
2 changed files +220 -17
- src/domain/pool_question.rs +171 -7
- src/domain/solution.rs +49 -10
src/domain/pool_question.rsmodified+171 -7
| @@ -25,6 +25,72 @@ use crate::domain::user::UserId; | |||
| 25 | use crate::error::{AppError, ValidationError}; | 25 | use crate::error::{AppError, ValidationError}; |
| 26 | use crate::validate::validate_required; | 26 | use crate::validate::validate_required; |
| 27 | 27 | ||
| 28 | +/// Move the question's `asked_at` **and** run `statement` — a write to | ||
| 29 | +/// something hanging off a question — in one transaction, handing back the row | ||
| 30 | +/// it returned. `NotFound` means the question is gone and nothing was written. | ||
| 31 | +/// | ||
| 32 | +/// The move is what makes the question's **existence** part of the child's own | ||
| 33 | +/// write, the way [`crate::domain::menu::bump_menu_and_write`] does for a menu: | ||
| 34 | +/// the `UPDATE` matches nothing once the row is deleted, and a delete racing | ||
| 35 | +/// this one touches the very key this transaction writes, so the two cannot | ||
| 36 | +/// both commit. Reading the question first does *not* survive that race — the | ||
| 37 | +/// read sees a row [`PoolQuestion::delete`] has removed but not committed, | ||
| 38 | +/// while its `DELETE solution WHERE question = $q` ran on a snapshot predating | ||
| 39 | +/// this insert, so both commit and the child outlives its question with neither | ||
| 40 | +/// caller told anything. | ||
| 41 | +/// | ||
| 42 | +/// `asked_at` rather than a revision column because this row carries no counter | ||
| 43 | +/// to bump and must not grow one for this alone. It is put back *by captured | ||
| 44 | +/// value* in the same transaction, so nothing outside ever observes the move | ||
| 45 | +/// and the row is byte-identical afterwards (the pool lists order on it). | ||
| 46 | +/// Writing the same value would buy nothing: an `UPDATE` that leaves the | ||
| 47 | +/// document unchanged is elided and never reaches the store's write set, so it | ||
| 48 | +/// collides with nothing. | ||
| 49 | +/// | ||
| 50 | +/// Admissible for [`transaction_with_retry`] as long as `statement` is: the | ||
| 51 | +/// `UPDATE`s, `SELECT`, `IF`/`THROW` and `RETURN` can never answer "already | ||
| 52 | +/// exists". | ||
| 53 | +pub(crate) async fn bump_question_and_write<T: SurrealValue>( | ||
| 54 | + question: &PoolQuestionId, | ||
| 55 | + statement: &str, | ||
| 56 | + mut bindings: Vec<(String, surrealdb::types::Value)>, | ||
| 57 | + db: &Database, | ||
| 58 | +) -> Result<Option<T>, AppError> { | ||
| 59 | + bindings.push(("q".into(), question.record().into_value())); | ||
| 60 | + let (mut result, mut errors) = transaction_with_retry( | ||
| 61 | + db, | ||
| 62 | + &format!( | ||
| 63 | + "BEGIN TRANSACTION; | ||
| 64 | + LET $was_asked = (SELECT VALUE asked_at FROM ONLY $q); | ||
| 65 | + LET $bumped = (UPDATE $q SET asked_at = asked_at + 1 RETURN VALUE id); | ||
| 66 | + IF array::len($bumped) = 0 {{ THROW 'no_question' }}; | ||
| 67 | + UPDATE $q SET asked_at = $was_asked; | ||
| 68 | + LET $row = ({statement}); | ||
| 69 | + RETURN $row; | ||
| 70 | + COMMIT TRANSACTION;" | ||
| 71 | + ), | ||
| 72 | + &bindings, | ||
| 73 | + &["no_question"], | ||
| 74 | + ) | ||
| 75 | + .await?; | ||
| 76 | + // An aborted transaction errors *every* slot, most with a generic "not | ||
| 77 | + // executed" — only the THROW's own slot names the reason. | ||
| 78 | + if errors | ||
| 79 | + .values() | ||
| 80 | + .any(|error| error.to_string().contains("no_question")) | ||
| 81 | + { | ||
| 82 | + return Err(AppError::NotFound); | ||
| 83 | + } | ||
| 84 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 85 | + return Err(error.into()); | ||
| 86 | + } | ||
| 87 | + // The trailing `RETURN` is the last statement before `COMMIT`, so its slot | ||
| 88 | + // follows the statement count rather than a hand-kept number; | ||
| 89 | + // `num_statements` counts BEGIN and COMMIT. | ||
| 90 | + let slot = result.num_statements().saturating_sub(2); | ||
| 91 | + Ok(result.take::<Vec<T>>(slot)?.into_iter().next()) | ||
| 92 | +} | ||
| 93 | + | ||
| 28 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 94 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 29 | pub struct PoolQuestionId(RecordId); | 95 | pub struct PoolQuestionId(RecordId); |
| 30 | 96 | ||
| @@ -324,20 +390,28 @@ impl PoolQuestion { | |||
| 324 | /// the removed rows — the question's *and* the swept solutions' — so the | 390 | /// the removed rows — the question's *and* the swept solutions' — so the |
| 325 | /// caller can take every image blob off disk (solutions carry photos too, | 391 | /// caller can take every image blob off disk (solutions carry photos too, |
| 326 | /// and a row-only sweep would strand theirs forever). | 392 | /// and a row-only sweep would strand theirs forever). |
| 393 | + /// | ||
| 394 | + /// Rides the retry because a solution offer now writes this very row | ||
| 395 | + /// ([`bump_question_and_write`]): the two contend by design, and a lost | ||
| 396 | + /// round through a bare `check()` was a 500 for a delete that only had to | ||
| 397 | + /// be re-sent. Admissible — a `DELETE` can never answer "already exists". | ||
| 327 | pub async fn delete( | 398 | pub async fn delete( |
| 328 | id: &PoolQuestionId, | 399 | id: &PoolQuestionId, |
| 329 | db: &Database, | 400 | db: &Database, |
| 330 | ) -> Result<Option<(PoolQuestion, Vec<Solution>)>, AppError> { | 401 | ) -> Result<Option<(PoolQuestion, Vec<Solution>)>, AppError> { |
| 331 | - let mut result = db | 402 | + let (mut result, mut errors) = transaction_with_retry( |
| 332 | - .query( | 403 | + db, |
| 333 | - "BEGIN TRANSACTION; | 404 | + "BEGIN TRANSACTION; |
| 334 | DELETE solution WHERE question = $q RETURN BEFORE; | 405 | DELETE solution WHERE question = $q RETURN BEFORE; |
| 335 | DELETE $q RETURN BEFORE; | 406 | DELETE $q RETURN BEFORE; |
| 336 | COMMIT TRANSACTION;", | 407 | COMMIT TRANSACTION;", |
| 337 | - ) | 408 | + &[("q".into(), id.record().into_value())], |
| 338 | - .bind(("q", id.record())) | 409 | + &[], |
| 339 | - .await? | 410 | + ) |
| 340 | - .check()?; | 411 | + .await?; |
| 412 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 413 | + return Err(error.into()); | ||
| 414 | + } | ||
| 341 | // Slots count BEGIN: the solution sweep is slot 1, the question slot 2. | 415 | // Slots count BEGIN: the solution sweep is slot 1, the question slot 2. |
| 342 | let solutions = result.take::<Vec<Solution>>(1)?; | 416 | let solutions = result.take::<Vec<Solution>>(1)?; |
| 343 | Ok(result | 417 | Ok(result |
| @@ -642,4 +716,94 @@ mod tests { | |||
| 642 | .is_none() | 716 | .is_none() |
| 643 | ); | 717 | ); |
| 644 | } | 718 | } |
| 719 | + | ||
| 720 | + /// The [`crate::domain::exam_answer::ExamAnswer::save`] defect, one domain | ||
| 721 | + /// over: a solution offered inside its question's delete window must not | ||
| 722 | + /// outlive it. Guarding the offer by *reading* the question does not do it | ||
| 723 | + /// — the read sees a row [`PoolQuestion::delete`] has removed but not | ||
| 724 | + /// committed, while its `DELETE solution WHERE question = $q` ran on a | ||
| 725 | + /// snapshot predating the offer, so both commit and the solution is left | ||
| 726 | + /// pointing at a question that is gone. Nothing can reach it after that: | ||
| 727 | + /// every route to a solution goes through its question, so neither a | ||
| 728 | + /// reader nor a second delete can ever clear it, and its photo stays on | ||
| 729 | + /// disk for good. [`bump_question_and_write`] moves the question's own | ||
| 730 | + /// `asked_at` instead, so the two transactions touch one key and the store | ||
| 731 | + /// refuses one of them. | ||
| 732 | + /// | ||
| 733 | + /// The window is opened by the database, not by a lucky interleaving: a | ||
| 734 | + /// `DEFINE EVENT` on `pool_question` fires *inside* the delete's own | ||
| 735 | + /// transaction the instant the row goes, so the `SLEEP` lands exactly | ||
| 736 | + /// between the delete and its cascade every time. | ||
| 737 | + /// | ||
| 738 | + /// Real server, and `#[ignore]`d for it: the subject *is* the store's | ||
| 739 | + /// conflict detection, which `init_mem`'s embedded engine does not have — | ||
| 740 | + /// it commits both writes and answers `Ok` to each, so this passes there on | ||
| 741 | + /// broken code. | ||
| 742 | + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 743 | + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 744 | + async fn a_solution_offered_inside_a_delete_never_outlives_its_question() { | ||
| 745 | + let (db, _serialized) = database::init_test_server("solution_race").await; | ||
| 746 | + // Hold the delete open for a full second after the row is gone, while | ||
| 747 | + // its cascade still has to run. | ||
| 748 | + db.query( | ||
| 749 | + "DEFINE EVENT hold_the_window ON TABLE pool_question WHEN $event = 'DELETE' \ | ||
| 750 | + THEN { SLEEP 1s; };", | ||
| 751 | + ) | ||
| 752 | + .await | ||
| 753 | + .unwrap() | ||
| 754 | + .check() | ||
| 755 | + .unwrap(); | ||
| 756 | + | ||
| 757 | + let (mut solutions, mut swept, mut delete_500) = (0, 0, 0); | ||
| 758 | + for round in 0..4 { | ||
| 759 | + let asker = UserId::from_key(&Ulid::new().to_string()); | ||
| 760 | + let helper = UserId::from_key(&Ulid::new().to_string()); | ||
| 761 | + let q = question(&asker).insert(&db).await.unwrap(); | ||
| 762 | + let id = q.get_id().clone(); | ||
| 763 | + | ||
| 764 | + let drop_it = { | ||
| 765 | + let (db, id) = (db.clone(), id.clone()); | ||
| 766 | + tokio::spawn(async move { PoolQuestion::delete(&id, &db).await }) | ||
| 767 | + }; | ||
| 768 | + // The offer starts inside the held window — the question row is | ||
| 769 | + // gone but uncommitted, which is exactly what a read believes. | ||
| 770 | + tokio::time::sleep(std::time::Duration::from_millis(300)).await; | ||
| 771 | + let child = { | ||
| 772 | + let (db, id) = (db.clone(), id.clone()); | ||
| 773 | + tokio::spawn(async move { | ||
| 774 | + Solution::new( | ||
| 775 | + &id, | ||
| 776 | + &helper, | ||
| 777 | + SolutionBody::try_new("Kismi integrasyon uygula.").unwrap(), | ||
| 778 | + ) | ||
| 779 | + .insert(&db) | ||
| 780 | + .await | ||
| 781 | + }) | ||
| 782 | + }; | ||
| 783 | + let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); | ||
| 784 | + // A 404 for the offer is a correct answer; the only defect is | ||
| 785 | + // stored state. The delete must not 500 either — it contends with | ||
| 786 | + // the offer by design and a lost round is re-sent, not reported. | ||
| 787 | + assert!( | ||
| 788 | + !matches!(child, Err(AppError::Db(_))), | ||
| 789 | + "round {round}: a raced offer must be answered, not 500: {child:?}" | ||
| 790 | + ); | ||
| 791 | + if matches!(drop_it, Err(AppError::Db(_))) { | ||
| 792 | + delete_500 += 1; | ||
| 793 | + } | ||
| 794 | + | ||
| 795 | + // Stored state is the whole verdict; a return value is not evidence. | ||
| 796 | + if PoolQuestion::read(&id, &db).await.unwrap().is_none() { | ||
| 797 | + swept += 1; | ||
| 798 | + solutions += Solution::list_for(&id, None, 0, &db).await.unwrap().0.len(); | ||
| 799 | + } | ||
| 800 | + } | ||
| 801 | + eprintln!("PoolQuestion::delete raced by an offer: {swept}/4 rounds deleted the question"); | ||
| 802 | + assert!( | ||
| 803 | + swept > 0, | ||
| 804 | + "no round ever deleted the question, so the window was never reached" | ||
| 805 | + ); | ||
| 806 | + assert_eq!(solutions, 0, "a solution outlived its question"); | ||
| 807 | + assert_eq!(delete_500, 0, "a raced delete must retry, not 500"); | ||
| 808 | + } | ||
| 645 | } | 809 | } |
src/domain/solution.rsmodified+49 -10
| @@ -16,7 +16,7 @@ use crate::database::Database; | |||
| 16 | use crate::domain::monotonic_id::next_ulid; | 16 | use crate::domain::monotonic_id::next_ulid; |
| 17 | use crate::domain::note_file::FileContentType; | 17 | use crate::domain::note_file::FileContentType; |
| 18 | use crate::domain::page::PagedList; | 18 | use crate::domain::page::PagedList; |
| 19 | -use crate::domain::pool_question::PoolQuestionId; | 19 | +use crate::domain::pool_question::{PoolQuestionId, bump_question_and_write}; |
| 20 | use crate::domain::timestamp::Timestamp; | 20 | use crate::domain::timestamp::Timestamp; |
| 21 | use crate::domain::user::UserId; | 21 | use crate::domain::user::UserId; |
| 22 | use crate::error::{AppError, ValidationError}; | 22 | use crate::error::{AppError, ValidationError}; |
| @@ -130,10 +130,32 @@ impl Solution { | |||
| 130 | self.image_size | 130 | self.image_size |
| 131 | } | 131 | } |
| 132 | 132 | ||
| 133 | + /// Offer the solution. `NotFound` = the question is gone, and nothing was | ||
| 134 | + /// written: the create rides [`bump_question_and_write`], so the question's | ||
| 135 | + /// existence is a *write* to its row rather than a read the handler made a | ||
| 136 | + /// moment earlier — a bare create landing inside | ||
| 137 | + /// [`PoolQuestion::delete`](crate::domain::pool_question::PoolQuestion::delete)'s | ||
| 138 | + /// window was swept by nothing and left a solution no route could ever | ||
| 139 | + /// reach or remove (every path to one goes through its question), photo | ||
| 140 | + /// blob included. | ||
| 141 | + /// | ||
| 142 | + /// Re-sendable despite the `CREATE`: `$id` is a ULID minted once per call | ||
| 143 | + /// on a table with no `UNIQUE` index, so a re-send cannot answer "already | ||
| 144 | + /// exists" — the one thing the retry could not survive. | ||
| 133 | pub async fn insert(self, db: &Database) -> Result<Solution, AppError> { | 145 | pub async fn insert(self, db: &Database) -> Result<Solution, AppError> { |
| 134 | // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber | 146 | // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber |
| 135 | - let created: Option<Solution> = db.create(self.id.record()).content(self).await?; | 147 | + let (question, id) = (self.question.clone(), self.id.record()); |
| 136 | - created.ok_or_else(|| AppError::Internal("failed to create solution".into())) | 148 | + bump_question_and_write( |
| 149 | + &question, | ||
| 150 | + "CREATE $id CONTENT $solution", | ||
| 151 | + vec![ | ||
| 152 | + ("id".into(), id.into_value()), | ||
| 153 | + ("solution".into(), self.into_value()), | ||
| 154 | + ], | ||
| 155 | + db, | ||
| 156 | + ) | ||
| 157 | + .await? | ||
| 158 | + .ok_or_else(|| AppError::Internal("failed to create solution".into())) | ||
| 137 | } | 159 | } |
| 138 | 160 | ||
| 139 | /// Read a solution only if it belongs to `question` — keeps the nested | 161 | /// Read a solution only if it belongs to `question` — keeps the nested |
| @@ -256,11 +278,28 @@ mod tests { | |||
| 256 | 278 | ||
| 257 | use super::*; | 279 | use super::*; |
| 258 | 280 | ||
| 281 | + /// A real question row: offering a solution moves its question's | ||
| 282 | + /// `asked_at` (that is what keeps a solution from outliving its question), | ||
| 283 | + /// so a minted id nothing wrote is a 404. | ||
| 284 | + async fn question_row(db: &Database) -> PoolQuestionId { | ||
| 285 | + use crate::domain::pool_question::{PoolQuestion, PoolQuestionBody, PoolQuestionTitle}; | ||
| 286 | + PoolQuestion::new( | ||
| 287 | + &UserId::from_key(&Ulid::new().to_string()), | ||
| 288 | + PoolQuestionTitle::try_new("soru").unwrap(), | ||
| 289 | + PoolQuestionBody::try_new("neden").unwrap(), | ||
| 290 | + ) | ||
| 291 | + .insert(db) | ||
| 292 | + .await | ||
| 293 | + .unwrap() | ||
| 294 | + .get_id() | ||
| 295 | + .clone() | ||
| 296 | + } | ||
| 297 | + | ||
| 259 | #[tokio::test] | 298 | #[tokio::test] |
| 260 | async fn rows_scope_to_their_question_and_list_oldest_first() { | 299 | async fn rows_scope_to_their_question_and_list_oldest_first() { |
| 261 | let db = crate::database::init_mem().await.unwrap(); | 300 | let db = crate::database::init_mem().await.unwrap(); |
| 262 | - let question_a = PoolQuestionId::generate(); | 301 | + let question_a = question_row(&db).await; |
| 263 | - let question_b = PoolQuestionId::generate(); | 302 | + let question_b = question_row(&db).await; |
| 264 | let author = UserId::from_key(&Ulid::new().to_string()); | 303 | let author = UserId::from_key(&Ulid::new().to_string()); |
| 265 | 304 | ||
| 266 | // Distinct offer times so the assertion pins the real contract — | 305 | // Distinct offer times so the assertion pins the real contract — |
| @@ -322,7 +361,7 @@ mod tests { | |||
| 322 | #[tokio::test] | 361 | #[tokio::test] |
| 323 | async fn image_set_replace_clear_report_the_replaced_blob() { | 362 | async fn image_set_replace_clear_report_the_replaced_blob() { |
| 324 | let db = crate::database::init_mem().await.unwrap(); | 363 | let db = crate::database::init_mem().await.unwrap(); |
| 325 | - let question = PoolQuestionId::generate(); | 364 | + let question = question_row(&db).await; |
| 326 | let author = UserId::from_key(&Ulid::new().to_string()); | 365 | let author = UserId::from_key(&Ulid::new().to_string()); |
| 327 | let png = FileContentType::try_new("image/png").unwrap(); | 366 | let png = FileContentType::try_new("image/png").unwrap(); |
| 328 | 367 | ||
| @@ -388,7 +427,7 @@ mod tests { | |||
| 388 | #[tokio::test] | 427 | #[tokio::test] |
| 389 | async fn set_body_edits_in_place() { | 428 | async fn set_body_edits_in_place() { |
| 390 | let db = crate::database::init_mem().await.unwrap(); | 429 | let db = crate::database::init_mem().await.unwrap(); |
| 391 | - let question = PoolQuestionId::generate(); | 430 | + let question = question_row(&db).await; |
| 392 | let author = UserId::from_key(&Ulid::new().to_string()); | 431 | let author = UserId::from_key(&Ulid::new().to_string()); |
| 393 | 432 | ||
| 394 | let solution = Solution::new( | 433 | let solution = Solution::new( |
| @@ -427,9 +466,9 @@ mod tests { | |||
| 427 | #[tokio::test] | 466 | #[tokio::test] |
| 428 | async fn counts_for_groups_per_question() { | 467 | async fn counts_for_groups_per_question() { |
| 429 | let db = crate::database::init_mem().await.unwrap(); | 468 | let db = crate::database::init_mem().await.unwrap(); |
| 430 | - let two = PoolQuestionId::generate(); | 469 | + let two = question_row(&db).await; |
| 431 | - let one = PoolQuestionId::generate(); | 470 | + let one = question_row(&db).await; |
| 432 | - let none = PoolQuestionId::generate(); | 471 | + let none = question_row(&db).await; |
| 433 | let author = UserId::from_key(&Ulid::new().to_string()); | 472 | let author = UserId::from_key(&Ulid::new().to_string()); |
| 434 | 473 | ||
| 435 | for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] { | 474 | for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] { |