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;
5353 // only about how many writes a process has in flight.
5454 static CLAIM_LOCK: Mutex<()> = Mutex::const_new(());
5555
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+
5664 /// "No cap" as a number, so the guard stays one comparison instead of a
5765 /// nullable branch: `NONE`/`NULL` bind ambiguity is a worse trade than a
5866 /// sentinel no roster will ever reach.
src/domain/class_group.rsmodified+136 -67
@@ -21,7 +21,7 @@ use crate::domain::cap;
2121 use crate::domain::field_update::FieldUpdate;
2222 use crate::domain::monotonic_id::next_ulid;
2323 use crate::domain::page::PagedList;
24-use crate::domain::term::TermId;
24+use crate::domain::term::{self, TermId};
2525 use crate::domain::user::UserId;
2626 use crate::error::{AppError, ValidationError};
2727 use crate::validate::{validate_optional, validate_required};
@@ -122,10 +122,12 @@ impl ClassGroup {
122122 &self.creator == user
123123 }
124124
125- /// Create the class, claiming a reference on the term it links (if any)
126- /// *before* the row is written: the claim is a conditional write on the term
127- /// row, so it fails when the term is already gone and it makes the term
128- /// undeletable the instant this link exists.
125+ /// Create the class, claiming a reference on the term it links (if any) in
126+ /// the *same transaction* as the row, exactly as
127+ /// [`crate::domain::course::Course::create`] does: the claim is a
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.
129131 pub async fn create(
130132 creator: &UserId,
131133 name: ClassName,
@@ -133,10 +135,6 @@ impl ClassGroup {
133135 term: Option<TermId>,
134136 db: &Database,
135137 ) -> Result<ClassGroup, AppError> {
136- if let Some(term) = &term {
137- claim_term(term, db).await?;
138- }
139- let claimed = term.clone();
140138 let class = ClassGroup {
141139 id: ClassGroupId::generate(),
142140 creator: creator.clone(),
@@ -144,20 +142,27 @@ impl ClassGroup {
144142 grade,
145143 term,
146144 };
147- let created: Result<Option<ClassGroup>, _> =
148- db.create(class.id.record()).content(class).await;
149- match created {
150- Ok(Some(created)) => Ok(created),
151- other => {
152- // The link never landed, so the reference has to go back.
153- if let Some(term) = &claimed {
154- cap::release(&term.record(), TERM_CLASS_COUNT_FIELD, db).await?;
155- }
156- match other {
157- Err(err) => Err(err.into()),
158- _ => Err(AppError::Internal("failed to create class".into())),
159- }
160- }
145+ let id = class.id.record();
146+ let Some(term) = class.term.clone() else {
147+ let created: Option<ClassGroup> = db.create(id).content(class).await?;
148+ return created.ok_or_else(|| AppError::Internal("failed to create class".into()));
149+ };
150+ match cap::claim_and_create(
151+ &term.record(),
152+ TERM_CLASS_COUNT_FIELD,
153+ cap::UNLIMITED,
154+ &id,
155+ &class,
156+ db,
157+ )
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())),
161166 }
162167 }
163168
@@ -182,10 +187,10 @@ impl ClassGroup {
182187 /// they take the outer/inner `Option<Option<_>>`: `None` = omitted (keep),
183188 /// `Some(None)` = clear.
184189 ///
185- /// A term move is claim-then-write-then-release, in that order, exactly as
186- /// in [`crate::domain::course::Course::update`]: the new term is made
187- /// undeletable before the link points at it, and the old one is only let go
188- /// once the link has actually moved off it.
190+ /// A term move claims the new term and releases the old one inside the very
191+ /// transaction that moves the link, exactly as in
192+ /// [`crate::domain::course::Course::update`]: both counters and the link
193+ /// commit together, so no crash can strand a count on a term nothing links.
189194 pub async fn update(
190195 self,
191196 name: Option<ClassName>,
@@ -193,37 +198,14 @@ impl ClassGroup {
193198 term: Option<Option<TermId>>,
194199 db: &Database,
195200 ) -> Result<ClassGroup, AppError> {
196- let claimed = match &term {
197- Some(Some(new)) if Some(new) != self.term.as_ref() => {
198- claim_term(new, db).await?;
199- Some(new.clone())
200- }
201- _ => None,
202- };
203- let updated = FieldUpdate::new(self.id.record())
201+ let (claim, release) = term::ref_move(self.term.as_ref(), &term);
202+ FieldUpdate::new(self.id.record())
204203 .set("name", name)
205204 .set("grade", grade)
206205 .set("term", term.map(|term| term.map(|term| term.record())))
206+ .refcount(TERM_CLASS_COUNT_FIELD, claim, release, term::gone_error())
207207 .run::<ClassGroup>(db)
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- }
208+ .await
227209 }
228210
229211 /// Delete the class and give its term reference back. Nothing cascades: a
@@ -280,19 +262,6 @@ impl ClassGroup {
280262 }
281263 }
282264
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-
296265 #[cfg(test)]
297266 mod tests {
298267 use super::*;
@@ -329,6 +298,25 @@ mod tests {
329298 .unwrap()
330299 }
331300
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+
332320 /// How many rows `sql` selects ids for.
333321 async fn rows(sql: &str, db: &Database) -> usize {
334322 let mut result = db.query(sql).await.unwrap().check().unwrap();
@@ -438,6 +426,87 @@ mod tests {
438426 }
439427 }
440428
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+
441510 /// [`crate::domain::course::Course::delete`]'s class sweep: deleting a course
442511 /// takes its `class_course` attachments with it and gives each class its
443512 /// 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};
99 use crate::domain::cap;
1010 use crate::domain::field_update::FieldUpdate;
1111 use crate::domain::page::PagedList;
12-use crate::domain::term::TermId;
12+use crate::domain::term::{self, TermId};
1313 use crate::domain::user::UserId;
1414 use crate::error::{AppError, ValidationError};
1515 use crate::validate::{validate_course_kind, validate_optional, validate_required};
@@ -161,11 +161,12 @@ impl Course {
161161 self.teachers.contains(user)
162162 }
163163
164- /// Create the course, claiming a reference on the term it links (if any)
165- /// *before* the row is written: the claim is a conditional write on the
166- /// 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-write
168- /// mutex it replaced could not do.
164+ /// Create the course, claiming a reference on the term it links (if any) in
165+ /// the *same transaction* as the row: the claim is a conditional write on
166+ /// the term row, so it fails when the term is already gone and it makes the
167+ /// term undeletable the instant this link exists — and a crash can never
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).
169170 pub async fn create(
170171 creator: &UserId,
171172 title: CourseTitle,
@@ -175,10 +176,6 @@ impl Course {
175176 capacity: Option<i64>,
176177 db: &Database,
177178 ) -> Result<Course, AppError> {
178- if let Some(term) = &term {
179- claim_term(term, db).await?;
180- }
181- let claimed = term.clone();
182179 let course = Course {
183180 id: CourseId::generate(),
184181 creator: creator.clone(),
@@ -189,20 +186,27 @@ impl Course {
189186 description,
190187 kind,
191188 };
192- let created: Result<Option<Course>, _> =
193- db.create(course.id.record()).content(course).await;
194- match created {
195- Ok(Some(created)) => Ok(created),
196- other => {
197- // The link never landed, so the reference has to go back.
198- if let Some(term) = &claimed {
199- cap::release(&term.record(), COURSE_COUNT_FIELD, db).await?;
200- }
201- match other {
202- Err(err) => Err(err.into()),
203- _ => Err(AppError::Internal("failed to create course".into())),
204- }
205- }
189+ let id = course.id.record();
190+ let Some(term) = course.term.clone() else {
191+ let created: Option<Course> = db.create(id).content(course).await?;
192+ return created.ok_or_else(|| AppError::Internal("failed to create course".into()));
193+ };
194+ match cap::claim_and_create(
195+ &term.record(),
196+ COURSE_COUNT_FIELD,
197+ cap::UNLIMITED,
198+ &id,
199+ &course,
200+ db,
201+ )
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())),
206210 }
207211 }
208212
@@ -280,43 +284,21 @@ impl Course {
280284 capacity: Option<Option<i64>>,
281285 db: &Database,
282286 ) -> Result<Course, AppError> {
283- // A term move is claim-then-write-then-release, in that order: the new
284- // term is made undeletable before the link points at it, and the old
285- // one is only let go once the link has actually moved off it. Doing it
286- // the other way round would open exactly the window this replaced.
287- let claimed = match &term {
288- Some(Some(new)) if Some(new) != self.term.as_ref() => {
289- claim_term(new, db).await?;
290- Some(new.clone())
291- }
292- _ => None,
293- };
294- let updated = FieldUpdate::new(self.id.record())
287+ // A term move claims the new term and releases the old one inside the
288+ // very transaction that moves the link, so no crash can leave a count
289+ // without its link (the term would be undeletable forever) or a link
290+ // without its count. A PATCH that carried no `term_id`, or re-stated the
291+ // link it already had, moves neither counter.
292+ let (claim, release) = term::ref_move(self.term.as_ref(), &term);
293+ FieldUpdate::new(self.id.record())
295294 .set("title", title)
296295 .set("description", description)
297296 .set("kind", kind)
298297 .set("term", term.map(|term| term.map(|term| term.record())))
299298 .set("capacity", capacity)
299+ .refcount(COURSE_COUNT_FIELD, claim, release, term::gone_error())
300300 .run::<Course>(db)
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- }
301+ .await
320302 }
321303
322304 /// Assign `teacher` to run this course, or return the course untouched if
@@ -472,23 +454,10 @@ impl Course {
472454 }
473455 }
474456
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-
489457 #[cfg(test)]
490458 mod tests {
491459 use super::*;
460+ use crate::domain::term::{Term, TermName};
492461
493462 async fn course_on(term: Option<TermId>, db: &Database) -> Course {
494463 Course::create(
@@ -557,8 +526,6 @@ mod tests {
557526 /// back. Dropping the release in `delete` leaves the term deletable never.
558527 #[tokio::test]
559528 async fn a_term_is_deletable_only_once_no_course_links_it() {
560- use crate::domain::term::{Term, TermName};
561-
562529 let db = crate::database::init_mem().await.unwrap();
563530 let at = crate::domain::timestamp::Timestamp::from_millis;
564531 let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db)
@@ -613,6 +580,136 @@ mod tests {
613580 assert!(error.to_string().contains("term does not exist"));
614581 }
615582
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+
616713 #[tokio::test]
617714 async fn title_is_required() {
618715 assert!(CourseTitle::try_new("algebra").is_ok());
src/domain/field_update.rsmodified+122 -3
@@ -24,9 +24,16 @@
2424
2525 use surrealdb::types::{RecordId, SurrealValue, Value};
2626
27-use crate::database::{Database, write_with_retry};
27+use crate::database::{Database, transaction_with_retry, write_with_retry};
28+use crate::domain::cap;
2829 use crate::error::AppError;
2930
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+
3037 pub struct FieldUpdate {
3138 id: RecordId,
3239 /// `field = $field` fragments, in the order they were set.
@@ -36,6 +43,8 @@ pub struct FieldUpdate {
3643 ordered: Option<(&'static str, &'static str, AppError)>,
3744 /// `(condition, refusal)` for [`FieldUpdate::guard`].
3845 guard: Option<(&'static str, AppError)>,
46+ /// `(counter field, claim, release, refusal)` for [`FieldUpdate::refcount`].
47+ refcount: Option<(&'static str, Option<RecordId>, Option<RecordId>, AppError)>,
3948 }
4049
4150 impl FieldUpdate {
@@ -46,11 +55,13 @@ impl FieldUpdate {
4655 bindings: Vec::new(),
4756 ordered: None,
4857 guard: None,
58+ refcount: None,
4959 }
5060 }
5161
5262 /// 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.
5465 #[must_use]
5566 pub fn set<T: SurrealValue>(mut self, field: &'static str, value: Option<T>) -> Self {
5667 if let Some(value) = value {
@@ -97,9 +108,38 @@ impl FieldUpdate {
97108 self
98109 }
99110
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+
100139 /// Run the update and return the stored row. An empty request writes
101140 /// nothing at all and reads the row back unchanged.
102141 pub async fn run<T: SurrealValue>(mut self, db: &Database) -> Result<T, AppError> {
142+ let moved = self.refcount.take();
103143 if self.assignments.is_empty() {
104144 let row: Option<T> = db.select(self.id).await?;
105145 return row.ok_or(AppError::NotFound);
@@ -145,7 +185,13 @@ impl FieldUpdate {
145185 // Retried on a write conflict: a guarded PATCH contends on the very row
146186 // its guard reads, and the loser wrote nothing, so re-sending it is the
147187 // 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+ };
149195 // No row back means the guard bit (or, in the window after the handler's
150196 // read, the row was deleted — the guard cannot tell the two apart, and
151197 // reports the refusal it was given).
@@ -158,3 +204,76 @@ impl FieldUpdate {
158204 self.bindings.iter().any(|(name, _)| name == field)
159205 }
160206 }
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 {
4141 }
4242 }
4343
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+
4470 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
4571 pub struct TermName(String);
4672