forge
Explore
Log in

Don't you dare go Hollow

🧷 close the cross-table races the locks never closed

Browse files at this commit

4f7bdaf780f9410d8a2d7ec96c1373b30952dd4eAhmet Kaan GümüşParent: 6c87eca
  • fix
    • 🧷 close the cross-table races the locks never closed
Show full message
fix: 🧷 close the cross-table races the locks never closed

Every remaining check-then-write that spanned tables becomes a
single-record conditional write, so it holds across replicas:

- subject delete: refcounts (exam_question_count/homework_count) claimed
  and released by every question/homework write; the triple lock hold
  dies, BANK/TERM/ENROLL locks die outright
- exam kinds: kind_ref {count,retired} records; grading claims, removal
  retires only at zero — grading a removed kind and re-kinding a graded
  exam are now 409 (both previously silently mis-weighted marks)
- homework: the grade stamps the submission row in its own transaction;
  student writes are conditional on the stamp being absent
- appointments: slot occupancy is a cap-1 counter; the lock survives
  only for the within-replica approved-overlap check
- meals: seat counter + menu version CAS (price can no longer tear mid
  booking) + deterministic menu:date_slot id kills duplicate publish
- cap::claim_and_create: member gate, then seat, then child CREATE in
  one transaction — a duplicate loser no longer eats a stranger's seat
  or gets refused for a row it already owns
- boot: the two unguarded lease statements now retry on transaction
  conflict (the escape was ~1-in-15 under full-suite load)

Two races reviewed and accepted, documented in README ## Concurrency
model: the attempt-seq late save (one history row, grade of record
untouched) and cross-replica approved-overlap (visible, cancellable).

Deployment contract (README): counter-adding releases restart all
replicas together — an old binary's writes skip new counters and the
= NONE backfill guard rightly refuses to re-seed.

Every guard is mutation-proven; backfills are one-time, = NONE-guarded,
ordered after the destructive sweeps, and verified against the live
volume.

40 changed files +4155 -897

README.mdmodified+69 -14
@@ -675,9 +675,9 @@ window filtering, before paging; negative values are a `400` naming the field.
675 | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) · paged |675 | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) · paged |
676 | GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) · paged · `?starts_after=&ends_after=` window (soonest first) |676 | GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) · paged · `?starts_after=&ends_after=` window (soonest first) |
677 | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |677 | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |
678-| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `mode` frozen once attempted, re-drafting frozen once attempts/results exist — the rest stays live; concurrent edits merge, never silently revert each other) |678+| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `kind` and `mode` frozen once marks/attempts exist, re-drafting frozen once attempts/results exist — the rest stays live; concurrent edits merge, never silently revert each other) |
679 | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |679 | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |
680-| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only; drafts can't be graded, `409`) |680+| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only; drafts, and exams whose kind the school has removed, can't be graded, `409`) |
681 | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged |681 | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged |
682 | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |682 | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |
683 | DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |683 | DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |
@@ -773,7 +773,7 @@ window filtering, before paging; negative values are a `400` naming the field.
773 | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |773 | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |
774 | GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` — full |774 | GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` — full |
775 | 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` |775 | 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` |
776-| 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 (see "Per-school policy") |776+| 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") |
777 | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) |777 | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) |
778 | GET | `/terms` | student | List terms, newest first · paged |778 | GET | `/terms` | student | List terms, newest first · paged |
779 | GET | `/terms/{id}` | student | Get one term |779 | GET | `/terms/{id}` | student | Get one term |
@@ -790,7 +790,7 @@ window filtering, before paging; negative values are a `400` naming the field.
790 | GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |790 | GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |
791 | GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |791 | GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |
792 | 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 |792 | 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 |
793-| 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 or its cutoff has passed |793+| 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 |
794 | 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 |794 | 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 |
795 | GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included · paged |795 | GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included · paged |
796 | 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 |796 | 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 |
@@ -967,7 +967,9 @@ particular person and a particular topic, so approve/reject still applies.
967 967
968 A booking is `pending`, `approved`, `rejected`, or `cancelled`. The first two968 A booking is `pending`, `approved`, `rejected`, or `cancelled`. The first two
969 are **live** and hold the slot; rejecting or cancelling frees it for someone969 are **live** and hold the slot; rejecting or cancelling frees it for someone
970-else immediately (occupancy is counted live, never stored as a flag). The970+else immediately (the slot carries an `occupied` counter, taken by a booking
971+and handed back in the same transaction as the reject or cancel that settles
972+it, so the guard holds across replicas). The
971 decisions:973 decisions:
972 974
973 - `PATCH /{id}/approve` — the slot's teacher (or manager+) confirms. Refused975 - `PATCH /{id}/approve` — the slot's teacher (or manager+) confirms. Refused
@@ -981,7 +983,7 @@ decisions:
981 simply by rescheduling to a time that works. Refused (`409`) once the983 simply by rescheduling to a time that works. Refused (`409`) once the
982 meeting's window has started: a984 meeting's window has started: a
983 meeting that already began is history, not a plan. The guard sits in the985 meeting that already began is history, not a plan. The guard sits in the
984- domain's `cancel` itself, under the appointment lock and on a fresh read, so986+ domain's `cancel` itself, on a fresh read compared-and-set into the row, so
985 every way of cancelling — the decline below included — inherits it.987 every way of cancelling — the decline below included — inherits it.
986 - `PATCH /{id}/reschedule` (`{starts_at, ends_at}`) — the teacher988 - `PATCH /{id}/reschedule` (`{starts_at, ends_at}`) — the teacher
987 **counter-proposes**. The times land on the *same* row as989 **counter-proposes**. The times land on the *same* row as
@@ -1132,7 +1134,12 @@ editable `settings` singleton (`GET /settings` for any signed-in user,
1132 re-weights every exam of that kind at once. For the same reason a kind1134 re-weights every exam of that kind at once. For the same reason a kind
1133 whose exams already carry marks cannot be removed from the list (`409`):1135 whose exams already carry marks cannot be removed from the list (`409`):
1134 those marks would silently re-weight. An unmarked kind leaves freely, and1136 those marks would silently re-weight. An unmarked kind leaves freely, and
1135- an exam keeping a since-removed kind counts with weight `1`.1137+ an exam keeping a since-removed kind counts with weight `1` — but it can no
1138+ longer be graded (`409`) until the school offers that kind again, which is
1139+ what keeps "a marked kind cannot be removed" true from both ends. The same
1140+ rule pointed at one exam: an exam that already carries marks keeps its
1141+ `kind` (`PATCH /exams/{id}` answers `409`), because re-pointing it would
1142+ re-weight those marks just as silently.
1136 - **`attendance_statuses`** — what attendance marking accepts. The core four1143 - **`attendance_statuses`** — what attendance marking accepts. The core four
1137 (`present`, `absent`, `late`, `excused`) are mandatory because the1144 (`present`, `absent`, `late`, `excused`) are mandatory because the
1138 attendance rate is defined over them (`(present+late) /1145 attendance rate is defined over them (`(present+late) /
@@ -1167,7 +1174,8 @@ policy still matches the snapshot it merged from (retrying over the fresh row
1167 otherwise), so two managers patching different fields both land instead of1174 otherwise), so two managers patching different fields both land instead of
1168 the later write silently reverting the earlier one. Editing a list never1175 the later write silently reverting the earlier one. Editing a list never
1169 rewrites history: an exam keeps its retired kind, a roll-call row keeps its1176 rewrites history: an exam keeps its retired kind, a roll-call row keeps its
1170-retired status — only **new writes** are held to the current lists.1177+retired status — only **new writes** are held to the current lists (which is
1178+why grading an exam whose kind has left the list is refused).
1171 1179
1172 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").1180 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").
1173 1181
@@ -1698,9 +1706,12 @@ a bank row **never freezes** — its owner can edit or delete it forever.
1698 1706
1699 `POST /bank-questions` (teacher+) saves one, stamping the caller as its1707 `POST /bank-questions` (teacher+) saves one, stamping the caller as its
1700 **owner**. `subject_id` is origin metadata, but it must **exist** — an unknown1708 **owner**. `subject_id` is origin metadata, but it must **exist** — an unknown
1701-subject is a `400` (create and PATCH alike); the reverse guard holds too, so1709+subject is a `400` (create and PATCH alike). The reverse guard does **not**
1702-deleting a subject a template still references is a `409` (same as exam1710+hold here, unlike exam questions and homework: a template never blocks a
1703-questions and homework). Reads are school-wide: `GET /bank-questions` lists the1711+subject delete, which simply clears `subject` off every template that carried
1712+it (only a template's owner may re-tag it, so a `409` would be one a manager
1713+could never clear — and a private template raising it would leak its
1714+existence). Reads are school-wide: `GET /bank-questions` lists the
1704 whole bank (paged, `?subject=<id>` narrows by origin subject, `?owner=<id>` — or1715 whole bank (paged, `?subject=<id>` narrows by origin subject, `?owner=<id>` — or
1705 `?owner=me` — by owner) and `GET /bank-questions/{bid}` fetches one with1716 `?owner=me` — by owner) and `GET /bank-questions/{bid}` fetches one with
1706 `correct` included — any teacher+ can browse and reuse what any colleague1717 `correct` included — any teacher+ can browse and reuse what any colleague
@@ -2274,6 +2285,47 @@ as the message's `error_code`.
2274 add fields (a model name, token counts) and a future backend may send more2285 add fields (a model name, token counts) and a future backend may send more
2275 context without either end having to be redeployed in lockstep.2286 context without either end having to be redeployed in lockstep.
2276 2287
2288+## Concurrency model
2289+
2290+The backend runs as more than one replica against one database, so every
2291+invariant is guarded where all replicas can see it. Three tiers:
2292+
2293+1. **Single-row conditional writes** — compare-and-set (`save_if_unchanged`),
2294+ `UPDATE … WHERE`, stored counters (`domain::cap`), leases. These hold
2295+ *across replicas*: the database decides the winner, the loser retries or
2296+ gets a 409.
2297+2. **In-transaction `IF … THROW` gates** — the check runs inside the same
2298+ statement as the write it authorizes, so it is atomic with it. Used where
2299+ the rule reads the row being written (state machines, delete guards).
2300+ "Is anything still attached?" is answered the same way, by a counter on the
2301+ row being deleted rather than a `SELECT` over the children: a course is
2302+ deletable while its `enrollment_count` is zero, a term while its
2303+ `course_count` is (courses claim that reference *before* they write the
2304+ link, and give it back when the link moves or the course is deleted).
2305+ Where the child also carries a deterministic id — one enrollment per
2306+ (course, user), one registration per (event, user) — the seat and the row
2307+ are claimed in one transaction (`cap::claim_and_create`), so a duplicate
2308+ `CREATE` rolls its own seat back instead of costing a stranger their place.
2309+3. **Two accepted races**, reviewed and deliberately left open:
2310+ - *Attempt-seq late save* — a save racing a retake can stamp an answer onto
2311+ the just-terminal previous sitting. Damage: one history row; the grade of
2312+ record (latest `seq`) is never touched.
2313+ - *Approved-overlap* — two replicas approving in the same instant can
2314+ double-book a teacher. Damage: one overlapping half-hour, visible to both
2315+ parties, fixable by cancelling either side.
2316+
2317+In-process locks that remain do so for reasons a database write cannot serve:
2318+`PRESENCE_LOCK` guards in-process socket state, `CLAIM_LOCK` keeps one
2319+counter writer per process (the `WHERE` clause is the cap — the lock only
2320+tames the retry loop, and keeps the tests' in-memory engine deterministic),
2321+`APPOINTMENT_LOCK` still collapses the common within-replica overlap case.
2322+
2323+Deployment contract: a release that adds or renames a stored counter must
2324+restart *all* replicas together (`podman compose down` + `up`), never rolling.
2325+An old binary writes rows without touching the new counters, the `= NONE`
2326+backfill guard (correctly) refuses to re-seed, and the resulting permanent
2327+under-count lets a guard approve exactly what it exists to refuse.
2328+
2277 ## Layout2329 ## Layout
2278 2330
2279 ```2331 ```
@@ -2310,7 +2362,9 @@ src/
2310 cap.rs claim()/release(): the cross-replica count caps — an atomic2362 cap.rs claim()/release(): the cross-replica count caps — an atomic
2311 `UPDATE parent SET n += 1 WHERE n < cap` on a counter column2363 `UPDATE parent SET n += 1 WHERE n < cap` on a counter column
2312 of the parent row, replacing the per-process mutexes that2364 of the parent row, replacing the per-process mutexes that
2313- only held while one instance owned the database2365+ only held while one instance owned the database;
2366+ claim_and_create() commits that seat and the child row in
2367+ one transaction, for children with a deterministic id
2314 text_fold.rs case- and diacritic-insensitive folding for search, shared by2368 text_fold.rs case- and diacritic-insensitive folding for search, shared by
2315 the Rust needle and the SurrealQL column (Turkish İ/ı, ü, ö…)2369 the Rust needle and the SurrealQL column (Turkish İ/ı, ü, ö…)
2316 session.rs SessionId · SessionToken · Session (7-day expiry)2370 session.rs SessionId · SessionToken · Session (7-day expiry)
@@ -2374,8 +2428,9 @@ src/
2374 AppointmentSlot (a teacher's published availability; a2428 AppointmentSlot (a teacher's published availability; a
2375 recurring publish is expanded into rows sharing a series id)2429 recurring publish is expanded into rows sharing a series id)
2376 appointment.rs AppointmentId · AppointmentStatus · AppointmentReason ·2430 appointment.rs AppointmentId · AppointmentStatus · AppointmentReason ·
2377- Appointment (a booking on a slot; occupancy and overlap are2431+ Appointment (a booking on a slot; occupancy is the slot's
2378- derived under APPOINTMENT_LOCK, never stored)2432+ stored `occupied` cap-1 counter, overlap is derived under
2433+ APPOINTMENT_LOCK)
2379 pomodoro.rs PomodoroSessionId · PomodoroSession (student focus log)2434 pomodoro.rs PomodoroSessionId · PomodoroSession (student focus log)
2380 pool_question.rs PoolQuestionId · PoolQuestionTitle · PoolQuestionBody ·2435 pool_question.rs PoolQuestionId · PoolQuestionTitle · PoolQuestionBody ·
2381 PoolQuestion (student-asked question; teacher-approved into2436 PoolQuestion (student-asked question; teacher-approved into
src/constant.rsmodified+51 -0
@@ -742,6 +742,11 @@ pub const DIETARY_PROFILE_TABLE: &str = "dietary_profile";
742 pub const MEAL_BOOKING_TABLE: &str = "meal_booking";742 pub const MEAL_BOOKING_TABLE: &str = "meal_booking";
743 pub const MEAL_ATTENDANCE_TABLE: &str = "meal_attendance";743 pub const MEAL_ATTENDANCE_TABLE: &str = "meal_attendance";
744 pub const MEAL_LEDGER_TABLE: &str = "meal_ledger";744 pub const MEAL_LEDGER_TABLE: &str = "meal_ledger";
745+/// One row per *name* the school's settings offer, keyed by the name itself:
746+/// how many rows still reference it, and whether it has been retired out of the
747+/// list (see the reference counters in [`crate::domain::cap`]).
748+pub const KIND_REF_TABLE: &str = "kind_ref";
749+pub const SLOT_REF_TABLE: &str = "slot_ref";
745 750
746 // --- cross-replica cap counters ----------------------------------------751 // --- cross-replica cap counters ----------------------------------------
747 752
@@ -754,9 +759,55 @@ pub const MEAL_LEDGER_TABLE: &str = "meal_ledger";
754 /// SCHEMAFULL refusing the write.759 /// SCHEMAFULL refusing the write.
755 pub const ENROLLMENT_COUNT_FIELD: &str = "enrollment_count";760 pub const ENROLLMENT_COUNT_FIELD: &str = "enrollment_count";
756 pub const REGISTRATION_COUNT_FIELD: &str = "registration_count";761 pub const REGISTRATION_COUNT_FIELD: &str = "registration_count";
762+/// Not a cap — a refcount, and the whole of the term delete guard: how many
763+/// courses link this term. A term may only be dropped at zero, and the count
764+/// is claimed before a course's link is written, so the two decisions contend
765+/// on the term row instead of on a cross-table `SELECT` no transaction orders.
766+pub const COURSE_COUNT_FIELD: &str = "course_count";
757 pub const NOTE_FILE_COUNT_FIELD: &str = "file_count";767 pub const NOTE_FILE_COUNT_FIELD: &str = "file_count";
758 pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count";768 pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count";
759 pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count";769 pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count";
770+/// Cap 1, not N: an appointment slot holds at most one live booking, so this
771+/// counter is really an "is it taken" flag kept in the shape every other cap
772+/// uses (`claim`/`release`), which is what makes rejecting or cancelling a
773+/// booking give the slot back.
774+pub const SLOT_OCCUPIED_FIELD: &str = "occupied";
775+/// Not caps either, and uncapped by design: how many exam questions and how
776+/// many homework still point at a subject. A subject may be deleted exactly
777+/// while both read zero, so the delete's own `WHERE` decides it — the
778+/// cross-table "does anything reference this?" count it replaces served one
779+/// replica only.
780+pub const SUBJECT_QUESTION_COUNT_FIELD: &str = "exam_question_count";
781+pub const SUBJECT_HOMEWORK_COUNT_FIELD: &str = "homework_count";
782+/// How many marks an exam carries. Uncapped too, and the only counter its
783+/// entity carries as a field: the exam's save is a whole-row `CONTENT` write,
784+/// which would wipe a column the struct did not know about. That save pins it,
785+/// which is what makes "this exam has no marks" — the gate a kind change is
786+/// refused on — decided at write time rather than at read time.
787+pub const EXAM_RESULT_COUNT_FIELD: &str = "result_count";
788+/// The two columns of a reference-counter row (`kind_ref`, `slot_ref`): how
789+/// many rows still point at the name, and whether it has left the school's
790+/// list. Both `option<…>`, absent meaning zero references and in service.
791+pub const REF_COUNT_FIELD: &str = "count";
792+pub const REF_RETIRED_FIELD: &str = "retired";
793+/// Seats held on one menu — the meal capacity cap.
794+pub const MENU_SEAT_COUNT_FIELD: &str = "seats_booked";
795+/// Not a cap: the menu's revision, bumped by every write that can change what
796+/// a seat costs (a dish added, re-priced or removed, the capacity moved). A
797+/// booking claims its seat only at the revision it read the price at, so the
798+/// price frozen onto the row is one the menu really carried at that instant.
799+pub const MENU_VERSION_FIELD: &str = "version";
800+
801+/// Not a cap either: the grade that froze a homework submission, absent while
802+/// the submission is still open. Every student-side write to a submission (its
803+/// text, its files) carries `graded_by_result = NONE` as a condition, so the
804+/// "not graded yet" decision and the write it licenses are one conditional
805+/// single-record write rather than a cross-table read a peer replica can
806+/// outrun. Set by grading, cleared by un-grading, never by the student.
807+pub const SUBMISSION_GRADED_FIELD: &str = "graded_by_result";
808+/// The condition itself, spelled once: a submission is writable exactly while
809+/// its grade stamp is absent.
810+pub const SUBMISSION_OPEN_GUARD: &str = "graded_by_result = NONE";
760 811
761 /// How hard a counter write tries before giving up, and the first backoff step812 /// How hard a counter write tries before giving up, and the first backoff step
762 /// it sleeps between attempts (doubling, plus jitter). Contention on one record813 /// it sleeps between attempts (doubling, plus jitter). Contention on one record
src/database.rsmodified+79 -14
@@ -7,9 +7,10 @@ use surrealdb::types::SurrealValue;
7 7
8 use crate::config::Config;8 use crate::config::Config;
9 use crate::constant::{9 use crate::constant::{
10- CHATBOT_PENDING_STALE_SECS, MIGRATION_LOCK_CLAIM, MIGRATION_LOCK_DDL, MIGRATION_LOCK_HEARTBEAT,10+ CAS_UPDATE_RETRIES, CHATBOT_PENDING_STALE_SECS, MIGRATION_LOCK_CLAIM, MIGRATION_LOCK_DDL,
11- MIGRATION_LOCK_HEARTBEAT_SECS, MIGRATION_LOCK_LEASE_SECS, MIGRATION_LOCK_POLL_MS,11+ MIGRATION_LOCK_HEARTBEAT, MIGRATION_LOCK_HEARTBEAT_SECS, MIGRATION_LOCK_LEASE_SECS,
12- MIGRATION_LOCK_STAMP, MIGRATION_LOCK_STATE, MIGRATION_LOCK_TAKEOVER, MIGRATION_LOCK_WAIT_SECS,12+ MIGRATION_LOCK_POLL_MS, MIGRATION_LOCK_STAMP, MIGRATION_LOCK_STATE, MIGRATION_LOCK_TAKEOVER,
13+ MIGRATION_LOCK_WAIT_SECS,
13 };14 };
14 use crate::domain::user::{Password, User, Username};15 use crate::domain::user::{Password, User, Username};
15 use crate::error::AppError;16 use crate::error::AppError;
@@ -143,13 +144,24 @@ async fn boot_once(
143 if claim(db, MIGRATION_LOCK_CLAIM, &me, lease_ms).await? {144 if claim(db, MIGRATION_LOCK_CLAIM, &me, lease_ms).await? {
144 return leader_applies(db, &me, admin).await.map(|()| true);145 return leader_applies(db, &me, admin).await.map(|()| true);
145 }146 }
146- let state: Option<LockState> = db147+ let read = db
147 .query(MIGRATION_LOCK_STATE)148 .query(MIGRATION_LOCK_STATE)
148 .bind(("lease_ms", lease_ms))149 .bind(("lease_ms", lease_ms))
149 .bind(("fingerprint", migration_fingerprint()))150 .bind(("fingerprint", migration_fingerprint()))
150- .await?151+ .await
151- .check()?152+ .and_then(|response| response.check())
152- .take(0)?;153+ .and_then(|mut response| response.take::<Option<LockState>>(0));
154+ let state = match read {
155+ Ok(state) => state,
156+ // The leader heartbeats this very row every few seconds and rivals
157+ // take it over, so a read of it can be aborted as retryable — which
158+ // is not an error about the lock, just "no answer this round". This
159+ // poll loop, with its deadline, *is* the bounded retry the conflict
160+ // asks for, so treat it like a missing row and look again. Retrying
161+ // a `SELECT` is free of side effects by construction.
162+ Err(err) if lost_the_race(&err) => None,
163+ Err(err) => return Err(err.into()),
164+ };
153 match state {165 match state {
154 // A live lease, stamped with our own fingerprint: the exact schema166 // A live lease, stamped with our own fingerprint: the exact schema
155 // this process needs is in place, so stop waiting.167 // this process needs is in place, so stop waiting.
@@ -328,13 +340,34 @@ async fn leader_applies(
328 lost = renew_lease(db, me) => return Err(lost),340 lost = renew_lease(db, me) => return Err(lost),
329 }341 }
330 342
331- let mut response = db343+ // The stamp is the one write in this path with nothing above it to retry
332- .query(MIGRATION_LOCK_STAMP)344+ // it: waiters are polling the same row and taking it over, so the
333- .bind(("me", me.to_string()))345+ // key-value layer can abort ours as retryable, and an escaping conflict
334- .bind(("fingerprint", migration_fingerprint()))346+ // fails a boot that had already migrated everything. Repeating it is safe
335- .await?347+ // despite `applies += 1` — a conflicted transaction commits nothing, and
336- .check()?;348+ // the statement's `holder` guard turns a *genuine* takeover into an empty
337- let stamped: Vec<String> = response.take(0)?;349+ // result rather than a second count. Bounded, because a conflict that
350+ // never clears is a real failure and must stay one.
351+ let mut stamped: Vec<String> = Vec::new();
352+ for attempt in 0..CAS_UPDATE_RETRIES {
353+ let attempted = db
354+ .query(MIGRATION_LOCK_STAMP)
355+ .bind(("me", me.to_string()))
356+ .bind(("fingerprint", migration_fingerprint()))
357+ .await
358+ .and_then(|response| response.check());
359+ match attempted {
360+ Ok(mut response) => {
361+ stamped = response.take(0)?;
362+ break;
363+ }
364+ Err(err) if lost_the_race(&err) && attempt + 1 < CAS_UPDATE_RETRIES => {
365+ tracing::warn!("stamping the boot migration lock conflicted ({err}) — retrying");
366+ tokio::time::sleep(std::time::Duration::from_millis(MIGRATION_LOCK_POLL_MS)).await;
367+ }
368+ Err(err) => return Err(err.into()),
369+ }
370+ }
338 if stamped.is_empty() {371 if stamped.is_empty() {
339 // The same verdict as a lost renewal, for the same reason — this is the372 // The same verdict as a lost renewal, for the same reason — this is the
340 // backstop for losing the lock in the window between the last renewal373 // backstop for losing the lock in the window between the last renewal
@@ -524,6 +557,38 @@ mod tests {
524 );557 );
525 }558 }
526 559
560+ /// The same race with enough processes in it to actually hit the
561+ /// key-value layer's retryable aborts: eight boots contending for one lock
562+ /// row collide on the losers' state read and the leader's stamp, which with
563+ /// two boots surfaces only once in a few full-suite runs.
564+ ///
565+ /// What it asserts is deliberately narrow: no boot may fail with a
566+ /// *retryable* conflict. A conflict is the layer asking to be asked again,
567+ /// so one reaching the caller is always a missing retry — while the other
568+ /// outcomes of a crowded election (a leader that loses its lease to a
569+ /// taker) are documented behaviour, not bugs, and asserting against them
570+ /// here would only make this flaky. Exactly-once stays the two-boot test's
571+ /// job.
572+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
573+ async fn a_crowd_of_boots_never_surfaces_a_retryable_conflict() {
574+ let db = unmigrated().await;
575+ let boots: Vec<_> = (0..8)
576+ .map(|_| {
577+ let db = db.clone();
578+ tokio::spawn(async move { boot_once(&db, admin(), Duration::from_secs(30)).await })
579+ })
580+ .collect();
581+ for boot in boots {
582+ if let Err(err) = boot.await.unwrap() {
583+ let message = err.to_string();
584+ assert!(
585+ !message.contains("can be retried") && !message.contains("conflict"),
586+ "a retryable conflict escaped boot_once instead of being retried: {message}"
587+ );
588+ }
589+ }
590+ }
591+
527 /// A leader killed mid-migration leaves its claim behind. Nothing may592 /// A leader killed mid-migration leaves its claim behind. Nothing may
528 /// require a human with a SurrealQL prompt to clear it: the next boot takes593 /// require a human with a SurrealQL prompt to clear it: the next boot takes
529 /// the lease over once it has gone unrenewed past the horizon.594 /// the lease over once it has gone unrenewed past the horizon.
src/domain/appointment.rsmodified+200 -84
@@ -2,28 +2,32 @@
2 //! for the meeting with a reason; the teacher approves, rejects, or2 //! for the meeting with a reason; the teacher approves, rejects, or
3 //! counter-proposes another time.3 //! counter-proposes another time.
4 //!4 //!
5-//! Two *cross-record* invariants live here, and both are guarded by5+//! Two *cross-record* invariants live here, guarded very differently:
6-//! [`APPOINTMENT_LOCK`] rather than by the database:
7 //!6 //!
8-//! - **One live booking per slot.** Occupancy is counted from the rows, not7+//! - **One live booking per slot** — the `occupied` counter on the slot row, a
9-//! stored — so rejecting or cancelling frees the slot with nothing to reset.8+//! [`cap`](crate::domain::cap) of one. Booking [`claim`](cap::claim)s it;
9+//! rejecting or cancelling gives it back in the *same transaction* as the
10+//! status flip, so the slot frees itself with nothing to sweep. Both are
11+//! single-record conditional writes, so this invariant holds across replicas.
10 //! - **No double-booked person.** An approved meeting may not overlap another12 //! - **No double-booked person.** An approved meeting may not overlap another
11-//! approved meeting of the same teacher *or* of the same requester.13+//! approved meeting of the same teacher *or* of the same requester. That is a
12-//!14+//! count-then-write over *many* rows, which a `BEGIN…COMMIT` does not
13-//! Both are count-then-write checks across records, which a `BEGIN…COMMIT`15+//! serialize in SurrealDB (write-skew), so it stays under
14-//! does not serialize in SurrealDB (write-skew: two racing bookings each see a16+//! [`APPOINTMENT_LOCK`] — and stays replica-local.
15-//! free slot).
16 //!17 //!
17 //! The *single-row* invariant — a decision must be written onto the state it18 //! The *single-row* invariant — a decision must be written onto the state it
18 //! was validated against — is **not** the lock's job, and never was: the lock19 //! was validated against — is **not** the lock's job, and never was: the lock
19 //! is process-local, so two replicas each take their own copy of it and a20 //! is process-local, so two replicas each take their own copy of it and a
20 //! whole-row save would silently drop the other's decision. That one is a21 //! whole-row save would silently drop the other's decision. That one is a
21 //! compare-and-set ([`Appointment::save_if_unchanged`]), which holds across22 //! compare-and-set ([`Appointment::save_if_unchanged`]), which holds across
22-//! replicas. The lock stays for the two counts above, which no per-row23+//! replicas.
23-//! conditional write can cover.24+//!
24-// ponytail: with more than one replica those two counts are only25+//! Overlap is a **documented accepted race** (reviewed, not an oversight):
25-// replica-local. Closing them needs a stored occupancy counter (`domain::cap`)26+//! it is a predicate over *other* rows with no single row to key a counter or
26-// rather than a lock — deliberately not built here.27+//! a CAS on, so across replicas two approvals decided in the same instant can
28+//! both land. Damage is one double-booked half-hour, visible to both parties
29+//! and fixable by cancelling either side — no money, no grade, no data loss.
30+//! Closing it would need a lease row per teacher taken on every approval.
27 31
28 use std::sync::LazyLock;32 use std::sync::LazyLock;
29 33
@@ -31,20 +35,33 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
31 use tokio::sync::Mutex;35 use tokio::sync::Mutex;
32 use ulid::Generator;36 use ulid::Generator;
33 37
34-use crate::constant::{APPOINTMENT_TABLE, CAS_UPDATE_RETRIES, MAX_APPOINTMENT_REASON_LEN};38+use crate::constant::{
39+ APPOINTMENT_TABLE, CAS_UPDATE_RETRIES, MAX_APPOINTMENT_REASON_LEN, SLOT_OCCUPIED_FIELD,
40+};
35 use crate::database::{Database, lost_the_race};41 use crate::database::{Database, lost_the_race};
36 use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId};42 use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId};
43+use crate::domain::cap;
37 use crate::domain::page::PagedList;44 use crate::domain::page::PagedList;
38 use crate::domain::timestamp::Timestamp;45 use crate::domain::timestamp::Timestamp;
39 use crate::domain::user::UserId;46 use crate::domain::user::UserId;
40 use crate::error::{AppError, ValidationError};47 use crate::error::{AppError, ValidationError};
41 use crate::validate::validate_required;48 use crate::validate::validate_required;
42 49
43-/// Serializes every occupancy/overlap decision: the check and the write it50+/// Serializes the **overlap** check and the write it authorizes — nothing else.
44-/// authorizes must be one atomic step, and SurrealDB transactions do not51+/// "Is this teacher (or this requester) already committed at that time" is a
45-/// conflict-check a cross-record `count()` against a concurrent insert.52+/// predicate over other appointment rows, and SurrealDB does not conflict-check
53+/// a cross-record read against a concurrent insert, so the check and its write
54+/// have to be one atomic step *within this process*. Occupancy is no longer its
55+/// business: that is the slot's `occupied` counter, a conditional single-record
56+/// write that holds between replicas too.
57+///
58+/// Which leaves the accepted race the module doc records: this lock is
59+/// process-local, so two replicas can each approve an overlapping meeting in
60+/// the same instant. Visible to both parties, undone by cancelling either side.
46 ///61 ///
47-/// Lock order: no path ever holds this together with `ENROLL_LOCK`,62+/// Lock order: taken *before* `cap`'s `CLAIM_LOCK` (booking claims a slot while
63+/// holding this) and never the other way round. No path ever holds this
64+/// together with `ENROLL_LOCK`,
48 /// `TERM_LOCK`, `EXAM_LOCK`, or `PRESENCE_LOCK` — appointments65 /// `TERM_LOCK`, `EXAM_LOCK`, or `PRESENCE_LOCK` — appointments
49 /// touch no roster, term, event seat, or exam room, and none of those touch66 /// touch no roster, term, event seat, or exam room, and none of those touch
50 /// appointments — so they cannot deadlock. Should a future path ever need two,67 /// appointments — so they cannot deadlock. Should a future path ever need two,
@@ -299,60 +316,15 @@ impl Appointment {
299 }))316 }))
300 }317 }
301 318
302- /// Does `slot` still hold a booking that keeps it occupied? The slot
303- /// delete guard's question, and the re-booking gate's. Caller must hold
304- /// [`APPOINTMENT_LOCK`].
305- pub async fn has_live_booking(
306- slot: &AppointmentSlotId,
307- db: &Database,
308- ) -> Result<bool, AppError> {
309- let mut result = db
310- .query(
311- "SELECT * FROM appointment WHERE slot = $slot \
312- AND status IN ['pending', 'approved'] LIMIT 1",
313- )
314- .bind(("slot", slot.record()))
315- .await?
316- .check()?;
317- Ok(!result.take::<Vec<Appointment>>(0)?.is_empty())
318- }
319-
320- /// Same question as [`has_live_booking`](Self::has_live_booking) asked of a
321- /// whole series at once: does *any* of `slots` still hold an occupied
322- /// booking? One round-trip, because a weekly publish is up to 52 slots and
323- /// the caller asks while holding the lock. Caller must hold
324- /// [`APPOINTMENT_LOCK`], for the same reason: the answer is only meaningful
325- /// while no booking can be written.
326- ///
327- /// No slots, no bookings — answered without a query, since an empty `IN`
328- /// list is a needless round-trip and must never read as "occupied".
329- pub async fn any_live_booking(
330- slots: &[AppointmentSlotId],
331- db: &Database,
332- ) -> Result<bool, AppError> {
333- if slots.is_empty() {
334- return Ok(false);
335- }
336- let records: Vec<RecordId> = slots.iter().map(AppointmentSlotId::record).collect();
337- let mut result = db
338- .query(
339- "SELECT * FROM appointment WHERE slot IN $slots \
340- AND status IN ['pending', 'approved'] LIMIT 1",
341- )
342- .bind(("slots", records))
343- .await?
344- .check()?;
345- Ok(!result.take::<Vec<Appointment>>(0)?.is_empty())
346- }
347-
348 /// Request `slot`. Lands `pending`: publishing availability is not consent319 /// Request `slot`. Lands `pending`: publishing availability is not consent
349 /// to a specific person and topic.320 /// to a specific person and topic.
350 ///321 ///
351- /// Refused (409) when the slot's window has already opened, when it already322+ /// Refused (409) when the slot's window has already opened, when it is
352- /// carries a live booking, or when the requester is already committed323+ /// already taken, or when the requester is already committed elsewhere at
353- /// elsewhere at that time — all re-derived324+ /// that time. The slot is taken by [`cap::claim`] on the slot row — a
354- /// from a fresh read under [`APPOINTMENT_LOCK`], so two racing requests325+ /// conditional single-record write, so two racing requests cannot both find
355- /// cannot both find the slot free.326+ /// it free however many replicas they arrive at; the requester's own overlap
327+ /// is the lock's part.
356 pub async fn book(328 pub async fn book(
357 slot: &AppointmentSlotId,329 slot: &AppointmentSlotId,
358 requester: &UserId,330 requester: &UserId,
@@ -363,9 +335,6 @@ impl Appointment {
363 let slot_row = AppointmentSlot::read(slot, db)335 let slot_row = AppointmentSlot::read(slot, db)
364 .await?336 .await?
365 .ok_or(AppError::NotFound)?;337 .ok_or(AppError::NotFound)?;
366- if Self::has_live_booking(slot, db).await? {
367- return Err(AppError::Conflict("the slot is already booked"));
368- }
369 // A window that has opened is history, not a plan: `cancel` refuses to338 // A window that has opened is history, not a plan: `cancel` refuses to
370 // call off a meeting that started, so such a booking would be stuck339 // call off a meeting that started, so such a booking would be stuck
371 // forever. `list_upcoming` hides these slots, but a stale id still340 // forever. `list_upcoming` hides these slots, but a stale id still
@@ -390,6 +359,17 @@ impl Appointment {
390 "you already have an appointment at that time",359 "you already have an appointment at that time",
391 ));360 ));
392 }361 }
362+ // Last, so nothing above can refuse *after* the slot was taken. A slot
363+ // deleted since the read above is gone, not full — the claim's `WHERE`
364+ // finds no row either way, so the distinction is re-read rather than
365+ // guessed.
366+ let seat = slot.record();
367+ if !cap::claim(&seat, SLOT_OCCUPIED_FIELD, 1, db).await? {
368+ if AppointmentSlot::read(slot, db).await?.is_none() {
369+ return Err(AppError::NotFound);
370+ }
371+ return Err(AppError::Conflict("the slot is already booked"));
372+ }
393 let appointment = Appointment {373 let appointment = Appointment {
394 id: AppointmentId::generate(),374 id: AppointmentId::generate(),
395 slot: slot.clone(),375 slot: slot.clone(),
@@ -405,11 +385,21 @@ impl Appointment {
405 reject_reason: None,385 reject_reason: None,
406 created_at: Timestamp::now(),386 created_at: Timestamp::now(),
407 };387 };
408- let created: Option<Appointment> = db388+ let created: Result<Option<Appointment>, _> = db
409 .create(appointment.id.record())389 .create(appointment.id.record())
410 .content(appointment)390 .content(appointment)
411- .await?;391+ .await;
412- created.ok_or_else(|| AppError::Internal("failed to book the appointment".into()))392+ match created {
393+ Ok(Some(created)) => Ok(created),
394+ // The booking never landed, so the slot it took goes back.
395+ other => {
396+ cap::release(&seat, SLOT_OCCUPIED_FIELD, db).await?;
397+ Err(match other {
398+ Err(err) => err.into(),
399+ _ => AppError::Internal("failed to book the appointment".into()),
400+ })
401+ }
402+ }
413 }403 }
414 404
415 pub async fn read(id: &AppointmentId, db: &Database) -> Result<Option<Appointment>, AppError> {405 pub async fn read(id: &AppointmentId, db: &Database) -> Result<Option<Appointment>, AppError> {
@@ -509,14 +499,15 @@ impl Appointment {
509 Err(contended())499 Err(contended())
510 }500 }
511 501
512- /// Turn the request down. Frees the slot: occupancy counts live rows only.502+ /// Turn the request down. Frees the slot — the seat goes back with the
503+ /// status flip, in one transaction. No lock: this decides nothing about
504+ /// anyone's calendar, and the write is its own guard.
513 pub async fn reject(505 pub async fn reject(
514 id: &AppointmentId,506 id: &AppointmentId,
515 decided_by: &UserId,507 decided_by: &UserId,
516 reason: Option<AppointmentReason>,508 reason: Option<AppointmentReason>,
517 db: &Database,509 db: &Database,
518 ) -> Result<Appointment, AppError> {510 ) -> Result<Appointment, AppError> {
519- let _guard = APPOINTMENT_LOCK.lock().await;
520 for _ in 0..CAS_UPDATE_RETRIES {511 for _ in 0..CAS_UPDATE_RETRIES {
521 let expected = Self::read_pending(id, db).await?;512 let expected = Self::read_pending(id, db).await?;
522 let mut rejected = expected.clone();513 let mut rejected = expected.clone();
@@ -547,7 +538,6 @@ impl Appointment {
547 reason: Option<AppointmentReason>,538 reason: Option<AppointmentReason>,
548 db: &Database,539 db: &Database,
549 ) -> Result<Appointment, AppError> {540 ) -> Result<Appointment, AppError> {
550- let _guard = APPOINTMENT_LOCK.lock().await;
551 for _ in 0..CAS_UPDATE_RETRIES {541 for _ in 0..CAS_UPDATE_RETRIES {
552 let expected = Self::read(id, db).await?.ok_or(AppError::NotFound)?;542 let expected = Self::read(id, db).await?.ok_or(AppError::NotFound)?;
553 if !expected.status.is_live() {543 if !expected.status.is_live() {
@@ -595,7 +585,8 @@ impl Appointment {
595 }585 }
596 .into());586 .into());
597 }587 }
598- let _guard = APPOINTMENT_LOCK.lock().await;588+ // No lock: a proposal commits nobody's calendar (the booking goes back
589+ // to `pending`), and it neither takes nor frees the slot's seat.
599 for _ in 0..CAS_UPDATE_RETRIES {590 for _ in 0..CAS_UPDATE_RETRIES {
600 let expected = Self::read(id, db).await?.ok_or(AppError::NotFound)?;591 let expected = Self::read(id, db).await?.ok_or(AppError::NotFound)?;
601 if !expected.status.is_live() {592 if !expected.status.is_live() {
@@ -664,20 +655,34 @@ impl Appointment {
664 /// A store-level write conflict is reported the same way as a miss: it655 /// A store-level write conflict is reported the same way as a miss: it
665 /// means a concurrent write committed on this row, which is exactly the656 /// means a concurrent write committed on this row, which is exactly the
666 /// "reload and re-decide" case.657 /// "reload and re-decide" case.
658+ ///
659+ /// A transition out of a live status (reject, cancel) hands the slot's
660+ /// `occupied` seat back, in this same transaction — the counter is the
661+ /// authority on whether the slot is taken, so it must move if and only if
662+ /// the status did. The decrement is `WHERE`-gated on the CAS having written
663+ /// something, so a lost race frees nothing.
667 async fn save_if_unchanged(664 async fn save_if_unchanged(
668 self,665 self,
669 expected: &Appointment,666 expected: &Appointment,
670 db: &Database,667 db: &Database,
671 ) -> Result<Option<Appointment>, AppError> {668 ) -> Result<Option<Appointment>, AppError> {
669+ let frees_the_slot = expected.status.is_live() && !self.status.is_live();
672 let attempted = async {670 let attempted = async {
673 let mut result = db671 let mut result = db
674 .query(672 .query(
675- "UPDATE $id CONTENT $new \673+ "BEGIN TRANSACTION;
674+ LET $done = (UPDATE $id CONTENT $new \
676 WHERE status = $status \675 WHERE status = $status \
677 AND proposed_starts_at = $proposed_starts_at \676 AND proposed_starts_at = $proposed_starts_at \
678 AND proposed_ends_at = $proposed_ends_at \677 AND proposed_ends_at = $proposed_ends_at \
679- AND decided_by = $decided_by",678+ AND decided_by = $decided_by);
679+ UPDATE $slot SET occupied = math::max([(occupied ?? 0) - 1, 0])
680+ WHERE $frees AND array::len($done) > 0;
681+ RETURN $done;
682+ COMMIT TRANSACTION;",
680 )683 )
684+ .bind(("slot", expected.slot.record()))
685+ .bind(("frees", frees_the_slot))
681 .bind(("id", expected.id.record()))686 .bind(("id", expected.id.record()))
682 .bind(("status", expected.status))687 .bind(("status", expected.status))
683 .bind(("proposed_starts_at", expected.proposed_starts_at))688 .bind(("proposed_starts_at", expected.proposed_starts_at))
@@ -686,7 +691,8 @@ impl Appointment {
686 .bind(("new", self))691 .bind(("new", self))
687 .await?692 .await?
688 .check()?;693 .check()?;
689- result.take::<Vec<Appointment>>(0)694+ // BEGIN, the LET, and the counter write take a slot each.
695+ result.take::<Vec<Appointment>>(3)
690 }696 }
691 .await;697 .await;
692 match attempted {698 match attempted {
@@ -940,7 +946,115 @@ mod tests {
940 assert_eq!(saved.get_proposed_starts_at(), Some(proposed_starts_at));946 assert_eq!(saved.get_proposed_starts_at(), Some(proposed_starts_at));
941 }947 }
942 948
943- /// Occupancy is derived, so a rejected booking must hand the slot back.949+ /// What the slot row itself says about being taken — the authority every
950+ /// gate now reads, in any replica.
951+ async fn occupied(slot: &AppointmentSlotId, db: &Database) -> i64 {
952+ let mut result = db
953+ .query("SELECT VALUE (occupied ?? 0) FROM $slot")
954+ .bind(("slot", slot.record()))
955+ .await
956+ .unwrap()
957+ .check()
958+ .unwrap();
959+ result.take::<Vec<i64>>(0).unwrap()[0]
960+ }
961+
962+ /// The double-book race, as the *other replica* runs it: `APPOINTMENT_LOCK`
963+ /// is process-local, so a second process's booking arrives at the database
964+ /// with nothing between it and the slot but the claim's own `WHERE`. Driven
965+ /// through [`cap::claim`] directly rather than through a `join!`, since the
966+ /// in-memory engine can drop one of two concurrent writes to a record and
967+ /// still answer `Ok` — this asks the primitive the exact question the race
968+ /// asks it.
969+ ///
970+ /// Deleting the `WHERE (occupied ?? 0) < $cap` from `cap::claim` makes the
971+ /// second claim succeed and this fail (mutation-proved).
972+ #[tokio::test]
973+ async fn a_second_replica_cannot_claim_a_booked_slot() {
974+ let db = crate::database::init_mem().await.unwrap();
975+ let teacher = UserId::from_key("t1");
976+ let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db)
977+ .await
978+ .unwrap();
979+ assert_eq!(occupied(slot.get_id(), &db).await, 0);
980+
981+ Appointment::book(
982+ slot.get_id(),
983+ &UserId::from_key("s1"),
984+ AppointmentReason::try_new("görüşme").unwrap(),
985+ &db,
986+ )
987+ .await
988+ .unwrap();
989+ assert_eq!(occupied(slot.get_id(), &db).await, 1);
990+
991+ assert!(
992+ !cap::claim(&slot.get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db)
993+ .await
994+ .unwrap(),
995+ "the slot's seat must already be taken"
996+ );
997+ // And the racer's refusal left the stored state alone: one booking, one
998+ // seat — not two of either.
999+ assert_eq!(occupied(slot.get_id(), &db).await, 1);
1000+ assert_eq!(
1001+ Appointment::list_for_slot(slot.get_id(), &db)
1002+ .await
1003+ .unwrap()
1004+ .len(),
1005+ 1
1006+ );
1007+ }
1008+
1009+ /// Cancelling gives the seat back in the same transaction as the status
1010+ /// flip — the counter is the only thing that says a slot is free, so a
1011+ /// cancel that moved one without the other would strand the slot forever.
1012+ #[tokio::test]
1013+ async fn cancelling_hands_the_seat_back_with_the_status() {
1014+ let db = crate::database::init_mem().await.unwrap();
1015+ let teacher = UserId::from_key("t1");
1016+ let student = UserId::from_key("s1");
1017+ let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db)
1018+ .await
1019+ .unwrap();
1020+ let booking = Appointment::book(
1021+ slot.get_id(),
1022+ &student,
1023+ AppointmentReason::try_new("görüşme").unwrap(),
1024+ &db,
1025+ )
1026+ .await
1027+ .unwrap();
1028+ Appointment::approve(booking.get_id(), &teacher, &db)
1029+ .await
1030+ .unwrap();
1031+ assert_eq!(occupied(slot.get_id(), &db).await, 1, "approval holds it");
1032+
1033+ Appointment::cancel(booking.get_id(), &student, None, &db)
1034+ .await
1035+ .unwrap();
1036+ assert_eq!(occupied(slot.get_id(), &db).await, 0);
1037+ // Cancelling twice is refused, so the seat cannot go back twice either.
1038+ assert!(
1039+ Appointment::cancel(booking.get_id(), &student, None, &db)
1040+ .await
1041+ .is_err()
1042+ );
1043+ assert_eq!(occupied(slot.get_id(), &db).await, 0);
1044+ assert!(
1045+ Appointment::book(
1046+ slot.get_id(),
1047+ &UserId::from_key("s2"),
1048+ AppointmentReason::try_new("görüşme").unwrap(),
1049+ &db
1050+ )
1051+ .await
1052+ .is_ok()
1053+ );
1054+ assert_eq!(occupied(slot.get_id(), &db).await, 1);
1055+ }
1056+
1057+ /// Occupancy frees on reject, so the slot can be re-booked.
944 #[tokio::test]1058 #[tokio::test]
945 async fn rejecting_frees_the_slot_for_re_booking() {1059 async fn rejecting_frees_the_slot_for_re_booking() {
946 let db = crate::database::init_mem().await.unwrap();1060 let db = crate::database::init_mem().await.unwrap();
@@ -966,9 +1080,11 @@ mod tests {
966 Appointment::reject(first.get_id(), &teacher, None, &db)1080 Appointment::reject(first.get_id(), &teacher, None, &db)
967 .await1081 .await
968 .unwrap();1082 .unwrap();
1083+ assert_eq!(occupied(slot.get_id(), &db).await, 0);
969 let second = Appointment::book(slot.get_id(), &UserId::from_key("s2"), reason(), &db)1084 let second = Appointment::book(slot.get_id(), &UserId::from_key("s2"), reason(), &db)
970 .await1085 .await
971 .unwrap();1086 .unwrap();
972 assert_eq!(second.get_status(), AppointmentStatus::Pending);1087 assert_eq!(second.get_status(), AppointmentStatus::Pending);
1088+ assert_eq!(occupied(slot.get_id(), &db).await, 1);
973 }1089 }
974 }1090 }
src/domain/appointment_slot.rsmodified+112 -23
@@ -1,8 +1,11 @@
1 //! A teacher's published availability: "I am free here, book me". A slot is1 //! A teacher's published availability: "I am free here, book me". A slot is
2-//! pure calendar — it carries no booking state at all. Whether it is taken is2+//! nearly pure calendar: the one piece of booking state it carries is the
3-//! *derived* from its [`Appointment`] rows under [`APPOINTMENT_LOCK`], so a3+//! `occupied` counter (a [`cap`](crate::domain::cap) of one), taken when a
4-//! rejected or cancelled booking frees the slot again without any flag to4+//! booking is made and given back in the same transaction as the reject or
5-//! reset (and without a UNIQUE index, which would keep a dead booking's seat).5+//! cancel that settles it — so the slot frees itself again, and unlike a UNIQUE
6+//! index it does not keep a dead booking's seat. Stored rather than counted
7+//! from the [`Appointment`] rows because a conditional write on one row is the
8+//! only guard that survives a second replica.
6 //!9 //!
7 //! A recurring publish is expanded into concrete rows here, at write time,10 //! A recurring publish is expanded into concrete rows here, at write time,
8 //! sharing one `series` id — no recurrence rule is ever evaluated at read11 //! sharing one `series` id — no recurrence rule is ever evaluated at read
@@ -430,11 +433,10 @@ impl AppointmentSlot {
430 /// Settled bookings (rejected/cancelled) are history of a slot that is433 /// Settled bookings (rejected/cancelled) are history of a slot that is
431 /// going away, so they cascade out with it, like [`Event::delete`]'s rows.434 /// going away, so they cascade out with it, like [`Event::delete`]'s rows.
432 ///435 ///
433- /// The occupancy read and the delete run under [`APPOINTMENT_LOCK`], so a436+ /// The guard is the delete's own `WHERE`, so no booking can land between a
434- /// booking cannot land between them and outlive its slot.437+ /// check and the row going away — in this replica or another.
435 pub async fn delete(self, db: &Database) -> Result<AppointmentSlot, AppError> {438 pub async fn delete(self, db: &Database) -> Result<AppointmentSlot, AppError> {
436- let _guard = APPOINTMENT_LOCK.lock().await;439+ Self::delete_free(std::slice::from_ref(&self.id), db).await?;
437- Self::delete_locked(std::slice::from_ref(&self.id), db).await?;
438 Ok(self)440 Ok(self)
439 }441 }
440 442
@@ -445,34 +447,61 @@ impl AppointmentSlot {
445 series: &SlotSeries,447 series: &SlotSeries,
446 db: &Database,448 db: &Database,
447 ) -> Result<Vec<AppointmentSlot>, AppError> {449 ) -> Result<Vec<AppointmentSlot>, AppError> {
448- let _guard = APPOINTMENT_LOCK.lock().await;
449 let slots = Self::list_for_series(series, db).await?;450 let slots = Self::list_for_series(series, db).await?;
450 if slots.is_empty() {451 if slots.is_empty() {
451 return Err(AppError::NotFound);452 return Err(AppError::NotFound);
452 }453 }
453 let ids: Vec<AppointmentSlotId> = slots.iter().map(|slot| slot.id.clone()).collect();454 let ids: Vec<AppointmentSlotId> = slots.iter().map(|slot| slot.id.clone()).collect();
454- Self::delete_locked(&ids, db).await?;455+ Self::delete_free(&ids, db).await?;
455 Ok(slots)456 Ok(slots)
456 }457 }
457 458
458- /// Shared body of both deletes. Caller must already hold459+ /// Shared body of both deletes: drop every named slot, but only while its
459- /// [`APPOINTMENT_LOCK`]: the live-booking check is only meaningful while460+ /// `occupied` counter says nobody is waiting on it — the delete's own
460- /// no booking can be written.461+ /// `WHERE` is the guard, which is what makes it hold against a booking
461- async fn delete_locked(ids: &[AppointmentSlotId], db: &Database) -> Result<(), AppError> {462+ /// landing in another replica (a separate read-then-delete could not).
462- if Appointment::any_live_booking(ids, db).await? {463+ ///
464+ /// All-or-nothing across the whole list: if fewer rows go than were named,
465+ /// the transaction is thrown away, so a series never loses its free weeks
466+ /// and keeps the booked one. Whether that shortfall was a live booking or a
467+ /// slot that no longer exists is read off what survived — the occupied rows
468+ /// are still there, a vanished one is not — which is the 409/404 the caller
469+ /// used to get from a separate check.
470+ async fn delete_free(ids: &[AppointmentSlotId], db: &Database) -> Result<(), AppError> {
471+ let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect();
472+ let mut result = db
473+ .query(
474+ "BEGIN TRANSACTION;
475+ LET $gone = (DELETE $slots WHERE (occupied ?? 0) = 0 RETURN BEFORE);
476+ IF array::len($gone) != array::len($slots) {
477+ THROW IF array::len((SELECT VALUE id FROM appointment_slot
478+ WHERE id IN $slots)) > 0 { 'slot_occupied' } ELSE { 'slot_missing' }
479+ };
480+ DELETE appointment WHERE slot IN $slots;
481+ RETURN $gone;
482+ COMMIT TRANSACTION;",
483+ )
484+ .bind(("slots", records))
485+ .await?;
486+ // An aborted transaction errors every slot; only the THROW's own slot
487+ // names the marker (the `Exam::update` treatment).
488+ let mut errors = result.take_errors();
489+ let thrown = |marker: &str| {
490+ errors
491+ .values()
492+ .any(|error| error.to_string().contains(marker))
493+ };
494+ if thrown("slot_occupied") {
463 return Err(AppError::Conflict(495 return Err(AppError::Conflict(
464 "the slot has a pending or approved booking",496 "the slot has a pending or approved booking",
465 ));497 ));
466 }498 }
467- let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect();499+ if thrown("slot_missing") {
468- let mut result = db
469- .query("DELETE appointment WHERE slot IN $slots; DELETE $slots RETURN BEFORE;")
470- .bind(("slots", records))
471- .await?
472- .check()?;
473- if result.take::<Vec<AppointmentSlot>>(1)?.is_empty() {
474 return Err(AppError::NotFound);500 return Err(AppError::NotFound);
475 }501 }
502+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
503+ return Err(error.into());
504+ }
476 Ok(())505 Ok(())
477 }506 }
478 }507 }
@@ -480,7 +509,8 @@ impl AppointmentSlot {
480 #[cfg(test)]509 #[cfg(test)]
481 mod tests {510 mod tests {
482 use super::*;511 use super::*;
483- use crate::constant::MILLIS_PER_DAY;512+ use crate::constant::{MILLIS_PER_DAY, SLOT_OCCUPIED_FIELD};
513+ use crate::domain::cap;
484 514
485 fn at(millis: i64) -> Timestamp {515 fn at(millis: i64) -> Timestamp {
486 Timestamp::from_millis(millis)516 Timestamp::from_millis(millis)
@@ -723,6 +753,65 @@ mod tests {
723 );753 );
724 }754 }
725 755
756+ /// The delete-vs-book race: a booking that lands in another replica between
757+ /// this delete's read and its write must still keep the slot alive, so the
758+ /// guard has to be the delete's own `WHERE` — here driven by taking the seat
759+ /// the way that replica would, with no booking row to read.
760+ ///
761+ /// A series is all-or-nothing: one taken week refuses the whole publish,
762+ /// and the free weeks must survive the refusal.
763+ #[tokio::test]
764+ async fn a_taken_slot_is_never_deleted_and_takes_its_series_with_it() {
765+ let db = crate::database::init_mem().await.unwrap();
766+ let teacher = UserId::from_key("t1");
767+ let slots = AppointmentSlot::publish_weekly(
768+ &teacher,
769+ at(1_000),
770+ at(2_000),
771+ None,
772+ at(1_000 + 2 * MILLIS_PER_WEEK),
773+ &db,
774+ )
775+ .await
776+ .unwrap();
777+ let series = slots[0].get_series().cloned().unwrap();
778+
779+ // A free slot goes, and its series is deletable while every week is free.
780+ assert!(slots[0].clone().delete(&db).await.is_ok());
781+ // The seat on the middle week is taken — no booking row, exactly as a
782+ // racing replica would leave it mid-flight.
783+ assert!(
784+ cap::claim(&slots[1].get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db)
785+ .await
786+ .unwrap()
787+ );
788+ assert!(matches!(
789+ slots[1].clone().delete(&db).await,
790+ Err(AppError::Conflict(
791+ "the slot has a pending or approved booking"
792+ ))
793+ ));
794+ assert!(matches!(
795+ AppointmentSlot::delete_series(&series, &db).await,
796+ Err(AppError::Conflict(_))
797+ ));
798+ // Refused, not half-applied: the free third week is still published.
799+ assert_eq!(
800+ AppointmentSlot::list_for_series(&series, &db)
801+ .await
802+ .unwrap()
803+ .len(),
804+ 2
805+ );
806+
807+ // A slot that is simply gone is a 404, not a 409 — the delete tells the
808+ // two shortfalls apart by what survived it.
809+ assert!(matches!(
810+ slots[0].clone().delete(&db).await,
811+ Err(AppError::NotFound)
812+ ));
813+ }
814+
726 #[tokio::test]815 #[tokio::test]
727 async fn weekly_publish_that_self_overlaps_is_refused() {816 async fn weekly_publish_that_self_overlaps_is_refused() {
728 let db = crate::database::init_mem().await.unwrap();817 let db = crate::database::init_mem().await.unwrap();
src/domain/bank_question.rsmodified+21 -6
@@ -771,10 +771,25 @@ mod tests {
771 771
772 let exam = ExamId::generate();772 let exam = ExamId::generate();
773 let other_exam = ExamId::generate();773 let other_exam = ExamId::generate();
774- async fn instantiate(exam: &ExamId, source: &BankQuestion, db: &Database) {774+ // A real subject row: an exam question claims a reference on its
775+ // subject, so a minted id it never wrote would be refused.
776+ let subject = crate::domain::subject::Subject::create(
777+ &crate::domain::course::CourseId::generate(),
778+ crate::domain::subject::SubjectName::try_new("topic").unwrap(),
779+ crate::domain::subject::SubjectDescription::try_new("").unwrap(),
780+ &db,
781+ )
782+ .await
783+ .unwrap();
784+ async fn instantiate(
785+ exam: &ExamId,
786+ subject: &SubjectId,
787+ source: &BankQuestion,
788+ db: &Database,
789+ ) {
775 ExamQuestion::create_from_bank(790 ExamQuestion::create_from_bank(
776 exam,791 exam,
777- SubjectId::generate(),792+ subject.clone(),
778 source.get_text().clone(),793 source.get_text().clone(),
779 source.get_points(),794 source.get_points(),
780 source.spec(),795 source.spec(),
@@ -785,13 +800,13 @@ mod tests {
785 .unwrap();800 .unwrap();
786 }801 }
787 // Two copies of the same template, in two different exams.802 // Two copies of the same template, in two different exams.
788- instantiate(&exam, &used_twice, &db).await;803+ instantiate(&exam, subject.get_id(), &used_twice, &db).await;
789- instantiate(&other_exam, &used_twice, &db).await;804+ instantiate(&other_exam, subject.get_id(), &used_twice, &db).await;
790- instantiate(&exam, &used_once, &db).await;805+ instantiate(&exam, subject.get_id(), &used_once, &db).await;
791 // A hand-authored question has no `from_bank` and must not be tallied.806 // A hand-authored question has no `from_bank` and must not be tallied.
792 ExamQuestion::create(807 ExamQuestion::create(
793 &exam,808 &exam,
794- SubjectId::generate(),809+ subject.get_id().clone(),
795 QuestionText::try_new("mine").unwrap(),810 QuestionText::try_new("mine").unwrap(),
796 QuestionPoints::try_new(1).unwrap(),811 QuestionPoints::try_new(1).unwrap(),
797 spec(),812 spec(),
src/domain/cap.rsmodified+228 -10
@@ -26,10 +26,10 @@
26 // drift is ever observed, the repair is the same GROUP BY count the backfill26 // drift is ever observed, the repair is the same GROUP BY count the backfill
27 // runs, issued by hand with the field's `= NONE` guard dropped.27 // runs, issued by hand with the field's `= NONE` guard dropped.
28 28
29-use surrealdb::types::RecordId;29+use surrealdb::types::{RecordId, SurrealValue};
30 use tokio::sync::Mutex;30 use tokio::sync::Mutex;
31 31
32-use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES};32+use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, REF_COUNT_FIELD, REF_RETIRED_FIELD};
33 use crate::database::{Database, lost_the_race};33 use crate::database::{Database, lost_the_race};
34 use crate::domain::timestamp::Timestamp;34 use crate::domain::timestamp::Timestamp;
35 use crate::error::AppError;35 use crate::error::AppError;
@@ -69,13 +69,176 @@ pub(crate) async fn claim(
69 cap: i64,69 cap: i64,
70 db: &Database,70 db: &Database,
71 ) -> Result<bool, AppError> {71 ) -> Result<bool, AppError> {
72+ claim_at(parent, field, cap, "", db).await
73+}
74+
75+/// [`claim`], but only while `guard` — an extra predicate on that same parent
76+/// row — also holds. A caller whose insert has a second precondition (a homework
77+/// submission's file add is refused once the work is graded) gets both decided
78+/// by the one conditional write, instead of by a read a peer replica can outrun.
79+/// A miss is either "full" *or* "the guard failed"; the caller re-reads to tell
80+/// them apart, and only to pick the message. `guard` is always an in-crate SQL
81+/// literal, never user input.
82+pub(crate) async fn claim_when(
83+ parent: &RecordId,
84+ field: &str,
85+ cap: i64,
86+ guard: &str,
87+ db: &Database,
88+) -> Result<bool, AppError> {
89+ claim_at(parent, field, cap, guard, db).await
90+}
91+
92+async fn claim_at(
93+ parent: &RecordId,
94+ field: &str,
95+ cap: i64,
96+ extra: &str,
97+ db: &Database,
98+) -> Result<bool, AppError> {
99+ let extra = if extra.is_empty() {
100+ String::new()
101+ } else {
102+ format!(" AND ({extra})")
103+ };
72 let sql = format!(104 let sql = format!(
73 "UPDATE $parent SET {field} = ({field} ?? 0) + 1 \105 "UPDATE $parent SET {field} = ({field} ?? 0) + 1 \
74- WHERE ({field} ?? 0) < $cap RETURN VALUE id"106+ WHERE ({field} ?? 0) < $num{extra} RETURN VALUE id"
75 );107 );
76 Ok(!write(&sql, parent, cap, db).await?.is_empty())108 Ok(!write(&sql, parent, cap, db).await?.is_empty())
77 }109 }
78 110
111+/// The `THROW` markers the in-transaction gates below abort with: no room, and
112+/// this pair already holds its row.
113+const FULL_MARK: &str = "cap_full";
114+const HELD_MARK: &str = "cap_held";
115+
116+/// What [`claim_and_create`] settled.
117+pub(crate) enum Claimed<T> {
118+ /// The seat and the row committed together.
119+ Made(T),
120+ /// The cap is full or the parent row is gone — nothing was written.
121+ Full,
122+ /// Another writer placed this very row first, so this caller never owed a
123+ /// seat: nothing was written, and the winner's row is the answer.
124+ Duplicate,
125+}
126+
127+/// Take a slot on `parent`'s `field` counter *and* write the child that fills
128+/// it, in one transaction.
129+///
130+/// [`claim`] followed by a separate insert cannot promise this. Where the child
131+/// carries a deterministic id (one row per pair), two writers placing the *same*
132+/// pair both pass the claim — neither row exists yet — so on a tight cap the
133+/// second is told "full" for a seat it was never going to need, and a release
134+/// afterwards is too late to unsay it. A process-wide mutex hid that inside one
135+/// process and hid nothing between two. Here the duplicate `CREATE` aborts the
136+/// transaction, which takes its own increment with it, and the caller reads the
137+/// winner's row back — so the counter never counts a row that does not exist,
138+/// in any replica.
139+///
140+/// The row is looked for *before* the seat is claimed, in that same
141+/// transaction, because on a tight cap the claim is the first thing to fail: a
142+/// member whose row a rival placed a moment ago would be told "full" about a
143+/// seat they already hold. The order makes "you are already in" outrank "there
144+/// is no room", which is what every caller's early return promises anyway.
145+pub(crate) async fn claim_and_create<T: SurrealValue + Clone>(
146+ parent: &RecordId,
147+ field: &str,
148+ cap: i64,
149+ id: &RecordId,
150+ content: &T,
151+ db: &Database,
152+) -> Result<Claimed<T>, AppError> {
153+ let sql = format!(
154+ "BEGIN TRANSACTION;
155+ LET $held = (SELECT VALUE id FROM $id);
156+ IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }};
157+ LET $seat = (UPDATE $parent SET {field} = ({field} ?? 0) + 1 \
158+ WHERE ({field} ?? 0) < $num RETURN VALUE id);
159+ IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }};
160+ CREATE $id CONTENT $row;
161+ COMMIT TRANSACTION;"
162+ );
163+ let _guard = CLAIM_LOCK.lock().await;
164+ let mut last = None;
165+ for attempt in 0..CAP_WRITE_TRIES {
166+ backoff(attempt).await;
167+ let attempted = db
168+ .query(sql.as_str())
169+ .bind(("parent", parent.clone()))
170+ .bind(("num", cap))
171+ .bind(("id", id.clone()))
172+ .bind(("row", content.clone()))
173+ .await;
174+ let mut result = match attempted {
175+ Ok(result) => result,
176+ Err(err) if lost_the_race(&err) => {
177+ last = Some(err);
178+ continue;
179+ }
180+ Err(err) => return Err(err.into()),
181+ };
182+ // An aborted transaction errors *every* slot, most with a generic "not
183+ // executed" — only the failing slot says why.
184+ let mut errors = result.take_errors();
185+ // "Already a member" is read first: it outranks a full cap, and the two
186+ // never both fire (the gate aborts before the seat is touched).
187+ if errors
188+ .values()
189+ .any(|error| error.to_string().contains(HELD_MARK) || error.is_already_exists())
190+ {
191+ return Ok(Claimed::Duplicate);
192+ }
193+ if errors
194+ .values()
195+ .any(|error| error.to_string().contains(FULL_MARK))
196+ {
197+ return Ok(Claimed::Full);
198+ }
199+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
200+ if !lost_the_race(&error) {
201+ return Err(error.into());
202+ }
203+ last = Some(error);
204+ continue;
205+ }
206+ // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5.
207+ return result
208+ .take::<Vec<T>>(5)?
209+ .into_iter()
210+ .next()
211+ .map(Claimed::Made)
212+ .ok_or_else(|| AppError::Internal("cap claim wrote no row".into()));
213+ }
214+ Err(last
215+ .map(AppError::from)
216+ .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into())))
217+}
218+
219+/// Wait out one lost round. Exponential with jitter, because racers arrive in
220+/// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them.
221+/// Attempt zero waits not at all.
222+async fn backoff(attempt: usize) {
223+ if attempt == 0 {
224+ return;
225+ }
226+ let step = CAP_WRITE_BACKOFF_MS << (attempt - 1);
227+ let jitter = Timestamp::now().as_millis().unsigned_abs() % step.max(1);
228+ tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await;
229+}
230+
231+/// Move `parent` to its next revision. A revision column is not a cap: it is
232+/// what a reader pins a value it took off the parent to, so that a write which
233+/// invalidates that value (a menu's price) can refuse the claim carrying the old
234+/// one. Every such mutation bumps *before* it writes, so a stale claim is
235+/// refused whether or not the mutation itself then lands.
236+pub(crate) async fn bump(parent: &RecordId, field: &str, db: &Database) -> Result<(), AppError> {
237+ let sql = format!("UPDATE $parent SET {field} = ({field} ?? 0) + 1 RETURN VALUE id");
238+ write(&sql, parent, UNLIMITED, db).await?;
239+ Ok(())
240+}
241+
79 /// Give a claimed slot back, for the insert that never landed. Clamped at zero242 /// Give a claimed slot back, for the insert that never landed. Clamped at zero
80 /// so a double release can never push a counter negative and open the cap.243 /// so a double release can never push a counter negative and open the cap.
81 pub(crate) async fn release(parent: &RecordId, field: &str, db: &Database) -> Result<(), AppError> {244 pub(crate) async fn release(parent: &RecordId, field: &str, db: &Database) -> Result<(), AppError> {
@@ -85,6 +248,63 @@ pub(crate) async fn release(parent: &RecordId, field: &str, db: &Database) -> Re
85 Ok(())248 Ok(())
86 }249 }
87 250
251+// --- reference counters --------------------------------------------------
252+//
253+// The same single-record guard, pointed the other way. A cap asks "is there
254+// room for one more child?"; a reference counter asks "may this *name* still be
255+// used, and does anything still use it?" — the shape behind "an exam kind
256+// nothing is graded under may leave the school's settings". Both questions are
257+// answered by one row per name (`kind_ref:<name>`, `slot_ref:<name>`), created
258+// on first use, so the removal and the last claim contend on a record rather
259+// than on a cross-table count no transaction serializes.
260+//
261+// The two writes are exact mirrors: a claim lands only while the name is not
262+// retired, a retirement lands only while the count is zero. Whichever reaches
263+// the record first, the other is refused — in any process.
264+
265+/// Take `n` references on `id`. `false` = the name is retired and the caller
266+/// must refuse; nothing was written.
267+pub(crate) async fn claim_ref(id: &RecordId, n: i64, db: &Database) -> Result<bool, AppError> {
268+ let sql = format!(
269+ "UPSERT $parent SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + $num \
270+ WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id"
271+ );
272+ Ok(!write(&sql, id, n, db).await?.is_empty())
273+}
274+
275+/// Give `n` references back — the referencing rows are gone (or never landed).
276+/// Clamped at zero like [`release`], so a double release cannot push a counter
277+/// below the rows it counts and let a used name be retired.
278+pub(crate) async fn release_ref(id: &RecordId, n: i64, db: &Database) -> Result<(), AppError> {
279+ let sql = format!(
280+ "UPSERT $parent SET {REF_COUNT_FIELD} = \
281+ math::max([({REF_COUNT_FIELD} ?? 0) - $num, 0]) RETURN VALUE id"
282+ );
283+ write(&sql, id, n, db).await?;
284+ Ok(())
285+}
286+
287+/// Retire the name behind `id`: no further claim succeeds. `false` = something
288+/// still references it and the caller must refuse; nothing was written.
289+/// Idempotent — retiring an already-retired unused name lands again.
290+pub(crate) async fn retire(id: &RecordId, db: &Database) -> Result<bool, AppError> {
291+ // Parenthesized `??`: `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which
292+ // is truthy for *every* row and would retire a name still in use.
293+ let sql = format!(
294+ "UPSERT $parent SET {REF_RETIRED_FIELD} = true \
295+ WHERE ({REF_COUNT_FIELD} ?? 0) = 0 RETURN VALUE id"
296+ );
297+ Ok(!write(&sql, id, UNLIMITED, db).await?.is_empty())
298+}
299+
300+/// Put a name back in service — it re-entered the list it was retired from, or
301+/// the edit that retired it never landed.
302+pub(crate) async fn unretire(id: &RecordId, db: &Database) -> Result<(), AppError> {
303+ let sql = format!("UPSERT $parent SET {REF_RETIRED_FIELD} = false RETURN VALUE id");
304+ write(&sql, id, UNLIMITED, db).await?;
305+ Ok(())
306+}
307+
88 /// Run one conditional counter write, retrying while the store reports a write308 /// Run one conditional counter write, retrying while the store reports a write
89 /// conflict.309 /// conflict.
90 ///310 ///
@@ -94,25 +314,23 @@ pub(crate) async fn release(parent: &RecordId, field: &str, db: &Database) -> Re
94 /// never letting two writers reach the database at once. So the queueing has to314 /// never letting two writers reach the database at once. So the queueing has to
95 /// happen here. Backoff is exponential with jitter, because racers arrive in315 /// happen here. Backoff is exponential with jitter, because racers arrive in
96 /// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them.316 /// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them.
317+/// `num` is the statement's one number, bound as `$num`: a cap for the claims,
318+/// a step for the reference counters below.
97 async fn write(319 async fn write(
98 sql: &str,320 sql: &str,
99 parent: &RecordId,321 parent: &RecordId,
100- cap: i64,322+ num: i64,
101 db: &Database,323 db: &Database,
102 ) -> Result<Vec<RecordId>, AppError> {324 ) -> Result<Vec<RecordId>, AppError> {
103 let _guard = CLAIM_LOCK.lock().await;325 let _guard = CLAIM_LOCK.lock().await;
104 let mut last = None;326 let mut last = None;
105 for attempt in 0..CAP_WRITE_TRIES {327 for attempt in 0..CAP_WRITE_TRIES {
106- if attempt > 0 {328+ backoff(attempt).await;
107- let step = CAP_WRITE_BACKOFF_MS << (attempt - 1);
108- let jitter = Timestamp::now().as_millis().unsigned_abs() % step.max(1);
109- tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await;
110- }
111 let attempted = async {329 let attempted = async {
112 let mut result = db330 let mut result = db
113 .query(sql)331 .query(sql)
114 .bind(("parent", parent.clone()))332 .bind(("parent", parent.clone()))
115- .bind(("cap", cap))333+ .bind(("num", num))
116 .await?334 .await?
117 .check()?;335 .check()?;
118 result.take::<Vec<RecordId>>(0)336 result.take::<Vec<RecordId>>(0)
src/domain/course.rsmodified+254 -16
@@ -1,8 +1,12 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 use ulid::Ulid;2 use ulid::Ulid;
3 3
4-use crate::constant::{COURSE_TABLE, MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN};4+use crate::constant::{
5+ COURSE_COUNT_FIELD, COURSE_TABLE, ENROLLMENT_COUNT_FIELD, MAX_COURSE_DESCRIPTION_LEN,
6+ MAX_COURSE_TITLE_LEN, REF_COUNT_FIELD,
7+};
5 use crate::database::Database;8 use crate::database::Database;
9+use crate::domain::cap;
6 use crate::domain::field_update::FieldUpdate;10 use crate::domain::field_update::FieldUpdate;
7 use crate::domain::page::PagedList;11 use crate::domain::page::PagedList;
8 use crate::domain::term::TermId;12 use crate::domain::term::TermId;
@@ -10,6 +14,10 @@ use crate::domain::user::UserId;
10 use crate::error::{AppError, ValidationError};14 use crate::error::{AppError, ValidationError};
11 use crate::validate::{validate_course_kind, validate_optional, validate_required};15 use crate::validate::{validate_course_kind, validate_optional, validate_required};
12 16
17+/// The `THROW` marker the delete guard aborts with — a roster that is not
18+/// empty, or a course row that is no longer there.
19+const ROSTER_MARK: &str = "course_roster";
20+
13 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]21 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
14 pub struct CourseId(RecordId);22 pub struct CourseId(RecordId);
15 23
@@ -153,6 +161,11 @@ impl Course {
153 self.teachers.contains(user)161 self.teachers.contains(user)
154 }162 }
155 163
164+ /// Create the course, claiming a reference on the term it links (if any)
165+ /// *before* the row is written: the claim is a conditional write on the
166+ /// term row, so it fails when the term is already gone and it makes the
167+ /// term undeletable the instant this link exists — across replicas, which
168+ /// the mutex it replaced could not do inside one process.
156 pub async fn create(169 pub async fn create(
157 creator: &UserId,170 creator: &UserId,
158 title: CourseTitle,171 title: CourseTitle,
@@ -162,18 +175,35 @@ impl Course {
162 capacity: Option<i64>,175 capacity: Option<i64>,
163 db: &Database,176 db: &Database,
164 ) -> Result<Course, AppError> {177 ) -> Result<Course, AppError> {
178+ if let Some(term) = &term {
179+ claim_term(term, db).await?;
180+ }
181+ let claimed = term.clone();
165 let course = Course {182 let course = Course {
166 id: CourseId::generate(),183 id: CourseId::generate(),
167 creator: creator.clone(),184 creator: creator.clone(),
168 teachers: Vec::new(),185 teachers: Vec::new(),
186+ term,
187+ capacity,
169 title,188 title,
170 description,189 description,
171 kind,190 kind,
172- term,
173- capacity,
174 };191 };
175- let created: Option<Course> = db.create(course.id.record()).content(course).await?;192+ let created: Result<Option<Course>, _> =
176- created.ok_or_else(|| AppError::Internal("failed to create course".into()))193+ db.create(course.id.record()).content(course).await;
194+ match created {
195+ Ok(Some(created)) => Ok(created),
196+ other => {
197+ // The link never landed, so the reference has to go back.
198+ if let Some(term) = &claimed {
199+ cap::release(&term.record(), COURSE_COUNT_FIELD, db).await?;
200+ }
201+ match other {
202+ Err(err) => Err(err.into()),
203+ _ => Err(AppError::Internal("failed to create course".into())),
204+ }
205+ }
206+ }
177 }207 }
178 208
179 pub async fn read(id: &CourseId, db: &Database) -> Result<Option<Course>, AppError> {209 pub async fn read(id: &CourseId, db: &Database) -> Result<Option<Course>, AppError> {
@@ -250,14 +280,43 @@ impl Course {
250 capacity: Option<Option<i64>>,280 capacity: Option<Option<i64>>,
251 db: &Database,281 db: &Database,
252 ) -> Result<Course, AppError> {282 ) -> Result<Course, AppError> {
253- FieldUpdate::new(self.id.record())283+ // A term move is claim-then-write-then-release, in that order: the new
284+ // term is made undeletable before the link points at it, and the old
285+ // one is only let go once the link has actually moved off it. Doing it
286+ // the other way round would open exactly the window this replaced.
287+ let claimed = match &term {
288+ Some(Some(new)) if Some(new) != self.term.as_ref() => {
289+ claim_term(new, db).await?;
290+ Some(new.clone())
291+ }
292+ _ => None,
293+ };
294+ let updated = FieldUpdate::new(self.id.record())
254 .set("title", title)295 .set("title", title)
255 .set("description", description)296 .set("description", description)
256 .set("kind", kind)297 .set("kind", kind)
257 .set("term", term.map(|term| term.map(|term| term.record())))298 .set("term", term.map(|term| term.map(|term| term.record())))
258 .set("capacity", capacity)299 .set("capacity", capacity)
259 .run::<Course>(db)300 .run::<Course>(db)
260- .await301+ .await;
302+ match updated {
303+ Ok(updated) => {
304+ // The stored row is the authority on where the link ended up —
305+ // a PATCH that carried no `term_id` leaves it untouched.
306+ if let Some(old) = &self.term
307+ && updated.term.as_ref() != Some(old)
308+ {
309+ cap::release(&old.record(), COURSE_COUNT_FIELD, db).await?;
310+ }
311+ Ok(updated)
312+ }
313+ Err(err) => {
314+ if let Some(new) = &claimed {
315+ cap::release(&new.record(), COURSE_COUNT_FIELD, db).await?;
316+ }
317+ Err(err)
318+ }
319+ }
261 }320 }
262 321
263 /// Assign `teacher` to run this course, or return the course untouched if322 /// Assign `teacher` to run this course, or return the course untouched if
@@ -332,9 +391,36 @@ impl Course {
332 /// leave an exam pointing at a deleted course. The image and391 /// leave an exam pointing at a deleted course. The image and
333 /// homework-file *blobs* are the web layer's to remove — it collects392 /// homework-file *blobs* are the web layer's to remove — it collects
334 /// their names before calling this.393 /// their names before calling this.
335- pub async fn delete(self, db: &Database) -> Result<Course, AppError> {394+ ///
336- db.query(395+ /// The marks going with it give their exam kinds' references back, counted
396+ /// per kind inside this same transaction — the mirror of `Exam::delete`.
397+ /// Skipping it would leave every kind the course graded under counted
398+ /// forever, and a counted kind can never leave the school's settings.
399+ ///
400+ /// `false` = refused, nothing was written: someone is still enrolled. The
401+ /// roster is read off the course's own `enrollment_count`, so the check and
402+ /// the delete are one conditional write on one record — an enroll racing
403+ /// this either takes its seat first (and the delete is refused) or finds
404+ /// the row gone (and is refused itself), in any replica. `Err(NotFound)`
405+ /// keeps the answer a concurrent *delete* used to get.
406+ pub async fn delete(self, db: &Database) -> Result<bool, AppError> {
407+ let mut result = db
408+ .query(format!(
337 "BEGIN TRANSACTION;409 "BEGIN TRANSACTION;
410+ LET $gone = (DELETE $course WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE);
411+ IF array::len($gone) = 0 {{ THROW '{ROSTER_MARK}' }};
412+ FOR $row IN $gone {{
413+ IF $row.term != NONE {{
414+ UPDATE $row.term SET {COURSE_COUNT_FIELD} = \
415+ math::max([({COURSE_COUNT_FIELD} ?? 0) - 1, 0]);
416+ }};
417+ }};
418+ FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result
419+ WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course)
420+ GROUP BY kind) ?? []) {{
421+ UPDATE type::record('kind_ref', $row.kind) SET {REF_COUNT_FIELD} = \
422+ math::max([({REF_COUNT_FIELD} ?? 0) - $row.n, 0])
423+ }};
338 DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);424 DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
339 DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);425 DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
340 DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);426 DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
@@ -350,20 +436,172 @@ impl Course {
350 DELETE subject WHERE course = $course;436 DELETE subject WHERE course = $course;
351 DELETE homework WHERE course = $course;437 DELETE homework WHERE course = $course;
352 DELETE exam WHERE course = $course;438 DELETE exam WHERE course = $course;
353- COMMIT TRANSACTION;",439+ COMMIT TRANSACTION;"
354- )440+ ))
355- .bind(("course", self.id.record()))441+ .bind(("course", self.id.record()))
356- .await?442+ .await?;
357- .check()?;443+ // An aborted transaction errors *every* slot, most with a generic "not
358- let deleted: Option<Course> = db.delete(self.id.record()).await?;444+ // executed" — only the THROW's own slot names the marker.
359- deleted.ok_or(AppError::NotFound)445+ let mut errors = result.take_errors();
446+ if errors
447+ .values()
448+ .any(|error| error.to_string().contains(ROSTER_MARK))
449+ {
450+ // Full stop or already gone: the guard cannot tell those apart, and
451+ // only the refusal path pays for the extra read that can.
452+ return match Self::read(&self.id, db).await? {
453+ Some(_) => Ok(false),
454+ None => Err(AppError::NotFound),
455+ };
456+ }
457+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
458+ return Err(error.into());
459+ }
460+ Ok(true)
360 }461 }
361 }462 }
362 463
464+/// Take a reference on `term` for a course about to link it. The conditional
465+/// write doubles as the existence check: a term that a delete already removed
466+/// matches nothing, and the caller answers exactly what the pre-flight lookup
467+/// in `web::terms::resolve_term` would have.
468+async fn claim_term(term: &TermId, db: &Database) -> Result<(), AppError> {
469+ if cap::claim(&term.record(), COURSE_COUNT_FIELD, cap::UNLIMITED, db).await? {
470+ return Ok(());
471+ }
472+ Err(AppError::Validation(ValidationError::Invalid {
473+ field: "term_id",
474+ reason: "term does not exist",
475+ }))
476+}
477+
363 #[cfg(test)]478 #[cfg(test)]
364 mod tests {479 mod tests {
365 use super::*;480 use super::*;
366 481
482+ async fn course_on(term: Option<TermId>, db: &Database) -> Course {
483+ Course::create(
484+ &UserId::from_key("teacher"),
485+ CourseTitle::try_new("algebra").unwrap(),
486+ CourseDescription::try_new("").unwrap(),
487+ CourseKind::course(),
488+ term,
489+ None,
490+ db,
491+ )
492+ .await
493+ .unwrap()
494+ }
495+
496+ /// The bite test for the delete guard that replaced `ENROLL_LOCK`: the
497+ /// roster check is now the `WHERE` on the delete itself, so only the guard
498+ /// can refuse — and it must refuse having written nothing, cascade
499+ /// included. A `>= 0` guard passes the roster branch and fails here.
500+ #[tokio::test]
501+ async fn a_course_with_a_roster_refuses_to_delete() {
502+ use crate::domain::enrollment::Enrollment;
503+
504+ let db = crate::database::init_mem().await.unwrap();
505+ let teacher = UserId::from_key("teacher");
506+ let student = UserId::from_key("student");
507+ let course = course_on(None, &db).await;
508+ Enrollment::enroll(course.get_id(), &student, &teacher, &db)
509+ .await
510+ .unwrap();
511+
512+ assert!(
513+ !course.clone().delete(&db).await.unwrap(),
514+ "a non-empty roster must refuse the delete"
515+ );
516+ assert!(
517+ Course::read(course.get_id(), &db).await.unwrap().is_some(),
518+ "a refused delete may write nothing"
519+ );
520+ assert!(
521+ Enrollment::read_for_user(course.get_id(), &student, &db)
522+ .await
523+ .unwrap()
524+ .is_some(),
525+ "…the cascade least of all"
526+ );
527+
528+ Enrollment::remove(course.get_id(), &student, &db)
529+ .await
530+ .unwrap();
531+ assert!(course.clone().delete(&db).await.unwrap());
532+ assert!(Course::read(course.get_id(), &db).await.unwrap().is_none());
533+
534+ // The other half of the same guard: once the course row is gone the
535+ // seat claim matches nothing, so a late enroll is a 404 rather than a
536+ // roster row that outlived its course.
537+ let late = Enrollment::enroll(course.get_id(), &student, &teacher, &db)
538+ .await
539+ .expect_err("enrolling into a deleted course must fail");
540+ assert!(matches!(late, AppError::NotFound), "got {late:?}");
541+ }
542+
543+ /// The bite test for the refcount that replaced `TERM_LOCK`: a term is
544+ /// undeletable exactly while a course links it, and every way a link can
545+ /// end — PATCH away, and the course's own delete — gives the reference
546+ /// back. Dropping the release in `delete` leaves the term deletable never.
547+ #[tokio::test]
548+ async fn a_term_is_deletable_only_once_no_course_links_it() {
549+ use crate::domain::term::{Term, TermName};
550+
551+ let db = crate::database::init_mem().await.unwrap();
552+ let at = crate::domain::timestamp::Timestamp::from_millis;
553+ let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db)
554+ .await
555+ .unwrap();
556+
557+ let linked = course_on(Some(term.get_id().clone()), &db).await;
558+ let patched = course_on(Some(term.get_id().clone()), &db).await;
559+ assert!(
560+ !term.clone().delete(&db).await.unwrap(),
561+ "two linked courses must refuse the delete"
562+ );
563+
564+ patched
565+ .update(None, None, None, Some(None), None, &db)
566+ .await
567+ .unwrap();
568+ assert!(
569+ !term.clone().delete(&db).await.unwrap(),
570+ "one link is still one link"
571+ );
572+
573+ assert!(linked.delete(&db).await.unwrap());
574+ assert!(
575+ term.clone().delete(&db).await.unwrap(),
576+ "the last link gone, the term may go"
577+ );
578+ let again = term.delete(&db).await;
579+ assert!(
580+ matches!(again, Err(AppError::NotFound)),
581+ "a second delete is a 404, not a refusal: {again:?}"
582+ );
583+ }
584+
585+ /// The claim doubles as the existence check the lock used to make safe:
586+ /// a term that is already gone cannot be linked, with the same 400 the
587+ /// web layer's pre-flight lookup gives.
588+ #[tokio::test]
589+ async fn a_course_cannot_link_a_term_that_is_gone() {
590+ let db = crate::database::init_mem().await.unwrap();
591+ let error = Course::create(
592+ &UserId::from_key("teacher"),
593+ CourseTitle::try_new("algebra").unwrap(),
594+ CourseDescription::try_new("").unwrap(),
595+ CourseKind::course(),
596+ Some(TermId::from_key("gone")),
597+ None,
598+ &db,
599+ )
600+ .await
601+ .expect_err("a missing term must not be linkable");
602+ assert!(error.to_string().contains("term does not exist"));
603+ }
604+
367 #[tokio::test]605 #[tokio::test]
368 async fn title_is_required() {606 async fn title_is_required() {
369 assert!(CourseTitle::try_new("algebra").is_ok());607 assert!(CourseTitle::try_new("algebra").is_ok());
src/domain/enrollment.rsmodified+31 -54
@@ -1,24 +1,13 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2-use tokio::sync::Mutex;
3 2
4 use crate::constant::{ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE};3 use crate::constant::{ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE};
5-use crate::database::{Database, lost_the_race};4+use crate::database::Database;
6 use crate::domain::cap;5 use crate::domain::cap;
7 use crate::domain::course::{Course, CourseId};6 use crate::domain::course::{Course, CourseId};
8 use crate::domain::page::PagedList;7 use crate::domain::page::PagedList;
9 use crate::domain::user::UserId;8 use crate::domain::user::UserId;
10 use crate::error::AppError;9 use crate::error::AppError;
11 10
12-/// Serializes the roster check of a course delete against a concurrent enroll,
13-/// so a student can't join a course that is already on its way out.
14-//
15-// ponytail: process-local, so with two replicas the delete-vs-enroll window is
16-// only narrowed, not closed — a student can still land on a course another
17-// replica is deleting, and the cascade then leaves nothing behind but a 404 on
18-// the next read. Closing it needs the same treatment the capacity cap got: a
19-// deleting flag on the course row that the enroll's conditional UPDATE checks.
20-pub(crate) static ENROLL_LOCK: Mutex<()> = Mutex::const_new(());
21-
22 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]11 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
23 pub struct EnrollmentId(RecordId);12 pub struct EnrollmentId(RecordId);
24 13
@@ -82,13 +71,15 @@ impl Enrollment {
82 /// single-record conditional write, so the cap holds across replicas and71 /// single-record conditional write, so the cap holds across replicas and
83 /// against a concurrent capacity PATCH alike. An already enrolled user is72 /// against a concurrent capacity PATCH alike. An already enrolled user is
84 /// returned as-is even when the roster is full, and never charged a seat.73 /// returned as-is even when the roster is full, and never charged a seat.
74+ /// The same claim is the delete guard's other half: it is refused outright
75+ /// once the course row is gone, and while it holds a seat the course cannot
76+ /// be deleted — so no roster row can outlive its course.
85 pub async fn enroll(77 pub async fn enroll(
86 course: &CourseId,78 course: &CourseId,
87 user: &UserId,79 user: &UserId,
88 enrolled_by: &UserId,80 enrolled_by: &UserId,
89 db: &Database,81 db: &Database,
90 ) -> Result<Enrollment, AppError> {82 ) -> Result<Enrollment, AppError> {
91- let _guard = ENROLL_LOCK.lock().await;
92 if let Some(existing) = Self::read_for_user(course, user, db).await? {83 if let Some(existing) = Self::read_for_user(course, user, db).await? {
93 return Ok(existing);84 return Ok(existing);
94 }85 }
@@ -96,43 +87,39 @@ impl Enrollment {
96 .await?87 .await?
97 .ok_or(AppError::NotFound)?88 .ok_or(AppError::NotFound)?
98 .get_capacity();89 .get_capacity();
99- let seats = course.record();
100- if !cap::claim(
101- &seats,
102- ENROLLMENT_COUNT_FIELD,
103- capacity.unwrap_or(cap::UNLIMITED),
104- db,
105- )
106- .await?
107- {
108- return Err(AppError::Conflict("the course is full"));
109- }
110 let enrollment = Enrollment {90 let enrollment = Enrollment {
111 id: EnrollmentId::composite(course, user),91 id: EnrollmentId::composite(course, user),
112 course: course.clone(),92 course: course.clone(),
113 user: user.clone(),93 user: user.clone(),
114 enrolled_by: enrolled_by.clone(),94 enrolled_by: enrolled_by.clone(),
115 };95 };
116- // CREATE, not UPSERT: a duplicate has to be *seen*, or the pair's second96+ // CREATE, not UPSERT, and in the seat's own transaction: a duplicate has
117- // writer would silently keep the seat it claimed for a row that already97+ // to be *seen*, or the pair's second writer would keep the seat it
118- // existed and the counter would drift above the roster forever.98+ // claimed for a row that already existed and the counter would drift
119- let saved: Result<Option<Enrollment>, _> =99+ // above the roster forever.
120- db.create(enrollment.id.record()).content(enrollment).await;100+ match cap::claim_and_create(
121- match saved {101+ &course.record(),
122- Ok(Some(saved)) => Ok(saved),102+ ENROLLMENT_COUNT_FIELD,
123- Ok(None) => {103+ capacity.unwrap_or(cap::UNLIMITED),
124- cap::release(&seats, ENROLLMENT_COUNT_FIELD, db).await?;104+ &enrollment.id.record(),
125- Err(AppError::Internal("failed to enroll user".into()))105+ &enrollment,
126- }106+ db,
127- Err(err) => {107+ )
128- cap::release(&seats, ENROLLMENT_COUNT_FIELD, db).await?;108+ .await?
129- if !lost_the_race(&err) {109+ {
130- return Err(err.into());110+ cap::Claimed::Made(saved) => Ok(saved),
131- }111+ // Someone placed this pair first; their row is the answer, and no
132- Self::read_for_user(course, user, db)112+ // seat was spent finding that out.
133- .await?113+ cap::Claimed::Duplicate => Self::read_for_user(course, user, db)
134- .ok_or_else(|| AppError::Internal("failed to enroll user".into()))114+ .await?
135- }115+ .ok_or_else(|| AppError::Internal("failed to enroll user".into())),
116+ // Full, or the course was deleted between the read and the claim —
117+ // the conditional write matches nothing either way, and only this
118+ // path pays for the read that tells them apart.
119+ cap::Claimed::Full => match Course::read(course, db).await? {
120+ Some(_) => Err(AppError::Conflict("the course is full")),
121+ None => Err(AppError::NotFound),
122+ },
136 }123 }
137 }124 }
138 125
@@ -151,16 +138,6 @@ impl Enrollment {
151 Ok(result.take::<Vec<Enrollment>>(0)?.into_iter().next())138 Ok(result.take::<Vec<Enrollment>>(0)?.into_iter().next())
152 }139 }
153 140
154- /// True iff anyone is still on the course's roster — the delete guard.
155- pub async fn any_for_course(course: &CourseId, db: &Database) -> Result<bool, AppError> {
156- let mut result = db
157- .query("SELECT VALUE id FROM enrollment WHERE course = $course LIMIT 1")
158- .bind(("course", course.record()))
159- .await?
160- .check()?;
161- Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
162- }
163-
164 pub async fn list_for_course(141 pub async fn list_for_course(
165 course: &CourseId,142 course: &CourseId,
166 limit: Option<i64>,143 limit: Option<i64>,
src/domain/exam.rsmodified+42 -0
@@ -290,6 +290,14 @@ pub struct Exam {
290 // managers, cannot be sat, and cannot be graded. Rows predating the290 // managers, cannot be sat, and cannot be graded. Rows predating the
291 // column are backfilled published (`false`).291 // column are backfilled published (`false`).
292 draft: bool,292 draft: bool,
293+ /// How many marks the exam carries — a cap-style counter ([`cap::claim`]
294+ /// from the grade, decremented by every delete of a mark), absent meaning
295+ /// zero. Unlike every other counter it is carried *in the struct*, because
296+ /// the save below is a whole-row `CONTENT` write: a column this type did
297+ /// not know about would be wiped by the next exam PATCH. Being in the row
298+ /// is also what makes it useful — the save pins it, so a grade landing
299+ /// mid-PATCH refuses the save instead of slipping past its gates.
300+ result_count: Option<i64>,
293 }301 }
294 302
295 impl Exam {303 impl Exam {
@@ -297,6 +305,11 @@ impl Exam {
297 &self.id305 &self.id
298 }306 }
299 307
308+ /// The marks this exam carries, as the counter reads (absent = none yet).
309+ pub fn get_result_count(&self) -> i64 {
310+ self.result_count.unwrap_or(0)
311+ }
312+
300 pub fn get_creator(&self) -> &UserId {313 pub fn get_creator(&self) -> &UserId {
301 &self.creator314 &self.creator
302 }315 }
@@ -403,6 +416,7 @@ impl Exam {
403 allow_rejoin,416 allow_rejoin,
404 allow_review,417 allow_review,
405 draft,418 draft,
419+ result_count: None,
406 };420 };
407 let created: Option<Exam> = db.create(exam.id.record()).content(exam).await?;421 let created: Option<Exam> = db.create(exam.id.record()).content(exam).await?;
408 created.ok_or_else(|| AppError::Internal("failed to create exam".into()))422 created.ok_or_else(|| AppError::Internal("failed to create exam".into()))
@@ -523,6 +537,7 @@ impl Exam {
523 AND allow_rejoin = $was_allow_rejoin537 AND allow_rejoin = $was_allow_rejoin
524 AND allow_review = $was_allow_review538 AND allow_review = $was_allow_review
525 AND draft = $was_draft539 AND draft = $was_draft
540+ AND (result_count ?? 0) = $was_results
526 RETURN AFTER;541 RETURN AFTER;
527 COMMIT TRANSACTION;",542 COMMIT TRANSACTION;",
528 )543 )
@@ -539,6 +554,12 @@ impl Exam {
539 .bind(("was_allow_rejoin", was.8))554 .bind(("was_allow_rejoin", was.8))
540 .bind(("was_allow_review", was.9))555 .bind(("was_allow_review", was.9))
541 .bind(("was_draft", was.10))556 .bind(("was_draft", was.10))
557+ // The mark counter is pinned like every other column this write
558+ // replaces, and for a sharper reason: a grade increments it, so
559+ // pinning it is what makes "this exam had no marks" — the gate the
560+ // handler refuses a kind change on — true at *write* time and not
561+ // merely at read time. A mark landing in between refuses the save.
562+ .bind(("was_results", self.result_count.unwrap_or(0)))
542 .bind(("new", self))563 .bind(("new", self))
543 .await?;564 .await?;
544 // An aborted transaction errors every slot; only the THROW's names the565 // An aborted transaction errors every slot; only the THROW's names the
@@ -566,15 +587,35 @@ impl Exam {
566 /// Bank templates saved out of this exam survive it — they are a separate,587 /// Bank templates saved out of this exam survive it — they are a separate,
567 /// reusable library — so only their `source_exam` provenance link is cleared,588 /// reusable library — so only their `source_exam` provenance link is cleared,
568 /// in the same transaction, never left pointing at a dead exam.589 /// in the same transaction, never left pointing at a dead exam.
590+ ///
591+ /// The questions about to be cascaded each hold a reference on their
592+ /// subject, which is what keeps that subject from being deleted under them.
593+ /// They are given back in this same transaction, counted per subject, so
594+ /// deleting an exam frees its subjects for deletion and nothing else does.
595+ /// The marks give their *kind* references back the same way, and it has to
596+ /// be the same way: counted outside the transaction, a mark deleted by a
597+ /// concurrent `remove_result` in the gap would be released twice — once by
598+ /// each — which on a kind another exam still uses reads as one mark too
599+ /// few, and that is a kind wrongly free to leave the settings.
569 pub async fn delete(self, db: &Database) -> Result<Exam, AppError> {600 pub async fn delete(self, db: &Database) -> Result<Exam, AppError> {
570 let mut result = db601 let mut result = db
571 .query(602 .query(
572 "BEGIN TRANSACTION;603 "BEGIN TRANSACTION;
604+ FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result
605+ WHERE exam = $ex GROUP BY kind) ?? []) {
606+ UPDATE type::record('kind_ref', $row.kind) SET count =
607+ math::max([(count ?? 0) - $row.n, 0])
608+ };
573 DELETE exam_result WHERE exam = $ex;609 DELETE exam_result WHERE exam = $ex;
574 DELETE exam_attempt WHERE exam = $ex;610 DELETE exam_attempt WHERE exam = $ex;
575 DELETE exam_answer WHERE exam = $ex;611 DELETE exam_answer WHERE exam = $ex;
576 DELETE answer_image WHERE exam = $ex;612 DELETE answer_image WHERE exam = $ex;
577 DELETE question_image WHERE exam = $ex;613 DELETE question_image WHERE exam = $ex;
614+ FOR $row IN ((SELECT subject, count() AS n FROM exam_question
615+ WHERE exam = $ex GROUP BY subject) ?? []) {
616+ UPDATE $row.subject SET exam_question_count =
617+ math::max([(exam_question_count ?? 0) - $row.n, 0])
618+ };
578 DELETE exam_question WHERE exam = $ex;619 DELETE exam_question WHERE exam = $ex;
579 UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex;620 UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex;
580 LET $before = (DELETE $ex RETURN BEFORE);621 LET $before = (DELETE $ex RETURN BEFORE);
@@ -697,6 +738,7 @@ mod tests {
697 1,738 1,
698 Mark::try_new(80).unwrap(),739 Mark::try_new(80).unwrap(),
699 &UserId::generate(),740 &UserId::generate(),
741+ exam.get_kind().as_str(),
700 &db,742 &db,
701 )743 )
702 .await744 .await
src/domain/exam_attempt.rsmodified+11 -1
@@ -438,9 +438,19 @@ mod tests {
438 &[],438 &[],
439 )439 )
440 .unwrap();440 .unwrap();
441+ // A real subject row, not a minted id: a question claims a reference on
442+ // its subject and is refused if that subject does not exist.
443+ let subject = crate::domain::subject::Subject::create(
444+ &crate::domain::course::CourseId::generate(),
445+ crate::domain::subject::SubjectName::try_new("topic").unwrap(),
446+ crate::domain::subject::SubjectDescription::try_new("").unwrap(),
447+ db,
448+ )
449+ .await
450+ .unwrap();
441 let question = ExamQuestion::create(451 let question = ExamQuestion::create(
442 exam.get_id(),452 exam.get_id(),
443- crate::domain::subject::SubjectId::generate(),453+ subject.get_id().clone(),
444 crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(),454 crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(),
445 QuestionPoints::try_new(5).unwrap(),455 QuestionPoints::try_new(5).unwrap(),
446 spec,456 spec,
src/domain/exam_question.rsmodified+94 -47
@@ -3,10 +3,11 @@ use ulid::Ulid;
3 3
4 use crate::constant::{4 use crate::constant::{
5 EXAM_QUESTION_TABLE, MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN,5 EXAM_QUESTION_TABLE, MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN,
6- MIN_QUESTION_CHOICES,6+ MIN_QUESTION_CHOICES, SUBJECT_QUESTION_COUNT_FIELD,
7 };7 };
8 use crate::database::Database;8 use crate::database::Database;
9 use crate::domain::bank_question::BankQuestionId;9 use crate::domain::bank_question::BankQuestionId;
10+use crate::domain::cap;
10 use crate::domain::exam::ExamId;11 use crate::domain::exam::ExamId;
11 use crate::domain::exam_attempt::ExamAttempt;12 use crate::domain::exam_attempt::ExamAttempt;
12 use crate::domain::monotonic_id::next_ulid;13 use crate::domain::monotonic_id::next_ulid;
@@ -393,6 +394,20 @@ impl ExamQuestion {
393 from_bank: Option<BankQuestionId>,394 from_bank: Option<BankQuestionId>,
394 db: &Database,395 db: &Database,
395 ) -> Result<ExamQuestion, AppError> {396 ) -> Result<ExamQuestion, AppError> {
397+ // Take the subject's reference before the row exists, exactly as a cap
398+ // is claimed before the child it caps ([`cap::claim`], here uncapped):
399+ // the subject delete is conditioned on that counter reading zero, so
400+ // the two contend on the subject record and a question can no longer
401+ // land on a subject another replica is deleting. A miss means the
402+ // subject is already gone — the same 400 the web layer's pre-flight
403+ // check answers with.
404+ let counted = subject.record();
405+ if !cap::claim(&counted, SUBJECT_QUESTION_COUNT_FIELD, cap::UNLIMITED, db).await? {
406+ return Err(AppError::Validation(ValidationError::Invalid {
407+ field: "subject_id",
408+ reason: "subject does not exist",
409+ }));
410+ }
396 let question = ExamQuestion {411 let question = ExamQuestion {
397 id: ExamQuestionId::generate(),412 id: ExamQuestionId::generate(),
398 exam: exam.clone(),413 exam: exam.clone(),
@@ -409,18 +424,28 @@ impl ExamQuestion {
409 // The freeze gate rides in the same transaction as the insert: a424 // The freeze gate rides in the same transaction as the insert: a
410 // question cannot appear under an exam somebody has already started,425 // question cannot appear under an exam somebody has already started,
411 // whichever replica the two requests hit.426 // whichever replica the two requests hit.
412- let mut result = db427+ let inserted = async {
413- .query(ExamAttempt::unfrozen("CREATE $id CONTENT $question;"))428+ let mut result = db
414- .bind(("freeze_exam", exam.record()))429+ .query(ExamAttempt::unfrozen("CREATE $id CONTENT $question;"))
415- .bind(("id", question.id.record()))430+ .bind(("freeze_exam", exam.record()))
416- .bind(("question", question))431+ .bind(("id", question.id.record()))
417- .await?;432+ .bind(("question", question))
418- ExamAttempt::frozen_check(&mut result)?;433+ .await?;
419- result434+ ExamAttempt::frozen_check(&mut result)?;
420- .take::<Vec<ExamQuestion>>(ExamAttempt::FROZEN_SLOT)?435+ result
421- .into_iter()436+ .take::<Vec<ExamQuestion>>(ExamAttempt::FROZEN_SLOT)?
422- .next()437+ .into_iter()
423- .ok_or_else(|| AppError::Internal("failed to create exam question".into()))438+ .next()
439+ .ok_or_else(|| AppError::Internal("failed to create exam question".into()))
440+ }
441+ .await;
442+ if inserted.is_err() {
443+ // The row never landed (a frozen exam, most often), so the
444+ // reference it took goes straight back — otherwise the subject
445+ // would be undeletable for a question that does not exist.
446+ cap::release(&counted, SUBJECT_QUESTION_COUNT_FIELD, db).await?;
447+ }
448+ inserted
424 }449 }
425 450
426 pub async fn read(451 pub async fn read(
@@ -443,17 +468,6 @@ impl ExamQuestion {
443 .await468 .await
444 }469 }
445 470
446- /// Whether any question anywhere references `subject` — the gate that
447- /// blocks deleting a subject still in use.
448- pub async fn any_for_subject(subject: &SubjectId, db: &Database) -> Result<bool, AppError> {
449- let mut result = db
450- .query("SELECT VALUE id FROM exam_question WHERE subject = $subject LIMIT 1")
451- .bind(("subject", subject.record()))
452- .await?
453- .check()?;
454- Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
455- }
456-
457 /// Write the editable fields, refused outright once the exam has an471 /// Write the editable fields, refused outright once the exam has an
458 /// attempt — the freeze gate is part of this transaction, not a check the472 /// attempt — the freeze gate is part of this transaction, not a check the
459 /// caller made a moment earlier under a lock.473 /// caller made a moment earlier under a lock.
@@ -472,26 +486,49 @@ impl ExamQuestion {
472 spec: QuestionSpec,486 spec: QuestionSpec,
473 db: &Database,487 db: &Database,
474 ) -> Result<ExamQuestion, AppError> {488 ) -> Result<ExamQuestion, AppError> {
475- let mut result = db489+ // A re-tag moves a reference: the new subject is claimed *before* the
476- .query(ExamAttempt::unfrozen(490+ // write and the old one released only once it lands, so at no instant
477- "UPDATE $id SET subject = $subject, text = $text, points = $points,491+ // is either subject under-counted — the direction that would let one be
478- kind = $kind, choices = $choices, correct = $correct RETURN AFTER;",492+ // deleted while this question still points at it. Both counters staying
479- ))493+ // put is the ordinary case (`subject` omitted from the PATCH), and it
480- .bind(("freeze_exam", self.exam.record()))494+ // costs nothing.
481- .bind(("id", self.id.record()))495+ let retag = (subject != self.subject).then(|| (subject.record(), self.subject.record()));
482- .bind(("subject", subject.record()))496+ if let Some((next, _)) = &retag
483- .bind(("text", text))497+ && !cap::claim(next, SUBJECT_QUESTION_COUNT_FIELD, cap::UNLIMITED, db).await?
484- .bind(("points", points))498+ {
485- .bind(("kind", spec.kind))499+ return Err(AppError::Validation(ValidationError::Invalid {
486- .bind(("choices", spec.choices))500+ field: "subject_id",
487- .bind(("correct", spec.correct))501+ reason: "subject does not exist",
488- .await?;502+ }));
489- ExamAttempt::frozen_check(&mut result)?;503+ }
490- result504+ let written = async {
491- .take::<Vec<ExamQuestion>>(ExamAttempt::FROZEN_SLOT)?505+ let mut result = db
492- .into_iter()506+ .query(ExamAttempt::unfrozen(
493- .next()507+ "UPDATE $id SET subject = $subject, text = $text, points = $points,
494- .ok_or(AppError::NotFound)508+ kind = $kind, choices = $choices, correct = $correct RETURN AFTER;",
509+ ))
510+ .bind(("freeze_exam", self.exam.record()))
511+ .bind(("id", self.id.record()))
512+ .bind(("subject", subject.record()))
513+ .bind(("text", text))
514+ .bind(("points", points))
515+ .bind(("kind", spec.kind))
516+ .bind(("choices", spec.choices))
517+ .bind(("correct", spec.correct))
518+ .await?;
519+ ExamAttempt::frozen_check(&mut result)?;
520+ result
521+ .take::<Vec<ExamQuestion>>(ExamAttempt::FROZEN_SLOT)?
522+ .into_iter()
523+ .next()
524+ .ok_or(AppError::NotFound)
525+ }
526+ .await;
527+ if let Some((next, previous)) = &retag {
528+ let give_back = if written.is_ok() { previous } else { next };
529+ cap::release(give_back, SUBJECT_QUESTION_COUNT_FIELD, db).await?;
530+ }
531+ written
495 }532 }
496 533
497 /// Point the question's `banked_as` at the bank template it was just saved534 /// Point the question's `banked_as` at the bank template it was just saved
@@ -538,15 +575,25 @@ impl ExamQuestion {
538 .query(ExamAttempt::unfrozen(575 .query(ExamAttempt::unfrozen(
539 "DELETE exam_answer WHERE question = $q;576 "DELETE exam_answer WHERE question = $q;
540 DELETE question_image WHERE question = $q;577 DELETE question_image WHERE question = $q;
541- DELETE $q RETURN BEFORE;",578+ LET $gone = (DELETE $q RETURN BEFORE);
579+ FOR $sub IN ($gone.subject ?? []) {
580+ UPDATE $sub SET exam_question_count =
581+ math::max([(exam_question_count ?? 0) - 1, 0])
582+ };
583+ RETURN $gone;",
542 ))584 ))
543 .bind(("freeze_exam", self.exam.record()))585 .bind(("freeze_exam", self.exam.record()))
544 .bind(("q", self.id.record()))586 .bind(("q", self.id.record()))
545 .await?;587 .await?;
546 ExamAttempt::frozen_check(&mut result)?;588 ExamAttempt::frozen_check(&mut result)?;
547- // Two cascade statements ahead of the delete itself.589+ // The subject's reference is given back inside this same transaction,
590+ // driven off what the delete actually removed — a question that wasn't
591+ // there decrements nothing. Read through the trailing `RETURN` rather
592+ // than a hand-counted slot, so inserting a cascade statement above can
593+ // never turn a delete into a 404 (see [`crate::domain::exam::Exam`]).
594+ let slot = result.num_statements().saturating_sub(2);
548 result595 result
549- .take::<Vec<ExamQuestion>>(ExamAttempt::FROZEN_SLOT + 2)?596+ .take::<Vec<ExamQuestion>>(slot)?
550 .into_iter()597 .into_iter()
551 .next()598 .next()
552 .ok_or(AppError::NotFound)599 .ok_or(AppError::NotFound)
src/domain/exam_result.rsmodified+136 -29
@@ -2,8 +2,11 @@ use std::collections::HashMap;
2 2
3 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};3 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
4 4
5-use crate::constant::EXAM_RESULT_TABLE;5+use crate::constant::{
6+ EXAM_RESULT_COUNT_FIELD, EXAM_RESULT_TABLE, KIND_REF_TABLE, REF_COUNT_FIELD,
7+};
6 use crate::database::Database;8 use crate::database::Database;
9+use crate::domain::cap;
7 use crate::domain::course::CourseId;10 use crate::domain::course::CourseId;
8 use crate::domain::exam::ExamId;11 use crate::domain::exam::ExamId;
9 use crate::domain::key;12 use crate::domain::key;
@@ -17,6 +20,25 @@ pub(crate) fn draft_error() -> AppError {
17 AppError::Conflict("this exam is a draft — publish it before grading")20 AppError::Conflict("this exam is a draft — publish it before grading")
18 }21 }
19 22
23+/// The reference counter for one exam kind — how many marks are written under
24+/// that name, and whether the school has retired it (see
25+/// [`crate::domain::cap`]). Keyed by the name itself: the kind is snapshotted
26+/// text on the exam, and this row is what makes "a kind nothing is graded under
27+/// may be removed" a decision two replicas can share.
28+pub(crate) fn kind_ref(kind: &str) -> RecordId {
29+ RecordId::new(KIND_REF_TABLE, kind)
30+}
31+
32+/// The refusal a mark meets once its kind has left the school's list. The
33+/// mirror of the settings-side 409: whichever of the two writes reaches the
34+/// counter first, the other is told the name is no longer usable.
35+pub(crate) fn retired_kind_error(kind: &str) -> AppError {
36+ AppError::ConflictOwned(format!(
37+ "the '{kind}' exam kind has been removed from the school's settings — \
38+ add it back before grading this exam"
39+ ))
40+}
41+
20 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]42 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
21 pub struct ExamResultId(RecordId);43 pub struct ExamResultId(RecordId);
22 44
@@ -58,6 +80,14 @@ impl Mark {
58 }80 }
59 }81 }
60 82
83+/// What one mark write reports back: the stored row, and whether it replaced a
84+/// mark that was already there.
85+#[derive(Debug, Clone, SurrealValue)]
86+struct Written {
87+ existed: bool,
88+ result: ExamResult,
89+}
90+
61 #[derive(Debug, Clone, SurrealValue)]91 #[derive(Debug, Clone, SurrealValue)]
62 pub struct ExamResult {92 pub struct ExamResult {
63 id: ExamResultId,93 id: ExamResultId,
@@ -155,14 +185,54 @@ impl ExamResult {
155 /// converge on one row instead of racing the unique index into a 500.185 /// converge on one row instead of racing the unique index into a 500.
156 /// Grading a retake writes a fresh mark at the current seq and never touches186 /// Grading a retake writes a fresh mark at the current seq and never touches
157 /// prior sittings' marks; the latest seq is the grade-of-record.187 /// prior sittings' marks; the latest seq is the grade-of-record.
188+ ///
189+ /// `kind` is the exam's kind, and this is where a mark takes its reference
190+ /// on it — claimed *before* the write, given back when the write turns out
191+ /// to have been an overwrite (one mark, one reference) or to have failed. A
192+ /// kind the school has retired refuses the claim, which is the same
193+ /// invariant the settings guard enforces from the other side, and the one
194+ /// crash window left over-counts a kind (refusing a removal) rather than
195+ /// letting a mark exist under a kind nothing counted.
196+ ///
197+ /// The exam's own `result_count` is claimed in the same breath, and it is
198+ /// what a kind change is refused against: the exam PATCH pins that counter,
199+ /// so a mark landing while it decides cannot slip past its gate and leave
200+ /// itself counted under a kind its exam no longer carries.
158 pub async fn grade(201 pub async fn grade(
159 exam: &ExamId,202 exam: &ExamId,
160 user: &UserId,203 user: &UserId,
161 seq: i64,204 seq: i64,
162 mark: Mark,205 mark: Mark,
163 graded_by: &UserId,206 graded_by: &UserId,
207+ kind: &str,
164 db: &Database,208 db: &Database,
165 ) -> Result<ExamResult, AppError> {209 ) -> Result<ExamResult, AppError> {
210+ let counter = kind_ref(kind);
211+ if !cap::claim_ref(&counter, 1, db).await? {
212+ return Err(retired_kind_error(kind));
213+ }
214+ cap::claim(&exam.record(), EXAM_RESULT_COUNT_FIELD, cap::UNLIMITED, db).await?;
215+ let written = Self::write_mark(exam, user, seq, mark, graded_by, db).await;
216+ match written {
217+ // An overwrite is not a second mark: both counters go back, or a
218+ // regrade would drift them upward and freeze the kind for good.
219+ Ok(Written { existed: true, .. }) | Err(_) => {
220+ cap::release_ref(&counter, 1, db).await?;
221+ cap::release(&exam.record(), EXAM_RESULT_COUNT_FIELD, db).await?;
222+ }
223+ Ok(_) => {}
224+ }
225+ written.map(|written| written.result)
226+ }
227+
228+ async fn write_mark(
229+ exam: &ExamId,
230+ user: &UserId,
231+ seq: i64,
232+ mark: Mark,
233+ graded_by: &UserId,
234+ db: &Database,
235+ ) -> Result<Written, AppError> {
166 let result = ExamResult {236 let result = ExamResult {
167 id: ExamResultId::composite(exam, user, seq),237 id: ExamResultId::composite(exam, user, seq),
168 exam: exam.clone(),238 exam: exam.clone(),
@@ -176,11 +246,17 @@ impl ExamResult {
176 // them, a mark and a re-draft racing each other can only ever leave one246 // them, a mark and a re-draft racing each other can only ever leave one
177 // of the two applied, whichever process either ran in. The caller's247 // of the two applied, whichever process either ran in. The caller's
178 // pre-flight check answers the same 409 one round trip earlier.248 // pre-flight check answers the same 409 one round trip earlier.
249+ // Whether the row was already there rides out of the transaction with
250+ // the mark: the answer decides if this grade owes the kind a reference,
251+ // and read anywhere else it would be a guess about a row two graders
252+ // may be writing at once.
179 let mut written = db253 let mut written = db
180 .query(254 .query(
181 "BEGIN TRANSACTION;255 "BEGIN TRANSACTION;
182 IF (SELECT VALUE draft FROM ONLY $exam) { THROW 'exam_draft' };256 IF (SELECT VALUE draft FROM ONLY $exam) { THROW 'exam_draft' };
183- UPSERT $id CONTENT $result RETURN AFTER;257+ LET $before = (SELECT VALUE id FROM ONLY $id);
258+ LET $after = (UPSERT $id CONTENT $result RETURN AFTER);
259+ RETURN { existed: $before != NONE, result: $after[0] };
184 COMMIT TRANSACTION;",260 COMMIT TRANSACTION;",
185 )261 )
186 .bind(("exam", exam.record()))262 .bind(("exam", exam.record()))
@@ -197,9 +273,12 @@ impl ExamResult {
197 if let Some(error) = errors.drain().map(|(_, error)| error).next() {273 if let Some(error) = errors.drain().map(|(_, error)| error).next() {
198 return Err(error.into());274 return Err(error.into());
199 }275 }
200- // BEGIN and the IF take a slot each.276+ // The trailing `RETURN` is always the last statement before `COMMIT`,
277+ // so its slot follows the statement count instead of a hand-kept
278+ // number — see `Exam::delete` for the bug the hand-kept one caused.
279+ let slot = written.num_statements().saturating_sub(2);
201 written280 written
202- .take::<Vec<ExamResult>>(2)?281+ .take::<Vec<Written>>(slot)?
203 .into_iter()282 .into_iter()
204 .next()283 .next()
205 .ok_or_else(|| AppError::Internal("failed to record exam result".into()))284 .ok_or_else(|| AppError::Internal("failed to record exam result".into()))
@@ -225,22 +304,6 @@ impl ExamResult {
225 Ok(Self::latest_per_pair(result.take::<Vec<ExamResult>>(0)?))304 Ok(Self::latest_per_pair(result.take::<Vec<ExamResult>>(0)?))
226 }305 }
227 306
228- /// True iff any exam of `kind` has produced a mark — the settings guard
229- /// against removing an exam kind that grades already depend on (weights are
230- /// read live from settings, so dropping the kind would silently re-weight
231- /// those marks).
232- pub async fn any_for_kind(kind: &str, db: &Database) -> Result<bool, AppError> {
233- let mut result = db
234- .query(
235- "SELECT VALUE id FROM exam_result
236- WHERE exam IN (SELECT VALUE id FROM exam WHERE kind = $kind) LIMIT 1",
237- )
238- .bind(("kind", kind.to_string()))
239- .await?
240- .check()?;
241- Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
242- }
243-
244 pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamResult>, AppError> {307 pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamResult>, AppError> {
245 let mut result = db308 let mut result = db
246 .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC")309 .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC")
@@ -269,18 +332,44 @@ impl ExamResult {
269 Ok(result.take::<Vec<ExamResult>>(0)?)332 Ok(result.take::<Vec<ExamResult>>(0)?)
270 }333 }
271 334
335+ /// Delete every sitting's mark for one (exam, user) pair. `kind` is the
336+ /// exam's: the marks give their references back, so a kind nothing is
337+ /// graded under any more can leave the settings again.
272 pub async fn remove(338 pub async fn remove(
273 exam: &ExamId,339 exam: &ExamId,
274 user: &UserId,340 user: &UserId,
341+ kind: &str,
275 db: &Database,342 db: &Database,
276 ) -> Result<Option<ExamResult>, AppError> {343 ) -> Result<Option<ExamResult>, AppError> {
344+ // Both counters go back *inside* the delete's own transaction, driven
345+ // off the rows this statement actually deleted. Counted outside it, a
346+ // cascade (exam or course delete) taking the same rows in the gap would
347+ // release them a second time, and on a kind another exam still grades
348+ // under, one release too many reads as one mark too few — a kind
349+ // wrongly free to leave the settings.
277 let mut result = db350 let mut result = db
278- .query("DELETE exam_result WHERE exam = $ex AND user = $usr RETURN BEFORE")351+ .query(format!(
352+ "BEGIN TRANSACTION;
353+ LET $gone = (DELETE exam_result WHERE exam = $ex AND user = $usr RETURN BEFORE);
354+ IF array::len($gone) > 0 {{
355+ UPDATE type::record('kind_ref', $kind) SET {REF_COUNT_FIELD} =
356+ math::max([({REF_COUNT_FIELD} ?? 0) - array::len($gone), 0]);
357+ UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} =
358+ math::max([({EXAM_RESULT_COUNT_FIELD} ?? 0) - array::len($gone), 0]);
359+ }};
360+ RETURN $gone;
361+ COMMIT TRANSACTION;"
362+ ))
279 .bind(("ex", exam.record()))363 .bind(("ex", exam.record()))
280 .bind(("usr", user.record()))364 .bind(("usr", user.record()))
365+ .bind(("kind", kind.to_string()))
281 .await?366 .await?
282 .check()?;367 .check()?;
283- Ok(result.take::<Vec<ExamResult>>(0)?.into_iter().next())368+ // `RETURN` is the last statement before `COMMIT`; its slot follows the
369+ // statement count, as in `Exam::delete`.
370+ let slot = result.num_statements().saturating_sub(2);
371+ let removed = result.take::<Vec<ExamResult>>(slot)?;
372+ Ok(removed.into_iter().next())
284 }373 }
285 }374 }
286 375
@@ -305,12 +394,28 @@ mod tests {
305 let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");394 let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
306 395
307 // Grade sitting #1, then a retake as sitting #2 — two rows, not one.396 // Grade sitting #1, then a retake as sitting #2 — two rows, not one.
308- ExamResult::grade(&exam, &user, 1, Mark::try_new(40).unwrap(), &teacher, &db)397+ ExamResult::grade(
309- .await398+ &exam,
310- .unwrap();399+ &user,
311- let second = ExamResult::grade(&exam, &user, 2, Mark::try_new(90).unwrap(), &teacher, &db)400+ 1,
312- .await401+ Mark::try_new(40).unwrap(),
313- .unwrap();402+ &teacher,
403+ "midterm",
404+ &db,
405+ )
406+ .await
407+ .unwrap();
408+ let second = ExamResult::grade(
409+ &exam,
410+ &user,
411+ 2,
412+ Mark::try_new(90).unwrap(),
413+ &teacher,
414+ "midterm",
415+ &db,
416+ )
417+ .await
418+ .unwrap();
314 assert_eq!(second.get_seq(), 2);419 assert_eq!(second.get_seq(), 2);
315 420
316 // Grade-of-record is the latest sitting's mark.421 // Grade-of-record is the latest sitting's mark.
@@ -339,7 +444,9 @@ mod tests {
339 );444 );
340 445
341 // Deleting the pair removes every sitting.446 // Deleting the pair removes every sitting.
342- ExamResult::remove(&exam, &user, &db).await.unwrap();447+ ExamResult::remove(&exam, &user, "midterm", &db)
448+ .await
449+ .unwrap();
343 assert!(450 assert!(
344 ExamResult::list_all_for_exam_user(&exam, &user, &db)451 ExamResult::list_all_for_exam_user(&exam, &user, &db)
345 .await452 .await
src/domain/homework.rsmodified+66 -21
@@ -13,8 +13,12 @@
13 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};13 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
14 use ulid::Ulid;14 use ulid::Ulid;
15 15
16-use crate::constant::{HOMEWORK_TABLE, MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN};16+use crate::constant::{
17+ HOMEWORK_TABLE, MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN,
18+ SUBJECT_HOMEWORK_COUNT_FIELD,
19+};
17 use crate::database::Database;20 use crate::database::Database;
21+use crate::domain::cap;
18 use crate::domain::course::CourseId;22 use crate::domain::course::CourseId;
19 use crate::domain::field_update::FieldUpdate;23 use crate::domain::field_update::FieldUpdate;
20 use crate::domain::subject::SubjectId;24 use crate::domain::subject::SubjectId;
@@ -156,6 +160,20 @@ impl Homework {
156 created_by: &UserId,160 created_by: &UserId,
157 db: &Database,161 db: &Database,
158 ) -> Result<Homework, AppError> {162 ) -> Result<Homework, AppError> {
163+ // Take the subject's reference before the row exists — the exam
164+ // question's twin ([`crate::domain::exam_question::ExamQuestion`]): the
165+ // subject delete is refused while this counter is non-zero, so the
166+ // create and the delete contend on the subject record rather than on a
167+ // cross-table count only one replica could see. A miss means the
168+ // subject is already gone, which is the 400 the web layer's pre-flight
169+ // check answers with.
170+ let counted = subject.record();
171+ if !cap::claim(&counted, SUBJECT_HOMEWORK_COUNT_FIELD, cap::UNLIMITED, db).await? {
172+ return Err(AppError::Validation(ValidationError::Invalid {
173+ field: "subject_id",
174+ reason: "subject does not exist",
175+ }));
176+ }
159 let homework = Homework {177 let homework = Homework {
160 id: HomeworkId::generate(),178 id: HomeworkId::generate(),
161 course: course.clone(),179 course: course.clone(),
@@ -167,8 +185,20 @@ impl Homework {
167 created_by: created_by.clone(),185 created_by: created_by.clone(),
168 created_at: Timestamp::now(),186 created_at: Timestamp::now(),
169 };187 };
170- let created: Option<Homework> = db.create(homework.id.record()).content(homework).await?;188+ let created: Result<Option<Homework>, AppError> = db
171- created.ok_or_else(|| AppError::Internal("failed to create homework".into()))189+ .create(homework.id.record())
190+ .content(homework)
191+ .await
192+ .map_err(AppError::from);
193+ match created {
194+ Ok(Some(homework)) => Ok(homework),
195+ other => {
196+ // Nothing landed, so the reference goes straight back.
197+ cap::release(&counted, SUBJECT_HOMEWORK_COUNT_FIELD, db).await?;
198+ other?;
199+ Err(AppError::Internal("failed to create homework".into()))
200+ }
201+ }
172 }202 }
173 203
174 pub async fn read(id: &HomeworkId, db: &Database) -> Result<Option<Homework>, AppError> {204 pub async fn read(id: &HomeworkId, db: &Database) -> Result<Option<Homework>, AppError> {
@@ -242,19 +272,6 @@ impl Homework {
242 Ok(result.take::<Vec<Homework>>(0)?)272 Ok(result.take::<Vec<Homework>>(0)?)
243 }273 }
244 274
245- /// Whether any homework still references `subject` — the subject delete
246- /// guard's question: a subject with homework can't be deleted until the
247- /// homework is re-tagged or removed. Mirrors
248- /// [`crate::domain::exam_question::ExamQuestion::any_for_subject`].
249- pub async fn any_for_subject(subject: &SubjectId, db: &Database) -> Result<bool, AppError> {
250- let mut result = db
251- .query("SELECT VALUE id FROM homework WHERE subject = $subject LIMIT 1")
252- .bind(("subject", subject.record()))
253- .await?
254- .check()?;
255- Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
256- }
257-
258 /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework.275 /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework.
259 /// Request-scoped: every parameter is `Option`, `None` meaning the PATCH276 /// Request-scoped: every parameter is `Option`, `None` meaning the PATCH
260 /// did not carry that field, so it is not written at all. Handing the277 /// did not carry that field, so it is not written at all. Handing the
@@ -279,14 +296,35 @@ impl Homework {
279 ) -> Result<Homework, AppError> {296 ) -> Result<Homework, AppError> {
280 let assigned = assigned297 let assigned = assigned
281 .map(|subset| subset.map(|users| users.iter().map(UserId::record).collect::<Vec<_>>()));298 .map(|subset| subset.map(|users| users.iter().map(UserId::record).collect::<Vec<_>>()));
282- FieldUpdate::new(self.id.record())299+ // A re-tag moves a reference: claim the new subject before the write,
300+ // release the old only after it lands, so neither is ever
301+ // under-counted (the direction that would let a subject this homework
302+ // points at be deleted). Same shape as the exam question's re-tag.
303+ let retag = subject
304+ .as_ref()
305+ .filter(|next| **next != self.subject)
306+ .map(|next| (next.record(), self.subject.record()));
307+ if let Some((next, _)) = &retag
308+ && !cap::claim(next, SUBJECT_HOMEWORK_COUNT_FIELD, cap::UNLIMITED, db).await?
309+ {
310+ return Err(AppError::Validation(ValidationError::Invalid {
311+ field: "subject_id",
312+ reason: "subject does not exist",
313+ }));
314+ }
315+ let written = FieldUpdate::new(self.id.record())
283 .set("subject", subject.map(|subject| subject.record()))316 .set("subject", subject.map(|subject| subject.record()))
284 .set("title", title)317 .set("title", title)
285 .set("description", description)318 .set("description", description)
286 .set("due_at", due_at)319 .set("due_at", due_at)
287 .set("assigned", assigned)320 .set("assigned", assigned)
288 .run::<Homework>(db)321 .run::<Homework>(db)
289- .await322+ .await;
323+ if let Some((next, previous)) = &retag {
324+ let give_back = if written.is_ok() { previous } else { next };
325+ cap::release(give_back, SUBJECT_HOMEWORK_COUNT_FIELD, db).await?;
326+ }
327+ written
290 }328 }
291 329
292 /// Delete the homework and cascade its submissions, their files, and its330 /// Delete the homework and cascade its submissions, their files, and its
@@ -302,14 +340,21 @@ impl Homework {
302 DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw);340 DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw);
303 DELETE homework_submission WHERE homework = $hw;341 DELETE homework_submission WHERE homework = $hw;
304 DELETE homework_result WHERE homework = $hw;342 DELETE homework_result WHERE homework = $hw;
305- DELETE $hw RETURN BEFORE;343+ LET $gone = (DELETE $hw RETURN BEFORE);
344+ FOR $sub IN ($gone.subject ?? []) {
345+ UPDATE $sub SET homework_count = math::max([(homework_count ?? 0) - 1, 0])
346+ };
347+ RETURN $gone;
306 COMMIT TRANSACTION;",348 COMMIT TRANSACTION;",
307 )349 )
308 .bind(("hw", self.id.record()))350 .bind(("hw", self.id.record()))
309 .await?351 .await?
310 .check()?;352 .check()?;
311- // BEGIN is slot 0; the homework's own DELETE is slot 4.353+ // The subject's reference is given back in this same transaction, off
312- let deleted: Option<Homework> = result.take::<Vec<Homework>>(4)?.into_iter().next();354+ // what the delete actually removed. Read through the trailing `RETURN`,
355+ // not a hand-counted slot — see [`crate::domain::exam::Exam::delete`].
356+ let slot = result.num_statements().saturating_sub(2);
357+ let deleted: Option<Homework> = result.take::<Vec<Homework>>(slot)?.into_iter().next();
313 deleted.ok_or(AppError::NotFound)358 deleted.ok_or(AppError::NotFound)
314 }359 }
315 }360 }
src/domain/homework_file.rsmodified+108 -18
@@ -13,12 +13,13 @@ use ulid::Ulid;
13 13
14 use crate::constant::{14 use crate::constant::{
15 HOMEWORK_FILE_TABLE, MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD,15 HOMEWORK_FILE_TABLE, MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD,
16+ SUBMISSION_OPEN_GUARD,
16 };17 };
17 use crate::database::Database;18 use crate::database::Database;
18 use crate::domain::cap;19 use crate::domain::cap;
19 use crate::domain::course::CourseId;20 use crate::domain::course::CourseId;
20 use crate::domain::homework::HomeworkId;21 use crate::domain::homework::HomeworkId;
21-use crate::domain::homework_submission::HomeworkSubmissionId;22+use crate::domain::homework_submission::{HomeworkSubmission, HomeworkSubmissionId};
22 use crate::domain::note_file::{FileContentType, FileName};23 use crate::domain::note_file::{FileContentType, FileName};
23 use crate::domain::timestamp::Timestamp;24 use crate::domain::timestamp::Timestamp;
24 use crate::error::AppError;25 use crate::error::AppError;
@@ -60,6 +61,16 @@ pub struct HomeworkFile {
60 created_at: Timestamp,61 created_at: Timestamp,
61 }62 }
62 63
64+/// What [`HomeworkFile::delete`]'s transaction reports: whether the submission
65+/// was still open (`open` = 1, the gate bit) and the row it then removed. Two
66+/// answers in one object because an empty `gone` alone cannot say whether the
67+/// delete was refused or the file had simply vanished.
68+#[derive(Debug, SurrealValue)]
69+struct DeleteOutcome {
70+ open: i64,
71+ gone: Vec<HomeworkFile>,
72+}
73+
63 impl HomeworkFile {74 impl HomeworkFile {
64 /// Assemble a row (fresh blob name generated here) without persisting it.75 /// Assemble a row (fresh blob name generated here) without persisting it.
65 /// The caller writes the blob under [`Self::get_file`] first, then calls76 /// The caller writes the blob under [`Self::get_file`] first, then calls
@@ -111,20 +122,27 @@ impl HomeworkFile {
111 }122 }
112 123
113 /// Persist the row assembled by [`Self::new`], refusing once its submission124 /// Persist the row assembled by [`Self::new`], refusing once its submission
114- /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`]. The slot is taken by125+ /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`)
115- /// [`cap::claim`] on the submission row — a conditional single-record write,126+ /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own
116- /// the only guard that holds when the racing uploads are in two replicas,127+ /// wording). Both are decided by one [`cap::claim_when`] on the submission
117- /// the same story as `NoteFile::insert`.128+ /// row — a conditional single-record write, the only guard that holds when
118- pub async fn insert(self, db: &Database) -> Result<HomeworkFile, AppError> {129+ /// the racing writers are in two replicas, the same story as
130+ /// `NoteFile::insert`. Which of the two conditions failed is read back
131+ /// afterwards, off the losing path only, and only to pick the message.
132+ pub async fn insert(self, db: &Database) -> Result<Option<HomeworkFile>, AppError> {
119 let submission = self.submission.record();133 let submission = self.submission.record();
120- if !cap::claim(134+ if !cap::claim_when(
121 &submission,135 &submission,
122 SUBMISSION_FILE_COUNT_FIELD,136 SUBMISSION_FILE_COUNT_FIELD,
123 MAX_HOMEWORK_FILES_PER_SUBMISSION as i64,137 MAX_HOMEWORK_FILES_PER_SUBMISSION as i64,
138+ SUBMISSION_OPEN_GUARD,
124 db,139 db,
125 )140 )
126 .await?141 .await?
127 {142 {
143+ if HomeworkSubmission::is_graded(&self.submission, db).await? {
144+ return Ok(None);
145+ }
128 return Err(AppError::Conflict(146 return Err(AppError::Conflict(
129 "the submission already holds the maximum of 10 files — delete one first",147 "the submission already holds the maximum of 10 files — delete one first",
130 ));148 ));
@@ -133,7 +151,7 @@ impl HomeworkFile {
133 let created: Result<Option<HomeworkFile>, _> =151 let created: Result<Option<HomeworkFile>, _> =
134 db.create(self.id.record()).content(self).await;152 db.create(self.id.record()).content(self).await;
135 match created {153 match created {
136- Ok(Some(created)) => Ok(created),154+ Ok(Some(created)) => Ok(Some(created)),
137 Ok(None) => {155 Ok(None) => {
138 cap::release(&submission, SUBMISSION_FILE_COUNT_FIELD, db).await?;156 cap::release(&submission, SUBMISSION_FILE_COUNT_FIELD, db).await?;
139 Err(AppError::Internal("failed to create homework file".into()))157 Err(AppError::Internal("failed to create homework file".into()))
@@ -242,23 +260,44 @@ impl HomeworkFile {
242 /// Delete the row and give its slot back in the same transaction. The260 /// Delete the row and give its slot back in the same transaction. The
243 /// submission survives, so its counter has to be corrected; the cascades261 /// submission survives, so its counter has to be corrected; the cascades
244 /// that delete the submission itself take the counter with it.262 /// that delete the submission itself take the counter with it.
245- pub async fn delete(self, db: &Database) -> Result<HomeworkFile, AppError> {263+ ///
264+ /// The gate is the first statement: a conditional write on the *submission*
265+ /// row — the "last touched" re-stamp a file delete owes the late flag
266+ /// anyway — carrying [`SUBMISSION_OPEN_GUARD`]. Nothing else in the
267+ /// transaction runs unless it bit, so a grade landing concurrently either
268+ /// stamps first (this delete is refused, `Ok(None)`) or stamps after (the
269+ /// file was already gone when it graded). `Err(NotFound)` still means the
270+ /// file row itself had vanished.
271+ pub async fn delete(self, db: &Database) -> Result<Option<HomeworkFile>, AppError> {
246 let mut result = db272 let mut result = db
247- .query(273+ .query(format!(
248 "BEGIN TRANSACTION;274 "BEGIN TRANSACTION;
249- LET $gone = (DELETE $id RETURN BEFORE);275+ LET $open = (UPDATE $sub SET updated_at = $now \
276+ WHERE {SUBMISSION_OPEN_GUARD} RETURN VALUE id);
277+ LET $gone = IF array::len($open) > 0 {{ (DELETE $id RETURN BEFORE) }} ELSE {{ [] }};
250 UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]);278 UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]);
251- RETURN $gone;279+ RETURN {{ open: array::len($open), gone: $gone }};
252- COMMIT TRANSACTION;",280+ COMMIT TRANSACTION;"
253- )281+ ))
254 .bind(("id", self.id.record()))282 .bind(("id", self.id.record()))
255 .bind(("sub", self.submission.record()))283 .bind(("sub", self.submission.record()))
284+ .bind(("now", Timestamp::now()))
256 .await?285 .await?
257 .check()?;286 .check()?;
258- result287+ // BEGIN is slot 0, the two LETs slots 1-2 and the counter fix slot 3;
259- .take::<Vec<HomeworkFile>>(3)?288+ // the RETURN is slot 4.
289+ let outcome: Option<DeleteOutcome> =
290+ result.take::<Vec<DeleteOutcome>>(4)?.into_iter().next();
291+ let outcome =
292+ outcome.ok_or_else(|| AppError::Internal("failed to delete homework file".into()))?;
293+ if outcome.open == 0 {
294+ return Ok(None);
295+ }
296+ outcome
297+ .gone
260 .into_iter()298 .into_iter()
261 .next()299 .next()
300+ .map(Some)
262 .ok_or(AppError::NotFound)301 .ok_or(AppError::NotFound)
263 }302 }
264 }303 }
@@ -286,6 +325,7 @@ mod tests {
286 // A real submission row, so the GC join through it resolves.325 // A real submission row, so the GC join through it resolves.
287 let submission = HomeworkSubmission::upsert(&homework, &user, None, &db)326 let submission = HomeworkSubmission::upsert(&homework, &user, None, &db)
288 .await327 .await
328+ .unwrap()
289 .unwrap();329 .unwrap();
290 let sub_a = submission.get_id().clone();330 let sub_a = submission.get_id().clone();
291 let sub_b = HomeworkSubmissionId::composite(331 let sub_b = HomeworkSubmissionId::composite(
@@ -293,7 +333,7 @@ mod tests {
293 &UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"),333 &UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"),
294 );334 );
295 335
296- let stored = a_file(&sub_a).insert(&db).await.unwrap();336+ let stored = a_file(&sub_a).insert(&db).await.unwrap().unwrap();
297 // Readable under its own submission, invisible under another.337 // Readable under its own submission, invisible under another.
298 assert!(338 assert!(
299 HomeworkFile::read_for(stored.get_id(), &sub_a, &db)339 HomeworkFile::read_for(stored.get_id(), &sub_a, &db)
@@ -342,11 +382,61 @@ mod tests {
342 382
343 // Fill to the cap, then the 11th is refused.383 // Fill to the cap, then the 11th is refused.
344 for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION {384 for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION {
345- a_file(&sub_a).insert(&db).await.unwrap();385+ a_file(&sub_a).insert(&db).await.unwrap().unwrap();
346 }386 }
347 assert!(matches!(387 assert!(matches!(
348 a_file(&sub_a).insert(&db).await,388 a_file(&sub_a).insert(&db).await,
349 Err(AppError::Conflict(_))389 Err(AppError::Conflict(_))
350 ));390 ));
351 }391 }
392+
393+ /// A graded submission takes no more files and gives none up — decided by
394+ /// the same conditional write that claims the file slot, so no
395+ /// `homework_result` read stands between the check and the write.
396+ ///
397+ /// Bite check: drop [`SUBMISSION_OPEN_GUARD`] from `insert`'s
398+ /// [`cap::claim_when`] and the add below lands; drop it from `delete`'s gate
399+ /// and the delete below succeeds.
400+ #[tokio::test]
401+ async fn a_grade_freezes_the_files_too() {
402+ use crate::domain::homework_result::{HomeworkResult, HomeworkStatus};
403+
404+ let db = crate::database::init_mem().await.unwrap();
405+ let homework = HomeworkId::from_key("01TESTHWAAAAAAAAAAAAAAAAAA");
406+ let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
407+ let submission = HomeworkSubmission::upsert(&homework, &user, None, &db)
408+ .await
409+ .unwrap()
410+ .unwrap();
411+ let sub = submission.get_id().clone();
412+ let stored = a_file(&sub).insert(&db).await.unwrap().unwrap();
413+
414+ HomeworkResult::grade(
415+ &homework,
416+ &user,
417+ HomeworkStatus::try_new("done").unwrap(),
418+ None,
419+ &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"),
420+ &db,
421+ )
422+ .await
423+ .unwrap();
424+
425+ // Neither adding nor removing an attachment: `None` is the freeze, and
426+ // the cap's own `Err(Conflict)` stays distinct from it.
427+ assert!(a_file(&sub).insert(&db).await.unwrap().is_none());
428+ assert!(stored.clone().delete(&db).await.unwrap().is_none());
429+ assert_eq!(
430+ HomeworkFile::count_for_submission(&sub, &db).await.unwrap(),
431+ 1,
432+ "the graded submission keeps exactly the files it was graded on"
433+ );
434+ // The refused add took no slot either, so un-grading gives back a
435+ // submission with room, not one that silently lost nine.
436+ HomeworkResult::remove(&homework, &user, &db).await.unwrap();
437+ for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION {
438+ a_file(&sub).insert(&db).await.unwrap().unwrap();
439+ }
440+ assert!(stored.delete(&db).await.unwrap().is_some());
441+ }
352 }442 }
src/domain/homework_result.rsmodified+59 -9
@@ -13,11 +13,12 @@
13 13
14 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};14 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
15 15
16-use crate::constant::HOMEWORK_RESULT_TABLE;16+use crate::constant::{HOMEWORK_RESULT_TABLE, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD};
17 use crate::database::Database;17 use crate::database::Database;
18 use crate::domain::course::CourseId;18 use crate::domain::course::CourseId;
19 use crate::domain::exam_result::Mark;19 use crate::domain::exam_result::Mark;
20 use crate::domain::homework::HomeworkId;20 use crate::domain::homework::HomeworkId;
21+use crate::domain::homework_submission::HomeworkSubmissionId;
21 use crate::domain::timestamp::Timestamp;22 use crate::domain::timestamp::Timestamp;
22 use crate::domain::user::UserId;23 use crate::domain::user::UserId;
23 use crate::error::{AppError, ValidationError};24 use crate::error::{AppError, ValidationError};
@@ -119,6 +120,22 @@ impl HomeworkResult {
119 /// UPSERT — concurrent grades for the same pair converge on one row instead120 /// UPSERT — concurrent grades for the same pair converge on one row instead
120 /// of racing a unique index into a 500. Grading before the due date, or121 /// of racing a unique index into a 500. Grading before the due date, or
121 /// before any submission exists, is allowed (the caller's policy call).122 /// before any submission exists, is allowed (the caller's policy call).
123+ ///
124+ /// In the same transaction the grade *stamps* the student's submission
125+ /// ([`crate::constant::SUBMISSION_GRADED_FIELD`]), which is what freezes it:
126+ /// every student-side write to that row then fails its own
127+ /// `graded_by_result = NONE` condition, with no cross-table read for a peer
128+ /// replica to slip past. A submission that does not exist yet is left alone
129+ /// — grading absent work must not conjure a hand-in (the report reads
130+ /// `submitted`/`missing`/`late` straight off that row).
131+ //
132+ // ponytail: that one case keeps a residual race — a student's *first* hand-in
133+ // committing between this grade and nothing-to-stamp lands unstamped, so a
134+ // grade of never-submitted work can end up beside an editable submission.
135+ // The web layer's pre-flight read still refuses it whenever the grade landed
136+ // first, so only a genuine collision slips through. Closing it needs a row to
137+ // stamp: either a tombstone submission every read path learns to ignore, or
138+ // moving the freeze onto a per-(homework, user) record both sides own.
122 pub async fn grade(139 pub async fn grade(
123 homework: &HomeworkId,140 homework: &HomeworkId,
124 user: &UserId,141 user: &UserId,
@@ -127,8 +144,10 @@ impl HomeworkResult {
127 graded_by: &UserId,144 graded_by: &UserId,
128 db: &Database,145 db: &Database,
129 ) -> Result<HomeworkResult, AppError> {146 ) -> Result<HomeworkResult, AppError> {
147+ let id = HomeworkResultId::composite(homework, user);
148+ let submission = HomeworkSubmissionId::composite(homework, user);
130 let result = HomeworkResult {149 let result = HomeworkResult {
131- id: HomeworkResultId::composite(homework, user),150+ id: id.clone(),
132 homework: homework.clone(),151 homework: homework.clone(),
133 user: user.clone(),152 user: user.clone(),
134 status,153 status,
@@ -136,8 +155,25 @@ impl HomeworkResult {
136 graded_by: graded_by.clone(),155 graded_by: graded_by.clone(),
137 created_at: Timestamp::now(),156 created_at: Timestamp::now(),
138 };157 };
139- let saved: Option<HomeworkResult> = db.upsert(result.id.record()).content(result).await?;158+ let mut saved = db
140- saved.ok_or_else(|| AppError::Internal("failed to record homework result".into()))159+ .query(format!(
160+ "BEGIN TRANSACTION;
161+ UPSERT $id CONTENT $row RETURN AFTER;
162+ UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = $id \
163+ WHERE {SUBMISSION_OPEN_GUARD};
164+ COMMIT TRANSACTION;"
165+ ))
166+ .bind(("id", id.record()))
167+ .bind(("sub", submission.record()))
168+ .bind(("row", result.into_value()))
169+ .await?
170+ .check()?;
171+ // BEGIN is slot 0; the result's UPSERT is slot 1, the stamp slot 2.
172+ saved
173+ .take::<Vec<HomeworkResult>>(1)?
174+ .into_iter()
175+ .next()
176+ .ok_or_else(|| AppError::Internal("failed to record homework result".into()))
141 }177 }
142 178
143 /// `user`'s grade for `homework`, if graded.179 /// `user`'s grade for `homework`, if graded.
@@ -186,19 +222,33 @@ impl HomeworkResult {
186 }222 }
187 223
188 /// Un-grade (homework, user), returning the removed row (`None` if there224 /// Un-grade (homework, user), returning the removed row (`None` if there
189- /// was none). Removing the grade unfreezes the student's submission.225+ /// was none). Removing the grade unfreezes the student's submission, so the
226+ /// stamp [`grade`](Self::grade) left on it is cleared in the same
227+ /// transaction — scoped to *this* grade's id, so it can never wipe a stamp a
228+ /// concurrent re-grade has just written.
190 pub async fn remove(229 pub async fn remove(
191 homework: &HomeworkId,230 homework: &HomeworkId,
192 user: &UserId,231 user: &UserId,
193 db: &Database,232 db: &Database,
194 ) -> Result<Option<HomeworkResult>, AppError> {233 ) -> Result<Option<HomeworkResult>, AppError> {
234+ let id = HomeworkResultId::composite(homework, user);
195 let mut result = db235 let mut result = db
196- .query("DELETE homework_result WHERE homework = $hw AND user = $usr RETURN BEFORE")236+ .query(format!(
197- .bind(("hw", homework.record()))237+ "BEGIN TRANSACTION;
198- .bind(("usr", user.record()))238+ DELETE $id RETURN BEFORE;
239+ UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = NONE \
240+ WHERE {SUBMISSION_GRADED_FIELD} = $id;
241+ COMMIT TRANSACTION;"
242+ ))
243+ .bind(("id", id.record()))
244+ .bind((
245+ "sub",
246+ HomeworkSubmissionId::composite(homework, user).record(),
247+ ))
199 .await?248 .await?
200 .check()?;249 .check()?;
201- Ok(result.take::<Vec<HomeworkResult>>(0)?.into_iter().next())250+ // BEGIN is slot 0; the grade's DELETE is slot 1, the unstamp slot 2.
251+ Ok(result.take::<Vec<HomeworkResult>>(1)?.into_iter().next())
202 }252 }
203 }253 }
204 254
src/domain/homework_submission.rsmodified+137 -26
@@ -14,7 +14,10 @@
14 14
15 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};15 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
16 16
17-use crate::constant::{HOMEWORK_SUBMISSION_TABLE, MAX_HOMEWORK_TEXT_LEN};17+use crate::constant::{
18+ HOMEWORK_SUBMISSION_TABLE, MAX_HOMEWORK_TEXT_LEN, SUBMISSION_GRADED_FIELD,
19+ SUBMISSION_OPEN_GUARD,
20+};
18 use crate::database::Database;21 use crate::database::Database;
19 use crate::domain::homework::HomeworkId;22 use crate::domain::homework::HomeworkId;
20 use crate::domain::timestamp::Timestamp;23 use crate::domain::timestamp::Timestamp;
@@ -100,9 +103,10 @@ impl HomeworkSubmission {
100 self.updated_at103 self.updated_at
101 }104 }
102 105
103- /// Create or re-stamp `user`'s submission to `homework`. `updated_at` moves106+ /// Create or re-stamp `user`'s submission to `homework`, unless a grade has
104- /// to now every time; `submitted_at` (readonly, the first-submit stamp) is107+ /// frozen it — `None` means frozen, and the caller answers 409. `updated_at`
105- /// kept on an existing row and set only on a fresh one.108+ /// moves to now every time; `submitted_at` (readonly, the first-submit stamp)
109+ /// is kept on an existing row and set only on a fresh one.
106 ///110 ///
107 /// Hand-written rather than `.content()` on purpose: `.content()` re-sends111 /// Hand-written rather than `.content()` on purpose: `.content()` re-sends
108 /// the whole row, so it would carry a `submitted_at`, and any value differing112 /// the whole row, so it would carry a `submitted_at`, and any value differing
@@ -110,20 +114,26 @@ impl HomeworkSubmission {
110 /// `submitted_at = submitted_at ?? $now` expression preserves it inside the114 /// `submitted_at = submitted_at ?? $now` expression preserves it inside the
111 /// one UPSERT statement — race-free without a lock, where a read-then-content115 /// one UPSERT statement — race-free without a lock, where a read-then-content
112 /// could let two concurrent first-submits pick different stamps and 500.116 /// could let two concurrent first-submits pick different stamps and 500.
117+ ///
118+ /// The `WHERE` is the freeze: [`SUBMISSION_OPEN_GUARD`] makes "not graded
119+ /// yet" a condition of this very write instead of a read the grading replica
120+ /// can land behind. An absent row satisfies it (the stamp is `NONE` there
121+ /// too), so a first submit still creates.
113 pub async fn upsert(122 pub async fn upsert(
114 homework: &HomeworkId,123 homework: &HomeworkId,
115 user: &UserId,124 user: &UserId,
116 text: Option<SubmissionText>,125 text: Option<SubmissionText>,
117 db: &Database,126 db: &Database,
118- ) -> Result<HomeworkSubmission, AppError> {127+ ) -> Result<Option<HomeworkSubmission>, AppError> {
119 let id = HomeworkSubmissionId::composite(homework, user);128 let id = HomeworkSubmissionId::composite(homework, user);
120 let now = Timestamp::now();129 let now = Timestamp::now();
121 let text = text.map(|text| text.as_str().to_string());130 let text = text.map(|text| text.as_str().to_string());
122 let mut saved = db131 let mut saved = db
123- .query(132+ .query(format!(
124 "UPSERT $id SET homework = $hw, user = $usr, text = $text, \133 "UPSERT $id SET homework = $hw, user = $usr, text = $text, \
125- updated_at = $now, submitted_at = submitted_at ?? $now RETURN AFTER",134+ updated_at = $now, submitted_at = submitted_at ?? $now \
126- )135+ WHERE {SUBMISSION_OPEN_GUARD} RETURN AFTER"
136+ ))
127 .bind(("id", id.record()))137 .bind(("id", id.record()))
128 .bind(("hw", homework.record()))138 .bind(("hw", homework.record()))
129 .bind(("usr", user.record()))139 .bind(("usr", user.record()))
@@ -131,11 +141,7 @@ impl HomeworkSubmission {
131 .bind(("now", now))141 .bind(("now", now))
132 .await?142 .await?
133 .check()?;143 .check()?;
134- saved144+ Ok(saved.take::<Vec<HomeworkSubmission>>(0)?.into_iter().next())
135- .take::<Vec<HomeworkSubmission>>(0)?
136- .into_iter()
137- .next()
138- .ok_or_else(|| AppError::Internal("failed to save homework submission".into()))
139 }145 }
140 146
141 /// Re-stamp a submission's `updated_at` to now, leaving its text and files147 /// Re-stamp a submission's `updated_at` to now, leaving its text and files
@@ -163,6 +169,20 @@ impl HomeworkSubmission {
163 .ok_or(AppError::NotFound)169 .ok_or(AppError::NotFound)
164 }170 }
165 171
172+ /// Whether a grade has frozen this submission. Only ever read to tell two
173+ /// refusals apart *after* a conditional write has already refused one — the
174+ /// stamp on the row, never this read, is what decides.
175+ pub async fn is_graded(id: &HomeworkSubmissionId, db: &Database) -> Result<bool, AppError> {
176+ let mut result = db
177+ .query(format!(
178+ "SELECT VALUE id FROM $id WHERE {SUBMISSION_GRADED_FIELD} != NONE"
179+ ))
180+ .bind(("id", id.record()))
181+ .await?
182+ .check()?;
183+ Ok(!result.take::<Vec<HomeworkSubmissionId>>(0)?.is_empty())
184+ }
185+
166 /// `user`'s submission to `homework`, if they have one.186 /// `user`'s submission to `homework`, if they have one.
167 pub async fn read_for(187 pub async fn read_for(
168 homework: &HomeworkId,188 homework: &HomeworkId,
@@ -192,25 +212,27 @@ impl HomeworkSubmission {
192 /// can't leave a file pointing at a vanished submission. The file *blobs*212 /// can't leave a file pointing at a vanished submission. The file *blobs*
193 /// are the web layer's to unlink: it lists them213 /// are the web layer's to unlink: it lists them
194 /// ([`crate::domain::homework_file::HomeworkFile::list_for_submission`])214 /// ([`crate::domain::homework_file::HomeworkFile::list_for_submission`])
195- /// before calling this. The caller has already refused the delete if the215+ /// before calling this. `None` means a grade froze the row (the caller
196- /// submission is graded (a result exists).216+ /// answers 409): the submission's own delete carries
197- pub async fn delete(self, db: &Database) -> Result<HomeworkSubmission, AppError> {217+ /// [`SUBMISSION_OPEN_GUARD`], and the file wipe is conditional on it having
218+ /// bitten, so a refused delete leaves the children standing too.
219+ pub async fn delete(self, db: &Database) -> Result<Option<HomeworkSubmission>, AppError> {
198 let mut result = db220 let mut result = db
199- .query(221+ .query(format!(
200 "BEGIN TRANSACTION;222 "BEGIN TRANSACTION;
201- DELETE homework_file WHERE submission = $sub;223+ LET $gone = (DELETE $sub WHERE {SUBMISSION_OPEN_GUARD} RETURN BEFORE);
202- DELETE $sub RETURN BEFORE;224+ IF array::len($gone) > 0 {{ DELETE homework_file WHERE submission = $sub }};
203- COMMIT TRANSACTION;",225+ RETURN $gone;
204- )226+ COMMIT TRANSACTION;"
227+ ))
205 .bind(("sub", self.id.record()))228 .bind(("sub", self.id.record()))
206 .await?229 .await?
207 .check()?;230 .check()?;
208- // BEGIN is slot 0, the file wipe slot 1; the submission's DELETE is slot 2.231+ // BEGIN is slot 0, the LET slot 1 and the IF slot 2; the RETURN is slot 3.
209- let deleted: Option<HomeworkSubmission> = result232+ Ok(result
210- .take::<Vec<HomeworkSubmission>>(2)?233+ .take::<Vec<HomeworkSubmission>>(3)?
211 .into_iter()234 .into_iter()
212- .next();235+ .next())
213- deleted.ok_or(AppError::NotFound)
214 }236 }
215 }237 }
216 238
@@ -238,11 +260,13 @@ mod tests {
238 &db,260 &db,
239 )261 )
240 .await262 .await
263+ .unwrap()
241 .unwrap();264 .unwrap();
242 // A re-submit lands on the same row: submitted_at (the first hand-in)265 // A re-submit lands on the same row: submitted_at (the first hand-in)
243 // pinned, updated_at moves forward, and the text can be cleared.266 // pinned, updated_at moves forward, and the text can be cleared.
244 let second = HomeworkSubmission::upsert(&homework, &user, None, &db)267 let second = HomeworkSubmission::upsert(&homework, &user, None, &db)
245 .await268 .await
269+ .unwrap()
246 .unwrap();270 .unwrap();
247 assert_eq!(first.get_id(), second.get_id());271 assert_eq!(first.get_id(), second.get_id());
248 assert_eq!(first.get_submitted_at(), second.get_submitted_at());272 assert_eq!(first.get_submitted_at(), second.get_submitted_at());
@@ -258,6 +282,92 @@ mod tests {
258 );282 );
259 }283 }
260 284
285+ /// The freeze, as stored state rather than as a race: the grade stamps the
286+ /// submission row, and from then on the submission's own writes fail their
287+ /// condition — no read of `homework_result` involved, which is what makes it
288+ /// hold when the grader is in the other replica. Un-grading clears the stamp
289+ /// and the row is writable again.
290+ ///
291+ /// Bite check: drop `WHERE graded_by_result = NONE` from
292+ /// [`HomeworkSubmission::upsert`] and the "version B" upsert below comes
293+ /// back `Some` — the exact swap this guards against.
294+ #[tokio::test]
295+ async fn a_grade_freezes_the_submission_row_itself() {
296+ let db = crate::database::init_mem().await.unwrap();
297+ let homework = HomeworkId::from_key("01TESTHWAAAAAAAAAAAAAAAAAA");
298+ let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
299+ let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
300+ let graded = |value| {
301+ let text = SubmissionText::try_new(value).unwrap();
302+ HomeworkSubmission::upsert(&homework, &user, Some(text), &db)
303+ };
304+
305+ let version_a = graded("version A").await.unwrap().unwrap();
306+ assert!(
307+ !HomeworkSubmission::is_graded(version_a.get_id(), &db)
308+ .await
309+ .unwrap()
310+ );
311+
312+ crate::domain::homework_result::HomeworkResult::grade(
313+ &homework,
314+ &user,
315+ crate::domain::homework_result::HomeworkStatus::try_new("done").unwrap(),
316+ None,
317+ &teacher,
318+ &db,
319+ )
320+ .await
321+ .unwrap();
322+ assert!(
323+ HomeworkSubmission::is_graded(version_a.get_id(), &db)
324+ .await
325+ .unwrap()
326+ );
327+
328+ // The swap the teacher would never see: refused, and the stored text is
329+ // still the version that was graded.
330+ assert!(graded("version B").await.unwrap().is_none());
331+ assert_eq!(
332+ HomeworkSubmission::read_for(&homework, &user, &db)
333+ .await
334+ .unwrap()
335+ .and_then(|row| row.get_text().map(|text| text.as_str().to_string())),
336+ Some("version A".to_string())
337+ );
338+ // ... and so is withdrawing it wholesale.
339+ let frozen = HomeworkSubmission::read_for(&homework, &user, &db)
340+ .await
341+ .unwrap()
342+ .unwrap();
343+ assert!(frozen.delete(&db).await.unwrap().is_none());
344+ assert!(
345+ HomeworkSubmission::read_for(&homework, &user, &db)
346+ .await
347+ .unwrap()
348+ .is_some()
349+ );
350+
351+ // Un-grading unfreezes it, stamp and all.
352+ crate::domain::homework_result::HomeworkResult::remove(&homework, &user, &db)
353+ .await
354+ .unwrap();
355+ assert!(
356+ !HomeworkSubmission::is_graded(version_a.get_id(), &db)
357+ .await
358+ .unwrap()
359+ );
360+ let reopened = graded("version B").await.unwrap().unwrap();
361+ assert_eq!(
362+ reopened.get_text().map(SubmissionText::as_str),
363+ Some("version B")
364+ );
365+ // The two-stamp lateness rule is untouched by any of it: the first
366+ // hand-in is still the first hand-in.
367+ assert_eq!(reopened.get_submitted_at(), version_a.get_submitted_at());
368+ assert!(reopened.get_updated_at() >= version_a.get_updated_at());
369+ }
370+
261 #[tokio::test]371 #[tokio::test]
262 async fn touch_moves_updated_at_but_not_submitted_at_or_text() {372 async fn touch_moves_updated_at_but_not_submitted_at_or_text() {
263 let db = crate::database::init_mem().await.unwrap();373 let db = crate::database::init_mem().await.unwrap();
@@ -271,6 +381,7 @@ mod tests {
271 &db,381 &db,
272 )382 )
273 .await383 .await
384+ .unwrap()
274 .unwrap();385 .unwrap();
275 // A file add/delete touches the submission: updated_at moves (never386 // A file add/delete touches the submission: updated_at moves (never
276 // backwards), while the first-submit stamp and the text stay put.387 // backwards), while the first-submit stamp and the text stay put.
src/domain/meal_booking.rsmodified+480 -109
@@ -10,21 +10,30 @@
10 //! auditable against the money it moved. Only `booked` rows count against10 //! auditable against the money it moved. Only `booked` rows count against
11 //! the menu's capacity, which is what makes the seat genuinely free again —11 //! the menu's capacity, which is what makes the seat genuinely free again —
12 //! and re-booking is the same UPSERT flipping it back.12 //! and re-booking is the same UPSERT flipping it back.
13-//! - **The capacity check runs under [`MENU_LOCK`]**, the lock that already13+//! - **Capacity is the menu's `seats_booked` counter**, claimed by a
14-//! serializes everything counting rows against one menu. Count-then-write is14+//! conditional single-record write ([`cap`]). Counting the rows instead is
15-//! write-skew: SurrealDB's transactions do not conflict-check a cross-record15+//! write-skew — SurrealDB does not conflict-check a cross-record count
16-//! count against a concurrent insert, so an unlocked check over-admits.16+//! against a concurrent insert — and a process-wide lock around that count
17-//! - **The seat and its money move together, inside that lock.** Booking17+//! only holds inside one replica, which the school no longer runs one of.
18-//! charges and cancelling reverses right here, not in the web layer after the18+//! Cancelling gives the seat back in the *same transaction* as the flip.
19-//! lock was dropped — a seam between the two let concurrent `POST`s bill one19+//! - **The price is claimed, not just read.** The seat is taken at the menu
20-//! seat twice. The lock stays a *leaf*: nothing below it takes another.20+//! revision the price was read at, in the same transaction as the row
21+//! ([`MealBooking::claim_and_place`]), so a dish re-priced mid-booking loses
22+//! the claim and the booking re-reads both. A seat can only ever be billed a
23+//! price its menu genuinely carried.
24+//! - **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 let
26+//! concurrent `POST`s bill one seat twice.
21 27
22 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};28 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
23 29
24-use crate::constant::MEAL_BOOKING_TABLE;30+use crate::constant::{
25-use crate::database::Database;31+ CAS_UPDATE_RETRIES, MEAL_BOOKING_TABLE, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD,
32+};
33+use crate::database::{Database, lost_the_race};
34+use crate::domain::cap::{self, Claimed};
26 use crate::domain::meal_ledger::{LedgerAmount, MealLedger};35 use crate::domain::meal_ledger::{LedgerAmount, MealLedger};
27-use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot};36+use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot};
28 use crate::domain::page::PagedList;37 use crate::domain::page::PagedList;
29 use crate::domain::settings::{MealSlotDef, Settings};38 use crate::domain::settings::{MealSlotDef, Settings};
30 use crate::domain::timestamp::Timestamp;39 use crate::domain::timestamp::Timestamp;
@@ -140,24 +149,23 @@ impl MealBooking {
140 }149 }
141 150
142 /// Book (idempotently) `student` onto `menu` **and bill the seat**. Already151 /// Book (idempotently) `student` onto `menu` **and bill the seat**. Already
143- /// booked is returned as-is; a cancelled row is revived by the same UPSERT,152+ /// booked is returned as-is, claiming nothing; a cancelled row is revived as
144- /// as a fresh attempt at the current `price`. When the menu carries a153+ /// a fresh attempt at the current price. A full menu refuses the seat (409),
145- /// capacity, a full one refuses new seats (409) — the whole154+ /// decided by the counter's own `WHERE` rather than by a count this process
146- /// check-then-write runs under [`MENU_LOCK`], and the cap is re-derived155+ /// took a moment ago.
147- /// from a fresh menu read inside it, since neither the transaction model
148- /// nor a caller-supplied menu survives a concurrent capacity PATCH.
149 ///156 ///
150- /// The price is snapshotted **inside that same lock**, not handed in by the157+ /// The price is read from the menu and then **claimed with it**: the seat is
151- /// web layer: dish writes take the lock too, so the sum frozen onto the row158+ /// only taken while the menu still stands at the revision the price was read
152- /// is the menu as it stood the instant the seat was taken. Snapshotted159+ /// at, so a dish added, re-priced or removed in that gap loses the claim and
153- /// outside it, a dish landing in the gap was stored as `None` = "was free160+ /// the whole decision is made again on fresh figures. What is frozen onto
154- /// then" — and no repeat `POST` ever heals that, since a held seat is161+ /// the row is therefore always a price the menu genuinely carried at the
155- /// returned as-is.162+ /// instant the seat was taken — the guarantee a lock could only give inside
163+ /// one replica.
156 ///164 ///
157- /// The charge is appended inside the lock too, keyed by (seat, attempt):165+ /// The charge is appended after, keyed by (seat, attempt): eight concurrent
158- /// eight concurrent `POST`s of one seat hold one seat and write one charge166+ /// `POST`s of one seat hold one seat and write one charge line. The price is
159- /// line. The price is `None` when the menu is free, and that `None` is167+ /// `None` when the menu is free, and that `None` is stored, so a dish added
160- /// stored, so a dish added later never bills a seat retroactively.168+ /// later never bills a seat retroactively.
161 ///169 ///
162 /// `cutoff` is the school's one meal deadline (see [`MealCutoff`]): once170 /// `cutoff` is the school's one meal deadline (see [`MealCutoff`]): once
163 /// serving time is that close, the seat is fixed either way.171 /// serving time is that close, the seat is fixed either way.
@@ -168,60 +176,167 @@ impl MealBooking {
168 cutoff: &MealCutoff,176 cutoff: &MealCutoff,
169 db: &Database,177 db: &Database,
170 ) -> Result<MealBooking, AppError> {178 ) -> Result<MealBooking, AppError> {
171- let _guard = MENU_LOCK.lock().await;
172- let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?;
173- check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?;
174- // Before the seat: an unchargeable menu (dishes summing past the cap)
175- // must refuse the booking outright, never leave a booked-but-unbilled
176- // row behind.
177- let price = MealLedger::price_snapshot(menu, db).await?;
178 let id = MealBookingId::composite(menu, student);179 let id = MealBookingId::composite(menu, student);
179- let existing: Option<MealBooking> = db.select(id.record()).await?;180+ let seats = menu.record();
180- let booking = match existing {181+ for _ in 0..CAS_UPDATE_RETRIES {
182+ let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?;
183+ 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?;
181 // The seat is already held: same attempt, same price it was taken189 // The seat is already held: same attempt, same price it was taken
182- // at. Today's menu price bills nobody who booked yesterday's.190+ // at. Today's menu price bills nobody who booked yesterday's. No
183- Some(held) if held.status == MealBookingStatus::Booked => held,191+ // seat is claimed, so a double-click cannot count two.
184- existing => {192+ if let Some(held) = existing
185- if let Some(capacity) = fresh.get_capacity()193+ .clone()
186- && Self::list_live_for_menu(menu, db).await?.len() as i64 >= capacity194+ .filter(|row| row.status == MealBookingStatus::Booked)
187- {195+ {
188- return Err(AppError::Conflict("the menu is fully booked"));196+ MealLedger::charge_booking(&held, booked_by, db).await?;
189- }197+ return Ok(held);
190- let booking = MealBooking {
191- id,
192- menu: menu.clone(),
193- student: student.clone(),
194- // `booked_by` and `created_at` are READONLY columns: a
195- // revived row keeps whoever opened the seat, and when.
196- booked_by: existing
197- .as_ref()
198- .map_or_else(|| booked_by.clone(), |row| row.booked_by.clone()),
199- status: MealBookingStatus::Booked,
200- attempt: existing.as_ref().map_or(1, |row| row.attempt + 1),
201- price_minor: price,
202- cancelled_at: None,
203- created_at: existing
204- .as_ref()
205- .map_or_else(Timestamp::now, |row| row.created_at),
206- };
207- let saved: Option<MealBooking> =
208- db.upsert(booking.id.record()).content(booking).await?;
209- saved.ok_or_else(|| AppError::Internal("failed to book the meal".into()))?
210 }198 }
211- };199+ let fresh_row = MealBooking {
212- // Writes nothing when this attempt is already billed, so the repeat200+ id: id.clone(),
213- // POST above costs nothing and a charge that failed once self-heals.201+ menu: menu.clone(),
214- MealLedger::charge_booking(&booking, booked_by, db).await?;202+ student: student.clone(),
215- Ok(booking)203+ booked_by: booked_by.clone(),
204+ status: MealBookingStatus::Booked,
205+ attempt: 1,
206+ price_minor: price,
207+ cancelled_at: None,
208+ created_at: Timestamp::now(),
209+ };
210+ let booking = match Self::claim_and_place(
211+ &seats,
212+ fresh.get_capacity().unwrap_or(cap::UNLIMITED),
213+ fresh.get_version(),
214+ &fresh_row,
215+ price,
216+ db,
217+ )
218+ .await?
219+ {
220+ Claimed::Made(booking) => booking,
221+ // Another `POST` of this very pair placed the row first, and it
222+ // owed no second seat: this caller never took one (the whole
223+ // transaction rolled back), so the winner's row is the answer.
224+ Claimed::Duplicate => Self::read(&id, db).await?.ok_or(AppError::NotFound)?,
225+ // Full, moved, or gone — one `WHERE` refused all three, so the
226+ // reason is re-read rather than guessed. A moved menu is not a
227+ // refusal: the price above is stale, so price and seat are
228+ // taken again together.
229+ Claimed::Full => match Menu::read(menu, db).await? {
230+ None => return Err(AppError::NotFound),
231+ Some(now) if now.get_version() != fresh.get_version() => continue,
232+ Some(_) => return Err(AppError::Conflict("the menu is fully booked")),
233+ },
234+ };
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+ }
240+ Err(AppError::Conflict(
241+ "the menu kept changing underneath this booking",
242+ ))
243+ }
244+
245+ /// Take the seat **and** place the row in one transaction, at the menu
246+ /// revision the price was read at.
247+ ///
248+ /// The seat and the row cannot be two steps. The id is the (menu, student)
249+ /// pair, so two `POST`s of the same seat both find no row and both claim —
250+ /// and on a tight cap the second is then told "full" for a seat it never
251+ /// owed, while the winner's row may not even be visible yet. Here the
252+ /// duplicate `CREATE` aborts the transaction, which takes its increment with
253+ /// it: the counter never counts a row that does not exist, and a loser is
254+ /// answered with the winner's booking instead of a refusal. Same shape as
255+ /// [`cap::claim_and_create`], with the revision guard and the revival of a
256+ /// cancelled row that the general form does not carry.
257+ ///
258+ /// A cancelled row is revived in place (a fresh attempt at `price`) rather
259+ /// than recreated: `booked_by` and `created_at` are READONLY history — who
260+ /// opened the seat, and when.
261+ async fn claim_and_place(
262+ seats: &RecordId,
263+ cap: i64,
264+ seen: i64,
265+ row: &MealBooking,
266+ price: Option<LedgerAmount>,
267+ db: &Database,
268+ ) -> Result<Claimed<MealBooking>, AppError> {
269+ // Parenthesized `??` throughout: `a ?? 0 = $seen` binds the wrong way.
270+ let sql = format!(
271+ "BEGIN TRANSACTION;
272+ LET $held = (SELECT VALUE id FROM $id WHERE status = 'booked');
273+ IF array::len($held) > 0 {{ THROW 'held' }};
274+ LET $seat = (UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = \
275+ ({MENU_SEAT_COUNT_FIELD} ?? 0) + 1 \
276+ WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) < $cap \
277+ AND ({MENU_VERSION_FIELD} ?? 0) = $seen RETURN VALUE id);
278+ IF array::len($seat) = 0 {{ THROW 'no_seat' }};
279+ LET $revived = (UPDATE $id SET status = 'booked', attempt = attempt + 1, \
280+ price_minor = $price, cancelled_at = NONE \
281+ WHERE status = 'cancelled' RETURN AFTER);
282+ IF array::len($revived) = 0 {{ CREATE $id CONTENT $row }};
283+ RETURN SELECT * FROM ONLY $id;
284+ COMMIT TRANSACTION;"
285+ );
286+ for _ in 0..CAS_UPDATE_RETRIES {
287+ let mut result = match db
288+ .query(sql.as_str())
289+ .bind(("menu", seats.clone()))
290+ .bind(("cap", cap))
291+ .bind(("seen", seen))
292+ .bind(("id", row.id.record()))
293+ .bind(("price", price))
294+ .bind(("row", row.clone()))
295+ .await
296+ {
297+ Ok(result) => result,
298+ Err(err) if lost_the_race(&err) => continue,
299+ Err(err) => return Err(err.into()),
300+ };
301+ // An aborted transaction errors *every* slot, most with a generic
302+ // "not executed" — only the failing slot says why, so scan them all.
303+ let mut errors = result.take_errors();
304+ if errors
305+ .values()
306+ .any(|error| error.to_string().contains("no_seat"))
307+ {
308+ return Ok(Claimed::Full);
309+ }
310+ if errors
311+ .values()
312+ .any(|error| error.to_string().contains("held") || error.is_already_exists())
313+ {
314+ return Ok(Claimed::Duplicate);
315+ }
316+ if errors.values().any(lost_the_race) {
317+ continue;
318+ }
319+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
320+ return Err(error.into());
321+ }
322+ // Slots count BEGIN, three LETs and three IFs: the RETURN is slot 7.
323+ return match result.take::<Option<MealBooking>>(7)? {
324+ Some(placed) => Ok(Claimed::Made(placed)),
325+ None => Err(AppError::Internal("failed to book the meal".into())),
326+ };
327+ }
328+ Err(AppError::Conflict(
329+ "the menu kept changing underneath this booking",
330+ ))
216 }331 }
217 332
218 /// Free the seat: flip to `cancelled`, stamp the moment, **and give the333 /// Free the seat: flip to `cancelled`, stamp the moment, **and give the
219 /// money back**. Refused (409) only once the cutoff has passed.334 /// money back**. Refused (409) only once the cutoff has passed.
220 ///335 ///
221- /// Under [`MENU_LOCK`] like [`Self::book`], and the row is re-read inside336+ /// The row is re-read here and the flip is conditional on it still being
222- /// it: the caller's copy may predate a concurrent re-book, and cancelling a337+ /// `booked`: the caller's copy may predate a concurrent re-book, and
223- /// stale attempt would strand that attempt's charge forever. The reversal338+ /// cancelling a stale attempt would strand that attempt's charge forever.
224- /// is keyed to the attempt, so a retried cancel refunds exactly once.339+ /// The reversal is keyed to the attempt, so a retried cancel refunds once.
225 ///340 ///
226 /// **Idempotent, and that is what makes the refund recoverable.** The flip341 /// **Idempotent, and that is what makes the refund recoverable.** The flip
227 /// and the reversal are two writes; a handler future dropped between them342 /// and the reversal are two writes; a handler future dropped between them
@@ -239,7 +354,6 @@ impl MealBooking {
239 recorded_by: &UserId,354 recorded_by: &UserId,
240 db: &Database,355 db: &Database,
241 ) -> Result<MealBooking, AppError> {356 ) -> Result<MealBooking, AppError> {
242- let _guard = MENU_LOCK.lock().await;
243 let fresh = Self::read(&self.id, db).await?.ok_or(AppError::NotFound)?;357 let fresh = Self::read(&self.id, db).await?.ok_or(AppError::NotFound)?;
244 if fresh.status == MealBookingStatus::Cancelled {358 if fresh.status == MealBookingStatus::Cancelled {
245 MealLedger::reverse_booking(&fresh, recorded_by, db).await?;359 MealLedger::reverse_booking(&fresh, recorded_by, db).await?;
@@ -249,19 +363,62 @@ impl MealBooking {
249 .await?363 .await?
250 .ok_or(AppError::NotFound)?;364 .ok_or(AppError::NotFound)?;
251 check_cutoff(menu.get_date(), menu.get_slot(), cutoff)?;365 check_cutoff(menu.get_date(), menu.get_slot(), cutoff)?;
252- let cancelled = MealBooking {366+ // Lost the flip to a concurrent cancel: its row is the truth, and the
253- status: MealBookingStatus::Cancelled,367+ // reversal replay below heals whatever it left unfinished.
254- cancelled_at: Some(Timestamp::now()),368+ let saved = match Self::release_seat(&fresh, db).await? {
255- ..fresh369+ Some(cancelled) => cancelled,
370+ None => Self::read(&self.id, db).await?.ok_or(AppError::NotFound)?,
256 };371 };
257- let saved: Option<MealBooking> =
258- db.upsert(cancelled.id.record()).content(cancelled).await?;
259- let saved =
260- saved.ok_or_else(|| AppError::Internal("failed to cancel the booking".into()))?;
261 MealLedger::reverse_booking(&saved, recorded_by, db).await?;372 MealLedger::reverse_booking(&saved, recorded_by, db).await?;
262 Ok(saved)373 Ok(saved)
263 }374 }
264 375
376+ /// 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 ran
378+ /// without the flip frees a seat still held, and a flip without the
379+ /// decrement locks a seat nothing can ever release. The counter follows the
380+ /// flip's own result (`array::len`), so a row already cancelled — by a
381+ /// racing cancel, or by this call retried — decrements nothing.
382+ ///
383+ /// `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 on
385+ /// it, and that contention is the cap working, not an error.
386+ async fn release_seat(
387+ booked: &MealBooking,
388+ db: &Database,
389+ ) -> Result<Option<MealBooking>, AppError> {
390+ for _ in 0..CAS_UPDATE_RETRIES {
391+ let attempted = async {
392+ let mut result = db
393+ .query(format!(
394+ "BEGIN TRANSACTION;
395+ LET $flipped = (UPDATE $id SET status = 'cancelled', \
396+ cancelled_at = $now WHERE status = 'booked' RETURN AFTER);
397+ UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = math::max([\
398+ ({MENU_SEAT_COUNT_FIELD} ?? 0) - array::len($flipped), 0]);
399+ RETURN $flipped;
400+ COMMIT TRANSACTION;"
401+ ))
402+ .bind(("id", booked.id.record()))
403+ .bind(("menu", booked.menu.record()))
404+ .bind(("now", Timestamp::now()))
405+ .await?
406+ .check()?;
407+ // Slots count BEGIN and the LET: the RETURN is slot 3.
408+ result.take::<Vec<MealBooking>>(3)
409+ }
410+ .await;
411+ match attempted {
412+ Ok(rows) => return Ok(rows.into_iter().next()),
413+ Err(err) if lost_the_race(&err) => {}
414+ Err(err) => return Err(err.into()),
415+ }
416+ }
417+ Err(AppError::Conflict(
418+ "the menu kept changing underneath this cancellation",
419+ ))
420+ }
421+
265 pub async fn read(id: &MealBookingId, db: &Database) -> Result<Option<MealBooking>, AppError> {422 pub async fn read(id: &MealBookingId, db: &Database) -> Result<Option<MealBooking>, AppError> {
266 Ok(db.select(id.record()).await?)423 Ok(db.select(id.record()).await?)
267 }424 }
@@ -282,33 +439,6 @@ impl MealBooking {
282 .await439 .await
283 }440 }
284 441
285- /// The seats actually held — the capacity count.
286- pub async fn list_live_for_menu(
287- menu: &MenuId,
288- db: &Database,
289- ) -> Result<Vec<MealBooking>, AppError> {
290- let mut result = db
291- .query("SELECT * FROM meal_booking WHERE menu = $menu AND status = 'booked'")
292- .bind(("menu", menu.record()))
293- .await?
294- .check()?;
295- Ok(result.take::<Vec<MealBooking>>(0)?)
296- }
297-
298- /// True iff a seat on the menu is still held — the menu delete guard.
299- /// Callers hold [`MENU_LOCK`] so a booking cannot slip in behind it.
300- pub async fn any_live_for_menu(menu: &MenuId, db: &Database) -> Result<bool, AppError> {
301- let mut result = db
302- .query(
303- "SELECT VALUE id FROM meal_booking \
304- WHERE menu = $menu AND status = 'booked' LIMIT 1",
305- )
306- .bind(("menu", menu.record()))
307- .await?
308- .check()?;
309- Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
310- }
311-
312 /// Every seat held for one of `students`, newest first — a caller's own442 /// Every seat held for one of `students`, newest first — a caller's own
313 /// list is themselves plus whoever they hold a *live* parent link to.443 /// list is themselves plus whoever they hold a *live* parent link to.
314 ///444 ///
@@ -411,6 +541,7 @@ mod tests {
411 use surrealdb::types::Value;541 use surrealdb::types::Value;
412 542
413 use super::*;543 use super::*;
544+ use crate::domain::menu_dish::{DishName, DishPrice, DishTags, MenuDish};
414 545
415 /// The `status` column is `TYPE string`: an object-wrapped enum would be546 /// The `status` column is `TYPE string`: an object-wrapped enum would be
416 /// rejected on write, and the `status = 'booked'` capacity count would547 /// rejected on write, and the `status = 'booked'` capacity count would
@@ -424,6 +555,246 @@ mod tests {
424 }555 }
425 }556 }
426 557
558+ /// A published menu on a fresh in-memory database, plus a student.
559+ async fn menu(capacity: Option<i64>) -> (Database, MenuId) {
560+ let db = crate::database::init_mem().await.unwrap();
561+ let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()];
562+ let menu = Menu::create(
563+ MenuDate::try_new("2026-09-14").unwrap(),
564+ MenuSlot::try_new("lunch", &slots).unwrap(),
565+ capacity,
566+ &UserId::generate(),
567+ &db,
568+ )
569+ .await
570+ .unwrap();
571+ (db, menu.get_id().clone())
572+ }
573+
574+ /// The stored counter, absent reading as zero — the number the cap's
575+ /// `WHERE` actually compares, not one recomputed from the rows.
576+ async fn seats(menu: &MenuId, db: &Database) -> i64 {
577+ let mut result = db
578+ .query("SELECT VALUE seats_booked FROM $id")
579+ .bind(("id", menu.record()))
580+ .await
581+ .unwrap()
582+ .check()
583+ .unwrap();
584+ result
585+ .take::<Vec<Option<i64>>>(0)
586+ .unwrap()
587+ .into_iter()
588+ .next()
589+ .flatten()
590+ .unwrap_or(0)
591+ }
592+
593+ async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish {
594+ MenuDish::create(
595+ menu,
596+ DishName::try_new("çorba").unwrap(),
597+ None,
598+ DishPrice::try_new(price).unwrap(),
599+ DishTags::try_new(&[], &[]).unwrap(),
600+ db,
601+ )
602+ .await
603+ .unwrap()
604+ }
605+
606+ /// The counter is the cap's authority, so it has to track the seats exactly:
607+ /// a repeat booking must not count twice, a cancel must hand its seat back
608+ /// in the same breath as the flip, and a second cancel must not hand back a
609+ /// seat that was already returned (which would open the cap by one forever).
610+ #[tokio::test]
611+ async fn the_seat_counter_follows_the_seats_it_guards() {
612+ let (db, menu) = menu(Some(1)).await;
613+ let (ali, veli) = (UserId::generate(), UserId::generate());
614+ let open = MealCutoff::default();
615+
616+ let booking = MealBooking::book(&menu, &ali, &ali, &open, &db)
617+ .await
618+ .unwrap();
619+ assert_eq!(seats(&menu, &db).await, 1);
620+ // The same seat again is a no-op, not a second claim.
621+ MealBooking::book(&menu, &ali, &ali, &open, &db)
622+ .await
623+ .unwrap();
624+ assert_eq!(seats(&menu, &db).await, 1);
625+ // …and the cap bites for anyone else while it is held.
626+ assert!(matches!(
627+ MealBooking::book(&menu, &veli, &veli, &open, &db).await,
628+ Err(AppError::Conflict(_))
629+ ));
630+
631+ let cancelled = booking.cancel(&open, &ali, &db).await.unwrap();
632+ assert_eq!(cancelled.get_status(), MealBookingStatus::Cancelled);
633+ assert_eq!(seats(&menu, &db).await, 0);
634+ // Cancelling again is idempotent all the way down to the counter.
635+ cancelled.cancel(&open, &ali, &db).await.unwrap();
636+ assert_eq!(seats(&menu, &db).await, 0);
637+
638+ // The freed seat is real, and taking it again counts once.
639+ let revived = MealBooking::book(&menu, &veli, &veli, &open, &db)
640+ .await
641+ .unwrap();
642+ assert_eq!(revived.get_attempt(), 1);
643+ assert_eq!(seats(&menu, &db).await, 1);
644+ }
645+
646+ /// A menu whose row is gone or whose seats are held refuses its own delete,
647+ /// in the `WHERE` rather than in a read the delete then trusts.
648+ #[tokio::test]
649+ async fn a_held_seat_refuses_the_menu_delete() {
650+ let (db, id) = menu(None).await;
651+ let ali = UserId::generate();
652+ let booking = MealBooking::book(&id, &ali, &ali, &MealCutoff::default(), &db)
653+ .await
654+ .unwrap();
655+ let row = Menu::read(&id, &db).await.unwrap().unwrap();
656+ assert!(matches!(
657+ row.clone().delete(&db).await,
658+ Err(AppError::Conflict(_))
659+ ));
660+ booking
661+ .cancel(&MealCutoff::default(), &ali, &db)
662+ .await
663+ .unwrap();
664+ assert!(row.delete(&db).await.is_ok());
665+ }
666+
667+ /// The price a seat is billed must be one the menu carried *at the moment
668+ /// the seat was taken*. The claim carries the revision the price was read
669+ /// at, so a dish written in between refuses it — this is that refusal,
670+ /// driven by hand because no single-process interleaving can produce it.
671+ #[tokio::test]
672+ async fn a_seat_cannot_be_claimed_at_a_revision_the_menu_has_left() {
673+ let (db, menu) = menu(None).await;
674+ let ali = UserId::generate();
675+ let seen = Menu::read(&menu, &db).await.unwrap().unwrap().get_version();
676+ // A dish lands: the price a booking read a moment ago is now stale.
677+ add_dish(&menu, 1_000, &db).await;
678+ let row = MealBooking {
679+ id: MealBookingId::composite(&menu, &ali),
680+ menu: menu.clone(),
681+ student: ali.clone(),
682+ booked_by: ali,
683+ status: MealBookingStatus::Booked,
684+ attempt: 1,
685+ price_minor: None,
686+ cancelled_at: None,
687+ created_at: Timestamp::now(),
688+ };
689+ let place = async |seen| {
690+ MealBooking::claim_and_place(&menu.record(), cap::UNLIMITED, seen, &row, None, &db)
691+ .await
692+ .unwrap()
693+ };
694+ assert!(
695+ matches!(place(seen).await, Claimed::Full),
696+ "a claim at a revision the menu has left must be refused"
697+ );
698+ assert_eq!(seats(&menu, &db).await, 0, "and must write nothing");
699+ assert!(
700+ MealBooking::read(row.get_id(), &db)
701+ .await
702+ .unwrap()
703+ .is_none(),
704+ "the refused transaction must not leave the row behind either"
705+ );
706+
707+ // Re-read, and the same seat is taken with the row it belongs to.
708+ let now = Menu::read(&menu, &db).await.unwrap().unwrap().get_version();
709+ assert!(now > seen);
710+ assert!(matches!(place(now).await, Claimed::Made(_)));
711+ assert_eq!(seats(&menu, &db).await, 1);
712+ // …and a second placement of that very row owes no second seat.
713+ assert!(matches!(place(now).await, Claimed::Duplicate));
714+ assert_eq!(
715+ seats(&menu, &db).await,
716+ 1,
717+ "a duplicate rolls its seat back"
718+ );
719+ }
720+
721+ /// Every write that can move what a seat costs moves the revision — the
722+ /// half of the rule the CAS above cannot enforce by itself. A dish added,
723+ /// re-priced or removed, and the capacity moved: each must leave the menu at
724+ /// a revision no in-flight booking is still holding.
725+ #[tokio::test]
726+ async fn every_menu_write_that_moves_the_price_moves_the_revision() {
727+ let (db, id) = menu(None).await;
728+ let mut seen = 0;
729+ let mut moved = async |db: &Database| {
730+ let now = Menu::read(&id, db).await.unwrap().unwrap().get_version();
731+ let stepped = now > seen;
732+ seen = now;
733+ stepped
734+ };
735+ assert!(!moved(&db).await, "a fresh menu starts where it starts");
736+
737+ let dish = add_dish(&id, 1_000, &db).await;
738+ assert!(moved(&db).await, "a dish added");
739+ let dish = dish
740+ .update(
741+ None,
742+ None,
743+ Some(DishPrice::try_new(2_000).unwrap()),
744+ None,
745+ &db,
746+ )
747+ .await
748+ .unwrap();
749+ assert!(moved(&db).await, "a dish re-priced");
750+ dish.delete(&db).await.unwrap();
751+ assert!(moved(&db).await, "a dish removed");
752+ Menu::read(&id, &db)
753+ .await
754+ .unwrap()
755+ .unwrap()
756+ .update(Some(Some(5)), &db)
757+ .await
758+ .unwrap();
759+ assert!(moved(&db).await, "the capacity moved");
760+ }
761+
762+ /// A booking placed after a price edit is billed the new price, and one
763+ /// placed before keeps the old one — the seat's `price_minor` is history,
764+ /// never re-read from the menu.
765+ #[tokio::test]
766+ async fn a_seat_keeps_the_price_it_was_taken_at() {
767+ let (db, menu) = menu(None).await;
768+ let (ali, veli) = (UserId::generate(), UserId::generate());
769+ let open = MealCutoff::default();
770+ add_dish(&menu, 1_000, &db).await;
771+
772+ let early = MealBooking::book(&menu, &ali, &ali, &open, &db)
773+ .await
774+ .unwrap();
775+ add_dish(&menu, 500, &db).await;
776+ let late = MealBooking::book(&menu, &veli, &veli, &open, &db)
777+ .await
778+ .unwrap();
779+
780+ assert_eq!(
781+ early.get_price_minor().map(LedgerAmount::as_minor),
782+ Some(1_000)
783+ );
784+ assert_eq!(
785+ late.get_price_minor().map(LedgerAmount::as_minor),
786+ Some(1_500)
787+ );
788+ // The seat taken before the second dish is not re-billed for it.
789+ let held = MealBooking::book(&menu, &ali, &ali, &open, &db)
790+ .await
791+ .unwrap();
792+ assert_eq!(
793+ held.get_price_minor().map(LedgerAmount::as_minor),
794+ Some(1_000)
795+ );
796+ }
797+
427 fn cutoff(minutes: Option<i64>, serving_minute: Option<i64>) -> MealCutoff {798 fn cutoff(minutes: Option<i64>, serving_minute: Option<i64>) -> MealCutoff {
428 MealCutoff {799 MealCutoff {
429 minutes,800 minutes,
src/domain/meal_ledger.rsmodified+25 -11
@@ -46,9 +46,10 @@ use surrealdb::types::{AlreadyExistsError, RecordId, RecordIdKey, SurrealValue};
46 use ulid::Generator;46 use ulid::Generator;
47 47
48 use crate::constant::{48 use crate::constant::{
49- MAX_LEDGER_AMOUNT_MINOR, MAX_LEDGER_METHOD_LEN, MAX_LEDGER_NOTE_LEN, MEAL_LEDGER_TABLE,49+ CAS_UPDATE_RETRIES, MAX_LEDGER_AMOUNT_MINOR, MAX_LEDGER_METHOD_LEN, MAX_LEDGER_NOTE_LEN,
50+ MEAL_LEDGER_TABLE,
50 };51 };
51-use crate::database::Database;52+use crate::database::{Database, lost_the_race};
52 use crate::domain::meal_booking::{MealBooking, MealBookingId};53 use crate::domain::meal_booking::{MealBooking, MealBookingId};
53 use crate::domain::menu::MenuId;54 use crate::domain::menu::MenuId;
54 use crate::domain::menu_dish::MenuDish;55 use crate::domain::menu_dish::MenuDish;
@@ -277,17 +278,31 @@ impl MealLedger {
277 /// guarantee is `CREATE`'s own: on an existing id it *errors* and leaves278 /// guarantee is `CREATE`'s own: on an existing id it *errors* and leaves
278 /// the row untouched, so the writer that lost the race reads back the279 /// the row untouched, so the writer that lost the race reads back the
279 /// winner's line instead of failing the request with a 500.280 /// winner's line instead of failing the request with a 500.
281+ ///
282+ /// A *write conflict* is the same race decided one layer down — two
283+ /// appends of one id arriving together are no longer serialized by a
284+ /// process-wide lock, so the store aborts one as retryable instead of
285+ /// answering it "already exists". Both are read back the same way, and a
286+ /// conflict that turns out to have written nothing is simply tried again;
287+ /// no path here can write a second line, since the id is the key.
280 async fn append(row: MealLedger, db: &Database) -> Result<MealLedger, AppError> {288 async fn append(row: MealLedger, db: &Database) -> Result<MealLedger, AppError> {
281 if let Some(existing) = Self::read(&row.id, db).await? {289 if let Some(existing) = Self::read(&row.id, db).await? {
282 return Ok(existing);290 return Ok(existing);
283 }291 }
284 let id = row.id.clone();292 let id = row.id.clone();
285- let created: Option<MealLedger> = match db.create(id.record()).content(row).await {293+ for _ in 0..CAS_UPDATE_RETRIES {
286- Ok(created) => created,294+ match db.create(id.record()).content(row.clone()).await {
287- Err(e) if is_duplicate_record(&e) => Self::read(&id, db).await?,295+ Ok(Some(created)) => return Ok(created),
288- Err(e) => return Err(e.into()),296+ Ok(None) => break,
289- };297+ Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => {
290- created.ok_or_else(|| AppError::Internal("failed to write the ledger line".into()))298+ if let Some(existing) = Self::read(&id, db).await? {
299+ return Ok(existing);
300+ }
301+ }
302+ Err(e) => return Err(e.into()),
303+ }
304+ }
305+ Err(AppError::Internal("failed to write the ledger line".into()))
291 }306 }
292 307
293 pub async fn read(id: &MealLedgerId, db: &Database) -> Result<Option<MealLedger>, AppError> {308 pub async fn read(id: &MealLedgerId, db: &Database) -> Result<Option<MealLedger>, AppError> {
@@ -322,9 +337,8 @@ impl MealLedger {
322 /// The price comes off the *booking row*, never off the menu as it stands337 /// The price comes off the *booking row*, never off the menu as it stands
323 /// now: a seat taken while the menu was free carries `None` forever, so338 /// now: a seat taken while the menu was free carries `None` forever, so
324 /// "was free" is a recorded fact and a later dish never bills a seat339 /// "was free" is a recorded fact and a later dish never bills a seat
325- /// retroactively. Called under340+ /// retroactively. Called from [`MealBooking::book`] alone, right after the seat
326- /// [`MENU_LOCK`](crate::domain::menu::MENU_LOCK), from341+ /// was claimed, so the seat and its money move together.
327- /// [`MealBooking::book`] alone, so the seat and its money move together.
328 ///342 ///
329 /// Replaying it is free: the id is `(booking, attempt)`, so a duplicate343 /// Replaying it is free: the id is `(booking, attempt)`, so a duplicate
330 /// `POST` writes nothing, and an attempt whose charge failed the first time344 /// `POST` writes nothing, and an attempt whose charge failed the first time
src/domain/menu.rsmodified+123 -55
@@ -10,14 +10,14 @@
10 //! - **`slot` is a snapshot**, not a link into settings. Retiring a slot must10 //! - **`slot` is a snapshot**, not a link into settings. Retiring a slot must
11 //! never rewrite a menu already published under it.11 //! never rewrite a menu already published under it.
12 12
13-use std::sync::LazyLock;
14-
15 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};13 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
16 use tokio::sync::Mutex;14 use tokio::sync::Mutex;
17-use ulid::Generator;
18 15
19-use crate::constant::{MAX_MENU_CAPACITY, MENU_TABLE};16+use crate::constant::{
20-use crate::database::Database;17+ MAX_MENU_CAPACITY, MENU_SEAT_COUNT_FIELD, MENU_TABLE, MENU_VERSION_FIELD, SLOT_REF_TABLE,
18+};
19+use crate::database::{Database, lost_the_race};
20+use crate::domain::cap;
21 use crate::domain::field_update::FieldUpdate;21 use crate::domain::field_update::FieldUpdate;
22 use crate::domain::menu_dish::MenuDish;22 use crate::domain::menu_dish::MenuDish;
23 use crate::domain::page::PagedList;23 use crate::domain::page::PagedList;
@@ -26,38 +26,46 @@ use crate::domain::timestamp::Timestamp;
26 use crate::domain::user::UserId;26 use crate::domain::user::UserId;
27 use crate::error::{AppError, ValidationError};27 use crate::error::{AppError, ValidationError};
28 28
29-/// Serializes "is there already a menu for this day and slot?" against the29+/// Serializes what is left that counts rows against one menu: the dish cap
30-/// publish it authorizes — a count-then-write pair SurrealDB does not30+/// (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB does not
31-/// conflict-check, so the UNIQUE index would otherwise be the only thing31+/// conflict-check). Publishing no longer needs it — the day+slot *is* the
32-/// standing between two racing publishes and a 500. Also held by the settings32+/// record id — and neither does a booking, a menu delete, or the settings
33-/// slot-removal guard, whose check ("was any menu published for this slot?")33+/// slot-removal guard: those went to conditional single-record writes
34-/// is the mirror image.34+/// ([`crate::domain::cap`]), which hold across replicas as this lock cannot.
35+//
36+// ponytail: the dish cap is therefore still replica-local — two replicas can
37+// each add the 50th dish. Closing it is another `cap` counter (`dish_count` on
38+// the menu row) plus its backfill; the ceiling is 51 dishes on a menu, not
39+// money or a seat, so it was not worth the column here.
35 ///40 ///
36-/// Lock order: `EXAM_LOCK` (taken by the same settings write) is always taken41+/// A leaf: nothing held under it takes another lock.
37-/// *before* this one; nothing here ever takes `EXAM_LOCK`, so the two cannot
38-/// deadlock.
39 pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(());42 pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(());
40 43
41-/// Mints menu ids in write order — `Ulid::new()`'s random low bits sort44+/// The reference counter for one meal slot — how many menus are published under
42-/// arbitrarily within one millisecond, which would scramble the `id` tie-break45+/// that name, and whether the school has retired it (see
43-/// of the listings below.46+/// [`crate::domain::cap`]). The mirror of
44-static IDS: LazyLock<std::sync::Mutex<Generator>> =47+/// [`kind_ref`](crate::domain::exam_result::kind_ref) for exam kinds: the slot
45- LazyLock::new(|| std::sync::Mutex::new(Generator::new()));48+/// is snapshotted text on the menu, so this row is the only place the two
49+/// tables' relationship is a single record two replicas can contend on.
50+pub(crate) fn slot_ref(slot: &str) -> RecordId {
51+ RecordId::new(SLOT_REF_TABLE, slot)
52+}
46 53
47 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]54 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
48 pub struct MenuId(RecordId);55 pub struct MenuId(RecordId);
49 56
50 impl MenuId {57 impl MenuId {
51- pub fn generate() -> Self {58+ /// The one id a menu for this day and slot can have. Deterministic on
52- let mut ids = IDS.lock().expect("menu id generator poisoned");59+ /// purpose (the `EnrollmentId` trick): two replicas publishing the same
53- // The only error is exhausting the random bits within one millisecond60+ /// meal race on a single record instead of writing two rows, so the loser
54- // (2^80 ids deep); it clears itself as the clock ticks, so retry.61+ /// is told "already exists" by the store and answered the same 409 the
55- let ulid = loop {62+ /// pre-check gives. `date` is fixed-width `YYYY-MM-DD`, so the `_` joiner
56- if let Ok(ulid) = ids.generate() {63+ /// cannot be read two ways however the school spells its slots.
57- break ulid;64+ pub fn for_slot(date: &MenuDate, slot: &MenuSlot) -> Self {
58- }65+ Self(RecordId::new(
59- };66+ MENU_TABLE,
60- Self(RecordId::new(MENU_TABLE, ulid.to_string()))67+ format!("{}_{}", date.as_str(), slot.as_str()),
68+ ))
61 }69 }
62 70
63 pub fn from_key(key: &str) -> Self {71 pub fn from_key(key: &str) -> Self {
@@ -156,6 +164,12 @@ pub struct Menu {
156 date: MenuDate,164 date: MenuDate,
157 slot: MenuSlot,165 slot: MenuSlot,
158 capacity: Option<i64>,166 capacity: Option<i64>,
167+ /// The menu's revision (see [`MENU_VERSION_FIELD`]). Absent on rows written
168+ /// before the column existed, which reads as revision zero — the same thing
169+ /// `(version ?? 0)` says in the claim's `WHERE`. The seat counter is
170+ /// deliberately *not* here: it is the database's to own, and a whole-row
171+ /// save must never carry a stale copy of it.
172+ version: Option<i64>,
159 created_by: UserId,173 created_by: UserId,
160 created_at: Timestamp,174 created_at: Timestamp,
161 }175 }
@@ -177,6 +191,13 @@ impl Menu {
177 self.capacity191 self.capacity
178 }192 }
179 193
194+ /// The revision a booking must still find on the row when it claims its
195+ /// seat. Absent (a pre-column row) is revision zero, exactly as the `WHERE`
196+ /// reads it.
197+ pub fn get_version(&self) -> i64 {
198+ self.version.unwrap_or(0)
199+ }
200+
180 pub fn get_created_by(&self) -> &UserId {201 pub fn get_created_by(&self) -> &UserId {
181 &self.created_by202 &self.created_by
182 }203 }
@@ -185,9 +206,14 @@ impl Menu {
185 self.created_at206 self.created_at
186 }207 }
187 208
188- /// Publish a menu. Refused (409) when the day+slot already carries one —209+ /// Publish a menu. Refused (409) when the day+slot already carries one.
189- /// re-checked under [`MENU_LOCK`], so two racing publishes cannot both find210+ ///
190- /// the day free and trip the UNIQUE index into a 500.211+ /// The day and slot *are* the record id ([`MenuId::for_slot`]), so the
212+ /// refusal is decided by the store rather than by a check a peer replica can
213+ /// outrun: two publishes of the same meal write one id, and the loser's
214+ /// "already exists" becomes the same 409. The pre-check stays for the
215+ /// ordinary case — and for menus published before ids were derived, whose
216+ /// ULID key no new publish can collide with.
191 pub async fn create(217 pub async fn create(
192 date: MenuDate,218 date: MenuDate,
193 slot: MenuSlot,219 slot: MenuSlot,
@@ -195,22 +221,44 @@ impl Menu {
195 created_by: &UserId,221 created_by: &UserId,
196 db: &Database,222 db: &Database,
197 ) -> Result<Menu, AppError> {223 ) -> Result<Menu, AppError> {
198- let _guard = MENU_LOCK.lock().await;224+ let taken = AppError::Conflict("a menu is already published for that date and slot");
199 if Self::find(&date, &slot, db).await?.is_some() {225 if Self::find(&date, &slot, db).await?.is_some() {
200- return Err(AppError::Conflict(226+ return Err(taken);
201- "a menu is already published for that date and slot",227+ }
202- ));228+ // The menu takes a reference on its slot, which is what stops the slot
229+ // being dropped from the settings while this menu (whose slot is only
230+ // snapshotted text) still points at it. Claimed before the write and
231+ // given back if the write does not land, exactly like a seat.
232+ let counter = slot_ref(slot.as_str());
233+ if !cap::claim_ref(&counter, 1, db).await? {
234+ return Err(AppError::ConflictOwned(format!(
235+ "the '{}' meal slot has been removed from the school's settings",
236+ slot.as_str()
237+ )));
203 }238 }
204 let menu = Menu {239 let menu = Menu {
205- id: MenuId::generate(),240+ id: MenuId::for_slot(&date, &slot),
206 date,241 date,
207 slot,242 slot,
208 capacity,243 capacity,
244+ version: Some(0),
209 created_by: created_by.clone(),245 created_by: created_by.clone(),
210 created_at: Timestamp::now(),246 created_at: Timestamp::now(),
211 };247 };
212- let created: Option<Menu> = db.create(menu.id.record()).content(menu).await?;248+ match db.create(menu.id.record()).content(menu).await {
213- created.ok_or_else(|| AppError::Internal("failed to publish the menu".into()))249+ Ok(Some(created)) => Ok(created),
250+ Ok(None) => {
251+ cap::release_ref(&counter, 1, db).await?;
252+ Err(AppError::Internal("failed to publish the menu".into()))
253+ }
254+ Err(err) => {
255+ cap::release_ref(&counter, 1, db).await?;
256+ match lost_the_race(&err) {
257+ true => Err(taken),
258+ false => Err(err.into()),
259+ }
260+ }
261+ }
214 }262 }
215 263
216 pub async fn read(id: &MenuId, db: &Database) -> Result<Option<Menu>, AppError> {264 pub async fn read(id: &MenuId, db: &Database) -> Result<Option<Menu>, AppError> {
@@ -255,37 +303,57 @@ impl Menu {
255 /// Only `capacity` is writable: `date` and `slot` are `READONLY` columns,303 /// Only `capacity` is writable: `date` and `slot` are `READONLY` columns,
256 /// because moving a published menu to another day is a different menu.304 /// because moving a published menu to another day is a different menu.
257 /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped.305 /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped.
306+ ///
307+ /// Moving the cap moves the revision first ([`cap::bump`]): a booking that
308+ /// read the old cap must not claim its seat against it, or a shrink
309+ /// over-admits by exactly the bookings in flight.
258 pub async fn update(310 pub async fn update(
259 self,311 self,
260 capacity: Option<Option<i64>>,312 capacity: Option<Option<i64>>,
261 db: &Database,313 db: &Database,
262 ) -> Result<Menu, AppError> {314 ) -> Result<Menu, AppError> {
315+ if capacity.is_some() {
316+ cap::bump(&self.id.record(), MENU_VERSION_FIELD, db).await?;
317+ }
263 FieldUpdate::new(self.id.record())318 FieldUpdate::new(self.id.record())
264 .set("capacity", capacity)319 .set("capacity", capacity)
265 .run::<Menu>(db)320 .run::<Menu>(db)
266 .await321 .await
267 }322 }
268 323
269- /// Whether any menu was ever published for this slot name — the guard
270- /// behind removing a slot from `meal_slots`, mirroring
271- /// [`ExamResult::any_for_kind`](crate::domain::exam_result::ExamResult::any_for_kind).
272- /// Menus snapshot the slot as text, so this is a plain string match.
273- /// Callers hold [`MENU_LOCK`] so a publish cannot slip in behind the check.
274- pub async fn any_for_slot(slot: &str, db: &Database) -> Result<bool, AppError> {
275- let mut result = db
276- .query("SELECT VALUE id FROM menu WHERE slot = $slot LIMIT 1")
277- .bind(("slot", slot.to_string()))
278- .await?
279- .check()?;
280- Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
281- }
282-
283 /// Delete the menu and the dishes on it — a dish has no meaning without324 /// Delete the menu and the dishes on it — a dish has no meaning without
284 /// its menu, and the `menu` link is `READONLY`, so it cannot be re-homed.325 /// its menu, and the `menu` link is `READONLY`, so it cannot be re-homed.
326+ ///
327+ /// Refused (409) while a seat is still held, and the *row itself* decides
328+ /// that: the delete carries the seat counter in its `WHERE`, so a booking
329+ /// landing in another replica at that instant either takes its seat before
330+ /// the delete (which then finds a non-zero counter and refuses) or after it
331+ /// (and finds no menu). A read-then-delete pair had a window where both
332+ /// happened — a paid seat on a menu that no longer exists.
333+ ///
334+ /// The dishes go *after* the row: their cascade must not run for a delete
335+ /// the counter refused.
285 pub async fn delete(self, db: &Database) -> Result<Menu, AppError> {336 pub async fn delete(self, db: &Database) -> Result<Menu, AppError> {
337+ let mut result = db
338+ .query(format!(
339+ "DELETE $id WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE"
340+ ))
341+ .bind(("id", self.id.record()))
342+ .await?
343+ .check()?;
344+ let Some(deleted) = result.take::<Vec<Menu>>(0)?.into_iter().next() else {
345+ // Nothing back: either seats are held, or the menu is already gone.
346+ return Err(match Self::read(&self.id, db).await? {
347+ Some(_) => AppError::Conflict("the menu still has live bookings"),
348+ None => AppError::NotFound,
349+ });
350+ };
286 MenuDish::delete_for_menu(&self.id, db).await?;351 MenuDish::delete_for_menu(&self.id, db).await?;
287- let deleted: Option<Menu> = db.delete(self.id.record()).await?;352+ // The slot gets its reference back — a slot no menu is published for
288- deleted.ok_or(AppError::NotFound)353+ // any more may leave the settings again. After the delete, so a crash
354+ // over-counts (refusing a removal) rather than under-counts.
355+ cap::release_ref(&slot_ref(deleted.slot.as_str()), 1, db).await?;
356+ Ok(deleted)
289 }357 }
290 }358 }
291 359
src/domain/menu_dish.rsmodified+55 -3
@@ -12,9 +12,10 @@ use ulid::Generator;
12 12
13 use crate::constant::{13 use crate::constant::{
14 MAX_DISH_DESCRIPTION_LEN, MAX_DISH_NAME_LEN, MAX_DISH_PRICE_MINOR, MAX_DISH_TAGS,14 MAX_DISH_DESCRIPTION_LEN, MAX_DISH_NAME_LEN, MAX_DISH_PRICE_MINOR, MAX_DISH_TAGS,
15- MENU_DISH_TABLE,15+ MENU_DISH_TABLE, MENU_VERSION_FIELD,
16 };16 };
17 use crate::database::Database;17 use crate::database::Database;
18+use crate::domain::cap;
18 use crate::domain::field_update::FieldUpdate;19 use crate::domain::field_update::FieldUpdate;
19 use crate::domain::menu::MenuId;20 use crate::domain::menu::MenuId;
20 use crate::domain::timestamp::Timestamp;21 use crate::domain::timestamp::Timestamp;
@@ -185,6 +186,7 @@ impl MenuDish {
185 self.created_at186 self.created_at
186 }187 }
187 188
189+ /// Add a dish. Moves the menu's revision *first* — see [`Self::bump_menu`].
188 pub async fn create(190 pub async fn create(
189 menu: &MenuId,191 menu: &MenuId,
190 name: DishName,192 name: DishName,
@@ -202,8 +204,43 @@ impl MenuDish {
202 tags,204 tags,
203 created_at: Timestamp::now(),205 created_at: Timestamp::now(),
204 };206 };
205- let created: Option<MenuDish> = db.create(dish.id.record()).content(dish).await?;207+ // The revision bump and the insert are one transaction, and the bump is
206- created.ok_or_else(|| AppError::Internal("failed to add the dish".into()))208+ // what makes the menu's existence part of it: the `UPDATE` matches
209+ // nothing once the menu row is deleted, and a delete racing this one
210+ // touches the very key this transaction writes, so the two cannot both
211+ // commit. Without that, a dish landing just after `DELETE /menus/{id}`
212+ // removed the row but before its cascade ran outlived its menu.
213+ let mut result = db
214+ .query(format!(
215+ "BEGIN TRANSACTION;
216+ LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \
217+ ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id);
218+ IF array::len($bumped) = 0 {{ THROW 'no_menu' }};
219+ CREATE $id CONTENT $dish;
220+ COMMIT TRANSACTION;"
221+ ))
222+ .bind(("menu", menu.record()))
223+ .bind(("id", dish.id.record()))
224+ .bind(("dish", dish))
225+ .await?;
226+ // An aborted transaction errors *every* slot, most with a generic "not
227+ // executed" — only the THROW's own slot names the reason.
228+ let mut errors = result.take_errors();
229+ if errors
230+ .values()
231+ .any(|error| error.to_string().contains("no_menu"))
232+ {
233+ return Err(AppError::NotFound);
234+ }
235+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
236+ return Err(error.into());
237+ }
238+ // Slots count BEGIN, the LET and the IF: the CREATE is slot 3.
239+ result
240+ .take::<Vec<MenuDish>>(3)?
241+ .into_iter()
242+ .next()
243+ .ok_or_else(|| AppError::Internal("failed to add the dish".into()))
207 }244 }
208 245
209 pub async fn read(id: &MenuDishId, db: &Database) -> Result<Option<MenuDish>, AppError> {246 pub async fn read(id: &MenuDishId, db: &Database) -> Result<Option<MenuDish>, AppError> {
@@ -240,6 +277,19 @@ impl MenuDish {
240 Ok(Self::list_for_menu(menu, db).await?.len())277 Ok(Self::list_for_menu(menu, db).await?.len())
241 }278 }
242 279
280+ /// What a seat on this dish's menu costs changed, so the menu is now at a
281+ /// new revision and any booking that priced itself against the old one has
282+ /// to re-read. Called *before* the write, never after: bumped-and-not-written
283+ /// costs a booking one retry, written-and-not-bumped bills a seat a price
284+ /// the menu no longer carries.
285+ ///
286+ /// Deliberately on every dish write, not only the ones that move
287+ /// `price_minor`: a re-tagged dish is cheap to re-read, and a rule that
288+ /// applies to every write cannot be forgotten by the next field added here.
289+ async fn bump_menu(menu: &MenuId, db: &Database) -> Result<(), AppError> {
290+ cap::bump(&menu.record(), MENU_VERSION_FIELD, db).await
291+ }
292+
243 /// Write only the fields the PATCH carried. `description` is nullable, so293 /// Write only the fields the PATCH carried. `description` is nullable, so
244 /// it takes the three-way shape: absent = keep, `Some(None)` = clear.294 /// it takes the three-way shape: absent = keep, `Some(None)` = clear.
245 pub async fn update(295 pub async fn update(
@@ -250,6 +300,7 @@ impl MenuDish {
250 tags: Option<DishTags>,300 tags: Option<DishTags>,
251 db: &Database,301 db: &Database,
252 ) -> Result<MenuDish, AppError> {302 ) -> Result<MenuDish, AppError> {
303+ Self::bump_menu(&self.menu, db).await?;
253 FieldUpdate::new(self.id.record())304 FieldUpdate::new(self.id.record())
254 .set("name", name)305 .set("name", name)
255 .set("description", description)306 .set("description", description)
@@ -260,6 +311,7 @@ impl MenuDish {
260 }311 }
261 312
262 pub async fn delete(self, db: &Database) -> Result<MenuDish, AppError> {313 pub async fn delete(self, db: &Database) -> Result<MenuDish, AppError> {
314+ Self::bump_menu(&self.menu, db).await?;
263 let deleted: Option<MenuDish> = db.delete(self.id.record()).await?;315 let deleted: Option<MenuDish> = db.delete(self.id.record()).await?;
264 deleted.ok_or(AppError::NotFound)316 deleted.ok_or(AppError::NotFound)
265 }317 }
src/domain/registration.rsmodified+25 -34
@@ -1,7 +1,7 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3 use crate::constant::{REGISTRATION_COUNT_FIELD, REGISTRATION_TABLE};3 use crate::constant::{REGISTRATION_COUNT_FIELD, REGISTRATION_TABLE};
4-use crate::database::{Database, lost_the_race};4+use crate::database::Database;
5 use crate::domain::cap;5 use crate::domain::cap;
6 use crate::domain::event::{Event, EventId};6 use crate::domain::event::{Event, EventId};
7 use crate::domain::user::UserId;7 use crate::domain::user::UserId;
@@ -83,45 +83,36 @@ impl Registration {
83 .await?83 .await?
84 .ok_or(AppError::NotFound)?84 .ok_or(AppError::NotFound)?
85 .registration_capacity()?;85 .registration_capacity()?;
86- let seats = event.record();
87- if !cap::claim(
88- &seats,
89- REGISTRATION_COUNT_FIELD,
90- capacity.unwrap_or(cap::UNLIMITED),
91- db,
92- )
93- .await?
94- {
95- return Err(AppError::Conflict("the event is full"));
96- }
97 let registration = Registration {86 let registration = Registration {
98 id: RegistrationId::composite(event, user),87 id: RegistrationId::composite(event, user),
99 event: event.clone(),88 event: event.clone(),
100 user: user.clone(),89 user: user.clone(),
101 registered_by: registered_by.clone(),90 registered_by: registered_by.clone(),
102 };91 };
103- let created: Result<Option<Registration>, _> = db92+ match cap::claim_and_create(
104- .create(registration.id.record())93+ &event.record(),
105- .content(registration)94+ REGISTRATION_COUNT_FIELD,
106- .await;95+ capacity.unwrap_or(cap::UNLIMITED),
107- match created {96+ &registration.id.record(),
108- Ok(Some(created)) => Ok(created),97+ &registration,
109- Ok(None) => {98+ db,
110- cap::release(&seats, REGISTRATION_COUNT_FIELD, db).await?;99+ )
111- Err(AppError::Internal("failed to register user".into()))100+ .await?
112- }101+ {
113- // A concurrent placement of the same pair got there first: give the102+ cap::Claimed::Made(created) => Ok(created),
114- // seat back and hand its row over, the same no-op the early return103+ // A concurrent placement of the same pair got there first: hand its
115- // above would have made.104+ // row over, the same no-op the early return above would have made,
116- Err(err) => {105+ // and with no seat spent either way.
117- cap::release(&seats, REGISTRATION_COUNT_FIELD, db).await?;106+ cap::Claimed::Duplicate => Self::read_for_user(event, user, db)
118- if !lost_the_race(&err) {107+ .await?
119- return Err(err.into());108+ .ok_or_else(|| AppError::Internal("failed to register user".into())),
120- }109+ // Full, or the event was deleted between the read and the claim —
121- Self::read_for_user(event, user, db)110+ // the conditional write matches nothing either way, and only this
122- .await?111+ // path pays for the read that tells them apart.
123- .ok_or_else(|| AppError::Internal("failed to register user".into()))112+ cap::Claimed::Full => match Event::read(event, db).await? {
124- }113+ Some(_) => Err(AppError::Conflict("the event is full")),
114+ None => Err(AppError::NotFound),
115+ },
125 }116 }
126 }117 }
127 118
src/domain/subject.rsmodified+52 -8
@@ -166,23 +166,67 @@ impl Subject {
166 /// pointing at a subject that no longer exists.166 /// pointing at a subject that no longer exists.
167 ///167 ///
168 /// Exam questions and homework are *not* cascaded: their `subject` is a168 /// Exam questions and homework are *not* cascaded: their `subject` is a
169- /// required field the web layer refuses to orphan (both still block the169+ /// required field that may not be orphaned, so either one still refuses the
170- /// delete with a 409). The bank's is optional metadata, and blocking on it170+ /// delete with a 409. That refusal is the delete's own `WHERE`, read off the
171- /// was a dead end — only the template's owner may re-tag it, so a manager171+ /// two reference counters this row carries
172- /// could never clear their own 409, and a private template raising it172+ /// ([`crate::constant::SUBJECT_QUESTION_COUNT_FIELD`] and its homework
173- /// leaked its existence.173+ /// twin), which is what makes it hold when the question is created on
174+ /// another replica — the cross-table `SELECT … LIMIT 1` it replaces was a
175+ /// count-then-delete no transaction serializes, pinned by three
176+ /// process-wide locks that only ever served one process.
177+ ///
178+ /// Which of the two blocked is read off the counters *before* the delete,
179+ /// purely to pick the message; the decision itself was already made by the
180+ /// `WHERE`.
181+ ///
182+ /// The bank's subject is optional metadata, and blocking on it was a dead
183+ /// end — only the template's owner may re-tag it, so a manager could never
184+ /// clear their own 409, and a private template raising it leaked its
185+ /// existence. Its cascade runs *after* the conditional delete, so a refused
186+ /// delete leaves every template's subject where it was.
174 pub async fn delete(self, db: &Database) -> Result<Subject, AppError> {187 pub async fn delete(self, db: &Database) -> Result<Subject, AppError> {
175 let mut result = db188 let mut result = db
176 .query(189 .query(
177 "BEGIN TRANSACTION;190 "BEGIN TRANSACTION;
191+ LET $held = (SELECT exam_question_count AS q, homework_count AS h FROM $sub);
192+ LET $before = (DELETE $sub
193+ WHERE (exam_question_count ?? 0) = 0 AND (homework_count ?? 0) = 0
194+ RETURN BEFORE);
195+ IF array::len($before) = 0 {
196+ THROW IF array::len($held) = 0 { 'subject_missing' }
197+ ELSE IF ($held[0].q ?? 0) > 0 { 'subject_questions' }
198+ ELSE { 'subject_homework' }
199+ };
178 UPDATE bank_question SET subject = NONE WHERE subject = $sub;200 UPDATE bank_question SET subject = NONE WHERE subject = $sub;
179- LET $before = (DELETE $sub RETURN BEFORE);
180 RETURN $before;201 RETURN $before;
181 COMMIT TRANSACTION;",202 COMMIT TRANSACTION;",
182 )203 )
183 .bind(("sub", self.id.record()))204 .bind(("sub", self.id.record()))
184- .await?205+ .await?;
185- .check()?;206+ // An aborted transaction errors every slot; only the THROW's own slot
207+ // names the marker (the [`crate::domain::appointment_slot`] treatment).
208+ let mut errors = result.take_errors();
209+ let thrown = |marker: &str| {
210+ errors
211+ .values()
212+ .any(|error| error.to_string().contains(marker))
213+ };
214+ if thrown("subject_questions") {
215+ return Err(AppError::Conflict(
216+ "exam questions still reference this subject — re-tag or delete them first",
217+ ));
218+ }
219+ if thrown("subject_homework") {
220+ return Err(AppError::Conflict(
221+ "homework still references this subject — re-tag or delete it first",
222+ ));
223+ }
224+ if thrown("subject_missing") {
225+ return Err(AppError::NotFound);
226+ }
227+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
228+ return Err(error.into());
229+ }
186 // Read through the trailing `RETURN`, not a counted slot — see230 // Read through the trailing `RETURN`, not a counted slot — see
187 // [`crate::domain::exam::Exam::delete`].231 // [`crate::domain::exam::Exam::delete`].
188 let slot = result.num_statements().saturating_sub(2);232 let slot = result.num_statements().saturating_sub(2);
src/domain/term.rsmodified+25 -33
@@ -7,10 +7,9 @@
7 //! rule that guards exams/lessons/events deliberately does not apply here.7 //! rule that guards exams/lessons/events deliberately does not apply here.
8 8
9 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};9 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
10-use tokio::sync::Mutex;
11 use ulid::Ulid;10 use ulid::Ulid;
12 11
13-use crate::constant::{MAX_TERM_NAME_LEN, TERM_TABLE};12+use crate::constant::{COURSE_COUNT_FIELD, MAX_TERM_NAME_LEN, TERM_TABLE};
14 use crate::database::Database;13 use crate::database::Database;
15 use crate::domain::field_update::FieldUpdate;14 use crate::domain::field_update::FieldUpdate;
16 use crate::domain::page::PagedList;15 use crate::domain::page::PagedList;
@@ -18,24 +17,6 @@ use crate::domain::timestamp::{Timestamp, range_error};
18 use crate::error::{AppError, ValidationError};17 use crate::error::{AppError, ValidationError};
19 use crate::validate::validate_required;18 use crate::validate::validate_required;
20 19
21-/// Serializes the term delete guard (does any course still link it?) against
22-/// the course writes that assign a term, so a course can't land on a term that
23-/// is already on its way out. Course writes take it only when they actually
24-/// link a term.
25-///
26-/// Two leases remain, both cross-record and both replica-*local*: the delete
27-/// guard in `web::terms::delete_term`, and the term lookup in
28-/// `web::courses`' create/update. The range check a PATCH makes is no longer
29-/// one of them — it is a `WHERE` on the update itself
30-/// ([`crate::domain::field_update::FieldUpdate::ordered`]), which holds across
31-/// replicas as this mutex never did.
32-///
33-/// Lock order: no path ever holds this and `ENROLL_LOCK` at the same time — the
34-/// course writes that take this one touch no roster, and the course delete that
35-/// takes `ENROLL_LOCK` touches no term — so the two cannot deadlock. Should a
36-/// future path need both, take `ENROLL_LOCK` first.
37-pub(crate) static TERM_LOCK: Mutex<()> = Mutex::const_new(());
38-
39 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]20 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
40 pub struct TermId(RecordId);21 pub struct TermId(RecordId);
41 22
@@ -152,22 +133,33 @@ impl Term {
152 .await133 .await
153 }134 }
154 135
155- /// True iff any course still links to this term — the delete guard.136+ /// Delete the term, but only while no course links it — nothing here
156- pub async fn any_course(id: &TermId, db: &Database) -> Result<bool, AppError> {137+ /// unlinks or cascades. `false` = refused, nothing was written.
138+ ///
139+ /// The roster of linking courses is the term's own `course_count`
140+ /// refcount, claimed by [`crate::domain::course::Course::create`] and
141+ /// `update` *before* they write a link, so the check and the delete are one
142+ /// conditional write on one record: a course write racing this either
143+ /// claims first (and the delete is refused) or finds the row gone (and is
144+ /// refused itself, with the same 400 the lookup gives). `Err(NotFound)`
145+ /// keeps the answer a concurrent *delete* used to get.
146+ pub async fn delete(self, db: &Database) -> Result<bool, AppError> {
157 let mut result = db147 let mut result = db
158- .query("SELECT VALUE id FROM course WHERE term = $term LIMIT 1")148+ .query(format!(
159- .bind(("term", id.record()))149+ "DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE"
150+ ))
151+ .bind(("term", self.id.record()))
160 .await?152 .await?
161 .check()?;153 .check()?;
162- Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())154+ if !result.take::<Vec<Term>>(0)?.is_empty() {
163- }155+ return Ok(true);
164-156+ }
165- /// Delete the term. Callers must refuse while [`Term::any_course`] holds —157+ // Still linked or already gone: the one statement cannot tell those
166- /// nothing here unlinks or cascades, so a term is only ever dropped once no158+ // apart, and only the refusal path pays for the read that can.
167- /// course points at it.159+ match Self::read(&self.id, db).await? {
168- pub async fn delete(self, db: &Database) -> Result<Term, AppError> {160+ Some(_) => Ok(false),
169- let deleted: Option<Term> = db.delete(self.id.record()).await?;161+ None => Err(AppError::NotFound),
170- deleted.ok_or(AppError::NotFound)162+ }
171 }163 }
172 }164 }
173 165
src/migration_sql.rsmodified+133 -3
@@ -180,6 +180,9 @@ pub const MIGRATION: &str = "
180 DEFINE FIELD IF NOT EXISTS name ON term TYPE string;180 DEFINE FIELD IF NOT EXISTS name ON term TYPE string;
181 DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int;181 DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int;
182 DEFINE FIELD IF NOT EXISTS ends_at ON term TYPE int;182 DEFINE FIELD IF NOT EXISTS ends_at ON term TYPE int;
183+ -- Courses still linking this term, the cross-replica delete guard (see
184+ -- `crate::domain::cap`). Absent reads as zero, so no Rust struct needs it.
185+ DEFINE FIELD IF NOT EXISTS course_count ON term TYPE option<int>;
183 186
184 DEFINE TABLE IF NOT EXISTS course SCHEMAFULL;187 DEFINE TABLE IF NOT EXISTS course SCHEMAFULL;
185 DEFINE FIELD IF NOT EXISTS creator ON course TYPE record<user>;188 DEFINE FIELD IF NOT EXISTS creator ON course TYPE record<user>;
@@ -196,6 +199,11 @@ pub const MIGRATION: &str = "
196 DEFINE FIELD IF NOT EXISTS course ON subject TYPE record<course>;199 DEFINE FIELD IF NOT EXISTS course ON subject TYPE record<course>;
197 DEFINE FIELD IF NOT EXISTS name ON subject TYPE string;200 DEFINE FIELD IF NOT EXISTS name ON subject TYPE string;
198 DEFINE FIELD IF NOT EXISTS description ON subject TYPE string;201 DEFINE FIELD IF NOT EXISTS description ON subject TYPE string;
202+ -- How many exam questions and how many homework still point here. The
203+ -- delete is conditioned on both reading zero, which is what makes the
204+ -- guard hold against a question created on another replica.
205+ DEFINE FIELD IF NOT EXISTS exam_question_count ON subject TYPE option<int>;
206+ DEFINE FIELD IF NOT EXISTS homework_count ON subject TYPE option<int>;
199 DEFINE INDEX IF NOT EXISTS subject_course ON subject FIELDS course;207 DEFINE INDEX IF NOT EXISTS subject_course ON subject FIELDS course;
200 208
201 DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL;209 DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL;
@@ -258,6 +266,10 @@ pub const MIGRATION: &str = "
258 DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true;266 DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true;
259 DEFINE FIELD IF NOT EXISTS allow_review ON exam TYPE bool DEFAULT false;267 DEFINE FIELD IF NOT EXISTS allow_review ON exam TYPE bool DEFAULT false;
260 DEFINE FIELD IF NOT EXISTS draft ON exam TYPE bool DEFAULT false;268 DEFINE FIELD IF NOT EXISTS draft ON exam TYPE bool DEFAULT false;
269+ -- How many marks the exam carries (2026-07-27). A kind change is refused
270+ -- against it, and the exam's own compare-and-set pins it, so a grade
271+ -- landing mid-PATCH refuses that save instead of slipping past its gates.
272+ DEFINE FIELD IF NOT EXISTS result_count ON exam TYPE option<int>;
261 DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course;273 DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course;
262 274
263 DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL;275 DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL;
@@ -469,6 +481,13 @@ pub const MIGRATION: &str = "
469 DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY;481 DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY;
470 DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int;482 DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int;
471 DEFINE FIELD IF NOT EXISTS file_count ON homework_submission TYPE option<int>;483 DEFINE FIELD IF NOT EXISTS file_count ON homework_submission TYPE option<int>;
484+ -- The grade that froze this submission, absent while it is still open. The
485+ -- freeze used to be a cross-table read (does a homework_result exist?)
486+ -- followed by a write here, which no lock can hold across replicas; the
487+ -- stamp turns every submission edit into a conditional single-record write
488+ -- (`WHERE graded_by_result = NONE`), the one guard that survives. Set by
489+ -- grading, cleared by un-grading, never by the student.
490+ DEFINE FIELD IF NOT EXISTS graded_by_result ON homework_submission TYPE option<record<homework_result>>;
472 DEFINE INDEX IF NOT EXISTS homework_submission_homework ON homework_submission FIELDS homework;491 DEFINE INDEX IF NOT EXISTS homework_submission_homework ON homework_submission FIELDS homework;
473 492
474 DEFINE TABLE IF NOT EXISTS homework_file SCHEMAFULL;493 DEFINE TABLE IF NOT EXISTS homework_file SCHEMAFULL;
@@ -493,14 +512,17 @@ pub const MIGRATION: &str = "
493 -- slots, a student or parent books one. `series` groups the occurrences a512 -- slots, a student or parent books one. `series` groups the occurrences a
494 -- weekly repeat expanded into, so one cancel deletes one row and a series513 -- weekly repeat expanded into, so one cancel deletes one row and a series
495 -- delete finds the rest. A booking's live/dead state is the `status`514 -- delete finds the rest. A booking's live/dead state is the `status`
496- -- string; occupancy is derived from it under the appointment lock rather515+ -- string; `occupied` is the cap-1 counter that says whether the slot is
497- -- than stored, so a rejected or cancelled booking frees its slot again.516+ -- taken (2026-07-27 — it used to be counted from the booking rows under a
517+ -- process-local lock, which two replicas could each pass), decremented in
518+ -- the same transaction as the reject/cancel that frees it.
498 -- The `proposed_*` fields carry a teacher's counter-proposal on the same519 -- The `proposed_*` fields carry a teacher's counter-proposal on the same
499- -- row until the requester accepts. No BACKFILL: both tables are new.520+ -- row until the requester accepts.
500 DEFINE TABLE IF NOT EXISTS appointment_slot SCHEMAFULL;521 DEFINE TABLE IF NOT EXISTS appointment_slot SCHEMAFULL;
501 DEFINE FIELD IF NOT EXISTS teacher ON appointment_slot TYPE record<user>;522 DEFINE FIELD IF NOT EXISTS teacher ON appointment_slot TYPE record<user>;
502 DEFINE FIELD IF NOT EXISTS starts_at ON appointment_slot TYPE int;523 DEFINE FIELD IF NOT EXISTS starts_at ON appointment_slot TYPE int;
503 DEFINE FIELD IF NOT EXISTS ends_at ON appointment_slot TYPE int;524 DEFINE FIELD IF NOT EXISTS ends_at ON appointment_slot TYPE int;
525+ DEFINE FIELD IF NOT EXISTS occupied ON appointment_slot TYPE option<int>;
504 DEFINE FIELD IF NOT EXISTS note ON appointment_slot TYPE option<string>;526 DEFINE FIELD IF NOT EXISTS note ON appointment_slot TYPE option<string>;
505 DEFINE FIELD IF NOT EXISTS series ON appointment_slot TYPE option<string>;527 DEFINE FIELD IF NOT EXISTS series ON appointment_slot TYPE option<string>;
506 DEFINE FIELD IF NOT EXISTS created_at ON appointment_slot TYPE int;528 DEFINE FIELD IF NOT EXISTS created_at ON appointment_slot TYPE int;
@@ -536,6 +558,13 @@ pub const MIGRATION: &str = "
536 DEFINE FIELD IF NOT EXISTS date ON menu TYPE string READONLY;558 DEFINE FIELD IF NOT EXISTS date ON menu TYPE string READONLY;
537 DEFINE FIELD IF NOT EXISTS slot ON menu TYPE string READONLY;559 DEFINE FIELD IF NOT EXISTS slot ON menu TYPE string READONLY;
538 DEFINE FIELD IF NOT EXISTS capacity ON menu TYPE option<int>;560 DEFINE FIELD IF NOT EXISTS capacity ON menu TYPE option<int>;
561+ -- `seats_booked` is the seat cap's counter (see `domain::cap`) and
562+ -- `version` the menu's revision: a booking claims its seat only while the
563+ -- menu still stands at the revision it read the price at, so a dish
564+ -- re-priced mid-booking cannot be billed as the old price. Both absent
565+ -- means zero, which is what `(x ?? 0)` reads on a row written before them.
566+ DEFINE FIELD IF NOT EXISTS seats_booked ON menu TYPE option<int>;
567+ DEFINE FIELD IF NOT EXISTS version ON menu TYPE option<int>;
539 DEFINE FIELD IF NOT EXISTS created_by ON menu TYPE record<user> READONLY;568 DEFINE FIELD IF NOT EXISTS created_by ON menu TYPE record<user> READONLY;
540 DEFINE FIELD IF NOT EXISTS created_at ON menu TYPE int READONLY;569 DEFINE FIELD IF NOT EXISTS created_at ON menu TYPE int READONLY;
541 DEFINE INDEX IF NOT EXISTS menu_date_slot ON menu FIELDS date, slot UNIQUE;570 DEFINE INDEX IF NOT EXISTS menu_date_slot ON menu FIELDS date, slot UNIQUE;
@@ -600,6 +629,21 @@ pub const MIGRATION: &str = "
600 DEFINE FIELD IF NOT EXISTS recorded_by ON meal_ledger TYPE record<user> READONLY;629 DEFINE FIELD IF NOT EXISTS recorded_by ON meal_ledger TYPE record<user> READONLY;
601 DEFINE FIELD IF NOT EXISTS created_at ON meal_ledger TYPE int READONLY;630 DEFINE FIELD IF NOT EXISTS created_at ON meal_ledger TYPE int READONLY;
602 DEFINE INDEX IF NOT EXISTS meal_ledger_student ON meal_ledger FIELDS student;631 DEFINE INDEX IF NOT EXISTS meal_ledger_student ON meal_ledger FIELDS student;
632+
633+ -- Reference counters, one row per *name* the settings offer, keyed by the
634+ -- name itself (2026-07-27). They are how 'a kind nothing is graded under
635+ -- may be removed' survives a second replica: the guard used to be a
636+ -- count-then-write across two tables under a process-wide lock, and the
637+ -- database serializes neither half of that. Both columns are `option<…>`
638+ -- so an absent row reads as zero references, in service — the counter is
639+ -- created by the first claim, never seeded per name.
640+ DEFINE TABLE IF NOT EXISTS kind_ref SCHEMAFULL;
641+ DEFINE FIELD IF NOT EXISTS count ON kind_ref TYPE option<int>;
642+ DEFINE FIELD IF NOT EXISTS retired ON kind_ref TYPE option<bool>;
643+
644+ DEFINE TABLE IF NOT EXISTS slot_ref SCHEMAFULL;
645+ DEFINE FIELD IF NOT EXISTS count ON slot_ref TYPE option<int>;
646+ DEFINE FIELD IF NOT EXISTS retired ON slot_ref TYPE option<bool>;
603 ";647 ";
604 648
605 /// Data backfills for rows written by older binaries. Runs *after* (and apart649 /// Data backfills for rows written by older binaries. Runs *after* (and apart
@@ -742,6 +786,19 @@ pub const BACKFILL: &str = "
742 UPDATE answer_image SET seq = 1 WHERE seq = NONE;786 UPDATE answer_image SET seq = 1 WHERE seq = NONE;
743 UPDATE exam_result SET seq = 1 WHERE seq = NONE;787 UPDATE exam_result SET seq = 1 WHERE seq = NONE;
744 788
789+ -- The homework freeze became cross-replica (2026-07-27): a grade that
790+ -- predates the stamp column has to put it on the submission it already
791+ -- froze, or that submission would read as open and be editable again.
792+ -- Result and submission share the deterministic `{homework}_{user}` key, so
793+ -- the owning row is addressed directly rather than searched for; an UPDATE
794+ -- of a record that isn't there (graded absent work) is an empty no-op. The
795+ -- `= NONE` guard keeps it one-time, for the same reason the counters below
796+ -- are one-time — a peer replica is serving while this runs.
797+ FOR $r IN ((SELECT VALUE id FROM homework_result) ?? []) {
798+ UPDATE type::record('homework_submission', record::id($r))
799+ SET graded_by_result = $r WHERE graded_by_result = NONE;
800+ };
801+
745 -- Count caps became cross-replica (2026-07-27): the authority moved from a802 -- Count caps became cross-replica (2026-07-27): the authority moved from a
746 -- process-wide mutex to a counter column on the parent row, so every parent803 -- process-wide mutex to a counter column on the parent row, so every parent
747 -- that predates the column is seeded from the children it actually has.804 -- that predates the column is seeded from the children it actually has.
@@ -756,6 +813,14 @@ pub const BACKFILL: &str = "
756 };813 };
757 UPDATE course SET enrollment_count = 0 WHERE enrollment_count = NONE;814 UPDATE course SET enrollment_count = 0 WHERE enrollment_count = NONE;
758 815
816+ -- The one refcount among them: courses per term, not children per parent.
817+ -- Same one-time `= NONE` guard, and `WHERE term != NONE` keeps the
818+ -- unlinked courses out of the group (they would form a NONE bucket).
819+ FOR $row IN ((SELECT term, count() AS n FROM course WHERE term != NONE GROUP BY term) ?? []) {
820+ UPDATE $row.term SET course_count = $row.n WHERE course_count = NONE;
821+ };
822+ UPDATE term SET course_count = 0 WHERE course_count = NONE;
823+
759 FOR $row IN ((SELECT event, count() AS n FROM registration GROUP BY event) ?? []) {824 FOR $row IN ((SELECT event, count() AS n FROM registration GROUP BY event) ?? []) {
760 UPDATE $row.event SET registration_count = $row.n WHERE registration_count = NONE;825 UPDATE $row.event SET registration_count = $row.n WHERE registration_count = NONE;
761 };826 };
@@ -775,6 +840,71 @@ pub const BACKFILL: &str = "
775 UPDATE $row.user_id SET chatbot_thread_count = $row.n WHERE chatbot_thread_count = NONE;840 UPDATE $row.user_id SET chatbot_thread_count = $row.n WHERE chatbot_thread_count = NONE;
776 };841 };
777 UPDATE user SET chatbot_thread_count = 0 WHERE chatbot_thread_count = NONE;842 UPDATE user SET chatbot_thread_count = 0 WHERE chatbot_thread_count = NONE;
843+
844+ -- The appointment slot's counter is the odd one out: it counts only the
845+ -- bookings that are still *live*, because a rejected or cancelled one gave
846+ -- the slot back long before this column existed.
847+ FOR $row IN ((SELECT slot, count() AS n FROM appointment
848+ WHERE status IN ['pending', 'approved'] GROUP BY slot) ?? []) {
849+ UPDATE $row.slot SET occupied = $row.n WHERE occupied = NONE;
850+ };
851+ UPDATE appointment_slot SET occupied = 0 WHERE occupied = NONE;
852+
853+ -- A menu's seats, counted from the bookings still *held* — a cancelled one
854+ -- gave its seat back before this column existed, exactly like the slot
855+ -- above. `version` gets no pass at all: absent already reads as revision
856+ -- zero everywhere it is compared, so writing it would be a no-op that
857+ -- touches every menu row.
858+ FOR $row IN ((SELECT menu, count() AS n FROM meal_booking
859+ WHERE status = 'booked' GROUP BY menu) ?? []) {
860+ UPDATE $row.menu SET seats_booked = $row.n WHERE seats_booked = NONE;
861+ };
862+ UPDATE menu SET seats_booked = 0 WHERE seats_booked = NONE;
863+
864+ -- A subject's two reference counters, seeded from what actually points at
865+ -- it. This must run *after* the legacy sweep above destroys the questions
866+ -- that predate subjects, or a subject would be seeded with rows that are
867+ -- about to vanish and could then never be deleted. No zero pass, for the
868+ -- same reason `version` gets none: absent already reads as zero in the
869+ -- delete's `(count ?? 0) = 0` guard, so writing it would touch every
870+ -- subject row to say what it already says.
871+ FOR $row IN ((SELECT subject, count() AS n FROM exam_question GROUP BY subject) ?? []) {
872+ UPDATE $row.subject SET exam_question_count = $row.n WHERE exam_question_count = NONE;
873+ };
874+
875+ FOR $row IN ((SELECT subject, count() AS n FROM homework GROUP BY subject) ?? []) {
876+ UPDATE $row.subject SET homework_count = $row.n WHERE homework_count = NONE;
877+ };
878+
879+ -- The settings guards became cross-replica the same way (2026-07-27): an
880+ -- exam kind counts the marks written under it, a meal slot the menus
881+ -- published for it, and a name is removable exactly while its counter reads
882+ -- zero. Rows written before the counters existed are counted once here.
883+ --
884+ -- Same `= NONE` guard and the same reason as the caps above: a peer replica
885+ -- may already be serving, and recomputing a counter it is incrementing
886+ -- would hand back a reference that is still held. No zero pass either — an
887+ -- absent counter already reads as zero, and a name nobody ever used needs
888+ -- no row at all.
889+ --
890+ -- Marks predate the counter but so may their *kind*: an exam whose kind was
891+ -- removed from the list long ago is counted too, which only ever refuses a
892+ -- removal that already happened. `slot` is text on the menu, so its group
893+ -- needs no join; `kind` lives on the exam, one hop from the mark.
894+ FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result GROUP BY kind) ?? []) {
895+ UPSERT type::record('kind_ref', $row.kind) SET count = $row.n WHERE count = NONE;
896+ };
897+
898+ FOR $row IN ((SELECT slot, count() AS n FROM menu GROUP BY slot) ?? []) {
899+ UPSERT type::record('slot_ref', $row.slot) SET count = $row.n WHERE count = NONE;
900+ };
901+
902+ -- Same one-time seeding for the per-exam mark counter: an exam graded by an
903+ -- older binary must read as graded, or its kind could be changed under the
904+ -- marks it already carries.
905+ FOR $row IN ((SELECT exam, count() AS n FROM exam_result GROUP BY exam) ?? []) {
906+ UPDATE $row.exam SET result_count = $row.n WHERE result_count = NONE;
907+ };
778 ";908 ";
779 909
780 /// The migration batches, in the order a boot applies them — and the *only*910 /// The migration batches, in the order a boot applies them — and the *only*
src/web/bank_questions.rsmodified+13 -27
@@ -45,22 +45,19 @@ use super::{
45 remove_blob, serve_inline_blob, set_or_clear, store_blob,45 remove_blob, serve_inline_blob, set_or_clear, store_blob,
46 };46 };
47 47
48-/// Serializes bank writes that adopt a `subject` against a concurrent subject48+// There is no `BANK_LOCK` any more. It served exactly one pairing — a
49-/// delete — the one invariant left here, and a **replica-local** one: it orders49+// subject-exists check here against the subject delete's cascade that clears
50-/// requests inside one process, and there are two. Every lease is now a50+// `subject` off every template — and that delete no longer takes any lock: it
51-/// *reader* lease taken across a subject-exists check and the write that adopts51+// is a conditional statement on the subject's own reference counters, which
52-/// it: bank create, bank update, and save-to-bank. (Update used to take the52+// bank templates deliberately do not hold (blocking on them was a dead end; see
53-/// writer lease for its read-modify-write; that is a compare-and-set on the row53+// [`crate::domain::subject::Subject::delete`]). With the writer gone the three
54-/// itself now, which holds across replicas.) The subject delete takes the writer54+// reader leases guarded nothing, and what they claimed to guard was already
55-/// lease across the cascade that clears `subject` off every template, so a55+// open in production: the lock ordered one process, and the backend runs two.
56-/// template can't land on a subject that vanished mid-flight (it would outlive56+//
57-/// the sweep) — the bank twin of the57+// The race it leaves is the one the cascade already accepts — a template can
58-/// [`super::exams::EXAM_LOCK`]/[`super::homework::HOMEWORK_LOCK`] guards.58+// adopt a subject the same instant it is deleted and be left holding a dangling
59-/// Save-to-bank (`question_to_bank`) takes the same reader lease across its59+// id. Every read tolerates that: `subject_name` resolves to empty, exactly as
60-/// question read and insert: the source question can be re-tagged/deleted, so60+// it does for the templates the cascade did clear.
61-/// its subject isn't otherwise pinned. Held after EXAM_LOCK/HOMEWORK_LOCK in
62-/// the delete path; bank writers take only this one, so no cycle.
63-pub(crate) static BANK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
64 61
65 pub fn routes() -> OpenApiRouter<AppState> {62 pub fn routes() -> OpenApiRouter<AppState> {
66 OpenApiRouter::new()63 OpenApiRouter::new()
@@ -435,9 +432,6 @@ async fn create_question(
435 RequireTeacher(user): RequireTeacher,432 RequireTeacher(user): RequireTeacher,
436 Json(req): Json<CreateBankQuestion>,433 Json(req): Json<CreateBankQuestion>,
437 ) -> Result<(StatusCode, Json<BankQuestionResponse>), AppError> {434 ) -> Result<(StatusCode, Json<BankQuestionResponse>), AppError> {
438- // Reader lease of [`BANK_LOCK`]: the exists-check and the insert are one
439- // unit, so a subject delete can't slip between them (see the lock's doc).
440- let _guard = BANK_LOCK.read().await;
441 // Origin metadata only — no course to check it against, but it must exist.435 // Origin metadata only — no course to check it against, but it must exist.
442 let subject = subject_must_exist(&req.subject_id, &st.db).await?;436 let subject = subject_must_exist(&req.subject_id, &st.db).await?;
443 let text = QuestionText::try_new(&req.text)?;437 let text = QuestionText::try_new(&req.text)?;
@@ -627,14 +621,6 @@ async fn update_question(
627 Path(bid): Path<String>,621 Path(bid): Path<String>,
628 Json(req): Json<UpdateBankQuestion>,622 Json(req): Json<UpdateBankQuestion>,
629 ) -> Result<Json<BankQuestionResponse>, AppError> {623 ) -> Result<Json<BankQuestionResponse>, AppError> {
630- // Reader lease of [`BANK_LOCK`], exactly like the create path and for the
631- // one thing it buys: the subject-exists check below is paired with the
632- // subject delete that sweeps this table (that cascade takes the writer
633- // lease), so a template cannot be pinned to a subject on its way out. It is
634- // replica-local, like every lock here. The *writer* lease this used to take
635- // was aimed at the read-modify-write below, which it only serialized inside
636- // one process — that is now a compare-and-set on the row itself.
637- let _guard = BANK_LOCK.read().await;
638 // Read, merge and write again while the row keeps moving underneath: the624 // Read, merge and write again while the row keeps moving underneath: the
639 // guarded write refuses on a snapshot that has gone stale, so both edits625 // guarded write refuses on a snapshot that has gone stale, so both edits
640 // land instead of the later one reverting the earlier.626 // land instead of the later one reverting the earlier.
src/web/courses.rsmodified+16 -32
@@ -12,7 +12,7 @@ use crate::database::Database;
12 use crate::domain::answer_image::AnswerImage;12 use crate::domain::answer_image::AnswerImage;
13 use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};13 use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};
14 use crate::domain::course_session::{CourseSession, SessionTopic};14 use crate::domain::course_session::{CourseSession, SessionTopic};
15-use crate::domain::enrollment::{ENROLL_LOCK, Enrollment};15+use crate::domain::enrollment::Enrollment;
16 use crate::domain::exam::{16 use crate::domain::exam::{
17 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule,17 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule,
18 ExamTitle,18 ExamTitle,
@@ -23,13 +23,12 @@ use crate::domain::question_image::QuestionImage;
23 use crate::domain::role::Role;23 use crate::domain::role::Role;
24 use crate::domain::settings::Settings;24 use crate::domain::settings::Settings;
25 use crate::domain::subject::{Subject, SubjectDescription, SubjectName};25 use crate::domain::subject::{Subject, SubjectDescription, SubjectName};
26-use crate::domain::term::TERM_LOCK;
27 use crate::domain::timestamp::Timestamp;26 use crate::domain::timestamp::Timestamp;
28 use crate::domain::user::{User, UserId};27 use crate::domain::user::{User, UserId};
29 use crate::error::{AppError, ErrorResponse, ValidationError};28 use crate::error::{AppError, ErrorResponse, ValidationError};
30 use crate::state::AppState;29 use crate::state::AppState;
31 30
32-use super::homework::{HOMEWORK_LOCK, description_or_none, resolve_assigned};31+use super::homework::{description_or_none, resolve_assigned};
33 use super::sessions::resolve_session_teacher;32 use super::sessions::resolve_session_teacher;
34 use super::subjects::subject_in_course;33 use super::subjects::subject_in_course;
35 use super::terms::resolve_term;34 use super::terms::resolve_term;
@@ -274,13 +273,9 @@ async fn create_course(
274 Some(ref kind) => CourseKind::try_new(kind)?,273 Some(ref kind) => CourseKind::try_new(kind)?,
275 None => CourseKind::course(),274 None => CourseKind::course(),
276 };275 };
277- // [`TERM_LOCK`] holds the term lookup and the save together, so the link276+ // Pre-flight only: [`Course::create`] claims a reference on the term before
278- // can't be written onto a term a concurrent delete just cleared. Only a277+ // it writes the link, and a term deleted in between fails that claim with
279- // write that actually links a term needs it.278+ // this very error — so an unknown id reads the same whichever side wins.
280- let _term_guard = match req.term_id {
281- Some(_) => Some(TERM_LOCK.lock().await),
282- None => None,
283- };
284 let term = resolve_term(req.term_id.as_deref(), &st.db).await?;279 let term = resolve_term(req.term_id.as_deref(), &st.db).await?;
285 check_capacity(req.capacity)?;280 check_capacity(req.capacity)?;
286 let course = Course::create(281 let course = Course::create(
@@ -441,12 +436,6 @@ async fn update_course(
441 .map(CourseDescription::try_new)436 .map(CourseDescription::try_new)
442 .transpose()?;437 .transpose()?;
443 let kind = req.kind.as_deref().map(CourseKind::try_new).transpose()?;438 let kind = req.kind.as_deref().map(CourseKind::try_new).transpose()?;
444- // Same [`TERM_LOCK`] window as create — held over the lookup and the save
445- // whenever this PATCH links a term (clearing or omitting needs no guard).
446- let _term_guard = match req.term_id {
447- Some(Some(_)) => Some(TERM_LOCK.lock().await),
448- _ => None,
449- };
450 // Both columns are nullable, so both stay clearable: omitted is `None`439 // Both columns are nullable, so both stay clearable: omitted is `None`
451 // (keep), an explicit `null` is `Some(None)` (write `NONE`).440 // (keep), an explicit `null` is `Some(None)` (write `NONE`).
452 let term = match req.term_id {441 let term = match req.term_id {
@@ -499,21 +488,18 @@ async fn delete_course(
499 "only the course creator or a manager/admin can delete this course",488 "only the course creator or a manager/admin can delete this course",
500 ));489 ));
501 }490 }
502- // [`ENROLL_LOCK`] holds the roster check and the delete together, so an
503- // enroll that just passed its capacity check can't land its row on a
504- // course that vanished mid-flight.
505- let _guard = ENROLL_LOCK.lock().await;
506- if Enrollment::any_for_course(course.get_id(), &st.db).await? {
507- return Err(AppError::Conflict(
508- "students are still enrolled in this course — remove them first",
509- ));
510- }
511 // Rows go first (the delete cascades them), blobs after — a crash in491 // Rows go first (the delete cascades them), blobs after — a crash in
512- // between strands at worst an unreachable blob.492+ // between strands at worst an unreachable blob. The keys are read before
493+ // the delete because it takes their rows with it; a refused delete just
494+ // drops them unused.
513 let image_files = QuestionImage::file_keys_for_course(course.get_id(), &st.db).await?;495 let image_files = QuestionImage::file_keys_for_course(course.get_id(), &st.db).await?;
514 let answer_image_files = AnswerImage::file_keys_for_course(course.get_id(), &st.db).await?;496 let answer_image_files = AnswerImage::file_keys_for_course(course.get_id(), &st.db).await?;
515 let homework_files = HomeworkFile::file_keys_for_course(course.get_id(), &st.db).await?;497 let homework_files = HomeworkFile::file_keys_for_course(course.get_id(), &st.db).await?;
516- course.delete(&st.db).await?;498+ if !course.delete(&st.db).await? {
499+ return Err(AppError::Conflict(
500+ "students are still enrolled in this course — remove them first",
501+ ));
502+ }
517 for file in image_files503 for file in image_files
518 .iter()504 .iter()
519 .chain(&answer_image_files)505 .chain(&answer_image_files)
@@ -1048,11 +1034,9 @@ async fn create_homework_in_course(
1048 };1034 };
1049 let due_at = Timestamp::from_millis(req.due_at);1035 let due_at = Timestamp::from_millis(req.due_at);
1050 check_not_past("due_at", Some(due_at))?;1036 check_not_past("due_at", Some(due_at))?;
1051- // Reader lease of [`HOMEWORK_LOCK`], held from the subject check through1037+ // No lease: the create takes the subject's reference counter in the same
1052- // the create: a subject delete (a writer, which checks for homework) can't1038+ // breath as the row, and the subject delete is refused while that counter
1053- // vanish the subject between its validation here and the row landing with1039+ // is non-zero — so the check below is only a pre-flight for the message.
1054- // it.
1055- let _guard = HOMEWORK_LOCK.read().await;
1056 let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;1040 let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;
1057 let assigned = resolve_assigned(req.assigned, course.get_id(), &st.db).await?;1041 let assigned = resolve_assigned(req.assigned, course.get_id(), &st.db).await?;
1058 let homework = Homework::create(1042 let homework = Homework::create(
src/web/exam_ws.rsmodified+7 -0
@@ -396,6 +396,13 @@ async fn handle_message(
396 // of [`EXAM_LOCK`] from the gates through the upsert, exactly396 // of [`EXAM_LOCK`] from the gates through the upsert, exactly
397 // like `save_answer_checked` — and dropped before the socket397 // like `save_answer_checked` — and dropped before the socket
398 // sends, so a slow client never stalls a writer.398 // sends, so a slow client never stalls a writer.
399+ //
400+ // ponytail (accepted race, reviewed): the lease is process-local,
401+ // so across replicas a save already in flight can land on the
402+ // room's sitting just after a retake made it terminal. It writes a
403+ // history row for the old seq; the grade of record (latest seq) is
404+ // untouched. The fix is a `current_seq` claim on every save — the
405+ // hottest path here — so the cost beats the damage and it stays.
399 let guard = EXAM_LOCK.read().await;406 let guard = EXAM_LOCK.read().await;
400 // Tracks how far the gates got: only once the sitting resolved can407 // Tracks how far the gates got: only once the sitting resolved can
401 // a failure possibly be about this one question rather than about408 // a failure possibly be about this one question rather than about
src/web/exams/attempts.rsmodified+8 -0
@@ -665,6 +665,14 @@ pub(crate) async fn save_answer_checked(
665 // Reader lease of [`EXAM_LOCK`]: the writable gate and the upsert are665 // Reader lease of [`EXAM_LOCK`]: the writable gate and the upsert are
666 // one unit, or a retake's wipe-and-create (a writer) slips in between666 // one unit, or a retake's wipe-and-create (a writer) slips in between
667 // and this stale save lands on the fresh blank sheet.667 // and this stale save lands on the fresh blank sheet.
668+ //
669+ // ponytail (accepted race, reviewed): the lease is process-local, so with
670+ // more than one replica a save that started just before a retake can still
671+ // stamp its answer onto the *old* seq, milliseconds after that sitting went
672+ // terminal. Damage is confined to a history row — the grade of record is
673+ // the latest seq, which the late write never touches. Closing it needs a
674+ // `current_seq` claim on every answer save, the hottest path in the app;
675+ // cost beats the damage, so it stays open on purpose.
668 let _guard = EXAM_LOCK.read().await;676 let _guard = EXAM_LOCK.read().await;
669 let attempt = writable_attempt(exam, user, db).await?;677 let attempt = writable_attempt(exam, user, db).await?;
670 save_answer_in(exam, &attempt, question_id, selected, text, db).await678 save_answer_in(exam, &attempt, question_id, selected, text, db).await
src/web/exams/mod.rsmodified+48 -15
@@ -78,19 +78,22 @@ impl Scheduled for Exam {
78 ///78 ///
79 /// Read side — the answer saves (REST and the exam room), from the79 /// Read side — the answer saves (REST and the exam room), from the
80 /// writable-attempt gate through the upsert; the grade write (draft gate80 /// writable-attempt gate through the upsert; the grade write (draft gate
81-/// through the result upsert); the exam PATCH, whose mode/re-draft gates count81+/// through the result upsert); and the exam PATCH, whose mode/re-draft gates
82-/// attempts and results; and the three question writes that first check a82+/// count attempts and results. These stay concurrent with each other.
83-/// subject belongs to the course. These stay concurrent with each other.
84 ///83 ///
85-/// Write side — attempt starts (the max-attempts count and the retake's answer84+/// Write side — attempt starts alone (the max-attempts count and the retake's
86-/// wipe) and the subject delete's cascade. So a save can never land on a sheet85+/// answer wipe). So a save can never land on a sheet a retake just wiped, and a
87-/// a retake just wiped, a mark can never land on an exam mid-flight into86+/// mark can never land on an exam mid-flight into hiding.
88-/// hiding, and a question can never adopt a subject being swept.
89 ///87 ///
90-/// The question freeze gate is *not* on this list any more: it rides inside88+/// Two rules have left this list. The question freeze gate rides inside each
91-/// each question/image write's own transaction89+/// question/image write's own transaction
92 /// ([`crate::domain::exam_attempt::ExamAttempt::unfrozen`]), and the exam PATCH90 /// ([`crate::domain::exam_attempt::ExamAttempt::unfrozen`]), and the exam PATCH
93-/// no longer needs the writer lease because its save is a compare-and-set.91+/// no longer needs the writer lease because its save is a compare-and-set. The
92+/// subject delete's cascade — the only writer outside attempt starts, paired
93+/// with the question writes' subject check — is now a conditional statement on
94+/// the subject's own reference counter
95+/// ([`crate::domain::subject::Subject::delete`]), which every question create,
96+/// re-tag and delete moves.
94 // ponytail: global RwLock, shard per-exam if save latency ever matters.97 // ponytail: global RwLock, shard per-exam if save latency ever matters.
95 pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());98 pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
96 99
@@ -162,7 +165,9 @@ struct UpdateExam {
162 description: Option<String>,165 description: Option<String>,
163 /// The assessment form — one of the school's exam kinds (`GET /settings`).166 /// The assessment form — one of the school's exam kinds (`GET /settings`).
164 /// Changing it re-weights the exam: the course average uses the kind's167 /// Changing it re-weights the exam: the course average uses the kind's
165- /// settings-configured weight.168+ /// settings-configured weight. For that reason an exam that already carries
169+ /// marks keeps its kind (`409`) — those marks would silently re-weight,
170+ /// exactly what the settings' kind-removal guard refuses.
166 kind: Option<String>,171 kind: Option<String>,
167 /// `sync`, `async`, or `open`. Omit to keep the current mode; send `null`172 /// `sync`, `async`, or `open`. Omit to keep the current mode; send `null`
168 /// to turn the exam back into an offline-graded one. Frozen once anyone173 /// to turn the exam back into an offline-graded one. Frozen once anyone
@@ -385,7 +390,7 @@ async fn get_exam(
385 (status = 401, description = "Not authenticated", body = ErrorResponse),390 (status = 401, description = "Not authenticated", body = ErrorResponse),
386 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),391 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
387 (status = 404, description = "Not found", body = ErrorResponse),392 (status = 404, description = "Not found", body = ErrorResponse),
388- (status = 409, description = "Mode change after attempts started, re-drafting an exam that has attempts or results, or the exam kept changing under concurrent edits", body = ErrorResponse),393+ (status = 409, description = "Mode change after attempts started, re-drafting an exam that has attempts or results, a kind change on an exam that already carries marks, or the exam kept changing under concurrent edits", body = ErrorResponse),
389 ),394 ),
390 )]395 )]
391 async fn update_exam(396 async fn update_exam(
@@ -502,6 +507,19 @@ async fn update_exam(
502 }507 }
503 }508 }
504 509
510+ // A graded exam keeps its kind. Moving it re-weights every mark it
511+ // already carries — the same silent re-weighting the settings' removal
512+ // guard refuses — and it would strand those marks' references on the
513+ // kind they were counted under, freeing the kind the exam now claims to
514+ // be. Marks are counted on the exam row, and the save below *pins* that
515+ // counter, so a grade landing between this read and the write refuses
516+ // the save (the loop then re-reads and answers the 409 below).
517+ if kind.as_str() != exam.get_kind().as_str() && exam.get_result_count() > 0 {
518+ return Err(AppError::Conflict(
519+ "cannot change the kind of an exam that already has marks",
520+ ));
521+ }
522+
505 if let Some(updated) = exam523 if let Some(updated) = exam
506 .update_if_unchanged(524 .update_if_unchanged(
507 title,525 title,
@@ -594,7 +612,7 @@ async fn delete_exam(
594 (status = 401, description = "Not authenticated", body = ErrorResponse),612 (status = 401, description = "Not authenticated", body = ErrorResponse),
595 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse),613 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse),
596 (status = 404, description = "Exam not found", body = ErrorResponse),614 (status = 404, description = "Exam not found", body = ErrorResponse),
597- (status = 409, description = "The exam is a draft", body = ErrorResponse),615+ (status = 409, description = "The exam is a draft, or its kind has been removed from the school's settings", body = ErrorResponse),
598 ),616 ),
599 )]617 )]
600 async fn grade(618 async fn grade(
@@ -669,7 +687,16 @@ async fn grade(
669 let seq = ExamAttempt::read_latest_for_user(&exam_id, &target, &st.db)687 let seq = ExamAttempt::read_latest_for_user(&exam_id, &target, &st.db)
670 .await?688 .await?
671 .map_or(1, |a| a.get_seq());689 .map_or(1, |a| a.get_seq());
672- let result = ExamResult::grade(&exam_id, &target, seq, mark, teacher.get_id(), &st.db).await?;690+ let result = ExamResult::grade(
691+ &exam_id,
692+ &target,
693+ seq,
694+ mark,
695+ teacher.get_id(),
696+ exam.get_kind().as_str(),
697+ &st.db,
698+ )
699+ .await?;
673 let people = PersonRef::map_of(&[&target_user, &teacher]);700 let people = PersonRef::map_of(&[&target_user, &teacher]);
674 Ok(Json(ExamResultResponse::new(&result, &people)))701 Ok(Json(ExamResultResponse::new(&result, &people)))
675 }702 }
@@ -790,7 +817,13 @@ async fn remove_result(
790 "only the course creator, an assigned teacher, or a manager/admin can remove results",817 "only the course creator, an assigned teacher, or a manager/admin can remove results",
791 ));818 ));
792 }819 }
793- let removed = ExamResult::remove(exam.get_id(), &UserId::from_key(&target), &st.db).await?;820+ let removed = ExamResult::remove(
821+ exam.get_id(),
822+ &UserId::from_key(&target),
823+ exam.get_kind().as_str(),
824+ &st.db,
825+ )
826+ .await?;
794 if removed.is_none() {827 if removed.is_none() {
795 return Err(AppError::NotFound);828 return Err(AppError::NotFound);
796 }829 }
src/web/exams/questions.rsmodified+11 -20
@@ -218,11 +218,10 @@ pub(crate) async fn create_question(
218 "only the course creator, an assigned teacher, or a manager/admin can author questions",218 "only the course creator, an assigned teacher, or a manager/admin can author questions",
219 ));219 ));
220 }220 }
221- // Reader lease of [`EXAM_LOCK`], for the subject check alone: a subject221+ // No lease: the subject check below is only a pre-flight for the message,
222- // delete (which takes the writer lease) must not invalidate a subject this222+ // and the insert takes the subject's reference counter in the same breath —
223- // just validated. Replica-local, like every lock here. The freeze gate no223+ // a subject delete lands either wholly before it (400) or is refused. The
224- // longer needs the lease — it rides inside the insert's own transaction.224+ // freeze gate rides inside the insert's own transaction.
225- let _guard = EXAM_LOCK.read().await;
226 ensure_questions_editable(exam.get_id(), &st.db).await?;225 ensure_questions_editable(exam.get_id(), &st.db).await?;
227 226
228 let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;227 let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;
@@ -346,9 +345,8 @@ pub(crate) async fn update_question(
346 "only the course creator, an assigned teacher, or a manager/admin can edit questions",345 "only the course creator, an assigned teacher, or a manager/admin can edit questions",
347 ));346 ));
348 }347 }
349- // Reader lease of [`EXAM_LOCK`] for the subject check — see348+ // No lease — see `create_question`; a re-tag moves the subject's reference
350- // `create_question`. The freeze gate rides in the update's transaction.349+ // counter, and the freeze gate rides in the update's transaction.
351- let _guard = EXAM_LOCK.read().await;
352 ensure_questions_editable(exam.get_id(), &st.db).await?;350 ensure_questions_editable(exam.get_id(), &st.db).await?;
353 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;351 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
354 352
@@ -504,9 +502,8 @@ pub(crate) async fn question_from_bank(
504 "only the course creator, an assigned teacher, or a manager/admin can author questions",502 "only the course creator, an assigned teacher, or a manager/admin can author questions",
505 ));503 ));
506 }504 }
507- // Reader lease of [`EXAM_LOCK`] for the subject check — same reasoning as505+ // No lease — same reasoning as `create_question`. The freeze gate rides in
508- // `create_question`. The freeze gate rides in the insert's transaction.506+ // the insert's transaction.
509- let _guard = EXAM_LOCK.read().await;
510 ensure_questions_editable(exam.get_id(), &st.db).await?;507 ensure_questions_editable(exam.get_id(), &st.db).await?;
511 let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;508 let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;
512 509
@@ -758,12 +755,9 @@ pub(crate) async fn question_to_bank(
758 "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank",755 "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank",
759 ));756 ));
760 }757 }
761- // Reader lease of [`BANK_LOCK`] across the question read and the insert: the758+ // No lease: `BANK_LOCK` is gone with the subject delete's writer lease, and
762- // template adopts the question's subject, so without it a subject delete759+ // a template left holding a deleted subject reads as an empty
763- // could slip between the two and leave the fresh template pointing at a760+ // `subject_name` either way (see [`crate::web::bank_questions`]).
764- // subject its cascade had already swept (that cascade runs under BANK_LOCK's
765- // writer lease, so holding the reader lease orders us either side of it).
766- let _bank_guard = crate::web::bank_questions::BANK_LOCK.read().await;
767 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;761 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
768 762
769 // `create_from_exam` mints its own id and insert (the funnel), fed the763 // `create_from_exam` mints its own id and insert (the funnel), fed the
@@ -825,9 +819,6 @@ pub(crate) async fn question_to_bank(
825 // template silently vanishing over a metadata write is worse than a819 // template silently vanishing over a metadata write is worse than a
826 // template with no back-link (the next save re-links it).820 // template with no back-link (the next save re-links it).
827 let question_key = question.get_id().key().to_string();821 let question_key = question.get_id().key().to_string();
828- // The bank lease has done its job (the template is inserted, its subject
829- // pinned); hand it back before the link write.
830- drop(_bank_guard);
831 // No exam lease around the back-link any more, and none is needed: this is a822 // No exam lease around the back-link any more, and none is needed: this is a
832 // single-column `UPDATE`, and `ExamQuestion::update` no longer re-states823 // single-column `UPDATE`, and `ExamQuestion::update` no longer re-states
833 // this column from a snapshot (it names the columns it writes), so a824 // this column from a snapshot (it names the columns it writes), so a
src/web/homework.rsmodified+86 -41
@@ -44,15 +44,31 @@ use super::{
44 44
45 /// Serializes the homework subsystem's cross-record check-then-writes, which45 /// Serializes the homework subsystem's cross-record check-then-writes, which
46 /// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as46 /// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as
47-/// [`crate::web::exams::EXAM_LOCK`]. The class of bug: a submission stays47+/// [`crate::web::exams::EXAM_LOCK`]. It is a *within-replica* guard only, so
48-/// editable only *until a result exists*, so the "no grade yet" read and the48+/// the rule it can no longer be trusted with is the freeze: a graded submission
49-/// submission write that depends on it must not straddle a concurrent grade,49+/// used to stay unedited because the "no grade yet" read and the write it
50-/// and a homework delete must not race a submission landing under it. Read side50+/// licensed sat under one lease, which two processes never shared. That rule
51-/// (steps 3/4): the student's submission and file writes, held from the51+/// moved into the database — grading stamps
52-/// ungraded gate through the upsert, concurrent with each other. Write side:52+/// [`crate::constant::SUBMISSION_GRADED_FIELD`] on the submission row and every
53-/// grade/ungrade (steps 3/4) and the homework-delete cascade here. Lock order,53+/// student-side write carries `graded_by_result = NONE` as its own condition.
54-/// where both are taken: `HOMEWORK_LOCK` before the file-cap `Mutex`, never the54+///
55-/// reverse.55+/// What still leases it, honestly:
56+/// - Write: the homework PATCH's orphan guard ([`update_homework`]), the
57+/// homework-delete cascade ([`delete_homework`]), and grade/ungrade — which
58+/// read the homework itself under the lease so a concurrent delete can't
59+/// leave a result row under a vanished homework.
60+/// - Read: the student's submission/file writes, which no longer gate the
61+/// freeze but still must not land under a PATCH re-scoping the audience out
62+/// from under them.
63+///
64+/// The subject rule has left: creating a homework and re-tagging one move the
65+/// subject's reference counter, and the subject delete is refused while that
66+/// counter is non-zero ([`crate::domain::subject::Subject::delete`]), so
67+/// neither the create ([`super::courses`]) nor the outside writer the subject
68+/// delete used to take is on this list any more.
69+///
70+/// Lock order, where both are taken: `HOMEWORK_LOCK` before the counter lock in
71+/// [`crate::domain::cap`], never the reverse.
56 // ponytail: global RwLock, shard per-homework if write latency ever matters.72 // ponytail: global RwLock, shard per-homework if write latency ever matters.
57 pub(crate) static HOMEWORK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());73 pub(crate) static HOMEWORK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
58 74
@@ -299,8 +315,9 @@ async fn update_homework(
299 // Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the315 // Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the
300 // live submissions and results, and the row write depends on what it saw —316 // live submissions and results, and the row write depends on what it saw —
301 // without the lease a submission (a reader) could land between the check317 // without the lease a submission (a reader) could land between the check
302- // and the write, orphaned by the narrowing that just missed it. The lease318+ // and the write, orphaned by the narrowing that just missed it. The subject
303- // also pins the subject re-tag against a concurrent subject delete.319+ // re-tag no longer needs it — it moves the two subjects' reference counters
320+ // inside `Homework::update`.
304 let _guard = HOMEWORK_LOCK.write().await;321 let _guard = HOMEWORK_LOCK.write().await;
305 322
306 // Only what the request carried: an omitted field stays `None` and is never323 // Only what the request carried: an omitted field stays `None` and is never
@@ -609,10 +626,15 @@ async fn submit(
609 Some(ref text) if !text.is_empty() => Some(SubmissionText::try_new(text)?),626 Some(ref text) if !text.is_empty() => Some(SubmissionText::try_new(text)?),
610 _ => None,627 _ => None,
611 };628 };
612- // Reader lease of HOMEWORK_LOCK, held from the graded gate through the write:629+ // Reader lease of HOMEWORK_LOCK: no longer the freeze (that is the stamp on
613- // the "no grade yet" read and the upsert that depends on it are one unit, or630+ // the row, below), but still the interlock against a PATCH re-scoping this
614- // a grade landing between them lets an edit slip onto a frozen submission.631+ // homework's audience while the submission lands under it.
615 let _guard = HOMEWORK_LOCK.read().await;632 let _guard = HOMEWORK_LOCK.read().await;
633+ // The graded gate, twice over. This read answers the common case — graded
634+ // minutes ago, and the student who never submitted has no row to carry the
635+ // freeze; the upsert's own `WHERE` (the grade stamp on the row) is what
636+ // holds when the grade lands *while* this request runs, in this replica or
637+ // the other one.
616 if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db)638 if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db)
617 .await?639 .await?
618 .is_some()640 .is_some()
@@ -621,13 +643,18 @@ async fn submit(
621 "this homework has been graded — ask the teacher to remove the grade before editing your submission",643 "this homework has been graded — ask the teacher to remove the grade before editing your submission",
622 ));644 ));
623 }645 }
624- // 201-vs-200: a prior read under the lock is exact, where comparing the646+ // 201-vs-200: a prior read is exact, where comparing the returned stamps
625- // returned stamps would misreport a same-millisecond re-submit as a create.647+ // would misreport a same-millisecond re-submit as a create.
626 let existed = HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db)648 let existed = HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db)
627 .await?649 .await?
628 .is_some();650 .is_some();
629- let submission =651+ let Some(submission) =
630- HomeworkSubmission::upsert(homework.get_id(), user.get_id(), text, &st.db).await?;652+ HomeworkSubmission::upsert(homework.get_id(), user.get_id(), text, &st.db).await?
653+ else {
654+ return Err(AppError::Conflict(
655+ "this homework has been graded — ask the teacher to remove the grade before editing your submission",
656+ ));
657+ };
631 let files = HomeworkFile::list_for_submission(submission.get_id(), &st.db).await?;658 let files = HomeworkFile::list_for_submission(submission.get_id(), &st.db).await?;
632 let status = if existed {659 let status = if existed {
633 StatusCode::OK660 StatusCode::OK
@@ -705,6 +732,7 @@ async fn delete_submission(
705 Path(id): Path<String>,732 Path(id): Path<String>,
706 ) -> Result<StatusCode, AppError> {733 ) -> Result<StatusCode, AppError> {
707 let homework = gate_own_submission(&id, &user, &st.db).await?;734 let homework = gate_own_submission(&id, &user, &st.db).await?;
735+ // Reader lease as in `submit` — the audience interlock, not the freeze.
708 let _guard = HOMEWORK_LOCK.read().await;736 let _guard = HOMEWORK_LOCK.read().await;
709 if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db)737 if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db)
710 .await?738 .await?
@@ -720,7 +748,13 @@ async fn delete_submission(
720 // Collect blob names before the cascade (submission.delete wipes the file748 // Collect blob names before the cascade (submission.delete wipes the file
721 // rows in the same transaction), then unlink after the rows are gone.749 // rows in the same transaction), then unlink after the rows are gone.
722 let files = HomeworkFile::list_for_submission(submission.get_id(), &st.db).await?;750 let files = HomeworkFile::list_for_submission(submission.get_id(), &st.db).await?;
723- submission.delete(&st.db).await?;751+ // The delete carries the freeze as its own condition, so a grade landing
752+ // since the read above refuses it rather than wiping graded work.
753+ if submission.delete(&st.db).await?.is_none() {
754+ return Err(AppError::Conflict(
755+ "this homework has been graded — ask the teacher to remove the grade before deleting your submission",
756+ ));
757+ }
724 for file in &files {758 for file in &files {
725 remove_blob(&st.files_path, file.get_file()).await;759 remove_blob(&st.files_path, file.get_file()).await;
726 }760 }
@@ -799,29 +833,33 @@ async fn upload_submission_file(
799 let name = FileName::try_new(&upload.name.unwrap_or_default())?;833 let name = FileName::try_new(&upload.name.unwrap_or_default())?;
800 let content_type = FileContentType::try_new(&upload.content_type.unwrap_or_default())?;834 let content_type = FileContentType::try_new(&upload.content_type.unwrap_or_default())?;
801 835
802- // Reader lease of HOMEWORK_LOCK, held from the graded gate through the write.836+ const GRADED: AppError = AppError::Conflict(
837+ "this homework has been graded — ask the teacher to remove the grade before adding files",
838+ );
839+ // Reader lease as in `submit` — the audience interlock, not the freeze.
840+ // Taken before the cap claim inside `insert`, never after (the lock order
841+ // is HOMEWORK_LOCK, then the counter lock).
803 let _guard = HOMEWORK_LOCK.read().await;842 let _guard = HOMEWORK_LOCK.read().await;
843+ // The common-case gate; the freeze itself rides on the writes below.
804 if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db)844 if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db)
805 .await?845 .await?
806 .is_some()846 .is_some()
807 {847 {
808- return Err(AppError::Conflict(848+ return Err(GRADED);
809- "this homework has been graded — ask the teacher to remove the grade before adding files",
810- ));
811 }849 }
812 // A submission row must exist to hang the file off; auto-create an empty one850 // A submission row must exist to hang the file off; auto-create an empty one
813 // for the photo-only case rather than force a separate text submit first.851 // for the photo-only case rather than force a separate text submit first.
814- let submission = match HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db)852+ let submission =
815- .await?853+ match HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db).await? {
816- {854+ Some(existing) => existing,
817- Some(existing) => existing,855+ None => HomeworkSubmission::upsert(homework.get_id(), user.get_id(), None, &st.db)
818- None => HomeworkSubmission::upsert(homework.get_id(), user.get_id(), None, &st.db).await?,856+ .await?
819- };857+ .ok_or(GRADED)?,
858+ };
820 859
821 // Blob first, row second — a stored row always points at a real blob. The860 // Blob first, row second — a stored row always points at a real blob. The
822- // 10-file cap is enforced inside `insert` under its own lock (order:861+ // 10-file cap and the freeze are one conditional write on the submission row
823- // HOMEWORK_LOCK then the cap Mutex, never reversed). Unlink the fresh blob if862+ // inside `insert`. Unlink the fresh blob if the row insert loses either.
824- // the row insert loses the cap race.
825 let file = HomeworkFile::new(863 let file = HomeworkFile::new(
826 submission.get_id(),864 submission.get_id(),
827 name,865 name,
@@ -833,10 +871,12 @@ async fn upload_submission_file(
833 .await871 .await
834 .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?;872 .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?;
835 let stored = match file.insert(&st.db).await {873 let stored = match file.insert(&st.db).await {
836- Ok(stored) => stored,874+ Ok(Some(stored)) => stored,
837- Err(err) => {875+ // `None` is the freeze biting, an `Err` the file cap (or worse); either
876+ // way the blob just written has no row and must go.
877+ landed => {
838 let _ = tokio::fs::remove_file(&path).await;878 let _ = tokio::fs::remove_file(&path).await;
839- return Err(err);879+ return Err(landed.err().unwrap_or(GRADED));
840 }880 }
841 };881 };
842 // A landed file moves the submission's "last touched" clock (the late flag).882 // A landed file moves the submission's "last touched" clock (the late flag).
@@ -923,24 +963,29 @@ async fn delete_submission_file(
923 Path((id, fid)): Path<(String, String)>,963 Path((id, fid)): Path<(String, String)>,
924 ) -> Result<StatusCode, AppError> {964 ) -> Result<StatusCode, AppError> {
925 let homework = gate_own_submission(&id, &user, &st.db).await?;965 let homework = gate_own_submission(&id, &user, &st.db).await?;
966+ const GRADED: AppError = AppError::Conflict(
967+ "this homework has been graded — ask the teacher to remove the grade before deleting files",
968+ );
969+ // Reader lease as in `submit` — the audience interlock, not the freeze.
926 let _guard = HOMEWORK_LOCK.read().await;970 let _guard = HOMEWORK_LOCK.read().await;
927 if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db)971 if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db)
928 .await?972 .await?
929 .is_some()973 .is_some()
930 {974 {
931- return Err(AppError::Conflict(975+ return Err(GRADED);
932- "this homework has been graded — ask the teacher to remove the grade before deleting files",
933- ));
934 }976 }
935 let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id());977 let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id());
936 let file = HomeworkFile::read_for(&HomeworkFileId::from_key(&fid), &submission, &st.db)978 let file = HomeworkFile::read_for(&HomeworkFileId::from_key(&fid), &submission, &st.db)
937 .await?979 .await?
938 .ok_or(AppError::NotFound)?;980 .ok_or(AppError::NotFound)?;
939 let blob = file.get_file().to_string();981 let blob = file.get_file().to_string();
940- file.delete(&st.db).await?;982+ // The delete's own transaction re-stamps the submission's "last touched"
983+ // clock (the late flag) as its freeze gate, so a refused delete moves
984+ // nothing and no separate touch is owed here.
985+ if file.delete(&st.db).await?.is_none() {
986+ return Err(GRADED);
987+ }
941 remove_blob(&st.files_path, &blob).await;988 remove_blob(&st.files_path, &blob).await;
942- // A removed file moves the submission's "last touched" clock (the late flag).
943- HomeworkSubmission::touch(&submission, &st.db).await?;
944 Ok(StatusCode::NO_CONTENT)989 Ok(StatusCode::NO_CONTENT)
945 }990 }
946 991
src/web/meals.rsmodified+17 -23
@@ -242,7 +242,7 @@ async fn one_menu(
242 (status = 400, description = "Malformed date, unknown slot, or out-of-range capacity", body = ErrorResponse),242 (status = 400, description = "Malformed date, unknown slot, or out-of-range capacity", body = ErrorResponse),
243 (status = 401, description = "Not authenticated", body = ErrorResponse),243 (status = 401, description = "Not authenticated", body = ErrorResponse),
244 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),244 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
245- (status = 409, description = "A menu already exists for that date and slot", body = ErrorResponse),245+ (status = 409, description = "A menu already exists for that date and slot, or the slot was removed from the settings mid-request", body = ErrorResponse),
246 ),246 ),
247 )]247 )]
248 async fn create_menu(248 async fn create_menu(
@@ -371,14 +371,8 @@ async fn delete_menu(
371 let menu = Menu::read(&MenuId::from_key(&id), &st.db)371 let menu = Menu::read(&MenuId::from_key(&id), &st.db)
372 .await?372 .await?
373 .ok_or(AppError::NotFound)?;373 .ok_or(AppError::NotFound)?;
374- // [`MENU_LOCK`] holds the seat check and the delete together, so a booking374+ // The seat check rides in the delete's own `WHERE` (see `Menu::delete`), so
375- // cannot land on a menu that is already on its way out.375+ // a booking landing in another replica cannot slip between the two.
376- let _guard = MENU_LOCK.lock().await;
377- if MealBooking::any_live_for_menu(menu.get_id(), &st.db).await? {
378- return Err(AppError::Conflict(
379- "the menu still has live bookings — cancel them first",
380- ));
381- }
382 menu.delete(&st.db).await?;376 menu.delete(&st.db).await?;
383 Ok(StatusCode::NO_CONTENT)377 Ok(StatusCode::NO_CONTENT)
384 }378 }
@@ -416,15 +410,15 @@ async fn add_dish(
416 .flatten();410 .flatten();
417 let price = DishPrice::try_new(req.price_minor)?;411 let price = DishPrice::try_new(req.price_minor)?;
418 let tags = DishTags::try_new(&req.tags, &Settings::load(&st.db).await?.get_dietary_tags())?;412 let tags = DishTags::try_new(&req.tags, &Settings::load(&st.db).await?.get_dietary_tags())?;
419- // Dish writes take [`MENU_LOCK`] because a booking snapshots the menu's413+ // Dish writes take [`MENU_LOCK`] for the dish cap alone: count-then-write
420- // price under it: a dish landing mid-booking would be stored on the seat as414+ // is write-skew, so the count and the insert have to be one step. The
421- // "the menu was free", and a held seat is never re-priced. It also makes415+ // *price* no longer needs it — a dish write moves the menu's revision, and
422- // the dish cap a real cap — count-then-write is write-skew otherwise. The416+ // a booking claims its seat at the revision it priced itself against.
423- // lock stays a leaf: nothing below here takes another.417+ // The lock stays a leaf: nothing below here takes another.
424 let _guard = MENU_LOCK.lock().await;418 let _guard = MENU_LOCK.lock().await;
425- // The menu is read *inside* the lock, like `MealBooking::book` does: read419+ // The menu is read *inside* the lock: read before it, a `DELETE /menus/{id}`
426- // before it, a `DELETE /menus/{id}` running in the gap takes its cascade420+ // running in the gap takes its cascade with it and this dish lands on a menu
427- // with it and this dish lands on a menu that no longer exists.421+ // that no longer exists.
428 let menu = Menu::read(&MenuId::from_key(&id), &st.db)422 let menu = Menu::read(&MenuId::from_key(&id), &st.db)
429 .await?423 .await?
430 .ok_or(AppError::NotFound)?;424 .ok_or(AppError::NotFound)?;
@@ -810,7 +804,7 @@ async fn booking_target(
810 (status = 401, description = "Not authenticated", body = ErrorResponse),804 (status = 401, description = "Not authenticated", body = ErrorResponse),
811 (status = 403, description = "Not a student booking for themselves, nor a parent booking for a linked student", body = ErrorResponse),805 (status = 403, description = "Not a student booking for themselves, nor a parent booking for a linked student", body = ErrorResponse),
812 (status = 404, description = "No such menu", body = ErrorResponse),806 (status = 404, description = "No such menu", body = ErrorResponse),
813- (status = 409, description = "The menu is full, or its cutoff has passed", body = ErrorResponse),807+ (status = 409, description = "The menu is full, its cutoff has passed, or the menu kept being edited while the seat was being taken", body = ErrorResponse),
814 ),808 ),
815 )]809 )]
816 async fn book_meal(810 async fn book_meal(
@@ -822,10 +816,10 @@ async fn book_meal(
822 let student = booking_target(&user, req.student_id.as_deref(), &st.db).await?;816 let student = booking_target(&user, req.student_id.as_deref(), &st.db).await?;
823 let cutoff = meal_cutoff(&st.db).await?;817 let cutoff = meal_cutoff(&st.db).await?;
824 let menu = MenuId::from_key(&id);818 let menu = MenuId::from_key(&id);
825- // Price, seat and charge all land together under `MENU_LOCK`, keyed by819+ // Price, seat and charge land as one decision (see `MealBooking::book`),
826- // (seat, attempt) — a double-click books one seat and bills it once, and a820+ // keyed by (seat, attempt) — a double-click books one seat and bills it
827- // dish cannot slip in between the price snapshot and the row it is frozen821+ // once, and a dish landing between the price and the seat is refused by the
828- // onto.822+ // claim rather than billed.
829 let booking = MealBooking::book(&menu, &student, user.get_id(), &cutoff, &st.db).await?;823 let booking = MealBooking::book(&menu, &student, user.get_id(), &cutoff, &st.db).await?;
830 let items = booking_responses(std::slice::from_ref(&booking), &st.db).await?;824 let items = booking_responses(std::slice::from_ref(&booking), &st.db).await?;
831 Ok((825 Ok((
@@ -927,7 +921,7 @@ async fn list_menu_bookings(
927 (status = 401, description = "Not authenticated", body = ErrorResponse),921 (status = 401, description = "Not authenticated", body = ErrorResponse),
928 (status = 403, description = "Not the booking's student, nor their parent", body = ErrorResponse),922 (status = 403, description = "Not the booking's student, nor their parent", body = ErrorResponse),
929 (status = 404, description = "Not found", body = ErrorResponse),923 (status = 404, description = "Not found", body = ErrorResponse),
930- (status = 409, description = "The cutoff has passed", body = ErrorResponse),924+ (status = 409, description = "The cutoff has passed, or the menu was too contended to free the seat", body = ErrorResponse),
931 ),925 ),
932 )]926 )]
933 async fn cancel_booking(927 async fn cancel_booking(
src/web/settings.rsmodified+111 -53
@@ -5,14 +5,17 @@ use utoipa::ToSchema;
5 use utoipa_axum::router::OpenApiRouter;5 use utoipa_axum::router::OpenApiRouter;
6 use utoipa_axum::routes;6 use utoipa_axum::routes;
7 7
8+use surrealdb::types::RecordId;
9+
8 use crate::constant::CAS_UPDATE_RETRIES;10 use crate::constant::CAS_UPDATE_RETRIES;
9-use crate::domain::exam_result::ExamResult;11+use crate::database::Database;
10-use crate::domain::menu::{MENU_LOCK, Menu};12+use crate::domain::cap;
13+use crate::domain::exam_result::kind_ref;
14+use crate::domain::menu::slot_ref;
11 use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings};15 use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings};
12 use crate::error::{AppError, ErrorResponse};16 use crate::error::{AppError, ErrorResponse};
13 use crate::state::AppState;17 use crate::state::AppState;
14 18
15-use super::exams::EXAM_LOCK;
16 use super::{CurrentUser, RequireManager, set_or_clear};19 use super::{CurrentUser, RequireManager, set_or_clear};
17 20
18 pub fn routes() -> OpenApiRouter<AppState> {21 pub fn routes() -> OpenApiRouter<AppState> {
@@ -231,7 +234,8 @@ async fn get_settings(
231 /// every exam of that kind. For that reason a kind whose exams already carry234 /// every exam of that kind. For that reason a kind whose exams already carry
232 /// marks cannot be dropped from the list (409) — those marks would silently235 /// marks cannot be dropped from the list (409) — those marks would silently
233 /// re-weight to 1; an unmarked kind leaves freely, and an exam whose kind is236 /// re-weight to 1; an unmarked kind leaves freely, and an exam whose kind is
234-/// gone counts with weight 1 until the kind returns. `max_file_bytes` likewise237+/// gone counts with weight 1 but cannot be graded (409) until the kind
238+/// returns — the other end of the same rule. `max_file_bytes` likewise
235 /// applies at upload time only — already-stored files keep their size, and the239 /// applies at upload time only — already-stored files keep their size, and the
236 /// chatbot knobs apply to the next chat request only. `meal_slots` follows the240 /// chatbot knobs apply to the next chat request only. `meal_slots` follows the
237 /// exam-kind rule: a slot a menu was already published for cannot be dropped241 /// exam-kind rule: a slot a menu was already published for cannot be dropped
@@ -259,21 +263,6 @@ async fn update_settings(
259 // otherwise a concurrent PATCH of a *different* field would be silently263 // otherwise a concurrent PATCH of a *different* field would be silently
260 // reverted by whichever whole-row write lands second. A refused save264 // reverted by whichever whole-row write lands second. A refused save
261 // reloads and re-merges, so both edits land.265 // reloads and re-merges, so both edits land.
262- // Writer lease of [`EXAM_LOCK`] while the kind list is being replaced: the
263- // no-marks check below and the save are one unit, so a grade (a reader)
264- // can't land the first mark of a kind that is being dropped mid-flight.
265- let _guard = match req.exam_kinds {
266- Some(_) => Some(EXAM_LOCK.write().await),
267- None => None,
268- };
269- // Same shape for the slot list: the "was a menu ever published for it?"
270- // check and the save are one unit, so a publish cannot land on a slot that
271- // is being dropped mid-flight. Taken after EXAM_LOCK; nothing under
272- // MENU_LOCK ever takes EXAM_LOCK, so the pair cannot deadlock.
273- let _menu_guard = match req.meal_slots {
274- Some(_) => Some(MENU_LOCK.lock().await),
275- None => None,
276- };
277 for _ in 0..CAS_UPDATE_RETRIES {266 for _ in 0..CAS_UPDATE_RETRIES {
278 let current = Settings::load(&st.db).await?;267 let current = Settings::load(&st.db).await?;
279 268
@@ -284,26 +273,6 @@ async fn update_settings(
284 .collect::<Result<Vec<_>, _>>()?,273 .collect::<Result<Vec<_>, _>>()?,
285 None => current.get_exam_kinds().to_vec(),274 None => current.get_exam_kinds().to_vec(),
286 };275 };
287- // A kind that graded exams still count under cannot leave the list —
288- // weights are read live, so dropping it would silently re-weight every
289- // mark of that kind. Re-checked on every retry: the snapshot it is
290- // diffed against is the one the save is conditioned on.
291- for gone in current.get_exam_kinds().iter().filter(|kind| {
292- !exam_kinds
293- .iter()
294- .any(|new| new.get_name() == kind.get_name())
295- }) {
296- if ExamResult::any_for_kind(gone.get_name(), &st.db).await? {
297- return Err(AppError::ConflictOwned(format!(
298- "exams of kind '{}' are already graded — the kind cannot be removed",
299- gone.get_name()
300- )));
301- }
302- }
303- // Same shape for meal slots: a slot a menu was already published for
304- // cannot leave the list — the menu snapshotted the name as text, and a
305- // slot no longer offered would leave that menu unreachable from the
306- // school's own list.
307 let meal_slots = match &req.meal_slots {276 let meal_slots = match &req.meal_slots {
308 Some(slots) => slots277 Some(slots) => slots
309 .iter()278 .iter()
@@ -311,18 +280,6 @@ async fn update_settings(
311 .collect::<Result<Vec<_>, _>>()?,280 .collect::<Result<Vec<_>, _>>()?,
312 None => current.get_meal_slots(),281 None => current.get_meal_slots(),
313 };282 };
314- for gone in current.get_meal_slots().iter().filter(|slot| {
315- !meal_slots
316- .iter()
317- .any(|new| new.get_name() == slot.get_name())
318- }) {
319- if Menu::any_for_slot(gone.get_name(), &st.db).await? {
320- return Err(AppError::ConflictOwned(format!(
321- "menus are already published for the '{}' slot — it cannot be removed",
322- gone.get_name()
323- )));
324- }
325- }
326 let attendance_statuses = req283 let attendance_statuses = req
327 .attendance_statuses284 .attendance_statuses
328 .clone()285 .clone()
@@ -334,6 +291,13 @@ async fn update_settings(
334 .collect::<Result<Vec<_>, _>>()?,291 .collect::<Result<Vec<_>, _>>()?,
335 None => current.get_grade_bands().to_vec(),292 None => current.get_grade_bands().to_vec(),
336 };293 };
294+ // The name lists as they stand and as they would stand, for the removal
295+ // guards below — a list edit is judged by which names it drops.
296+ let was_kinds = kind_names(current.get_exam_kinds());
297+ 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);
300+
337 // Merge over the snapshot's resolved values: an omitted field keeps301 // Merge over the snapshot's resolved values: an omitted field keeps
338 // whatever the row (or the default behind an unset field) reads as.302 // whatever the row (or the default behind an unset field) reads as.
339 let mut params = current.params();303 let mut params = current.params();
@@ -361,11 +325,105 @@ async fn update_settings(
361 .unwrap_or(params.meal_cancel_cutoff_minutes);325 .unwrap_or(params.meal_cancel_cutoff_minutes);
362 326
363 let settings = Settings::try_new(params)?;327 let settings = Settings::try_new(params)?;
364- if let Some(saved) = settings.save_if_unchanged(&current, &st.db).await? {328+
365- return Ok(Json(SettingsResponse::new(&saved)));329+ // The removal guards. A name leaves a list by being *retired* on its
330+ // reference counter — one conditional write on one record, which lands
331+ // only while nothing references the name and refuses every claim from
332+ // that instant on. That is the whole guard: the check and the removal
333+ // used to be a cross-table count and a save held together by a
334+ // process-wide lock, which the second replica walked straight through.
335+ //
336+ // 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 save
338+ // that then does not land undoes them (`restore`) before the next try.
339+ let mut retired: Vec<RecordId> = Vec::new();
340+ let mut refused = None;
341+ for gone in missing(&was_kinds, &now_kinds) {
342+ let counter = kind_ref(&gone);
343+ if !cap::retire(&counter, &st.db).await? {
344+ refused = Some(AppError::ConflictOwned(format!(
345+ "exams of kind '{gone}' are already graded — the kind cannot be removed"
346+ )));
347+ break;
348+ }
349+ retired.push(counter);
350+ }
351+ // 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 a
353+ // slot no longer offered would leave that menu unreachable from the
354+ // school's own list.
355+ if refused.is_none() {
356+ for gone in missing(&was_slots, &now_slots) {
357+ let counter = slot_ref(&gone);
358+ if !cap::retire(&counter, &st.db).await? {
359+ refused = Some(AppError::ConflictOwned(format!(
360+ "menus are already published for the '{gone}' slot — it cannot be removed"
361+ )));
362+ break;
363+ }
364+ retired.push(counter);
365+ }
366+ }
367+ if let Some(refused) = refused {
368+ restore(&retired, &st.db).await?;
369+ return Err(refused);
370+ }
371+ // 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 (or
373+ // a menu) under a kind the school offers again must not be refused.
374+ for back in missing(&now_kinds, &was_kinds) {
375+ cap::unretire(&kind_ref(&back), &st.db).await?;
376+ }
377+ for back in missing(&now_slots, &was_slots) {
378+ cap::unretire(&slot_ref(&back), &st.db).await?;
379+ }
380+
381+ match settings.save_if_unchanged(&current, &st.db).await {
382+ Ok(Some(saved)) => return Ok(Json(SettingsResponse::new(&saved))),
383+ // The row moved under the snapshot these guards were judged against:
384+ // put the names back and re-merge, or the next attempt would decide
385+ // against a list nobody asked for.
386+ Ok(None) => restore(&retired, &st.db).await?,
387+ Err(err) => {
388+ restore(&retired, &st.db).await?;
389+ return Err(err);
390+ }
366 }391 }
367 }392 }
368 Err(AppError::Conflict(393 Err(AppError::Conflict(
369 "the settings kept changing underneath this update — try again",394 "the settings kept changing underneath this update — try again",
370 ))395 ))
371 }396 }
397+
398+fn kind_names(kinds: &[ExamKindDef]) -> Vec<String> {
399+ kinds
400+ .iter()
401+ .map(|kind| kind.get_name().to_string())
402+ .collect()
403+}
404+
405+fn slot_names(slots: &[MealSlotDef]) -> Vec<String> {
406+ slots
407+ .iter()
408+ .map(|slot| slot.get_name().to_string())
409+ .collect()
410+}
411+
412+/// The names `before` carries that `after` does not — a list edit's removals,
413+/// or its additions with the arguments swapped.
414+fn missing(before: &[String], after: &[String]) -> Vec<String> {
415+ before
416+ .iter()
417+ .filter(|name| !after.contains(name))
418+ .cloned()
419+ .collect()
420+}
421+
422+/// Put back every name this attempt retired: the edit that would have removed
423+/// them did not land, so they are still names the school offers.
424+async fn restore(names: &[RecordId], db: &Database) -> Result<(), AppError> {
425+ for name in names {
426+ cap::unretire(name, db).await?;
427+ }
428+ Ok(())
429+}
src/web/subjects.rsmodified+5 -34
@@ -8,16 +8,11 @@ use utoipa_axum::routes;
8 8
9 use crate::database::Database;9 use crate::database::Database;
10 use crate::domain::course::{Course, CourseId};10 use crate::domain::course::{Course, CourseId};
11-use crate::domain::exam_question::ExamQuestion;
12-use crate::domain::homework::Homework;
13 use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName};11 use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName};
14 use crate::error::{AppError, ErrorResponse, ValidationError};12 use crate::error::{AppError, ErrorResponse, ValidationError};
15 use crate::state::AppState;13 use crate::state::AppState;
16 14
17-use super::bank_questions::BANK_LOCK;
18 use super::courses::{can_manage_course, can_view_course};15 use super::courses::{can_manage_course, can_view_course};
19-use super::exams::EXAM_LOCK;
20-use super::homework::HOMEWORK_LOCK;
21 use super::{CurrentUser, RequireTeacher, SubjectResponse};16 use super::{CurrentUser, RequireTeacher, SubjectResponse};
22 17
23 pub fn routes() -> OpenApiRouter<AppState> {18 pub fn routes() -> OpenApiRouter<AppState> {
@@ -194,35 +189,11 @@ async fn delete_subject(
194 "only the course creator, an assigned teacher, or a manager/admin can delete this subject",189 "only the course creator, an assigned teacher, or a manager/admin can delete this subject",
195 ));190 ));
196 }191 }
197- // Writer lease of [`EXAM_LOCK`]: the no-questions check and the delete192+ // No locks: the two checks *are* the delete's `WHERE`, decided against the
198- // are one unit, so a question create/update that just validated this193+ // subject's own reference counters inside one statement. This used to be
199- // subject can't land its row on a subject that vanished mid-flight.194+ // three process-wide locks (the only site that held more than one) around
200- let _guard = EXAM_LOCK.write().await;195+ // two cross-table counts, which served one replica and let the other create
201- if ExamQuestion::any_for_subject(subject.get_id(), &st.db).await? {196+ // a question on a subject being deleted.
202- return Err(AppError::Conflict(
203- "exam questions still reference this subject — re-tag or delete them first",
204- ));
205- }
206- // The homework twin of the guard above, under [`HOMEWORK_LOCK`]'s writer
207- // lease: homework create validates its subject under the read side and the
208- // PATCH re-tag under the write side, so the no-homework check and the
209- // delete can't straddle a row that just adopted this subject. This is the
210- // only place both locks are held; the order is EXAM_LOCK, then
211- // HOMEWORK_LOCK.
212- let _homework_guard = HOMEWORK_LOCK.write().await;
213- if Homework::any_for_subject(subject.get_id(), &st.db).await? {
214- return Err(AppError::Conflict(
215- "homework still references this subject — re-tag or delete it first",
216- ));
217- }
218- // Bank templates carry this subject as optional origin metadata, so they
219- // don't block: `Subject::delete` clears it off them in the delete's own
220- // transaction. Writer lease of [`BANK_LOCK`] all the same — bank
221- // create/update validate their subject and write under the reader lease, so
222- // without it a template could adopt this subject *after* the cascade ran
223- // and outlive it. Held last; the order is EXAM_LOCK, then HOMEWORK_LOCK,
224- // then BANK_LOCK.
225- let _bank_guard = BANK_LOCK.write().await;
226 subject.delete(&st.db).await?;197 subject.delete(&st.db).await?;
227 Ok(StatusCode::NO_CONTENT)198 Ok(StatusCode::NO_CONTENT)
228 }199 }
src/web/terms.rsmodified+2 -6
@@ -7,7 +7,7 @@ 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::term::{TERM_LOCK, Term, TermId, TermName};10+use crate::domain::term::{Term, TermId, TermName};
11 use crate::domain::timestamp::Timestamp;11 use crate::domain::timestamp::Timestamp;
12 use crate::error::{AppError, ErrorResponse, ValidationError};12 use crate::error::{AppError, ErrorResponse, ValidationError};
13 use crate::state::AppState;13 use crate::state::AppState;
@@ -229,14 +229,10 @@ async fn delete_term(
229 let term = Term::read(&TermId::from_key(&id), &st.db)229 let term = Term::read(&TermId::from_key(&id), &st.db)
230 .await?230 .await?
231 .ok_or(AppError::NotFound)?;231 .ok_or(AppError::NotFound)?;
232- // [`TERM_LOCK`] holds the link check and the delete together, so a course232+ if !term.delete(&st.db).await? {
233- // write that just resolved this term can't land its link on a dead row.
234- let _guard = TERM_LOCK.lock().await;
235- if Term::any_course(term.get_id(), &st.db).await? {
236 return Err(AppError::Conflict(233 return Err(AppError::Conflict(
237 "courses are still linked to this term — unlink them first",234 "courses are still linked to this term — unlink them first",
238 ));235 ));
239 }236 }
240- term.delete(&st.db).await?;
241 Ok(StatusCode::NO_CONTENT)237 Ok(StatusCode::NO_CONTENT)
242 }238 }
tests/integration.rsmodified+469 -18
@@ -3331,17 +3331,37 @@ async fn kind_weight_edits_reweight_reports_live() {
3331 3331
3332 // The PATCH above also retired `project` (allowed — no marks of that kind3332 // The PATCH above also retired `project` (allowed — no marks of that kind
3333 // existed yet; a graded kind can't leave at all, see3333 // existed yet; a graded kind can't leave at all, see
3334- // `exam_kind_removal_blocks_while_marks_exist`). Its exam lives on and3334+ // `exam_kind_removal_blocks_while_marks_exist`). Its exam lives on, but a
3335- // counts with weight 1.3335+ // retired kind takes no new marks: that is the other end of the same rule,
3336+ // and it is what keeps "a kind with marks cannot be removed" true however
3337+ // the two writes interleave.
3338+ let grade_project = async || {
3339+ send(
3340+ &app,
3341+ "POST",
3342+ &format!("/exams/{project}/results"),
3343+ Some(&teacher),
3344+ Some(json!({ "mark": 60, "user_id": alice_id })),
3345+ )
3346+ .await
3347+ };
3348+ assert_eq!(grade_project().await.status, StatusCode::CONFLICT);
3349+ // Offered again — at weight 1, so the exam counts exactly as an exam of a
3350+ // since-removed kind would have.
3336 let res = send(3351 let res = send(
3337 &app,3352 &app,
3338- "POST",3353+ "PATCH",
3339- &format!("/exams/{project}/results"),3354+ "/settings",
3340- Some(&teacher),3355+ Some(&manager),
3341- Some(json!({ "mark": 60, "user_id": alice_id })),3356+ Some(json!({ "exam_kinds": [
3357+ {"name": "quiz", "weight": 1},
3358+ {"name": "oral", "weight": 3},
3359+ {"name": "project", "weight": 1},
3360+ ]})),
3342 )3361 )
3343 .await;3362 .await;
3344 assert_eq!(res.status, StatusCode::OK);3363 assert_eq!(res.status, StatusCode::OK);
3364+ assert_eq!(grade_project().await.status, StatusCode::OK);
3345 // (40 + 240 + 60) / 5 = 68.3365 // (40 + 240 + 60) / 5 = 68.
3346 let report = send(&app, "GET", "/marks/me", Some(&alice), None).await;3366 let report = send(&app, "GET", "/marks/me", Some(&alice), None).await;
3347 assert_eq!(report.body["courses"][0]["average"], 68.0);3367 assert_eq!(report.body["courses"][0]["average"], 68.0);
@@ -4175,11 +4195,11 @@ async fn concurrent_enrolls_never_exceed_course_capacity() {
4175 /// be full forever. Stored state is the only witness: the embedded engine can4195 /// be full forever. Stored state is the only witness: the embedded engine can
4176 /// tell two racers they both won, so the HTTP statuses prove nothing.4196 /// tell two racers they both won, so the HTTP statuses prove nothing.
4177 //4197 //
4178-// ponytail: `ENROLL_LOCK` serializes the enrolls inside one process, so what4198+// Nothing serializes these any more: the seat and the row are claimed in one
4179-// this actually drives is the already-enrolled early return; the `CREATE`-loser4199+// transaction (`cap::claim_and_create`), so a racer that loses the id has its
4180-// release only runs when the two racers sit on different replicas. Both paths4200+// own increment rolled back with the transaction and reads the winner's row
4181-// are pinned by the same assertion below (counter == roster), which is the part4201+// instead of being told the course is full. Both the early return and that
4182-// that matters.4202+// rollback are pinned by the assertion below (counter == roster).
4183 #[tokio::test]4203 #[tokio::test]
4184 async fn concurrent_enrolls_of_one_pair_claim_one_seat() {4204 async fn concurrent_enrolls_of_one_pair_claim_one_seat() {
4185 let (app, db) = app_and_db().await;4205 let (app, db) = app_and_db().await;
@@ -4229,6 +4249,317 @@ async fn concurrent_enrolls_of_one_pair_claim_one_seat() {
4229 );4249 );
4230 }4250 }
4231 4251
4252+/// The same stampede on a course with exactly one seat. Every racer enrolls the
4253+/// *same* student, so between them they owe one seat — but on a cap this tight
4254+/// the claim is the first thing to fail, and answering that with "the course is
4255+/// full" would refuse a student the enrollment that just succeeded on their
4256+/// behalf. So the pair's own row is looked for inside the claim's transaction,
4257+/// before the seat is blamed. Drop that gate and every loser here is a 409.
4258+#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
4259+async fn concurrent_enrolls_of_one_seat_never_refuse_their_own_winner() {
4260+ let (app, db) = app_and_db().await;
4261+ let teacher = login_as(&app, &db, "tight_teacher", "teacher").await;
4262+ let student = login(&app, "tight_student").await;
4263+ let student_id = me_id(&app, &student).await;
4264+ let res = send(
4265+ &app,
4266+ "POST",
4267+ "/courses",
4268+ Some(&teacher),
4269+ Some(json!({ "title": "one seat", "description": "", "capacity": 1 })),
4270+ )
4271+ .await;
4272+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
4273+ let course = id_of(&res.body);
4274+ let uri = format!("/courses/{course}/enrollments");
4275+
4276+ let mut tasks = Vec::new();
4277+ for _ in 0..8 {
4278+ let (app, teacher, uri) = (app.clone(), teacher.clone(), uri.clone());
4279+ let body = json!({ "user_id": student_id });
4280+ tasks.push(tokio::spawn(async move {
4281+ send(&app, "POST", &uri, Some(&teacher), Some(body)).await
4282+ }));
4283+ }
4284+ for task in tasks {
4285+ let res = task.await.unwrap();
4286+ assert_eq!(
4287+ res.status,
4288+ StatusCode::OK,
4289+ "one student, one seat, no refusal: {}",
4290+ res.body
4291+ );
4292+ }
4293+
4294+ let roster = send(&app, "GET", &uri, Some(&teacher), None).await;
4295+ assert_eq!(common::total(&roster.body), 1, "one seat: {}", roster.body);
4296+ let mut counted = db
4297+ .query("SELECT VALUE enrollment_count FROM type::record('course', $c)")
4298+ .bind(("c", course.clone()))
4299+ .await
4300+ .expect("counter read")
4301+ .check()
4302+ .expect("counter read");
4303+ assert_eq!(
4304+ counted.take::<Vec<i64>>(0).expect("counter column"),
4305+ vec![1],
4306+ "and the seat it cost is the one seat the course has"
4307+ );
4308+}
4309+
4310+/// The two reference counters a subject carries — the whole basis of its
4311+/// delete guard — must equal the rows that actually point at it, through every
4312+/// writer: create, re-tag, delete, and the exam cascade. Nothing recomputes
4313+/// them, so a single missed decrement makes a subject undeletable forever.
4314+///
4315+/// This bites on the halves the HTTP status alone cannot see. Drop the
4316+/// release of the *old* subject from either re-tag and the counter drifts up:
4317+/// the last delete below comes back 409 instead of 204.
4318+#[tokio::test]
4319+async fn subject_reference_counts_track_every_writer() {
4320+ let (app, db) = app_and_db().await;
4321+ let teacher = login_as(&app, &db, "refc_t", "teacher").await;
4322+ let course = create_course(&app, &teacher, "physics").await;
4323+ let from = create_subject(&app, &teacher, &course, "optics").await;
4324+ let to = create_subject(&app, &teacher, &course, "waves").await;
4325+ let exam = create_exam(&app, &teacher, &course, "midterm", "midterm").await;
4326+ let due = Timestamp::now().as_millis() + 86_400_000;
4327+
4328+ let counts = async |subject: &str| -> (i64, i64) {
4329+ let mut result = db
4330+ .query(
4331+ "SELECT VALUE [exam_question_count ?? 0, homework_count ?? 0] \
4332+ FROM type::record('subject', $s)",
4333+ )
4334+ .bind(("s", subject.to_string()))
4335+ .await
4336+ .expect("counter read")
4337+ .check()
4338+ .expect("counter read");
4339+ let pair = result
4340+ .take::<Vec<Vec<i64>>>(0)
4341+ .expect("counter columns")
4342+ .pop()
4343+ .expect("the subject row");
4344+ (pair[0], pair[1])
4345+ };
4346+
4347+ let question = create_question(
4348+ &app,
4349+ &teacher,
4350+ &exam,
4351+ &from,
4352+ json!({ "text": "How fast?", "kind": "text", "points": 10 }),
4353+ )
4354+ .await;
4355+ let cascaded = create_question(
4356+ &app,
4357+ &teacher,
4358+ &exam,
4359+ &from,
4360+ json!({ "text": "How bright?", "kind": "text", "points": 10 }),
4361+ )
4362+ .await;
4363+ let homework = create_homework(&app, &teacher, &course, &from, "lenses", due).await;
4364+ assert_eq!(counts(&from).await, (2, 1), "two questions and a homework");
4365+ assert_eq!(counts(&to).await, (0, 0), "the spare subject holds nothing");
4366+
4367+ // A re-tag moves a reference: both ends must move, not just the new one.
4368+ let res = send(
4369+ &app,
4370+ "PATCH",
4371+ &format!("/exams/{exam}/questions/{question}"),
4372+ Some(&teacher),
4373+ Some(json!({ "subject_id": to })),
4374+ )
4375+ .await;
4376+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
4377+ let res = send(
4378+ &app,
4379+ "PATCH",
4380+ &format!("/homework/{homework}"),
4381+ Some(&teacher),
4382+ Some(json!({ "subject_id": to })),
4383+ )
4384+ .await;
4385+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
4386+ assert_eq!(counts(&from).await, (1, 0), "both re-tags must have left");
4387+ assert_eq!(counts(&to).await, (1, 1), "and both must have arrived");
4388+
4389+ // A re-tag back to where it already is moves nothing.
4390+ let res = send(
4391+ &app,
4392+ "PATCH",
4393+ &format!("/homework/{homework}"),
4394+ Some(&teacher),
4395+ Some(json!({ "subject_id": to })),
4396+ )
4397+ .await;
4398+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
4399+ assert_eq!(counts(&to).await, (1, 1), "a no-op re-tag is a no-op");
4400+
4401+ // Deleting the referencing rows gives every reference back — including the
4402+ // question the *exam* cascade takes with it, which the row delete never
4403+ // sees.
4404+ let res = send(
4405+ &app,
4406+ "DELETE",
4407+ &format!("/homework/{homework}"),
4408+ Some(&teacher),
4409+ None,
4410+ )
4411+ .await;
4412+ assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
4413+ let res = send(
4414+ &app,
4415+ "DELETE",
4416+ &format!("/exams/{exam}/questions/{question}"),
4417+ Some(&teacher),
4418+ None,
4419+ )
4420+ .await;
4421+ assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
4422+ assert_eq!(counts(&to).await, (0, 0), "the new subject is free again");
4423+ assert_eq!(
4424+ counts(&from).await,
4425+ (1, 0),
4426+ "the cascaded question still holds"
4427+ );
4428+ assert!(!cascaded.is_empty());
4429+
4430+ let res = send(
4431+ &app,
4432+ "DELETE",
4433+ &format!("/exams/{exam}"),
4434+ Some(&teacher),
4435+ None,
4436+ )
4437+ .await;
4438+ assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
4439+ assert_eq!(counts(&from).await, (0, 0), "the exam cascade gave it back");
4440+
4441+ for subject in [&from, &to] {
4442+ let res = send(
4443+ &app,
4444+ "DELETE",
4445+ &format!("/subjects/{subject}"),
4446+ Some(&teacher),
4447+ None,
4448+ )
4449+ .await;
4450+ assert_eq!(
4451+ res.status,
4452+ StatusCode::NO_CONTENT,
4453+ "an unreferenced subject must delete: {}",
4454+ res.body
4455+ );
4456+ }
4457+}
4458+
4459+/// A subject delete racing question creates on the same subject. Exactly one
4460+/// outcome is legal, and it is decided by the delete's own `WHERE`: either the
4461+/// subject is gone and *no* question points at it, or it survived and its
4462+/// counter equals the questions that landed. Stored state is the only witness —
4463+/// the embedded engine can tell two racers they both won, so the statuses prove
4464+/// nothing.
4465+///
4466+/// The count-then-delete this replaced fails here: it reads "no questions",
4467+/// then deletes while a create that already passed its own subject check lands
4468+/// its row on the corpse.
4469+#[tokio::test]
4470+async fn a_subject_delete_racing_question_creates_leaves_no_orphan() {
4471+ let (app, db) = app_and_db().await;
4472+ let teacher = login_as(&app, &db, "race_t", "teacher").await;
4473+ let course = create_course(&app, &teacher, "chemistry").await;
4474+ let subject = create_subject(&app, &teacher, &course, "bonds").await;
4475+ let exam = create_exam(&app, &teacher, &course, "quiz", "quiz").await;
4476+ // One question already tagged before the race starts, so the delete is
4477+ // never legal: whichever way the interleaving falls, it must be refused.
4478+ create_question(
4479+ &app,
4480+ &teacher,
4481+ &exam,
4482+ &subject,
4483+ json!({ "text": "first", "kind": "text", "points": 1 }),
4484+ )
4485+ .await;
4486+
4487+ let mut handles = Vec::new();
4488+ for i in 0..8 {
4489+ let (app, teacher, exam, subject) =
4490+ (app.clone(), teacher.clone(), exam.clone(), subject.clone());
4491+ handles.push(tokio::spawn(async move {
4492+ let body = json!({
4493+ "text": format!("q{i}"),
4494+ "kind": "text",
4495+ "points": 1,
4496+ "subject_id": subject,
4497+ });
4498+ send(
4499+ &app,
4500+ "POST",
4501+ &format!("/exams/{exam}/questions"),
4502+ Some(&teacher),
4503+ Some(body),
4504+ )
4505+ .await
4506+ .status
4507+ }));
4508+ }
4509+ let killer = {
4510+ let (app, teacher, subject) = (app.clone(), teacher.clone(), subject.clone());
4511+ tokio::spawn(async move {
4512+ send(
4513+ &app,
4514+ "DELETE",
4515+ &format!("/subjects/{subject}"),
4516+ Some(&teacher),
4517+ None,
4518+ )
4519+ .await
4520+ .status
4521+ })
4522+ };
4523+ for handle in handles {
4524+ let status = handle.await.unwrap();
4525+ assert!(
4526+ status == StatusCode::CREATED || status == StatusCode::BAD_REQUEST,
4527+ "a create either lands or is told the subject is gone, got {status}"
4528+ );
4529+ }
4530+ let killed = killer.await.unwrap();
4531+
4532+ let mut result = db
4533+ .query("SELECT VALUE exam_question_count ?? 0 FROM type::record('subject', $s)")
4534+ .bind(("s", subject.clone()))
4535+ .await
4536+ .expect("counter read")
4537+ .check()
4538+ .expect("counter read");
4539+ let counter = result.take::<Vec<i64>>(0).expect("counter column");
4540+ let mut rows = db
4541+ .query("SELECT VALUE id FROM exam_question WHERE subject = type::record('subject', $s)")
4542+ .bind(("s", subject.clone()))
4543+ .await
4544+ .expect("row read")
4545+ .check()
4546+ .expect("row read");
4547+ let landed = rows
4548+ .take::<Vec<surrealdb::types::RecordId>>(0)
4549+ .expect("question rows")
4550+ .len() as i64;
4551+ assert_eq!(
4552+ killed,
4553+ StatusCode::CONFLICT,
4554+ "a subject a question already points at may never be deleted"
4555+ );
4556+ assert_eq!(
4557+ counter.first().copied(),
4558+ Some(landed),
4559+ "the subject must survive with its counter equal to the rows it guards"
4560+ );
4561+}
4562+
4232 /// The signup list freezes the moment the event starts — both directions.4563 /// The signup list freezes the moment the event starts — both directions.
4233 /// (The create-time no-past grace lets a just-started event exist, which is4564 /// (The create-time no-past grace lets a just-started event exist, which is
4234 /// exactly a closed list.)4565 /// exactly a closed list.)
@@ -11235,14 +11566,15 @@ async fn settings_round_trip_the_food_program_knobs() {
11235 }11566 }
11236 11567
11237 // A published menu pins the slot it snapshotted: dropping it is a 409.11568 // A published menu pins the slot it snapshotted: dropping it is a 409.
11238- db.query(11569+ let menu = send(
11239- "CREATE menu SET date = '2026-07-27', slot = 'lunch',11570+ &app,
11240- created_by = (SELECT VALUE id FROM user LIMIT 1)[0], created_at = 0",11571+ "POST",
11572+ "/meals/menus",
11573+ Some(&manager),
11574+ Some(json!({ "date": "2026-07-27", "slot": "lunch" })),
11241 )11575 )
11242- .await11576+ .await;
11243- .unwrap()11577+ assert_eq!(menu.status, StatusCode::CREATED, "{}", menu.body);
11244- .check()
11245- .unwrap();
11246 let res = send(11578 let res = send(
11247 &app,11579 &app,
11248 "PATCH",11580 "PATCH",
@@ -20939,6 +21271,63 @@ async fn concurrent_meal_bookings_never_exceed_the_capacity() {
20939 )21271 )
20940 .await;21272 .await;
20941 assert_eq!(common::total(&res.body), 3, "and only three rows exist");21273 assert_eq!(common::total(&res.body), 3, "and only three rows exist");
21274+
21275+ // The rows are downstream of the counter, so assert the counter itself:
21276+ // it is what every replica's `WHERE` compares, and a drift here would open
21277+ // the cap on the next booking however tidy the listing looks.
21278+ let mut counted = db
21279+ .query("SELECT VALUE seats_booked FROM type::record('menu', $m)")
21280+ .bind(("m", menu.clone()))
21281+ .await
21282+ .expect("counter read")
21283+ .check()
21284+ .expect("counter read");
21285+ assert_eq!(
21286+ counted.take::<Vec<i64>>(0).expect("counter column"),
21287+ vec![3],
21288+ "the stored seat counter must agree with the seats handed out"
21289+ );
21290+}
21291+
21292+/// Publishing the same day+slot twice at once must be one menu and one 409 —
21293+/// never two rows and never a 500. The day and slot *are* the record id, so the
21294+/// racers collide on a single record inside the database rather than on a
21295+/// check-then-write pair, which is the only form that also holds when the two
21296+/// `POST`s land on different replicas.
21297+#[tokio::test]
21298+async fn concurrent_duplicate_menu_publishes_conflict_not_500() {
21299+ let (app, db) = app_and_db().await;
21300+ let mgr = login_as(&app, &db, "publish_race_mgr", "manager").await;
21301+
21302+ let mut handles = Vec::new();
21303+ for _ in 0..8 {
21304+ let app = app.clone();
21305+ let mgr = mgr.clone();
21306+ handles.push(tokio::spawn(async move {
21307+ send(
21308+ &app,
21309+ "POST",
21310+ "/meals/menus",
21311+ Some(&mgr),
21312+ Some(json!({ "date": "2026-09-14", "slot": "lunch" })),
21313+ )
21314+ .await
21315+ .status
21316+ }));
21317+ }
21318+ let mut published = 0;
21319+ for h in handles {
21320+ let status = h.await.unwrap();
21321+ assert!(
21322+ status == StatusCode::CREATED || status == StatusCode::CONFLICT,
21323+ "a lost publish must be a 409, never a 500: {status}"
21324+ );
21325+ published += i32::from(status == StatusCode::CREATED);
21326+ }
21327+ assert_eq!(published, 1, "exactly one publish won");
21328+
21329+ let res = send(&app, "GET", "/meals/menus", Some(&mgr), None).await;
21330+ assert_eq!(common::total(&res.body), 1, "and exactly one menu exists");
20942 }21331 }
20943 21332
20944 /// Two appends of one ledger id must both succeed: the id is the idempotence21333 /// Two appends of one ledger id must both succeed: the id is the idempotence
@@ -22184,6 +22573,68 @@ async fn concurrent_bookings_of_one_seat_bill_it_once() {
22184 );22573 );
22185 }22574 }
22186 22575
22576+/// The same stampede on a menu with exactly one seat. Every racer is the *same*
22577+/// student, so between them they owe one seat — but each claims before it can
22578+/// know another already placed the row, and the losers' claims are refused as
22579+/// "full". Answering that with a 409 would refuse a student the booking that
22580+/// just succeeded on their behalf, so a refused claim looks for this very seat
22581+/// before it blames the cap.
22582+#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
22583+async fn concurrent_bookings_of_one_seat_never_refuse_their_own_winner() {
22584+ let (app, db) = app_and_db().await;
22585+ let mgr = login_as(&app, &db, "tight_mgr", "manager").await;
22586+ let stu = login(&app, "tight_stu").await;
22587+ let res = send(
22588+ &app,
22589+ "POST",
22590+ "/meals/menus",
22591+ Some(&mgr),
22592+ Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 1 })),
22593+ )
22594+ .await;
22595+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
22596+ let menu = id_of(&res.body);
22597+
22598+ let mut tasks = Vec::new();
22599+ for _ in 0..8 {
22600+ let (app, stu, menu) = (app.clone(), stu.clone(), menu.clone());
22601+ tasks.push(tokio::spawn(async move {
22602+ send(
22603+ &app,
22604+ "POST",
22605+ &format!("/meals/menus/{menu}/bookings"),
22606+ Some(&stu),
22607+ Some(json!({})),
22608+ )
22609+ .await
22610+ }));
22611+ }
22612+ for task in tasks {
22613+ let res = task.await.unwrap();
22614+ assert_eq!(
22615+ res.status,
22616+ StatusCode::CREATED,
22617+ "one student, one seat, no refusal: {}",
22618+ res.body
22619+ );
22620+ }
22621+
22622+ let res = send(&app, "GET", "/meals/bookings/me", Some(&stu), None).await;
22623+ assert_eq!(common::total(&res.body), 1, "one seat: {}", res.body);
22624+ let mut counted = db
22625+ .query("SELECT VALUE seats_booked FROM type::record('menu', $m)")
22626+ .bind(("m", menu.clone()))
22627+ .await
22628+ .expect("counter read")
22629+ .check()
22630+ .expect("counter read");
22631+ assert_eq!(
22632+ counted.take::<Vec<i64>>(0).expect("counter column"),
22633+ vec![1],
22634+ "and the seat it cost is the one seat the menu has"
22635+ );
22636+}
22637+
22187 /// A repeat POST racing the cancel. A cancel that reverses whatever charge it22638 /// A repeat POST racing the cancel. A cancel that reverses whatever charge it
22188 /// can find, off a booking row read before the lock, can flip the seat to22639 /// can find, off a booking row read before the lock, can flip the seat to
22189 /// `cancelled` while the charge of a newer attempt stands — the student owes22640 /// `cancelled` while the charge of a newer attempt stands — the student owes
tests/limits_completeness.rsmodified+6 -0
@@ -45,6 +45,12 @@ const EXCLUDED: &[(&str, &str)] = &[
45 "CAP_WRITE_BACKOFF_MS",45 "CAP_WRITE_BACKOFF_MS",
46 "internal backoff between cap counter retries",46 "internal backoff between cap counter retries",
47 ),47 ),
48+ (
49+ "SUBMISSION_OPEN_GUARD",
50+ "SQL fragment: the condition every homework-submission write carries so \
51+ a grade freezes it in the database; the client sees the freeze as a 409, \
52+ never as a number",
53+ ),
48 (54 (
49 "UPLOAD_BODY_OVERHEAD_BYTES",55 "UPLOAD_BODY_OVERHEAD_BYTES",
50 "multipart headroom over max_file_bytes; the client sizes against \56 "multipart headroom over max_file_bytes; the client sizes against \
tests/name_refs.rsadded+400 -0
@@ -0,0 +1,400 @@
1+//! The settings' two removal guards, now that they are reference counters
2+//! rather than a count-then-write under a process-wide lock: an exam kind may
3+//! leave `exam_kinds` only while no mark is written under it, and a meal slot
4+//! may leave `meal_slots` only while no menu is published for it.
5+//!
6+//! Each test below bites on one half of the pair — the retirement's `WHERE`
7+//! (nothing may leave while it is referenced) or the claim's (nothing may be
8+//! referenced once it has left). Drop either predicate and a test here fails;
9+//! that is the point of the suite, because the guard itself is invisible in
10+//! the happy path.
11+
12+mod common;
13+
14+use axum::http::StatusCode;
15+use common::{create_course, create_exam, enroll, login_as, me_id, send};
16+use hezarfen_backend::database;
17+use serde_json::{Value, json};
18+
19+/// The two kinds these tests move in and out of the school's list.
20+fn kinds(names: &[&str]) -> Value {
21+ json!(
22+ names
23+ .iter()
24+ .map(|name| json!({ "name": name, "weight": 1 }))
25+ .collect::<Vec<_>>()
26+ )
27+}
28+
29+fn slots(names: &[&str]) -> Value {
30+ json!(
31+ names
32+ .iter()
33+ .map(|name| json!({ "name": name, "serving_minute": 720 }))
34+ .collect::<Vec<_>>()
35+ )
36+}
37+
38+fn listed_kinds(body: &Value) -> Vec<String> {
39+ body["exam_kinds"]
40+ .as_array()
41+ .expect("exam_kinds")
42+ .iter()
43+ .map(|kind| kind["name"].as_str().expect("name").to_string())
44+ .collect()
45+}
46+
47+/// A graded student, an exam of `kind`, and the manager's cookie.
48+struct School {
49+ app: axum::Router,
50+ db: hezarfen_backend::database::Database,
51+ boss: String,
52+ course: String,
53+ exam: String,
54+ student: String,
55+}
56+
57+async fn school_with_kinds(names: &[&str]) -> School {
58+ let (app, db) = common::app_and_db().await;
59+ let boss = login_as(&app, &db, "boss", "manager").await;
60+ let student_cookie = login_as(&app, &db, "kid", "student").await;
61+ let student = me_id(&app, &student_cookie).await;
62+ let res = send(
63+ &app,
64+ "PATCH",
65+ "/settings",
66+ Some(&boss),
67+ Some(json!({ "exam_kinds": kinds(names) })),
68+ )
69+ .await;
70+ assert_eq!(res.status, StatusCode::OK, "seed exam kinds");
71+ let course = create_course(&app, &boss, "Maths").await;
72+ enroll(&app, &boss, &course, &student).await;
73+ let exam = create_exam(&app, &boss, &course, "Midterm", names[0]).await;
74+ School {
75+ app,
76+ db,
77+ boss,
78+ course,
79+ exam,
80+ student,
81+ }
82+}
83+
84+impl School {
85+ async fn grade(&self, mark: i64) -> common::Res {
86+ self.grade_exam(&self.exam.clone(), mark).await
87+ }
88+
89+ async fn grade_exam(&self, exam: &str, mark: i64) -> common::Res {
90+ send(
91+ &self.app,
92+ "POST",
93+ &format!("/exams/{exam}/results"),
94+ Some(&self.boss),
95+ Some(json!({ "user_id": self.student, "mark": mark })),
96+ )
97+ .await
98+ }
99+
100+ async fn set_kinds(&self, names: &[&str]) -> common::Res {
101+ send(
102+ &self.app,
103+ "PATCH",
104+ "/settings",
105+ Some(&self.boss),
106+ Some(json!({ "exam_kinds": kinds(names) })),
107+ )
108+ .await
109+ }
110+
111+ async fn settings(&self) -> Value {
112+ send(&self.app, "GET", "/settings", Some(&self.boss), None)
113+ .await
114+ .body
115+ }
116+}
117+
118+/// The retirement's `WHERE`: a kind a mark is written under does not leave the
119+/// list, and the refused edit changes *nothing* — not the stored list, and not
120+/// the kind's own usability.
121+#[tokio::test]
122+async fn a_graded_kind_cannot_be_removed_and_nothing_moves() {
123+ let school = school_with_kinds(&["lab", "quiz"]).await;
124+ assert_eq!(school.grade(80).await.status, StatusCode::OK);
125+
126+ let res = school.set_kinds(&["quiz"]).await;
127+ assert_eq!(res.status, StatusCode::CONFLICT);
128+ assert_eq!(
129+ res.body["error"],
130+ "exams of kind 'lab' are already graded — the kind cannot be removed"
131+ );
132+
133+ // The list the school reads back still carries the kind...
134+ assert_eq!(listed_kinds(&school.settings().await), ["lab", "quiz"]);
135+ // ...and so does the counter: a refused removal must not leave the kind
136+ // retired, or every later grade under it would be refused instead.
137+ assert_eq!(school.grade(90).await.status, StatusCode::OK);
138+}
139+
140+/// A regrade is not a second reference: one mark, one reference, however many
141+/// times it is overwritten — otherwise the counter would drift upward and the
142+/// kind could never be removed again.
143+#[tokio::test]
144+async fn marks_release_their_kind_when_they_are_deleted() {
145+ let school = school_with_kinds(&["lab", "quiz"]).await;
146+ for mark in [10, 20, 30] {
147+ assert_eq!(school.grade(mark).await.status, StatusCode::OK);
148+ }
149+
150+ let res = send(
151+ &school.app,
152+ "DELETE",
153+ &format!("/exams/{}/results/{}", school.exam, school.student),
154+ Some(&school.boss),
155+ None,
156+ )
157+ .await;
158+ assert_eq!(res.status, StatusCode::NO_CONTENT);
159+
160+ // Nothing is graded under it any more, so it leaves freely.
161+ assert_eq!(school.set_kinds(&["quiz"]).await.status, StatusCode::OK);
162+ assert_eq!(listed_kinds(&school.settings().await), ["quiz"]);
163+}
164+
165+/// The claim's `WHERE`, the other half of the same race: once the kind is out
166+/// of the list, a mark can no longer land under it. Whichever of the two
167+/// writes reaches the counter first, the other is refused — which is what makes
168+/// the pair safe with two replicas and no shared lock.
169+#[tokio::test]
170+async fn a_removed_kind_refuses_a_grade() {
171+ let school = school_with_kinds(&["lab", "quiz"]).await;
172+ // Nothing graded yet, so the kind leaves — the exam keeps carrying it.
173+ assert_eq!(school.set_kinds(&["quiz"]).await.status, StatusCode::OK);
174+
175+ let res = school.grade(80).await;
176+ assert_eq!(res.status, StatusCode::CONFLICT);
177+ assert_eq!(
178+ res.body["error"],
179+ "the 'lab' exam kind has been removed from the school's settings — \
180+ add it back before grading this exam"
181+ );
182+
183+ // Adding it back puts it in service again.
184+ assert_eq!(
185+ school.set_kinds(&["quiz", "lab"]).await.status,
186+ StatusCode::OK
187+ );
188+ assert_eq!(school.grade(80).await.status, StatusCode::OK);
189+}
190+
191+/// An exam's kind is frozen once it carries marks: re-pointing it would
192+/// re-weight them silently (and strand their references on the kind they were
193+/// counted under). Ungraded, it moves freely — and its next mark is counted
194+/// under the kind it moved to.
195+#[tokio::test]
196+async fn a_graded_exams_kind_is_frozen() {
197+ let school = school_with_kinds(&["lab", "quiz"]).await;
198+ let repoint = async || {
199+ send(
200+ &school.app,
201+ "PATCH",
202+ &format!("/exams/{}", school.exam),
203+ Some(&school.boss),
204+ Some(json!({ "kind": "quiz" })),
205+ )
206+ .await
207+ };
208+ // Ungraded: the move lands.
209+ assert_eq!(repoint().await.status, StatusCode::OK);
210+ assert_eq!(school.grade(80).await.status, StatusCode::OK);
211+ // The mark went to the kind the exam now carries, not the one it left.
212+ assert_eq!(school.set_kinds(&["quiz"]).await.status, StatusCode::OK);
213+ assert_eq!(
214+ school.set_kinds(&["lab", "quiz"]).await.status,
215+ StatusCode::OK
216+ );
217+
218+ // Graded: the move is refused, and the exam keeps the kind it had.
219+ let back = send(
220+ &school.app,
221+ "PATCH",
222+ &format!("/exams/{}", school.exam),
223+ Some(&school.boss),
224+ Some(json!({ "kind": "lab" })),
225+ )
226+ .await;
227+ assert_eq!(back.status, StatusCode::CONFLICT);
228+ assert_eq!(
229+ back.body["error"],
230+ "cannot change the kind of an exam that already has marks"
231+ );
232+ // Everything else on the exam still edits, marks or no marks.
233+ let title = send(
234+ &school.app,
235+ "PATCH",
236+ &format!("/exams/{}", school.exam),
237+ Some(&school.boss),
238+ Some(json!({ "title": "Midterm II" })),
239+ )
240+ .await;
241+ assert_eq!(title.status, StatusCode::OK);
242+}
243+
244+/// Deleting an exam frees exactly the marks it cascaded — no more. Two exams
245+/// share the kind here: releasing one mark too many (the shape a count taken
246+/// outside the cascade's transaction produces) would read as no marks left and
247+/// let the kind walk out of the settings while the second exam is still graded.
248+#[tokio::test]
249+async fn deleting_one_exam_frees_only_its_own_marks() {
250+ let school = school_with_kinds(&["lab", "quiz"]).await;
251+ let second = create_exam(&school.app, &school.boss, &school.course, "Final", "lab").await;
252+ assert_eq!(school.grade(80).await.status, StatusCode::OK);
253+ assert_eq!(school.grade_exam(&second, 70).await.status, StatusCode::OK);
254+
255+ let gone = send(
256+ &school.app,
257+ "DELETE",
258+ &format!("/exams/{}", school.exam),
259+ Some(&school.boss),
260+ None,
261+ )
262+ .await;
263+ assert_eq!(gone.status, StatusCode::NO_CONTENT);
264+
265+ // The other exam's mark still holds the kind down.
266+ let refused = school.set_kinds(&["quiz"]).await;
267+ assert_eq!(refused.status, StatusCode::CONFLICT);
268+ assert_eq!(
269+ refused.body["error"],
270+ "exams of kind 'lab' are already graded — the kind cannot be removed"
271+ );
272+
273+ // Only when the last graded exam goes does the kind go free.
274+ let last = send(
275+ &school.app,
276+ "DELETE",
277+ &format!("/exams/{second}"),
278+ Some(&school.boss),
279+ None,
280+ )
281+ .await;
282+ assert_eq!(last.status, StatusCode::NO_CONTENT);
283+ assert_eq!(school.set_kinds(&["quiz"]).await.status, StatusCode::OK);
284+}
285+
286+/// A course delete cascades its exams' marks, so it owes their kinds the same
287+/// references back — otherwise the kind is held down by marks that no longer
288+/// exist, forever.
289+#[tokio::test]
290+async fn deleting_a_course_frees_the_kinds_its_marks_held() {
291+ let school = school_with_kinds(&["lab", "quiz"]).await;
292+ assert_eq!(school.grade(80).await.status, StatusCode::OK);
293+ // A course with a roster refuses the delete; the mark stays either way.
294+ common::unenroll(&school.app, &school.boss, &school.course, &school.student).await;
295+
296+ let gone = send(
297+ &school.app,
298+ "DELETE",
299+ &format!("/courses/{}", school.course),
300+ Some(&school.boss),
301+ None,
302+ )
303+ .await;
304+ assert_eq!(gone.status, StatusCode::NO_CONTENT, "{}", gone.body);
305+
306+ assert_eq!(school.set_kinds(&["quiz"]).await.status, StatusCode::OK);
307+ assert_eq!(listed_kinds(&school.settings().await), ["quiz"]);
308+}
309+
310+/// The same pair for meal slots, whose reference is a published menu.
311+#[tokio::test]
312+async fn a_published_menu_pins_its_meal_slot() {
313+ let (app, db) = common::app_and_db().await;
314+ let boss = login_as(&app, &db, "boss", "manager").await;
315+ let set_slots = async |names: &[&str]| {
316+ send(
317+ &app,
318+ "PATCH",
319+ "/settings",
320+ Some(&boss),
321+ Some(json!({ "meal_slots": slots(names) })),
322+ )
323+ .await
324+ };
325+ assert_eq!(set_slots(&["lunch", "snack"]).await.status, StatusCode::OK);
326+
327+ let menu = send(
328+ &app,
329+ "POST",
330+ "/meals/menus",
331+ Some(&boss),
332+ Some(json!({ "date": "2030-01-09", "slot": "lunch" })),
333+ )
334+ .await;
335+ assert_eq!(menu.status, StatusCode::CREATED);
336+ let menu_id = common::id_of(&menu.body);
337+
338+ let refused = set_slots(&["snack"]).await;
339+ assert_eq!(refused.status, StatusCode::CONFLICT);
340+ assert_eq!(
341+ refused.body["error"],
342+ "menus are already published for the 'lunch' slot — it cannot be removed"
343+ );
344+
345+ // Retire the menu and the slot is free to leave — then no new menu may be
346+ // published under it.
347+ let deleted = send(
348+ &app,
349+ "DELETE",
350+ &format!("/meals/menus/{menu_id}"),
351+ Some(&boss),
352+ None,
353+ )
354+ .await;
355+ assert_eq!(deleted.status, StatusCode::NO_CONTENT);
356+ assert_eq!(set_slots(&["snack"]).await.status, StatusCode::OK);
357+
358+ let late = send(
359+ &app,
360+ "POST",
361+ "/meals/menus",
362+ Some(&boss),
363+ Some(json!({ "date": "2030-01-10", "slot": "lunch" })),
364+ )
365+ .await;
366+ assert_eq!(
367+ late.status,
368+ StatusCode::BAD_REQUEST,
369+ "slot is no longer served"
370+ );
371+}
372+
373+/// Marks and menus written before the counters existed still hold their name
374+/// down: the boot backfill counts them once. Aged by deleting the counter rows
375+/// a live binary keeps — which is exactly the state an older binary's database
376+/// arrives in.
377+#[tokio::test]
378+async fn rows_written_before_the_counters_are_counted_at_boot() {
379+ let school = school_with_kinds(&["lab", "quiz"]).await;
380+ assert_eq!(school.grade(80).await.status, StatusCode::OK);
381+
382+ school
383+ .db
384+ .query("DELETE kind_ref; DELETE slot_ref;")
385+ .await
386+ .expect("age the database")
387+ .check()
388+ .expect("aged");
389+
390+ // Without the backfill the mark is invisible to the guard and the kind
391+ // walks straight out of the list.
392+ database::migrate(&school.db).await.expect("reboot");
393+
394+ let res = school.set_kinds(&["quiz"]).await;
395+ assert_eq!(res.status, StatusCode::CONFLICT);
396+ assert_eq!(
397+ res.body["error"],
398+ "exams of kind 'lab' are already graded — the kind cannot be removed"
399+ );
400+}
tests/persistence.rsmodified+340 -0
@@ -10,6 +10,7 @@ use axum::Router;
10 use axum::http::StatusCode;10 use axum::http::StatusCode;
11 use common::{create_course, create_exam, create_subject, enroll, me_id, send, set_role};11 use common::{create_course, create_exam, create_subject, enroll, me_id, send, set_role};
12 use hezarfen_backend::database::Database;12 use hezarfen_backend::database::Database;
13+use hezarfen_backend::domain::timestamp::Timestamp;
13 use hezarfen_backend::rate_limit::RateLimitConfig;14 use hezarfen_backend::rate_limit::RateLimitConfig;
14 use hezarfen_backend::state::AppState;15 use hezarfen_backend::state::AppState;
15 use hezarfen_backend::{build_router, database};16 use hezarfen_backend::{build_router, database};
@@ -1264,3 +1265,342 @@ async fn cap_counters_are_seeded_from_the_rows_that_predate_them() {
1264 let up = common::upload_file(&app, &ali, &note, "eleventh.txt", "", b"x").await;1265 let up = common::upload_file(&app, &ali, &note, "eleventh.txt", "", b"x").await;
1265 assert_eq!(up.status, StatusCode::CONFLICT, "{}", up.body);1266 assert_eq!(up.status, StatusCode::CONFLICT, "{}", up.body);
1266 }1267 }
1268+
1269+/// The appointment slot's counter is the odd one out: it seeds from the
1270+/// bookings that are still *live*, because a rejected or cancelled one gave the
1271+/// slot back long before the column existed (2026-07-27). A slot aged into the
1272+/// pre-counter shape must come back taken if someone is still waiting on it,
1273+/// and free if nobody is — a flat recount of its rows would get the second case
1274+/// wrong and lock a free slot out of the calendar for good.
1275+#[tokio::test]
1276+async fn slot_occupancy_is_seeded_from_the_bookings_that_are_still_live() {
1277+ let (app, db) = common::app_and_db().await;
1278+ let teacher = common::login_as(&app, &db, "teacher", "teacher").await;
1279+ let veli = common::login(&app, "veli").await;
1280+ let ayse = common::login(&app, "ayse").await;
1281+ let now = hezarfen_backend::domain::timestamp::Timestamp::now().as_millis();
1282+ let hour = 3_600_000;
1283+
1284+ async fn publish(app: &Router, who: &str, starts_at: i64) -> String {
1285+ let res = send(
1286+ app,
1287+ "POST",
1288+ "/appointments/slots",
1289+ Some(who),
1290+ Some(json!({ "starts_at": starts_at, "ends_at": starts_at + 3_600_000 })),
1291+ )
1292+ .await;
1293+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1294+ common::id_of(&res.body[0])
1295+ }
1296+ async fn book(app: &Router, who: &str, slot: &str) -> common::Res {
1297+ send(
1298+ app,
1299+ "POST",
1300+ "/appointments",
1301+ Some(who),
1302+ Some(json!({ "slot": slot, "reason": "görüşme" })),
1303+ )
1304+ .await
1305+ }
1306+
1307+ let taken = publish(&app, &teacher, now + hour).await;
1308+ let freed = publish(&app, &teacher, now + 3 * hour).await;
1309+ let held = common::id_of(&book(&app, &veli, &taken).await.body);
1310+ let gone = common::id_of(&book(&app, &veli, &freed).await.body);
1311+ let res = send(
1312+ &app,
1313+ "PATCH",
1314+ &format!("/appointments/{gone}/reject"),
1315+ Some(&teacher),
1316+ None,
1317+ )
1318+ .await;
1319+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1320+
1321+ // Age both slots into the pre-counter shape.
1322+ db.query("UPDATE appointment_slot UNSET occupied;")
1323+ .await
1324+ .expect("age the rows")
1325+ .check()
1326+ .expect("age the rows");
1327+
1328+ let app = reboot(&db).await;
1329+
1330+ // The still-pending booking keeps its slot; the rejected one's slot is free.
1331+ let res = book(&app, &ayse, &taken).await;
1332+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
1333+ let res = book(&app, &ayse, &freed).await;
1334+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1335+
1336+ // And the seeded seat is still a seat, not a stuck flag: cancelling the
1337+ // held booking hands it back.
1338+ let res = send(
1339+ &app,
1340+ "PATCH",
1341+ &format!("/appointments/{held}/cancel"),
1342+ Some(&veli),
1343+ None,
1344+ )
1345+ .await;
1346+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1347+ let res = book(&app, &ayse, &taken).await;
1348+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1349+}
1350+
1351+/// A submission graded before the freeze moved into the database (2026-07-27)
1352+/// carries no `graded_by_result` stamp, and an absent stamp is exactly what the
1353+/// student's writes now take as "still open" — so without the backfill an
1354+/// upgrade would quietly unfreeze every already-graded submission. The backfill
1355+/// stamps each one from the grade it already has; graded-but-never-submitted
1356+/// work has no row to stamp and must stay that way (the report reads
1357+/// `submitted`/`missing` straight off its absence).
1358+#[tokio::test]
1359+async fn graded_submissions_are_stamped_by_the_backfill() {
1360+ let (app, db) = common::app_and_db().await;
1361+ let teacher = common::login_as(&app, &db, "teacher", "teacher").await;
1362+ let ali = common::login(&app, "ali").await;
1363+ let veli = common::login(&app, "veli").await;
1364+ let (ali_id, veli_id) = (me_id(&app, &ali).await, me_id(&app, &veli).await);
1365+ let course = create_course(&app, &teacher, "math").await;
1366+ let subject = create_subject(&app, &teacher, &course, "algebra").await;
1367+ enroll(&app, &teacher, &course, &ali_id).await;
1368+ enroll(&app, &teacher, &course, &veli_id).await;
1369+ let due_at = Timestamp::now().as_millis() + 86_400_000;
1370+ let hw = common::create_homework(&app, &teacher, &course, &subject, "essay", due_at).await;
1371+
1372+ // Ali hands in and is graded; Veli never hands in and is graded `missing`.
1373+ let res = send(
1374+ &app,
1375+ "POST",
1376+ &format!("/homework/{hw}/submission"),
1377+ Some(&ali),
1378+ Some(json!({ "text": "version A" })),
1379+ )
1380+ .await;
1381+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1382+ for (user, status) in [(&ali_id, "done"), (&veli_id, "missing")] {
1383+ let res = send(
1384+ &app,
1385+ "POST",
1386+ &format!("/homework/{hw}/results"),
1387+ Some(&teacher),
1388+ Some(json!({ "user": user, "status": status })),
1389+ )
1390+ .await;
1391+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1392+ }
1393+
1394+ // Age the row into the pre-stamp shape.
1395+ db.query("UPDATE homework_submission UNSET graded_by_result;")
1396+ .await
1397+ .expect("age the row")
1398+ .check()
1399+ .expect("age the row");
1400+ let app = reboot(&db).await;
1401+
1402+ let mut stamps = db
1403+ .query("SELECT VALUE graded_by_result FROM homework_submission; SELECT VALUE id FROM homework_submission;")
1404+ .await
1405+ .expect("read stamps")
1406+ .check()
1407+ .expect("read stamps");
1408+ let stamped = stamps
1409+ .take::<Vec<surrealdb::types::RecordId>>(0)
1410+ .expect("graded_by_result");
1411+ let rows = stamps
1412+ .take::<Vec<surrealdb::types::RecordId>>(1)
1413+ .expect("submission ids");
1414+ assert_eq!(rows.len(), 1, "grading absent work must not conjure a row");
1415+ assert_eq!(
1416+ stamped.len(),
1417+ 1,
1418+ "the surviving submission must come back stamped by its grade"
1419+ );
1420+ assert_eq!(
1421+ format!("{:?}", stamped[0].key),
1422+ format!("{:?}", rows[0].key),
1423+ "the stamp must name the grade of that very (homework, user) pair"
1424+ );
1425+ assert_eq!(
1426+ stamped[0].table.to_string(),
1427+ "homework_result",
1428+ "the stamp must point at the grade table"
1429+ );
1430+
1431+ // And the freeze bites again, which an unstamped row would not have done.
1432+ let res = send(
1433+ &app,
1434+ "POST",
1435+ &format!("/homework/{hw}/submission"),
1436+ Some(&ali),
1437+ Some(json!({ "text": "version B" })),
1438+ )
1439+ .await;
1440+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
1441+ // Veli, graded but never submitted, still reports as not-submitted.
1442+ let res = send(
1443+ &app,
1444+ "GET",
1445+ &format!("/homework/{hw}/submission"),
1446+ Some(&veli),
1447+ None,
1448+ )
1449+ .await;
1450+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
1451+}
1452+
1453+/// A menu written before the seat counter existed (2026-07-27) carries none,
1454+/// which reads as zero — an uncapped menu for every seat already sold. The
1455+/// backfill seeds it from the bookings that are still *held*: a cancelled one
1456+/// gave its seat back long before the column existed, so counting rows flatly
1457+/// would lock out a seat nobody holds.
1458+#[tokio::test]
1459+async fn menu_seats_are_seeded_from_the_bookings_that_are_still_held() {
1460+ let (app, db) = common::app_and_db().await;
1461+ let mgr = common::login_as(&app, &db, "seat_mgr", "manager").await;
1462+ let ali = common::login(&app, "seat_ali").await;
1463+ let veli = common::login(&app, "seat_veli").await;
1464+ let ayse = common::login(&app, "seat_ayse").await;
1465+
1466+ let res = send(
1467+ &app,
1468+ "POST",
1469+ "/meals/menus",
1470+ Some(&mgr),
1471+ Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 2 })),
1472+ )
1473+ .await;
1474+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1475+ let menu = common::id_of(&res.body);
1476+
1477+ let book = async |who: &str| {
1478+ send(
1479+ &app,
1480+ "POST",
1481+ &format!("/meals/menus/{menu}/bookings"),
1482+ Some(who),
1483+ Some(json!({})),
1484+ )
1485+ .await
1486+ };
1487+ let held = book(&ali).await;
1488+ assert_eq!(held.status, StatusCode::CREATED, "{}", held.body);
1489+ let given_back = common::id_of(&book(&veli).await.body);
1490+ let res = send(
1491+ &app,
1492+ "DELETE",
1493+ &format!("/meals/bookings/{given_back}"),
1494+ Some(&veli),
1495+ None,
1496+ )
1497+ .await;
1498+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1499+
1500+ // Age the menu into the pre-counter shape.
1501+ db.query("UPDATE menu UNSET seats_booked;")
1502+ .await
1503+ .expect("age the row")
1504+ .check()
1505+ .expect("age the row");
1506+
1507+ // Same database, so the router above keeps serving; what matters is that
1508+ // the migration ran again over the aged row.
1509+ let _ = reboot(&db).await;
1510+
1511+ let mut counted = db
1512+ .query("SELECT VALUE seats_booked FROM menu")
1513+ .await
1514+ .expect("counter read")
1515+ .check()
1516+ .expect("counter read");
1517+ assert_eq!(
1518+ counted.take::<Vec<i64>>(0).expect("counter column"),
1519+ vec![1],
1520+ "only the seat still held may be counted back"
1521+ );
1522+
1523+ // The seeded counter is a real cap, not a decoration: one seat is left.
1524+ assert_eq!(book(&ayse).await.status, StatusCode::CREATED);
1525+ assert_eq!(book(&veli).await.status, StatusCode::CONFLICT);
1526+}
1527+
1528+/// A subject written before its two reference counters existed (2026-07-27)
1529+/// carries neither, and an absent counter reads as zero — which is exactly
1530+/// "nothing points at me", so the delete guard would wave through a subject
1531+/// half the school's questions are tagged with. The backfill counts the rows
1532+/// that actually point at each subject, once.
1533+///
1534+/// The bite is the last assertion: seed the counters wrong (or not at all) and
1535+/// the delete comes back `204` instead of `409`.
1536+#[tokio::test]
1537+async fn subject_reference_counts_are_seeded_from_the_rows_that_predate_them() {
1538+ let (app, db) = common::app_and_db().await;
1539+ let teacher = common::login_as(&app, &db, "seed_t", "teacher").await;
1540+ let course = create_course(&app, &teacher, "biology").await;
1541+ let tagged = create_subject(&app, &teacher, &course, "cells").await;
1542+ let untouched = create_subject(&app, &teacher, &course, "genes").await;
1543+ let exam = create_exam(&app, &teacher, &course, "quiz", "quiz").await;
1544+ for text in ["what?", "why?"] {
1545+ let res = send(
1546+ &app,
1547+ "POST",
1548+ &format!("/exams/{exam}/questions"),
1549+ Some(&teacher),
1550+ Some(json!({
1551+ "text": text,
1552+ "kind": "text",
1553+ "points": 1,
1554+ "subject_id": tagged,
1555+ })),
1556+ )
1557+ .await;
1558+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1559+ }
1560+ let due = Timestamp::now().as_millis() + 86_400_000;
1561+ common::create_homework(&app, &teacher, &course, &tagged, "mitosis", due).await;
1562+
1563+ // Age both subjects into the pre-counter shape.
1564+ db.query("UPDATE subject UNSET exam_question_count, homework_count;")
1565+ .await
1566+ .expect("age the rows")
1567+ .check()
1568+ .expect("age the rows");
1569+
1570+ let app = reboot(&db).await;
1571+
1572+ let mut counted = db
1573+ .query(
1574+ "SELECT VALUE [exam_question_count ?? 0, homework_count ?? 0] \
1575+ FROM subject ORDER BY id ASC",
1576+ )
1577+ .await
1578+ .expect("counter read")
1579+ .check()
1580+ .expect("counter read");
1581+ assert_eq!(
1582+ counted.take::<Vec<Vec<i64>>>(0).expect("counter columns"),
1583+ vec![vec![2, 1], vec![0, 0]],
1584+ "each subject must be seeded from the rows that point at it"
1585+ );
1586+
1587+ // The seeded counters are the delete guard itself, not a decoration.
1588+ let res = send(
1589+ &app,
1590+ "DELETE",
1591+ &format!("/subjects/{tagged}"),
1592+ Some(&teacher),
1593+ None,
1594+ )
1595+ .await;
1596+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
1597+ let res = send(
1598+ &app,
1599+ "DELETE",
1600+ &format!("/subjects/{untouched}"),
1601+ Some(&teacher),
1602+ None,
1603+ )
1604+ .await;
1605+ assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
1606+}