forge
Explore
Log in

Don't you dare go Hollow

🏫 stop a deleted course from sticking in a blueprint

Browse files at this commit

b0f72a5ff5c6076cbf541d52ece43006cc3a6121Ahmet Kaan GümüşParent: 340ff4f
  • fix
    • 🏫 stop a deleted course from sticking in a blueprint
Show full message
fix: 🏫 stop a deleted course from sticking in a blueprint

A grade template holds its courses as a list on its own row, so nothing in
`Course::delete`'s cascade could reach it: the id stayed, and the repair
every doc surface named — `PATCH` the template back as it stands — is a 400
for naming a course that does not exist. The pump's own prune only fires
while walking a section, so at a grade with no sections the id was permanent.

The cascade now sweeps `class_blueprint` in the same transaction that
detaches the course from the sections. Table scan, deliberately unindexed:
one row per grade label, and a course delete is rare — and the per-element
index the WHERE would want (`FIELDS courses[*]`) is the one this store
answers with no rows at all.

`prune` stays for the window the sweep cannot cover (a course deleted after
a pump read the list it walks) and for ids written before this existed; its
comment no longer argues the sweep should not exist.
README.mdmodified+20 -9
@@ -830,7 +830,7 @@ window filtering, before paging; negative values are a `400` naming the field.
830 | GET | `/courses/me` | student | The caller's **enrolled** courses · paged |830 | GET | `/courses/me` | student | The caller's **enrolled** courses · paged |
831 | GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |831 | GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |
832 | PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |832 | PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager; `409` if the `term_id` it moves off changed since the read — nothing written, re-read and retry) |
833-| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included) (creator, or manager+ — **not** an assigned teacher; `409` while anyone is still enrolled) |833+| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included); its class attachments and its id in every grade blueprint go with it (creator, or manager+ — **not** an assigned teacher; `409` while anyone is still enrolled) |
834 | POST | `/courses/{id}/teachers` | manager | `{user_id}` — assign a **teacher+** to run the course (idempotent; returns the course; `409` + undo if that account is demoted mid-request) |834 | POST | `/courses/{id}/teachers` | manager | `{user_id}` — assign a **teacher+** to run the course (idempotent; returns the course; `409` + undo if that account is demoted mid-request) |
835 | DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |835 | DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |
836 | POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |836 | POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full); enrolling a class-pumped student clears the row's `source`, so a class sweep can no longer take them back |
@@ -2946,10 +2946,10 @@ at one grade, and the caller is asking about all of them.
2946 A course a human attached by hand **counts as carried**. The template asks for2946 A course a human attached by hand **counts as carried**. The template asks for
2947 the course, not for the pump's tag, and a course already on the class is a no-op2947 the course, not for the pump's tag, and a course already on the class is a no-op
2948 for a pump whoever attached it — a status read that disagreed would send2948 for a pump whoever attached it — a status read that disagreed would send
2949-managers chasing rows no pump will ever write. A course in the template that no2949+managers chasing rows no pump will ever write. `missing` only ever names
2950-longer exists is the one deliberate piece of noise: it reads as missing from2950+courses that **still exist**: deleting a course takes its id out of every
2951-every section, because that is the truth about the section and this route may2951+template holding it (see below), so there is no dangling id left for this read
2952-not write, so the dangling id stays until the next pump prunes it.2952+to report.
2953 2953
2954 **Finishing a partial pump** is one of two idempotent calls, and neither needs2954 **Finishing a partial pump** is one of two idempotent calls, and neither needs
2955 any new machinery:2955 any new machinery:
@@ -2979,10 +2979,11 @@ A skip's `reason` is a **machine code**, not a sentence: the client owns the
2979 wording (and the language), the same id-plus-client-label shape roles and2979 wording (and the language), the same id-plus-client-label shape roles and
2980 course kinds have. The set is closed, and each code names the record that2980 course kinds have. The set is closed, and each code names the record that
2981 actually failed: `class_deleted` (the section vanished mid-pump),2981 actually failed: `class_deleted` (the section vanished mid-pump),
2982-`course_deleted` (the course was deleted; the pump also removes the dangling id2982+`course_deleted` (the course was deleted **while the pump ran** — one deleted
2983-from the template, so the template shrinks and the skip is reported once for the2983+before it started is already out of the template; the pump removes that id too,
2984-whole grade — the sections after the first one are not asked again — and never2984+so the skip is reported once for the whole grade — the sections after the first
2985-again on a later pump), `class_at_course_ceiling`, `class_roster_too_large`2985+one are not asked again — and never again on a later pump),
2986+`class_at_course_ceiling`, `class_roster_too_large`
2986 (the section holds more students than one attach may enroll at once),2987 (the section holds more students than one attach may enroll at once),
2987 `course_full` (no free2988 `course_full` (no free
2988 seat for the whole section), and2989 seat for the whole section), and
@@ -3029,6 +3030,16 @@ class first exactly as a manual detach does), and a course a human attached to
3029 that class by hand carries no tag and is left exactly where it is. Deleting a3030 that class by hand carries no tag and is left exactly where it is. Deleting a
3030 blueprint applies that to its whole list.3031 blueprint applies that to its whole list.
3031 3032
3033+**Deleting the course itself takes it out of every template naming it**, in the
3034+same transaction that detaches it from the sections. A template holds its
3035+courses as a list on its own row, so nothing else could reach them, and the id
3036+would otherwise be permanent rather than merely stale: the pump prunes a dead id
3037+only while walking a section, so a grade with no sections could never drop one,
3038+and `PATCH`ing the template back as it stands — the repair this section points
3039+at — is a `400` for naming a course that does not exist. The sweep is a scan of
3040+`class_blueprint`, which is deliberately unindexed: the table holds one row per
3041+grade label the school uses, and a course delete is rare.
3042+
3032 `DELETE /classes/blueprints/{grade}` removes the row **first** and then sweeps3043 `DELETE /classes/blueprints/{grade}` removes the row **first** and then sweeps
3033 by that tag, rather than by the list the call read: an edit that adds a course3044 by that tag, rather than by the list the call read: an edit that adds a course
3034 and pumps it while the delete runs would otherwise leave rows tagged with a3045 and pumps it while the delete runs would otherwise leave rows tagged with a
src/domain/class_blueprint.rsmodified+23 -10
@@ -531,8 +531,10 @@ impl ClassBlueprint {
531 /// A course id the blueprint holds but that no longer exists reads as531 /// A course id the blueprint holds but that no longer exists reads as
532 /// missing from every section. It is the truth about the section, and this532 /// missing from every section. It is the truth about the section, and this
533 /// read cannot prune it the way a pump does ([`Self::prune`]) without533 /// read cannot prune it the way a pump does ([`Self::prune`]) without
534- /// writing; the next pump — `PATCH`ing the same list back — drops the id534+ /// writing — but it is no longer a state a course delete leaves behind: the
535- /// and this noise with it.535+ /// delete's own cascade takes the id out of every template naming it, so
536+ /// only a row written before that cascade existed, or one the pump's own
537+ /// window ([`Self::prune`]) is about to clear, can still show it.
536 ///538 ///
537 /// Unpaged, like the [`ClassGroup::list_for_grade`] it is built on: the set539 /// Unpaged, like the [`ClassGroup::list_for_grade`] it is built on: the set
538 /// is the şube one school runs at one grade, and the caller is asking about540 /// is the şube one school runs at one grade, and the caller is asking about
@@ -575,14 +577,25 @@ impl ClassBlueprint {
575 577
576 /// Drop a course that no longer exists out of this blueprint's list.578 /// Drop a course that no longer exists out of this blueprint's list.
577 ///579 ///
578- /// [`crate::domain::course::Course::delete`] takes the `class_course` links580+ /// The delete does this itself now:
579- /// a course had, but nothing it can reach names the blueprints holding its581+ /// [`crate::domain::course::Course::delete`] sweeps `class_blueprint` in
580- /// id — so a deleted course stays in the list and every future pump refuses582+ /// the same cascade that takes the course's `class_course` links, so a
581- /// it again, on every class, forever. A skip a manager cannot act on is583+ /// template stops naming a course the instant that course goes. This used
582- /// noise, so the pump that *finds* the dangling id also removes it: once584+ /// to be the *only* thing that could remove such an id, and that was the
583- /// for the run that found it (later classes in the same [`Self::pump`] skip585+ /// bug: it fires only while walking a section, so a grade with no sections
584- /// it by its dead-course set rather than re-attempting and re-pruning it),586+ /// could never reach it, and the repair every doc surface pointed at
585- /// and never again afterwards, because the list no longer holds it.587+ /// (`PATCH` the list back as it stands) is a `400` for naming a course that
588+ /// does not exist. A permanent dangling id, and no call that could clear
589+ /// it.
590+ ///
591+ /// What is left for this to do is the **window** the sweep cannot cover: a
592+ /// pump walks a snapshot of the list it read, so a course deleted after
593+ /// that read is still attempted, and the delete's sweep has already run
594+ /// past a row it will not visit again. The skip is then reported once for
595+ /// the run that found it (later classes in the same [`Self::pump`] skip it
596+ /// by its dead-course set rather than re-attempting and re-pruning it), and
597+ /// this write is a no-op against a list the cascade already trimmed. It
598+ /// also clears ids written before that cascade existed.
586 ///599 ///
587 /// Not a compare-and-set, unlike [`Self::set_courses`]: "a course that does600 /// Not a compare-and-set, unlike [`Self::set_courses`]: "a course that does
588 /// not exist is not in this list" holds for every version of the list, so601 /// not exist is not in this list" holds for every version of the list, so
src/domain/course.rsmodified+16 -0
@@ -400,6 +400,21 @@ impl Course {
400 /// homework-file *blobs* are the web layer's to remove — it collects400 /// homework-file *blobs* are the web layer's to remove — it collects
401 /// their names before calling this.401 /// their names before calling this.
402 ///402 ///
403+ /// The **grade blueprints** naming it are swept in that same transaction.
404+ /// Nothing else can reach them — a blueprint holds its courses as a list on
405+ /// its own row, not as link rows this cascade could delete — and an id left
406+ /// behind is permanent rather than merely stale: the pump's own
407+ /// [`crate::domain::class_blueprint::ClassBlueprint::prune`] fires only
408+ /// while walking a section, so a grade with no sections can never drop one,
409+ /// and every `PATCH` of that template is refused for naming a course that
410+ /// does not exist, which is precisely the call documented as the repair.
411+ ///
412+ /// It is a table scan, deliberately unindexed: `class_blueprint` holds one
413+ /// row per grade label the school uses (a dozen), a course delete is rare,
414+ /// and the per-element index the `WHERE` would want
415+ /// (`FIELDS courses[*]`) is the one this store answers with **no rows at
416+ /// all** — the trap [`Self::list_for_teacher`] documents.
417+ ///
403 /// The marks going with it give their exam kinds' references back, counted418 /// The marks going with it give their exam kinds' references back, counted
404 /// per kind inside this same transaction — the mirror of `Exam::delete`.419 /// per kind inside this same transaction — the mirror of `Exam::delete`.
405 /// Skipping it would leave every kind the course graded under counted420 /// Skipping it would leave every kind the course graded under counted
@@ -442,6 +457,7 @@ impl Course {
442 UPDATE $row.class SET {CLASS_COURSE_COUNT_FIELD} = \457 UPDATE $row.class SET {CLASS_COURSE_COUNT_FIELD} = \
443 math::max([({CLASS_COURSE_COUNT_FIELD} ?? 0) - 1, 0]);458 math::max([({CLASS_COURSE_COUNT_FIELD} ?? 0) - 1, 0]);
444 }};459 }};
460+ UPDATE class_blueprint SET courses -= $course WHERE $course IN courses;
445 DELETE session_attendance WHERE course = $course;461 DELETE session_attendance WHERE course = $course;
446 DELETE course_session WHERE course = $course;462 DELETE course_session WHERE course = $course;
447 DELETE enrollment WHERE course = $course;463 DELETE enrollment WHERE course = $course;
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. It reaches sections in both directions — creating or editing one retro-pumps every class already at the grade, and a class created afterwards at a blueprinted grade is stocked from it by `POST /classes` itself, whose `201` therefore answers `{class, skipped, stocked_from}` (`stocked_from` is the grade label of the template that stocked it, `null` when none covers the grade, which is what tells that apart from a template that applied cleanly; a stocking that could not be carried out reads `null` too, and the retry for both is the idempotent `POST /classes/{id}/blueprint`). Pumping is 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. The same body carries `matched`, the number of sections the pump actually reached: a grade label is free text matched exactly, so `\"9 \"` and `\"9-A\"` are not `\"9\"`, and `matched: 0` with an empty `skipped` is a saved template that stocked nothing rather than one that stocked everything. `GET /classes?grade=<label>` is the read that goes with it: the sections carrying that exact label (matched verbatim, since normalizing it would disagree with the pump this exists to debug), `?grade=` on its own the sections carrying no grade at all, an unknown label an empty page rather than a `404`, and a `total` counting the filtered set so `?limit=&offset=` pages through it. `GET /classes/blueprints/{grade}/status` closes the loop: a read-only `{grade, courses, matched, sections[{class, class_name, missing}]}` naming, for every section carrying the label, the template courses it does not carry — unpaged, since the set is the şube one school runs at one grade — because a pump's `skipped` list otherwise lives only in the one response that reported it. A course a human attached **by hand** counts as carried, exactly as it does for the pump, and a course in the template that no longer exists reads as missing everywhere until the next pump drops the dangling id. Both fixes it points at are idempotent: `POST /classes/{id}/blueprint` re-stocks one section, and `PATCH`ing a blueprint with the list it already holds re-runs the whole grade's pump (the compare-and-set matches the unchanged list, nothing is dropped, everything is re-attached). A class whose `grade` is edited **after** it was stocked keeps the courses the *old* grade's blueprint attached — they still carry that blueprint's tag, so dropping one from that template still detaches them — and takes nothing from the new grade's template until one of those two calls runs; that is deliberate, since reconciling on a label `PATCH` would delete live enrollments as a side effect of a rename, and this status read is what makes the drift visible instead of silent. 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`, `blueprint_deleted`), like every other enum here. The **manual** attaches answer that same vocabulary, each route with its own set: a `409` from `POST /classes/{id}/courses` carries `duplicate`, `class_at_course_ceiling`, `class_roster_too_large` or `course_full`, and one from `POST /classes/{id}/members` carries `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `course_full` or `linked_course_missing`. The three *deleted* codes are a pump's alone — on a manual attach a deleted class or course is a `404`, never a `409` — and the ceiling pair differs by route because the ceilings do: a member add is refused by a full roster (`class_at_roster_ceiling`) or by a course list longer than one add may enroll at once (`class_course_list_too_large`), a course attach by the mirror of both. `duplicate` (already attached / already a member) is a refusal on either route, and no skip for a pump, which asked for a row that is already in place; `linked_course_missing` (another course on that section no longer exists — detach it first) only the member add can meet, since it is the one attach that walks the section's existing course links while a pump attaches a course it has just proved alive. No other route publishes a `code`, and the field is simply absent where it does not. 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 `/ \\ ? # %`"),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. It reaches sections in both directions — creating or editing one retro-pumps every class already at the grade, and a class created afterwards at a blueprinted grade is stocked from it by `POST /classes` itself, whose `201` therefore answers `{class, skipped, stocked_from}` (`stocked_from` is the grade label of the template that stocked it, `null` when none covers the grade, which is what tells that apart from a template that applied cleanly; a stocking that could not be carried out reads `null` too, and the retry for both is the idempotent `POST /classes/{id}/blueprint`). Pumping is 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. The same body carries `matched`, the number of sections the pump actually reached: a grade label is free text matched exactly, so `\"9 \"` and `\"9-A\"` are not `\"9\"`, and `matched: 0` with an empty `skipped` is a saved template that stocked nothing rather than one that stocked everything. `GET /classes?grade=<label>` is the read that goes with it: the sections carrying that exact label (matched verbatim, since normalizing it would disagree with the pump this exists to debug), `?grade=` on its own the sections carrying no grade at all, an unknown label an empty page rather than a `404`, and a `total` counting the filtered set so `?limit=&offset=` pages through it. `GET /classes/blueprints/{grade}/status` closes the loop: a read-only `{grade, courses, matched, sections[{class, class_name, missing}]}` naming, for every section carrying the label, the template courses it does not carry — unpaged, since the set is the şube one school runs at one grade — because a pump's `skipped` list otherwise lives only in the one response that reported it. A course a human attached **by hand** counts as carried, exactly as it does for the pump, and `missing` only ever names courses that still exist: deleting a course takes its id out of every blueprint holding it, in the same cascade that detaches it from the sections, so no template is left naming a course that is gone (which used to be permanent at a grade with no sections, and made the re-`PATCH` below a `400`). Both fixes it points at are idempotent: `POST /classes/{id}/blueprint` re-stocks one section, and `PATCH`ing a blueprint with the list it already holds re-runs the whole grade's pump (the compare-and-set matches the unchanged list, nothing is dropped, everything is re-attached). A class whose `grade` is edited **after** it was stocked keeps the courses the *old* grade's blueprint attached — they still carry that blueprint's tag, so dropping one from that template still detaches them — and takes nothing from the new grade's template until one of those two calls runs; that is deliberate, since reconciling on a label `PATCH` would delete live enrollments as a side effect of a rename, and this status read is what makes the drift visible instead of silent. 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`, `blueprint_deleted`), like every other enum here. The **manual** attaches answer that same vocabulary, each route with its own set: a `409` from `POST /classes/{id}/courses` carries `duplicate`, `class_at_course_ceiling`, `class_roster_too_large` or `course_full`, and one from `POST /classes/{id}/members` carries `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `course_full` or `linked_course_missing`. The three *deleted* codes are a pump's alone — on a manual attach a deleted class or course is a `404`, never a `409` — and the ceiling pair differs by route because the ceilings do: a member add is refused by a full roster (`class_at_roster_ceiling`) or by a course list longer than one add may enroll at once (`class_course_list_too_large`), a course attach by the mirror of both. `duplicate` (already attached / already a member) is a refusal on either route, and no skip for a pump, which asked for a row that is already in place; `linked_course_missing` (another course on that section no longer exists — detach it first) only the member add can meet, since it is the one attach that walks the section's existing course links while a pump attaches a course it has just proved alive. No other route publishes a `code`, and the field is simply absent where it does not. 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+7 -6
@@ -1028,9 +1028,10 @@ struct SkipResponse {
1028 /// Why that course could not be attached to that class, as a machine code1028 /// Why that course could not be attached to that class, as a machine code
1029 /// the client words itself — the same id-plus-client-label shape roles and1029 /// the client words itself — the same id-plus-client-label shape roles and
1030 /// course kinds have. The set is closed: `class_deleted` (the section was1030 /// course kinds have. The set is closed: `class_deleted` (the section was
1031- /// deleted while the pump ran), `course_deleted` (the course itself is1031+ /// deleted while the pump ran), `course_deleted` (the course itself was
1032- /// gone; the pump also drops that dangling id from the blueprint, so this1032+ /// deleted while the pump ran — a course deleted before it started is
1033- /// is reported once for the whole grade and never again),1033+ /// already out of the template; the pump drops that id too, so this is
1034+ /// reported once for the whole grade and never again),
1034 /// `class_at_course_ceiling` (the1035 /// `class_at_course_ceiling` (the
1035 /// section already holds `max_class_courses`), `class_roster_too_large`1036 /// section already holds `max_class_courses`), `class_roster_too_large`
1036 /// (the section holds more students than one attach may enroll at once),1037 /// (the section holds more students than one attach may enroll at once),
@@ -1348,9 +1349,9 @@ async fn delete_blueprint(
1348 /// empty `missing` everywhere is a grade fully stocked.1349 /// empty `missing` everywhere is a grade fully stocked.
1349 ///1350 ///
1350 /// A course a human attached by hand counts as carried, exactly as it does for1351 /// A course a human attached by hand counts as carried, exactly as it does for
1351-/// the pump — the template asks for the course, not for the pump's tag. A1352+/// the pump — the template asks for the course, not for the pump's tag.
1352-/// course in the template that no longer exists reads as missing from every1353+/// Deleting a course takes it out of every template naming it, so `missing`
1353-/// section; the next pump drops the dangling id from the template.1354+/// names courses that still exist.
1354 ///1355 ///
1355 /// The fix for anything listed is one of two idempotent calls:1356 /// The fix for anything listed is one of two idempotent calls:
1356 /// `POST /classes/{id}/blueprint` for one section, or `PATCH` the blueprint1357 /// `POST /classes/{id}/blueprint` for one section, or `PATCH` the blueprint
tests/regress_blueprints.rsmodified+195 -12
@@ -71,6 +71,34 @@ async fn source_of(class: &str, course: &str, db: &Database) -> Option<String> {
71 .filter(|key| !key.is_empty())71 .filter(|key| !key.is_empty())
72 }72 }
73 73
74+/// Does that grade's template still name that course, in the store?
75+async fn templated(grade: &str, course: &str, db: &Database) -> bool {
76+ rows(
77+ &format!(
78+ "SELECT VALUE id FROM class_blueprint \
79+ WHERE grade = '{grade}' AND course:{course} IN courses"
80+ ),
81+ db,
82+ )
83+ .await
84+ == 1
85+}
86+
87+/// The course list one grade's template hands back over HTTP, ready to be sent
88+/// straight back at it — the self-heal `PATCH` a manager is told to make.
89+async fn held(app: &axum::Router, cookie: &str, grade: &str) -> Vec<Value> {
90+ let res = send(
91+ app,
92+ "GET",
93+ &format!("/classes/blueprints/{grade}"),
94+ Some(cookie),
95+ None,
96+ )
97+ .await;
98+ assert_eq!(res.status, StatusCode::OK, "{:?}", res.body);
99+ res.body["courses"].as_array().unwrap().clone()
100+}
101+
74 /// Create a class section as `cookie`; returns its id.102 /// Create a class section as `cookie`; returns its id.
75 async fn create_class(app: &axum::Router, cookie: &str, name: &str, grade: &str) -> String {103 async fn create_class(app: &axum::Router, cookie: &str, name: &str, grade: &str) -> String {
76 let res = send(104 let res = send(
@@ -435,6 +463,13 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() {
435 /// A create whose stocking cannot place everything still creates the class: the463 /// A create whose stocking cannot place everything still creates the class: the
436 /// pair that did not fit comes back in `skipped`, best-effort exactly like464 /// pair that did not fit comes back in `skipped`, best-effort exactly like
437 /// every other pump here.465 /// every other pump here.
466+///
467+/// The dead course is forged in the store rather than deleted through the API,
468+/// because `DELETE /courses/{id}` now takes the id out of every template naming
469+/// it (see `deleting_a_course_takes_it_out_of_every_blueprint`) and would leave
470+/// nothing to skip. What is left here is exactly the state that still occurs: a
471+/// row written before that cascade existed, and the pump's own window — a
472+/// course deleted after the pump read the list it walks.
438 #[tokio::test]473 #[tokio::test]
439 async fn a_create_reports_what_its_blueprint_could_not_stock() {474 async fn a_create_reports_what_its_blueprint_could_not_stock() {
440 let (app, db) = app_and_db().await;475 let (app, db) = app_and_db().await;
@@ -451,18 +486,20 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() {
451 .await;486 .await;
452 assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body);487 assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body);
453 488
454- // Delete a course out from under the template. Nothing carries it yet — no489+ // Take a course out from under the template, leaving its id in the list —
455- // section exists at grade 9 — so this is the pair that cannot fit when the490+ // the state the delete's own sweep no longer produces, and the one a pump
456- // first one is created.491+ // meets when a course goes after it read the list. Nothing carries it yet
457- let dropped = send(492+ // (no section exists at grade 9), so this is the pair that cannot fit when
458- &app,493+ // the first one is created.
459- "DELETE",494+ db.query(format!("DELETE course:{physics}"))
460- &format!("/courses/{physics}"),495+ .await
461- Some(&manager),496+ .unwrap()
462- None,497+ .check()
463- )498+ .unwrap();
464- .await;499+ assert!(
465- assert_eq!(dropped.status, StatusCode::NO_CONTENT, "{:?}", dropped.body);500+ templated("9", &physics, &db).await,
501+ "the id is still listed"
502+ );
466 503
467 let res = send(504 let res = send(
468 &app,505 &app,
@@ -1235,3 +1272,149 @@ async fn a_status_read_names_the_course_a_section_is_short() {
1235 );1272 );
1236 }1273 }
1237 }1274 }
1275+
1276+/// Deleting a course takes its id out of every template holding it, in the
1277+/// cascade that detaches it from the sections.
1278+///
1279+/// Without that sweep the id stayed in the list forever and every doc surface
1280+/// lied: `PATCH`ing the template back **as it stands** is the documented
1281+/// self-heal, and it answered `400` ("one of these courses does not exist"),
1282+/// because the handler resolves the ids the *request* names — the very ones it
1283+/// had just read back. So the assertion that matters is not only that the store
1284+/// is clean but that the round trip a manager is told to make succeeds.
1285+#[tokio::test]
1286+async fn deleting_a_course_takes_it_out_of_every_blueprint() {
1287+ let (app, db) = app_and_db().await;
1288+ let manager = login_as(&app, &db, "mgr", "manager").await;
1289+ let algebra = create_course(&app, &manager, "algebra").await;
1290+ let history = create_course(&app, &manager, "history").await;
1291+ // No students: the section is here so the pump has something to walk, and
1292+ // an empty roster is what lets the course be deleted at all (one with a
1293+ // student on it is a 409).
1294+ let class = create_class(&app, &manager, "9-A", "9").await;
1295+
1296+ let made = send(
1297+ &app,
1298+ "POST",
1299+ "/classes/blueprints",
1300+ Some(&manager),
1301+ Some(json!({ "grade": "9", "course_ids": [algebra.clone(), history.clone()] })),
1302+ )
1303+ .await;
1304+ assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body);
1305+ assert!(attached(&class, &history, &db).await);
1306+
1307+ let deleted = send(
1308+ &app,
1309+ "DELETE",
1310+ &format!("/courses/{history}"),
1311+ Some(&manager),
1312+ None,
1313+ )
1314+ .await;
1315+ assert_eq!(deleted.status, StatusCode::NO_CONTENT, "{:?}", deleted.body);
1316+
1317+ assert!(
1318+ !templated("9", &history, &db).await,
1319+ "the deleted course is out of the template"
1320+ );
1321+ assert!(
1322+ templated("9", &algebra, &db).await,
1323+ "…and nothing else is — the sweep names one course"
1324+ );
1325+ assert!(
1326+ !attached(&class, &history, &db).await,
1327+ "the section's link goes in the same cascade"
1328+ );
1329+
1330+ // The self-heal, made exactly as documented: read the list, send it back.
1331+ let courses = held(&app, &manager, "9").await;
1332+ assert_eq!(
1333+ courses.len(),
1334+ 1,
1335+ "the read agrees with the store: {courses:?}"
1336+ );
1337+ let healed = send(
1338+ &app,
1339+ "PATCH",
1340+ "/classes/blueprints/9",
1341+ Some(&manager),
1342+ Some(json!({ "course_ids": courses })),
1343+ )
1344+ .await;
1345+ assert_eq!(healed.status, StatusCode::OK, "{:?}", healed.body);
1346+
1347+ // …and the status read has no phantom to report.
1348+ let status = send(
1349+ &app,
1350+ "GET",
1351+ "/classes/blueprints/9/status",
1352+ Some(&manager),
1353+ None,
1354+ )
1355+ .await;
1356+ assert_eq!(status.status, StatusCode::OK, "{:?}", status.body);
1357+ assert!(
1358+ missing(&status, &class).is_empty(),
1359+ "a course that no longer exists is not something a section is short: {:?}",
1360+ status.body
1361+ );
1362+}
1363+
1364+/// The case no pump could ever repair: a grade with **zero** sections.
1365+///
1366+/// The prune that used to be the only thing removing a dead id fires while
1367+/// walking a section, and `POST /classes/{id}/blueprint` needs a section to run
1368+/// against — so at a grade nothing carries, no call in the whole API could
1369+/// clear the id. This sweep runs off the course's own delete, which does not
1370+/// care whether the grade has sections.
1371+#[tokio::test]
1372+async fn a_grade_with_no_sections_still_loses_its_deleted_course() {
1373+ let (app, db) = app_and_db().await;
1374+ let manager = login_as(&app, &db, "mgr", "manager").await;
1375+ let algebra = create_course(&app, &manager, "algebra").await;
1376+
1377+ let made = send(
1378+ &app,
1379+ "POST",
1380+ "/classes/blueprints",
1381+ Some(&manager),
1382+ Some(json!({ "grade": "11", "course_ids": [algebra.clone()] })),
1383+ )
1384+ .await;
1385+ assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body);
1386+ assert_eq!(made.body["matched"], 0, "no section carries the label");
1387+
1388+ let deleted = send(
1389+ &app,
1390+ "DELETE",
1391+ &format!("/courses/{algebra}"),
1392+ Some(&manager),
1393+ None,
1394+ )
1395+ .await;
1396+ assert_eq!(deleted.status, StatusCode::NO_CONTENT, "{:?}", deleted.body);
1397+
1398+ assert!(
1399+ !templated("11", &algebra, &db).await,
1400+ "no section to walk, and the id is gone anyway"
1401+ );
1402+ assert!(
1403+ held(&app, &manager, "11").await.is_empty(),
1404+ "the read agrees with the store"
1405+ );
1406+ let healed = send(
1407+ &app,
1408+ "PATCH",
1409+ "/classes/blueprints/11",
1410+ Some(&manager),
1411+ Some(json!({ "course_ids": [] })),
1412+ )
1413+ .await;
1414+ assert_eq!(
1415+ healed.status,
1416+ StatusCode::OK,
1417+ "the template is editable again: {:?}",
1418+ healed.body
1419+ );
1420+}