forge
Explore
Log in

Don't you dare go Hollow

πŸ”© close the bug hunt across meals, classes and caps

Browse files at this commit

7198cea5aad3b5a987eebdc53c7168490310d9dcAhmet Kaan GümüşParent: c9b707a
  • fix
    • πŸ”© close the bug hunt across meals, classes and caps
Show full message
fix: πŸ”© close the bug hunt across meals, classes and caps

A three-domain hunt, its fixes, and a verifier panel that refuted two of
them. Kept as one commit because the pieces interlock β€” cap.rs, the
settings pair and the pump all move together, and no smaller cut compiles.

Money can no longer be lost or stranded. Both seat transitions carry
their ledger line inside their own transaction: the claim writes the
charge, the flip writes the reversal. Before, a crash between the two
left a seat held with no bill, or a bill with no seat, keyed to an
attempt no later request could ever reach. A lost cancel could refund a
live seat. The menu revision was bumped in a query of its own, so a
booking reading in the gap claimed against a capacity or a price the
menu had already left.

Deleting a menu now takes its marks and its dishes with it, in the
transaction that deletes the row. The id is deterministic on (date,
slot), so anything left behind came back on the next publish β€” the
kitchen reading "served" for a student who never came.

A seat is always releasable: manager+ cancels any booking and is not
bound by the cutoff, so a promoted student's seat no longer wedges its
menu forever, and a debt that outlived its owner's role can be settled.
Canteen money follows /payments and is manager+, not teacher+ β€” what a
family owes the school is not classroom information.

The class pump claims its pivot in-transaction. An attach racing a
course delete used to commit a link to a row that was gone, and nothing
could then detach it or delete the class. A hand enroll now disowns a
pumped row, so a sweep cannot take back a roster decision an operator
made by hand. The role sweep is one transaction. Rosters are ordered by
when a student was added, which is what they always claimed. Both class
axes have a ceiling, and each refuses on the other's, because a pump
writes one row per member per course in a single transaction.

Settings edits are serialized: retire is idempotent, so an undo log
cannot tell the attempt that flipped a name from one that found it
already flipped, and the loser un-retired what the winner had legally
retired β€” leaving a kind gone from the list, gradable, and unremovable
for good. Grading now checks the school's list, not only the counter.
Three caps that read a snapshot integer now read the live column.

A clear marker is charged to the board's lifetime counter and boot
repairs the boards that predate it. Blank canvases refuse the clear, and
the room reports that as its own code: the refusal text had drifted into
the substring the WebSocket read as "closed", which told a live room it
was permanently read-only.

Verified against the real volume: both boot backfills, the slot-name
rule and its grandfather clause, and the new money gate.

36 changed files +4817 -594

README.mdmodified+224 -58
@@ -700,20 +700,20 @@ window filtering, before paging; negative values are a `400` naming the field.
700 | 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) |700 | 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) |
701 | POST | `/courses/{id}/teachers` | manager | `{user_id}` β€” assign a **teacher+** to run the course (idempotent; returns the course) |701 | POST | `/courses/{id}/teachers` | manager | `{user_id}` β€” assign a **teacher+** to run the course (idempotent; returns the course) |
702 | DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |702 | DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |
703-| 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) |703+| 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 |
704-| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) Β· paged |704+| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) β€” each row carries `source`, the class that pumped it or `null` for hand-placed Β· paged |
705 | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |705 | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |
706 | POST | `/classes` | manager | `{name, grade?, term_id?}` β€” create a class (şube); `grade` is a free-text year label |706 | POST | `/classes` | manager | `{name, grade?, term_id?}` β€” create a class (şube); `grade` is a free-text year label |
707 | GET | `/classes` | teacher | List classes, newest first Β· paged |707 | GET | `/classes` | teacher | List classes, newest first Β· paged |
708 | GET | `/classes/{id}` | teacher | Get one class |708 | GET | `/classes/{id}` | teacher | Get one class |
709 | PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read β€” nothing written, re-read and retry) |709 | PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`; `409` if the `term_id` it moves off changed since the read β€” nothing written, re-read and retry) |
710 | DELETE | `/classes/{id}` | manager | Delete a class β€” `409` while it still holds students or courses |710 | DELETE | `/classes/{id}` | manager | Delete a class β€” `409` while it still holds students or courses |
711-| POST | `/classes/{id}/members` | manager | `{user_id}` β€” add a **student**; enrolls them into every attached course (`409` if one is full, naming it, or if already a member) |711+| POST | `/classes/{id}/members` | manager | `{user_id}` β€” add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists β€” detach that link first β€” if already a member, or once the class holds `max_class_members`) |
712-| GET | `/classes/{id}/members` | teacher | List the class roster Β· paged |712+| GET | `/classes/{id}/members` | teacher | List the class roster, newest added first Β· paged |
713 | DELETE | `/classes/{id}/members/{user}` | manager | Remove a member β€” sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |713 | DELETE | `/classes/{id}/members/{user}` | manager | Remove a member β€” sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |
714-| POST | `/classes/{id}/courses` | teacher | `{course_id}` β€” attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, or if already attached) |714+| POST | `/classes/{id}/courses` | teacher | `{course_id}` β€” attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |
715-| GET | `/classes/{id}/courses` | teacher | List the class's attached courses Β· paged |715+| GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first Β· paged |
716-| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) β€” the same sweep along the course axis |716+| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) β€” the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |
717 | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` β€” add a lesson (course manager; teacher defaults to the caller) |717 | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` β€” add a lesson (course manager; teacher defaults to the caller) |
718 | GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) Β· paged |718 | GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, assigned teacher, or manager+) Β· paged |
719 | POST | `/courses/{id}/subjects` | teacher | `{name, description?}` β€” add a curriculum subject (course manager) |719 | POST | `/courses/{id}/subjects` | teacher | `{name, description?}` β€” add a curriculum subject (course manager) |
@@ -829,34 +829,34 @@ window filtering, before paging; negative values are a `400` naming the field.
829 | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |829 | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |
830 | GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` β€” full |830 | GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` β€” full |
831 | GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` |831 | GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` |
832-| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on "Invalid lists, bands, file limit, or chat limits"; `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see "Per-school policy") |832+| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on "Invalid lists, bands, file limit, or chat limits" β€” a meal slot name carrying `/ \ ? # %` is refused here too, since the name becomes a menu's URL id (a name the stored list already carries is exempt, so an older list stays editable β€” it still cannot carry a new menu); `409` when a removed exam kind still has graded exams, or a removed meal slot still has published menus (see "Per-school policy") |
833 | POST | `/terms` | manager | `{name, starts_at, ends_at}` β€” past dates allowed (calendar backfill) |833 | POST | `/terms` | manager | `{name, starts_at, ends_at}` β€” past dates allowed (calendar backfill) |
834 | GET | `/terms` | student | List terms, newest first Β· paged |834 | GET | `/terms` | student | List terms, newest first Β· paged |
835 | GET | `/terms/{id}` | student | Get one term |835 | GET | `/terms/{id}` | student | Get one term |
836 | PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |836 | PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |
837 | DELETE | `/terms/{id}` | manager | Delete a term β€” `409` while any course or class still links to it |837 | DELETE | `/terms/{id}` | manager | Delete a term β€” `409` while any course or class still links to it |
838-| POST | `/meals/menus` | manager | `{date, slot, capacity?}` β€” publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots`; `409` when that day+slot is already published |838+| POST | `/meals/menus` | manager | `{date, slot, capacity?}` β€” publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots` and may not contain `/ \ ? # %` (it becomes part of the menu's URL id); `409` when that day+slot is already published |
839 | GET | `/meals/menus` | student | List menus with their dishes, newest day first Β· `?from=&to=` inclusive `YYYY-MM-DD` range Β· paged |839 | GET | `/meals/menus` | student | List menus with their dishes, newest day first Β· `?from=&to=` inclusive `YYYY-MM-DD` range Β· paged |
840 | GET | `/meals/menus/{id}` | student | One menu with its dishes |840 | GET | `/meals/menus/{id}` | student | One menu with its dishes |
841 | PATCH | `/meals/menus/{id}` | manager | `{capacity}` β€” the only mutable field (`null` = uncapped); `date` and `slot` are immutable |841 | PATCH | `/meals/menus/{id}` | manager | `{capacity}` β€” the only mutable field (`null` = uncapped); `date` and `slot` are immutable |
842-| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat |842+| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes and its attendance marks go with it, in the same transaction; `409` while anyone still holds a seat |
843 | POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` β€” add a dish (≀ 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` |843 | POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` β€” add a dish (≀ 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` |
844-| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `"description": null` clears it) |844+| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `"description": null` clears it); `404` once its menu is gone |
845-| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu |845+| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu; `404` once that menu is gone |
846 | GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |846 | GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |
847 | GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |847 | GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |
848 | PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` β€” record what a student may not eat (`tags` replaces the list, `"note": null` clears it); **manager+**, a student never edits their own |848 | PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` β€” record what a student may not eat (`tags` replaces the list, `"note": null` clears it); **manager+**, a student never edits their own |
849 | POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` β€” take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned |849 | POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` β€” take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned |
850 | GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first Β· paged |850 | GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first Β· paged |
851 | GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included Β· paged |851 | GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included Β· paged |
852-| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays); idempotent β€” cancelling again is a `200` that replays the refund; `409` past the cutoff |852+| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays) β€” its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent β€” cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** β€” a manager+ frees a closed meal's seat |
853-| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` β€” mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; **moves no money** |853+| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` β€” mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; `404` if the menu is unpublished mid-request; **moves no money** |
854 | GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu Β· paged |854 | GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu Β· paged |
855 | GET | `/meals/attendance/{user}` | student | One student's meal-attendance history Β· `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day Β· paged Β· own id always, otherwise teacher+ or a parent link |855 | GET | `/meals/attendance/{user}` | student | One student's meal-attendance history Β· `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day Β· paged Β· own id always, otherwise teacher+ or a parent link |
856 | GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |856 | GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |
857-| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link |857+| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise **manager+** or a parent link β€” a teacher gets a `403`, canteen debt is family debt |
858-| GET | `/meals/ledger/{user}` | student | That student's statement β€” every charge, credit, reversal β€” newest first Β· paged Β· same gate |858+| GET | `/meals/ledger/{user}` | student | That student's statement β€” every charge, credit, reversal β€” newest first Β· paged Β· same gate (manager+, parent link, or own) |
859-| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` β€” record money received; **admin only**, appends a `credit` line |859+| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` β€” record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) |
860 | POST | `/payments/plans` | manager | `{name, installments}` β€” write a fee plan (1–60 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody |860 | POST | `/payments/plans` | manager | `{name, installments}` β€” write a fee plan (1–60 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody |
861 | GET | `/payments/plans` | manager | List fee plans, newest first Β· paged |861 | GET | `/payments/plans` | manager | List fee plans, newest first Β· paged |
862 | GET | `/payments/plans/{id}` | manager | One fee plan with its schedule |862 | GET | `/payments/plans/{id}` | manager | One fee plan with its schedule |
@@ -887,7 +887,7 @@ window filtering, before paging; negative values are a `400` naming the field.
887 | GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included Β· `?epoch=` for one epoch Β· paged |887 | GET | `/boards/{id}/history` | student | The whole append-only log, oldest first, `clear` markers included Β· `?epoch=` for one epoch Β· paged |
888 | GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) Β· paged |888 | GET | `/boards/{id}/epochs` | student | The epoch index: every `clear` marker (the epoch it closed, that epoch's final stroke count, who cleared, when) Β· paged |
889 | PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` β€” re-title (any participant); the roster and the lock are the creator's alone (`403`) |889 | PATCH | `/boards/{id}` | student | `{title?, participants?, locked?}` β€” re-title (any participant); the roster and the lock are the creator's alone (`403`) |
890-| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap β€” nothing is deleted; `409` on a closed board |890+| POST | `/boards/{id}/clear` | student | **Creator only**: bump the epoch, blanking the live canvas and resetting its cap β€” nothing is deleted; `409` on a closed board, and on a canvas that is **already blank** (the marker is a stored row, so a clear has to close at least one mark to be worth one) |
891 | POST | `/boards/{id}/close` | student | **Creator only**: retire the board β€” permanently read-only, still fully readable; idempotent, and there is no reopen |891 | POST | `/boards/{id}/close` | student | **Creator only**: retire the board β€” permanently read-only, still fully readable; idempotent, and there is no reopen |
892 | DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |892 | DELETE | `/boards/{id}` | student | **Creator only**: delete the board and its whole stroke log; frees one of the creator's board seats |
893 | GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see "Collaborative whiteboard") |893 | GET | `/boards/{id}/ws` | student | **WebSocket** board room: a `join` replays the current epoch, every accepted stroke fans out to the other participants (see "Collaborative whiteboard") |
@@ -1263,7 +1263,7 @@ rewrites history: an exam keeps its retired kind, a roll-call row keeps its
1263 retired status β€” only **new writes** are held to the current lists (which is1263 retired status β€” only **new writes** are held to the current lists (which is
1264 why grading an exam whose kind has left the list is refused).1264 why grading an exam whose kind has left the list is refused).
1265 1265
1266-The kitchen is data too: a manager publishes a **menu** per calendar day and meal slot, with its dishes, their dietary tags, and prices in minor units; booking a seat charges that price as a snapshot and an admin records the cash that comes back in (see "Food program: menus, dishes, bookings & the ledger").1266+The kitchen is data too: a manager publishes a **menu** per calendar day and meal slot, with its dishes, their dietary tags, and prices in minor units; booking a seat charges that price as a snapshot and an admin records the cash that comes back in (see "Food program: menus, dishes, bookings & the ledger"). The one shape rule on a **meal slot's name** lives here: it may not contain `/`, `\`, `?`, `#` or `%` (`400`), because the name is copied verbatim into a menu's record id and that id is a URL path segment β€” a slot the settings accepted but no menu could be addressed under would be a slot the canteen cannot use. A name the stored list *already* carries is exempt, so a list written before the rule existed can still be edited around the offending name β€” otherwise one bad slot froze the whole list, since re-sending it is a `400` and dropping it is a `409` once a menu used it. The grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it.
1267 1267
1268 Academic structure is data too. **Terms** (`/terms`) model whatever calendar1268 Academic structure is data too. **Terms** (`/terms`) model whatever calendar
1269 the school runs β€” semester, trimester, quarter systems are just rows with a1269 the school runs β€” semester, trimester, quarter systems are just rows with a
@@ -1299,6 +1299,22 @@ The school publishes **one menu per calendar day and meal slot** (`POST
1299 booking cutoff resolves it live from the current list. The mirror of that rule lives in settings: a slot any1299 booking cutoff resolves it live from the current list. The mirror of that rule lives in settings: a slot any
1300 menu was published for cannot be removed from the list (`409`), same1300 menu was published for cannot be removed from the list (`409`), same
1301 contract exam kinds have with graded exams.1301 contract exam kinds have with graded exams.
1302+- **A slot name may not contain `/`, `\`, `?`, `#` or `%`** β€” a `400` at
1303+ `PATCH /settings` when the slot is defined, and again here when a menu is
1304+ published under one. The name goes verbatim into the menu's record id, and
1305+ that id is a URL path segment: a slot called `a/b` would publish a menu at
1306+ `/meals/menus/2026-09-14_a/b`, an address no route can ever match again β€” the
1307+ menu could not be read, edited or deleted. Ordinary names are untouched;
1308+ spaces and Turkish letters percent-encode into one segment as they always
1309+ have.
1310+- **A name the school's stored list already carries is exempt from that rule.**
1311+ It is younger than the lists it validates, and `PATCH /settings` re-validates
1312+ the *whole* submitted list β€” so a school that stored `a/b` before the rule
1313+ existed could never edit `meal_slots` again: re-sending the name is a `400`
1314+ and dropping it is a `409` the moment a menu was published under it. The
1315+ grandfathered name is exactly as unusable as it already was β€” no menu may be
1316+ published under it β€” and dropping it is still the only way to be rid of it.
1317+ The rule stays in full force for every *new* name.
1302 1318
1303 The day+slot pair is unique: a second publish for the same meal answers `409`1319 The day+slot pair is unique: a second publish for the same meal answers `409`
1304 β€” edit the first one instead. Only `capacity` is patchable (`null` = uncapped)1320 β€” edit the first one instead. Only `capacity` is patchable (`null` = uncapped)
@@ -1309,7 +1325,11 @@ menu.
1309 `PATCH`/`DELETE /meals/dishes/{did}`). Each carries a name, an optional1325 `PATCH`/`DELETE /meals/dishes/{did}`). Each carries a name, an optional
1310 description (blank or `null` clears it), dietary `tags` drawn from the1326 description (blank or `null` clears it), dietary `tags` drawn from the
1311 school's `dietary_tags` list β€” an unknown tag is a `400`, never a stored1327 school's `dietary_tags` list β€” an unknown tag is a `400`, never a stored
1312-string β€” and a `price_minor`.1328+string β€” and a `price_minor`. Every dish write moves its **menu's** revision in
1329+the same transaction (that is what keeps a booking from freezing a price the
1330+menu has already left, below), which also makes the menu's existence part of
1331+the write: editing or deleting a dish whose menu has since been unpublished is
1332+a `404`, not a write onto a menu that is gone.
1313 1333
1314 ### Dietary profiles and conflicts1334 ### Dietary profiles and conflicts
1315 1335
@@ -1343,8 +1363,18 @@ many menus or dishes the page holds.
1343 is ever introduced by transport or by a client's JSON number parser.1363 is ever introduced by transport or by a client's JSON number parser.
1344 1364
1345 Reads are open to every authenticated user β€” a student has to see what is1365 Reads are open to every authenticated user β€” a student has to see what is
1346-being served β€” and every write is manager+. Deleting a menu takes its dishes1366+being served β€” and every write is manager+. The exception is the money:
1347-with it: a dish has no meaning apart from the menu it was published on.1367+`GET /meals/balance/{user}` and `GET /meals/ledger/{user}` are manager+ (or
1368+the student, or their parent), gated exactly like `/payments`. Deleting a menu takes its dishes
1369+**and its attendance marks** with it, in the same transaction as the row: a
1370+dish has no meaning apart from the menu it was published on, and a menu's
1371+record id is deterministic on day+slot, so anything left behind would come back
1372+attached to the *next* menu published for that meal β€” the kitchen reading
1373+"served" for a student who never came, priced off food nobody re-entered.
1374+Cancelled **bookings** deliberately stay: their `attempt` counter is what keeps
1375+the ledger's `(booking, attempt)` ids unique, and a re-book on a republished
1376+menu would otherwise reuse an id the ledger already holds and bill the seat
1377+nothing.
1348 1378
1349 **Bookings** are seats on a published menu (`POST1379 **Bookings** are seats on a published menu (`POST
1350 /meals/menus/{id}/bookings`). One row per (menu, student), keyed by a1380 /meals/menus/{id}/bookings`). One row per (menu, student), keyed by a
@@ -1365,15 +1395,33 @@ teacher or manager ordering a child's lunch is a `403`.
1365 timed out) is recovered by sending it again. Refusing it as a `409` β€” as it1395 timed out) is recovered by sending it again. Refusing it as a `409` β€” as it
1366 once did β€” made that state permanent: no route could append the missing1396 once did β€” made that state permanent: no route could append the missing
1367 reversal, and the student stayed billed for a seat they no longer held.1397 reversal, and the student stayed billed for a seat they no longer held.
1368-- **The capacity check is serialized in-process.** Counting rows and then1398+- **A manager+ may cancel anybody's seat.** Booking is student-and-parent
1369- writing one is write-skew: SurrealDB does not conflict-check a cross-record1399+ only, and cancelling used to be the same door β€” which left a seat nobody on
1370- count against a concurrent insert, so 24 students racing for 3 seats would1400+ the API could give back the moment its student was promoted to staff or its
1371- otherwise all pass the count. The whole check-then-write runs under the same1401+ parent was unlinked: the menu refused its own deletion forever and the charge
1372- lock a menu publish takes, and the cap is re-read inside it.1402+ could never be reversed, since cancelling is the only route that reverses
1373-- **One cutoff closes both ends.** Within the school's1403+ one. A role change deliberately sweeps no bookings on its own; moving money
1374- `meal_cancel_cutoff_minutes` of the meal's serving time, neither a new1404+ is a decision, not a side effect.
1375- booking nor a cancellation lands (`409`) β€” the kitchen's headcount has to1405+- **The capacity check is a single conditional write, decided by the
1376- settle at some point. `null` (the default) means no cutoff at all. The1406+ database.** Counting rows and then writing one would be write-skew β€”
1407+ SurrealDB does not conflict-check a cross-record count against a concurrent
1408+ insert, so 24 students racing for 3 seats would all pass the count β€” so the
1409+ seat is instead claimed on a counter kept on the **menu row itself**, taken
1410+ and spent by one `UPDATE … WHERE` that also places the booking row in the
1411+ same transaction. No lock is involved and none would help: a duplicate
1412+ `POST` rolls its own seat back rather than costing a stranger their place.
1413+- **One cutoff closes both ends β€” for the people it is aimed at.** Within the
1414+ school's `meal_cancel_cutoff_minutes` of the meal's serving time, neither a
1415+ new booking nor a cancellation lands (`409`) β€” the kitchen's headcount has to
1416+ settle at some point. `null` (the default) means no cutoff at all. It binds
1417+ **students and parents only**: a manager+ cancelling somebody's seat is not
1418+ held to it, because the deadline exists to stop students gaming the headcount
1419+ and that is no reason to leave staff holding a seat they cannot free. Past
1420+ the cutoff an uncancellable seat also made its menu undeletable forever (a
1421+ menu with a live booking refuses its own deletion) and its charge
1422+ unreversable, since cancelling is the only route that reverses one. A meal
1423+ already closed is therefore still freeable, and its menu still deletable, by
1424+ manager+ β€” the same state a school that set no cutoff at all runs under. The
1377 cutoff is measured back from the menu's `date` **plus the slot's1425 cutoff is measured back from the menu's `date` **plus the slot's
1378 `serving_minute`** (`GET /settings`), so a two-hour cutoff on a lunch served1426 `serving_minute`** (`GET /settings`), so a two-hour cutoff on a lunch served
1379 at `720` closes at 10:00 UTC that morning, not at 22:00 the night before.1427 at `720` closes at 10:00 UTC that morning, not at 22:00 the night before.
@@ -1412,6 +1460,13 @@ list meaning two things would let a school change one by editing the other.
1412 One row per (menu, student) keyed by a composite id, so a correction re-marks1460 One row per (menu, student) keyed by a composite id, so a correction re-marks
1413 the same row instead of stacking a second one.1461 the same row instead of stacking a second one.
1414 1462
1463+The menu has to still be there: a mark whose menu is unpublished mid-request is
1464+a `404` and writes nothing. The existence check *is* the write's own target
1465+rather than a read the write then trusts, because a menu's id is deterministic
1466+on day+slot β€” an unconditional mark landing just after the delete committed
1467+would be swept by nothing and would reappear as a mark on the next menu
1468+published for that meal.
1469+
1415 **Attendance has zero billing effect.** Booking is the sole charge trigger, so1470 **Attendance has zero billing effect.** Booking is the sole charge trigger, so
1416 a student who booked and did not eat still pays β€” the kitchen bought the food.1471 a student who booked and did not eat still pays β€” the kitchen bought the food.
1417 There is no no-show penalty, no refund-on-missed, and no auto-reversal:1472 There is no no-show penalty, no refund-on-missed, and no auto-reversal:
@@ -1459,29 +1514,54 @@ money on account. Amounts are stored positive; the sign lives in the `kind`.
1459 but the booking row records that it *was* free, so "free when taken" is1514 but the booking row records that it *was* free, so "free when taken" is
1460 never confused with "not billed yet": pricing the menu afterwards leaves1515 never confused with "not billed yet": pricing the menu afterwards leaves
1461 every seat already taken on it free.1516 every seat already taken on it free.
1462-- **Charge and reversal are keyed by `(booking, attempt)`.** The seat and its1517+- **Charge and reversal are keyed by `(booking, attempt)`.** The seat, its row
1463- money move together under one in-process lock, and the ledger id is derived1518+ and its money move together in one transaction on *both* sides β€” the claim
1519+ writes the charge, the flip writes the reversal β€” and the ledger id is derived
1464 from the seat plus how many times it has been taken β€” so eight simultaneous1520 from the seat plus how many times it has been taken β€” so eight simultaneous
1465 `POST`s of one seat write one charge, a retried cancel refunds once, and a1521 `POST`s of one seat write one charge, a retried cancel refunds once, and a
1466 write that failed halfway heals when the request is repeated. Booking the1522 write that failed halfway heals when the request is repeated. Booking the
1467 same seat twice bills once because the *identity* is the same, never1523 same seat twice bills once because the *identity* is the same, never
1468 because a scan happened to see the first charge in time.1524 because a scan happened to see the first charge in time.
1469 - **Cancelling appends a `reversal`** for the charge's exact amount, with1525 - **Cancelling appends a `reversal`** for the charge's exact amount, with
1470- `source` pointing at the charge it undoes. The charge row itself stays. A1526+ `source` pointing at the charge it undoes, and it is written **by the same
1471- cancel past the cutoff is already a `409`, so a reversal only ever follows a1527+ transaction that flips the seat** β€” not appended after it. The two as
1472- legal cancel β€” and repeating a cancel replays the reversal, which is what1528+ separate writes left a crash in between with a seat given back and the
1473- makes the refund recoverable rather than a one-shot the network can lose.1529+ student still billed, and no later cancel would ever repay it, because the
1474- Re-booking afterwards is a **fresh** charge at the then-current price.1530+ money is keyed to the attempt the flip had already consumed. Folded in, the
1475-- **The price snapshot is taken under the booking lock**, and dish1531+ seat cannot come back without the money. Booking is folded the same way β€” the
1476- create/edit/delete take that same lock. Taken outside it, a dish added1532+ charge rides the claim's own transaction, because a charge appended afterwards
1477- between the sum and the seat would be frozen onto the row as "the menu was1533+ let a cancel land in the gap, reverse nothing (there was no charge yet), and
1478- free then" β€” and nothing heals it, since a seat already held is returned1534+ the bill arrive anyway: a student holding no seat and owing money. The reversal is written only when
1479- as-is, never re-priced.1535+ the charge it undoes is really there, checked inside that same transaction β€”
1536+ a refund with no charge behind it invents money. The charge row itself stays.
1537+ Repeating a cancel replays the reversal, which is what heals a seat flipped
1538+ before that was true and makes the refund recoverable rather than a one-shot
1539+ the network can lose; the cutoff is deliberately not re-checked on that path,
1540+ since the seat is already given back. Re-booking afterwards is a **fresh**
1541+ charge at the then-current price.
1542+- **The price snapshot is pinned by the menu's revision, not by a lock.** The
1543+ dishes are summed a round trip before the seat is claimed, so a dish landing
1544+ in between would otherwise be frozen onto the row as "the menu was free
1545+ then" β€” and nothing heals that, since a seat already held is returned as-is,
1546+ never re-priced. Instead every dish write bumps a revision counter on the
1547+ menu, and the claim that takes the seat *also* asserts the menu is still at
1548+ the revision the price was read at: the booking is refused, re-reads, and
1549+ prices and seats itself again together. A lock around the read could not have
1550+ promised this β€” the price is read a round trip before the claim either way β€”
1551+ so what is frozen is always a price the menu genuinely carried at the instant
1552+ the seat was taken. A menu edited over and over under one booking gives up
1553+ after a few rounds with a `409`.
1480 - **A no-show still pays.** Meal attendance has zero billing effect β€” nothing1554 - **A no-show still pays.** Meal attendance has zero billing effect β€” nothing
1481 in the ledger reads or writes it. The seat was reserved and the food was1555 in the ledger reads or writes it. The seat was reserved and the food was
1482 cooked; there is no no-show penalty and no no-show refund.1556 cooked; there is no no-show penalty and no no-show refund.
1483 - **`POST /meals/credits` is admin-only**, not manager: writing down cash1557 - **`POST /meals/credits` is admin-only**, not manager: writing down cash
1484- received is the highest-trust action in the app. It appends a `credit` for a1558+ received is the highest-trust action in the app. The target must be a
1559+ **student, or anyone who already carries meal-ledger lines**: only a student
1560+ runs up a meal balance, so crediting anyone else is a typo and a typo here is
1561+ money in the wrong ledger β€” but a debt outlives its debtor's role change, and
1562+ the student-only rule alone made a promoted student's debt permanently
1563+ unsettleable, since no other route appends a credit. A mistyped staff id
1564+ carries no lines, so it is still a `400`. It appends a `credit` for a
1485 student with a positive `amount_minor` (≀ 10 000 000), an optional `method`1565 student with a positive `amount_minor` (≀ 10 000 000), an optional `method`
1486 ("cash", "havale", …) and `note`, and records the admin as `recorded_by`.1566 ("cash", "havale", …) and `note`, and records the admin as `recorded_by`.
1487 There is no payment gateway and no card data, ever. An over-credit is1567 There is no payment gateway and no card data, ever. An over-credit is
@@ -1490,7 +1570,10 @@ money on account. Amounts are stored positive; the sign lives in the `kind`.
1490 `GET /meals/balance/me` is the caller's own balance. `GET1570 `GET /meals/balance/me` is the caller's own balance. `GET
1491 /meals/balance/{user}` and `GET /meals/ledger/{user}` (paged, newest line1571 /meals/balance/{user}` and `GET /meals/ledger/{user}` (paged, newest line
1492 first) read a student's: your own id always passes, anyone else's needs1572 first) read a student's: your own id always passes, anyone else's needs
1493-teacher+ or a `parent_link` to that student. A charge's `source` is the1573+**manager+** or a `parent_link` to that student β€” **a teacher gets a `403`**,
1574+the one pair in this block narrower than the rest of it. Canteen debt is
1575+family debt: the money follows the `/payments` rule, not the classroom one,
1576+while the dietary profile, booking and attendance reads stay teacher+. A charge's `source` is the
1494 booking id it came from, a reversal's is the charge line it reverses, and a1577 booking id it came from, a reversal's is the charge line it reverses, and a
1495 credit has none.1578 credit has none.
1496 1579
@@ -1505,7 +1588,8 @@ them would make either statement unreadable.
1505 Every write here is **manager+**. Reads are narrower than the other1588 Every write here is **manager+**. Reads are narrower than the other
1506 per-student reports: the student themselves, a parent holding a live link to1589 per-student reports: the student themselves, a parent holding a live link to
1507 them, or manager+ β€” **a teacher gets a `403` on every `/payments` route**,1590 them, or manager+ β€” **a teacher gets a `403` on every `/payments` route**,
1508-because what a family owes the school is not classroom information.1591+because what a family owes the school is not classroom information. The
1592+canteen's balance and ledger follow the same rule, for the same reason.
1509 1593
1510 ### Fee plans and what turns them into money1594 ### Fee plans and what turns them into money
1511 1595
@@ -2161,8 +2245,10 @@ already carries β€” and what gets written is an ordinary `enrollment` row, the
2161 same one `POST /courses/{id}/enrollments` writes, counted against the same2245 same one `POST /courses/{id}/enrollments` writes, counted against the same
2162 `enrollment_count`. Each row a class writes is tagged with it as the row's2246 `enrollment_count`. Each row a class writes is tagged with it as the row's
2163 `source`; **no `source` means placed by hand**, and that one bit is what makes2247 `source`; **no `source` means placed by hand**, and that one bit is what makes
2164-the sweeps below safe. It is internal bookkeeping, not API surface: no2248+the sweeps below safe. It rides back out on every enrollment response
2165-enrollment response returns it.2249+(`GET /courses/{id}/enrollments`) as the class's id, or `null` for a
2250+hand-placed row β€” without it no client could tell which of the roster rows it
2251+is showing a class change is about to remove.
2166 2252
2167 **Already enrolled is skipped.** A pair that already has an enrollment row is2253 **Already enrolled is skipped.** A pair that already has an enrollment row is
2168 left exactly as it stands β€” no second seat charged, no `source` rewritten. A2254 left exactly as it stands β€” no second seat charged, no `source` rewritten. A
@@ -2178,6 +2264,14 @@ naming it (`course:<key> is full, so the class cannot take this student`,
2178 claimed earlier in the same run: a half-enrolled class is worse than a refused2264 claimed earlier in the same run: a half-enrolled class is worse than a refused
2179 one, and the refusal names the course whose capacity to raise.2265 one, and the refusal names the course whose capacity to raise.
2180 2266
2267+A second `409` reads off the same claim and is deliberately told apart from it:
2268+one of the class's attached courses **no longer exists**
2269+(`course:<key> no longer exists β€” detach it from this class first`). A seat
2270+claim that matches nothing means "full" *or* "no such row", and reporting a
2271+stale attachment as a full course would send staff off to raise a capacity that
2272+is not there β€” on a class every member-add now fails on. Detach the link and
2273+the class works again.
2274+
2181 **Removals take back only what the class pumped, and repair before they2275 **Removals take back only what the class pumped, and repair before they
2182 delete.** Removing a member (`DELETE /classes/{id}/members/{user}`) or2276 delete.** Removing a member (`DELETE /classes/{id}/members/{user}`) or
2183 detaching a course (`DELETE /classes/{id}/courses/{course}`) sweeps the2277 detaching a course (`DELETE /classes/{id}/courses/{course}`) sweeps the
@@ -2199,14 +2293,31 @@ remain a member, because the pump runs on writes, never on a schedule. Staff
2199 put them back by enrolling them by hand (which makes the row hand-placed) or2293 put them back by enrolling them by hand (which makes the row hand-placed) or
2200 by detaching and re-attaching the course.2294 by detaching and re-attaching the course.
2201 2295
2296+**And a manual enroll wins too, permanently.** `POST /courses/{id}/enrollments`
2297+landing on a row a class pumped takes the row *off* that class β€” its `source`
2298+is cleared, the response comes back with `"source": null` β€” so no later class
2299+sweep can undo a placement an operator made on purpose. That is the mirror of
2300+the rule above: hand-placed beats pumped in both directions, and without it
2301+"hand-placed" was a state only a *first* enroll could ever reach.
2302+
2202 **Delete guards.** A class still holding members or attached courses refuses2303 **Delete guards.** A class still holding members or attached courses refuses
2203 deletion with a `409` ("remove its members and detach its courses first") β€”2304 deletion with a `409` ("remove its members and detach its courses first") β€”
2204 the roster it owes is never dropped out from under the courses silently. A2305 the roster it owes is never dropped out from under the courses silently. A
2205 term linked by any class refuses deletion the same way courses make it refuse.2306 term linked by any class refuses deletion the same way courses make it refuse.
2206 Deleting a **course** detaches it from every class it was on (its enrollments2307 Deleting a **course** detaches it from every class it was on (its enrollments
2207 go with it), and a role change that takes a user off `student` drops their2308 go with it), and a role change that takes a user off `student` drops their
2208-class memberships exactly as it drops their enrollments β€” a membership left2309+class memberships exactly as it drops their enrollments β€” in one transaction,
2209-behind would keep pumping them back into courses.2310+because a membership left behind would keep pumping them back into courses,
2311+while an enrollment left behind would stay tagged with a class the released
2312+counters had already made deletable, and nothing could ever sweep it again.
2313+
2314+**A link to a deleted course detaches instead of refusing.** Should a
2315+`class_course` row ever be left pointing at a course row that is gone,
2316+`DELETE /classes/{id}/courses/{course}` still answers `204`: management rights
2317+are read *off* the course, so a stale link had no readable owner and the detach
2318+used to `404` forever β€” which also left the class permanently undeletable, its
2319+attachment counter counting a row nothing could sweep. There is no roster left
2320+to protect, and the caller is already teacher+.
2210 2321
2211 **Who may.** Creating, editing and deleting a class, and adding or removing2322 **Who may.** Creating, editing and deleting a class, and adding or removing
2212 its members, is **manager+** β€” a class is school structure, not classroom2323 its members, is **manager+** β€” a class is school structure, not classroom
@@ -2214,15 +2325,37 @@ work. Attaching or detaching a course takes management rights on **that
2214 course** (its creator, a teacher assigned to it, or manager+), since the call2325 course** (its creator, a teacher assigned to it, or manager+), since the call
2215 writes that course's roster and nothing else: the same right enrolling one2326 writes that course's roster and nothing else: the same right enrolling one
2216 student takes. Every read (`GET /classes`, `/classes/{id}`, its members and2327 student takes. Every read (`GET /classes`, `/classes/{id}`, its members and
2217-its courses, all paged, newest first) is **teacher+**.2328+its courses, all paged, newest first) is **teacher+** β€” and "newest" here means
2329+when the student was *added* or the course *attached*, not the student's or the
2330+course's own id, which is what a link row keyed on the pair would otherwise
2331+sort by. Rows written before that stamp existed carry none, and sort last.
2218 2332
2219 **Codes.** Adding a member or attaching a course answers `201`; a repeat is a2333 **Codes.** Adding a member or attaching a course answers `201`; a repeat is a
2220 `409` ("the student is already in this class", "the course is already on this2334 `409` ("the student is already in this class", "the course is already on this
2221 class"). An id in the **body** that names nothing β€” an unknown `user_id` or2335 class"). An id in the **body** that names nothing β€” an unknown `user_id` or
2222 `course_id`, or a member who is not a `student` β€” is a `400`; an id in the2336 `course_id`, or a member who is not a `student` β€” is a `400`; an id in the
2223 **path** that names nothing (the class, or a member/course that was not on it)2337 **path** that names nothing (the class, or a member/course that was not on it)
2224-is a `404`. Bounds: name ≀ 200 characters, grade ≀ 20, both published in the2338+is a `404`. Bounds: name ≀ 200 characters, grade ≀ 20, **at most 200 students
2225-`course` group of `GET /limits`.2339+and 50 courses** per class (`max_class_members`, `max_class_courses`), all four
2340+published in the `course` group of `GET /limits`. Past either ceiling the
2341+add or the attach is a `409` naming it ("this class already holds 200
2342+students") β€” a standing class someone can make room in, which is why it is not
2343+the `404` a deleted class answers. Those two numbers are not comfort limits:
2344+adding a member writes one enrollment per attached course and attaching a
2345+course writes one per member, both in a *single* transaction, so each axis's
2346+ceiling is the bound on the other axis's write loop β€” an unbounded class is an
2347+unbounded transaction any manager could trigger.
2348+
2349+Which is why each write is refused on the **other** axis too. A class already
2350+standing *above* a ceiling cannot take a member while it holds more than 50
2351+courses ("this class holds more than 50 courses β€” detach some before adding a
2352+student"), nor a course while it holds more than 200 students ("this class
2353+holds more than 200 students β€” remove some before attaching a course"), both
2354+`409`. Room on the axis being written is not the question: the write loop's
2355+length is set by the other one, and letting it run because *this* side has
2356+space is exactly the unbounded transaction the ceilings exist to prevent. Only
2357+a class that predates the ceilings can be there, and only shrinking the
2358+overloaded axis clears it.
2226 2359
2227 ## Quick tour (curl)2360 ## Quick tour (curl)
2228 2361
@@ -2652,6 +2785,13 @@ markers *are* the epoch index, which is why there is no epochs table and why
2652 the open (unclosed) epoch is deliberately absent from `GET /boards/{id}/epochs`.2785 the open (unclosed) epoch is deliberately absent from `GET /boards/{id}/epochs`.
2653 `DELETE /boards/{id}` is the one operation here that really destroys marks.2786 `DELETE /boards/{id}` is the one operation here that really destroys marks.
2654 2787
2788+**A blank canvas cannot be cleared** (`409` β€” as a closed board is, while a
2789+participant who is not the creator gets the `403` the two doors above give
2790+them). The marker is a real stored row and it is charged to the board's
2791+lifetime budget, so a clear has to close at least one mark to be worth one β€”
2792+without that rule every press of a button the creator can hold down minted a
2793+free row, and the epoch index filled with zero-stroke sessions.
2794+
2655 **Three caps, and only one of them is terminal** (all three published at `GET2795 **Three caps, and only one of them is terminal** (all three published at `GET
2656 /limits` under `board`):2796 /limits` under `board`):
2657 2797
@@ -2660,6 +2800,19 @@ the open (unclosed) epoch is deliberately absent from `GET /boards/{id}/epochs`.
2660 history is kept, drawing resumes.2800 history is kept, drawing resumes.
2661 - `max_board_strokes` bounds the board's **lifetime** storage β€”2801 - `max_board_strokes` bounds the board's **lifetime** storage β€”
2662 `total_stroke_count`, which never resets, because a clear keeps its history.2802 `total_stroke_count`, which never resets, because a clear keeps its history.
2803+ It counts **rows on the board**, not strokes drawn: a `clear` marker is a
2804+ stored row, so it costs one unit of the budget like any mark. The marker's
2805+ own unit is the one thing not refused at the ceiling β€” the last stroke of a
2806+ board's budget may well be closed by a clear, and refusing that would drop
2807+ the very marker the history needs to index the final epoch β€” so a board holds
2808+ at most `max_board_strokes + 1` rows. That held only for boards born after
2809+ the marker started paying, so **boot recomputes every board's
2810+ `total_stroke_count` from its actual rows**: a board an older binary cleared
2811+ is short exactly one per past clear, and an under-counting board is one that
2812+ keeps taking marks past the storage ceiling. This is the one backfill that is
2813+ not `= NONE`-guarded, and the one counter that may be recomputed β€” it is not
2814+ an opinion the live system maintains, it is the board's row count, so
2815+ recomputing converges instead of overwriting and the next boot writes nothing.
2663 Hitting it stamps `closed_at` and the board becomes **permanently2816 Hitting it stamps `closed_at` and the board becomes **permanently
2664 read-only**: still fully readable and replayable, never deleted, and there is2817 read-only**: still fully readable and replayable, never deleted, and there is
2665 no reopen β€” open a new board. `POST /boards/{id}/close` is the manual form of2818 no reopen β€” open a new board. `POST /boards/{id}/close` is the manual form of
@@ -2711,10 +2864,19 @@ value the client picks, echoed **verbatim** on that message's `saved` or
2711 server never reads it.2864 server never reads it.
2712 2865
2713 `error` codes are a closed set: `epoch_full` (the live canvas is full β€” clear2866 `error` codes are a closed set: `epoch_full` (the live canvas is full β€” clear
2714-it and keep drawing), `board_closed` (permanently read-only), `locked`,2867+it and keep drawing), `canvas_blank` (there was nothing on the canvas to clear
2715-`forbidden` (a creator-only command from a participant), `resync` (below),2868+β€” the board is still live and still drawable), `board_closed` (permanently
2716-`invalid` (bad JSON, an unknown frame, an over-long payload), `not_found`,2869+read-only), `locked`, `forbidden` (a creator-only command from a participant),
2717-`unauthorized`, `too_many_requests`, `conflict`, `internal`.2870+`resync` (below), `invalid` (bad JSON, an unknown frame, an over-long payload),
2871+`not_found`, `unauthorized`, `too_many_requests`, `conflict`, `internal`.
2872+
2873+The two that look alike are the two that must not be confused: `board_closed`
2874+is **terminal** and `canvas_blank` is **nothing to do**. A client that treats
2875+them alike sends a live room off clearing a canvas it never needed to lose β€”
2876+which is exactly what a code guessed from a *substring* of the refusal did
2877+("the canvas is already blank" contains the word "closed"), so the server now
2878+matches the refusal constants by value and a test pairs every one of them with
2879+the code its client must act on.
2718 2880
2719 **Persist, then publish.** A stroke is fanned out only after its row has2881 **Persist, then publish.** A stroke is fanned out only after its row has
2720 landed, so the channel can never carry a mark the database refused (a locked2882 landed, so the channel can never carry a mark the database refused (a locked
@@ -2812,7 +2974,11 @@ stop-the-world β€” `podman compose down` then `up`, never overlapping β€” and a
2812 release that adds or renames a stored counter *requires* it. An old binary2974 release that adds or renames a stored counter *requires* it. An old binary
2813 writes rows without touching the new counter, the `= NONE` backfill guard2975 writes rows without touching the new counter, the `= NONE` backfill guard
2814 (correctly) refuses to re-seed, and the resulting permanent under-count lets a2976 (correctly) refuses to re-seed, and the resulting permanent under-count lets a
2815-guard approve exactly what it exists to refuse. In-flight work does not survive2977+guard approve exactly what it exists to refuse. The one exception is a counter
2978+that is not an opinion but a plain row count β€” a board's `total_stroke_count`,
2979+recomputed from its strokes on every boot rather than seeded once, which is why
2980+that repair heals an under-count the `= NONE` guard would have skipped.
2981+In-flight work does not survive
2816 a restart either: a chatbot turn mid-inference settles `failed`/`interrupted`.2982 a restart either: a chatbot turn mid-inference settles `failed`/`interrupted`.
2817 2983
2818 ## Layout2984 ## Layout
src/constant.rsmodified+18 -0
@@ -92,6 +92,24 @@ pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000;
92 pub const MAX_CLASS_NAME_LEN: usize = 200;92 pub const MAX_CLASS_NAME_LEN: usize = 200;
93 pub const MAX_CLASS_GRADE_LEN: usize = 20;93 pub const MAX_CLASS_GRADE_LEN: usize = 20;
94 94
95+/// How big one class may get, on each of its two axes. These are not comfort
96+/// numbers: attaching a course to a class writes one enrollment per member and
97+/// adding a member writes one per attached course, both in a *single*
98+/// transaction, so each axis's counter is the bound on the other axis's write
99+/// loop β€” a class with no ceiling is an unbounded transaction anyone with the
100+/// manager role can trigger. A şube is a homeroom (`MAX_HOMEWORK_ASSIGNED`
101+/// shares the 200) and its timetable is a school week, not a catalogue.
102+///
103+/// Which is also why each write is refused on the *other* axis: a class created
104+/// before these numbers existed can stand above one of them, and the axis being
105+/// added to having room says nothing about the loop's length β€” that is set by
106+/// the axis it multiplies against. So the pump refuses a member while the class
107+/// holds more than `MAX_CLASS_COURSES` courses and a course while it holds more
108+/// than `MAX_CLASS_MEMBERS` students, and only shrinking the overloaded side
109+/// clears it.
110+pub const MAX_CLASS_MEMBERS: i64 = 200;
111+pub const MAX_CLASS_COURSES: i64 = 50;
112+
95 pub const MAX_SUBJECT_NAME_LEN: usize = 200;113 pub const MAX_SUBJECT_NAME_LEN: usize = 200;
96 pub const MAX_SUBJECT_DESCRIPTION_LEN: usize = 2_000;114 pub const MAX_SUBJECT_DESCRIPTION_LEN: usize = 2_000;
97 115
src/domain/board_stroke.rsmodified+84 -21
@@ -38,10 +38,34 @@ use crate::validate::validate_required;
38 const KIND_STROKE: &str = BOARD_STROKE_KINDS[0];38 const KIND_STROKE: &str = BOARD_STROKE_KINDS[0];
39 const KIND_CLEAR: &str = BOARD_STROKE_KINDS[1];39 const KIND_CLEAR: &str = BOARD_STROKE_KINDS[1];
40 40
41-/// The `THROW` the clear transaction refuses with: not the creator, or the41+/// The `THROW` the clear transaction refuses with: a blank canvas, not the
42-/// board is already closed. A decision, so it outranks a lost round.42+/// creator, or the board is already closed. A decision, so it outranks a lost
43+/// round.
43 const CLEAR_REFUSED: &str = "board_clear_refused";44 const CLEAR_REFUSED: &str = "board_clear_refused";
44 45
46+/// The public words of every refusal this module raises. `pub` because
47+/// `src/web/board_ws.rs` turns each into the machine-readable `code` its room
48+/// sends, and it matches these constants by value β€” a classifier that guessed
49+/// from a substring silently re-labelled a blank canvas as the *terminal*
50+/// `board_closed` the moment this wording changed.
51+pub const EPOCH_FULL: &str = "this board is full β€” clear it to keep drawing";
52+pub const BOARD_LOCKED: &str = "this board is locked β€” the creator has paused drawing";
53+pub const BOARD_CLOSED: &str = "this board is closed β€” it is permanently read-only";
54+pub const BOARD_MOVED: &str = "this board changed while you were drawing β€” draw it again";
55+pub const CANVAS_BLANK: &str = "there is nothing on this canvas to clear";
56+pub const NOT_THE_CREATOR: &str = "only the board's creator can clear the board";
57+
58+/// Every *conflict* refusal above β€” `NOT_THE_CREATOR` is a `Forbidden`, coded
59+/// by its variant alone. Listed so the room's classifier can be *proved* to
60+/// cover them all (src/web/board_ws.rs) rather than trusted to.
61+pub const REFUSALS: [&str; 5] = [
62+ EPOCH_FULL,
63+ BOARD_LOCKED,
64+ BOARD_CLOSED,
65+ BOARD_MOVED,
66+ CANVAS_BLANK,
67+];
68+
45 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]69 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
46 pub struct BoardStrokeId(RecordId);70 pub struct BoardStrokeId(RecordId);
47 71
@@ -165,9 +189,7 @@ impl BoardStroke {
165 cap::ClaimedTwo::Made(saved) => Ok(saved),189 cap::ClaimedTwo::Made(saved) => Ok(saved),
166 // The live canvas is full and nothing else: recoverable by a clear,190 // The live canvas is full and nothing else: recoverable by a clear,
167 // which resets this counter without losing a single mark.191 // which resets this counter without losing a single mark.
168- cap::ClaimedTwo::FullSoft => Err(AppError::Conflict(192+ cap::ClaimedTwo::FullSoft => Err(AppError::Conflict(EPOCH_FULL)),
169- "this board is full β€” clear it to keep drawing",
170- )),
171 // Three refusals share this answer (lifetime full / guard failed /193 // Three refusals share this answer (lifetime full / guard failed /
172 // board gone), so the board is re-read to tell them apart. A board194 // board gone), so the board is re-read to tell them apart. A board
173 // that changed state in between still gets told "no" β€” but only a195 // that changed state in between still gets told "no" β€” but only a
@@ -180,9 +202,7 @@ impl BoardStroke {
180 async fn why_refused(board: &BoardId, db: &Database) -> Result<AppError, AppError> {202 async fn why_refused(board: &BoardId, db: &Database) -> Result<AppError, AppError> {
181 let board = Board::read(board, db).await?.ok_or(AppError::NotFound)?;203 let board = Board::read(board, db).await?.ok_or(AppError::NotFound)?;
182 if board.is_locked() {204 if board.is_locked() {
183- return Ok(AppError::Conflict(205+ return Ok(AppError::Conflict(BOARD_LOCKED));
184- "this board is locked β€” the creator has paused drawing",
185- ));
186 }206 }
187 if board.get_closed_at().is_none() {207 if board.get_closed_at().is_none() {
188 // Not closed yet. The lifetime counter has to say so *itself*:208 // Not closed yet. The lifetime counter has to say so *itself*:
@@ -191,17 +211,13 @@ impl BoardStroke {
191 // is open again now would otherwise be stamped read-only at one211 // is open again now would otherwise be stamped read-only at one
192 // stroke of a 50 000 budget β€” irreversibly, with no reopen.212 // stroke of a 50 000 budget β€” irreversibly, with no reopen.
193 if Self::total_strokes(board.get_id(), db).await? < MAX_BOARD_STROKES {213 if Self::total_strokes(board.get_id(), db).await? < MAX_BOARD_STROKES {
194- return Ok(AppError::Conflict(214+ return Ok(AppError::Conflict(BOARD_MOVED));
195- "this board changed while you were drawing β€” draw it again",
196- ));
197 }215 }
198 // `Board::close` is the one-way idempotent stamp: a second append216 // `Board::close` is the one-way idempotent stamp: a second append
199 // takes this branch too and leaves the first `closed_at` standing.217 // takes this branch too and leaves the first `closed_at` standing.
200 board.close(db).await?;218 board.close(db).await?;
201 }219 }
202- Ok(AppError::Conflict(220+ Ok(AppError::Conflict(BOARD_CLOSED))
203- "this board is closed β€” it is permanently read-only",
204- ))
205 }221 }
206 222
207 /// The lifetime counter as the store holds it β€” the board struct223 /// The lifetime counter as the store holds it β€” the board struct
@@ -223,6 +239,26 @@ impl BoardStroke {
223 /// the epoch's final count β€” written apart, a crash between them would239 /// the epoch's final count β€” written apart, a crash between them would
224 /// leave an epoch no marker indexes, and the playback would silently join240 /// leave an epoch no marker indexes, and the playback would silently join
225 /// two sessions into one.241 /// two sessions into one.
242+ ///
243+ /// **The marker pays the lifetime counter.** It is a real `board_stroke`
244+ /// row, so a marker that claimed nothing left `total_stroke_count` counting
245+ /// strokes *drawn* rather than rows *stored*, and `MAX_BOARD_STROKES`
246+ /// stopped bounding the table. Charged here, the counter is exactly the row
247+ /// count again β€” the counter is reset and re-read in the same statement, so
248+ /// the increment cannot be split off from the marker it pays for.
249+ ///
250+ /// **A blank canvas cannot be cleared.** Without it every call minted a row
251+ /// for free, one per press of a button the creator can hold down. Requiring
252+ /// the epoch counter to be non-zero pays for each marker with at least one
253+ /// stroke it closes β€” and "there is nothing on this canvas to clear" is the
254+ /// honest answer to the call it refuses. The epochs index keeps its meaning
255+ /// too: no zero-stroke epoch can enter it.
256+ ///
257+ /// The marker's own increment is not capped: the last stroke of a board's
258+ /// budget may be closed by a marker, so a board holds at most
259+ /// `MAX_BOARD_STROKES + 1` rows. Capping it would refuse the clear that
260+ /// files the final epoch in the index, which is the one clear the history
261+ /// needs.
226 pub async fn clear(262 pub async fn clear(
227 board: &BoardId,263 board: &BoardId,
228 by: &UserId,264 by: &UserId,
@@ -233,8 +269,10 @@ impl BoardStroke {
233 // parses as `?? (0 = …)` and stores a boolean count (src/constant.rs:699).269 // parses as `?? (0 = …)` and stores a boolean count (src/constant.rs:699).
234 let sql = format!(270 let sql = format!(
235 "BEGIN TRANSACTION;271 "BEGIN TRANSACTION;
236- LET $before = (UPDATE $b SET epoch += 1, {BOARD_EPOCH_STROKE_COUNT_FIELD} = 0 \272+ LET $before = (UPDATE $b SET epoch += 1, {BOARD_EPOCH_STROKE_COUNT_FIELD} = 0, \
237- WHERE creator = $by AND closed_at = NONE RETURN BEFORE);273+ {BOARD_TOTAL_STROKE_COUNT_FIELD} = ({BOARD_TOTAL_STROKE_COUNT_FIELD} ?? 0) + 1 \
274+ WHERE creator = $by AND closed_at = NONE \
275+ AND ({BOARD_EPOCH_STROKE_COUNT_FIELD} ?? 0) > 0 RETURN BEFORE);
238 IF array::len($before) = 0 {{ THROW '{CLEAR_REFUSED}' }};276 IF array::len($before) = 0 {{ THROW '{CLEAR_REFUSED}' }};
239 CREATE $mid CONTENT {{ board: $b, author: $by, kind: $kind, \277 CREATE $mid CONTENT {{ board: $b, author: $by, kind: $kind, \
240 epoch: $before[0].epoch, \278 epoch: $before[0].epoch, \
@@ -249,15 +287,18 @@ impl BoardStroke {
249 ("kind".into(), KIND_CLEAR.into_value()),287 ("kind".into(), KIND_CLEAR.into_value()),
250 ("now".into(), Timestamp::now().as_millis().into_value()),288 ("now".into(), Timestamp::now().as_millis().into_value()),
251 ];289 ];
290+ // The epoch counter is reset here, which is a counter write like any
291+ // other, so it owes the process the same one-at-a-time discipline
292+ // (`cap::counter_lock`) β€” and unlike a lone conditional claim it is
293+ // read back in the same statement, by the marker's `count`.
294+ let _guard = cap::counter_lock().await;
252 let (mut result, mut errors) =295 let (mut result, mut errors) =
253 transaction_with_retry(db, &sql, &bound, &[CLEAR_REFUSED]).await?;296 transaction_with_retry(db, &sql, &bound, &[CLEAR_REFUSED]).await?;
254 if errors297 if errors
255 .values()298 .values()
256 .any(|error| error.to_string().contains(CLEAR_REFUSED))299 .any(|error| error.to_string().contains(CLEAR_REFUSED))
257 {300 {
258- return Err(AppError::Conflict(301+ return Err(Self::why_clear_refused(board, by, db).await?);
259- "this board cannot be cleared β€” it is closed, or you did not create it",
260- ));
261 }302 }
262 if let Some(error) = errors.drain().map(|(_, error)| error).next() {303 if let Some(error) = errors.drain().map(|(_, error)| error).next() {
263 return Err(error.into());304 return Err(error.into());
@@ -271,6 +312,26 @@ impl BoardStroke {
271 .ok_or_else(|| AppError::Internal("board clear wrote no marker".into()))312 .ok_or_else(|| AppError::Internal("board clear wrote no marker".into()))
272 }313 }
273 314
315+ /// Which of the clear guard's three conditions said no. One `WHERE` cannot
316+ /// report that itself, so the board is re-read β€” on the refusal path only,
317+ /// like [`Self::why_refused`]. The distinction is not cosmetic: a closed
318+ /// board is terminal for the room, a blank canvas is an ordinary "nothing
319+ /// to do" and a room told otherwise stops drawing for good.
320+ async fn why_clear_refused(
321+ board: &BoardId,
322+ by: &UserId,
323+ db: &Database,
324+ ) -> Result<AppError, AppError> {
325+ let board = Board::read(board, db).await?.ok_or(AppError::NotFound)?;
326+ if board.get_closed_at().is_some() {
327+ return Ok(AppError::Conflict(BOARD_CLOSED));
328+ }
329+ if !board.is_creator(by) {
330+ return Ok(AppError::Forbidden(NOT_THE_CREATOR));
331+ }
332+ Ok(AppError::Conflict(CANVAS_BLANK))
333+ }
334+
274 /// What a joining socket draws: the current epoch's marks only, in mint335 /// What a joining socket draws: the current epoch's marks only, in mint
275 /// order, one [`BOARD_REPLAY_CHUNK`] at a time.336 /// order, one [`BOARD_REPLAY_CHUNK`] at a time.
276 ///337 ///
@@ -606,13 +667,15 @@ mod tests {
606 marker.get_epoch()667 marker.get_epoch()
607 );668 );
608 }669 }
609- // And the refused stroke claimed nothing: two marks, two epochs.670+ // And the refused stroke claimed nothing: two marks and the two
671+ // markers that closed them, which is every row on the table.
610 assert_eq!(672 assert_eq!(
611 BoardStroke::total_strokes(board.get_id(), &db)673 BoardStroke::total_strokes(board.get_id(), &db)
612 .await674 .await
613 .unwrap(),675 .unwrap(),
614- 2676+ 4
615 );677 );
678+ assert_eq!(stored.len(), 4);
616 }679 }
617 680
618 /// The `next_ulid` hazard: rows minted inside one millisecond must replay681 /// The `next_ulid` hazard: rows minted inside one millisecond must replay
src/domain/cap.rsmodified+257 -28
@@ -58,6 +58,17 @@ static CLAIM_LOCK: Mutex<()> = Mutex::const_new(());
58 /// instead of [`write`]'s β€” [`crate::domain::field_update::FieldUpdate`]'s term58 /// instead of [`write`]'s β€” [`crate::domain::field_update::FieldUpdate`]'s term
59 /// move claims and releases inside the very `UPDATE`'s transaction, and still59 /// move claims and releases inside the very `UPDATE`'s transaction, and still
60 /// owes the process one counter write at a time.60 /// owes the process one counter write at a time.
61+///
62+/// **Is it load-bearing?** For the caps themselves, no β€” every one of them is a
63+/// single conditional write the store decides, and it decides it the same way
64+/// with a dozen writers in flight. So a counter write that skips this lock is
65+/// not a hole in a cap, and "every other site takes it" is not a correctness
66+/// argument. What the lock *is* load-bearing for is (a) the test suite, whose
67+/// in-memory engine forges wins under concurrency, and (b) any guard built out
68+/// of **two** statements that must not interleave with a rival's pair β€”
69+/// [`retire_name`] is exactly that, and it is why a skipped lock there would be
70+/// a real bug while a skipped lock around a lone `UPDATE … WHERE` is only
71+/// contention.
61 pub(crate) async fn counter_lock() -> tokio::sync::MutexGuard<'static, ()> {72 pub(crate) async fn counter_lock() -> tokio::sync::MutexGuard<'static, ()> {
62 CLAIM_LOCK.lock().await73 CLAIM_LOCK.lock().await
63 }74 }
@@ -149,7 +160,33 @@ pub(crate) async fn claim_and_create<T: SurrealValue + Clone>(
149 content: &T,160 content: &T,
150 db: &Database,161 db: &Database,
151 ) -> Result<Claimed<T>, AppError> {162 ) -> Result<Claimed<T>, AppError> {
152- claim_at_and_create(parent, field, cap, "", id, content, db).await163+ claim_at_and_create(parent, field, "$num", cap, "", id, content, db).await
164+}
165+
166+/// [`claim_and_create`] against a cap the *statement* reads rather than one the
167+/// caller snapshotted: `cap_expr` is SQL evaluated on the parent row at write
168+/// time (`audience.capacity ?? $num`, a subquery onto the settings singleton),
169+/// and `fallback` is the `$num` it coalesces to when the column is unset.
170+///
171+/// A snapshotted cap is only ever a claim about the past. Bound as an integer,
172+/// a `PATCH` that *lowers* the cap while N requests are in flight admits all N
173+/// anyway β€” each one is measured against the number its own read saw, and the
174+/// single-record guard that makes concurrent claimers safe against each other
175+/// says nothing about the writer of the cap itself. Read inside the same
176+/// conditional write, the lowered cap refuses the very next claimer, because
177+/// the write that lowered it and the write that reads it contend on one record.
178+///
179+/// `cap_expr` is always an in-crate SQL literal, never text from a client.
180+pub(crate) async fn claim_live_and_create<T: SurrealValue + Clone>(
181+ parent: &RecordId,
182+ field: &str,
183+ cap_expr: &str,
184+ fallback: i64,
185+ id: &RecordId,
186+ content: &T,
187+ db: &Database,
188+) -> Result<Claimed<T>, AppError> {
189+ claim_at_and_create(parent, field, cap_expr, fallback, "", id, content, db).await
153 }190 }
154 191
155 /// [`claim_and_create`], but only while `guard` β€” an extra predicate on that192 /// [`claim_and_create`], but only while `guard` β€” an extra predicate on that
@@ -175,12 +212,14 @@ pub(crate) async fn claim_when_and_create<T: SurrealValue + Clone>(
175 content: &T,212 content: &T,
176 db: &Database,213 db: &Database,
177 ) -> Result<Claimed<T>, AppError> {214 ) -> Result<Claimed<T>, AppError> {
178- claim_at_and_create(parent, field, cap, guard, id, content, db).await215+ claim_at_and_create(parent, field, "$num", cap, guard, id, content, db).await
179 }216 }
180 217
218+#[allow(clippy::too_many_arguments)]
181 async fn claim_at_and_create<T: SurrealValue + Clone>(219 async fn claim_at_and_create<T: SurrealValue + Clone>(
182 parent: &RecordId,220 parent: &RecordId,
183 field: &str,221 field: &str,
222+ cap_expr: &str,
184 cap: i64,223 cap: i64,
185 extra: &str,224 extra: &str,
186 id: &RecordId,225 id: &RecordId,
@@ -197,7 +236,7 @@ async fn claim_at_and_create<T: SurrealValue + Clone>(
197 LET $held = (SELECT VALUE id FROM $id);236 LET $held = (SELECT VALUE id FROM $id);
198 IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }};237 IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }};
199 LET $seat = (UPDATE $parent SET {field} = ({field} ?? 0) + 1 \238 LET $seat = (UPDATE $parent SET {field} = ({field} ?? 0) + 1 \
200- WHERE ({field} ?? 0) < $num{extra} RETURN VALUE id);239+ WHERE ({field} ?? 0) < ({cap_expr}){extra} RETURN VALUE id);
201 IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }};240 IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }};
202 CREATE $id CONTENT $row;241 CREATE $id CONTENT $row;
203 COMMIT TRANSACTION;"242 COMMIT TRANSACTION;"
@@ -390,17 +429,6 @@ pub(crate) async fn claim_two_when_and_create<T: SurrealValue + Clone>(
390 .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into())))429 .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into())))
391 }430 }
392 431
393-/// Move `parent` to its next revision. A revision column is not a cap: it is
394-/// what a reader pins a value it took off the parent to, so that a write which
395-/// invalidates that value (a menu's price) can refuse the claim carrying the old
396-/// one. Every such mutation bumps *before* it writes, so a stale claim is
397-/// refused whether or not the mutation itself then lands.
398-pub(crate) async fn bump(parent: &RecordId, field: &str, db: &Database) -> Result<(), AppError> {
399- let sql = format!("UPDATE $parent SET {field} = ({field} ?? 0) + 1 RETURN VALUE id");
400- write(&sql, parent, UNLIMITED, db).await?;
401- Ok(())
402-}
403-
404 // --- reference counters --------------------------------------------------432 // --- reference counters --------------------------------------------------
405 //433 //
406 // The same single-record guard, pointed the other way. A cap asks "is there434 // The same single-record guard, pointed the other way. A cap asks "is there
@@ -520,25 +548,104 @@ pub(crate) async fn claim_ref_and_create<T: SurrealValue + Clone>(
520 .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into())))548 .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into())))
521 }549 }
522 550
523-/// Retire the name behind `id`: no further claim succeeds. `false` = something551+/// What a retire / un-retire write did to the name's bit.
524-/// still references it and the caller must refuse; nothing was written.552+///
525-/// Idempotent β€” retiring an already-retired unused name lands again.553+/// The distinction a rollback lives on. Both writes are idempotent, so "it
526-pub(crate) async fn retire(id: &RecordId, db: &Database) -> Result<bool, AppError> {554+/// ended up retired" says nothing about *who* retired it: a caller that undoes
555+/// a no-op undoes whoever really did flip the bit β€” two settings PATCHes each
556+/// dropping the same exam kind, one of them losing the row's compare-and-set,
557+/// left the kind gone from the list with its counter reading "in service",
558+/// which is a kind that grades again and can then never be removed.
559+pub(crate) enum Switched {
560+ /// This call flipped the bit; a rollback owes the opposite write.
561+ Flipped,
562+ /// The bit already stood that way β€” this call wrote nothing, so there is
563+ /// nothing to take back, and taking it back would undo somebody else.
564+ Unchanged,
565+ /// Retirement only: something still references the name and the caller must
566+ /// refuse. Nothing was written.
567+ InUse,
568+}
569+
570+/// Retire the name behind `id`: no further claim succeeds. Idempotent β€” a
571+/// retirement of an already-retired unused name lands again, and says so
572+/// ([`Switched::Unchanged`]) so the caller does not roll back a bit it never
573+/// set.
574+pub(crate) async fn retire_name(id: &RecordId, db: &Database) -> Result<Switched, AppError> {
527 // Parenthesized `??`: `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which575 // Parenthesized `??`: `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which
528 // is truthy for *every* row and would retire a name still in use.576 // is truthy for *every* row and would retire a name still in use.
577+ //
578+ // The bit as it stood is read in the *same round trip* as the write, so the
579+ // pair is one hold of `CLAIM_LOCK` (see [`switch`]) and no rival in this
580+ // process can retire the name between them and be undone by this caller.
529 let sql = format!(581 let sql = format!(
530- "UPSERT $parent SET {REF_RETIRED_FIELD} = true \582+ "SELECT VALUE ({REF_RETIRED_FIELD} ?? false) FROM $parent;
531- WHERE ({REF_COUNT_FIELD} ?? 0) = 0 RETURN VALUE id"583+ UPSERT $parent SET {REF_RETIRED_FIELD} = true \
584+ WHERE ({REF_COUNT_FIELD} ?? 0) = 0 RETURN VALUE id"
532 );585 );
533- Ok(!write(&sql, id, UNLIMITED, db).await?.is_empty())586+ let (was, landed) = switch(&sql, id, db).await?;
587+ Ok(match (landed, was) {
588+ (false, _) => Switched::InUse,
589+ (true, true) => Switched::Unchanged,
590+ (true, false) => Switched::Flipped,
591+ })
534 }592 }
535 593
536 /// Put a name back in service β€” it re-entered the list it was retired from, or594 /// Put a name back in service β€” it re-entered the list it was retired from, or
537-/// the edit that retired it never landed.595+/// the edit that retired it never landed. [`Switched::Flipped`] only when the
538-pub(crate) async fn unretire(id: &RecordId, db: &Database) -> Result<(), AppError> {596+/// name really was retired, for [`retire_name`]'s reason pointed the other way.
539- let sql = format!("UPSERT $parent SET {REF_RETIRED_FIELD} = false RETURN VALUE id");597+pub(crate) async fn unretire_name(id: &RecordId, db: &Database) -> Result<Switched, AppError> {
540- write(&sql, id, UNLIMITED, db).await?;598+ let sql = format!(
541- Ok(())599+ "SELECT VALUE ({REF_RETIRED_FIELD} ?? false) FROM $parent;
600+ UPSERT $parent SET {REF_RETIRED_FIELD} = false RETURN VALUE id"
601+ );
602+ let (was, _) = switch(&sql, id, db).await?;
603+ Ok(if was {
604+ Switched::Flipped
605+ } else {
606+ Switched::Unchanged
607+ })
608+}
609+
610+/// [`retire_name`] as the yes/no the domain probes ask β€” did the name end up
611+/// retired? **Test-only**: production callers roll their edit back and need to
612+/// know which of the two "yes" answers they got.
613+#[cfg(test)]
614+pub(crate) async fn retire(id: &RecordId, db: &Database) -> Result<bool, AppError> {
615+ Ok(!matches!(retire_name(id, db).await?, Switched::InUse))
616+}
617+
618+/// The read of the `retired` bit and the write that moves it, one round trip
619+/// under one [`CLAIM_LOCK`] hold: `(bit as it stood, did the write match)`.
620+async fn switch(sql: &str, parent: &RecordId, db: &Database) -> Result<(bool, bool), AppError> {
621+ let _guard = CLAIM_LOCK.lock().await;
622+ let mut last = None;
623+ for attempt in 0..CAP_WRITE_TRIES {
624+ backoff(attempt).await;
625+ let attempted = async {
626+ let mut result = db
627+ .query(sql)
628+ .bind(("parent", parent.clone()))
629+ .await?
630+ .check()?;
631+ let was = result
632+ .take::<Vec<bool>>(0)?
633+ .first()
634+ .copied()
635+ .unwrap_or(false);
636+ let landed = !result.take::<Vec<RecordId>>(1)?.is_empty();
637+ Ok::<_, surrealdb::Error>((was, landed))
638+ }
639+ .await;
640+ match attempted {
641+ Ok(answer) => return Ok(answer),
642+ Err(err) if lost_the_race(&err) => last = Some(err),
643+ Err(err) => return Err(err.into()),
644+ }
645+ }
646+ Err(last
647+ .map(AppError::from)
648+ .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into())))
542 }649 }
543 650
544 /// Run one conditional counter write, retrying while the store reports a write651 /// Run one conditional counter write, retrying while the store reports a write
@@ -550,8 +657,11 @@ pub(crate) async fn unretire(id: &RecordId, db: &Database) -> Result<(), AppErro
550 /// never letting two writers reach the database at once. So the queueing has to657 /// never letting two writers reach the database at once. So the queueing has to
551 /// happen here. Backoff is exponential with jitter, because racers arrive in658 /// happen here. Backoff is exponential with jitter, because racers arrive in
552 /// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them.659 /// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them.
553-/// `num` is the statement's one number, bound as `$num`: a cap for the claims,660+/// `num` is the statement's one number, bound as `$num` β€” the cap.
554-/// a step for the reference counters below.661+///
662+/// **Test-only**, like its one caller [`claim`]: every production counter write
663+/// now rides its child row's transaction and carries its own loop.
664+#[cfg(test)]
555 async fn write(665 async fn write(
556 sql: &str,666 sql: &str,
557 parent: &RecordId,667 parent: &RecordId,
@@ -853,6 +963,125 @@ mod tests {
853 assert_eq!(menus(&db).await, 0);963 assert_eq!(menus(&db).await, 0);
854 }964 }
855 965
966+ /// The `retired` bit as the store holds it, `None` when the row is absent.
967+ async fn bit(db: &Database) -> Option<bool> {
968+ let mut result = db
969+ .query("SELECT VALUE retired FROM slot_ref:lunch")
970+ .await
971+ .unwrap()
972+ .check()
973+ .unwrap();
974+ result.take::<Vec<bool>>(0).unwrap().first().copied()
975+ }
976+
977+ fn lunch() -> RecordId {
978+ RecordId::new(crate::constant::SLOT_REF_TABLE, "lunch")
979+ }
980+
981+ /// Retirement is idempotent, so "it is retired now" is *not* "I retired
982+ /// it" β€” and a caller that rolls back on the second answer un-retires a
983+ /// name somebody else legitimately took out of service. That is the whole
984+ /// settings-CAS wedge: the list drops the name, the counter says in
985+ /// service, the name grades again and can then never be removed.
986+ #[tokio::test]
987+ async fn a_second_retirement_says_it_changed_nothing() {
988+ let db = a_slot(0, false).await;
989+ assert!(matches!(
990+ retire_name(&lunch(), &db).await.unwrap(),
991+ Switched::Flipped
992+ ));
993+ assert!(matches!(
994+ retire_name(&lunch(), &db).await.unwrap(),
995+ Switched::Unchanged
996+ ));
997+ assert_eq!(bit(&db).await, Some(true), "the winner's bit still stands");
998+ }
999+
1000+ /// The mirror: only the un-retire that really put a name back in service
1001+ /// owes a re-retirement, so a re-add that never lands cannot be undone
1002+ /// twice.
1003+ #[tokio::test]
1004+ async fn a_second_un_retirement_says_it_changed_nothing() {
1005+ let db = a_slot(0, true).await;
1006+ assert!(matches!(
1007+ unretire_name(&lunch(), &db).await.unwrap(),
1008+ Switched::Flipped
1009+ ));
1010+ assert!(matches!(
1011+ unretire_name(&lunch(), &db).await.unwrap(),
1012+ Switched::Unchanged
1013+ ));
1014+ assert_eq!(bit(&db).await, Some(false));
1015+ }
1016+
1017+ /// A referenced name is refused, and the refusal writes nothing β€” the
1018+ /// caller must not record an undo for it either.
1019+ #[tokio::test]
1020+ async fn a_referenced_name_refuses_and_leaves_the_bit_alone() {
1021+ let db = a_slot(1, false).await;
1022+ assert!(matches!(
1023+ retire_name(&lunch(), &db).await.unwrap(),
1024+ Switched::InUse
1025+ ));
1026+ assert_eq!(bit(&db).await, Some(false));
1027+ }
1028+
1029+ // --- claim_live_and_create ------------------------------------------
1030+
1031+ /// The cap the statement reads and the cap the caller remembers are
1032+ /// different numbers the moment anyone edits the cap. `epoch` stands in for
1033+ /// a capacity column here β€” any int on the parent row does.
1034+ #[tokio::test]
1035+ async fn a_live_cap_refuses_where_the_caller_s_snapshot_admits() {
1036+ let db = a_board(1, 0, false).await;
1037+ db.query("UPDATE board:b SET epoch = 1")
1038+ .await
1039+ .unwrap()
1040+ .check()
1041+ .unwrap();
1042+
1043+ // Live: one seat, one taken β€” full, and nothing written.
1044+ let live = claim_live_and_create(
1045+ &RecordId::new("board", "b"),
1046+ BOARD_EPOCH_STROKE_COUNT_FIELD,
1047+ "epoch ?? $num",
1048+ UNLIMITED,
1049+ &RecordId::new("board_stroke", "s1"),
1050+ &a_stroke(),
1051+ &db,
1052+ )
1053+ .await
1054+ .unwrap();
1055+ assert!(matches!(live, Claimed::Full));
1056+ assert_eq!(stored(&db).await, (1, 0));
1057+ assert_eq!(strokes(&db).await, 0);
1058+
1059+ // The same row, the same instant, against a cap of 5 the caller read
1060+ // before it was lowered: admitted. That gap is the over-admission.
1061+ assert!(matches!(claim_one(&db, 5, "s2").await, Claimed::Made(_)));
1062+ assert_eq!(stored(&db).await, (2, 0));
1063+ }
1064+
1065+ /// An unset capacity column means "no cap", which is the bound `$num`
1066+ /// fallback β€” not a cap of zero that refuses everything.
1067+ #[tokio::test]
1068+ async fn an_absent_live_cap_falls_back_to_the_bound_number() {
1069+ let db = a_board(0, 0, false).await;
1070+ let made = claim_live_and_create(
1071+ &RecordId::new("board", "b"),
1072+ BOARD_EPOCH_STROKE_COUNT_FIELD,
1073+ "capacity ?? $num",
1074+ UNLIMITED,
1075+ &RecordId::new("board_stroke", "s1"),
1076+ &a_stroke(),
1077+ &db,
1078+ )
1079+ .await
1080+ .unwrap();
1081+ assert!(matches!(made, Claimed::Made(_)));
1082+ assert_eq!(stored(&db).await, (1, 0));
1083+ }
1084+
856 #[tokio::test]1085 #[tokio::test]
857 async fn a_duplicate_row_claims_no_reference() {1086 async fn a_duplicate_row_claims_no_reference() {
858 let db = a_slot(0, false).await;1087 let db = a_slot(0, false).await;
src/domain/chatbot_thread.rsmodified+20 -9
@@ -7,12 +7,12 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
7 use ulid::Ulid;7 use ulid::Ulid;
8 8
9 use crate::constant::{9 use crate::constant::{
10- CHATBOT_THREAD_COUNT_FIELD, CHATBOT_THREAD_TABLE, MAX_CHATBOT_THREAD_TITLE_LEN,10+ CHATBOT_THREAD_COUNT_FIELD, CHATBOT_THREAD_TABLE, DEFAULT_MAX_CHATBOT_THREADS,
11+ MAX_CHATBOT_THREAD_TITLE_LEN, SETTINGS_KEY, SETTINGS_TABLE,
11 };12 };
12 use crate::database::Database;13 use crate::database::Database;
13 use crate::domain::cap;14 use crate::domain::cap;
14 use crate::domain::page::PagedList;15 use crate::domain::page::PagedList;
15-use crate::domain::settings::Settings;
16 use crate::domain::timestamp::Timestamp;16 use crate::domain::timestamp::Timestamp;
17 use crate::domain::user::UserId;17 use crate::domain::user::UserId;
18 use crate::error::{AppError, ValidationError};18 use crate::error::{AppError, ValidationError};
@@ -90,16 +90,24 @@ impl ChatbotThread {
90 90
91 /// Start a thread unless `user` is already at the school's91 /// Start a thread unless `user` is already at the school's
92 /// `max_chatbot_threads`. The slot is taken on the user row in the same92 /// `max_chatbot_threads`. The slot is taken on the user row in the same
93- /// transaction as the thread ([`cap::claim_and_create`]) β€” an atomic93+ /// transaction as the thread ([`cap::claim_live_and_create`]) β€” an atomic
94 /// single-record write, so two requests racing the same user's last slot94 /// single-record write, so two requests racing the same user's last slot
95- /// cannot both win, the counter can never count a row that did not commit,95+ /// cannot both win and the counter can never count a row that did not
96- /// and the cap is read fresh so a concurrent settings PATCH is respected.96+ /// commit.
97+ ///
98+ /// The cap is the one *live* on the settings singleton, sub-queried inside
99+ /// that same conditional write rather than bound as a number: this cap does
100+ /// not live on the parent row (the seat is on the user, the limit is the
101+ /// school's), and a snapshot of it admits every request already in flight
102+ /// when a `PATCH /settings` lowers it. The subquery costs one extra record
103+ /// read per claim on a path that already reads the row it writes.
104+ /// `DEFAULT_MAX_CHATBOT_THREADS` is the fallback the settings row's own
105+ /// absent column means β€” no row, or a school that never set the knob.
97 pub async fn create_capped(106 pub async fn create_capped(
98 user: &UserId,107 user: &UserId,
99 title: Option<ChatbotThreadTitle>,108 title: Option<ChatbotThreadTitle>,
100 db: &Database,109 db: &Database,
101 ) -> Result<ChatbotThread, AppError> {110 ) -> Result<ChatbotThread, AppError> {
102- let limit = Settings::load(db).await?.get_max_chatbot_threads();
103 let now = Timestamp::now();111 let now = Timestamp::now();
104 let thread = ChatbotThread {112 let thread = ChatbotThread {
105 id: ChatbotThreadId::generate(),113 id: ChatbotThreadId::generate(),
@@ -108,10 +116,13 @@ impl ChatbotThread {
108 created_at: now,116 created_at: now,
109 updated_at: now,117 updated_at: now,
110 };118 };
111- match cap::claim_and_create(119+ match cap::claim_live_and_create(
112 &user.record(),120 &user.record(),
113 CHATBOT_THREAD_COUNT_FIELD,121 CHATBOT_THREAD_COUNT_FIELD,
114- limit,122+ &format!(
123+ "(SELECT VALUE max_chatbot_threads FROM ONLY {SETTINGS_TABLE}:{SETTINGS_KEY}) ?? $num"
124+ ),
125+ DEFAULT_MAX_CHATBOT_THREADS,
115 &thread.id.record(),126 &thread.id.record(),
116 &thread,127 &thread,
117 db,128 db,
@@ -237,7 +248,7 @@ impl ChatbotThread {
237 #[cfg(test)]248 #[cfg(test)]
238 mod tests {249 mod tests {
239 use super::*;250 use super::*;
240- use crate::domain::settings::SettingsParams;251+ use crate::domain::settings::{Settings, SettingsParams};
241 252
242 /// The owner's counter and the threads it counts, both re-read out of the253 /// The owner's counter and the threads it counts, both re-read out of the
243 /// store β€” never off a return value, which the in-memory engine forges254 /// store β€” never off a return value, which the in-memory engine forges
src/domain/class_course.rsmodified+29 -5
@@ -6,12 +6,13 @@
6 6
7 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};7 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
8 8
9-use crate::constant::CLASS_COURSE_TABLE;9+use crate::constant::{CLASS_COURSE_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
10 use crate::database::Database;10 use crate::database::Database;
11 use crate::domain::class_group::ClassGroupId;11 use crate::domain::class_group::ClassGroupId;
12-use crate::domain::class_pump::{Attached, Axis, Sweep, attach, detach, link_id};12+use crate::domain::class_pump::{Attached, Axis, attach, detach, link_id};
13 use crate::domain::course::CourseId;13 use crate::domain::course::CourseId;
14 use crate::domain::page::PagedList;14 use crate::domain::page::PagedList;
15+use crate::domain::timestamp::Timestamp;
15 use crate::domain::user::UserId;16 use crate::domain::user::UserId;
16 use crate::error::AppError;17 use crate::error::AppError;
17 18
@@ -43,6 +44,11 @@ pub struct ClassCourse {
43 class: ClassGroupId,44 class: ClassGroupId,
44 course: CourseId,45 course: CourseId,
45 attached_by: UserId,46 attached_by: UserId,
47+ /// When it was attached, and the *only* thing "newest first" can mean here:
48+ /// the row's id is the (class, course) pair, so ordering by it sorts the
49+ /// list by the course's own ULID. Optional because rows written before this
50+ /// column carry no stamp β€” see the migration note.
51+ attached_at: Option<Timestamp>,
46 }52 }
47 53
48 impl ClassCourse {54 impl ClassCourse {
@@ -79,6 +85,7 @@ impl ClassCourse {
79 class: class.clone(),85 class: class.clone(),
80 course: course.clone(),86 course: course.clone(),
81 attached_by: attached_by.clone(),87 attached_by: attached_by.clone(),
88+ attached_at: Some(Timestamp::now()),
82 };89 };
83 match attach(90 match attach(
84 class,91 class,
@@ -94,9 +101,24 @@ impl ClassCourse {
94 Attached::Made(saved) => Ok(saved),101 Attached::Made(saved) => Ok(saved),
95 Attached::Duplicate => Err(AppError::Conflict("the course is already on this class")),102 Attached::Duplicate => Err(AppError::Conflict("the course is already on this class")),
96 Attached::Gone => Err(AppError::NotFound),103 Attached::Gone => Err(AppError::NotFound),
104+ Attached::ClassFull => Err(AppError::ConflictOwned(format!(
105+ "this class already holds {MAX_CLASS_COURSES} courses"
106+ ))),
107+ // The other axis: attaching one course enrolls the whole roster, so
108+ // a class over *that* ceiling cannot take a course however few it
109+ // carries. Only a class predating the ceiling can be here.
110+ Attached::ClassOverloaded => Err(AppError::ConflictOwned(format!(
111+ "this class holds more than {MAX_CLASS_MEMBERS} students β€” \
112+ remove some before attaching a course"
113+ ))),
97 Attached::Full(full) => Err(AppError::ConflictOwned(format!(114 Attached::Full(full) => Err(AppError::ConflictOwned(format!(
98 "{full} cannot hold the whole class"115 "{full} cannot hold the whole class"
99 ))),116 ))),
117+ // Another of the class's links points at a deleted course. This
118+ // axis claims its own pivot, so it is never *this* course.
119+ Attached::CourseGone(course) => Err(AppError::ConflictOwned(format!(
120+ "{course} no longer exists β€” detach it from this class first"
121+ ))),
100 }122 }
101 }123 }
102 124
@@ -114,7 +136,6 @@ impl ClassCourse {
114 let gone = detach(136 let gone = detach(
115 "$link",137 "$link",
116 Axis::Course,138 Axis::Course,
117- Sweep::Rows,
118 &[(139 &[(
119 "link".into(),140 "link".into(),
120 ClassCourseId::composite(class, course)141 ClassCourseId::composite(class, course)
@@ -127,7 +148,10 @@ impl ClassCourse {
127 (gone > 0).then_some(()).ok_or(AppError::NotFound)148 (gone > 0).then_some(()).ok_or(AppError::NotFound)
128 }149 }
129 150
130- /// The courses a class is attached to, newest first.151+ /// The courses a class is attached to, newest first β€” by when they were
152+ /// attached, not by the course's own id, which is what the composite record
153+ /// id sorts on. A row older than the column carries no stamp at all, and
154+ /// NONE sorts last under DESC β€” the honest place for a row of unknown age.
131 pub async fn list_for_class(155 pub async fn list_for_class(
132 class: &ClassGroupId,156 class: &ClassGroupId,
133 limit: Option<i64>,157 limit: Option<i64>,
@@ -136,7 +160,7 @@ impl ClassCourse {
136 ) -> Result<(Vec<ClassCourse>, i64), AppError> {160 ) -> Result<(Vec<ClassCourse>, i64), AppError> {
137 PagedList::new(161 PagedList::new(
138 format!("{CLASS_COURSE_TABLE} WHERE class = $class"),162 format!("{CLASS_COURSE_TABLE} WHERE class = $class"),
139- "ORDER BY id DESC",163+ "ORDER BY attached_at DESC, id DESC",
140 )164 )
141 .bind("class", class.record())165 .bind("class", class.record())
142 .run(limit, offset, db)166 .run(limit, offset, db)
src/domain/class_member.rsmodified+55 -35
@@ -7,11 +7,12 @@
7 7
8 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};8 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
9 9
10-use crate::constant::CLASS_MEMBER_TABLE;10+use crate::constant::{CLASS_MEMBER_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
11 use crate::database::Database;11 use crate::database::Database;
12 use crate::domain::class_group::ClassGroupId;12 use crate::domain::class_group::ClassGroupId;
13-use crate::domain::class_pump::{Attached, Axis, Sweep, attach, detach, link_id};13+use crate::domain::class_pump::{Attached, Axis, attach, detach, link_id};
14 use crate::domain::page::PagedList;14 use crate::domain::page::PagedList;
15+use crate::domain::timestamp::Timestamp;
15 use crate::domain::user::UserId;16 use crate::domain::user::UserId;
16 use crate::error::AppError;17 use crate::error::AppError;
17 18
@@ -43,6 +44,11 @@ pub struct ClassMember {
43 class: ClassGroupId,44 class: ClassGroupId,
44 user: UserId,45 user: UserId,
45 added_by: UserId,46 added_by: UserId,
47+ /// When they were added, and the *only* thing "newest first" can mean here:
48+ /// the row's id is the (class, user) pair, so ordering by it sorts the
49+ /// roster by the student's account ULID. Optional because rows written
50+ /// before this column carry no stamp β€” see the migration note.
51+ added_at: Option<Timestamp>,
46 }52 }
47 53
48 impl ClassMember {54 impl ClassMember {
@@ -80,6 +86,7 @@ impl ClassMember {
80 class: class.clone(),86 class: class.clone(),
81 user: user.clone(),87 user: user.clone(),
82 added_by: added_by.clone(),88 added_by: added_by.clone(),
89+ added_at: Some(Timestamp::now()),
83 };90 };
84 match attach(91 match attach(
85 class,92 class,
@@ -95,9 +102,25 @@ impl ClassMember {
95 Attached::Made(saved) => Ok(saved),102 Attached::Made(saved) => Ok(saved),
96 Attached::Duplicate => Err(AppError::Conflict("the student is already in this class")),103 Attached::Duplicate => Err(AppError::Conflict("the student is already in this class")),
97 Attached::Gone => Err(AppError::NotFound),104 Attached::Gone => Err(AppError::NotFound),
105+ Attached::ClassFull => Err(AppError::ConflictOwned(format!(
106+ "this class already holds {MAX_CLASS_MEMBERS} students"
107+ ))),
108+ // The other axis: adding one student enrolls them into every
109+ // attached course, so a class over *that* ceiling cannot take a
110+ // member however much room its roster has.
111+ Attached::ClassOverloaded => Err(AppError::ConflictOwned(format!(
112+ "this class holds more than {MAX_CLASS_COURSES} courses β€” \
113+ detach some before adding a student"
114+ ))),
98 Attached::Full(course) => Err(AppError::ConflictOwned(format!(115 Attached::Full(course) => Err(AppError::ConflictOwned(format!(
99 "{course} is full, so the class cannot take this student"116 "{course} is full, so the class cannot take this student"
100 ))),117 ))),
118+ // Not a capacity problem, and told apart from one on purpose: no
119+ // number anyone can raise unblocks this class, only detaching the
120+ // link the deleted course left behind.
121+ Attached::CourseGone(course) => Err(AppError::ConflictOwned(format!(
122+ "{course} no longer exists β€” detach it from this class first"
123+ ))),
101 }124 }
102 }125 }
103 126
@@ -116,7 +139,6 @@ impl ClassMember {
116 let gone = detach(139 let gone = detach(
117 "$link",140 "$link",
118 Axis::Member,141 Axis::Member,
119- Sweep::Rows,
120 &[(142 &[(
121 "link".into(),143 "link".into(),
122 ClassMemberId::composite(class, user).record().into_value(),144 ClassMemberId::composite(class, user).record().into_value(),
@@ -127,23 +149,10 @@ impl ClassMember {
127 (gone > 0).then_some(()).ok_or(AppError::NotFound)149 (gone > 0).then_some(()).ok_or(AppError::NotFound)
128 }150 }
129 151
130- /// Drop every class `user` belongs to, giving each class its member count152+ /// The class's roster, newest first β€” by when the student was added, not by
131- /// back β€” and nothing else. The enrollments are153+ /// their account id, which is what the composite record id sorts on.
132- /// [`crate::domain::enrollment::Enrollment::delete_for_user`]'s to delete;154+ /// A row older than the column carries no stamp at all, and NONE sorts last
133- /// this sweeping them too would decrement the same seats twice.155+ /// under DESC β€” which is the honest place for a row of unknown age.
134- pub async fn delete_for_user(user: &UserId, db: &Database) -> Result<(), AppError> {
135- detach(
136- &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),
137- Axis::Member,
138- Sweep::CounterOnly,
139- &[("usr".into(), user.record().into_value())],
140- db,
141- )
142- .await?;
143- Ok(())
144- }
145-
146- /// The class's roster, newest first.
147 pub async fn list_for_class(156 pub async fn list_for_class(
148 class: &ClassGroupId,157 class: &ClassGroupId,
149 limit: Option<i64>,158 limit: Option<i64>,
@@ -152,7 +161,7 @@ impl ClassMember {
152 ) -> Result<(Vec<ClassMember>, i64), AppError> {161 ) -> Result<(Vec<ClassMember>, i64), AppError> {
153 PagedList::new(162 PagedList::new(
154 format!("{CLASS_MEMBER_TABLE} WHERE class = $class"),163 format!("{CLASS_MEMBER_TABLE} WHERE class = $class"),
155- "ORDER BY id DESC",164+ "ORDER BY added_at DESC, id DESC",
156 )165 )
157 .bind("class", class.record())166 .bind("class", class.record())
158 .run(limit, offset, db)167 .run(limit, offset, db)
@@ -476,11 +485,12 @@ pub(crate) mod tests {
476 assert_eq!(counter("class_member_count", class.record(), &db).await, 0);485 assert_eq!(counter("class_member_count", class.record(), &db).await, 0);
477 }486 }
478 487
479- /// The role-demotion sweep: memberships go and their counters come back,488+ /// The role-change sweep, which is now one transaction over both tables:
480- /// while the enrollment rows are left for `Enrollment::delete_for_user`.489+ /// the memberships go with their counters, the enrollment rows go with
481- /// Decrementing those seats here as well would take each one back twice.490+ /// their seats, and each seat comes back exactly once β€” the double
491+ /// decrement the old two-call split existed to avoid.
482 #[tokio::test]492 #[tokio::test]
483- async fn delete_for_user_leaves_the_enrollments_alone() {493+ async fn the_role_sweep_takes_memberships_and_enrollments_together() {
484 let db = crate::database::init_mem().await.unwrap();494 let db = crate::database::init_mem().await.unwrap();
485 let manager = UserId::from_key("manager");495 let manager = UserId::from_key("manager");
486 let student = UserId::from_key("student");496 let student = UserId::from_key("student");
@@ -497,7 +507,9 @@ pub(crate) mod tests {
497 .await507 .await
498 .unwrap();508 .unwrap();
499 509
500- ClassMember::delete_for_user(&student, &db).await.unwrap();510+ crate::domain::class_pump::sweep_non_student(&student, &db)
511+ .await
512+ .unwrap();
501 assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);513 assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);
502 for class in [&first, &second] {514 for class in [&first, &second] {
503 assert_eq!(515 assert_eq!(
@@ -508,18 +520,26 @@ pub(crate) mod tests {
508 }520 }
509 assert_eq!(521 assert_eq!(
510 source_of(&algebra, &student, &db).await,522 source_of(&algebra, &student, &db).await,
511- Some(Some(first.clone())),523+ None,
512- "the enrollment is the other sweep's to delete"524+ "the enrollment goes in the same transaction as the membership"
513 );525 );
514 assert_eq!(526 assert_eq!(
515 counter("enrollment_count", algebra.record(), &db).await,527 counter("enrollment_count", algebra.record(), &db).await,
516- 1,528+ 0,
517- "…and its seat is the other sweep's to release"529+ "…and its seat comes back once, not twice"
530+ );
531+ // Which is the point of folding them: the class the student was in is
532+ // free of them entirely β€” no membership, no count, and no enrollment
533+ // row left tagged with a class that is about to be deletable.
534+ assert!(
535+ crate::domain::class_group::ClassGroup::read(&second, &db)
536+ .await
537+ .unwrap()
538+ .unwrap()
539+ .delete(&db)
540+ .await
541+ .unwrap(),
542+ "a class holding neither members nor courses must delete"
518 );543 );
519-
520- // Which is exactly what the demotion calls next, and the seat comes
521- // back once, not twice.
522- Enrollment::delete_for_user(&student, &db).await.unwrap();
523- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);
524 }544 }
525 }545 }
src/domain/class_pump.rsmodified+233 -47
@@ -26,22 +26,44 @@ use surrealdb::types::{RecordId, SurrealValue, Value};
26 26
27 use crate::constant::{27 use crate::constant::{
28 CLASS_COURSE_COUNT_FIELD, CLASS_COURSE_TABLE, CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE,28 CLASS_COURSE_COUNT_FIELD, CLASS_COURSE_TABLE, CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE,
29- ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE,29+ ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS,
30 };30 };
31 use crate::database::{Database, transaction_with_retry};31 use crate::database::{Database, transaction_with_retry};
32 use crate::domain::cap;32 use crate::domain::cap;
33-use crate::domain::class_group::ClassGroupId;33+use crate::domain::class_group::{ClassGroup, ClassGroupId};
34+use crate::domain::user::UserId;
34 use crate::error::AppError;35 use crate::error::AppError;
35 36
36-/// The `THROW` markers [`attach`] aborts with. `FULL_MARK` is a *prefix*: the37+/// The `THROW` markers [`attach`] aborts with. `FULL_MARK` and `MISSING_MARK`
37-/// record id of the course that had no seat is appended to it, because "the38+/// are *prefixes*: the record id of the course the loop stopped on is appended
38-/// class does not fit" is unanswerable without knowing which course to raise39+/// to them, because neither "the class does not fit" nor "that course is gone"
39-/// the capacity of, and the loop only learns that at runtime. The whole id and40+/// is answerable without naming the course, and the loop only learns which one
40-/// not just the key, so the refusal names something a caller can look up41+/// at runtime. The whole id and not just the key, so the refusal names
41-/// without knowing which table it came from.42+/// something a caller can look up without knowing which table it came from.
43+///
44+/// `MISSING_MARK` is deliberately not `FULL_MARK`: a seat claim that matches
45+/// nothing means "full" *or* "no such row", and reporting a class-course link
46+/// left pointing at a deleted course as a full course sends the caller to raise
47+/// a capacity that does not exist, on a class every member add now fails on.
48+///
49+/// `CAP_MARK` is the class counter's claim matching nothing, which is "the
50+/// class is full" *or* "the class is gone" β€” one conditional write cannot say
51+/// which, so it stays one marker and the read that tells them apart is paid for
52+/// only on that path (the same shape as
53+/// [`crate::domain::enrollment::Enrollment::enroll`]). It is not `GONE_MARK`:
54+/// that one is the *pivot* claim, which is a different row.
55+///
56+/// `OVER_MARK` is the *other* axis already standing above its own ceiling β€”
57+/// which no claim on this axis can see, and which is what bounds this
58+/// 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 when
60+/// it is reported as "this class holds too many students".
42 const HELD_MARK: &str = "class_held";61 const HELD_MARK: &str = "class_held";
43 const GONE_MARK: &str = "class_gone";62 const GONE_MARK: &str = "class_gone";
63+const CAP_MARK: &str = "class_cap";
64+const OVER_MARK: &str = "class_over";
44 const FULL_MARK: &str = "class_full:";65 const FULL_MARK: &str = "class_full:";
66+const MISSING_MARK: &str = "class_no_course:";
45 67
46 /// What [`attach`] settled.68 /// What [`attach`] settled.
47 pub(crate) enum Attached<T> {69 pub(crate) enum Attached<T> {
@@ -51,12 +73,26 @@ pub(crate) enum Attached<T> {
51 /// The link already exists β€” nothing was written, and no seat was spent73 /// The link already exists β€” nothing was written, and no seat was spent
52 /// finding that out.74 /// finding that out.
53 Duplicate,75 Duplicate,
54- /// The class row is gone (a concurrent delete won). Nothing was written.76+ /// The class row β€” or, on the course axis, the course being attached β€” is
77+ /// gone (a concurrent delete won). Nothing was written.
55 Gone,78 Gone,
79+ /// The class is at its own ceiling on this axis. Nothing was written, and
80+ /// it is told apart from [`Attached::Gone`] because a full class is a
81+ /// standing row someone can make room in, not a 404.
82+ ClassFull,
83+ /// The class stands *above* the ceiling on the other axis, so the write
84+ /// loop this attach would run is longer than any transaction is allowed to
85+ /// be. Only a class predating the ceilings can be here, and only its own
86+ /// axis can make room β€” which is why it is not [`Attached::ClassFull`].
87+ ClassOverloaded,
56 /// One of the courses had no free seat, named by its key. Nothing was88 /// One of the courses had no free seat, named by its key. Nothing was
57 /// written β€” not one of the earlier seats in the same run, which is the89 /// written β€” not one of the earlier seats in the same run, which is the
58 /// whole point of doing this in a transaction.90 /// whole point of doing this in a transaction.
59 Full(String),91 Full(String),
92+ /// One of the courses the class carries no longer exists, named by its id:
93+ /// a stale `class_course` link. Nothing was written, and no capacity anyone
94+ /// can raise will change that answer.
95+ CourseGone(String),
60 }96 }
61 97
62 /// Which way the pump runs: the loop below needs a `(course, user)` pair per98 /// Which way the pump runs: the loop below needs a `(course, user)` pair per
@@ -96,6 +132,37 @@ impl Axis {
96 }132 }
97 }133 }
98 134
135+ /// The in-transaction proof that this axis's *pivot* row is still there,
136+ /// as the statements that claim it.
137+ ///
138+ /// The class counter's conditional claim covers the class; nothing covered
139+ /// the course. With an empty roster the pair loop in [`attach`] touches no
140+ /// row at all, so a concurrent `DELETE /courses/{id}` conflicts with
141+ /// nothing β€” SurrealDB does not conflict-check that (write-skew) β€” and the
142+ /// attach commits a `class_course` row pointing at a course that no longer
143+ /// exists. A conditional write on the course row *is* the check: it matches
144+ /// nothing once the row is gone, and it puts this transaction on the very
145+ /// record the course's delete guard writes.
146+ ///
147+ /// The counter is re-stated verbatim rather than incremented: the row must
148+ /// be touched, not changed, and `count = count` leaves an absent counter
149+ /// absent, so the boot backfill still sees the `NONE` it seeds off.
150+ ///
151+ /// The member axis claims nothing: its pivot is a user, whose row is no
152+ /// class write's to touch, and a membership left pointing at a deleted user
153+ /// is still removable by its own route β€” which is exactly what a link to a
154+ /// deleted course was not.
155+ fn pivot_claim(&self) -> String {
156+ match self {
157+ Axis::Member => String::new(),
158+ Axis::Course => format!(
159+ "LET $alive = (UPDATE $pivot SET {ENROLLMENT_COUNT_FIELD} = \
160+ {ENROLLMENT_COUNT_FIELD} RETURN VALUE id);
161+ IF array::len($alive) = 0 {{ THROW '{GONE_MARK}' }};"
162+ ),
163+ }
164+ }
165+
99 /// The class counter this axis's link rows are counted on. Taken off the166 /// The class counter this axis's link rows are counted on. Taken off the
100 /// axis rather than passed in beside it, because the two are one fact and a167 /// axis rather than passed in beside it, because the two are one fact and a
101 /// call site that paired the member axis with the course counter would168 /// call site that paired the member axis with the course counter would
@@ -107,15 +174,87 @@ impl Axis {
107 Axis::Course => CLASS_COURSE_COUNT_FIELD,174 Axis::Course => CLASS_COURSE_COUNT_FIELD,
108 }175 }
109 }176 }
177+
178+ /// How many link rows this axis's counter may reach. Taken off the axis
179+ /// beside the counter it bounds, for the same reason.
180+ ///
181+ /// This is what makes the pair loop in [`attach`] finite, and it does it
182+ /// *crosswise*: the member axis's loop iterates the class's `class_course`
183+ /// rows, which the course axis's counter caps, and the course axis's loop
184+ /// iterates its `class_member` rows, which the member axis's counter caps.
185+ /// So bounding the two counters bounds both write loops β€” one transaction
186+ /// can never carry more than `MAX_CLASS_MEMBERS`/`MAX_CLASS_COURSES`
187+ /// enrollment writes.
188+ ///
189+ /// Crosswise is also why the claim alone is not enough. It bounds the axis
190+ /// being *added*, and the loop it runs is the length of the *other* one: a
191+ /// class that already holds more members than `MAX_CLASS_MEMBERS` β€” the
192+ /// layer shipped before either ceiling existed, so a real volume can carry
193+ /// one β€” could still have a course attached, and that attach writes one
194+ /// enrollment per member. So [`attach`] checks the other axis too
195+ /// ([`Axis::other`]), and the bound holds for stale classes as well.
196+ fn cap(&self) -> i64 {
197+ match self {
198+ Axis::Member => MAX_CLASS_MEMBERS,
199+ Axis::Course => MAX_CLASS_COURSES,
200+ }
201+ }
202+
203+ /// The axis whose link rows this one's write loop iterates β€” its counter is
204+ /// the length of that loop, and its ceiling is therefore the second half of
205+ /// the bound.
206+ fn other(&self) -> Axis {
207+ match self {
208+ Axis::Member => Axis::Course,
209+ Axis::Course => Axis::Member,
210+ }
211+ }
110 }212 }
111 213
112-/// Whether a [`detach`] also reconciles the enrollment rows its links pumped.214+/// Everything a user's role change *off* `student` invalidates, in one
113-pub(crate) enum Sweep {215+/// transaction: every class membership they hold (each class getting its member
114- /// Repair or delete them, per the rule in [`detach`].216+/// count back) and every enrollment row they hold (each course getting its seat
115- Rows,217+/// back).
116- /// Release the counters and touch nothing else, because something else owns218+///
117- /// the enrollment side of this same event.219+/// One transaction because the two halves are one fact. Run as two, a failure
118- CounterOnly,220+/// between them released the memberships and both class counters while the
221+/// enrollment rows kept `source = class_group:X` β€” the class then passed its
222+/// zero-zero delete guard, and the rows were left tagged with a class that no
223+/// longer existed and that no sweep could ever reach. Ordering them the other
224+/// way only swaps which corruption is reachable: memberships surviving on a
225+/// non-student are memberships the next attach pumps back into a course.
226+///
227+/// The enrollment side takes *every* row, hand-placed ones included, and that
228+/// is the rule rather than an oversight: what the role change invalidates is
229+/// not "rows a class wrote" but enrollment itself β€” only students enroll, and
230+/// enrollment is what gates sitting exams, being graded and appearing on a
231+/// roster. A row kept for a teacher would grant nothing and count a seat.
232+/// Nothing restores them on a demotion back to `student`; a promotion is a
233+/// roster decision of its own.
234+pub(crate) async fn sweep_non_student(user: &UserId, db: &Database) -> Result<(), AppError> {
235+ let sql = format!(
236+ "BEGIN TRANSACTION;
237+ LET $links = (DELETE {CLASS_MEMBER_TABLE} WHERE user = $usr RETURN BEFORE);
238+ FOR $link IN ($links ?? []) {{
239+ UPDATE $link.class SET {CLASS_MEMBER_COUNT_FIELD} = \
240+ math::max([({CLASS_MEMBER_COUNT_FIELD} ?? 0) - 1, 0]);
241+ }};
242+ LET $gone = (DELETE {ENROLLMENT_TABLE} WHERE user = $usr RETURN BEFORE);
243+ FOR $row IN ($gone ?? []) {{
244+ UPDATE $row.course SET {ENROLLMENT_COUNT_FIELD} = \
245+ math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]);
246+ }};
247+ COMMIT TRANSACTION;"
248+ );
249+ // Admissible by construction: `DELETE` and `UPDATE` only, so no statement
250+ // can answer "already exists" and every lost round is a plain re-send.
251+ let (_, mut errors) =
252+ transaction_with_retry(db, &sql, &[("usr".into(), user.record().into_value())], &[])
253+ .await?;
254+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
255+ return Err(error.into());
256+ }
257+ Ok(())
119 }258 }
120 259
121 /// Write `link` and enroll everything it implies, or write nothing at all.260 /// Write `link` and enroll everything it implies, or write nothing at all.
@@ -129,7 +268,9 @@ pub(crate) enum Sweep {
129 /// The class counter is claimed by a conditional write rather than a bare268 /// The class counter is claimed by a conditional write rather than a bare
130 /// increment, so a class deleted out from under this run matches nothing and269 /// increment, so a class deleted out from under this run matches nothing and
131 /// the whole cascade aborts: [`Attached::Gone`] instead of a counter on a row270 /// the whole cascade aborts: [`Attached::Gone`] instead of a counter on a row
132-/// that no longer exists.271+/// that no longer exists. The same write carries the axis's [`Axis::cap`],
272+/// which is what keeps the pair loop below β€” and therefore this transaction β€”
273+/// finite: [`Attached::ClassFull`] once the class is at its ceiling.
133 ///274 ///
134 /// Every enrollment in the loop is *skipped* when the pair already has a row β€”275 /// Every enrollment in the loop is *skipped* when the pair already has a row β€”
135 /// no seat charged, and the existing row's `source` left exactly as it was, so276 /// no seat charged, and the existing row's `source` left exactly as it was, so
@@ -153,18 +294,29 @@ pub(crate) async fn attach<T: SurrealValue + Clone>(
153 ) -> Result<Attached<T>, AppError> {294 ) -> Result<Attached<T>, AppError> {
154 let count_field = axis.counter();295 let count_field = axis.counter();
155 let pairs = axis.pairs();296 let pairs = axis.pairs();
297+ let alive = axis.pivot_claim();
298+ let other = axis.other();
299+ let over_field = other.counter();
300+ // Read off the class row inside the transaction that claims it, so the
301+ // count this refuses on is the one the pair loop below would iterate.
156 let sql = format!(302 let sql = format!(
157 "BEGIN TRANSACTION;303 "BEGIN TRANSACTION;
158 LET $held = (SELECT VALUE id FROM $link);304 LET $held = (SELECT VALUE id FROM $link);
159 IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }};305 IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }};
306+ {alive}
307+ LET $over = (SELECT VALUE id FROM $class WHERE ({over_field} ?? 0) > $other_cap);
308+ IF array::len($over) > 0 {{ THROW '{OVER_MARK}' }};
160 LET $counted = (UPDATE $class SET {count_field} = ({count_field} ?? 0) + 1 \309 LET $counted = (UPDATE $class SET {count_field} = ({count_field} ?? 0) + 1 \
161- WHERE ({count_field} ?? 0) < $unlimited RETURN VALUE id);310+ WHERE ({count_field} ?? 0) < $class_cap RETURN VALUE id);
162- IF array::len($counted) = 0 {{ THROW '{GONE_MARK}' }};311+ IF array::len($counted) = 0 {{ THROW '{CAP_MARK}' }};
163 CREATE $link CONTENT $row;312 CREATE $link CONTENT $row;
164 FOR $pair IN (({pairs}) ?? []) {{313 FOR $pair IN (({pairs}) ?? []) {{
165 LET $seat_of = type::record('{ENROLLMENT_TABLE}', string::concat(314 LET $seat_of = type::record('{ENROLLMENT_TABLE}', string::concat(
166 record::id($pair.course), '_', record::id($pair.user)));315 record::id($pair.course), '_', record::id($pair.user)));
167 IF array::len((SELECT VALUE id FROM $seat_of)) = 0 {{316 IF array::len((SELECT VALUE id FROM $seat_of)) = 0 {{
317+ IF array::len((SELECT VALUE id FROM $pair.course)) = 0 {{
318+ THROW '{MISSING_MARK}' + <string>$pair.course
319+ }};
168 LET $seat = (UPDATE $pair.course SET {ENROLLMENT_COUNT_FIELD} = \320 LET $seat = (UPDATE $pair.course SET {ENROLLMENT_COUNT_FIELD} = \
169 ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 \321 ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 \
170 WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) < (capacity ?? $unlimited) \322 WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) < (capacity ?? $unlimited) \
@@ -188,8 +340,17 @@ pub(crate) async fn attach<T: SurrealValue + Clone>(
188 ("pivot".into(), pivot.into_value()),340 ("pivot".into(), pivot.into_value()),
189 ("by".into(), by.into_value()),341 ("by".into(), by.into_value()),
190 ("unlimited".into(), cap::UNLIMITED.into_value()),342 ("unlimited".into(), cap::UNLIMITED.into_value()),
343+ ("class_cap".into(), axis.cap().into_value()),
344+ ("other_cap".into(), other.cap().into_value()),
345+ ],
346+ &[
347+ HELD_MARK,
348+ GONE_MARK,
349+ OVER_MARK,
350+ CAP_MARK,
351+ FULL_MARK,
352+ MISSING_MARK,
191 ],353 ],
192- &[HELD_MARK, GONE_MARK, FULL_MARK],
193 )354 )
194 .await?;355 .await?;
195 // "Already linked" is read first: it outranks both refusals below, and the356 // "Already linked" is read first: it outranks both refusals below, and the
@@ -214,30 +375,60 @@ pub(crate) async fn attach<T: SurrealValue + Clone>(
214 {375 {
215 return Ok(Attached::Gone);376 return Ok(Attached::Gone);
216 }377 }
378+ // Read before the ceiling below: a class over the *other* axis's ceiling is
379+ // refused whether or not this axis has room, and being told it is full on
380+ // an axis with places left is an answer nobody can act on.
381+ if errors
382+ .values()
383+ .any(|error| error.to_string().contains(OVER_MARK))
384+ {
385+ return Ok(Attached::ClassOverloaded);
386+ }
387+ // Full, or the class is gone β€” the counter claim matches nothing either
388+ // way, and only this path pays for the read that tells them apart.
389+ if errors
390+ .values()
391+ .any(|error| error.to_string().contains(CAP_MARK))
392+ {
393+ return Ok(match ClassGroup::read(class, db).await? {
394+ Some(_) => Attached::ClassFull,
395+ None => Attached::Gone,
396+ });
397+ }
398+ // The stale link is read before "full": both come out of the same seat
399+ // claim matching nothing, and only one of them is a capacity problem.
400+ if let Some(course) = errors
401+ .values()
402+ .find_map(|error| named_course(&error.to_string(), MISSING_MARK))
403+ {
404+ return Ok(Attached::CourseGone(course));
405+ }
217 if let Some(course) = errors406 if let Some(course) = errors
218 .values()407 .values()
219- .find_map(|error| full_course(&error.to_string()))408+ .find_map(|error| named_course(&error.to_string(), FULL_MARK))
220 {409 {
221 return Ok(Attached::Full(course));410 return Ok(Attached::Full(course));
222 }411 }
223 if let Some(error) = errors.drain().map(|(_, error)| error).next() {412 if let Some(error) = errors.drain().map(|(_, error)| error).next() {
224 return Err(error.into());413 return Err(error.into());
225 }414 }
226- // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5.415+ // Slots count BEGIN and three LET/IF pairs: the CREATE is slot 7 β€” or 9 on
416+ // an axis that claims its pivot with a LET/IF pair of its own.
417+ let made = if alive.is_empty() { 7 } else { 9 };
227 result418 result
228- .take::<Vec<T>>(5)?419+ .take::<Vec<T>>(made)?
229 .into_iter()420 .into_iter()
230 .next()421 .next()
231 .map(Attached::Made)422 .map(Attached::Made)
232 .ok_or_else(|| AppError::Internal("the class pump wrote no link row".into()))423 .ok_or_else(|| AppError::Internal("the class pump wrote no link row".into()))
233 }424 }
234 425
235-/// The course id out of a `class_full:<table>:<key>` abort. Table names and the426+/// The course id out of a `<mark><table>:<key>` abort. Table names and the
236 /// generated ULID keys here are alphanumeric and `:` joins them, so the id ends427 /// generated ULID keys here are alphanumeric and `:` joins them, so the id ends
237 /// where the store's own wrapping around the thrown text begins.428 /// where the store's own wrapping around the thrown text begins.
238-fn full_course(message: &str) -> Option<String> {429+fn named_course(message: &str, mark: &str) -> Option<String> {
239 let id: String = message430 let id: String = message
240- .split_once(FULL_MARK)?431+ .split_once(mark)?
241 .1432 .1
242 .chars()433 .chars()
243 .take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | ':'))434 .take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | ':'))
@@ -264,28 +455,19 @@ fn full_course(message: &str) -> Option<String> {
264 /// "this class has a member" and "that member has a live pumped row" are455 /// "this class has a member" and "that member has a live pumped row" are
265 /// independent facts and the loop simply finds nothing to sweep.456 /// independent facts and the loop simply finds nothing to sweep.
266 ///457 ///
267-/// [`Sweep::CounterOnly`] is the deliberate half of this: dropping a *user's*
268-/// whole membership releases the counters and nothing else, because
269-/// `Enrollment::delete_for_user` owns the enrollment side of that same event and
270-/// a second decrement of the same seat is a bug, not a belt.
271-///
272 /// Admissible by construction: `DELETE` and `UPDATE` only, so no statement in458 /// Admissible by construction: `DELETE` and `UPDATE` only, so no statement in
273 /// the cascade can answer "already exists" and every lost round is a plain459 /// the cascade can answer "already exists" and every lost round is a plain
274 /// re-send.460 /// re-send.
275 pub(crate) async fn detach(461 pub(crate) async fn detach(
276 links: &str,462 links: &str,
277 axis: Axis,463 axis: Axis,
278- sweep: Sweep,
279 bindings: &[(String, Value)],464 bindings: &[(String, Value)],
280 db: &Database,465 db: &Database,
281 ) -> Result<i64, AppError> {466 ) -> Result<i64, AppError> {
282 let count_field = axis.counter();467 let count_field = axis.counter();
283- let sweep = match sweep {468+ let scope = axis.scope();
284- Sweep::CounterOnly => String::new(),469+ let sweep = format!(
285- Sweep::Rows => {470+ "FOR $row IN ((SELECT id, course, user FROM {ENROLLMENT_TABLE} \
286- let scope = axis.scope();
287- format!(
288- "FOR $row IN ((SELECT id, course, user FROM {ENROLLMENT_TABLE} \
289 WHERE {scope} AND source = $link.class) ?? []) {{471 WHERE {scope} AND source = $link.class) ?? []) {{
290 LET $rivals = (SELECT VALUE class FROM {CLASS_COURSE_TABLE} \472 LET $rivals = (SELECT VALUE class FROM {CLASS_COURSE_TABLE} \
291 WHERE course = $row.course AND class != $link.class);473 WHERE course = $row.course AND class != $link.class);
@@ -299,9 +481,7 @@ pub(crate) async fn detach(
299 math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]);481 math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]);
300 }};482 }};
301 }};"483 }};"
302- )484+ );
303- }
304- };
305 let sql = format!(485 let sql = format!(
306 "BEGIN TRANSACTION;486 "BEGIN TRANSACTION;
307 LET $gone = (DELETE {links} RETURN BEFORE);487 LET $gone = (DELETE {links} RETURN BEFORE);
@@ -386,7 +566,6 @@ mod tests {
386 let gone = detach(566 let gone = detach(
387 &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),567 &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),
388 Axis::Member,568 Axis::Member,
389- Sweep::CounterOnly,
390 &[("usr".into(), student.record().into_value())],569 &[("usr".into(), student.record().into_value())],
391 &db,570 &db,
392 )571 )
@@ -409,7 +588,6 @@ mod tests {
409 let again = detach(588 let again = detach(
410 &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),589 &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),
411 Axis::Member,590 Axis::Member,
412- Sweep::CounterOnly,
413 &[("usr".into(), student.record().into_value())],591 &[("usr".into(), student.record().into_value())],
414 &db,592 &db,
415 )593 )
@@ -421,14 +599,22 @@ mod tests {
421 #[test]599 #[test]
422 fn a_full_abort_names_its_course() {600 fn a_full_abort_names_its_course() {
423 assert_eq!(601 assert_eq!(
424- full_course("An error occurred: class_full:course:01J8XZ0K3Q"),602+ named_course("An error occurred: class_full:course:01J8XZ0K3Q", FULL_MARK),
425 Some("course:01J8XZ0K3Q".to_string())603 Some("course:01J8XZ0K3Q".to_string())
426 );604 );
427 assert_eq!(605 assert_eq!(
428- full_course("class_full:course:algebra'"),606+ named_course("class_full:course:algebra'", FULL_MARK),
607+ Some("course:algebra".into())
608+ );
609+ assert_eq!(named_course("class_held", FULL_MARK), None);
610+ assert_eq!(named_course("class_full:", FULL_MARK), None);
611+ // And the stale-link abort reads off the same shape, without the two
612+ // markers ever matching each other's text.
613+ assert_eq!(
614+ named_course("class_no_course:course:algebra'", MISSING_MARK),
429 Some("course:algebra".into())615 Some("course:algebra".into())
430 );616 );
431- assert_eq!(full_course("class_held"), None);617+ assert_eq!(named_course("class_no_course:course:a", FULL_MARK), None);
432- assert_eq!(full_course("class_full:"), None);618+ assert_eq!(named_course("class_full:course:a", MISSING_MARK), None);
433 }619 }
434 }620 }
src/domain/enrollment.rsmodified+137 -48
@@ -1,7 +1,7 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3 use crate::constant::{ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE};3 use crate::constant::{ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE};
4-use crate::database::Database;4+use crate::database::{Database, transaction_with_retry};
5 use crate::domain::cap;5 use crate::domain::cap;
6 use crate::domain::class_group::ClassGroupId;6 use crate::domain::class_group::ClassGroupId;
7 use crate::domain::course::{Course, CourseId};7 use crate::domain::course::{Course, CourseId};
@@ -9,6 +9,11 @@ use crate::domain::page::PagedList;
9 use crate::domain::user::UserId;9 use crate::domain::user::UserId;
10 use crate::error::AppError;10 use crate::error::AppError;
11 11
12+/// The `THROW` markers [`Enrollment::enroll`]'s claim aborts with: this pair
13+/// already holds a row, and the roster is full.
14+const HELD_MARK: &str = "enroll_held";
15+const FULL_MARK: &str = "enroll_full";
16+
12 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]17 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
13 pub struct EnrollmentId(RecordId);18 pub struct EnrollmentId(RecordId);
14 19
@@ -80,13 +85,22 @@ impl Enrollment {
80 /// pair converge on one row instead of racing the unique index into a 500:85 /// pair converge on one row instead of racing the unique index into a 500:
81 /// the loser of the `CREATE` reads the winner's row back and returns it.86 /// the loser of the `CREATE` reads the winner's row back and returns it.
82 /// When the course carries a capacity, a full roster refuses new members87 /// When the course carries a capacity, a full roster refuses new members
83- /// (409) β€” the seat is taken by [`cap::claim`] on the course row, an atomic88+ /// (409) β€” the seat is taken by a single-record conditional write on the
84- /// single-record conditional write, so the cap holds against concurrent89+ /// course row whose bound is the row's *own* `capacity` column, read inside
85- /// enrolls and a concurrent capacity PATCH alike. An already enrolled user is90+ /// the same statement that spends the seat. A snapshot integer taken by a
86- /// returned as-is even when the roster is full, and never charged a seat.91+ /// read beforehand would be exactly the number a concurrent capacity PATCH
87- /// The same claim is the delete guard's other half: it is refused outright92+ /// invalidates, which is what this promised and did not do. An already
88- /// once the course row is gone, and while it holds a seat the course cannot93+ /// enrolled user is returned as-is even when the roster is full, and never
89- /// be deleted β€” so no roster row can outlive its course.94+ /// charged a seat. The same claim is the delete guard's other half: it
95+ /// matches nothing once the course row is gone, and while it holds a seat
96+ /// the course cannot be deleted β€” so no roster row can outlive its course.
97+ ///
98+ /// On admissibility ([`crate::database::transaction_with_retry`]): the
99+ /// `CREATE` here *can* answer "already exists", but only to a rival that
100+ /// landed inside this very window β€” and the re-send then sees that row at
101+ /// the `$held` gate and takes the other branch, so the loop converges
102+ /// instead of re-asking a settled question. Same shape, same reason, as
103+ /// [`crate::domain::class_pump::attach`].
90 pub async fn enroll(104 pub async fn enroll(
91 course: &CourseId,105 course: &CourseId,
92 user: &UserId,106 user: &UserId,
@@ -94,12 +108,8 @@ impl Enrollment {
94 db: &Database,108 db: &Database,
95 ) -> Result<Enrollment, AppError> {109 ) -> Result<Enrollment, AppError> {
96 if let Some(existing) = Self::read_for_user(course, user, db).await? {110 if let Some(existing) = Self::read_for_user(course, user, db).await? {
97- return Ok(existing);111+ return Self::disown_if_pumped(existing, db).await;
98 }112 }
99- let capacity = Course::read(course, db)
100- .await?
101- .ok_or(AppError::NotFound)?
102- .get_capacity();
103 let enrollment = Enrollment {113 let enrollment = Enrollment {
104 id: EnrollmentId::composite(course, user),114 id: EnrollmentId::composite(course, user),
105 course: course.clone(),115 course: course.clone(),
@@ -113,30 +123,101 @@ impl Enrollment {
113 // to be *seen*, or the pair's second writer would keep the seat it123 // to be *seen*, or the pair's second writer would keep the seat it
114 // claimed for a row that already existed and the counter would drift124 // claimed for a row that already existed and the counter would drift
115 // above the roster forever.125 // above the roster forever.
116- match cap::claim_and_create(126+ //
117- &course.record(),127+ // Parenthesized `??` throughout: `n ?? 0 < cap` parses as
118- ENROLLMENT_COUNT_FIELD,128+ // `n ?? (0 < cap)`, which is truthy for every row and would enroll past
119- capacity.unwrap_or(cap::UNLIMITED),129+ // the capacity.
120- &enrollment.id.record(),130+ let sql = format!(
121- &enrollment,131+ "BEGIN TRANSACTION;
132+ LET $held = (SELECT VALUE id FROM $id);
133+ IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }};
134+ LET $seat = (UPDATE $course SET {ENROLLMENT_COUNT_FIELD} = \
135+ ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 \
136+ WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) < (capacity ?? $unlimited) \
137+ RETURN VALUE id);
138+ IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }};
139+ CREATE $id CONTENT $row;
140+ COMMIT TRANSACTION;"
141+ );
142+ // The process still sends its counter writes one at a time (see
143+ // [`cap::counter_lock`]); this statement moves the same counter every
144+ // cap claim does.
145+ let _guard = cap::counter_lock().await;
146+ let (mut result, mut errors) = transaction_with_retry(
122 db,147 db,
148+ &sql,
149+ &[
150+ ("id".into(), enrollment.id.record().into_value()),
151+ ("row".into(), enrollment.clone().into_value()),
152+ ("course".into(), course.record().into_value()),
153+ ("unlimited".into(), cap::UNLIMITED.into_value()),
154+ ],
155+ &[HELD_MARK, FULL_MARK],
123 )156 )
124- .await?157+ .await?;
158+ // Someone placed this pair first; their row is the answer, and no seat
159+ // was spent finding that out. It is read first: it outranks the refusal
160+ // below, and the gate aborts before the seat is touched.
161+ if errors
162+ .values()
163+ .any(|error| error.to_string().contains(HELD_MARK))
164+ {
165+ return match Self::read_for_user(course, user, db).await? {
166+ Some(existing) => Self::disown_if_pumped(existing, db).await,
167+ None => Err(AppError::Internal("failed to enroll user".into())),
168+ };
169+ }
170+ // Full, or the course is gone β€” the conditional write matches nothing
171+ // either way, and only this path pays for the read that tells them
172+ // apart.
173+ if errors
174+ .values()
175+ .any(|error| error.to_string().contains(FULL_MARK))
125 {176 {
126- cap::Claimed::Made(saved) => Ok(saved),177+ return match Course::read(course, db).await? {
127- // Someone placed this pair first; their row is the answer, and no
128- // seat was spent finding that out.
129- cap::Claimed::Duplicate => Self::read_for_user(course, user, db)
130- .await?
131- .ok_or_else(|| AppError::Internal("failed to enroll user".into())),
132- // Full, or the course was deleted between the read and the claim β€”
133- // the conditional write matches nothing either way, and only this
134- // path pays for the read that tells them apart.
135- cap::Claimed::Full => match Course::read(course, db).await? {
136 Some(_) => Err(AppError::Conflict("the course is full")),178 Some(_) => Err(AppError::Conflict("the course is full")),
137 None => Err(AppError::NotFound),179 None => Err(AppError::NotFound),
138- },180+ };
181+ }
182+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
183+ return Err(error.into());
139 }184 }
185+ // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5.
186+ result
187+ .take::<Vec<Enrollment>>(5)?
188+ .into_iter()
189+ .next()
190+ .ok_or_else(|| AppError::Internal("failed to enroll user".into()))
191+ }
192+
193+ /// A hand enroll landing on a row a class pumped takes the row *off* the
194+ /// class: `source` goes, so no later class sweep can unenroll a student an
195+ /// operator placed on purpose. The mirror of the rule the sweep already
196+ /// holds in the other direction β€” a manual unenroll wins, permanently β€” and
197+ /// without it "hand-placed" was a state only a first enroll could reach.
198+ ///
199+ /// `UNSET`, not `= NONE`: absence *is* the meaning of this column (see the
200+ /// struct doc), and it is what a hand enroll writes on the create path.
201+ async fn disown_if_pumped(existing: Enrollment, db: &Database) -> Result<Enrollment, AppError> {
202+ if existing.source.is_none() {
203+ return Ok(existing);
204+ }
205+ let mut result = db
206+ .query("UPDATE $id UNSET source RETURN AFTER")
207+ .bind(("id", existing.id.record()))
208+ .await?
209+ .check()?;
210+ // A row that is no longer there is not an internal error: an unenroll
211+ // (or the class sweep a role change runs) landing between the read
212+ // above and this write matches nothing, and the caller asked to be
213+ // enrolled β€” which they were, by the row this call was handed. The
214+ // disown is all that is lost, and it is lost to a delete that took the
215+ // whole row with it.
216+ Ok(result
217+ .take::<Vec<Enrollment>>(0)?
218+ .into_iter()
219+ .next()
220+ .unwrap_or(existing))
140 }221 }
141 222
142 /// Some(_) iff `user` is enrolled in `course` β€” the grading gate.223 /// Some(_) iff `user` is enrolled in `course` β€” the grading gate.
@@ -166,23 +247,6 @@ impl Enrollment {
166 .await247 .await
167 }248 }
168 249
169- /// Drop every enrollment `user` holds, across all courses. Only students
170- /// enroll, so promotion out of `student` calls this to clear the rosters.
171- pub async fn delete_for_user(user: &UserId, db: &Database) -> Result<(), AppError> {
172- db.query(
173- "BEGIN TRANSACTION;
174- LET $gone = (DELETE enrollment WHERE user = $usr RETURN BEFORE);
175- FOR $row IN ($gone ?? []) {
176- UPDATE $row.course SET enrollment_count = math::max([(enrollment_count ?? 0) - 1, 0]);
177- };
178- COMMIT TRANSACTION;",
179- )
180- .bind(("usr", user.record()))
181- .await?
182- .check()?;
183- Ok(())
184- }
185-
186 pub async fn remove(250 pub async fn remove(
187 course: &CourseId,251 course: &CourseId,
188 user: &UserId,252 user: &UserId,
@@ -237,6 +301,31 @@ mod tests {
237 assert_eq!(decoded.get_source(), None);301 assert_eq!(decoded.get_source(), None);
238 }302 }
239 303
304+ /// A pumped row that vanishes under the disown β€” a concurrent unenroll, or
305+ /// the sweep a role change runs β€” must answer the row the caller was
306+ /// handed, not a 500. The `UPDATE` matches nothing and used to fall through
307+ /// to `AppError::Internal`, turning a race the old code answered 200 into a
308+ /// server error on an ordinary `POST /courses/{id}/enrollments`.
309+ #[tokio::test]
310+ async fn a_vanished_row_is_not_an_internal_error() {
311+ let db = crate::database::init_mem().await.unwrap();
312+ let class = crate::domain::class_group::ClassGroupId::from_key("9a");
313+ let course = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");
314+ let student = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U");
315+ // Never written: the same store state a delete in the window leaves.
316+ let ghost = Enrollment {
317+ id: EnrollmentId::composite(&course, &student),
318+ course: course.clone(),
319+ user: student.clone(),
320+ enrolled_by: UserId::from_key("mgr"),
321+ source: Some(class),
322+ };
323+
324+ let answered = Enrollment::disown_if_pumped(ghost, &db).await.unwrap();
325+ assert_eq!(answered.get_user(), &student);
326+ assert_eq!(answered.get_course(), &course);
327+ }
328+
240 /// And the other half of "absence is the meaning": a hand-placed enrollment329 /// And the other half of "absence is the meaning": a hand-placed enrollment
241 /// must store *no* source key, or a class sweep would take back a row it330 /// must store *no* source key, or a class sweep would take back a row it
242 /// never wrote. Asserted on the stored row, not the returned one.331 /// never wrote. Asserted on the stored row, not the returned one.
src/domain/exam_question.rsmodified+10 -8
@@ -641,14 +641,16 @@ impl ExamQuestion {
641 pub async fn delete(self, db: &Database) -> Result<ExamQuestion, AppError> {641 pub async fn delete(self, db: &Database) -> Result<ExamQuestion, AppError> {
642 let mut result = ExamAttempt::write_unfrozen(642 let mut result = ExamAttempt::write_unfrozen(
643 &self.exam,643 &self.exam,
644- "DELETE exam_answer WHERE question = $q;644+ &format!(
645- DELETE question_image WHERE question = $q;645+ "DELETE exam_answer WHERE question = $q;
646- LET $gone = (DELETE $q RETURN BEFORE);646+ DELETE question_image WHERE question = $q;
647- FOR $sub IN ($gone.subject ?? []) {647+ LET $gone = (DELETE $q RETURN BEFORE);
648- UPDATE $sub SET exam_question_count =648+ FOR $sub IN ($gone.subject ?? []) {{
649- math::max([(exam_question_count ?? 0) - 1, 0])649+ UPDATE $sub SET {SUBJECT_QUESTION_COUNT_FIELD} =
650- };650+ math::max([({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) - 1, 0])
651- RETURN $gone;",651+ }};
652+ RETURN $gone;"
653+ ),
652 vec![("q".into(), self.id.record().into_value())],654 vec![("q".into(), self.id.record().into_value())],
653 db,655 db,
654 )656 )
src/domain/field_update.rsmodified+153 -6
@@ -221,6 +221,15 @@ impl FieldUpdate {
221 let cas = moved221 let cas = moved
222 .as_ref()222 .as_ref()
223 .map(|(_, link, ..)| format!("{link} = $ref_expected"));223 .map(|(_, link, ..)| format!("{link} = $ref_expected"));
224+ // The caller's own guards, kept apart from the CAS: the split below has
225+ // to ask "did *only* the link move?", and a probe that ignores them
226+ // answers "the link moved" to a write its `.guard()` refused outright.
227+ let own = ordered
228+ .iter()
229+ .chain(extra.iter())
230+ .cloned()
231+ .collect::<Vec<_>>()
232+ .join(" AND ");
224 let conditions: Vec<String> = ordered.into_iter().chain(extra).chain(cas).collect();233 let conditions: Vec<String> = ordered.into_iter().chain(extra).chain(cas).collect();
225 let guard = if conditions.is_empty() {234 let guard = if conditions.is_empty() {
226 String::new()235 String::new()
@@ -234,7 +243,7 @@ impl FieldUpdate {
234 // its guard reads, and the loser wrote nothing, so re-sending it is the243 // its guard reads, and the loser wrote nothing, so re-sending it is the
235 // recovery β€” see [`write_with_retry`].244 // recovery β€” see [`write_with_retry`].
236 let rows: Vec<T> = match moved {245 let rows: Vec<T> = match moved {
237- Some(moved) => run_with_refcount(db, &sql, self.bindings, moved).await?,246+ Some(moved) => run_with_refcount(db, &sql, &own, self.bindings, moved).await?,
238 None => write_with_retry(db, &sql, &self.bindings).await?,247 None => write_with_retry(db, &sql, &self.bindings).await?,
239 };248 };
240 // No row back means the guard bit (or, in the window after the handler's249 // No row back means the guard bit (or, in the window after the handler's
@@ -265,6 +274,7 @@ impl FieldUpdate {
265 async fn run_with_refcount<T: SurrealValue>(274 async fn run_with_refcount<T: SurrealValue>(
266 db: &Database,275 db: &Database,
267 update: &str,276 update: &str,
277+ own_guards: &str,
268 mut bindings: Vec<(String, Value)>,278 mut bindings: Vec<(String, Value)>,
269 (field, link, expected, claim, release, refused): Refcount,279 (field, link, expected, claim, release, refused): Refcount,
270 ) -> Result<Vec<T>, AppError> {280 ) -> Result<Vec<T>, AppError> {
@@ -295,13 +305,22 @@ async fn run_with_refcount<T: SurrealValue>(
295 // Without this the claim would outlive a row write that matched nothing β€”305 // Without this the claim would outlive a row write that matched nothing β€”
296 // the very leak the transaction exists to close. Nothing was written yet306 // the very leak the transaction exists to close. Nothing was written yet
297 // either way, so the probe that tells the two empty cases apart is free to307 // either way, so the probe that tells the two empty cases apart is free to
298- // be another `UPDATE`: it matches only a row that is *there* and whose link308+ // be another `UPDATE`: it matches only a row that is *there*, whose *own*
299- // has moved off what the handler read, which is the CAS having bitten. A309+ // guards still hold, and whose link has moved off what the handler read β€”
300- // deleted row and a plain guard refusal both miss it and keep the answer310+ // which is the CAS, and nothing else, having bitten. A deleted row and a
301- // they have always got.311+ // plain guard refusal both miss it and keep the answer they have always
312+ // got. Carrying the caller's guards is what keeps that true when a write is
313+ // refused for *both* reasons at once: a `.guard()`/`.ordered()` refusal is
314+ // the caller's own answer to give, and reporting it as "the link moved"
315+ // would send the client to re-read a link that was never its problem.
316+ let still_mine = if own_guards.is_empty() {
317+ String::new()
318+ } else {
319+ format!("({own_guards}) AND ")
320+ };
302 statements.push(format!(321 statements.push(format!(
303 "IF array::len($row) = 0 {{ \322 "IF array::len($row) = 0 {{ \
304- LET $live = (UPDATE $id WHERE {link} != $ref_expected RETURN VALUE id); \323+ LET $live = (UPDATE $id WHERE {still_mine}{link} != $ref_expected RETURN VALUE id); \
305 IF array::len($live) = 0 {{ THROW '{ROW_MARK}' }} ELSE {{ THROW '{STALE_MARK}' }} }}"324 IF array::len($live) = 0 {{ THROW '{ROW_MARK}' }} ELSE {{ THROW '{STALE_MARK}' }} }}"
306 ));325 ));
307 statements.push("RETURN $row".into());326 statements.push("RETURN $row".into());
@@ -343,3 +362,131 @@ async fn run_with_refcount<T: SurrealValue>(
343 // removes errored slots, which would renumber the rest.362 // removes errored slots, which would renumber the rest.
344 Ok(result.take::<Vec<T>>(slot)?)363 Ok(result.take::<Vec<T>>(slot)?)
345 }364 }
365+
366+#[cfg(test)]
367+mod tests {
368+ use super::*;
369+ use crate::constant::SUBJECT_HOMEWORK_COUNT_FIELD;
370+ use crate::database::init_mem;
371+
372+ /// Two subjects and one homework tagged with the first. The `course` and
373+ /// `created_by` links point at rows that do not exist β€” a `record<…>` type
374+ /// constrains the table, not the existence, and nothing here reads them.
375+ async fn seeded() -> Database {
376+ let db = init_mem().await.unwrap();
377+ db.query(
378+ "CREATE subject:s1 SET course = course:c, name = 'a', description = '';
379+ CREATE subject:s2 SET course = course:c, name = 'b', description = '';
380+ CREATE homework:h1 SET course = course:c, subject = subject:s1,
381+ title = 't', due_at = 1, created_by = user:u, created_at = 1;",
382+ )
383+ .await
384+ .unwrap()
385+ .check()
386+ .unwrap();
387+ db
388+ }
389+
390+ /// The two subjects' homework counters, re-read out of the store.
391+ async fn counts(db: &Database) -> Vec<i64> {
392+ let mut result = db
393+ .query(format!(
394+ "SELECT VALUE ({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) FROM subject ORDER BY id"
395+ ))
396+ .await
397+ .unwrap()
398+ .check()
399+ .unwrap();
400+ result.take::<Vec<i64>>(0).unwrap()
401+ }
402+
403+ fn homework() -> RecordId {
404+ RecordId::new("homework", "h1")
405+ }
406+
407+ fn subject(key: &str) -> RecordId {
408+ RecordId::new("subject", key)
409+ }
410+
411+ /// A write refused by the caller's *own* guard must answer with the
412+ /// caller's own refusal, even when the link it carries has also moved since
413+ /// the handler read it. Both are true; only one is the client's problem,
414+ /// and "re-read the link and retry" sends them chasing a `409` that a retry
415+ /// cannot clear β€” the guard will refuse the next attempt exactly the same.
416+ #[tokio::test]
417+ async fn a_guard_refusal_outranks_a_link_that_also_moved() {
418+ let db = seeded().await;
419+ let refused = FieldUpdate::new(homework())
420+ .set("subject", Some(subject("s2")))
421+ .guard("title = 'never'", AppError::Conflict("the caller's own no"))
422+ .refcount(
423+ SUBJECT_HOMEWORK_COUNT_FIELD,
424+ "subject",
425+ // Stale: the row says `s1`, so the CAS bites too.
426+ Some(subject("s9")),
427+ Some(subject("s2")),
428+ Some(subject("s9")),
429+ AppError::Conflict("the subject is gone"),
430+ )
431+ .run::<Value>(&db)
432+ .await
433+ .unwrap_err();
434+ assert_eq!(refused.to_string(), "conflict: the caller's own no");
435+ // The abort took the claim with it, and the link never moved.
436+ assert_eq!(counts(&db).await, vec![0, 0]);
437+ }
438+
439+ /// ...and with the guard satisfied, a moved link is still reported as a
440+ /// moved link β€” the answer every current caller relies on.
441+ #[tokio::test]
442+ async fn a_moved_link_alone_is_still_the_stale_move_409() {
443+ let db = seeded().await;
444+ let refused = FieldUpdate::new(homework())
445+ .set("subject", Some(subject("s2")))
446+ .guard("title = 't'", AppError::Conflict("the caller's own no"))
447+ .refcount(
448+ SUBJECT_HOMEWORK_COUNT_FIELD,
449+ "subject",
450+ Some(subject("s9")),
451+ Some(subject("s2")),
452+ Some(subject("s9")),
453+ AppError::Conflict("the subject is gone"),
454+ )
455+ .run::<Value>(&db)
456+ .await
457+ .unwrap_err();
458+ assert!(
459+ refused
460+ .to_string()
461+ .contains("the link this update moves changed"),
462+ "{refused}"
463+ );
464+ assert_eq!(counts(&db).await, vec![0, 0]);
465+ }
466+
467+ /// The unguarded shape every production caller uses today: the link moves,
468+ /// the counters move with it, in one transaction.
469+ #[tokio::test]
470+ async fn an_unguarded_move_still_lands_with_both_counters() {
471+ let db = seeded().await;
472+ db.query("UPDATE subject:s1 SET homework_count = 1")
473+ .await
474+ .unwrap()
475+ .check()
476+ .unwrap();
477+ FieldUpdate::new(homework())
478+ .set("subject", Some(subject("s2")))
479+ .refcount(
480+ SUBJECT_HOMEWORK_COUNT_FIELD,
481+ "subject",
482+ Some(subject("s1")),
483+ Some(subject("s2")),
484+ Some(subject("s1")),
485+ AppError::Conflict("the subject is gone"),
486+ )
487+ .run::<Value>(&db)
488+ .await
489+ .unwrap();
490+ assert_eq!(counts(&db).await, vec![0, 1]);
491+ }
492+}
src/domain/homework.rsmodified+13 -10
@@ -348,16 +348,19 @@ impl Homework {
348 pub async fn delete(self, db: &Database) -> Result<Homework, AppError> {348 pub async fn delete(self, db: &Database) -> Result<Homework, AppError> {
349 let mut result = db349 let mut result = db
350 .query(350 .query(
351- "BEGIN TRANSACTION;351+ format!(
352- DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw);352+ "BEGIN TRANSACTION;
353- DELETE homework_submission WHERE homework = $hw;353+ DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw);
354- DELETE homework_result WHERE homework = $hw;354+ DELETE homework_submission WHERE homework = $hw;
355- LET $gone = (DELETE $hw RETURN BEFORE);355+ DELETE homework_result WHERE homework = $hw;
356- FOR $sub IN ($gone.subject ?? []) {356+ LET $gone = (DELETE $hw RETURN BEFORE);
357- UPDATE $sub SET homework_count = math::max([(homework_count ?? 0) - 1, 0])357+ FOR $sub IN ($gone.subject ?? []) {{
358- };358+ UPDATE $sub SET {SUBJECT_HOMEWORK_COUNT_FIELD} =
359- RETURN $gone;359+ math::max([({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) - 1, 0])
360- COMMIT TRANSACTION;",360+ }};
361+ RETURN $gone;
362+ COMMIT TRANSACTION;"
363+ ),
361 )364 )
362 .bind(("hw", self.id.record()))365 .bind(("hw", self.id.record()))
363 .await?366 .await?
src/domain/meal_attendance.rsmodified+18 -3
@@ -110,13 +110,22 @@ impl MealAttendance {
110 /// Record (or overwrite) whether `student` ate off `menu`. One row per110 /// Record (or overwrite) whether `student` ate off `menu`. One row per
111 /// pair by construction, so a correction is the same UPSERT flipping the111 /// pair by construction, so a correction is the same UPSERT flipping the
112 /// status. No ledger line, ever β€” see the module header.112 /// status. No ledger line, ever β€” see the module header.
113+ ///
114+ /// `None` = the menu is gone, and the mark was *not* written. The menu's
115+ /// existence is the `UPSERT`'s own target rather than a read the write then
116+ /// trusts: the id list comes out of a `SELECT` over the menu row, so a menu
117+ /// deleted a moment ago yields no target and the statement writes nothing.
118+ /// An unconditional upsert landing just after `DELETE /meals/menus/{id}`
119+ /// committed left a mark its cascade had already swept β€” and since
120+ /// [`MenuId::for_slot`] is deterministic, republishing that day and slot
121+ /// resurrected it as a mark on the new menu.
113 pub async fn mark(122 pub async fn mark(
114 menu: &MenuId,123 menu: &MenuId,
115 student: &UserId,124 student: &UserId,
116 status: MealAttendanceStatus,125 status: MealAttendanceStatus,
117 marked_by: &UserId,126 marked_by: &UserId,
118 db: &Database,127 db: &Database,
119- ) -> Result<MealAttendance, AppError> {128+ ) -> Result<Option<MealAttendance>, AppError> {
120 let row = MealAttendance {129 let row = MealAttendance {
121 id: MealAttendanceId::composite(menu, student),130 id: MealAttendanceId::composite(menu, student),
122 menu: menu.clone(),131 menu: menu.clone(),
@@ -125,8 +134,14 @@ impl MealAttendance {
125 marked_by: marked_by.clone(),134 marked_by: marked_by.clone(),
126 marked_at: Timestamp::now(),135 marked_at: Timestamp::now(),
127 };136 };
128- let saved: Option<MealAttendance> = db.upsert(row.id.record()).content(row).await?;137+ let mut result = db
129- saved.ok_or_else(|| AppError::Internal("failed to mark meal attendance".into()))138+ .query("UPSERT (SELECT VALUE $id FROM $menu) CONTENT $row RETURN AFTER")
139+ .bind(("id", row.id.record()))
140+ .bind(("menu", menu.record()))
141+ .bind(("row", row))
142+ .await?
143+ .check()?;
144+ Ok(result.take::<Vec<MealAttendance>>(0)?.into_iter().next())
130 }145 }
131 146
132 /// The kitchen's list for one menu.147 /// The kitchen's list for one menu.
src/domain/meal_booking.rsmodified+329 -52
@@ -23,7 +23,10 @@
23 //! price its menu genuinely carried.23 //! price its menu genuinely carried.
24 //! - **The seat and its money move together.** Booking charges and cancelling24 //! - **The seat and its money move together.** Booking charges and cancelling
25 //! reverses right here, not in the web layer β€” a seam between the two let25 //! reverses right here, not in the web layer β€” a seam between the two let
26-//! concurrent `POST`s bill one seat twice.26+//! concurrent `POST`s bill one seat twice β€” and *both* ledger lines are
27+//! written by the very transaction that moves the seat, because money that
28+//! trails the seat by one write can be overtaken by the next attempt and
29+//! stranded forever: every ledger id carries the attempt it belongs to.
27 30
28 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};31 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
29 32
@@ -162,10 +165,10 @@ impl MealBooking {
162 /// instant the seat was taken β€” a guarantee a lock around the read could165 /// instant the seat was taken β€” a guarantee a lock around the read could
163 /// not give, since the price is read a round trip before the claim.166 /// not give, since the price is read a round trip before the claim.
164 ///167 ///
165- /// The charge is appended after, keyed by (seat, attempt): eight concurrent168+ /// The charge rides that same transaction, keyed by (seat, attempt): eight
166- /// `POST`s of one seat hold one seat and write one charge line. The price is169+ /// concurrent `POST`s of one seat hold one seat and write one charge line.
167- /// `None` when the menu is free, and that `None` is stored, so a dish added170+ /// The price is `None` when the menu is free, and that `None` is stored, so
168- /// later never bills a seat retroactively.171+ /// a dish added later never bills a seat retroactively.
169 ///172 ///
170 /// `cutoff` is the school's one meal deadline (see [`MealCutoff`]): once173 /// `cutoff` is the school's one meal deadline (see [`MealCutoff`]): once
171 /// serving time is that close, the seat is fixed either way.174 /// serving time is that close, the seat is fixed either way.
@@ -181,14 +184,17 @@ impl MealBooking {
181 for _ in 0..CAS_UPDATE_RETRIES {184 for _ in 0..CAS_UPDATE_RETRIES {
182 let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?;185 let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?;
183 check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?;186 check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?;
184- // Before the seat: an unchargeable menu (dishes summing past the
185- // cap) must refuse the booking outright, never leave a
186- // booked-but-unbilled row behind.
187- let price = MealLedger::price_snapshot(menu, db).await?;
188 let existing: Option<MealBooking> = db.select(id.record()).await?;187 let existing: Option<MealBooking> = db.select(id.record()).await?;
189 // The seat is already held: same attempt, same price it was taken188 // The seat is already held: same attempt, same price it was taken
190 // at. Today's menu price bills nobody who booked yesterday's. No189 // at. Today's menu price bills nobody who booked yesterday's. No
191 // seat is claimed, so a double-click cannot count two.190 // seat is claimed, so a double-click cannot count two.
191+ //
192+ // Answered *before* the menu is priced, and that ordering is the
193+ // rule: pricing first made a repeat POST of a seat already held 400
194+ // ("amount_minor must be between…") as soon as the menu's dishes
195+ // summed past the chargeable maximum β€” refusing to replay a seat
196+ // the student holds, over a price that seat was never going to be
197+ // billed.
192 if let Some(held) = existing198 if let Some(held) = existing
193 .clone()199 .clone()
194 .filter(|row| row.status == MealBookingStatus::Booked)200 .filter(|row| row.status == MealBookingStatus::Booked)
@@ -196,32 +202,47 @@ impl MealBooking {
196 MealLedger::charge_booking(&held, booked_by, db).await?;202 MealLedger::charge_booking(&held, booked_by, db).await?;
197 return Ok(held);203 return Ok(held);
198 }204 }
205+ // Before the seat: an unchargeable menu (dishes summing past the
206+ // cap) must refuse the booking outright, never leave a
207+ // booked-but-unbilled row behind.
208+ let price = MealLedger::price_snapshot(menu, db).await?;
209+ // The attempt is settled *here*, not by the revival's `attempt + 1`,
210+ // because the charge id is (seat, attempt) and the charge has to be
211+ // built before the transaction that writes it. `existing` is either
212+ // absent or cancelled β€” a booked row returned above.
199 let fresh_row = MealBooking {213 let fresh_row = MealBooking {
200 id: id.clone(),214 id: id.clone(),
201 menu: menu.clone(),215 menu: menu.clone(),
202 student: student.clone(),216 student: student.clone(),
203 booked_by: booked_by.clone(),217 booked_by: booked_by.clone(),
204 status: MealBookingStatus::Booked,218 status: MealBookingStatus::Booked,
205- attempt: 1,219+ attempt: existing.map_or(1, |prior| prior.attempt + 1),
206 price_minor: price,220 price_minor: price,
207 cancelled_at: None,221 cancelled_at: None,
208 created_at: Timestamp::now(),222 created_at: Timestamp::now(),
209 };223 };
210- let booking = match Self::claim_and_place(224+ let charge = MealLedger::charge_for(&fresh_row, booked_by);
225+ match Self::claim_and_place(
211 &seats,226 &seats,
212 fresh.get_capacity().unwrap_or(cap::UNLIMITED),227 fresh.get_capacity().unwrap_or(cap::UNLIMITED),
213 fresh.get_version(),228 fresh.get_version(),
214 &fresh_row,229 &fresh_row,
215 price,230 price,
231+ charge.as_ref(),
216 db,232 db,
217 )233 )
218 .await?234 .await?
219 {235 {
220- Claimed::Made(booking) => booking,236+ // Seat, row and charge committed together; nothing is owed
221- // Another `POST` of this very pair placed the row first, and it237+ // after this call, which is the whole point of folding them.
222- // owed no second seat: this caller never took one (the whole238+ Claimed::Made(booking) => return Ok(booking),
223- // transaction rolled back), so the winner's row is the answer.239+ // Another `POST` of this very pair moved the row first, and this
224- Claimed::Duplicate => Self::read(&id, db).await?.ok_or(AppError::NotFound)?,240+ // caller never took a seat (the whole transaction rolled back).
241+ // The decision is simply made again rather than answered off a
242+ // row read here: the winner may have left it `cancelled` at an
243+ // attempt this call never saw, and the loop's own held-seat path
244+ // is what returns a live seat *and* replays its charge.
245+ Claimed::Duplicate => continue,
225 // Full, moved, or gone β€” one `WHERE` refused all three, so the246 // Full, moved, or gone β€” one `WHERE` refused all three, so the
226 // reason is re-read rather than guessed. A moved menu is not a247 // reason is re-read rather than guessed. A moved menu is not a
227 // refusal: the price above is stale, so price and seat are248 // refusal: the price above is stale, so price and seat are
@@ -231,11 +252,7 @@ impl MealBooking {
231 Some(now) if now.get_version() != fresh.get_version() => continue,252 Some(now) if now.get_version() != fresh.get_version() => continue,
232 Some(_) => return Err(AppError::Conflict("the menu is fully booked")),253 Some(_) => return Err(AppError::Conflict("the menu is fully booked")),
233 },254 },
234- };255+ }
235- // Writes nothing when this attempt is already billed, so the repeat
236- // POST above costs nothing and a charge that failed once self-heals.
237- MealLedger::charge_booking(&booking, booked_by, db).await?;
238- return Ok(booking);
239 }256 }
240 Err(AppError::Conflict(257 Err(AppError::Conflict(
241 "the menu kept changing underneath this booking",258 "the menu kept changing underneath this booking",
@@ -258,14 +275,42 @@ impl MealBooking {
258 /// A cancelled row is revived in place (a fresh attempt at `price`) rather275 /// A cancelled row is revived in place (a fresh attempt at `price`) rather
259 /// than recreated: `booked_by` and `created_at` are READONLY history β€” who276 /// than recreated: `booked_by` and `created_at` are READONLY history β€” who
260 /// opened the seat, and when.277 /// opened the seat, and when.
278+ ///
279+ /// **The charge rides this transaction too**, for the same reason the
280+ /// refund rides the cancel's: appended a write later, a cancel landing in
281+ /// the gap finds no charge, reverses nothing, and the charge lands after it
282+ /// β€” the seat given back and the money still owed, unreversible by any
283+ /// route, because every ledger id carries the attempt the cancel has already
284+ /// moved past. That is why `row.attempt` is minted by the *caller*: the
285+ /// charge's id is (seat, attempt), so the number cannot be the revival's own
286+ /// `attempt + 1` any more. The revival is fenced on the attempt it read
287+ /// instead, so a rival that revived first loses this claim (the `CREATE`
288+ /// below then finds the row and aborts the whole transaction) rather than
289+ /// billing its attempt at this call's id.
290+ ///
291+ /// The charge is created only if it is not already there β€” a duplicate
292+ /// `CREATE` would abort the transaction and cost the seat, and an attempt
293+ /// billed twice is the one thing money code may never do.
261 async fn claim_and_place(294 async fn claim_and_place(
262 seats: &RecordId,295 seats: &RecordId,
263 cap: i64,296 cap: i64,
264 seen: i64,297 seen: i64,
265 row: &MealBooking,298 row: &MealBooking,
266 price: Option<LedgerAmount>,299 price: Option<LedgerAmount>,
300+ charge: Option<&MealLedger>,
267 db: &Database,301 db: &Database,
268 ) -> Result<Claimed<MealBooking>, AppError> {302 ) -> Result<Claimed<MealBooking>, AppError> {
303+ // Empty when the menu is free: a seat that costs nothing owes no line.
304+ let bill = match charge {
305+ Some(_) => {
306+ "IF array::len((SELECT VALUE id FROM $charge)) = 0 \
307+ { CREATE $charge CONTENT $line };"
308+ }
309+ None => "",
310+ };
311+ // Slots count BEGIN, three LETs, three IFs and β€” when there is money to
312+ // take β€” the charge's IF, so the RETURN is slot 7 or 8.
313+ let returned = if charge.is_some() { 8 } else { 7 };
269 // Parenthesized `??` throughout: `a ?? 0 = $seen` binds the wrong way.314 // Parenthesized `??` throughout: `a ?? 0 = $seen` binds the wrong way.
270 let sql = format!(315 let sql = format!(
271 "BEGIN TRANSACTION;316 "BEGIN TRANSACTION;
@@ -276,24 +321,31 @@ impl MealBooking {
276 WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) < $cap \321 WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) < $cap \
277 AND ({MENU_VERSION_FIELD} ?? 0) = $seen RETURN VALUE id);322 AND ({MENU_VERSION_FIELD} ?? 0) = $seen RETURN VALUE id);
278 IF array::len($seat) = 0 {{ THROW 'no_seat' }};323 IF array::len($seat) = 0 {{ THROW 'no_seat' }};
279- LET $revived = (UPDATE $id SET status = 'booked', attempt = attempt + 1, \324+ LET $revived = (UPDATE $id SET status = 'booked', attempt = $attempt, \
280 price_minor = $price, cancelled_at = NONE \325 price_minor = $price, cancelled_at = NONE \
281- WHERE status = 'cancelled' RETURN AFTER);326+ WHERE status = 'cancelled' AND attempt = $attempt - 1 RETURN AFTER);
282 IF array::len($revived) = 0 {{ CREATE $id CONTENT $row }};327 IF array::len($revived) = 0 {{ CREATE $id CONTENT $row }};
328+ {bill}
283 RETURN SELECT * FROM ONLY $id;329 RETURN SELECT * FROM ONLY $id;
284 COMMIT TRANSACTION;"330 COMMIT TRANSACTION;"
285 );331 );
286 for _ in 0..CAS_UPDATE_RETRIES {332 for _ in 0..CAS_UPDATE_RETRIES {
287- let mut result = match db333+ let query = db
288 .query(sql.as_str())334 .query(sql.as_str())
289 .bind(("menu", seats.clone()))335 .bind(("menu", seats.clone()))
290 .bind(("cap", cap))336 .bind(("cap", cap))
291 .bind(("seen", seen))337 .bind(("seen", seen))
292 .bind(("id", row.id.record()))338 .bind(("id", row.id.record()))
339+ .bind(("attempt", row.attempt))
293 .bind(("price", price))340 .bind(("price", price))
294- .bind(("row", row.clone()))341+ .bind(("row", row.clone()));
295- .await342+ let query = match charge {
296- {343+ Some(line) => query
344+ .bind(("charge", line.get_id().record()))
345+ .bind(("line", line.clone())),
346+ None => query,
347+ };
348+ let mut result = match query.await {
297 Ok(result) => result,349 Ok(result) => result,
298 Err(err) if lost_the_race(&err) => continue,350 Err(err) if lost_the_race(&err) => continue,
299 Err(err) => return Err(err.into()),351 Err(err) => return Err(err.into()),
@@ -319,8 +371,7 @@ impl MealBooking {
319 if let Some(error) = errors.drain().map(|(_, error)| error).next() {371 if let Some(error) = errors.drain().map(|(_, error)| error).next() {
320 return Err(error.into());372 return Err(error.into());
321 }373 }
322- // Slots count BEGIN, three LETs and three IFs: the RETURN is slot 7.374+ return match result.take::<Option<MealBooking>>(returned)? {
323- return match result.take::<Option<MealBooking>>(7)? {
324 Some(placed) => Ok(Claimed::Made(placed)),375 Some(placed) => Ok(Claimed::Made(placed)),
325 None => Err(AppError::Internal("failed to book the meal".into())),376 None => Err(AppError::Internal("failed to book the meal".into())),
326 };377 };
@@ -338,16 +389,19 @@ impl MealBooking {
338 /// cancelling a stale attempt would strand that attempt's charge forever.389 /// cancelling a stale attempt would strand that attempt's charge forever.
339 /// The reversal is keyed to the attempt, so a retried cancel refunds once.390 /// The reversal is keyed to the attempt, so a retried cancel refunds once.
340 ///391 ///
341- /// **Idempotent, and that is what makes the refund recoverable.** The flip392+ /// **The refund is not a second write.** It is appended by the very
342- /// and the reversal are two writes; a handler future dropped between them393+ /// transaction that flips the row (see [`Self::release_seat`]), so a
343- /// (the client closed the tab, a proxy timed out) or a `create` that errors394+ /// handler future dropped mid-cancel, a proxy timing out or the store going
344- /// leaves the seat free and the charge standing. Refusing an395+ /// away cannot leave the seat free with the charge standing β€” the state a
345- /// already-cancelled row β€” as this used to β€” made that state permanent:396+ /// re-book then made permanent, since every ledger id carries the attempt
346- /// no route on the API could ever append the missing reversal. So a397+ /// the re-book has already moved past.
347- /// cancelled row replays the reversal instead, which either heals the gap398+ ///
348- /// or writes nothing at all. The cutoff is not re-checked on that path: the399+ /// **Idempotent all the same**, which is what heals a seat flipped before
349- /// seat is already given back, and refusing to finish the refund because400+ /// that was true: a cancelled row replays the reversal instead of being
350- /// the meal has since closed would strand the money exactly as before.401+ /// refused, and that either completes an old missing line or writes nothing
402+ /// at all. The cutoff is not re-checked on that path: the seat is already
403+ /// given back, and refusing to finish the refund because the meal has since
404+ /// closed would strand the money exactly as before.
351 pub async fn cancel(405 pub async fn cancel(
352 self,406 self,
353 cutoff: &MealCutoff,407 cutoff: &MealCutoff,
@@ -363,16 +417,38 @@ impl MealBooking {
363 .await?417 .await?
364 .ok_or(AppError::NotFound)?;418 .ok_or(AppError::NotFound)?;
365 check_cutoff(menu.get_date(), menu.get_slot(), cutoff)?;419 check_cutoff(menu.get_date(), menu.get_slot(), cutoff)?;
366- // Lost the flip to a concurrent cancel: its row is the truth, and the420+ // Lost the flip: another cancel took the seat back first. Its row is
367- // reversal replay below heals whatever it left unfinished.421+ // the truth β€” but only the attempt *this* call was cancelling may be
368- let saved = match Self::release_seat(&fresh, db).await? {422+ // refunded off it (see [`Self::refundable_after_lost_flip`]).
423+ let saved = match Self::release_seat(&fresh, recorded_by, db).await? {
369 Some(cancelled) => cancelled,424 Some(cancelled) => cancelled,
370- None => Self::read(&self.id, db).await?.ok_or(AppError::NotFound)?,425+ None => {
426+ let live = Self::read(&self.id, db).await?.ok_or(AppError::NotFound)?;
427+ if !Self::refundable_after_lost_flip(&fresh, &live) {
428+ return Ok(live);
429+ }
430+ live
431+ }
371 };432 };
372 MealLedger::reverse_booking(&saved, recorded_by, db).await?;433 MealLedger::reverse_booking(&saved, recorded_by, db).await?;
373 Ok(saved)434 Ok(saved)
374 }435 }
375 436
437+ /// May a cancel that released *nothing* still refund what it read?
438+ ///
439+ /// Only when the row it finds is the very attempt it was cancelling, still
440+ /// cancelled. A cancel is two writes, and between them the seat can be
441+ /// re-booked: the row then reads `booked` at attempt N+1 with a live charge
442+ /// against it, and reversing that β€” as re-reading and refunding blindly did
443+ /// β€” refunds a seat that is still held *and* still counted, and burns the
444+ /// `(booking, attempt)` ledger id that attempt's own cancel needs, so it
445+ /// could never be refunded afterwards. A row at another attempt is the same
446+ /// story one step further on: whoever cancelled attempt N appended its
447+ /// reversal, and this call has nothing left to heal.
448+ fn refundable_after_lost_flip(seen: &MealBooking, live: &MealBooking) -> bool {
449+ live.status == MealBookingStatus::Cancelled && live.attempt == seen.attempt
450+ }
451+
376 /// Flip the seat to `cancelled` and give it back to the menu's counter **in452 /// Flip the seat to `cancelled` and give it back to the menu's counter **in
377 /// one transaction**, so the two can never disagree: a decrement that ran453 /// one transaction**, so the two can never disagree: a decrement that ran
378 /// without the flip frees a seat still held, and a flip without the454 /// without the flip frees a seat still held, and a flip without the
@@ -380,32 +456,69 @@ impl MealBooking {
380 /// flip's own result (`array::len`), so a row already cancelled β€” by a456 /// flip's own result (`array::len`), so a row already cancelled β€” by a
381 /// racing cancel, or by this call retried β€” decrements nothing.457 /// racing cancel, or by this call retried β€” decrements nothing.
382 ///458 ///
459+ /// **The refund rides this transaction too**, and it has to: the flip and a
460+ /// reversal appended after it are two writes, and a crash in between leaves
461+ /// the seat free with the charge standing β€” after which a re-book moves the
462+ /// row to attempt N+1 and *no* route can ever write the `(booking, N)`
463+ /// reversal, because the money is keyed to the attempt. Folded in here the
464+ /// seat cannot come back without the money, the same way the counter cannot
465+ /// move without the flip. The reversal is written only when the charge it
466+ /// undoes is really there (checked in the transaction, so no round trip can
467+ /// invalidate it): a refund with no charge behind it invents money.
468+ ///
469+ /// The book side is folded the same way ([`Self::claim_and_place`]), so
470+ /// there is no half-second anywhere in which a seat is held with no charge
471+ /// against it, or a charge stands with no seat behind it.
472+ ///
383 /// `None` = the row was not `booked` any more. Retried while the store473 /// `None` = the row was not `booked` any more. Retried while the store
384 /// reports a write conflict: the menu row is contended by every booking on474 /// reports a write conflict: the menu row is contended by every booking on
385 /// it, and that contention is the cap working, not an error.475 /// it, and that contention is the cap working, not an error.
386 async fn release_seat(476 async fn release_seat(
387 booked: &MealBooking,477 booked: &MealBooking,
478+ recorded_by: &UserId,
388 db: &Database,479 db: &Database,
389 ) -> Result<Option<MealBooking>, AppError> {480 ) -> Result<Option<MealBooking>, AppError> {
481+ let refund = MealLedger::reversal_for(booked, recorded_by);
482+ // Guarded three ways: nothing was flipped (a rival cancelled first, and
483+ // its own transaction carried the refund), the charge never landed, or
484+ // this attempt is already refunded β€” none of which may abort the flip.
485+ let reverse = match refund {
486+ Some(_) => {
487+ "IF array::len($flipped) > 0 \
488+ AND array::len((SELECT VALUE id FROM $charge)) > 0 \
489+ AND array::len((SELECT VALUE id FROM $reversal)) = 0 \
490+ { CREATE $reversal CONTENT $line };"
491+ }
492+ None => "",
493+ };
494+ // Slots count BEGIN, the LET, the seat UPDATE and β€” when there is money
495+ // to give back β€” the IF.
496+ let returned = if refund.is_some() { 4 } else { 3 };
390 for _ in 0..CAS_UPDATE_RETRIES {497 for _ in 0..CAS_UPDATE_RETRIES {
391 let attempted = async {498 let attempted = async {
392- let mut result = db499+ let query = db
393 .query(format!(500 .query(format!(
394 "BEGIN TRANSACTION;501 "BEGIN TRANSACTION;
395 LET $flipped = (UPDATE $id SET status = 'cancelled', \502 LET $flipped = (UPDATE $id SET status = 'cancelled', \
396 cancelled_at = $now WHERE status = 'booked' RETURN AFTER);503 cancelled_at = $now WHERE status = 'booked' RETURN AFTER);
397 UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = math::max([\504 UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = math::max([\
398 ({MENU_SEAT_COUNT_FIELD} ?? 0) - array::len($flipped), 0]);505 ({MENU_SEAT_COUNT_FIELD} ?? 0) - array::len($flipped), 0]);
506+ {reverse}
399 RETURN $flipped;507 RETURN $flipped;
400 COMMIT TRANSACTION;"508 COMMIT TRANSACTION;"
401 ))509 ))
402 .bind(("id", booked.id.record()))510 .bind(("id", booked.id.record()))
403 .bind(("menu", booked.menu.record()))511 .bind(("menu", booked.menu.record()))
404- .bind(("now", Timestamp::now()))512+ .bind(("now", Timestamp::now()));
405- .await?513+ let query = match &refund {
406- .check()?;514+ Some((charge, line)) => query
407- // Slots count BEGIN and the LET: the RETURN is slot 3.515+ .bind(("charge", charge.record()))
408- result.take::<Vec<MealBooking>>(3)516+ .bind(("reversal", line.get_id().record()))
517+ .bind(("line", line.clone())),
518+ None => query,
519+ };
520+ let mut result = query.await?.check()?;
521+ result.take::<Vec<MealBooking>>(returned)
409 }522 }
410 .await;523 .await;
411 match attempted {524 match attempted {
@@ -687,9 +800,17 @@ mod tests {
687 created_at: Timestamp::now(),800 created_at: Timestamp::now(),
688 };801 };
689 let place = async |seen| {802 let place = async |seen| {
690- MealBooking::claim_and_place(&menu.record(), cap::UNLIMITED, seen, &row, None, &db)803+ MealBooking::claim_and_place(
691- .await804+ &menu.record(),
692- .unwrap()805+ cap::UNLIMITED,
806+ seen,
807+ &row,
808+ None,
809+ None,
810+ &db,
811+ )
812+ .await
813+ .unwrap()
693 };814 };
694 assert!(815 assert!(
695 matches!(place(seen).await, Claimed::Full),816 matches!(place(seen).await, Claimed::Full),
@@ -795,6 +916,162 @@ mod tests {
795 );916 );
796 }917 }
797 918
919+ /// A cancel that lost its flip may only refund the attempt it was actually
920+ /// cancelling. Driven against the predicate rather than through `cancel`:
921+ /// the row is re-read *inside* the call, so the only way it can disagree
922+ /// with what the flip found is a genuine concurrent write, which no
923+ /// single-process interleaving (and no in-memory engine) can stage.
924+ #[tokio::test]
925+ async fn a_lost_flip_refunds_only_the_attempt_it_released() {
926+ let (db, menu) = menu(None).await;
927+ let (ali, veli) = (UserId::generate(), UserId::generate());
928+ let open = MealCutoff::default();
929+ add_dish(&menu, 1_000, &db).await;
930+
931+ let seen = MealBooking::book(&menu, &ali, &ali, &open, &db)
932+ .await
933+ .unwrap();
934+ let cancelled = seen.clone().cancel(&open, &ali, &db).await.unwrap();
935+ // The seat this cancel released: its own attempt, still cancelled.
936+ assert!(MealBooking::refundable_after_lost_flip(&seen, &cancelled));
937+
938+ // A re-book landed in the window. The row is `booked` again with a live
939+ // charge against it β€” refunding that frees money for a seat that is
940+ // still held, and burns the ledger id its own cancel will need.
941+ let rebooked = MealBooking::book(&menu, &ali, &ali, &open, &db)
942+ .await
943+ .unwrap();
944+ assert_eq!(rebooked.get_attempt(), seen.get_attempt() + 1);
945+ assert!(!MealBooking::refundable_after_lost_flip(&seen, &rebooked));
946+
947+ // Re-booked *and* cancelled again: that cancel appended the reversal
948+ // for its own attempt, and this call has nothing left to heal.
949+ let later = rebooked.cancel(&open, &ali, &db).await.unwrap();
950+ assert!(!MealBooking::refundable_after_lost_flip(&seen, &later));
951+
952+ // And the ordinary lost race β€” another cancel of the same attempt got
953+ // there first β€” still replays the refund, which is what heals a cancel
954+ // cut short between the flip and the ledger line.
955+ let other = MealBooking::book(&menu, &veli, &veli, &open, &db)
956+ .await
957+ .unwrap();
958+ let freed = other.clone().cancel(&open, &veli, &db).await.unwrap();
959+ assert!(MealBooking::refundable_after_lost_flip(&other, &freed));
960+ }
961+
962+ /// The seat may not come back without the money. Driven against
963+ /// [`MealBooking::release_seat`] rather than through `cancel`, because what
964+ /// is under test is precisely what a *crash right after the flip* leaves
965+ /// behind: appended a write later, the reversal is lost with the process,
966+ /// and a re-book then moves the row to the next attempt and locks the
967+ /// `(booking, attempt)` reversal id out for good β€” the charge is
968+ /// unreversible by any route on the API.
969+ #[tokio::test]
970+ async fn the_seat_cannot_be_freed_without_its_refund() {
971+ let (db, menu) = menu(None).await;
972+ let ali = UserId::generate();
973+ let open = MealCutoff::default();
974+ add_dish(&menu, 1_000, &db).await;
975+ let booked = MealBooking::book(&menu, &ali, &ali, &open, &db)
976+ .await
977+ .unwrap();
978+
979+ // The flip alone β€” nothing else runs afterwards, as after a crash.
980+ let freed = MealBooking::release_seat(&booked, &ali, &db)
981+ .await
982+ .unwrap()
983+ .expect("the seat was held, so the flip must take it back");
984+ assert_eq!(freed.get_status(), MealBookingStatus::Cancelled);
985+ assert_eq!(seats(&menu, &db).await, 0);
986+ assert_eq!(
987+ MealLedger::balance_of(&ali, &db).await.unwrap(),
988+ 0,
989+ "the reversal must have committed with the flip, not after it"
990+ );
991+
992+ // And the re-book that used to strand the charge now finds it settled:
993+ // a fresh attempt, billed once more, with the old one squared away.
994+ MealBooking::book(&menu, &ali, &ali, &open, &db)
995+ .await
996+ .unwrap();
997+ assert_eq!(MealLedger::balance_of(&ali, &db).await.unwrap(), -1_000);
998+ }
999+
1000+ /// The seat may not be held without its money. Driven against
1001+ /// [`MealBooking::claim_and_place`] rather than through `book`, because what
1002+ /// is under test is precisely what the gap between the two writes leaves
1003+ /// behind: a cancel landing there finds no charge to reverse, reverses
1004+ /// nothing, and the charge then lands anyway β€” a student holding no seat and
1005+ /// owing money, with the `(booking, attempt)` reversal id burnt for good.
1006+ #[tokio::test]
1007+ async fn the_seat_cannot_be_claimed_without_its_charge() {
1008+ let (db, menu) = menu(None).await;
1009+ let ali = UserId::generate();
1010+ add_dish(&menu, 1_000, &db).await;
1011+ let price = MealLedger::price_snapshot(&menu, &db).await.unwrap();
1012+ let seen = Menu::read(&menu, &db).await.unwrap().unwrap().get_version();
1013+ let row = MealBooking {
1014+ id: MealBookingId::composite(&menu, &ali),
1015+ menu: menu.clone(),
1016+ student: ali.clone(),
1017+ booked_by: ali.clone(),
1018+ status: MealBookingStatus::Booked,
1019+ attempt: 1,
1020+ price_minor: price,
1021+ cancelled_at: None,
1022+ created_at: Timestamp::now(),
1023+ };
1024+ let charge = MealLedger::charge_for(&row, &ali);
1025+ // The claim alone β€” nothing else runs afterwards, as after a crash.
1026+ let place = async || {
1027+ MealBooking::claim_and_place(
1028+ &menu.record(),
1029+ cap::UNLIMITED,
1030+ seen,
1031+ &row,
1032+ price,
1033+ charge.as_ref(),
1034+ &db,
1035+ )
1036+ .await
1037+ .unwrap()
1038+ };
1039+ assert!(matches!(place().await, Claimed::Made(_)));
1040+ assert_eq!(seats(&menu, &db).await, 1);
1041+ assert_eq!(
1042+ MealLedger::balance_of(&ali, &db).await.unwrap(),
1043+ -1_000,
1044+ "the charge must have committed with the claim, not after it"
1045+ );
1046+
1047+ // Replayed: the seat is already held, so the whole transaction rolls
1048+ // back β€” no second seat and, just as importantly, no second charge.
1049+ assert!(matches!(place().await, Claimed::Duplicate));
1050+ assert_eq!(seats(&menu, &db).await, 1);
1051+ assert_eq!(MealLedger::balance_of(&ali, &db).await.unwrap(), -1_000);
1052+ }
1053+
1054+ /// A free menu owes no refund, so the flip must carry no ledger line at all
1055+ /// β€” the branch the reversal's conditional statement adds.
1056+ #[tokio::test]
1057+ async fn a_seat_that_was_never_billed_frees_without_a_line() {
1058+ let (db, menu) = menu(None).await;
1059+ let ali = UserId::generate();
1060+ let booked = MealBooking::book(&menu, &ali, &ali, &MealCutoff::default(), &db)
1061+ .await
1062+ .unwrap();
1063+
1064+ MealBooking::release_seat(&booked, &ali, &db)
1065+ .await
1066+ .unwrap()
1067+ .expect("a free seat is still a seat");
1068+ assert_eq!(seats(&menu, &db).await, 0);
1069+ let (lines, total) = MealLedger::list_for_student(&ali, None, 0, &db)
1070+ .await
1071+ .unwrap();
1072+ assert!(lines.is_empty() && total == 0, "a free seat moves no money");
1073+ }
1074+
798 fn cutoff(minutes: Option<i64>, serving_minute: Option<i64>) -> MealCutoff {1075 fn cutoff(minutes: Option<i64>, serving_minute: Option<i64>) -> MealCutoff {
799 MealCutoff {1076 MealCutoff {
800 minutes,1077 minutes,
src/domain/meal_ledger.rsmodified+76 -49
@@ -26,8 +26,12 @@
26 //! seat taken while the menu was free stays free, because "free" is recorded26 //! seat taken while the menu was free stays free, because "free" is recorded
27 //! on the row rather than inferred from the absence of a charge.27 //! on the row rather than inferred from the absence of a charge.
28 //! - **A cancel appends a `reversal`**, for the charge's exact amount, with28 //! - **A cancel appends a `reversal`**, for the charge's exact amount, with
29-//! `source` pointing at the charge it undoes. The charge row stays. Booking29+//! `source` pointing at the charge it undoes, *in the same transaction as the
30-//! again after a cancel is a *fresh* charge at the then-current price.30+//! flip that frees the seat*. The charge row stays. Booking again after a
31+//! cancel is a *fresh* charge at the then-current price β€” and since every
32+//! line is keyed by the attempt, a reversal that landed a transaction later
33+//! than its flip could be overtaken by that re-book and then never be
34+//! writable at all.
31 //! - **Every booking line is keyed by `(booking, attempt)`.** Both the charge35 //! - **Every booking line is keyed by `(booking, attempt)`.** Both the charge
32 //! and its reversal derive their record id from the seat and the attempt36 //! and its reversal derive their record id from the seat and the attempt
33 //! number, so replaying either writes nothing at all. Money must never37 //! number, so replaying either writes nothing at all. Money must never
@@ -348,31 +352,40 @@ impl MealLedger {
348 recorded_by: &UserId,352 recorded_by: &UserId,
349 db: &Database,353 db: &Database,
350 ) -> Result<(), AppError> {354 ) -> Result<(), AppError> {
351- let Some(amount) = booking.get_price_minor() else {355+ let Some(line) = Self::charge_for(booking, recorded_by) else {
352 return Ok(());356 return Ok(());
353 };357 };
354- Self::append(358+ Self::append(line, db).await?;
355- MealLedger {
356- id: MealLedgerId::for_attempt(
357- booking.get_id(),
358- booking.get_attempt(),
359- MealLedgerKind::Charge,
360- ),
361- student: booking.get_student().clone(),
362- kind: MealLedgerKind::Charge,
363- amount_minor: amount,
364- source: Some(booking.get_id().record()),
365- method: None,
366- note: None,
367- recorded_by: recorded_by.clone(),
368- created_at: Timestamp::now(),
369- },
370- db,
371- )
372- .await?;
373 Ok(())359 Ok(())
374 }360 }
375 361
362+ /// The charge `booking`'s current attempt owes β€” the line
363+ /// [`MealBooking::claim_and_place`] appends inside the very transaction that
364+ /// takes the seat. `None` when the menu was free, which owes no line.
365+ ///
366+ /// Only the row is built here; whether it is already there is a read, and
367+ /// the caller that writes in one transaction has to make it there. Note the
368+ /// attempt has to be settled *before* the SQL runs, which is why the claim
369+ /// mints the number itself rather than letting the revival increment it.
370+ pub(crate) fn charge_for(booking: &MealBooking, recorded_by: &UserId) -> Option<MealLedger> {
371+ let amount = booking.get_price_minor()?;
372+ Some(MealLedger {
373+ id: MealLedgerId::for_attempt(
374+ booking.get_id(),
375+ booking.get_attempt(),
376+ MealLedgerKind::Charge,
377+ ),
378+ student: booking.get_student().clone(),
379+ kind: MealLedgerKind::Charge,
380+ amount_minor: amount,
381+ source: Some(booking.get_id().record()),
382+ method: None,
383+ note: None,
384+ recorded_by: recorded_by.clone(),
385+ created_at: Timestamp::now(),
386+ })
387+ }
388+
376 /// Give the money back for a cancelled `booking`: a new `reversal` line for389 /// Give the money back for a cancelled `booking`: a new `reversal` line for
377 /// the charge's exact amount, pointing at it. The charge is never touched.390 /// the charge's exact amount, pointing at it. The charge is never touched.
378 /// A booking that was never billed (a free menu) reverses nothing, and391 /// A booking that was never billed (a free menu) reverses nothing, and
@@ -380,46 +393,60 @@ impl MealLedger {
380 /// the very charge it undoes, so it can only exist alongside it.393 /// the very charge it undoes, so it can only exist alongside it.
381 ///394 ///
382 /// Keyed by `(booking, attempt)` like the charge, so a retried cancel395 /// Keyed by `(booking, attempt)` like the charge, so a retried cancel
383- /// refunds once. A cancel cut short between the status flip and this396+ /// refunds once. The line normally lands *inside* the flip's own
384- /// reversal is recovered by repeating the cancel β€” which is precisely why397+ /// transaction ([`MealBooking::release_seat`]); this path is what heals a
385- /// [`MealBooking::cancel`] replays this on an already-cancelled row instead398+ /// seat flipped before that was true, and it is why
399+ /// [`MealBooking::cancel`] replays it on an already-cancelled row instead
386 /// of refusing it. Nothing else on the API can append the missing line.400 /// of refusing it. Nothing else on the API can append the missing line.
387 pub async fn reverse_booking(401 pub async fn reverse_booking(
388 booking: &MealBooking,402 booking: &MealBooking,
389 recorded_by: &UserId,403 recorded_by: &UserId,
390 db: &Database,404 db: &Database,
391 ) -> Result<(), AppError> {405 ) -> Result<(), AppError> {
392- let Some(amount) = booking.get_price_minor() else {406+ let Some((charge, line)) = Self::reversal_for(booking, recorded_by) else {
393 return Ok(());407 return Ok(());
394 };408 };
409+ if Self::read(&charge, db).await?.is_none() {
410+ return Ok(());
411+ }
412+ Self::append(line, db).await?;
413+ Ok(())
414+ }
415+
416+ /// The refund `booking`'s current attempt owes, as `(the charge it undoes,
417+ /// the reversal line)` β€” the two ids [`MealBooking::release_seat`] needs to
418+ /// append the money back inside the transaction that frees the seat.
419+ /// `None` when the seat was never billed (a free menu), which owes no line.
420+ ///
421+ /// Only the ids and the row are built here: whether the charge exists is a
422+ /// read, and the caller that writes in one transaction has to make it there
423+ /// rather than a round trip earlier.
424+ pub(crate) fn reversal_for(
425+ booking: &MealBooking,
426+ recorded_by: &UserId,
427+ ) -> Option<(MealLedgerId, MealLedger)> {
428+ let amount = booking.get_price_minor()?;
395 let charge = MealLedgerId::for_attempt(429 let charge = MealLedgerId::for_attempt(
396 booking.get_id(),430 booking.get_id(),
397 booking.get_attempt(),431 booking.get_attempt(),
398 MealLedgerKind::Charge,432 MealLedgerKind::Charge,
399 );433 );
400- if Self::read(&charge, db).await?.is_none() {434+ let line = MealLedger {
401- return Ok(());435+ id: MealLedgerId::for_attempt(
402- }436+ booking.get_id(),
403- Self::append(437+ booking.get_attempt(),
404- MealLedger {438+ MealLedgerKind::Reversal,
405- id: MealLedgerId::for_attempt(439+ ),
406- booking.get_id(),440+ student: booking.get_student().clone(),
407- booking.get_attempt(),441+ kind: MealLedgerKind::Reversal,
408- MealLedgerKind::Reversal,442+ amount_minor: amount,
409- ),443+ source: Some(charge.record()),
410- student: booking.get_student().clone(),444+ method: None,
411- kind: MealLedgerKind::Reversal,445+ note: None,
412- amount_minor: amount,446+ recorded_by: recorded_by.clone(),
413- source: Some(charge.record()),447+ created_at: Timestamp::now(),
414- method: None,448+ };
415- note: None,449+ Some((charge, line))
416- recorded_by: recorded_by.clone(),
417- created_at: Timestamp::now(),
418- },
419- db,
420- )
421- .await?;
422- Ok(())
423 }450 }
424 451
425 /// Money in: a payment received, or an opening balance.452 /// Money in: a payment received, or an opening balance.
src/domain/menu.rsmodified+136 -19
@@ -14,13 +14,11 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
14 use tokio::sync::Mutex;14 use tokio::sync::Mutex;
15 15
16 use crate::constant::{16 use crate::constant::{
17- MAX_MENU_CAPACITY, MENU_SEAT_COUNT_FIELD, MENU_TABLE, MENU_VERSION_FIELD, REF_COUNT_FIELD,17+ MAX_MENU_CAPACITY, MEAL_ATTENDANCE_TABLE, MENU_DISH_TABLE, MENU_SEAT_COUNT_FIELD, MENU_TABLE,
18- SLOT_REF_TABLE,18+ MENU_VERSION_FIELD, REF_COUNT_FIELD, SLOT_REF_TABLE,
19 };19 };
20-use crate::database::{Database, transaction_with_retry};20+use crate::database::{Database, transaction_with_retry, write_with_retry};
21 use crate::domain::cap;21 use crate::domain::cap;
22-use crate::domain::field_update::FieldUpdate;
23-use crate::domain::menu_dish::MenuDish;
24 use crate::domain::page::PagedList;22 use crate::domain::page::PagedList;
25 use crate::domain::settings::MealSlotDef;23 use crate::domain::settings::MealSlotDef;
26 use crate::domain::timestamp::Timestamp;24 use crate::domain::timestamp::Timestamp;
@@ -40,7 +38,13 @@ use crate::error::{AppError, ValidationError};
40 // backfill; the ceiling is 51 dishes on a menu, not money or a seat, so it was38 // backfill; the ceiling is 51 dishes on a menu, not money or a seat, so it was
41 // not worth the column here.39 // not worth the column here.
42 ///40 ///
43-/// A leaf: nothing held under it takes another lock.41+/// **A leaf**: every dish write held under it moves the menu's revision inside
42+/// its *own* transaction ([`MenuDish::bump_menu_and_write`](crate::domain::menu_dish)),
43+/// so no path under this lock reaches `cap`'s counter lock any more β€” it did
44+/// while the bump was a `cap` call of its own. Should one ever need both, the
45+/// order is `MENU_LOCK` β†’ `CLAIM_LOCK` and nothing may take this lock while
46+/// holding a counter lock: that is the invariant a new caller must keep, and it
47+/// is what would keep the pair deadlock-free.
44 pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(());48 pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(());
45 49
46 /// The reference counter for one meal slot β€” how many menus are published under50 /// The reference counter for one meal slot β€” how many menus are published under
@@ -138,6 +142,22 @@ impl MenuSlot {
138 reason: "not one of the school's meal slots (see GET /settings)",142 reason: "not one of the school's meal slots (see GET /settings)",
139 });143 });
140 }144 }
145+ // The slot goes verbatim into the menu's record id ([`MenuId::for_slot`]),
146+ // and that id is a URL path segment: a slot named `a/b` publishes a menu
147+ // at `/meals/menus/2026-09-14_a/b`, which no route can ever address
148+ // again β€” the menu could not be read, edited or deleted.
149+ // `MealSlotDef::try_new` refuses the same characters, so no school can
150+ // define such a slot; this is the second gate, and it is what a
151+ // settings row written before that rule runs into.
152+ if value
153+ .chars()
154+ .any(|c| matches!(c, '/' | '\\' | '?' | '#' | '%'))
155+ {
156+ return Err(ValidationError::Invalid {
157+ field: "slot",
158+ reason: "meal slot names used for menus must not contain / \\ ? # or %",
159+ });
160+ }
141 Ok(Self(value.to_string()))161 Ok(Self(value.to_string()))
142 }162 }
143 163
@@ -297,21 +317,40 @@ impl Menu {
297 /// because moving a published menu to another day is a different menu.317 /// because moving a published menu to another day is a different menu.
298 /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped.318 /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped.
299 ///319 ///
300- /// Moving the cap moves the revision first ([`cap::bump`]): a booking that320+ /// The revision moves **in the same statement** as the cap, indivisibly: a
301- /// read the old cap must not claim its seat against it, or a shrink321+ /// booking claims its seat against the revision
302- /// over-admits by exactly the bookings in flight.322+ /// it read the cap at, so a shrink that bumped in a query of its own left a
323+ /// window where the row carried the *new* revision and the *old* cap β€” and
324+ /// a booking arriving there passes a CAS meant to refuse it, over-admitting
325+ /// by exactly the seats in flight.
303 pub async fn update(326 pub async fn update(
304 self,327 self,
305 capacity: Option<Option<i64>>,328 capacity: Option<Option<i64>>,
306 db: &Database,329 db: &Database,
307 ) -> Result<Menu, AppError> {330 ) -> Result<Menu, AppError> {
308- if capacity.is_some() {331+ let Some(capacity) = capacity else {
309- cap::bump(&self.id.record(), MENU_VERSION_FIELD, db).await?;332+ // A PATCH carrying nothing writes nothing and bumps nothing: no
310- }333+ // booking's price or cap has moved, so none owes a re-read.
311- FieldUpdate::new(self.id.record())334+ return Self::read(&self.id, db).await?.ok_or(AppError::NotFound);
312- .set("capacity", capacity)335+ };
313- .run::<Menu>(db)336+ let sql = format!(
314- .await337+ "UPDATE $id SET capacity = $capacity, \
338+ {MENU_VERSION_FIELD} = ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN AFTER"
339+ );
340+ // One counter write in flight at a time, like every other one.
341+ let _guard = cap::counter_lock().await;
342+ write_with_retry::<Menu>(
343+ db,
344+ &sql,
345+ &[
346+ ("id".into(), self.id.record().into_value()),
347+ ("capacity".into(), capacity.into_value()),
348+ ],
349+ )
350+ .await?
351+ .into_iter()
352+ .next()
353+ .ok_or(AppError::NotFound)
315 }354 }
316 355
317 /// Delete the menu and the dishes on it β€” a dish has no meaning without356 /// Delete the menu and the dishes on it β€” a dish has no meaning without
@@ -330,8 +369,22 @@ impl Menu {
330 /// in a query of its own, a crash between the two left the slot counted by369 /// in a query of its own, a crash between the two left the slot counted by
331 /// a menu that no longer exists: a slot nobody can retire.370 /// a menu that no longer exists: a slot nobody can retire.
332 ///371 ///
333- /// The dishes go *after* the row: their cascade must not run for a delete372+ /// The marks go in that same `FOR`, for a sharper reason than tidiness:
334- /// the counter refused.373+ /// [`MenuId::for_slot`] is deterministic, so republishing the same day and
374+ /// slot mints the *same* record id. A mark left behind would come back as a
375+ /// mark on the new menu β€” the kitchen reading "served" for a student who
376+ /// never came β€” and until then the student's own report cites a menu that
377+ /// is gone. Attendance carries no money and no counter, so it is safe to
378+ /// drop; cancelled *bookings* deliberately stay, because their `attempt`
379+ /// counter is what keeps the ledger's `(booking, attempt)` keys unique. Cut
380+ /// those and a re-book on a republished menu would reuse a charge id the
381+ /// ledger already holds, and the append (idempotent by design) would bill
382+ /// the seat nothing.
383+ ///
384+ /// The dishes ride in that `FOR` too, and for the same reason as the marks:
385+ /// run after the transaction committed, a crash between the two orphaned
386+ /// them on a record id republishing the day and slot mints again β€” a new
387+ /// menu serving (and pricing) the old one's food.
335 pub async fn delete(self, db: &Database) -> Result<Menu, AppError> {388 pub async fn delete(self, db: &Database) -> Result<Menu, AppError> {
336 let sql = format!(389 let sql = format!(
337 "BEGIN TRANSACTION;390 "BEGIN TRANSACTION;
@@ -339,6 +392,8 @@ impl Menu {
339 FOR $row IN ($gone ?? []) {{392 FOR $row IN ($gone ?? []) {{
340 UPSERT $counter SET {REF_COUNT_FIELD} = \393 UPSERT $counter SET {REF_COUNT_FIELD} = \
341 math::max([({REF_COUNT_FIELD} ?? 0) - 1, 0]);394 math::max([({REF_COUNT_FIELD} ?? 0) - 1, 0]);
395+ DELETE {MEAL_ATTENDANCE_TABLE} WHERE menu = $id;
396+ DELETE {MENU_DISH_TABLE} WHERE menu = $id;
342 }};397 }};
343 RETURN $gone;398 RETURN $gone;
344 COMMIT TRANSACTION;"399 COMMIT TRANSACTION;"
@@ -368,7 +423,6 @@ impl Menu {
368 None => AppError::NotFound,423 None => AppError::NotFound,
369 });424 });
370 };425 };
371- MenuDish::delete_for_menu(&self.id, db).await?;
372 Ok(deleted)426 Ok(deleted)
373 }427 }
374 }428 }
@@ -403,6 +457,40 @@ mod tests {
403 assert!(MenuSlot::try_new("lunch", &[]).is_err());457 assert!(MenuSlot::try_new("lunch", &[]).is_err());
404 }458 }
405 459
460+ /// The slot becomes the menu's record id, and the id becomes a URL path
461+ /// segment: a name carrying a separator publishes a menu at an address no
462+ /// route can match again. `MealSlotDef::try_new` refuses the name too, so
463+ /// no school can define such a slot any more β€” this gate is what a settings
464+ /// row written *before* that rule still runs into. Ordinary names β€” spaces
465+ /// and Turkish letters included β€” are untouched; they percent-encode into
466+ /// one segment as they always have.
467+ #[test]
468+ fn a_slot_name_that_would_break_the_menu_url_is_refused() {
469+ // The only shape that can still carry such a name: a stored slot,
470+ // decoded rather than constructed.
471+ use surrealdb::types::Value;
472+ let stale = |name: &str| {
473+ let Value::Object(mut object) =
474+ MealSlotDef::try_new("lunch", None).unwrap().into_value()
475+ else {
476+ panic!("a slot must encode as an object");
477+ };
478+ object.insert("name".to_string(), Value::String(name.into()));
479+ vec![MealSlotDef::from_value(Value::Object(object)).unwrap()]
480+ };
481+ let named = |name: &str| {
482+ MenuSlot::try_new(name, &stale(name))
483+ .map(|slot| MenuId::for_slot(&MenuDate::try_new("2026-09-14").unwrap(), &slot))
484+ };
485+ for broken in ["a/b", "a\\b", "a?b", "a#b", "a%b"] {
486+ assert!(named(broken).is_err(), "{broken} must not become an id");
487+ }
488+ assert_eq!(
489+ named("âğle yemeği").unwrap().key(),
490+ "2026-09-14_âğle yemeği"
491+ );
492+ }
493+
406 #[test]494 #[test]
407 fn capacity_is_bounded_but_optional() {495 fn capacity_is_bounded_but_optional() {
408 assert!(validate_capacity(None).is_ok());496 assert!(validate_capacity(None).is_ok());
@@ -541,6 +629,35 @@ mod tests {
541 assert_eq!(refs(&db).await, 0);629 assert_eq!(refs(&db).await, 0);
542 }630 }
543 631
632+ /// The cap and the revision are one write. Nothing single-process can
633+ /// observe the torn state the two-query version left (a bumped revision
634+ /// over a cap that had not moved yet), so what is pinned here is the pair:
635+ /// the revision steps exactly once per cap move, and never for a PATCH that
636+ /// carried no cap at all β€” a booking re-reads only when something it priced
637+ /// itself against actually changed.
638+ #[tokio::test]
639+ async fn the_cap_and_the_revision_move_together_or_not_at_all() {
640+ let db = school().await;
641+ let menu = publish("2026-08-05", &db).await.unwrap();
642+ let id = menu.get_id().clone();
643+ assert_eq!(menu.get_version(), 0);
644+
645+ let capped = menu.update(Some(Some(5)), &db).await.unwrap();
646+ assert_eq!(capped.get_capacity(), Some(5));
647+ assert_eq!(capped.get_version(), 1);
648+ // Re-read out of the store, never off the return value.
649+ let stored = Menu::read(&id, &db).await.unwrap().unwrap();
650+ assert_eq!((stored.get_capacity(), stored.get_version()), (Some(5), 1));
651+
652+ // An empty PATCH moves neither, and reads the row back unchanged.
653+ let same = stored.update(None, &db).await.unwrap();
654+ assert_eq!((same.get_capacity(), same.get_version()), (Some(5), 1));
655+
656+ // Clearing the cap is a move like any other.
657+ let uncapped = same.update(Some(None), &db).await.unwrap();
658+ assert_eq!((uncapped.get_capacity(), uncapped.get_version()), (None, 2));
659+ }
660+
544 #[tokio::test]661 #[tokio::test]
545 async fn deleting_hands_the_reference_back_in_the_same_step() {662 async fn deleting_hands_the_reference_back_in_the_same_step() {
546 let db = school().await;663 let db = school().await;
src/domain/menu_dish.rsmodified+99 -30
@@ -7,7 +7,7 @@
7 7
8 use std::sync::LazyLock;8 use std::sync::LazyLock;
9 9
10-use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};10+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value};
11 use ulid::Generator;11 use ulid::Generator;
12 12
13 use crate::constant::{13 use crate::constant::{
@@ -15,8 +15,6 @@ use crate::constant::{
15 MENU_DISH_TABLE, MENU_VERSION_FIELD,15 MENU_DISH_TABLE, MENU_VERSION_FIELD,
16 };16 };
17 use crate::database::{Database, transaction_with_retry};17 use crate::database::{Database, transaction_with_retry};
18-use crate::domain::cap;
19-use crate::domain::field_update::FieldUpdate;
20 use crate::domain::menu::MenuId;18 use crate::domain::menu::MenuId;
21 use crate::domain::timestamp::Timestamp;19 use crate::domain::timestamp::Timestamp;
22 use crate::error::{AppError, ValidationError};20 use crate::error::{AppError, ValidationError};
@@ -287,21 +285,74 @@ impl MenuDish {
287 Ok(Self::list_for_menu(menu, db).await?.len())285 Ok(Self::list_for_menu(menu, db).await?.len())
288 }286 }
289 287
290- /// What a seat on this dish's menu costs changed, so the menu is now at a288+ /// Move the menu's revision **and** run `statement`, in one transaction.
291- /// new revision and any booking that priced itself against the old one has289+ ///
292- /// to re-read. Called *before* the write, never after: bumped-and-not-written290+ /// What a seat on this dish's menu costs is about to change, so any booking
293- /// costs a booking one retry, written-and-not-bumped bills a seat a price291+ /// that priced itself against the old revision has to re-read. The bump
294- /// the menu no longer carries.292+ /// cannot be a query of its own: in the gap the menu row carries the *new*
293+ /// revision with the *old* price, and a booking reading there passes the
294+ /// very CAS that exists to refuse it β€” a seat billed a price the menu had
295+ /// already left, or admitted past a capacity that had already shrunk.
296+ ///
297+ /// The bump also makes the menu's existence part of the write ([`Self::create`]
298+ /// leans on the same thing): the `UPDATE` matches nothing once the menu row
299+ /// is deleted, and a delete racing this one touches the very key this
300+ /// transaction writes, so the two cannot both commit.
295 ///301 ///
296 /// Deliberately on every dish write, not only the ones that move302 /// Deliberately on every dish write, not only the ones that move
297 /// `price_minor`: a re-tagged dish is cheap to re-read, and a rule that303 /// `price_minor`: a re-tagged dish is cheap to re-read, and a rule that
298 /// applies to every write cannot be forgotten by the next field added here.304 /// applies to every write cannot be forgotten by the next field added here.
299- async fn bump_menu(menu: &MenuId, db: &Database) -> Result<(), AppError> {305+ ///
300- cap::bump(&menu.record(), MENU_VERSION_FIELD, db).await306+ /// Admissible for [`transaction_with_retry`]: every statement is an
307+ /// `UPDATE`, a `DELETE`, a `SELECT`, an `IF`/`THROW` or a `RETURN`, and none
308+ /// of those can answer "already exists" β€” a lost round wrote nothing, so
309+ /// re-sending it is the recovery.
310+ async fn bump_menu_and_write(
311+ menu: &MenuId,
312+ statement: &str,
313+ mut bindings: Vec<(String, Value)>,
314+ db: &Database,
315+ ) -> Result<Option<MenuDish>, AppError> {
316+ bindings.push(("menu".into(), menu.record().into_value()));
317+ let (mut result, mut errors) = transaction_with_retry(
318+ db,
319+ &format!(
320+ "BEGIN TRANSACTION;
321+ LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \
322+ ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id);
323+ IF array::len($bumped) = 0 {{ THROW 'no_menu' }};
324+ LET $row = ({statement});
325+ RETURN $row;
326+ COMMIT TRANSACTION;"
327+ ),
328+ &bindings,
329+ &["no_menu"],
330+ )
331+ .await?;
332+ // An aborted transaction errors *every* slot, most with a generic "not
333+ // executed" β€” only the THROW's own slot names the reason.
334+ if errors
335+ .values()
336+ .any(|error| error.to_string().contains("no_menu"))
337+ {
338+ return Err(AppError::NotFound);
339+ }
340+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
341+ return Err(error.into());
342+ }
343+ // Slots count BEGIN, the LET, the IF and the second LET: the RETURN is 4.
344+ Ok(result.take::<Vec<MenuDish>>(4)?.into_iter().next())
301 }345 }
302 346
303 /// Write only the fields the PATCH carried. `description` is nullable, so347 /// Write only the fields the PATCH carried. `description` is nullable, so
304 /// it takes the three-way shape: absent = keep, `Some(None)` = clear.348 /// it takes the three-way shape: absent = keep, `Some(None)` = clear.
349+ ///
350+ /// The `SET` is built here rather than by
351+ /// [`FieldUpdate`](crate::domain::field_update::FieldUpdate) because the
352+ /// revision bump lands on *another* row and has to share this write's
353+ /// transaction; the field-by-field scoping β€” an omitted field is never
354+ /// written, so a concurrent PATCH of another one is not reverted β€” is the
355+ /// same rule, spelled out.
305 pub async fn update(356 pub async fn update(
306 self,357 self,
307 name: Option<DishName>,358 name: Option<DishName>,
@@ -310,29 +361,47 @@ impl MenuDish {
310 tags: Option<DishTags>,361 tags: Option<DishTags>,
311 db: &Database,362 db: &Database,
312 ) -> Result<MenuDish, AppError> {363 ) -> Result<MenuDish, AppError> {
313- Self::bump_menu(&self.menu, db).await?;364+ let mut sets: Vec<&str> = Vec::new();
314- FieldUpdate::new(self.id.record())365+ let mut bindings: Vec<(String, Value)> = vec![("id".into(), self.id.record().into_value())];
315- .set("name", name)366+ let mut set = |field: &'static str, value: Option<Value>| {
316- .set("description", description)367+ if let Some(value) = value {
317- .set("price_minor", price_minor)368+ sets.push(field);
318- .set("tags", tags)369+ bindings.push((field.into(), value));
319- .run::<MenuDish>(db)370+ }
320- .await371+ };
372+ set("name", name.map(SurrealValue::into_value));
373+ set("description", description.map(SurrealValue::into_value));
374+ set("price_minor", price_minor.map(SurrealValue::into_value));
375+ set("tags", tags.map(SurrealValue::into_value));
376+ // A PATCH that carried nothing writes nothing and reads the row back,
377+ // exactly as `FieldUpdate` answers one β€” but it still moves the
378+ // revision, because "every dish write bumps" is the rule a caller can
379+ // rely on without knowing which fields were on the wire.
380+ let statement = if sets.is_empty() {
381+ "SELECT * FROM $id".to_string()
382+ } else {
383+ format!(
384+ "UPDATE $id SET {} RETURN AFTER",
385+ sets.iter()
386+ .map(|field| format!("{field} = ${field}"))
387+ .collect::<Vec<_>>()
388+ .join(", ")
389+ )
390+ };
391+ Self::bump_menu_and_write(&self.menu, &statement, bindings, db)
392+ .await?
393+ .ok_or(AppError::NotFound)
321 }394 }
322 395
323 pub async fn delete(self, db: &Database) -> Result<MenuDish, AppError> {396 pub async fn delete(self, db: &Database) -> Result<MenuDish, AppError> {
324- Self::bump_menu(&self.menu, db).await?;397+ Self::bump_menu_and_write(
325- let deleted: Option<MenuDish> = db.delete(self.id.record()).await?;398+ &self.menu,
326- deleted.ok_or(AppError::NotFound)399+ "DELETE $id RETURN BEFORE",
327- }400+ vec![("id".into(), self.id.record().into_value())],
328-401+ db,
329- /// Drop every dish on a menu β€” the menu delete's cascade.402+ )
330- pub async fn delete_for_menu(menu: &MenuId, db: &Database) -> Result<(), AppError> {403+ .await?
331- db.query("DELETE menu_dish WHERE menu = $menu")404+ .ok_or(AppError::NotFound)
332- .bind(("menu", menu.record()))
333- .await?
334- .check()?;
335- Ok(())
336 }405 }
337 }406 }
338 407
src/domain/registration.rsmodified+15 -6
@@ -67,9 +67,12 @@ impl Registration {
67 /// cap is set and every seat is taken. Someone already listed gets their67 /// cap is set and every seat is taken. Someone already listed gets their
68 /// existing row back untouched β€” a true no-op that never counts against68 /// existing row back untouched β€” a true no-op that never counts against
69 /// the cap and never rewrites who placed them. The seat is taken by69 /// the cap and never rewrites who placed them. The seat is taken by
70- /// [`cap::claim`] on the event row β€” an atomic single-record conditional70+ /// [`cap::claim_live_and_create`] on the event row β€” an atomic single-record
71- /// write, so neither a racing registration nor a concurrent71+ /// conditional write that reads `audience.capacity` off that same row as it
72- /// capacity/audience/schedule PATCH can over-admit.72+ /// decides, so neither a racing registration nor a concurrent PATCH
73+ /// *lowering* the capacity can over-admit. Bound as a number instead, the
74+ /// snapshot below would admit every request already in flight when the
75+ /// lower cap landed.
73 pub async fn register(76 pub async fn register(
74 event: &EventId,77 event: &EventId,
75 user: &UserId,78 user: &UserId,
@@ -79,7 +82,9 @@ impl Registration {
79 if let Some(existing) = Self::read_for_user(event, user, db).await? {82 if let Some(existing) = Self::read_for_user(event, user, db).await? {
80 return Ok(existing);83 return Ok(existing);
81 }84 }
82- let capacity = Event::read(event, db)85+ // Read for its refusals only β€” the audience kind and the closing time.
86+ // The seat count itself is re-read by the claim.
87+ Event::read(event, db)
83 .await?88 .await?
84 .ok_or(AppError::NotFound)?89 .ok_or(AppError::NotFound)?
85 .registration_capacity()?;90 .registration_capacity()?;
@@ -89,10 +94,14 @@ impl Registration {
89 user: user.clone(),94 user: user.clone(),
90 registered_by: registered_by.clone(),95 registered_by: registered_by.clone(),
91 };96 };
92- match cap::claim_and_create(97+ match cap::claim_live_and_create(
93 &event.record(),98 &event.record(),
94 REGISTRATION_COUNT_FIELD,99 REGISTRATION_COUNT_FIELD,
95- capacity.unwrap_or(cap::UNLIMITED),100+ // An uncapped registration list stores no `capacity` key at all
101+ // (SurrealDB drops a `NONE`-valued object key), so the coalesce is
102+ // what "unlimited" reads as.
103+ "audience.capacity ?? $num",
104+ cap::UNLIMITED,
96 &registration.id.record(),105 &registration.id.record(),
97 &registration,106 &registration,
98 db,107 db,
src/domain/settings.rsmodified+60 -0
@@ -12,6 +12,7 @@
12 //! existing rows, and `UPDATE` re-validates whole records).12 //! existing rows, and `UPDATE` re-validates whole records).
13 13
14 use surrealdb::types::{RecordId, SurrealValue};14 use surrealdb::types::{RecordId, SurrealValue};
15+use tokio::sync::Mutex;
15 16
16 use crate::constant::{17 use crate::constant::{
17 DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_DIETARY_TAGS,18 DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_DIETARY_TAGS,
@@ -27,6 +28,32 @@ use crate::database::Database;
27 use crate::domain::text_fold;28 use crate::domain::text_fold;
28 use crate::error::{AppError, ValidationError};29 use crate::error::{AppError, ValidationError};
29 30
31+/// One settings edit at a time, over the whole process.
32+///
33+/// A list edit is a **pair** of writes, and the pair is the guard: every name
34+/// the edit drops is retired on its reference counter first (which refuses
35+/// every later claim), and only then is the list itself committed with a
36+/// compare-and-set against the snapshot the removals were judged from. Neither
37+/// write can be made to cover the other. Both retirement and un-retirement are
38+/// *idempotent*, so a rival that decided the same removal against the same
39+/// snapshot is told "already retired" and records no rollback β€” and when it is
40+/// that rival's save that wins the compare-and-set, the attempt which really
41+/// flipped the bit rolls it back, leaving the name off the stored list with a
42+/// counter reading "in service": gradable again, and unremovable for good once
43+/// a mark lands. No per-name bit can close that, because `Unchanged` has
44+/// erased which attempt owns the flip.
45+///
46+/// So the pair is serialized instead. Every writer of the singleton goes
47+/// through `PATCH /settings`, and the deployment runs one replica by contract
48+/// (stop-the-world upgrades), so process-wide is deployment-wide here β€” the
49+/// same argument [`crate::domain::cap`]'s own lock makes for `retire_name`'s
50+/// two statements, one level up. The compare-and-set stays: it is what keeps a
51+/// crashed or rolled-back attempt from writing a list nobody merged.
52+///
53+/// **Lock order:** `SETTINGS_LOCK` β†’ `cap`'s `CLAIM_LOCK`, never the reverse β€”
54+/// the retirements are taken while this is held.
55+pub(crate) static SETTINGS_LOCK: Mutex<()> = Mutex::const_new(());
56+
30 /// One exam kind the school runs (`"midterm"`, `"oral"`, …) with its weight:57 /// One exam kind the school runs (`"midterm"`, `"oral"`, …) with its weight:
31 /// how many times an exam of that kind counts into its course's average.58 /// how many times an exam of that kind counts into its course's average.
32 /// Weight lives here, not on the exam β€” reweighting a kind reweights every59 /// Weight lives here, not on the exam β€” reweighting a kind reweights every
@@ -86,6 +113,24 @@ pub struct MealSlotDef {
86 113
87 impl MealSlotDef {114 impl MealSlotDef {
88 pub fn try_new(name: &str, serving_minute: Option<i64>) -> Result<Self, ValidationError> {115 pub fn try_new(name: &str, serving_minute: Option<i64>) -> Result<Self, ValidationError> {
116+ Self::build(name, serving_minute, false)
117+ }
118+
119+ /// [`Self::try_new`] for a name the stored list *already* carries.
120+ ///
121+ /// The URL-safety rule below is younger than the lists it validates, and
122+ /// `PATCH /settings` re-validates the whole submitted list β€” so a school
123+ /// that stored a slot named `a/b` before the rule existed could never edit
124+ /// `meal_slots` again: re-sending the name is a 400, and dropping it is a
125+ /// 409 the moment a menu was published under it. Grandfathering a name the
126+ /// row already holds unwedges the rest of the list while leaving the rule
127+ /// in full force for every *new* name β€” the stored one is exactly as
128+ /// unusable as it already was, and dropping it stays the only way out.
129+ pub fn try_kept(name: &str, serving_minute: Option<i64>) -> Result<Self, ValidationError> {
130+ Self::build(name, serving_minute, true)
131+ }
132+
133+ fn build(name: &str, serving_minute: Option<i64>, kept: bool) -> Result<Self, ValidationError> {
89 let name = name.trim();134 let name = name.trim();
90 if name.is_empty() || name.chars().count() > MAX_SETTINGS_ITEM_LEN {135 if name.is_empty() || name.chars().count() > MAX_SETTINGS_ITEM_LEN {
91 return Err(ValidationError::Invalid {136 return Err(ValidationError::Invalid {
@@ -93,6 +138,21 @@ impl MealSlotDef {
93 reason: "slot names must be 1 to 50 characters",138 reason: "slot names must be 1 to 50 characters",
94 });139 });
95 }140 }
141+ // The name goes verbatim into a menu's record id, and that id is a URL
142+ // path segment: a slot named `a/b` would define a slot no menu can ever
143+ // be published under (`MenuSlot::try_new` refuses the same characters,
144+ // at the one place a name becomes an id). Refusing it here too is what
145+ // keeps the settings from offering a slot the canteen cannot use.
146+ if !kept
147+ && name
148+ .chars()
149+ .any(|c| matches!(c, '/' | '\\' | '?' | '#' | '%'))
150+ {
151+ return Err(ValidationError::Invalid {
152+ field: "meal_slots",
153+ reason: "meal slot names used for menus must not contain / \\ ? # or %",
154+ });
155+ }
96 if let Some(minute) = serving_minute {156 if let Some(minute) = serving_minute {
97 in_range(157 in_range(
98 "meal_slots",158 "meal_slots",
src/lib.rsmodified+4 -4
@@ -36,7 +36,7 @@ use crate::state::AppState;
36 info(36 info(
37 title = "Hezarfen Backend API",37 title = "Hezarfen Backend API",
38 version = env!("CARGO_PKG_VERSION"),38 version = env!("CARGO_PKG_VERSION"),
39- description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents β€” stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/archive/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images β€” an illustration on any question, and per-option pictures on choice questions; students can attach an answer drawing to any question in their attempt. Enrollment, exam-sitting, roll call, and marks are student-only β€” staff run them, they don't take part. Every event carries an audience β€” the whole school, one role, a course's enrollment, or a registration list β€” that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds β€” `course` (a regular taught course), `study` (a supervised study session β€” etΓΌt), and `club` (a student club β€” kulΓΌp) β€” may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) β€” an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Students can also be grouped into classes (şube β€” a `9-A`), which are bulk enrollment rather than a second kind of membership: attaching a course to a class enrolls its whole roster, adding a member enrolls them into every course the class already carries, and what gets written are ordinary enrollment rows tagged with the class that pumped them (untagged = placed by hand, and a hand-placed row is never adopted, never swept). An attach or a member-add that any target course has no seat for is refused whole (409 naming that course), removing a member or detaching a course takes back only the rows that class pumped β€” re-tagging a row a second class still claims instead of dropping it β€” and a class still holding members or courses refuses deletion. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. Courses also hand out homework: teacher-assigned per course to the whole course or a named subset the unnamed never even see (404s, no existence leak), subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark β€” the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences β€” theme (`light`/`dark`), language (`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` β€” any hex, not a fixed palette) β€” self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports β€” and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem β€” same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it β€” rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it β€” text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze β€” and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. Teachers keep an **appointment calendar**: a teacher+ publishes availability slots (one-off, or repeating weekly up to an `until` date as a series that deletes as one), and students and parents book a slot with a reason β€” the booking lands `pending` until the teacher approves it, rejects it, or counter-proposes another time (which sends it back to `pending` for the requester to accept or decline); the requester may cancel until the meeting starts β€” a teacher ends a booking by rejecting it, or by counter-proposing and then rejecting an approved one β€” one live booking holds a slot, a teacher's published windows may not overlap each other (`409`, half-open, so back-to-back slots are fine), and no approved meeting may overlap another for the teacher or the requester. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` β€” transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope β€” paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count. Every fixed validation bound β€” field lengths, numeric ranges, and the closed value sets (roles, course kinds, exam and question kinds, homework statuses, uploadable image types) β€” is published at `GET /limits` (no auth, cache for the session), so a client validates against the server's own constants instead of a hard-coded copy that drifts. It also reports this server's live rate-limit tiers, so a client learns its request budget instead of discovering it by collecting a `429`, and it keeps answering while the database is down β€” a client booting against a degraded backend still gets the contract.",39+ description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents β€” stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/archive/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images β€” an illustration on any question, and per-option pictures on choice questions; students can attach an answer drawing to any question in their attempt. Enrollment, exam-sitting, roll call, and marks are student-only β€” staff run them, they don't take part. Every event carries an audience β€” the whole school, one role, a course's enrollment, or a registration list β€” that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds β€” `course` (a regular taught course), `study` (a supervised study session β€” etΓΌt), and `club` (a student club β€” kulΓΌp) β€” may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) β€” an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Students can also be grouped into classes (şube β€” a `9-A`), which are bulk enrollment rather than a second kind of membership: attaching a course to a class enrolls its whole roster, adding a member enrolls them into every course the class already carries, and what gets written are ordinary enrollment rows tagged with the class that pumped them (that tag rides out as the enrollment response's `source`; `null` = placed by hand, and a hand-placed row is never adopted, never swept β€” enrolling a pumped student by hand clears the tag, the mirror of a manual unenroll winning permanently). An attach or a member-add that any target course has no seat for is refused whole (409 naming that course), as is one whose class already holds `max_class_members` students or `max_class_courses` courses (200 and 50: each add writes one enrollment per row on the other axis in a single transaction, so each ceiling is the bound on the other's write loop) or one whose class carries a link to a course that no longer exists (409 naming it β€” detach that link, no capacity will help); removing a member or detaching a course takes back only the rows that class pumped β€” re-tagging a row a second class still claims instead of dropping it β€” and a class still holding members or courses refuses deletion. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. Courses also hand out homework: teacher-assigned per course to the whole course or a named subset the unnamed never even see (404s, no existence leak), subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark β€” the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences β€” theme (`light`/`dark`), language (`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` β€” any hex, not a fixed palette) β€” self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports β€” and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem β€” same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it β€” rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it β€” text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze β€” and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. Teachers keep an **appointment calendar**: a teacher+ publishes availability slots (one-off, or repeating weekly up to an `until` date as a series that deletes as one), and students and parents book a slot with a reason β€” the booking lands `pending` until the teacher approves it, rejects it, or counter-proposes another time (which sends it back to `pending` for the requester to accept or decline); the requester may cancel until the meeting starts β€” a teacher ends a booking by rejecting it, or by counter-proposing and then rejecting an approved one β€” one live booking holds a slot, a teacher's published windows may not overlap each other (`409`, half-open, so back-to-back slots are fine), and no approved meeting may overlap another for the teacher or the requester. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` β€” transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope β€” paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count. Every fixed validation bound β€” field lengths, numeric ranges, and the closed value sets (roles, course kinds, exam and question kinds, homework statuses, uploadable image types) β€” is published at `GET /limits` (no auth, cache for the session), so a client validates against the server's own constants instead of a hard-coded copy that drifts. It also reports this server's live rate-limit tiers, so a client learns its request budget instead of discovering it by collecting a `429`, and it keeps answering while the database is down β€” a client booting against a degraded backend still gets the contract.",
40 ),40 ),
41 modifiers(&SecurityAddon),41 modifiers(&SecurityAddon),
42 tags(42 tags(
@@ -58,13 +58,13 @@ use crate::state::AppState;
58 (name = "bank", description = "The question bank: reusable question templates, **private by default**. A template is visible to its owner (and admins) alone until its owner explicitly publishes it by `PATCH`ing `visibility` to `school`, at which point every teacher+ sees it β€” saving a question to the bank must never broadcast its `correct` answer key as a side effect. A template the caller may not see is a `404` on every route, never a `403` (a 403 would confirm it exists). A teacher+ reads what they can see (`GET /bank-questions`: `?subject=` origin filter, `?owner=` (a user id or `me`), `?q=` text search, `?visibility=private|school` β€” the last narrows the caller's own view and never widens it, so `private` means \"my drafts\", never another teacher's) and instantiates any visible template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template β€” text, points, `choice`/`text` spec, illustration, and option pictures β€” into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only β€” the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Editing, deleting, or publishing a template needs ownership (its owner, or an admin β€” 403 otherwise); as a consequence of that admin bypass, an admin may publish or unpublish another teacher's private template, which is accepted by design. Templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≀ the school's `max_file_bytes`), owner-gated to write and readable by whoever may see the template"),58 (name = "bank", description = "The question bank: reusable question templates, **private by default**. A template is visible to its owner (and admins) alone until its owner explicitly publishes it by `PATCH`ing `visibility` to `school`, at which point every teacher+ sees it β€” saving a question to the bank must never broadcast its `correct` answer key as a side effect. A template the caller may not see is a `404` on every route, never a `403` (a 403 would confirm it exists). A teacher+ reads what they can see (`GET /bank-questions`: `?subject=` origin filter, `?owner=` (a user id or `me`), `?q=` text search, `?visibility=private|school` β€” the last narrows the caller's own view and never widens it, so `private` means \"my drafts\", never another teacher's) and instantiates any visible template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template β€” text, points, `choice`/`text` spec, illustration, and option pictures β€” into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only β€” the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Editing, deleting, or publishing a template needs ownership (its owner, or an admin β€” 403 otherwise); as a consequence of that admin bypass, an admin may publish or unpublish another teacher's private template, which is accepted by design. Templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≀ the school's `max_file_bytes`), owner-gated to write and readable by whoever may see the template"),
59 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),59 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),
60 (name = "exams", description = "Exams (per course, weighted by their kind β€” see `settings`): results, sync/async/open scheduling, attempts (students only β€” staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind β€” the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≀ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side β€” one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` β€” a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped β€” never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded β€” attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` β€” JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams β€” no `mode`, or `open` β€” drop out); without it the list stays newest-first"),60 (name = "exams", description = "Exams (per course, weighted by their kind β€” see `settings`): results, sync/async/open scheduling, attempts (students only β€” staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind β€” the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≀ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side β€” one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` β€” a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped β€” never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded β€” attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` β€” JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams β€” no `mode`, or `open` β€” drop out); without it the list stays newest-first"),
61- (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` β€” `date` is text, `YYYY-MM-DD`, and `slot` must be one of the school's `meal_slots` from `GET /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` β€” edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer β€” this API never speaks decimals or floats about money. Deleting a menu takes its dishes with it. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` β€” own always, otherwise teacher+ or a parent link β€” and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list β€” the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served); every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) β€” staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat; a full menu is a `409`, and that cap is serialized in-process, since a cross-record count is not conflict-checked against a concurrent insert. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** β€” cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. The school's `meal_cancel_cutoff_minutes` closes both ends at once β€” inside that window neither booking nor cancelling lands (`409`) β€” measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** β€” this API stores no school timezone, so staff enter UTC). A slot with no `serving_minute` set falls back to midnight UTC of that date, the pre-serving-time behaviour. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to β€” the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** β€” no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row, under the same in-process lock every dish write takes, so no dish can land between the sum and the seat), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once β€” the charge and its reversal are keyed by (booking, attempt) and written under the same in-process lock as the seat, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge β€” the charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` β€” `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked β€” no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?}`) and is **admin-only**, not manager β€” the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as teacher+ or as a parent linked to them"),61+ (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` β€” `date` is text, `YYYY-MM-DD`, and `slot` must be one of the school's `meal_slots` from `GET /settings`, and may not contain `/ \\ ? # %` β€” the slot name is copied into the menu's record id, which is a URL path segment, so such a menu could never be addressed again; the same characters are refused at `PATCH /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` β€” edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`, both `404` once the dish's menu is gone β€” every dish write moves its menu's revision in the same transaction, which makes the menu's existence part of the write), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer β€” this API never speaks decimals or floats about money. Deleting a menu takes its dishes **and its attendance marks** with it, in the same transaction as the row: a menu's id is deterministic on day+slot, so anything left behind would resurface attached to the next menu published for that meal. Cancelled bookings deliberately stay β€” their `attempt` counter is what keeps the ledger's `(booking, attempt)` ids unique. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` β€” own always, otherwise teacher+ or a parent link β€” and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list β€” the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served) except the two money reads below; every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) β€” staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat; a full menu is a `409`, and that cap is a single conditional write on a counter kept on the menu row β€” taken and spent in the same transaction that places the booking, since counting rows and then writing one is write-skew. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row β€” its student, their parent, or **any manager+**, so a seat and its charge stay reachable once the student it was booked for is no longer a student) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** β€” cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. The school's `meal_cancel_cutoff_minutes` closes both ends at once β€” inside that window neither booking nor cancelling lands (`409`) β€” but it binds **students and parents only**: a manager+ is not held to it, since a deadline meant to stop students gaming the kitchen's headcount is no reason to leave staff holding a seat they cannot free, on a menu that then refuses its own deletion forever and a charge that can never be reversed. It is measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** β€” this API stores no school timezone, so staff enter UTC). A slot with no `serving_minute` set falls back to midnight UTC of that date, the pre-serving-time behaviour. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to β€” the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** β€” no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row; the claim that takes the seat asserts the menu is still at the revision the price was read at, and every dish write bumps that revision, so a dish landing between the sum and the seat refuses the booking, which re-reads and prices itself again), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once β€” the charge and its reversal are keyed by (booking, attempt), and the seat and its flip move in one transaction, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge, written by the **same transaction that flips the seat** rather than after it β€” as two writes a crash in between gave the seat back and left the student billed, with no later cancel able to repay it, since the money is keyed to the attempt the flip had already consumed; the reversal lands only when the charge it undoes is really there, checked inside that transaction, because a refund with no charge behind it invents money. The charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` β€” `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled; a `404` when the menu is unpublished mid-request, because the menu row is the write's own target and a mark left on a deleted menu would resurface on the next one published for that day and slot), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked β€” no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?}`, whose target must be a student or anyone already carrying meal-ledger lines β€” a debt outlives its debtor's role change and has to stay settleable, while a mistyped staff id carries no lines and is still a `400`) and is **admin-only**, not manager β€” the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as **manager+** or as a parent linked to them β€” **a teacher gets a `403`**, the same rule every `/payments` route holds, because canteen debt is family debt and what a family owes is not classroom information"),
62 (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` β€” a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruş) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. There is no scheduler and no sweep. Assignment is **replay-safe by identity** β€” an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) β€” so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree β€” write a new plan instead. That freeze is a **counter on the plan row**, incremented in the same transaction as the assignment it counts, and the edit and the delete are conditional writes against it β€” so a manager editing a plan at the very instant it is being assigned is decided one way or the other by the database, never left half-applied, and the installments a first assignment bills are read back from the stored plan at the moment it freezes. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** β€” it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) β€” allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, …}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters β€” no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `<target>_k_<key>` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice β€” even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `<line>_r` and so reverses once however often it is retried. Payments and refunds are capped by the line they target (`409` past it) β€” that cap is a cross-record sum, which the database cannot enforce on its own β€” it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", …). Every write here is **manager+** β€” teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope β€” the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ β€” **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup β€” plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) β€” all folded from the raw lines on every request and stored nowhere"),62 (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` β€” a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruş) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. There is no scheduler and no sweep. Assignment is **replay-safe by identity** β€” an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) β€” so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree β€” write a new plan instead. That freeze is a **counter on the plan row**, incremented in the same transaction as the assignment it counts, and the edit and the delete are conditional writes against it β€” so a manager editing a plan at the very instant it is being assigned is decided one way or the other by the database, never left half-applied, and the installments a first assignment bills are read back from the stored plan at the moment it freezes. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** β€” it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) β€” allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, …}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters β€” no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `<target>_k_<key>` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice β€” even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `<line>_r` and so reverses once however often it is retried. Payments and refunds are capped by the line they target (`409` past it) β€” that cap is a cross-record sum, which the database cannot enforce on its own β€” it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", …). Every write here is **manager+** β€” teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope β€” the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ β€” **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup β€” plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) β€” all folded from the raw lines on every request and stored nowhere"),
63 (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),63 (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),
64- (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` β€” note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) β€” those marks would silently re-weight. Also the food program: the meal slots menus are published for β€” each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) β€” the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` β€” one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. Read: any authenticated user; edit: manager+"),64+ (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` β€” note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) β€” those marks would silently re-weight. Also the food program: the meal slots menus are published for β€” each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) β€” the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` β€” one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. A slot name may not contain `/ \\ ? # %` (400) β€” the name is copied verbatim into a menu's record id, which is a URL path segment β€” but a name the school's stored list already carries is exempt from that rule, since re-validating it would leave a list written before the rule existed unable to be edited at all: re-sending the name is a 400 and dropping it is a 409 once a menu used it. A grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it. Read: any authenticated user; edit: manager+"),
65 (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) β€” re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"),65 (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) β€” re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"),
66 (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course β€” whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files β€” any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored β€” the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark β€” grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks); a linked parent reads a student's homework report β€” statuses, late flags, marks β€” but never the submitted files"),66 (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course β€” whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files β€” any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored β€” the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark β€” grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks); a linked parent reads a student's homework report β€” statuses, late flags, marks β€” but never the submitted files"),
67- (name = "boards", description = "Collaborative whiteboards. Anyone **from `student` upwards** opens a board (`POST /boards`) with a title and an ad-hoc invite list of user ids β€” no course, session or appointment is involved β€” and every participant draws on it; the creator alone clears, locks, closes or deletes it. The `parent` role has no whiteboard access whatsoever: it is refused `POST /boards` and `GET /boards` with a `403`, and cannot be named in an invite list at all (`400`) β€” so a parent is never on a roster, which makes every id-scoped route and the room's door answer the outsider's `404` rather than a `403` that would confirm the board exists. A caller who is not on a board gets a `404` for it on every route, existence included, while a participant who is not the creator gets a `403` on those four commands (they are already rendering the board, so hiding it from them would be a lie their client cannot act on). Strokes are **append-only and a clear deletes nothing**: it bumps the board's `epoch`, so the live canvas empties while every mark ever drawn stays stored β€” `GET /boards/{id}/strokes` is the current epoch (what a client draws to catch up), `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers, each carrying the epoch it closed, that epoch's final stroke count, who cleared and when (the markers *are* the index, so the open epoch is deliberately absent from it). Two growth caps, both published at `GET /limits`: `max_epoch_strokes` bounds the *live* canvas and is recoverable (clear it and drawing resumes, losing nothing), while `max_board_strokes` bounds the board's *lifetime* storage and stamps `closed_at` on the way past β€” a closed board is permanently read-only and fully readable, never deleted, and there is no reopen. `POST /boards/{id}/close` is the manual form of that, and idempotent. `DELETE /boards/{id}` is the one operation here that really destroys marks β€” it takes the whole stroke log with it and frees one of the creator's `max_boards_per_creator` seats. `PATCH /boards/{id}` re-titles (any participant) or changes the roster and the lock (creator only). Not in this spec (WebSocket): the live board room at `GET /boards/{id}/ws`, where the drawing itself happens β€” JSON frames, cookie-authed, and a **404** at the door for anyone not on the board. A `join` replays the current epoch only (chunked `strokes`, then `synced` with the cursor to resume from); a `stroke` is persisted before it is fanned out, so every canvas in the room is showing rows that committed; `clear` and `lock` are the creator's alone and refuse anyone else with `error{code:\"forbidden\"}` *without* closing their socket. The REST mutations above fan out into the same room, and a roster change drops the socket of anyone it removed. See `src/web/board_ws.rs` for the frame-by-frame protocol"),67+ (name = "boards", description = "Collaborative whiteboards. Anyone **from `student` upwards** opens a board (`POST /boards`) with a title and an ad-hoc invite list of user ids β€” no course, session or appointment is involved β€” and every participant draws on it; the creator alone clears, locks, closes or deletes it. The `parent` role has no whiteboard access whatsoever: it is refused `POST /boards` and `GET /boards` with a `403`, and cannot be named in an invite list at all (`400`) β€” so a parent is never on a roster, which makes every id-scoped route and the room's door answer the outsider's `404` rather than a `403` that would confirm the board exists. A caller who is not on a board gets a `404` for it on every route, existence included, while a participant who is not the creator gets a `403` on those four commands (they are already rendering the board, so hiding it from them would be a lie their client cannot act on). Strokes are **append-only and a clear deletes nothing**: it bumps the board's `epoch`, so the live canvas empties while every mark ever drawn stays stored β€” `GET /boards/{id}/strokes` is the current epoch (what a client draws to catch up), `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers (a clear needs at least one mark to close: an **already-blank** canvas answers `409` alongside the closed board, since the marker is a stored row charged to the lifetime cap), each carrying the epoch it closed, that epoch's final stroke count, who cleared and when (the markers *are* the index, so the open epoch is deliberately absent from it). Two growth caps, both published at `GET /limits`: `max_epoch_strokes` bounds the *live* canvas and is recoverable (clear it and drawing resumes, losing nothing), while `max_board_strokes` bounds the board's *lifetime* storage β€” rows on the board, so a `clear` marker costs one unit like any mark, and a board holds at most `max_board_strokes + 1` rows because the marker closing the final stroke is never the one refused β€” and stamps `closed_at` on the way past β€” a closed board is permanently read-only and fully readable, never deleted, and there is no reopen. `POST /boards/{id}/close` is the manual form of that, and idempotent. `DELETE /boards/{id}` is the one operation here that really destroys marks β€” it takes the whole stroke log with it and frees one of the creator's `max_boards_per_creator` seats. `PATCH /boards/{id}` re-titles (any participant) or changes the roster and the lock (creator only). Not in this spec (WebSocket): the live board room at `GET /boards/{id}/ws`, where the drawing itself happens β€” JSON frames, cookie-authed, and a **404** at the door for anyone not on the board. A `join` replays the current epoch only (chunked `strokes`, then `synced` with the cursor to resume from); a `stroke` is persisted before it is fanned out, so every canvas in the room is showing rows that committed; `clear` and `lock` are the creator's alone and refuse anyone else with `error{code:\"forbidden\"}` *without* closing their socket. The REST mutations above fan out into the same room, and a roster change drops the socket of anyone it removed. See `src/web/board_ws.rs` for the frame-by-frame protocol"),
68 (name = "terms", description = "Academic terms (semester/trimester/quarter β€” whatever the school runs); courses and classes may link to one. A term still linked by any course or class cannot be deleted (409) β€” unlink them first. Read: any authenticated user; edit: manager+"),68 (name = "terms", description = "Academic terms (semester/trimester/quarter β€” whatever the school runs); courses and classes may link to one. A term still linked by any course or class cannot be deleted (409) β€” unlink them first. Read: any authenticated user; edit: manager+"),
69 ),69 ),
70 )]70 )]
src/migration_sql.rsmodified+28 -0
@@ -280,6 +280,14 @@ pub const MIGRATION: &str = "
280 DEFINE FIELD IF NOT EXISTS class ON class_member TYPE record<class_group>;280 DEFINE FIELD IF NOT EXISTS class ON class_member TYPE record<class_group>;
281 DEFINE FIELD IF NOT EXISTS user ON class_member TYPE record<user>;281 DEFINE FIELD IF NOT EXISTS user ON class_member TYPE record<user>;
282 DEFINE FIELD IF NOT EXISTS added_by ON class_member TYPE record<user>;282 DEFINE FIELD IF NOT EXISTS added_by ON class_member TYPE record<user>;
283+ -- When the student was put in. Both link tables key on the *pair*
284+ -- (`<class>_<user>`), so ordering a roster by its record id sorts it by the
285+ -- member's account ULID β€” an arbitrary order the routes nevertheless
286+ -- documented as newest-first. `option<int>` and no BACKFILL: rows written
287+ -- before this column are of unknown age, and an absent stamp is NONE, which
288+ -- SurrealDB sorts *last* under DESC β€” already the honest place for them, so
289+ -- there is no number to invent.
290+ DEFINE FIELD IF NOT EXISTS added_at ON class_member TYPE option<int>;
283 DEFINE INDEX IF NOT EXISTS class_member_class_user ON class_member FIELDS class, user UNIQUE;291 DEFINE INDEX IF NOT EXISTS class_member_class_user ON class_member FIELDS class, user UNIQUE;
284 DEFINE INDEX IF NOT EXISTS class_member_class ON class_member FIELDS class;292 DEFINE INDEX IF NOT EXISTS class_member_class ON class_member FIELDS class;
285 DEFINE INDEX IF NOT EXISTS class_member_user ON class_member FIELDS user;293 DEFINE INDEX IF NOT EXISTS class_member_user ON class_member FIELDS user;
@@ -288,6 +296,9 @@ pub const MIGRATION: &str = "
288 DEFINE FIELD IF NOT EXISTS class ON class_course TYPE record<class_group>;296 DEFINE FIELD IF NOT EXISTS class ON class_course TYPE record<class_group>;
289 DEFINE FIELD IF NOT EXISTS course ON class_course TYPE record<course>;297 DEFINE FIELD IF NOT EXISTS course ON class_course TYPE record<course>;
290 DEFINE FIELD IF NOT EXISTS attached_by ON class_course TYPE record<user>;298 DEFINE FIELD IF NOT EXISTS attached_by ON class_course TYPE record<user>;
299+ -- The mirror of `class_member.added_at`, for the same reason: without it
300+ -- the course list is ordered by the *course's* ULID.
301+ DEFINE FIELD IF NOT EXISTS attached_at ON class_course TYPE option<int>;
291 DEFINE INDEX IF NOT EXISTS class_course_class_course ON class_course FIELDS class, course UNIQUE;302 DEFINE INDEX IF NOT EXISTS class_course_class_course ON class_course FIELDS class, course UNIQUE;
292 DEFINE INDEX IF NOT EXISTS class_course_class ON class_course FIELDS class;303 DEFINE INDEX IF NOT EXISTS class_course_class ON class_course FIELDS class;
293 DEFINE INDEX IF NOT EXISTS class_course_course ON class_course FIELDS course;304 DEFINE INDEX IF NOT EXISTS class_course_course ON class_course FIELDS course;
@@ -1057,6 +1068,23 @@ pub const BACKFILL: &str = "
1057 FOR $row IN ((SELECT plan, count() AS n FROM fee_plan_assignment GROUP BY plan) ?? []) {1068 FOR $row IN ((SELECT plan, count() AS n FROM fee_plan_assignment GROUP BY plan) ?? []) {
1058 UPDATE $row.plan SET assignment_count = $row.n WHERE assignment_count = NONE;1069 UPDATE $row.plan SET assignment_count = $row.n WHERE assignment_count = NONE;
1059 };1070 };
1071+
1072+ -- The clear marker began paying the board's lifetime counter (2026-08-02):
1073+ -- it is a real `board_stroke` row, so a marker that charged nothing left
1074+ -- `total_stroke_count` counting marks *drawn* instead of rows *stored*, and
1075+ -- every board an older binary cleared is short exactly one per past clear.
1076+ --
1077+ -- The only repair here that is NOT `= NONE`-guarded, and the one counter
1078+ -- that may be: it is not an opinion the live system maintains, it is the
1079+ -- board's row count β€” every stroke and every marker charges 1, and a stroke
1080+ -- row is only ever deleted with the board itself (domain::board_stroke).
1081+ -- So recomputing converges instead of overwriting, and `!= $row.n` writes
1082+ -- nothing on the next boot, when every counter already equals its count.
1083+ -- No zero pass: a board nobody drew on forms no group, and an absent
1084+ -- counter already reads as zero through the `?? 0` every reader applies.
1085+ FOR $row IN ((SELECT board, count() AS n FROM board_stroke GROUP BY board) ?? []) {
1086+ UPDATE $row.board SET total_stroke_count = $row.n WHERE total_stroke_count != $row.n;
1087+ };
1060 ";1088 ";
1061 1089
1062 /// The migration batches, in the order a boot applies them β€” and the *only*1090 /// The migration batches, in the order a boot applies them β€” and the *only*
src/web/board_ws.rsmodified+60 -75
@@ -68,7 +68,7 @@ use tokio::sync::broadcast::error::RecvError;
68 use crate::constant::{BOARD_REPLAY_CHUNK, BOARD_WS_TICK_SECS, MAX_BOARD_ID_LEN};68 use crate::constant::{BOARD_REPLAY_CHUNK, BOARD_WS_TICK_SECS, MAX_BOARD_ID_LEN};
69 use crate::database::Database;69 use crate::database::Database;
70 use crate::domain::board::{Board, BoardId};70 use crate::domain::board::{Board, BoardId};
71-use crate::domain::board_stroke::BoardStroke;71+use crate::domain::board_stroke::{self, BoardStroke};
72 use crate::domain::role::Role;72 use crate::domain::role::Role;
73 use crate::domain::timestamp::Timestamp;73 use crate::domain::timestamp::Timestamp;
74 use crate::domain::user::UserId;74 use crate::domain::user::UserId;
@@ -524,24 +524,23 @@ async fn creator_board(
524 }524 }
525 }525 }
526 526
527-/// A machine-readable `code` beside the public words. The three refusals the527+/// A machine-readable `code` beside the public words. Each refusal the board
528-/// stroke path can raise are distinguished by their message, because that is528+/// path can raise means a different thing to a client: `epoch_full` is
529-/// what [`BoardStroke::append`] hands back and each one means a different thing529+/// recoverable by clearing, `locked` is a pause that will lift, `canvas_blank`
530-/// to a client: `epoch_full` is recoverable by clearing, `locked` is a pause530+/// is nothing to do, `board_closed` is terminal.
531-/// that will lift, `board_closed` is terminal.531+///
532+/// The match is on the refusal *constants* [`board_stroke`] raises, by value β€”
533+/// never on a substring of them. Guessing from a substring made every reworded
534+/// refusal a silent re-labelling: "the canvas is already blank" contains the
535+/// word "closed", so a blank canvas told a live room its board was finished.
532 fn error_frame(err: &AppError, client_seq: Option<u64>) -> Value {536 fn error_frame(err: &AppError, client_seq: Option<u64>) -> Value {
533 let code = match err {537 let code = match err {
534 AppError::Forbidden(_) => "forbidden",538 AppError::Forbidden(_) => "forbidden",
535- AppError::Conflict(message) if message.contains("clear it to keep drawing") => "epoch_full",539+ AppError::Conflict(message) if *message == board_stroke::EPOCH_FULL => "epoch_full",
536- AppError::Conflict(message) if message.contains("locked") => "locked",540+ AppError::Conflict(message) if *message == board_stroke::BOARD_LOCKED => "locked",
537- // "read-only" (the lifetime cap), and the clear's own "it is closed, or541+ AppError::Conflict(message) if *message == board_stroke::BOARD_CLOSED => "board_closed",
538- // you did not create it" β€” the socket already checked the creator, so542+ AppError::Conflict(message) if *message == board_stroke::CANVAS_BLANK => "canvas_blank",
539- // what is left is closed, and that is what the client must act on.543+ // Everything else, `BOARD_MOVED` included: retryable, never terminal.
540- AppError::Conflict(message)
541- if message.contains("read-only") || message.contains("closed") =>
542- {
543- "board_closed"
544- }
545 AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict",544 AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict",
546 AppError::Validation(_) | AppError::PayloadTooLarge(_) => "invalid",545 AppError::Validation(_) | AppError::PayloadTooLarge(_) => "invalid",
547 AppError::NotFound => "not_found",546 AppError::NotFound => "not_found",
@@ -563,45 +562,44 @@ fn error_frame(err: &AppError, client_seq: Option<u64>) -> Value {
563 mod tests {562 mod tests {
564 use super::*;563 use super::*;
565 564
566- /// The three refusals `append` can answer with are one `Conflict` variant565+ fn code(err: AppError) -> String {
567- /// apiece, told apart only by their wording β€” so this pairing is the whole566+ error_frame(&err, None)["code"]
568- /// contract behind `epoch_full` (clear and carry on), `locked` (wait) and567+ .as_str()
569- /// `board_closed` (never again). Getting it wrong sends a paused room off568+ .unwrap()
570- /// clearing a canvas it never needed to lose.569+ .to_string()
570+ }
571+
572+ /// The pairing is the whole contract behind `epoch_full` (clear and carry
573+ /// on), `locked` (wait), `canvas_blank` (nothing to do) and `board_closed`
574+ /// (never again). Getting it wrong sends a paused room off clearing a
575+ /// canvas it never needed to lose.
576+ ///
577+ /// Written against the constants, never against copies of their words: a
578+ /// test that pins the wording rots into a test of a string the code can no
579+ /// longer emit, which is exactly how the blank canvas shipped as
580+ /// `board_closed` through a green suite. The length assertion is the other
581+ /// half β€” a refusal added to `board_stroke::REFUSALS` fails here until it
582+ /// is given the code its client must act on.
571 #[test]583 #[test]
572 fn every_refusal_gets_the_code_its_client_must_act_on() {584 fn every_refusal_gets_the_code_its_client_must_act_on() {
573- let code = |err: AppError| {585+ let pairs = [
574- error_frame(&err, None)["code"]586+ (board_stroke::EPOCH_FULL, "epoch_full"),
575- .as_str()587+ (board_stroke::BOARD_LOCKED, "locked"),
576- .unwrap()588+ (board_stroke::BOARD_CLOSED, "board_closed"),
577- .to_string()589+ (board_stroke::CANVAS_BLANK, "canvas_blank"),
578- };590+ // A stroke that lost its epoch to a clear is a plain retryable
591+ // conflict, and must never be mistaken for terminal.
592+ (board_stroke::BOARD_MOVED, "conflict"),
593+ ];
579 assert_eq!(594 assert_eq!(
580- code(AppError::Conflict(595+ pairs.len(),
581- "this board is full β€” clear it to keep drawing"596+ board_stroke::REFUSALS.len(),
582- )),597+ "a refusal the room cannot code"
583- "epoch_full"
584- );
585- assert_eq!(
586- code(AppError::Conflict(
587- "this board is locked β€” the creator has paused drawing"
588- )),
589- "locked"
590- );
591- assert_eq!(
592- code(AppError::Conflict(
593- "this board is closed β€” it is permanently read-only"
594- )),
595- "board_closed"
596- );
597- // A stroke that lost its epoch to a clear is none of the three: it is a
598- // plain retryable conflict, and must never be mistaken for terminal.
599- assert_eq!(
600- code(AppError::Conflict(
601- "this board changed while you were drawing β€” draw it again"
602- )),
603- "conflict"
604 );598 );
599+ for (message, expected) in pairs {
600+ assert!(board_stroke::REFUSALS.contains(&message));
601+ assert_eq!(code(AppError::Conflict(message)), expected, "{message}");
602+ }
605 assert_eq!(code(AppError::Forbidden("nope")), "forbidden");603 assert_eq!(code(AppError::Forbidden("nope")), "forbidden");
606 // Internals are logged, never wired.604 // Internals are logged, never wired.
607 let frame = error_frame(&AppError::Internal("secret".into()), None);605 let frame = error_frame(&AppError::Internal("secret".into()), None);
@@ -609,36 +607,23 @@ mod tests {
609 assert_eq!(frame["message"], "internal server error");607 assert_eq!(frame["message"], "internal server error");
610 }608 }
611 609
612- /// Every refusal the room can raise has to reach the client as the code610+ /// A blank canvas is the refusal that hides: it is a *live* board saying
613- /// that tells it what to *do*: clear (recoverable), wait (paused) or stop611+ /// "nothing to clear", so it must never carry the terminal code. The two it
614- /// (terminal). The clear's own refusal is the one that hides β€” it names two612+ /// sits between are checked with it, since what matters is that no two of
615- /// causes, but the socket has already checked the creator, so what is left613+ /// the three collapse into one code.
616- /// is `board_closed` and never the generic `conflict`.
617 #[test]614 #[test]
618- fn each_refusal_keeps_its_own_code() {615+ fn a_blank_canvas_is_never_terminal() {
619- let code = |err: AppError| {
620- error_frame(&err, None)["code"]
621- .as_str()
622- .unwrap()
623- .to_string()
624- };
625 assert_eq!(616 assert_eq!(
626- code(AppError::Conflict(617+ code(AppError::Conflict(board_stroke::CANVAS_BLANK)),
627- "this board cannot be cleared β€” it is closed, or you did not create it"618+ "canvas_blank"
628- )),
629- "board_closed"
630 );619 );
631 assert_eq!(620 assert_eq!(
632- code(AppError::Conflict(621+ code(AppError::Conflict(board_stroke::BOARD_CLOSED)),
633- "this board is locked β€” the creator has paused drawing"622+ "board_closed"
634- )),
635- "locked"
636 );623 );
637 assert_eq!(624 assert_eq!(
638- code(AppError::Conflict(625+ code(AppError::Conflict(board_stroke::BOARD_LOCKED)),
639- "this board is full β€” clear it to keep drawing"626+ "locked"
640- )),
641- "epoch_full"
642 );627 );
643 }628 }
644 629
src/web/boards.rsmodified+4 -2
@@ -504,7 +504,9 @@ async fn update_board(
504 /// stroke count, so the live canvas is blank while every mark ever drawn stays504 /// stroke count, so the live canvas is blank while every mark ever drawn stays
505 /// readable through `/history`. Also resets the live-canvas cap, which is how a505 /// readable through `/history`. Also resets the live-canvas cap, which is how a
506 /// board that answered "clear it to keep drawing" is recovered. `409` on a506 /// board that answered "clear it to keep drawing" is recovered. `409` on a
507-/// closed board.507+/// closed board, and on a canvas that is **already blank** β€” the marker is a
508+/// real stroke row charged to the board's lifetime cap, so a clear has to close
509+/// at least one mark to be worth a row.
508 #[utoipa::path(510 #[utoipa::path(
509 post,511 post,
510 path = "/{id}/clear",512 path = "/{id}/clear",
@@ -516,7 +518,7 @@ async fn update_board(
516 (status = 401, description = "Not authenticated", body = ErrorResponse),518 (status = 401, description = "Not authenticated", body = ErrorResponse),
517 (status = 403, description = "Only the creator may clear the board", body = ErrorResponse),519 (status = 403, description = "Only the creator may clear the board", body = ErrorResponse),
518 (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),520 (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
519- (status = 409, description = "The board is closed", body = ErrorResponse),521+ (status = 409, description = "The canvas is already blank, or the board is closed", body = ErrorResponse),
520 ),522 ),
521 )]523 )]
522 async fn clear_board(524 async fn clear_board(
src/web/classes.rsmodified+17 -9
@@ -362,7 +362,7 @@ async fn delete_class(
362 (status = 401, description = "Not authenticated", body = ErrorResponse),362 (status = 401, description = "Not authenticated", body = ErrorResponse),
363 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),363 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
364 (status = 404, description = "Class not found", body = ErrorResponse),364 (status = 404, description = "Class not found", body = ErrorResponse),
365- (status = 409, description = "Already in this class, or one of its courses is full", body = ErrorResponse),365+ (status = 409, description = "Already in this class, the class is at its student ceiling (max_class_members), one of its courses is full, or one of them no longer exists (a stale attachment β€” detach it)", body = ErrorResponse),
366 ),366 ),
367 )]367 )]
368 async fn add_member(368 async fn add_member(
@@ -488,7 +488,7 @@ async fn remove_member(
488 (status = 401, description = "Not authenticated", body = ErrorResponse),488 (status = 401, description = "Not authenticated", body = ErrorResponse),
489 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),489 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
490 (status = 404, description = "Class not found", body = ErrorResponse),490 (status = 404, description = "Class not found", body = ErrorResponse),
491- (status = 409, description = "Already attached, or the course cannot hold the whole class", body = ErrorResponse),491+ (status = 409, description = "Already attached, the class is at its course ceiling (max_class_courses), or the course cannot hold the whole class", body = ErrorResponse),
492 ),492 ),
493 )]493 )]
494 async fn attach_course(494 async fn attach_course(
@@ -556,7 +556,9 @@ async fn list_class_courses(
556 /// that course, like attaching. The enrollments the class pumped into it are556 /// that course, like attaching. The enrollments the class pumped into it are
557 /// swept β€” except rows another attached class still claims (re-tagged to it)557 /// swept β€” except rows another attached class still claims (re-tagged to it)
558 /// and rows placed by hand (left standing). A course that was not attached is a558 /// and rows placed by hand (left standing). A course that was not attached is a
559-/// 404.559+/// 404 β€” but a course row that is *gone* is not: the link a deleted course left
560+/// behind detaches (the rights check has nothing left to read, and no roster
561+/// left to protect), or the class holding it could never be deleted.
560 #[utoipa::path(562 #[utoipa::path(
561 delete,563 delete,
562 path = "/{id}/courses/{course}",564 path = "/{id}/courses/{course}",
@@ -570,7 +572,7 @@ async fn list_class_courses(
570 (status = 204, description = "Detached"),572 (status = 204, description = "Detached"),
571 (status = 401, description = "Not authenticated", body = ErrorResponse),573 (status = 401, description = "Not authenticated", body = ErrorResponse),
572 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),574 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
573- (status = 404, description = "Class or course not found, or that course was not attached", body = ErrorResponse),575+ (status = 404, description = "Class not found, or that course was not attached β€” a course row that is gone does not refuse the detach, it is the reason for it", body = ErrorResponse),
574 ),576 ),
575 )]577 )]
576 async fn detach_course(578 async fn detach_course(
@@ -579,15 +581,21 @@ async fn detach_course(
579 Path((id, course)): Path<(String, String)>,581 Path((id, course)): Path<(String, String)>,
580 ) -> Result<StatusCode, AppError> {582 ) -> Result<StatusCode, AppError> {
581 let class = class_or_404(&id, &st.db).await?;583 let class = class_or_404(&id, &st.db).await?;
582- let course = Course::read(&CourseId::from_key(&course), &st.db)584+ let course = CourseId::from_key(&course);
583- .await?585+ // The rights check is skipped when the course row is gone, rather than the
584- .ok_or(AppError::NotFound)?;586+ // whole detach refused: management rights are read *off* the course, so a
585- if !can_manage_course(&course, &user) {587+ // link left pointing at a deleted course had no readable owner and this
588+ // route answered 404 forever β€” which also left the class undeletable, its
589+ // attachment counter counting a row nothing could sweep. There is no roster
590+ // left to protect, and the caller is already teacher+.
591+ if let Some(course) = Course::read(&course, &st.db).await?
592+ && !can_manage_course(&course, &user)
593+ {
586 return Err(AppError::Forbidden(594 return Err(AppError::Forbidden(
587 "only the course creator, an assigned teacher, or a manager/admin can detach this course from a class",595 "only the course creator, an assigned teacher, or a manager/admin can detach this course from a class",
588 ));596 ));
589 }597 }
590- ClassCourse::detach(class.get_id(), course.get_id(), &st.db).await?;598+ ClassCourse::detach(class.get_id(), &course, &st.db).await?;
591 Ok(StatusCode::NO_CONTENT)599 Ok(StatusCode::NO_CONTENT)
592 }600 }
593 601
src/web/courses.rsmodified+11 -0
@@ -160,6 +160,13 @@ struct EnrollmentResponse {
160 user: PersonRef,160 user: PersonRef,
161 /// Who enrolled them.161 /// Who enrolled them.
162 enrolled_by: PersonRef,162 enrolled_by: PersonRef,
163+ /// The class (`GET /classes/{id}`) this row was pumped by, or `null` when a
164+ /// human placed it directly. A row with a class on it is *swept* when that
165+ /// class drops the student or detaches the course; a `null` one is nobody's
166+ /// to take back. Without it no client could tell which of its roster rows a
167+ /// class change is about to remove.
168+ #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
169+ source: Option<String>,
163 }170 }
164 171
165 impl EnrollmentResponse {172 impl EnrollmentResponse {
@@ -169,6 +176,7 @@ impl EnrollmentResponse {
169 course: enrollment.get_course().key().to_string(),176 course: enrollment.get_course().key().to_string(),
170 user: PersonRef::resolve(people, enrollment.get_user()),177 user: PersonRef::resolve(people, enrollment.get_user()),
171 enrolled_by: PersonRef::resolve(people, enrollment.get_enrolled_by()),178 enrolled_by: PersonRef::resolve(people, enrollment.get_enrolled_by()),
179+ source: enrollment.get_source().map(|class| class.key().to_string()),
172 }180 }
173 }181 }
174 }182 }
@@ -609,6 +617,9 @@ async fn unassign_teacher(
609 /// student membership, and it gates sitting exams, being graded, and the class617 /// student membership, and it gates sitting exams, being graded, and the class
610 /// roster, all student-only. A course with a `capacity` refuses new members618 /// roster, all student-only. A course with a `capacity` refuses new members
611 /// once the roster is full (someone already enrolled is returned as-is).619 /// once the roster is full (someone already enrolled is returned as-is).
620+/// Enrolling a student a class pumped in takes the row *off* that class β€”
621+/// `source` comes back `null` β€” so a later class sweep can no longer undo a
622+/// placement made by hand, the mirror of a manual unenroll winning permanently.
612 #[utoipa::path(623 #[utoipa::path(
613 post,624 post,
614 path = "/{id}/enrollments",625 path = "/{id}/enrollments",
src/web/exams/mod.rsmodified+16 -0
@@ -644,6 +644,22 @@ async fn grade(
644 if exam.is_draft() {644 if exam.is_draft() {
645 return Err(crate::domain::exam_result::draft_error());645 return Err(crate::domain::exam_result::draft_error());
646 }646 }
647+ // The exam's kind must still be one the school offers. `kind_ref`'s retired
648+ // bit is what actually refuses the mark inside `ExamResult::grade`, and it
649+ // is a *different record* from the list β€” a settings PATCH moves both, so
650+ // anything that leaves them disagreeing (a rolled-back retirement, a hand
651+ // edit) would otherwise reopen grading under a kind nobody lists, which is
652+ // also a mark that averages at weight 1 forever. Both gates, same answer;
653+ // this one is a read, the counter's is the one that survives a race.
654+ let kind = exam.get_kind().as_str();
655+ if !Settings::load(&st.db)
656+ .await?
657+ .get_exam_kinds()
658+ .iter()
659+ .any(|offered| offered.get_name() == kind)
660+ {
661+ return Err(crate::domain::exam_result::retired_kind_error(kind));
662+ }
647 663
648 let mark = Mark::try_new(req.mark)?;664 let mark = Mark::try_new(req.mark)?;
649 let target = UserId::from_key(&req.user_id);665 let target = UserId::from_key(&req.user_id);
src/web/limits.rsmodified+6 -0
@@ -122,6 +122,10 @@ struct CourseLimits {
122 max_class_name_len: usize,122 max_class_name_len: usize,
123 /// A class's optional free-text grade label ("9", "10-A").123 /// A class's optional free-text grade label ("9", "10-A").
124 max_class_grade_len: usize,124 max_class_grade_len: usize,
125+ /// Students one class may hold. Removing one frees a place.
126+ max_class_members: i64,
127+ /// Courses one class may be attached to. Detaching one frees a place.
128+ max_class_courses: i64,
125 }129 }
126 130
127 /// Exams, their questions, answers, and marks.131 /// Exams, their questions, answers, and marks.
@@ -426,6 +430,8 @@ impl LimitsResponse {
426 max_term_name_len: MAX_TERM_NAME_LEN,430 max_term_name_len: MAX_TERM_NAME_LEN,
427 max_class_name_len: MAX_CLASS_NAME_LEN,431 max_class_name_len: MAX_CLASS_NAME_LEN,
428 max_class_grade_len: MAX_CLASS_GRADE_LEN,432 max_class_grade_len: MAX_CLASS_GRADE_LEN,
433+ max_class_members: MAX_CLASS_MEMBERS,
434+ max_class_courses: MAX_CLASS_COURSES,
429 },435 },
430 exam: ExamLimits {436 exam: ExamLimits {
431 max_title_len: MAX_EXAM_TITLE_LEN,437 max_title_len: MAX_EXAM_TITLE_LEN,
src/web/meals.rsmodified+100 -23
@@ -3,7 +3,8 @@
3 //!3 //!
4 //! Reads are open to every authenticated user (a student picks their lunch),4 //! Reads are open to every authenticated user (a student picks their lunch),
5 //! writes are manager+ β€” publishing what the school serves is kitchen5 //! writes are manager+ β€” publishing what the school serves is kitchen
6-//! administration, not teaching.6+//! administration, not teaching. The balance and the ledger are the exception:
7+//! they are manager+ like `/payments`, since canteen debt is family debt.
7 //!8 //!
8 //! Money only ever *appends* here (see [`MealLedger`]): booking charges a price9 //! Money only ever *appends* here (see [`MealLedger`]): booking charges a price
9 //! snapshot, cancelling reverses it, and recording a payment is admin-only.10 //! snapshot, cancelling reverses it, and recording a payment is admin-only.
@@ -414,7 +415,10 @@ async fn add_dish(
414 // is write-skew, so the count and the insert have to be one step. The415 // is write-skew, so the count and the insert have to be one step. The
415 // *price* no longer needs it β€” a dish write moves the menu's revision, and416 // *price* no longer needs it β€” a dish write moves the menu's revision, and
416 // a booking claims its seat at the revision it priced itself against.417 // a booking claims its seat at the revision it priced itself against.
417- // The lock stays a leaf: nothing below here takes another.418+ // The lock is a leaf again: the revision bump rides the dish write's own
419+ // transaction now, so nothing held under it takes `cap`'s counter lock. It
420+ // stays a leaf only while that holds β€” see [`MENU_LOCK`] for the order a
421+ // caller that changes it must keep.
418 let _guard = MENU_LOCK.lock().await;422 let _guard = MENU_LOCK.lock().await;
419 // The menu is read *inside* the lock: read before it, a `DELETE /menus/{id}`423 // The menu is read *inside* the lock: read before it, a `DELETE /menus/{id}`
420 // running in the gap takes its cascade with it and this dish lands on a menu424 // running in the gap takes its cascade with it and this dish lands on a menu
@@ -902,8 +906,13 @@ async fn list_menu_bookings(
902 906
903 /// Give the seat back. The row survives, flipped to `cancelled` β€” the seat is907 /// Give the seat back. The row survives, flipped to `cancelled` β€” the seat is
904 /// free for someone else, and the cancellation stays auditable. Only the908 /// free for someone else, and the cancellation stays auditable. Only the
905-/// student it is for, or their parent, may cancel it. Refused (`409`) once the909+/// student it is for, or their parent, may cancel it β€” and for them it is
906-/// school's `meal_cancel_cutoff_minutes` has closed the meal.910+/// refused (`409`) once the school's `meal_cancel_cutoff_minutes` has closed
911+/// the meal.
912+///
913+/// Manager+ may cancel anyone's booking, and is not bound by the cutoff β€” the
914+/// seat and the money have to stay reachable when the student it was booked for
915+/// is no longer a student, or when the meal has already closed.
907 ///916 ///
908 /// **Idempotent**: cancelling an already-cancelled booking is a `200` with the917 /// **Idempotent**: cancelling an already-cancelled booking is a `200` with the
909 /// row as it stands, not a `409`. Repeating it also replays the refund, so a918 /// row as it stands, not a `409`. Repeating it also replays the refund, so a
@@ -919,9 +928,9 @@ async fn list_menu_bookings(
919 responses(928 responses(
920 (status = 200, description = "Cancelled (also when it already was β€” the call is idempotent and replays the refund)", body = BookingResponse),929 (status = 200, description = "Cancelled (also when it already was β€” the call is idempotent and replays the refund)", body = BookingResponse),
921 (status = 401, description = "Not authenticated", body = ErrorResponse),930 (status = 401, description = "Not authenticated", body = ErrorResponse),
922- (status = 403, description = "Not the booking's student, nor their parent", body = ErrorResponse),931+ (status = 403, description = "Not the booking's student, their parent, nor a manager", body = ErrorResponse),
923 (status = 404, description = "Not found", body = ErrorResponse),932 (status = 404, description = "Not found", body = ErrorResponse),
924- (status = 409, description = "The cutoff has passed, or the menu was too contended to free the seat", body = ErrorResponse),933+ (status = 409, description = "The cutoff has passed (students and parents only), or the menu was too contended to free the seat", body = ErrorResponse),
925 ),934 ),
926 )]935 )]
927 async fn cancel_booking(936 async fn cancel_booking(
@@ -932,14 +941,34 @@ async fn cancel_booking(
932 let booking = MealBooking::read(&MealBookingId::from_key(&bid), &st.db)941 let booking = MealBooking::read(&MealBookingId::from_key(&bid), &st.db)
933 .await?942 .await?
934 .ok_or(AppError::NotFound)?;943 .ok_or(AppError::NotFound)?;
935- // Same door as booking: whoever may take the seat may give it back.944+ // Manager+ may give back *any* seat. Not a convenience: `booking_target`
936- let target = booking_target(&user, Some(booking.get_student().key()), &st.db).await?;945+ // grants only students and parents, so a student promoted to staff (or a
937- if &target != booking.get_student() {946+ // parent unlinked) left a live seat nobody on the API could cancel β€” the
938- return Err(AppError::Forbidden("not your booking"));947+ // menu 409s its own delete forever and the charge can never be reversed,
948+ // since cancelling is the only route that reverses one. Promotion itself
949+ // deliberately sweeps nothing: moving money is a decision, not a side
950+ // effect of a role change.
951+ let staff = user.get_role().at_least(Role::Manager);
952+ if !staff {
953+ // Same door as booking: whoever may take the seat may give it back.
954+ let target = booking_target(&user, Some(booking.get_student().key()), &st.db).await?;
955+ if &target != booking.get_student() {
956+ return Err(AppError::Forbidden("not your booking"));
957+ }
939 }958 }
940- let cutoff = meal_cutoff(&st.db).await?;959+ // …and the cutoff does not bind them either. It exists to stop students
941- // Flips the row and appends the reversal for that attempt's charge960+ // gaming the kitchen's headcount, which is no reason to leave staff holding
942- // together, under the same lock booking uses; the charge itself stays.961+ // a seat they cannot free: past the cutoff the seat was uncancellable, and
962+ // its menu β€” which refuses its own delete while a seat is held β€” was
963+ // undeletable with it, forever. A deadline that binds nobody is exactly the
964+ // one a school that set no `meal_cancel_cutoff_minutes` already runs under.
965+ let cutoff = if staff {
966+ MealCutoff::default()
967+ } else {
968+ meal_cutoff(&st.db).await?
969+ };
970+ // Flips the row and appends the reversal for that attempt's charge in one
971+ // transaction; the charge itself stays.
943 let cancelled = booking.cancel(&cutoff, user.get_id(), &st.db).await?;972 let cancelled = booking.cancel(&cutoff, user.get_id(), &st.db).await?;
944 let items = booking_responses(std::slice::from_ref(&cancelled), &st.db).await?;973 let items = booking_responses(std::slice::from_ref(&cancelled), &st.db).await?;
945 Ok(Json(974 Ok(Json(
@@ -1051,8 +1080,12 @@ async fn mark_attendance(
1051 reason: "target user does not exist",1080 reason: "target user does not exist",
1052 }));1081 }));
1053 }1082 }
1054- let row =1083+ // The menu rides in the write's own target (see [`MealAttendance::mark`]),
1055- MealAttendance::mark(menu.get_id(), &student, status, marker.get_id(), &st.db).await?;1084+ // so a delete landing between the read above and this write leaves no mark
1085+ // behind β€” it answers 404 instead, exactly as the read would have.
1086+ let row = MealAttendance::mark(menu.get_id(), &student, status, marker.get_id(), &st.db)
1087+ .await?
1088+ .ok_or(AppError::NotFound)?;
1056 let items = attendance_responses(std::slice::from_ref(&row), &st.db).await?;1089 let items = attendance_responses(std::slice::from_ref(&row), &st.db).await?;
1057 Ok(Json(1090 Ok(Json(
1058 items.into_iter().next().expect("one mark in, one out"),1091 items.into_iter().next().expect("one mark in, one out"),
@@ -1225,6 +1258,39 @@ async fn ensure_can_read_student(
1225 super::ensure_can_observe(caller, target, db).await1258 super::ensure_can_observe(caller, target, db).await
1226 }1259 }
1227 1260
1261+/// May `caller` read `target`'s meal *money* β€” balance and ledger? Own always;
1262+/// a parent only for a student they hold a live link to; manager+ for anyone.
1263+///
1264+/// Deliberately narrower than [`ensure_can_read_student`], which still gates
1265+/// the profile, booking and attendance reads at teacher+: **a teacher sees no
1266+/// money**. Canteen debt is family debt, so this is the same rule (and the same
1267+/// 403) `/payments` has always held β€” what a family owes the school is not
1268+/// classroom information, and neither is what it owes the canteen.
1269+async fn ensure_can_read_money(
1270+ caller: &User,
1271+ target: &UserId,
1272+ db: &Database,
1273+) -> Result<(), AppError> {
1274+ if caller.get_id() == target || caller.get_role().at_least(Role::Manager) {
1275+ return Ok(());
1276+ }
1277+ // The link row alone is not the grant: a link whose student side changed
1278+ // role must be inert, so the target's live role is re-read. A missing or
1279+ // non-student target falls through to the same 403 β€” a parent never gets an
1280+ // existence oracle.
1281+ if caller.get_role() == Role::Parent
1282+ && ParentLink::exists(caller.get_id(), target, db).await?
1283+ && User::read(target, db)
1284+ .await?
1285+ .is_some_and(|target| target.get_role() == Role::Student)
1286+ {
1287+ return Ok(());
1288+ }
1289+ Err(AppError::Forbidden(
1290+ "requires manager role or higher, or a parent link to this student",
1291+ ))
1292+}
1293+
1228 /// What the caller owes or has on account.1294 /// What the caller owes or has on account.
1229 #[utoipa::path(1295 #[utoipa::path(
1230 get,1296 get,
@@ -1243,8 +1309,9 @@ async fn my_balance(
1243 balance_response(user.get_id(), &st.db).await1309 balance_response(user.get_id(), &st.db).await
1244 }1310 }
1245 1311
1246-/// One student's meal balance. Requires teacher+, or a parent link to them β€”1312+/// One student's meal balance. Requires manager+, or a parent link to them β€”
1247-/// the caller's own id always passes.1313+/// the caller's own id always passes. A teacher gets a `403`: canteen debt is
1314+/// family debt, gated exactly like `/payments`.
1248 #[utoipa::path(1315 #[utoipa::path(
1249 get,1316 get,
1250 path = "/balance/{user}",1317 path = "/balance/{user}",
@@ -1254,7 +1321,7 @@ async fn my_balance(
1254 responses(1321 responses(
1255 (status = 200, description = "The student's meal balance", body = BalanceResponse),1322 (status = 200, description = "The student's meal balance", body = BalanceResponse),
1256 (status = 401, description = "Not authenticated", body = ErrorResponse),1323 (status = 401, description = "Not authenticated", body = ErrorResponse),
1257- (status = 403, description = "Requires teacher role or higher, or a parent link", body = ErrorResponse),1324+ (status = 403, description = "Requires manager role or higher, or a parent link", body = ErrorResponse),
1258 ),1325 ),
1259 )]1326 )]
1260 async fn user_balance(1327 async fn user_balance(
@@ -1263,7 +1330,7 @@ async fn user_balance(
1263 Path(user): Path<String>,1330 Path(user): Path<String>,
1264 ) -> Result<Json<BalanceResponse>, AppError> {1331 ) -> Result<Json<BalanceResponse>, AppError> {
1265 let target = UserId::from_key(&user);1332 let target = UserId::from_key(&user);
1266- ensure_can_read_student(&caller, &target, &st.db).await?;1333+ ensure_can_read_money(&caller, &target, &st.db).await?;
1267 balance_response(&target, &st.db).await1334 balance_response(&target, &st.db).await
1268 }1335 }
1269 1336
@@ -1280,7 +1347,7 @@ async fn user_balance(
1280 (status = 200, description = "A page of ledger lines (all of them when unpaged)", body = Page<LedgerResponse>),1347 (status = 200, description = "A page of ledger lines (all of them when unpaged)", body = Page<LedgerResponse>),
1281 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),1348 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
1282 (status = 401, description = "Not authenticated", body = ErrorResponse),1349 (status = 401, description = "Not authenticated", body = ErrorResponse),
1283- (status = 403, description = "Requires teacher role or higher, or a parent link", body = ErrorResponse),1350+ (status = 403, description = "Requires manager role or higher, or a parent link", body = ErrorResponse),
1284 ),1351 ),
1285 )]1352 )]
1286 async fn user_ledger(1353 async fn user_ledger(
@@ -1291,7 +1358,7 @@ async fn user_ledger(
1291 ) -> Result<Json<Page<LedgerResponse>>, AppError> {1358 ) -> Result<Json<Page<LedgerResponse>>, AppError> {
1292 let (limit, offset) = page.resolve()?;1359 let (limit, offset) = page.resolve()?;
1293 let target = UserId::from_key(&user);1360 let target = UserId::from_key(&user);
1294- ensure_can_read_student(&caller, &target, &st.db).await?;1361+ ensure_can_read_money(&caller, &target, &st.db).await?;
1295 let (rows, total) = MealLedger::list_for_student(&target, limit, offset, &st.db).await?;1362 let (rows, total) = MealLedger::list_for_student(&target, limit, offset, &st.db).await?;
1296 let items = ledger_responses(&rows, &st.db).await?;1363 let items = ledger_responses(&rows, &st.db).await?;
1297 Ok(Json(Page::new(items, total, limit, offset)))1364 Ok(Json(Page::new(items, total, limit, offset)))
@@ -1313,7 +1380,9 @@ struct RecordCredit {
1313 }1380 }
1314 1381
1315 /// Record money received from a student. **Admin only** β€” not manager: writing1382 /// Record money received from a student. **Admin only** β€” not manager: writing
1316-/// down cash is the highest-trust action in the app. Appends a `credit` line;1383+/// down cash is the highest-trust action in the app. The target must be a
1384+/// student, or anyone who already carries meal-ledger lines β€” a debt survives
1385+/// its debtor's role change, and it has to stay settleable. Appends a `credit` line;
1317 /// nothing in the ledger is ever edited or removed, so an over-credit is1386 /// nothing in the ledger is ever edited or removed, so an over-credit is
1318 /// corrected by a compensating line, not by a fix-up.1387 /// corrected by a compensating line, not by a fix-up.
1319 #[utoipa::path(1388 #[utoipa::path(
@@ -1337,12 +1406,20 @@ async fn record_credit(
1337 ) -> Result<(StatusCode, Json<LedgerResponse>), AppError> {1406 ) -> Result<(StatusCode, Json<LedgerResponse>), AppError> {
1338 let student = UserId::from_key(&req.student_id);1407 let student = UserId::from_key(&req.student_id);
1339 // Only a student carries a meal balance; crediting anyone else is a typo,1408 // Only a student carries a meal balance; crediting anyone else is a typo,
1340- // and a typo here is money in the wrong ledger.1409+ // and a typo here is money in the wrong ledger. Unless they already carry
1410+ // ledger lines: a debt outlives its debtor's role change (a student
1411+ // promoted to staff keeps what they owed), and the student rule alone made
1412+ // that debt permanently unsettleable β€” there is no other route that
1413+ // appends a credit. A typo'd staff id has no lines, so it still 400s.
1341 if User::read(&student, &st.db)1414 if User::read(&student, &st.db)
1342 .await?1415 .await?
1343 .ok_or(AppError::NotFound)?1416 .ok_or(AppError::NotFound)?
1344 .get_role()1417 .get_role()
1345 != Role::Student1418 != Role::Student
1419+ && MealLedger::list_for_student(&student, Some(1), 0, &st.db)
1420+ .await?
1421+ .0
1422+ .is_empty()
1346 {1423 {
1347 return Err(AppError::Validation(ValidationError::Invalid {1424 return Err(AppError::Validation(ValidationError::Invalid {
1348 field: "student_id",1425 field: "student_id",
src/web/settings.rsmodified+402 -31
@@ -12,7 +12,7 @@ use crate::database::Database;
12 use crate::domain::cap;12 use crate::domain::cap;
13 use crate::domain::exam_result::kind_ref;13 use crate::domain::exam_result::kind_ref;
14 use crate::domain::menu::slot_ref;14 use crate::domain::menu::slot_ref;
15-use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings};15+use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, SETTINGS_LOCK, Settings};
16 use crate::error::{AppError, ErrorResponse};16 use crate::error::{AppError, ErrorResponse};
17 use crate::state::AppState;17 use crate::state::AppState;
18 18
@@ -189,7 +189,10 @@ struct UpdateSettings {
189 /// (minutes past midnight **UTC**, `0`–`1439`) the booking cutoff counts189 /// (minutes past midnight **UTC**, `0`–`1439`) the booking cutoff counts
190 /// back from. `[]` switches the meal program off. A slot a menu was already190 /// back from. `[]` switches the meal program off. A slot a menu was already
191 /// published for cannot be removed (409); its serving time may be edited191 /// published for cannot be removed (409); its serving time may be edited
192- /// freely and applies live, to menus already published for it too.192+ /// freely and applies live, to menus already published for it too. Names
193+ /// must not contain `/ \ ? # %` (a menu's id carries the name into a URL) β€”
194+ /// except a name the school already stores, which stays submittable so a
195+ /// list written before that rule can still be edited.
193 #[schema(max_items = 20)]196 #[schema(max_items = 20)]
194 meal_slots: Option<Vec<MealSlotDto>>,197 meal_slots: Option<Vec<MealSlotDto>>,
195 /// Replaces the whole list when present: at most 20 unique entries, each198 /// Replaces the whole list when present: at most 20 unique entries, each
@@ -239,7 +242,10 @@ async fn get_settings(
239 /// applies at upload time only β€” already-stored files keep their size, and the242 /// applies at upload time only β€” already-stored files keep their size, and the
240 /// chatbot knobs apply to the next chat request only. `meal_slots` follows the243 /// chatbot knobs apply to the next chat request only. `meal_slots` follows the
241 /// exam-kind rule: a slot a menu was already published for cannot be dropped244 /// exam-kind rule: a slot a menu was already published for cannot be dropped
242-/// (409), because the menu snapshotted its name.245+/// (409), because the menu snapshotted its name. Slot names must not contain
246+/// `/ \ ? # %` (400) β€” a menu's id carries the name into a URL β€” but a name
247+/// already on the school's stored list is exempt, so a list written before that
248+/// rule can still be edited around it.
243 #[utoipa::path(249 #[utoipa::path(
244 patch,250 patch,
245 path = "/",251 path = "/",
@@ -259,12 +265,24 @@ async fn update_settings(
259 RequireManager(_user): RequireManager,265 RequireManager(_user): RequireManager,
260 Json(req): Json<UpdateSettings>,266 Json(req): Json<UpdateSettings>,
261 ) -> Result<Json<SettingsResponse>, AppError> {267 ) -> Result<Json<SettingsResponse>, AppError> {
268+ Ok(Json(SettingsResponse::new(&apply(&req, &st.db).await?)))
269+}
270+
271+/// The whole edit β€” snapshot, merge, retire, save β€” as one operation, so the
272+/// tests can drive it the way two managers do. Split out of the handler for
273+/// nothing else.
274+async fn apply(req: &UpdateSettings, db: &Database) -> Result<Settings, AppError> {
275+ // One settings edit at a time: the removals below are decided against the
276+ // snapshot this loop loads and written *before* the save that justifies
277+ // them, and no per-name bookkeeping can make that pair survive a rival's
278+ // pair interleaving with it (see `SETTINGS_LOCK`).
279+ let _guard = SETTINGS_LOCK.lock().await;
262 // Merge over a snapshot, then save only while the row still matches it β€”280 // Merge over a snapshot, then save only while the row still matches it β€”
263 // otherwise a concurrent PATCH of a *different* field would be silently281 // otherwise a concurrent PATCH of a *different* field would be silently
264 // reverted by whichever whole-row write lands second. A refused save282 // reverted by whichever whole-row write lands second. A refused save
265 // reloads and re-merges, so both edits land.283 // reloads and re-merges, so both edits land.
266 for _ in 0..CAS_UPDATE_RETRIES {284 for _ in 0..CAS_UPDATE_RETRIES {
267- let current = Settings::load(&st.db).await?;285+ let current = Settings::load(db).await?;
268 286
269 let exam_kinds = match &req.exam_kinds {287 let exam_kinds = match &req.exam_kinds {
270 Some(kinds) => kinds288 Some(kinds) => kinds
@@ -273,10 +291,21 @@ async fn update_settings(
273 .collect::<Result<Vec<_>, _>>()?,291 .collect::<Result<Vec<_>, _>>()?,
274 None => current.get_exam_kinds().to_vec(),292 None => current.get_exam_kinds().to_vec(),
275 };293 };
294+ let was_slots = slot_names(&current.get_meal_slots());
276 let meal_slots = match &req.meal_slots {295 let meal_slots = match &req.meal_slots {
277 Some(slots) => slots296 Some(slots) => slots
278 .iter()297 .iter()
279- .map(|slot| MealSlotDef::try_new(&slot.name, slot.serving_minute))298+ .map(|slot| {
299+ // A name the row already carries is validated as a kept one:
300+ // the charset rule is younger than the stored lists, and
301+ // re-validating one under it would leave a school unable to
302+ // edit the rest of its slots at all (`MealSlotDef::try_kept`).
303+ if was_slots.iter().any(|kept| kept == slot.name.trim()) {
304+ MealSlotDef::try_kept(&slot.name, slot.serving_minute)
305+ } else {
306+ MealSlotDef::try_new(&slot.name, slot.serving_minute)
307+ }
308+ })
280 .collect::<Result<Vec<_>, _>>()?,309 .collect::<Result<Vec<_>, _>>()?,
281 None => current.get_meal_slots(),310 None => current.get_meal_slots(),
282 };311 };
@@ -295,7 +324,6 @@ async fn update_settings(
295 // guards below β€” a list edit is judged by which names it drops.324 // guards below β€” a list edit is judged by which names it drops.
296 let was_kinds = kind_names(current.get_exam_kinds());325 let was_kinds = kind_names(current.get_exam_kinds());
297 let now_kinds = kind_names(&exam_kinds);326 let now_kinds = kind_names(&exam_kinds);
298- let was_slots = slot_names(&current.get_meal_slots());
299 let now_slots = slot_names(&meal_slots);327 let now_slots = slot_names(&meal_slots);
300 328
301 // Merge over the snapshot's resolved values: an omitted field keeps329 // Merge over the snapshot's resolved values: an omitted field keeps
@@ -336,17 +364,27 @@ async fn update_settings(
336 // Retired before the save, never after: the other order leaves a window364 // Retired before the save, never after: the other order leaves a window
337 // in which a mark lands under a kind the settings no longer list. A save365 // in which a mark lands under a kind the settings no longer list. A save
338 // that then does not land undoes them (`restore`) before the next try.366 // that then does not land undoes them (`restore`) before the next try.
339- let mut retired: Vec<RecordId> = Vec::new();367+ //
368+ // Only a write that actually *flipped* a bit is recorded for that undo.
369+ // Retirement is idempotent, so two PATCHes dropping the same kind are
370+ // both told "retired" β€” and the one whose save then loses the row's CAS
371+ // used to un-retire the winner's kind, leaving it off the list with its
372+ // counter in service: gradable again, its count then non-zero, and so
373+ // impossible to remove ever after.
374+ let mut undo: Vec<Undo> = Vec::new();
340 let mut refused = None;375 let mut refused = None;
341 for gone in missing(&was_kinds, &now_kinds) {376 for gone in missing(&was_kinds, &now_kinds) {
342 let counter = kind_ref(&gone);377 let counter = kind_ref(&gone);
343- if !cap::retire(&counter, &st.db).await? {378+ match cap::retire_name(&counter, db).await? {
344- refused = Some(AppError::ConflictOwned(format!(379+ cap::Switched::Flipped => undo.push(Undo::Retired(counter)),
345- "exams of kind '{gone}' are already graded β€” the kind cannot be removed"380+ cap::Switched::Unchanged => {}
346- )));381+ cap::Switched::InUse => {
347- break;382+ refused = Some(AppError::ConflictOwned(format!(
383+ "exams of kind '{gone}' are already graded β€” the kind cannot be removed"
384+ )));
385+ break;
386+ }
348 }387 }
349- retired.push(counter);
350 }388 }
351 // Same shape for meal slots: a slot a menu was already published for389 // Same shape for meal slots: a slot a menu was already published for
352 // cannot leave the list β€” the menu snapshotted the name as text, and a390 // cannot leave the list β€” the menu snapshotted the name as text, and a
@@ -355,37 +393,46 @@ async fn update_settings(
355 if refused.is_none() {393 if refused.is_none() {
356 for gone in missing(&was_slots, &now_slots) {394 for gone in missing(&was_slots, &now_slots) {
357 let counter = slot_ref(&gone);395 let counter = slot_ref(&gone);
358- if !cap::retire(&counter, &st.db).await? {396+ match cap::retire_name(&counter, db).await? {
359- refused = Some(AppError::ConflictOwned(format!(397+ cap::Switched::Flipped => undo.push(Undo::Retired(counter)),
360- "menus are already published for the '{gone}' slot β€” it cannot be removed"398+ cap::Switched::Unchanged => {}
361- )));399+ cap::Switched::InUse => {
362- break;400+ refused = Some(AppError::ConflictOwned(format!(
401+ "menus are already published for the '{gone}' slot β€” it cannot be removed"
402+ )));
403+ break;
404+ }
363 }405 }
364- retired.push(counter);
365 }406 }
366 }407 }
367 if let Some(refused) = refused {408 if let Some(refused) = refused {
368- restore(&retired, &st.db).await?;409+ restore(&undo, db).await?;
369 return Err(refused);410 return Err(refused);
370 }411 }
371 // A name re-entering a list is back in service: its counter still412 // A name re-entering a list is back in service: its counter still
372 // carries the retirement from the edit that dropped it, and a mark (or413 // carries the retirement from the edit that dropped it, and a mark (or
373 // a menu) under a kind the school offers again must not be refused.414 // a menu) under a kind the school offers again must not be refused.
415+ // Recorded for the same undo as the retirements β€” a re-add whose save
416+ // does not land leaves a name off the list that grades happily.
374 for back in missing(&now_kinds, &was_kinds) {417 for back in missing(&now_kinds, &was_kinds) {
375- cap::unretire(&kind_ref(&back), &st.db).await?;418+ if let cap::Switched::Flipped = cap::unretire_name(&kind_ref(&back), db).await? {
419+ undo.push(Undo::Unretired(kind_ref(&back)));
420+ }
376 }421 }
377 for back in missing(&now_slots, &was_slots) {422 for back in missing(&now_slots, &was_slots) {
378- cap::unretire(&slot_ref(&back), &st.db).await?;423+ if let cap::Switched::Flipped = cap::unretire_name(&slot_ref(&back), db).await? {
424+ undo.push(Undo::Unretired(slot_ref(&back)));
425+ }
379 }426 }
380 427
381- match settings.save_if_unchanged(&current, &st.db).await {428+ match settings.save_if_unchanged(&current, db).await {
382- Ok(Some(saved)) => return Ok(Json(SettingsResponse::new(&saved))),429+ Ok(Some(saved)) => return Ok(saved),
383 // The row moved under the snapshot these guards were judged against:430 // The row moved under the snapshot these guards were judged against:
384 // put the names back and re-merge, or the next attempt would decide431 // put the names back and re-merge, or the next attempt would decide
385 // against a list nobody asked for.432 // against a list nobody asked for.
386- Ok(None) => restore(&retired, &st.db).await?,433+ Ok(None) => restore(&undo, db).await?,
387 Err(err) => {434 Err(err) => {
388- restore(&retired, &st.db).await?;435+ restore(&undo, db).await?;
389 return Err(err);436 return Err(err);
390 }437 }
391 }438 }
@@ -419,11 +466,335 @@ fn missing(before: &[String], after: &[String]) -> Vec<String> {
419 .collect()466 .collect()
420 }467 }
421 468
422-/// Put back every name this attempt retired: the edit that would have removed469+/// One `retired` bit this attempt moved, and which way β€” what `restore` needs
423-/// them did not land, so they are still names the school offers.470+/// to put it back. Only bits this attempt actually *flipped* are listed: a
424-async fn restore(names: &[RecordId], db: &Database) -> Result<(), AppError> {471+/// write that changed nothing has nothing to take back, and taking it back
425- for name in names {472+/// would undo the concurrent edit that really did move it.
426- cap::unretire(name, db).await?;473+enum Undo {
474+ /// Retired for a removal; put it back in service.
475+ Retired(RecordId),
476+ /// Put back in service for a re-add; retire it again.
477+ Unretired(RecordId),
478+}
479+
480+/// Undo every bit this attempt moved: the edit that justified them did not
481+/// land, so the lists the school offers are still the ones it started with.
482+async fn restore(undo: &[Undo], db: &Database) -> Result<(), AppError> {
483+ for step in undo {
484+ match step {
485+ Undo::Retired(name) => {
486+ cap::unretire_name(name, db).await?;
487+ }
488+ // A re-retirement can be refused: a mark (or a menu) landed under
489+ // the name during the window it was in service. Refusing to undo is
490+ // then the honest answer β€” the reference is real, and retiring over
491+ // it would make the row's kind ungradable while nothing lists it.
492+ // The name is left in service, matching the list this attempt is
493+ // about to re-read.
494+ Undo::Unretired(name) => {
495+ cap::retire_name(name, db).await?;
496+ }
497+ }
427 }498 }
428 Ok(())499 Ok(())
429 }500 }
501+
502+#[cfg(test)]
503+mod tests {
504+ use super::*;
505+ use crate::database::init_mem;
506+
507+ /// The `retired` bit as the store holds it, `None` when no counter row was
508+ /// ever written β€” read back, never inferred from a return value.
509+ async fn bit(db: &Database, counter: RecordId) -> Option<bool> {
510+ let mut result = db
511+ .query("SELECT VALUE retired FROM $id")
512+ .bind(("id", counter))
513+ .await
514+ .unwrap()
515+ .check()
516+ .unwrap();
517+ result.take::<Vec<bool>>(0).unwrap().first().copied()
518+ }
519+
520+ /// Two managers drop the same exam kind at once; one of them loses the
521+ /// row's compare-and-set and rolls its attempt back. The winner's
522+ /// retirement must survive that rollback β€” undone, the kind is off the list
523+ /// with a counter that still grades, and the first mark to land makes it
524+ /// unremovable for good.
525+ ///
526+ /// The loser's half is what runs here: a retirement that changed nothing
527+ /// records no undo, so `restore` has nothing to take back.
528+ #[tokio::test]
529+ async fn the_loser_of_a_settings_race_cannot_un_retire_the_winner_s_kind() {
530+ let db = init_mem().await.unwrap();
531+ let counter = kind_ref("midterm");
532+
533+ // The winner's PATCH retires the kind.
534+ assert!(matches!(
535+ cap::retire_name(&counter, &db).await.unwrap(),
536+ cap::Switched::Flipped
537+ ));
538+
539+ // The loser's PATCH decides the same removal against the same snapshot,
540+ // then its save is refused.
541+ let mut undo = Vec::new();
542+ if let cap::Switched::Flipped = cap::retire_name(&counter, &db).await.unwrap() {
543+ undo.push(Undo::Retired(counter.clone()));
544+ }
545+ assert!(undo.is_empty(), "a no-op retirement records no undo");
546+ restore(&undo, &db).await.unwrap();
547+
548+ assert_eq!(
549+ bit(&db, counter).await,
550+ Some(true),
551+ "the winner's retirement must outlive the loser's rollback"
552+ );
553+ }
554+
555+ /// The mirror hole: a re-*added* name is put back in service before the
556+ /// save, so a save that does not land owes a re-retirement. Without it the
557+ /// name is off the stored list with a counter that grades happily.
558+ #[tokio::test]
559+ async fn a_rollback_re_retires_a_name_this_attempt_put_back_in_service() {
560+ let db = init_mem().await.unwrap();
561+ let counter = slot_ref("lunch");
562+ cap::retire_name(&counter, &db).await.unwrap();
563+
564+ // The attempt re-adds the slot, then its save is refused.
565+ let mut undo = Vec::new();
566+ if let cap::Switched::Flipped = cap::unretire_name(&counter, &db).await.unwrap() {
567+ undo.push(Undo::Unretired(counter.clone()));
568+ }
569+ assert_eq!(undo.len(), 1, "a real un-retirement is undoable");
570+ restore(&undo, &db).await.unwrap();
571+
572+ assert_eq!(
573+ bit(&db, counter).await,
574+ Some(true),
575+ "a re-add that never landed must leave the slot retired"
576+ );
577+ }
578+
579+ /// ...unless a menu was published in the window the slot was back in
580+ /// service. The reference is real, so the re-retirement is refused and the
581+ /// slot stays usable β€” the honest end of the same rule, not a silent
582+ /// overwrite of a live reference.
583+ #[tokio::test]
584+ async fn a_rollback_leaves_a_name_that_gained_a_reference_in_service() {
585+ let db = init_mem().await.unwrap();
586+ let counter = slot_ref("lunch");
587+ cap::retire_name(&counter, &db).await.unwrap();
588+ cap::unretire_name(&counter, &db).await.unwrap();
589+ db.query("UPDATE $id SET count = 1")
590+ .bind(("id", counter.clone()))
591+ .await
592+ .unwrap()
593+ .check()
594+ .unwrap();
595+
596+ restore(&[Undo::Unretired(counter.clone())], &db)
597+ .await
598+ .unwrap();
599+
600+ assert_eq!(bit(&db, counter).await, Some(false));
601+ }
602+
603+ // --- the whole edit, driven the way two managers drive it -------------
604+
605+ /// A `PATCH` body, built the way the router builds one.
606+ fn patch(body: serde_json::Value) -> UpdateSettings {
607+ serde_json::from_value(body).unwrap()
608+ }
609+
610+ /// A `meal_slots`/`exam_kinds` list as the DTO carries it.
611+ fn kinds(names: &[&str]) -> serde_json::Value {
612+ names
613+ .iter()
614+ .map(|name| serde_json::json!({ "name": name, "weight": 1 }))
615+ .collect()
616+ }
617+
618+ fn slots(names: &[&str]) -> serde_json::Value {
619+ names
620+ .iter()
621+ .map(|name| serde_json::json!({ "name": name, "serving_minute": null }))
622+ .collect()
623+ }
624+
625+ /// The lists as the store holds them.
626+ async fn stored(db: &Database) -> (Vec<String>, Vec<String>) {
627+ let settings = Settings::load(db).await.unwrap();
628+ (
629+ kind_names(settings.get_exam_kinds()),
630+ slot_names(&settings.get_meal_slots()),
631+ )
632+ }
633+
634+ /// The whole invariant, over the reachable half of the race: two managers
635+ /// drop the same exam kind at once, both edits go through the real path,
636+ /// and when both have returned the counter's `retired` bit must agree with
637+ /// the list the store actually holds.
638+ ///
639+ /// One of the two decides the removal, retires the kind and saves; the
640+ /// other cannot even see the old list, because the whole snapshot-retire-
641+ /// save pair is serialized (`SETTINGS_LOCK`). Interleaved, the second
642+ /// attempt would be told "already retired", record no undo, win the
643+ /// compare-and-set, and leave the first attempt un-retiring the kind it had
644+ /// legitimately removed β€” off the list and gradable.
645+ #[tokio::test]
646+ async fn two_edits_dropping_the_same_kind_leave_it_retired() {
647+ let db = init_mem().await.unwrap();
648+ let without = patch(serde_json::json!({
649+ "exam_kinds": kinds(&["homework", "quiz", "final", "project", "oral"]),
650+ }));
651+
652+ let (a, b) = tokio::join!(apply(&without, &db), apply(&without, &db));
653+ a.unwrap();
654+ b.unwrap();
655+
656+ let (kinds, _) = stored(&db).await;
657+ assert!(
658+ !kinds.contains(&"midterm".to_string()),
659+ "dropped from the list"
660+ );
661+ assert_eq!(
662+ bit(&db, kind_ref("midterm")).await,
663+ Some(true),
664+ "a kind the stored list no longer offers must not grade"
665+ );
666+ }
667+
668+ /// The property those two outcomes rest on, asserted on its own because a
669+ /// `join!` cannot be made to schedule the losing order: the edit is a pair
670+ /// of writes β€” retire the dropped names, then commit the list β€” and no
671+ /// rival's pair may run between them.
672+ ///
673+ /// Retirement is idempotent, so an interleaved rival is told "already
674+ /// retired", records no rollback, wins the compare-and-set, and leaves the
675+ /// attempt that really flipped the bit un-retiring a kind the stored list
676+ /// no longer offers: gradable again, and unremovable for good once a mark
677+ /// lands. Holding the lock stands in for a rival mid-pair here β€” nothing
678+ /// the other edit does may be visible until the pair completes.
679+ #[tokio::test]
680+ async fn a_rival_edit_cannot_run_between_a_retirement_and_its_save() {
681+ let db = init_mem().await.unwrap();
682+ let without = patch(serde_json::json!({
683+ "exam_kinds": kinds(&["homework", "quiz", "final", "project", "oral"]),
684+ }));
685+
686+ let held = SETTINGS_LOCK.lock().await;
687+ let rival = tokio::spawn({
688+ let db = db.clone();
689+ async move { apply(&without, &db).await.map(|_| ()) }
690+ });
691+ tokio::time::sleep(std::time::Duration::from_millis(200)).await;
692+
693+ assert_eq!(
694+ bit(&db, kind_ref("midterm")).await,
695+ None,
696+ "a rival's pair must not have started, let alone half-landed"
697+ );
698+ assert!(stored(&db).await.0.contains(&"midterm".to_string()));
699+
700+ drop(held);
701+ rival.await.unwrap().unwrap();
702+ assert_eq!(bit(&db, kind_ref("midterm")).await, Some(true));
703+ assert!(!stored(&db).await.0.contains(&"midterm".to_string()));
704+ }
705+
706+ /// The mirror: two managers put the same kind *back* at once. The attempt
707+ /// that loses must not re-retire a name the winner's stored list carries β€”
708+ /// a listed kind that refuses every grade.
709+ #[tokio::test]
710+ async fn two_edits_re_adding_the_same_kind_leave_it_in_service() {
711+ let db = init_mem().await.unwrap();
712+ let without = patch(serde_json::json!({
713+ "exam_kinds": kinds(&["homework", "quiz", "final", "project", "oral"]),
714+ }));
715+ apply(&without, &db).await.unwrap();
716+ let with = patch(serde_json::json!({
717+ "exam_kinds": kinds(&["homework", "quiz", "midterm", "final", "project", "oral"]),
718+ }));
719+
720+ let (a, b) = tokio::join!(apply(&with, &db), apply(&with, &db));
721+ a.unwrap();
722+ b.unwrap();
723+
724+ let (kinds, _) = stored(&db).await;
725+ assert!(kinds.contains(&"midterm".to_string()), "back on the list");
726+ assert_eq!(
727+ bit(&db, kind_ref("midterm")).await,
728+ Some(false),
729+ "a kind the stored list offers must grade"
730+ );
731+ }
732+
733+ /// The same pair over meal slots, which retire on their own counters.
734+ #[tokio::test]
735+ async fn two_edits_dropping_the_same_slot_leave_it_retired() {
736+ let db = init_mem().await.unwrap();
737+ let without = patch(serde_json::json!({
738+ "meal_slots": slots(&["breakfast", "snack"]),
739+ }));
740+
741+ let (a, b) = tokio::join!(apply(&without, &db), apply(&without, &db));
742+ a.unwrap();
743+ b.unwrap();
744+
745+ let (_, stored_slots) = stored(&db).await;
746+ assert!(!stored_slots.contains(&"lunch".to_string()));
747+ assert_eq!(bit(&db, slot_ref("lunch")).await, Some(true));
748+ }
749+
750+ // --- the stale slot name that wedged the whole list -------------------
751+
752+ /// A school that stored `a/b` before the URL-safety rule existed.
753+ async fn a_school_with_a_stale_slot(db: &Database) {
754+ let mut params = Settings::defaults().params();
755+ params.meal_slots = vec![
756+ MealSlotDef::try_kept("a/b", None).unwrap(),
757+ MealSlotDef::try_new("lunch", None).unwrap(),
758+ ];
759+ Settings::try_new(params).unwrap().save(db).await.unwrap();
760+ }
761+
762+ /// The wedge: re-sending a stored name is the only way to *keep* it, and
763+ /// dropping it 409s once a menu references it β€” so validating it under the
764+ /// younger rule locks the school out of its own `meal_slots` forever. A
765+ /// stored name is submittable; a new one with the same characters is not.
766+ #[tokio::test]
767+ async fn a_stored_slot_name_stays_submittable_but_a_new_one_does_not() {
768+ let db = init_mem().await.unwrap();
769+ a_school_with_a_stale_slot(&db).await;
770+
771+ let edit = patch(serde_json::json!({
772+ "meal_slots": slots(&["a/b", "lunch", "dinner"]),
773+ }));
774+ apply(&edit, &db).await.unwrap();
775+ let (_, stored_slots) = stored(&db).await;
776+ assert_eq!(stored_slots, ["a/b", "lunch", "dinner"]);
777+
778+ let fresh = patch(serde_json::json!({
779+ "meal_slots": slots(&["a/b", "lunch", "c/d"]),
780+ }));
781+ assert!(
782+ apply(&fresh, &db).await.is_err(),
783+ "a name no school ever stored is still refused"
784+ );
785+ }
786+
787+ /// And an edit that never mentions `meal_slots` still carries the list
788+ /// over unvalidated β€” the behaviour the wedge report leaned on.
789+ #[tokio::test]
790+ async fn an_unrelated_edit_carries_a_stale_slot_name_over() {
791+ let db = init_mem().await.unwrap();
792+ a_school_with_a_stale_slot(&db).await;
793+
794+ let elsewhere = patch(serde_json::json!({ "max_file_bytes": 2048 }));
795+ let saved = apply(&elsewhere, &db).await.unwrap();
796+
797+ assert_eq!(saved.get_max_file_bytes(), 2048);
798+ assert_eq!(slot_names(&saved.get_meal_slots()), ["a/b", "lunch"]);
799+ }
800+}
src/web/users.rsmodified+6 -9
@@ -7,9 +7,8 @@ use utoipa_axum::router::OpenApiRouter;
7 use utoipa_axum::routes;7 use utoipa_axum::routes;
8 8
9 use crate::database::Database;9 use crate::database::Database;
10-use crate::domain::class_member::ClassMember;10+use crate::domain::class_pump;
11 use crate::domain::course::Course;11 use crate::domain::course::Course;
12-use crate::domain::enrollment::Enrollment;
13 use crate::domain::parent_link::ParentLink;12 use crate::domain::parent_link::ParentLink;
14 use crate::domain::preferences::{Language, PaletteColor, Theme};13 use crate::domain::preferences::{Language, PaletteColor, Theme};
15 use crate::domain::profile::{BirthDate, Email, PersonName, Phone};14 use crate::domain::profile::{BirthDate, Email, PersonName, Phone};
@@ -399,14 +398,12 @@ async fn set_role(
399 // Parent links get the same sweep on both sides: only students are398 // Parent links get the same sweep on both sides: only students are
400 // observed and only parents observe, so a role change off either end399 // observed and only parents observe, so a role change off either end
401 // drops the rows instead of leaving dead grants around.400 // drops the rows instead of leaving dead grants around.
402- // The class memberships go first and the enrollments second: the class401+ // The class memberships and the enrollments go in *one* transaction: run
403- // sweep deliberately leaves the enrollment rows alone, so running it after402+ // as two, a failure between them left enrollment rows tagged with a class
404- // would find nothing to repair and running it before costs nothing either403+ // whose counters had already been released, so the class could be deleted
405- // way. Both are needed β€” a membership left behind would keep pumping the404+ // and nothing could ever sweep the rows again.
406- // user back into courses and make its class undeletable.
407 if role != Role::Student {405 if role != Role::Student {
408- ClassMember::delete_for_user(&target, &st.db).await?;406+ class_pump::sweep_non_student(&target, &st.db).await?;
409- Enrollment::delete_for_user(&target, &st.db).await?;
410 ParentLink::delete_where_student(&target, &st.db).await?;407 ParentLink::delete_where_student(&target, &st.db).await?;
411 }408 }
412 if role != Role::Parent {409 if role != Role::Parent {
tests/e2e.rsmodified+38 -0
@@ -3003,6 +3003,44 @@ async fn a_roster_change_drops_only_the_socket_it_removed() {
3003 );3003 );
3004 }3004 }
3005 3005
3006+/// Test 15 β€” clearing a blank canvas is a *live* board saying "nothing to do",
3007+/// and the room must say so with a non-terminal code. It shipped as
3008+/// `board_closed` β€” the terminal one β€” because the classifier guessed the code
3009+/// from a substring of the refusal's words, and the reworded refusal happens to
3010+/// contain "closed". A creator who double-clicks clear would have been told the
3011+/// board was finished forever, on a board still open and still drawable.
3012+#[tokio::test]
3013+async fn clearing_a_blank_canvas_never_tells_the_room_the_board_is_closed() {
3014+ let room = board_room_fixture().await;
3015+ let (base, board) = (&room.base, &room.board_id);
3016+ let mut ali = board_open(base, board, Some(&room.creator_cookie))
3017+ .await
3018+ .expect("upgrade");
3019+ board_join(&mut ali, None, None).await;
3020+
3021+ // Nothing drawn yet: there is no epoch to close.
3022+ ws_send(&mut ali, json!({ "type": "clear" })).await;
3023+ let error = board_frame_of_type(&mut ali, "error").await;
3024+ assert_eq!(error["code"], "canvas_blank", "{error}");
3025+
3026+ // The same refusal after a real clear β€” the second press of the button.
3027+ board_draw(&mut ali, "one").await;
3028+ ws_send(&mut ali, json!({ "type": "clear" })).await;
3029+ board_frame_of_type(&mut ali, "cleared").await;
3030+ ws_send(&mut ali, json!({ "type": "clear" })).await;
3031+ assert_eq!(
3032+ board_frame_of_type(&mut ali, "error").await["code"],
3033+ "canvas_blank"
3034+ );
3035+
3036+ // And the board really is live: the socket draws on, into the new epoch.
3037+ board_draw(&mut ali, "two").await;
3038+ assert_eq!(
3039+ stored_payloads(&room.db, board, 1).await,
3040+ vec!["two".to_string()]
3041+ );
3042+}
3043+
3006 /// The class layer over real HTTP with three cookie jars: the office builds the3044 /// The class layer over real HTTP with three cookie jars: the office builds the
3007 /// class, the teacher hands over their own course, and the student β€” who was3045 /// class, the teacher hands over their own course, and the student β€” who was
3008 /// never enrolled by anyone β€” finds it on `GET /courses/me`. Taking them out of3046 /// never enrolled by anyone β€” finds it on `GET /courses/me`. Taking them out of
tests/integration.rsmodified+102 -5
@@ -22076,9 +22076,9 @@ async fn meal_credits_are_admin_only_and_raise_the_balance() {
22076 }22076 }
22077 22077
22078 /// Whose money a caller may read: their own, their linked child's, or β€” as22078 /// Whose money a caller may read: their own, their linked child's, or β€” as
22079-/// teacher+ β€” anyone's. Never another family's.22079+/// manager+ β€” anyone's. Never another family's, and never a teacher's business.
22080 #[tokio::test]22080 #[tokio::test]
22081-async fn meal_balance_reads_follow_the_observer_gate() {22081+async fn meal_balance_reads_are_manager_only_outside_the_family() {
22082 let (app, db) = app_and_db().await;22082 let (app, db) = app_and_db().await;
22083 let admin = login_as(&app, &db, "wallet_boss", "admin").await;22083 let admin = login_as(&app, &db, "wallet_boss", "admin").await;
22084 let teacher = login_as(&app, &db, "wallet_teacher", "teacher").await;22084 let teacher = login_as(&app, &db, "wallet_teacher", "teacher").await;
@@ -22149,7 +22149,8 @@ async fn meal_balance_reads_follow_the_observer_gate() {
22149 .await;22149 .await;
22150 assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);22150 assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
22151 22151
22152- // Teacher+ reads any student's.22152+ // A teacher does not, however: what a family owes the canteen is money,
22153+ // and money is manager+ here exactly as it is on /payments.
22153 let res = send(22154 let res = send(
22154 &app,22155 &app,
22155 "GET",22156 "GET",
@@ -22158,6 +22159,17 @@ async fn meal_balance_reads_follow_the_observer_gate() {
22158 None,22159 None,
22159 )22160 )
22160 .await;22161 .await;
22162+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
22163+
22164+ // Manager+ reads any student's.
22165+ let res = send(
22166+ &app,
22167+ "GET",
22168+ &format!("/meals/balance/{ali_id}"),
22169+ Some(&admin),
22170+ None,
22171+ )
22172+ .await;
22161 assert_eq!(res.status, StatusCode::OK, "{}", res.body);22173 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
22162 }22174 }
22163 22175
@@ -22322,6 +22334,90 @@ async fn meal_attendance_never_moves_money() {
22322 assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);22334 assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
22323 }22335 }
22324 22336
22337+/// Deleting a menu takes its marks with it. The menu id is deterministic on
22338+/// `(date, slot)`, so republishing the same meal mints the *same* record id: a
22339+/// mark left behind by the deleted menu would come back as a mark on the new
22340+/// one β€” the kitchen would read "served" for a student who never came, and the
22341+/// student's own report would cite a menu that no longer exists.
22342+#[tokio::test]
22343+async fn deleting_a_menu_takes_its_attendance_with_it() {
22344+ let (app, db) = app_and_db().await;
22345+ let mgr = login_as(&app, &db, "ghost_mgr", "manager").await;
22346+ let teacher = login_as(&app, &db, "ghost_teacher", "teacher").await;
22347+ let ali = login(&app, "ghost_ali").await;
22348+ let ali_id = me_id(&app, &ali).await;
22349+
22350+ let publish = json!({ "date": "2026-10-05", "slot": "lunch" });
22351+ let res = send(
22352+ &app,
22353+ "POST",
22354+ "/meals/menus",
22355+ Some(&mgr),
22356+ Some(publish.clone()),
22357+ )
22358+ .await;
22359+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
22360+ let menu = id_of(&res.body);
22361+
22362+ let res = send(
22363+ &app,
22364+ "POST",
22365+ &format!("/meals/menus/{menu}/attendance"),
22366+ Some(&teacher),
22367+ Some(json!({ "student_id": ali_id, "status": "served" })),
22368+ )
22369+ .await;
22370+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
22371+
22372+ // No seat was ever taken, so the counter guard lets the delete through.
22373+ let res = send(
22374+ &app,
22375+ "DELETE",
22376+ &format!("/meals/menus/{menu}"),
22377+ Some(&mgr),
22378+ None,
22379+ )
22380+ .await;
22381+ assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
22382+
22383+ // The student's own report must not cite a menu that is gone.
22384+ let res = send(
22385+ &app,
22386+ "GET",
22387+ &format!("/meals/attendance/{ali_id}"),
22388+ Some(&teacher),
22389+ None,
22390+ )
22391+ .await;
22392+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
22393+ assert_eq!(
22394+ common::total(&res.body),
22395+ 0,
22396+ "the mark outlived the menu it was taken on"
22397+ );
22398+
22399+ // Republishing the same day and slot lands on the same record id.
22400+ let res = send(&app, "POST", "/meals/menus", Some(&mgr), Some(publish)).await;
22401+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
22402+ let again = id_of(&res.body);
22403+ assert_eq!(again, menu, "the id is deterministic on (date, slot)");
22404+
22405+ let res = send(
22406+ &app,
22407+ "GET",
22408+ &format!("/meals/menus/{menu}/attendance"),
22409+ Some(&teacher),
22410+ None,
22411+ )
22412+ .await;
22413+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
22414+ assert_eq!(
22415+ common::total(&res.body),
22416+ 0,
22417+ "the deleted menu's mark came back on the republished one"
22418+ );
22419+}
22420+
22325 /// The per-student report: a lexical `?from=&to=` window over the menu's day,22421 /// The per-student report: a lexical `?from=&to=` window over the menu's day,
22326 /// readable by teacher+ or a linked parent and by nobody else.22422 /// readable by teacher+ or a linked parent and by nobody else.
22327 #[tokio::test]22423 #[tokio::test]
@@ -24718,8 +24814,9 @@ async fn a_full_canvas_is_refused_until_the_creator_clears_it() {
24718 );24814 );
24719 assert_eq!(24815 assert_eq!(
24720 stored_counters(&db, &board).await,24816 stored_counters(&db, &board).await,
24721- vec![1, MAX_EPOCH_STROKES + 1],24817+ vec![1, MAX_EPOCH_STROKES + 2],
24722- "the epoch counter reset; the lifetime counter did not"24818+ "the epoch counter reset; the lifetime counter kept the clear marker \
24819+ it minted and the new stroke"
24723 );24820 );
24724 let res = send(24821 let res = send(
24725 &app,24822 &app,
tests/persistence.rsmodified+3 -2
@@ -2079,8 +2079,9 @@ async fn boards_and_their_strokes_survive_remigration() {
2079 .unwrap();2079 .unwrap();
2080 assert_eq!(2080 assert_eq!(
2081 result.take::<Vec<Vec<i64>>>(0).unwrap()[0],2081 result.take::<Vec<Vec<i64>>>(0).unwrap()[0],
2082- vec![1, 3, 1],2082+ vec![1, 4, 1],
2083- "epoch counter, lifetime counter and the creator's board_count"2083+ "epoch counter, lifetime counter (three strokes and the clear marker \
2084+ they paid for) and the creator's board_count"
2084 );2085 );
2085 2086
2086 // And the board is still writable after the boot β€” the counters that came2087 // And the board is still writable after the boot β€” the counters that came
tests/regress_caps.rsadded+607 -0
@@ -0,0 +1,607 @@
1+//! Regressions for the counter/cap defects found in the 2026-08-02 sweep:
2+//! settings retirement rollback, the exam-kind gate on grading, snapshotted
3+//! caps, and the whiteboard clear marker.
4+//!
5+//! Everything here is deterministic. Where a defect only bites a true race, the
6+//! *reachable half* is driven instead β€” the corrupt state the race leaves
7+//! behind is written straight into the store, and the assertion is on what the
8+//! store holds afterwards. The in-memory engine forges wins under concurrency
9+//! (src/domain/cap.rs), so no test below asks it who won.
10+
11+mod common;
12+
13+use axum::http::StatusCode;
14+use common::{app_and_db, create_course, create_exam, enroll, id_of, login, login_as, me_id, send};
15+use hezarfen_backend::domain::board::BoardId;
16+use hezarfen_backend::domain::board_stroke::BoardStroke;
17+use hezarfen_backend::domain::user::UserId;
18+use serde_json::json;
19+
20+/// The default kinds, minus one β€” the body a manager sends to drop `midterm`.
21+fn kinds_without_midterm() -> serde_json::Value {
22+ json!({"exam_kinds": [{"name": "final", "weight": 3}, {"name": "oral", "weight": 1}]})
23+}
24+
25+/// Grading is gated twice: by the school's list and by the kind's reference
26+/// counter. Only the counter used to be consulted, so *any* disagreement
27+/// between the two records reopened grading under a kind nobody offers β€” which
28+/// is exactly what a settings PATCH whose save lost the row's compare-and-set
29+/// used to leave behind (it un-retired the winner's kind). The list is the
30+/// school's own answer, so it refuses on its own.
31+#[tokio::test]
32+async fn a_kind_off_the_schools_list_cannot_be_graded_even_with_a_live_counter() {
33+ let (app, db) = app_and_db().await;
34+ let teacher = login_as(&app, &db, "ogretmen", "teacher").await;
35+ let manager = login_as(&app, &db, "mudur", "manager").await;
36+ let student = login(&app, "ogrenci").await;
37+ let student_id = me_id(&app, &student).await;
38+ let course = create_course(&app, &teacher, "Matematik").await;
39+ enroll(&app, &teacher, &course, &student_id).await;
40+ let exam = create_exam(&app, &teacher, &course, "Vize", "midterm").await;
41+
42+ // The kind leaves the list β€” legal, nothing is graded under it yet.
43+ let res = send(
44+ &app,
45+ "PATCH",
46+ "/settings",
47+ Some(&manager),
48+ Some(kinds_without_midterm()),
49+ )
50+ .await;
51+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
52+
53+ // The corrupt half a lost settings race used to leave: the name is off the
54+ // list, but its counter says "in service".
55+ db.query("UPSERT kind_ref:midterm SET retired = false")
56+ .await
57+ .unwrap()
58+ .check()
59+ .unwrap();
60+
61+ let res = send(
62+ &app,
63+ "POST",
64+ &format!("/exams/{exam}/results"),
65+ Some(&teacher),
66+ Some(json!({ "user_id": student_id, "mark": 80 })),
67+ )
68+ .await;
69+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
70+ assert!(
71+ res.body["error"]
72+ .as_str()
73+ .unwrap()
74+ .contains("removed from the school's settings"),
75+ "{}",
76+ res.body
77+ );
78+
79+ // And nothing landed: no mark, and the exam's result counter never moved.
80+ let res = send(
81+ &app,
82+ "GET",
83+ &format!("/exams/{exam}/results"),
84+ Some(&teacher),
85+ None,
86+ )
87+ .await;
88+ assert_eq!(common::total(&res.body), 0);
89+}
90+
91+/// Putting the kind back in the list makes the very same grade land β€” the gate
92+/// is the list, not a one-way door.
93+#[tokio::test]
94+async fn re_adding_the_kind_lets_the_grade_land() {
95+ let (app, db) = app_and_db().await;
96+ let teacher = login_as(&app, &db, "ogretmen", "teacher").await;
97+ let manager = login_as(&app, &db, "mudur", "manager").await;
98+ let student = login(&app, "ogrenci").await;
99+ let student_id = me_id(&app, &student).await;
100+ let course = create_course(&app, &teacher, "Matematik").await;
101+ enroll(&app, &teacher, &course, &student_id).await;
102+ let exam = create_exam(&app, &teacher, &course, "Vize", "midterm").await;
103+ let grade = json!({ "user_id": student_id, "mark": 80 });
104+
105+ send(
106+ &app,
107+ "PATCH",
108+ "/settings",
109+ Some(&manager),
110+ Some(kinds_without_midterm()),
111+ )
112+ .await;
113+ let res = send(
114+ &app,
115+ "POST",
116+ &format!("/exams/{exam}/results"),
117+ Some(&teacher),
118+ Some(grade.clone()),
119+ )
120+ .await;
121+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
122+
123+ let res = send(
124+ &app,
125+ "PATCH",
126+ "/settings",
127+ Some(&manager),
128+ Some(json!({"exam_kinds": [
129+ {"name": "midterm", "weight": 2},
130+ {"name": "final", "weight": 3},
131+ {"name": "oral", "weight": 1},
132+ ]})),
133+ )
134+ .await;
135+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
136+
137+ let res = send(
138+ &app,
139+ "POST",
140+ &format!("/exams/{exam}/results"),
141+ Some(&teacher),
142+ Some(grade),
143+ )
144+ .await;
145+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
146+}
147+
148+/// The chatbot cap lives on the *settings singleton*, not on the row the seat
149+/// is taken on, so the claim sub-queries it inside its own conditional write.
150+/// A cap read at the wrong place answers one of two ways β€” always the built-in
151+/// default (the school's edit ignored) or always zero (nobody may ever start a
152+/// thread) β€” and this pins it against both.
153+#[tokio::test]
154+async fn the_chatbot_cap_is_the_one_on_the_settings_row() {
155+ let (app, db) = app_and_db().await;
156+ let manager = login_as(&app, &db, "mudur", "manager").await;
157+ let user = login(&app, "ali").await;
158+
159+ let res = send(
160+ &app,
161+ "PATCH",
162+ "/settings",
163+ Some(&manager),
164+ Some(json!({ "max_chatbot_threads": 1 })),
165+ )
166+ .await;
167+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
168+
169+ // One thread fits the school's cap of 1...
170+ let res = start_thread(&app, &user).await;
171+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
172+ // ...the second does not. (Under the built-in default of 50 it would.)
173+ let res = start_thread(&app, &user).await;
174+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
175+
176+ // Raising the cap re-opens it, which no always-zero read could do.
177+ let res = send(
178+ &app,
179+ "PATCH",
180+ "/settings",
181+ Some(&manager),
182+ Some(json!({ "max_chatbot_threads": 2 })),
183+ )
184+ .await;
185+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
186+ let res = start_thread(&app, &user).await;
187+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
188+}
189+
190+/// Open one chatbot thread as `cookie`.
191+async fn start_thread(app: &axum::Router, cookie: &str) -> common::Res {
192+ send(
193+ app,
194+ "POST",
195+ "/chatbot/threads",
196+ Some(cookie),
197+ Some(json!({ "title": "Soru" })),
198+ )
199+ .await
200+}
201+
202+/// The registration cap is read off `audience.capacity` on the event row as the
203+/// seat is taken, not bound as a number the handler read first. A mis-aimed
204+/// live read is an *unlimited* list (the column reads `NONE`), so the refusal
205+/// below is what proves the expression lands on the real column.
206+#[tokio::test]
207+async fn a_registration_list_is_capped_by_the_column_on_its_own_row() {
208+ let (app, db) = app_and_db().await;
209+ let teacher = login_as(&app, &db, "ogretmen", "teacher").await;
210+ let first = login(&app, "ali").await;
211+ let second = login(&app, "veli").await;
212+ let first_id = me_id(&app, &first).await;
213+ let second_id = me_id(&app, &second).await;
214+
215+ let res = send(
216+ &app,
217+ "POST",
218+ "/events",
219+ Some(&teacher),
220+ Some(json!({
221+ "title": "Gezi",
222+ "audience": { "kind": "registration", "capacity": 1 },
223+ })),
224+ )
225+ .await;
226+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
227+ let event = id_of(&res.body);
228+
229+ let res = seat(&app, &teacher, &event, &first_id).await;
230+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
231+ let res = seat(&app, &teacher, &event, &second_id).await;
232+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
233+
234+ // The refusal wrote nothing: one seat, one row.
235+ let res = send(
236+ &app,
237+ "GET",
238+ &format!("/events/{event}/roster"),
239+ Some(&teacher),
240+ None,
241+ )
242+ .await;
243+ assert_eq!(common::total(&res.body), 1, "{}", res.body);
244+}
245+
246+/// Put `user` on `event`'s signup list as `cookie`.
247+async fn seat(app: &axum::Router, cookie: &str, event: &str, user: &str) -> common::Res {
248+ send(
249+ app,
250+ "POST",
251+ &format!("/events/{event}/register"),
252+ Some(cookie),
253+ Some(json!({ "user_id": user })),
254+ )
255+ .await
256+}
257+
258+/// A whiteboard clear mints a real `board_stroke` row (the epoch marker) and
259+/// claims neither counter, so a clear of an already-blank canvas was a free row
260+/// β€” pressed in a loop, an unbounded table behind a cap that only ever counted
261+/// strokes *drawn*. Nothing to clear is now a refusal, which pays for every
262+/// marker with at least one stroke it closes.
263+#[tokio::test]
264+async fn a_blank_canvas_cannot_be_cleared_for_a_free_row() {
265+ let (app, db) = app_and_db().await;
266+ let ali = login(&app, "ali").await;
267+ let ali_id = me_id(&app, &ali).await;
268+ let res = send(
269+ &app,
270+ "POST",
271+ "/boards",
272+ Some(&ali),
273+ Some(json!({ "title": "Geometri", "participants": [] })),
274+ )
275+ .await;
276+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
277+ let board = id_of(&res.body);
278+ // A board nobody has drawn on has nothing to clear.
279+ let res = clear(&app, &ali, &board).await;
280+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
281+ assert_eq!(rows(&db, &board).await, 0, "the refusal minted no marker");
282+
283+ // One mark pays for one marker...
284+ BoardStroke::append(
285+ &BoardId::from_key(&board),
286+ &UserId::from_key(&ali_id),
287+ "{\"p\":[1,2]}",
288+ 0,
289+ &db,
290+ )
291+ .await
292+ .expect("append");
293+ let res = clear(&app, &ali, &board).await;
294+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
295+ assert_eq!(rows(&db, &board).await, 2, "the stroke and its marker");
296+
297+ // ...and the blank canvas it leaves buys no more.
298+ let res = clear(&app, &ali, &board).await;
299+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
300+ assert_eq!(rows(&db, &board).await, 2);
301+ assert_eq!(
302+ stored_epoch(&db, &board).await,
303+ 1,
304+ "a refused clear must not move the epoch either"
305+ );
306+}
307+
308+/// End the board's current epoch as `cookie`.
309+async fn clear(app: &axum::Router, cookie: &str, board: &str) -> common::Res {
310+ send(
311+ app,
312+ "POST",
313+ &format!("/boards/{board}/clear"),
314+ Some(cookie),
315+ None,
316+ )
317+ .await
318+}
319+
320+/// Rows on `board_stroke` for one board, markers included.
321+async fn rows(db: &hezarfen_backend::database::Database, board: &str) -> usize {
322+ let mut result = db
323+ .query("SELECT VALUE id FROM board_stroke WHERE board = $b")
324+ .bind(("b", BoardId::from_key(board).record()))
325+ .await
326+ .unwrap()
327+ .check()
328+ .unwrap();
329+ result
330+ .take::<Vec<surrealdb::types::RecordId>>(0)
331+ .unwrap()
332+ .len()
333+}
334+
335+/// The board's stored epoch β€” the clear's other half.
336+async fn stored_epoch(db: &hezarfen_backend::database::Database, board: &str) -> i64 {
337+ let mut result = db
338+ .query("SELECT VALUE epoch FROM $b")
339+ .bind(("b", BoardId::from_key(board).record()))
340+ .await
341+ .unwrap()
342+ .check()
343+ .unwrap();
344+ result.take::<Vec<i64>>(0).unwrap()[0]
345+}
346+
347+/// The clear marker is a row on the table, so the lifetime counter has to
348+/// count it. Charging only the strokes made `total_stroke_count` under-count
349+/// the rows it is supposed to bound by one per clear β€” `MAX_BOARD_STROKES`
350+/// stopped meaning "rows on this board". The counter is asserted against the
351+/// rows the store actually holds, which is the invariant, not a number.
352+#[tokio::test]
353+async fn a_clear_marker_is_charged_to_the_lifetime_counter() {
354+ let (app, db) = app_and_db().await;
355+ let ali = login(&app, "ali").await;
356+ let ali_id = me_id(&app, &ali).await;
357+ let res = send(
358+ &app,
359+ "POST",
360+ "/boards",
361+ Some(&ali),
362+ Some(json!({ "title": "Geometri", "participants": [] })),
363+ )
364+ .await;
365+ let board = id_of(&res.body);
366+ for _ in 0..2 {
367+ BoardStroke::append(
368+ &BoardId::from_key(&board),
369+ &UserId::from_key(&ali_id),
370+ "{\"p\":[1,2]}",
371+ 0,
372+ &db,
373+ )
374+ .await
375+ .expect("append");
376+ }
377+ let res = clear(&app, &ali, &board).await;
378+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
379+
380+ // Two strokes plus the marker that closed them: three rows, and the
381+ // lifetime counter says three. The epoch counter reset, as always.
382+ assert_eq!(rows(&db, &board).await, 3);
383+ assert_eq!(counters(&db, &board).await, (0, 3));
384+
385+ // The next epoch keeps counting from there β€” a marker is never re-counted
386+ // and never uncounted.
387+ BoardStroke::append(
388+ &BoardId::from_key(&board),
389+ &UserId::from_key(&ali_id),
390+ "{\"p\":[3,4]}",
391+ 1,
392+ &db,
393+ )
394+ .await
395+ .expect("append");
396+ clear(&app, &ali, &board).await;
397+ assert_eq!(rows(&db, &board).await, 5);
398+ assert_eq!(counters(&db, &board).await, (0, 5));
399+}
400+
401+/// `(epoch_stroke_count, total_stroke_count)` as the store holds them.
402+async fn counters(db: &hezarfen_backend::database::Database, board: &str) -> (i64, i64) {
403+ let mut result = db
404+ .query("SELECT VALUE [epoch_stroke_count ?? 0, total_stroke_count ?? 0] FROM $b")
405+ .bind(("b", BoardId::from_key(board).record()))
406+ .await
407+ .unwrap()
408+ .check()
409+ .unwrap();
410+ let rows: Vec<Vec<i64>> = result.take(0).unwrap();
411+ (rows[0][0], rows[0][1])
412+}
413+
414+/// A menu's record id is `<date>_<slot>` and that id is a URL path segment, so
415+/// a slot named `a/b` is a slot no menu can ever be published under. The menu
416+/// side refuses those characters; the settings side used to accept them, which
417+/// let a school define a slot the canteen could never use β€” a dead entry only
418+/// another settings PATCH could clear.
419+#[tokio::test]
420+async fn a_slot_name_that_no_menu_id_could_carry_is_refused_by_settings() {
421+ let (app, db) = app_and_db().await;
422+ let manager = login_as(&app, &db, "mudur", "manager").await;
423+ for bad in ["a/b", "a\\b", "a?b", "a#b", "a%b"] {
424+ let res = send(
425+ &app,
426+ "PATCH",
427+ "/settings",
428+ Some(&manager),
429+ Some(json!({"meal_slots": [{"name": bad}]})),
430+ )
431+ .await;
432+ assert_eq!(
433+ res.status,
434+ StatusCode::BAD_REQUEST,
435+ "slot {bad} was accepted: {}",
436+ res.body
437+ );
438+ }
439+ // The legal name still lands, and the refusals left the list alone.
440+ let res = send(
441+ &app,
442+ "PATCH",
443+ "/settings",
444+ Some(&manager),
445+ Some(json!({"meal_slots": [{"name": "âğle yemeği"}]})),
446+ )
447+ .await;
448+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
449+ assert_eq!(res.body["meal_slots"][0]["name"], "âğle yemeği");
450+
451+ // Stale data: a row written before this rule keeps its name, and must not
452+ // wedge an edit that never touches the meal slots. The carried-over list
453+ // goes back into the row as it stands (`MealSlotDef::try_new` runs on the
454+ // *request's* slots only), so an unrelated PATCH still lands.
455+ db.query("UPDATE settings:school SET meal_slots = [{ name: 'a/b', serving_minute: NONE }]")
456+ .await
457+ .unwrap()
458+ .check()
459+ .unwrap();
460+ let res = send(
461+ &app,
462+ "PATCH",
463+ "/settings",
464+ Some(&manager),
465+ Some(json!({"max_file_bytes": 1048576})),
466+ )
467+ .await;
468+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
469+ assert_eq!(res.body["max_file_bytes"], 1048576);
470+ assert_eq!(
471+ res.body["meal_slots"][0]["name"], "a/b",
472+ "the stale slot rides through untouched"
473+ );
474+}
475+
476+/// A board an older binary cleared carries a lifetime counter short by one row
477+/// per past clear, because the marker only started paying it on 2026-08-02 β€”
478+/// and `MAX_BOARD_STROKES` bounds *rows*, so an under-counted board can outgrow
479+/// the table cap it is supposed to obey. Boot recomputes the counter from the
480+/// rows themselves, which is what the counter means.
481+#[tokio::test]
482+async fn a_boards_lifetime_counter_is_repaired_from_its_rows_on_boot() {
483+ let (app, db) = app_and_db().await;
484+ let ali = login(&app, "ali").await;
485+ let ali_id = me_id(&app, &ali).await;
486+ let res = send(
487+ &app,
488+ "POST",
489+ "/boards",
490+ Some(&ali),
491+ Some(json!({ "title": "Geometri", "participants": [] })),
492+ )
493+ .await;
494+ let board = id_of(&res.body);
495+ BoardStroke::append(
496+ &BoardId::from_key(&board),
497+ &UserId::from_key(&ali_id),
498+ "{\"p\":[1,2]}",
499+ 0,
500+ &db,
501+ )
502+ .await
503+ .expect("append");
504+ clear(&app, &ali, &board).await;
505+ assert_eq!(rows(&db, &board).await, 2, "the stroke and its marker");
506+
507+ // Age the row to what the previous binary left behind: the marker charged
508+ // nothing, so the counter counts the stroke alone.
509+ db.query("UPDATE $b SET total_stroke_count = 1")
510+ .bind(("b", BoardId::from_key(&board).record()))
511+ .await
512+ .unwrap()
513+ .check()
514+ .unwrap();
515+ assert_eq!(counters(&db, &board).await, (0, 1));
516+
517+ hezarfen_backend::database::migrate(&db)
518+ .await
519+ .expect("re-migration");
520+ assert_eq!(
521+ counters(&db, &board).await,
522+ (0, 2),
523+ "the counter is the board's row count again"
524+ );
525+
526+ // Idempotent: it recomputes the same number, it does not add one per boot β€”
527+ // the failure mode a counter repair actually has.
528+ for _ in 0..2 {
529+ hezarfen_backend::database::migrate(&db)
530+ .await
531+ .expect("re-migration");
532+ }
533+ assert_eq!(counters(&db, &board).await, (0, 2));
534+ assert_eq!(rows(&db, &board).await, 2, "and it wrote no rows");
535+}
536+
537+/// A slot name the school *already stores* must stay submittable.
538+///
539+/// The URL-safety rule on slot names is younger than the lists it validates,
540+/// and `PATCH /settings` re-validates the whole submitted list β€” so a school
541+/// holding a pre-rule name was locked out of `meal_slots` entirely: re-sending
542+/// the name 400s, and dropping it 409s the moment a menu references it. The
543+/// stored name is grandfathered; a new one with the same characters is not.
544+#[tokio::test]
545+async fn a_stale_slot_name_no_longer_wedges_the_rest_of_the_list() {
546+ let (app, db) = app_and_db().await;
547+ let admin = login_as(&app, &db, "slot_wedge_admin", "admin").await;
548+
549+ // A legal edit first: `UPDATE` on the singleton is a no-op until the row
550+ // exists, and an absent row reads as the built-in defaults.
551+ let res = send(
552+ &app,
553+ "PATCH",
554+ "/settings",
555+ Some(&admin),
556+ Some(json!({ "meal_slots": [{"name": "lunch"}] })),
557+ )
558+ .await;
559+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
560+
561+ // The list as a database written before the rule holds it, plus the menu
562+ // reference that makes dropping the name a 409.
563+ db.query(
564+ "UPDATE settings:school SET meal_slots = \
565+ [{ name: 'a/b', serving_minute: NONE }, { name: 'lunch', serving_minute: NONE }];
566+ UPSERT slot_ref:`a/b` SET count = 1;",
567+ )
568+ .await
569+ .unwrap()
570+ .check()
571+ .unwrap();
572+
573+ // Editing the *rest* of the list works, stale name carried along.
574+ let res = send(
575+ &app,
576+ "PATCH",
577+ "/settings",
578+ Some(&admin),
579+ Some(json!({ "meal_slots": [
580+ {"name": "a/b"}, {"name": "lunch"}, {"name": "kahvaltΔ±"},
581+ ] })),
582+ )
583+ .await;
584+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
585+
586+ // Dropping it is still the 409 the published menu earns it...
587+ let res = send(
588+ &app,
589+ "PATCH",
590+ "/settings",
591+ Some(&admin),
592+ Some(json!({ "meal_slots": [{"name": "lunch"}] })),
593+ )
594+ .await;
595+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
596+
597+ // ...and a name nobody stored is still refused outright.
598+ let res = send(
599+ &app,
600+ "PATCH",
601+ "/settings",
602+ Some(&admin),
603+ Some(json!({ "meal_slots": [{"name": "a/b"}, {"name": "lunch"}, {"name": "c/d"}] })),
604+ )
605+ .await;
606+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
607+}
tests/regress_classes.rsadded+774 -0
@@ -0,0 +1,774 @@
1+//! Regressions for the class (şube) layer, its enrollment side, and the sweep a
2+//! role change runs. Every test here pins a defect that shipped: a link left
3+//! pointing at a deleted course, the refusal that misnamed it, a hand enroll a
4+//! class could still undo, and the two-transaction role sweep.
5+
6+mod common;
7+
8+use axum::http::StatusCode;
9+use common::{app_and_db, create_course, login_as, me_id, send};
10+use hezarfen_backend::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
11+use hezarfen_backend::database::Database;
12+use hezarfen_backend::domain::class_course::ClassCourse;
13+use hezarfen_backend::domain::class_group::{ClassGroup, ClassName};
14+use hezarfen_backend::domain::class_member::ClassMember;
15+use hezarfen_backend::domain::course::CourseId;
16+use hezarfen_backend::domain::user::UserId;
17+use hezarfen_backend::error::AppError;
18+use serde_json::json;
19+
20+/// One counter, re-read out of the store β€” never off a response body.
21+async fn counter(sql: &str, db: &Database) -> i64 {
22+ let mut result = db.query(sql).await.unwrap().check().unwrap();
23+ result
24+ .take::<Vec<i64>>(0)
25+ .unwrap()
26+ .first()
27+ .copied()
28+ .unwrap_or(0)
29+}
30+
31+/// How many rows `sql` selects ids for.
32+async fn rows(sql: &str, db: &Database) -> i64 {
33+ let mut result = db.query(sql).await.unwrap().check().unwrap();
34+ result
35+ .take::<Vec<surrealdb::types::RecordId>>(0)
36+ .unwrap()
37+ .len() as i64
38+}
39+
40+/// Delete a course row the way a *concurrent* `DELETE /courses/{id}` racing an
41+/// attach leaves the store: the row goes, the `class_course` link it never saw
42+/// stays. The real cascade sweeps those links, so this is the only way to reach
43+/// the state from a test β€” and the state the pump's in-transaction claim exists
44+/// to make unreachable in the first place.
45+async fn wipe_course_row(course: &str, db: &Database) {
46+ db.query("DELETE type::record('course', $key)")
47+ .bind(("key", course.to_string()))
48+ .await
49+ .unwrap()
50+ .check()
51+ .unwrap();
52+}
53+
54+/// B1(a). A class with *zero* members makes the pump's pair loop empty, so the
55+/// attach transaction touched no row a concurrent course delete wrote and
56+/// SurrealDB's write-skew let both commit β€” a `class_course` row pointing at a
57+/// course that does not exist. The pivot claim is what makes that impossible.
58+#[tokio::test]
59+async fn an_attach_onto_a_deleted_course_writes_no_link() {
60+ let (_app, db) = app_and_db().await;
61+ let manager = UserId::from_key("manager");
62+ let class = ClassGroup::create(
63+ &manager,
64+ ClassName::try_new("9-A").unwrap(),
65+ None,
66+ None,
67+ &db,
68+ )
69+ .await
70+ .unwrap();
71+ // A course id nothing ever created: the same row a delete that won the race
72+ // leaves behind.
73+ let ghost = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");
74+
75+ let refused = ClassCourse::attach(class.get_id(), &ghost, &manager, &db).await;
76+ assert!(
77+ refused.is_err(),
78+ "attaching a course that is gone must be refused: {refused:?}"
79+ );
80+ assert_eq!(
81+ rows("SELECT VALUE id FROM class_course", &db).await,
82+ 0,
83+ "no link row may point at a course that does not exist"
84+ );
85+ assert_eq!(
86+ counter("SELECT VALUE class_course_count ?? 0 FROM class_group", &db).await,
87+ 0,
88+ "…and the class must not count one either, or it is undeletable forever"
89+ );
90+}
91+
92+/// B1(b). The other half: a link that *did* land that way must still be
93+/// removable. `DELETE /classes/{c}/courses/{id}` read the course before the
94+/// link, so a deleted course made the route answer 404 forever β€” and the class
95+/// 409 forever, over an attachment nothing could sweep.
96+#[tokio::test]
97+async fn a_stale_link_detaches_and_frees_its_class() {
98+ let (app, db) = app_and_db().await;
99+ let manager = login_as(&app, &db, "manager", "manager").await;
100+ let course = create_course(&app, &manager, "algebra").await;
101+ let class = {
102+ let res = send(
103+ &app,
104+ "POST",
105+ "/classes",
106+ Some(&manager),
107+ Some(json!({ "name": "9-A" })),
108+ )
109+ .await;
110+ assert_eq!(res.status, StatusCode::CREATED);
111+ res.body["id"].as_str().unwrap().to_string()
112+ };
113+ let attached = send(
114+ &app,
115+ "POST",
116+ &format!("/classes/{class}/courses"),
117+ Some(&manager),
118+ Some(json!({ "course_id": course })),
119+ )
120+ .await;
121+ assert_eq!(attached.status, StatusCode::CREATED);
122+ wipe_course_row(&course, &db).await;
123+
124+ let detached = send(
125+ &app,
126+ "DELETE",
127+ &format!("/classes/{class}/courses/{course}"),
128+ Some(&manager),
129+ None,
130+ )
131+ .await;
132+ assert_eq!(
133+ detached.status,
134+ StatusCode::NO_CONTENT,
135+ "a link whose course is gone must still detach: {:?}",
136+ detached.body
137+ );
138+ let deleted = send(
139+ &app,
140+ "DELETE",
141+ &format!("/classes/{class}"),
142+ Some(&manager),
143+ None,
144+ )
145+ .await;
146+ assert_eq!(
147+ deleted.status,
148+ StatusCode::NO_CONTENT,
149+ "…and the class it blocked must be deletable again: {:?}",
150+ deleted.body
151+ );
152+
153+ // A course that was never attached is still a 404 β€” the guard that turns
154+ // "sweep the stale link" into "delete anything" is the link row, not the
155+ // course row.
156+ let again = send(
157+ &app,
158+ "DELETE",
159+ &format!("/classes/{class}/courses/{course}"),
160+ Some(&manager),
161+ None,
162+ )
163+ .await;
164+ assert_eq!(again.status, StatusCode::NOT_FOUND);
165+}
166+
167+/// B2. Every member add into a class holding such a link answered
168+/// `409 "<course> is full"` β€” a course that does not exist, so no capacity
169+/// anyone could raise would ever let a student in. The two causes come out of
170+/// one seat claim matching nothing, and they must not read as one answer.
171+#[tokio::test]
172+async fn a_member_add_names_a_stale_link_rather_than_calling_it_full() {
173+ let (app, db) = app_and_db().await;
174+ let manager = login_as(&app, &db, "manager", "manager").await;
175+ let student = login_as(&app, &db, "student", "student").await;
176+ let student_id = me_id(&app, &student).await;
177+ let course = create_course(&app, &manager, "algebra").await;
178+ let class = {
179+ let res = send(
180+ &app,
181+ "POST",
182+ "/classes",
183+ Some(&manager),
184+ Some(json!({ "name": "9-A" })),
185+ )
186+ .await;
187+ res.body["id"].as_str().unwrap().to_string()
188+ };
189+ send(
190+ &app,
191+ "POST",
192+ &format!("/classes/{class}/courses"),
193+ Some(&manager),
194+ Some(json!({ "course_id": course })),
195+ )
196+ .await;
197+ wipe_course_row(&course, &db).await;
198+
199+ let refused = send(
200+ &app,
201+ "POST",
202+ &format!("/classes/{class}/members"),
203+ Some(&manager),
204+ Some(json!({ "user_id": student_id })),
205+ )
206+ .await;
207+ assert_eq!(refused.status, StatusCode::CONFLICT);
208+ let message = refused.body["error"].as_str().unwrap_or_default();
209+ assert!(
210+ message.contains("no longer exists") && message.contains(&course),
211+ "the refusal must name the vanished course, not a capacity: {message}"
212+ );
213+ assert!(
214+ !message.contains("full"),
215+ "a course that does not exist is not a full one: {message}"
216+ );
217+ assert_eq!(
218+ rows("SELECT VALUE id FROM class_member", &db).await,
219+ 0,
220+ "a refused add writes nothing"
221+ );
222+}
223+
224+/// B3. A hand enroll over a row a class pumped must take the row off the class,
225+/// or the next sweep unenrolls a student an operator placed on purpose β€”
226+/// the mirror of the manual unenroll that a class may never undo.
227+#[tokio::test]
228+async fn a_hand_enroll_takes_the_row_off_the_class() {
229+ let (app, db) = app_and_db().await;
230+ let manager = login_as(&app, &db, "manager", "manager").await;
231+ let student = login_as(&app, &db, "student", "student").await;
232+ let student_id = me_id(&app, &student).await;
233+ let course = create_course(&app, &manager, "algebra").await;
234+ let class = {
235+ let res = send(
236+ &app,
237+ "POST",
238+ "/classes",
239+ Some(&manager),
240+ Some(json!({ "name": "9-A" })),
241+ )
242+ .await;
243+ res.body["id"].as_str().unwrap().to_string()
244+ };
245+ send(
246+ &app,
247+ "POST",
248+ &format!("/classes/{class}/courses"),
249+ Some(&manager),
250+ Some(json!({ "course_id": course })),
251+ )
252+ .await;
253+ let added = send(
254+ &app,
255+ "POST",
256+ &format!("/classes/{class}/members"),
257+ Some(&manager),
258+ Some(json!({ "user_id": student_id })),
259+ )
260+ .await;
261+ assert_eq!(added.status, StatusCode::CREATED);
262+
263+ // The pumped row names its class, and says so on the wire β€” a client that
264+ // cannot see `source` cannot tell which of its roster rows is sweepable.
265+ let roster = send(
266+ &app,
267+ "GET",
268+ &format!("/courses/{course}/enrollments"),
269+ Some(&manager),
270+ None,
271+ )
272+ .await;
273+ assert_eq!(roster.body["items"][0]["source"], json!(class));
274+
275+ let by_hand = send(
276+ &app,
277+ "POST",
278+ &format!("/courses/{course}/enrollments"),
279+ Some(&manager),
280+ Some(json!({ "user_id": student_id })),
281+ )
282+ .await;
283+ assert_eq!(by_hand.status, StatusCode::OK);
284+ assert_eq!(
285+ by_hand.body["source"],
286+ json!(null),
287+ "a hand enroll must take the row off the class"
288+ );
289+ assert_eq!(
290+ rows("SELECT VALUE id FROM enrollment WHERE source != NONE", &db).await,
291+ 0,
292+ "…in the stored row, not just the response"
293+ );
294+
295+ // Which is the whole point: the class letting the student go now leaves the
296+ // hand-placed row standing, with its seat still counted.
297+ let removed = send(
298+ &app,
299+ "DELETE",
300+ &format!("/classes/{class}/members/{student_id}"),
301+ Some(&manager),
302+ None,
303+ )
304+ .await;
305+ assert_eq!(removed.status, StatusCode::NO_CONTENT);
306+ assert_eq!(
307+ rows("SELECT VALUE id FROM enrollment", &db).await,
308+ 1,
309+ "the class may not unenroll a student an operator enrolled by hand"
310+ );
311+ assert_eq!(
312+ counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await,
313+ 1,
314+ "…and the seat it never paid for may not be released"
315+ );
316+}
317+
318+/// B5. The role sweep is one transaction over both tables. Pinned end to end:
319+/// a promotion leaves no membership, no enrollment and no counter behind, so
320+/// the class is deletable and no row is left tagged with it. (The half-apply
321+/// itself needs a crash between two statements, which no test can schedule β€”
322+/// this pins the state the fold must always land in.)
323+#[tokio::test]
324+async fn a_role_change_sweeps_memberships_and_enrollments_together() {
325+ let (app, db) = app_and_db().await;
326+ let admin = login_as(&app, &db, "patron", "admin").await;
327+ let manager = login_as(&app, &db, "manager", "manager").await;
328+ let student = login_as(&app, &db, "student", "student").await;
329+ let student_id = me_id(&app, &student).await;
330+ let course = create_course(&app, &manager, "algebra").await;
331+ let class = {
332+ let res = send(
333+ &app,
334+ "POST",
335+ "/classes",
336+ Some(&manager),
337+ Some(json!({ "name": "9-A" })),
338+ )
339+ .await;
340+ res.body["id"].as_str().unwrap().to_string()
341+ };
342+ send(
343+ &app,
344+ "POST",
345+ &format!("/classes/{class}/courses"),
346+ Some(&manager),
347+ Some(json!({ "course_id": course })),
348+ )
349+ .await;
350+ send(
351+ &app,
352+ "POST",
353+ &format!("/classes/{class}/members"),
354+ Some(&manager),
355+ Some(json!({ "user_id": student_id })),
356+ )
357+ .await;
358+ assert_eq!(rows("SELECT VALUE id FROM enrollment", &db).await, 1);
359+
360+ let promoted = send(
361+ &app,
362+ "PATCH",
363+ &format!("/users/{student_id}/role"),
364+ Some(&admin),
365+ Some(json!({ "role": "teacher" })),
366+ )
367+ .await;
368+ assert_eq!(promoted.status, StatusCode::OK);
369+
370+ assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);
371+ assert_eq!(
372+ rows("SELECT VALUE id FROM enrollment", &db).await,
373+ 0,
374+ "a non-student holds no roster row, whoever wrote it"
375+ );
376+ assert_eq!(
377+ counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await,
378+ 0,
379+ "the seat comes back exactly once"
380+ );
381+ assert_eq!(
382+ counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await,
383+ 0
384+ );
385+ // Nothing is left tagged with the class, so letting it go strands nothing.
386+ let detached = send(
387+ &app,
388+ "DELETE",
389+ &format!("/classes/{class}/courses/{course}"),
390+ Some(&manager),
391+ None,
392+ )
393+ .await;
394+ assert_eq!(detached.status, StatusCode::NO_CONTENT);
395+ let deleted = send(
396+ &app,
397+ "DELETE",
398+ &format!("/classes/{class}"),
399+ Some(&manager),
400+ None,
401+ )
402+ .await;
403+ assert_eq!(deleted.status, StatusCode::NO_CONTENT);
404+}
405+
406+/// B4. The roster cap is claimed off the course row's *own* `capacity` column
407+/// now, not off an integer read moments earlier β€” so a capacity PATCH cannot be
408+/// outrun by an enroll that snapshotted the old number. The over-admit that
409+/// bug allowed needs two writers interleaved inside one request, which the
410+/// in-memory engine cannot be made to schedule; what is pinned here is that the
411+/// converted statement still refuses, still admits, and still tells a full
412+/// course from a deleted one.
413+#[tokio::test]
414+async fn the_roster_cap_is_claimed_off_the_live_capacity_column() {
415+ let (app, db) = app_and_db().await;
416+ let manager = login_as(&app, &db, "manager", "manager").await;
417+ let first = login_as(&app, &db, "sena", "student").await;
418+ let second = login_as(&app, &db, "suat", "student").await;
419+ let first_id = me_id(&app, &first).await;
420+ let second_id = me_id(&app, &second).await;
421+ let course = {
422+ let res = send(
423+ &app,
424+ "POST",
425+ "/courses",
426+ Some(&manager),
427+ Some(json!({ "title": "algebra", "capacity": 1 })),
428+ )
429+ .await;
430+ assert_eq!(res.status, StatusCode::CREATED);
431+ res.body["id"].as_str().unwrap().to_string()
432+ };
433+ let enroll = |who: String| {
434+ let app = app.clone();
435+ let manager = manager.clone();
436+ let course = course.clone();
437+ async move {
438+ send(
439+ &app,
440+ "POST",
441+ &format!("/courses/{course}/enrollments"),
442+ Some(&manager),
443+ Some(json!({ "user_id": who })),
444+ )
445+ .await
446+ }
447+ };
448+
449+ assert_eq!(enroll(first_id.clone()).await.status, StatusCode::OK);
450+ assert_eq!(
451+ enroll(second_id.clone()).await.status,
452+ StatusCode::CONFLICT,
453+ "the cap must bite at one"
454+ );
455+ // Re-enrolling the student who is already in is answered off their row, not
456+ // off the (full) counter, and costs no seat.
457+ assert_eq!(enroll(first_id.clone()).await.status, StatusCode::OK);
458+ assert_eq!(
459+ counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await,
460+ 1
461+ );
462+
463+ // Raise the cap and the very next claim sees the new number, because it
464+ // reads the column rather than a copy of it.
465+ let raised = send(
466+ &app,
467+ "PATCH",
468+ &format!("/courses/{course}"),
469+ Some(&manager),
470+ Some(json!({ "capacity": 2 })),
471+ )
472+ .await;
473+ assert_eq!(raised.status, StatusCode::OK);
474+ assert_eq!(enroll(second_id.clone()).await.status, StatusCode::OK);
475+ assert_eq!(
476+ counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await,
477+ 2
478+ );
479+
480+ // And a course deleted out from under the claim is a 404, not a 409: the
481+ // conditional write matches nothing either way, and only that path pays for
482+ // the read that tells them apart.
483+ wipe_course_row(&course, &db).await;
484+ db.query("DELETE enrollment")
485+ .await
486+ .unwrap()
487+ .check()
488+ .unwrap();
489+ assert_eq!(enroll(first_id).await.status, StatusCode::NOT_FOUND);
490+}
491+
492+/// D1. Both link tables key on the *pair* (`<class>_<user>`), so the
493+/// documented "newest first" was implemented as `ORDER BY id DESC` β€” which
494+/// sorts the roster by the member's account ULID, an order that has nothing to
495+/// do with when anyone was added. The three students here are added in an order
496+/// their ids do not reproduce, so id-ordering and stamp-ordering disagree.
497+#[tokio::test]
498+async fn a_roster_is_ordered_by_when_a_student_was_added() {
499+ let (_app, db) = app_and_db().await;
500+ let manager = UserId::from_key("manager");
501+ let class = ClassGroup::create(
502+ &manager,
503+ ClassName::try_new("9-A").unwrap(),
504+ None,
505+ None,
506+ &db,
507+ )
508+ .await
509+ .unwrap()
510+ .get_id()
511+ .clone();
512+
513+ // Keys chosen so `id DESC` (c, b, a) is not the reverse of the insertion
514+ // order (a, c, b): only a real stamp can tell the two apart. The waits are
515+ // what keep the millisecond stamps distinct β€” a tie falls back to the id,
516+ // which is the very order under test.
517+ let added = ["a", "c", "b"];
518+ for key in added {
519+ ClassMember::add(&class, &UserId::from_key(key), &manager, &db)
520+ .await
521+ .unwrap();
522+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;
523+ }
524+
525+ let (roster, _) = ClassMember::list_for_class(&class, None, 0, &db)
526+ .await
527+ .unwrap();
528+ let order: Vec<&str> = roster
529+ .iter()
530+ .map(|member| member.get_user().key())
531+ .collect();
532+ assert_eq!(
533+ order,
534+ vec!["b", "c", "a"],
535+ "the roster must come back newest-added first, not sorted by account id"
536+ );
537+
538+ // A row written before the stamp column existed carries no `added_at` at
539+ // all β€” the state a real volume is in. It is of unknown age, and NONE
540+ // sorting last under DESC is what makes that the oldest, rather than an
541+ // invented number putting it anywhere else.
542+ db.query("UPDATE class_member SET added_at = NONE WHERE user = $usr")
543+ .bind(("usr", UserId::from_key("c").record()))
544+ .await
545+ .unwrap()
546+ .check()
547+ .unwrap();
548+ let (roster, _) = ClassMember::list_for_class(&class, None, 0, &db)
549+ .await
550+ .unwrap();
551+ assert_eq!(
552+ roster
553+ .iter()
554+ .map(|member| member.get_user().key())
555+ .collect::<Vec<_>>(),
556+ vec!["b", "a", "c"],
557+ "a stamp-less row must sort oldest, not first"
558+ );
559+}
560+
561+/// D1, the other axis: the course list had the same defect, ordered by the
562+/// *course's* ULID.
563+#[tokio::test]
564+async fn a_class_course_list_is_ordered_by_when_it_was_attached() {
565+ let (app, db) = app_and_db().await;
566+ let manager_cookie = login_as(&app, &db, "manager", "manager").await;
567+ let manager = UserId::from_key(&me_id(&app, &manager_cookie).await);
568+ let class = ClassGroup::create(
569+ &manager,
570+ ClassName::try_new("9-A").unwrap(),
571+ None,
572+ None,
573+ &db,
574+ )
575+ .await
576+ .unwrap()
577+ .get_id()
578+ .clone();
579+
580+ // Courses are ULID-keyed, so their ids rise with creation; attaching them
581+ // back-to-front makes id order and attach order disagree.
582+ let mut courses = Vec::new();
583+ for title in ["first", "second", "third"] {
584+ courses.push(CourseId::from_key(
585+ &create_course(&app, &manager_cookie, title).await,
586+ ));
587+ }
588+ for course in courses.iter().rev() {
589+ ClassCourse::attach(&class, course, &manager, &db)
590+ .await
591+ .unwrap();
592+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;
593+ }
594+
595+ let (attached, _) = ClassCourse::list_for_class(&class, None, 0, &db)
596+ .await
597+ .unwrap();
598+ let order: Vec<&str> = attached
599+ .iter()
600+ .map(|link| link.get_course().key())
601+ .collect();
602+ assert_eq!(
603+ order,
604+ courses.iter().map(|c| c.key()).collect::<Vec<_>>(),
605+ "the list must come back newest-attached first, not sorted by course id"
606+ );
607+}
608+
609+/// D2. Attaching a course writes one enrollment per member and adding a member
610+/// writes one per attached course, both in a *single* transaction β€” with no
611+/// class-size ceiling anywhere, that transaction was unbounded. The counter's
612+/// claim now carries the bound, so the refusal happens before the loop runs.
613+///
614+/// The counter is seeded rather than filled by 200 real adds: it *is* the gate
615+/// the claim reads, and the boundary is what is under test, not the 199 adds
616+/// that lead up to it.
617+#[tokio::test]
618+async fn a_class_refuses_the_member_past_its_ceiling() {
619+ let (_app, db) = app_and_db().await;
620+ let manager = UserId::from_key("manager");
621+ let class = ClassGroup::create(
622+ &manager,
623+ ClassName::try_new("9-A").unwrap(),
624+ None,
625+ None,
626+ &db,
627+ )
628+ .await
629+ .unwrap()
630+ .get_id()
631+ .clone();
632+ db.query("UPDATE $class SET class_member_count = $at")
633+ .bind(("class", class.record()))
634+ .bind(("at", MAX_CLASS_MEMBERS - 1))
635+ .await
636+ .unwrap()
637+ .check()
638+ .unwrap();
639+
640+ ClassMember::add(&class, &UserId::from_key("last"), &manager, &db)
641+ .await
642+ .expect("the place under the ceiling is still free");
643+ let refused = ClassMember::add(&class, &UserId::from_key("over"), &manager, &db).await;
644+ assert!(
645+ matches!(refused, Err(AppError::ConflictOwned(ref message))
646+ if message.contains(&MAX_CLASS_MEMBERS.to_string())),
647+ "a full class is a 409 naming its ceiling, never a 404: {refused:?}"
648+ );
649+ assert_eq!(
650+ counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await,
651+ MAX_CLASS_MEMBERS,
652+ "a refused add may not tick the counter past the cap"
653+ );
654+ assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 1);
655+
656+ // And the refusal a *deleted* class earns must stay a 404: both come out of
657+ // the same counter claim matching nothing, and only one of them is a
658+ // ceiling anybody can make room under.
659+ db.query("DELETE $class")
660+ .bind(("class", class.record()))
661+ .await
662+ .unwrap()
663+ .check()
664+ .unwrap();
665+ let gone = ClassMember::add(&class, &UserId::from_key("ghost"), &manager, &db).await;
666+ assert!(
667+ matches!(gone, Err(AppError::NotFound)),
668+ "a class that is gone is a 404: {gone:?}"
669+ );
670+}
671+
672+/// The ceilings bind the axis being *added*, and the transaction they bound is
673+/// the length of the *other* one β€” so a class that already stands above a
674+/// ceiling walked straight past both. The class layer shipped before either
675+/// number existed, so a real volume can hold a 300-strong class, and attaching
676+/// one course to it wrote 300 enrollments in a single transaction: exactly the
677+/// unbounded write `MAX_CLASS_MEMBERS` was added to make impossible. The attach
678+/// now refuses on the other axis too, and says which one.
679+///
680+/// The counter is seeded rather than filled by 201 real adds: it *is* what the
681+/// pump reads, and it is what a stale class carries.
682+#[tokio::test]
683+async fn a_class_over_the_other_axis_ceiling_attaches_nothing() {
684+ let (app, db) = app_and_db().await;
685+ let cookie = login_as(&app, &db, "manager", "manager").await;
686+ let manager = UserId::from_key(&me_id(&app, &cookie).await);
687+ let class = ClassGroup::create(
688+ &manager,
689+ ClassName::try_new("9-A").unwrap(),
690+ None,
691+ None,
692+ &db,
693+ )
694+ .await
695+ .unwrap()
696+ .get_id()
697+ .clone();
698+ let algebra = CourseId::from_key(&create_course(&app, &cookie, "algebra").await);
699+ db.query("UPDATE $class SET class_member_count = $over")
700+ .bind(("class", class.record()))
701+ .bind(("over", MAX_CLASS_MEMBERS + 1))
702+ .await
703+ .unwrap()
704+ .check()
705+ .unwrap();
706+
707+ let refused = ClassCourse::attach(&class, &algebra, &manager, &db).await;
708+ assert!(
709+ matches!(refused, Err(AppError::ConflictOwned(ref message))
710+ if message.contains(&MAX_CLASS_MEMBERS.to_string())),
711+ "the refusal must name the axis that is over, not the one with room: {refused:?}"
712+ );
713+ assert_eq!(
714+ rows("SELECT VALUE id FROM class_course", &db).await,
715+ 0,
716+ "a refused attach may not leave the link behind"
717+ );
718+ assert_eq!(
719+ counter("SELECT VALUE class_course_count ?? 0 FROM class_group", &db).await,
720+ 0,
721+ "…nor tick the axis it was refused on"
722+ );
723+
724+ // Back under the ceiling, the very same attach goes through: the refusal is
725+ // the standing count, not the class.
726+ db.query("UPDATE $class SET class_member_count = $at")
727+ .bind(("class", class.record()))
728+ .bind(("at", MAX_CLASS_MEMBERS))
729+ .await
730+ .unwrap()
731+ .check()
732+ .unwrap();
733+ ClassCourse::attach(&class, &algebra, &manager, &db)
734+ .await
735+ .expect("a class exactly at the ceiling is still a bounded transaction");
736+}
737+
738+/// The mirror: a class carrying more courses than `MAX_CLASS_COURSES` takes no
739+/// new member, because adding one enrolls them into every attached course.
740+#[tokio::test]
741+async fn a_class_over_the_course_ceiling_takes_no_member() {
742+ let (_app, db) = app_and_db().await;
743+ let manager = UserId::from_key("manager");
744+ let class = ClassGroup::create(
745+ &manager,
746+ ClassName::try_new("9-B").unwrap(),
747+ None,
748+ None,
749+ &db,
750+ )
751+ .await
752+ .unwrap()
753+ .get_id()
754+ .clone();
755+ db.query("UPDATE $class SET class_course_count = $over")
756+ .bind(("class", class.record()))
757+ .bind(("over", MAX_CLASS_COURSES + 1))
758+ .await
759+ .unwrap()
760+ .check()
761+ .unwrap();
762+
763+ let refused = ClassMember::add(&class, &UserId::from_key("ali"), &manager, &db).await;
764+ assert!(
765+ matches!(refused, Err(AppError::ConflictOwned(ref message))
766+ if message.contains(&MAX_CLASS_COURSES.to_string())),
767+ "the refusal must name the courses, not the roster: {refused:?}"
768+ );
769+ assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);
770+ assert_eq!(
771+ counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await,
772+ 0
773+ );
774+}
tests/regress_meals.rsadded+673 -0
@@ -0,0 +1,673 @@
1+//! Regressions for the food program's money and its menus. Each test here
2+//! stands for one defect that shipped: a seat that could not be replayed, a
3+//! seat nobody could cancel, a debt nobody could settle, a mark that outlived
4+//! its menu, a dish edit that outlived its own.
5+//!
6+//! Router-level, same shape as `integration.rs`, plus a few direct domain calls
7+//! where the defect sits *below* a handler's read (a mark landing after the
8+//! menu is gone is not reachable through the route, which reads it first).
9+
10+mod common;
11+
12+use axum::http::StatusCode;
13+use common::{app_and_db, id_of, login, login_as, me_id, send, set_role};
14+use hezarfen_backend::domain::meal_attendance::{MealAttendance, MealAttendanceStatus};
15+use hezarfen_backend::domain::menu::MenuId;
16+use hezarfen_backend::domain::user::UserId;
17+use serde_json::json;
18+
19+/// Publish a menu for `date`, uncapped unless told otherwise.
20+async fn publish(app: &axum::Router, mgr: &str, date: &str) -> String {
21+ let res = send(
22+ app,
23+ "POST",
24+ "/meals/menus",
25+ Some(mgr),
26+ Some(json!({ "date": date, "slot": "lunch" })),
27+ )
28+ .await;
29+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
30+ id_of(&res.body)
31+}
32+
33+async fn add_dish(app: &axum::Router, mgr: &str, menu: &str, price: i64) -> String {
34+ let res = send(
35+ app,
36+ "POST",
37+ &format!("/meals/menus/{menu}/dishes"),
38+ Some(mgr),
39+ Some(json!({ "name": "Γ§orba", "price_minor": price })),
40+ )
41+ .await;
42+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
43+ id_of(&res.body)
44+}
45+
46+/// A repeat `POST` of a seat the student already holds must replay that seat,
47+/// whatever the menu costs *now*. Pricing the menu before the already-booked
48+/// short circuit made it a `400` ("amount_minor must be between…") the moment
49+/// the dishes summed past the chargeable maximum β€” refusing to hand back a seat
50+/// over a price it was never going to be billed.
51+#[tokio::test]
52+async fn a_repeat_booking_replays_the_held_seat_however_dear_the_menu_gets() {
53+ let (app, db) = app_and_db().await;
54+ let mgr = login_as(&app, &db, "dear_mgr", "manager").await;
55+ let ali = login(&app, "dear_ali").await;
56+ let menu = publish(&app, &mgr, "2026-09-14").await;
57+ add_dish(&app, &mgr, &menu, 1_000).await;
58+
59+ let res = send(
60+ &app,
61+ "POST",
62+ &format!("/meals/menus/{menu}/bookings"),
63+ Some(&ali),
64+ Some(json!({})),
65+ )
66+ .await;
67+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
68+ let booking = id_of(&res.body);
69+
70+ // The menu is re-dressed until a seat on it could not be billed at all
71+ // (`MAX_LEDGER_AMOUNT_MINOR` is 10 000 000 minor units).
72+ for _ in 0..11 {
73+ add_dish(&app, &mgr, &menu, 1_000_000).await;
74+ }
75+
76+ let res = send(
77+ &app,
78+ "POST",
79+ &format!("/meals/menus/{menu}/bookings"),
80+ Some(&ali),
81+ Some(json!({})),
82+ )
83+ .await;
84+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
85+ assert_eq!(id_of(&res.body), booking, "the same seat, replayed");
86+ assert_eq!(res.body["status"], "booked");
87+
88+ // …and the replay bills nothing new: the seat still owes its own price.
89+ let res = send(
90+ &app,
91+ "GET",
92+ &format!("/meals/balance/{}", me_id(&app, &ali).await),
93+ Some(&mgr),
94+ None,
95+ )
96+ .await;
97+ assert_eq!(res.body["balance_minor"], -1_000);
98+
99+ // A student who has no seat yet is still refused outright, rather than
100+ // being handed one nothing can charge for.
101+ let veli = login(&app, "dear_veli").await;
102+ let res = send(
103+ &app,
104+ "POST",
105+ &format!("/meals/menus/{menu}/bookings"),
106+ Some(&veli),
107+ Some(json!({})),
108+ )
109+ .await;
110+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
111+}
112+
113+/// A seat outlives the role that took it. Only the student or their parent may
114+/// cancel, so a promoted student's live seat used to be uncancellable: the menu
115+/// refused its own delete forever and the charge could never be reversed, since
116+/// cancelling is the only route that appends a reversal. Manager+ may cancel
117+/// any seat, and nothing sweeps bookings on a role change β€” moving money is a
118+/// decision, never a side effect.
119+#[tokio::test]
120+async fn a_manager_can_cancel_the_seat_of_someone_who_is_no_longer_a_student() {
121+ let (app, db) = app_and_db().await;
122+ let mgr = login_as(&app, &db, "promo_mgr", "manager").await;
123+ let ali = login(&app, "promo_ali").await;
124+ let ali_id = me_id(&app, &ali).await;
125+ let menu = publish(&app, &mgr, "2026-09-15").await;
126+ add_dish(&app, &mgr, &menu, 4_500).await;
127+
128+ let res = send(
129+ &app,
130+ "POST",
131+ &format!("/meals/menus/{menu}/bookings"),
132+ Some(&ali),
133+ Some(json!({})),
134+ )
135+ .await;
136+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
137+ let booking = id_of(&res.body);
138+
139+ // Ali becomes staff. The seat is still held, still counted, still charged.
140+ set_role(&db, "promo_ali", "teacher").await;
141+ let res = send(
142+ &app,
143+ "DELETE",
144+ &format!("/meals/bookings/{booking}"),
145+ Some(&ali),
146+ None,
147+ )
148+ .await;
149+ assert_eq!(
150+ res.status,
151+ StatusCode::FORBIDDEN,
152+ "a teacher does not book meals, so they do not cancel their own either"
153+ );
154+
155+ let res = send(
156+ &app,
157+ "DELETE",
158+ &format!("/meals/bookings/{booking}"),
159+ Some(&mgr),
160+ None,
161+ )
162+ .await;
163+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
164+ assert_eq!(res.body["status"], "cancelled");
165+
166+ // The seat is genuinely back β€” the menu may be unpublished β€” and so is the
167+ // money: the reversal landed with the flip.
168+ let res = send(
169+ &app,
170+ "GET",
171+ &format!("/meals/balance/{ali_id}"),
172+ Some(&mgr),
173+ None,
174+ )
175+ .await;
176+ assert_eq!(res.body["balance_minor"], 0);
177+ let res = send(
178+ &app,
179+ "DELETE",
180+ &format!("/meals/menus/{menu}"),
181+ Some(&mgr),
182+ None,
183+ )
184+ .await;
185+ assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
186+
187+ // A classmate still cannot cancel someone else's seat.
188+ let menu = publish(&app, &mgr, "2026-09-16").await;
189+ let veli = login(&app, "promo_veli").await;
190+ let res = send(
191+ &app,
192+ "POST",
193+ &format!("/meals/menus/{menu}/bookings"),
194+ Some(&veli),
195+ Some(json!({})),
196+ )
197+ .await;
198+ let seat = id_of(&res.body);
199+ let can = login(&app, "promo_can").await;
200+ let res = send(
201+ &app,
202+ "DELETE",
203+ &format!("/meals/bookings/{seat}"),
204+ Some(&can),
205+ None,
206+ )
207+ .await;
208+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
209+}
210+
211+/// A debt survives its debtor's role change, so settling it has to. The credit
212+/// route took students only, which made such a debt permanently unpayable β€”
213+/// there is no other route that appends a credit. A target with no ledger
214+/// history at all is still refused, so a typo'd staff id cannot take money.
215+#[tokio::test]
216+async fn a_credit_settles_a_debt_that_outlived_the_students_role() {
217+ let (app, db) = app_and_db().await;
218+ let admin = login_as(&app, &db, "credit_admin", "admin").await;
219+ let ali = login(&app, "credit_ali").await;
220+ let ali_id = me_id(&app, &ali).await;
221+ let menu = publish(&app, &admin, "2026-09-17").await;
222+ add_dish(&app, &admin, &menu, 4_500).await;
223+ let res = send(
224+ &app,
225+ "POST",
226+ &format!("/meals/menus/{menu}/bookings"),
227+ Some(&ali),
228+ Some(json!({})),
229+ )
230+ .await;
231+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
232+
233+ set_role(&db, "credit_ali", "teacher").await;
234+ let res = send(
235+ &app,
236+ "POST",
237+ "/meals/credits",
238+ Some(&admin),
239+ Some(json!({ "student_id": ali_id, "amount_minor": 4_500 })),
240+ )
241+ .await;
242+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
243+ let res = send(
244+ &app,
245+ "GET",
246+ &format!("/meals/balance/{ali_id}"),
247+ Some(&admin),
248+ None,
249+ )
250+ .await;
251+ assert_eq!(res.body["balance_minor"], 0, "the debt is settled");
252+
253+ // Staff who never ate here carry no balance, so the typo still bites.
254+ let clean = login_as(&app, &db, "credit_clean", "teacher").await;
255+ let clean_id = me_id(&app, &clean).await;
256+ let res = send(
257+ &app,
258+ "POST",
259+ "/meals/credits",
260+ Some(&admin),
261+ Some(json!({ "student_id": clean_id, "amount_minor": 4_500 })),
262+ )
263+ .await;
264+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
265+}
266+
267+/// A mark must not create a row for a menu that is gone. The handler reads the
268+/// menu first, so this is driven below it β€” exactly the interleaving a mark in
269+/// flight while `DELETE /meals/menus/{id}` commits produces. The stake is not
270+/// tidiness: menu ids are deterministic on (date, slot), so an orphan mark comes
271+/// back as a mark on the *next* menu published for that meal.
272+#[tokio::test]
273+async fn a_mark_for_a_menu_that_is_gone_writes_no_row() {
274+ let (app, db) = app_and_db().await;
275+ let mgr = login_as(&app, &db, "mark_mgr", "manager").await;
276+ let ali = login(&app, "mark_ali").await;
277+ let ali_id = UserId::from_key(&me_id(&app, &ali).await);
278+ let mgr_id = UserId::from_key(&me_id(&app, &mgr).await);
279+ let menu = MenuId::from_key(&publish(&app, &mgr, "2026-09-18").await);
280+
281+ // The menu goes while the mark is on its way down.
282+ let res = send(
283+ &app,
284+ "DELETE",
285+ &format!("/meals/menus/{}", menu.key()),
286+ Some(&mgr),
287+ None,
288+ )
289+ .await;
290+ assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
291+
292+ let marked = MealAttendance::mark(
293+ &menu,
294+ &ali_id,
295+ MealAttendanceStatus::try_new("served").unwrap(),
296+ &mgr_id,
297+ &db,
298+ )
299+ .await
300+ .expect("the mark is refused, not an error");
301+ assert!(marked.is_none(), "no menu, no mark");
302+
303+ // Republishing that very day and slot mints the same id β€” and must not
304+ // inherit a mark for a meal nobody attended.
305+ let again = publish(&app, &mgr, "2026-09-18").await;
306+ assert_eq!(again, menu.key(), "the id is deterministic on date+slot");
307+ let res = send(
308+ &app,
309+ "GET",
310+ &format!("/meals/menus/{again}/attendance"),
311+ Some(&mgr),
312+ None,
313+ )
314+ .await;
315+ assert_eq!(common::total(&res.body), 0, "{}", res.body);
316+
317+ // The live menu still takes marks, and re-marking corrects in place.
318+ for status in ["served", "missed"] {
319+ let res = send(
320+ &app,
321+ "POST",
322+ &format!("/meals/menus/{again}/attendance"),
323+ Some(&mgr),
324+ Some(json!({ "student_id": ali_id.key(), "status": status })),
325+ )
326+ .await;
327+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
328+ assert_eq!(res.body["status"], status);
329+ }
330+ let res = send(
331+ &app,
332+ "GET",
333+ &format!("/meals/menus/{again}/attendance"),
334+ Some(&mgr),
335+ None,
336+ )
337+ .await;
338+ assert_eq!(common::total(&res.body), 1, "one row per (menu, person)");
339+}
340+
341+/// A dish write is fenced by its menu's existence, because the revision bump it
342+/// rides on *is* that fence: both are one transaction now, so an edit can no
343+/// longer land on a menu that has been unpublished β€” which is the same window
344+/// that let a booking see a bumped revision with the old price.
345+#[tokio::test]
346+async fn a_dish_write_is_refused_once_its_menu_is_gone() {
347+ let (app, db) = app_and_db().await;
348+ let mgr = login_as(&app, &db, "orphan_mgr", "manager").await;
349+ let menu = publish(&app, &mgr, "2026-09-19").await;
350+ let dish = add_dish(&app, &mgr, &menu, 1_000).await;
351+
352+ // The menu row alone is removed, leaving the dish exactly as a delete
353+ // interrupted between the row and its cascade would have.
354+ db.query("DELETE $id")
355+ .bind(("id", MenuId::from_key(&menu).record()))
356+ .await
357+ .unwrap()
358+ .check()
359+ .unwrap();
360+
361+ let res = send(
362+ &app,
363+ "PATCH",
364+ &format!("/meals/dishes/{dish}"),
365+ Some(&mgr),
366+ Some(json!({ "price_minor": 9_000 })),
367+ )
368+ .await;
369+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
370+ let res = send(
371+ &app,
372+ "DELETE",
373+ &format!("/meals/dishes/{dish}"),
374+ Some(&mgr),
375+ None,
376+ )
377+ .await;
378+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
379+
380+ // …and on a live menu both still work, at a fresh revision each time.
381+ let menu = publish(&app, &mgr, "2026-09-20").await;
382+ let dish = add_dish(&app, &mgr, &menu, 1_000).await;
383+ let res = send(
384+ &app,
385+ "PATCH",
386+ &format!("/meals/dishes/{dish}"),
387+ Some(&mgr),
388+ Some(json!({ "price_minor": 9_000 })),
389+ )
390+ .await;
391+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
392+ assert_eq!(res.body["price_minor"], 9_000);
393+ let res = send(
394+ &app,
395+ "DELETE",
396+ &format!("/meals/dishes/{dish}"),
397+ Some(&mgr),
398+ None,
399+ )
400+ .await;
401+ assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
402+}
403+
404+/// Unpublishing takes the dishes with it *in the delete's own transaction*: the
405+/// menu id is deterministic, so a cascade that ran afterwards and was cut short
406+/// left the next menu for that meal serving β€” and pricing β€” the old one's food.
407+#[tokio::test]
408+async fn unpublishing_takes_the_dishes_with_the_row() {
409+ let (app, db) = app_and_db().await;
410+ let mgr = login_as(&app, &db, "cascade_mgr", "manager").await;
411+ let menu = publish(&app, &mgr, "2026-09-21").await;
412+ add_dish(&app, &mgr, &menu, 1_000).await;
413+ send(
414+ &app,
415+ "DELETE",
416+ &format!("/meals/menus/{menu}"),
417+ Some(&mgr),
418+ None,
419+ )
420+ .await;
421+
422+ let again = publish(&app, &mgr, "2026-09-21").await;
423+ assert_eq!(again, menu, "the id is deterministic on date+slot");
424+ let res = send(
425+ &app,
426+ "GET",
427+ &format!("/meals/menus/{again}"),
428+ Some(&mgr),
429+ None,
430+ )
431+ .await;
432+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
433+ assert_eq!(
434+ res.body["dishes"].as_array().unwrap().len(),
435+ 0,
436+ "a republished meal starts empty"
437+ );
438+
439+ // A seat on it is therefore free, not billed for food nobody serves.
440+ let ali = login(&app, "cascade_ali").await;
441+ let res = send(
442+ &app,
443+ "POST",
444+ &format!("/meals/menus/{again}/bookings"),
445+ Some(&ali),
446+ Some(json!({})),
447+ )
448+ .await;
449+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
450+ let res = send(
451+ &app,
452+ "GET",
453+ &format!("/meals/balance/{}", me_id(&app, &ali).await),
454+ Some(&mgr),
455+ None,
456+ )
457+ .await;
458+ assert_eq!(res.body["balance_minor"], 0);
459+}
460+
461+/// A slot name goes verbatim into the menu's record id, and that id is a URL
462+/// path segment. A slot named `a/b` published a menu at an address no route
463+/// could ever match again β€” unreadable, uneditable, undeletable.
464+///
465+/// The settings now refuse the name outright, so the only way such a slot can
466+/// still be on a school's list is a row written before that rule β€” which is
467+/// what is staged straight into the store here. This gate is what that row
468+/// runs into.
469+#[tokio::test]
470+async fn a_slot_whose_name_would_break_the_menu_url_cannot_be_published() {
471+ let (app, db) = app_and_db().await;
472+ let admin = login_as(&app, &db, "slot_admin", "admin").await;
473+ let res = send(
474+ &app,
475+ "PATCH",
476+ "/settings",
477+ Some(&admin),
478+ Some(json!({ "meal_slots": [{"name": "a/b"}, {"name": "lunch"}] })),
479+ )
480+ .await;
481+ assert_eq!(
482+ res.status,
483+ StatusCode::BAD_REQUEST,
484+ "the settings must refuse the name themselves: {}",
485+ res.body
486+ );
487+
488+ // The legal half of that edit lands, which is what creates the row...
489+ let res = send(
490+ &app,
491+ "PATCH",
492+ "/settings",
493+ Some(&admin),
494+ Some(json!({ "meal_slots": [{"name": "lunch"}] })),
495+ )
496+ .await;
497+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
498+
499+ // ...and the stale row is that list as a database written before the rule.
500+ db.query(
501+ "UPDATE settings:school SET meal_slots = \
502+ [{ name: 'a/b', serving_minute: NONE }, { name: 'lunch', serving_minute: NONE }]",
503+ )
504+ .await
505+ .unwrap()
506+ .check()
507+ .unwrap();
508+
509+ let res = send(
510+ &app,
511+ "POST",
512+ "/meals/menus",
513+ Some(&admin),
514+ Some(json!({ "date": "2026-09-22", "slot": "a/b" })),
515+ )
516+ .await;
517+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
518+ // The school's other slots are unaffected.
519+ let res = send(
520+ &app,
521+ "POST",
522+ "/meals/menus",
523+ Some(&admin),
524+ Some(json!({ "date": "2026-09-22", "slot": "lunch" })),
525+ )
526+ .await;
527+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
528+}
529+
530+/// The cutoff exists to stop students moving the kitchen's headcount at the
531+/// last minute. It bound *staff* too, and that half-closed the very wedge
532+/// manager-cancel was widened to open: past the deadline the seat could not be
533+/// freed by anyone, and a menu refuses its own delete while a seat is held β€”
534+/// so the menu was undeletable and the charge unreversible, forever. Manager+
535+/// now cancels through a closed cutoff; students and parents still do not.
536+#[tokio::test]
537+async fn a_closed_cutoff_still_lets_a_manager_free_the_seat() {
538+ let (app, db) = app_and_db().await;
539+ let admin = login_as(&app, &db, "shut_adm", "admin").await;
540+ let mgr = login_as(&app, &db, "shut_mgr", "manager").await;
541+ let ali = login(&app, "shut_ali").await;
542+ let ali_id = me_id(&app, &ali).await;
543+ // A day long past β€” booked while the school ran no deadline at all.
544+ let menu = publish(&app, &mgr, "2020-01-02").await;
545+ add_dish(&app, &mgr, &menu, 1_000).await;
546+ let res = send(
547+ &app,
548+ "POST",
549+ &format!("/meals/menus/{menu}/bookings"),
550+ Some(&ali),
551+ Some(json!({})),
552+ )
553+ .await;
554+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
555+ let booking = id_of(&res.body);
556+
557+ // The school sets a deadline, and it closed on this menu long ago.
558+ let res = send(
559+ &app,
560+ "PATCH",
561+ "/settings",
562+ Some(&admin),
563+ Some(json!({ "meal_cancel_cutoff_minutes": 60 })),
564+ )
565+ .await;
566+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
567+
568+ let res = send(
569+ &app,
570+ "DELETE",
571+ &format!("/meals/bookings/{booking}"),
572+ Some(&ali),
573+ None,
574+ )
575+ .await;
576+ assert_eq!(
577+ res.status,
578+ StatusCode::CONFLICT,
579+ "the student is still bound by the cutoff: {}",
580+ res.body
581+ );
582+
583+ let res = send(
584+ &app,
585+ "DELETE",
586+ &format!("/meals/bookings/{booking}"),
587+ Some(&mgr),
588+ None,
589+ )
590+ .await;
591+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
592+ // The refund is the point: a bypass that freed the seat and kept the charge
593+ // would only move the wedge onto the money.
594+ let res = send(
595+ &app,
596+ "GET",
597+ &format!("/meals/balance/{ali_id}"),
598+ Some(&mgr),
599+ None,
600+ )
601+ .await;
602+ assert_eq!(res.body["balance_minor"], 0, "{}", res.body);
603+
604+ // …and with the seat back, the menu is deletable again.
605+ let res = send(
606+ &app,
607+ "DELETE",
608+ &format!("/meals/menus/{menu}"),
609+ Some(&mgr),
610+ None,
611+ )
612+ .await;
613+ assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
614+}
615+
616+/// Canteen debt is family debt, not classroom information β€” the same rule
617+/// `/payments` has always held. The two money reads shipped gated teacher+
618+/// (`ensure_can_observe`), so a form teacher could read what a family owed the
619+/// canteen while the identical `/payments` read 403'd them. Everything else in
620+/// the meals block β€” dietary profiles, bookings, attendance β€” stays teacher+ on
621+/// purpose; only the money moved.
622+#[tokio::test]
623+async fn only_manager_reads_another_students_meal_money() {
624+ let (app, db) = app_and_db().await;
625+ let admin = login_as(&app, &db, "money_admin", "admin").await;
626+ let mgr = login_as(&app, &db, "money_mgr", "manager").await;
627+ let teacher = login_as(&app, &db, "money_teacher", "teacher").await;
628+ let ali = login(&app, "money_ali").await;
629+ let ali_id = me_id(&app, &ali).await;
630+ let mother = login_as(&app, &db, "money_mother", "parent").await;
631+ let stranger = login_as(&app, &db, "money_stranger", "parent").await;
632+ let res = send(
633+ &app,
634+ "POST",
635+ &format!("/users/{}/students", me_id(&app, &mother).await),
636+ Some(&admin),
637+ Some(json!({ "user_id": ali_id })),
638+ )
639+ .await;
640+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
641+
642+ for route in [
643+ format!("/meals/balance/{ali_id}"),
644+ format!("/meals/ledger/{ali_id}"),
645+ ] {
646+ for (who, cookie, want) in [
647+ ("teacher", &teacher, StatusCode::FORBIDDEN),
648+ ("unlinked parent", &stranger, StatusCode::FORBIDDEN),
649+ ("manager", &mgr, StatusCode::OK),
650+ ("admin", &admin, StatusCode::OK),
651+ ("linked parent", &mother, StatusCode::OK),
652+ ("the student themselves", &ali, StatusCode::OK),
653+ ] {
654+ let res = send(&app, "GET", &route, Some(cookie), None).await;
655+ assert_eq!(res.status, want, "{who} on {route}: {}", res.body);
656+ }
657+ }
658+
659+ // The rest of the block did not move with the money: a teacher still reads
660+ // the allergen list and the attendance history they need at the door.
661+ for route in [
662+ format!("/meals/profiles/{ali_id}"),
663+ format!("/meals/attendance/{ali_id}"),
664+ ] {
665+ let res = send(&app, "GET", &route, Some(&teacher), None).await;
666+ assert_eq!(
667+ res.status,
668+ StatusCode::OK,
669+ "teacher on {route}: {}",
670+ res.body
671+ );
672+ }
673+}