forge
Explore
Log in

Don't you dare go Hollow

🔒 stop a deleted blueprint from stranding the rows it tagged

Browse files at this commit

b1c8e7acbb4ad7acd23551ecb35491dc5d54e886Ahmet Kaan GümüşParent: b7a351c
  • fix
    • 🔒 stop a deleted blueprint from stranding the rows it tagged
Show full message
fix: 🔒 stop a deleted blueprint from stranding the rows it tagged

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.mdmodified+27 -3
@@ -847,7 +847,7 @@ window filtering, before paging; negative values are a `400` naming the field.
847 | GET | `/classes/blueprints` | manager | List every grade blueprint · paged |847 | GET | `/classes/blueprints` | manager | List every grade blueprint · paged |
848 | GET | `/classes/blueprints/{grade}` | manager | One grade's blueprint |848 | GET | `/classes/blueprints/{grade}` | manager | One grade's blueprint |
849 | PATCH | `/classes/blueprints/{grade}` | manager | Replace the course list and reconcile every section at that grade (returns `skipped`) |849 | PATCH | `/classes/blueprints/{grade}` | manager | Replace the course list and reconcile every section at that grade (returns `skipped`) |
850-| DELETE | `/classes/blueprints/{grade}` | manager | Delete the blueprint and detach every attachment it made |850+| DELETE | `/classes/blueprints/{grade}` | manager | Delete the blueprint and detach every attachment it made (409 if the list changed since it was read) |
851 | POST | `/classes/{id}/blueprint` | manager | Stock one section from its grade's blueprint (returns `skipped`) |851 | POST | `/classes/{id}/blueprint` | manager | Stock one section from its grade's blueprint (returns `skipped`) |
852 | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) |852 | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) |
853 | GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) · paged |853 | 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),
2872 from the template, so the template shrinks and the skip is reported once and2872 from the template, so the template shrinks and the skip is reported once and
2873 never again), `class_at_course_ceiling`, `class_roster_too_large` (the section2873 never again), `class_at_course_ceiling`, `class_roster_too_large` (the section
2874 holds more students than one attach may enroll at once), `course_full` (no free2874 holds more students than one attach may enroll at once), `course_full` (no free
2875-seat for the whole section), and `linked_course_missing` (another course2875+seat for the whole section), `linked_course_missing` (another course
2876-already attached to that section no longer exists — detach it first).2876+already attached to that section no longer exists — detach it first), and
2877+`blueprint_deleted` (the template itself was deleted while the pump ran —
2878+nothing was attached, and there is nothing left to retry).
2877 2879
2878 **Removal spares what a human placed.** Every attachment a blueprint makes is2880 **Removal spares what a human placed.** Every attachment a blueprint makes is
2879 tagged with it. Dropping a course from the list detaches it only where the2881 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
2882 that class by hand carries no tag and is left exactly where it is. Deleting a2884 that class by hand carries no tag and is left exactly where it is. Deleting a
2883 blueprint applies that to its whole list.2885 blueprint applies that to its whole list.
2884 2886
2887+`DELETE /classes/blueprints/{grade}` removes the row **first** and then sweeps
2888+by that tag, rather than by the list the call read: an edit that adds a course
2889+and pumps it while the delete runs would otherwise leave rows tagged with a
2890+blueprint that no longer exists, and since the grade label *is* the record id,
2891+nothing could ever reach them again. The pump carries the other half of that —
2892+an attach whose blueprint was deleted mid-run writes nothing and is reported as
2893+`blueprint_deleted`. Those two narrow the window rather than close it — a pump
2894+that read the template alive can still commit its link after the sweep has run,
2895+since a read of one record and a write of another are not serialized against
2896+each other — so the delete and each individual attach are also serialized in
2897+process: the delete holds a write lease across its compare-and-set and its
2898+sweep, and a pump takes a read lease one course at a time, so a delete never
2899+waits behind a whole grade. The backend runs single-replica by decision, which
2900+is what makes an in-process lock the complete answer. The delete is also a
2901+compare-and-set on the list the call read: a `409` means somebody edited the
2902+template in between, and nothing was written — though a template deleted and
2903+recreated at the same grade with the same list satisfies that comparison, which
2904+is accepted, since the end state is the one the caller asked for. The remaining
2905+cost is a **process crash** between the delete and its sweep, which no lock
2906+survives: it leaves inert tagged attachments behind, still detachable one at a
2907+time at `DELETE /classes/{id}/courses/{course}`, with every counter exact.
2908+
2885 A blueprint names no term — the class names its own. The grade label is the2909 A blueprint names no term — the class names its own. The grade label is the
2886 blueprint's id, so there is one per grade (a second is a `409`), and it must be2910 blueprint's id, so there is one per grade (a second is a `409`), and it must be
2887 non-empty and contain none of `/ \ ? # %`.2911 non-empty and contain none of `/ \ ? # %`.
src/domain/class_blueprint.rsmodified+308 -30
@@ -32,6 +32,7 @@
32 //! the same reason the pump does.32 //! the same reason the pump does.
33 33
34 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};34 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
35+use tokio::sync::RwLock;
35 36
36 use crate::constant::{CLASS_BLUEPRINT_TABLE, CLASS_COURSE_TABLE, MAX_CLASS_COURSES};37 use crate::constant::{CLASS_BLUEPRINT_TABLE, CLASS_COURSE_TABLE, MAX_CLASS_COURSES};
37 use crate::database::Database;38 use crate::database::Database;
@@ -43,6 +44,33 @@ use crate::domain::page::PagedList;
43 use crate::domain::user::UserId;44 use crate::domain::user::UserId;
44 use crate::error::{AppError, ValidationError};45 use crate::error::{AppError, ValidationError};
45 46
47+/// Serializes a blueprint's delete against the attaches made on its behalf.
48+///
49+/// [`ClassBlueprint::delete`] removes the row and then sweeps by the provenance
50+/// tag, and every guarded attach reads that same row *inside* its own
51+/// transaction ([`crate::domain::class_pump::attach`]'s `source` claim). Those
52+/// two are a cross-record read-then-write racing a write to the record read,
53+/// which `BEGIN`/`COMMIT` does not serialize (SurrealDB write skew): a pump can
54+/// see the blueprint alive, have the delete commit and sweep past it, and only
55+/// then commit its own `class_course` row — tagged with a record that no longer
56+/// exists and that no sweep can ever reach again, since the grade label *is*
57+/// the id. Delete-first and the in-transaction claim narrow that window; this
58+/// closes it.
59+///
60+/// The delete holds the **write** lease across its compare-and-set and its
61+/// sweep, so the sweep sees every attach that committed before it and no attach
62+/// commits after it. Each guarded attach holds the **read** lease for the span
63+/// of its own transaction — taken per course in [`ClassBlueprint::apply_to`],
64+/// never around a whole pump, so a delete waits behind one attach rather than
65+/// an unbounded loop. `tokio`'s `RwLock` is fair, so a steady stream of pump
66+/// leases cannot starve that waiting delete.
67+///
68+/// In-process is deployment-wide here: single-replica by decision, with
69+/// stop-the-world upgrades — the same argument
70+/// [`crate::domain::settings::SETTINGS_LOCK`] makes. No other lock is taken
71+/// under it, so it has no ordering rule to break.
72+pub(crate) static BLUEPRINT_LOCK: RwLock<()> = RwLock::const_new(());
73+
46 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]74 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
47 pub struct ClassBlueprintId(RecordId);75 pub struct ClassBlueprintId(RecordId);
48 76
@@ -109,7 +137,9 @@ pub struct Skip {
109 /// vanished when the course did sends them to look at a section that is137 /// vanished when the course did sends them to look at a section that is
110 /// standing right there. `linked_course_missing` is a third: *another* course138 /// standing right there. `linked_course_missing` is a third: *another* course
111 /// already attached to this class no longer exists, and it must be detached139 /// already attached to this class no longer exists, and it must be detached
112-/// before this attach can be retried.140+/// before this attach can be retried. `blueprint_deleted` is the pump losing
141+/// the template itself mid-run — the only skip that says nothing about the
142+/// (class, course) pair it names.
113 fn skip_reason(landed: &Attached<ClassCourse>) -> Option<&'static str> {143 fn skip_reason(landed: &Attached<ClassCourse>) -> Option<&'static str> {
114 match landed {144 match landed {
115 Attached::Made(_) | Attached::Duplicate => None,145 Attached::Made(_) | Attached::Duplicate => None,
@@ -119,6 +149,7 @@ fn skip_reason(landed: &Attached<ClassCourse>) -> Option<&'static str> {
119 Attached::ClassOverloaded => Some("class_roster_too_large"),149 Attached::ClassOverloaded => Some("class_roster_too_large"),
120 Attached::Full(_) => Some("course_full"),150 Attached::Full(_) => Some("course_full"),
121 Attached::CourseGone(_) => Some("linked_course_missing"),151 Attached::CourseGone(_) => Some("linked_course_missing"),
152+ Attached::SourceGone => Some("blueprint_deleted"),
122 }153 }
123 }154 }
124 155
@@ -242,6 +273,14 @@ impl ClassBlueprint {
242 ///273 ///
243 /// Removals run first: a course leaving frees a place under the per-class274 /// Removals run first: a course leaving frees a place under the per-class
244 /// course ceiling that the same edit's additions can then use.275 /// course ceiling that the same edit's additions can then use.
276+ ///
277+ /// Takes no [`BLUEPRINT_LOCK`] lease, deliberately: holding the write lease
278+ /// across its own pump would deadlock on the read lease that pump takes,
279+ /// and a lease would close nothing anyway — the pump's claim asks whether
280+ /// the blueprint *exists*, not what it holds, so an edit racing a pump is
281+ /// only ever the retro-pump this feature is built on. Rows a racing edit
282+ /// leaves behind stay reachable, because [`Self::delete`] sweeps the whole
283+ /// tag rather than a list.
245 pub async fn set_courses(284 pub async fn set_courses(
246 self,285 self,
247 courses: Vec<CourseId>,286 courses: Vec<CourseId>,
@@ -273,7 +312,7 @@ impl ClassBlueprint {
273 None => Err(AppError::NotFound),312 None => Err(AppError::NotFound),
274 };313 };
275 };314 };
276- saved.drop_courses(&dropped, db).await?;315+ saved.drop_courses(Some(&dropped), db).await?;
277 let skipped = saved.pump(by, db).await?;316 let skipped = saved.pump(by, db).await?;
278 Ok((saved, skipped))317 Ok((saved, skipped))
279 }318 }
@@ -282,16 +321,79 @@ impl ClassBlueprint {
282 /// human attached to those classes by hand carry no `source` and are left321 /// human attached to those classes by hand carry no `source` and are left
283 /// exactly where they are — the same cut a single removal makes, applied to322 /// exactly where they are — the same cut a single removal makes, applied to
284 /// the whole list, because a template that is gone owns nothing.323 /// the whole list, because a template that is gone owns nothing.
324+ ///
325+ /// The row goes **first**, and the sweep that follows is by the provenance
326+ /// tag rather than by the list this caller read. Sweeping first was the
327+ /// mirror image of a race: a `PATCH` adding a course and pumping it while
328+ /// this ran landed rows tagged with a blueprint the delete then removed,
329+ /// and nothing could ever sweep them again — the grade label *is* the
330+ /// record id, so only a blueprint recreated at that grade could even name
331+ /// them. Never revert to sweep-first.
332+ ///
333+ /// Deleting first plus the pump's own in-transaction claim on this row
334+ /// ([`Attached::SourceGone`]) **narrows** that window; it does not close
335+ /// it. The claim is a read of `class_blueprint` in a transaction that
336+ /// writes `class_course`, racing this delete's write to
337+ /// `class_blueprint` — a cross-record pair `BEGIN`/`COMMIT` does not
338+ /// serialize, so a pump that read the row alive can still commit its link
339+ /// after the sweep has run. [`BLUEPRINT_LOCK`] is what closes it: the write
340+ /// lease below spans the compare-and-set and the sweep, the read lease in
341+ /// [`Self::apply_to`] spans each attach, and single-replica deployment
342+ /// makes an in-process lock the whole answer.
343+ ///
344+ /// What is left is a **process crash** between the delete and the sweep — a
345+ /// lock does not survive the process. That leaves inert `class_course` rows
346+ /// tagged with a blueprint that is gone; they are still detachable one at a
347+ /// time at `DELETE /classes/{id}/courses/{course}`, and every counter stays
348+ /// exact because each detach is its own transaction.
349+ ///
350+ /// The delete is a compare-and-set on the list this caller read, like
351+ /// [`Self::set_courses`]: an edit landing in between is a `409` rather than
352+ /// a silent detach of somebody else's additions. Known hole, accepted: the
353+ /// grade label *is* the record id and the comparison is by **content**, so
354+ /// a blueprint deleted and recreated at the same grade with the same list
355+ /// satisfies `WHERE courses = $held` and this call deletes the *new* row.
356+ /// Content-equal is intent-equal — the end state is the one the caller
357+ /// asked for — and telling the two apart needs a revision column on the
358+ /// row, which nothing else here would use.
285 pub async fn delete(self, db: &Database) -> Result<(), AppError> {359 pub async fn delete(self, db: &Database) -> Result<(), AppError> {
286- self.drop_courses(&self.courses.clone(), db).await?;360+ // Held through the sweep: it must see every attach that committed
287- let gone: Option<ClassBlueprint> = db.delete(self.id.record()).await?;361+ // before it, and no attach may commit after it.
288- gone.map(|_| ()).ok_or(AppError::NotFound)362+ let _lease = BLUEPRINT_LOCK.write().await;
363+ let mut result = db
364+ .query("DELETE $id WHERE courses = $held RETURN BEFORE")
365+ .bind(("id", self.id.record()))
366+ .bind(("held", self.courses.clone()))
367+ .await?
368+ .check()?;
369+ if result.take::<Vec<ClassBlueprint>>(0)?.is_empty() {
370+ // Matched nothing: the row is gone, or its list moved since this
371+ // caller read it. Only this path pays for the read that tells them
372+ // apart.
373+ return match Self::read(&self.id, db).await? {
374+ Some(_) => Err(AppError::Conflict(
375+ "this blueprint changed since you read it — re-read and retry",
376+ )),
377+ None => Err(AppError::NotFound),
378+ };
379+ }
380+ self.drop_courses(None, db).await
289 }381 }
290 382
291 /// Attach every course in this blueprint to `class`, skipping — never383 /// Attach every course in this blueprint to `class`, skipping — never
292 /// aborting on — the ones that do not fit. A course already on the class is384 /// aborting on — the ones that do not fit. A course already on the class is
293 /// a no-op, whoever attached it: this is what makes a pump repeatable, and385 /// a no-op, whoever attached it: this is what makes a pump repeatable, and
294 /// what stops it re-tagging a hand-attached course as its own.386 /// what stops it re-tagging a hand-attached course as its own.
387+ ///
388+ /// This is the *only* place a sourced attach is made — [`Self::pump`], the
389+ /// create-time and per-class pumps in [`crate::web::classes`] all come
390+ /// through here — so it is where each one takes [`BLUEPRINT_LOCK`] for
391+ /// reading, one course at a time. A delete landing mid-pump is then clean
392+ /// by construction: the attaches that already committed are found by its
393+ /// tag sweep, and the ones that have not yet started meet the deleted row
394+ /// at their own in-transaction claim and answer `blueprint_deleted`. Per
395+ /// course rather than per pump, because the pump's loop is unbounded and a
396+ /// delete may not wait behind all of it.
295 pub async fn apply_to(397 pub async fn apply_to(
296 &self,398 &self,
297 class: &ClassGroup,399 class: &ClassGroup,
@@ -300,8 +402,10 @@ impl ClassBlueprint {
300 ) -> Result<Vec<Skip>, AppError> {402 ) -> Result<Vec<Skip>, AppError> {
301 let mut skipped = Vec::new();403 let mut skipped = Vec::new();
302 for course in &self.courses {404 for course in &self.courses {
303- let landed =405+ let landed = {
304- ClassCourse::attach_sourced(class.get_id(), course, by, Some(&self.id), db).await?;406+ let _lease = BLUEPRINT_LOCK.read().await;
407+ ClassCourse::attach_sourced(class.get_id(), course, by, Some(&self.id), db).await?
408+ };
305 if matches!(landed, Attached::PivotGone) {409 if matches!(landed, Attached::PivotGone) {
306 self.prune(course, db).await?;410 self.prune(course, db).await?;
307 }411 }
@@ -343,6 +447,10 @@ impl ClassBlueprint {
343 /// and re-running it changes nothing. No sweep follows it either — the447 /// and re-running it changes nothing. No sweep follows it either — the
344 /// attachments it would sweep are exactly the ones the course's own delete448 /// attachments it would sweep are exactly the ones the course's own delete
345 /// already took.449 /// already took.
450+ ///
451+ /// No [`BLUEPRINT_LOCK`] lease either: an `UPDATE` of a record that is gone
452+ /// writes nothing, so this cannot resurrect a blueprint a delete took while
453+ /// the pump around it was running.
346 async fn prune(&self, course: &CourseId, db: &Database) -> Result<(), AppError> {454 async fn prune(&self, course: &CourseId, db: &Database) -> Result<(), AppError> {
347 db.query("UPDATE $id SET courses = array::complement(courses ?? [], [$course])")455 db.query("UPDATE $id SET courses = array::complement(courses ?? [], [$course])")
348 .bind(("id", self.id.record()))456 .bind(("id", self.id.record()))
@@ -352,8 +460,13 @@ impl ClassBlueprint {
352 Ok(())460 Ok(())
353 }461 }
354 462
355- /// Detach `courses` from every class *this blueprint* attached them to, and463+ /// Detach this blueprint's attachments — the ones for `courses`, or *every*
356- /// sweep the enrollments those attachments pumped.464+ /// row carrying its tag when `None` — and sweep the enrollments they
465+ /// pumped.
466+ ///
467+ /// `None` is the delete's whole point: it asks the tag rather than a list,
468+ /// so a course a racing edit added and pumped after this caller read the
469+ /// row is swept too, which no snapshot of the list could ever name.
357 ///470 ///
358 /// `source` is the whole filter, so a row without the key — a hand attach —471 /// `source` is the whole filter, so a row without the key — a hand attach —
359 /// is never matched, and a class that acquired the same course by hand472 /// is never matched, and a class that acquired the same course by hand
@@ -375,26 +488,40 @@ impl ClassBlueprint {
375 /// The rows are read first rather than derived from the classes at this488 /// The rows are read first rather than derived from the classes at this
376 /// grade: a class whose grade was edited after the pump still carries this489 /// grade: a class whose grade was edited after the pump still carries this
377 /// blueprint's attachments, and only the `source` tag can find it.490 /// blueprint's attachments, and only the `source` tag can find it.
378- async fn drop_courses(&self, courses: &[CourseId], db: &Database) -> Result<(), AppError> {491+ async fn drop_courses(
379- for course in courses {492+ &self,
380- let mut found = db493+ courses: Option<&[CourseId]>,
381- .query(format!(494+ db: &Database,
382- "SELECT VALUE id FROM {CLASS_COURSE_TABLE} \495+ ) -> Result<(), AppError> {
383- WHERE course = $course AND source = $blueprint"496+ let named: Vec<RecordId> = courses
384- ))497+ .unwrap_or_default()
385- .bind(("course", course.record()))498+ .iter()
386- .bind(("blueprint", self.id.record()))499+ .map(CourseId::record)
387- .await?500+ .collect();
388- .check()?;501+ if courses.is_some() && named.is_empty() {
389- for link in found.take::<Vec<RecordId>>(0)? {502+ return Ok(());
390- detach(503+ }
391- "$link",504+ let only = if courses.is_some() {
392- Axis::Course,505+ "AND course IN $courses"
393- &[("link".into(), link.into_value())],506+ } else {
394- db,507+ ""
395- )508+ };
396- .await?;509+ let mut found = db
397- }510+ .query(format!(
511+ "SELECT VALUE id FROM {CLASS_COURSE_TABLE} WHERE source = $blueprint {only}"
512+ ))
513+ .bind(("blueprint", self.id.record()))
514+ .bind(("courses", named))
515+ .await?
516+ .check()?;
517+ for link in found.take::<Vec<RecordId>>(0)? {
518+ detach(
519+ "$link",
520+ Axis::Course,
521+ &[("link".into(), link.into_value())],
522+ db,
523+ )
524+ .await?;
398 }525 }
399 Ok(())526 Ok(())
400 }527 }
@@ -403,7 +530,8 @@ impl ClassBlueprint {
403 #[cfg(test)]530 #[cfg(test)]
404 mod tests {531 mod tests {
405 use super::*;532 use super::*;
406- use crate::domain::class_member::tests::{a_class, a_course};533+ use crate::constant::CLASS_COURSE_COUNT_FIELD;
534+ use crate::domain::class_member::tests::{a_class, a_course, counter, rows};
407 535
408 /// A blueprint holding `courses`, at grade "9".536 /// A blueprint holding `courses`, at grade "9".
409 async fn a_blueprint(courses: Vec<CourseId>, db: &Database) -> ClassBlueprint {537 async fn a_blueprint(courses: Vec<CourseId>, db: &Database) -> ClassBlueprint {
@@ -519,6 +647,155 @@ mod tests {
519 );647 );
520 }648 }
521 649
650+ /// The delete is a compare-and-set, and it runs *before* the sweep — so a
651+ /// handle whose list moved cannot take the row, and nothing it would have
652+ /// swept is touched either.
653+ ///
654+ /// Provoked with a stale handle rather than a concurrent request, which is
655+ /// exactly the state a `PATCH` landing between the read and the delete puts
656+ /// this caller in, and deterministic where two live requests are not.
657+ #[tokio::test]
658+ async fn a_delete_of_a_list_that_moved_is_a_409_that_writes_nothing() {
659+ let db = crate::database::init_mem().await.unwrap();
660+ let manager = UserId::from_key("manager");
661+ let algebra = a_course("algebra", None, &db).await;
662+ let physics = a_course("physics", None, &db).await;
663+ let class = ClassGroup::read(&a_class("9-A", &db).await, &db)
664+ .await
665+ .unwrap()
666+ .unwrap();
667+ let stale = a_blueprint(vec![algebra.clone()], &db).await;
668+ stale.apply_to(&class, &manager, &db).await.unwrap();
669+
670+ // The edit this caller did not see: it adds a course and pumps it into
671+ // the section. (The pump is applied by hand because the helper class
672+ // carries no grade for `set_courses`'s own loop to find.)
673+ let (edited, _) = ClassBlueprint::read(stale.get_id(), &db)
674+ .await
675+ .unwrap()
676+ .unwrap()
677+ .set_courses(vec![algebra, physics], &manager, &db)
678+ .await
679+ .unwrap();
680+ edited.apply_to(&class, &manager, &db).await.unwrap();
681+
682+ let refused = stale.delete(&db).await;
683+ assert!(
684+ matches!(refused, Err(AppError::Conflict(_))),
685+ "a list that moved is a 409, not a silent delete: {refused:?}"
686+ );
687+ assert!(
688+ ClassBlueprint::read(&ClassBlueprintId::from_key("9"), &db)
689+ .await
690+ .unwrap()
691+ .is_some(),
692+ "the row the caller did not read is still there"
693+ );
694+ assert_eq!(
695+ rows("SELECT VALUE id FROM class_course", &db).await,
696+ 2,
697+ "and neither attachment was swept — including the one this handle \
698+ never knew about"
699+ );
700+ }
701+
702+ /// The lease is real: a delete cannot start while a guarded attach holds
703+ /// the read side.
704+ ///
705+ /// That is the whole point of the lock — without it a pump could commit its
706+ /// `class_course` row *after* the delete had swept past, stranding a row
707+ /// tagged with a blueprint nothing can reach. Two live requests would be a
708+ /// coin flip the in-memory engine lies about, so the lease is held directly
709+ /// and the delete is watched not-finishing on a timeout.
710+ #[tokio::test]
711+ async fn a_delete_waits_for_an_attach_in_flight() {
712+ let db = crate::database::init_mem().await.unwrap();
713+ let manager = UserId::from_key("manager");
714+ let algebra = a_course("algebra", None, &db).await;
715+ let class = ClassGroup::read(&a_class("9-A", &db).await, &db)
716+ .await
717+ .unwrap()
718+ .unwrap();
719+ let blueprint = a_blueprint(vec![algebra], &db).await;
720+ blueprint.apply_to(&class, &manager, &db).await.unwrap();
721+
722+ // Stand in for an attach mid-transaction, which is exactly the lease
723+ // `apply_to` holds around one course.
724+ let attaching = BLUEPRINT_LOCK.read().await;
725+ let mut deleting = {
726+ let db = db.clone();
727+ let blueprint = blueprint.clone();
728+ tokio::spawn(async move { blueprint.delete(&db).await })
729+ };
730+ assert!(
731+ tokio::time::timeout(std::time::Duration::from_millis(150), &mut deleting)
732+ .await
733+ .is_err(),
734+ "the delete must not run while an attach is in flight"
735+ );
736+ assert_eq!(
737+ rows("SELECT VALUE id FROM class_blueprint", &db).await,
738+ 1,
739+ "…and it must not have swept anything either"
740+ );
741+
742+ drop(attaching);
743+ deleting.await.unwrap().unwrap();
744+ assert_eq!(
745+ rows("SELECT VALUE id FROM class_blueprint", &db).await,
746+ 0,
747+ "once the attach is done the delete goes through"
748+ );
749+ assert_eq!(
750+ rows("SELECT VALUE id FROM class_course", &db).await,
751+ 0,
752+ "…taking every row carrying its tag with it"
753+ );
754+ }
755+
756+ /// The other half: a pump holding a handle to a blueprint that has since
757+ /// been deleted writes nothing at all, and says so with its own code.
758+ ///
759+ /// Without the in-transaction claim the attach would land a `class_course`
760+ /// row tagged with a record that no longer exists — the delete's sweep has
761+ /// already run, and the grade label *is* the id, so nothing could ever
762+ /// reach that row again.
763+ #[tokio::test]
764+ async fn a_pump_whose_blueprint_died_attaches_nothing() {
765+ let db = crate::database::init_mem().await.unwrap();
766+ let manager = UserId::from_key("manager");
767+ let algebra = a_course("algebra", None, &db).await;
768+ let class = ClassGroup::read(&a_class("9-A", &db).await, &db)
769+ .await
770+ .unwrap()
771+ .unwrap();
772+ let stale = a_blueprint(vec![algebra], &db).await;
773+ ClassBlueprint::read(stale.get_id(), &db)
774+ .await
775+ .unwrap()
776+ .unwrap()
777+ .delete(&db)
778+ .await
779+ .unwrap();
780+
781+ let skipped = stale.apply_to(&class, &manager, &db).await.unwrap();
782+ assert_eq!(skipped.len(), 1, "{skipped:?}");
783+ assert_eq!(
784+ skipped[0].reason, "blueprint_deleted",
785+ "the template went, not the class or the course"
786+ );
787+ assert_eq!(
788+ rows("SELECT VALUE id FROM class_course", &db).await,
789+ 0,
790+ "a row tagged with a deleted blueprint is one nothing can sweep"
791+ );
792+ assert_eq!(
793+ counter(CLASS_COURSE_COUNT_FIELD, class.get_id().record(), &db).await,
794+ 0,
795+ "…and no counter moved for it"
796+ );
797+ }
798+
522 #[test]799 #[test]
523 fn a_grade_key_must_be_addressable() {800 fn a_grade_key_must_be_addressable() {
524 assert!(ClassBlueprint::grade_key("").is_err());801 assert!(ClassBlueprint::grade_key("").is_err());
@@ -572,6 +849,7 @@ mod tests {
572 Attached::CourseGone("course:algebra".into()),849 Attached::CourseGone("course:algebra".into()),
573 "linked_course_missing",850 "linked_course_missing",
574 ),851 ),
852+ (Attached::SourceGone, "blueprint_deleted"),
575 ] {853 ] {
576 assert_eq!(854 assert_eq!(
577 skip_reason(&refusal),855 skip_reason(&refusal),
src/domain/class_course.rsmodified+10 -1
@@ -118,6 +118,11 @@ impl ClassCourse {
118 Attached::CourseGone(course) => Err(AppError::ConflictOwned(format!(118 Attached::CourseGone(course) => Err(AppError::ConflictOwned(format!(
119 "{course} no longer exists — detach it from this class first"119 "{course} no longer exists — detach it from this class first"
120 ))),120 ))),
121+ // This path passes no source, so the claim that answers this is
122+ // never in the transaction it ran.
123+ Attached::SourceGone => Err(AppError::Internal(
124+ "a hand attach has no blueprint to lose".into(),
125+ )),
121 }126 }
122 }127 }
123 128
@@ -132,7 +137,10 @@ impl ClassCourse {
132 ///137 ///
133 /// `source` is the provenance tag, and it is written by the same statement138 /// `source` is the provenance tag, and it is written by the same statement
134 /// that writes the link, so no attachment can exist without the answer to139 /// that writes the link, so no attachment can exist without the answer to
135- /// "may a blueprint take this back".140+ /// "may a blueprint take this back". It is also *claimed* in that
141+ /// transaction ([`Attached::SourceGone`]): a blueprint deleted while this
142+ /// pump ran has already swept by that tag, so a row landing afterwards
143+ /// would carry a name nothing can reach.
136 pub(crate) async fn attach_sourced(144 pub(crate) async fn attach_sourced(
137 class: &ClassGroupId,145 class: &ClassGroupId,
138 course: &CourseId,146 course: &CourseId,
@@ -155,6 +163,7 @@ impl ClassCourse {
155 &link,163 &link,
156 course.record(),164 course.record(),
157 attached_by.record(),165 attached_by.record(),
166+ source.map(ClassBlueprintId::record),
158 db,167 db,
159 )168 )
160 .await169 .await
src/domain/class_member.rsmodified+6 -0
@@ -95,6 +95,7 @@ impl ClassMember {
95 &member,95 &member,
96 user.record(),96 user.record(),
97 added_by.record(),97 added_by.record(),
98+ None,
98 db,99 db,
99 )100 )
100 .await?101 .await?
@@ -123,6 +124,11 @@ impl ClassMember {
123 Attached::CourseGone(course) => Err(AppError::ConflictOwned(format!(124 Attached::CourseGone(course) => Err(AppError::ConflictOwned(format!(
124 "{course} no longer exists — detach it from this class first"125 "{course} no longer exists — detach it from this class first"
125 ))),126 ))),
127+ // Only an attach run on a blueprint's behalf states that claim, and
128+ // a membership is nobody's but its own.
129+ Attached::SourceGone => Err(AppError::Internal(
130+ "a class membership has no blueprint to lose".into(),
131+ )),
126 }132 }
127 }133 }
128 134
src/domain/class_pump.rsmodified+101 -35
@@ -58,13 +58,33 @@ use crate::error::AppError;
58 /// transaction's write loop (see [`Axis::cap`]). It is its own marker because58 /// transaction's write loop (see [`Axis::cap`]). It is its own marker because
59 /// "this class holds too many courses" is not an answer anyone can act on when59 /// "this class holds too many courses" is not an answer anyone can act on when
60 /// it is reported as "this class holds too many students".60 /// it is reported as "this class holds too many students".
61+///
62+/// `SOURCE_MARK` is the record that *asked* for this attach — a grade blueprint
63+/// — being gone by the time the transaction runs. It is the only marker a
64+/// caller opts into (only a sourced attach states the claim), and it exists
65+/// because a blueprint's delete sweeps by that tag: a row landing after the
66+/// sweep would carry the name of a template no sweep can ever reach again.
61 const HELD_MARK: &str = "class_held";67 const HELD_MARK: &str = "class_held";
62 const GONE_MARK: &str = "class_gone";68 const GONE_MARK: &str = "class_gone";
63 const CAP_MARK: &str = "class_cap";69 const CAP_MARK: &str = "class_cap";
64 const OVER_MARK: &str = "class_over";70 const OVER_MARK: &str = "class_over";
71+const SOURCE_MARK: &str = "class_no_blueprint";
65 const FULL_MARK: &str = "class_full:";72 const FULL_MARK: &str = "class_full:";
66 const MISSING_MARK: &str = "class_no_course:";73 const MISSING_MARK: &str = "class_no_course:";
67 74
75+/// An in-transaction existence claim as its own two statements: read `read`
76+/// into `$name`, and abort with `mark` when it matched nothing.
77+///
78+/// Two statements and not one string, because [`attach`] takes the `CREATE`'s
79+/// result slot off the *length* of its statement list — a pair returned as one
80+/// element would count as one slot and silently read the wrong result back.
81+fn claim(name: &str, read: &str, mark: &str) -> Vec<String> {
82+ vec![
83+ format!("LET ${name} = ({read})"),
84+ format!("IF array::len(${name}) = 0 {{ THROW '{mark}' }}"),
85+ ]
86+}
87+
68 /// What [`attach`] settled.88 /// What [`attach`] settled.
69 #[derive(Debug)]89 #[derive(Debug)]
70 pub(crate) enum Attached<T> {90 pub(crate) enum Attached<T> {
@@ -98,6 +118,12 @@ pub(crate) enum Attached<T> {
98 /// a stale `class_course` link. Nothing was written, and no capacity anyone118 /// a stale `class_course` link. Nothing was written, and no capacity anyone
99 /// can raise will change that answer.119 /// can raise will change that answer.
100 CourseGone(String),120 CourseGone(String),
121+ /// The blueprint this attach was sourced from is gone — a delete landed
122+ /// between the pump reading the template and this transaction running.
123+ /// Nothing was written, which is the point: a row tagged with a blueprint
124+ /// that no longer exists is one nothing can ever sweep. Only a sourced
125+ /// attach can be answered this.
126+ SourceGone,
101 }127 }
102 128
103 /// Which way the pump runs: the loop below needs a `(course, user)` pair per129 /// Which way the pump runs: the loop below needs a `(course, user)` pair per
@@ -157,13 +183,16 @@ impl Axis {
157 /// class write's to touch, and a membership left pointing at a deleted user183 /// class write's to touch, and a membership left pointing at a deleted user
158 /// is still removable by its own route — which is exactly what a link to a184 /// is still removable by its own route — which is exactly what a link to a
159 /// deleted course was not.185 /// deleted course was not.
160- fn pivot_claim(&self) -> String {186+ fn pivot_claim(&self) -> Vec<String> {
161 match self {187 match self {
162- Axis::Member => String::new(),188+ Axis::Member => Vec::new(),
163- Axis::Course => format!(189+ Axis::Course => claim(
164- "LET $alive = (UPDATE $pivot SET {ENROLLMENT_COUNT_FIELD} = \190+ "alive",
165- {ENROLLMENT_COUNT_FIELD} RETURN VALUE id);191+ &format!(
166- IF array::len($alive) = 0 {{ THROW '{GONE_MARK}' }};"192+ "UPDATE $pivot SET {ENROLLMENT_COUNT_FIELD} = \
193+ {ENROLLMENT_COUNT_FIELD} RETURN VALUE id"
194+ ),
195+ GONE_MARK,
167 ),196 ),
168 }197 }
169 }198 }
@@ -252,6 +281,11 @@ impl Axis {
252 /// and re-sending the whole cascade then *sees* the row and takes the other281 /// and re-sending the whole cascade then *sees* the row and takes the other
253 /// branch. The retry converges instead of re-asking a settled question, which282 /// branch. The retry converges instead of re-asking a settled question, which
254 /// is the restriction's actual test.283 /// is the restriction's actual test.
284+///
285+/// `source` is the record whose behalf this attach runs on — a grade blueprint
286+/// — and supplying it adds one more claim: that it is still there when the
287+/// transaction runs ([`Attached::SourceGone`]). A hand attach owns itself and
288+/// passes `None`.
255 pub(crate) async fn attach<T: SurrealValue + Clone>(289 pub(crate) async fn attach<T: SurrealValue + Clone>(
256 class: &ClassGroupId,290 class: &ClassGroupId,
257 axis: Axis,291 axis: Axis,
@@ -259,27 +293,46 @@ pub(crate) async fn attach<T: SurrealValue + Clone>(
259 row: &T,293 row: &T,
260 pivot: RecordId,294 pivot: RecordId,
261 by: RecordId,295 by: RecordId,
296+ source: Option<RecordId>,
262 db: &Database,297 db: &Database,
263 ) -> Result<Attached<T>, AppError> {298 ) -> Result<Attached<T>, AppError> {
264 let count_field = axis.counter();299 let count_field = axis.counter();
265 let pairs = axis.pairs();300 let pairs = axis.pairs();
266- let alive = axis.pivot_claim();
267 let other = axis.other();301 let other = axis.other();
268 let over_field = other.counter();302 let over_field = other.counter();
303+ // One statement per element, because the `CREATE`'s result slot is this
304+ // list's own length at the moment it is pushed. It used to be a
305+ // hand-counted constant with a case per optional claim, and only the path
306+ // carrying that claim would ever have paid for a miscount.
307+ let mut statements = vec![
308+ "BEGIN TRANSACTION".to_string(),
309+ "LET $held = (SELECT VALUE id FROM $link)".to_string(),
310+ format!("IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}"),
311+ ];
312+ if source.is_some() {
313+ statements.extend(claim("source", "SELECT VALUE id FROM $guard", SOURCE_MARK));
314+ }
315+ statements.extend(axis.pivot_claim());
269 // Read off the class row inside the transaction that claims it, so the316 // Read off the class row inside the transaction that claims it, so the
270 // count this refuses on is the one the pair loop below would iterate.317 // count this refuses on is the one the pair loop below would iterate.
271- let sql = format!(318+ statements.push(format!(
272- "BEGIN TRANSACTION;319+ "LET $over = (SELECT VALUE id FROM $class WHERE ({over_field} ?? 0) > $other_cap)"
273- LET $held = (SELECT VALUE id FROM $link);320+ ));
274- IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }};321+ statements.push(format!(
275- {alive}322+ "IF array::len($over) > 0 {{ THROW '{OVER_MARK}' }}"
276- LET $over = (SELECT VALUE id FROM $class WHERE ({over_field} ?? 0) > $other_cap);323+ ));
277- IF array::len($over) > 0 {{ THROW '{OVER_MARK}' }};324+ statements.push(format!(
278- LET $counted = (UPDATE $class SET {count_field} = ({count_field} ?? 0) + 1 \325+ "LET $counted = (UPDATE $class SET {count_field} = ({count_field} ?? 0) + 1 \
279- WHERE ({count_field} ?? 0) < $class_cap RETURN VALUE id);326+ WHERE ({count_field} ?? 0) < $class_cap RETURN VALUE id)"
280- IF array::len($counted) = 0 {{ THROW '{CAP_MARK}' }};327+ ));
281- CREATE $link CONTENT $row;328+ statements.push(format!(
282- FOR $pair IN (({pairs}) ?? []) {{329+ "IF array::len($counted) = 0 {{ THROW '{CAP_MARK}' }}"
330+ ));
331+ // Taken as it is pushed: this is the slot the link row comes back out of.
332+ let made = statements.len();
333+ statements.push("CREATE $link CONTENT $row".to_string());
334+ statements.push(format!(
335+ "FOR $pair IN (({pairs}) ?? []) {{
283 LET $seat_of = type::record('{ENROLLMENT_TABLE}', string::concat(336 LET $seat_of = type::record('{ENROLLMENT_TABLE}', string::concat(
284 record::id($pair.course), '_', record::id($pair.user)));337 record::id($pair.course), '_', record::id($pair.user)));
285 IF array::len((SELECT VALUE id FROM $seat_of)) = 0 {{338 IF array::len((SELECT VALUE id FROM $seat_of)) = 0 {{
@@ -296,26 +349,32 @@ pub(crate) async fn attach<T: SurrealValue + Clone>(
296 CREATE $seat_of CONTENT {{ course: $pair.course, user: $pair.user, \349 CREATE $seat_of CONTENT {{ course: $pair.course, user: $pair.user, \
297 enrolled_by: $by, source: $class }};350 enrolled_by: $by, source: $class }};
298 }};351 }};
299- }};352+ }}"
300- COMMIT TRANSACTION;"353+ ));
301- );354+ statements.push("COMMIT TRANSACTION".to_string());
355+ let sql = format!("{};", statements.join(";\n"));
356+ let mut bindings = vec![
357+ ("class".into(), class.record().into_value()),
358+ ("link".into(), link.clone().into_value()),
359+ ("row".into(), row.clone().into_value()),
360+ ("pivot".into(), pivot.into_value()),
361+ ("by".into(), by.into_value()),
362+ ("unlimited".into(), cap::UNLIMITED.into_value()),
363+ ("class_cap".into(), axis.cap().into_value()),
364+ ("other_cap".into(), other.cap().into_value()),
365+ ];
366+ if let Some(guard) = source {
367+ bindings.push(("guard".into(), guard.into_value()));
368+ }
302 let (mut result, mut errors) = transaction_with_retry(369 let (mut result, mut errors) = transaction_with_retry(
303 db,370 db,
304 &sql,371 &sql,
305- &[372+ &bindings,
306- ("class".into(), class.record().into_value()),
307- ("link".into(), link.clone().into_value()),
308- ("row".into(), row.clone().into_value()),
309- ("pivot".into(), pivot.into_value()),
310- ("by".into(), by.into_value()),
311- ("unlimited".into(), cap::UNLIMITED.into_value()),
312- ("class_cap".into(), axis.cap().into_value()),
313- ("other_cap".into(), other.cap().into_value()),
314- ],
315 &[373 &[
316 HELD_MARK,374 HELD_MARK,
317 GONE_MARK,375 GONE_MARK,
318 OVER_MARK,376 OVER_MARK,
377+ SOURCE_MARK,
319 CAP_MARK,378 CAP_MARK,
320 FULL_MARK,379 FULL_MARK,
321 MISSING_MARK,380 MISSING_MARK,
@@ -338,6 +397,16 @@ pub(crate) async fn attach<T: SurrealValue + Clone>(
338 {397 {
339 return Ok(Attached::Duplicate);398 return Ok(Attached::Duplicate);
340 }399 }
400+ // The blueprint that asked for this attach is gone, and that outranks every
401+ // refusal below it: none of them is an answer anyone can act on once the
402+ // template that wanted the row has been deleted — and its claim stands
403+ // first in the transaction, so it aborts before they could fire anyway.
404+ if errors
405+ .values()
406+ .any(|error| error.to_string().contains(SOURCE_MARK))
407+ {
408+ return Ok(Attached::SourceGone);
409+ }
341 if errors410 if errors
342 .values()411 .values()
343 .any(|error| error.to_string().contains(GONE_MARK))412 .any(|error| error.to_string().contains(GONE_MARK))
@@ -381,9 +450,6 @@ pub(crate) async fn attach<T: SurrealValue + Clone>(
381 if let Some(error) = errors.drain().map(|(_, error)| error).next() {450 if let Some(error) = errors.drain().map(|(_, error)| error).next() {
382 return Err(error.into());451 return Err(error.into());
383 }452 }
384- // Slots count BEGIN and three LET/IF pairs: the CREATE is slot 7 — or 9 on
385- // an axis that claims its pivot with a LET/IF pair of its own.
386- let made = if alive.is_empty() { 7 } else { 9 };
387 result453 result
388 .take::<Vec<T>>(made)?454 .take::<Vec<T>>(made)?
389 .into_iter()455 .into_iter()
src/lib.rsmodified+1 -1
@@ -50,7 +50,7 @@ use crate::state::AppState;
50 (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"),50 (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"),
51 (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"),51 (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"),
52 (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"),52 (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"),
53- (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 `/ \\ ? # %`"),53+ (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 `/ \\ ? # %`"),
54 (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"),54 (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"),
55 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),55 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),
56 (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"),56 (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"),
src/web/classes.rsmodified+8 -2
@@ -938,9 +938,11 @@ struct SkipResponse {
938 /// is reported once and never again), `class_at_course_ceiling` (the938 /// is reported once and never again), `class_at_course_ceiling` (the
939 /// section already holds `max_class_courses`), `class_roster_too_large`939 /// section already holds `max_class_courses`), `class_roster_too_large`
940 /// (the section holds more students than one attach may enroll at once),940 /// (the section holds more students than one attach may enroll at once),
941- /// `course_full` (the course has no free seat for the whole section), and941+ /// `course_full` (the course has no free seat for the whole section),
942 /// `linked_course_missing` (another course already attached to this942 /// `linked_course_missing` (another course already attached to this
943- /// section no longer exists — detach it before retrying).943+ /// section no longer exists — detach it before retrying), and
944+ /// `blueprint_deleted` (the blueprint itself was deleted while the pump
945+ /// ran; nothing was attached, and there is nothing left to retry).
944 #[schema(example = "course_full")]946 #[schema(example = "course_full")]
945 reason: String,947 reason: String,
946 }948 }
@@ -1150,6 +1152,9 @@ async fn update_blueprint(
1150 /// blueprint made is detached with it (their pumped enrollments swept the usual1152 /// blueprint made is detached with it (their pumped enrollments swept the usual
1151 /// way); a course a human attached to one of those classes by hand carries no1153 /// way); a course a human attached to one of those classes by hand carries no
1152 /// blueprint tag and survives.1154 /// blueprint tag and survives.
1155+///
1156+/// A `409` means the course list changed between this call reading the
1157+/// blueprint and deleting it — nothing was written; re-read and retry.
1153 #[utoipa::path(1158 #[utoipa::path(
1154 delete,1159 delete,
1155 path = "/blueprints/{grade}",1160 path = "/blueprints/{grade}",
@@ -1161,6 +1166,7 @@ async fn update_blueprint(
1161 (status = 401, description = "Not authenticated", body = ErrorResponse),1166 (status = 401, description = "Not authenticated", body = ErrorResponse),
1162 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),1167 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
1163 (status = 404, description = "No blueprint for that grade", body = ErrorResponse),1168 (status = 404, description = "No blueprint for that grade", body = ErrorResponse),
1169+ (status = 409, description = "The course list changed since this call read it — nothing was written, re-read and retry", body = ErrorResponse),
1164 ),1170 ),
1165 )]1171 )]
1166 async fn delete_blueprint(1172 async fn delete_blueprint(
tests/regress_blueprints.rsmodified+104 -0
@@ -641,3 +641,107 @@ async fn a_row_written_before_the_column_reads_as_hand_attached() {
641 1641 1
642 );642 );
643 }643 }
644+
645+/// The window the lock exists to close, made visible.
646+///
647+/// `ClassBlueprint::delete` removes the row and then sweeps by the provenance
648+/// tag, while a pump reads that row inside the transaction that writes the link
649+/// — a cross-record read-then-write the store does not serialize. A pump that
650+/// passed its liveness claim and then lost the blueprint commits a
651+/// `class_course` row tagged with a record nothing can reach, since the grade
652+/// label *is* the id and no sweep will ever run for it again.
653+///
654+/// Racing two requests would be a coin flip the in-memory engine lies about, so
655+/// the delete is injected by the database itself: a `DEFINE EVENT` on
656+/// `class_course` fires *inside* the pump's own transaction, the instant the
657+/// link row lands — which is exactly "after the guard passed, before the
658+/// commit", every single time. This is a below-the-lock probe by construction
659+/// (the store deletes the row, not `ClassBlueprint::delete`), so it does not
660+/// test `BLUEPRINT_LOCK`; it pins the end state that lock prevents in-process,
661+/// and the recovery contract that covers the one residue it cannot — a process
662+/// crash between the delete and its sweep.
663+#[tokio::test]
664+async fn a_blueprint_lost_mid_attach_strands_a_row_that_stays_detachable() {
665+ let (app, db) = app_and_db().await;
666+ let manager = login_as(&app, &db, "mgr", "manager").await;
667+ let algebra = create_course(&app, &manager, "algebra").await;
668+ let made = send(
669+ &app,
670+ "POST",
671+ "/classes/blueprints",
672+ Some(&manager),
673+ Some(json!({ "grade": "9", "course_ids": [algebra.clone()] })),
674+ )
675+ .await;
676+ assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body);
677+ // The section comes after the template, so nothing is attached until the
678+ // pump below runs.
679+ let class = create_class(&app, &manager, "9-A", "9").await;
680+ assert!(!attached(&class, &algebra, &db).await);
681+
682+ // Delete the blueprint from inside the very write that attaches on its
683+ // behalf.
684+ db.query(
685+ "DEFINE EVENT lose_blueprint ON TABLE class_course WHEN $event = 'CREATE' \
686+ THEN { DELETE type::record('class_blueprint', '9'); };",
687+ )
688+ .await
689+ .unwrap()
690+ .check()
691+ .unwrap();
692+
693+ let pumped = send(
694+ &app,
695+ "POST",
696+ &format!("/classes/{class}/blueprint"),
697+ Some(&manager),
698+ None,
699+ )
700+ .await;
701+ assert_eq!(pumped.status, StatusCode::OK, "{:?}", pumped.body);
702+ assert!(
703+ skips(&pumped).is_empty(),
704+ "the pump was told it succeeded — which is what makes the row below \
705+ invisible to the caller: {:?}",
706+ pumped.body
707+ );
708+
709+ assert_eq!(
710+ rows("SELECT VALUE id FROM class_blueprint", &db).await,
711+ 0,
712+ "the injected delete really landed"
713+ );
714+ assert!(
715+ attached(&class, &algebra, &db).await,
716+ "the link committed after its blueprint was gone: this is the stranded \
717+ row, tagged with a record no sweep can ever reach"
718+ );
719+ assert_eq!(source_of(&class, &algebra, &db).await, Some("9".into()));
720+
721+ // The documented recovery: a human detaches it one course at a time, and
722+ // the counters come back exact.
723+ let detached = send(
724+ &app,
725+ "DELETE",
726+ &format!("/classes/{class}/courses/{algebra}"),
727+ Some(&manager),
728+ None,
729+ )
730+ .await;
731+ assert_eq!(
732+ detached.status,
733+ StatusCode::NO_CONTENT,
734+ "{:?}",
735+ detached.body
736+ );
737+ assert!(!attached(&class, &algebra, &db).await);
738+ assert_eq!(
739+ counter(
740+ &format!("SELECT VALUE (class_course_count ?? 0) FROM class_group:{class}"),
741+ &db
742+ )
743+ .await,
744+ 0,
745+ "a stranded row still releases its counter when it is detached"
746+ );
747+}