From b1c8e7acbb4ad7acd23551ecb35491dc5d54e886 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 4 Aug 2026 20:49:57 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=94=92=20stop=20a=20deleted=20blue?= =?UTF-8?q?print=20from=20stranding=20the=20rows=20it=20tagged?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Delete swept the course list the handler had read and then removed the row, so a pump adding a course in between left class_course rows tagged with a blueprint that no longer existed — reachable by nothing, since the sweep is the only thing that reads the tag. Delete now takes a compare-and-set on that list, removes the row first and only then sweeps by the tag itself, so a racing addition is swept too; the pump answers blueprint_deleted rather than landing an orphan, claiming the blueprint inside its own transaction; and BLUEPRINT_LOCK closes what neither could, since SurrealDB does not serialise the pump's cross-record read against this delete. The residue is a process crash between the delete and the sweep, which no lock survives: inert rows, a detach each, counters exact. The pump's created-row slot was hand-counted (7, or 9 on an axis with a pivot claim). The guard would have shifted it silently on the only path that uses the guard, so the statement list is built as a list and the slot is read off its length. --- README.md | 30 ++- src/domain/class_blueprint.rs | 338 +++++++++++++++++++++++++++++++--- src/domain/class_course.rs | 11 +- src/domain/class_member.rs | 6 + src/domain/class_pump.rs | 136 ++++++++++---- src/lib.rs | 2 +- src/web/classes.rs | 10 +- tests/regress_blueprints.rs | 104 +++++++++++ 8 files changed, 565 insertions(+), 72 deletions(-) diff --git a/README.md b/README.md index 86995dc..88fd774 100644 --- a/README.md +++ b/README.md @@ -847,7 +847,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/classes/blueprints` | manager | List every grade blueprint · paged | | GET | `/classes/blueprints/{grade}` | manager | One grade's blueprint | | PATCH | `/classes/blueprints/{grade}` | manager | Replace the course list and reconcile every section at that grade (returns `skipped`) | -| DELETE | `/classes/blueprints/{grade}` | manager | Delete the blueprint and detach every attachment it made | +| DELETE | `/classes/blueprints/{grade}` | manager | Delete the blueprint and detach every attachment it made (409 if the list changed since it was read) | | POST | `/classes/{id}/blueprint` | manager | Stock one section from its grade's blueprint (returns `skipped`) | | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) | | GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) · paged | @@ -2872,8 +2872,10 @@ actually failed: `class_deleted` (the section vanished mid-pump), from the template, so the template shrinks and the skip is reported once and never again), `class_at_course_ceiling`, `class_roster_too_large` (the section holds more students than one attach may enroll at once), `course_full` (no free -seat for the whole section), and `linked_course_missing` (another course -already attached to that section no longer exists — detach it first). +seat for the whole section), `linked_course_missing` (another course +already attached to that section no longer exists — detach it first), and +`blueprint_deleted` (the template itself was deleted while the pump ran — +nothing was attached, and there is nothing left to retry). **Removal spares what a human placed.** Every attachment a blueprint makes is tagged with it. Dropping a course from the list detaches it only where the @@ -2882,6 +2884,28 @@ class first exactly as a manual detach does), and a course a human attached to that class by hand carries no tag and is left exactly where it is. Deleting a blueprint applies that to its whole list. +`DELETE /classes/blueprints/{grade}` removes the row **first** and then sweeps +by that tag, rather than by the list the call read: an edit that adds a course +and pumps it while the delete runs would otherwise leave rows tagged with a +blueprint that no longer exists, and since the grade label *is* the record id, +nothing could ever reach them again. The pump carries the other half of that — +an attach whose blueprint was deleted mid-run writes nothing and is reported as +`blueprint_deleted`. Those two narrow the window rather than close it — a pump +that read the template alive can still commit its link after the sweep has run, +since a read of one record and a write of another are not serialized against +each other — so the delete and each individual attach are also serialized in +process: the delete holds a write lease across its compare-and-set and its +sweep, and a pump takes a read lease one course at a time, so a delete never +waits behind a whole grade. The backend runs single-replica by decision, which +is what makes an in-process lock the complete answer. The delete is also a +compare-and-set on the list the call read: a `409` means somebody edited the +template in between, and nothing was written — though a template deleted and +recreated at the same grade with the same list satisfies that comparison, which +is accepted, since the end state is the one the caller asked for. The remaining +cost is a **process crash** between the delete and its sweep, which no lock +survives: it leaves inert tagged attachments behind, still detachable one at a +time at `DELETE /classes/{id}/courses/{course}`, with every counter exact. + A blueprint names no term — the class names its own. The grade label is the blueprint's id, so there is one per grade (a second is a `409`), and it must be non-empty and contain none of `/ \ ? # %`. diff --git a/src/domain/class_blueprint.rs b/src/domain/class_blueprint.rs index 725018b..87ae9ea 100644 --- a/src/domain/class_blueprint.rs +++ b/src/domain/class_blueprint.rs @@ -32,6 +32,7 @@ //! the same reason the pump does. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use tokio::sync::RwLock; use crate::constant::{CLASS_BLUEPRINT_TABLE, CLASS_COURSE_TABLE, MAX_CLASS_COURSES}; use crate::database::Database; @@ -43,6 +44,33 @@ use crate::domain::page::PagedList; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; +/// Serializes a blueprint's delete against the attaches made on its behalf. +/// +/// [`ClassBlueprint::delete`] removes the row and then sweeps by the provenance +/// tag, and every guarded attach reads that same row *inside* its own +/// transaction ([`crate::domain::class_pump::attach`]'s `source` claim). Those +/// two are a cross-record read-then-write racing a write to the record read, +/// which `BEGIN`/`COMMIT` does not serialize (SurrealDB write skew): a pump can +/// see the blueprint alive, have the delete commit and sweep past it, and only +/// then commit its own `class_course` row — tagged with a record that no longer +/// exists and that no sweep can ever reach again, since the grade label *is* +/// the id. Delete-first and the in-transaction claim narrow that window; this +/// closes it. +/// +/// The delete holds the **write** lease across its compare-and-set and its +/// sweep, so the sweep sees every attach that committed before it and no attach +/// commits after it. Each guarded attach holds the **read** lease for the span +/// of its own transaction — taken per course in [`ClassBlueprint::apply_to`], +/// never around a whole pump, so a delete waits behind one attach rather than +/// an unbounded loop. `tokio`'s `RwLock` is fair, so a steady stream of pump +/// leases cannot starve that waiting delete. +/// +/// In-process is deployment-wide here: single-replica by decision, with +/// stop-the-world upgrades — the same argument +/// [`crate::domain::settings::SETTINGS_LOCK`] makes. No other lock is taken +/// under it, so it has no ordering rule to break. +pub(crate) static BLUEPRINT_LOCK: RwLock<()> = RwLock::const_new(()); + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ClassBlueprintId(RecordId); @@ -109,7 +137,9 @@ pub struct Skip { /// vanished when the course did sends them to look at a section that is /// standing right there. `linked_course_missing` is a third: *another* course /// already attached to this class no longer exists, and it must be detached -/// before this attach can be retried. +/// before this attach can be retried. `blueprint_deleted` is the pump losing +/// the template itself mid-run — the only skip that says nothing about the +/// (class, course) pair it names. fn skip_reason(landed: &Attached) -> Option<&'static str> { match landed { Attached::Made(_) | Attached::Duplicate => None, @@ -119,6 +149,7 @@ fn skip_reason(landed: &Attached) -> Option<&'static str> { Attached::ClassOverloaded => Some("class_roster_too_large"), Attached::Full(_) => Some("course_full"), Attached::CourseGone(_) => Some("linked_course_missing"), + Attached::SourceGone => Some("blueprint_deleted"), } } @@ -242,6 +273,14 @@ impl ClassBlueprint { /// /// Removals run first: a course leaving frees a place under the per-class /// course ceiling that the same edit's additions can then use. + /// + /// Takes no [`BLUEPRINT_LOCK`] lease, deliberately: holding the write lease + /// across its own pump would deadlock on the read lease that pump takes, + /// and a lease would close nothing anyway — the pump's claim asks whether + /// the blueprint *exists*, not what it holds, so an edit racing a pump is + /// only ever the retro-pump this feature is built on. Rows a racing edit + /// leaves behind stay reachable, because [`Self::delete`] sweeps the whole + /// tag rather than a list. pub async fn set_courses( self, courses: Vec, @@ -273,7 +312,7 @@ impl ClassBlueprint { None => Err(AppError::NotFound), }; }; - saved.drop_courses(&dropped, db).await?; + saved.drop_courses(Some(&dropped), db).await?; let skipped = saved.pump(by, db).await?; Ok((saved, skipped)) } @@ -282,16 +321,79 @@ impl ClassBlueprint { /// human attached to those classes by hand carry no `source` and are left /// exactly where they are — the same cut a single removal makes, applied to /// the whole list, because a template that is gone owns nothing. + /// + /// The row goes **first**, and the sweep that follows is by the provenance + /// tag rather than by the list this caller read. Sweeping first was the + /// mirror image of a race: a `PATCH` adding a course and pumping it while + /// this ran landed rows tagged with a blueprint the delete then removed, + /// and nothing could ever sweep them again — the grade label *is* the + /// record id, so only a blueprint recreated at that grade could even name + /// them. Never revert to sweep-first. + /// + /// Deleting first plus the pump's own in-transaction claim on this row + /// ([`Attached::SourceGone`]) **narrows** that window; it does not close + /// it. The claim is a read of `class_blueprint` in a transaction that + /// writes `class_course`, racing this delete's write to + /// `class_blueprint` — a cross-record pair `BEGIN`/`COMMIT` does not + /// serialize, so a pump that read the row alive can still commit its link + /// after the sweep has run. [`BLUEPRINT_LOCK`] is what closes it: the write + /// lease below spans the compare-and-set and the sweep, the read lease in + /// [`Self::apply_to`] spans each attach, and single-replica deployment + /// makes an in-process lock the whole answer. + /// + /// What is left is a **process crash** between the delete and the sweep — a + /// lock does not survive the process. That leaves inert `class_course` rows + /// tagged with a blueprint that is gone; they are still detachable one at a + /// time at `DELETE /classes/{id}/courses/{course}`, and every counter stays + /// exact because each detach is its own transaction. + /// + /// The delete is a compare-and-set on the list this caller read, like + /// [`Self::set_courses`]: an edit landing in between is a `409` rather than + /// a silent detach of somebody else's additions. Known hole, accepted: the + /// grade label *is* the record id and the comparison is by **content**, so + /// a blueprint deleted and recreated at the same grade with the same list + /// satisfies `WHERE courses = $held` and this call deletes the *new* row. + /// Content-equal is intent-equal — the end state is the one the caller + /// asked for — and telling the two apart needs a revision column on the + /// row, which nothing else here would use. pub async fn delete(self, db: &Database) -> Result<(), AppError> { - self.drop_courses(&self.courses.clone(), db).await?; - let gone: Option = db.delete(self.id.record()).await?; - gone.map(|_| ()).ok_or(AppError::NotFound) + // Held through the sweep: it must see every attach that committed + // before it, and no attach may commit after it. + let _lease = BLUEPRINT_LOCK.write().await; + let mut result = db + .query("DELETE $id WHERE courses = $held RETURN BEFORE") + .bind(("id", self.id.record())) + .bind(("held", self.courses.clone())) + .await? + .check()?; + if result.take::>(0)?.is_empty() { + // Matched nothing: the row is gone, or its list moved since this + // caller read it. Only this path pays for the read that tells them + // apart. + return match Self::read(&self.id, db).await? { + Some(_) => Err(AppError::Conflict( + "this blueprint changed since you read it — re-read and retry", + )), + None => Err(AppError::NotFound), + }; + } + self.drop_courses(None, db).await } /// Attach every course in this blueprint to `class`, skipping — never /// aborting on — the ones that do not fit. A course already on the class is /// a no-op, whoever attached it: this is what makes a pump repeatable, and /// what stops it re-tagging a hand-attached course as its own. + /// + /// This is the *only* place a sourced attach is made — [`Self::pump`], the + /// create-time and per-class pumps in [`crate::web::classes`] all come + /// through here — so it is where each one takes [`BLUEPRINT_LOCK`] for + /// reading, one course at a time. A delete landing mid-pump is then clean + /// by construction: the attaches that already committed are found by its + /// tag sweep, and the ones that have not yet started meet the deleted row + /// at their own in-transaction claim and answer `blueprint_deleted`. Per + /// course rather than per pump, because the pump's loop is unbounded and a + /// delete may not wait behind all of it. pub async fn apply_to( &self, class: &ClassGroup, @@ -300,8 +402,10 @@ impl ClassBlueprint { ) -> Result, AppError> { let mut skipped = Vec::new(); for course in &self.courses { - let landed = - ClassCourse::attach_sourced(class.get_id(), course, by, Some(&self.id), db).await?; + let landed = { + let _lease = BLUEPRINT_LOCK.read().await; + ClassCourse::attach_sourced(class.get_id(), course, by, Some(&self.id), db).await? + }; if matches!(landed, Attached::PivotGone) { self.prune(course, db).await?; } @@ -343,6 +447,10 @@ impl ClassBlueprint { /// and re-running it changes nothing. No sweep follows it either — the /// attachments it would sweep are exactly the ones the course's own delete /// already took. + /// + /// No [`BLUEPRINT_LOCK`] lease either: an `UPDATE` of a record that is gone + /// writes nothing, so this cannot resurrect a blueprint a delete took while + /// the pump around it was running. async fn prune(&self, course: &CourseId, db: &Database) -> Result<(), AppError> { db.query("UPDATE $id SET courses = array::complement(courses ?? [], [$course])") .bind(("id", self.id.record())) @@ -352,8 +460,13 @@ impl ClassBlueprint { Ok(()) } - /// Detach `courses` from every class *this blueprint* attached them to, and - /// sweep the enrollments those attachments pumped. + /// Detach this blueprint's attachments — the ones for `courses`, or *every* + /// row carrying its tag when `None` — and sweep the enrollments they + /// pumped. + /// + /// `None` is the delete's whole point: it asks the tag rather than a list, + /// so a course a racing edit added and pumped after this caller read the + /// row is swept too, which no snapshot of the list could ever name. /// /// `source` is the whole filter, so a row without the key — a hand attach — /// is never matched, and a class that acquired the same course by hand @@ -375,26 +488,40 @@ impl ClassBlueprint { /// The rows are read first rather than derived from the classes at this /// grade: a class whose grade was edited after the pump still carries this /// blueprint's attachments, and only the `source` tag can find it. - async fn drop_courses(&self, courses: &[CourseId], db: &Database) -> Result<(), AppError> { - for course in courses { - let mut found = db - .query(format!( - "SELECT VALUE id FROM {CLASS_COURSE_TABLE} \ - WHERE course = $course AND source = $blueprint" - )) - .bind(("course", course.record())) - .bind(("blueprint", self.id.record())) - .await? - .check()?; - for link in found.take::>(0)? { - detach( - "$link", - Axis::Course, - &[("link".into(), link.into_value())], - db, - ) - .await?; - } + async fn drop_courses( + &self, + courses: Option<&[CourseId]>, + db: &Database, + ) -> Result<(), AppError> { + let named: Vec = courses + .unwrap_or_default() + .iter() + .map(CourseId::record) + .collect(); + if courses.is_some() && named.is_empty() { + return Ok(()); + } + let only = if courses.is_some() { + "AND course IN $courses" + } else { + "" + }; + let mut found = db + .query(format!( + "SELECT VALUE id FROM {CLASS_COURSE_TABLE} WHERE source = $blueprint {only}" + )) + .bind(("blueprint", self.id.record())) + .bind(("courses", named)) + .await? + .check()?; + for link in found.take::>(0)? { + detach( + "$link", + Axis::Course, + &[("link".into(), link.into_value())], + db, + ) + .await?; } Ok(()) } @@ -403,7 +530,8 @@ impl ClassBlueprint { #[cfg(test)] mod tests { use super::*; - use crate::domain::class_member::tests::{a_class, a_course}; + use crate::constant::CLASS_COURSE_COUNT_FIELD; + use crate::domain::class_member::tests::{a_class, a_course, counter, rows}; /// A blueprint holding `courses`, at grade "9". async fn a_blueprint(courses: Vec, db: &Database) -> ClassBlueprint { @@ -519,6 +647,155 @@ mod tests { ); } + /// The delete is a compare-and-set, and it runs *before* the sweep — so a + /// handle whose list moved cannot take the row, and nothing it would have + /// swept is touched either. + /// + /// Provoked with a stale handle rather than a concurrent request, which is + /// exactly the state a `PATCH` landing between the read and the delete puts + /// this caller in, and deterministic where two live requests are not. + #[tokio::test] + async fn a_delete_of_a_list_that_moved_is_a_409_that_writes_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let algebra = a_course("algebra", None, &db).await; + let physics = a_course("physics", None, &db).await; + let class = ClassGroup::read(&a_class("9-A", &db).await, &db) + .await + .unwrap() + .unwrap(); + let stale = a_blueprint(vec![algebra.clone()], &db).await; + stale.apply_to(&class, &manager, &db).await.unwrap(); + + // The edit this caller did not see: it adds a course and pumps it into + // the section. (The pump is applied by hand because the helper class + // carries no grade for `set_courses`'s own loop to find.) + let (edited, _) = ClassBlueprint::read(stale.get_id(), &db) + .await + .unwrap() + .unwrap() + .set_courses(vec![algebra, physics], &manager, &db) + .await + .unwrap(); + edited.apply_to(&class, &manager, &db).await.unwrap(); + + let refused = stale.delete(&db).await; + assert!( + matches!(refused, Err(AppError::Conflict(_))), + "a list that moved is a 409, not a silent delete: {refused:?}" + ); + assert!( + ClassBlueprint::read(&ClassBlueprintId::from_key("9"), &db) + .await + .unwrap() + .is_some(), + "the row the caller did not read is still there" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_course", &db).await, + 2, + "and neither attachment was swept — including the one this handle \ + never knew about" + ); + } + + /// The lease is real: a delete cannot start while a guarded attach holds + /// the read side. + /// + /// That is the whole point of the lock — without it a pump could commit its + /// `class_course` row *after* the delete had swept past, stranding a row + /// tagged with a blueprint nothing can reach. Two live requests would be a + /// coin flip the in-memory engine lies about, so the lease is held directly + /// and the delete is watched not-finishing on a timeout. + #[tokio::test] + async fn a_delete_waits_for_an_attach_in_flight() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let algebra = a_course("algebra", None, &db).await; + let class = ClassGroup::read(&a_class("9-A", &db).await, &db) + .await + .unwrap() + .unwrap(); + let blueprint = a_blueprint(vec![algebra], &db).await; + blueprint.apply_to(&class, &manager, &db).await.unwrap(); + + // Stand in for an attach mid-transaction, which is exactly the lease + // `apply_to` holds around one course. + let attaching = BLUEPRINT_LOCK.read().await; + let mut deleting = { + let db = db.clone(); + let blueprint = blueprint.clone(); + tokio::spawn(async move { blueprint.delete(&db).await }) + }; + assert!( + tokio::time::timeout(std::time::Duration::from_millis(150), &mut deleting) + .await + .is_err(), + "the delete must not run while an attach is in flight" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_blueprint", &db).await, + 1, + "…and it must not have swept anything either" + ); + + drop(attaching); + deleting.await.unwrap().unwrap(); + assert_eq!( + rows("SELECT VALUE id FROM class_blueprint", &db).await, + 0, + "once the attach is done the delete goes through" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_course", &db).await, + 0, + "…taking every row carrying its tag with it" + ); + } + + /// The other half: a pump holding a handle to a blueprint that has since + /// been deleted writes nothing at all, and says so with its own code. + /// + /// Without the in-transaction claim the attach would land a `class_course` + /// row tagged with a record that no longer exists — the delete's sweep has + /// already run, and the grade label *is* the id, so nothing could ever + /// reach that row again. + #[tokio::test] + async fn a_pump_whose_blueprint_died_attaches_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let algebra = a_course("algebra", None, &db).await; + let class = ClassGroup::read(&a_class("9-A", &db).await, &db) + .await + .unwrap() + .unwrap(); + let stale = a_blueprint(vec![algebra], &db).await; + ClassBlueprint::read(stale.get_id(), &db) + .await + .unwrap() + .unwrap() + .delete(&db) + .await + .unwrap(); + + let skipped = stale.apply_to(&class, &manager, &db).await.unwrap(); + assert_eq!(skipped.len(), 1, "{skipped:?}"); + assert_eq!( + skipped[0].reason, "blueprint_deleted", + "the template went, not the class or the course" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_course", &db).await, + 0, + "a row tagged with a deleted blueprint is one nothing can sweep" + ); + assert_eq!( + counter(CLASS_COURSE_COUNT_FIELD, class.get_id().record(), &db).await, + 0, + "…and no counter moved for it" + ); + } + #[test] fn a_grade_key_must_be_addressable() { assert!(ClassBlueprint::grade_key("").is_err()); @@ -572,6 +849,7 @@ mod tests { Attached::CourseGone("course:algebra".into()), "linked_course_missing", ), + (Attached::SourceGone, "blueprint_deleted"), ] { assert_eq!( skip_reason(&refusal), diff --git a/src/domain/class_course.rs b/src/domain/class_course.rs index da5d14a..b09b495 100644 --- a/src/domain/class_course.rs +++ b/src/domain/class_course.rs @@ -118,6 +118,11 @@ impl ClassCourse { Attached::CourseGone(course) => Err(AppError::ConflictOwned(format!( "{course} no longer exists — detach it from this class first" ))), + // This path passes no source, so the claim that answers this is + // never in the transaction it ran. + Attached::SourceGone => Err(AppError::Internal( + "a hand attach has no blueprint to lose".into(), + )), } } @@ -132,7 +137,10 @@ impl ClassCourse { /// /// `source` is the provenance tag, and it is written by the same statement /// that writes the link, so no attachment can exist without the answer to - /// "may a blueprint take this back". + /// "may a blueprint take this back". It is also *claimed* in that + /// transaction ([`Attached::SourceGone`]): a blueprint deleted while this + /// pump ran has already swept by that tag, so a row landing afterwards + /// would carry a name nothing can reach. pub(crate) async fn attach_sourced( class: &ClassGroupId, course: &CourseId, @@ -155,6 +163,7 @@ impl ClassCourse { &link, course.record(), attached_by.record(), + source.map(ClassBlueprintId::record), db, ) .await diff --git a/src/domain/class_member.rs b/src/domain/class_member.rs index 3390167..703fd6c 100644 --- a/src/domain/class_member.rs +++ b/src/domain/class_member.rs @@ -95,6 +95,7 @@ impl ClassMember { &member, user.record(), added_by.record(), + None, db, ) .await? @@ -123,6 +124,11 @@ impl ClassMember { Attached::CourseGone(course) => Err(AppError::ConflictOwned(format!( "{course} no longer exists — detach it from this class first" ))), + // Only an attach run on a blueprint's behalf states that claim, and + // a membership is nobody's but its own. + Attached::SourceGone => Err(AppError::Internal( + "a class membership has no blueprint to lose".into(), + )), } } diff --git a/src/domain/class_pump.rs b/src/domain/class_pump.rs index b6c2097..d9b836a 100644 --- a/src/domain/class_pump.rs +++ b/src/domain/class_pump.rs @@ -58,13 +58,33 @@ use crate::error::AppError; /// transaction's write loop (see [`Axis::cap`]). It is its own marker because /// "this class holds too many courses" is not an answer anyone can act on when /// it is reported as "this class holds too many students". +/// +/// `SOURCE_MARK` is the record that *asked* for this attach — a grade blueprint +/// — being gone by the time the transaction runs. It is the only marker a +/// caller opts into (only a sourced attach states the claim), and it exists +/// because a blueprint's delete sweeps by that tag: a row landing after the +/// sweep would carry the name of a template no sweep can ever reach again. const HELD_MARK: &str = "class_held"; const GONE_MARK: &str = "class_gone"; const CAP_MARK: &str = "class_cap"; const OVER_MARK: &str = "class_over"; +const SOURCE_MARK: &str = "class_no_blueprint"; const FULL_MARK: &str = "class_full:"; const MISSING_MARK: &str = "class_no_course:"; +/// An in-transaction existence claim as its own two statements: read `read` +/// into `$name`, and abort with `mark` when it matched nothing. +/// +/// Two statements and not one string, because [`attach`] takes the `CREATE`'s +/// result slot off the *length* of its statement list — a pair returned as one +/// element would count as one slot and silently read the wrong result back. +fn claim(name: &str, read: &str, mark: &str) -> Vec { + vec![ + format!("LET ${name} = ({read})"), + format!("IF array::len(${name}) = 0 {{ THROW '{mark}' }}"), + ] +} + /// What [`attach`] settled. #[derive(Debug)] pub(crate) enum Attached { @@ -98,6 +118,12 @@ pub(crate) enum Attached { /// a stale `class_course` link. Nothing was written, and no capacity anyone /// can raise will change that answer. CourseGone(String), + /// The blueprint this attach was sourced from is gone — a delete landed + /// between the pump reading the template and this transaction running. + /// Nothing was written, which is the point: a row tagged with a blueprint + /// that no longer exists is one nothing can ever sweep. Only a sourced + /// attach can be answered this. + SourceGone, } /// Which way the pump runs: the loop below needs a `(course, user)` pair per @@ -157,13 +183,16 @@ impl Axis { /// class write's to touch, and a membership left pointing at a deleted user /// is still removable by its own route — which is exactly what a link to a /// deleted course was not. - fn pivot_claim(&self) -> String { + fn pivot_claim(&self) -> Vec { match self { - Axis::Member => String::new(), - Axis::Course => format!( - "LET $alive = (UPDATE $pivot SET {ENROLLMENT_COUNT_FIELD} = \ - {ENROLLMENT_COUNT_FIELD} RETURN VALUE id); - IF array::len($alive) = 0 {{ THROW '{GONE_MARK}' }};" + Axis::Member => Vec::new(), + Axis::Course => claim( + "alive", + &format!( + "UPDATE $pivot SET {ENROLLMENT_COUNT_FIELD} = \ + {ENROLLMENT_COUNT_FIELD} RETURN VALUE id" + ), + GONE_MARK, ), } } @@ -252,6 +281,11 @@ impl Axis { /// and re-sending the whole cascade then *sees* the row and takes the other /// branch. The retry converges instead of re-asking a settled question, which /// is the restriction's actual test. +/// +/// `source` is the record whose behalf this attach runs on — a grade blueprint +/// — and supplying it adds one more claim: that it is still there when the +/// transaction runs ([`Attached::SourceGone`]). A hand attach owns itself and +/// passes `None`. pub(crate) async fn attach( class: &ClassGroupId, axis: Axis, @@ -259,27 +293,46 @@ pub(crate) async fn attach( row: &T, pivot: RecordId, by: RecordId, + source: Option, db: &Database, ) -> Result, AppError> { let count_field = axis.counter(); let pairs = axis.pairs(); - let alive = axis.pivot_claim(); let other = axis.other(); let over_field = other.counter(); + // One statement per element, because the `CREATE`'s result slot is this + // list's own length at the moment it is pushed. It used to be a + // hand-counted constant with a case per optional claim, and only the path + // carrying that claim would ever have paid for a miscount. + let mut statements = vec![ + "BEGIN TRANSACTION".to_string(), + "LET $held = (SELECT VALUE id FROM $link)".to_string(), + format!("IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}"), + ]; + if source.is_some() { + statements.extend(claim("source", "SELECT VALUE id FROM $guard", SOURCE_MARK)); + } + statements.extend(axis.pivot_claim()); // Read off the class row inside the transaction that claims it, so the // count this refuses on is the one the pair loop below would iterate. - let sql = format!( - "BEGIN TRANSACTION; - LET $held = (SELECT VALUE id FROM $link); - IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; - {alive} - LET $over = (SELECT VALUE id FROM $class WHERE ({over_field} ?? 0) > $other_cap); - IF array::len($over) > 0 {{ THROW '{OVER_MARK}' }}; - LET $counted = (UPDATE $class SET {count_field} = ({count_field} ?? 0) + 1 \ - WHERE ({count_field} ?? 0) < $class_cap RETURN VALUE id); - IF array::len($counted) = 0 {{ THROW '{CAP_MARK}' }}; - CREATE $link CONTENT $row; - FOR $pair IN (({pairs}) ?? []) {{ + statements.push(format!( + "LET $over = (SELECT VALUE id FROM $class WHERE ({over_field} ?? 0) > $other_cap)" + )); + statements.push(format!( + "IF array::len($over) > 0 {{ THROW '{OVER_MARK}' }}" + )); + statements.push(format!( + "LET $counted = (UPDATE $class SET {count_field} = ({count_field} ?? 0) + 1 \ + WHERE ({count_field} ?? 0) < $class_cap RETURN VALUE id)" + )); + statements.push(format!( + "IF array::len($counted) = 0 {{ THROW '{CAP_MARK}' }}" + )); + // Taken as it is pushed: this is the slot the link row comes back out of. + let made = statements.len(); + statements.push("CREATE $link CONTENT $row".to_string()); + statements.push(format!( + "FOR $pair IN (({pairs}) ?? []) {{ LET $seat_of = type::record('{ENROLLMENT_TABLE}', string::concat( record::id($pair.course), '_', record::id($pair.user))); IF array::len((SELECT VALUE id FROM $seat_of)) = 0 {{ @@ -296,26 +349,32 @@ pub(crate) async fn attach( CREATE $seat_of CONTENT {{ course: $pair.course, user: $pair.user, \ enrolled_by: $by, source: $class }}; }}; - }}; - COMMIT TRANSACTION;" - ); + }}" + )); + statements.push("COMMIT TRANSACTION".to_string()); + let sql = format!("{};", statements.join(";\n")); + let mut bindings = vec![ + ("class".into(), class.record().into_value()), + ("link".into(), link.clone().into_value()), + ("row".into(), row.clone().into_value()), + ("pivot".into(), pivot.into_value()), + ("by".into(), by.into_value()), + ("unlimited".into(), cap::UNLIMITED.into_value()), + ("class_cap".into(), axis.cap().into_value()), + ("other_cap".into(), other.cap().into_value()), + ]; + if let Some(guard) = source { + bindings.push(("guard".into(), guard.into_value())); + } let (mut result, mut errors) = transaction_with_retry( db, &sql, - &[ - ("class".into(), class.record().into_value()), - ("link".into(), link.clone().into_value()), - ("row".into(), row.clone().into_value()), - ("pivot".into(), pivot.into_value()), - ("by".into(), by.into_value()), - ("unlimited".into(), cap::UNLIMITED.into_value()), - ("class_cap".into(), axis.cap().into_value()), - ("other_cap".into(), other.cap().into_value()), - ], + &bindings, &[ HELD_MARK, GONE_MARK, OVER_MARK, + SOURCE_MARK, CAP_MARK, FULL_MARK, MISSING_MARK, @@ -338,6 +397,16 @@ pub(crate) async fn attach( { return Ok(Attached::Duplicate); } + // The blueprint that asked for this attach is gone, and that outranks every + // refusal below it: none of them is an answer anyone can act on once the + // template that wanted the row has been deleted — and its claim stands + // first in the transaction, so it aborts before they could fire anyway. + if errors + .values() + .any(|error| error.to_string().contains(SOURCE_MARK)) + { + return Ok(Attached::SourceGone); + } if errors .values() .any(|error| error.to_string().contains(GONE_MARK)) @@ -381,9 +450,6 @@ pub(crate) async fn attach( if let Some(error) = errors.drain().map(|(_, error)| error).next() { return Err(error.into()); } - // Slots count BEGIN and three LET/IF pairs: the CREATE is slot 7 — or 9 on - // an axis that claims its pivot with a LET/IF pair of its own. - let made = if alive.is_empty() { 7 } else { 9 }; result .take::>(made)? .into_iter() diff --git a/src/lib.rs b/src/lib.rs index 8d79a62..c8fd770 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,7 +50,7 @@ use crate::state::AppState; (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked, an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"), (name = "events", description = "Calendar events and attendance. An event's `audience` is its expected-attendee roster, not a visibility wall: everyone sees every event. Aim it at the whole school, one role, a course's enrollment, a class section's (şube) roster, or a hand-built registration list. Rosters resolve live, so role changes, (un)enrollments and class-roster changes move people in and out by themselves. Attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"), (name = "courses", description = "Courses — kind `course` (a regular taught course), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. Both rights are re-checked against the caller's live role on every request: `creator` is a historical column no demotion sweeps, so an account that falls below `teacher` keeps neither management nor deletion of a course it made (the course stays reachable to its assigned teachers and to manager+), and the course drops out of their `/courses`, `/exams` and `/homework` catalogs unless they are enrolled in it. A session's `teacher` column carries the same floor: teaching a session grants neither its roll call nor a view of it once the account falls below `teacher`. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) — empty the roster first"), - (name = "classes", description = "Class sections (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class — the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept — and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent — the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sınıf öğretmeni) with `teacher_id` — any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role — staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole. A grade may also carry a **blueprint** (`/classes/blueprints`): the list of courses every section at that grade takes. Creating or editing one retro-pumps every class already at the grade, and does so best-effort — a section that cannot take a course (it is at its course ceiling, or the course has no free seat for the whole section) is skipped and returned in `skipped`, while every other section is still stocked, so a blueprint edit can leave a deliberately partial state. Each skip's `reason` is a machine code out of a closed set the client words itself (`class_deleted`, `course_deleted`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`, `linked_course_missing`), like every other enum here. Dropping a course from a blueprint detaches it wherever the blueprint attached it (and deleting the blueprint drops its whole list), but a course a human attached to a class by hand carries no blueprint tag and always survives — the same absent-key rule that protects an individually placed enrollment. A blueprint names no term; the class names its own. The grade label is the blueprint's id, so there is exactly one per grade, and it must be non-empty and free of `/ \\ ? # %`"), + (name = "classes", description = "Class sections (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class — the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept — and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent — the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sınıf öğretmeni) with `teacher_id` — any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role — staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole. A grade may also carry a **blueprint** (`/classes/blueprints`): the list of courses every section at that grade takes. Creating or editing one retro-pumps every class already at the grade, and does so best-effort — a section that cannot take a course (it is at its course ceiling, or the course has no free seat for the whole section) is skipped and returned in `skipped`, while every other section is still stocked, so a blueprint edit can leave a deliberately partial state. Each skip's `reason` is a machine code out of a closed set the client words itself (`class_deleted`, `course_deleted`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`, `linked_course_missing`, `blueprint_deleted`), like every other enum here. Dropping a course from a blueprint detaches it wherever the blueprint attached it (and deleting the blueprint drops its whole list — the row goes first and the attachments are then swept by their tag, so a course another manager added and pumped while the delete ran is swept too, and a pump that loses its blueprint mid-run attaches nothing and reports `blueprint_deleted`; deleting a blueprint whose list moved since the caller read it is a `409`), but a course a human attached to a class by hand carries no blueprint tag and always survives — the same absent-key rule that protects an individually placed enrollment. A blueprint names no term; the class names its own. The grade label is the blueprint's id, so there is exactly one per grade, and it must be non-empty and free of `/ \\ ? # %`"), (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher). Roll call is also what feeds two badge counters (see `users`): the first mark taken for a lesson credits its teacher's `lessons_held_total` once, and a student marked `present` or `late` gains a `lessons_attended_total` a later correction gives back"), (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"), diff --git a/src/web/classes.rs b/src/web/classes.rs index 33639dd..cc26911 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -938,9 +938,11 @@ struct SkipResponse { /// is reported once and never again), `class_at_course_ceiling` (the /// section already holds `max_class_courses`), `class_roster_too_large` /// (the section holds more students than one attach may enroll at once), - /// `course_full` (the course has no free seat for the whole section), and + /// `course_full` (the course has no free seat for the whole section), /// `linked_course_missing` (another course already attached to this - /// section no longer exists — detach it before retrying). + /// section no longer exists — detach it before retrying), and + /// `blueprint_deleted` (the blueprint itself was deleted while the pump + /// ran; nothing was attached, and there is nothing left to retry). #[schema(example = "course_full")] reason: String, } @@ -1150,6 +1152,9 @@ async fn update_blueprint( /// blueprint made is detached with it (their pumped enrollments swept the usual /// way); a course a human attached to one of those classes by hand carries no /// blueprint tag and survives. +/// +/// A `409` means the course list changed between this call reading the +/// blueprint and deleting it — nothing was written; re-read and retry. #[utoipa::path( delete, path = "/blueprints/{grade}", @@ -1161,6 +1166,7 @@ async fn update_blueprint( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "No blueprint for that grade", body = ErrorResponse), + (status = 409, description = "The course list changed since this call read it — nothing was written, re-read and retry", body = ErrorResponse), ), )] async fn delete_blueprint( diff --git a/tests/regress_blueprints.rs b/tests/regress_blueprints.rs index 400662b..08812db 100644 --- a/tests/regress_blueprints.rs +++ b/tests/regress_blueprints.rs @@ -641,3 +641,107 @@ async fn a_row_written_before_the_column_reads_as_hand_attached() { 1 ); } + +/// The window the lock exists to close, made visible. +/// +/// `ClassBlueprint::delete` removes the row and then sweeps by the provenance +/// tag, while a pump reads that row inside the transaction that writes the link +/// — a cross-record read-then-write the store does not serialize. A pump that +/// passed its liveness claim and then lost the blueprint commits a +/// `class_course` row tagged with a record nothing can reach, since the grade +/// label *is* the id and no sweep will ever run for it again. +/// +/// Racing two requests would be a coin flip the in-memory engine lies about, so +/// the delete is injected by the database itself: a `DEFINE EVENT` on +/// `class_course` fires *inside* the pump's own transaction, the instant the +/// link row lands — which is exactly "after the guard passed, before the +/// commit", every single time. This is a below-the-lock probe by construction +/// (the store deletes the row, not `ClassBlueprint::delete`), so it does not +/// test `BLUEPRINT_LOCK`; it pins the end state that lock prevents in-process, +/// and the recovery contract that covers the one residue it cannot — a process +/// crash between the delete and its sweep. +#[tokio::test] +async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "mgr", "manager").await; + let algebra = create_course(&app, &manager, "algebra").await; + let made = send( + &app, + "POST", + "/classes/blueprints", + Some(&manager), + Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })), + ) + .await; + assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body); + // The section comes after the template, so nothing is attached until the + // pump below runs. + let class = create_class(&app, &manager, "9-A", "9").await; + assert!(!attached(&class, &algebra, &db).await); + + // Delete the blueprint from inside the very write that attaches on its + // behalf. + db.query( + "DEFINE EVENT lose_blueprint ON TABLE class_course WHEN $event = 'CREATE' \ + THEN { DELETE type::record('class_blueprint', '9'); };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let pumped = send( + &app, + "POST", + &format!("/classes/{class}/blueprint"), + Some(&manager), + None, + ) + .await; + assert_eq!(pumped.status, StatusCode::OK, "{:?}", pumped.body); + assert!( + skips(&pumped).is_empty(), + "the pump was told it succeeded — which is what makes the row below \ + invisible to the caller: {:?}", + pumped.body + ); + + assert_eq!( + rows("SELECT VALUE id FROM class_blueprint", &db).await, + 0, + "the injected delete really landed" + ); + assert!( + attached(&class, &algebra, &db).await, + "the link committed after its blueprint was gone: this is the stranded \ + row, tagged with a record no sweep can ever reach" + ); + assert_eq!(source_of(&class, &algebra, &db).await, Some("9".into())); + + // The documented recovery: a human detaches it one course at a time, and + // the counters come back exact. + let detached = send( + &app, + "DELETE", + &format!("/classes/{class}/courses/{algebra}"), + Some(&manager), + None, + ) + .await; + assert_eq!( + detached.status, + StatusCode::NO_CONTENT, + "{:?}", + detached.body + ); + assert!(!attached(&class, &algebra, &db).await); + assert_eq!( + counter( + &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"), + &db + ) + .await, + 0, + "a stranded row still releases its counter when it is detached" + ); +}