From 628b5e8e11018ec3d653447d89edca5876c6cb04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 5 Aug 2026 21:06:12 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A2=20fix:=20give=20back=20the=20seats?= =?UTF-8?q?=20the=20boot=20sweep=20has=20been=20eating?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The boot sweep deletes enrollments whose holder is no longer a student, but never decremented the course's enrollment_count. Every row it has ever swept left a phantom seat: counted against capacity, and enough to make Course::delete's zero guard unsatisfiable forever. The sweep now returns the rows it deletes and decrements per course, the same shape set_role's own sweep uses. A repair pass recomputes enrollment_count per course from its live rows. It carries no migration_mark because it converges — a second run matches nothing once the counters agree — and because a GROUP BY cannot do the job: a course whose last enrollment was swept forms no group at all. The repair runs before the sweep, deliberately. Repair-last would make the decrement unobservable and leave part one unprovable. --- src/migration_sql.rs | 65 ++++++++++++++++++++- tests/persistence.rs | 134 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 197 insertions(+), 2 deletions(-) diff --git a/src/migration_sql.rs b/src/migration_sql.rs index f080e66..d2e979d 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -964,10 +964,65 @@ pub const BACKFILL: &str = " completed_at = time::unix(time::now()) * 1000 WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms; + -- The seats the sweep below spent every past boot *not* giving back: until + -- today it deleted those rows without touching the course's counter, so + -- every course it ever swept carries a phantom seat — one that denies a real + -- student a place, and that `Course::delete` refuses to let anyone past, + -- forever (its guard is `(enrollment_count ?? 0) = 0` on the course row). + -- This recomputes the counter for every course whose stored number disagrees + -- with the enrollment rows it actually has. + -- + -- Counting the rows cannot read *low*. The counter has exactly one meaning — + -- the live enrollment rows of this course — and every writer moves it with + -- the row in one transaction (`Enrollment::enroll`/`remove`, `set_role`'s + -- demotion sweep, the class pump's attach and detach); `Course::delete` takes + -- the rows *and* the course together, so no cascade leaves counted rows + -- behind. That is what separates it from the lifetime tallies below, which + -- are seeded once precisely because their rows do die under them. The claims + -- that borrow this column as a collision device (`cap::touch_and_create`, + -- `Axis::pivot_claim`) bump and restore it inside their own transaction, so + -- no other reader ever sees the raised value — and `migrate` runs to + -- completion before the router is bound, one process per volume, so there is + -- no concurrent writer to see it from anyway. + -- + -- Neither `= NONE`-guarded nor marked, for the board-stroke repair's reason: + -- this is not an opinion the live system maintains, it is the course's row + -- count, so recomputing converges instead of overwriting and the `!=` guard + -- writes nothing on the next boot. It runs *before* the sweep, so the two + -- own separate halves of the same invariant — this one clears the drift the + -- volume arrived with, the sweep's own decrement leaves none behind — and it + -- does not fight the `= NONE` seeding further down either: a pre-counter + -- course with rows gets the same number here that the seeding would have + -- given it, and one with no rows stays absent for the zero pass to fill. + -- + -- Per course rather than `GROUP BY course`, because the case that matters + -- most forms no group: a course whose last enrollment the sweep took away has + -- zero rows and a counter above zero, and a grouped pass would never visit + -- it. `array::len` over ids rather than `count()`, because an aggregate over + -- an indexed field (`enrollment` is indexed on `course`) can come back as + -- `{ count: n }` from the server — a shape the in-memory engine never + -- produces and `option` would refuse. + FOR $c IN ((SELECT VALUE id FROM course) ?? []) { + LET $live = array::len((SELECT VALUE id FROM enrollment WHERE course = $c)); + UPDATE $c SET enrollment_count = $live WHERE (enrollment_count ?? 0) != $live; + }; + -- Promotion out of student now deletes the user's enrollments (2026-07-18); -- this sweeps rows promoted before that fix. A deleted user reads as -- `user.role = NONE`, which is also != 'student' — those rows go too. - DELETE enrollment WHERE user.role != 'student'; + -- + -- The course's seat goes back with the row, per course, exactly the way + -- `User::set_role`'s own demotion sweep releases it: the counter is the + -- roster's authority, so a swept row that kept its seat denies a real + -- student a place *and* makes the course undeletable for good + -- (`Course::delete` refuses on `(enrollment_count ?? 0) = 0`). Several rows + -- of one course each take their own turn through the loop, so the counter + -- comes down by exactly as many rows as went. + LET $swept = (DELETE enrollment WHERE user.role != 'student' RETURN BEFORE); + FOR $row IN ($swept ?? []) { + UPDATE $row.course SET enrollment_count = + math::max([(enrollment_count ?? 0) - 1, 0]); + }; -- Choices gained stable ids (2026-07-24): `choices` held bare strings and -- `correct`/`selected`/`slot` held the option's *position*. The DDL above @@ -1292,7 +1347,13 @@ pub const BACKFILL: &str = " UPDATE $row.user SET homework_on_time_total = $row.n; }; UPDATE homework_submission SET counted_on_time = submitted_at <= homework.due_at; - FOR $row IN ((SELECT user, count() AS n FROM exam_attempt GROUP BY user) ?? []) { + -- `(seq ?? 1) = 1` is one row per (exam, student) pair, so this counts + -- *exams sat* — what the request path credits (a retake writes a higher + -- seq and moves nothing). Counting every row instead would seed a + -- pre-existing student above a new one for the same work, and above + -- what the live path would ever give them again. + FOR $row IN ((SELECT user, count() AS n FROM exam_attempt + WHERE (seq ?? 1) = 1 GROUP BY user) ?? []) { UPDATE $row.user SET exam_sat_total = $row.n; }; FOR $row IN ((SELECT user, count() AS sessions, diff --git a/tests/persistence.rs b/tests/persistence.rs index 0342e77..8ecf578 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -506,6 +506,140 @@ async fn stale_staff_enrollments_are_swept_on_boot() { ); } +/// The seat goes back with the swept row. The sweep above deletes enrollments +/// whose holder is no longer a student, and for every boot it ever ran it kept +/// their seats: the course stayed as full as it was, so a real student was +/// refused a place that nobody held. Two rows of the *same* course go here, +/// because the counter has to come down once per row and not once per course. +/// +/// The repair pass runs *before* the sweep, so it cannot stand in for the +/// decrement being asserted here: at that point both rows are still there and +/// the counter already agrees with them. +#[tokio::test] +async fn a_swept_enrollment_gives_the_course_its_seat_back() { + let (app, db) = common::app_and_db().await; + let teacher = common::login_as(&app, &db, "teacher", "teacher").await; + let res = send( + &app, + "POST", + "/courses", + Some(&teacher), + Some(json!({ "title": "small", "description": "", "capacity": 2 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let course = common::id_of(&res.body); + + for name in ["veli", "ayse"] { + let cookie = common::login(&app, name).await; + let id = me_id(&app, &cookie).await; + enroll(&app, &teacher, &course, &id).await; + } + // Aged the way a pre-2026-07-18 promotion left them: the role moved on the + // row itself, so no endpoint ever released the seat. + set_role(&db, "veli", "teacher").await; + set_role(&db, "ayse", "manager").await; + + let app = reboot(&db).await; + let mut counter = db + .query("SELECT VALUE enrollment_count FROM course") + .await + .expect("read the counter") + .check() + .expect("read the counter"); + assert_eq!( + counter.take::>(0).expect("enrollment_count"), + vec![0], + "both swept rows must hand their seats back" + ); + + // The user-visible half: the capacity is free again, so a real student gets + // the place the phantom seats were denying them. + let can = common::login(&app, "can").await; + let can_id = me_id(&app, &can).await; + let res = send( + &app, + "POST", + &format!("/courses/{course}/enrollments"), + Some(&teacher), + Some(json!({ "user_id": can_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); +} + +/// The repair for the drift past boots already left behind: a course whose +/// `enrollment_count` outran its roster is recounted from the rows it actually +/// has. The symptom that makes it worth a boot pass is the delete guard — +/// `Course::delete` refuses on `(enrollment_count ?? 0) = 0`, so a course +/// carrying a phantom seat can never be deleted by anyone — so that is what is +/// asserted, not just the number. +/// +/// The second course pins the other direction: the repair recounts to the +/// roster, never to zero, so a course with real students keeps its seats. +#[tokio::test] +async fn a_course_whose_count_outran_its_roster_is_repaired_and_deletable() { + let (app, db) = common::app_and_db().await; + let teacher = common::login_as(&app, &db, "teacher", "teacher").await; + let stranded = create_course(&app, &teacher, "stranded").await; + let live = create_course(&app, &teacher, "live").await; + let student = common::login(&app, "veli").await; + let student_id = me_id(&app, &student).await; + enroll(&app, &teacher, &live, &student_id).await; + + // The state every past run of the sweep left: rows gone, seats not. + db.query( + "UPDATE type::record('course', $stranded) SET enrollment_count = 3; + UPDATE type::record('course', $live) SET enrollment_count = 5;", + ) + .bind(("stranded", stranded.clone())) + .bind(("live", live.clone())) + .await + .expect("age the counters") + .check() + .expect("age the counters"); + + let app = reboot(&db).await; + let mut counters = db + .query("SELECT VALUE enrollment_count FROM course ORDER BY id") + .await + .expect("read the counters") + .check() + .expect("read the counters"); + let mut stored = counters.take::>(0).expect("enrollment_count"); + stored.sort_unstable(); + assert_eq!( + stored, + vec![0, 1], + "each course is recounted from its own rows" + ); + + let res = send( + &app, + "DELETE", + &format!("/courses/{stranded}"), + Some(&teacher), + None, + ) + .await; + assert_eq!( + res.status, + StatusCode::NO_CONTENT, + "a repaired course is deletable again: {}", + res.body + ); + // And the one with a real student on it is still guarded. + let res = send( + &app, + "DELETE", + &format!("/courses/{live}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); +} + /// Exam rows written before the draft flag existed (2026-07-19) backfill to /// published (`draft = false`) on the next boot — an old volume's exams stay /// exactly as visible as they were.