forge
Explore
Log in

Don't you dare go Hollow

🔩 claim term refcounts inside the row transaction

Browse files at this commit

324b078f596e68b1536b9401c310f0faad2b4179Ahmet Kaan GümüşParent: 0c7403b
  • fix
    • 🔩 claim term refcounts inside the row transaction
Show full message
fix: 🔩 claim term refcounts inside the row transaction
src/domain/cap.rsmodified+8 -0
@@ -53,6 +53,14 @@ use crate::error::AppError;
53 // only about how many writes a process has in flight.53 // only about how many writes a process has in flight.
54 static CLAIM_LOCK: Mutex<()> = Mutex::const_new(());54 static CLAIM_LOCK: Mutex<()> = Mutex::const_new(());
55 55
56+/// [`CLAIM_LOCK`], for a counter write that rides someone else's transaction
57+/// instead of [`write`]'s — [`crate::domain::field_update::FieldUpdate`]'s term
58+/// move claims and releases inside the very `UPDATE`'s transaction, and still
59+/// owes the process one counter write at a time.
60+pub(crate) async fn counter_lock() -> tokio::sync::MutexGuard<'static, ()> {
61+ CLAIM_LOCK.lock().await
62+}
63+
56 /// "No cap" as a number, so the guard stays one comparison instead of a64 /// "No cap" as a number, so the guard stays one comparison instead of a
57 /// nullable branch: `NONE`/`NULL` bind ambiguity is a worse trade than a65 /// nullable branch: `NONE`/`NULL` bind ambiguity is a worse trade than a
58 /// sentinel no roster will ever reach.66 /// sentinel no roster will ever reach.
src/domain/class_group.rsmodified+136 -67
@@ -21,7 +21,7 @@ use crate::domain::cap;
21 use crate::domain::field_update::FieldUpdate;21 use crate::domain::field_update::FieldUpdate;
22 use crate::domain::monotonic_id::next_ulid;22 use crate::domain::monotonic_id::next_ulid;
23 use crate::domain::page::PagedList;23 use crate::domain::page::PagedList;
24-use crate::domain::term::TermId;24+use crate::domain::term::{self, TermId};
25 use crate::domain::user::UserId;25 use crate::domain::user::UserId;
26 use crate::error::{AppError, ValidationError};26 use crate::error::{AppError, ValidationError};
27 use crate::validate::{validate_optional, validate_required};27 use crate::validate::{validate_optional, validate_required};
@@ -122,10 +122,12 @@ impl ClassGroup {
122 &self.creator == user122 &self.creator == user
123 }123 }
124 124
125- /// Create the class, claiming a reference on the term it links (if any)125+ /// Create the class, claiming a reference on the term it links (if any) in
126- /// *before* the row is written: the claim is a conditional write on the term126+ /// the *same transaction* as the row, exactly as
127- /// row, so it fails when the term is already gone and it makes the term127+ /// [`crate::domain::course::Course::create`] does: the claim is a
128- /// undeletable the instant this link exists.128+ /// conditional write on the term row, so it fails when the term is already
129+ /// gone, it makes the term undeletable the instant this link exists, and no
130+ /// crash can leave either half without the other.
129 pub async fn create(131 pub async fn create(
130 creator: &UserId,132 creator: &UserId,
131 name: ClassName,133 name: ClassName,
@@ -133,10 +135,6 @@ impl ClassGroup {
133 term: Option<TermId>,135 term: Option<TermId>,
134 db: &Database,136 db: &Database,
135 ) -> Result<ClassGroup, AppError> {137 ) -> Result<ClassGroup, AppError> {
136- if let Some(term) = &term {
137- claim_term(term, db).await?;
138- }
139- let claimed = term.clone();
140 let class = ClassGroup {138 let class = ClassGroup {
141 id: ClassGroupId::generate(),139 id: ClassGroupId::generate(),
142 creator: creator.clone(),140 creator: creator.clone(),
@@ -144,20 +142,27 @@ impl ClassGroup {
144 grade,142 grade,
145 term,143 term,
146 };144 };
147- let created: Result<Option<ClassGroup>, _> =145+ let id = class.id.record();
148- db.create(class.id.record()).content(class).await;146+ let Some(term) = class.term.clone() else {
149- match created {147+ let created: Option<ClassGroup> = db.create(id).content(class).await?;
150- Ok(Some(created)) => Ok(created),148+ return created.ok_or_else(|| AppError::Internal("failed to create class".into()));
151- other => {149+ };
152- // The link never landed, so the reference has to go back.150+ match cap::claim_and_create(
153- if let Some(term) = &claimed {151+ &term.record(),
154- cap::release(&term.record(), TERM_CLASS_COUNT_FIELD, db).await?;152+ TERM_CLASS_COUNT_FIELD,
155- }153+ cap::UNLIMITED,
156- match other {154+ &id,
157- Err(err) => Err(err.into()),155+ &class,
158- _ => Err(AppError::Internal("failed to create class".into())),156+ db,
159- }157+ )
160- }158+ .await?
159+ {
160+ cap::Claimed::Made(created) => Ok(created),
161+ // Uncapped, so "full" can only mean the conditional write matched no
162+ // term row at all — the claim doubles as the existence check.
163+ cap::Claimed::Full => Err(term::gone_error()),
164+ // Unreachable: the id is a ULID this call just generated.
165+ cap::Claimed::Duplicate => Err(AppError::Internal("failed to create class".into())),
161 }166 }
162 }167 }
163 168
@@ -182,10 +187,10 @@ impl ClassGroup {
182 /// they take the outer/inner `Option<Option<_>>`: `None` = omitted (keep),187 /// they take the outer/inner `Option<Option<_>>`: `None` = omitted (keep),
183 /// `Some(None)` = clear.188 /// `Some(None)` = clear.
184 ///189 ///
185- /// A term move is claim-then-write-then-release, in that order, exactly as190+ /// A term move claims the new term and releases the old one inside the very
186- /// in [`crate::domain::course::Course::update`]: the new term is made191+ /// transaction that moves the link, exactly as in
187- /// undeletable before the link points at it, and the old one is only let go192+ /// [`crate::domain::course::Course::update`]: both counters and the link
188- /// once the link has actually moved off it.193+ /// commit together, so no crash can strand a count on a term nothing links.
189 pub async fn update(194 pub async fn update(
190 self,195 self,
191 name: Option<ClassName>,196 name: Option<ClassName>,
@@ -193,37 +198,14 @@ impl ClassGroup {
193 term: Option<Option<TermId>>,198 term: Option<Option<TermId>>,
194 db: &Database,199 db: &Database,
195 ) -> Result<ClassGroup, AppError> {200 ) -> Result<ClassGroup, AppError> {
196- let claimed = match &term {201+ let (claim, release) = term::ref_move(self.term.as_ref(), &term);
197- Some(Some(new)) if Some(new) != self.term.as_ref() => {202+ FieldUpdate::new(self.id.record())
198- claim_term(new, db).await?;
199- Some(new.clone())
200- }
201- _ => None,
202- };
203- let updated = FieldUpdate::new(self.id.record())
204 .set("name", name)203 .set("name", name)
205 .set("grade", grade)204 .set("grade", grade)
206 .set("term", term.map(|term| term.map(|term| term.record())))205 .set("term", term.map(|term| term.map(|term| term.record())))
206+ .refcount(TERM_CLASS_COUNT_FIELD, claim, release, term::gone_error())
207 .run::<ClassGroup>(db)207 .run::<ClassGroup>(db)
208- .await;208+ .await
209- match updated {
210- Ok(updated) => {
211- // The stored row is the authority on where the link ended up —
212- // a PATCH that carried no `term_id` leaves it untouched.
213- if let Some(old) = &self.term
214- && updated.term.as_ref() != Some(old)
215- {
216- cap::release(&old.record(), TERM_CLASS_COUNT_FIELD, db).await?;
217- }
218- Ok(updated)
219- }
220- Err(err) => {
221- if let Some(new) = &claimed {
222- cap::release(&new.record(), TERM_CLASS_COUNT_FIELD, db).await?;
223- }
224- Err(err)
225- }
226- }
227 }209 }
228 210
229 /// Delete the class and give its term reference back. Nothing cascades: a211 /// Delete the class and give its term reference back. Nothing cascades: a
@@ -280,19 +262,6 @@ impl ClassGroup {
280 }262 }
281 }263 }
282 264
283-/// Take a reference on `term` for a class about to link it. The conditional
284-/// write doubles as the existence check — the class half of
285-/// [`crate::domain::course`]'s `claim_term`, against the class column.
286-async fn claim_term(term: &TermId, db: &Database) -> Result<(), AppError> {
287- if cap::claim(&term.record(), TERM_CLASS_COUNT_FIELD, cap::UNLIMITED, db).await? {
288- return Ok(());
289- }
290- Err(AppError::Validation(ValidationError::Invalid {
291- field: "term_id",
292- reason: "term does not exist",
293- }))
294-}
295-
296 #[cfg(test)]265 #[cfg(test)]
297 mod tests {266 mod tests {
298 use super::*;267 use super::*;
@@ -329,6 +298,25 @@ mod tests {
329 .unwrap()298 .unwrap()
330 }299 }
331 300
301+ /// The stored `class_count` on one term, absent counting as zero.
302+ async fn count_on(term: &TermId, db: &Database) -> i64 {
303+ let mut result = db
304+ .query(format!(
305+ "SELECT VALUE ({TERM_CLASS_COUNT_FIELD} ?? 0) FROM $term"
306+ ))
307+ .bind(("term", term.record()))
308+ .await
309+ .unwrap()
310+ .check()
311+ .unwrap();
312+ result
313+ .take::<Vec<i64>>(0)
314+ .unwrap()
315+ .first()
316+ .copied()
317+ .unwrap_or(0)
318+ }
319+
332 /// How many rows `sql` selects ids for.320 /// How many rows `sql` selects ids for.
333 async fn rows(sql: &str, db: &Database) -> usize {321 async fn rows(sql: &str, db: &Database) -> usize {
334 let mut result = db.query(sql).await.unwrap().check().unwrap();322 let mut result = db.query(sql).await.unwrap().check().unwrap();
@@ -438,6 +426,87 @@ mod tests {
438 }426 }
439 }427 }
440 428
429+ /// The class half of the invariant on the create path: a refused create
430+ /// leaves neither the row nor a count stranded on a term (which the term's
431+ /// delete guard reads, so a stray one would make it undeletable forever).
432+ #[tokio::test]
433+ async fn a_refused_create_writes_neither_row_nor_count() {
434+ let db = crate::database::init_mem().await.unwrap();
435+ let term = a_term(&db).await;
436+ let id = term.get_id().clone();
437+ assert!(term.delete(&db).await.unwrap());
438+
439+ let error = ClassGroup::create(
440+ &UserId::from_key("manager"),
441+ ClassName::try_new("9-A").unwrap(),
442+ None,
443+ Some(id),
444+ &db,
445+ )
446+ .await
447+ .expect_err("a term that is gone must not be linkable");
448+ assert!(error.to_string().contains("term does not exist"));
449+ assert_eq!(
450+ rows("SELECT VALUE id FROM class_group", &db).await,
451+ 0,
452+ "a refused create may write no row"
453+ );
454+ assert_eq!(
455+ rows("SELECT VALUE id FROM term", &db).await,
456+ 0,
457+ "…and least of all a count on a term it just brought back"
458+ );
459+ }
460+
461+ /// The class mirror of
462+ /// [`crate::domain::course::Course`]'s move tests: a term move carries both
463+ /// counters with the link, and a move to a term that is gone rolls the
464+ /// release back with the abort (the transaction releases before it claims,
465+ /// so the old count would be 0 if the abort did not undo it).
466+ #[tokio::test]
467+ async fn a_class_term_move_moves_both_counts_or_neither() {
468+ let db = crate::database::init_mem().await.unwrap();
469+ let at = crate::domain::timestamp::Timestamp::from_millis;
470+ let from = a_term(&db).await;
471+ let to = Term::create(TermName::try_new("2027").unwrap(), at(100), at(200), &db)
472+ .await
473+ .unwrap();
474+ let dead = Term::create(TermName::try_new("2028").unwrap(), at(100), at(200), &db)
475+ .await
476+ .unwrap();
477+ let dead_id = dead.get_id().clone();
478+ assert!(dead.delete(&db).await.unwrap());
479+ let class = class_on(Some(from.get_id().clone()), &db).await;
480+
481+ let error = class
482+ .clone()
483+ .update(
484+ Some(ClassName::try_new("9-B").unwrap()),
485+ None,
486+ Some(Some(dead_id)),
487+ &db,
488+ )
489+ .await
490+ .expect_err("a term that is gone must not be linkable");
491+ assert!(error.to_string().contains("term does not exist"));
492+ let stored = ClassGroup::read(class.get_id(), &db).await.unwrap().unwrap();
493+ assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put");
494+ assert_eq!(stored.get_name().as_str(), "9-A", "…and so does the row");
495+ assert_eq!(
496+ count_on(from.get_id(), &db).await,
497+ 1,
498+ "the release must roll back with the abort"
499+ );
500+
501+ let moved = class
502+ .update(None, None, Some(Some(to.get_id().clone())), &db)
503+ .await
504+ .unwrap();
505+ assert_eq!(moved.get_term(), Some(to.get_id()));
506+ assert_eq!(count_on(from.get_id(), &db).await, 0, "the old term is free");
507+ assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not");
508+ }
509+
441 /// [`crate::domain::course::Course::delete`]'s class sweep: deleting a course510 /// [`crate::domain::course::Course::delete`]'s class sweep: deleting a course
442 /// takes its `class_course` attachments with it and gives each class its511 /// takes its `class_course` attachments with it and gives each class its
443 /// count back, or the classes would be undeletable forever over rows that512 /// count back, or the classes would be undeletable forever over rows that
src/domain/course.rsmodified+168 -71
@@ -9,7 +9,7 @@ use crate::database::{Database, transaction_with_retry};
9 use crate::domain::cap;9 use crate::domain::cap;
10 use crate::domain::field_update::FieldUpdate;10 use crate::domain::field_update::FieldUpdate;
11 use crate::domain::page::PagedList;11 use crate::domain::page::PagedList;
12-use crate::domain::term::TermId;12+use crate::domain::term::{self, TermId};
13 use crate::domain::user::UserId;13 use crate::domain::user::UserId;
14 use crate::error::{AppError, ValidationError};14 use crate::error::{AppError, ValidationError};
15 use crate::validate::{validate_course_kind, validate_optional, validate_required};15 use crate::validate::{validate_course_kind, validate_optional, validate_required};
@@ -161,11 +161,12 @@ impl Course {
161 self.teachers.contains(user)161 self.teachers.contains(user)
162 }162 }
163 163
164- /// Create the course, claiming a reference on the term it links (if any)164+ /// Create the course, claiming a reference on the term it links (if any) in
165- /// *before* the row is written: the claim is a conditional write on the165+ /// the *same transaction* as the row: the claim is a conditional write on
166- /// term row, so it fails when the term is already gone and it makes the166+ /// the term row, so it fails when the term is already gone and it makes the
167- /// term undeletable the instant this link exists, which the count-then-write167+ /// term undeletable the instant this link exists — and a crash can never
168- /// mutex it replaced could not do.168+ /// leave one without the other, which a claim sent as its own query could
169+ /// (the count would strand and the term be undeletable forever).
169 pub async fn create(170 pub async fn create(
170 creator: &UserId,171 creator: &UserId,
171 title: CourseTitle,172 title: CourseTitle,
@@ -175,10 +176,6 @@ impl Course {
175 capacity: Option<i64>,176 capacity: Option<i64>,
176 db: &Database,177 db: &Database,
177 ) -> Result<Course, AppError> {178 ) -> Result<Course, AppError> {
178- if let Some(term) = &term {
179- claim_term(term, db).await?;
180- }
181- let claimed = term.clone();
182 let course = Course {179 let course = Course {
183 id: CourseId::generate(),180 id: CourseId::generate(),
184 creator: creator.clone(),181 creator: creator.clone(),
@@ -189,20 +186,27 @@ impl Course {
189 description,186 description,
190 kind,187 kind,
191 };188 };
192- let created: Result<Option<Course>, _> =189+ let id = course.id.record();
193- db.create(course.id.record()).content(course).await;190+ let Some(term) = course.term.clone() else {
194- match created {191+ let created: Option<Course> = db.create(id).content(course).await?;
195- Ok(Some(created)) => Ok(created),192+ return created.ok_or_else(|| AppError::Internal("failed to create course".into()));
196- other => {193+ };
197- // The link never landed, so the reference has to go back.194+ match cap::claim_and_create(
198- if let Some(term) = &claimed {195+ &term.record(),
199- cap::release(&term.record(), COURSE_COUNT_FIELD, db).await?;196+ COURSE_COUNT_FIELD,
200- }197+ cap::UNLIMITED,
201- match other {198+ &id,
202- Err(err) => Err(err.into()),199+ &course,
203- _ => Err(AppError::Internal("failed to create course".into())),200+ db,
204- }201+ )
205- }202+ .await?
203+ {
204+ cap::Claimed::Made(created) => Ok(created),
205+ // Uncapped, so "full" can only mean the conditional write matched no
206+ // term row at all — the existence check the pre-flight lookup makes.
207+ cap::Claimed::Full => Err(term::gone_error()),
208+ // Unreachable: the id is a ULID this call just generated.
209+ cap::Claimed::Duplicate => Err(AppError::Internal("failed to create course".into())),
206 }210 }
207 }211 }
208 212
@@ -280,43 +284,21 @@ impl Course {
280 capacity: Option<Option<i64>>,284 capacity: Option<Option<i64>>,
281 db: &Database,285 db: &Database,
282 ) -> Result<Course, AppError> {286 ) -> Result<Course, AppError> {
283- // A term move is claim-then-write-then-release, in that order: the new287+ // A term move claims the new term and releases the old one inside the
284- // term is made undeletable before the link points at it, and the old288+ // very transaction that moves the link, so no crash can leave a count
285- // one is only let go once the link has actually moved off it. Doing it289+ // without its link (the term would be undeletable forever) or a link
286- // the other way round would open exactly the window this replaced.290+ // without its count. A PATCH that carried no `term_id`, or re-stated the
287- let claimed = match &term {291+ // link it already had, moves neither counter.
288- Some(Some(new)) if Some(new) != self.term.as_ref() => {292+ let (claim, release) = term::ref_move(self.term.as_ref(), &term);
289- claim_term(new, db).await?;293+ FieldUpdate::new(self.id.record())
290- Some(new.clone())
291- }
292- _ => None,
293- };
294- let updated = FieldUpdate::new(self.id.record())
295 .set("title", title)294 .set("title", title)
296 .set("description", description)295 .set("description", description)
297 .set("kind", kind)296 .set("kind", kind)
298 .set("term", term.map(|term| term.map(|term| term.record())))297 .set("term", term.map(|term| term.map(|term| term.record())))
299 .set("capacity", capacity)298 .set("capacity", capacity)
299+ .refcount(COURSE_COUNT_FIELD, claim, release, term::gone_error())
300 .run::<Course>(db)300 .run::<Course>(db)
301- .await;301+ .await
302- match updated {
303- Ok(updated) => {
304- // The stored row is the authority on where the link ended up —
305- // a PATCH that carried no `term_id` leaves it untouched.
306- if let Some(old) = &self.term
307- && updated.term.as_ref() != Some(old)
308- {
309- cap::release(&old.record(), COURSE_COUNT_FIELD, db).await?;
310- }
311- Ok(updated)
312- }
313- Err(err) => {
314- if let Some(new) = &claimed {
315- cap::release(&new.record(), COURSE_COUNT_FIELD, db).await?;
316- }
317- Err(err)
318- }
319- }
320 }302 }
321 303
322 /// Assign `teacher` to run this course, or return the course untouched if304 /// Assign `teacher` to run this course, or return the course untouched if
@@ -472,23 +454,10 @@ impl Course {
472 }454 }
473 }455 }
474 456
475-/// Take a reference on `term` for a course about to link it. The conditional
476-/// write doubles as the existence check: a term that a delete already removed
477-/// matches nothing, and the caller answers exactly what the pre-flight lookup
478-/// in `web::terms::resolve_term` would have.
479-async fn claim_term(term: &TermId, db: &Database) -> Result<(), AppError> {
480- if cap::claim(&term.record(), COURSE_COUNT_FIELD, cap::UNLIMITED, db).await? {
481- return Ok(());
482- }
483- Err(AppError::Validation(ValidationError::Invalid {
484- field: "term_id",
485- reason: "term does not exist",
486- }))
487-}
488-
489 #[cfg(test)]457 #[cfg(test)]
490 mod tests {458 mod tests {
491 use super::*;459 use super::*;
460+ use crate::domain::term::{Term, TermName};
492 461
493 async fn course_on(term: Option<TermId>, db: &Database) -> Course {462 async fn course_on(term: Option<TermId>, db: &Database) -> Course {
494 Course::create(463 Course::create(
@@ -557,8 +526,6 @@ mod tests {
557 /// back. Dropping the release in `delete` leaves the term deletable never.526 /// back. Dropping the release in `delete` leaves the term deletable never.
558 #[tokio::test]527 #[tokio::test]
559 async fn a_term_is_deletable_only_once_no_course_links_it() {528 async fn a_term_is_deletable_only_once_no_course_links_it() {
560- use crate::domain::term::{Term, TermName};
561-
562 let db = crate::database::init_mem().await.unwrap();529 let db = crate::database::init_mem().await.unwrap();
563 let at = crate::domain::timestamp::Timestamp::from_millis;530 let at = crate::domain::timestamp::Timestamp::from_millis;
564 let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db)531 let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db)
@@ -613,6 +580,136 @@ mod tests {
613 assert!(error.to_string().contains("term does not exist"));580 assert!(error.to_string().contains("term does not exist"));
614 }581 }
615 582
583+ /// The stored `course_count` on one term, absent counting as zero.
584+ async fn count_on(term: &TermId, db: &Database) -> i64 {
585+ let mut result = db
586+ .query(format!("SELECT VALUE ({COURSE_COUNT_FIELD} ?? 0) FROM $term"))
587+ .bind(("term", term.record()))
588+ .await
589+ .unwrap()
590+ .check()
591+ .unwrap();
592+ result
593+ .take::<Vec<i64>>(0)
594+ .unwrap()
595+ .first()
596+ .copied()
597+ .unwrap_or(0)
598+ }
599+
600+ /// How many rows `sql` selects ids for.
601+ async fn rows(sql: &str, db: &Database) -> usize {
602+ let mut result = db.query(sql).await.unwrap().check().unwrap();
603+ result.take::<Vec<RecordId>>(0).unwrap().len()
604+ }
605+
606+ async fn a_term(name: &str, db: &Database) -> Term {
607+ let at = crate::domain::timestamp::Timestamp::from_millis;
608+ Term::create(TermName::try_new(name).unwrap(), at(100), at(200), db)
609+ .await
610+ .unwrap()
611+ }
612+
613+ /// The invariant, on the create path: a claim and the row it accounts for
614+ /// commit together or not at all. A refused create must therefore leave
615+ /// *neither* — no course row, and no count stranded on a term (which is
616+ /// worse than it sounds: the term's delete guard reads that count, so a
617+ /// stray one makes the term undeletable forever).
618+ #[tokio::test]
619+ async fn a_refused_create_writes_neither_row_nor_count() {
620+ let db = crate::database::init_mem().await.unwrap();
621+ let term = a_term("2026", &db).await;
622+ let id = term.get_id().clone();
623+ assert!(term.delete(&db).await.unwrap());
624+
625+ let error = Course::create(
626+ &UserId::from_key("teacher"),
627+ CourseTitle::try_new("algebra").unwrap(),
628+ CourseDescription::try_new("").unwrap(),
629+ CourseKind::course(),
630+ Some(id),
631+ None,
632+ &db,
633+ )
634+ .await
635+ .expect_err("a term that is gone must not be linkable");
636+ assert!(error.to_string().contains("term does not exist"));
637+ assert_eq!(
638+ rows("SELECT VALUE id FROM course", &db).await,
639+ 0,
640+ "a refused create may write no row"
641+ );
642+ assert_eq!(
643+ rows("SELECT VALUE id FROM term", &db).await,
644+ 0,
645+ "…and least of all a count on a term it just brought back"
646+ );
647+ }
648+
649+ /// The invariant on the PATCH path, both directions: a move carries the new
650+ /// term's claim and the old term's release with the link itself.
651+ #[tokio::test]
652+ async fn a_term_move_moves_the_count() {
653+ let db = crate::database::init_mem().await.unwrap();
654+ let from = a_term("2026", &db).await;
655+ let to = a_term("2027", &db).await;
656+ let course = course_on(Some(from.get_id().clone()), &db).await;
657+ assert_eq!(count_on(from.get_id(), &db).await, 1);
658+
659+ let moved = course
660+ .update(None, None, None, Some(Some(to.get_id().clone())), None, &db)
661+ .await
662+ .unwrap();
663+ assert_eq!(moved.get_term(), Some(to.get_id()));
664+ assert_eq!(count_on(from.get_id(), &db).await, 0, "the old term is free");
665+ assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not");
666+ assert!(from.clone().delete(&db).await.unwrap());
667+ assert!(!to.clone().delete(&db).await.unwrap());
668+ }
669+
670+ /// The rollback proof. The transaction releases the old term *before* it
671+ /// claims the new one, so a move to a term that is gone has already
672+ /// decremented when the claim throws — the old count still being 1 is the
673+ /// abort undoing a write that really happened, not a branch that never ran.
674+ /// The title moves in the same PATCH, and must not stick either.
675+ #[tokio::test]
676+ async fn a_term_move_to_a_dead_term_leaves_everything_untouched() {
677+ let db = crate::database::init_mem().await.unwrap();
678+ let from = a_term("2026", &db).await;
679+ let dead = a_term("2027", &db).await;
680+ let dead_id = dead.get_id().clone();
681+ assert!(dead.delete(&db).await.unwrap());
682+ let course = course_on(Some(from.get_id().clone()), &db).await;
683+
684+ let error = course
685+ .clone()
686+ .update(
687+ Some(CourseTitle::try_new("moved").unwrap()),
688+ None,
689+ None,
690+ Some(Some(dead_id)),
691+ None,
692+ &db,
693+ )
694+ .await
695+ .expect_err("a term that is gone must not be linkable");
696+ assert!(error.to_string().contains("term does not exist"));
697+
698+ let stored = Course::read(course.get_id(), &db).await.unwrap().unwrap();
699+ assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put");
700+ assert_eq!(stored.get_title().as_str(), "algebra", "…and so does the row");
701+ assert_eq!(
702+ count_on(from.get_id(), &db).await,
703+ 1,
704+ "the release must roll back with the abort"
705+ );
706+ assert_eq!(
707+ rows("SELECT VALUE id FROM term", &db).await,
708+ 1,
709+ "the dead term must not be resurrected by the claim"
710+ );
711+ }
712+
616 #[tokio::test]713 #[tokio::test]
617 async fn title_is_required() {714 async fn title_is_required() {
618 assert!(CourseTitle::try_new("algebra").is_ok());715 assert!(CourseTitle::try_new("algebra").is_ok());
src/domain/field_update.rsmodified+122 -3
@@ -24,9 +24,16 @@
24 24
25 use surrealdb::types::{RecordId, SurrealValue, Value};25 use surrealdb::types::{RecordId, SurrealValue, Value};
26 26
27-use crate::database::{Database, write_with_retry};27+use crate::database::{Database, transaction_with_retry, write_with_retry};
28+use crate::domain::cap;
28 use crate::error::AppError;29 use crate::error::AppError;
29 30
31+/// The `THROW` markers [`FieldUpdate::refcount`]'s transaction aborts with: the
32+/// row the reference was to be claimed on is gone, and the row being patched is
33+/// gone (or its guard bit).
34+const CLAIM_MARK: &str = "ref_claim_gone";
35+const ROW_MARK: &str = "ref_row_gone";
36+
30 pub struct FieldUpdate {37 pub struct FieldUpdate {
31 id: RecordId,38 id: RecordId,
32 /// `field = $field` fragments, in the order they were set.39 /// `field = $field` fragments, in the order they were set.
@@ -36,6 +43,8 @@ pub struct FieldUpdate {
36 ordered: Option<(&'static str, &'static str, AppError)>,43 ordered: Option<(&'static str, &'static str, AppError)>,
37 /// `(condition, refusal)` for [`FieldUpdate::guard`].44 /// `(condition, refusal)` for [`FieldUpdate::guard`].
38 guard: Option<(&'static str, AppError)>,45 guard: Option<(&'static str, AppError)>,
46+ /// `(counter field, claim, release, refusal)` for [`FieldUpdate::refcount`].
47+ refcount: Option<(&'static str, Option<RecordId>, Option<RecordId>, AppError)>,
39 }48 }
40 49
41 impl FieldUpdate {50 impl FieldUpdate {
@@ -46,11 +55,13 @@ impl FieldUpdate {
46 bindings: Vec::new(),55 bindings: Vec::new(),
47 ordered: None,56 ordered: None,
48 guard: None,57 guard: None,
58+ refcount: None,
49 }59 }
50 }60 }
51 61
52 /// Write `field` only when the request carried it. The bind variable is62 /// Write `field` only when the request carried it. The bind variable is
53- /// named after the field, so `id` is the one name a caller must not use.63+ /// named after the field, so `id` — and `ref_claim`/`ref_release`, which
64+ /// [`FieldUpdate::refcount`] binds — are the names a caller must not use.
54 #[must_use]65 #[must_use]
55 pub fn set<T: SurrealValue>(mut self, field: &'static str, value: Option<T>) -> Self {66 pub fn set<T: SurrealValue>(mut self, field: &'static str, value: Option<T>) -> Self {
56 if let Some(value) = value {67 if let Some(value) = value {
@@ -97,9 +108,38 @@ impl FieldUpdate {
97 self108 self
98 }109 }
99 110
111+ /// Move a reference counter *with* this write: `claim` takes one on the row
112+ /// the link moves to, `release` gives one back on the row it moves off, and
113+ /// both ride the same `BEGIN…COMMIT` as the `UPDATE` that moves the link.
114+ ///
115+ /// That is the whole point. A claim sent as its own query leaves a window
116+ /// where a crash strands a count on a row nothing links any more — and a
117+ /// count is what a delete guard reads, so the stranded one makes its parent
118+ /// undeletable forever. `refused` is the answer when the claimed row is gone
119+ /// (the conditional write doubles as the existence check, as in
120+ /// [`crate::domain::cap`]); the transaction then aborts, so the release and
121+ /// the row write never happened either.
122+ ///
123+ /// Only ever called alongside a `.set()` of the very column that carries the
124+ /// link, so the empty-request short-circuit below cannot swallow a move.
125+ #[must_use]
126+ pub fn refcount(
127+ mut self,
128+ field: &'static str,
129+ claim: Option<RecordId>,
130+ release: Option<RecordId>,
131+ refused: AppError,
132+ ) -> Self {
133+ if claim.is_some() || release.is_some() {
134+ self.refcount = Some((field, claim, release, refused));
135+ }
136+ self
137+ }
138+
100 /// Run the update and return the stored row. An empty request writes139 /// Run the update and return the stored row. An empty request writes
101 /// nothing at all and reads the row back unchanged.140 /// nothing at all and reads the row back unchanged.
102 pub async fn run<T: SurrealValue>(mut self, db: &Database) -> Result<T, AppError> {141 pub async fn run<T: SurrealValue>(mut self, db: &Database) -> Result<T, AppError> {
142+ let moved = self.refcount.take();
103 if self.assignments.is_empty() {143 if self.assignments.is_empty() {
104 let row: Option<T> = db.select(self.id).await?;144 let row: Option<T> = db.select(self.id).await?;
105 return row.ok_or(AppError::NotFound);145 return row.ok_or(AppError::NotFound);
@@ -145,7 +185,13 @@ impl FieldUpdate {
145 // Retried on a write conflict: a guarded PATCH contends on the very row185 // Retried on a write conflict: a guarded PATCH contends on the very row
146 // its guard reads, and the loser wrote nothing, so re-sending it is the186 // its guard reads, and the loser wrote nothing, so re-sending it is the
147 // recovery — see [`write_with_retry`].187 // recovery — see [`write_with_retry`].
148- let rows: Vec<T> = write_with_retry(db, &sql, &self.bindings).await?;188+ let rows: Vec<T> = match moved {
189+ Some((field, claim, release, ref_refused)) => {
190+ run_with_refcount(db, &sql, self.bindings, field, claim, release, ref_refused)
191+ .await?
192+ }
193+ None => write_with_retry(db, &sql, &self.bindings).await?,
194+ };
149 // No row back means the guard bit (or, in the window after the handler's195 // No row back means the guard bit (or, in the window after the handler's
150 // read, the row was deleted — the guard cannot tell the two apart, and196 // read, the row was deleted — the guard cannot tell the two apart, and
151 // reports the refusal it was given).197 // reports the refusal it was given).
@@ -158,3 +204,76 @@ impl FieldUpdate {
158 self.bindings.iter().any(|(name, _)| name == field)204 self.bindings.iter().any(|(name, _)| name == field)
159 }205 }
160 }206 }
207+
208+/// Send `update` with its counter move, as one transaction. An empty `Vec` back
209+/// means the row write matched nothing, exactly as [`write_with_retry`] would
210+/// have reported it, so the caller's refusal is unchanged.
211+///
212+/// Admissible for [`transaction_with_retry`]: every statement is an `UPDATE`,
213+/// an `IF`/`THROW` or a `RETURN`, and none of those can answer "already
214+/// exists" — a lost round writes nothing and re-sending it is the recovery.
215+#[allow(clippy::too_many_arguments)]
216+async fn run_with_refcount<T: SurrealValue>(
217+ db: &Database,
218+ update: &str,
219+ mut bindings: Vec<(String, Value)>,
220+ field: &'static str,
221+ claim: Option<RecordId>,
222+ release: Option<RecordId>,
223+ refused: AppError,
224+) -> Result<Vec<T>, AppError> {
225+ // Parenthesized `??` throughout: `n ?? 0 + 1` parses as `n ?? (0 + 1)`.
226+ // Both counter writes commit with the row write or neither does, so their
227+ // order is free — the release goes first because that is what makes the
228+ // rollback observable: a move to a term that is gone decrements before the
229+ // claim throws, and the old count still being there proves the abort undid
230+ // it (`a_term_move_to_a_dead_term_leaves_everything_untouched`).
231+ let mut statements: Vec<String> = Vec::new();
232+ if let Some(release) = release {
233+ statements.push(format!(
234+ "UPDATE $ref_release SET {field} = math::max([({field} ?? 0) - 1, 0])"
235+ ));
236+ bindings.push(("ref_release".into(), release.into_value()));
237+ }
238+ if let Some(claim) = claim {
239+ statements.push(format!(
240+ "LET $seat = (UPDATE $ref_claim SET {field} = ({field} ?? 0) + 1 RETURN VALUE id)"
241+ ));
242+ statements.push(format!("IF array::len($seat) = 0 {{ THROW '{CLAIM_MARK}' }}"));
243+ bindings.push(("ref_claim".into(), claim.into_value()));
244+ }
245+ statements.push(format!("LET $row = ({update})"));
246+ // Without this the claim would outlive a row write that matched nothing —
247+ // the very leak the transaction exists to close.
248+ statements.push(format!("IF array::len($row) = 0 {{ THROW '{ROW_MARK}' }}"));
249+ statements.push("RETURN $row".into());
250+ let sql = format!(
251+ "BEGIN TRANSACTION; {}; COMMIT TRANSACTION;",
252+ statements.join("; ")
253+ );
254+ // BEGIN is slot 0, so the trailing RETURN sits at `statements.len()`.
255+ let slot = statements.len();
256+
257+ // One counter write in flight at a time, like every other counter write.
258+ let _guard = cap::counter_lock().await;
259+ let (mut result, mut errors) =
260+ transaction_with_retry(db, &sql, &bindings, &[CLAIM_MARK, ROW_MARK]).await?;
261+ if errors
262+ .values()
263+ .any(|error| error.to_string().contains(CLAIM_MARK))
264+ {
265+ return Err(refused);
266+ }
267+ if errors
268+ .values()
269+ .any(|error| error.to_string().contains(ROW_MARK))
270+ {
271+ return Ok(Vec::new());
272+ }
273+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
274+ return Err(error.into());
275+ }
276+ // Sound only because the error map came back empty: `take_errors` swap-
277+ // removes errored slots, which would renumber the rest.
278+ Ok(result.take::<Vec<T>>(slot)?)
279+}
src/domain/term.rsmodified+26 -0
@@ -41,6 +41,32 @@ impl TermId {
41 }41 }
42 }42 }
43 43
44+/// The answer every link to a term that is not there gets — the claim is a
45+/// conditional write on the term row, so a term a delete already removed
46+/// matches nothing and the caller says exactly what `web::terms::resolve_term`'s
47+/// pre-flight lookup would have.
48+pub fn gone_error() -> AppError {
49+ AppError::Validation(ValidationError::Invalid {
50+ field: "term_id",
51+ reason: "term does not exist",
52+ })
53+}
54+
55+/// What a PATCH's `term` field owes the refcounts: the term to claim, and the
56+/// one to give back. Covers all three moves — set (none→some), move
57+/// (some→other) and clear (some→none) — and moves nothing for a PATCH that
58+/// omitted the field or re-stated the link it already had.
59+pub fn ref_move(
60+ current: Option<&TermId>,
61+ patch: &Option<Option<TermId>>,
62+) -> (Option<RecordId>, Option<RecordId>) {
63+ match patch {
64+ None => (None, None),
65+ Some(next) if next.as_ref() == current => (None, None),
66+ Some(next) => (next.as_ref().map(TermId::record), current.map(TermId::record)),
67+ }
68+}
69+
44 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]70 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
45 pub struct TermName(String);71 pub struct TermName(String);
46 72