forge
Explore
Log in

Don't you dare go Hollow

🧹 report a dead course once per pump, not once per section

Browse files at this commit

7bfebea71f59dee63b037de461b8eb0f5ac3008cAhmet Kaan GümüşParent: b1c8e7a
  • fix
    • 🧹 report a dead course once per pump, not once per section
Show full message
fix: 🧹 report a dead course once per pump, not once per section

A course deleted out from under a blueprint is pruned by the pump that
finds it, but the pump looped its sections over the list it read at the
start, so twelve sections meant twelve identical skips and twelve prune
writes for one dead course — and the rustdoc claimed otherwise.

The run now carries what it has found dead, and a blueprint that is
itself deleted mid-run ends the loop rather than answering for every
section left: the remaining sections would all answer the same. The
skips already collected are still returned, because the sections before
it did attach.
README.mdmodified+9 -4
@@ -2869,13 +2869,18 @@ wording (and the language), the same id-plus-client-label shape roles and
28692869 course kinds have. The set is closed, and each code names the record that
28702870 actually failed: `class_deleted` (the section vanished mid-pump),
28712871 `course_deleted` (the course was deleted; the pump also removes the dangling id
2872-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 section
2874-holds more students than one attach may enroll at once), `course_full` (no free
2872+from the template, so the template shrinks and the skip is reported once for the
2873+whole grade — the sections after the first one are not asked again — and never
2874+again on a later pump), `class_at_course_ceiling`, `class_roster_too_large`
2875+(the section holds more students than one attach may enroll at once),
2876+`course_full` (no free
28752877 seat for the whole section), `linked_course_missing` (another course
28762878 already attached to that section no longer exists — detach it first), and
28772879 `blueprint_deleted` (the template itself was deleted while the pump ran —
2878-nothing was attached, and there is nothing left to retry).
2880+nothing was attached, and there is nothing left to retry). That last one **ends
2881+the run**: it says nothing about the (section, course) pair it names, so every
2882+remaining section would only repeat it. It is reported once, the sections
2883+already stocked stay stocked, and the call still succeeds.
28792884
28802885 **Removal spares what a human placed.** Every attachment a blueprint makes is
28812886 tagged with it. Dropping a course from the list detaches it only where the
src/domain/class_blueprint.rsmodified+170 -5
@@ -394,6 +394,10 @@ impl ClassBlueprint {
394394 /// at their own in-transaction claim and answer `blueprint_deleted`. Per
395395 /// course rather than per pump, because the pump's loop is unbounded and a
396396 /// delete may not wait behind all of it.
397+ ///
398+ /// One class, so `blueprint_deleted` is an ordinary skip here: the courses
399+ /// after it are not tried, because the template they would ask for is the
400+ /// one that just went.
397401 pub async fn apply_to(
398402 &self,
399403 class: &ClassGroup,
@@ -401,13 +405,39 @@ impl ClassBlueprint {
401405 db: &Database,
402406 ) -> Result<Vec<Skip>, AppError> {
403407 let mut skipped = Vec::new();
408+ self.apply_courses(class, by, &mut Vec::new(), &mut skipped, db)
409+ .await?;
410+ Ok(skipped)
411+ }
412+
413+ /// One class's share of a pump, and the body both callers above share.
414+ ///
415+ /// `dead` is the courses this run already found deleted: they are not
416+ /// attempted again, so neither the skip nor [`Self::prune`]'s write repeats
417+ /// on the next section. A course newly found gone joins it.
418+ ///
419+ /// Answers `false` when the blueprint itself is gone — a caller looping
420+ /// over classes must stop, because every remaining one would answer exactly
421+ /// the same.
422+ async fn apply_courses(
423+ &self,
424+ class: &ClassGroup,
425+ by: &UserId,
426+ dead: &mut Vec<CourseId>,
427+ skipped: &mut Vec<Skip>,
428+ db: &Database,
429+ ) -> Result<bool, AppError> {
404430 for course in &self.courses {
431+ if dead.contains(course) {
432+ continue;
433+ }
405434 let landed = {
406435 let _lease = BLUEPRINT_LOCK.read().await;
407436 ClassCourse::attach_sourced(class.get_id(), course, by, Some(&self.id), db).await?
408437 };
409438 if matches!(landed, Attached::PivotGone) {
410439 self.prune(course, db).await?;
440+ dead.push(course.clone());
411441 }
412442 if let Some(reason) = skip_reason(&landed) {
413443 skipped.push(Skip {
@@ -417,17 +447,39 @@ impl ClassBlueprint {
417447 reason,
418448 });
419449 }
450+ if matches!(landed, Attached::SourceGone) {
451+ return Ok(false);
452+ }
420453 }
421- Ok(skipped)
454+ Ok(true)
422455 }
423456
424457 /// [`Self::apply_to`] every class at this blueprint's grade. The write loop
425458 /// is one transaction per (class, course) and bounded by neither — see the
426459 /// module note.
460+ ///
461+ /// Two things are said once for the whole run rather than once per section,
462+ /// since a section cannot make either of them untrue. A course that no
463+ /// longer exists is pruned and skipped on the first class that meets it and
464+ /// left out of every class after it. And a `blueprint_deleted` **aborts the
465+ /// grade loop**: under [`BLUEPRINT_LOCK`] that answer is precisely "a
466+ /// delete landed mid-pump", so it is reported once and the remaining
467+ /// classes are not walked.
468+ ///
469+ /// The abort is still a `Ok(skipped)`, not an error: the attaches that
470+ /// committed before the delete stand (its sweep took the ones it could
471+ /// reach), and a partial state reported in full is what best-effort means
472+ /// everywhere else here.
427473 pub async fn pump(&self, by: &UserId, db: &Database) -> Result<Vec<Skip>, AppError> {
428474 let mut skipped = Vec::new();
475+ let mut dead = Vec::new();
429476 for class in ClassGroup::list_for_grade(&self.grade, db).await? {
430- skipped.extend(self.apply_to(&class, by, db).await?);
477+ if !self
478+ .apply_courses(&class, by, &mut dead, &mut skipped, db)
479+ .await?
480+ {
481+ break;
482+ }
431483 }
432484 Ok(skipped)
433485 }
@@ -438,8 +490,10 @@ impl ClassBlueprint {
438490 /// a course had, but nothing it can reach names the blueprints holding its
439491 /// id — so a deleted course stays in the list and every future pump refuses
440492 /// it again, on every class, forever. A skip a manager cannot act on is
441- /// noise, so the pump that *finds* the dangling id also removes it, and the
442- /// removal is reported once (the skip) rather than every time.
493+ /// noise, so the pump that *finds* the dangling id also removes it: once
494+ /// for the run that found it (later classes in the same [`Self::pump`] skip
495+ /// it by its dead-course set rather than re-attempting and re-pruning it),
496+ /// and never again afterwards, because the list no longer holds it.
443497 ///
444498 /// Not a compare-and-set, unlike [`Self::set_courses`]: "a course that does
445499 /// not exist is not in this list" holds for every version of the list, so
@@ -531,7 +585,24 @@ impl ClassBlueprint {
531585 mod tests {
532586 use super::*;
533587 use crate::constant::CLASS_COURSE_COUNT_FIELD;
534- use crate::domain::class_member::tests::{a_class, a_course, counter, rows};
588+ use crate::domain::class_course::ClassCourseId;
589+ use crate::domain::class_group::ClassName;
590+ use crate::domain::class_member::tests::{a_class, a_course, counter, exists, rows};
591+
592+ /// A section that a pump's own grade loop can actually find — [`a_class`]
593+ /// carries no grade at all, so `list_for_grade` reaches none of them.
594+ async fn a_section(name: &str, db: &Database) -> ClassGroup {
595+ ClassGroup::create(
596+ &UserId::from_key("manager"),
597+ ClassName::try_new(name).unwrap(),
598+ Some(ClassBlueprint::grade_key("9").unwrap()),
599+ None,
600+ None,
601+ db,
602+ )
603+ .await
604+ .unwrap()
605+ }
535606
536607 /// A blueprint holding `courses`, at grade "9".
537608 async fn a_blueprint(courses: Vec<CourseId>, db: &Database) -> ClassBlueprint {
@@ -796,6 +867,100 @@ mod tests {
796867 );
797868 }
798869
870+ /// A course that no longer exists is pruned and reported **once for the
871+ /// pump**, not once per section: twelve sections at a grade must not answer
872+ /// one dead course with twelve identical skips and twelve identical prune
873+ /// writes. The live course still reaches every section.
874+ ///
875+ /// Stored state is what is asserted — the in-memory engine forges wins, so
876+ /// the links are re-read rather than counted off the return value.
877+ #[tokio::test]
878+ async fn a_dead_course_is_pruned_and_skipped_once_for_the_whole_grade() {
879+ let db = crate::database::init_mem().await.unwrap();
880+ let manager = UserId::from_key("manager");
881+ let astronomy = a_course("astronomy", None, &db).await;
882+ let algebra = a_course("algebra", None, &db).await;
883+ let a = a_section("9-A", &db).await;
884+ let b = a_section("9-B", &db).await;
885+ let blueprint = a_blueprint(vec![astronomy.clone(), algebra.clone()], &db).await;
886+ db.query("DELETE $c")
887+ .bind(("c", astronomy.record()))
888+ .await
889+ .unwrap()
890+ .check()
891+ .unwrap();
892+
893+ let skipped = blueprint.pump(&manager, &db).await.unwrap();
894+ assert_eq!(
895+ skipped.len(),
896+ 1,
897+ "one dead course is one skip for the grade, not one per section: {skipped:?}"
898+ );
899+ assert_eq!(skipped[0].reason, "course_deleted");
900+ assert_eq!(
901+ ClassBlueprint::read(blueprint.get_id(), &db)
902+ .await
903+ .unwrap()
904+ .unwrap()
905+ .get_courses(),
906+ &[algebra.clone()],
907+ "and the list is pruned to the course that still exists"
908+ );
909+ for class in [&a, &b] {
910+ assert!(
911+ exists(
912+ ClassCourseId::composite(class.get_id(), &algebra).record(),
913+ &db
914+ )
915+ .await,
916+ "the live course still reached {}",
917+ class.get_name().as_str()
918+ );
919+ }
920+ assert_eq!(
921+ rows("SELECT VALUE id FROM class_course", &db).await,
922+ 2,
923+ "…and nothing else was attached"
924+ );
925+ }
926+
927+ /// A blueprint that is gone ends the whole grade loop: the answer is about
928+ /// the template, so every remaining section would only repeat it. Reported
929+ /// once, and as `Ok` — best-effort, with whatever committed left standing.
930+ ///
931+ /// Provoked with a stale handle rather than a live interleaving, which the
932+ /// in-memory engine cannot be made to produce; it is the same state a
933+ /// delete landing between the read and the pump leaves this caller in.
934+ #[tokio::test]
935+ async fn a_deleted_blueprint_stops_the_grade_loop_after_one_skip() {
936+ let db = crate::database::init_mem().await.unwrap();
937+ let manager = UserId::from_key("manager");
938+ let algebra = a_course("algebra", None, &db).await;
939+ a_section("9-A", &db).await;
940+ a_section("9-B", &db).await;
941+ let stale = a_blueprint(vec![algebra], &db).await;
942+ ClassBlueprint::read(stale.get_id(), &db)
943+ .await
944+ .unwrap()
945+ .unwrap()
946+ .delete(&db)
947+ .await
948+ .unwrap();
949+
950+ let skipped = stale.pump(&manager, &db).await.unwrap();
951+ assert_eq!(
952+ skipped.len(),
953+ 1,
954+ "the template went once, not once per section: {skipped:?}"
955+ );
956+ assert_eq!(skipped[0].reason, "blueprint_deleted");
957+ assert_eq!(
958+ rows("SELECT VALUE id FROM class_course", &db).await,
959+ 0,
960+ "…and nothing was attached under a blueprint nothing could sweep"
961+ );
962+ }
963+
799964 #[test]
800965 fn a_grade_key_must_be_addressable() {
801966 assert!(ClassBlueprint::grade_key("").is_err());
src/web/classes.rsmodified+4 -2
@@ -935,14 +935,16 @@ struct SkipResponse {
935935 /// course kinds have. The set is closed: `class_deleted` (the section was
936936 /// deleted while the pump ran), `course_deleted` (the course itself is
937937 /// gone; the pump also drops that dangling id from the blueprint, so this
938- /// is reported once and never again), `class_at_course_ceiling` (the
938+ /// is reported once for the whole grade and never again),
939+ /// `class_at_course_ceiling` (the
939940 /// section already holds `max_class_courses`), `class_roster_too_large`
940941 /// (the section holds more students than one attach may enroll at once),
941942 /// `course_full` (the course has no free seat for the whole section),
942943 /// `linked_course_missing` (another course already attached to this
943944 /// section no longer exists — detach it before retrying), and
944945 /// `blueprint_deleted` (the blueprint itself was deleted while the pump
945- /// ran; nothing was attached, and there is nothing left to retry).
946+ /// ran; nothing was attached, and there is nothing left to retry — it ends
947+ /// the run, so it appears once however many sections were left).
946948 #[schema(example = "course_full")]
947949 reason: String,
948950 }