forge
Explore
Log in

Don't you dare go Hollow

🔩 finish the counter-claim sweep, guard every carried link

Browse files at this commit

a290672f4c8fce29d6dfc726a5e8160d71bfe29cAhmet Kaan GümüşParent: a8435ee
  • fix
    • 🔩 finish the counter-claim sweep, guard every carried link
Show full message
fix: 🔩 finish the counter-claim sweep, guard every carried link
src/domain/class_group.rsmodified+61 -0
@@ -522,6 +522,67 @@ mod tests {
522 assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not");522 assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not");
523 }523 }
524 524
525+ /// The class twin of
526+ /// [`crate::domain::course`]'s `a_stale_mover_is_refused_and_claims_nothing`
527+ /// and `a_stale_re_stater_is_refused_and_reverts_nothing`, in one: both
528+ /// PATCHes compute their counter move from the row as *they* read it, so a
529+ /// second one running on the pre-move struct would claim a second seat for
530+ /// one link (the mover) or drag the link back and strand the winner's claim
531+ /// (the re-stater, which shifts no counter at all and so is only ever
532+ /// stopped by a guard armed off the *carried column*). Both must be refused
533+ /// with the counts reading as if they never ran.
534+ #[tokio::test]
535+ async fn a_stale_class_term_write_is_refused_and_moves_no_count() {
536+ let db = crate::database::init_mem().await.unwrap();
537+ let at = crate::domain::timestamp::Timestamp::from_millis;
538+ let from = a_term(&db).await;
539+ let to = Term::create(TermName::try_new("2027").unwrap(), at(100), at(200), &db)
540+ .await
541+ .unwrap();
542+ let other = Term::create(TermName::try_new("2028").unwrap(), at(100), at(200), &db)
543+ .await
544+ .unwrap();
545+ let class = class_on(Some(from.get_id().clone()), &db).await;
546+ let stale = class.clone();
547+ class
548+ .update(None, None, Some(Some(to.get_id().clone())), &db)
549+ .await
550+ .unwrap();
551+
552+ // The mover: its snapshot says `from`, so it would release `from` and
553+ // claim `other` on top of the winner's claim on `to`.
554+ let error = stale
555+ .clone()
556+ .update(None, None, Some(Some(other.get_id().clone())), &db)
557+ .await
558+ .expect_err("a mover that read a link it no longer holds must be refused");
559+ assert!(matches!(error, AppError::Conflict(_)), "{error:?}");
560+ // The re-stater: shifts no counter, so only the CAS can stop it.
561+ let error = stale
562+ .clone()
563+ .update(None, None, Some(Some(from.get_id().clone())), &db)
564+ .await
565+ .expect_err("re-stating a link someone else moved must be refused");
566+ assert!(matches!(error, AppError::Conflict(_)), "{error:?}");
567+
568+ let stored = ClassGroup::read(stale.get_id(), &db)
569+ .await
570+ .unwrap()
571+ .unwrap();
572+ assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link");
573+ assert_eq!(count_on(from.get_id(), &db).await, 0, "released once");
574+ assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once");
575+ assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed");
576+
577+ // A genuine no-op re-state still lands and still moves nothing.
578+ let same = stored
579+ .update(None, None, Some(Some(to.get_id().clone())), &db)
580+ .await
581+ .expect("re-stating the link the row really holds is not a conflict");
582+ assert_eq!(same.get_term(), Some(to.get_id()));
583+ assert_eq!(count_on(to.get_id(), &db).await, 1, "still one seat");
584+ }
585+
525 /// [`crate::domain::course::Course::delete`]'s class sweep: deleting a course586 /// [`crate::domain::course::Course::delete`]'s class sweep: deleting a course
526 /// takes its `class_course` attachments with it and gives each class its587 /// takes its `class_course` attachments with it and gives each class its
527 /// count back, or the classes would be undeletable forever over rows that588 /// count back, or the classes would be undeletable forever over rows that
src/domain/course.rsmodified+61 -0
@@ -759,6 +759,67 @@ mod tests {
759 assert_eq!(stored.get_term(), Some(to.get_id()));759 assert_eq!(stored.get_term(), Some(to.get_id()));
760 }760 }
761 761
762+ /// The same race with the counters taken out of it. A PATCH that re-states
763+ /// the term its snapshot showed shifts *nothing* — [`term::ref_move`] hands
764+ /// back no claim and no release — so if the guard were armed off the counter
765+ /// move it would not be armed here at all, and the write would land: the
766+ /// winner's link silently dragged back, its claim stranded on a term nothing
767+ /// points at (undeletable forever) and the reverted-to term linked at a
768+ /// count of zero (deletable while linked). The guard is armed by the request
769+ /// *carrying* the column instead, which is why this is refused.
770+ #[tokio::test]
771+ async fn a_stale_re_stater_is_refused_and_reverts_nothing() {
772+ let db = crate::database::init_mem().await.unwrap();
773+ let from = a_term("2026", &db).await;
774+ let to = a_term("2027", &db).await;
775+ let course = course_on(Some(from.get_id().clone()), &db).await;
776+ let stale = course.clone();
777+ course
778+ .update(None, None, None, Some(Some(to.get_id().clone())), None, &db)
779+ .await
780+ .unwrap();
781+
782+ let error = stale
783+ .clone()
784+ .update(
785+ None,
786+ None,
787+ None,
788+ Some(Some(from.get_id().clone())),
789+ None,
790+ &db,
791+ )
792+ .await
793+ .expect_err("re-stating a link someone else moved must be refused");
794+ assert!(
795+ matches!(error, AppError::Conflict(_)),
796+ "a lost CAS is a conflict, not a silent 200: {error:?}"
797+ );
798+ let stored = Course::read(stale.get_id(), &db).await.unwrap().unwrap();
799+ assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link");
800+ assert_eq!(
801+ count_on(from.get_id(), &db).await,
802+ 0,
803+ "the reverted-to term must not end up linked at zero"
804+ );
805+ assert_eq!(
806+ count_on(to.get_id(), &db).await,
807+ 1,
808+ "…nor the winner's term counted with nothing pointing at it"
809+ );
810+
811+ // A *genuine* no-op re-state — nobody moved underneath it — still lands,
812+ // and still moves no counter: the CAS passes trivially.
813+ let fresh = Course::read(stale.get_id(), &db).await.unwrap().unwrap();
814+ let same = fresh
815+ .update(None, None, None, Some(Some(to.get_id().clone())), None, &db)
816+ .await
817+ .expect("re-stating the link the row really holds is not a conflict");
818+ assert_eq!(same.get_term(), Some(to.get_id()));
819+ assert_eq!(count_on(from.get_id(), &db).await, 0, "nothing moved");
820+ assert_eq!(count_on(to.get_id(), &db).await, 1, "…in either direction");
821+ }
822+
762 /// The rollback proof. The transaction releases the old term *before* it823 /// The rollback proof. The transaction releases the old term *before* it
763 /// claims the new one, so a move to a term that is gone has already824 /// claims the new one, so a move to a term that is gone has already
764 /// decremented when the claim throws — the old count still being 1 is the825 /// decremented when the claim throws — the old count still being 1 is the
src/domain/exam_attempt.rsmodified+32 -5
@@ -354,6 +354,24 @@ impl ExamAttempt {
354 statements: &str,354 statements: &str,
355 bindings: Vec<(String, surrealdb::types::Value)>,355 bindings: Vec<(String, surrealdb::types::Value)>,
356 db: &Database,356 db: &Database,
357+ ) -> Result<surrealdb::IndexedResults, AppError> {
358+ Self::write_unfrozen_with(exam, statements, bindings, Vec::new(), db).await
359+ }
360+
361+ /// [`Self::write_unfrozen`] for statements that carry gates of their own:
362+ /// each `(marker, refusal)` names a `THROW` the caller's SQL aborts with and
363+ /// the error it means. The markers are handed to [`transaction_with_retry`]
364+ /// too, so an abort on one is a refusal rather than a round to re-send.
365+ ///
366+ /// The freeze still outranks every one of them: a caller folding a counter
367+ /// claim in here is refused as frozen even when its own gate would also have
368+ /// fired, which is the answer the pre-flight check has always given.
369+ pub(crate) async fn write_unfrozen_with(
370+ exam: &ExamId,
371+ statements: &str,
372+ bindings: Vec<(String, surrealdb::types::Value)>,
373+ refusals: Vec<(&str, AppError)>,
374+ db: &Database,
357 ) -> Result<surrealdb::IndexedResults, AppError> {375 ) -> Result<surrealdb::IndexedResults, AppError> {
358 let sql = format!(376 let sql = format!(
359 "BEGIN TRANSACTION;377 "BEGIN TRANSACTION;
@@ -364,13 +382,22 @@ impl ExamAttempt {
364 );382 );
365 let mut bound = vec![("freeze_exam".into(), exam.record().into_value())];383 let mut bound = vec![("freeze_exam".into(), exam.record().into_value())];
366 bound.extend(bindings);384 bound.extend(bindings);
367- let (result, mut errors) = transaction_with_retry(db, &sql, &bound, &[FROZEN_MARK]).await?;385+ let mut marks = vec![FROZEN_MARK];
368- if errors386+ marks.extend(refusals.iter().map(|(marker, _)| *marker));
369- .values()387+ let (result, mut errors) = transaction_with_retry(db, &sql, &bound, &marks).await?;
370- .any(|error| error.to_string().contains(FROZEN_MARK))388+ let thrown = |marker: &str| {
371- {389+ errors
390+ .values()
391+ .any(|error| error.to_string().contains(marker))
392+ };
393+ if thrown(FROZEN_MARK) {
372 return Err(frozen_error());394 return Err(frozen_error());
373 }395 }
396+ for (marker, refusal) in refusals {
397+ if thrown(marker) {
398+ return Err(refusal);
399+ }
400+ }
374 match errors.drain().map(|(_, error)| error).next() {401 match errors.drain().map(|(_, error)| error).next() {
375 Some(error) => Err(error.into()),402 Some(error) => Err(error.into()),
376 None => Ok(result),403 None => Ok(result),
src/domain/exam_question.rsmodified+464 -87
@@ -16,6 +16,23 @@ use crate::domain::subject::SubjectId;
16 use crate::error::{AppError, ValidationError};16 use crate::error::{AppError, ValidationError};
17 use crate::validate::{validate_question_kind, validate_question_points, validate_required};17 use crate::validate::{validate_question_kind, validate_question_points, validate_required};
18 18
19+/// The `THROW` markers the folded counter moves abort with: the subject the
20+/// reference was to be claimed on is gone, the question being patched is gone,
21+/// and the subject this move started from is no longer the one the handler
22+/// read. File-local like every other marker set (`cap`'s, `subject`'s).
23+const SUBJECT_MARK: &str = "question_subject_gone";
24+const ROW_MARK: &str = "question_row_gone";
25+const STALE_MARK: &str = "question_stale_move";
26+
27+/// The one answer for a subject that isn't there — a claim missing it and the
28+/// web layer's pre-flight lookup missing it are the same 400.
29+fn dead_subject() -> AppError {
30+ AppError::Validation(ValidationError::Invalid {
31+ field: "subject_id",
32+ reason: "subject does not exist",
33+ })
34+}
35+
19 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]36 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
20 pub struct ExamQuestionId(RecordId);37 pub struct ExamQuestionId(RecordId);
21 38
@@ -394,20 +411,7 @@ impl ExamQuestion {
394 from_bank: Option<BankQuestionId>,411 from_bank: Option<BankQuestionId>,
395 db: &Database,412 db: &Database,
396 ) -> Result<ExamQuestion, AppError> {413 ) -> Result<ExamQuestion, AppError> {
397- // Take the subject's reference before the row exists, exactly as a cap
398- // is claimed before the child it caps ([`cap::claim`], here uncapped):
399- // the subject delete is conditioned on that counter reading zero, so
400- // the two contend on the subject record and a question can no longer
401- // land on a subject a concurrent request is deleting. A miss means the
402- // subject is already gone — the same 400 the web layer's pre-flight
403- // check answers with.
404 let counted = subject.record();414 let counted = subject.record();
405- if !cap::claim(&counted, SUBJECT_QUESTION_COUNT_FIELD, cap::UNLIMITED, db).await? {
406- return Err(AppError::Validation(ValidationError::Invalid {
407- field: "subject_id",
408- reason: "subject does not exist",
409- }));
410- }
411 let question = ExamQuestion {415 let question = ExamQuestion {
412 id: ExamQuestionId::generate(),416 id: ExamQuestionId::generate(),
413 exam: exam.clone(),417 exam: exam.clone(),
@@ -421,39 +425,48 @@ impl ExamQuestion {
421 // An insert never banks anything: only a to-bank save writes this.425 // An insert never banks anything: only a to-bank save writes this.
422 banked_as: None,426 banked_as: None,
423 };427 };
424- // The freeze gate rides in the same transaction as the insert: a428+ // The freeze gate and the subject's reference ride in the same
425- // question cannot appear under an exam somebody has already started,429+ // transaction as the insert: a question cannot appear under an exam
426- // however the two requests interleave.430+ // somebody has already started, and the claim that accounts for it
427- let inserted = async {431+ // cannot outlive a row that never landed. Claiming in its own query
428- // Re-sendable despite the `CREATE`: a lost round aborts having432+ // (with a release on failure, as this did) leaves a window where a
429- // written nothing and `$id` is a ULID minted once per call, so the433+ // crash strands the count — and the subject delete is conditioned on
430- // re-send cannot answer "already exists" (there is no UNIQUE index434+ // that count reading zero, so a stranded one makes the subject
431- // on `exam_question`) — the one thing the retry cannot survive.435+ // undeletable forever. A missed claim means the subject is already gone
432- let id = question.id.record();436+ // — the same 400 the web layer's pre-flight check answers with.
433- let mut result = ExamAttempt::write_unfrozen(437+ //
434- exam,438+ // Re-sendable despite the `CREATE`: a lost round aborts having written
435- "CREATE $id CONTENT $question;",439+ // nothing and `$id` is a ULID minted once per call, so the re-send
436- vec![440+ // cannot answer "already exists" (there is no UNIQUE index on
437- ("id".into(), id.into_value()),441+ // `exam_question`) — the one thing the retry cannot survive.
438- ("question".into(), question.into_value()),442+ let id = question.id.record();
439- ],443+ // One counter write in flight at a time, like every other counter write.
440- db,444+ let _guard = cap::counter_lock().await;
441- )445+ let mut result = ExamAttempt::write_unfrozen_with(
442- .await?;446+ exam,
443- result447+ &format!(
444- .take::<Vec<ExamQuestion>>(ExamAttempt::FROZEN_SLOT)?448+ "LET $seat = (UPDATE $subject SET {SUBJECT_QUESTION_COUNT_FIELD} = \
445- .into_iter()449+ ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id);
446- .next()450+ IF array::len($seat) = 0 {{ THROW '{SUBJECT_MARK}' }};
447- .ok_or_else(|| AppError::Internal("failed to create exam question".into()))451+ CREATE $id CONTENT $question;"
448- }452+ ),
449- .await;453+ vec![
450- if inserted.is_err() {454+ ("subject".into(), counted.into_value()),
451- // The row never landed (a frozen exam, most often), so the455+ ("id".into(), id.into_value()),
452- // reference it took goes straight back — otherwise the subject456+ ("question".into(), question.into_value()),
453- // would be undeletable for a question that does not exist.457+ ],
454- cap::release(&counted, SUBJECT_QUESTION_COUNT_FIELD, db).await?;458+ vec![(SUBJECT_MARK, dead_subject())],
455- }459+ db,
456- inserted460+ )
461+ .await?;
462+ // Counted off the statements that actually ran rather than a fixed
463+ // slot, so folding another gate in above can never mis-read the row.
464+ let slot = result.num_statements().saturating_sub(2);
465+ result
466+ .take::<Vec<ExamQuestion>>(slot)?
467+ .into_iter()
468+ .next()
469+ .ok_or_else(|| AppError::Internal("failed to create exam question".into()))
457 }470 }
458 471
459 pub async fn read(472 pub async fn read(
@@ -494,50 +507,96 @@ impl ExamQuestion {
494 spec: QuestionSpec,507 spec: QuestionSpec,
495 db: &Database,508 db: &Database,
496 ) -> Result<ExamQuestion, AppError> {509 ) -> Result<ExamQuestion, AppError> {
497- // A re-tag moves a reference: the new subject is claimed *before* the510+ // A re-tag moves a reference, and the move rides the very transaction
498- // write and the old one released only once it lands, so at no instant511+ // that moves the link: the old subject's release, the new one's claim
499- // is either subject under-counted — the direction that would let one be512+ // and the row write commit together or not at all, so no crash can
500- // deleted while this question still points at it. Both counters staying513+ // strand a count on a subject nothing points at (which would make it
501- // put is the ordinary case (`subject` omitted from the PATCH), and it514+ // undeletable forever).
502- // costs nothing.515+ //
516+ // The two are armed on *different* conditions, which is the whole of
517+ // the rule ([`crate::domain::field_update::FieldUpdate::refcount`] states
518+ // it the same way): the counter statements only when the link actually
519+ // changes, but the CAS whenever this write *carries* the link — and it
520+ // always does, because the handler fills an omitted `subject_id` from
521+ // the row it read (`web::exams::questions`), so `subject` is in the
522+ // `SET` of every one of these updates. Arming the CAS on "changed"
523+ // instead would leave the re-stater through: a PATCH carrying the
524+ // subject its own stale snapshot held, sent while a rival's move
525+ // already landed, writes that stale subject straight back over the
526+ // winner — a revert with the counters left pointing at the move.
503 let retag = (subject != self.subject).then(|| (subject.record(), self.subject.record()));527 let retag = (subject != self.subject).then(|| (subject.record(), self.subject.record()));
504- if let Some((next, _)) = &retag528+ let write = "UPDATE $id SET subject = $subject, text = $text, points = $points,
505- && !cap::claim(next, SUBJECT_QUESTION_COUNT_FIELD, cap::UNLIMITED, db).await?529+ kind = $kind, choices = $choices, correct = $correct";
506- {530+ let mut bindings = vec![
507- return Err(AppError::Validation(ValidationError::Invalid {531+ ("id".into(), self.id.record().into_value()),
508- field: "subject_id",532+ ("subject".into(), subject.record().into_value()),
509- reason: "subject does not exist",533+ ("text".into(), text.into_value()),
510- }));534+ ("points".into(), points.into_value()),
511- }535+ ("kind".into(), spec.kind.into_value()),
512- let written = async {536+ ("choices".into(), spec.choices.into_value()),
513- let mut result = ExamAttempt::write_unfrozen(537+ ("correct".into(), spec.correct.into_value()),
514- &self.exam,538+ ];
515- "UPDATE $id SET subject = $subject, text = $text, points = $points,539+ let mut statements: Vec<String> = Vec::new();
516- kind = $kind, choices = $choices, correct = $correct RETURN AFTER;",540+ let mut refusals: Vec<(&str, AppError)> = Vec::new();
517- vec![
518- ("id".into(), self.id.record().into_value()),
519- ("subject".into(), subject.record().into_value()),
520- ("text".into(), text.into_value()),
521- ("points".into(), points.into_value()),
522- ("kind".into(), spec.kind.into_value()),
523- ("choices".into(), spec.choices.into_value()),
524- ("correct".into(), spec.correct.into_value()),
525- ],
526- db,
527- )
528- .await?;
529- result
530- .take::<Vec<ExamQuestion>>(ExamAttempt::FROZEN_SLOT)?
531- .into_iter()
532- .next()
533- .ok_or(AppError::NotFound)
534- }
535- .await;
536 if let Some((next, previous)) = &retag {541 if let Some((next, previous)) = &retag {
537- let give_back = if written.is_ok() { previous } else { next };542+ statements.push(format!(
538- cap::release(give_back, SUBJECT_QUESTION_COUNT_FIELD, db).await?;543+ "UPDATE $ref_release SET {SUBJECT_QUESTION_COUNT_FIELD} = \
544+ math::max([({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) - 1, 0])"
545+ ));
546+ statements.push(format!(
547+ "LET $seat = (UPDATE $ref_claim SET {SUBJECT_QUESTION_COUNT_FIELD} = \
548+ ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id)"
549+ ));
550+ statements.push(format!(
551+ "IF array::len($seat) = 0 {{ THROW '{SUBJECT_MARK}' }}"
552+ ));
553+ bindings.push(("ref_claim".into(), next.clone().into_value()));
554+ bindings.push(("ref_release".into(), previous.clone().into_value()));
555+ refusals.push((SUBJECT_MARK, dead_subject()));
539 }556 }
540- written557+ // The CAS: the row write matches only while the question still sits on
558+ // the subject this handler read. A genuine no-op re-state passes it
559+ // trivially (the row holds exactly what is expected); a stale one —
560+ // whether it moves the link or restates it — matches nothing, aborts
561+ // the whole transaction, and so claims nothing and answers 409.
562+ bindings.push(("ref_expected".into(), self.subject.record().into_value()));
563+ statements.push(format!(
564+ "LET $row = ({write} WHERE subject = $ref_expected RETURN AFTER)"
565+ ));
566+ statements.push(format!(
567+ "IF array::len($row) = 0 {{ \
568+ LET $live = (UPDATE $id WHERE subject != $ref_expected RETURN VALUE id); \
569+ IF array::len($live) = 0 {{ THROW '{ROW_MARK}' }} \
570+ ELSE {{ THROW '{STALE_MARK}' }} }}"
571+ ));
572+ statements.push("RETURN $row".into());
573+ refusals.push((
574+ STALE_MARK,
575+ AppError::Conflict(
576+ "the subject this question was read on changed since; re-read and retry",
577+ ),
578+ ));
579+ // The row is gone: the same 404 an empty write answers with, so the
580+ // deleted-row case is unchanged.
581+ refusals.push((ROW_MARK, AppError::NotFound));
582+ let statements = format!("{};", statements.join("; "));
583+ // One counter write in flight at a time — only a move writes one.
584+ let _guard = match &retag {
585+ Some(_) => Some(cap::counter_lock().await),
586+ None => None,
587+ };
588+ let mut result =
589+ ExamAttempt::write_unfrozen_with(&self.exam, &statements, bindings, refusals, db)
590+ .await?;
591+ // Read off the trailing `RETURN` rather than a fixed slot: a re-tag
592+ // arms three more statements than a plain PATCH does (and an `IF`
593+ // block is one slot whether or not it is taken).
594+ let slot = result.num_statements().saturating_sub(2);
595+ result
596+ .take::<Vec<ExamQuestion>>(slot)?
597+ .into_iter()
598+ .next()
599+ .ok_or(AppError::NotFound)
541 }600 }
542 601
543 /// Point the question's `banked_as` at the bank template it was just saved602 /// Point the question's `banked_as` at the bank template it was just saved
@@ -961,6 +1020,324 @@ mod tests {
961 }1020 }
962 }1021 }
963 1022
1023+ /// The subject reference counter, which is what the subject's delete guard
1024+ /// reads: every one of these asserts *stored* state, because a claim that
1025+ /// outlives the row it accounts for makes its subject undeletable forever.
1026+ mod counters {
1027+ use super::*;
1028+ use crate::database::init_mem;
1029+ use crate::domain::course::CourseId;
1030+ use crate::domain::exam::{
1031+ Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,
1032+ };
1033+ use crate::domain::settings::Settings;
1034+ use crate::domain::subject::{Subject, SubjectDescription, SubjectName};
1035+ use crate::domain::user::UserId;
1036+
1037+ async fn an_exam(db: &Database) -> Exam {
1038+ let kinds = Settings::defaults().get_exam_kinds().to_vec();
1039+ Exam::create(
1040+ &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"),
1041+ &CourseId::from_key("01TESTCOURSEAAAAAAAAAAAAAA"),
1042+ ExamTitle::try_new("practice").unwrap(),
1043+ ExamDescription::try_new("").unwrap(),
1044+ ExamKind::try_new("quiz", &kinds).unwrap(),
1045+ ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None)
1046+ .unwrap(),
1047+ ExamAttemptLimit::try_new(1).unwrap(),
1048+ true,
1049+ false,
1050+ false,
1051+ db,
1052+ )
1053+ .await
1054+ .unwrap()
1055+ }
1056+
1057+ async fn a_subject(db: &Database) -> Subject {
1058+ Subject::create(
1059+ &CourseId::generate(),
1060+ SubjectName::try_new("topic").unwrap(),
1061+ SubjectDescription::try_new("").unwrap(),
1062+ db,
1063+ )
1064+ .await
1065+ .unwrap()
1066+ }
1067+
1068+ /// The editable payload, fresh per call (each one is consumed).
1069+ fn body() -> (QuestionText, QuestionPoints, QuestionSpec) {
1070+ (
1071+ QuestionText::try_new("3 + 3?").unwrap(),
1072+ QuestionPoints::try_new(5).unwrap(),
1073+ QuestionSpec::try_new(kind("text"), None, None, &[]).unwrap(),
1074+ )
1075+ }
1076+
1077+ async fn a_question(exam: &Exam, on: &SubjectId, db: &Database) -> ExamQuestion {
1078+ let (text, points, spec) = body();
1079+ ExamQuestion::create(exam.get_id(), on.clone(), text, points, spec, db)
1080+ .await
1081+ .unwrap()
1082+ }
1083+
1084+ async fn moved(
1085+ question: ExamQuestion,
1086+ to: &SubjectId,
1087+ db: &Database,
1088+ ) -> Result<ExamQuestion, AppError> {
1089+ let (text, points, spec) = body();
1090+ question.update(to.clone(), text, points, spec, db).await
1091+ }
1092+
1093+ /// The stored `exam_question_count` on one subject, absent = zero.
1094+ async fn count_on(subject: &SubjectId, db: &Database) -> i64 {
1095+ let mut result = db
1096+ .query(format!(
1097+ "SELECT VALUE ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) FROM $sub"
1098+ ))
1099+ .bind(("sub", subject.record()))
1100+ .await
1101+ .unwrap()
1102+ .check()
1103+ .unwrap();
1104+ result
1105+ .take::<Vec<i64>>(0)
1106+ .unwrap()
1107+ .first()
1108+ .copied()
1109+ .unwrap_or(0)
1110+ }
1111+
1112+ async fn rows(sql: &str, db: &Database) -> usize {
1113+ let mut result = db.query(sql).await.unwrap().check().unwrap();
1114+ result.take::<Vec<RecordId>>(0).unwrap().len()
1115+ }
1116+
1117+ /// The freeze outranks the counter move, on both paths — and because
1118+ /// the claim now rides the refused transaction, "outranks" has to mean
1119+ /// the counters read as if nothing ran.
1120+ #[tokio::test]
1121+ async fn a_frozen_exam_leaves_the_subject_counters_untouched() {
1122+ let db = init_mem().await.unwrap();
1123+ let exam = an_exam(&db).await;
1124+ let (from, to) = (a_subject(&db).await, a_subject(&db).await);
1125+ let (from, to) = (from.get_id().clone(), to.get_id().clone());
1126+ let question = a_question(&exam, &from, &db).await;
1127+ assert_eq!(count_on(&from, &db).await, 1);
1128+
1129+ ExamAttempt::start(&exam, &UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"), &db)
1130+ .await
1131+ .unwrap();
1132+
1133+ let (text, points, spec) = body();
1134+ let error = ExamQuestion::create(exam.get_id(), to.clone(), text, points, spec, &db)
1135+ .await
1136+ .expect_err("a started exam takes no new questions");
1137+ assert!(matches!(error, AppError::Conflict(_)), "{error:?}");
1138+ assert_eq!(count_on(&to, &db).await, 0, "the refused claim rolled back");
1139+
1140+ let error = moved(question, &to, &db)
1141+ .await
1142+ .expect_err("a started exam takes no re-tag either");
1143+ assert!(matches!(error, AppError::Conflict(_)), "{error:?}");
1144+ assert_eq!(count_on(&from, &db).await, 1, "the release rolled back too");
1145+ assert_eq!(count_on(&to, &db).await, 0);
1146+ }
1147+
1148+ /// The create-path invariant: a refused create writes neither the row
1149+ /// nor a count — least of all on a subject it would have to invent.
1150+ #[tokio::test]
1151+ async fn a_create_on_a_dead_subject_writes_neither_row_nor_count() {
1152+ let db = init_mem().await.unwrap();
1153+ let exam = an_exam(&db).await;
1154+ let subject = a_subject(&db).await;
1155+ let id = subject.get_id().clone();
1156+ subject.delete(&db).await.unwrap();
1157+
1158+ let (text, points, spec) = body();
1159+ let error = ExamQuestion::create(exam.get_id(), id, text, points, spec, &db)
1160+ .await
1161+ .expect_err("a subject that is gone must not be taggable");
1162+ assert!(error.to_string().contains("subject does not exist"));
1163+ assert_eq!(
1164+ rows("SELECT VALUE id FROM exam_question", &db).await,
1165+ 0,
1166+ "a refused create may write no row"
1167+ );
1168+ assert_eq!(
1169+ rows("SELECT VALUE id FROM subject", &db).await,
1170+ 0,
1171+ "…and least of all a count on a subject it just brought back"
1172+ );
1173+ }
1174+
1175+ #[tokio::test]
1176+ async fn a_subject_move_moves_the_count() {
1177+ let db = init_mem().await.unwrap();
1178+ let exam = an_exam(&db).await;
1179+ let (from, to) = (a_subject(&db).await, a_subject(&db).await);
1180+ let (from, to) = (from.get_id().clone(), to.get_id().clone());
1181+ let question = a_question(&exam, &from, &db).await;
1182+
1183+ let after = moved(question, &to, &db).await.unwrap();
1184+ assert_eq!(after.get_subject(), &to);
1185+ assert_eq!(count_on(&from, &db).await, 0, "the old subject is free");
1186+ assert_eq!(count_on(&to, &db).await, 1, "the new one is not");
1187+ }
1188+
1189+ #[tokio::test]
1190+ async fn a_move_to_a_dead_subject_leaves_everything_untouched() {
1191+ let db = init_mem().await.unwrap();
1192+ let exam = an_exam(&db).await;
1193+ let from = a_subject(&db).await.get_id().clone();
1194+ let dead = a_subject(&db).await;
1195+ let gone = dead.get_id().clone();
1196+ dead.delete(&db).await.unwrap();
1197+ let question = a_question(&exam, &from, &db).await;
1198+
1199+ let error = moved(question.clone(), &gone, &db)
1200+ .await
1201+ .expect_err("a subject that is gone must not be taggable");
1202+ assert!(error.to_string().contains("subject does not exist"));
1203+ let stored = ExamQuestion::read(question.get_id(), &db)
1204+ .await
1205+ .unwrap()
1206+ .unwrap();
1207+ assert_eq!(stored.get_subject(), &from, "the link never moved");
1208+ assert_eq!(
1209+ count_on(&from, &db).await,
1210+ 1,
1211+ "the release rolled back with the claim"
1212+ );
1213+ assert_eq!(rows("SELECT VALUE id FROM subject", &db).await, 1);
1214+ }
1215+
1216+ /// The double-claim guard. Both movers compute their claim and release
1217+ /// from the row as *they* read it, so two PATCHes re-tagging the same
1218+ /// question both release the old subject and both claim their own
1219+ /// target — two counts for one link, and the loser's target is
1220+ /// undeletable forever. The second call here runs on the struct read
1221+ /// before the first one landed: it must be refused outright, and the
1222+ /// counts must read as if it never ran.
1223+ ///
1224+ /// Drop `AND subject = $ref_expected` from the row write in
1225+ /// [`ExamQuestion::update`] and this goes red on the very first
1226+ /// assertion — the stale mover is happily applied.
1227+ #[tokio::test]
1228+ async fn a_stale_mover_is_refused_and_claims_nothing() {
1229+ let db = init_mem().await.unwrap();
1230+ let exam = an_exam(&db).await;
1231+ let from = a_subject(&db).await.get_id().clone();
1232+ let to = a_subject(&db).await.get_id().clone();
1233+ let other = a_subject(&db).await.get_id().clone();
1234+ let question = a_question(&exam, &from, &db).await;
1235+ let stale = question.clone();
1236+
1237+ moved(question, &to, &db).await.unwrap();
1238+ let error = moved(stale.clone(), &other, &db)
1239+ .await
1240+ .expect_err("a mover that read a subject it no longer holds must be refused");
1241+ assert!(
1242+ matches!(error, AppError::Conflict(_)),
1243+ "a lost CAS is a conflict, not a 404 or a 500: {error:?}"
1244+ );
1245+
1246+ let stored = ExamQuestion::read(stale.get_id(), &db)
1247+ .await
1248+ .unwrap()
1249+ .unwrap();
1250+ assert_eq!(stored.get_subject(), &to, "the winner's link");
1251+ assert_eq!(count_on(&from, &db).await, 0, "released once, not twice");
1252+ assert_eq!(count_on(&to, &db).await, 1, "claimed once");
1253+ assert_eq!(count_on(&other, &db).await, 0, "never claimed");
1254+ }
1255+
1256+ /// The other half of the same race, and the one arming on "the subject
1257+ /// changed" lets through: this PATCH carries the subject its snapshot
1258+ /// already held, so it moves no counter — but a rival's move landed
1259+ /// first, and writing that stale subject back would revert the winner
1260+ /// while both counters still describe the move. The handler fills an
1261+ /// omitted `subject_id` from the row it read, so this is also every
1262+ /// text-only PATCH sent from a stale snapshot.
1263+ ///
1264+ /// Arm the CAS on the re-tag instead of on the write and this goes red
1265+ /// on the first assertion — the re-state lands 200.
1266+ #[tokio::test]
1267+ async fn a_stale_re_stater_is_refused_and_reverts_nothing() {
1268+ let db = init_mem().await.unwrap();
1269+ let exam = an_exam(&db).await;
1270+ let from = a_subject(&db).await.get_id().clone();
1271+ let to = a_subject(&db).await.get_id().clone();
1272+ let question = a_question(&exam, &from, &db).await;
1273+ let stale = question.clone();
1274+
1275+ moved(question, &to, &db).await.unwrap();
1276+ let error = moved(stale.clone(), &from, &db)
1277+ .await
1278+ .expect_err("re-stating a subject a rival moved off must be refused");
1279+ assert!(
1280+ matches!(error, AppError::Conflict(_)),
1281+ "a lost CAS is a conflict, not a silent revert: {error:?}"
1282+ );
1283+
1284+ let stored = ExamQuestion::read(stale.get_id(), &db)
1285+ .await
1286+ .unwrap()
1287+ .unwrap();
1288+ assert_eq!(stored.get_subject(), &to, "the winner's link stands");
1289+ assert_eq!(
1290+ count_on(&from, &db).await,
1291+ 0,
1292+ "released once, and stayed so"
1293+ );
1294+ assert_eq!(count_on(&to, &db).await, 1, "claimed once, and stayed so");
1295+ }
1296+
1297+ /// …and the price of arming the CAS on every write is nothing: a PATCH
1298+ /// re-stating the subject the row really holds passes it trivially.
1299+ #[tokio::test]
1300+ async fn a_no_op_re_state_still_lands() {
1301+ let db = init_mem().await.unwrap();
1302+ let exam = an_exam(&db).await;
1303+ let on = a_subject(&db).await.get_id().clone();
1304+ let question = a_question(&exam, &on, &db).await;
1305+
1306+ let (_, points, spec) = body();
1307+ let after = question
1308+ .update(
1309+ on.clone(),
1310+ QuestionText::try_new("4 + 4?").unwrap(),
1311+ points,
1312+ spec,
1313+ &db,
1314+ )
1315+ .await
1316+ .expect("re-stating the subject the row holds is not a conflict");
1317+ assert_eq!(after.get_text().as_str(), "4 + 4?");
1318+ assert_eq!(after.get_subject(), &on);
1319+ assert_eq!(count_on(&on, &db).await, 1, "no counter moved");
1320+ }
1321+
1322+ /// A re-tag of a question whose row is gone is still the 404 it was,
1323+ /// not the stale-mover 409 — the two empty-`$row` cases stay apart.
1324+ #[tokio::test]
1325+ async fn a_move_of_a_deleted_question_is_still_a_404() {
1326+ let db = init_mem().await.unwrap();
1327+ let exam = an_exam(&db).await;
1328+ let from = a_subject(&db).await.get_id().clone();
1329+ let to = a_subject(&db).await.get_id().clone();
1330+ let question = a_question(&exam, &from, &db).await;
1331+ question.clone().delete(&db).await.unwrap();
1332+
1333+ let error = moved(question, &to, &db)
1334+ .await
1335+ .expect_err("a deleted question cannot be re-tagged");
1336+ assert!(matches!(error, AppError::NotFound), "{error:?}");
1337+ assert_eq!(count_on(&to, &db).await, 0, "and nothing was claimed");
1338+ }
1339+ }
1340+
964 #[tokio::test]1341 #[tokio::test]
965 async fn spec_rejects_blank_or_oversized_choices() {1342 async fn spec_rejects_blank_or_oversized_choices() {
966 let with = |text: String| {1343 let with = |text: String| {
src/domain/field_update.rsmodified+24 -6
@@ -146,6 +146,16 @@ impl FieldUpdate {
146 /// link — a count with no link is exactly what makes a term undeletable146 /// link — a count with no link is exactly what makes a term undeletable
147 /// forever. The loser's row write matches nothing and the whole transaction147 /// forever. The loser's row write matches nothing and the whole transaction
148 /// aborts, so it claims nothing and answers 409.148 /// aborts, so it claims nothing and answers 409.
149+ ///
150+ /// **Carrying the link and shifting a counter are separate questions**, and
151+ /// the CAS keys off the first one — `run` arms it for any request that
152+ /// `.set()` this column, `claim`/`release` both `None` included. A PATCH
153+ /// *re-stating* the link its snapshot showed shifts no counter, but it is
154+ /// the same stale read: run it against a row someone else has since moved
155+ /// and the unguarded write silently drags the link back, stranding the
156+ /// winner's claim on a term nothing points at (undeletable forever) and
157+ /// leaving the reverted-to term linked at zero (deletable while linked).
158+ /// Gating the CAS on the counters is what let that through.
149 #[must_use]159 #[must_use]
150 pub fn refcount(160 pub fn refcount(
151 mut self,161 mut self,
@@ -156,16 +166,19 @@ impl FieldUpdate {
156 release: Option<RecordId>,166 release: Option<RecordId>,
157 refused: AppError,167 refused: AppError,
158 ) -> Self {168 ) -> Self {
159- if claim.is_some() || release.is_some() {169+ self.refcount = Some((field, link, expected, claim, release, refused));
160- self.refcount = Some((field, link, expected, claim, release, refused));
161- }
162 self170 self
163 }171 }
164 172
165 /// Run the update and return the stored row. An empty request writes173 /// Run the update and return the stored row. An empty request writes
166 /// nothing at all and reads the row back unchanged.174 /// nothing at all and reads the row back unchanged.
167 pub async fn run<T: SurrealValue>(mut self, db: &Database) -> Result<T, AppError> {175 pub async fn run<T: SurrealValue>(mut self, db: &Database) -> Result<T, AppError> {
176+ // Armed by the *request*, not by the counters: a PATCH that carries the
177+ // link column gets the CAS even when it re-states the value it read and
178+ // so shifts nothing. Decided here rather than in `refcount` so the
179+ // builder's call order cannot silently disarm it — `run` is always last.
168 let moved = self.refcount.take();180 let moved = self.refcount.take();
181+ let moved = moved.filter(|(_, link, ..)| self.is_set(link));
169 if self.assignments.is_empty() {182 if self.assignments.is_empty() {
170 let row: Option<T> = db.select(self.id).await?;183 let row: Option<T> = db.select(self.id).await?;
171 return row.ok_or(AppError::NotFound);184 return row.ok_or(AppError::NotFound);
@@ -199,9 +212,9 @@ impl FieldUpdate {
199 None => (None, None),212 None => (None, None),
200 };213 };
201 refused = refused.or(extra_refused);214 refused = refused.or(extra_refused);
202- // Armed only for a move that actually shifts a counter, so a plain PATCH215+ // A PATCH that does not carry the link at all writes the same unguarded
203- // — and a `term` PATCH that re-stated the link it already had — writes216+ // `UPDATE` it always did — it re-states nothing and races nobody. Probed
204- // the same unguarded `UPDATE` it always did. Probed on the mem engine:217+ // on the mem engine:
205 // a bound `None` comes through as `NONE` and `link = NONE` matches a row218 // a bound `None` comes through as `NONE` and `link = NONE` matches a row
206 // whose option column was never set, while failing one that holds a219 // whose option column was never set, while failing one that holds a
207 // record, so the absent-link shape needs no `??`.220 // record, so the absent-link shape needs no `??`.
@@ -241,6 +254,11 @@ impl FieldUpdate {
241 /// means the row write matched nothing, exactly as [`write_with_retry`] would254 /// means the row write matched nothing, exactly as [`write_with_retry`] would
242 /// have reported it, so the caller's refusal is unchanged.255 /// have reported it, so the caller's refusal is unchanged.
243 ///256 ///
257+/// A re-statement shifts no counter, so `claim` and `release` are both `None`
258+/// and the transaction is the CAS'd row write and its split alone — still a
259+/// transaction, because the split's probe must see the same snapshot the write
260+/// was refused against.
261+///
244 /// Admissible for [`transaction_with_retry`]: every statement is an `UPDATE`,262 /// Admissible for [`transaction_with_retry`]: every statement is an `UPDATE`,
245 /// an `IF`/`THROW` or a `RETURN`, and none of those can answer "already263 /// an `IF`/`THROW` or a `RETURN`, and none of those can answer "already
246 /// exists" — a lost round writes nothing and re-sending it is the recovery.264 /// exists" — a lost round writes nothing and re-sending it is the recovery.
src/domain/homework.rsmodified+310 -47
@@ -27,6 +27,17 @@ use crate::domain::user::UserId;
27 use crate::error::{AppError, ValidationError};27 use crate::error::{AppError, ValidationError};
28 use crate::validate::{validate_optional, validate_required};28 use crate::validate::{validate_optional, validate_required};
29 29
30+/// The answer a link to a subject that is not there gets, on create and on
31+/// re-tag alike — both claims are conditional writes on the subject row, so a
32+/// subject a delete already removed matches nothing and the caller says exactly
33+/// what the web layer's pre-flight lookup would have.
34+fn subject_gone() -> AppError {
35+ AppError::Validation(ValidationError::Invalid {
36+ field: "subject_id",
37+ reason: "subject does not exist",
38+ })
39+}
40+
30 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]41 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
31 pub struct HomeworkId(RecordId);42 pub struct HomeworkId(RecordId);
32 43
@@ -160,20 +171,16 @@ impl Homework {
160 created_by: &UserId,171 created_by: &UserId,
161 db: &Database,172 db: &Database,
162 ) -> Result<Homework, AppError> {173 ) -> Result<Homework, AppError> {
163- // Take the subject's reference before the row exists — the exam174+ // The subject's reference is taken in the very transaction that writes
164- // question's twin ([`crate::domain::exam_question::ExamQuestion`]): the175+ // the row — the exam question's twin
165- // subject delete is refused while this counter is non-zero, so the176+ // ([`crate::domain::exam_question::ExamQuestion`]): the subject delete
166- // create and the delete contend on the subject record rather than on a177+ // is refused while this counter is non-zero, so the create and the
167- // cross-table count neither of them sees the other move. A miss means the178+ // delete contend on the subject record rather than on a cross-table
168- // subject is already gone, which is the 400 the web layer's pre-flight179+ // count neither of them sees the other move, and a crash can no longer
169- // check answers with.180+ // strand a claim that would make the subject undeletable forever. A
181+ // refused claim means the subject is already gone, which is the 400 the
182+ // web layer's pre-flight check answers with.
170 let counted = subject.record();183 let counted = subject.record();
171- if !cap::claim(&counted, SUBJECT_HOMEWORK_COUNT_FIELD, cap::UNLIMITED, db).await? {
172- return Err(AppError::Validation(ValidationError::Invalid {
173- field: "subject_id",
174- reason: "subject does not exist",
175- }));
176- }
177 let homework = Homework {184 let homework = Homework {
178 id: HomeworkId::generate(),185 id: HomeworkId::generate(),
179 course: course.clone(),186 course: course.clone(),
@@ -185,19 +192,20 @@ impl Homework {
185 created_by: created_by.clone(),192 created_by: created_by.clone(),
186 created_at: Timestamp::now(),193 created_at: Timestamp::now(),
187 };194 };
188- let created: Result<Option<Homework>, AppError> = db195+ let id = homework.id.record();
189- .create(homework.id.record())196+ match cap::claim_and_create(
190- .content(homework)197+ &counted,
191- .await198+ SUBJECT_HOMEWORK_COUNT_FIELD,
192- .map_err(AppError::from);199+ cap::UNLIMITED,
193- match created {200+ &id,
194- Ok(Some(homework)) => Ok(homework),201+ &homework,
195- other => {202+ db,
196- // Nothing landed, so the reference goes straight back.203+ )
197- cap::release(&counted, SUBJECT_HOMEWORK_COUNT_FIELD, db).await?;204+ .await?
198- other?;205+ {
199- Err(AppError::Internal("failed to create homework".into()))206+ cap::Claimed::Made(created) => Ok(created),
200- }207+ cap::Claimed::Full => Err(subject_gone()),
208+ cap::Claimed::Duplicate => Err(AppError::Internal("failed to create homework".into())),
201 }209 }
202 }210 }
203 211
@@ -296,35 +304,39 @@ impl Homework {
296 ) -> Result<Homework, AppError> {304 ) -> Result<Homework, AppError> {
297 let assigned = assigned305 let assigned = assigned
298 .map(|subset| subset.map(|users| users.iter().map(UserId::record).collect::<Vec<_>>()));306 .map(|subset| subset.map(|users| users.iter().map(UserId::record).collect::<Vec<_>>()));
299- // A re-tag moves a reference: claim the new subject before the write,307+ // A re-tag moves a reference: the new subject's claim and the old one's
300- // release the old only after it lands, so neither is ever308+ // release ride the same transaction as the link write, so no crash can
301- // under-counted (the direction that would let a subject this homework309+ // leave a count without its link (the subject would be undeletable
302- // points at be deleted). Same shape as the exam question's re-tag.310+ // forever) or a link without its count. `subject` is required, so the
303- let retag = subject311+ // snapshot's value is always the CAS expectation — two PATCHes moving
312+ // the same homework off the same subject would otherwise both claim
313+ // their target, and the loser is refused with a 409 instead. The
314+ // `.refcount` call is unconditional: the CAS is armed by the request
315+ // *carrying* `subject_id`, not by a counter moving, so a PATCH that
316+ // re-states the tag its snapshot showed — shifting no counter at all —
317+ // is still refused when a rival moved the tag in between. A PATCH that
318+ // carried no `subject_id` arms nothing and writes what it always did.
319+ let (claim, release) = subject
304 .as_ref()320 .as_ref()
305 .filter(|next| **next != self.subject)321 .filter(|next| **next != self.subject)
306- .map(|next| (next.record(), self.subject.record()));322+ .map(|next| (next.record(), self.subject.record()))
307- if let Some((next, _)) = &retag323+ .unzip();
308- && !cap::claim(next, SUBJECT_HOMEWORK_COUNT_FIELD, cap::UNLIMITED, db).await?324+ FieldUpdate::new(self.id.record())
309- {
310- return Err(AppError::Validation(ValidationError::Invalid {
311- field: "subject_id",
312- reason: "subject does not exist",
313- }));
314- }
315- let written = FieldUpdate::new(self.id.record())
316 .set("subject", subject.map(|subject| subject.record()))325 .set("subject", subject.map(|subject| subject.record()))
317 .set("title", title)326 .set("title", title)
318 .set("description", description)327 .set("description", description)
319 .set("due_at", due_at)328 .set("due_at", due_at)
320 .set("assigned", assigned)329 .set("assigned", assigned)
330+ .refcount(
331+ SUBJECT_HOMEWORK_COUNT_FIELD,
332+ "subject",
333+ Some(self.subject.record()),
334+ claim,
335+ release,
336+ subject_gone(),
337+ )
321 .run::<Homework>(db)338 .run::<Homework>(db)
322- .await;339+ .await
323- if let Some((next, previous)) = &retag {
324- let give_back = if written.is_ok() { previous } else { next };
325- cap::release(give_back, SUBJECT_HOMEWORK_COUNT_FIELD, db).await?;
326- }
327- written
328 }340 }
329 341
330 /// Delete the homework and cascade its submissions, their files, and its342 /// Delete the homework and cascade its submissions, their files, and its
@@ -399,4 +411,255 @@ mod tests {
399 assert!(with(Some(vec![a.clone()])).student_sees(&a));411 assert!(with(Some(vec![a.clone()])).student_sees(&a));
400 assert!(!with(Some(vec![a.clone()])).student_sees(&b));412 assert!(!with(Some(vec![a.clone()])).student_sees(&b));
401 }413 }
414+
415+ use crate::domain::subject::{Subject, SubjectDescription, SubjectName};
416+
417+ async fn a_subject(name: &str, db: &Database) -> Subject {
418+ Subject::create(
419+ &CourseId::from_key("course"),
420+ SubjectName::try_new(name).unwrap(),
421+ SubjectDescription::try_new("").unwrap(),
422+ db,
423+ )
424+ .await
425+ .unwrap()
426+ }
427+
428+ async fn homework_on(subject: &SubjectId, db: &Database) -> Homework {
429+ Homework::create(
430+ &CourseId::from_key("course"),
431+ subject,
432+ HomeworkTitle::try_new("essay").unwrap(),
433+ None,
434+ Timestamp::from_millis(1),
435+ None,
436+ &UserId::from_key("teacher"),
437+ db,
438+ )
439+ .await
440+ .unwrap()
441+ }
442+
443+ /// The stored `homework_count` on one subject, absent counting as zero.
444+ async fn count_on(subject: &SubjectId, db: &Database) -> i64 {
445+ let mut result = db
446+ .query(format!(
447+ "SELECT VALUE ({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) FROM $sub"
448+ ))
449+ .bind(("sub", subject.record()))
450+ .await
451+ .unwrap()
452+ .check()
453+ .unwrap();
454+ result
455+ .take::<Vec<i64>>(0)
456+ .unwrap()
457+ .first()
458+ .copied()
459+ .unwrap_or(0)
460+ }
461+
462+ /// How many rows `sql` selects ids for.
463+ async fn rows(sql: &str, db: &Database) -> usize {
464+ let mut result = db.query(sql).await.unwrap().check().unwrap();
465+ result.take::<Vec<RecordId>>(0).unwrap().len()
466+ }
467+
468+ /// The invariant on the create path: the claim and the row it accounts for
469+ /// commit together or not at all. A refused create leaves *neither* — no
470+ /// homework row, and no count stranded on a subject (the subject's delete
471+ /// guard reads that count, so a stray one makes it undeletable forever).
472+ #[tokio::test]
473+ async fn a_refused_create_writes_neither_row_nor_count() {
474+ let db = crate::database::init_mem().await.unwrap();
475+ let subject = a_subject("algebra", &db).await;
476+ let id = subject.get_id().clone();
477+ subject.delete(&db).await.unwrap();
478+
479+ let error = Homework::create(
480+ &CourseId::from_key("course"),
481+ &id,
482+ HomeworkTitle::try_new("essay").unwrap(),
483+ None,
484+ Timestamp::from_millis(1),
485+ None,
486+ &UserId::from_key("teacher"),
487+ &db,
488+ )
489+ .await
490+ .expect_err("a subject that is gone must not be taggable");
491+ assert!(error.to_string().contains("subject does not exist"));
492+ assert_eq!(
493+ rows("SELECT VALUE id FROM homework", &db).await,
494+ 0,
495+ "a refused create may write no row"
496+ );
497+ assert_eq!(
498+ rows("SELECT VALUE id FROM subject", &db).await,
499+ 0,
500+ "…and least of all a count on a subject it just brought back"
501+ );
502+ }
503+
504+ /// The invariant on the PATCH path: a re-tag carries the new subject's
505+ /// claim and the old one's release with the link itself.
506+ #[tokio::test]
507+ async fn a_subject_move_moves_the_count() {
508+ let db = crate::database::init_mem().await.unwrap();
509+ let from = a_subject("algebra", &db).await;
510+ let to = a_subject("geometry", &db).await;
511+ let homework = homework_on(from.get_id(), &db).await;
512+ assert_eq!(count_on(from.get_id(), &db).await, 1);
513+
514+ let moved = homework
515+ .update(Some(to.get_id().clone()), None, None, None, None, &db)
516+ .await
517+ .unwrap();
518+ assert_eq!(moved.get_subject(), to.get_id());
519+ assert_eq!(
520+ count_on(from.get_id(), &db).await,
521+ 0,
522+ "the old subject is free"
523+ );
524+ assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not");
525+ assert!(from.delete(&db).await.is_ok(), "no reference left");
526+ assert!(
527+ to.delete(&db).await.is_err(),
528+ "the reference moved here refuses the delete"
529+ );
530+ }
531+
532+ /// The claim throws inside the same transaction as the link write, so a
533+ /// move onto a subject that is gone rolls the release back with it: the row
534+ /// keeps its tag and both counters read as if nothing ran.
535+ #[tokio::test]
536+ async fn a_move_to_a_dead_subject_leaves_everything_untouched() {
537+ let db = crate::database::init_mem().await.unwrap();
538+ let from = a_subject("algebra", &db).await;
539+ let dead = a_subject("geometry", &db).await;
540+ let gone = dead.get_id().clone();
541+ dead.delete(&db).await.unwrap();
542+ let homework = homework_on(from.get_id(), &db).await;
543+
544+ let error = homework
545+ .clone()
546+ .update(Some(gone.clone()), None, None, None, None, &db)
547+ .await
548+ .expect_err("a subject that is gone must not be taggable");
549+ assert!(error.to_string().contains("subject does not exist"));
550+ let stored = Homework::read(homework.get_id(), &db)
551+ .await
552+ .unwrap()
553+ .unwrap();
554+ assert_eq!(stored.get_subject(), from.get_id(), "the tag never moved");
555+ assert_eq!(
556+ count_on(from.get_id(), &db).await,
557+ 1,
558+ "the release rolled back with the claim"
559+ );
560+ assert_eq!(
561+ rows("SELECT VALUE id FROM subject", &db).await,
562+ 1,
563+ "the dead subject was not brought back by a count"
564+ );
565+ assert_eq!(count_on(&gone, &db).await, 0);
566+ }
567+
568+ /// The double-claim guard. Both movers compute their claim and release from
569+ /// the row as *they* read it, so two PATCHes re-tagging the same homework
570+ /// off the same subject both release it and both claim their target — two
571+ /// counts for one link, and the loser's target is undeletable forever. The
572+ /// second call here runs on the struct read before the first one landed,
573+ /// which is that race with the interleaving pinned: it must be refused
574+ /// outright, and the counts must read as if it never ran.
575+ #[tokio::test]
576+ async fn a_stale_mover_is_refused_and_claims_nothing() {
577+ let db = crate::database::init_mem().await.unwrap();
578+ let from = a_subject("algebra", &db).await;
579+ let to = a_subject("geometry", &db).await;
580+ let other = a_subject("calculus", &db).await;
581+ let homework = homework_on(from.get_id(), &db).await;
582+ let stale = homework.clone();
583+ homework
584+ .update(Some(to.get_id().clone()), None, None, None, None, &db)
585+ .await
586+ .unwrap();
587+
588+ let error = stale
589+ .clone()
590+ .update(Some(other.get_id().clone()), None, None, None, None, &db)
591+ .await
592+ .expect_err("a mover that read a tag it no longer holds must be refused");
593+ assert!(
594+ matches!(error, AppError::Conflict(_)),
595+ "a lost CAS is a conflict, not a 404 or a 500: {error:?}"
596+ );
597+ let stored = Homework::read(stale.get_id(), &db).await.unwrap().unwrap();
598+ assert_eq!(stored.get_subject(), to.get_id(), "the winner's tag");
599+ assert_eq!(
600+ count_on(from.get_id(), &db).await,
601+ 0,
602+ "released once, not twice"
603+ );
604+ assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once");
605+ assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed");
606+ }
607+
608+ /// The same race with the counters taken out of it. A PATCH that re-states
609+ /// the subject its snapshot showed shifts *nothing* — no claim and no
610+ /// release — so if the guard were armed off the counter move it would not be
611+ /// armed here at all, and the write would land: the winner's tag silently
612+ /// dragged back, its claim stranded on a subject nothing points at
613+ /// (undeletable forever) and the reverted-to subject tagged at a count of
614+ /// zero (deletable while tagged). The guard is armed by the request
615+ /// *carrying* the column instead, which is why this is refused.
616+ #[tokio::test]
617+ async fn a_stale_re_stater_is_refused_and_reverts_nothing() {
618+ let db = crate::database::init_mem().await.unwrap();
619+ let from = a_subject("algebra", &db).await;
620+ let to = a_subject("geometry", &db).await;
621+ let homework = homework_on(from.get_id(), &db).await;
622+ let stale = homework.clone();
623+ homework
624+ .update(Some(to.get_id().clone()), None, None, None, None, &db)
625+ .await
626+ .unwrap();
627+
628+ let error = stale
629+ .clone()
630+ .update(Some(from.get_id().clone()), None, None, None, None, &db)
631+ .await
632+ .expect_err("re-stating a tag someone else moved must be refused");
633+ assert!(
634+ matches!(error, AppError::Conflict(_)),
635+ "a lost CAS is a conflict, not a silent 200: {error:?}"
636+ );
637+ let stored = Homework::read(stale.get_id(), &db).await.unwrap().unwrap();
638+ assert_eq!(stored.get_subject(), to.get_id(), "the winner's tag");
639+ assert_eq!(
640+ count_on(from.get_id(), &db).await,
641+ 0,
642+ "the reverted-to subject must not end up tagged at zero"
643+ );
644+ assert_eq!(
645+ count_on(to.get_id(), &db).await,
646+ 1,
647+ "…nor the winner's subject counted with nothing pointing at it"
648+ );
649+
650+ // A *genuine* no-op re-state — nobody moved underneath it — still lands,
651+ // and still moves no counter: the CAS passes trivially.
652+ let fresh = Homework::read(stale.get_id(), &db).await.unwrap().unwrap();
653+ let same = fresh
654+ .update(Some(to.get_id().clone()), None, None, None, None, &db)
655+ .await
656+ .expect("re-stating the tag actually held is not a race");
657+ assert_eq!(same.get_subject(), to.get_id());
658+ assert_eq!(
659+ count_on(from.get_id(), &db).await,
660+ 0,
661+ "still no counter move"
662+ );
663+ assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once, still");
664+ }
402 }665 }
src/domain/homework_file.rsmodified+58 -29
@@ -124,42 +124,38 @@ impl HomeworkFile {
124 /// Persist the row assembled by [`Self::new`], refusing once its submission124 /// Persist the row assembled by [`Self::new`], refusing once its submission
125 /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`)125 /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`)
126 /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own126 /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own
127- /// wording). Both are decided by one [`cap::claim_when`] on the submission127+ /// wording). Both are decided by one [`cap::claim_when_and_create`] on the
128- /// row — a conditional single-record write, the only guard that holds when128+ /// submission row — the seat and the file row commit together, so a crash
129- /// two uploads race, the same story as129+ /// between them can no longer leave a slot claimed by a file that does not
130- /// `NoteFile::insert`. Which of the two conditions failed is read back130+ /// exist, and a losing upload never has to be un-counted. Which of the two
131- /// afterwards, off the losing path only, and only to pick the message.131+ /// conditions refused it is read back afterwards, off the losing path only,
132+ /// and only to pick the message: `Claimed::Full` says "full *or* graded *or*
133+ /// the submission is gone".
132 pub async fn insert(self, db: &Database) -> Result<Option<HomeworkFile>, AppError> {134 pub async fn insert(self, db: &Database) -> Result<Option<HomeworkFile>, AppError> {
133- let submission = self.submission.record();135+ // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber
134- if !cap::claim_when(136+ match cap::claim_when_and_create(
135- &submission,137+ &self.submission.record(),
136 SUBMISSION_FILE_COUNT_FIELD,138 SUBMISSION_FILE_COUNT_FIELD,
137 MAX_HOMEWORK_FILES_PER_SUBMISSION as i64,139 MAX_HOMEWORK_FILES_PER_SUBMISSION as i64,
138 SUBMISSION_OPEN_GUARD,140 SUBMISSION_OPEN_GUARD,
141+ &self.id.record(),
142+ &self,
139 db,143 db,
140 )144 )
141 .await?145 .await?
142 {146 {
143- if HomeworkSubmission::is_graded(&self.submission, db).await? {147+ cap::Claimed::Made(created) => Ok(Some(created)),
144- return Ok(None);148+ cap::Claimed::Full => {
145- }149+ if HomeworkSubmission::is_graded(&self.submission, db).await? {
146- return Err(AppError::Conflict(150+ return Ok(None);
147- "the submission already holds the maximum of 10 files — delete one first",151+ }
148- ));152+ Err(AppError::Conflict(
149- }153+ "the submission already holds the maximum of 10 files — delete one first",
150- // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber154+ ))
151- let created: Result<Option<HomeworkFile>, _> =
152- db.create(self.id.record()).content(self).await;
153- match created {
154- Ok(Some(created)) => Ok(Some(created)),
155- Ok(None) => {
156- cap::release(&submission, SUBMISSION_FILE_COUNT_FIELD, db).await?;
157- Err(AppError::Internal("failed to create homework file".into()))
158- }
159- Err(err) => {
160- cap::release(&submission, SUBMISSION_FILE_COUNT_FIELD, db).await?;
161- Err(err.into())
162 }155 }
156+ // The id is a fresh ULID minted by `new`, so a row already holding it
157+ // is a collision, not a re-upload.
158+ cap::Claimed::Duplicate => Err(AppError::Internal("homework file id collided".into())),
163 }159 }
164 }160 }
165 161
@@ -317,6 +313,20 @@ mod tests {
317 )313 )
318 }314 }
319 315
316+ /// The counter as *stored* — the only witness that the seat and the row
317+ /// moved together, since every other read counts the rows themselves.
318+ async fn stored_count(submission: &HomeworkSubmissionId, db: &Database) -> i64 {
319+ db.query("SELECT VALUE file_count FROM $sub")
320+ .bind(("sub", submission.record()))
321+ .await
322+ .unwrap()
323+ .take::<Vec<i64>>(0)
324+ .unwrap()
325+ .into_iter()
326+ .next()
327+ .unwrap_or(0)
328+ }
329+
320 #[tokio::test]330 #[tokio::test]
321 async fn rows_scope_to_their_submission_gc_and_cap() {331 async fn rows_scope_to_their_submission_gc_and_cap() {
322 let db = crate::database::init_mem().await.unwrap();332 let db = crate::database::init_mem().await.unwrap();
@@ -353,6 +363,11 @@ mod tests {
353 .unwrap(),363 .unwrap(),
354 1364 1
355 );365 );
366+ assert_eq!(
367+ stored_count(&sub_a, &db).await,
368+ 1,
369+ "the seat rode with the row"
370+ );
356 371
357 // The grader's download scoping: found under its own homework, invisible372 // The grader's download scoping: found under its own homework, invisible
358 // under another — so a teacher can't read it by naming a homework they373 // under another — so a teacher can't read it by naming a homework they
@@ -388,6 +403,17 @@ mod tests {
388 a_file(&sub_a).insert(&db).await,403 a_file(&sub_a).insert(&db).await,
389 Err(AppError::Conflict(_))404 Err(AppError::Conflict(_))
390 ));405 ));
406+ // The refusal wrote nothing at all: neither a row nor a seat.
407+ assert_eq!(
408+ HomeworkFile::count_for_submission(&sub_a, &db)
409+ .await
410+ .unwrap() as i64,
411+ stored_count(&sub_a, &db).await,
412+ );
413+ assert_eq!(
414+ stored_count(&sub_a, &db).await,
415+ MAX_HOMEWORK_FILES_PER_SUBMISSION as i64
416+ );
391 }417 }
392 418
393 /// A graded submission takes no more files and gives none up — decided by419 /// A graded submission takes no more files and gives none up — decided by
@@ -395,8 +421,8 @@ mod tests {
395 /// `homework_result` read stands between the check and the write.421 /// `homework_result` read stands between the check and the write.
396 ///422 ///
397 /// Bite check: drop [`SUBMISSION_OPEN_GUARD`] from `insert`'s423 /// Bite check: drop [`SUBMISSION_OPEN_GUARD`] from `insert`'s
398- /// [`cap::claim_when`] and the add below lands; drop it from `delete`'s gate424+ /// [`cap::claim_when_and_create`] and the add below lands; drop it from
399- /// and the delete below succeeds.425+ /// `delete`'s gate and the delete below succeeds.
400 #[tokio::test]426 #[tokio::test]
401 async fn a_grade_freezes_the_files_too() {427 async fn a_grade_freezes_the_files_too() {
402 use crate::domain::homework_result::{HomeworkResult, HomeworkStatus};428 use crate::domain::homework_result::{HomeworkResult, HomeworkStatus};
@@ -431,6 +457,9 @@ mod tests {
431 1,457 1,
432 "the graded submission keeps exactly the files it was graded on"458 "the graded submission keeps exactly the files it was graded on"
433 );459 );
460+ // Refused by the *guard*, not the cap (nine seats free) — and still no
461+ // seat moved, so the counter matches the rows.
462+ assert_eq!(stored_count(&sub, &db).await, 1);
434 // The refused add took no slot either, so un-grading gives back a463 // The refused add took no slot either, so un-grading gives back a
435 // submission with room, not one that silently lost nine.464 // submission with room, not one that silently lost nine.
436 HomeworkResult::remove(&homework, &user, &db).await.unwrap();465 HomeworkResult::remove(&homework, &user, &db).await.unwrap();
src/domain/menu.rsmodified+211 -35
@@ -14,9 +14,10 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
14 use tokio::sync::Mutex;14 use tokio::sync::Mutex;
15 15
16 use crate::constant::{16 use crate::constant::{
17- MAX_MENU_CAPACITY, MENU_SEAT_COUNT_FIELD, MENU_TABLE, MENU_VERSION_FIELD, SLOT_REF_TABLE,17+ MAX_MENU_CAPACITY, MENU_SEAT_COUNT_FIELD, MENU_TABLE, MENU_VERSION_FIELD, REF_COUNT_FIELD,
18+ SLOT_REF_TABLE,
18 };19 };
19-use crate::database::{Database, lost_the_race};20+use crate::database::{Database, transaction_with_retry};
20 use crate::domain::cap;21 use crate::domain::cap;
21 use crate::domain::field_update::FieldUpdate;22 use crate::domain::field_update::FieldUpdate;
22 use crate::domain::menu_dish::MenuDish;23 use crate::domain::menu_dish::MenuDish;
@@ -228,15 +229,11 @@ impl Menu {
228 }229 }
229 // The menu takes a reference on its slot, which is what stops the slot230 // The menu takes a reference on its slot, which is what stops the slot
230 // being dropped from the settings while this menu (whose slot is only231 // being dropped from the settings while this menu (whose slot is only
231- // snapshotted text) still points at it. Claimed before the write and232+ // snapshotted text) still points at it. Claimed *inside* the write's own
232- // given back if the write does not land, exactly like a seat.233+ // transaction: a claim of its own could land and the row then fail to,
234+ // leaving the slot counted by a menu that does not exist — a slot
235+ // nobody can ever retire, and no crash window is small enough for that.
233 let counter = slot_ref(slot.as_str());236 let counter = slot_ref(slot.as_str());
234- if !cap::claim_ref(&counter, 1, db).await? {
235- return Err(AppError::ConflictOwned(format!(
236- "the '{}' meal slot has been removed from the school's settings",
237- slot.as_str()
238- )));
239- }
240 let menu = Menu {237 let menu = Menu {
241 id: MenuId::for_slot(&date, &slot),238 id: MenuId::for_slot(&date, &slot),
242 date,239 date,
@@ -246,19 +243,14 @@ impl Menu {
246 created_by: created_by.clone(),243 created_by: created_by.clone(),
247 created_at: Timestamp::now(),244 created_at: Timestamp::now(),
248 };245 };
249- match db.create(menu.id.record()).content(menu).await {246+ let id = menu.id.record();
250- Ok(Some(created)) => Ok(created),247+ match cap::claim_ref_and_create(&counter, 1, &id, &menu, db).await? {
251- Ok(None) => {248+ cap::ClaimedRef::Made(created) => Ok(created),
252- cap::release_ref(&counter, 1, db).await?;249+ cap::ClaimedRef::Duplicate => Err(taken),
253- Err(AppError::Internal("failed to publish the menu".into()))250+ cap::ClaimedRef::Retired => Err(AppError::ConflictOwned(format!(
254- }251+ "the '{}' meal slot has been removed from the school's settings",
255- Err(err) => {252+ menu.slot.as_str()
256- cap::release_ref(&counter, 1, db).await?;253+ ))),
257- match lost_the_race(&err) {
258- true => Err(taken),
259- false => Err(err.into()),
260- }
261- }
262 }254 }
263 }255 }
264 256
@@ -332,17 +324,44 @@ impl Menu {
332 /// (and finds no menu). A read-then-delete pair had a window where both324 /// (and finds no menu). A read-then-delete pair had a window where both
333 /// happened — a paid seat on a menu that no longer exists.325 /// happened — a paid seat on a menu that no longer exists.
334 ///326 ///
327+ /// The slot gets its reference back in that same transaction — a slot no
328+ /// menu is published for any more may leave the settings again, and the
329+ /// `FOR` runs only over a row the guard actually took. Released afterwards
330+ /// in a query of its own, a crash between the two left the slot counted by
331+ /// a menu that no longer exists: a slot nobody can retire.
332+ ///
335 /// The dishes go *after* the row: their cascade must not run for a delete333 /// The dishes go *after* the row: their cascade must not run for a delete
336 /// the counter refused.334 /// the counter refused.
337 pub async fn delete(self, db: &Database) -> Result<Menu, AppError> {335 pub async fn delete(self, db: &Database) -> Result<Menu, AppError> {
338- let mut result = db336+ let sql = format!(
339- .query(format!(337+ "BEGIN TRANSACTION;
340- "DELETE $id WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE"338+ LET $gone = (DELETE $id WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE);
341- ))339+ FOR $row IN ($gone ?? []) {{
342- .bind(("id", self.id.record()))340+ UPSERT $counter SET {REF_COUNT_FIELD} = \
343- .await?341+ math::max([({REF_COUNT_FIELD} ?? 0) - 1, 0]);
344- .check()?;342+ }};
345- let Some(deleted) = result.take::<Vec<Menu>>(0)?.into_iter().next() else {343+ RETURN $gone;
344+ COMMIT TRANSACTION;"
345+ );
346+ // `slot` is a `READONLY` column, so this counter is the one the deleted
347+ // row carries. Nothing here can answer "already exists" — the `UPSERT`
348+ // is keyed by a slot name on a table with no `UNIQUE` index, so it
349+ // resolves onto the row it names ([`transaction_with_retry`]).
350+ let (mut result, mut errors) = transaction_with_retry(
351+ db,
352+ &sql,
353+ &[
354+ ("id".into(), self.id.record().into_value()),
355+ ("counter".into(), slot_ref(self.slot.as_str()).into_value()),
356+ ],
357+ &[],
358+ )
359+ .await?;
360+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
361+ return Err(error.into());
362+ }
363+ // BEGIN, the LET and the FOR take a slot each.
364+ let Some(deleted) = result.take::<Vec<Menu>>(3)?.into_iter().next() else {
346 // Nothing back: either seats are held, or the menu is already gone.365 // Nothing back: either seats are held, or the menu is already gone.
347 return Err(match Self::read(&self.id, db).await? {366 return Err(match Self::read(&self.id, db).await? {
348 Some(_) => AppError::Conflict("the menu still has live bookings"),367 Some(_) => AppError::Conflict("the menu still has live bookings"),
@@ -350,10 +369,6 @@ impl Menu {
350 });369 });
351 };370 };
352 MenuDish::delete_for_menu(&self.id, db).await?;371 MenuDish::delete_for_menu(&self.id, db).await?;
353- // The slot gets its reference back — a slot no menu is published for
354- // any more may leave the settings again. After the delete, so a crash
355- // over-counts (refusing a removal) rather than under-counts.
356- cap::release_ref(&slot_ref(deleted.slot.as_str()), 1, db).await?;
357 Ok(deleted)372 Ok(deleted)
358 }373 }
359 }374 }
@@ -396,4 +411,165 @@ mod tests {
396 assert!(validate_capacity(Some(-1)).is_err());411 assert!(validate_capacity(Some(-1)).is_err());
397 assert!(validate_capacity(Some(MAX_MENU_CAPACITY + 1)).is_err());412 assert!(validate_capacity(Some(MAX_MENU_CAPACITY + 1)).is_err());
398 }413 }
414+
415+ // --- the slot reference and the menu row move together ---------------
416+
417+ async fn school() -> Database {
418+ let db = crate::database::init_mem().await.unwrap();
419+ db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';")
420+ .await
421+ .unwrap()
422+ .check()
423+ .unwrap();
424+ db
425+ }
426+
427+ fn lunch() -> MenuSlot {
428+ MenuSlot::try_new("lunch", &[MealSlotDef::try_new("lunch", None).unwrap()]).unwrap()
429+ }
430+
431+ /// The reference count, re-read out of the store — never off a return
432+ /// value, which the in-memory engine forges wins on.
433+ async fn refs(db: &Database) -> i64 {
434+ let mut result = db
435+ .query("SELECT VALUE (count ?? 0) FROM $id")
436+ .bind(("id", slot_ref("lunch")))
437+ .await
438+ .unwrap()
439+ .check()
440+ .unwrap();
441+ result
442+ .take::<Vec<i64>>(0)
443+ .unwrap()
444+ .into_iter()
445+ .next()
446+ .unwrap_or(0)
447+ }
448+
449+ async fn publish(date: &str, db: &Database) -> Result<Menu, AppError> {
450+ Menu::create(
451+ MenuDate::try_new(date).unwrap(),
452+ lunch(),
453+ None,
454+ &UserId::from_key("teacher"),
455+ db,
456+ )
457+ .await
458+ }
459+
460+ /// Plant a menu row the pre-check will (or will not) find, without going
461+ /// through the claim — a row published before the counter existed.
462+ async fn plant(id: &MenuId, date: &str, db: &Database) {
463+ db.query(
464+ "CREATE $id SET date = $date, slot = 'lunch', \
465+ created_by = user:teacher, created_at = 1",
466+ )
467+ .bind(("id", id.record()))
468+ .bind(("date", date.to_string()))
469+ .await
470+ .unwrap()
471+ .check()
472+ .unwrap();
473+ }
474+
475+ #[tokio::test]
476+ async fn publishing_lands_the_menu_and_its_reference_together() {
477+ let db = school().await;
478+ let menu = publish("2026-08-02", &db).await.unwrap();
479+ assert!(Menu::read(menu.get_id(), &db).await.unwrap().is_some());
480+ assert_eq!(refs(&db).await, 1);
481+
482+ // The day+slot pre-check answers the second publish — and a refusal
483+ // may not count the slot, or the menu would outlive its own reference.
484+ let again = publish("2026-08-02", &db)
485+ .await
486+ .expect_err("that day and slot are taken");
487+ assert!(matches!(again, AppError::Conflict(_)), "got {again:?}");
488+ assert_eq!(refs(&db).await, 1);
489+ }
490+
491+ #[tokio::test]
492+ async fn a_retired_slot_refuses_and_writes_nothing() {
493+ let db = school().await;
494+ assert!(cap::retire(&slot_ref("lunch"), &db).await.unwrap());
495+
496+ let refused = publish("2026-08-02", &db)
497+ .await
498+ .expect_err("the slot left the settings");
499+ assert!(
500+ matches!(refused, AppError::ConflictOwned(_)),
501+ "got {refused:?}"
502+ );
503+ assert_eq!(refs(&db).await, 0);
504+ assert!(
505+ Menu::find(&MenuDate::try_new("2026-08-02").unwrap(), &lunch(), &db)
506+ .await
507+ .unwrap()
508+ .is_none()
509+ );
510+ }
511+
512+ /// The race the fold exists for: a rival places the very row this publish
513+ /// is placing, between the pre-check and the write. Only the claim's own
514+ /// gate can answer it, and its answer must cost no reference.
515+ #[tokio::test]
516+ async fn a_rival_on_the_id_answers_taken_and_counts_nothing() {
517+ let db = school().await;
518+ let id = MenuId::for_slot(&MenuDate::try_new("2026-08-02").unwrap(), &lunch());
519+ // Planted under another day, so `find` misses it exactly as it would
520+ // in the instant before the rival's own row was visible.
521+ plant(&id, "1999-01-01", &db).await;
522+
523+ let taken = publish("2026-08-02", &db)
524+ .await
525+ .expect_err("the id is taken");
526+ assert!(matches!(taken, AppError::Conflict(_)), "got {taken:?}");
527+ assert_eq!(refs(&db).await, 0);
528+ }
529+
530+ /// Menus published before ids were derived keep a ULID key a new publish
531+ /// cannot collide with, so the pre-check is the only thing that can refuse.
532+ #[tokio::test]
533+ async fn a_legacy_ulid_menu_still_answers_taken() {
534+ let db = school().await;
535+ plant(&MenuId::from_key("01JLEGACYMENU"), "2026-08-02", &db).await;
536+
537+ let taken = publish("2026-08-02", &db)
538+ .await
539+ .expect_err("that day and slot are taken");
540+ assert!(matches!(taken, AppError::Conflict(_)), "got {taken:?}");
541+ assert_eq!(refs(&db).await, 0);
542+ }
543+
544+ #[tokio::test]
545+ async fn deleting_hands_the_reference_back_in_the_same_step() {
546+ let db = school().await;
547+ let monday = publish("2026-08-03", &db).await.unwrap();
548+ publish("2026-08-04", &db).await.unwrap();
549+ assert_eq!(refs(&db).await, 2);
550+
551+ let id = monday.get_id().clone();
552+ let ghost = monday.clone();
553+ monday.delete(&db).await.unwrap();
554+ assert!(Menu::read(&id, &db).await.unwrap().is_none());
555+ assert_eq!(refs(&db).await, 1, "the row and its reference go together");
556+
557+ // Deleting what is already gone hands nothing back: a second release
558+ // would leave a slot one menu still uses free to be retired.
559+ let gone = ghost.delete(&db).await.expect_err("already deleted");
560+ assert!(matches!(gone, AppError::NotFound), "got {gone:?}");
561+ assert_eq!(refs(&db).await, 1);
562+ assert!(
563+ !cap::retire(&slot_ref("lunch"), &db).await.unwrap(),
564+ "a slot a menu is still published for may not be retired"
565+ );
566+
567+ // …and once the last menu goes, it may.
568+ let last = Menu::find(&MenuDate::try_new("2026-08-04").unwrap(), &lunch(), &db)
569+ .await
570+ .unwrap()
571+ .unwrap();
572+ last.delete(&db).await.unwrap();
573+ assert_eq!(refs(&db).await, 0);
574+ }
399 }575 }