From a290672f4c8fce29d6dfc726a5e8160d71bfe29c 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 01:29:50 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=94=A9=20finish=20the=20counter-cl?= =?UTF-8?q?aim=20sweep,=20guard=20every=20carried=20link?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/domain/class_group.rs | 61 ++++ src/domain/course.rs | 61 ++++ src/domain/exam_attempt.rs | 37 ++- src/domain/exam_question.rs | 551 ++++++++++++++++++++++++++++++------ src/domain/field_update.rs | 30 +- src/domain/homework.rs | 357 ++++++++++++++++++++--- src/domain/homework_file.rs | 87 ++++-- src/domain/menu.rs | 246 +++++++++++++--- 8 files changed, 1221 insertions(+), 209 deletions(-) diff --git a/src/domain/class_group.rs b/src/domain/class_group.rs index 0aeaa88..35c3018 100644 --- a/src/domain/class_group.rs +++ b/src/domain/class_group.rs @@ -522,6 +522,67 @@ mod tests { assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); } + /// The class twin of + /// [`crate::domain::course`]'s `a_stale_mover_is_refused_and_claims_nothing` + /// and `a_stale_re_stater_is_refused_and_reverts_nothing`, in one: both + /// PATCHes compute their counter move from the row as *they* read it, so a + /// second one running on the pre-move struct would claim a second seat for + /// one link (the mover) or drag the link back and strand the winner's claim + /// (the re-stater, which shifts no counter at all and so is only ever + /// stopped by a guard armed off the *carried column*). Both must be refused + /// with the counts reading as if they never ran. + #[tokio::test] + async fn a_stale_class_term_write_is_refused_and_moves_no_count() { + let db = crate::database::init_mem().await.unwrap(); + let at = crate::domain::timestamp::Timestamp::from_millis; + let from = a_term(&db).await; + let to = Term::create(TermName::try_new("2027").unwrap(), at(100), at(200), &db) + .await + .unwrap(); + let other = Term::create(TermName::try_new("2028").unwrap(), at(100), at(200), &db) + .await + .unwrap(); + let class = class_on(Some(from.get_id().clone()), &db).await; + let stale = class.clone(); + class + .update(None, None, Some(Some(to.get_id().clone())), &db) + .await + .unwrap(); + + // The mover: its snapshot says `from`, so it would release `from` and + // claim `other` on top of the winner's claim on `to`. + let error = stale + .clone() + .update(None, None, Some(Some(other.get_id().clone())), &db) + .await + .expect_err("a mover that read a link it no longer holds must be refused"); + assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); + // The re-stater: shifts no counter, so only the CAS can stop it. + let error = stale + .clone() + .update(None, None, Some(Some(from.get_id().clone())), &db) + .await + .expect_err("re-stating a link someone else moved must be refused"); + assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); + + let stored = ClassGroup::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"); + assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once"); + assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed"); + + // A genuine no-op re-state still lands and still moves nothing. + let same = stored + .update(None, None, Some(Some(to.get_id().clone())), &db) + .await + .expect("re-stating the link the row really holds is not a conflict"); + assert_eq!(same.get_term(), Some(to.get_id())); + assert_eq!(count_on(to.get_id(), &db).await, 1, "still one seat"); + } + /// [`crate::domain::course::Course::delete`]'s class sweep: deleting a course /// takes its `class_course` attachments with it and gives each class its /// count back, or the classes would be undeletable forever over rows that diff --git a/src/domain/course.rs b/src/domain/course.rs index ed0c9c6..070e8c5 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -759,6 +759,67 @@ mod tests { assert_eq!(stored.get_term(), Some(to.get_id())); } + /// The same race with the counters taken out of it. A PATCH that re-states + /// the term its snapshot showed shifts *nothing* — [`term::ref_move`] hands + /// back no claim and no release — so if the guard were armed off the counter + /// move it would not be armed here at all, and the write would land: the + /// winner's link silently dragged back, its claim stranded on a term nothing + /// points at (undeletable forever) and the reverted-to term linked at a + /// count of zero (deletable while linked). The guard is armed by the request + /// *carrying* the column instead, which is why this is refused. + #[tokio::test] + async fn a_stale_re_stater_is_refused_and_reverts_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let from = a_term("2026", &db).await; + let to = a_term("2027", &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(from.get_id().clone())), + None, + &db, + ) + .await + .expect_err("re-stating a link someone else moved must be refused"); + assert!( + matches!(error, AppError::Conflict(_)), + "a lost CAS is a conflict, not a silent 200: {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, + "the reverted-to term must not end up linked at zero" + ); + assert_eq!( + count_on(to.get_id(), &db).await, + 1, + "…nor the winner's term counted with nothing pointing at it" + ); + + // A *genuine* no-op re-state — nobody moved underneath it — still lands, + // and still moves no counter: the CAS passes trivially. + let fresh = Course::read(stale.get_id(), &db).await.unwrap().unwrap(); + let same = fresh + .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) + .await + .expect("re-stating the link the row really holds is not a conflict"); + assert_eq!(same.get_term(), Some(to.get_id())); + assert_eq!(count_on(from.get_id(), &db).await, 0, "nothing moved"); + assert_eq!(count_on(to.get_id(), &db).await, 1, "…in either direction"); + } + /// 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 diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs index eee7284..ef02000 100644 --- a/src/domain/exam_attempt.rs +++ b/src/domain/exam_attempt.rs @@ -354,6 +354,24 @@ impl ExamAttempt { statements: &str, bindings: Vec<(String, surrealdb::types::Value)>, db: &Database, + ) -> Result { + Self::write_unfrozen_with(exam, statements, bindings, Vec::new(), db).await + } + + /// [`Self::write_unfrozen`] for statements that carry gates of their own: + /// each `(marker, refusal)` names a `THROW` the caller's SQL aborts with and + /// the error it means. The markers are handed to [`transaction_with_retry`] + /// too, so an abort on one is a refusal rather than a round to re-send. + /// + /// The freeze still outranks every one of them: a caller folding a counter + /// claim in here is refused as frozen even when its own gate would also have + /// fired, which is the answer the pre-flight check has always given. + pub(crate) async fn write_unfrozen_with( + exam: &ExamId, + statements: &str, + bindings: Vec<(String, surrealdb::types::Value)>, + refusals: Vec<(&str, AppError)>, + db: &Database, ) -> Result { let sql = format!( "BEGIN TRANSACTION; @@ -364,13 +382,22 @@ impl ExamAttempt { ); let mut bound = vec![("freeze_exam".into(), exam.record().into_value())]; bound.extend(bindings); - let (result, mut errors) = transaction_with_retry(db, &sql, &bound, &[FROZEN_MARK]).await?; - if errors - .values() - .any(|error| error.to_string().contains(FROZEN_MARK)) - { + let mut marks = vec![FROZEN_MARK]; + marks.extend(refusals.iter().map(|(marker, _)| *marker)); + let (result, mut errors) = transaction_with_retry(db, &sql, &bound, &marks).await?; + let thrown = |marker: &str| { + errors + .values() + .any(|error| error.to_string().contains(marker)) + }; + if thrown(FROZEN_MARK) { return Err(frozen_error()); } + for (marker, refusal) in refusals { + if thrown(marker) { + return Err(refusal); + } + } match errors.drain().map(|(_, error)| error).next() { Some(error) => Err(error.into()), None => Ok(result), diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index 4bf304e..177fd40 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -16,6 +16,23 @@ use crate::domain::subject::SubjectId; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_question_kind, validate_question_points, validate_required}; +/// The `THROW` markers the folded counter moves abort with: the subject the +/// reference was to be claimed on is gone, the question being patched is gone, +/// and the subject this move started from is no longer the one the handler +/// read. File-local like every other marker set (`cap`'s, `subject`'s). +const SUBJECT_MARK: &str = "question_subject_gone"; +const ROW_MARK: &str = "question_row_gone"; +const STALE_MARK: &str = "question_stale_move"; + +/// The one answer for a subject that isn't there — a claim missing it and the +/// web layer's pre-flight lookup missing it are the same 400. +fn dead_subject() -> AppError { + AppError::Validation(ValidationError::Invalid { + field: "subject_id", + reason: "subject does not exist", + }) +} + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ExamQuestionId(RecordId); @@ -394,20 +411,7 @@ impl ExamQuestion { from_bank: Option, db: &Database, ) -> Result { - // Take the subject's reference before the row exists, exactly as a cap - // is claimed before the child it caps ([`cap::claim`], here uncapped): - // the subject delete is conditioned on that counter reading zero, so - // the two contend on the subject record and a question can no longer - // land on a subject a concurrent request is deleting. A miss means the - // subject is already gone — the same 400 the web layer's pre-flight - // check answers with. let counted = subject.record(); - if !cap::claim(&counted, SUBJECT_QUESTION_COUNT_FIELD, cap::UNLIMITED, db).await? { - return Err(AppError::Validation(ValidationError::Invalid { - field: "subject_id", - reason: "subject does not exist", - })); - } let question = ExamQuestion { id: ExamQuestionId::generate(), exam: exam.clone(), @@ -421,39 +425,48 @@ impl ExamQuestion { // An insert never banks anything: only a to-bank save writes this. banked_as: None, }; - // The freeze gate rides in the same transaction as the insert: a - // question cannot appear under an exam somebody has already started, - // however the two requests interleave. - let inserted = async { - // Re-sendable despite the `CREATE`: a lost round aborts having - // written nothing and `$id` is a ULID minted once per call, so the - // re-send cannot answer "already exists" (there is no UNIQUE index - // on `exam_question`) — the one thing the retry cannot survive. - let id = question.id.record(); - let mut result = ExamAttempt::write_unfrozen( - exam, - "CREATE $id CONTENT $question;", - vec![ - ("id".into(), id.into_value()), - ("question".into(), question.into_value()), - ], - db, - ) - .await?; - result - .take::>(ExamAttempt::FROZEN_SLOT)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to create exam question".into())) - } - .await; - if inserted.is_err() { - // The row never landed (a frozen exam, most often), so the - // reference it took goes straight back — otherwise the subject - // would be undeletable for a question that does not exist. - cap::release(&counted, SUBJECT_QUESTION_COUNT_FIELD, db).await?; - } - inserted + // The freeze gate and the subject's reference ride in the same + // transaction as the insert: a question cannot appear under an exam + // somebody has already started, and the claim that accounts for it + // cannot outlive a row that never landed. Claiming in its own query + // (with a release on failure, as this did) leaves a window where a + // crash strands the count — and the subject delete is conditioned on + // that count reading zero, so a stranded one makes the subject + // undeletable forever. A missed claim means the subject is already gone + // — the same 400 the web layer's pre-flight check answers with. + // + // Re-sendable despite the `CREATE`: a lost round aborts having written + // nothing and `$id` is a ULID minted once per call, so the re-send + // cannot answer "already exists" (there is no UNIQUE index on + // `exam_question`) — the one thing the retry cannot survive. + let id = question.id.record(); + // One counter write in flight at a time, like every other counter write. + let _guard = cap::counter_lock().await; + let mut result = ExamAttempt::write_unfrozen_with( + exam, + &format!( + "LET $seat = (UPDATE $subject SET {SUBJECT_QUESTION_COUNT_FIELD} = \ + ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); + IF array::len($seat) = 0 {{ THROW '{SUBJECT_MARK}' }}; + CREATE $id CONTENT $question;" + ), + vec![ + ("subject".into(), counted.into_value()), + ("id".into(), id.into_value()), + ("question".into(), question.into_value()), + ], + vec![(SUBJECT_MARK, dead_subject())], + db, + ) + .await?; + // Counted off the statements that actually ran rather than a fixed + // slot, so folding another gate in above can never mis-read the row. + let slot = result.num_statements().saturating_sub(2); + result + .take::>(slot)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to create exam question".into())) } pub async fn read( @@ -494,50 +507,96 @@ impl ExamQuestion { spec: QuestionSpec, db: &Database, ) -> Result { - // A re-tag moves a reference: the new subject is claimed *before* the - // write and the old one released only once it lands, so at no instant - // is either subject under-counted — the direction that would let one be - // deleted while this question still points at it. Both counters staying - // put is the ordinary case (`subject` omitted from the PATCH), and it - // costs nothing. + // A re-tag moves a reference, and the move rides the very transaction + // that moves the link: the old subject's release, the new one's claim + // and the row write commit together or not at all, so no crash can + // strand a count on a subject nothing points at (which would make it + // undeletable forever). + // + // The two are armed on *different* conditions, which is the whole of + // the rule ([`crate::domain::field_update::FieldUpdate::refcount`] states + // it the same way): the counter statements only when the link actually + // changes, but the CAS whenever this write *carries* the link — and it + // always does, because the handler fills an omitted `subject_id` from + // the row it read (`web::exams::questions`), so `subject` is in the + // `SET` of every one of these updates. Arming the CAS on "changed" + // instead would leave the re-stater through: a PATCH carrying the + // subject its own stale snapshot held, sent while a rival's move + // already landed, writes that stale subject straight back over the + // winner — a revert with the counters left pointing at the move. let retag = (subject != self.subject).then(|| (subject.record(), self.subject.record())); - if let Some((next, _)) = &retag - && !cap::claim(next, SUBJECT_QUESTION_COUNT_FIELD, cap::UNLIMITED, db).await? - { - return Err(AppError::Validation(ValidationError::Invalid { - field: "subject_id", - reason: "subject does not exist", - })); - } - let written = async { - let mut result = ExamAttempt::write_unfrozen( - &self.exam, - "UPDATE $id SET subject = $subject, text = $text, points = $points, - kind = $kind, choices = $choices, correct = $correct RETURN AFTER;", - vec![ - ("id".into(), self.id.record().into_value()), - ("subject".into(), subject.record().into_value()), - ("text".into(), text.into_value()), - ("points".into(), points.into_value()), - ("kind".into(), spec.kind.into_value()), - ("choices".into(), spec.choices.into_value()), - ("correct".into(), spec.correct.into_value()), - ], - db, - ) - .await?; - result - .take::>(ExamAttempt::FROZEN_SLOT)? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } - .await; + let write = "UPDATE $id SET subject = $subject, text = $text, points = $points, + kind = $kind, choices = $choices, correct = $correct"; + let mut bindings = vec![ + ("id".into(), self.id.record().into_value()), + ("subject".into(), subject.record().into_value()), + ("text".into(), text.into_value()), + ("points".into(), points.into_value()), + ("kind".into(), spec.kind.into_value()), + ("choices".into(), spec.choices.into_value()), + ("correct".into(), spec.correct.into_value()), + ]; + let mut statements: Vec = Vec::new(); + let mut refusals: Vec<(&str, AppError)> = Vec::new(); if let Some((next, previous)) = &retag { - let give_back = if written.is_ok() { previous } else { next }; - cap::release(give_back, SUBJECT_QUESTION_COUNT_FIELD, db).await?; + statements.push(format!( + "UPDATE $ref_release SET {SUBJECT_QUESTION_COUNT_FIELD} = \ + math::max([({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) - 1, 0])" + )); + statements.push(format!( + "LET $seat = (UPDATE $ref_claim SET {SUBJECT_QUESTION_COUNT_FIELD} = \ + ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id)" + )); + statements.push(format!( + "IF array::len($seat) = 0 {{ THROW '{SUBJECT_MARK}' }}" + )); + bindings.push(("ref_claim".into(), next.clone().into_value())); + bindings.push(("ref_release".into(), previous.clone().into_value())); + refusals.push((SUBJECT_MARK, dead_subject())); } - written + // The CAS: the row write matches only while the question still sits on + // the subject this handler read. A genuine no-op re-state passes it + // trivially (the row holds exactly what is expected); a stale one — + // whether it moves the link or restates it — matches nothing, aborts + // the whole transaction, and so claims nothing and answers 409. + bindings.push(("ref_expected".into(), self.subject.record().into_value())); + statements.push(format!( + "LET $row = ({write} WHERE subject = $ref_expected RETURN AFTER)" + )); + statements.push(format!( + "IF array::len($row) = 0 {{ \ + LET $live = (UPDATE $id WHERE subject != $ref_expected RETURN VALUE id); \ + IF array::len($live) = 0 {{ THROW '{ROW_MARK}' }} \ + ELSE {{ THROW '{STALE_MARK}' }} }}" + )); + statements.push("RETURN $row".into()); + refusals.push(( + STALE_MARK, + AppError::Conflict( + "the subject this question was read on changed since; re-read and retry", + ), + )); + // The row is gone: the same 404 an empty write answers with, so the + // deleted-row case is unchanged. + refusals.push((ROW_MARK, AppError::NotFound)); + let statements = format!("{};", statements.join("; ")); + // One counter write in flight at a time — only a move writes one. + let _guard = match &retag { + Some(_) => Some(cap::counter_lock().await), + None => None, + }; + let mut result = + ExamAttempt::write_unfrozen_with(&self.exam, &statements, bindings, refusals, db) + .await?; + // Read off the trailing `RETURN` rather than a fixed slot: a re-tag + // arms three more statements than a plain PATCH does (and an `IF` + // block is one slot whether or not it is taken). + let slot = result.num_statements().saturating_sub(2); + result + .take::>(slot)? + .into_iter() + .next() + .ok_or(AppError::NotFound) } /// Point the question's `banked_as` at the bank template it was just saved @@ -961,6 +1020,324 @@ mod tests { } } + /// The subject reference counter, which is what the subject's delete guard + /// reads: every one of these asserts *stored* state, because a claim that + /// outlives the row it accounts for makes its subject undeletable forever. + mod counters { + use super::*; + use crate::database::init_mem; + use crate::domain::course::CourseId; + use crate::domain::exam::{ + Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, + }; + use crate::domain::settings::Settings; + use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; + use crate::domain::user::UserId; + + async fn an_exam(db: &Database) -> Exam { + let kinds = Settings::defaults().get_exam_kinds().to_vec(); + Exam::create( + &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), + &CourseId::from_key("01TESTCOURSEAAAAAAAAAAAAAA"), + ExamTitle::try_new("practice").unwrap(), + ExamDescription::try_new("").unwrap(), + ExamKind::try_new("quiz", &kinds).unwrap(), + ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None) + .unwrap(), + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + false, + db, + ) + .await + .unwrap() + } + + async fn a_subject(db: &Database) -> Subject { + Subject::create( + &CourseId::generate(), + SubjectName::try_new("topic").unwrap(), + SubjectDescription::try_new("").unwrap(), + db, + ) + .await + .unwrap() + } + + /// The editable payload, fresh per call (each one is consumed). + fn body() -> (QuestionText, QuestionPoints, QuestionSpec) { + ( + QuestionText::try_new("3 + 3?").unwrap(), + QuestionPoints::try_new(5).unwrap(), + QuestionSpec::try_new(kind("text"), None, None, &[]).unwrap(), + ) + } + + async fn a_question(exam: &Exam, on: &SubjectId, db: &Database) -> ExamQuestion { + let (text, points, spec) = body(); + ExamQuestion::create(exam.get_id(), on.clone(), text, points, spec, db) + .await + .unwrap() + } + + async fn moved( + question: ExamQuestion, + to: &SubjectId, + db: &Database, + ) -> Result { + let (text, points, spec) = body(); + question.update(to.clone(), text, points, spec, db).await + } + + /// The stored `exam_question_count` on one subject, absent = zero. + async fn count_on(subject: &SubjectId, db: &Database) -> i64 { + let mut result = db + .query(format!( + "SELECT VALUE ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) FROM $sub" + )) + .bind(("sub", subject.record())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap_or(0) + } + + async fn rows(sql: &str, db: &Database) -> usize { + let mut result = db.query(sql).await.unwrap().check().unwrap(); + result.take::>(0).unwrap().len() + } + + /// The freeze outranks the counter move, on both paths — and because + /// the claim now rides the refused transaction, "outranks" has to mean + /// the counters read as if nothing ran. + #[tokio::test] + async fn a_frozen_exam_leaves_the_subject_counters_untouched() { + let db = init_mem().await.unwrap(); + let exam = an_exam(&db).await; + let (from, to) = (a_subject(&db).await, a_subject(&db).await); + let (from, to) = (from.get_id().clone(), to.get_id().clone()); + let question = a_question(&exam, &from, &db).await; + assert_eq!(count_on(&from, &db).await, 1); + + ExamAttempt::start(&exam, &UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"), &db) + .await + .unwrap(); + + let (text, points, spec) = body(); + let error = ExamQuestion::create(exam.get_id(), to.clone(), text, points, spec, &db) + .await + .expect_err("a started exam takes no new questions"); + assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); + assert_eq!(count_on(&to, &db).await, 0, "the refused claim rolled back"); + + let error = moved(question, &to, &db) + .await + .expect_err("a started exam takes no re-tag either"); + assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); + assert_eq!(count_on(&from, &db).await, 1, "the release rolled back too"); + assert_eq!(count_on(&to, &db).await, 0); + } + + /// The create-path invariant: a refused create writes neither the row + /// nor a count — least of all on a subject it would have to invent. + #[tokio::test] + async fn a_create_on_a_dead_subject_writes_neither_row_nor_count() { + let db = init_mem().await.unwrap(); + let exam = an_exam(&db).await; + let subject = a_subject(&db).await; + let id = subject.get_id().clone(); + subject.delete(&db).await.unwrap(); + + let (text, points, spec) = body(); + let error = ExamQuestion::create(exam.get_id(), id, text, points, spec, &db) + .await + .expect_err("a subject that is gone must not be taggable"); + assert!(error.to_string().contains("subject does not exist")); + assert_eq!( + rows("SELECT VALUE id FROM exam_question", &db).await, + 0, + "a refused create may write no row" + ); + assert_eq!( + rows("SELECT VALUE id FROM subject", &db).await, + 0, + "…and least of all a count on a subject it just brought back" + ); + } + + #[tokio::test] + async fn a_subject_move_moves_the_count() { + let db = init_mem().await.unwrap(); + let exam = an_exam(&db).await; + let (from, to) = (a_subject(&db).await, a_subject(&db).await); + let (from, to) = (from.get_id().clone(), to.get_id().clone()); + let question = a_question(&exam, &from, &db).await; + + let after = moved(question, &to, &db).await.unwrap(); + assert_eq!(after.get_subject(), &to); + assert_eq!(count_on(&from, &db).await, 0, "the old subject is free"); + assert_eq!(count_on(&to, &db).await, 1, "the new one is not"); + } + + #[tokio::test] + async fn a_move_to_a_dead_subject_leaves_everything_untouched() { + let db = init_mem().await.unwrap(); + let exam = an_exam(&db).await; + let from = a_subject(&db).await.get_id().clone(); + let dead = a_subject(&db).await; + let gone = dead.get_id().clone(); + dead.delete(&db).await.unwrap(); + let question = a_question(&exam, &from, &db).await; + + let error = moved(question.clone(), &gone, &db) + .await + .expect_err("a subject that is gone must not be taggable"); + assert!(error.to_string().contains("subject does not exist")); + let stored = ExamQuestion::read(question.get_id(), &db) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.get_subject(), &from, "the link never moved"); + assert_eq!( + count_on(&from, &db).await, + 1, + "the release rolled back with the claim" + ); + assert_eq!(rows("SELECT VALUE id FROM subject", &db).await, 1); + } + + /// The double-claim guard. Both movers compute their claim and release + /// from the row as *they* read it, so two PATCHes re-tagging the same + /// question both release the old subject and both claim their own + /// 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: it must be refused outright, and the + /// counts must read as if it never ran. + /// + /// Drop `AND subject = $ref_expected` from the row write in + /// [`ExamQuestion::update`] and this goes red on the very first + /// assertion — the stale mover is happily applied. + #[tokio::test] + async fn a_stale_mover_is_refused_and_claims_nothing() { + let db = init_mem().await.unwrap(); + let exam = an_exam(&db).await; + let from = a_subject(&db).await.get_id().clone(); + let to = a_subject(&db).await.get_id().clone(); + let other = a_subject(&db).await.get_id().clone(); + let question = a_question(&exam, &from, &db).await; + let stale = question.clone(); + + moved(question, &to, &db).await.unwrap(); + let error = moved(stale.clone(), &other, &db) + .await + .expect_err("a mover that read a subject 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 = ExamQuestion::read(stale.get_id(), &db) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.get_subject(), &to, "the winner's link"); + assert_eq!(count_on(&from, &db).await, 0, "released once, not twice"); + assert_eq!(count_on(&to, &db).await, 1, "claimed once"); + assert_eq!(count_on(&other, &db).await, 0, "never claimed"); + } + + /// The other half of the same race, and the one arming on "the subject + /// changed" lets through: this PATCH carries the subject its snapshot + /// already held, so it moves no counter — but a rival's move landed + /// first, and writing that stale subject back would revert the winner + /// while both counters still describe the move. The handler fills an + /// omitted `subject_id` from the row it read, so this is also every + /// text-only PATCH sent from a stale snapshot. + /// + /// Arm the CAS on the re-tag instead of on the write and this goes red + /// on the first assertion — the re-state lands 200. + #[tokio::test] + async fn a_stale_re_stater_is_refused_and_reverts_nothing() { + let db = init_mem().await.unwrap(); + let exam = an_exam(&db).await; + let from = a_subject(&db).await.get_id().clone(); + let to = a_subject(&db).await.get_id().clone(); + let question = a_question(&exam, &from, &db).await; + let stale = question.clone(); + + moved(question, &to, &db).await.unwrap(); + let error = moved(stale.clone(), &from, &db) + .await + .expect_err("re-stating a subject a rival moved off must be refused"); + assert!( + matches!(error, AppError::Conflict(_)), + "a lost CAS is a conflict, not a silent revert: {error:?}" + ); + + let stored = ExamQuestion::read(stale.get_id(), &db) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.get_subject(), &to, "the winner's link stands"); + assert_eq!( + count_on(&from, &db).await, + 0, + "released once, and stayed so" + ); + assert_eq!(count_on(&to, &db).await, 1, "claimed once, and stayed so"); + } + + /// …and the price of arming the CAS on every write is nothing: a PATCH + /// re-stating the subject the row really holds passes it trivially. + #[tokio::test] + async fn a_no_op_re_state_still_lands() { + let db = init_mem().await.unwrap(); + let exam = an_exam(&db).await; + let on = a_subject(&db).await.get_id().clone(); + let question = a_question(&exam, &on, &db).await; + + let (_, points, spec) = body(); + let after = question + .update( + on.clone(), + QuestionText::try_new("4 + 4?").unwrap(), + points, + spec, + &db, + ) + .await + .expect("re-stating the subject the row holds is not a conflict"); + assert_eq!(after.get_text().as_str(), "4 + 4?"); + assert_eq!(after.get_subject(), &on); + assert_eq!(count_on(&on, &db).await, 1, "no counter moved"); + } + + /// A re-tag of a question whose row is gone is still the 404 it was, + /// not the stale-mover 409 — the two empty-`$row` cases stay apart. + #[tokio::test] + async fn a_move_of_a_deleted_question_is_still_a_404() { + let db = init_mem().await.unwrap(); + let exam = an_exam(&db).await; + let from = a_subject(&db).await.get_id().clone(); + let to = a_subject(&db).await.get_id().clone(); + let question = a_question(&exam, &from, &db).await; + question.clone().delete(&db).await.unwrap(); + + let error = moved(question, &to, &db) + .await + .expect_err("a deleted question cannot be re-tagged"); + assert!(matches!(error, AppError::NotFound), "{error:?}"); + assert_eq!(count_on(&to, &db).await, 0, "and nothing was claimed"); + } + } + #[tokio::test] async fn spec_rejects_blank_or_oversized_choices() { let with = |text: String| { diff --git a/src/domain/field_update.rs b/src/domain/field_update.rs index 018658b..f464819 100644 --- a/src/domain/field_update.rs +++ b/src/domain/field_update.rs @@ -146,6 +146,16 @@ impl FieldUpdate { /// 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. + /// + /// **Carrying the link and shifting a counter are separate questions**, and + /// the CAS keys off the first one — `run` arms it for any request that + /// `.set()` this column, `claim`/`release` both `None` included. A PATCH + /// *re-stating* the link its snapshot showed shifts no counter, but it is + /// the same stale read: run it against a row someone else has since moved + /// and the unguarded write silently drags the link back, stranding the + /// winner's claim on a term nothing points at (undeletable forever) and + /// leaving the reverted-to term linked at zero (deletable while linked). + /// Gating the CAS on the counters is what let that through. #[must_use] pub fn refcount( mut self, @@ -156,16 +166,19 @@ impl FieldUpdate { release: Option, refused: AppError, ) -> Self { - if claim.is_some() || release.is_some() { - self.refcount = Some((field, link, expected, claim, release, refused)); - } + self.refcount = Some((field, link, expected, claim, release, refused)); self } /// Run the update and return the stored row. An empty request writes /// nothing at all and reads the row back unchanged. pub async fn run(mut self, db: &Database) -> Result { + // Armed by the *request*, not by the counters: a PATCH that carries the + // link column gets the CAS even when it re-states the value it read and + // so shifts nothing. Decided here rather than in `refcount` so the + // builder's call order cannot silently disarm it — `run` is always last. let moved = self.refcount.take(); + let moved = moved.filter(|(_, link, ..)| self.is_set(link)); if self.assignments.is_empty() { let row: Option = db.select(self.id).await?; return row.ok_or(AppError::NotFound); @@ -199,9 +212,9 @@ impl FieldUpdate { None => (None, None), }; refused = refused.or(extra_refused); - // 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 PATCH that does not carry the link at all writes the same unguarded + // `UPDATE` it always did — it re-states nothing and races nobody. 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 `??`. @@ -241,6 +254,11 @@ impl FieldUpdate { /// means the row write matched nothing, exactly as [`write_with_retry`] would /// have reported it, so the caller's refusal is unchanged. /// +/// A re-statement shifts no counter, so `claim` and `release` are both `None` +/// and the transaction is the CAS'd row write and its split alone — still a +/// transaction, because the split's probe must see the same snapshot the write +/// was refused against. +/// /// 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. diff --git a/src/domain/homework.rs b/src/domain/homework.rs index 136b759..c78b8e1 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -27,6 +27,17 @@ use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_optional, validate_required}; +/// The answer a link to a subject that is not there gets, on create and on +/// re-tag alike — both claims are conditional writes on the subject row, so a +/// subject a delete already removed matches nothing and the caller says exactly +/// what the web layer's pre-flight lookup would have. +fn subject_gone() -> AppError { + AppError::Validation(ValidationError::Invalid { + field: "subject_id", + reason: "subject does not exist", + }) +} + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct HomeworkId(RecordId); @@ -160,20 +171,16 @@ impl Homework { created_by: &UserId, db: &Database, ) -> Result { - // Take the subject's reference before the row exists — the exam - // question's twin ([`crate::domain::exam_question::ExamQuestion`]): the - // subject delete is refused while this counter is non-zero, so the - // create and the delete contend on the subject record rather than on a - // cross-table count neither of them sees the other move. A miss means the - // subject is already gone, which is the 400 the web layer's pre-flight - // check answers with. + // The subject's reference is taken in the very transaction that writes + // the row — the exam question's twin + // ([`crate::domain::exam_question::ExamQuestion`]): the subject delete + // is refused while this counter is non-zero, so the create and the + // delete contend on the subject record rather than on a cross-table + // count neither of them sees the other move, and a crash can no longer + // strand a claim that would make the subject undeletable forever. A + // refused claim means the subject is already gone, which is the 400 the + // web layer's pre-flight check answers with. let counted = subject.record(); - if !cap::claim(&counted, SUBJECT_HOMEWORK_COUNT_FIELD, cap::UNLIMITED, db).await? { - return Err(AppError::Validation(ValidationError::Invalid { - field: "subject_id", - reason: "subject does not exist", - })); - } let homework = Homework { id: HomeworkId::generate(), course: course.clone(), @@ -185,19 +192,20 @@ impl Homework { created_by: created_by.clone(), created_at: Timestamp::now(), }; - let created: Result, AppError> = db - .create(homework.id.record()) - .content(homework) - .await - .map_err(AppError::from); - match created { - Ok(Some(homework)) => Ok(homework), - other => { - // Nothing landed, so the reference goes straight back. - cap::release(&counted, SUBJECT_HOMEWORK_COUNT_FIELD, db).await?; - other?; - Err(AppError::Internal("failed to create homework".into())) - } + let id = homework.id.record(); + match cap::claim_and_create( + &counted, + SUBJECT_HOMEWORK_COUNT_FIELD, + cap::UNLIMITED, + &id, + &homework, + db, + ) + .await? + { + cap::Claimed::Made(created) => Ok(created), + cap::Claimed::Full => Err(subject_gone()), + cap::Claimed::Duplicate => Err(AppError::Internal("failed to create homework".into())), } } @@ -296,35 +304,39 @@ impl Homework { ) -> Result { let assigned = assigned .map(|subset| subset.map(|users| users.iter().map(UserId::record).collect::>())); - // A re-tag moves a reference: claim the new subject before the write, - // release the old only after it lands, so neither is ever - // under-counted (the direction that would let a subject this homework - // points at be deleted). Same shape as the exam question's re-tag. - let retag = subject + // A re-tag moves a reference: the new subject's claim and the old one's + // release ride the same transaction as the link write, so no crash can + // leave a count without its link (the subject would be undeletable + // forever) or a link without its count. `subject` is required, so the + // snapshot's value is always the CAS expectation — two PATCHes moving + // the same homework off the same subject would otherwise both claim + // their target, and the loser is refused with a 409 instead. The + // `.refcount` call is unconditional: the CAS is armed by the request + // *carrying* `subject_id`, not by a counter moving, so a PATCH that + // re-states the tag its snapshot showed — shifting no counter at all — + // is still refused when a rival moved the tag in between. A PATCH that + // carried no `subject_id` arms nothing and writes what it always did. + let (claim, release) = subject .as_ref() .filter(|next| **next != self.subject) - .map(|next| (next.record(), self.subject.record())); - if let Some((next, _)) = &retag - && !cap::claim(next, SUBJECT_HOMEWORK_COUNT_FIELD, cap::UNLIMITED, db).await? - { - return Err(AppError::Validation(ValidationError::Invalid { - field: "subject_id", - reason: "subject does not exist", - })); - } - let written = FieldUpdate::new(self.id.record()) + .map(|next| (next.record(), self.subject.record())) + .unzip(); + FieldUpdate::new(self.id.record()) .set("subject", subject.map(|subject| subject.record())) .set("title", title) .set("description", description) .set("due_at", due_at) .set("assigned", assigned) + .refcount( + SUBJECT_HOMEWORK_COUNT_FIELD, + "subject", + Some(self.subject.record()), + claim, + release, + subject_gone(), + ) .run::(db) - .await; - if let Some((next, previous)) = &retag { - let give_back = if written.is_ok() { previous } else { next }; - cap::release(give_back, SUBJECT_HOMEWORK_COUNT_FIELD, db).await?; - } - written + .await } /// Delete the homework and cascade its submissions, their files, and its @@ -399,4 +411,255 @@ mod tests { assert!(with(Some(vec![a.clone()])).student_sees(&a)); assert!(!with(Some(vec![a.clone()])).student_sees(&b)); } + + use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; + + async fn a_subject(name: &str, db: &Database) -> Subject { + Subject::create( + &CourseId::from_key("course"), + SubjectName::try_new(name).unwrap(), + SubjectDescription::try_new("").unwrap(), + db, + ) + .await + .unwrap() + } + + async fn homework_on(subject: &SubjectId, db: &Database) -> Homework { + Homework::create( + &CourseId::from_key("course"), + subject, + HomeworkTitle::try_new("essay").unwrap(), + None, + Timestamp::from_millis(1), + None, + &UserId::from_key("teacher"), + db, + ) + .await + .unwrap() + } + + /// The stored `homework_count` on one subject, absent counting as zero. + async fn count_on(subject: &SubjectId, db: &Database) -> i64 { + let mut result = db + .query(format!( + "SELECT VALUE ({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) FROM $sub" + )) + .bind(("sub", subject.record())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap_or(0) + } + + /// How many rows `sql` selects ids for. + async fn rows(sql: &str, db: &Database) -> usize { + let mut result = db.query(sql).await.unwrap().check().unwrap(); + result.take::>(0).unwrap().len() + } + + /// The invariant on the create path: the claim and the row it accounts for + /// commit together or not at all. A refused create leaves *neither* — no + /// homework row, and no count stranded on a subject (the subject's delete + /// guard reads that count, so a stray one makes it undeletable forever). + #[tokio::test] + async fn a_refused_create_writes_neither_row_nor_count() { + let db = crate::database::init_mem().await.unwrap(); + let subject = a_subject("algebra", &db).await; + let id = subject.get_id().clone(); + subject.delete(&db).await.unwrap(); + + let error = Homework::create( + &CourseId::from_key("course"), + &id, + HomeworkTitle::try_new("essay").unwrap(), + None, + Timestamp::from_millis(1), + None, + &UserId::from_key("teacher"), + &db, + ) + .await + .expect_err("a subject that is gone must not be taggable"); + assert!(error.to_string().contains("subject does not exist")); + assert_eq!( + rows("SELECT VALUE id FROM homework", &db).await, + 0, + "a refused create may write no row" + ); + assert_eq!( + rows("SELECT VALUE id FROM subject", &db).await, + 0, + "…and least of all a count on a subject it just brought back" + ); + } + + /// The invariant on the PATCH path: a re-tag carries the new subject's + /// claim and the old one's release with the link itself. + #[tokio::test] + async fn a_subject_move_moves_the_count() { + let db = crate::database::init_mem().await.unwrap(); + let from = a_subject("algebra", &db).await; + let to = a_subject("geometry", &db).await; + let homework = homework_on(from.get_id(), &db).await; + assert_eq!(count_on(from.get_id(), &db).await, 1); + + let moved = homework + .update(Some(to.get_id().clone()), None, None, None, None, &db) + .await + .unwrap(); + assert_eq!(moved.get_subject(), to.get_id()); + assert_eq!( + count_on(from.get_id(), &db).await, + 0, + "the old subject is free" + ); + assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); + assert!(from.delete(&db).await.is_ok(), "no reference left"); + assert!( + to.delete(&db).await.is_err(), + "the reference moved here refuses the delete" + ); + } + + /// The claim throws inside the same transaction as the link write, so a + /// move onto a subject that is gone rolls the release back with it: the row + /// keeps its tag and both counters read as if nothing ran. + #[tokio::test] + async fn a_move_to_a_dead_subject_leaves_everything_untouched() { + let db = crate::database::init_mem().await.unwrap(); + let from = a_subject("algebra", &db).await; + let dead = a_subject("geometry", &db).await; + let gone = dead.get_id().clone(); + dead.delete(&db).await.unwrap(); + let homework = homework_on(from.get_id(), &db).await; + + let error = homework + .clone() + .update(Some(gone.clone()), None, None, None, None, &db) + .await + .expect_err("a subject that is gone must not be taggable"); + assert!(error.to_string().contains("subject does not exist")); + let stored = Homework::read(homework.get_id(), &db) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.get_subject(), from.get_id(), "the tag never moved"); + assert_eq!( + count_on(from.get_id(), &db).await, + 1, + "the release rolled back with the claim" + ); + assert_eq!( + rows("SELECT VALUE id FROM subject", &db).await, + 1, + "the dead subject was not brought back by a count" + ); + assert_eq!(count_on(&gone, &db).await, 0); + } + + /// The double-claim guard. Both movers compute their claim and release from + /// the row as *they* read it, so two PATCHes re-tagging the same homework + /// off the same subject 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_subject("algebra", &db).await; + let to = a_subject("geometry", &db).await; + let other = a_subject("calculus", &db).await; + let homework = homework_on(from.get_id(), &db).await; + let stale = homework.clone(); + homework + .update(Some(to.get_id().clone()), None, None, None, None, &db) + .await + .unwrap(); + + let error = stale + .clone() + .update(Some(other.get_id().clone()), None, None, None, None, &db) + .await + .expect_err("a mover that read a tag 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 = Homework::read(stale.get_id(), &db).await.unwrap().unwrap(); + assert_eq!(stored.get_subject(), to.get_id(), "the winner's tag"); + 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"); + } + + /// The same race with the counters taken out of it. A PATCH that re-states + /// the subject its snapshot showed shifts *nothing* — no claim and no + /// release — so if the guard were armed off the counter move it would not be + /// armed here at all, and the write would land: the winner's tag silently + /// dragged back, its claim stranded on a subject nothing points at + /// (undeletable forever) and the reverted-to subject tagged at a count of + /// zero (deletable while tagged). The guard is armed by the request + /// *carrying* the column instead, which is why this is refused. + #[tokio::test] + async fn a_stale_re_stater_is_refused_and_reverts_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let from = a_subject("algebra", &db).await; + let to = a_subject("geometry", &db).await; + let homework = homework_on(from.get_id(), &db).await; + let stale = homework.clone(); + homework + .update(Some(to.get_id().clone()), None, None, None, None, &db) + .await + .unwrap(); + + let error = stale + .clone() + .update(Some(from.get_id().clone()), None, None, None, None, &db) + .await + .expect_err("re-stating a tag someone else moved must be refused"); + assert!( + matches!(error, AppError::Conflict(_)), + "a lost CAS is a conflict, not a silent 200: {error:?}" + ); + let stored = Homework::read(stale.get_id(), &db).await.unwrap().unwrap(); + assert_eq!(stored.get_subject(), to.get_id(), "the winner's tag"); + assert_eq!( + count_on(from.get_id(), &db).await, + 0, + "the reverted-to subject must not end up tagged at zero" + ); + assert_eq!( + count_on(to.get_id(), &db).await, + 1, + "…nor the winner's subject counted with nothing pointing at it" + ); + + // A *genuine* no-op re-state — nobody moved underneath it — still lands, + // and still moves no counter: the CAS passes trivially. + let fresh = Homework::read(stale.get_id(), &db).await.unwrap().unwrap(); + let same = fresh + .update(Some(to.get_id().clone()), None, None, None, None, &db) + .await + .expect("re-stating the tag actually held is not a race"); + assert_eq!(same.get_subject(), to.get_id()); + assert_eq!( + count_on(from.get_id(), &db).await, + 0, + "still no counter move" + ); + assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once, still"); + } } diff --git a/src/domain/homework_file.rs b/src/domain/homework_file.rs index ce1db2c..bdaff07 100644 --- a/src/domain/homework_file.rs +++ b/src/domain/homework_file.rs @@ -124,42 +124,38 @@ impl HomeworkFile { /// Persist the row assembled by [`Self::new`], refusing once its submission /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`) /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own - /// wording). Both are decided by one [`cap::claim_when`] on the submission - /// row — a conditional single-record write, the only guard that holds when - /// two uploads race, the same story as - /// `NoteFile::insert`. Which of the two conditions failed is read back - /// afterwards, off the losing path only, and only to pick the message. + /// wording). Both are decided by one [`cap::claim_when_and_create`] on the + /// submission row — the seat and the file row commit together, so a crash + /// between them can no longer leave a slot claimed by a file that does not + /// exist, and a losing upload never has to be un-counted. Which of the two + /// conditions refused it is read back afterwards, off the losing path only, + /// and only to pick the message: `Claimed::Full` says "full *or* graded *or* + /// the submission is gone". pub async fn insert(self, db: &Database) -> Result, AppError> { - let submission = self.submission.record(); - if !cap::claim_when( - &submission, + // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber + match cap::claim_when_and_create( + &self.submission.record(), SUBMISSION_FILE_COUNT_FIELD, MAX_HOMEWORK_FILES_PER_SUBMISSION as i64, SUBMISSION_OPEN_GUARD, + &self.id.record(), + &self, db, ) .await? { - if HomeworkSubmission::is_graded(&self.submission, db).await? { - return Ok(None); - } - return Err(AppError::Conflict( - "the submission 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(Some(created)), - Ok(None) => { - cap::release(&submission, SUBMISSION_FILE_COUNT_FIELD, db).await?; - Err(AppError::Internal("failed to create homework file".into())) - } - Err(err) => { - cap::release(&submission, SUBMISSION_FILE_COUNT_FIELD, db).await?; - Err(err.into()) + cap::Claimed::Made(created) => Ok(Some(created)), + cap::Claimed::Full => { + if HomeworkSubmission::is_graded(&self.submission, db).await? { + return Ok(None); + } + Err(AppError::Conflict( + "the submission already holds the maximum of 10 files — delete one first", + )) } + // The id is a fresh ULID minted by `new`, so a row already holding it + // is a collision, not a re-upload. + cap::Claimed::Duplicate => Err(AppError::Internal("homework file id collided".into())), } } @@ -317,6 +313,20 @@ mod tests { ) } + /// The counter as *stored* — the only witness that the seat and the row + /// moved together, since every other read counts the rows themselves. + async fn stored_count(submission: &HomeworkSubmissionId, db: &Database) -> i64 { + db.query("SELECT VALUE file_count FROM $sub") + .bind(("sub", submission.record())) + .await + .unwrap() + .take::>(0) + .unwrap() + .into_iter() + .next() + .unwrap_or(0) + } + #[tokio::test] async fn rows_scope_to_their_submission_gc_and_cap() { let db = crate::database::init_mem().await.unwrap(); @@ -353,6 +363,11 @@ mod tests { .unwrap(), 1 ); + assert_eq!( + stored_count(&sub_a, &db).await, + 1, + "the seat rode with the row" + ); // The grader's download scoping: found under its own homework, invisible // under another — so a teacher can't read it by naming a homework they @@ -388,6 +403,17 @@ mod tests { a_file(&sub_a).insert(&db).await, Err(AppError::Conflict(_)) )); + // The refusal wrote nothing at all: neither a row nor a seat. + assert_eq!( + HomeworkFile::count_for_submission(&sub_a, &db) + .await + .unwrap() as i64, + stored_count(&sub_a, &db).await, + ); + assert_eq!( + stored_count(&sub_a, &db).await, + MAX_HOMEWORK_FILES_PER_SUBMISSION as i64 + ); } /// A graded submission takes no more files and gives none up — decided by @@ -395,8 +421,8 @@ mod tests { /// `homework_result` read stands between the check and the write. /// /// Bite check: drop [`SUBMISSION_OPEN_GUARD`] from `insert`'s - /// [`cap::claim_when`] and the add below lands; drop it from `delete`'s gate - /// and the delete below succeeds. + /// [`cap::claim_when_and_create`] and the add below lands; drop it from + /// `delete`'s gate and the delete below succeeds. #[tokio::test] async fn a_grade_freezes_the_files_too() { use crate::domain::homework_result::{HomeworkResult, HomeworkStatus}; @@ -431,6 +457,9 @@ mod tests { 1, "the graded submission keeps exactly the files it was graded on" ); + // Refused by the *guard*, not the cap (nine seats free) — and still no + // seat moved, so the counter matches the rows. + assert_eq!(stored_count(&sub, &db).await, 1); // The refused add took no slot either, so un-grading gives back a // submission with room, not one that silently lost nine. HomeworkResult::remove(&homework, &user, &db).await.unwrap(); diff --git a/src/domain/menu.rs b/src/domain/menu.rs index e98fd15..f63691a 100644 --- a/src/domain/menu.rs +++ b/src/domain/menu.rs @@ -14,9 +14,10 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use tokio::sync::Mutex; use crate::constant::{ - MAX_MENU_CAPACITY, MENU_SEAT_COUNT_FIELD, MENU_TABLE, MENU_VERSION_FIELD, SLOT_REF_TABLE, + MAX_MENU_CAPACITY, MENU_SEAT_COUNT_FIELD, MENU_TABLE, MENU_VERSION_FIELD, REF_COUNT_FIELD, + SLOT_REF_TABLE, }; -use crate::database::{Database, lost_the_race}; +use crate::database::{Database, transaction_with_retry}; use crate::domain::cap; use crate::domain::field_update::FieldUpdate; use crate::domain::menu_dish::MenuDish; @@ -228,15 +229,11 @@ impl Menu { } // The menu takes a reference on its slot, which is what stops the slot // being dropped from the settings while this menu (whose slot is only - // snapshotted text) still points at it. Claimed before the write and - // given back if the write does not land, exactly like a seat. + // snapshotted text) still points at it. Claimed *inside* the write's own + // transaction: a claim of its own could land and the row then fail to, + // leaving the slot counted by a menu that does not exist — a slot + // nobody can ever retire, and no crash window is small enough for that. let counter = slot_ref(slot.as_str()); - if !cap::claim_ref(&counter, 1, db).await? { - return Err(AppError::ConflictOwned(format!( - "the '{}' meal slot has been removed from the school's settings", - slot.as_str() - ))); - } let menu = Menu { id: MenuId::for_slot(&date, &slot), date, @@ -246,19 +243,14 @@ impl Menu { created_by: created_by.clone(), created_at: Timestamp::now(), }; - match db.create(menu.id.record()).content(menu).await { - Ok(Some(created)) => Ok(created), - Ok(None) => { - cap::release_ref(&counter, 1, db).await?; - Err(AppError::Internal("failed to publish the menu".into())) - } - Err(err) => { - cap::release_ref(&counter, 1, db).await?; - match lost_the_race(&err) { - true => Err(taken), - false => Err(err.into()), - } - } + let id = menu.id.record(); + match cap::claim_ref_and_create(&counter, 1, &id, &menu, db).await? { + cap::ClaimedRef::Made(created) => Ok(created), + cap::ClaimedRef::Duplicate => Err(taken), + cap::ClaimedRef::Retired => Err(AppError::ConflictOwned(format!( + "the '{}' meal slot has been removed from the school's settings", + menu.slot.as_str() + ))), } } @@ -332,17 +324,44 @@ impl Menu { /// (and finds no menu). A read-then-delete pair had a window where both /// happened — a paid seat on a menu that no longer exists. /// + /// The slot gets its reference back in that same transaction — a slot no + /// menu is published for any more may leave the settings again, and the + /// `FOR` runs only over a row the guard actually took. Released afterwards + /// in a query of its own, a crash between the two left the slot counted by + /// a menu that no longer exists: a slot nobody can retire. + /// /// The dishes go *after* the row: their cascade must not run for a delete /// the counter refused. pub async fn delete(self, db: &Database) -> Result { - let mut result = db - .query(format!( - "DELETE $id WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE" - )) - .bind(("id", self.id.record())) - .await? - .check()?; - let Some(deleted) = result.take::>(0)?.into_iter().next() else { + let sql = format!( + "BEGIN TRANSACTION; + LET $gone = (DELETE $id WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); + FOR $row IN ($gone ?? []) {{ + UPSERT $counter SET {REF_COUNT_FIELD} = \ + math::max([({REF_COUNT_FIELD} ?? 0) - 1, 0]); + }}; + RETURN $gone; + COMMIT TRANSACTION;" + ); + // `slot` is a `READONLY` column, so this counter is the one the deleted + // row carries. Nothing here can answer "already exists" — the `UPSERT` + // is keyed by a slot name on a table with no `UNIQUE` index, so it + // resolves onto the row it names ([`transaction_with_retry`]). + let (mut result, mut errors) = transaction_with_retry( + db, + &sql, + &[ + ("id".into(), self.id.record().into_value()), + ("counter".into(), slot_ref(self.slot.as_str()).into_value()), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // BEGIN, the LET and the FOR take a slot each. + let Some(deleted) = result.take::>(3)?.into_iter().next() else { // Nothing back: either seats are held, or the menu is already gone. return Err(match Self::read(&self.id, db).await? { Some(_) => AppError::Conflict("the menu still has live bookings"), @@ -350,10 +369,6 @@ impl Menu { }); }; MenuDish::delete_for_menu(&self.id, db).await?; - // The slot gets its reference back — a slot no menu is published for - // any more may leave the settings again. After the delete, so a crash - // over-counts (refusing a removal) rather than under-counts. - cap::release_ref(&slot_ref(deleted.slot.as_str()), 1, db).await?; Ok(deleted) } } @@ -396,4 +411,165 @@ mod tests { assert!(validate_capacity(Some(-1)).is_err()); assert!(validate_capacity(Some(MAX_MENU_CAPACITY + 1)).is_err()); } + + // --- the slot reference and the menu row move together --------------- + + async fn school() -> Database { + let db = crate::database::init_mem().await.unwrap(); + db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';") + .await + .unwrap() + .check() + .unwrap(); + db + } + + fn lunch() -> MenuSlot { + MenuSlot::try_new("lunch", &[MealSlotDef::try_new("lunch", None).unwrap()]).unwrap() + } + + /// The reference count, re-read out of the store — never off a return + /// value, which the in-memory engine forges wins on. + async fn refs(db: &Database) -> i64 { + let mut result = db + .query("SELECT VALUE (count ?? 0) FROM $id") + .bind(("id", slot_ref("lunch"))) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .into_iter() + .next() + .unwrap_or(0) + } + + async fn publish(date: &str, db: &Database) -> Result { + Menu::create( + MenuDate::try_new(date).unwrap(), + lunch(), + None, + &UserId::from_key("teacher"), + db, + ) + .await + } + + /// Plant a menu row the pre-check will (or will not) find, without going + /// through the claim — a row published before the counter existed. + async fn plant(id: &MenuId, date: &str, db: &Database) { + db.query( + "CREATE $id SET date = $date, slot = 'lunch', \ + created_by = user:teacher, created_at = 1", + ) + .bind(("id", id.record())) + .bind(("date", date.to_string())) + .await + .unwrap() + .check() + .unwrap(); + } + + #[tokio::test] + async fn publishing_lands_the_menu_and_its_reference_together() { + let db = school().await; + let menu = publish("2026-08-02", &db).await.unwrap(); + assert!(Menu::read(menu.get_id(), &db).await.unwrap().is_some()); + assert_eq!(refs(&db).await, 1); + + // The day+slot pre-check answers the second publish — and a refusal + // may not count the slot, or the menu would outlive its own reference. + let again = publish("2026-08-02", &db) + .await + .expect_err("that day and slot are taken"); + assert!(matches!(again, AppError::Conflict(_)), "got {again:?}"); + assert_eq!(refs(&db).await, 1); + } + + #[tokio::test] + async fn a_retired_slot_refuses_and_writes_nothing() { + let db = school().await; + assert!(cap::retire(&slot_ref("lunch"), &db).await.unwrap()); + + let refused = publish("2026-08-02", &db) + .await + .expect_err("the slot left the settings"); + assert!( + matches!(refused, AppError::ConflictOwned(_)), + "got {refused:?}" + ); + assert_eq!(refs(&db).await, 0); + assert!( + Menu::find(&MenuDate::try_new("2026-08-02").unwrap(), &lunch(), &db) + .await + .unwrap() + .is_none() + ); + } + + /// The race the fold exists for: a rival places the very row this publish + /// is placing, between the pre-check and the write. Only the claim's own + /// gate can answer it, and its answer must cost no reference. + #[tokio::test] + async fn a_rival_on_the_id_answers_taken_and_counts_nothing() { + let db = school().await; + let id = MenuId::for_slot(&MenuDate::try_new("2026-08-02").unwrap(), &lunch()); + // Planted under another day, so `find` misses it exactly as it would + // in the instant before the rival's own row was visible. + plant(&id, "1999-01-01", &db).await; + + let taken = publish("2026-08-02", &db) + .await + .expect_err("the id is taken"); + assert!(matches!(taken, AppError::Conflict(_)), "got {taken:?}"); + assert_eq!(refs(&db).await, 0); + } + + /// Menus published before ids were derived keep a ULID key a new publish + /// cannot collide with, so the pre-check is the only thing that can refuse. + #[tokio::test] + async fn a_legacy_ulid_menu_still_answers_taken() { + let db = school().await; + plant(&MenuId::from_key("01JLEGACYMENU"), "2026-08-02", &db).await; + + let taken = publish("2026-08-02", &db) + .await + .expect_err("that day and slot are taken"); + assert!(matches!(taken, AppError::Conflict(_)), "got {taken:?}"); + assert_eq!(refs(&db).await, 0); + } + + #[tokio::test] + async fn deleting_hands_the_reference_back_in_the_same_step() { + let db = school().await; + let monday = publish("2026-08-03", &db).await.unwrap(); + publish("2026-08-04", &db).await.unwrap(); + assert_eq!(refs(&db).await, 2); + + let id = monday.get_id().clone(); + let ghost = monday.clone(); + monday.delete(&db).await.unwrap(); + assert!(Menu::read(&id, &db).await.unwrap().is_none()); + assert_eq!(refs(&db).await, 1, "the row and its reference go together"); + + // Deleting what is already gone hands nothing back: a second release + // would leave a slot one menu still uses free to be retired. + let gone = ghost.delete(&db).await.expect_err("already deleted"); + assert!(matches!(gone, AppError::NotFound), "got {gone:?}"); + assert_eq!(refs(&db).await, 1); + assert!( + !cap::retire(&slot_ref("lunch"), &db).await.unwrap(), + "a slot a menu is still published for may not be retired" + ); + + // …and once the last menu goes, it may. + let last = Menu::find(&MenuDate::try_new("2026-08-04").unwrap(), &lunch(), &db) + .await + .unwrap() + .unwrap(); + last.delete(&db).await.unwrap(); + assert_eq!(refs(&db).await, 0); + } }