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.
675675 | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) · paged |
676676 | 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) |
677677 | 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) |
679679 | 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`) |
681681 | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged |
682682 | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |
683683 | 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.
773773 | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |
774774 | GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` — full |
775775 | 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") |
777777 | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) |
778778 | GET | `/terms` | student | List terms, newest first · paged |
779779 | GET | `/terms/{id}` | student | Get one term |
@@ -790,7 +790,7 @@ window filtering, before paging; negative values are a `400` naming the field.
790790 | GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |
791791 | GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |
792792 | 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 |
794794 | 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 |
795795 | GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included · paged |
796796 | 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.
967967
968968 A booking is `pending`, `approved`, `rejected`, or `cancelled`. The first two
969969 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). The
970+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
971973 decisions:
972974
973975 - `PATCH /{id}/approve` — the slot's teacher (or manager+) confirms. Refused
@@ -981,7 +983,7 @@ decisions:
981983 simply by rescheduling to a time that works. Refused (`409`) once the
982984 meeting's window has started: a
983985 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, so
986+ domain's `cancel` itself, on a fresh read compared-and-set into the row, so
985987 every way of cancelling — the decline below included — inherits it.
986988 - `PATCH /{id}/reschedule` (`{starts_at, ends_at}`) — the teacher
987989 **counter-proposes**. The times land on the *same* row as
@@ -1132,7 +1134,12 @@ editable `settings` singleton (`GET /settings` for any signed-in user,
11321134 re-weights every exam of that kind at once. For the same reason a kind
11331135 whose exams already carry marks cannot be removed from the list (`409`):
11341136 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.
11361143 - **`attendance_statuses`** — what attendance marking accepts. The core four
11371144 (`present`, `absent`, `late`, `excused`) are mandatory because the
11381145 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
11671174 otherwise), so two managers patching different fields both land instead of
11681175 the later write silently reverting the earlier one. Editing a list never
11691176 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).
11711179
11721180 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").
11731181
@@ -1698,9 +1706,12 @@ a bank row **never freezes** — its owner can edit or delete it forever.
16981706
16991707 `POST /bank-questions` (teacher+) saves one, stamping the caller as its
17001708 **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, so
1702-deleting a subject a template still references is a `409` (same as exam
1703-questions and homework). Reads are school-wide: `GET /bank-questions` lists the
1709+subject is a `400` (create and PATCH alike). The reverse guard does **not**
1710+hold here, unlike exam questions and homework: a template never blocks a
1711+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
17041715 whole bank (paged, `?subject=<id>` narrows by origin subject, `?owner=<id>` — or
17051716 `?owner=me` — by owner) and `GET /bank-questions/{bid}` fetches one with
17061717 `correct` included — any teacher+ can browse and reuse what any colleague
@@ -2274,6 +2285,47 @@ as the message's `error_code`.
22742285 add fields (a model name, token counts) and a future backend may send more
22752286 context without either end having to be redeployed in lockstep.
22762287
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+
22772329 ## Layout
22782330
22792331 ```
@@ -2310,7 +2362,9 @@ src/
23102362 cap.rs claim()/release(): the cross-replica count caps — an atomic
23112363 `UPDATE parent SET n += 1 WHERE n < cap` on a counter column
23122364 of the parent row, replacing the per-process mutexes that
2313- only held while one instance owned the database
2365+ 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
23142368 text_fold.rs case- and diacritic-insensitive folding for search, shared by
23152369 the Rust needle and the SurrealQL column (Turkish İ/ı, ü, ö…)
23162370 session.rs SessionId · SessionToken · Session (7-day expiry)
@@ -2374,8 +2428,9 @@ src/
23742428 AppointmentSlot (a teacher's published availability; a
23752429 recurring publish is expanded into rows sharing a series id)
23762430 appointment.rs AppointmentId · AppointmentStatus · AppointmentReason ·
2377- Appointment (a booking on a slot; occupancy and overlap are
2378- derived under APPOINTMENT_LOCK, never stored)
2431+ Appointment (a booking on a slot; occupancy is the slot's
2432+ stored `occupied` cap-1 counter, overlap is derived under
2433+ APPOINTMENT_LOCK)
23792434 pomodoro.rs PomodoroSessionId · PomodoroSession (student focus log)
23802435 pool_question.rs PoolQuestionId · PoolQuestionTitle · PoolQuestionBody ·
23812436 PoolQuestion (student-asked question; teacher-approved into
src/constant.rsmodified+51 -0
@@ -742,6 +742,11 @@ pub const DIETARY_PROFILE_TABLE: &str = "dietary_profile";
742742 pub const MEAL_BOOKING_TABLE: &str = "meal_booking";
743743 pub const MEAL_ATTENDANCE_TABLE: &str = "meal_attendance";
744744 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";
745750
746751 // --- cross-replica cap counters ----------------------------------------
747752
@@ -754,9 +759,55 @@ pub const MEAL_LEDGER_TABLE: &str = "meal_ledger";
754759 /// SCHEMAFULL refusing the write.
755760 pub const ENROLLMENT_COUNT_FIELD: &str = "enrollment_count";
756761 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";
757767 pub const NOTE_FILE_COUNT_FIELD: &str = "file_count";
758768 pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count";
759769 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";
760811
761812 /// How hard a counter write tries before giving up, and the first backoff step
762813 /// it sleeps between attempts (doubling, plus jitter). Contention on one record
src/database.rsmodified+79 -14
@@ -7,9 +7,10 @@ use surrealdb::types::SurrealValue;
77
88 use crate::config::Config;
99 use crate::constant::{
10- CHATBOT_PENDING_STALE_SECS, MIGRATION_LOCK_CLAIM, MIGRATION_LOCK_DDL, MIGRATION_LOCK_HEARTBEAT,
11- MIGRATION_LOCK_HEARTBEAT_SECS, MIGRATION_LOCK_LEASE_SECS, MIGRATION_LOCK_POLL_MS,
12- MIGRATION_LOCK_STAMP, MIGRATION_LOCK_STATE, MIGRATION_LOCK_TAKEOVER, MIGRATION_LOCK_WAIT_SECS,
10+ CAS_UPDATE_RETRIES, CHATBOT_PENDING_STALE_SECS, MIGRATION_LOCK_CLAIM, MIGRATION_LOCK_DDL,
11+ MIGRATION_LOCK_HEARTBEAT, MIGRATION_LOCK_HEARTBEAT_SECS, MIGRATION_LOCK_LEASE_SECS,
12+ MIGRATION_LOCK_POLL_MS, MIGRATION_LOCK_STAMP, MIGRATION_LOCK_STATE, MIGRATION_LOCK_TAKEOVER,
13+ MIGRATION_LOCK_WAIT_SECS,
1314 };
1415 use crate::domain::user::{Password, User, Username};
1516 use crate::error::AppError;
@@ -143,13 +144,24 @@ async fn boot_once(
143144 if claim(db, MIGRATION_LOCK_CLAIM, &me, lease_ms).await? {
144145 return leader_applies(db, &me, admin).await.map(|()| true);
145146 }
146- let state: Option<LockState> = db
147+ let read = db
147148 .query(MIGRATION_LOCK_STATE)
148149 .bind(("lease_ms", lease_ms))
149150 .bind(("fingerprint", migration_fingerprint()))
150- .await?
151- .check()?
152- .take(0)?;
151+ .await
152+ .and_then(|response| response.check())
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+ };
153165 match state {
154166 // A live lease, stamped with our own fingerprint: the exact schema
155167 // this process needs is in place, so stop waiting.
@@ -328,13 +340,34 @@ async fn leader_applies(
328340 lost = renew_lease(db, me) => return Err(lost),
329341 }
330342
331- let mut response = db
332- .query(MIGRATION_LOCK_STAMP)
333- .bind(("me", me.to_string()))
334- .bind(("fingerprint", migration_fingerprint()))
335- .await?
336- .check()?;
337- let stamped: Vec<String> = response.take(0)?;
343+ // The stamp is the one write in this path with nothing above it to retry
344+ // it: waiters are polling the same row and taking it over, so the
345+ // key-value layer can abort ours as retryable, and an escaping conflict
346+ // fails a boot that had already migrated everything. Repeating it is safe
347+ // despite `applies += 1` — a conflicted transaction commits nothing, and
348+ // the statement's `holder` guard turns a *genuine* takeover into an empty
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+ }
338371 if stamped.is_empty() {
339372 // The same verdict as a lost renewal, for the same reason — this is the
340373 // backstop for losing the lock in the window between the last renewal
@@ -524,6 +557,38 @@ mod tests {
524557 );
525558 }
526559
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+
527592 /// A leader killed mid-migration leaves its claim behind. Nothing may
528593 /// require a human with a SurrealQL prompt to clear it: the next boot takes
529594 /// the lease over once it has gone unrenewed past the horizon.
src/domain/appointment.rsmodified+200 -84
@@ -2,28 +2,32 @@
22 //! for the meeting with a reason; the teacher approves, rejects, or
33 //! counter-proposes another time.
44 //!
5-//! Two *cross-record* invariants live here, and both are guarded by
6-//! [`APPOINTMENT_LOCK`] rather than by the database:
5+//! Two *cross-record* invariants live here, guarded very differently:
76 //!
8-//! - **One live booking per slot.** Occupancy is counted from the rows, not
9-//! stored — so rejecting or cancelling frees the slot with nothing to reset.
7+//! - **One live booking per slot** — the `occupied` counter on the slot row, a
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.
1012 //! - **No double-booked person.** An approved meeting may not overlap another
11-//! approved meeting of the same teacher *or* of the same requester.
12-//!
13-//! Both are count-then-write checks across records, which a `BEGIN…COMMIT`
14-//! does not serialize in SurrealDB (write-skew: two racing bookings each see a
15-//! free slot).
13+//! approved meeting of the same teacher *or* of the same requester. That is a
14+//! count-then-write over *many* rows, which a `BEGIN…COMMIT` does not
15+//! serialize in SurrealDB (write-skew), so it stays under
16+//! [`APPOINTMENT_LOCK`] — and stays replica-local.
1617 //!
1718 //! The *single-row* invariant — a decision must be written onto the state it
1819 //! was validated against — is **not** the lock's job, and never was: the lock
1920 //! is process-local, so two replicas each take their own copy of it and a
2021 //! whole-row save would silently drop the other's decision. That one is a
2122 //! compare-and-set ([`Appointment::save_if_unchanged`]), which holds across
22-//! replicas. The lock stays for the two counts above, which no per-row
23-//! conditional write can cover.
24-// ponytail: with more than one replica those two counts are only
25-// replica-local. Closing them needs a stored occupancy counter (`domain::cap`)
26-// rather than a lock — deliberately not built here.
23+//! replicas.
24+//!
25+//! Overlap is a **documented accepted race** (reviewed, not an oversight):
26+//! it is a predicate over *other* rows with no single row to key a counter or
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.
2731
2832 use std::sync::LazyLock;
2933
@@ -31,20 +35,33 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
3135 use tokio::sync::Mutex;
3236 use ulid::Generator;
3337
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+};
3541 use crate::database::{Database, lost_the_race};
3642 use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId};
43+use crate::domain::cap;
3744 use crate::domain::page::PagedList;
3845 use crate::domain::timestamp::Timestamp;
3946 use crate::domain::user::UserId;
4047 use crate::error::{AppError, ValidationError};
4148 use crate::validate::validate_required;
4249
43-/// Serializes every occupancy/overlap decision: the check and the write it
44-/// authorizes must be one atomic step, and SurrealDB transactions do not
45-/// conflict-check a cross-record `count()` against a concurrent insert.
50+/// Serializes the **overlap** check and the write it authorizes — nothing else.
51+/// "Is this teacher (or this requester) already committed at that time" is a
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.
4661 ///
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`,
4865 /// `TERM_LOCK`, `EXAM_LOCK`, or `PRESENCE_LOCK` — appointments
4966 /// touch no roster, term, event seat, or exam room, and none of those touch
5067 /// appointments — so they cannot deadlock. Should a future path ever need two,
@@ -299,60 +316,15 @@ impl Appointment {
299316 }))
300317 }
301318
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-
348319 /// Request `slot`. Lands `pending`: publishing availability is not consent
349320 /// to a specific person and topic.
350321 ///
351- /// Refused (409) when the slot's window has already opened, when it already
352- /// carries a live booking, or when the requester is already committed
353- /// elsewhere at that time — all re-derived
354- /// from a fresh read under [`APPOINTMENT_LOCK`], so two racing requests
355- /// cannot both find the slot free.
322+ /// Refused (409) when the slot's window has already opened, when it is
323+ /// already taken, or when the requester is already committed elsewhere at
324+ /// that time. The slot is taken by [`cap::claim`] on the slot row — a
325+ /// conditional single-record write, so two racing requests cannot both find
326+ /// it free however many replicas they arrive at; the requester's own overlap
327+ /// is the lock's part.
356328 pub async fn book(
357329 slot: &AppointmentSlotId,
358330 requester: &UserId,
@@ -363,9 +335,6 @@ impl Appointment {
363335 let slot_row = AppointmentSlot::read(slot, db)
364336 .await?
365337 .ok_or(AppError::NotFound)?;
366- if Self::has_live_booking(slot, db).await? {
367- return Err(AppError::Conflict("the slot is already booked"));
368- }
369338 // A window that has opened is history, not a plan: `cancel` refuses to
370339 // call off a meeting that started, so such a booking would be stuck
371340 // forever. `list_upcoming` hides these slots, but a stale id still
@@ -390,6 +359,17 @@ impl Appointment {
390359 "you already have an appointment at that time",
391360 ));
392361 }
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+ }
393373 let appointment = Appointment {
394374 id: AppointmentId::generate(),
395375 slot: slot.clone(),
@@ -405,11 +385,21 @@ impl Appointment {
405385 reject_reason: None,
406386 created_at: Timestamp::now(),
407387 };
408- let created: Option<Appointment> = db
388+ let created: Result<Option<Appointment>, _> = db
409389 .create(appointment.id.record())
410390 .content(appointment)
411- .await?;
412- created.ok_or_else(|| AppError::Internal("failed to book the appointment".into()))
391+ .await;
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+ }
413403 }
414404
415405 pub async fn read(id: &AppointmentId, db: &Database) -> Result<Option<Appointment>, AppError> {
@@ -509,14 +499,15 @@ impl Appointment {
509499 Err(contended())
510500 }
511501
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.
513505 pub async fn reject(
514506 id: &AppointmentId,
515507 decided_by: &UserId,
516508 reason: Option<AppointmentReason>,
517509 db: &Database,
518510 ) -> Result<Appointment, AppError> {
519- let _guard = APPOINTMENT_LOCK.lock().await;
520511 for _ in 0..CAS_UPDATE_RETRIES {
521512 let expected = Self::read_pending(id, db).await?;
522513 let mut rejected = expected.clone();
@@ -547,7 +538,6 @@ impl Appointment {
547538 reason: Option<AppointmentReason>,
548539 db: &Database,
549540 ) -> Result<Appointment, AppError> {
550- let _guard = APPOINTMENT_LOCK.lock().await;
551541 for _ in 0..CAS_UPDATE_RETRIES {
552542 let expected = Self::read(id, db).await?.ok_or(AppError::NotFound)?;
553543 if !expected.status.is_live() {
@@ -595,7 +585,8 @@ impl Appointment {
595585 }
596586 .into());
597587 }
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.
599590 for _ in 0..CAS_UPDATE_RETRIES {
600591 let expected = Self::read(id, db).await?.ok_or(AppError::NotFound)?;
601592 if !expected.status.is_live() {
@@ -664,20 +655,34 @@ impl Appointment {
664655 /// A store-level write conflict is reported the same way as a miss: it
665656 /// means a concurrent write committed on this row, which is exactly the
666657 /// "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.
667664 async fn save_if_unchanged(
668665 self,
669666 expected: &Appointment,
670667 db: &Database,
671668 ) -> Result<Option<Appointment>, AppError> {
669+ let frees_the_slot = expected.status.is_live() && !self.status.is_live();
672670 let attempted = async {
673671 let mut result = db
674672 .query(
675- "UPDATE $id CONTENT $new \
673+ "BEGIN TRANSACTION;
674+ LET $done = (UPDATE $id CONTENT $new \
676675 WHERE status = $status \
677676 AND proposed_starts_at = $proposed_starts_at \
678677 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;",
680683 )
684+ .bind(("slot", expected.slot.record()))
685+ .bind(("frees", frees_the_slot))
681686 .bind(("id", expected.id.record()))
682687 .bind(("status", expected.status))
683688 .bind(("proposed_starts_at", expected.proposed_starts_at))
@@ -686,7 +691,8 @@ impl Appointment {
686691 .bind(("new", self))
687692 .await?
688693 .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)
690696 }
691697 .await;
692698 match attempted {
@@ -940,7 +946,115 @@ mod tests {
940946 assert_eq!(saved.get_proposed_starts_at(), Some(proposed_starts_at));
941947 }
942948
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.
9441058 #[tokio::test]
9451059 async fn rejecting_frees_the_slot_for_re_booking() {
9461060 let db = crate::database::init_mem().await.unwrap();
@@ -966,9 +1080,11 @@ mod tests {
9661080 Appointment::reject(first.get_id(), &teacher, None, &db)
9671081 .await
9681082 .unwrap();
1083+ assert_eq!(occupied(slot.get_id(), &db).await, 0);
9691084 let second = Appointment::book(slot.get_id(), &UserId::from_key("s2"), reason(), &db)
9701085 .await
9711086 .unwrap();
9721087 assert_eq!(second.get_status(), AppointmentStatus::Pending);
1088+ assert_eq!(occupied(slot.get_id(), &db).await, 1);
9731089 }
9741090 }
src/domain/appointment_slot.rsmodified+112 -23
@@ -1,8 +1,11 @@
11 //! 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 is
3-//! *derived* from its [`Appointment`] rows under [`APPOINTMENT_LOCK`], so a
4-//! rejected or cancelled booking frees the slot again without any flag to
5-//! reset (and without a UNIQUE index, which would keep a dead booking's seat).
2+//! nearly pure calendar: the one piece of booking state it carries is the
3+//! `occupied` counter (a [`cap`](crate::domain::cap) of one), taken when a
4+//! booking is made and given back in the same transaction as the reject or
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.
69 //!
710 //! A recurring publish is expanded into concrete rows here, at write time,
811 //! sharing one `series` id — no recurrence rule is ever evaluated at read
@@ -430,11 +433,10 @@ impl AppointmentSlot {
430433 /// Settled bookings (rejected/cancelled) are history of a slot that is
431434 /// going away, so they cascade out with it, like [`Event::delete`]'s rows.
432435 ///
433- /// The occupancy read and the delete run under [`APPOINTMENT_LOCK`], so a
434- /// booking cannot land between them and outlive its slot.
436+ /// The guard is the delete's own `WHERE`, so no booking can land between a
437+ /// check and the row going away — in this replica or another.
435438 pub async fn delete(self, db: &Database) -> Result<AppointmentSlot, AppError> {
436- let _guard = APPOINTMENT_LOCK.lock().await;
437- Self::delete_locked(std::slice::from_ref(&self.id), db).await?;
439+ Self::delete_free(std::slice::from_ref(&self.id), db).await?;
438440 Ok(self)
439441 }
440442
@@ -445,34 +447,61 @@ impl AppointmentSlot {
445447 series: &SlotSeries,
446448 db: &Database,
447449 ) -> Result<Vec<AppointmentSlot>, AppError> {
448- let _guard = APPOINTMENT_LOCK.lock().await;
449450 let slots = Self::list_for_series(series, db).await?;
450451 if slots.is_empty() {
451452 return Err(AppError::NotFound);
452453 }
453454 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?;
455456 Ok(slots)
456457 }
457458
458- /// Shared body of both deletes. Caller must already hold
459- /// [`APPOINTMENT_LOCK`]: the live-booking check is only meaningful while
460- /// no booking can be written.
461- async fn delete_locked(ids: &[AppointmentSlotId], db: &Database) -> Result<(), AppError> {
462- if Appointment::any_live_booking(ids, db).await? {
459+ /// Shared body of both deletes: drop every named slot, but only while its
460+ /// `occupied` counter says nobody is waiting on it — the delete's own
461+ /// `WHERE` is the guard, which is what makes it hold against a booking
462+ /// landing in another replica (a separate read-then-delete could not).
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") {
463495 return Err(AppError::Conflict(
464496 "the slot has a pending or approved booking",
465497 ));
466498 }
467- let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect();
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() {
499+ if thrown("slot_missing") {
474500 return Err(AppError::NotFound);
475501 }
502+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
503+ return Err(error.into());
504+ }
476505 Ok(())
477506 }
478507 }
@@ -480,7 +509,8 @@ impl AppointmentSlot {
480509 #[cfg(test)]
481510 mod tests {
482511 use super::*;
483- use crate::constant::MILLIS_PER_DAY;
512+ use crate::constant::{MILLIS_PER_DAY, SLOT_OCCUPIED_FIELD};
513+ use crate::domain::cap;
484514
485515 fn at(millis: i64) -> Timestamp {
486516 Timestamp::from_millis(millis)
@@ -723,6 +753,65 @@ mod tests {
723753 );
724754 }
725755
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+
726815 #[tokio::test]
727816 async fn weekly_publish_that_self_overlaps_is_refused() {
728817 let db = crate::database::init_mem().await.unwrap();
src/domain/bank_question.rsmodified+21 -6
@@ -771,10 +771,25 @@ mod tests {
771771
772772 let exam = ExamId::generate();
773773 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+ ) {
775790 ExamQuestion::create_from_bank(
776791 exam,
777- SubjectId::generate(),
792+ subject.clone(),
778793 source.get_text().clone(),
779794 source.get_points(),
780795 source.spec(),
@@ -785,13 +800,13 @@ mod tests {
785800 .unwrap();
786801 }
787802 // Two copies of the same template, in two different exams.
788- instantiate(&exam, &used_twice, &db).await;
789- instantiate(&other_exam, &used_twice, &db).await;
790- instantiate(&exam, &used_once, &db).await;
803+ instantiate(&exam, subject.get_id(), &used_twice, &db).await;
804+ instantiate(&other_exam, subject.get_id(), &used_twice, &db).await;
805+ instantiate(&exam, subject.get_id(), &used_once, &db).await;
791806 // A hand-authored question has no `from_bank` and must not be tallied.
792807 ExamQuestion::create(
793808 &exam,
794- SubjectId::generate(),
809+ subject.get_id().clone(),
795810 QuestionText::try_new("mine").unwrap(),
796811 QuestionPoints::try_new(1).unwrap(),
797812 spec(),
src/domain/cap.rsmodified+228 -10
@@ -26,10 +26,10 @@
2626 // drift is ever observed, the repair is the same GROUP BY count the backfill
2727 // runs, issued by hand with the field's `= NONE` guard dropped.
2828
29-use surrealdb::types::RecordId;
29+use surrealdb::types::{RecordId, SurrealValue};
3030 use tokio::sync::Mutex;
3131
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};
3333 use crate::database::{Database, lost_the_race};
3434 use crate::domain::timestamp::Timestamp;
3535 use crate::error::AppError;
@@ -69,13 +69,176 @@ pub(crate) async fn claim(
6969 cap: i64,
7070 db: &Database,
7171 ) -> 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+ };
72104 let sql = format!(
73105 "UPDATE $parent SET {field} = ({field} ?? 0) + 1 \
74- WHERE ({field} ?? 0) < $cap RETURN VALUE id"
106+ WHERE ({field} ?? 0) < $num{extra} RETURN VALUE id"
75107 );
76108 Ok(!write(&sql, parent, cap, db).await?.is_empty())
77109 }
78110
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+
79242 /// Give a claimed slot back, for the insert that never landed. Clamped at zero
80243 /// so a double release can never push a counter negative and open the cap.
81244 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
85248 Ok(())
86249 }
87250
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+
88308 /// Run one conditional counter write, retrying while the store reports a write
89309 /// conflict.
90310 ///
@@ -94,25 +314,23 @@ pub(crate) async fn release(parent: &RecordId, field: &str, db: &Database) -> Re
94314 /// never letting two writers reach the database at once. So the queueing has to
95315 /// happen here. Backoff is exponential with jitter, because racers arrive in
96316 /// 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.
97319 async fn write(
98320 sql: &str,
99321 parent: &RecordId,
100- cap: i64,
322+ num: i64,
101323 db: &Database,
102324 ) -> Result<Vec<RecordId>, AppError> {
103325 let _guard = CLAIM_LOCK.lock().await;
104326 let mut last = None;
105327 for attempt in 0..CAP_WRITE_TRIES {
106- if attempt > 0 {
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- }
328+ backoff(attempt).await;
111329 let attempted = async {
112330 let mut result = db
113331 .query(sql)
114332 .bind(("parent", parent.clone()))
115- .bind(("cap", cap))
333+ .bind(("num", num))
116334 .await?
117335 .check()?;
118336 result.take::<Vec<RecordId>>(0)
src/domain/course.rsmodified+254 -16
@@ -1,8 +1,12 @@
11 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
22 use ulid::Ulid;
33
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+};
58 use crate::database::Database;
9+use crate::domain::cap;
610 use crate::domain::field_update::FieldUpdate;
711 use crate::domain::page::PagedList;
812 use crate::domain::term::TermId;
@@ -10,6 +14,10 @@ use crate::domain::user::UserId;
1014 use crate::error::{AppError, ValidationError};
1115 use crate::validate::{validate_course_kind, validate_optional, validate_required};
1216
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+
1321 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
1422 pub struct CourseId(RecordId);
1523
@@ -153,6 +161,11 @@ impl Course {
153161 self.teachers.contains(user)
154162 }
155163
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.
156169 pub async fn create(
157170 creator: &UserId,
158171 title: CourseTitle,
@@ -162,18 +175,35 @@ impl Course {
162175 capacity: Option<i64>,
163176 db: &Database,
164177 ) -> Result<Course, AppError> {
178+ if let Some(term) = &term {
179+ claim_term(term, db).await?;
180+ }
181+ let claimed = term.clone();
165182 let course = Course {
166183 id: CourseId::generate(),
167184 creator: creator.clone(),
168185 teachers: Vec::new(),
186+ term,
187+ capacity,
169188 title,
170189 description,
171190 kind,
172- term,
173- capacity,
174191 };
175- let created: Option<Course> = db.create(course.id.record()).content(course).await?;
176- created.ok_or_else(|| AppError::Internal("failed to create course".into()))
192+ let created: Result<Option<Course>, _> =
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+ }
177207 }
178208
179209 pub async fn read(id: &CourseId, db: &Database) -> Result<Option<Course>, AppError> {
@@ -250,14 +280,43 @@ impl Course {
250280 capacity: Option<Option<i64>>,
251281 db: &Database,
252282 ) -> 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())
254295 .set("title", title)
255296 .set("description", description)
256297 .set("kind", kind)
257298 .set("term", term.map(|term| term.map(|term| term.record())))
258299 .set("capacity", capacity)
259300 .run::<Course>(db)
260- .await
301+ .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+ }
261320 }
262321
263322 /// Assign `teacher` to run this course, or return the course untouched if
@@ -332,9 +391,36 @@ impl Course {
332391 /// leave an exam pointing at a deleted course. The image and
333392 /// homework-file *blobs* are the web layer's to remove — it collects
334393 /// their names before calling this.
335- pub async fn delete(self, db: &Database) -> Result<Course, AppError> {
336- db.query(
394+ ///
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!(
337409 "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+ }};
338424 DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
339425 DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
340426 DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
@@ -350,20 +436,172 @@ impl Course {
350436 DELETE subject WHERE course = $course;
351437 DELETE homework WHERE course = $course;
352438 DELETE exam WHERE course = $course;
353- COMMIT TRANSACTION;",
354- )
355- .bind(("course", self.id.record()))
356- .await?
357- .check()?;
358- let deleted: Option<Course> = db.delete(self.id.record()).await?;
359- deleted.ok_or(AppError::NotFound)
439+ COMMIT TRANSACTION;"
440+ ))
441+ .bind(("course", self.id.record()))
442+ .await?;
443+ // An aborted transaction errors *every* slot, most with a generic "not
444+ // executed" — only the THROW's own slot names the marker.
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)
360461 }
361462 }
362463
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+
363478 #[cfg(test)]
364479 mod tests {
365480 use super::*;
366481
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+
367605 #[tokio::test]
368606 async fn title_is_required() {
369607 assert!(CourseTitle::try_new("algebra").is_ok());
src/domain/enrollment.rsmodified+31 -54
@@ -1,24 +1,13 @@
11 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2-use tokio::sync::Mutex;
32
43 use crate::constant::{ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE};
5-use crate::database::{Database, lost_the_race};
4+use crate::database::Database;
65 use crate::domain::cap;
76 use crate::domain::course::{Course, CourseId};
87 use crate::domain::page::PagedList;
98 use crate::domain::user::UserId;
109 use crate::error::AppError;
1110
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-
2211 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
2312 pub struct EnrollmentId(RecordId);
2413
@@ -82,13 +71,15 @@ impl Enrollment {
8271 /// single-record conditional write, so the cap holds across replicas and
8372 /// against a concurrent capacity PATCH alike. An already enrolled user is
8473 /// 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.
8577 pub async fn enroll(
8678 course: &CourseId,
8779 user: &UserId,
8880 enrolled_by: &UserId,
8981 db: &Database,
9082 ) -> Result<Enrollment, AppError> {
91- let _guard = ENROLL_LOCK.lock().await;
9283 if let Some(existing) = Self::read_for_user(course, user, db).await? {
9384 return Ok(existing);
9485 }
@@ -96,43 +87,39 @@ impl Enrollment {
9687 .await?
9788 .ok_or(AppError::NotFound)?
9889 .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- }
11090 let enrollment = Enrollment {
11191 id: EnrollmentId::composite(course, user),
11292 course: course.clone(),
11393 user: user.clone(),
11494 enrolled_by: enrolled_by.clone(),
11595 };
116- // CREATE, not UPSERT: a duplicate has to be *seen*, or the pair's second
117- // writer would silently keep the seat it claimed for a row that already
118- // existed and the counter would drift above the roster forever.
119- let saved: Result<Option<Enrollment>, _> =
120- db.create(enrollment.id.record()).content(enrollment).await;
121- match saved {
122- Ok(Some(saved)) => Ok(saved),
123- Ok(None) => {
124- cap::release(&seats, ENROLLMENT_COUNT_FIELD, db).await?;
125- Err(AppError::Internal("failed to enroll user".into()))
126- }
127- Err(err) => {
128- cap::release(&seats, ENROLLMENT_COUNT_FIELD, db).await?;
129- if !lost_the_race(&err) {
130- return Err(err.into());
131- }
132- Self::read_for_user(course, user, db)
133- .await?
134- .ok_or_else(|| AppError::Internal("failed to enroll user".into()))
135- }
96+ // CREATE, not UPSERT, and in the seat's own transaction: a duplicate has
97+ // to be *seen*, or the pair's second writer would keep the seat it
98+ // claimed for a row that already existed and the counter would drift
99+ // above the roster forever.
100+ match cap::claim_and_create(
101+ &course.record(),
102+ ENROLLMENT_COUNT_FIELD,
103+ capacity.unwrap_or(cap::UNLIMITED),
104+ &enrollment.id.record(),
105+ &enrollment,
106+ db,
107+ )
108+ .await?
109+ {
110+ cap::Claimed::Made(saved) => Ok(saved),
111+ // Someone placed this pair first; their row is the answer, and no
112+ // seat was spent finding that out.
113+ cap::Claimed::Duplicate => Self::read_for_user(course, user, db)
114+ .await?
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+ },
136123 }
137124 }
138125
@@ -151,16 +138,6 @@ impl Enrollment {
151138 Ok(result.take::<Vec<Enrollment>>(0)?.into_iter().next())
152139 }
153140
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-
164141 pub async fn list_for_course(
165142 course: &CourseId,
166143 limit: Option<i64>,
src/domain/exam.rsmodified+42 -0
@@ -290,6 +290,14 @@ pub struct Exam {
290290 // managers, cannot be sat, and cannot be graded. Rows predating the
291291 // column are backfilled published (`false`).
292292 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>,
293301 }
294302
295303 impl Exam {
@@ -297,6 +305,11 @@ impl Exam {
297305 &self.id
298306 }
299307
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+
300313 pub fn get_creator(&self) -> &UserId {
301314 &self.creator
302315 }
@@ -403,6 +416,7 @@ impl Exam {
403416 allow_rejoin,
404417 allow_review,
405418 draft,
419+ result_count: None,
406420 };
407421 let created: Option<Exam> = db.create(exam.id.record()).content(exam).await?;
408422 created.ok_or_else(|| AppError::Internal("failed to create exam".into()))
@@ -523,6 +537,7 @@ impl Exam {
523537 AND allow_rejoin = $was_allow_rejoin
524538 AND allow_review = $was_allow_review
525539 AND draft = $was_draft
540+ AND (result_count ?? 0) = $was_results
526541 RETURN AFTER;
527542 COMMIT TRANSACTION;",
528543 )
@@ -539,6 +554,12 @@ impl Exam {
539554 .bind(("was_allow_rejoin", was.8))
540555 .bind(("was_allow_review", was.9))
541556 .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)))
542563 .bind(("new", self))
543564 .await?;
544565 // An aborted transaction errors every slot; only the THROW's names the
@@ -566,15 +587,35 @@ impl Exam {
566587 /// Bank templates saved out of this exam survive it — they are a separate,
567588 /// reusable library — so only their `source_exam` provenance link is cleared,
568589 /// 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.
569600 pub async fn delete(self, db: &Database) -> Result<Exam, AppError> {
570601 let mut result = db
571602 .query(
572603 "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+ };
573609 DELETE exam_result WHERE exam = $ex;
574610 DELETE exam_attempt WHERE exam = $ex;
575611 DELETE exam_answer WHERE exam = $ex;
576612 DELETE answer_image WHERE exam = $ex;
577613 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+ };
578619 DELETE exam_question WHERE exam = $ex;
579620 UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex;
580621 LET $before = (DELETE $ex RETURN BEFORE);
@@ -697,6 +738,7 @@ mod tests {
697738 1,
698739 Mark::try_new(80).unwrap(),
699740 &UserId::generate(),
741+ exam.get_kind().as_str(),
700742 &db,
701743 )
702744 .await
src/domain/exam_attempt.rsmodified+11 -1
@@ -438,9 +438,19 @@ mod tests {
438438 &[],
439439 )
440440 .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();
441451 let question = ExamQuestion::create(
442452 exam.get_id(),
443- crate::domain::subject::SubjectId::generate(),
453+ subject.get_id().clone(),
444454 crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(),
445455 QuestionPoints::try_new(5).unwrap(),
446456 spec,
src/domain/exam_question.rsmodified+94 -47
@@ -3,10 +3,11 @@ use ulid::Ulid;
33
44 use crate::constant::{
55 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,
77 };
88 use crate::database::Database;
99 use crate::domain::bank_question::BankQuestionId;
10+use crate::domain::cap;
1011 use crate::domain::exam::ExamId;
1112 use crate::domain::exam_attempt::ExamAttempt;
1213 use crate::domain::monotonic_id::next_ulid;
@@ -393,6 +394,20 @@ impl ExamQuestion {
393394 from_bank: Option<BankQuestionId>,
394395 db: &Database,
395396 ) -> 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+ }
396411 let question = ExamQuestion {
397412 id: ExamQuestionId::generate(),
398413 exam: exam.clone(),
@@ -409,18 +424,28 @@ impl ExamQuestion {
409424 // The freeze gate rides in the same transaction as the insert: a
410425 // question cannot appear under an exam somebody has already started,
411426 // whichever replica the two requests hit.
412- let mut result = db
413- .query(ExamAttempt::unfrozen("CREATE $id CONTENT $question;"))
414- .bind(("freeze_exam", exam.record()))
415- .bind(("id", question.id.record()))
416- .bind(("question", question))
417- .await?;
418- ExamAttempt::frozen_check(&mut result)?;
419- result
420- .take::<Vec<ExamQuestion>>(ExamAttempt::FROZEN_SLOT)?
421- .into_iter()
422- .next()
423- .ok_or_else(|| AppError::Internal("failed to create exam question".into()))
427+ let inserted = async {
428+ let mut result = db
429+ .query(ExamAttempt::unfrozen("CREATE $id CONTENT $question;"))
430+ .bind(("freeze_exam", exam.record()))
431+ .bind(("id", question.id.record()))
432+ .bind(("question", question))
433+ .await?;
434+ ExamAttempt::frozen_check(&mut result)?;
435+ result
436+ .take::<Vec<ExamQuestion>>(ExamAttempt::FROZEN_SLOT)?
437+ .into_iter()
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
424449 }
425450
426451 pub async fn read(
@@ -443,17 +468,6 @@ impl ExamQuestion {
443468 .await
444469 }
445470
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-
457471 /// Write the editable fields, refused outright once the exam has an
458472 /// attempt — the freeze gate is part of this transaction, not a check the
459473 /// caller made a moment earlier under a lock.
@@ -472,26 +486,49 @@ impl ExamQuestion {
472486 spec: QuestionSpec,
473487 db: &Database,
474488 ) -> Result<ExamQuestion, AppError> {
475- let mut result = db
476- .query(ExamAttempt::unfrozen(
477- "UPDATE $id SET subject = $subject, text = $text, points = $points,
478- kind = $kind, choices = $choices, correct = $correct RETURN AFTER;",
479- ))
480- .bind(("freeze_exam", self.exam.record()))
481- .bind(("id", self.id.record()))
482- .bind(("subject", subject.record()))
483- .bind(("text", text))
484- .bind(("points", points))
485- .bind(("kind", spec.kind))
486- .bind(("choices", spec.choices))
487- .bind(("correct", spec.correct))
488- .await?;
489- ExamAttempt::frozen_check(&mut result)?;
490- result
491- .take::<Vec<ExamQuestion>>(ExamAttempt::FROZEN_SLOT)?
492- .into_iter()
493- .next()
494- .ok_or(AppError::NotFound)
489+ // A re-tag moves a reference: the new subject is claimed *before* the
490+ // write and the old one released only once it lands, so at no instant
491+ // is either subject under-counted — the direction that would let one be
492+ // deleted while this question still points at it. Both counters staying
493+ // put is the ordinary case (`subject` omitted from the PATCH), and it
494+ // costs nothing.
495+ let retag = (subject != self.subject).then(|| (subject.record(), self.subject.record()));
496+ if let Some((next, _)) = &retag
497+ && !cap::claim(next, SUBJECT_QUESTION_COUNT_FIELD, cap::UNLIMITED, db).await?
498+ {
499+ return Err(AppError::Validation(ValidationError::Invalid {
500+ field: "subject_id",
501+ reason: "subject does not exist",
502+ }));
503+ }
504+ let written = async {
505+ let mut result = db
506+ .query(ExamAttempt::unfrozen(
507+ "UPDATE $id SET subject = $subject, text = $text, points = $points,
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
495532 }
496533
497534 /// Point the question's `banked_as` at the bank template it was just saved
@@ -538,15 +575,25 @@ impl ExamQuestion {
538575 .query(ExamAttempt::unfrozen(
539576 "DELETE exam_answer WHERE question = $q;
540577 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;",
542584 ))
543585 .bind(("freeze_exam", self.exam.record()))
544586 .bind(("q", self.id.record()))
545587 .await?;
546588 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);
548595 result
549- .take::<Vec<ExamQuestion>>(ExamAttempt::FROZEN_SLOT + 2)?
596+ .take::<Vec<ExamQuestion>>(slot)?
550597 .into_iter()
551598 .next()
552599 .ok_or(AppError::NotFound)
src/domain/exam_result.rsmodified+136 -29
@@ -2,8 +2,11 @@ use std::collections::HashMap;
22
33 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
44
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+};
68 use crate::database::Database;
9+use crate::domain::cap;
710 use crate::domain::course::CourseId;
811 use crate::domain::exam::ExamId;
912 use crate::domain::key;
@@ -17,6 +20,25 @@ pub(crate) fn draft_error() -> AppError {
1720 AppError::Conflict("this exam is a draft — publish it before grading")
1821 }
1922
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+
2042 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
2143 pub struct ExamResultId(RecordId);
2244
@@ -58,6 +80,14 @@ impl Mark {
5880 }
5981 }
6082
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+
6191 #[derive(Debug, Clone, SurrealValue)]
6292 pub struct ExamResult {
6393 id: ExamResultId,
@@ -155,14 +185,54 @@ impl ExamResult {
155185 /// converge on one row instead of racing the unique index into a 500.
156186 /// Grading a retake writes a fresh mark at the current seq and never touches
157187 /// 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.
158201 pub async fn grade(
159202 exam: &ExamId,
160203 user: &UserId,
161204 seq: i64,
162205 mark: Mark,
163206 graded_by: &UserId,
207+ kind: &str,
164208 db: &Database,
165209 ) -> 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> {
166236 let result = ExamResult {
167237 id: ExamResultId::composite(exam, user, seq),
168238 exam: exam.clone(),
@@ -176,11 +246,17 @@ impl ExamResult {
176246 // them, a mark and a re-draft racing each other can only ever leave one
177247 // of the two applied, whichever process either ran in. The caller's
178248 // 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.
179253 let mut written = db
180254 .query(
181255 "BEGIN TRANSACTION;
182256 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] };
184260 COMMIT TRANSACTION;",
185261 )
186262 .bind(("exam", exam.record()))
@@ -197,9 +273,12 @@ impl ExamResult {
197273 if let Some(error) = errors.drain().map(|(_, error)| error).next() {
198274 return Err(error.into());
199275 }
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);
201280 written
202- .take::<Vec<ExamResult>>(2)?
281+ .take::<Vec<Written>>(slot)?
203282 .into_iter()
204283 .next()
205284 .ok_or_else(|| AppError::Internal("failed to record exam result".into()))
@@ -225,22 +304,6 @@ impl ExamResult {
225304 Ok(Self::latest_per_pair(result.take::<Vec<ExamResult>>(0)?))
226305 }
227306
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-
244307 pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamResult>, AppError> {
245308 let mut result = db
246309 .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC")
@@ -269,18 +332,44 @@ impl ExamResult {
269332 Ok(result.take::<Vec<ExamResult>>(0)?)
270333 }
271334
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.
272338 pub async fn remove(
273339 exam: &ExamId,
274340 user: &UserId,
341+ kind: &str,
275342 db: &Database,
276343 ) -> 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.
277350 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+ ))
279363 .bind(("ex", exam.record()))
280364 .bind(("usr", user.record()))
365+ .bind(("kind", kind.to_string()))
281366 .await?
282367 .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())
284373 }
285374 }
286375
@@ -305,12 +394,28 @@ mod tests {
305394 let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
306395
307396 // 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)
309- .await
310- .unwrap();
311- let second = ExamResult::grade(&exam, &user, 2, Mark::try_new(90).unwrap(), &teacher, &db)
312- .await
313- .unwrap();
397+ ExamResult::grade(
398+ &exam,
399+ &user,
400+ 1,
401+ Mark::try_new(40).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();
314419 assert_eq!(second.get_seq(), 2);
315420
316421 // Grade-of-record is the latest sitting's mark.
@@ -339,7 +444,9 @@ mod tests {
339444 );
340445
341446 // 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();
343450 assert!(
344451 ExamResult::list_all_for_exam_user(&exam, &user, &db)
345452 .await
src/domain/homework.rsmodified+66 -21
@@ -13,8 +13,12 @@
1313 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
1414 use ulid::Ulid;
1515
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+};
1720 use crate::database::Database;
21+use crate::domain::cap;
1822 use crate::domain::course::CourseId;
1923 use crate::domain::field_update::FieldUpdate;
2024 use crate::domain::subject::SubjectId;
@@ -156,6 +160,20 @@ impl Homework {
156160 created_by: &UserId,
157161 db: &Database,
158162 ) -> 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+ }
159177 let homework = Homework {
160178 id: HomeworkId::generate(),
161179 course: course.clone(),
@@ -167,8 +185,20 @@ impl Homework {
167185 created_by: created_by.clone(),
168186 created_at: Timestamp::now(),
169187 };
170- let created: Option<Homework> = db.create(homework.id.record()).content(homework).await?;
171- created.ok_or_else(|| AppError::Internal("failed to create homework".into()))
188+ let created: Result<Option<Homework>, AppError> = db
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+ }
172202 }
173203
174204 pub async fn read(id: &HomeworkId, db: &Database) -> Result<Option<Homework>, AppError> {
@@ -242,19 +272,6 @@ impl Homework {
242272 Ok(result.take::<Vec<Homework>>(0)?)
243273 }
244274
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-
258275 /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework.
259276 /// Request-scoped: every parameter is `Option`, `None` meaning the PATCH
260277 /// did not carry that field, so it is not written at all. Handing the
@@ -279,14 +296,35 @@ impl Homework {
279296 ) -> Result<Homework, AppError> {
280297 let assigned = assigned
281298 .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())
283316 .set("subject", subject.map(|subject| subject.record()))
284317 .set("title", title)
285318 .set("description", description)
286319 .set("due_at", due_at)
287320 .set("assigned", assigned)
288321 .run::<Homework>(db)
289- .await
322+ .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
290328 }
291329
292330 /// Delete the homework and cascade its submissions, their files, and its
@@ -302,14 +340,21 @@ impl Homework {
302340 DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw);
303341 DELETE homework_submission WHERE homework = $hw;
304342 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;
306348 COMMIT TRANSACTION;",
307349 )
308350 .bind(("hw", self.id.record()))
309351 .await?
310352 .check()?;
311- // BEGIN is slot 0; the homework's own DELETE is slot 4.
312- let deleted: Option<Homework> = result.take::<Vec<Homework>>(4)?.into_iter().next();
353+ // The subject's reference is given back in this same transaction, off
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();
313358 deleted.ok_or(AppError::NotFound)
314359 }
315360 }
src/domain/homework_file.rsmodified+108 -18
@@ -13,12 +13,13 @@ use ulid::Ulid;
1313
1414 use crate::constant::{
1515 HOMEWORK_FILE_TABLE, MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD,
16+ SUBMISSION_OPEN_GUARD,
1617 };
1718 use crate::database::Database;
1819 use crate::domain::cap;
1920 use crate::domain::course::CourseId;
2021 use crate::domain::homework::HomeworkId;
21-use crate::domain::homework_submission::HomeworkSubmissionId;
22+use crate::domain::homework_submission::{HomeworkSubmission, HomeworkSubmissionId};
2223 use crate::domain::note_file::{FileContentType, FileName};
2324 use crate::domain::timestamp::Timestamp;
2425 use crate::error::AppError;
@@ -60,6 +61,16 @@ pub struct HomeworkFile {
6061 created_at: Timestamp,
6162 }
6263
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+
6374 impl HomeworkFile {
6475 /// Assemble a row (fresh blob name generated here) without persisting it.
6576 /// The caller writes the blob under [`Self::get_file`] first, then calls
@@ -111,20 +122,27 @@ impl HomeworkFile {
111122 }
112123
113124 /// Persist the row assembled by [`Self::new`], refusing once its submission
114- /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`]. The slot is taken by
115- /// [`cap::claim`] on the submission row — a conditional single-record write,
116- /// the only guard that holds when the racing uploads are in two replicas,
117- /// the same story as `NoteFile::insert`.
118- pub async fn insert(self, db: &Database) -> Result<HomeworkFile, AppError> {
125+ /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`)
126+ /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own
127+ /// wording). Both are decided by one [`cap::claim_when`] on the submission
128+ /// row — a conditional single-record write, the only guard that holds when
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> {
119133 let submission = self.submission.record();
120- if !cap::claim(
134+ if !cap::claim_when(
121135 &submission,
122136 SUBMISSION_FILE_COUNT_FIELD,
123137 MAX_HOMEWORK_FILES_PER_SUBMISSION as i64,
138+ SUBMISSION_OPEN_GUARD,
124139 db,
125140 )
126141 .await?
127142 {
143+ if HomeworkSubmission::is_graded(&self.submission, db).await? {
144+ return Ok(None);
145+ }
128146 return Err(AppError::Conflict(
129147 "the submission already holds the maximum of 10 files — delete one first",
130148 ));
@@ -133,7 +151,7 @@ impl HomeworkFile {
133151 let created: Result<Option<HomeworkFile>, _> =
134152 db.create(self.id.record()).content(self).await;
135153 match created {
136- Ok(Some(created)) => Ok(created),
154+ Ok(Some(created)) => Ok(Some(created)),
137155 Ok(None) => {
138156 cap::release(&submission, SUBMISSION_FILE_COUNT_FIELD, db).await?;
139157 Err(AppError::Internal("failed to create homework file".into()))
@@ -242,23 +260,44 @@ impl HomeworkFile {
242260 /// Delete the row and give its slot back in the same transaction. The
243261 /// submission survives, so its counter has to be corrected; the cascades
244262 /// 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> {
246272 let mut result = db
247- .query(
273+ .query(format!(
248274 "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 {{ [] }};
250278 UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]);
251- RETURN $gone;
252- COMMIT TRANSACTION;",
253- )
279+ RETURN {{ open: array::len($open), gone: $gone }};
280+ COMMIT TRANSACTION;"
281+ ))
254282 .bind(("id", self.id.record()))
255283 .bind(("sub", self.submission.record()))
284+ .bind(("now", Timestamp::now()))
256285 .await?
257286 .check()?;
258- result
259- .take::<Vec<HomeworkFile>>(3)?
287+ // BEGIN is slot 0, the two LETs slots 1-2 and the counter fix slot 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
260298 .into_iter()
261299 .next()
300+ .map(Some)
262301 .ok_or(AppError::NotFound)
263302 }
264303 }
@@ -286,6 +325,7 @@ mod tests {
286325 // A real submission row, so the GC join through it resolves.
287326 let submission = HomeworkSubmission::upsert(&homework, &user, None, &db)
288327 .await
328+ .unwrap()
289329 .unwrap();
290330 let sub_a = submission.get_id().clone();
291331 let sub_b = HomeworkSubmissionId::composite(
@@ -293,7 +333,7 @@ mod tests {
293333 &UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"),
294334 );
295335
296- let stored = a_file(&sub_a).insert(&db).await.unwrap();
336+ let stored = a_file(&sub_a).insert(&db).await.unwrap().unwrap();
297337 // Readable under its own submission, invisible under another.
298338 assert!(
299339 HomeworkFile::read_for(stored.get_id(), &sub_a, &db)
@@ -342,11 +382,61 @@ mod tests {
342382
343383 // Fill to the cap, then the 11th is refused.
344384 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();
346386 }
347387 assert!(matches!(
348388 a_file(&sub_a).insert(&db).await,
349389 Err(AppError::Conflict(_))
350390 ));
351391 }
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+ }
352442 }
src/domain/homework_result.rsmodified+59 -9
@@ -13,11 +13,12 @@
1313
1414 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
1515
16-use crate::constant::HOMEWORK_RESULT_TABLE;
16+use crate::constant::{HOMEWORK_RESULT_TABLE, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD};
1717 use crate::database::Database;
1818 use crate::domain::course::CourseId;
1919 use crate::domain::exam_result::Mark;
2020 use crate::domain::homework::HomeworkId;
21+use crate::domain::homework_submission::HomeworkSubmissionId;
2122 use crate::domain::timestamp::Timestamp;
2223 use crate::domain::user::UserId;
2324 use crate::error::{AppError, ValidationError};
@@ -119,6 +120,22 @@ impl HomeworkResult {
119120 /// UPSERT — concurrent grades for the same pair converge on one row instead
120121 /// of racing a unique index into a 500. Grading before the due date, or
121122 /// 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.
122139 pub async fn grade(
123140 homework: &HomeworkId,
124141 user: &UserId,
@@ -127,8 +144,10 @@ impl HomeworkResult {
127144 graded_by: &UserId,
128145 db: &Database,
129146 ) -> Result<HomeworkResult, AppError> {
147+ let id = HomeworkResultId::composite(homework, user);
148+ let submission = HomeworkSubmissionId::composite(homework, user);
130149 let result = HomeworkResult {
131- id: HomeworkResultId::composite(homework, user),
150+ id: id.clone(),
132151 homework: homework.clone(),
133152 user: user.clone(),
134153 status,
@@ -136,8 +155,25 @@ impl HomeworkResult {
136155 graded_by: graded_by.clone(),
137156 created_at: Timestamp::now(),
138157 };
139- let saved: Option<HomeworkResult> = db.upsert(result.id.record()).content(result).await?;
140- saved.ok_or_else(|| AppError::Internal("failed to record homework result".into()))
158+ let mut saved = db
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()))
141177 }
142178
143179 /// `user`'s grade for `homework`, if graded.
@@ -186,19 +222,33 @@ impl HomeworkResult {
186222 }
187223
188224 /// 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.
190229 pub async fn remove(
191230 homework: &HomeworkId,
192231 user: &UserId,
193232 db: &Database,
194233 ) -> Result<Option<HomeworkResult>, AppError> {
234+ let id = HomeworkResultId::composite(homework, user);
195235 let mut result = db
196- .query("DELETE homework_result WHERE homework = $hw AND user = $usr RETURN BEFORE")
197- .bind(("hw", homework.record()))
198- .bind(("usr", user.record()))
236+ .query(format!(
237+ "BEGIN TRANSACTION;
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+ ))
199248 .await?
200249 .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())
202252 }
203253 }
204254
src/domain/homework_submission.rsmodified+137 -26
@@ -14,7 +14,10 @@
1414
1515 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
1616
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+};
1821 use crate::database::Database;
1922 use crate::domain::homework::HomeworkId;
2023 use crate::domain::timestamp::Timestamp;
@@ -100,9 +103,10 @@ impl HomeworkSubmission {
100103 self.updated_at
101104 }
102105
103- /// Create or re-stamp `user`'s submission to `homework`. `updated_at` moves
104- /// to now every time; `submitted_at` (readonly, the first-submit stamp) is
105- /// kept on an existing row and set only on a fresh one.
106+ /// Create or re-stamp `user`'s submission to `homework`, unless a grade has
107+ /// frozen it — `None` means frozen, and the caller answers 409. `updated_at`
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.
106110 ///
107111 /// Hand-written rather than `.content()` on purpose: `.content()` re-sends
108112 /// the whole row, so it would carry a `submitted_at`, and any value differing
@@ -110,20 +114,26 @@ impl HomeworkSubmission {
110114 /// `submitted_at = submitted_at ?? $now` expression preserves it inside the
111115 /// one UPSERT statement — race-free without a lock, where a read-then-content
112116 /// 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.
113122 pub async fn upsert(
114123 homework: &HomeworkId,
115124 user: &UserId,
116125 text: Option<SubmissionText>,
117126 db: &Database,
118- ) -> Result<HomeworkSubmission, AppError> {
127+ ) -> Result<Option<HomeworkSubmission>, AppError> {
119128 let id = HomeworkSubmissionId::composite(homework, user);
120129 let now = Timestamp::now();
121130 let text = text.map(|text| text.as_str().to_string());
122131 let mut saved = db
123- .query(
132+ .query(format!(
124133 "UPSERT $id SET homework = $hw, user = $usr, text = $text, \
125- updated_at = $now, submitted_at = submitted_at ?? $now RETURN AFTER",
126- )
134+ updated_at = $now, submitted_at = submitted_at ?? $now \
135+ WHERE {SUBMISSION_OPEN_GUARD} RETURN AFTER"
136+ ))
127137 .bind(("id", id.record()))
128138 .bind(("hw", homework.record()))
129139 .bind(("usr", user.record()))
@@ -131,11 +141,7 @@ impl HomeworkSubmission {
131141 .bind(("now", now))
132142 .await?
133143 .check()?;
134- saved
135- .take::<Vec<HomeworkSubmission>>(0)?
136- .into_iter()
137- .next()
138- .ok_or_else(|| AppError::Internal("failed to save homework submission".into()))
144+ Ok(saved.take::<Vec<HomeworkSubmission>>(0)?.into_iter().next())
139145 }
140146
141147 /// Re-stamp a submission's `updated_at` to now, leaving its text and files
@@ -163,6 +169,20 @@ impl HomeworkSubmission {
163169 .ok_or(AppError::NotFound)
164170 }
165171
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+
166186 /// `user`'s submission to `homework`, if they have one.
167187 pub async fn read_for(
168188 homework: &HomeworkId,
@@ -192,25 +212,27 @@ impl HomeworkSubmission {
192212 /// can't leave a file pointing at a vanished submission. The file *blobs*
193213 /// are the web layer's to unlink: it lists them
194214 /// ([`crate::domain::homework_file::HomeworkFile::list_for_submission`])
195- /// before calling this. The caller has already refused the delete if the
196- /// submission is graded (a result exists).
197- pub async fn delete(self, db: &Database) -> Result<HomeworkSubmission, AppError> {
215+ /// before calling this. `None` means a grade froze the row (the caller
216+ /// answers 409): the submission's own delete carries
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> {
198220 let mut result = db
199- .query(
221+ .query(format!(
200222 "BEGIN TRANSACTION;
201- DELETE homework_file WHERE submission = $sub;
202- DELETE $sub RETURN BEFORE;
203- COMMIT TRANSACTION;",
204- )
223+ LET $gone = (DELETE $sub WHERE {SUBMISSION_OPEN_GUARD} RETURN BEFORE);
224+ IF array::len($gone) > 0 {{ DELETE homework_file WHERE submission = $sub }};
225+ RETURN $gone;
226+ COMMIT TRANSACTION;"
227+ ))
205228 .bind(("sub", self.id.record()))
206229 .await?
207230 .check()?;
208- // BEGIN is slot 0, the file wipe slot 1; the submission's DELETE is slot 2.
209- let deleted: Option<HomeworkSubmission> = result
210- .take::<Vec<HomeworkSubmission>>(2)?
231+ // BEGIN is slot 0, the LET slot 1 and the IF slot 2; the RETURN is slot 3.
232+ Ok(result
233+ .take::<Vec<HomeworkSubmission>>(3)?
211234 .into_iter()
212- .next();
213- deleted.ok_or(AppError::NotFound)
235+ .next())
214236 }
215237 }
216238
@@ -238,11 +260,13 @@ mod tests {
238260 &db,
239261 )
240262 .await
263+ .unwrap()
241264 .unwrap();
242265 // A re-submit lands on the same row: submitted_at (the first hand-in)
243266 // pinned, updated_at moves forward, and the text can be cleared.
244267 let second = HomeworkSubmission::upsert(&homework, &user, None, &db)
245268 .await
269+ .unwrap()
246270 .unwrap();
247271 assert_eq!(first.get_id(), second.get_id());
248272 assert_eq!(first.get_submitted_at(), second.get_submitted_at());
@@ -258,6 +282,92 @@ mod tests {
258282 );
259283 }
260284
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+
261371 #[tokio::test]
262372 async fn touch_moves_updated_at_but_not_submitted_at_or_text() {
263373 let db = crate::database::init_mem().await.unwrap();
@@ -271,6 +381,7 @@ mod tests {
271381 &db,
272382 )
273383 .await
384+ .unwrap()
274385 .unwrap();
275386 // A file add/delete touches the submission: updated_at moves (never
276387 // backwards), while the first-submit stamp and the text stay put.
src/domain/meal_booking.rsmodified+480 -109
@@ -10,21 +10,30 @@
1010 //! auditable against the money it moved. Only `booked` rows count against
1111 //! the menu's capacity, which is what makes the seat genuinely free again —
1212 //! and re-booking is the same UPSERT flipping it back.
13-//! - **The capacity check runs under [`MENU_LOCK`]**, the lock that already
14-//! serializes everything counting rows against one menu. Count-then-write is
15-//! write-skew: SurrealDB's transactions do not conflict-check a cross-record
16-//! count against a concurrent insert, so an unlocked check over-admits.
17-//! - **The seat and its money move together, inside that lock.** Booking
18-//! charges and cancelling reverses right here, not in the web layer after the
19-//! lock was dropped — a seam between the two let concurrent `POST`s bill one
20-//! seat twice. The lock stays a *leaf*: nothing below it takes another.
13+//! - **Capacity is the menu's `seats_booked` counter**, claimed by a
14+//! conditional single-record write ([`cap`]). Counting the rows instead is
15+//! write-skew — SurrealDB does not conflict-check a cross-record count
16+//! against a concurrent insert — and a process-wide lock around that count
17+//! only holds inside one replica, which the school no longer runs one of.
18+//! Cancelling gives the seat back in the *same transaction* as the flip.
19+//! - **The price is claimed, not just read.** The seat is taken at the menu
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.
2127
2228 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2329
24-use crate::constant::MEAL_BOOKING_TABLE;
25-use crate::database::Database;
30+use crate::constant::{
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};
2635 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};
2837 use crate::domain::page::PagedList;
2938 use crate::domain::settings::{MealSlotDef, Settings};
3039 use crate::domain::timestamp::Timestamp;
@@ -140,24 +149,23 @@ impl MealBooking {
140149 }
141150
142151 /// 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,
144- /// as a fresh attempt at the current `price`. When the menu carries a
145- /// capacity, a full one refuses new seats (409) — the whole
146- /// check-then-write runs under [`MENU_LOCK`], and the cap is re-derived
147- /// from a fresh menu read inside it, since neither the transaction model
148- /// nor a caller-supplied menu survives a concurrent capacity PATCH.
152+ /// booked is returned as-is, claiming nothing; a cancelled row is revived as
153+ /// a fresh attempt at the current price. A full menu refuses the seat (409),
154+ /// decided by the counter's own `WHERE` rather than by a count this process
155+ /// took a moment ago.
149156 ///
150- /// The price is snapshotted **inside that same lock**, not handed in by the
151- /// web layer: dish writes take the lock too, so the sum frozen onto the row
152- /// is the menu as it stood the instant the seat was taken. Snapshotted
153- /// outside it, a dish landing in the gap was stored as `None` = "was free
154- /// then" — and no repeat `POST` ever heals that, since a held seat is
155- /// returned as-is.
157+ /// The price is read from the menu and then **claimed with it**: the seat is
158+ /// only taken while the menu still stands at the revision the price was read
159+ /// at, so a dish added, re-priced or removed in that gap loses the claim and
160+ /// the whole decision is made again on fresh figures. What is frozen onto
161+ /// the row is therefore always a price the menu genuinely carried at the
162+ /// instant the seat was taken — the guarantee a lock could only give inside
163+ /// one replica.
156164 ///
157- /// The charge is appended inside the lock too, keyed by (seat, attempt):
158- /// eight concurrent `POST`s of one seat hold one seat and write one charge
159- /// line. The price is `None` when the menu is free, and that `None` is
160- /// stored, so a dish added later never bills a seat retroactively.
165+ /// The charge is appended after, keyed by (seat, attempt): eight concurrent
166+ /// `POST`s of one seat hold one seat and write one charge line. The price is
167+ /// `None` when the menu is free, and that `None` is stored, so a dish added
168+ /// later never bills a seat retroactively.
161169 ///
162170 /// `cutoff` is the school's one meal deadline (see [`MealCutoff`]): once
163171 /// serving time is that close, the seat is fixed either way.
@@ -168,60 +176,167 @@ impl MealBooking {
168176 cutoff: &MealCutoff,
169177 db: &Database,
170178 ) -> 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?;
178179 let id = MealBookingId::composite(menu, student);
179- let existing: Option<MealBooking> = db.select(id.record()).await?;
180- let booking = match existing {
180+ let seats = menu.record();
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?;
181189 // The seat is already held: same attempt, same price it was taken
182- // at. Today's menu price bills nobody who booked yesterday's.
183- Some(held) if held.status == MealBookingStatus::Booked => held,
184- existing => {
185- if let Some(capacity) = fresh.get_capacity()
186- && Self::list_live_for_menu(menu, db).await?.len() as i64 >= capacity
187- {
188- return Err(AppError::Conflict("the menu is fully booked"));
189- }
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()))?
190+ // at. Today's menu price bills nobody who booked yesterday's. No
191+ // seat is claimed, so a double-click cannot count two.
192+ if let Some(held) = existing
193+ .clone()
194+ .filter(|row| row.status == MealBookingStatus::Booked)
195+ {
196+ MealLedger::charge_booking(&held, booked_by, db).await?;
197+ return Ok(held);
210198 }
211- };
212- // Writes nothing when this attempt is already billed, so the repeat
213- // POST above costs nothing and a charge that failed once self-heals.
214- MealLedger::charge_booking(&booking, booked_by, db).await?;
215- Ok(booking)
199+ let fresh_row = MealBooking {
200+ id: id.clone(),
201+ menu: menu.clone(),
202+ student: student.clone(),
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+ ))
216331 }
217332
218333 /// Free the seat: flip to `cancelled`, stamp the moment, **and give the
219334 /// money back**. Refused (409) only once the cutoff has passed.
220335 ///
221- /// Under [`MENU_LOCK`] like [`Self::book`], and the row is re-read inside
222- /// it: the caller's copy may predate a concurrent re-book, and cancelling a
223- /// stale attempt would strand that attempt's charge forever. The reversal
224- /// is keyed to the attempt, so a retried cancel refunds exactly once.
336+ /// The row is re-read here and the flip is conditional on it still being
337+ /// `booked`: the caller's copy may predate a concurrent re-book, and
338+ /// cancelling a stale attempt would strand that attempt's charge forever.
339+ /// The reversal is keyed to the attempt, so a retried cancel refunds once.
225340 ///
226341 /// **Idempotent, and that is what makes the refund recoverable.** The flip
227342 /// and the reversal are two writes; a handler future dropped between them
@@ -239,7 +354,6 @@ impl MealBooking {
239354 recorded_by: &UserId,
240355 db: &Database,
241356 ) -> Result<MealBooking, AppError> {
242- let _guard = MENU_LOCK.lock().await;
243357 let fresh = Self::read(&self.id, db).await?.ok_or(AppError::NotFound)?;
244358 if fresh.status == MealBookingStatus::Cancelled {
245359 MealLedger::reverse_booking(&fresh, recorded_by, db).await?;
@@ -249,19 +363,62 @@ impl MealBooking {
249363 .await?
250364 .ok_or(AppError::NotFound)?;
251365 check_cutoff(menu.get_date(), menu.get_slot(), cutoff)?;
252- let cancelled = MealBooking {
253- status: MealBookingStatus::Cancelled,
254- cancelled_at: Some(Timestamp::now()),
255- ..fresh
366+ // Lost the flip to a concurrent cancel: its row is the truth, and the
367+ // reversal replay below heals whatever it left unfinished.
368+ let saved = match Self::release_seat(&fresh, db).await? {
369+ Some(cancelled) => cancelled,
370+ None => Self::read(&self.id, db).await?.ok_or(AppError::NotFound)?,
256371 };
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()))?;
261372 MealLedger::reverse_booking(&saved, recorded_by, db).await?;
262373 Ok(saved)
263374 }
264375
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+
265422 pub async fn read(id: &MealBookingId, db: &Database) -> Result<Option<MealBooking>, AppError> {
266423 Ok(db.select(id.record()).await?)
267424 }
@@ -282,33 +439,6 @@ impl MealBooking {
282439 .await
283440 }
284441
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-
312442 /// Every seat held for one of `students`, newest first — a caller's own
313443 /// list is themselves plus whoever they hold a *live* parent link to.
314444 ///
@@ -411,6 +541,7 @@ mod tests {
411541 use surrealdb::types::Value;
412542
413543 use super::*;
544+ use crate::domain::menu_dish::{DishName, DishPrice, DishTags, MenuDish};
414545
415546 /// The `status` column is `TYPE string`: an object-wrapped enum would be
416547 /// rejected on write, and the `status = 'booked'` capacity count would
@@ -424,6 +555,246 @@ mod tests {
424555 }
425556 }
426557
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+
427798 fn cutoff(minutes: Option<i64>, serving_minute: Option<i64>) -> MealCutoff {
428799 MealCutoff {
429800 minutes,
src/domain/meal_ledger.rsmodified+25 -11
@@ -46,9 +46,10 @@ use surrealdb::types::{AlreadyExistsError, RecordId, RecordIdKey, SurrealValue};
4646 use ulid::Generator;
4747
4848 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,
5051 };
51-use crate::database::Database;
52+use crate::database::{Database, lost_the_race};
5253 use crate::domain::meal_booking::{MealBooking, MealBookingId};
5354 use crate::domain::menu::MenuId;
5455 use crate::domain::menu_dish::MenuDish;
@@ -277,17 +278,31 @@ impl MealLedger {
277278 /// guarantee is `CREATE`'s own: on an existing id it *errors* and leaves
278279 /// the row untouched, so the writer that lost the race reads back the
279280 /// 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.
280288 async fn append(row: MealLedger, db: &Database) -> Result<MealLedger, AppError> {
281289 if let Some(existing) = Self::read(&row.id, db).await? {
282290 return Ok(existing);
283291 }
284292 let id = row.id.clone();
285- let created: Option<MealLedger> = match db.create(id.record()).content(row).await {
286- Ok(created) => created,
287- Err(e) if is_duplicate_record(&e) => Self::read(&id, db).await?,
288- Err(e) => return Err(e.into()),
289- };
290- created.ok_or_else(|| AppError::Internal("failed to write the ledger line".into()))
293+ for _ in 0..CAS_UPDATE_RETRIES {
294+ match db.create(id.record()).content(row.clone()).await {
295+ Ok(Some(created)) => return Ok(created),
296+ Ok(None) => break,
297+ Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => {
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()))
291306 }
292307
293308 pub async fn read(id: &MealLedgerId, db: &Database) -> Result<Option<MealLedger>, AppError> {
@@ -322,9 +337,8 @@ impl MealLedger {
322337 /// The price comes off the *booking row*, never off the menu as it stands
323338 /// now: a seat taken while the menu was free carries `None` forever, so
324339 /// "was free" is a recorded fact and a later dish never bills a seat
325- /// retroactively. Called under
326- /// [`MENU_LOCK`](crate::domain::menu::MENU_LOCK), from
327- /// [`MealBooking::book`] alone, so the seat and its money move together.
340+ /// retroactively. Called from [`MealBooking::book`] alone, right after the seat
341+ /// was claimed, so the seat and its money move together.
328342 ///
329343 /// Replaying it is free: the id is `(booking, attempt)`, so a duplicate
330344 /// `POST` writes nothing, and an attempt whose charge failed the first time
src/domain/menu.rsmodified+123 -55
@@ -10,14 +10,14 @@
1010 //! - **`slot` is a snapshot**, not a link into settings. Retiring a slot must
1111 //! never rewrite a menu already published under it.
1212
13-use std::sync::LazyLock;
14-
1513 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
1614 use tokio::sync::Mutex;
17-use ulid::Generator;
1815
19-use crate::constant::{MAX_MENU_CAPACITY, MENU_TABLE};
20-use crate::database::Database;
16+use crate::constant::{
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;
2121 use crate::domain::field_update::FieldUpdate;
2222 use crate::domain::menu_dish::MenuDish;
2323 use crate::domain::page::PagedList;
@@ -26,38 +26,46 @@ use crate::domain::timestamp::Timestamp;
2626 use crate::domain::user::UserId;
2727 use crate::error::{AppError, ValidationError};
2828
29-/// Serializes "is there already a menu for this day and slot?" against the
30-/// publish it authorizes — a count-then-write pair SurrealDB does not
31-/// conflict-check, so the UNIQUE index would otherwise be the only thing
32-/// standing between two racing publishes and a 500. Also held by the settings
33-/// slot-removal guard, whose check ("was any menu published for this slot?")
34-/// is the mirror image.
29+/// Serializes what is left that counts rows against one menu: the dish cap
30+/// (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB does not
31+/// conflict-check). Publishing no longer needs it — the day+slot *is* the
32+/// record id — and neither does a booking, a menu delete, or the settings
33+/// slot-removal guard: those went to conditional single-record writes
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.
3540 ///
36-/// Lock order: `EXAM_LOCK` (taken by the same settings write) is always taken
37-/// *before* this one; nothing here ever takes `EXAM_LOCK`, so the two cannot
38-/// deadlock.
41+/// A leaf: nothing held under it takes another lock.
3942 pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(());
4043
41-/// Mints menu ids in write order — `Ulid::new()`'s random low bits sort
42-/// arbitrarily within one millisecond, which would scramble the `id` tie-break
43-/// of the listings below.
44-static IDS: LazyLock<std::sync::Mutex<Generator>> =
45- LazyLock::new(|| std::sync::Mutex::new(Generator::new()));
44+/// The reference counter for one meal slot — how many menus are published under
45+/// that name, and whether the school has retired it (see
46+/// [`crate::domain::cap`]). The mirror of
47+/// [`kind_ref`](crate::domain::exam_result::kind_ref) for exam kinds: the slot
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+}
4653
4754 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
4855 pub struct MenuId(RecordId);
4956
5057 impl MenuId {
51- pub fn generate() -> Self {
52- let mut ids = IDS.lock().expect("menu id generator poisoned");
53- // The only error is exhausting the random bits within one millisecond
54- // (2^80 ids deep); it clears itself as the clock ticks, so retry.
55- let ulid = loop {
56- if let Ok(ulid) = ids.generate() {
57- break ulid;
58- }
59- };
60- Self(RecordId::new(MENU_TABLE, ulid.to_string()))
58+ /// The one id a menu for this day and slot can have. Deterministic on
59+ /// purpose (the `EnrollmentId` trick): two replicas publishing the same
60+ /// meal race on a single record instead of writing two rows, so the loser
61+ /// is told "already exists" by the store and answered the same 409 the
62+ /// pre-check gives. `date` is fixed-width `YYYY-MM-DD`, so the `_` joiner
63+ /// cannot be read two ways however the school spells its slots.
64+ pub fn for_slot(date: &MenuDate, slot: &MenuSlot) -> Self {
65+ Self(RecordId::new(
66+ MENU_TABLE,
67+ format!("{}_{}", date.as_str(), slot.as_str()),
68+ ))
6169 }
6270
6371 pub fn from_key(key: &str) -> Self {
@@ -156,6 +164,12 @@ pub struct Menu {
156164 date: MenuDate,
157165 slot: MenuSlot,
158166 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>,
159173 created_by: UserId,
160174 created_at: Timestamp,
161175 }
@@ -177,6 +191,13 @@ impl Menu {
177191 self.capacity
178192 }
179193
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+
180201 pub fn get_created_by(&self) -> &UserId {
181202 &self.created_by
182203 }
@@ -185,9 +206,14 @@ impl Menu {
185206 self.created_at
186207 }
187208
188- /// Publish a menu. Refused (409) when the day+slot already carries one —
189- /// re-checked under [`MENU_LOCK`], so two racing publishes cannot both find
190- /// the day free and trip the UNIQUE index into a 500.
209+ /// Publish a menu. Refused (409) when the day+slot already carries one.
210+ ///
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.
191217 pub async fn create(
192218 date: MenuDate,
193219 slot: MenuSlot,
@@ -195,22 +221,44 @@ impl Menu {
195221 created_by: &UserId,
196222 db: &Database,
197223 ) -> 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");
199225 if Self::find(&date, &slot, db).await?.is_some() {
200- return Err(AppError::Conflict(
201- "a menu is already published for that date and slot",
202- ));
226+ return Err(taken);
227+ }
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+ )));
203238 }
204239 let menu = Menu {
205- id: MenuId::generate(),
240+ id: MenuId::for_slot(&date, &slot),
206241 date,
207242 slot,
208243 capacity,
244+ version: Some(0),
209245 created_by: created_by.clone(),
210246 created_at: Timestamp::now(),
211247 };
212- let created: Option<Menu> = db.create(menu.id.record()).content(menu).await?;
213- created.ok_or_else(|| AppError::Internal("failed to publish the menu".into()))
248+ match db.create(menu.id.record()).content(menu).await {
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+ }
214262 }
215263
216264 pub async fn read(id: &MenuId, db: &Database) -> Result<Option<Menu>, AppError> {
@@ -255,37 +303,57 @@ impl Menu {
255303 /// Only `capacity` is writable: `date` and `slot` are `READONLY` columns,
256304 /// because moving a published menu to another day is a different menu.
257305 /// `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.
258310 pub async fn update(
259311 self,
260312 capacity: Option<Option<i64>>,
261313 db: &Database,
262314 ) -> Result<Menu, AppError> {
315+ if capacity.is_some() {
316+ cap::bump(&self.id.record(), MENU_VERSION_FIELD, db).await?;
317+ }
263318 FieldUpdate::new(self.id.record())
264319 .set("capacity", capacity)
265320 .run::<Menu>(db)
266321 .await
267322 }
268323
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-
283324 /// Delete the menu and the dishes on it — a dish has no meaning without
284325 /// 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.
285336 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+ };
286351 MenuDish::delete_for_menu(&self.id, db).await?;
287- let deleted: Option<Menu> = db.delete(self.id.record()).await?;
288- deleted.ok_or(AppError::NotFound)
352+ // The slot gets its reference back — a slot no menu is published for
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)
289357 }
290358 }
291359
src/domain/menu_dish.rsmodified+55 -3
@@ -12,9 +12,10 @@ use ulid::Generator;
1212
1313 use crate::constant::{
1414 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,
1616 };
1717 use crate::database::Database;
18+use crate::domain::cap;
1819 use crate::domain::field_update::FieldUpdate;
1920 use crate::domain::menu::MenuId;
2021 use crate::domain::timestamp::Timestamp;
@@ -185,6 +186,7 @@ impl MenuDish {
185186 self.created_at
186187 }
187188
189+ /// Add a dish. Moves the menu's revision *first* — see [`Self::bump_menu`].
188190 pub async fn create(
189191 menu: &MenuId,
190192 name: DishName,
@@ -202,8 +204,43 @@ impl MenuDish {
202204 tags,
203205 created_at: Timestamp::now(),
204206 };
205- let created: Option<MenuDish> = db.create(dish.id.record()).content(dish).await?;
206- created.ok_or_else(|| AppError::Internal("failed to add the dish".into()))
207+ // The revision bump and the insert are one transaction, and the bump is
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()))
207244 }
208245
209246 pub async fn read(id: &MenuDishId, db: &Database) -> Result<Option<MenuDish>, AppError> {
@@ -240,6 +277,19 @@ impl MenuDish {
240277 Ok(Self::list_for_menu(menu, db).await?.len())
241278 }
242279
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+
243293 /// Write only the fields the PATCH carried. `description` is nullable, so
244294 /// it takes the three-way shape: absent = keep, `Some(None)` = clear.
245295 pub async fn update(
@@ -250,6 +300,7 @@ impl MenuDish {
250300 tags: Option<DishTags>,
251301 db: &Database,
252302 ) -> Result<MenuDish, AppError> {
303+ Self::bump_menu(&self.menu, db).await?;
253304 FieldUpdate::new(self.id.record())
254305 .set("name", name)
255306 .set("description", description)
@@ -260,6 +311,7 @@ impl MenuDish {
260311 }
261312
262313 pub async fn delete(self, db: &Database) -> Result<MenuDish, AppError> {
314+ Self::bump_menu(&self.menu, db).await?;
263315 let deleted: Option<MenuDish> = db.delete(self.id.record()).await?;
264316 deleted.ok_or(AppError::NotFound)
265317 }
src/domain/registration.rsmodified+25 -34
@@ -1,7 +1,7 @@
11 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
22
33 use crate::constant::{REGISTRATION_COUNT_FIELD, REGISTRATION_TABLE};
4-use crate::database::{Database, lost_the_race};
4+use crate::database::Database;
55 use crate::domain::cap;
66 use crate::domain::event::{Event, EventId};
77 use crate::domain::user::UserId;
@@ -83,45 +83,36 @@ impl Registration {
8383 .await?
8484 .ok_or(AppError::NotFound)?
8585 .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- }
9786 let registration = Registration {
9887 id: RegistrationId::composite(event, user),
9988 event: event.clone(),
10089 user: user.clone(),
10190 registered_by: registered_by.clone(),
10291 };
103- let created: Result<Option<Registration>, _> = db
104- .create(registration.id.record())
105- .content(registration)
106- .await;
107- match created {
108- Ok(Some(created)) => Ok(created),
109- Ok(None) => {
110- cap::release(&seats, REGISTRATION_COUNT_FIELD, db).await?;
111- Err(AppError::Internal("failed to register user".into()))
112- }
113- // A concurrent placement of the same pair got there first: give the
114- // seat back and hand its row over, the same no-op the early return
115- // above would have made.
116- Err(err) => {
117- cap::release(&seats, REGISTRATION_COUNT_FIELD, db).await?;
118- if !lost_the_race(&err) {
119- return Err(err.into());
120- }
121- Self::read_for_user(event, user, db)
122- .await?
123- .ok_or_else(|| AppError::Internal("failed to register user".into()))
124- }
92+ match cap::claim_and_create(
93+ &event.record(),
94+ REGISTRATION_COUNT_FIELD,
95+ capacity.unwrap_or(cap::UNLIMITED),
96+ &registration.id.record(),
97+ &registration,
98+ db,
99+ )
100+ .await?
101+ {
102+ cap::Claimed::Made(created) => Ok(created),
103+ // A concurrent placement of the same pair got there first: hand its
104+ // row over, the same no-op the early return above would have made,
105+ // and with no seat spent either way.
106+ cap::Claimed::Duplicate => Self::read_for_user(event, user, db)
107+ .await?
108+ .ok_or_else(|| AppError::Internal("failed to register user".into())),
109+ // Full, or the event was deleted between the read and the claim —
110+ // the conditional write matches nothing either way, and only this
111+ // path pays for the read that tells them apart.
112+ cap::Claimed::Full => match Event::read(event, db).await? {
113+ Some(_) => Err(AppError::Conflict("the event is full")),
114+ None => Err(AppError::NotFound),
115+ },
125116 }
126117 }
127118
src/domain/subject.rsmodified+52 -8
@@ -166,23 +166,67 @@ impl Subject {
166166 /// pointing at a subject that no longer exists.
167167 ///
168168 /// Exam questions and homework are *not* cascaded: their `subject` is a
169- /// required field the web layer refuses to orphan (both still block the
170- /// delete with a 409). The bank's is optional metadata, and blocking on it
171- /// was a dead end — only the template's owner may re-tag it, so a manager
172- /// could never clear their own 409, and a private template raising it
173- /// leaked its existence.
169+ /// required field that may not be orphaned, so either one still refuses the
170+ /// delete with a 409. That refusal is the delete's own `WHERE`, read off the
171+ /// two reference counters this row carries
172+ /// ([`crate::constant::SUBJECT_QUESTION_COUNT_FIELD`] and its homework
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.
174187 pub async fn delete(self, db: &Database) -> Result<Subject, AppError> {
175188 let mut result = db
176189 .query(
177190 "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+ };
178200 UPDATE bank_question SET subject = NONE WHERE subject = $sub;
179- LET $before = (DELETE $sub RETURN BEFORE);
180201 RETURN $before;
181202 COMMIT TRANSACTION;",
182203 )
183204 .bind(("sub", self.id.record()))
184- .await?
185- .check()?;
205+ .await?;
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+ }
186230 // Read through the trailing `RETURN`, not a counted slot — see
187231 // [`crate::domain::exam::Exam::delete`].
188232 let slot = result.num_statements().saturating_sub(2);
src/domain/term.rsmodified+25 -33
@@ -7,10 +7,9 @@
77 //! rule that guards exams/lessons/events deliberately does not apply here.
88
99 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
10-use tokio::sync::Mutex;
1110 use ulid::Ulid;
1211
13-use crate::constant::{MAX_TERM_NAME_LEN, TERM_TABLE};
12+use crate::constant::{COURSE_COUNT_FIELD, MAX_TERM_NAME_LEN, TERM_TABLE};
1413 use crate::database::Database;
1514 use crate::domain::field_update::FieldUpdate;
1615 use crate::domain::page::PagedList;
@@ -18,24 +17,6 @@ use crate::domain::timestamp::{Timestamp, range_error};
1817 use crate::error::{AppError, ValidationError};
1918 use crate::validate::validate_required;
2019
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-
3920 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
4021 pub struct TermId(RecordId);
4122
@@ -152,22 +133,33 @@ impl Term {
152133 .await
153134 }
154135
155- /// True iff any course still links to this term — the delete guard.
156- pub async fn any_course(id: &TermId, db: &Database) -> Result<bool, AppError> {
136+ /// Delete the term, but only while no course links it — nothing here
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> {
157147 let mut result = db
158- .query("SELECT VALUE id FROM course WHERE term = $term LIMIT 1")
159- .bind(("term", id.record()))
148+ .query(format!(
149+ "DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE"
150+ ))
151+ .bind(("term", self.id.record()))
160152 .await?
161153 .check()?;
162- Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
163- }
164-
165- /// Delete the term. Callers must refuse while [`Term::any_course`] holds —
166- /// nothing here unlinks or cascades, so a term is only ever dropped once no
167- /// course points at it.
168- pub async fn delete(self, db: &Database) -> Result<Term, AppError> {
169- let deleted: Option<Term> = db.delete(self.id.record()).await?;
170- deleted.ok_or(AppError::NotFound)
154+ if !result.take::<Vec<Term>>(0)?.is_empty() {
155+ return Ok(true);
156+ }
157+ // Still linked or already gone: the one statement cannot tell those
158+ // apart, and only the refusal path pays for the read that can.
159+ match Self::read(&self.id, db).await? {
160+ Some(_) => Ok(false),
161+ None => Err(AppError::NotFound),
162+ }
171163 }
172164 }
173165
src/migration_sql.rsmodified+133 -3
@@ -180,6 +180,9 @@ pub const MIGRATION: &str = "
180180 DEFINE FIELD IF NOT EXISTS name ON term TYPE string;
181181 DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int;
182182 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>;
183186
184187 DEFINE TABLE IF NOT EXISTS course SCHEMAFULL;
185188 DEFINE FIELD IF NOT EXISTS creator ON course TYPE record<user>;
@@ -196,6 +199,11 @@ pub const MIGRATION: &str = "
196199 DEFINE FIELD IF NOT EXISTS course ON subject TYPE record<course>;
197200 DEFINE FIELD IF NOT EXISTS name ON subject TYPE string;
198201 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>;
199207 DEFINE INDEX IF NOT EXISTS subject_course ON subject FIELDS course;
200208
201209 DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL;
@@ -258,6 +266,10 @@ pub const MIGRATION: &str = "
258266 DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true;
259267 DEFINE FIELD IF NOT EXISTS allow_review ON exam TYPE bool DEFAULT false;
260268 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>;
261273 DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course;
262274
263275 DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL;
@@ -469,6 +481,13 @@ pub const MIGRATION: &str = "
469481 DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY;
470482 DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int;
471483 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>>;
472491 DEFINE INDEX IF NOT EXISTS homework_submission_homework ON homework_submission FIELDS homework;
473492
474493 DEFINE TABLE IF NOT EXISTS homework_file SCHEMAFULL;
@@ -493,14 +512,17 @@ pub const MIGRATION: &str = "
493512 -- slots, a student or parent books one. `series` groups the occurrences a
494513 -- weekly repeat expanded into, so one cancel deletes one row and a series
495514 -- delete finds the rest. A booking's live/dead state is the `status`
496- -- string; occupancy is derived from it under the appointment lock rather
497- -- than stored, so a rejected or cancelled booking frees its slot again.
515+ -- string; `occupied` is the cap-1 counter that says whether the slot is
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.
498519 -- 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.
500521 DEFINE TABLE IF NOT EXISTS appointment_slot SCHEMAFULL;
501522 DEFINE FIELD IF NOT EXISTS teacher ON appointment_slot TYPE record<user>;
502523 DEFINE FIELD IF NOT EXISTS starts_at ON appointment_slot TYPE int;
503524 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>;
504526 DEFINE FIELD IF NOT EXISTS note ON appointment_slot TYPE option<string>;
505527 DEFINE FIELD IF NOT EXISTS series ON appointment_slot TYPE option<string>;
506528 DEFINE FIELD IF NOT EXISTS created_at ON appointment_slot TYPE int;
@@ -536,6 +558,13 @@ pub const MIGRATION: &str = "
536558 DEFINE FIELD IF NOT EXISTS date ON menu TYPE string READONLY;
537559 DEFINE FIELD IF NOT EXISTS slot ON menu TYPE string READONLY;
538560 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>;
539568 DEFINE FIELD IF NOT EXISTS created_by ON menu TYPE record<user> READONLY;
540569 DEFINE FIELD IF NOT EXISTS created_at ON menu TYPE int READONLY;
541570 DEFINE INDEX IF NOT EXISTS menu_date_slot ON menu FIELDS date, slot UNIQUE;
@@ -600,6 +629,21 @@ pub const MIGRATION: &str = "
600629 DEFINE FIELD IF NOT EXISTS recorded_by ON meal_ledger TYPE record<user> READONLY;
601630 DEFINE FIELD IF NOT EXISTS created_at ON meal_ledger TYPE int READONLY;
602631 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>;
603647 ";
604648
605649 /// Data backfills for rows written by older binaries. Runs *after* (and apart
@@ -742,6 +786,19 @@ pub const BACKFILL: &str = "
742786 UPDATE answer_image SET seq = 1 WHERE seq = NONE;
743787 UPDATE exam_result SET seq = 1 WHERE seq = NONE;
744788
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+
745802 -- Count caps became cross-replica (2026-07-27): the authority moved from a
746803 -- process-wide mutex to a counter column on the parent row, so every parent
747804 -- that predates the column is seeded from the children it actually has.
@@ -756,6 +813,14 @@ pub const BACKFILL: &str = "
756813 };
757814 UPDATE course SET enrollment_count = 0 WHERE enrollment_count = NONE;
758815
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+
759824 FOR $row IN ((SELECT event, count() AS n FROM registration GROUP BY event) ?? []) {
760825 UPDATE $row.event SET registration_count = $row.n WHERE registration_count = NONE;
761826 };
@@ -775,6 +840,71 @@ pub const BACKFILL: &str = "
775840 UPDATE $row.user_id SET chatbot_thread_count = $row.n WHERE chatbot_thread_count = NONE;
776841 };
777842 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+ };
778908 ";
779909
780910 /// 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::{
4545 remove_blob, serve_inline_blob, set_or_clear, store_blob,
4646 };
4747
48-/// Serializes bank writes that adopt a `subject` against a concurrent subject
49-/// delete — the one invariant left here, and a **replica-local** one: it orders
50-/// requests inside one process, and there are two. Every lease is now a
51-/// *reader* lease taken across a subject-exists check and the write that adopts
52-/// it: bank create, bank update, and save-to-bank. (Update used to take the
53-/// writer lease for its read-modify-write; that is a compare-and-set on the row
54-/// itself now, which holds across replicas.) The subject delete takes the writer
55-/// lease across the cascade that clears `subject` off every template, so a
56-/// template can't land on a subject that vanished mid-flight (it would outlive
57-/// the sweep) — the bank twin of the
58-/// [`super::exams::EXAM_LOCK`]/[`super::homework::HOMEWORK_LOCK`] guards.
59-/// Save-to-bank (`question_to_bank`) takes the same reader lease across its
60-/// question read and insert: the source question can be re-tagged/deleted, so
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(());
48+// There is no `BANK_LOCK` any more. It served exactly one pairing — a
49+// subject-exists check here against the subject delete's cascade that clears
50+// `subject` off every template — and that delete no longer takes any lock: it
51+// is a conditional statement on the subject's own reference counters, which
52+// bank templates deliberately do not hold (blocking on them was a dead end; see
53+// [`crate::domain::subject::Subject::delete`]). With the writer gone the three
54+// reader leases guarded nothing, and what they claimed to guard was already
55+// open in production: the lock ordered one process, and the backend runs two.
56+//
57+// The race it leaves is the one the cascade already accepts — a template can
58+// adopt a subject the same instant it is deleted and be left holding a dangling
59+// id. Every read tolerates that: `subject_name` resolves to empty, exactly as
60+// it does for the templates the cascade did clear.
6461
6562 pub fn routes() -> OpenApiRouter<AppState> {
6663 OpenApiRouter::new()
@@ -435,9 +432,6 @@ async fn create_question(
435432 RequireTeacher(user): RequireTeacher,
436433 Json(req): Json<CreateBankQuestion>,
437434 ) -> 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;
441435 // Origin metadata only — no course to check it against, but it must exist.
442436 let subject = subject_must_exist(&req.subject_id, &st.db).await?;
443437 let text = QuestionText::try_new(&req.text)?;
@@ -627,14 +621,6 @@ async fn update_question(
627621 Path(bid): Path<String>,
628622 Json(req): Json<UpdateBankQuestion>,
629623 ) -> 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;
638624 // Read, merge and write again while the row keeps moving underneath: the
639625 // guarded write refuses on a snapshot that has gone stale, so both edits
640626 // land instead of the later one reverting the earlier.
src/web/courses.rsmodified+16 -32
@@ -12,7 +12,7 @@ use crate::database::Database;
1212 use crate::domain::answer_image::AnswerImage;
1313 use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};
1414 use crate::domain::course_session::{CourseSession, SessionTopic};
15-use crate::domain::enrollment::{ENROLL_LOCK, Enrollment};
15+use crate::domain::enrollment::Enrollment;
1616 use crate::domain::exam::{
1717 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule,
1818 ExamTitle,
@@ -23,13 +23,12 @@ use crate::domain::question_image::QuestionImage;
2323 use crate::domain::role::Role;
2424 use crate::domain::settings::Settings;
2525 use crate::domain::subject::{Subject, SubjectDescription, SubjectName};
26-use crate::domain::term::TERM_LOCK;
2726 use crate::domain::timestamp::Timestamp;
2827 use crate::domain::user::{User, UserId};
2928 use crate::error::{AppError, ErrorResponse, ValidationError};
3029 use crate::state::AppState;
3130
32-use super::homework::{HOMEWORK_LOCK, description_or_none, resolve_assigned};
31+use super::homework::{description_or_none, resolve_assigned};
3332 use super::sessions::resolve_session_teacher;
3433 use super::subjects::subject_in_course;
3534 use super::terms::resolve_term;
@@ -274,13 +273,9 @@ async fn create_course(
274273 Some(ref kind) => CourseKind::try_new(kind)?,
275274 None => CourseKind::course(),
276275 };
277- // [`TERM_LOCK`] holds the term lookup and the save together, so the link
278- // can't be written onto a term a concurrent delete just cleared. Only a
279- // write that actually links a term needs it.
280- let _term_guard = match req.term_id {
281- Some(_) => Some(TERM_LOCK.lock().await),
282- None => None,
283- };
276+ // Pre-flight only: [`Course::create`] claims a reference on the term before
277+ // it writes the link, and a term deleted in between fails that claim with
278+ // this very error — so an unknown id reads the same whichever side wins.
284279 let term = resolve_term(req.term_id.as_deref(), &st.db).await?;
285280 check_capacity(req.capacity)?;
286281 let course = Course::create(
@@ -441,12 +436,6 @@ async fn update_course(
441436 .map(CourseDescription::try_new)
442437 .transpose()?;
443438 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- };
450439 // Both columns are nullable, so both stay clearable: omitted is `None`
451440 // (keep), an explicit `null` is `Some(None)` (write `NONE`).
452441 let term = match req.term_id {
@@ -499,21 +488,18 @@ async fn delete_course(
499488 "only the course creator or a manager/admin can delete this course",
500489 ));
501490 }
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- }
511491 // 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.
513495 let image_files = QuestionImage::file_keys_for_course(course.get_id(), &st.db).await?;
514496 let answer_image_files = AnswerImage::file_keys_for_course(course.get_id(), &st.db).await?;
515497 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+ }
517503 for file in image_files
518504 .iter()
519505 .chain(&answer_image_files)
@@ -1048,11 +1034,9 @@ async fn create_homework_in_course(
10481034 };
10491035 let due_at = Timestamp::from_millis(req.due_at);
10501036 check_not_past("due_at", Some(due_at))?;
1051- // Reader lease of [`HOMEWORK_LOCK`], held from the subject check through
1052- // the create: a subject delete (a writer, which checks for homework) can't
1053- // vanish the subject between its validation here and the row landing with
1054- // it.
1055- let _guard = HOMEWORK_LOCK.read().await;
1037+ // No lease: the create takes the subject's reference counter in the same
1038+ // breath as the row, and the subject delete is refused while that counter
1039+ // is non-zero — so the check below is only a pre-flight for the message.
10561040 let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;
10571041 let assigned = resolve_assigned(req.assigned, course.get_id(), &st.db).await?;
10581042 let homework = Homework::create(
src/web/exam_ws.rsmodified+7 -0
@@ -396,6 +396,13 @@ async fn handle_message(
396396 // of [`EXAM_LOCK`] from the gates through the upsert, exactly
397397 // like `save_answer_checked` — and dropped before the socket
398398 // 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.
399406 let guard = EXAM_LOCK.read().await;
400407 // Tracks how far the gates got: only once the sitting resolved can
401408 // 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(
665665 // Reader lease of [`EXAM_LOCK`]: the writable gate and the upsert are
666666 // one unit, or a retake's wipe-and-create (a writer) slips in between
667667 // 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.
668676 let _guard = EXAM_LOCK.read().await;
669677 let attempt = writable_attempt(exam, user, db).await?;
670678 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 {
7878 ///
7979 /// Read side — the answer saves (REST and the exam room), from the
8080 /// writable-attempt gate through the upsert; the grade write (draft gate
81-/// through the result upsert); the exam PATCH, whose mode/re-draft gates count
82-/// attempts and results; and the three question writes that first check a
83-/// subject belongs to the course. These stay concurrent with each other.
81+/// through the result upsert); and the exam PATCH, whose mode/re-draft gates
82+/// count attempts and results. These stay concurrent with each other.
8483 ///
85-/// Write side — attempt starts (the max-attempts count and the retake's answer
86-/// wipe) and the subject delete's cascade. So a save can never land on a sheet
87-/// a retake just wiped, a mark can never land on an exam mid-flight into
88-/// hiding, and a question can never adopt a subject being swept.
84+/// Write side — attempt starts alone (the max-attempts count and the retake's
85+/// answer wipe). So a save can never land on a sheet a retake just wiped, and a
86+/// mark can never land on an exam mid-flight into hiding.
8987 ///
90-/// The question freeze gate is *not* on this list any more: it rides inside
91-/// each question/image write's own transaction
88+/// Two rules have left this list. The question freeze gate rides inside each
89+/// question/image write's own transaction
9290 /// ([`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.
9497 // ponytail: global RwLock, shard per-exam if save latency ever matters.
9598 pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
9699
@@ -162,7 +165,9 @@ struct UpdateExam {
162165 description: Option<String>,
163166 /// The assessment form — one of the school's exam kinds (`GET /settings`).
164167 /// 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.
166171 kind: Option<String>,
167172 /// `sync`, `async`, or `open`. Omit to keep the current mode; send `null`
168173 /// to turn the exam back into an offline-graded one. Frozen once anyone
@@ -385,7 +390,7 @@ async fn get_exam(
385390 (status = 401, description = "Not authenticated", body = ErrorResponse),
386391 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
387392 (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),
389394 ),
390395 )]
391396 async fn update_exam(
@@ -502,6 +507,19 @@ async fn update_exam(
502507 }
503508 }
504509
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+
505523 if let Some(updated) = exam
506524 .update_if_unchanged(
507525 title,
@@ -594,7 +612,7 @@ async fn delete_exam(
594612 (status = 401, description = "Not authenticated", body = ErrorResponse),
595613 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse),
596614 (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),
598616 ),
599617 )]
600618 async fn grade(
@@ -669,7 +687,16 @@ async fn grade(
669687 let seq = ExamAttempt::read_latest_for_user(&exam_id, &target, &st.db)
670688 .await?
671689 .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?;
673700 let people = PersonRef::map_of(&[&target_user, &teacher]);
674701 Ok(Json(ExamResultResponse::new(&result, &people)))
675702 }
@@ -790,7 +817,13 @@ async fn remove_result(
790817 "only the course creator, an assigned teacher, or a manager/admin can remove results",
791818 ));
792819 }
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?;
794827 if removed.is_none() {
795828 return Err(AppError::NotFound);
796829 }
src/web/exams/questions.rsmodified+11 -20
@@ -218,11 +218,10 @@ pub(crate) async fn create_question(
218218 "only the course creator, an assigned teacher, or a manager/admin can author questions",
219219 ));
220220 }
221- // Reader lease of [`EXAM_LOCK`], for the subject check alone: a subject
222- // delete (which takes the writer lease) must not invalidate a subject this
223- // just validated. Replica-local, like every lock here. The freeze gate no
224- // longer needs the lease — it rides inside the insert's own transaction.
225- let _guard = EXAM_LOCK.read().await;
221+ // No lease: the subject check below is only a pre-flight for the message,
222+ // and the insert takes the subject's reference counter in the same breath —
223+ // a subject delete lands either wholly before it (400) or is refused. The
224+ // freeze gate rides inside the insert's own transaction.
226225 ensure_questions_editable(exam.get_id(), &st.db).await?;
227226
228227 let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;
@@ -346,9 +345,8 @@ pub(crate) async fn update_question(
346345 "only the course creator, an assigned teacher, or a manager/admin can edit questions",
347346 ));
348347 }
349- // Reader lease of [`EXAM_LOCK`] for the subject check — see
350- // `create_question`. The freeze gate rides in the update's transaction.
351- let _guard = EXAM_LOCK.read().await;
348+ // No lease — see `create_question`; a re-tag moves the subject's reference
349+ // counter, and the freeze gate rides in the update's transaction.
352350 ensure_questions_editable(exam.get_id(), &st.db).await?;
353351 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
354352
@@ -504,9 +502,8 @@ pub(crate) async fn question_from_bank(
504502 "only the course creator, an assigned teacher, or a manager/admin can author questions",
505503 ));
506504 }
507- // Reader lease of [`EXAM_LOCK`] for the subject check — same reasoning as
508- // `create_question`. The freeze gate rides in the insert's transaction.
509- let _guard = EXAM_LOCK.read().await;
505+ // No lease — same reasoning as `create_question`. The freeze gate rides in
506+ // the insert's transaction.
510507 ensure_questions_editable(exam.get_id(), &st.db).await?;
511508 let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;
512509
@@ -758,12 +755,9 @@ pub(crate) async fn question_to_bank(
758755 "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank",
759756 ));
760757 }
761- // Reader lease of [`BANK_LOCK`] across the question read and the insert: the
762- // template adopts the question's subject, so without it a subject delete
763- // could slip between the two and leave the fresh template pointing at a
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;
758+ // No lease: `BANK_LOCK` is gone with the subject delete's writer lease, and
759+ // a template left holding a deleted subject reads as an empty
760+ // `subject_name` either way (see [`crate::web::bank_questions`]).
767761 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
768762
769763 // `create_from_exam` mints its own id and insert (the funnel), fed the
@@ -825,9 +819,6 @@ pub(crate) async fn question_to_bank(
825819 // template silently vanishing over a metadata write is worse than a
826820 // template with no back-link (the next save re-links it).
827821 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);
831822 // No exam lease around the back-link any more, and none is needed: this is a
832823 // single-column `UPDATE`, and `ExamQuestion::update` no longer re-states
833824 // 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::{
4444
4545 /// Serializes the homework subsystem's cross-record check-then-writes, which
4646 /// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as
47-/// [`crate::web::exams::EXAM_LOCK`]. The class of bug: a submission stays
48-/// editable only *until a result exists*, so the "no grade yet" read and the
49-/// submission write that depends on it must not straddle a concurrent grade,
50-/// and a homework delete must not race a submission landing under it. Read side
51-/// (steps 3/4): the student's submission and file writes, held from the
52-/// ungraded gate through the upsert, concurrent with each other. Write side:
53-/// grade/ungrade (steps 3/4) and the homework-delete cascade here. Lock order,
54-/// where both are taken: `HOMEWORK_LOCK` before the file-cap `Mutex`, never the
55-/// reverse.
47+/// [`crate::web::exams::EXAM_LOCK`]. It is a *within-replica* guard only, so
48+/// the rule it can no longer be trusted with is the freeze: a graded submission
49+/// used to stay unedited because the "no grade yet" read and the write it
50+/// licensed sat under one lease, which two processes never shared. That rule
51+/// moved into the database — grading stamps
52+/// [`crate::constant::SUBMISSION_GRADED_FIELD`] on the submission row and every
53+/// student-side write carries `graded_by_result = NONE` as its own condition.
54+///
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.
5672 // ponytail: global RwLock, shard per-homework if write latency ever matters.
5773 pub(crate) static HOMEWORK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
5874
@@ -299,8 +315,9 @@ async fn update_homework(
299315 // Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the
300316 // live submissions and results, and the row write depends on what it saw —
301317 // 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 lease
303- // also pins the subject re-tag against a concurrent subject delete.
318+ // and the write, orphaned by the narrowing that just missed it. The subject
319+ // re-tag no longer needs it — it moves the two subjects' reference counters
320+ // inside `Homework::update`.
304321 let _guard = HOMEWORK_LOCK.write().await;
305322
306323 // Only what the request carried: an omitted field stays `None` and is never
@@ -609,10 +626,15 @@ async fn submit(
609626 Some(ref text) if !text.is_empty() => Some(SubmissionText::try_new(text)?),
610627 _ => None,
611628 };
612- // Reader lease of HOMEWORK_LOCK, held from the graded gate through the write:
613- // the "no grade yet" read and the upsert that depends on it are one unit, or
614- // a grade landing between them lets an edit slip onto a frozen submission.
629+ // Reader lease of HOMEWORK_LOCK: no longer the freeze (that is the stamp on
630+ // the row, below), but still the interlock against a PATCH re-scoping this
631+ // homework's audience while the submission lands under it.
615632 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.
616638 if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db)
617639 .await?
618640 .is_some()
@@ -621,13 +643,18 @@ async fn submit(
621643 "this homework has been graded — ask the teacher to remove the grade before editing your submission",
622644 ));
623645 }
624- // 201-vs-200: a prior read under the lock is exact, where comparing the
625- // returned stamps would misreport a same-millisecond re-submit as a create.
646+ // 201-vs-200: a prior read is exact, where comparing the returned stamps
647+ // would misreport a same-millisecond re-submit as a create.
626648 let existed = HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db)
627649 .await?
628650 .is_some();
629- let submission =
630- HomeworkSubmission::upsert(homework.get_id(), user.get_id(), text, &st.db).await?;
651+ let Some(submission) =
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+ };
631658 let files = HomeworkFile::list_for_submission(submission.get_id(), &st.db).await?;
632659 let status = if existed {
633660 StatusCode::OK
@@ -705,6 +732,7 @@ async fn delete_submission(
705732 Path(id): Path<String>,
706733 ) -> Result<StatusCode, AppError> {
707734 let homework = gate_own_submission(&id, &user, &st.db).await?;
735+ // Reader lease as in `submit` — the audience interlock, not the freeze.
708736 let _guard = HOMEWORK_LOCK.read().await;
709737 if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db)
710738 .await?
@@ -720,7 +748,13 @@ async fn delete_submission(
720748 // Collect blob names before the cascade (submission.delete wipes the file
721749 // rows in the same transaction), then unlink after the rows are gone.
722750 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+ }
724758 for file in &files {
725759 remove_blob(&st.files_path, file.get_file()).await;
726760 }
@@ -799,29 +833,33 @@ async fn upload_submission_file(
799833 let name = FileName::try_new(&upload.name.unwrap_or_default())?;
800834 let content_type = FileContentType::try_new(&upload.content_type.unwrap_or_default())?;
801835
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).
803842 let _guard = HOMEWORK_LOCK.read().await;
843+ // The common-case gate; the freeze itself rides on the writes below.
804844 if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db)
805845 .await?
806846 .is_some()
807847 {
808- return Err(AppError::Conflict(
809- "this homework has been graded — ask the teacher to remove the grade before adding files",
810- ));
848+ return Err(GRADED);
811849 }
812850 // A submission row must exist to hang the file off; auto-create an empty one
813851 // 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)
815- .await?
816- {
817- Some(existing) => existing,
818- None => HomeworkSubmission::upsert(homework.get_id(), user.get_id(), None, &st.db).await?,
819- };
852+ let submission =
853+ match HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db).await? {
854+ Some(existing) => existing,
855+ None => HomeworkSubmission::upsert(homework.get_id(), user.get_id(), None, &st.db)
856+ .await?
857+ .ok_or(GRADED)?,
858+ };
820859
821860 // 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:
823- // HOMEWORK_LOCK then the cap Mutex, never reversed). Unlink the fresh blob if
824- // the row insert loses the cap race.
861+ // 10-file cap and the freeze are one conditional write on the submission row
862+ // inside `insert`. Unlink the fresh blob if the row insert loses either.
825863 let file = HomeworkFile::new(
826864 submission.get_id(),
827865 name,
@@ -833,10 +871,12 @@ async fn upload_submission_file(
833871 .await
834872 .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?;
835873 let stored = match file.insert(&st.db).await {
836- Ok(stored) => stored,
837- Err(err) => {
874+ Ok(Some(stored)) => stored,
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 => {
838878 let _ = tokio::fs::remove_file(&path).await;
839- return Err(err);
879+ return Err(landed.err().unwrap_or(GRADED));
840880 }
841881 };
842882 // A landed file moves the submission's "last touched" clock (the late flag).
@@ -923,24 +963,29 @@ async fn delete_submission_file(
923963 Path((id, fid)): Path<(String, String)>,
924964 ) -> Result<StatusCode, AppError> {
925965 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.
926970 let _guard = HOMEWORK_LOCK.read().await;
927971 if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db)
928972 .await?
929973 .is_some()
930974 {
931- return Err(AppError::Conflict(
932- "this homework has been graded — ask the teacher to remove the grade before deleting files",
933- ));
975+ return Err(GRADED);
934976 }
935977 let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id());
936978 let file = HomeworkFile::read_for(&HomeworkFileId::from_key(&fid), &submission, &st.db)
937979 .await?
938980 .ok_or(AppError::NotFound)?;
939981 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+ }
941988 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?;
944989 Ok(StatusCode::NO_CONTENT)
945990 }
946991
src/web/meals.rsmodified+17 -23
@@ -242,7 +242,7 @@ async fn one_menu(
242242 (status = 400, description = "Malformed date, unknown slot, or out-of-range capacity", body = ErrorResponse),
243243 (status = 401, description = "Not authenticated", body = ErrorResponse),
244244 (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),
246246 ),
247247 )]
248248 async fn create_menu(
@@ -371,14 +371,8 @@ async fn delete_menu(
371371 let menu = Menu::read(&MenuId::from_key(&id), &st.db)
372372 .await?
373373 .ok_or(AppError::NotFound)?;
374- // [`MENU_LOCK`] holds the seat check and the delete together, so a booking
375- // cannot land on a menu that is already on its way out.
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- }
374+ // The seat check rides in the delete's own `WHERE` (see `Menu::delete`), so
375+ // a booking landing in another replica cannot slip between the two.
382376 menu.delete(&st.db).await?;
383377 Ok(StatusCode::NO_CONTENT)
384378 }
@@ -416,15 +410,15 @@ async fn add_dish(
416410 .flatten();
417411 let price = DishPrice::try_new(req.price_minor)?;
418412 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's
420- // price under it: a dish landing mid-booking would be stored on the seat as
421- // "the menu was free", and a held seat is never re-priced. It also makes
422- // the dish cap a real cap — count-then-write is write-skew otherwise. The
423- // lock stays a leaf: nothing below here takes another.
413+ // Dish writes take [`MENU_LOCK`] for the dish cap alone: count-then-write
414+ // is write-skew, so the count and the insert have to be one step. The
415+ // *price* no longer needs it — a dish write moves the menu's revision, and
416+ // a booking claims its seat at the revision it priced itself against.
417+ // The lock stays a leaf: nothing below here takes another.
424418 let _guard = MENU_LOCK.lock().await;
425- // The menu is read *inside* the lock, like `MealBooking::book` does: read
426- // before it, a `DELETE /menus/{id}` running in the gap takes its cascade
427- // with it and this dish lands on a menu that no longer exists.
419+ // The menu is read *inside* the lock: read before it, a `DELETE /menus/{id}`
420+ // running in the gap takes its cascade with it and this dish lands on a menu
421+ // that no longer exists.
428422 let menu = Menu::read(&MenuId::from_key(&id), &st.db)
429423 .await?
430424 .ok_or(AppError::NotFound)?;
@@ -810,7 +804,7 @@ async fn booking_target(
810804 (status = 401, description = "Not authenticated", body = ErrorResponse),
811805 (status = 403, description = "Not a student booking for themselves, nor a parent booking for a linked student", body = ErrorResponse),
812806 (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),
814808 ),
815809 )]
816810 async fn book_meal(
@@ -822,10 +816,10 @@ async fn book_meal(
822816 let student = booking_target(&user, req.student_id.as_deref(), &st.db).await?;
823817 let cutoff = meal_cutoff(&st.db).await?;
824818 let menu = MenuId::from_key(&id);
825- // Price, seat and charge all land together under `MENU_LOCK`, keyed by
826- // (seat, attempt) — a double-click books one seat and bills it once, and a
827- // dish cannot slip in between the price snapshot and the row it is frozen
828- // onto.
819+ // Price, seat and charge land as one decision (see `MealBooking::book`),
820+ // keyed by (seat, attempt) — a double-click books one seat and bills it
821+ // once, and a dish landing between the price and the seat is refused by the
822+ // claim rather than billed.
829823 let booking = MealBooking::book(&menu, &student, user.get_id(), &cutoff, &st.db).await?;
830824 let items = booking_responses(std::slice::from_ref(&booking), &st.db).await?;
831825 Ok((
@@ -927,7 +921,7 @@ async fn list_menu_bookings(
927921 (status = 401, description = "Not authenticated", body = ErrorResponse),
928922 (status = 403, description = "Not the booking's student, nor their parent", body = ErrorResponse),
929923 (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),
931925 ),
932926 )]
933927 async fn cancel_booking(
src/web/settings.rsmodified+111 -53
@@ -5,14 +5,17 @@ use utoipa::ToSchema;
55 use utoipa_axum::router::OpenApiRouter;
66 use utoipa_axum::routes;
77
8+use surrealdb::types::RecordId;
9+
810 use crate::constant::CAS_UPDATE_RETRIES;
9-use crate::domain::exam_result::ExamResult;
10-use crate::domain::menu::{MENU_LOCK, Menu};
11+use crate::database::Database;
12+use crate::domain::cap;
13+use crate::domain::exam_result::kind_ref;
14+use crate::domain::menu::slot_ref;
1115 use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings};
1216 use crate::error::{AppError, ErrorResponse};
1317 use crate::state::AppState;
1418
15-use super::exams::EXAM_LOCK;
1619 use super::{CurrentUser, RequireManager, set_or_clear};
1720
1821 pub fn routes() -> OpenApiRouter<AppState> {
@@ -231,7 +234,8 @@ async fn get_settings(
231234 /// every exam of that kind. For that reason a kind whose exams already carry
232235 /// marks cannot be dropped from the list (409) — those marks would silently
233236 /// 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` likewise
237+/// 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
235239 /// applies at upload time only — already-stored files keep their size, and the
236240 /// chatbot knobs apply to the next chat request only. `meal_slots` follows the
237241 /// exam-kind rule: a slot a menu was already published for cannot be dropped
@@ -259,21 +263,6 @@ async fn update_settings(
259263 // otherwise a concurrent PATCH of a *different* field would be silently
260264 // reverted by whichever whole-row write lands second. A refused save
261265 // 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- };
277266 for _ in 0..CAS_UPDATE_RETRIES {
278267 let current = Settings::load(&st.db).await?;
279268
@@ -284,26 +273,6 @@ async fn update_settings(
284273 .collect::<Result<Vec<_>, _>>()?,
285274 None => current.get_exam_kinds().to_vec(),
286275 };
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.
307276 let meal_slots = match &req.meal_slots {
308277 Some(slots) => slots
309278 .iter()
@@ -311,18 +280,6 @@ async fn update_settings(
311280 .collect::<Result<Vec<_>, _>>()?,
312281 None => current.get_meal_slots(),
313282 };
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- }
326283 let attendance_statuses = req
327284 .attendance_statuses
328285 .clone()
@@ -334,6 +291,13 @@ async fn update_settings(
334291 .collect::<Result<Vec<_>, _>>()?,
335292 None => current.get_grade_bands().to_vec(),
336293 };
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+
337301 // Merge over the snapshot's resolved values: an omitted field keeps
338302 // whatever the row (or the default behind an unset field) reads as.
339303 let mut params = current.params();
@@ -361,11 +325,105 @@ async fn update_settings(
361325 .unwrap_or(params.meal_cancel_cutoff_minutes);
362326
363327 let settings = Settings::try_new(params)?;
364- if let Some(saved) = settings.save_if_unchanged(&current, &st.db).await? {
365- return Ok(Json(SettingsResponse::new(&saved)));
328+
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+ }
366391 }
367392 }
368393 Err(AppError::Conflict(
369394 "the settings kept changing underneath this update — try again",
370395 ))
371396 }
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;
88
99 use crate::database::Database;
1010 use crate::domain::course::{Course, CourseId};
11-use crate::domain::exam_question::ExamQuestion;
12-use crate::domain::homework::Homework;
1311 use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName};
1412 use crate::error::{AppError, ErrorResponse, ValidationError};
1513 use crate::state::AppState;
1614
17-use super::bank_questions::BANK_LOCK;
1815 use super::courses::{can_manage_course, can_view_course};
19-use super::exams::EXAM_LOCK;
20-use super::homework::HOMEWORK_LOCK;
2116 use super::{CurrentUser, RequireTeacher, SubjectResponse};
2217
2318 pub fn routes() -> OpenApiRouter<AppState> {
@@ -194,35 +189,11 @@ async fn delete_subject(
194189 "only the course creator, an assigned teacher, or a manager/admin can delete this subject",
195190 ));
196191 }
197- // Writer lease of [`EXAM_LOCK`]: the no-questions check and the delete
198- // are one unit, so a question create/update that just validated this
199- // subject can't land its row on a subject that vanished mid-flight.
200- let _guard = EXAM_LOCK.write().await;
201- if ExamQuestion::any_for_subject(subject.get_id(), &st.db).await? {
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;
192+ // No locks: the two checks *are* the delete's `WHERE`, decided against the
193+ // subject's own reference counters inside one statement. This used to be
194+ // three process-wide locks (the only site that held more than one) around
195+ // two cross-table counts, which served one replica and let the other create
196+ // a question on a subject being deleted.
226197 subject.delete(&st.db).await?;
227198 Ok(StatusCode::NO_CONTENT)
228199 }
src/web/terms.rsmodified+2 -6
@@ -7,7 +7,7 @@ use utoipa_axum::router::OpenApiRouter;
77 use utoipa_axum::routes;
88
99 use crate::database::Database;
10-use crate::domain::term::{TERM_LOCK, Term, TermId, TermName};
10+use crate::domain::term::{Term, TermId, TermName};
1111 use crate::domain::timestamp::Timestamp;
1212 use crate::error::{AppError, ErrorResponse, ValidationError};
1313 use crate::state::AppState;
@@ -229,14 +229,10 @@ async fn delete_term(
229229 let term = Term::read(&TermId::from_key(&id), &st.db)
230230 .await?
231231 .ok_or(AppError::NotFound)?;
232- // [`TERM_LOCK`] holds the link check and the delete together, so a course
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? {
232+ if !term.delete(&st.db).await? {
236233 return Err(AppError::Conflict(
237234 "courses are still linked to this term — unlink them first",
238235 ));
239236 }
240- term.delete(&st.db).await?;
241237 Ok(StatusCode::NO_CONTENT)
242238 }
tests/integration.rsmodified+469 -18
@@ -3331,17 +3331,37 @@ async fn kind_weight_edits_reweight_reports_live() {
33313331
33323332 // The PATCH above also retired `project` (allowed — no marks of that kind
33333333 // existed yet; a graded kind can't leave at all, see
3334- // `exam_kind_removal_blocks_while_marks_exist`). Its exam lives on and
3335- // counts with weight 1.
3334+ // `exam_kind_removal_blocks_while_marks_exist`). Its exam lives on, but a
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.
33363351 let res = send(
33373352 &app,
3338- "POST",
3339- &format!("/exams/{project}/results"),
3340- Some(&teacher),
3341- Some(json!({ "mark": 60, "user_id": alice_id })),
3353+ "PATCH",
3354+ "/settings",
3355+ Some(&manager),
3356+ Some(json!({ "exam_kinds": [
3357+ {"name": "quiz", "weight": 1},
3358+ {"name": "oral", "weight": 3},
3359+ {"name": "project", "weight": 1},
3360+ ]})),
33423361 )
33433362 .await;
33443363 assert_eq!(res.status, StatusCode::OK);
3364+ assert_eq!(grade_project().await.status, StatusCode::OK);
33453365 // (40 + 240 + 60) / 5 = 68.
33463366 let report = send(&app, "GET", "/marks/me", Some(&alice), None).await;
33473367 assert_eq!(report.body["courses"][0]["average"], 68.0);
@@ -4175,11 +4195,11 @@ async fn concurrent_enrolls_never_exceed_course_capacity() {
41754195 /// be full forever. Stored state is the only witness: the embedded engine can
41764196 /// tell two racers they both won, so the HTTP statuses prove nothing.
41774197 //
4178-// ponytail: `ENROLL_LOCK` serializes the enrolls inside one process, so what
4179-// this actually drives is the already-enrolled early return; the `CREATE`-loser
4180-// release only runs when the two racers sit on different replicas. Both paths
4181-// are pinned by the same assertion below (counter == roster), which is the part
4182-// that matters.
4198+// Nothing serializes these any more: the seat and the row are claimed in one
4199+// transaction (`cap::claim_and_create`), so a racer that loses the id has its
4200+// own increment rolled back with the transaction and reads the winner's row
4201+// instead of being told the course is full. Both the early return and that
4202+// rollback are pinned by the assertion below (counter == roster).
41834203 #[tokio::test]
41844204 async fn concurrent_enrolls_of_one_pair_claim_one_seat() {
41854205 let (app, db) = app_and_db().await;
@@ -4229,6 +4249,317 @@ async fn concurrent_enrolls_of_one_pair_claim_one_seat() {
42294249 );
42304250 }
42314251
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+
42324563 /// The signup list freezes the moment the event starts — both directions.
42334564 /// (The create-time no-past grace lets a just-started event exist, which is
42344565 /// exactly a closed list.)
@@ -11235,14 +11566,15 @@ async fn settings_round_trip_the_food_program_knobs() {
1123511566 }
1123611567
1123711568 // A published menu pins the slot it snapshotted: dropping it is a 409.
11238- db.query(
11239- "CREATE menu SET date = '2026-07-27', slot = 'lunch',
11240- created_by = (SELECT VALUE id FROM user LIMIT 1)[0], created_at = 0",
11569+ let menu = send(
11570+ &app,
11571+ "POST",
11572+ "/meals/menus",
11573+ Some(&manager),
11574+ Some(json!({ "date": "2026-07-27", "slot": "lunch" })),
1124111575 )
11242- .await
11243- .unwrap()
11244- .check()
11245- .unwrap();
11576+ .await;
11577+ assert_eq!(menu.status, StatusCode::CREATED, "{}", menu.body);
1124611578 let res = send(
1124711579 &app,
1124811580 "PATCH",
@@ -20939,6 +21271,63 @@ async fn concurrent_meal_bookings_never_exceed_the_capacity() {
2093921271 )
2094021272 .await;
2094121273 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");
2094221331 }
2094321332
2094421333 /// 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() {
2218422573 );
2218522574 }
2218622575
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+
2218722638 /// A repeat POST racing the cancel. A cancel that reverses whatever charge it
2218822639 /// can find, off a booking row read before the lock, can flip the seat to
2218922640 /// `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)] = &[
4545 "CAP_WRITE_BACKOFF_MS",
4646 "internal backoff between cap counter retries",
4747 ),
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+ ),
4854 (
4955 "UPLOAD_BODY_OVERHEAD_BYTES",
5056 "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;
1010 use axum::http::StatusCode;
1111 use common::{create_course, create_exam, create_subject, enroll, me_id, send, set_role};
1212 use hezarfen_backend::database::Database;
13+use hezarfen_backend::domain::timestamp::Timestamp;
1314 use hezarfen_backend::rate_limit::RateLimitConfig;
1415 use hezarfen_backend::state::AppState;
1516 use hezarfen_backend::{build_router, database};
@@ -1264,3 +1265,342 @@ async fn cap_counters_are_seeded_from_the_rows_that_predate_them() {
12641265 let up = common::upload_file(&app, &ali, &note, "eleventh.txt", "", b"x").await;
12651266 assert_eq!(up.status, StatusCode::CONFLICT, "{}", up.body);
12661267 }
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+}