From a8435eea94df7126b74ac8a80b88ae328e709dbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 2 Aug 2026 00:56:13 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=94=A9=20land=20counter=20claims?= =?UTF-8?q?=20with=20their=20rows,=20refuse=20stale=20movers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/domain/appointment.rs | 90 ++++++++--- src/domain/cap.rs | 290 ++++++++++++++++++++++++++++++++++- src/domain/chatbot_thread.rs | 107 +++++++++++-- src/domain/class_group.rs | 21 ++- src/domain/course.rs | 104 ++++++++++++- src/domain/exam_result.rs | 244 ++++++++++++++++++++++------- src/domain/field_update.rs | 90 ++++++++--- src/domain/note_file.rs | 103 ++++++++++--- src/domain/term.rs | 5 +- 9 files changed, 905 insertions(+), 149 deletions(-) diff --git a/src/domain/appointment.rs b/src/domain/appointment.rs index 48a4a08..c41d02f 100644 --- a/src/domain/appointment.rs +++ b/src/domain/appointment.rs @@ -5,7 +5,8 @@ //! Two *cross-record* invariants live here, guarded very differently: //! //! - **One live booking per slot** — the `occupied` counter on the slot row, a -//! [`cap`](crate::domain::cap) of one. Booking [`claim`](cap::claim)s it; +//! [`cap`](crate::domain::cap) of one. Booking claims it *with* the booking +//! row ([`claim_and_create`](cap::claim_and_create)); //! rejecting or cancelling gives it back in the *same transaction* as the //! status flip, so the slot frees itself with nothing to sweep. Both are //! single-record conditional writes, so the store decides it, not a lock. @@ -320,10 +321,12 @@ impl Appointment { /// /// Refused (409) when the slot's window has already opened, when it is /// already taken, or when the requester is already committed elsewhere at - /// that time. The slot is taken by [`cap::claim`] on the slot row — a - /// conditional single-record write, so two racing requests cannot both find - /// it free however they interleave; the requester's own overlap is the - /// lock's part. + /// that time. The slot is taken by [`cap::claim_and_create`], which writes + /// the booking in the *same transaction* as the seat — a conditional + /// single-record write, so two racing requests cannot both find it free + /// however they interleave, and a crash between the two can no longer leave + /// the slot occupied by a booking that does not exist. The requester's own + /// overlap is the lock's part. pub async fn book( slot: &AppointmentSlotId, requester: &UserId, @@ -363,12 +366,6 @@ impl Appointment { // finds no row either way, so the distinction is re-read rather than // guessed. let seat = slot.record(); - if !cap::claim(&seat, SLOT_OCCUPIED_FIELD, 1, db).await? { - if AppointmentSlot::read(slot, db).await?.is_none() { - return Err(AppError::NotFound); - } - return Err(AppError::Conflict("the slot is already booked")); - } let appointment = Appointment { id: AppointmentId::generate(), slot: slot.clone(), @@ -384,20 +381,26 @@ impl Appointment { reject_reason: None, created_at: Timestamp::now(), }; - let created: Result, _> = db - .create(appointment.id.record()) - .content(appointment) - .await; - match created { - Ok(Some(created)) => Ok(created), - // The booking never landed, so the slot it took goes back. - other => { - cap::release(&seat, SLOT_OCCUPIED_FIELD, db).await?; - Err(match other { - Err(err) => err.into(), - _ => AppError::Internal("failed to book the appointment".into()), - }) + match cap::claim_and_create( + &seat, + SLOT_OCCUPIED_FIELD, + 1, + &appointment.id.record(), + &appointment, + db, + ) + .await? + { + cap::Claimed::Made(created) => Ok(created), + cap::Claimed::Full => { + if AppointmentSlot::read(slot, db).await?.is_none() { + return Err(AppError::NotFound); + } + Err(AppError::Conflict("the slot is already booked")) } + // The id is a freshly minted ULID on a table with no UNIQUE index, + // so no rival can have aimed at it. + cap::Claimed::Duplicate => Err(AppError::Internal("appointment id collided".into())), } } @@ -1005,6 +1008,45 @@ mod tests { ); } + /// The seat and the booking row now land in one transaction, so the stored + /// state must move together: a taken slot refuses the next requester with + /// the counter *and* the row list untouched — a refusal that had already + /// bumped the counter would strand the slot forever. + #[tokio::test] + async fn a_refused_booking_moves_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let teacher = UserId::from_key("t1"); + let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) + .await + .unwrap(); + let reason = || AppointmentReason::try_new("görüşme").unwrap(); + + Appointment::book(slot.get_id(), &UserId::from_key("s1"), reason(), &db) + .await + .unwrap(); + assert_eq!(occupied(slot.get_id(), &db).await, 1); + + let refused = + Appointment::book(slot.get_id(), &UserId::from_key("s2"), reason(), &db).await; + assert!( + matches!(refused, Err(AppError::Conflict(_))), + "the slot is taken" + ); + assert_eq!( + occupied(slot.get_id(), &db).await, + 1, + "the refusal took no seat" + ); + assert_eq!( + Appointment::list_for_slot(slot.get_id(), &db) + .await + .unwrap() + .len(), + 1, + "and wrote no row" + ); + } + /// Cancelling gives the seat back in the same transaction as the status /// flip — the counter is the only thing that says a slot is free, so a /// cancel that moved one without the other would strand the slot forever. diff --git a/src/domain/cap.rs b/src/domain/cap.rs index e4a2c3a..d3f0868 100644 --- a/src/domain/cap.rs +++ b/src/domain/cap.rs @@ -120,6 +120,11 @@ async fn claim_at( const FULL_MARK: &str = "cap_full"; const HELD_MARK: &str = "cap_held"; +/// [`claim_ref_and_create`]'s third answer: the *name* is retired, which is not +/// a count being full — nothing empties it, and only putting the name back in +/// service lets a claim through. +const RETIRED_MARK: &str = "cap_retired"; + /// The two markers [`claim_two_when_and_create`] aborts with, one per counter, /// deliberately *not* shared: its two caps mean opposite things to the person /// who hit one. The soft cap is a resettable working set (a whiteboard's live @@ -166,12 +171,54 @@ pub(crate) async fn claim_and_create( content: &T, db: &Database, ) -> Result, AppError> { + claim_at_and_create(parent, field, cap, "", id, content, db).await +} + +/// [`claim_and_create`], but only while `guard` — an extra predicate on that +/// same parent row — also holds, exactly as [`claim_when`] is to [`claim`]: one +/// conditional write decides the cap *and* the caller's second precondition, so +/// no read a concurrent write can outrun sits between them. +/// +/// The contract that costs the caller something: [`Claimed::Full`] means "full +/// **or** the guard failed **or** the parent row is gone" — one marker for all +/// three, because the seat `UPDATE` matching nothing cannot say which clause +/// refused it. A caller that needs to tell them apart re-reads the parent, and +/// only to pick the message: none of the three is retryable into a success. +/// +/// `guard` is always an in-crate SQL literal or built in-crate out of numbers +/// this crate read back itself — never text from a client. +pub(crate) async fn claim_when_and_create( + parent: &RecordId, + field: &str, + cap: i64, + guard: &str, + id: &RecordId, + content: &T, + db: &Database, +) -> Result, AppError> { + claim_at_and_create(parent, field, cap, guard, id, content, db).await +} + +async fn claim_at_and_create( + parent: &RecordId, + field: &str, + cap: i64, + extra: &str, + id: &RecordId, + content: &T, + db: &Database, +) -> Result, AppError> { + let extra = if extra.is_empty() { + String::new() + } else { + format!(" AND ({extra})") + }; let sql = format!( "BEGIN TRANSACTION; LET $held = (SELECT VALUE id FROM $id); IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; LET $seat = (UPDATE $parent SET {field} = ({field} ?? 0) + 1 \ - WHERE ({field} ?? 0) < $num RETURN VALUE id); + WHERE ({field} ?? 0) < $num{extra} RETURN VALUE id); IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }}; CREATE $id CONTENT $row; COMMIT TRANSACTION;" @@ -408,6 +455,111 @@ pub(crate) async fn claim_ref(id: &RecordId, n: i64, db: &Database) -> Result { + /// The reference and the row committed together. + Made(T), + /// The name is retired — nothing was written, and no retry helps until the + /// name is put back in service. + Retired, + /// Another writer placed this very row first, so this caller never owed a + /// reference: nothing was written, and the winner's row is the answer. + Duplicate, +} +// +// A separate enum rather than a `Retired` variant on [`Claimed`]: that enum is +// matched exhaustively by a dozen callers in files this change does not touch, +// and a cap has no retired state to answer for anyway. + +/// Take one reference on `counter` *and* write the row that holds it, in one +/// transaction — [`claim_and_create`] pointed at a name instead of a cap. +/// +/// [`claim_ref`] followed by a separate insert cannot promise this: the claim +/// lands, the insert then fails or the process dies, and the name is counted as +/// used by a row that does not exist — which is a name nobody can ever retire. +/// Here the abort takes the increment with it. +/// +/// The `$held` gate comes first for [`claim_and_create`]'s reason: where the +/// child carries a deterministic id, a rival can place the very row this caller +/// is placing, and "you already have it" is the honest answer — one that must +/// not cost a reference. Which is also why this carries its own retry loop +/// rather than [`crate::database::transaction_with_retry`]'s: the `CREATE` can +/// legitimately answer "already exists", and that loop cannot tell that answer +/// from a lost round. The `UPSERT` cannot answer it — `kind_ref`/`slot_ref` +/// carry no `UNIQUE` index, so a write keyed by id resolves onto the row the id +/// names. +pub(crate) async fn claim_ref_and_create( + counter: &RecordId, + n: i64, + id: &RecordId, + content: &T, + db: &Database, +) -> Result, AppError> { + let sql = format!( + "BEGIN TRANSACTION; + LET $held = (SELECT VALUE id FROM $id); + IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; + LET $ref = (UPSERT $parent SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + $num \ + WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id); + IF array::len($ref) = 0 {{ THROW '{RETIRED_MARK}' }}; + CREATE $id CONTENT $row; + COMMIT TRANSACTION;" + ); + let _guard = CLAIM_LOCK.lock().await; + let mut last = None; + for attempt in 0..CAP_WRITE_TRIES { + backoff(attempt).await; + let attempted = db + .query(sql.as_str()) + .bind(("parent", counter.clone())) + .bind(("num", n)) + .bind(("id", id.clone())) + .bind(("row", content.clone())) + .await; + let mut result = match attempted { + Ok(result) => result, + Err(err) if lost_the_race(&err) => { + last = Some(err); + continue; + } + Err(err) => return Err(err.into()), + }; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the failing slot says why. The markers are read + // before the conflict check, because a `THROW` is a decision. + let mut errors = result.take_errors(); + if errors + .values() + .any(|error| error.to_string().contains(HELD_MARK) || error.is_already_exists()) + { + return Ok(ClaimedRef::Duplicate); + } + if errors + .values() + .any(|error| error.to_string().contains(RETIRED_MARK)) + { + return Ok(ClaimedRef::Retired); + } + if errors.values().any(lost_the_race) { + last = errors.drain().map(|(_, error)| error).find(lost_the_race); + continue; + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5. + return result + .take::>(5)? + .into_iter() + .next() + .map(ClaimedRef::Made) + .ok_or_else(|| AppError::Internal("cap claim wrote no row".into())); + } + Err(last + .map(AppError::from) + .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) +} + /// Give `n` references back — the referencing rows are gone (or never landed). /// Clamped at zero like [`release`], so a double release cannot push a counter /// below the rows it counts and let a used name be retired. @@ -625,4 +777,140 @@ mod tests { assert_eq!(stored(&db).await, (0, 0)); assert_eq!(strokes(&db).await, 0); } + + // --- claim_when_and_create ------------------------------------------ + + async fn claim_one(db: &Database, cap: i64, key: &str) -> Claimed { + claim_when_and_create( + &RecordId::new("board", "b"), + BOARD_EPOCH_STROKE_COUNT_FIELD, + cap, + BOARD_OPEN_GUARD, + &RecordId::new("board_stroke", key), + &a_stroke(), + db, + ) + .await + .unwrap() + } + + #[tokio::test] + async fn a_guarded_claim_advances_its_counter_exactly_once() { + let db = a_board(0, 0, false).await; + assert!(matches!(claim_one(&db, 9, "s1").await, Claimed::Made(_))); + assert_eq!(stored(&db).await, (1, 0)); + assert_eq!(strokes(&db).await, 1); + } + + /// A failed guard is refused as `Full` (the one marker covers full, guard + /// and missing parent), and must leave the counter and the table alone. + #[tokio::test] + async fn a_guard_refusal_advances_neither_counter_nor_row() { + let db = a_board(0, 0, true).await; + assert!(matches!(claim_one(&db, 9, "s1").await, Claimed::Full)); + assert_eq!(stored(&db).await, (0, 0)); + assert_eq!(strokes(&db).await, 0); + } + + /// The second writer at the same id owes no seat: the row is already there, + /// so the counter must not move a second time for it. + #[tokio::test] + async fn a_duplicate_row_claims_no_seat() { + let db = a_board(0, 0, false).await; + assert!(matches!(claim_one(&db, 9, "s1").await, Claimed::Made(_))); + assert!(matches!(claim_one(&db, 9, "s1").await, Claimed::Duplicate)); + assert_eq!(stored(&db).await, (1, 0)); + assert_eq!(strokes(&db).await, 1); + } + + // --- claim_ref_and_create ------------------------------------------- + + #[derive(Debug, Clone, SurrealValue)] + struct Menu { + date: String, + slot: String, + created_by: RecordId, + created_at: i64, + } + + async fn a_slot(count: i64, retired: bool) -> Database { + let db = crate::database::init_mem().await.unwrap(); + db.query( + "CREATE user:u SET username = 'u', password_hash = 'x'; + UPSERT slot_ref:lunch SET count = $count, retired = $retired;", + ) + .bind(("count", count)) + .bind(("retired", retired)) + .await + .unwrap() + .check() + .unwrap(); + db + } + + /// The reference count, re-read out of the store — never off a return + /// value, which the in-memory engine forges wins on (see `CLAIM_LOCK`). + async fn refs(db: &Database) -> i64 { + let mut result = db + .query("SELECT VALUE (count ?? 0) FROM slot_ref:lunch") + .await + .unwrap() + .check() + .unwrap(); + result.take::>(0).unwrap()[0] + } + + async fn menus(db: &Database) -> usize { + let mut result = db + .query("SELECT VALUE id FROM menu") + .await + .unwrap() + .check() + .unwrap(); + result.take::>(0).unwrap().len() + } + + async fn claim_slot(db: &Database, key: &str) -> ClaimedRef { + claim_ref_and_create( + &RecordId::new(crate::constant::SLOT_REF_TABLE, "lunch"), + 1, + &RecordId::new("menu", key), + &Menu { + date: "2026-08-02".into(), + slot: "lunch".into(), + created_by: RecordId::new("user", "u"), + created_at: 1, + }, + db, + ) + .await + .unwrap() + } + + #[tokio::test] + async fn a_reference_and_its_row_land_together() { + let db = a_slot(0, false).await; + assert!(matches!(claim_slot(&db, "m1").await, ClaimedRef::Made(_))); + assert_eq!(refs(&db).await, 1); + assert_eq!(menus(&db).await, 1); + } + + /// A retired name refuses, and the refusal must cost nothing: no row, no + /// count — a counted row on a retired name is a name nobody can retire. + #[tokio::test] + async fn a_retired_name_refuses_with_no_row_and_no_count() { + let db = a_slot(0, true).await; + assert!(matches!(claim_slot(&db, "m1").await, ClaimedRef::Retired)); + assert_eq!(refs(&db).await, 0); + assert_eq!(menus(&db).await, 0); + } + + #[tokio::test] + async fn a_duplicate_row_claims_no_reference() { + let db = a_slot(0, false).await; + assert!(matches!(claim_slot(&db, "m1").await, ClaimedRef::Made(_))); + assert!(matches!(claim_slot(&db, "m1").await, ClaimedRef::Duplicate)); + assert_eq!(refs(&db).await, 1); + assert_eq!(menus(&db).await, 1); + } } diff --git a/src/domain/chatbot_thread.rs b/src/domain/chatbot_thread.rs index a986d4b..79afc34 100644 --- a/src/domain/chatbot_thread.rs +++ b/src/domain/chatbot_thread.rs @@ -88,6 +88,10 @@ impl ChatbotThread { self.updated_at } + /// Write a thread row and nothing else. **Bypasses the cap counter**, so it + /// is only for tests that need a thread without one (`tests/persistence.rs` + /// cascade check); every production path goes through + /// [`ChatbotThread::create_capped`]. pub async fn create( user: &UserId, title: Option, @@ -106,28 +110,44 @@ impl ChatbotThread { } /// Start a thread unless `user` is already at the school's - /// `max_chatbot_threads`. The slot is taken by [`cap::claim`] on the user - /// row — an atomic single-record write, so two requests racing the same - /// user's last slot cannot both win, and the cap is read fresh so a - /// concurrent settings PATCH is respected. + /// `max_chatbot_threads`. The slot is taken on the user row in the same + /// transaction as the thread ([`cap::claim_and_create`]) — an atomic + /// single-record write, so two requests racing the same user's last slot + /// cannot both win, the counter can never count a row that did not commit, + /// and the cap is read fresh so a concurrent settings PATCH is respected. pub async fn create_capped( user: &UserId, title: Option, db: &Database, ) -> Result { let limit = Settings::load(db).await?.get_max_chatbot_threads(); - let owner = user.record(); - if !cap::claim(&owner, CHATBOT_THREAD_COUNT_FIELD, limit, db).await? { - return Err(AppError::Conflict( + let now = Timestamp::now(); + let thread = ChatbotThread { + id: ChatbotThreadId::generate(), + user_id: user.clone(), + title, + created_at: now, + updated_at: now, + }; + match cap::claim_and_create( + &user.record(), + CHATBOT_THREAD_COUNT_FIELD, + limit, + &thread.id.record(), + &thread, + db, + ) + .await? + { + cap::Claimed::Made(saved) => Ok(saved), + // Full, or the user's row is gone — the conditional write matches + // nothing either way. + cap::Claimed::Full => Err(AppError::Conflict( "you have reached the school's limit on saved threads — delete one first", - )); - } - match Self::create(user, title, db).await { - Ok(thread) => Ok(thread), - Err(err) => { - cap::release(&owner, CHATBOT_THREAD_COUNT_FIELD, db).await?; - Err(err) - } + )), + // The id is a freshly minted ULID on a table with no UNIQUE index, + // so no rival can have aimed at it. + cap::Claimed::Duplicate => Err(AppError::Internal("thread id collided".into())), } } @@ -238,6 +258,63 @@ impl ChatbotThread { #[cfg(test)] mod tests { use super::*; + use crate::domain::settings::SettingsParams; + + /// The owner's counter and the threads it counts, both re-read out of the + /// store — never off a return value, which the in-memory engine forges + /// wins on (see [`cap`]). + async fn stored(db: &Database) -> (i64, usize) { + let mut result = db + .query("SELECT VALUE (chatbot_thread_count ?? 0) FROM user:u") + .query("SELECT VALUE id FROM chatbot_thread") + .await + .unwrap() + .check() + .unwrap(); + let counter = result.take::>(0).unwrap(); + let rows = result.take::>(1).unwrap(); + (counter[0], rows.len()) + } + + async fn a_user_capped_at(threads: i64) -> Database { + let db = crate::database::init_mem().await.unwrap(); + db.query("CREATE user:u SET username = 'u', password_hash = 'x';") + .await + .unwrap() + .check() + .unwrap(); + Settings::try_new(SettingsParams { + max_chatbot_threads: threads, + ..Settings::defaults().params() + }) + .unwrap() + .save(&db) + .await + .unwrap(); + db + } + + /// The seat and the row commit together, so the counter the cap reads can + /// never disagree with the threads it counts — and a create refused at the + /// cap advances neither. + #[tokio::test] + async fn a_capped_create_moves_the_counter_with_the_row() { + let db = a_user_capped_at(1).await; + let user = UserId::from_key("u"); + + ChatbotThread::create_capped(&user, None, &db) + .await + .expect("first thread"); + assert_eq!(stored(&db).await, (1, 1)); + + let refused = ChatbotThread::create_capped(&user, None, &db).await; + assert!(matches!(refused, Err(AppError::Conflict(_))), "at the cap"); + assert_eq!( + stored(&db).await, + (1, 1), + "a refused create advances neither" + ); + } #[tokio::test] async fn title_is_required_and_bounded() { diff --git a/src/domain/class_group.rs b/src/domain/class_group.rs index d53dc74..0aeaa88 100644 --- a/src/domain/class_group.rs +++ b/src/domain/class_group.rs @@ -199,11 +199,19 @@ impl ClassGroup { db: &Database, ) -> Result { let (claim, release) = term::ref_move(self.term.as_ref(), &term); + let expected = self.term.as_ref().map(TermId::record); FieldUpdate::new(self.id.record()) .set("name", name) .set("grade", grade) .set("term", term.map(|term| term.map(|term| term.record()))) - .refcount(TERM_CLASS_COUNT_FIELD, claim, release, term::gone_error()) + .refcount( + TERM_CLASS_COUNT_FIELD, + "term", + expected, + claim, + release, + term::gone_error(), + ) .run::(db) .await } @@ -489,7 +497,10 @@ mod tests { .await .expect_err("a term that is gone must not be linkable"); assert!(error.to_string().contains("term does not exist")); - let stored = ClassGroup::read(class.get_id(), &db).await.unwrap().unwrap(); + let stored = ClassGroup::read(class.get_id(), &db) + .await + .unwrap() + .unwrap(); assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put"); assert_eq!(stored.get_name().as_str(), "9-A", "…and so does the row"); assert_eq!( @@ -503,7 +514,11 @@ mod tests { .await .unwrap(); assert_eq!(moved.get_term(), Some(to.get_id())); - assert_eq!(count_on(from.get_id(), &db).await, 0, "the old term is free"); + assert_eq!( + count_on(from.get_id(), &db).await, + 0, + "the old term is free" + ); assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); } diff --git a/src/domain/course.rs b/src/domain/course.rs index 2e3f216..ed0c9c6 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -290,13 +290,21 @@ impl Course { // without its count. A PATCH that carried no `term_id`, or re-stated the // link it already had, moves neither counter. let (claim, release) = term::ref_move(self.term.as_ref(), &term); + let expected = self.term.as_ref().map(TermId::record); FieldUpdate::new(self.id.record()) .set("title", title) .set("description", description) .set("kind", kind) .set("term", term.map(|term| term.map(|term| term.record()))) .set("capacity", capacity) - .refcount(COURSE_COUNT_FIELD, claim, release, term::gone_error()) + .refcount( + COURSE_COUNT_FIELD, + "term", + expected, + claim, + release, + term::gone_error(), + ) .run::(db) .await } @@ -583,7 +591,9 @@ mod tests { /// The stored `course_count` on one term, absent counting as zero. async fn count_on(term: &TermId, db: &Database) -> i64 { let mut result = db - .query(format!("SELECT VALUE ({COURSE_COUNT_FIELD} ?? 0) FROM $term")) + .query(format!( + "SELECT VALUE ({COURSE_COUNT_FIELD} ?? 0) FROM $term" + )) .bind(("term", term.record())) .await .unwrap() @@ -661,12 +671,94 @@ mod tests { .await .unwrap(); assert_eq!(moved.get_term(), Some(to.get_id())); - assert_eq!(count_on(from.get_id(), &db).await, 0, "the old term is free"); + assert_eq!( + count_on(from.get_id(), &db).await, + 0, + "the old term is free" + ); assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); assert!(from.clone().delete(&db).await.unwrap()); assert!(!to.clone().delete(&db).await.unwrap()); } + /// The double-claim guard. Both movers compute their claim and release from + /// the row as *they* read it, so two PATCHes moving the same course off the + /// same term both release it and both claim their target — two counts for + /// one link, and the loser's target is undeletable forever. The second call + /// here runs on the struct read before the first one landed, which is that + /// race with the interleaving pinned: it must be refused outright, and the + /// counts must read as if it never ran. + #[tokio::test] + async fn a_stale_mover_is_refused_and_claims_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let from = a_term("2026", &db).await; + let to = a_term("2027", &db).await; + let other = a_term("2028", &db).await; + let course = course_on(Some(from.get_id().clone()), &db).await; + let stale = course.clone(); + course + .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) + .await + .unwrap(); + + let error = stale + .clone() + .update( + None, + None, + None, + Some(Some(other.get_id().clone())), + None, + &db, + ) + .await + .expect_err("a mover that read a link it no longer holds must be refused"); + assert!( + matches!(error, AppError::Conflict(_)), + "a lost CAS is a conflict, not a 404 or a 500: {error:?}" + ); + let stored = Course::read(stale.get_id(), &db).await.unwrap().unwrap(); + assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link"); + assert_eq!( + count_on(from.get_id(), &db).await, + 0, + "released once, not twice" + ); + assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once"); + assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed"); + + // Same race from the other end: the snapshot says *no* link, so the CAS + // is against an absent column — the shape a bound `NONE` has to match. + let unlinked = course_on(None, &db).await; + let stale = unlinked.clone(); + unlinked + .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) + .await + .unwrap(); + let error = stale + .clone() + .update( + None, + None, + None, + Some(Some(other.get_id().clone())), + None, + &db, + ) + .await + .expect_err("a mover that read an absent link someone else filled must be refused"); + assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); + assert_eq!(count_on(to.get_id(), &db).await, 2, "one claim per link"); + assert_eq!( + count_on(other.get_id(), &db).await, + 0, + "still never claimed" + ); + // …and the unraced set still lands, so the CAS did not just break moves. + let stored = Course::read(stale.get_id(), &db).await.unwrap().unwrap(); + assert_eq!(stored.get_term(), Some(to.get_id())); + } + /// The rollback proof. The transaction releases the old term *before* it /// claims the new one, so a move to a term that is gone has already /// decremented when the claim throws — the old count still being 1 is the @@ -697,7 +789,11 @@ mod tests { let stored = Course::read(course.get_id(), &db).await.unwrap().unwrap(); assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put"); - assert_eq!(stored.get_title().as_str(), "algebra", "…and so does the row"); + assert_eq!( + stored.get_title().as_str(), + "algebra", + "…and so does the row" + ); assert_eq!( count_on(from.get_id(), &db).await, 1, diff --git a/src/domain/exam_result.rs b/src/domain/exam_result.rs index df5f20f..26c259f 100644 --- a/src/domain/exam_result.rs +++ b/src/domain/exam_result.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ - EXAM_RESULT_COUNT_FIELD, EXAM_RESULT_TABLE, KIND_REF_TABLE, REF_COUNT_FIELD, + EXAM_RESULT_COUNT_FIELD, EXAM_RESULT_TABLE, KIND_REF_TABLE, REF_COUNT_FIELD, REF_RETIRED_FIELD, }; use crate::database::{Database, transaction_with_retry}; use crate::domain::cap; @@ -81,13 +81,9 @@ impl Mark { } } -/// What one mark write reports back: the stored row, and whether it replaced a -/// mark that was already there. -#[derive(Debug, Clone, SurrealValue)] -struct Written { - existed: bool, - result: ExamResult, -} +/// The `THROW` marker the in-transaction kind claim aborts with — the mark's +/// own transaction refusing a name the school has retired. +const RETIRED_MARK: &str = "kind_retired"; #[derive(Debug, Clone, SurrealValue)] pub struct ExamResult { @@ -188,17 +184,23 @@ impl ExamResult { /// prior sittings' marks; the latest seq is the grade-of-record. /// /// `kind` is the exam's kind, and this is where a mark takes its reference - /// on it — claimed *before* the write, given back when the write turns out - /// to have been an overwrite (one mark, one reference) or to have failed. A - /// kind the school has retired refuses the claim, which is the same - /// invariant the settings guard enforces from the other side, and the one - /// crash window left over-counts a kind (refusing a removal) rather than - /// letting a mark exist under a kind nothing counted. + /// on it — claimed *inside the mark's own transaction*, and only on the + /// branch that is about to add a row. A kind the school has retired refuses + /// the claim, which is the same invariant the settings guard enforces from + /// the other side. Claimed before the write and released after, the pair had + /// two crash windows either side of the write that leaked a reference (a + /// kind frozen out of the settings for good) and an exam's `result_count`; + /// riding the transaction, both counters land exactly when the row does. /// /// The exam's own `result_count` is claimed in the same breath, and it is /// what a kind change is refused against: the exam PATCH pins that counter, /// so a mark landing while it decides cannot slip past its gate and leave /// itself counted under a kind its exam no longer carries. + /// + /// An overwrite (a regrade of a sitting already marked) claims *nothing*: + /// one mark, one reference, so the branch that finds a row simply leaves + /// both counters where they are — there is no claim to give back, and so no + /// window in which a crash could fail to give it. pub async fn grade( exam: &ExamId, user: &UserId, @@ -208,32 +210,6 @@ impl ExamResult { kind: &str, db: &Database, ) -> Result { - let counter = kind_ref(kind); - if !cap::claim_ref(&counter, 1, db).await? { - return Err(retired_kind_error(kind)); - } - cap::claim(&exam.record(), EXAM_RESULT_COUNT_FIELD, cap::UNLIMITED, db).await?; - let written = Self::write_mark(exam, user, seq, mark, graded_by, db).await; - match written { - // An overwrite is not a second mark: both counters go back, or a - // regrade would drift them upward and freeze the kind for good. - Ok(Written { existed: true, .. }) | Err(_) => { - cap::release_ref(&counter, 1, db).await?; - cap::release(&exam.record(), EXAM_RESULT_COUNT_FIELD, db).await?; - } - Ok(_) => {} - } - written.map(|written| written.result) - } - - async fn write_mark( - exam: &ExamId, - user: &UserId, - seq: i64, - mark: Mark, - graded_by: &UserId, - db: &Database, - ) -> Result { let result = ExamResult { id: ExamResultId::composite(exam, user, seq), exam: exam.clone(), @@ -250,33 +226,52 @@ impl ExamResult { // redundant with the draft one — a deleted exam reads NONE, which is // *falsy*, so the draft gate alone waved a mark onto an exam that no // longer existed. The caller's pre-flight check answers the same 409 - // one round trip earlier. - // Whether the row was already there rides out of the transaction with - // the mark: the answer decides if this grade owes the kind a reference, - // and read anywhere else it would be a guess about a row two graders - // may be writing at once. + // one round trip earlier. It is also what makes a separate "did the + // exam survive my claim?" check moot: the claim now sits behind this + // gate instead of in front of it. + // + // Whether the row was already there decides both counters, and it is + // read one statement before them inside the same transaction — read + // anywhere else it would be a guess about a row two graders may be + // writing at once. // // Re-sent while the store answers "conflict, retry": the gates read a - // column an exam PATCH writes, so the two contend on one record by - // design. Sound to re-send because the only write is an UPSERT on a - // deterministic id — `key::sitting(exam, user, seq)` *is* the - // `exam_result_exam_user_seq` unique tuple — so it can never answer - // "already exists", the one thing a retry cannot fix. + // column an exam PATCH writes, and the counters are the ones a + // concurrent delete gives back, so this contends on three records by + // design. Sound to re-send because no statement in it can legitimately + // answer "already exists": the counter writes are `UPDATE`/`UPSERT` on + // ids no rival can collide *into*, and the mark's own UPSERT is on a + // deterministic id bijective with the `exam_result_exam_user_seq` + // unique tuple — `key::sitting(exam, user, seq)` *is* that tuple, so + // the index entry can only ever point at the row the id already names + // and the write resolves onto it. A lost round aborts having written + // nothing, counters included. + let _guard = cap::counter_lock().await; let (mut written, mut errors) = transaction_with_retry( db, - "BEGIN TRANSACTION; - IF (SELECT VALUE id FROM ONLY $exam) IS NONE { THROW 'exam_missing' }; - IF (SELECT VALUE draft FROM ONLY $exam) { THROW 'exam_draft' }; + &format!( + "BEGIN TRANSACTION; + IF (SELECT VALUE id FROM ONLY $exam) IS NONE {{ THROW 'exam_missing' }}; + IF (SELECT VALUE draft FROM ONLY $exam) {{ THROW 'exam_draft' }}; LET $before = (SELECT VALUE id FROM ONLY $id); + IF $before = NONE {{ + LET $kind = (UPSERT $kref SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + 1 + WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id); + IF array::len($kind) = 0 {{ THROW '{RETIRED_MARK}' }}; + UPDATE $exam SET {EXAM_RESULT_COUNT_FIELD} = + ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1; + }}; LET $after = (UPSERT $id CONTENT $result RETURN AFTER); - RETURN { existed: $before != NONE, result: $after[0] }; - COMMIT TRANSACTION;", + RETURN $after[0]; + COMMIT TRANSACTION;" + ), &[ ("exam".into(), exam.record().into_value()), ("id".into(), result.id.record().into_value()), + ("kref".into(), kind_ref(kind).into_value()), ("result".into(), result.into_value()), ], - &["exam_missing", "exam_draft"], + &["exam_missing", "exam_draft", RETIRED_MARK], ) .await?; // An aborted transaction errors every slot and only the THROW's own @@ -293,15 +288,20 @@ impl ExamResult { if thrown("exam_draft") { return Err(draft_error()); } + if thrown(RETIRED_MARK) { + return Err(retired_kind_error(kind)); + } if let Some(error) = errors.drain().map(|(_, error)| error).next() { return Err(error.into()); } // The trailing `RETURN` is always the last statement before `COMMIT`, // so its slot follows the statement count instead of a hand-kept // number — see `Exam::delete` for the bug the hand-kept one caused. + // Probed on crate 3.2.3: an `IF { … }` block occupies exactly one slot + // however many statements it holds, and one whether or not it is taken. let slot = written.num_statements().saturating_sub(2); written - .take::>(slot)? + .take::>(slot)? .into_iter() .next() .ok_or_else(|| AppError::Internal("failed to record exam result".into())) @@ -531,5 +531,135 @@ mod tests { .unwrap() .is_empty() ); + assert_eq!(counters(&db, "midterm").await, (0, 0)); + } + + /// The two counters, re-read out of the store — never off a return value, + /// which the in-memory engine forges wins on (see `cap::CLAIM_LOCK`). A + /// missing `kind_ref` row is a zero, which is exactly how the backfill + /// treats it (`tests/persistence.rs` — no zero pass, deliberately). + async fn counters(db: &Database, kind: &str) -> (i64, i64) { + let mut result = db + .query( + "SELECT VALUE count ?? 0 FROM kind_ref WHERE record::id(id) = $kind; + SELECT VALUE result_count ?? 0 FROM exam;", + ) + .bind(("kind", kind.to_string())) + .await + .unwrap() + .check() + .unwrap(); + let kinds: Vec = result.take(0).unwrap(); + let exams: Vec = result.take(1).unwrap(); + ( + kinds.into_iter().next().unwrap_or(0), + exams.into_iter().next().unwrap_or(0), + ) + } + + async fn an_exam(db: &Database, exam: &ExamId, kind: &str) { + db.query( + "CREATE $ex SET creator = user:t, course = course:c, title = 't', + description = '', kind = $kind", + ) + .bind(("ex", exam.record())) + .bind(("kind", kind.to_string())) + .await + .unwrap() + .check() + .unwrap(); + } + + async fn grade( + db: &Database, + exam: &ExamId, + seq: i64, + mark: i64, + kind: &str, + ) -> Result { + ExamResult::grade( + exam, + &UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"), + seq, + Mark::try_new(mark).unwrap(), + &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), + kind, + db, + ) + .await + } + + /// Both counters ride the mark's own transaction: a new mark claims each + /// exactly once, and a *regrade* of the same sitting claims neither — one + /// mark, one reference. Claimed-then-released around the write, a regrade + /// drifted them upward and froze the kind out of the settings for good. + #[tokio::test] + async fn a_new_mark_moves_both_counters_and_a_regrade_moves_neither() { + let db = init_mem().await.unwrap(); + let exam = ExamId::from_key("01TESTEXAMCOUNTAAAAAAAAAAA"); + an_exam(&db, &exam, "midterm").await; + + grade(&db, &exam, 1, 40, "midterm").await.unwrap(); + assert_eq!(counters(&db, "midterm").await, (1, 1)); + + // Same sitting, new mark: an overwrite, so neither counter moves. + let regraded = grade(&db, &exam, 1, 90, "midterm").await.unwrap(); + assert_eq!(regraded.get_mark().as_i64(), 90); + assert_eq!(counters(&db, "midterm").await, (1, 1)); + + // A retake is a second row, so it does claim. + grade(&db, &exam, 2, 70, "midterm").await.unwrap(); + assert_eq!(counters(&db, "midterm").await, (2, 2)); + } + + /// A retired kind refuses the claim from inside the transaction, which + /// takes the mark and the exam's counter down with it — the settings guard + /// enforcing the same invariant from the other side. + #[tokio::test] + async fn a_retired_kind_refuses_the_mark_and_leaves_both_counters_alone() { + let db = init_mem().await.unwrap(); + let exam = ExamId::from_key("01TESTEXAMRETIREDAAAAAAAAA"); + an_exam(&db, &exam, "midterm").await; + assert!(cap::retire(&kind_ref("midterm"), &db).await.unwrap()); + + let refused = grade(&db, &exam, 1, 40, "midterm").await; + assert!( + matches!(&refused, Err(AppError::ConflictOwned(message)) + if message.contains("has been removed from the school's settings")), + "{refused:?}" + ); + assert!( + ExamResult::list_for_exam(&exam, &db) + .await + .unwrap() + .is_empty(), + "the mark must not have landed" + ); + assert_eq!(counters(&db, "midterm").await, (0, 0)); + } + + /// A draft exam refuses the mark, and the counters stay put — the gate + /// runs before the claim now, so there is nothing to give back. + #[tokio::test] + async fn a_draft_exam_refuses_the_mark_and_leaves_both_counters_alone() { + let db = init_mem().await.unwrap(); + let exam = ExamId::from_key("01TESTEXAMDRAFTAAAAAAAAAAA"); + an_exam(&db, &exam, "midterm").await; + db.query("UPDATE $ex SET draft = true") + .bind(("ex", exam.record())) + .await + .unwrap() + .check() + .unwrap(); + + let refused = grade(&db, &exam, 1, 40, "midterm").await; + assert!(matches!(refused, Err(AppError::Conflict(_))), "{refused:?}"); + assert!( + ExamResult::list_for_exam(&exam, &db) + .await + .unwrap() + .is_empty() + ); + assert_eq!(counters(&db, "midterm").await, (0, 0)); } } diff --git a/src/domain/field_update.rs b/src/domain/field_update.rs index 8ccdec0..018658b 100644 --- a/src/domain/field_update.rs +++ b/src/domain/field_update.rs @@ -29,10 +29,22 @@ use crate::domain::cap; use crate::error::AppError; /// The `THROW` markers [`FieldUpdate::refcount`]'s transaction aborts with: the -/// row the reference was to be claimed on is gone, and the row being patched is -/// gone (or its guard bit). +/// row the reference was to be claimed on is gone, the row being patched is +/// gone (or its guard bit), and the link this move started from is no longer +/// the one the handler read. const CLAIM_MARK: &str = "ref_claim_gone"; const ROW_MARK: &str = "ref_row_gone"; +const STALE_MARK: &str = "ref_stale_move"; + +/// `(counter field, link column, expected link, claim, release, refusal)`. +type Refcount = ( + &'static str, + &'static str, + Option, + Option, + Option, + AppError, +); pub struct FieldUpdate { id: RecordId, @@ -43,8 +55,9 @@ pub struct FieldUpdate { ordered: Option<(&'static str, &'static str, AppError)>, /// `(condition, refusal)` for [`FieldUpdate::guard`]. guard: Option<(&'static str, AppError)>, - /// `(counter field, claim, release, refusal)` for [`FieldUpdate::refcount`]. - refcount: Option<(&'static str, Option, Option, AppError)>, + /// `(counter field, link column, expected link, claim, release, refusal)` + /// for [`FieldUpdate::refcount`]. + refcount: Option, } impl FieldUpdate { @@ -60,8 +73,9 @@ impl FieldUpdate { } /// Write `field` only when the request carried it. The bind variable is - /// named after the field, so `id` — and `ref_claim`/`ref_release`, which - /// [`FieldUpdate::refcount`] binds — are the names a caller must not use. + /// named after the field, so `id` — and `ref_claim`/`ref_release`/ + /// `ref_expected`, which [`FieldUpdate::refcount`] binds — are the names a + /// caller must not use. #[must_use] pub fn set(mut self, field: &'static str, value: Option) -> Self { if let Some(value) = value { @@ -122,16 +136,28 @@ impl FieldUpdate { /// /// Only ever called alongside a `.set()` of the very column that carries the /// link, so the empty-request short-circuit below cannot swallow a move. + /// + /// `link` is that column (never `field`: the counter lives on the *other* + /// row, `course_count` on the term against a `term` link) and `expected` is + /// what the handler's snapshot said it held — `None` for a link that was + /// absent. The pair becomes a CAS on the row write, because claim and + /// release are computed from that snapshot: two PATCHes moving the same link + /// A→B both read A, and both would claim B, leaving B counted twice for one + /// link — a count with no link is exactly what makes a term undeletable + /// forever. The loser's row write matches nothing and the whole transaction + /// aborts, so it claims nothing and answers 409. #[must_use] pub fn refcount( mut self, field: &'static str, + link: &'static str, + expected: Option, claim: Option, release: Option, refused: AppError, ) -> Self { if claim.is_some() || release.is_some() { - self.refcount = Some((field, claim, release, refused)); + self.refcount = Some((field, link, expected, claim, release, refused)); } self } @@ -173,7 +199,16 @@ impl FieldUpdate { None => (None, None), }; refused = refused.or(extra_refused); - let conditions: Vec = ordered.into_iter().chain(extra).collect(); + // Armed only for a move that actually shifts a counter, so a plain PATCH + // — and a `term` PATCH that re-stated the link it already had — writes + // the same unguarded `UPDATE` it always did. Probed on the mem engine: + // a bound `None` comes through as `NONE` and `link = NONE` matches a row + // whose option column was never set, while failing one that holds a + // record, so the absent-link shape needs no `??`. + let cas = moved + .as_ref() + .map(|(_, link, ..)| format!("{link} = $ref_expected")); + let conditions: Vec = ordered.into_iter().chain(extra).chain(cas).collect(); let guard = if conditions.is_empty() { String::new() } else { @@ -186,10 +221,7 @@ impl FieldUpdate { // its guard reads, and the loser wrote nothing, so re-sending it is the // recovery — see [`write_with_retry`]. let rows: Vec = match moved { - Some((field, claim, release, ref_refused)) => { - run_with_refcount(db, &sql, self.bindings, field, claim, release, ref_refused) - .await? - } + Some(moved) => run_with_refcount(db, &sql, self.bindings, moved).await?, None => write_with_retry(db, &sql, &self.bindings).await?, }; // No row back means the guard bit (or, in the window after the handler's @@ -212,15 +244,11 @@ impl FieldUpdate { /// Admissible for [`transaction_with_retry`]: every statement is an `UPDATE`, /// an `IF`/`THROW` or a `RETURN`, and none of those can answer "already /// exists" — a lost round writes nothing and re-sending it is the recovery. -#[allow(clippy::too_many_arguments)] async fn run_with_refcount( db: &Database, update: &str, mut bindings: Vec<(String, Value)>, - field: &'static str, - claim: Option, - release: Option, - refused: AppError, + (field, link, expected, claim, release, refused): Refcount, ) -> Result, AppError> { // Parenthesized `??` throughout: `n ?? 0 + 1` parses as `n ?? (0 + 1)`. // Both counter writes commit with the row write or neither does, so their @@ -239,13 +267,25 @@ async fn run_with_refcount( statements.push(format!( "LET $seat = (UPDATE $ref_claim SET {field} = ({field} ?? 0) + 1 RETURN VALUE id)" )); - statements.push(format!("IF array::len($seat) = 0 {{ THROW '{CLAIM_MARK}' }}")); + statements.push(format!( + "IF array::len($seat) = 0 {{ THROW '{CLAIM_MARK}' }}" + )); bindings.push(("ref_claim".into(), claim.into_value())); } + bindings.push(("ref_expected".into(), expected.into_value())); statements.push(format!("LET $row = ({update})")); // Without this the claim would outlive a row write that matched nothing — - // the very leak the transaction exists to close. - statements.push(format!("IF array::len($row) = 0 {{ THROW '{ROW_MARK}' }}")); + // the very leak the transaction exists to close. Nothing was written yet + // either way, so the probe that tells the two empty cases apart is free to + // be another `UPDATE`: it matches only a row that is *there* and whose link + // has moved off what the handler read, which is the CAS having bitten. A + // deleted row and a plain guard refusal both miss it and keep the answer + // they have always got. + statements.push(format!( + "IF array::len($row) = 0 {{ \ + LET $live = (UPDATE $id WHERE {link} != $ref_expected RETURN VALUE id); \ + IF array::len($live) = 0 {{ THROW '{ROW_MARK}' }} ELSE {{ THROW '{STALE_MARK}' }} }}" + )); statements.push("RETURN $row".into()); let sql = format!( "BEGIN TRANSACTION; {}; COMMIT TRANSACTION;", @@ -257,13 +297,21 @@ async fn run_with_refcount( // One counter write in flight at a time, like every other counter write. let _guard = cap::counter_lock().await; let (mut result, mut errors) = - transaction_with_retry(db, &sql, &bindings, &[CLAIM_MARK, ROW_MARK]).await?; + transaction_with_retry(db, &sql, &bindings, &[CLAIM_MARK, ROW_MARK, STALE_MARK]).await?; if errors .values() .any(|error| error.to_string().contains(CLAIM_MARK)) { return Err(refused); } + if errors + .values() + .any(|error| error.to_string().contains(STALE_MARK)) + { + return Err(AppError::Conflict( + "the link this update moves changed since it was read; re-read and retry", + )); + } if errors .values() .any(|error| error.to_string().contains(ROW_MARK)) diff --git a/src/domain/note_file.rs b/src/domain/note_file.rs index 1bcc3f9..259c1a0 100644 --- a/src/domain/note_file.rs +++ b/src/domain/note_file.rs @@ -154,31 +154,32 @@ impl NoteFile { } /// Persist the row assembled by [`Self::new`], refusing once its note - /// already holds [`MAX_NOTE_FILES`]. The slot is taken by [`cap::claim`] on - /// the note row: a `BEGIN…COMMIT` around a count can't enforce the cap - /// (SurrealDB doesn't conflict-check a cross-record count against a - /// concurrent insert) and a process-wide mutex can't either, since it is - /// released around the very round trip the insert races — a conditional - /// single-record write can. + /// already holds [`MAX_NOTE_FILES`]. The slot and the row are taken together + /// by [`cap::claim_and_create`] on the note row: a `BEGIN…COMMIT` around a + /// count can't enforce the cap (SurrealDB doesn't conflict-check a + /// cross-record count against a concurrent insert) and a process-wide mutex + /// can't either, since it is released around the very round trip the insert + /// races — a conditional single-record write can. Claiming in a *separate* + /// query would enforce the cap but leak a slot on a crash between the two. pub async fn insert(self, db: &Database) -> Result { - let note = self.note.record(); - if !cap::claim(¬e, NOTE_FILE_COUNT_FIELD, MAX_NOTE_FILES as i64, db).await? { - return Err(AppError::Conflict( - "the note already holds the maximum of 10 files — delete one first", - )); - } // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - let created: Result, _> = db.create(self.id.record()).content(self).await; - match created { - Ok(Some(created)) => Ok(created), - Ok(None) => { - cap::release(¬e, NOTE_FILE_COUNT_FIELD, db).await?; - Err(AppError::Internal("failed to create note file".into())) - } - Err(err) => { - cap::release(¬e, NOTE_FILE_COUNT_FIELD, db).await?; - Err(err.into()) - } + match cap::claim_and_create( + &self.note.record(), + NOTE_FILE_COUNT_FIELD, + MAX_NOTE_FILES as i64, + &self.id.record(), + &self, + db, + ) + .await? + { + cap::Claimed::Made(created) => Ok(created), + // Also how a missing note reads: no note row means no slot to take. + cap::Claimed::Full => Err(AppError::Conflict( + "the note already holds the maximum of 10 files — delete one first", + )), + // Unreachable: the id is a ULID this call just generated. + cap::Claimed::Duplicate => Err(AppError::Internal("failed to create note file".into())), } } @@ -315,4 +316,60 @@ mod tests { file.delete(&db).await.unwrap(); assert!(listed(¬e_a).await.is_empty()); } + + /// The counter and the rows are written in one transaction, so the stored + /// count must equal the stored rows — after a success *and* after the + /// refusal that fills the cap, which must move neither. + #[tokio::test] + async fn counter_tracks_stored_rows() { + let db = crate::database::init_mem().await.unwrap(); + let note = crate::domain::note::Note::create( + &crate::domain::user::UserId::generate(), + crate::domain::note::NoteTitle::try_new("a").unwrap(), + crate::domain::note::NoteContent::try_new("body").unwrap(), + &db, + ) + .await + .unwrap() + .get_id() + .clone(); + let stored_count = async |note: &NoteId| -> i64 { + db.query("SELECT VALUE file_count FROM $note") + .bind(("note", note.record())) + .await + .unwrap() + .take::>(0) + .unwrap() + .into_iter() + .next() + .unwrap_or(0) + }; + let add = async |note: &NoteId| { + NoteFile::new( + note, + FileName::try_new("plan.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ) + .insert(&db) + .await + }; + + for filled in 1..=MAX_NOTE_FILES { + add(¬e).await.unwrap(); + assert_eq!(stored_count(¬e).await, filled as i64); + assert_eq!( + NoteFile::list_for(¬e, None, 0, &db).await.unwrap().1, + filled as i64 + ); + } + + // At the cap: the refusal writes nothing, counter included. + assert!(matches!(add(¬e).await, Err(AppError::Conflict(_)))); + assert_eq!(stored_count(¬e).await, MAX_NOTE_FILES as i64); + assert_eq!( + NoteFile::list_for(¬e, None, 0, &db).await.unwrap().1, + MAX_NOTE_FILES as i64 + ); + } } diff --git a/src/domain/term.rs b/src/domain/term.rs index ea9afb3..2c9f130 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -63,7 +63,10 @@ pub fn ref_move( match patch { None => (None, None), Some(next) if next.as_ref() == current => (None, None), - Some(next) => (next.as_ref().map(TermId::record), current.map(TermId::record)), + Some(next) => ( + next.as_ref().map(TermId::record), + current.map(TermId::record), + ), } }