diff --git a/README.md b/README.md index ae1aa25..f49e276 100644 --- a/README.md +++ b/README.md @@ -675,9 +675,9 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) · paged | | 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) | | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) | -| 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) | +| 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) | | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) | -| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only; drafts can't be graded, `409`) | +| 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`) | | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged | | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) | | 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. | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies | | GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` — full | | 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` | -| 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") | +| 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") | | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) | | GET | `/terms` | student | List terms, newest first · paged | | GET | `/terms/{id}` | student | Get one term | @@ -790,7 +790,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) | | GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link | | 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 | -| 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 | +| 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 | | 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 | | GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included · paged | | 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. A booking is `pending`, `approved`, `rejected`, or `cancelled`. The first two are **live** and hold the slot; rejecting or cancelling frees it for someone -else immediately (occupancy is counted live, never stored as a flag). The +else immediately (the slot carries an `occupied` counter, taken by a booking +and handed back in the same transaction as the reject or cancel that settles +it, so the guard holds across replicas). The decisions: - `PATCH /{id}/approve` — the slot's teacher (or manager+) confirms. Refused @@ -981,7 +983,7 @@ decisions: simply by rescheduling to a time that works. Refused (`409`) once the meeting's window has started: a meeting that already began is history, not a plan. The guard sits in the - domain's `cancel` itself, under the appointment lock and on a fresh read, so + domain's `cancel` itself, on a fresh read compared-and-set into the row, so every way of cancelling — the decline below included — inherits it. - `PATCH /{id}/reschedule` (`{starts_at, ends_at}`) — the teacher **counter-proposes**. The times land on the *same* row as @@ -1132,7 +1134,12 @@ editable `settings` singleton (`GET /settings` for any signed-in user, re-weights every exam of that kind at once. For the same reason a kind whose exams already carry marks cannot be removed from the list (`409`): those marks would silently re-weight. An unmarked kind leaves freely, and - an exam keeping a since-removed kind counts with weight `1`. + an exam keeping a since-removed kind counts with weight `1` — but it can no + longer be graded (`409`) until the school offers that kind again, which is + what keeps "a marked kind cannot be removed" true from both ends. The same + rule pointed at one exam: an exam that already carries marks keeps its + `kind` (`PATCH /exams/{id}` answers `409`), because re-pointing it would + re-weight those marks just as silently. - **`attendance_statuses`** — what attendance marking accepts. The core four (`present`, `absent`, `late`, `excused`) are mandatory because the 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 otherwise), so two managers patching different fields both land instead of the later write silently reverting the earlier one. Editing a list never rewrites history: an exam keeps its retired kind, a roll-call row keeps its -retired status — only **new writes** are held to the current lists. +retired status — only **new writes** are held to the current lists (which is +why grading an exam whose kind has left the list is refused). 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"). @@ -1698,9 +1706,12 @@ a bank row **never freezes** — its owner can edit or delete it forever. `POST /bank-questions` (teacher+) saves one, stamping the caller as its **owner**. `subject_id` is origin metadata, but it must **exist** — an unknown -subject is a `400` (create and PATCH alike); the reverse guard holds too, so -deleting a subject a template still references is a `409` (same as exam -questions and homework). Reads are school-wide: `GET /bank-questions` lists the +subject is a `400` (create and PATCH alike). The reverse guard does **not** +hold here, unlike exam questions and homework: a template never blocks a +subject delete, which simply clears `subject` off every template that carried +it (only a template's owner may re-tag it, so a `409` would be one a manager +could never clear — and a private template raising it would leak its +existence). Reads are school-wide: `GET /bank-questions` lists the whole bank (paged, `?subject=` narrows by origin subject, `?owner=` — or `?owner=me` — by owner) and `GET /bank-questions/{bid}` fetches one with `correct` included — any teacher+ can browse and reuse what any colleague @@ -2274,6 +2285,47 @@ as the message's `error_code`. add fields (a model name, token counts) and a future backend may send more context without either end having to be redeployed in lockstep. +## Concurrency model + +The backend runs as more than one replica against one database, so every +invariant is guarded where all replicas can see it. Three tiers: + +1. **Single-row conditional writes** — compare-and-set (`save_if_unchanged`), + `UPDATE … WHERE`, stored counters (`domain::cap`), leases. These hold + *across replicas*: the database decides the winner, the loser retries or + gets a 409. +2. **In-transaction `IF … THROW` gates** — the check runs inside the same + statement as the write it authorizes, so it is atomic with it. Used where + the rule reads the row being written (state machines, delete guards). + "Is anything still attached?" is answered the same way, by a counter on the + row being deleted rather than a `SELECT` over the children: a course is + deletable while its `enrollment_count` is zero, a term while its + `course_count` is (courses claim that reference *before* they write the + link, and give it back when the link moves or the course is deleted). + Where the child also carries a deterministic id — one enrollment per + (course, user), one registration per (event, user) — the seat and the row + are claimed in one transaction (`cap::claim_and_create`), so a duplicate + `CREATE` rolls its own seat back instead of costing a stranger their place. +3. **Two accepted races**, reviewed and deliberately left open: + - *Attempt-seq late save* — a save racing a retake can stamp an answer onto + the just-terminal previous sitting. Damage: one history row; the grade of + record (latest `seq`) is never touched. + - *Approved-overlap* — two replicas approving in the same instant can + double-book a teacher. Damage: one overlapping half-hour, visible to both + parties, fixable by cancelling either side. + +In-process locks that remain do so for reasons a database write cannot serve: +`PRESENCE_LOCK` guards in-process socket state, `CLAIM_LOCK` keeps one +counter writer per process (the `WHERE` clause is the cap — the lock only +tames the retry loop, and keeps the tests' in-memory engine deterministic), +`APPOINTMENT_LOCK` still collapses the common within-replica overlap case. + +Deployment contract: a release that adds or renames a stored counter must +restart *all* replicas together (`podman compose down` + `up`), never rolling. +An old binary writes rows without touching the new counters, the `= NONE` +backfill guard (correctly) refuses to re-seed, and the resulting permanent +under-count lets a guard approve exactly what it exists to refuse. + ## Layout ``` @@ -2310,7 +2362,9 @@ src/ cap.rs claim()/release(): the cross-replica count caps — an atomic `UPDATE parent SET n += 1 WHERE n < cap` on a counter column of the parent row, replacing the per-process mutexes that - only held while one instance owned the database + only held while one instance owned the database; + claim_and_create() commits that seat and the child row in + one transaction, for children with a deterministic id text_fold.rs case- and diacritic-insensitive folding for search, shared by the Rust needle and the SurrealQL column (Turkish İ/ı, ü, ö…) session.rs SessionId · SessionToken · Session (7-day expiry) @@ -2374,8 +2428,9 @@ src/ AppointmentSlot (a teacher's published availability; a recurring publish is expanded into rows sharing a series id) appointment.rs AppointmentId · AppointmentStatus · AppointmentReason · - Appointment (a booking on a slot; occupancy and overlap are - derived under APPOINTMENT_LOCK, never stored) + Appointment (a booking on a slot; occupancy is the slot's + stored `occupied` cap-1 counter, overlap is derived under + APPOINTMENT_LOCK) pomodoro.rs PomodoroSessionId · PomodoroSession (student focus log) pool_question.rs PoolQuestionId · PoolQuestionTitle · PoolQuestionBody · PoolQuestion (student-asked question; teacher-approved into diff --git a/src/constant.rs b/src/constant.rs index 0584713..275e8c6 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -742,6 +742,11 @@ pub const DIETARY_PROFILE_TABLE: &str = "dietary_profile"; pub const MEAL_BOOKING_TABLE: &str = "meal_booking"; pub const MEAL_ATTENDANCE_TABLE: &str = "meal_attendance"; pub const MEAL_LEDGER_TABLE: &str = "meal_ledger"; +/// One row per *name* the school's settings offer, keyed by the name itself: +/// how many rows still reference it, and whether it has been retired out of the +/// list (see the reference counters in [`crate::domain::cap`]). +pub const KIND_REF_TABLE: &str = "kind_ref"; +pub const SLOT_REF_TABLE: &str = "slot_ref"; // --- cross-replica cap counters ---------------------------------------- @@ -754,9 +759,55 @@ pub const MEAL_LEDGER_TABLE: &str = "meal_ledger"; /// SCHEMAFULL refusing the write. pub const ENROLLMENT_COUNT_FIELD: &str = "enrollment_count"; pub const REGISTRATION_COUNT_FIELD: &str = "registration_count"; +/// Not a cap — a refcount, and the whole of the term delete guard: how many +/// courses link this term. A term may only be dropped at zero, and the count +/// is claimed before a course's link is written, so the two decisions contend +/// on the term row instead of on a cross-table `SELECT` no transaction orders. +pub const COURSE_COUNT_FIELD: &str = "course_count"; pub const NOTE_FILE_COUNT_FIELD: &str = "file_count"; pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count"; pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; +/// Cap 1, not N: an appointment slot holds at most one live booking, so this +/// counter is really an "is it taken" flag kept in the shape every other cap +/// uses (`claim`/`release`), which is what makes rejecting or cancelling a +/// booking give the slot back. +pub const SLOT_OCCUPIED_FIELD: &str = "occupied"; +/// Not caps either, and uncapped by design: how many exam questions and how +/// many homework still point at a subject. A subject may be deleted exactly +/// while both read zero, so the delete's own `WHERE` decides it — the +/// cross-table "does anything reference this?" count it replaces served one +/// replica only. +pub const SUBJECT_QUESTION_COUNT_FIELD: &str = "exam_question_count"; +pub const SUBJECT_HOMEWORK_COUNT_FIELD: &str = "homework_count"; +/// How many marks an exam carries. Uncapped too, and the only counter its +/// entity carries as a field: the exam's save is a whole-row `CONTENT` write, +/// which would wipe a column the struct did not know about. That save pins it, +/// which is what makes "this exam has no marks" — the gate a kind change is +/// refused on — decided at write time rather than at read time. +pub const EXAM_RESULT_COUNT_FIELD: &str = "result_count"; +/// The two columns of a reference-counter row (`kind_ref`, `slot_ref`): how +/// many rows still point at the name, and whether it has left the school's +/// list. Both `option<…>`, absent meaning zero references and in service. +pub const REF_COUNT_FIELD: &str = "count"; +pub const REF_RETIRED_FIELD: &str = "retired"; +/// Seats held on one menu — the meal capacity cap. +pub const MENU_SEAT_COUNT_FIELD: &str = "seats_booked"; +/// Not a cap: the menu's revision, bumped by every write that can change what +/// a seat costs (a dish added, re-priced or removed, the capacity moved). A +/// booking claims its seat only at the revision it read the price at, so the +/// price frozen onto the row is one the menu really carried at that instant. +pub const MENU_VERSION_FIELD: &str = "version"; + +/// Not a cap either: the grade that froze a homework submission, absent while +/// the submission is still open. Every student-side write to a submission (its +/// text, its files) carries `graded_by_result = NONE` as a condition, so the +/// "not graded yet" decision and the write it licenses are one conditional +/// single-record write rather than a cross-table read a peer replica can +/// outrun. Set by grading, cleared by un-grading, never by the student. +pub const SUBMISSION_GRADED_FIELD: &str = "graded_by_result"; +/// The condition itself, spelled once: a submission is writable exactly while +/// its grade stamp is absent. +pub const SUBMISSION_OPEN_GUARD: &str = "graded_by_result = NONE"; /// How hard a counter write tries before giving up, and the first backoff step /// it sleeps between attempts (doubling, plus jitter). Contention on one record diff --git a/src/database.rs b/src/database.rs index d00c193..2d7f316 100644 --- a/src/database.rs +++ b/src/database.rs @@ -7,9 +7,10 @@ use surrealdb::types::SurrealValue; use crate::config::Config; use crate::constant::{ - CHATBOT_PENDING_STALE_SECS, MIGRATION_LOCK_CLAIM, MIGRATION_LOCK_DDL, MIGRATION_LOCK_HEARTBEAT, - MIGRATION_LOCK_HEARTBEAT_SECS, MIGRATION_LOCK_LEASE_SECS, MIGRATION_LOCK_POLL_MS, - MIGRATION_LOCK_STAMP, MIGRATION_LOCK_STATE, MIGRATION_LOCK_TAKEOVER, MIGRATION_LOCK_WAIT_SECS, + CAS_UPDATE_RETRIES, CHATBOT_PENDING_STALE_SECS, MIGRATION_LOCK_CLAIM, MIGRATION_LOCK_DDL, + MIGRATION_LOCK_HEARTBEAT, MIGRATION_LOCK_HEARTBEAT_SECS, MIGRATION_LOCK_LEASE_SECS, + MIGRATION_LOCK_POLL_MS, MIGRATION_LOCK_STAMP, MIGRATION_LOCK_STATE, MIGRATION_LOCK_TAKEOVER, + MIGRATION_LOCK_WAIT_SECS, }; use crate::domain::user::{Password, User, Username}; use crate::error::AppError; @@ -143,13 +144,24 @@ async fn boot_once( if claim(db, MIGRATION_LOCK_CLAIM, &me, lease_ms).await? { return leader_applies(db, &me, admin).await.map(|()| true); } - let state: Option = db + let read = db .query(MIGRATION_LOCK_STATE) .bind(("lease_ms", lease_ms)) .bind(("fingerprint", migration_fingerprint())) - .await? - .check()? - .take(0)?; + .await + .and_then(|response| response.check()) + .and_then(|mut response| response.take::>(0)); + let state = match read { + Ok(state) => state, + // The leader heartbeats this very row every few seconds and rivals + // take it over, so a read of it can be aborted as retryable — which + // is not an error about the lock, just "no answer this round". This + // poll loop, with its deadline, *is* the bounded retry the conflict + // asks for, so treat it like a missing row and look again. Retrying + // a `SELECT` is free of side effects by construction. + Err(err) if lost_the_race(&err) => None, + Err(err) => return Err(err.into()), + }; match state { // A live lease, stamped with our own fingerprint: the exact schema // this process needs is in place, so stop waiting. @@ -328,13 +340,34 @@ async fn leader_applies( lost = renew_lease(db, me) => return Err(lost), } - let mut response = db - .query(MIGRATION_LOCK_STAMP) - .bind(("me", me.to_string())) - .bind(("fingerprint", migration_fingerprint())) - .await? - .check()?; - let stamped: Vec = response.take(0)?; + // The stamp is the one write in this path with nothing above it to retry + // it: waiters are polling the same row and taking it over, so the + // key-value layer can abort ours as retryable, and an escaping conflict + // fails a boot that had already migrated everything. Repeating it is safe + // despite `applies += 1` — a conflicted transaction commits nothing, and + // the statement's `holder` guard turns a *genuine* takeover into an empty + // result rather than a second count. Bounded, because a conflict that + // never clears is a real failure and must stay one. + let mut stamped: Vec = Vec::new(); + for attempt in 0..CAS_UPDATE_RETRIES { + let attempted = db + .query(MIGRATION_LOCK_STAMP) + .bind(("me", me.to_string())) + .bind(("fingerprint", migration_fingerprint())) + .await + .and_then(|response| response.check()); + match attempted { + Ok(mut response) => { + stamped = response.take(0)?; + break; + } + Err(err) if lost_the_race(&err) && attempt + 1 < CAS_UPDATE_RETRIES => { + tracing::warn!("stamping the boot migration lock conflicted ({err}) — retrying"); + tokio::time::sleep(std::time::Duration::from_millis(MIGRATION_LOCK_POLL_MS)).await; + } + Err(err) => return Err(err.into()), + } + } if stamped.is_empty() { // The same verdict as a lost renewal, for the same reason — this is the // backstop for losing the lock in the window between the last renewal @@ -524,6 +557,38 @@ mod tests { ); } + /// The same race with enough processes in it to actually hit the + /// key-value layer's retryable aborts: eight boots contending for one lock + /// row collide on the losers' state read and the leader's stamp, which with + /// two boots surfaces only once in a few full-suite runs. + /// + /// What it asserts is deliberately narrow: no boot may fail with a + /// *retryable* conflict. A conflict is the layer asking to be asked again, + /// so one reaching the caller is always a missing retry — while the other + /// outcomes of a crowded election (a leader that loses its lease to a + /// taker) are documented behaviour, not bugs, and asserting against them + /// here would only make this flaky. Exactly-once stays the two-boot test's + /// job. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_crowd_of_boots_never_surfaces_a_retryable_conflict() { + let db = unmigrated().await; + let boots: Vec<_> = (0..8) + .map(|_| { + let db = db.clone(); + tokio::spawn(async move { boot_once(&db, admin(), Duration::from_secs(30)).await }) + }) + .collect(); + for boot in boots { + if let Err(err) = boot.await.unwrap() { + let message = err.to_string(); + assert!( + !message.contains("can be retried") && !message.contains("conflict"), + "a retryable conflict escaped boot_once instead of being retried: {message}" + ); + } + } + } + /// A leader killed mid-migration leaves its claim behind. Nothing may /// require a human with a SurrealQL prompt to clear it: the next boot takes /// the lease over once it has gone unrenewed past the horizon. diff --git a/src/domain/appointment.rs b/src/domain/appointment.rs index ea37d35..128457b 100644 --- a/src/domain/appointment.rs +++ b/src/domain/appointment.rs @@ -2,28 +2,32 @@ //! for the meeting with a reason; the teacher approves, rejects, or //! counter-proposes another time. //! -//! Two *cross-record* invariants live here, and both are guarded by -//! [`APPOINTMENT_LOCK`] rather than by the database: +//! Two *cross-record* invariants live here, guarded very differently: //! -//! - **One live booking per slot.** Occupancy is counted from the rows, not -//! stored — so rejecting or cancelling frees the slot with nothing to reset. +//! - **One live booking per slot** — the `occupied` counter on the slot row, a +//! [`cap`](crate::domain::cap) of one. Booking [`claim`](cap::claim)s it; +//! rejecting or cancelling gives it back in the *same transaction* as the +//! status flip, so the slot frees itself with nothing to sweep. Both are +//! single-record conditional writes, so this invariant holds across replicas. //! - **No double-booked person.** An approved meeting may not overlap another -//! approved meeting of the same teacher *or* of the same requester. -//! -//! Both are count-then-write checks across records, which a `BEGIN…COMMIT` -//! does not serialize in SurrealDB (write-skew: two racing bookings each see a -//! free slot). +//! approved meeting of the same teacher *or* of the same requester. That is a +//! count-then-write over *many* rows, which a `BEGIN…COMMIT` does not +//! serialize in SurrealDB (write-skew), so it stays under +//! [`APPOINTMENT_LOCK`] — and stays replica-local. //! //! The *single-row* invariant — a decision must be written onto the state it //! was validated against — is **not** the lock's job, and never was: the lock //! is process-local, so two replicas each take their own copy of it and a //! whole-row save would silently drop the other's decision. That one is a //! compare-and-set ([`Appointment::save_if_unchanged`]), which holds across -//! replicas. The lock stays for the two counts above, which no per-row -//! conditional write can cover. -// ponytail: with more than one replica those two counts are only -// replica-local. Closing them needs a stored occupancy counter (`domain::cap`) -// rather than a lock — deliberately not built here. +//! replicas. +//! +//! Overlap is a **documented accepted race** (reviewed, not an oversight): +//! it is a predicate over *other* rows with no single row to key a counter or +//! a CAS on, so across replicas two approvals decided in the same instant can +//! both land. Damage is one double-booked half-hour, visible to both parties +//! and fixable by cancelling either side — no money, no grade, no data loss. +//! Closing it would need a lease row per teacher taken on every approval. use std::sync::LazyLock; @@ -31,20 +35,33 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use tokio::sync::Mutex; use ulid::Generator; -use crate::constant::{APPOINTMENT_TABLE, CAS_UPDATE_RETRIES, MAX_APPOINTMENT_REASON_LEN}; +use crate::constant::{ + APPOINTMENT_TABLE, CAS_UPDATE_RETRIES, MAX_APPOINTMENT_REASON_LEN, SLOT_OCCUPIED_FIELD, +}; use crate::database::{Database, lost_the_race}; use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId}; +use crate::domain::cap; use crate::domain::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::validate_required; -/// Serializes every occupancy/overlap decision: the check and the write it -/// authorizes must be one atomic step, and SurrealDB transactions do not -/// conflict-check a cross-record `count()` against a concurrent insert. +/// Serializes the **overlap** check and the write it authorizes — nothing else. +/// "Is this teacher (or this requester) already committed at that time" is a +/// predicate over other appointment rows, and SurrealDB does not conflict-check +/// a cross-record read against a concurrent insert, so the check and its write +/// have to be one atomic step *within this process*. Occupancy is no longer its +/// business: that is the slot's `occupied` counter, a conditional single-record +/// write that holds between replicas too. +/// +/// Which leaves the accepted race the module doc records: this lock is +/// process-local, so two replicas can each approve an overlapping meeting in +/// the same instant. Visible to both parties, undone by cancelling either side. /// -/// Lock order: no path ever holds this together with `ENROLL_LOCK`, +/// Lock order: taken *before* `cap`'s `CLAIM_LOCK` (booking claims a slot while +/// holding this) and never the other way round. No path ever holds this +/// together with `ENROLL_LOCK`, /// `TERM_LOCK`, `EXAM_LOCK`, or `PRESENCE_LOCK` — appointments /// touch no roster, term, event seat, or exam room, and none of those touch /// appointments — so they cannot deadlock. Should a future path ever need two, @@ -299,60 +316,15 @@ impl Appointment { })) } - /// Does `slot` still hold a booking that keeps it occupied? The slot - /// delete guard's question, and the re-booking gate's. Caller must hold - /// [`APPOINTMENT_LOCK`]. - pub async fn has_live_booking( - slot: &AppointmentSlotId, - db: &Database, - ) -> Result { - let mut result = db - .query( - "SELECT * FROM appointment WHERE slot = $slot \ - AND status IN ['pending', 'approved'] LIMIT 1", - ) - .bind(("slot", slot.record())) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) - } - - /// Same question as [`has_live_booking`](Self::has_live_booking) asked of a - /// whole series at once: does *any* of `slots` still hold an occupied - /// booking? One round-trip, because a weekly publish is up to 52 slots and - /// the caller asks while holding the lock. Caller must hold - /// [`APPOINTMENT_LOCK`], for the same reason: the answer is only meaningful - /// while no booking can be written. - /// - /// No slots, no bookings — answered without a query, since an empty `IN` - /// list is a needless round-trip and must never read as "occupied". - pub async fn any_live_booking( - slots: &[AppointmentSlotId], - db: &Database, - ) -> Result { - if slots.is_empty() { - return Ok(false); - } - let records: Vec = slots.iter().map(AppointmentSlotId::record).collect(); - let mut result = db - .query( - "SELECT * FROM appointment WHERE slot IN $slots \ - AND status IN ['pending', 'approved'] LIMIT 1", - ) - .bind(("slots", records)) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) - } - /// Request `slot`. Lands `pending`: publishing availability is not consent /// to a specific person and topic. /// - /// Refused (409) when the slot's window has already opened, when it already - /// carries a live booking, or when the requester is already committed - /// elsewhere at that time — all re-derived - /// from a fresh read under [`APPOINTMENT_LOCK`], so two racing requests - /// cannot both find the slot free. + /// Refused (409) when the slot's window has already opened, when it is + /// already taken, or when the requester is already committed elsewhere at + /// that time. The slot is taken by [`cap::claim`] on the slot row — a + /// conditional single-record write, so two racing requests cannot both find + /// it free however many replicas they arrive at; the requester's own overlap + /// is the lock's part. pub async fn book( slot: &AppointmentSlotId, requester: &UserId, @@ -363,9 +335,6 @@ impl Appointment { let slot_row = AppointmentSlot::read(slot, db) .await? .ok_or(AppError::NotFound)?; - if Self::has_live_booking(slot, db).await? { - return Err(AppError::Conflict("the slot is already booked")); - } // A window that has opened is history, not a plan: `cancel` refuses to // call off a meeting that started, so such a booking would be stuck // forever. `list_upcoming` hides these slots, but a stale id still @@ -390,6 +359,17 @@ impl Appointment { "you already have an appointment at that time", )); } + // Last, so nothing above can refuse *after* the slot was taken. A slot + // deleted since the read above is gone, not full — the claim's `WHERE` + // finds no row either way, so the distinction is re-read rather than + // guessed. + let seat = slot.record(); + if !cap::claim(&seat, SLOT_OCCUPIED_FIELD, 1, db).await? { + if AppointmentSlot::read(slot, db).await?.is_none() { + return Err(AppError::NotFound); + } + return Err(AppError::Conflict("the slot is already booked")); + } let appointment = Appointment { id: AppointmentId::generate(), slot: slot.clone(), @@ -405,11 +385,21 @@ impl Appointment { reject_reason: None, created_at: Timestamp::now(), }; - let created: Option = db + let created: Result, _> = db .create(appointment.id.record()) .content(appointment) - .await?; - created.ok_or_else(|| AppError::Internal("failed to book the appointment".into())) + .await; + match created { + Ok(Some(created)) => Ok(created), + // The booking never landed, so the slot it took goes back. + other => { + cap::release(&seat, SLOT_OCCUPIED_FIELD, db).await?; + Err(match other { + Err(err) => err.into(), + _ => AppError::Internal("failed to book the appointment".into()), + }) + } + } } pub async fn read(id: &AppointmentId, db: &Database) -> Result, AppError> { @@ -509,14 +499,15 @@ impl Appointment { Err(contended()) } - /// Turn the request down. Frees the slot: occupancy counts live rows only. + /// Turn the request down. Frees the slot — the seat goes back with the + /// status flip, in one transaction. No lock: this decides nothing about + /// anyone's calendar, and the write is its own guard. pub async fn reject( id: &AppointmentId, decided_by: &UserId, reason: Option, db: &Database, ) -> Result { - let _guard = APPOINTMENT_LOCK.lock().await; for _ in 0..CAS_UPDATE_RETRIES { let expected = Self::read_pending(id, db).await?; let mut rejected = expected.clone(); @@ -547,7 +538,6 @@ impl Appointment { reason: Option, db: &Database, ) -> Result { - let _guard = APPOINTMENT_LOCK.lock().await; for _ in 0..CAS_UPDATE_RETRIES { let expected = Self::read(id, db).await?.ok_or(AppError::NotFound)?; if !expected.status.is_live() { @@ -595,7 +585,8 @@ impl Appointment { } .into()); } - let _guard = APPOINTMENT_LOCK.lock().await; + // No lock: a proposal commits nobody's calendar (the booking goes back + // to `pending`), and it neither takes nor frees the slot's seat. for _ in 0..CAS_UPDATE_RETRIES { let expected = Self::read(id, db).await?.ok_or(AppError::NotFound)?; if !expected.status.is_live() { @@ -664,20 +655,34 @@ impl Appointment { /// A store-level write conflict is reported the same way as a miss: it /// means a concurrent write committed on this row, which is exactly the /// "reload and re-decide" case. + /// + /// A transition out of a live status (reject, cancel) hands the slot's + /// `occupied` seat back, in this same transaction — the counter is the + /// authority on whether the slot is taken, so it must move if and only if + /// the status did. The decrement is `WHERE`-gated on the CAS having written + /// something, so a lost race frees nothing. async fn save_if_unchanged( self, expected: &Appointment, db: &Database, ) -> Result, AppError> { + let frees_the_slot = expected.status.is_live() && !self.status.is_live(); let attempted = async { let mut result = db .query( - "UPDATE $id CONTENT $new \ + "BEGIN TRANSACTION; + LET $done = (UPDATE $id CONTENT $new \ WHERE status = $status \ AND proposed_starts_at = $proposed_starts_at \ AND proposed_ends_at = $proposed_ends_at \ - AND decided_by = $decided_by", + AND decided_by = $decided_by); + UPDATE $slot SET occupied = math::max([(occupied ?? 0) - 1, 0]) + WHERE $frees AND array::len($done) > 0; + RETURN $done; + COMMIT TRANSACTION;", ) + .bind(("slot", expected.slot.record())) + .bind(("frees", frees_the_slot)) .bind(("id", expected.id.record())) .bind(("status", expected.status)) .bind(("proposed_starts_at", expected.proposed_starts_at)) @@ -686,7 +691,8 @@ impl Appointment { .bind(("new", self)) .await? .check()?; - result.take::>(0) + // BEGIN, the LET, and the counter write take a slot each. + result.take::>(3) } .await; match attempted { @@ -940,7 +946,115 @@ mod tests { assert_eq!(saved.get_proposed_starts_at(), Some(proposed_starts_at)); } - /// Occupancy is derived, so a rejected booking must hand the slot back. + /// What the slot row itself says about being taken — the authority every + /// gate now reads, in any replica. + async fn occupied(slot: &AppointmentSlotId, db: &Database) -> i64 { + let mut result = db + .query("SELECT VALUE (occupied ?? 0) FROM $slot") + .bind(("slot", slot.record())) + .await + .unwrap() + .check() + .unwrap(); + result.take::>(0).unwrap()[0] + } + + /// The double-book race, as the *other replica* runs it: `APPOINTMENT_LOCK` + /// is process-local, so a second process's booking arrives at the database + /// with nothing between it and the slot but the claim's own `WHERE`. Driven + /// through [`cap::claim`] directly rather than through a `join!`, since the + /// in-memory engine can drop one of two concurrent writes to a record and + /// still answer `Ok` — this asks the primitive the exact question the race + /// asks it. + /// + /// Deleting the `WHERE (occupied ?? 0) < $cap` from `cap::claim` makes the + /// second claim succeed and this fail (mutation-proved). + #[tokio::test] + async fn a_second_replica_cannot_claim_a_booked_slot() { + let db = crate::database::init_mem().await.unwrap(); + let teacher = UserId::from_key("t1"); + let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) + .await + .unwrap(); + assert_eq!(occupied(slot.get_id(), &db).await, 0); + + Appointment::book( + slot.get_id(), + &UserId::from_key("s1"), + AppointmentReason::try_new("görüşme").unwrap(), + &db, + ) + .await + .unwrap(); + assert_eq!(occupied(slot.get_id(), &db).await, 1); + + assert!( + !cap::claim(&slot.get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db) + .await + .unwrap(), + "the slot's seat must already be taken" + ); + // And the racer's refusal left the stored state alone: one booking, one + // seat — not two of either. + assert_eq!(occupied(slot.get_id(), &db).await, 1); + assert_eq!( + Appointment::list_for_slot(slot.get_id(), &db) + .await + .unwrap() + .len(), + 1 + ); + } + + /// Cancelling gives the seat back in the same transaction as the status + /// flip — the counter is the only thing that says a slot is free, so a + /// cancel that moved one without the other would strand the slot forever. + #[tokio::test] + async fn cancelling_hands_the_seat_back_with_the_status() { + let db = crate::database::init_mem().await.unwrap(); + let teacher = UserId::from_key("t1"); + let student = UserId::from_key("s1"); + let slot = AppointmentSlot::create(&teacher, soon(60_000), soon(120_000), None, &db) + .await + .unwrap(); + let booking = Appointment::book( + slot.get_id(), + &student, + AppointmentReason::try_new("görüşme").unwrap(), + &db, + ) + .await + .unwrap(); + Appointment::approve(booking.get_id(), &teacher, &db) + .await + .unwrap(); + assert_eq!(occupied(slot.get_id(), &db).await, 1, "approval holds it"); + + Appointment::cancel(booking.get_id(), &student, None, &db) + .await + .unwrap(); + assert_eq!(occupied(slot.get_id(), &db).await, 0); + // Cancelling twice is refused, so the seat cannot go back twice either. + assert!( + Appointment::cancel(booking.get_id(), &student, None, &db) + .await + .is_err() + ); + assert_eq!(occupied(slot.get_id(), &db).await, 0); + assert!( + Appointment::book( + slot.get_id(), + &UserId::from_key("s2"), + AppointmentReason::try_new("görüşme").unwrap(), + &db + ) + .await + .is_ok() + ); + assert_eq!(occupied(slot.get_id(), &db).await, 1); + } + + /// Occupancy frees on reject, so the slot can be re-booked. #[tokio::test] async fn rejecting_frees_the_slot_for_re_booking() { let db = crate::database::init_mem().await.unwrap(); @@ -966,9 +1080,11 @@ mod tests { Appointment::reject(first.get_id(), &teacher, None, &db) .await .unwrap(); + assert_eq!(occupied(slot.get_id(), &db).await, 0); let second = Appointment::book(slot.get_id(), &UserId::from_key("s2"), reason(), &db) .await .unwrap(); assert_eq!(second.get_status(), AppointmentStatus::Pending); + assert_eq!(occupied(slot.get_id(), &db).await, 1); } } diff --git a/src/domain/appointment_slot.rs b/src/domain/appointment_slot.rs index 89a3b9b..4b64965 100644 --- a/src/domain/appointment_slot.rs +++ b/src/domain/appointment_slot.rs @@ -1,8 +1,11 @@ //! A teacher's published availability: "I am free here, book me". A slot is -//! pure calendar — it carries no booking state at all. Whether it is taken is -//! *derived* from its [`Appointment`] rows under [`APPOINTMENT_LOCK`], so a -//! rejected or cancelled booking frees the slot again without any flag to -//! reset (and without a UNIQUE index, which would keep a dead booking's seat). +//! nearly pure calendar: the one piece of booking state it carries is the +//! `occupied` counter (a [`cap`](crate::domain::cap) of one), taken when a +//! booking is made and given back in the same transaction as the reject or +//! cancel that settles it — so the slot frees itself again, and unlike a UNIQUE +//! index it does not keep a dead booking's seat. Stored rather than counted +//! from the [`Appointment`] rows because a conditional write on one row is the +//! only guard that survives a second replica. //! //! A recurring publish is expanded into concrete rows here, at write time, //! sharing one `series` id — no recurrence rule is ever evaluated at read @@ -430,11 +433,10 @@ impl AppointmentSlot { /// Settled bookings (rejected/cancelled) are history of a slot that is /// going away, so they cascade out with it, like [`Event::delete`]'s rows. /// - /// The occupancy read and the delete run under [`APPOINTMENT_LOCK`], so a - /// booking cannot land between them and outlive its slot. + /// The guard is the delete's own `WHERE`, so no booking can land between a + /// check and the row going away — in this replica or another. pub async fn delete(self, db: &Database) -> Result { - let _guard = APPOINTMENT_LOCK.lock().await; - Self::delete_locked(std::slice::from_ref(&self.id), db).await?; + Self::delete_free(std::slice::from_ref(&self.id), db).await?; Ok(self) } @@ -445,34 +447,61 @@ impl AppointmentSlot { series: &SlotSeries, db: &Database, ) -> Result, AppError> { - let _guard = APPOINTMENT_LOCK.lock().await; let slots = Self::list_for_series(series, db).await?; if slots.is_empty() { return Err(AppError::NotFound); } let ids: Vec = slots.iter().map(|slot| slot.id.clone()).collect(); - Self::delete_locked(&ids, db).await?; + Self::delete_free(&ids, db).await?; Ok(slots) } - /// Shared body of both deletes. Caller must already hold - /// [`APPOINTMENT_LOCK`]: the live-booking check is only meaningful while - /// no booking can be written. - async fn delete_locked(ids: &[AppointmentSlotId], db: &Database) -> Result<(), AppError> { - if Appointment::any_live_booking(ids, db).await? { + /// Shared body of both deletes: drop every named slot, but only while its + /// `occupied` counter says nobody is waiting on it — the delete's own + /// `WHERE` is the guard, which is what makes it hold against a booking + /// landing in another replica (a separate read-then-delete could not). + /// + /// All-or-nothing across the whole list: if fewer rows go than were named, + /// the transaction is thrown away, so a series never loses its free weeks + /// and keeps the booked one. Whether that shortfall was a live booking or a + /// slot that no longer exists is read off what survived — the occupied rows + /// are still there, a vanished one is not — which is the 409/404 the caller + /// used to get from a separate check. + async fn delete_free(ids: &[AppointmentSlotId], db: &Database) -> Result<(), AppError> { + let records: Vec = ids.iter().map(|id| id.record()).collect(); + let mut result = db + .query( + "BEGIN TRANSACTION; + LET $gone = (DELETE $slots WHERE (occupied ?? 0) = 0 RETURN BEFORE); + IF array::len($gone) != array::len($slots) { + THROW IF array::len((SELECT VALUE id FROM appointment_slot + WHERE id IN $slots)) > 0 { 'slot_occupied' } ELSE { 'slot_missing' } + }; + DELETE appointment WHERE slot IN $slots; + RETURN $gone; + COMMIT TRANSACTION;", + ) + .bind(("slots", records)) + .await?; + // An aborted transaction errors every slot; only the THROW's own slot + // names the marker (the `Exam::update` treatment). + let mut errors = result.take_errors(); + let thrown = |marker: &str| { + errors + .values() + .any(|error| error.to_string().contains(marker)) + }; + if thrown("slot_occupied") { return Err(AppError::Conflict( "the slot has a pending or approved booking", )); } - let records: Vec = ids.iter().map(|id| id.record()).collect(); - let mut result = db - .query("DELETE appointment WHERE slot IN $slots; DELETE $slots RETURN BEFORE;") - .bind(("slots", records)) - .await? - .check()?; - if result.take::>(1)?.is_empty() { + if thrown("slot_missing") { return Err(AppError::NotFound); } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } Ok(()) } } @@ -480,7 +509,8 @@ impl AppointmentSlot { #[cfg(test)] mod tests { use super::*; - use crate::constant::MILLIS_PER_DAY; + use crate::constant::{MILLIS_PER_DAY, SLOT_OCCUPIED_FIELD}; + use crate::domain::cap; fn at(millis: i64) -> Timestamp { Timestamp::from_millis(millis) @@ -723,6 +753,65 @@ mod tests { ); } + /// The delete-vs-book race: a booking that lands in another replica between + /// this delete's read and its write must still keep the slot alive, so the + /// guard has to be the delete's own `WHERE` — here driven by taking the seat + /// the way that replica would, with no booking row to read. + /// + /// A series is all-or-nothing: one taken week refuses the whole publish, + /// and the free weeks must survive the refusal. + #[tokio::test] + async fn a_taken_slot_is_never_deleted_and_takes_its_series_with_it() { + let db = crate::database::init_mem().await.unwrap(); + let teacher = UserId::from_key("t1"); + let slots = AppointmentSlot::publish_weekly( + &teacher, + at(1_000), + at(2_000), + None, + at(1_000 + 2 * MILLIS_PER_WEEK), + &db, + ) + .await + .unwrap(); + let series = slots[0].get_series().cloned().unwrap(); + + // A free slot goes, and its series is deletable while every week is free. + assert!(slots[0].clone().delete(&db).await.is_ok()); + // The seat on the middle week is taken — no booking row, exactly as a + // racing replica would leave it mid-flight. + assert!( + cap::claim(&slots[1].get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db) + .await + .unwrap() + ); + assert!(matches!( + slots[1].clone().delete(&db).await, + Err(AppError::Conflict( + "the slot has a pending or approved booking" + )) + )); + assert!(matches!( + AppointmentSlot::delete_series(&series, &db).await, + Err(AppError::Conflict(_)) + )); + // Refused, not half-applied: the free third week is still published. + assert_eq!( + AppointmentSlot::list_for_series(&series, &db) + .await + .unwrap() + .len(), + 2 + ); + + // A slot that is simply gone is a 404, not a 409 — the delete tells the + // two shortfalls apart by what survived it. + assert!(matches!( + slots[0].clone().delete(&db).await, + Err(AppError::NotFound) + )); + } + #[tokio::test] async fn weekly_publish_that_self_overlaps_is_refused() { let db = crate::database::init_mem().await.unwrap(); diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index 30d9d1e..a96123c 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -771,10 +771,25 @@ mod tests { let exam = ExamId::generate(); let other_exam = ExamId::generate(); - async fn instantiate(exam: &ExamId, source: &BankQuestion, db: &Database) { + // A real subject row: an exam question claims a reference on its + // subject, so a minted id it never wrote would be refused. + let subject = crate::domain::subject::Subject::create( + &crate::domain::course::CourseId::generate(), + crate::domain::subject::SubjectName::try_new("topic").unwrap(), + crate::domain::subject::SubjectDescription::try_new("").unwrap(), + &db, + ) + .await + .unwrap(); + async fn instantiate( + exam: &ExamId, + subject: &SubjectId, + source: &BankQuestion, + db: &Database, + ) { ExamQuestion::create_from_bank( exam, - SubjectId::generate(), + subject.clone(), source.get_text().clone(), source.get_points(), source.spec(), @@ -785,13 +800,13 @@ mod tests { .unwrap(); } // Two copies of the same template, in two different exams. - instantiate(&exam, &used_twice, &db).await; - instantiate(&other_exam, &used_twice, &db).await; - instantiate(&exam, &used_once, &db).await; + instantiate(&exam, subject.get_id(), &used_twice, &db).await; + instantiate(&other_exam, subject.get_id(), &used_twice, &db).await; + instantiate(&exam, subject.get_id(), &used_once, &db).await; // A hand-authored question has no `from_bank` and must not be tallied. ExamQuestion::create( &exam, - SubjectId::generate(), + subject.get_id().clone(), QuestionText::try_new("mine").unwrap(), QuestionPoints::try_new(1).unwrap(), spec(), diff --git a/src/domain/cap.rs b/src/domain/cap.rs index 19f0ce5..6436392 100644 --- a/src/domain/cap.rs +++ b/src/domain/cap.rs @@ -26,10 +26,10 @@ // drift is ever observed, the repair is the same GROUP BY count the backfill // runs, issued by hand with the field's `= NONE` guard dropped. -use surrealdb::types::RecordId; +use surrealdb::types::{RecordId, SurrealValue}; use tokio::sync::Mutex; -use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES}; +use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, REF_COUNT_FIELD, REF_RETIRED_FIELD}; use crate::database::{Database, lost_the_race}; use crate::domain::timestamp::Timestamp; use crate::error::AppError; @@ -69,13 +69,176 @@ pub(crate) async fn claim( cap: i64, db: &Database, ) -> Result { + claim_at(parent, field, cap, "", db).await +} + +/// [`claim`], but only while `guard` — an extra predicate on that same parent +/// row — also holds. A caller whose insert has a second precondition (a homework +/// submission's file add is refused once the work is graded) gets both decided +/// by the one conditional write, instead of by a read a peer replica can outrun. +/// A miss is either "full" *or* "the guard failed"; the caller re-reads to tell +/// them apart, and only to pick the message. `guard` is always an in-crate SQL +/// literal, never user input. +pub(crate) async fn claim_when( + parent: &RecordId, + field: &str, + cap: i64, + guard: &str, + db: &Database, +) -> Result { + claim_at(parent, field, cap, guard, db).await +} + +async fn claim_at( + parent: &RecordId, + field: &str, + cap: i64, + extra: &str, + db: &Database, +) -> Result { + let extra = if extra.is_empty() { + String::new() + } else { + format!(" AND ({extra})") + }; let sql = format!( "UPDATE $parent SET {field} = ({field} ?? 0) + 1 \ - WHERE ({field} ?? 0) < $cap RETURN VALUE id" + WHERE ({field} ?? 0) < $num{extra} RETURN VALUE id" ); Ok(!write(&sql, parent, cap, db).await?.is_empty()) } +/// The `THROW` markers the in-transaction gates below abort with: no room, and +/// this pair already holds its row. +const FULL_MARK: &str = "cap_full"; +const HELD_MARK: &str = "cap_held"; + +/// What [`claim_and_create`] settled. +pub(crate) enum Claimed { + /// The seat and the row committed together. + Made(T), + /// The cap is full or the parent row is gone — nothing was written. + Full, + /// Another writer placed this very row first, so this caller never owed a + /// seat: nothing was written, and the winner's row is the answer. + Duplicate, +} + +/// Take a slot on `parent`'s `field` counter *and* write the child that fills +/// it, in one transaction. +/// +/// [`claim`] followed by a separate insert cannot promise this. Where the child +/// carries a deterministic id (one row per pair), two writers placing the *same* +/// pair both pass the claim — neither row exists yet — so on a tight cap the +/// second is told "full" for a seat it was never going to need, and a release +/// afterwards is too late to unsay it. A process-wide mutex hid that inside one +/// process and hid nothing between two. Here the duplicate `CREATE` aborts the +/// transaction, which takes its own increment with it, and the caller reads the +/// winner's row back — so the counter never counts a row that does not exist, +/// in any replica. +/// +/// The row is looked for *before* the seat is claimed, in that same +/// transaction, because on a tight cap the claim is the first thing to fail: a +/// member whose row a rival placed a moment ago would be told "full" about a +/// seat they already hold. The order makes "you are already in" outrank "there +/// is no room", which is what every caller's early return promises anyway. +pub(crate) async fn claim_and_create( + parent: &RecordId, + field: &str, + cap: i64, + id: &RecordId, + content: &T, + db: &Database, +) -> Result, AppError> { + let sql = format!( + "BEGIN TRANSACTION; + LET $held = (SELECT VALUE id FROM $id); + IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; + LET $seat = (UPDATE $parent SET {field} = ({field} ?? 0) + 1 \ + WHERE ({field} ?? 0) < $num RETURN VALUE id); + IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }}; + CREATE $id CONTENT $row; + COMMIT TRANSACTION;" + ); + let _guard = CLAIM_LOCK.lock().await; + let mut last = None; + for attempt in 0..CAP_WRITE_TRIES { + backoff(attempt).await; + let attempted = db + .query(sql.as_str()) + .bind(("parent", parent.clone())) + .bind(("num", cap)) + .bind(("id", id.clone())) + .bind(("row", content.clone())) + .await; + let mut result = match attempted { + Ok(result) => result, + Err(err) if lost_the_race(&err) => { + last = Some(err); + continue; + } + Err(err) => return Err(err.into()), + }; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the failing slot says why. + let mut errors = result.take_errors(); + // "Already a member" is read first: it outranks a full cap, and the two + // never both fire (the gate aborts before the seat is touched). + if errors + .values() + .any(|error| error.to_string().contains(HELD_MARK) || error.is_already_exists()) + { + return Ok(Claimed::Duplicate); + } + if errors + .values() + .any(|error| error.to_string().contains(FULL_MARK)) + { + return Ok(Claimed::Full); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + if !lost_the_race(&error) { + return Err(error.into()); + } + last = Some(error); + continue; + } + // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5. + return result + .take::>(5)? + .into_iter() + .next() + .map(Claimed::Made) + .ok_or_else(|| AppError::Internal("cap claim wrote no row".into())); + } + Err(last + .map(AppError::from) + .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) +} + +/// Wait out one lost round. Exponential with jitter, because racers arrive in +/// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them. +/// Attempt zero waits not at all. +async fn backoff(attempt: usize) { + if attempt == 0 { + return; + } + let step = CAP_WRITE_BACKOFF_MS << (attempt - 1); + let jitter = Timestamp::now().as_millis().unsigned_abs() % step.max(1); + tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await; +} + +/// Move `parent` to its next revision. A revision column is not a cap: it is +/// what a reader pins a value it took off the parent to, so that a write which +/// invalidates that value (a menu's price) can refuse the claim carrying the old +/// one. Every such mutation bumps *before* it writes, so a stale claim is +/// refused whether or not the mutation itself then lands. +pub(crate) async fn bump(parent: &RecordId, field: &str, db: &Database) -> Result<(), AppError> { + let sql = format!("UPDATE $parent SET {field} = ({field} ?? 0) + 1 RETURN VALUE id"); + write(&sql, parent, UNLIMITED, db).await?; + Ok(()) +} + /// Give a claimed slot back, for the insert that never landed. Clamped at zero /// so a double release can never push a counter negative and open the cap. 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 Ok(()) } +// --- reference counters -------------------------------------------------- +// +// The same single-record guard, pointed the other way. A cap asks "is there +// room for one more child?"; a reference counter asks "may this *name* still be +// used, and does anything still use it?" — the shape behind "an exam kind +// nothing is graded under may leave the school's settings". Both questions are +// answered by one row per name (`kind_ref:`, `slot_ref:`), created +// on first use, so the removal and the last claim contend on a record rather +// than on a cross-table count no transaction serializes. +// +// The two writes are exact mirrors: a claim lands only while the name is not +// retired, a retirement lands only while the count is zero. Whichever reaches +// the record first, the other is refused — in any process. + +/// Take `n` references on `id`. `false` = the name is retired and the caller +/// must refuse; nothing was written. +pub(crate) async fn claim_ref(id: &RecordId, n: i64, db: &Database) -> Result { + let sql = format!( + "UPSERT $parent SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + $num \ + WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id" + ); + Ok(!write(&sql, id, n, db).await?.is_empty()) +} + +/// Give `n` references back — the referencing rows are gone (or never landed). +/// Clamped at zero like [`release`], so a double release cannot push a counter +/// below the rows it counts and let a used name be retired. +pub(crate) async fn release_ref(id: &RecordId, n: i64, db: &Database) -> Result<(), AppError> { + let sql = format!( + "UPSERT $parent SET {REF_COUNT_FIELD} = \ + math::max([({REF_COUNT_FIELD} ?? 0) - $num, 0]) RETURN VALUE id" + ); + write(&sql, id, n, db).await?; + Ok(()) +} + +/// Retire the name behind `id`: no further claim succeeds. `false` = something +/// still references it and the caller must refuse; nothing was written. +/// Idempotent — retiring an already-retired unused name lands again. +pub(crate) async fn retire(id: &RecordId, db: &Database) -> Result { + // Parenthesized `??`: `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which + // is truthy for *every* row and would retire a name still in use. + let sql = format!( + "UPSERT $parent SET {REF_RETIRED_FIELD} = true \ + WHERE ({REF_COUNT_FIELD} ?? 0) = 0 RETURN VALUE id" + ); + Ok(!write(&sql, id, UNLIMITED, db).await?.is_empty()) +} + +/// Put a name back in service — it re-entered the list it was retired from, or +/// the edit that retired it never landed. +pub(crate) async fn unretire(id: &RecordId, db: &Database) -> Result<(), AppError> { + let sql = format!("UPSERT $parent SET {REF_RETIRED_FIELD} = false RETURN VALUE id"); + write(&sql, id, UNLIMITED, db).await?; + Ok(()) +} + /// Run one conditional counter write, retrying while the store reports a write /// conflict. /// @@ -94,25 +314,23 @@ pub(crate) async fn release(parent: &RecordId, field: &str, db: &Database) -> Re /// never letting two writers reach the database at once. So the queueing has to /// happen here. Backoff is exponential with jitter, because racers arrive in /// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them. +/// `num` is the statement's one number, bound as `$num`: a cap for the claims, +/// a step for the reference counters below. async fn write( sql: &str, parent: &RecordId, - cap: i64, + num: i64, db: &Database, ) -> Result, AppError> { let _guard = CLAIM_LOCK.lock().await; let mut last = None; for attempt in 0..CAP_WRITE_TRIES { - if attempt > 0 { - let step = CAP_WRITE_BACKOFF_MS << (attempt - 1); - let jitter = Timestamp::now().as_millis().unsigned_abs() % step.max(1); - tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await; - } + backoff(attempt).await; let attempted = async { let mut result = db .query(sql) .bind(("parent", parent.clone())) - .bind(("cap", cap)) + .bind(("num", num)) .await? .check()?; result.take::>(0) diff --git a/src/domain/course.rs b/src/domain/course.rs index 08440c3..9a06a29 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -1,8 +1,12 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; -use crate::constant::{COURSE_TABLE, MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN}; +use crate::constant::{ + COURSE_COUNT_FIELD, COURSE_TABLE, ENROLLMENT_COUNT_FIELD, MAX_COURSE_DESCRIPTION_LEN, + MAX_COURSE_TITLE_LEN, REF_COUNT_FIELD, +}; use crate::database::Database; +use crate::domain::cap; use crate::domain::field_update::FieldUpdate; use crate::domain::page::PagedList; use crate::domain::term::TermId; @@ -10,6 +14,10 @@ use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_course_kind, validate_optional, validate_required}; +/// The `THROW` marker the delete guard aborts with — a roster that is not +/// empty, or a course row that is no longer there. +const ROSTER_MARK: &str = "course_roster"; + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct CourseId(RecordId); @@ -153,6 +161,11 @@ impl Course { self.teachers.contains(user) } + /// Create the course, claiming a reference on the term it links (if any) + /// *before* the row is written: the claim is a conditional write on the + /// term row, so it fails when the term is already gone and it makes the + /// term undeletable the instant this link exists — across replicas, which + /// the mutex it replaced could not do inside one process. pub async fn create( creator: &UserId, title: CourseTitle, @@ -162,18 +175,35 @@ impl Course { capacity: Option, db: &Database, ) -> Result { + if let Some(term) = &term { + claim_term(term, db).await?; + } + let claimed = term.clone(); let course = Course { id: CourseId::generate(), creator: creator.clone(), teachers: Vec::new(), + term, + capacity, title, description, kind, - term, - capacity, }; - let created: Option = db.create(course.id.record()).content(course).await?; - created.ok_or_else(|| AppError::Internal("failed to create course".into())) + let created: Result, _> = + db.create(course.id.record()).content(course).await; + match created { + Ok(Some(created)) => Ok(created), + other => { + // The link never landed, so the reference has to go back. + if let Some(term) = &claimed { + cap::release(&term.record(), COURSE_COUNT_FIELD, db).await?; + } + match other { + Err(err) => Err(err.into()), + _ => Err(AppError::Internal("failed to create course".into())), + } + } + } } pub async fn read(id: &CourseId, db: &Database) -> Result, AppError> { @@ -250,14 +280,43 @@ impl Course { capacity: Option>, db: &Database, ) -> Result { - FieldUpdate::new(self.id.record()) + // A term move is claim-then-write-then-release, in that order: the new + // term is made undeletable before the link points at it, and the old + // one is only let go once the link has actually moved off it. Doing it + // the other way round would open exactly the window this replaced. + let claimed = match &term { + Some(Some(new)) if Some(new) != self.term.as_ref() => { + claim_term(new, db).await?; + Some(new.clone()) + } + _ => None, + }; + let updated = FieldUpdate::new(self.id.record()) .set("title", title) .set("description", description) .set("kind", kind) .set("term", term.map(|term| term.map(|term| term.record()))) .set("capacity", capacity) .run::(db) - .await + .await; + match updated { + Ok(updated) => { + // The stored row is the authority on where the link ended up — + // a PATCH that carried no `term_id` leaves it untouched. + if let Some(old) = &self.term + && updated.term.as_ref() != Some(old) + { + cap::release(&old.record(), COURSE_COUNT_FIELD, db).await?; + } + Ok(updated) + } + Err(err) => { + if let Some(new) = &claimed { + cap::release(&new.record(), COURSE_COUNT_FIELD, db).await?; + } + Err(err) + } + } } /// Assign `teacher` to run this course, or return the course untouched if @@ -332,9 +391,36 @@ impl Course { /// leave an exam pointing at a deleted course. The image and /// homework-file *blobs* are the web layer's to remove — it collects /// their names before calling this. - pub async fn delete(self, db: &Database) -> Result { - db.query( + /// + /// The marks going with it give their exam kinds' references back, counted + /// per kind inside this same transaction — the mirror of `Exam::delete`. + /// Skipping it would leave every kind the course graded under counted + /// forever, and a counted kind can never leave the school's settings. + /// + /// `false` = refused, nothing was written: someone is still enrolled. The + /// roster is read off the course's own `enrollment_count`, so the check and + /// the delete are one conditional write on one record — an enroll racing + /// this either takes its seat first (and the delete is refused) or finds + /// the row gone (and is refused itself), in any replica. `Err(NotFound)` + /// keeps the answer a concurrent *delete* used to get. + pub async fn delete(self, db: &Database) -> Result { + let mut result = db + .query(format!( "BEGIN TRANSACTION; + LET $gone = (DELETE $course WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); + IF array::len($gone) = 0 {{ THROW '{ROSTER_MARK}' }}; + FOR $row IN $gone {{ + IF $row.term != NONE {{ + UPDATE $row.term SET {COURSE_COUNT_FIELD} = \ + math::max([({COURSE_COUNT_FIELD} ?? 0) - 1, 0]); + }}; + }}; + FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result + WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course) + GROUP BY kind) ?? []) {{ + UPDATE type::record('kind_ref', $row.kind) SET {REF_COUNT_FIELD} = \ + math::max([({REF_COUNT_FIELD} ?? 0) - $row.n, 0]) + }}; DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); @@ -350,20 +436,172 @@ impl Course { DELETE subject WHERE course = $course; DELETE homework WHERE course = $course; DELETE exam WHERE course = $course; - COMMIT TRANSACTION;", - ) - .bind(("course", self.id.record())) - .await? - .check()?; - let deleted: Option = db.delete(self.id.record()).await?; - deleted.ok_or(AppError::NotFound) + COMMIT TRANSACTION;" + )) + .bind(("course", self.id.record())) + .await?; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the marker. + let mut errors = result.take_errors(); + if errors + .values() + .any(|error| error.to_string().contains(ROSTER_MARK)) + { + // Full stop or already gone: the guard cannot tell those apart, and + // only the refusal path pays for the extra read that can. + return match Self::read(&self.id, db).await? { + Some(_) => Ok(false), + None => Err(AppError::NotFound), + }; + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + Ok(true) } } +/// Take a reference on `term` for a course about to link it. The conditional +/// write doubles as the existence check: a term that a delete already removed +/// matches nothing, and the caller answers exactly what the pre-flight lookup +/// in `web::terms::resolve_term` would have. +async fn claim_term(term: &TermId, db: &Database) -> Result<(), AppError> { + if cap::claim(&term.record(), COURSE_COUNT_FIELD, cap::UNLIMITED, db).await? { + return Ok(()); + } + Err(AppError::Validation(ValidationError::Invalid { + field: "term_id", + reason: "term does not exist", + })) +} + #[cfg(test)] mod tests { use super::*; + async fn course_on(term: Option, db: &Database) -> Course { + Course::create( + &UserId::from_key("teacher"), + CourseTitle::try_new("algebra").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + term, + None, + db, + ) + .await + .unwrap() + } + + /// The bite test for the delete guard that replaced `ENROLL_LOCK`: the + /// roster check is now the `WHERE` on the delete itself, so only the guard + /// can refuse — and it must refuse having written nothing, cascade + /// included. A `>= 0` guard passes the roster branch and fails here. + #[tokio::test] + async fn a_course_with_a_roster_refuses_to_delete() { + use crate::domain::enrollment::Enrollment; + + let db = crate::database::init_mem().await.unwrap(); + let teacher = UserId::from_key("teacher"); + let student = UserId::from_key("student"); + let course = course_on(None, &db).await; + Enrollment::enroll(course.get_id(), &student, &teacher, &db) + .await + .unwrap(); + + assert!( + !course.clone().delete(&db).await.unwrap(), + "a non-empty roster must refuse the delete" + ); + assert!( + Course::read(course.get_id(), &db).await.unwrap().is_some(), + "a refused delete may write nothing" + ); + assert!( + Enrollment::read_for_user(course.get_id(), &student, &db) + .await + .unwrap() + .is_some(), + "…the cascade least of all" + ); + + Enrollment::remove(course.get_id(), &student, &db) + .await + .unwrap(); + assert!(course.clone().delete(&db).await.unwrap()); + assert!(Course::read(course.get_id(), &db).await.unwrap().is_none()); + + // The other half of the same guard: once the course row is gone the + // seat claim matches nothing, so a late enroll is a 404 rather than a + // roster row that outlived its course. + let late = Enrollment::enroll(course.get_id(), &student, &teacher, &db) + .await + .expect_err("enrolling into a deleted course must fail"); + assert!(matches!(late, AppError::NotFound), "got {late:?}"); + } + + /// The bite test for the refcount that replaced `TERM_LOCK`: a term is + /// undeletable exactly while a course links it, and every way a link can + /// end — PATCH away, and the course's own delete — gives the reference + /// back. Dropping the release in `delete` leaves the term deletable never. + #[tokio::test] + async fn a_term_is_deletable_only_once_no_course_links_it() { + use crate::domain::term::{Term, TermName}; + + let db = crate::database::init_mem().await.unwrap(); + let at = crate::domain::timestamp::Timestamp::from_millis; + let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db) + .await + .unwrap(); + + let linked = course_on(Some(term.get_id().clone()), &db).await; + let patched = course_on(Some(term.get_id().clone()), &db).await; + assert!( + !term.clone().delete(&db).await.unwrap(), + "two linked courses must refuse the delete" + ); + + patched + .update(None, None, None, Some(None), None, &db) + .await + .unwrap(); + assert!( + !term.clone().delete(&db).await.unwrap(), + "one link is still one link" + ); + + assert!(linked.delete(&db).await.unwrap()); + assert!( + term.clone().delete(&db).await.unwrap(), + "the last link gone, the term may go" + ); + let again = term.delete(&db).await; + assert!( + matches!(again, Err(AppError::NotFound)), + "a second delete is a 404, not a refusal: {again:?}" + ); + } + + /// The claim doubles as the existence check the lock used to make safe: + /// a term that is already gone cannot be linked, with the same 400 the + /// web layer's pre-flight lookup gives. + #[tokio::test] + async fn a_course_cannot_link_a_term_that_is_gone() { + let db = crate::database::init_mem().await.unwrap(); + let error = Course::create( + &UserId::from_key("teacher"), + CourseTitle::try_new("algebra").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + Some(TermId::from_key("gone")), + None, + &db, + ) + .await + .expect_err("a missing term must not be linkable"); + assert!(error.to_string().contains("term does not exist")); + } + #[tokio::test] async fn title_is_required() { assert!(CourseTitle::try_new("algebra").is_ok()); diff --git a/src/domain/enrollment.rs b/src/domain/enrollment.rs index 369d683..c88a849 100644 --- a/src/domain/enrollment.rs +++ b/src/domain/enrollment.rs @@ -1,24 +1,13 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use tokio::sync::Mutex; use crate::constant::{ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE}; -use crate::database::{Database, lost_the_race}; +use crate::database::Database; use crate::domain::cap; use crate::domain::course::{Course, CourseId}; use crate::domain::page::PagedList; use crate::domain::user::UserId; use crate::error::AppError; -/// Serializes the roster check of a course delete against a concurrent enroll, -/// so a student can't join a course that is already on its way out. -// -// ponytail: process-local, so with two replicas the delete-vs-enroll window is -// only narrowed, not closed — a student can still land on a course another -// replica is deleting, and the cascade then leaves nothing behind but a 404 on -// the next read. Closing it needs the same treatment the capacity cap got: a -// deleting flag on the course row that the enroll's conditional UPDATE checks. -pub(crate) static ENROLL_LOCK: Mutex<()> = Mutex::const_new(()); - #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct EnrollmentId(RecordId); @@ -82,13 +71,15 @@ impl Enrollment { /// single-record conditional write, so the cap holds across replicas and /// against a concurrent capacity PATCH alike. An already enrolled user is /// returned as-is even when the roster is full, and never charged a seat. + /// The same claim is the delete guard's other half: it is refused outright + /// once the course row is gone, and while it holds a seat the course cannot + /// be deleted — so no roster row can outlive its course. pub async fn enroll( course: &CourseId, user: &UserId, enrolled_by: &UserId, db: &Database, ) -> Result { - let _guard = ENROLL_LOCK.lock().await; if let Some(existing) = Self::read_for_user(course, user, db).await? { return Ok(existing); } @@ -96,43 +87,39 @@ impl Enrollment { .await? .ok_or(AppError::NotFound)? .get_capacity(); - let seats = course.record(); - if !cap::claim( - &seats, - ENROLLMENT_COUNT_FIELD, - capacity.unwrap_or(cap::UNLIMITED), - db, - ) - .await? - { - return Err(AppError::Conflict("the course is full")); - } let enrollment = Enrollment { id: EnrollmentId::composite(course, user), course: course.clone(), user: user.clone(), enrolled_by: enrolled_by.clone(), }; - // CREATE, not UPSERT: a duplicate has to be *seen*, or the pair's second - // writer would silently keep the seat it claimed for a row that already - // existed and the counter would drift above the roster forever. - let saved: Result, _> = - db.create(enrollment.id.record()).content(enrollment).await; - match saved { - Ok(Some(saved)) => Ok(saved), - Ok(None) => { - cap::release(&seats, ENROLLMENT_COUNT_FIELD, db).await?; - Err(AppError::Internal("failed to enroll user".into())) - } - Err(err) => { - cap::release(&seats, ENROLLMENT_COUNT_FIELD, db).await?; - if !lost_the_race(&err) { - return Err(err.into()); - } - Self::read_for_user(course, user, db) - .await? - .ok_or_else(|| AppError::Internal("failed to enroll user".into())) - } + // CREATE, not UPSERT, and in the seat's own transaction: a duplicate has + // to be *seen*, or the pair's second writer would keep the seat it + // claimed for a row that already existed and the counter would drift + // above the roster forever. + match cap::claim_and_create( + &course.record(), + ENROLLMENT_COUNT_FIELD, + capacity.unwrap_or(cap::UNLIMITED), + &enrollment.id.record(), + &enrollment, + db, + ) + .await? + { + cap::Claimed::Made(saved) => Ok(saved), + // Someone placed this pair first; their row is the answer, and no + // seat was spent finding that out. + cap::Claimed::Duplicate => Self::read_for_user(course, user, db) + .await? + .ok_or_else(|| AppError::Internal("failed to enroll user".into())), + // Full, or the course was deleted between the read and the claim — + // the conditional write matches nothing either way, and only this + // path pays for the read that tells them apart. + cap::Claimed::Full => match Course::read(course, db).await? { + Some(_) => Err(AppError::Conflict("the course is full")), + None => Err(AppError::NotFound), + }, } } @@ -151,16 +138,6 @@ impl Enrollment { Ok(result.take::>(0)?.into_iter().next()) } - /// True iff anyone is still on the course's roster — the delete guard. - pub async fn any_for_course(course: &CourseId, db: &Database) -> Result { - let mut result = db - .query("SELECT VALUE id FROM enrollment WHERE course = $course LIMIT 1") - .bind(("course", course.record())) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) - } - pub async fn list_for_course( course: &CourseId, limit: Option, diff --git a/src/domain/exam.rs b/src/domain/exam.rs index aced7cb..1e4cbe4 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -290,6 +290,14 @@ pub struct Exam { // managers, cannot be sat, and cannot be graded. Rows predating the // column are backfilled published (`false`). draft: bool, + /// How many marks the exam carries — a cap-style counter ([`cap::claim`] + /// from the grade, decremented by every delete of a mark), absent meaning + /// zero. Unlike every other counter it is carried *in the struct*, because + /// the save below is a whole-row `CONTENT` write: a column this type did + /// not know about would be wiped by the next exam PATCH. Being in the row + /// is also what makes it useful — the save pins it, so a grade landing + /// mid-PATCH refuses the save instead of slipping past its gates. + result_count: Option, } impl Exam { @@ -297,6 +305,11 @@ impl Exam { &self.id } + /// The marks this exam carries, as the counter reads (absent = none yet). + pub fn get_result_count(&self) -> i64 { + self.result_count.unwrap_or(0) + } + pub fn get_creator(&self) -> &UserId { &self.creator } @@ -403,6 +416,7 @@ impl Exam { allow_rejoin, allow_review, draft, + result_count: None, }; let created: Option = db.create(exam.id.record()).content(exam).await?; created.ok_or_else(|| AppError::Internal("failed to create exam".into())) @@ -523,6 +537,7 @@ impl Exam { AND allow_rejoin = $was_allow_rejoin AND allow_review = $was_allow_review AND draft = $was_draft + AND (result_count ?? 0) = $was_results RETURN AFTER; COMMIT TRANSACTION;", ) @@ -539,6 +554,12 @@ impl Exam { .bind(("was_allow_rejoin", was.8)) .bind(("was_allow_review", was.9)) .bind(("was_draft", was.10)) + // The mark counter is pinned like every other column this write + // replaces, and for a sharper reason: a grade increments it, so + // pinning it is what makes "this exam had no marks" — the gate the + // handler refuses a kind change on — true at *write* time and not + // merely at read time. A mark landing in between refuses the save. + .bind(("was_results", self.result_count.unwrap_or(0))) .bind(("new", self)) .await?; // An aborted transaction errors every slot; only the THROW's names the @@ -566,15 +587,35 @@ impl Exam { /// Bank templates saved out of this exam survive it — they are a separate, /// reusable library — so only their `source_exam` provenance link is cleared, /// in the same transaction, never left pointing at a dead exam. + /// + /// The questions about to be cascaded each hold a reference on their + /// subject, which is what keeps that subject from being deleted under them. + /// They are given back in this same transaction, counted per subject, so + /// deleting an exam frees its subjects for deletion and nothing else does. + /// The marks give their *kind* references back the same way, and it has to + /// be the same way: counted outside the transaction, a mark deleted by a + /// concurrent `remove_result` in the gap would be released twice — once by + /// each — which on a kind another exam still uses reads as one mark too + /// few, and that is a kind wrongly free to leave the settings. pub async fn delete(self, db: &Database) -> Result { let mut result = db .query( "BEGIN TRANSACTION; + FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result + WHERE exam = $ex GROUP BY kind) ?? []) { + UPDATE type::record('kind_ref', $row.kind) SET count = + math::max([(count ?? 0) - $row.n, 0]) + }; DELETE exam_result WHERE exam = $ex; DELETE exam_attempt WHERE exam = $ex; DELETE exam_answer WHERE exam = $ex; DELETE answer_image WHERE exam = $ex; DELETE question_image WHERE exam = $ex; + FOR $row IN ((SELECT subject, count() AS n FROM exam_question + WHERE exam = $ex GROUP BY subject) ?? []) { + UPDATE $row.subject SET exam_question_count = + math::max([(exam_question_count ?? 0) - $row.n, 0]) + }; DELETE exam_question WHERE exam = $ex; UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex; LET $before = (DELETE $ex RETURN BEFORE); @@ -697,6 +738,7 @@ mod tests { 1, Mark::try_new(80).unwrap(), &UserId::generate(), + exam.get_kind().as_str(), &db, ) .await diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs index da6293b..842f52c 100644 --- a/src/domain/exam_attempt.rs +++ b/src/domain/exam_attempt.rs @@ -438,9 +438,19 @@ mod tests { &[], ) .unwrap(); + // A real subject row, not a minted id: a question claims a reference on + // its subject and is refused if that subject does not exist. + let subject = crate::domain::subject::Subject::create( + &crate::domain::course::CourseId::generate(), + crate::domain::subject::SubjectName::try_new("topic").unwrap(), + crate::domain::subject::SubjectDescription::try_new("").unwrap(), + db, + ) + .await + .unwrap(); let question = ExamQuestion::create( exam.get_id(), - crate::domain::subject::SubjectId::generate(), + subject.get_id().clone(), crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(), QuestionPoints::try_new(5).unwrap(), spec, diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index 448c423..f189427 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -3,10 +3,11 @@ use ulid::Ulid; use crate::constant::{ EXAM_QUESTION_TABLE, MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, - MIN_QUESTION_CHOICES, + MIN_QUESTION_CHOICES, SUBJECT_QUESTION_COUNT_FIELD, }; use crate::database::Database; use crate::domain::bank_question::BankQuestionId; +use crate::domain::cap; use crate::domain::exam::ExamId; use crate::domain::exam_attempt::ExamAttempt; use crate::domain::monotonic_id::next_ulid; @@ -393,6 +394,20 @@ impl ExamQuestion { from_bank: Option, db: &Database, ) -> Result { + // Take the subject's reference before the row exists, exactly as a cap + // is claimed before the child it caps ([`cap::claim`], here uncapped): + // the subject delete is conditioned on that counter reading zero, so + // the two contend on the subject record and a question can no longer + // land on a subject another replica is deleting. A miss means the + // subject is already gone — the same 400 the web layer's pre-flight + // check answers with. + let counted = subject.record(); + if !cap::claim(&counted, SUBJECT_QUESTION_COUNT_FIELD, cap::UNLIMITED, db).await? { + return Err(AppError::Validation(ValidationError::Invalid { + field: "subject_id", + reason: "subject does not exist", + })); + } let question = ExamQuestion { id: ExamQuestionId::generate(), exam: exam.clone(), @@ -409,18 +424,28 @@ impl ExamQuestion { // The freeze gate rides in the same transaction as the insert: a // question cannot appear under an exam somebody has already started, // whichever replica the two requests hit. - let mut result = db - .query(ExamAttempt::unfrozen("CREATE $id CONTENT $question;")) - .bind(("freeze_exam", exam.record())) - .bind(("id", question.id.record())) - .bind(("question", question)) - .await?; - ExamAttempt::frozen_check(&mut result)?; - result - .take::>(ExamAttempt::FROZEN_SLOT)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to create exam question".into())) + let inserted = async { + let mut result = db + .query(ExamAttempt::unfrozen("CREATE $id CONTENT $question;")) + .bind(("freeze_exam", exam.record())) + .bind(("id", question.id.record())) + .bind(("question", question)) + .await?; + ExamAttempt::frozen_check(&mut result)?; + result + .take::>(ExamAttempt::FROZEN_SLOT)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to create exam question".into())) + } + .await; + if inserted.is_err() { + // The row never landed (a frozen exam, most often), so the + // reference it took goes straight back — otherwise the subject + // would be undeletable for a question that does not exist. + cap::release(&counted, SUBJECT_QUESTION_COUNT_FIELD, db).await?; + } + inserted } pub async fn read( @@ -443,17 +468,6 @@ impl ExamQuestion { .await } - /// Whether any question anywhere references `subject` — the gate that - /// blocks deleting a subject still in use. - pub async fn any_for_subject(subject: &SubjectId, db: &Database) -> Result { - let mut result = db - .query("SELECT VALUE id FROM exam_question WHERE subject = $subject LIMIT 1") - .bind(("subject", subject.record())) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) - } - /// Write the editable fields, refused outright once the exam has an /// attempt — the freeze gate is part of this transaction, not a check the /// caller made a moment earlier under a lock. @@ -472,26 +486,49 @@ impl ExamQuestion { spec: QuestionSpec, db: &Database, ) -> Result { - let mut result = db - .query(ExamAttempt::unfrozen( - "UPDATE $id SET subject = $subject, text = $text, points = $points, - kind = $kind, choices = $choices, correct = $correct RETURN AFTER;", - )) - .bind(("freeze_exam", self.exam.record())) - .bind(("id", self.id.record())) - .bind(("subject", subject.record())) - .bind(("text", text)) - .bind(("points", points)) - .bind(("kind", spec.kind)) - .bind(("choices", spec.choices)) - .bind(("correct", spec.correct)) - .await?; - ExamAttempt::frozen_check(&mut result)?; - result - .take::>(ExamAttempt::FROZEN_SLOT)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + // A re-tag moves a reference: the new subject is claimed *before* the + // write and the old one released only once it lands, so at no instant + // is either subject under-counted — the direction that would let one be + // deleted while this question still points at it. Both counters staying + // put is the ordinary case (`subject` omitted from the PATCH), and it + // costs nothing. + let retag = (subject != self.subject).then(|| (subject.record(), self.subject.record())); + if let Some((next, _)) = &retag + && !cap::claim(next, SUBJECT_QUESTION_COUNT_FIELD, cap::UNLIMITED, db).await? + { + return Err(AppError::Validation(ValidationError::Invalid { + field: "subject_id", + reason: "subject does not exist", + })); + } + let written = async { + let mut result = db + .query(ExamAttempt::unfrozen( + "UPDATE $id SET subject = $subject, text = $text, points = $points, + kind = $kind, choices = $choices, correct = $correct RETURN AFTER;", + )) + .bind(("freeze_exam", self.exam.record())) + .bind(("id", self.id.record())) + .bind(("subject", subject.record())) + .bind(("text", text)) + .bind(("points", points)) + .bind(("kind", spec.kind)) + .bind(("choices", spec.choices)) + .bind(("correct", spec.correct)) + .await?; + ExamAttempt::frozen_check(&mut result)?; + result + .take::>(ExamAttempt::FROZEN_SLOT)? + .into_iter() + .next() + .ok_or(AppError::NotFound) + } + .await; + if let Some((next, previous)) = &retag { + let give_back = if written.is_ok() { previous } else { next }; + cap::release(give_back, SUBJECT_QUESTION_COUNT_FIELD, db).await?; + } + written } /// Point the question's `banked_as` at the bank template it was just saved @@ -538,15 +575,25 @@ impl ExamQuestion { .query(ExamAttempt::unfrozen( "DELETE exam_answer WHERE question = $q; DELETE question_image WHERE question = $q; - DELETE $q RETURN BEFORE;", + LET $gone = (DELETE $q RETURN BEFORE); + FOR $sub IN ($gone.subject ?? []) { + UPDATE $sub SET exam_question_count = + math::max([(exam_question_count ?? 0) - 1, 0]) + }; + RETURN $gone;", )) .bind(("freeze_exam", self.exam.record())) .bind(("q", self.id.record())) .await?; ExamAttempt::frozen_check(&mut result)?; - // Two cascade statements ahead of the delete itself. + // The subject's reference is given back inside this same transaction, + // driven off what the delete actually removed — a question that wasn't + // there decrements nothing. Read through the trailing `RETURN` rather + // than a hand-counted slot, so inserting a cascade statement above can + // never turn a delete into a 404 (see [`crate::domain::exam::Exam`]). + let slot = result.num_statements().saturating_sub(2); result - .take::>(ExamAttempt::FROZEN_SLOT + 2)? + .take::>(slot)? .into_iter() .next() .ok_or(AppError::NotFound) diff --git a/src/domain/exam_result.rs b/src/domain/exam_result.rs index ef54122..d44917e 100644 --- a/src/domain/exam_result.rs +++ b/src/domain/exam_result.rs @@ -2,8 +2,11 @@ use std::collections::HashMap; use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::EXAM_RESULT_TABLE; +use crate::constant::{ + EXAM_RESULT_COUNT_FIELD, EXAM_RESULT_TABLE, KIND_REF_TABLE, REF_COUNT_FIELD, +}; use crate::database::Database; +use crate::domain::cap; use crate::domain::course::CourseId; use crate::domain::exam::ExamId; use crate::domain::key; @@ -17,6 +20,25 @@ pub(crate) fn draft_error() -> AppError { AppError::Conflict("this exam is a draft — publish it before grading") } +/// The reference counter for one exam kind — how many marks are written under +/// that name, and whether the school has retired it (see +/// [`crate::domain::cap`]). Keyed by the name itself: the kind is snapshotted +/// text on the exam, and this row is what makes "a kind nothing is graded under +/// may be removed" a decision two replicas can share. +pub(crate) fn kind_ref(kind: &str) -> RecordId { + RecordId::new(KIND_REF_TABLE, kind) +} + +/// The refusal a mark meets once its kind has left the school's list. The +/// mirror of the settings-side 409: whichever of the two writes reaches the +/// counter first, the other is told the name is no longer usable. +pub(crate) fn retired_kind_error(kind: &str) -> AppError { + AppError::ConflictOwned(format!( + "the '{kind}' exam kind has been removed from the school's settings — \ + add it back before grading this exam" + )) +} + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ExamResultId(RecordId); @@ -58,6 +80,14 @@ impl Mark { } } +/// What one mark write reports back: the stored row, and whether it replaced a +/// mark that was already there. +#[derive(Debug, Clone, SurrealValue)] +struct Written { + existed: bool, + result: ExamResult, +} + #[derive(Debug, Clone, SurrealValue)] pub struct ExamResult { id: ExamResultId, @@ -155,14 +185,54 @@ impl ExamResult { /// converge on one row instead of racing the unique index into a 500. /// Grading a retake writes a fresh mark at the current seq and never touches /// prior sittings' marks; the latest seq is the grade-of-record. + /// + /// `kind` is the exam's kind, and this is where a mark takes its reference + /// on it — claimed *before* the write, given back when the write turns out + /// to have been an overwrite (one mark, one reference) or to have failed. A + /// kind the school has retired refuses the claim, which is the same + /// invariant the settings guard enforces from the other side, and the one + /// crash window left over-counts a kind (refusing a removal) rather than + /// letting a mark exist under a kind nothing counted. + /// + /// The exam's own `result_count` is claimed in the same breath, and it is + /// what a kind change is refused against: the exam PATCH pins that counter, + /// so a mark landing while it decides cannot slip past its gate and leave + /// itself counted under a kind its exam no longer carries. pub async fn grade( exam: &ExamId, user: &UserId, seq: i64, mark: Mark, graded_by: &UserId, + kind: &str, db: &Database, ) -> Result { + let counter = kind_ref(kind); + if !cap::claim_ref(&counter, 1, db).await? { + return Err(retired_kind_error(kind)); + } + cap::claim(&exam.record(), EXAM_RESULT_COUNT_FIELD, cap::UNLIMITED, db).await?; + let written = Self::write_mark(exam, user, seq, mark, graded_by, db).await; + match written { + // An overwrite is not a second mark: both counters go back, or a + // regrade would drift them upward and freeze the kind for good. + Ok(Written { existed: true, .. }) | Err(_) => { + cap::release_ref(&counter, 1, db).await?; + cap::release(&exam.record(), EXAM_RESULT_COUNT_FIELD, db).await?; + } + Ok(_) => {} + } + written.map(|written| written.result) + } + + async fn write_mark( + exam: &ExamId, + user: &UserId, + seq: i64, + mark: Mark, + graded_by: &UserId, + db: &Database, + ) -> Result { let result = ExamResult { id: ExamResultId::composite(exam, user, seq), exam: exam.clone(), @@ -176,11 +246,17 @@ impl ExamResult { // them, a mark and a re-draft racing each other can only ever leave one // of the two applied, whichever process either ran in. The caller's // pre-flight check answers the same 409 one round trip earlier. + // Whether the row was already there rides out of the transaction with + // the mark: the answer decides if this grade owes the kind a reference, + // and read anywhere else it would be a guess about a row two graders + // may be writing at once. let mut written = db .query( "BEGIN TRANSACTION; IF (SELECT VALUE draft FROM ONLY $exam) { THROW 'exam_draft' }; - UPSERT $id CONTENT $result RETURN AFTER; + LET $before = (SELECT VALUE id FROM ONLY $id); + LET $after = (UPSERT $id CONTENT $result RETURN AFTER); + RETURN { existed: $before != NONE, result: $after[0] }; COMMIT TRANSACTION;", ) .bind(("exam", exam.record())) @@ -197,9 +273,12 @@ impl ExamResult { if let Some(error) = errors.drain().map(|(_, error)| error).next() { return Err(error.into()); } - // BEGIN and the IF take a slot each. + // The trailing `RETURN` is always the last statement before `COMMIT`, + // so its slot follows the statement count instead of a hand-kept + // number — see `Exam::delete` for the bug the hand-kept one caused. + let slot = written.num_statements().saturating_sub(2); written - .take::>(2)? + .take::>(slot)? .into_iter() .next() .ok_or_else(|| AppError::Internal("failed to record exam result".into())) @@ -225,22 +304,6 @@ impl ExamResult { Ok(Self::latest_per_pair(result.take::>(0)?)) } - /// True iff any exam of `kind` has produced a mark — the settings guard - /// against removing an exam kind that grades already depend on (weights are - /// read live from settings, so dropping the kind would silently re-weight - /// those marks). - pub async fn any_for_kind(kind: &str, db: &Database) -> Result { - let mut result = db - .query( - "SELECT VALUE id FROM exam_result - WHERE exam IN (SELECT VALUE id FROM exam WHERE kind = $kind) LIMIT 1", - ) - .bind(("kind", kind.to_string())) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) - } - pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result, AppError> { let mut result = db .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC") @@ -269,18 +332,44 @@ impl ExamResult { Ok(result.take::>(0)?) } + /// Delete every sitting's mark for one (exam, user) pair. `kind` is the + /// exam's: the marks give their references back, so a kind nothing is + /// graded under any more can leave the settings again. pub async fn remove( exam: &ExamId, user: &UserId, + kind: &str, db: &Database, ) -> Result, AppError> { + // Both counters go back *inside* the delete's own transaction, driven + // off the rows this statement actually deleted. Counted outside it, a + // cascade (exam or course delete) taking the same rows in the gap would + // release them a second time, and on a kind another exam still grades + // under, one release too many reads as one mark too few — a kind + // wrongly free to leave the settings. let mut result = db - .query("DELETE exam_result WHERE exam = $ex AND user = $usr RETURN BEFORE") + .query(format!( + "BEGIN TRANSACTION; + LET $gone = (DELETE exam_result WHERE exam = $ex AND user = $usr RETURN BEFORE); + IF array::len($gone) > 0 {{ + UPDATE type::record('kind_ref', $kind) SET {REF_COUNT_FIELD} = + math::max([({REF_COUNT_FIELD} ?? 0) - array::len($gone), 0]); + UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = + math::max([({EXAM_RESULT_COUNT_FIELD} ?? 0) - array::len($gone), 0]); + }}; + RETURN $gone; + COMMIT TRANSACTION;" + )) .bind(("ex", exam.record())) .bind(("usr", user.record())) + .bind(("kind", kind.to_string())) .await? .check()?; - Ok(result.take::>(0)?.into_iter().next()) + // `RETURN` is the last statement before `COMMIT`; its slot follows the + // statement count, as in `Exam::delete`. + let slot = result.num_statements().saturating_sub(2); + let removed = result.take::>(slot)?; + Ok(removed.into_iter().next()) } } @@ -305,12 +394,28 @@ mod tests { let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); // Grade sitting #1, then a retake as sitting #2 — two rows, not one. - ExamResult::grade(&exam, &user, 1, Mark::try_new(40).unwrap(), &teacher, &db) - .await - .unwrap(); - let second = ExamResult::grade(&exam, &user, 2, Mark::try_new(90).unwrap(), &teacher, &db) - .await - .unwrap(); + ExamResult::grade( + &exam, + &user, + 1, + Mark::try_new(40).unwrap(), + &teacher, + "midterm", + &db, + ) + .await + .unwrap(); + let second = ExamResult::grade( + &exam, + &user, + 2, + Mark::try_new(90).unwrap(), + &teacher, + "midterm", + &db, + ) + .await + .unwrap(); assert_eq!(second.get_seq(), 2); // Grade-of-record is the latest sitting's mark. @@ -339,7 +444,9 @@ mod tests { ); // Deleting the pair removes every sitting. - ExamResult::remove(&exam, &user, &db).await.unwrap(); + ExamResult::remove(&exam, &user, "midterm", &db) + .await + .unwrap(); assert!( ExamResult::list_all_for_exam_user(&exam, &user, &db) .await diff --git a/src/domain/homework.rs b/src/domain/homework.rs index c8bf734..adbc0c0 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -13,8 +13,12 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; -use crate::constant::{HOMEWORK_TABLE, MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN}; +use crate::constant::{ + HOMEWORK_TABLE, MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN, + SUBJECT_HOMEWORK_COUNT_FIELD, +}; use crate::database::Database; +use crate::domain::cap; use crate::domain::course::CourseId; use crate::domain::field_update::FieldUpdate; use crate::domain::subject::SubjectId; @@ -156,6 +160,20 @@ impl Homework { created_by: &UserId, db: &Database, ) -> Result { + // Take the subject's reference before the row exists — the exam + // question's twin ([`crate::domain::exam_question::ExamQuestion`]): the + // subject delete is refused while this counter is non-zero, so the + // create and the delete contend on the subject record rather than on a + // cross-table count only one replica could see. A miss means the + // subject is already gone, which is the 400 the web layer's pre-flight + // check answers with. + let counted = subject.record(); + if !cap::claim(&counted, SUBJECT_HOMEWORK_COUNT_FIELD, cap::UNLIMITED, db).await? { + return Err(AppError::Validation(ValidationError::Invalid { + field: "subject_id", + reason: "subject does not exist", + })); + } let homework = Homework { id: HomeworkId::generate(), course: course.clone(), @@ -167,8 +185,20 @@ impl Homework { created_by: created_by.clone(), created_at: Timestamp::now(), }; - let created: Option = db.create(homework.id.record()).content(homework).await?; - created.ok_or_else(|| AppError::Internal("failed to create homework".into())) + let created: Result, AppError> = db + .create(homework.id.record()) + .content(homework) + .await + .map_err(AppError::from); + match created { + Ok(Some(homework)) => Ok(homework), + other => { + // Nothing landed, so the reference goes straight back. + cap::release(&counted, SUBJECT_HOMEWORK_COUNT_FIELD, db).await?; + other?; + Err(AppError::Internal("failed to create homework".into())) + } + } } pub async fn read(id: &HomeworkId, db: &Database) -> Result, AppError> { @@ -242,19 +272,6 @@ impl Homework { Ok(result.take::>(0)?) } - /// Whether any homework still references `subject` — the subject delete - /// guard's question: a subject with homework can't be deleted until the - /// homework is re-tagged or removed. Mirrors - /// [`crate::domain::exam_question::ExamQuestion::any_for_subject`]. - pub async fn any_for_subject(subject: &SubjectId, db: &Database) -> Result { - let mut result = db - .query("SELECT VALUE id FROM homework WHERE subject = $subject LIMIT 1") - .bind(("subject", subject.record())) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) - } - /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework. /// Request-scoped: every parameter is `Option`, `None` meaning the PATCH /// did not carry that field, so it is not written at all. Handing the @@ -279,14 +296,35 @@ impl Homework { ) -> Result { let assigned = assigned .map(|subset| subset.map(|users| users.iter().map(UserId::record).collect::>())); - FieldUpdate::new(self.id.record()) + // A re-tag moves a reference: claim the new subject before the write, + // release the old only after it lands, so neither is ever + // under-counted (the direction that would let a subject this homework + // points at be deleted). Same shape as the exam question's re-tag. + let retag = subject + .as_ref() + .filter(|next| **next != self.subject) + .map(|next| (next.record(), self.subject.record())); + if let Some((next, _)) = &retag + && !cap::claim(next, SUBJECT_HOMEWORK_COUNT_FIELD, cap::UNLIMITED, db).await? + { + return Err(AppError::Validation(ValidationError::Invalid { + field: "subject_id", + reason: "subject does not exist", + })); + } + let written = FieldUpdate::new(self.id.record()) .set("subject", subject.map(|subject| subject.record())) .set("title", title) .set("description", description) .set("due_at", due_at) .set("assigned", assigned) .run::(db) - .await + .await; + if let Some((next, previous)) = &retag { + let give_back = if written.is_ok() { previous } else { next }; + cap::release(give_back, SUBJECT_HOMEWORK_COUNT_FIELD, db).await?; + } + written } /// Delete the homework and cascade its submissions, their files, and its @@ -302,14 +340,21 @@ impl Homework { DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw); DELETE homework_submission WHERE homework = $hw; DELETE homework_result WHERE homework = $hw; - DELETE $hw RETURN BEFORE; + LET $gone = (DELETE $hw RETURN BEFORE); + FOR $sub IN ($gone.subject ?? []) { + UPDATE $sub SET homework_count = math::max([(homework_count ?? 0) - 1, 0]) + }; + RETURN $gone; COMMIT TRANSACTION;", ) .bind(("hw", self.id.record())) .await? .check()?; - // BEGIN is slot 0; the homework's own DELETE is slot 4. - let deleted: Option = result.take::>(4)?.into_iter().next(); + // The subject's reference is given back in this same transaction, off + // what the delete actually removed. Read through the trailing `RETURN`, + // not a hand-counted slot — see [`crate::domain::exam::Exam::delete`]. + let slot = result.num_statements().saturating_sub(2); + let deleted: Option = result.take::>(slot)?.into_iter().next(); deleted.ok_or(AppError::NotFound) } } diff --git a/src/domain/homework_file.rs b/src/domain/homework_file.rs index 02bc85f..04793b8 100644 --- a/src/domain/homework_file.rs +++ b/src/domain/homework_file.rs @@ -13,12 +13,13 @@ use ulid::Ulid; use crate::constant::{ HOMEWORK_FILE_TABLE, MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD, + SUBMISSION_OPEN_GUARD, }; use crate::database::Database; use crate::domain::cap; use crate::domain::course::CourseId; use crate::domain::homework::HomeworkId; -use crate::domain::homework_submission::HomeworkSubmissionId; +use crate::domain::homework_submission::{HomeworkSubmission, HomeworkSubmissionId}; use crate::domain::note_file::{FileContentType, FileName}; use crate::domain::timestamp::Timestamp; use crate::error::AppError; @@ -60,6 +61,16 @@ pub struct HomeworkFile { created_at: Timestamp, } +/// What [`HomeworkFile::delete`]'s transaction reports: whether the submission +/// was still open (`open` = 1, the gate bit) and the row it then removed. Two +/// answers in one object because an empty `gone` alone cannot say whether the +/// delete was refused or the file had simply vanished. +#[derive(Debug, SurrealValue)] +struct DeleteOutcome { + open: i64, + gone: Vec, +} + impl HomeworkFile { /// Assemble a row (fresh blob name generated here) without persisting it. /// The caller writes the blob under [`Self::get_file`] first, then calls @@ -111,20 +122,27 @@ impl HomeworkFile { } /// Persist the row assembled by [`Self::new`], refusing once its submission - /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`]. The slot is taken by - /// [`cap::claim`] on the submission row — a conditional single-record write, - /// the only guard that holds when the racing uploads are in two replicas, - /// the same story as `NoteFile::insert`. - pub async fn insert(self, db: &Database) -> Result { + /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`) + /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own + /// wording). Both are decided by one [`cap::claim_when`] on the submission + /// row — a conditional single-record write, the only guard that holds when + /// the racing writers are in two replicas, the same story as + /// `NoteFile::insert`. Which of the two conditions failed is read back + /// afterwards, off the losing path only, and only to pick the message. + pub async fn insert(self, db: &Database) -> Result, AppError> { let submission = self.submission.record(); - if !cap::claim( + if !cap::claim_when( &submission, SUBMISSION_FILE_COUNT_FIELD, MAX_HOMEWORK_FILES_PER_SUBMISSION as i64, + SUBMISSION_OPEN_GUARD, db, ) .await? { + if HomeworkSubmission::is_graded(&self.submission, db).await? { + return Ok(None); + } return Err(AppError::Conflict( "the submission already holds the maximum of 10 files — delete one first", )); @@ -133,7 +151,7 @@ impl HomeworkFile { let created: Result, _> = db.create(self.id.record()).content(self).await; match created { - Ok(Some(created)) => Ok(created), + Ok(Some(created)) => Ok(Some(created)), Ok(None) => { cap::release(&submission, SUBMISSION_FILE_COUNT_FIELD, db).await?; Err(AppError::Internal("failed to create homework file".into())) @@ -242,23 +260,44 @@ impl HomeworkFile { /// Delete the row and give its slot back in the same transaction. The /// submission survives, so its counter has to be corrected; the cascades /// that delete the submission itself take the counter with it. - pub async fn delete(self, db: &Database) -> Result { + /// + /// The gate is the first statement: a conditional write on the *submission* + /// row — the "last touched" re-stamp a file delete owes the late flag + /// anyway — carrying [`SUBMISSION_OPEN_GUARD`]. Nothing else in the + /// transaction runs unless it bit, so a grade landing concurrently either + /// stamps first (this delete is refused, `Ok(None)`) or stamps after (the + /// file was already gone when it graded). `Err(NotFound)` still means the + /// file row itself had vanished. + pub async fn delete(self, db: &Database) -> Result, AppError> { let mut result = db - .query( + .query(format!( "BEGIN TRANSACTION; - LET $gone = (DELETE $id RETURN BEFORE); + LET $open = (UPDATE $sub SET updated_at = $now \ + WHERE {SUBMISSION_OPEN_GUARD} RETURN VALUE id); + LET $gone = IF array::len($open) > 0 {{ (DELETE $id RETURN BEFORE) }} ELSE {{ [] }}; UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); - RETURN $gone; - COMMIT TRANSACTION;", - ) + RETURN {{ open: array::len($open), gone: $gone }}; + COMMIT TRANSACTION;" + )) .bind(("id", self.id.record())) .bind(("sub", self.submission.record())) + .bind(("now", Timestamp::now())) .await? .check()?; - result - .take::>(3)? + // BEGIN is slot 0, the two LETs slots 1-2 and the counter fix slot 3; + // the RETURN is slot 4. + let outcome: Option = + result.take::>(4)?.into_iter().next(); + let outcome = + outcome.ok_or_else(|| AppError::Internal("failed to delete homework file".into()))?; + if outcome.open == 0 { + return Ok(None); + } + outcome + .gone .into_iter() .next() + .map(Some) .ok_or(AppError::NotFound) } } @@ -286,6 +325,7 @@ mod tests { // A real submission row, so the GC join through it resolves. let submission = HomeworkSubmission::upsert(&homework, &user, None, &db) .await + .unwrap() .unwrap(); let sub_a = submission.get_id().clone(); let sub_b = HomeworkSubmissionId::composite( @@ -293,7 +333,7 @@ mod tests { &UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"), ); - let stored = a_file(&sub_a).insert(&db).await.unwrap(); + let stored = a_file(&sub_a).insert(&db).await.unwrap().unwrap(); // Readable under its own submission, invisible under another. assert!( HomeworkFile::read_for(stored.get_id(), &sub_a, &db) @@ -342,11 +382,61 @@ mod tests { // Fill to the cap, then the 11th is refused. for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION { - a_file(&sub_a).insert(&db).await.unwrap(); + a_file(&sub_a).insert(&db).await.unwrap().unwrap(); } assert!(matches!( a_file(&sub_a).insert(&db).await, Err(AppError::Conflict(_)) )); } + + /// A graded submission takes no more files and gives none up — decided by + /// the same conditional write that claims the file slot, so no + /// `homework_result` read stands between the check and the write. + /// + /// Bite check: drop [`SUBMISSION_OPEN_GUARD`] from `insert`'s + /// [`cap::claim_when`] and the add below lands; drop it from `delete`'s gate + /// and the delete below succeeds. + #[tokio::test] + async fn a_grade_freezes_the_files_too() { + use crate::domain::homework_result::{HomeworkResult, HomeworkStatus}; + + let db = crate::database::init_mem().await.unwrap(); + let homework = HomeworkId::from_key("01TESTHWAAAAAAAAAAAAAAAAAA"); + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + let submission = HomeworkSubmission::upsert(&homework, &user, None, &db) + .await + .unwrap() + .unwrap(); + let sub = submission.get_id().clone(); + let stored = a_file(&sub).insert(&db).await.unwrap().unwrap(); + + HomeworkResult::grade( + &homework, + &user, + HomeworkStatus::try_new("done").unwrap(), + None, + &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), + &db, + ) + .await + .unwrap(); + + // Neither adding nor removing an attachment: `None` is the freeze, and + // the cap's own `Err(Conflict)` stays distinct from it. + assert!(a_file(&sub).insert(&db).await.unwrap().is_none()); + assert!(stored.clone().delete(&db).await.unwrap().is_none()); + assert_eq!( + HomeworkFile::count_for_submission(&sub, &db).await.unwrap(), + 1, + "the graded submission keeps exactly the files it was graded on" + ); + // The refused add took no slot either, so un-grading gives back a + // submission with room, not one that silently lost nine. + HomeworkResult::remove(&homework, &user, &db).await.unwrap(); + for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION { + a_file(&sub).insert(&db).await.unwrap().unwrap(); + } + assert!(stored.delete(&db).await.unwrap().is_some()); + } } diff --git a/src/domain/homework_result.rs b/src/domain/homework_result.rs index 3b459da..c965d4b 100644 --- a/src/domain/homework_result.rs +++ b/src/domain/homework_result.rs @@ -13,11 +13,12 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::HOMEWORK_RESULT_TABLE; +use crate::constant::{HOMEWORK_RESULT_TABLE, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD}; use crate::database::Database; use crate::domain::course::CourseId; use crate::domain::exam_result::Mark; use crate::domain::homework::HomeworkId; +use crate::domain::homework_submission::HomeworkSubmissionId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -119,6 +120,22 @@ impl HomeworkResult { /// UPSERT — concurrent grades for the same pair converge on one row instead /// of racing a unique index into a 500. Grading before the due date, or /// before any submission exists, is allowed (the caller's policy call). + /// + /// In the same transaction the grade *stamps* the student's submission + /// ([`crate::constant::SUBMISSION_GRADED_FIELD`]), which is what freezes it: + /// every student-side write to that row then fails its own + /// `graded_by_result = NONE` condition, with no cross-table read for a peer + /// replica to slip past. A submission that does not exist yet is left alone + /// — grading absent work must not conjure a hand-in (the report reads + /// `submitted`/`missing`/`late` straight off that row). + // + // ponytail: that one case keeps a residual race — a student's *first* hand-in + // committing between this grade and nothing-to-stamp lands unstamped, so a + // grade of never-submitted work can end up beside an editable submission. + // The web layer's pre-flight read still refuses it whenever the grade landed + // first, so only a genuine collision slips through. Closing it needs a row to + // stamp: either a tombstone submission every read path learns to ignore, or + // moving the freeze onto a per-(homework, user) record both sides own. pub async fn grade( homework: &HomeworkId, user: &UserId, @@ -127,8 +144,10 @@ impl HomeworkResult { graded_by: &UserId, db: &Database, ) -> Result { + let id = HomeworkResultId::composite(homework, user); + let submission = HomeworkSubmissionId::composite(homework, user); let result = HomeworkResult { - id: HomeworkResultId::composite(homework, user), + id: id.clone(), homework: homework.clone(), user: user.clone(), status, @@ -136,8 +155,25 @@ impl HomeworkResult { graded_by: graded_by.clone(), created_at: Timestamp::now(), }; - let saved: Option = db.upsert(result.id.record()).content(result).await?; - saved.ok_or_else(|| AppError::Internal("failed to record homework result".into())) + let mut saved = db + .query(format!( + "BEGIN TRANSACTION; + UPSERT $id CONTENT $row RETURN AFTER; + UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = $id \ + WHERE {SUBMISSION_OPEN_GUARD}; + COMMIT TRANSACTION;" + )) + .bind(("id", id.record())) + .bind(("sub", submission.record())) + .bind(("row", result.into_value())) + .await? + .check()?; + // BEGIN is slot 0; the result's UPSERT is slot 1, the stamp slot 2. + saved + .take::>(1)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to record homework result".into())) } /// `user`'s grade for `homework`, if graded. @@ -186,19 +222,33 @@ impl HomeworkResult { } /// Un-grade (homework, user), returning the removed row (`None` if there - /// was none). Removing the grade unfreezes the student's submission. + /// was none). Removing the grade unfreezes the student's submission, so the + /// stamp [`grade`](Self::grade) left on it is cleared in the same + /// transaction — scoped to *this* grade's id, so it can never wipe a stamp a + /// concurrent re-grade has just written. pub async fn remove( homework: &HomeworkId, user: &UserId, db: &Database, ) -> Result, AppError> { + let id = HomeworkResultId::composite(homework, user); let mut result = db - .query("DELETE homework_result WHERE homework = $hw AND user = $usr RETURN BEFORE") - .bind(("hw", homework.record())) - .bind(("usr", user.record())) + .query(format!( + "BEGIN TRANSACTION; + DELETE $id RETURN BEFORE; + UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = NONE \ + WHERE {SUBMISSION_GRADED_FIELD} = $id; + COMMIT TRANSACTION;" + )) + .bind(("id", id.record())) + .bind(( + "sub", + HomeworkSubmissionId::composite(homework, user).record(), + )) .await? .check()?; - Ok(result.take::>(0)?.into_iter().next()) + // BEGIN is slot 0; the grade's DELETE is slot 1, the unstamp slot 2. + Ok(result.take::>(1)?.into_iter().next()) } } diff --git a/src/domain/homework_submission.rs b/src/domain/homework_submission.rs index a87183f..79ed7d1 100644 --- a/src/domain/homework_submission.rs +++ b/src/domain/homework_submission.rs @@ -14,7 +14,10 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{HOMEWORK_SUBMISSION_TABLE, MAX_HOMEWORK_TEXT_LEN}; +use crate::constant::{ + HOMEWORK_SUBMISSION_TABLE, MAX_HOMEWORK_TEXT_LEN, SUBMISSION_GRADED_FIELD, + SUBMISSION_OPEN_GUARD, +}; use crate::database::Database; use crate::domain::homework::HomeworkId; use crate::domain::timestamp::Timestamp; @@ -100,9 +103,10 @@ impl HomeworkSubmission { self.updated_at } - /// Create or re-stamp `user`'s submission to `homework`. `updated_at` moves - /// to now every time; `submitted_at` (readonly, the first-submit stamp) is - /// kept on an existing row and set only on a fresh one. + /// Create or re-stamp `user`'s submission to `homework`, unless a grade has + /// frozen it — `None` means frozen, and the caller answers 409. `updated_at` + /// moves to now every time; `submitted_at` (readonly, the first-submit stamp) + /// is kept on an existing row and set only on a fresh one. /// /// Hand-written rather than `.content()` on purpose: `.content()` re-sends /// the whole row, so it would carry a `submitted_at`, and any value differing @@ -110,20 +114,26 @@ impl HomeworkSubmission { /// `submitted_at = submitted_at ?? $now` expression preserves it inside the /// one UPSERT statement — race-free without a lock, where a read-then-content /// could let two concurrent first-submits pick different stamps and 500. + /// + /// The `WHERE` is the freeze: [`SUBMISSION_OPEN_GUARD`] makes "not graded + /// yet" a condition of this very write instead of a read the grading replica + /// can land behind. An absent row satisfies it (the stamp is `NONE` there + /// too), so a first submit still creates. pub async fn upsert( homework: &HomeworkId, user: &UserId, text: Option, db: &Database, - ) -> Result { + ) -> Result, AppError> { let id = HomeworkSubmissionId::composite(homework, user); let now = Timestamp::now(); let text = text.map(|text| text.as_str().to_string()); let mut saved = db - .query( + .query(format!( "UPSERT $id SET homework = $hw, user = $usr, text = $text, \ - updated_at = $now, submitted_at = submitted_at ?? $now RETURN AFTER", - ) + updated_at = $now, submitted_at = submitted_at ?? $now \ + WHERE {SUBMISSION_OPEN_GUARD} RETURN AFTER" + )) .bind(("id", id.record())) .bind(("hw", homework.record())) .bind(("usr", user.record())) @@ -131,11 +141,7 @@ impl HomeworkSubmission { .bind(("now", now)) .await? .check()?; - saved - .take::>(0)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to save homework submission".into())) + Ok(saved.take::>(0)?.into_iter().next()) } /// Re-stamp a submission's `updated_at` to now, leaving its text and files @@ -163,6 +169,20 @@ impl HomeworkSubmission { .ok_or(AppError::NotFound) } + /// Whether a grade has frozen this submission. Only ever read to tell two + /// refusals apart *after* a conditional write has already refused one — the + /// stamp on the row, never this read, is what decides. + pub async fn is_graded(id: &HomeworkSubmissionId, db: &Database) -> Result { + let mut result = db + .query(format!( + "SELECT VALUE id FROM $id WHERE {SUBMISSION_GRADED_FIELD} != NONE" + )) + .bind(("id", id.record())) + .await? + .check()?; + Ok(!result.take::>(0)?.is_empty()) + } + /// `user`'s submission to `homework`, if they have one. pub async fn read_for( homework: &HomeworkId, @@ -192,25 +212,27 @@ impl HomeworkSubmission { /// can't leave a file pointing at a vanished submission. The file *blobs* /// are the web layer's to unlink: it lists them /// ([`crate::domain::homework_file::HomeworkFile::list_for_submission`]) - /// before calling this. The caller has already refused the delete if the - /// submission is graded (a result exists). - pub async fn delete(self, db: &Database) -> Result { + /// before calling this. `None` means a grade froze the row (the caller + /// answers 409): the submission's own delete carries + /// [`SUBMISSION_OPEN_GUARD`], and the file wipe is conditional on it having + /// bitten, so a refused delete leaves the children standing too. + pub async fn delete(self, db: &Database) -> Result, AppError> { let mut result = db - .query( + .query(format!( "BEGIN TRANSACTION; - DELETE homework_file WHERE submission = $sub; - DELETE $sub RETURN BEFORE; - COMMIT TRANSACTION;", - ) + LET $gone = (DELETE $sub WHERE {SUBMISSION_OPEN_GUARD} RETURN BEFORE); + IF array::len($gone) > 0 {{ DELETE homework_file WHERE submission = $sub }}; + RETURN $gone; + COMMIT TRANSACTION;" + )) .bind(("sub", self.id.record())) .await? .check()?; - // BEGIN is slot 0, the file wipe slot 1; the submission's DELETE is slot 2. - let deleted: Option = result - .take::>(2)? + // BEGIN is slot 0, the LET slot 1 and the IF slot 2; the RETURN is slot 3. + Ok(result + .take::>(3)? .into_iter() - .next(); - deleted.ok_or(AppError::NotFound) + .next()) } } @@ -238,11 +260,13 @@ mod tests { &db, ) .await + .unwrap() .unwrap(); // A re-submit lands on the same row: submitted_at (the first hand-in) // pinned, updated_at moves forward, and the text can be cleared. let second = HomeworkSubmission::upsert(&homework, &user, None, &db) .await + .unwrap() .unwrap(); assert_eq!(first.get_id(), second.get_id()); assert_eq!(first.get_submitted_at(), second.get_submitted_at()); @@ -258,6 +282,92 @@ mod tests { ); } + /// The freeze, as stored state rather than as a race: the grade stamps the + /// submission row, and from then on the submission's own writes fail their + /// condition — no read of `homework_result` involved, which is what makes it + /// hold when the grader is in the other replica. Un-grading clears the stamp + /// and the row is writable again. + /// + /// Bite check: drop `WHERE graded_by_result = NONE` from + /// [`HomeworkSubmission::upsert`] and the "version B" upsert below comes + /// back `Some` — the exact swap this guards against. + #[tokio::test] + async fn a_grade_freezes_the_submission_row_itself() { + let db = crate::database::init_mem().await.unwrap(); + let homework = HomeworkId::from_key("01TESTHWAAAAAAAAAAAAAAAAAA"); + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + let graded = |value| { + let text = SubmissionText::try_new(value).unwrap(); + HomeworkSubmission::upsert(&homework, &user, Some(text), &db) + }; + + let version_a = graded("version A").await.unwrap().unwrap(); + assert!( + !HomeworkSubmission::is_graded(version_a.get_id(), &db) + .await + .unwrap() + ); + + crate::domain::homework_result::HomeworkResult::grade( + &homework, + &user, + crate::domain::homework_result::HomeworkStatus::try_new("done").unwrap(), + None, + &teacher, + &db, + ) + .await + .unwrap(); + assert!( + HomeworkSubmission::is_graded(version_a.get_id(), &db) + .await + .unwrap() + ); + + // The swap the teacher would never see: refused, and the stored text is + // still the version that was graded. + assert!(graded("version B").await.unwrap().is_none()); + assert_eq!( + HomeworkSubmission::read_for(&homework, &user, &db) + .await + .unwrap() + .and_then(|row| row.get_text().map(|text| text.as_str().to_string())), + Some("version A".to_string()) + ); + // ... and so is withdrawing it wholesale. + let frozen = HomeworkSubmission::read_for(&homework, &user, &db) + .await + .unwrap() + .unwrap(); + assert!(frozen.delete(&db).await.unwrap().is_none()); + assert!( + HomeworkSubmission::read_for(&homework, &user, &db) + .await + .unwrap() + .is_some() + ); + + // Un-grading unfreezes it, stamp and all. + crate::domain::homework_result::HomeworkResult::remove(&homework, &user, &db) + .await + .unwrap(); + assert!( + !HomeworkSubmission::is_graded(version_a.get_id(), &db) + .await + .unwrap() + ); + let reopened = graded("version B").await.unwrap().unwrap(); + assert_eq!( + reopened.get_text().map(SubmissionText::as_str), + Some("version B") + ); + // The two-stamp lateness rule is untouched by any of it: the first + // hand-in is still the first hand-in. + assert_eq!(reopened.get_submitted_at(), version_a.get_submitted_at()); + assert!(reopened.get_updated_at() >= version_a.get_updated_at()); + } + #[tokio::test] async fn touch_moves_updated_at_but_not_submitted_at_or_text() { let db = crate::database::init_mem().await.unwrap(); @@ -271,6 +381,7 @@ mod tests { &db, ) .await + .unwrap() .unwrap(); // A file add/delete touches the submission: updated_at moves (never // backwards), while the first-submit stamp and the text stay put. diff --git a/src/domain/meal_booking.rs b/src/domain/meal_booking.rs index c821d6b..fdc370e 100644 --- a/src/domain/meal_booking.rs +++ b/src/domain/meal_booking.rs @@ -10,21 +10,30 @@ //! auditable against the money it moved. Only `booked` rows count against //! the menu's capacity, which is what makes the seat genuinely free again — //! and re-booking is the same UPSERT flipping it back. -//! - **The capacity check runs under [`MENU_LOCK`]**, the lock that already -//! serializes everything counting rows against one menu. Count-then-write is -//! write-skew: SurrealDB's transactions do not conflict-check a cross-record -//! count against a concurrent insert, so an unlocked check over-admits. -//! - **The seat and its money move together, inside that lock.** Booking -//! charges and cancelling reverses right here, not in the web layer after the -//! lock was dropped — a seam between the two let concurrent `POST`s bill one -//! seat twice. The lock stays a *leaf*: nothing below it takes another. +//! - **Capacity is the menu's `seats_booked` counter**, claimed by a +//! conditional single-record write ([`cap`]). Counting the rows instead is +//! write-skew — SurrealDB does not conflict-check a cross-record count +//! against a concurrent insert — and a process-wide lock around that count +//! only holds inside one replica, which the school no longer runs one of. +//! Cancelling gives the seat back in the *same transaction* as the flip. +//! - **The price is claimed, not just read.** The seat is taken at the menu +//! revision the price was read at, in the same transaction as the row +//! ([`MealBooking::claim_and_place`]), so a dish re-priced mid-booking loses +//! the claim and the booking re-reads both. A seat can only ever be billed a +//! price its menu genuinely carried. +//! - **The seat and its money move together.** Booking charges and cancelling +//! reverses right here, not in the web layer — a seam between the two let +//! concurrent `POST`s bill one seat twice. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::MEAL_BOOKING_TABLE; -use crate::database::Database; +use crate::constant::{ + CAS_UPDATE_RETRIES, MEAL_BOOKING_TABLE, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD, +}; +use crate::database::{Database, lost_the_race}; +use crate::domain::cap::{self, Claimed}; use crate::domain::meal_ledger::{LedgerAmount, MealLedger}; -use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot}; +use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot}; use crate::domain::page::PagedList; use crate::domain::settings::{MealSlotDef, Settings}; use crate::domain::timestamp::Timestamp; @@ -140,24 +149,23 @@ impl MealBooking { } /// Book (idempotently) `student` onto `menu` **and bill the seat**. Already - /// booked is returned as-is; a cancelled row is revived by the same UPSERT, - /// as a fresh attempt at the current `price`. When the menu carries a - /// capacity, a full one refuses new seats (409) — the whole - /// check-then-write runs under [`MENU_LOCK`], and the cap is re-derived - /// from a fresh menu read inside it, since neither the transaction model - /// nor a caller-supplied menu survives a concurrent capacity PATCH. + /// booked is returned as-is, claiming nothing; a cancelled row is revived as + /// a fresh attempt at the current price. A full menu refuses the seat (409), + /// decided by the counter's own `WHERE` rather than by a count this process + /// took a moment ago. /// - /// The price is snapshotted **inside that same lock**, not handed in by the - /// web layer: dish writes take the lock too, so the sum frozen onto the row - /// is the menu as it stood the instant the seat was taken. Snapshotted - /// outside it, a dish landing in the gap was stored as `None` = "was free - /// then" — and no repeat `POST` ever heals that, since a held seat is - /// returned as-is. + /// The price is read from the menu and then **claimed with it**: the seat is + /// only taken while the menu still stands at the revision the price was read + /// at, so a dish added, re-priced or removed in that gap loses the claim and + /// the whole decision is made again on fresh figures. What is frozen onto + /// the row is therefore always a price the menu genuinely carried at the + /// instant the seat was taken — the guarantee a lock could only give inside + /// one replica. /// - /// The charge is appended inside the lock too, keyed by (seat, attempt): - /// eight concurrent `POST`s of one seat hold one seat and write one charge - /// line. The price is `None` when the menu is free, and that `None` is - /// stored, so a dish added later never bills a seat retroactively. + /// The charge is appended after, keyed by (seat, attempt): eight concurrent + /// `POST`s of one seat hold one seat and write one charge line. The price is + /// `None` when the menu is free, and that `None` is stored, so a dish added + /// later never bills a seat retroactively. /// /// `cutoff` is the school's one meal deadline (see [`MealCutoff`]): once /// serving time is that close, the seat is fixed either way. @@ -168,60 +176,167 @@ impl MealBooking { cutoff: &MealCutoff, db: &Database, ) -> Result { - let _guard = MENU_LOCK.lock().await; - let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?; - check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?; - // Before the seat: an unchargeable menu (dishes summing past the cap) - // must refuse the booking outright, never leave a booked-but-unbilled - // row behind. - let price = MealLedger::price_snapshot(menu, db).await?; let id = MealBookingId::composite(menu, student); - let existing: Option = db.select(id.record()).await?; - let booking = match existing { + let seats = menu.record(); + for _ in 0..CAS_UPDATE_RETRIES { + let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?; + check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?; + // Before the seat: an unchargeable menu (dishes summing past the + // cap) must refuse the booking outright, never leave a + // booked-but-unbilled row behind. + let price = MealLedger::price_snapshot(menu, db).await?; + let existing: Option = db.select(id.record()).await?; // The seat is already held: same attempt, same price it was taken - // at. Today's menu price bills nobody who booked yesterday's. - Some(held) if held.status == MealBookingStatus::Booked => held, - existing => { - if let Some(capacity) = fresh.get_capacity() - && Self::list_live_for_menu(menu, db).await?.len() as i64 >= capacity - { - return Err(AppError::Conflict("the menu is fully booked")); - } - let booking = MealBooking { - id, - menu: menu.clone(), - student: student.clone(), - // `booked_by` and `created_at` are READONLY columns: a - // revived row keeps whoever opened the seat, and when. - booked_by: existing - .as_ref() - .map_or_else(|| booked_by.clone(), |row| row.booked_by.clone()), - status: MealBookingStatus::Booked, - attempt: existing.as_ref().map_or(1, |row| row.attempt + 1), - price_minor: price, - cancelled_at: None, - created_at: existing - .as_ref() - .map_or_else(Timestamp::now, |row| row.created_at), - }; - let saved: Option = - db.upsert(booking.id.record()).content(booking).await?; - saved.ok_or_else(|| AppError::Internal("failed to book the meal".into()))? + // at. Today's menu price bills nobody who booked yesterday's. No + // seat is claimed, so a double-click cannot count two. + if let Some(held) = existing + .clone() + .filter(|row| row.status == MealBookingStatus::Booked) + { + MealLedger::charge_booking(&held, booked_by, db).await?; + return Ok(held); } - }; - // Writes nothing when this attempt is already billed, so the repeat - // POST above costs nothing and a charge that failed once self-heals. - MealLedger::charge_booking(&booking, booked_by, db).await?; - Ok(booking) + let fresh_row = MealBooking { + id: id.clone(), + menu: menu.clone(), + student: student.clone(), + booked_by: booked_by.clone(), + status: MealBookingStatus::Booked, + attempt: 1, + price_minor: price, + cancelled_at: None, + created_at: Timestamp::now(), + }; + let booking = match Self::claim_and_place( + &seats, + fresh.get_capacity().unwrap_or(cap::UNLIMITED), + fresh.get_version(), + &fresh_row, + price, + db, + ) + .await? + { + Claimed::Made(booking) => booking, + // Another `POST` of this very pair placed the row first, and it + // owed no second seat: this caller never took one (the whole + // transaction rolled back), so the winner's row is the answer. + Claimed::Duplicate => Self::read(&id, db).await?.ok_or(AppError::NotFound)?, + // Full, moved, or gone — one `WHERE` refused all three, so the + // reason is re-read rather than guessed. A moved menu is not a + // refusal: the price above is stale, so price and seat are + // taken again together. + Claimed::Full => match Menu::read(menu, db).await? { + None => return Err(AppError::NotFound), + Some(now) if now.get_version() != fresh.get_version() => continue, + Some(_) => return Err(AppError::Conflict("the menu is fully booked")), + }, + }; + // Writes nothing when this attempt is already billed, so the repeat + // POST above costs nothing and a charge that failed once self-heals. + MealLedger::charge_booking(&booking, booked_by, db).await?; + return Ok(booking); + } + Err(AppError::Conflict( + "the menu kept changing underneath this booking", + )) + } + + /// Take the seat **and** place the row in one transaction, at the menu + /// revision the price was read at. + /// + /// The seat and the row cannot be two steps. The id is the (menu, student) + /// pair, so two `POST`s of the same seat both find no row and both claim — + /// and on a tight cap the second is then told "full" for a seat it never + /// owed, while the winner's row may not even be visible yet. Here the + /// duplicate `CREATE` aborts the transaction, which takes its increment with + /// it: the counter never counts a row that does not exist, and a loser is + /// answered with the winner's booking instead of a refusal. Same shape as + /// [`cap::claim_and_create`], with the revision guard and the revival of a + /// cancelled row that the general form does not carry. + /// + /// A cancelled row is revived in place (a fresh attempt at `price`) rather + /// than recreated: `booked_by` and `created_at` are READONLY history — who + /// opened the seat, and when. + async fn claim_and_place( + seats: &RecordId, + cap: i64, + seen: i64, + row: &MealBooking, + price: Option, + db: &Database, + ) -> Result, AppError> { + // Parenthesized `??` throughout: `a ?? 0 = $seen` binds the wrong way. + let sql = format!( + "BEGIN TRANSACTION; + LET $held = (SELECT VALUE id FROM $id WHERE status = 'booked'); + IF array::len($held) > 0 {{ THROW 'held' }}; + LET $seat = (UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = \ + ({MENU_SEAT_COUNT_FIELD} ?? 0) + 1 \ + WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) < $cap \ + AND ({MENU_VERSION_FIELD} ?? 0) = $seen RETURN VALUE id); + IF array::len($seat) = 0 {{ THROW 'no_seat' }}; + LET $revived = (UPDATE $id SET status = 'booked', attempt = attempt + 1, \ + price_minor = $price, cancelled_at = NONE \ + WHERE status = 'cancelled' RETURN AFTER); + IF array::len($revived) = 0 {{ CREATE $id CONTENT $row }}; + RETURN SELECT * FROM ONLY $id; + COMMIT TRANSACTION;" + ); + for _ in 0..CAS_UPDATE_RETRIES { + let mut result = match db + .query(sql.as_str()) + .bind(("menu", seats.clone())) + .bind(("cap", cap)) + .bind(("seen", seen)) + .bind(("id", row.id.record())) + .bind(("price", price)) + .bind(("row", row.clone())) + .await + { + Ok(result) => result, + Err(err) if lost_the_race(&err) => continue, + Err(err) => return Err(err.into()), + }; + // An aborted transaction errors *every* slot, most with a generic + // "not executed" — only the failing slot says why, so scan them all. + let mut errors = result.take_errors(); + if errors + .values() + .any(|error| error.to_string().contains("no_seat")) + { + return Ok(Claimed::Full); + } + if errors + .values() + .any(|error| error.to_string().contains("held") || error.is_already_exists()) + { + return Ok(Claimed::Duplicate); + } + if errors.values().any(lost_the_race) { + continue; + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Slots count BEGIN, three LETs and three IFs: the RETURN is slot 7. + return match result.take::>(7)? { + Some(placed) => Ok(Claimed::Made(placed)), + None => Err(AppError::Internal("failed to book the meal".into())), + }; + } + Err(AppError::Conflict( + "the menu kept changing underneath this booking", + )) } /// Free the seat: flip to `cancelled`, stamp the moment, **and give the /// money back**. Refused (409) only once the cutoff has passed. /// - /// Under [`MENU_LOCK`] like [`Self::book`], and the row is re-read inside - /// it: the caller's copy may predate a concurrent re-book, and cancelling a - /// stale attempt would strand that attempt's charge forever. The reversal - /// is keyed to the attempt, so a retried cancel refunds exactly once. + /// The row is re-read here and the flip is conditional on it still being + /// `booked`: the caller's copy may predate a concurrent re-book, and + /// cancelling a stale attempt would strand that attempt's charge forever. + /// The reversal is keyed to the attempt, so a retried cancel refunds once. /// /// **Idempotent, and that is what makes the refund recoverable.** The flip /// and the reversal are two writes; a handler future dropped between them @@ -239,7 +354,6 @@ impl MealBooking { recorded_by: &UserId, db: &Database, ) -> Result { - let _guard = MENU_LOCK.lock().await; let fresh = Self::read(&self.id, db).await?.ok_or(AppError::NotFound)?; if fresh.status == MealBookingStatus::Cancelled { MealLedger::reverse_booking(&fresh, recorded_by, db).await?; @@ -249,19 +363,62 @@ impl MealBooking { .await? .ok_or(AppError::NotFound)?; check_cutoff(menu.get_date(), menu.get_slot(), cutoff)?; - let cancelled = MealBooking { - status: MealBookingStatus::Cancelled, - cancelled_at: Some(Timestamp::now()), - ..fresh + // Lost the flip to a concurrent cancel: its row is the truth, and the + // reversal replay below heals whatever it left unfinished. + let saved = match Self::release_seat(&fresh, db).await? { + Some(cancelled) => cancelled, + None => Self::read(&self.id, db).await?.ok_or(AppError::NotFound)?, }; - let saved: Option = - db.upsert(cancelled.id.record()).content(cancelled).await?; - let saved = - saved.ok_or_else(|| AppError::Internal("failed to cancel the booking".into()))?; MealLedger::reverse_booking(&saved, recorded_by, db).await?; Ok(saved) } + /// Flip the seat to `cancelled` and give it back to the menu's counter **in + /// one transaction**, so the two can never disagree: a decrement that ran + /// without the flip frees a seat still held, and a flip without the + /// decrement locks a seat nothing can ever release. The counter follows the + /// flip's own result (`array::len`), so a row already cancelled — by a + /// racing cancel, or by this call retried — decrements nothing. + /// + /// `None` = the row was not `booked` any more. Retried while the store + /// reports a write conflict: the menu row is contended by every booking on + /// it, and that contention is the cap working, not an error. + async fn release_seat( + booked: &MealBooking, + db: &Database, + ) -> Result, AppError> { + for _ in 0..CAS_UPDATE_RETRIES { + let attempted = async { + let mut result = db + .query(format!( + "BEGIN TRANSACTION; + LET $flipped = (UPDATE $id SET status = 'cancelled', \ + cancelled_at = $now WHERE status = 'booked' RETURN AFTER); + UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = math::max([\ + ({MENU_SEAT_COUNT_FIELD} ?? 0) - array::len($flipped), 0]); + RETURN $flipped; + COMMIT TRANSACTION;" + )) + .bind(("id", booked.id.record())) + .bind(("menu", booked.menu.record())) + .bind(("now", Timestamp::now())) + .await? + .check()?; + // Slots count BEGIN and the LET: the RETURN is slot 3. + result.take::>(3) + } + .await; + match attempted { + Ok(rows) => return Ok(rows.into_iter().next()), + Err(err) if lost_the_race(&err) => {} + Err(err) => return Err(err.into()), + } + } + Err(AppError::Conflict( + "the menu kept changing underneath this cancellation", + )) + } + pub async fn read(id: &MealBookingId, db: &Database) -> Result, AppError> { Ok(db.select(id.record()).await?) } @@ -282,33 +439,6 @@ impl MealBooking { .await } - /// The seats actually held — the capacity count. - pub async fn list_live_for_menu( - menu: &MenuId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM meal_booking WHERE menu = $menu AND status = 'booked'") - .bind(("menu", menu.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// True iff a seat on the menu is still held — the menu delete guard. - /// Callers hold [`MENU_LOCK`] so a booking cannot slip in behind it. - pub async fn any_live_for_menu(menu: &MenuId, db: &Database) -> Result { - let mut result = db - .query( - "SELECT VALUE id FROM meal_booking \ - WHERE menu = $menu AND status = 'booked' LIMIT 1", - ) - .bind(("menu", menu.record())) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) - } - /// Every seat held for one of `students`, newest first — a caller's own /// list is themselves plus whoever they hold a *live* parent link to. /// @@ -411,6 +541,7 @@ mod tests { use surrealdb::types::Value; use super::*; + use crate::domain::menu_dish::{DishName, DishPrice, DishTags, MenuDish}; /// The `status` column is `TYPE string`: an object-wrapped enum would be /// rejected on write, and the `status = 'booked'` capacity count would @@ -424,6 +555,246 @@ mod tests { } } + /// A published menu on a fresh in-memory database, plus a student. + async fn menu(capacity: Option) -> (Database, MenuId) { + let db = crate::database::init_mem().await.unwrap(); + let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()]; + let menu = Menu::create( + MenuDate::try_new("2026-09-14").unwrap(), + MenuSlot::try_new("lunch", &slots).unwrap(), + capacity, + &UserId::generate(), + &db, + ) + .await + .unwrap(); + (db, menu.get_id().clone()) + } + + /// The stored counter, absent reading as zero — the number the cap's + /// `WHERE` actually compares, not one recomputed from the rows. + async fn seats(menu: &MenuId, db: &Database) -> i64 { + let mut result = db + .query("SELECT VALUE seats_booked FROM $id") + .bind(("id", menu.record())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>>(0) + .unwrap() + .into_iter() + .next() + .flatten() + .unwrap_or(0) + } + + async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish { + MenuDish::create( + menu, + DishName::try_new("çorba").unwrap(), + None, + DishPrice::try_new(price).unwrap(), + DishTags::try_new(&[], &[]).unwrap(), + db, + ) + .await + .unwrap() + } + + /// The counter is the cap's authority, so it has to track the seats exactly: + /// a repeat booking must not count twice, a cancel must hand its seat back + /// in the same breath as the flip, and a second cancel must not hand back a + /// seat that was already returned (which would open the cap by one forever). + #[tokio::test] + async fn the_seat_counter_follows_the_seats_it_guards() { + let (db, menu) = menu(Some(1)).await; + let (ali, veli) = (UserId::generate(), UserId::generate()); + let open = MealCutoff::default(); + + let booking = MealBooking::book(&menu, &ali, &ali, &open, &db) + .await + .unwrap(); + assert_eq!(seats(&menu, &db).await, 1); + // The same seat again is a no-op, not a second claim. + MealBooking::book(&menu, &ali, &ali, &open, &db) + .await + .unwrap(); + assert_eq!(seats(&menu, &db).await, 1); + // …and the cap bites for anyone else while it is held. + assert!(matches!( + MealBooking::book(&menu, &veli, &veli, &open, &db).await, + Err(AppError::Conflict(_)) + )); + + let cancelled = booking.cancel(&open, &ali, &db).await.unwrap(); + assert_eq!(cancelled.get_status(), MealBookingStatus::Cancelled); + assert_eq!(seats(&menu, &db).await, 0); + // Cancelling again is idempotent all the way down to the counter. + cancelled.cancel(&open, &ali, &db).await.unwrap(); + assert_eq!(seats(&menu, &db).await, 0); + + // The freed seat is real, and taking it again counts once. + let revived = MealBooking::book(&menu, &veli, &veli, &open, &db) + .await + .unwrap(); + assert_eq!(revived.get_attempt(), 1); + assert_eq!(seats(&menu, &db).await, 1); + } + + /// A menu whose row is gone or whose seats are held refuses its own delete, + /// in the `WHERE` rather than in a read the delete then trusts. + #[tokio::test] + async fn a_held_seat_refuses_the_menu_delete() { + let (db, id) = menu(None).await; + let ali = UserId::generate(); + let booking = MealBooking::book(&id, &ali, &ali, &MealCutoff::default(), &db) + .await + .unwrap(); + let row = Menu::read(&id, &db).await.unwrap().unwrap(); + assert!(matches!( + row.clone().delete(&db).await, + Err(AppError::Conflict(_)) + )); + booking + .cancel(&MealCutoff::default(), &ali, &db) + .await + .unwrap(); + assert!(row.delete(&db).await.is_ok()); + } + + /// The price a seat is billed must be one the menu carried *at the moment + /// the seat was taken*. The claim carries the revision the price was read + /// at, so a dish written in between refuses it — this is that refusal, + /// driven by hand because no single-process interleaving can produce it. + #[tokio::test] + async fn a_seat_cannot_be_claimed_at_a_revision_the_menu_has_left() { + let (db, menu) = menu(None).await; + let ali = UserId::generate(); + let seen = Menu::read(&menu, &db).await.unwrap().unwrap().get_version(); + // A dish lands: the price a booking read a moment ago is now stale. + add_dish(&menu, 1_000, &db).await; + let row = MealBooking { + id: MealBookingId::composite(&menu, &ali), + menu: menu.clone(), + student: ali.clone(), + booked_by: ali, + status: MealBookingStatus::Booked, + attempt: 1, + price_minor: None, + cancelled_at: None, + created_at: Timestamp::now(), + }; + let place = async |seen| { + MealBooking::claim_and_place(&menu.record(), cap::UNLIMITED, seen, &row, None, &db) + .await + .unwrap() + }; + assert!( + matches!(place(seen).await, Claimed::Full), + "a claim at a revision the menu has left must be refused" + ); + assert_eq!(seats(&menu, &db).await, 0, "and must write nothing"); + assert!( + MealBooking::read(row.get_id(), &db) + .await + .unwrap() + .is_none(), + "the refused transaction must not leave the row behind either" + ); + + // Re-read, and the same seat is taken with the row it belongs to. + let now = Menu::read(&menu, &db).await.unwrap().unwrap().get_version(); + assert!(now > seen); + assert!(matches!(place(now).await, Claimed::Made(_))); + assert_eq!(seats(&menu, &db).await, 1); + // …and a second placement of that very row owes no second seat. + assert!(matches!(place(now).await, Claimed::Duplicate)); + assert_eq!( + seats(&menu, &db).await, + 1, + "a duplicate rolls its seat back" + ); + } + + /// Every write that can move what a seat costs moves the revision — the + /// half of the rule the CAS above cannot enforce by itself. A dish added, + /// re-priced or removed, and the capacity moved: each must leave the menu at + /// a revision no in-flight booking is still holding. + #[tokio::test] + async fn every_menu_write_that_moves_the_price_moves_the_revision() { + let (db, id) = menu(None).await; + let mut seen = 0; + let mut moved = async |db: &Database| { + let now = Menu::read(&id, db).await.unwrap().unwrap().get_version(); + let stepped = now > seen; + seen = now; + stepped + }; + assert!(!moved(&db).await, "a fresh menu starts where it starts"); + + let dish = add_dish(&id, 1_000, &db).await; + assert!(moved(&db).await, "a dish added"); + let dish = dish + .update( + None, + None, + Some(DishPrice::try_new(2_000).unwrap()), + None, + &db, + ) + .await + .unwrap(); + assert!(moved(&db).await, "a dish re-priced"); + dish.delete(&db).await.unwrap(); + assert!(moved(&db).await, "a dish removed"); + Menu::read(&id, &db) + .await + .unwrap() + .unwrap() + .update(Some(Some(5)), &db) + .await + .unwrap(); + assert!(moved(&db).await, "the capacity moved"); + } + + /// A booking placed after a price edit is billed the new price, and one + /// placed before keeps the old one — the seat's `price_minor` is history, + /// never re-read from the menu. + #[tokio::test] + async fn a_seat_keeps_the_price_it_was_taken_at() { + let (db, menu) = menu(None).await; + let (ali, veli) = (UserId::generate(), UserId::generate()); + let open = MealCutoff::default(); + add_dish(&menu, 1_000, &db).await; + + let early = MealBooking::book(&menu, &ali, &ali, &open, &db) + .await + .unwrap(); + add_dish(&menu, 500, &db).await; + let late = MealBooking::book(&menu, &veli, &veli, &open, &db) + .await + .unwrap(); + + assert_eq!( + early.get_price_minor().map(LedgerAmount::as_minor), + Some(1_000) + ); + assert_eq!( + late.get_price_minor().map(LedgerAmount::as_minor), + Some(1_500) + ); + // The seat taken before the second dish is not re-billed for it. + let held = MealBooking::book(&menu, &ali, &ali, &open, &db) + .await + .unwrap(); + assert_eq!( + held.get_price_minor().map(LedgerAmount::as_minor), + Some(1_000) + ); + } + fn cutoff(minutes: Option, serving_minute: Option) -> MealCutoff { MealCutoff { minutes, diff --git a/src/domain/meal_ledger.rs b/src/domain/meal_ledger.rs index 1102c09..77bc0d0 100644 --- a/src/domain/meal_ledger.rs +++ b/src/domain/meal_ledger.rs @@ -46,9 +46,10 @@ use surrealdb::types::{AlreadyExistsError, RecordId, RecordIdKey, SurrealValue}; use ulid::Generator; use crate::constant::{ - MAX_LEDGER_AMOUNT_MINOR, MAX_LEDGER_METHOD_LEN, MAX_LEDGER_NOTE_LEN, MEAL_LEDGER_TABLE, + CAS_UPDATE_RETRIES, MAX_LEDGER_AMOUNT_MINOR, MAX_LEDGER_METHOD_LEN, MAX_LEDGER_NOTE_LEN, + MEAL_LEDGER_TABLE, }; -use crate::database::Database; +use crate::database::{Database, lost_the_race}; use crate::domain::meal_booking::{MealBooking, MealBookingId}; use crate::domain::menu::MenuId; use crate::domain::menu_dish::MenuDish; @@ -277,17 +278,31 @@ impl MealLedger { /// guarantee is `CREATE`'s own: on an existing id it *errors* and leaves /// the row untouched, so the writer that lost the race reads back the /// winner's line instead of failing the request with a 500. + /// + /// A *write conflict* is the same race decided one layer down — two + /// appends of one id arriving together are no longer serialized by a + /// process-wide lock, so the store aborts one as retryable instead of + /// answering it "already exists". Both are read back the same way, and a + /// conflict that turns out to have written nothing is simply tried again; + /// no path here can write a second line, since the id is the key. async fn append(row: MealLedger, db: &Database) -> Result { if let Some(existing) = Self::read(&row.id, db).await? { return Ok(existing); } let id = row.id.clone(); - let created: Option = match db.create(id.record()).content(row).await { - Ok(created) => created, - Err(e) if is_duplicate_record(&e) => Self::read(&id, db).await?, - Err(e) => return Err(e.into()), - }; - created.ok_or_else(|| AppError::Internal("failed to write the ledger line".into())) + for _ in 0..CAS_UPDATE_RETRIES { + match db.create(id.record()).content(row.clone()).await { + Ok(Some(created)) => return Ok(created), + Ok(None) => break, + Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => { + if let Some(existing) = Self::read(&id, db).await? { + return Ok(existing); + } + } + Err(e) => return Err(e.into()), + } + } + Err(AppError::Internal("failed to write the ledger line".into())) } pub async fn read(id: &MealLedgerId, db: &Database) -> Result, AppError> { @@ -322,9 +337,8 @@ impl MealLedger { /// The price comes off the *booking row*, never off the menu as it stands /// now: a seat taken while the menu was free carries `None` forever, so /// "was free" is a recorded fact and a later dish never bills a seat - /// retroactively. Called under - /// [`MENU_LOCK`](crate::domain::menu::MENU_LOCK), from - /// [`MealBooking::book`] alone, so the seat and its money move together. + /// retroactively. Called from [`MealBooking::book`] alone, right after the seat + /// was claimed, so the seat and its money move together. /// /// Replaying it is free: the id is `(booking, attempt)`, so a duplicate /// `POST` writes nothing, and an attempt whose charge failed the first time diff --git a/src/domain/menu.rs b/src/domain/menu.rs index a0be645..3e7cb5a 100644 --- a/src/domain/menu.rs +++ b/src/domain/menu.rs @@ -10,14 +10,14 @@ //! - **`slot` is a snapshot**, not a link into settings. Retiring a slot must //! never rewrite a menu already published under it. -use std::sync::LazyLock; - use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use tokio::sync::Mutex; -use ulid::Generator; -use crate::constant::{MAX_MENU_CAPACITY, MENU_TABLE}; -use crate::database::Database; +use crate::constant::{ + MAX_MENU_CAPACITY, MENU_SEAT_COUNT_FIELD, MENU_TABLE, MENU_VERSION_FIELD, SLOT_REF_TABLE, +}; +use crate::database::{Database, lost_the_race}; +use crate::domain::cap; use crate::domain::field_update::FieldUpdate; use crate::domain::menu_dish::MenuDish; use crate::domain::page::PagedList; @@ -26,38 +26,46 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -/// Serializes "is there already a menu for this day and slot?" against the -/// publish it authorizes — a count-then-write pair SurrealDB does not -/// conflict-check, so the UNIQUE index would otherwise be the only thing -/// standing between two racing publishes and a 500. Also held by the settings -/// slot-removal guard, whose check ("was any menu published for this slot?") -/// is the mirror image. +/// Serializes what is left that counts rows against one menu: the dish cap +/// (`MAX_DISHES_PER_MENU`, a count-then-write SurrealDB does not +/// conflict-check). Publishing no longer needs it — the day+slot *is* the +/// record id — and neither does a booking, a menu delete, or the settings +/// slot-removal guard: those went to conditional single-record writes +/// ([`crate::domain::cap`]), which hold across replicas as this lock cannot. +// +// ponytail: the dish cap is therefore still replica-local — two replicas can +// each add the 50th dish. Closing it is another `cap` counter (`dish_count` on +// the menu row) plus its backfill; the ceiling is 51 dishes on a menu, not +// money or a seat, so it was not worth the column here. /// -/// Lock order: `EXAM_LOCK` (taken by the same settings write) is always taken -/// *before* this one; nothing here ever takes `EXAM_LOCK`, so the two cannot -/// deadlock. +/// A leaf: nothing held under it takes another lock. pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(()); -/// Mints menu ids in write order — `Ulid::new()`'s random low bits sort -/// arbitrarily within one millisecond, which would scramble the `id` tie-break -/// of the listings below. -static IDS: LazyLock> = - LazyLock::new(|| std::sync::Mutex::new(Generator::new())); +/// The reference counter for one meal slot — how many menus are published under +/// that name, and whether the school has retired it (see +/// [`crate::domain::cap`]). The mirror of +/// [`kind_ref`](crate::domain::exam_result::kind_ref) for exam kinds: the slot +/// is snapshotted text on the menu, so this row is the only place the two +/// tables' relationship is a single record two replicas can contend on. +pub(crate) fn slot_ref(slot: &str) -> RecordId { + RecordId::new(SLOT_REF_TABLE, slot) +} #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct MenuId(RecordId); impl MenuId { - pub fn generate() -> Self { - let mut ids = IDS.lock().expect("menu id generator poisoned"); - // The only error is exhausting the random bits within one millisecond - // (2^80 ids deep); it clears itself as the clock ticks, so retry. - let ulid = loop { - if let Ok(ulid) = ids.generate() { - break ulid; - } - }; - Self(RecordId::new(MENU_TABLE, ulid.to_string())) + /// The one id a menu for this day and slot can have. Deterministic on + /// purpose (the `EnrollmentId` trick): two replicas publishing the same + /// meal race on a single record instead of writing two rows, so the loser + /// is told "already exists" by the store and answered the same 409 the + /// pre-check gives. `date` is fixed-width `YYYY-MM-DD`, so the `_` joiner + /// cannot be read two ways however the school spells its slots. + pub fn for_slot(date: &MenuDate, slot: &MenuSlot) -> Self { + Self(RecordId::new( + MENU_TABLE, + format!("{}_{}", date.as_str(), slot.as_str()), + )) } pub fn from_key(key: &str) -> Self { @@ -156,6 +164,12 @@ pub struct Menu { date: MenuDate, slot: MenuSlot, capacity: Option, + /// The menu's revision (see [`MENU_VERSION_FIELD`]). Absent on rows written + /// before the column existed, which reads as revision zero — the same thing + /// `(version ?? 0)` says in the claim's `WHERE`. The seat counter is + /// deliberately *not* here: it is the database's to own, and a whole-row + /// save must never carry a stale copy of it. + version: Option, created_by: UserId, created_at: Timestamp, } @@ -177,6 +191,13 @@ impl Menu { self.capacity } + /// The revision a booking must still find on the row when it claims its + /// seat. Absent (a pre-column row) is revision zero, exactly as the `WHERE` + /// reads it. + pub fn get_version(&self) -> i64 { + self.version.unwrap_or(0) + } + pub fn get_created_by(&self) -> &UserId { &self.created_by } @@ -185,9 +206,14 @@ impl Menu { self.created_at } - /// Publish a menu. Refused (409) when the day+slot already carries one — - /// re-checked under [`MENU_LOCK`], so two racing publishes cannot both find - /// the day free and trip the UNIQUE index into a 500. + /// Publish a menu. Refused (409) when the day+slot already carries one. + /// + /// The day and slot *are* the record id ([`MenuId::for_slot`]), so the + /// refusal is decided by the store rather than by a check a peer replica can + /// outrun: two publishes of the same meal write one id, and the loser's + /// "already exists" becomes the same 409. The pre-check stays for the + /// ordinary case — and for menus published before ids were derived, whose + /// ULID key no new publish can collide with. pub async fn create( date: MenuDate, slot: MenuSlot, @@ -195,22 +221,44 @@ impl Menu { created_by: &UserId, db: &Database, ) -> Result { - let _guard = MENU_LOCK.lock().await; + let taken = AppError::Conflict("a menu is already published for that date and slot"); if Self::find(&date, &slot, db).await?.is_some() { - return Err(AppError::Conflict( - "a menu is already published for that date and slot", - )); + return Err(taken); + } + // The menu takes a reference on its slot, which is what stops the slot + // being dropped from the settings while this menu (whose slot is only + // snapshotted text) still points at it. Claimed before the write and + // given back if the write does not land, exactly like a seat. + let counter = slot_ref(slot.as_str()); + if !cap::claim_ref(&counter, 1, db).await? { + return Err(AppError::ConflictOwned(format!( + "the '{}' meal slot has been removed from the school's settings", + slot.as_str() + ))); } let menu = Menu { - id: MenuId::generate(), + id: MenuId::for_slot(&date, &slot), date, slot, capacity, + version: Some(0), created_by: created_by.clone(), created_at: Timestamp::now(), }; - let created: Option = db.create(menu.id.record()).content(menu).await?; - created.ok_or_else(|| AppError::Internal("failed to publish the menu".into())) + match db.create(menu.id.record()).content(menu).await { + Ok(Some(created)) => Ok(created), + Ok(None) => { + cap::release_ref(&counter, 1, db).await?; + Err(AppError::Internal("failed to publish the menu".into())) + } + Err(err) => { + cap::release_ref(&counter, 1, db).await?; + match lost_the_race(&err) { + true => Err(taken), + false => Err(err.into()), + } + } + } } pub async fn read(id: &MenuId, db: &Database) -> Result, AppError> { @@ -255,37 +303,57 @@ impl Menu { /// Only `capacity` is writable: `date` and `slot` are `READONLY` columns, /// because moving a published menu to another day is a different menu. /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped. + /// + /// Moving the cap moves the revision first ([`cap::bump`]): a booking that + /// read the old cap must not claim its seat against it, or a shrink + /// over-admits by exactly the bookings in flight. pub async fn update( self, capacity: Option>, db: &Database, ) -> Result { + if capacity.is_some() { + cap::bump(&self.id.record(), MENU_VERSION_FIELD, db).await?; + } FieldUpdate::new(self.id.record()) .set("capacity", capacity) .run::(db) .await } - /// Whether any menu was ever published for this slot name — the guard - /// behind removing a slot from `meal_slots`, mirroring - /// [`ExamResult::any_for_kind`](crate::domain::exam_result::ExamResult::any_for_kind). - /// Menus snapshot the slot as text, so this is a plain string match. - /// Callers hold [`MENU_LOCK`] so a publish cannot slip in behind the check. - pub async fn any_for_slot(slot: &str, db: &Database) -> Result { - let mut result = db - .query("SELECT VALUE id FROM menu WHERE slot = $slot LIMIT 1") - .bind(("slot", slot.to_string())) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) - } - /// Delete the menu and the dishes on it — a dish has no meaning without /// its menu, and the `menu` link is `READONLY`, so it cannot be re-homed. + /// + /// Refused (409) while a seat is still held, and the *row itself* decides + /// that: the delete carries the seat counter in its `WHERE`, so a booking + /// landing in another replica at that instant either takes its seat before + /// the delete (which then finds a non-zero counter and refuses) or after it + /// (and finds no menu). A read-then-delete pair had a window where both + /// happened — a paid seat on a menu that no longer exists. + /// + /// The dishes go *after* the row: their cascade must not run for a delete + /// the counter refused. pub async fn delete(self, db: &Database) -> Result { + let mut result = db + .query(format!( + "DELETE $id WHERE ({MENU_SEAT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE" + )) + .bind(("id", self.id.record())) + .await? + .check()?; + let Some(deleted) = result.take::>(0)?.into_iter().next() else { + // Nothing back: either seats are held, or the menu is already gone. + return Err(match Self::read(&self.id, db).await? { + Some(_) => AppError::Conflict("the menu still has live bookings"), + None => AppError::NotFound, + }); + }; MenuDish::delete_for_menu(&self.id, db).await?; - let deleted: Option = db.delete(self.id.record()).await?; - deleted.ok_or(AppError::NotFound) + // The slot gets its reference back — a slot no menu is published for + // any more may leave the settings again. After the delete, so a crash + // over-counts (refusing a removal) rather than under-counts. + cap::release_ref(&slot_ref(deleted.slot.as_str()), 1, db).await?; + Ok(deleted) } } diff --git a/src/domain/menu_dish.rs b/src/domain/menu_dish.rs index 0dd0803..8c2d2a2 100644 --- a/src/domain/menu_dish.rs +++ b/src/domain/menu_dish.rs @@ -12,9 +12,10 @@ use ulid::Generator; use crate::constant::{ MAX_DISH_DESCRIPTION_LEN, MAX_DISH_NAME_LEN, MAX_DISH_PRICE_MINOR, MAX_DISH_TAGS, - MENU_DISH_TABLE, + MENU_DISH_TABLE, MENU_VERSION_FIELD, }; use crate::database::Database; +use crate::domain::cap; use crate::domain::field_update::FieldUpdate; use crate::domain::menu::MenuId; use crate::domain::timestamp::Timestamp; @@ -185,6 +186,7 @@ impl MenuDish { self.created_at } + /// Add a dish. Moves the menu's revision *first* — see [`Self::bump_menu`]. pub async fn create( menu: &MenuId, name: DishName, @@ -202,8 +204,43 @@ impl MenuDish { tags, created_at: Timestamp::now(), }; - let created: Option = db.create(dish.id.record()).content(dish).await?; - created.ok_or_else(|| AppError::Internal("failed to add the dish".into())) + // The revision bump and the insert are one transaction, and the bump is + // what makes the menu's existence part of it: the `UPDATE` matches + // nothing once the menu row is deleted, and a delete racing this one + // touches the very key this transaction writes, so the two cannot both + // commit. Without that, a dish landing just after `DELETE /menus/{id}` + // removed the row but before its cascade ran outlived its menu. + let mut result = db + .query(format!( + "BEGIN TRANSACTION; + LET $bumped = (UPDATE $menu SET {MENU_VERSION_FIELD} = \ + ({MENU_VERSION_FIELD} ?? 0) + 1 RETURN VALUE id); + IF array::len($bumped) = 0 {{ THROW 'no_menu' }}; + CREATE $id CONTENT $dish; + COMMIT TRANSACTION;" + )) + .bind(("menu", menu.record())) + .bind(("id", dish.id.record())) + .bind(("dish", dish)) + .await?; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the reason. + let mut errors = result.take_errors(); + if errors + .values() + .any(|error| error.to_string().contains("no_menu")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Slots count BEGIN, the LET and the IF: the CREATE is slot 3. + result + .take::>(3)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to add the dish".into())) } pub async fn read(id: &MenuDishId, db: &Database) -> Result, AppError> { @@ -240,6 +277,19 @@ impl MenuDish { Ok(Self::list_for_menu(menu, db).await?.len()) } + /// What a seat on this dish's menu costs changed, so the menu is now at a + /// new revision and any booking that priced itself against the old one has + /// to re-read. Called *before* the write, never after: bumped-and-not-written + /// costs a booking one retry, written-and-not-bumped bills a seat a price + /// the menu no longer carries. + /// + /// Deliberately on every dish write, not only the ones that move + /// `price_minor`: a re-tagged dish is cheap to re-read, and a rule that + /// applies to every write cannot be forgotten by the next field added here. + async fn bump_menu(menu: &MenuId, db: &Database) -> Result<(), AppError> { + cap::bump(&menu.record(), MENU_VERSION_FIELD, db).await + } + /// Write only the fields the PATCH carried. `description` is nullable, so /// it takes the three-way shape: absent = keep, `Some(None)` = clear. pub async fn update( @@ -250,6 +300,7 @@ impl MenuDish { tags: Option, db: &Database, ) -> Result { + Self::bump_menu(&self.menu, db).await?; FieldUpdate::new(self.id.record()) .set("name", name) .set("description", description) @@ -260,6 +311,7 @@ impl MenuDish { } pub async fn delete(self, db: &Database) -> Result { + Self::bump_menu(&self.menu, db).await?; let deleted: Option = db.delete(self.id.record()).await?; deleted.ok_or(AppError::NotFound) } diff --git a/src/domain/registration.rs b/src/domain/registration.rs index 045146f..662e2a3 100644 --- a/src/domain/registration.rs +++ b/src/domain/registration.rs @@ -1,7 +1,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{REGISTRATION_COUNT_FIELD, REGISTRATION_TABLE}; -use crate::database::{Database, lost_the_race}; +use crate::database::Database; use crate::domain::cap; use crate::domain::event::{Event, EventId}; use crate::domain::user::UserId; @@ -83,45 +83,36 @@ impl Registration { .await? .ok_or(AppError::NotFound)? .registration_capacity()?; - let seats = event.record(); - if !cap::claim( - &seats, - REGISTRATION_COUNT_FIELD, - capacity.unwrap_or(cap::UNLIMITED), - db, - ) - .await? - { - return Err(AppError::Conflict("the event is full")); - } let registration = Registration { id: RegistrationId::composite(event, user), event: event.clone(), user: user.clone(), registered_by: registered_by.clone(), }; - let created: Result, _> = db - .create(registration.id.record()) - .content(registration) - .await; - match created { - Ok(Some(created)) => Ok(created), - Ok(None) => { - cap::release(&seats, REGISTRATION_COUNT_FIELD, db).await?; - Err(AppError::Internal("failed to register user".into())) - } - // A concurrent placement of the same pair got there first: give the - // seat back and hand its row over, the same no-op the early return - // above would have made. - Err(err) => { - cap::release(&seats, REGISTRATION_COUNT_FIELD, db).await?; - if !lost_the_race(&err) { - return Err(err.into()); - } - Self::read_for_user(event, user, db) - .await? - .ok_or_else(|| AppError::Internal("failed to register user".into())) - } + match cap::claim_and_create( + &event.record(), + REGISTRATION_COUNT_FIELD, + capacity.unwrap_or(cap::UNLIMITED), + ®istration.id.record(), + ®istration, + db, + ) + .await? + { + cap::Claimed::Made(created) => Ok(created), + // A concurrent placement of the same pair got there first: hand its + // row over, the same no-op the early return above would have made, + // and with no seat spent either way. + cap::Claimed::Duplicate => Self::read_for_user(event, user, db) + .await? + .ok_or_else(|| AppError::Internal("failed to register user".into())), + // Full, or the event was deleted between the read and the claim — + // the conditional write matches nothing either way, and only this + // path pays for the read that tells them apart. + cap::Claimed::Full => match Event::read(event, db).await? { + Some(_) => Err(AppError::Conflict("the event is full")), + None => Err(AppError::NotFound), + }, } } diff --git a/src/domain/subject.rs b/src/domain/subject.rs index 35beb02..b47091c 100644 --- a/src/domain/subject.rs +++ b/src/domain/subject.rs @@ -166,23 +166,67 @@ impl Subject { /// pointing at a subject that no longer exists. /// /// Exam questions and homework are *not* cascaded: their `subject` is a - /// required field the web layer refuses to orphan (both still block the - /// delete with a 409). The bank's is optional metadata, and blocking on it - /// was a dead end — only the template's owner may re-tag it, so a manager - /// could never clear their own 409, and a private template raising it - /// leaked its existence. + /// required field that may not be orphaned, so either one still refuses the + /// delete with a 409. That refusal is the delete's own `WHERE`, read off the + /// two reference counters this row carries + /// ([`crate::constant::SUBJECT_QUESTION_COUNT_FIELD`] and its homework + /// twin), which is what makes it hold when the question is created on + /// another replica — the cross-table `SELECT … LIMIT 1` it replaces was a + /// count-then-delete no transaction serializes, pinned by three + /// process-wide locks that only ever served one process. + /// + /// Which of the two blocked is read off the counters *before* the delete, + /// purely to pick the message; the decision itself was already made by the + /// `WHERE`. + /// + /// The bank's subject is optional metadata, and blocking on it was a dead + /// end — only the template's owner may re-tag it, so a manager could never + /// clear their own 409, and a private template raising it leaked its + /// existence. Its cascade runs *after* the conditional delete, so a refused + /// delete leaves every template's subject where it was. pub async fn delete(self, db: &Database) -> Result { let mut result = db .query( "BEGIN TRANSACTION; + LET $held = (SELECT exam_question_count AS q, homework_count AS h FROM $sub); + LET $before = (DELETE $sub + WHERE (exam_question_count ?? 0) = 0 AND (homework_count ?? 0) = 0 + RETURN BEFORE); + IF array::len($before) = 0 { + THROW IF array::len($held) = 0 { 'subject_missing' } + ELSE IF ($held[0].q ?? 0) > 0 { 'subject_questions' } + ELSE { 'subject_homework' } + }; UPDATE bank_question SET subject = NONE WHERE subject = $sub; - LET $before = (DELETE $sub RETURN BEFORE); RETURN $before; COMMIT TRANSACTION;", ) .bind(("sub", self.id.record())) - .await? - .check()?; + .await?; + // An aborted transaction errors every slot; only the THROW's own slot + // names the marker (the [`crate::domain::appointment_slot`] treatment). + let mut errors = result.take_errors(); + let thrown = |marker: &str| { + errors + .values() + .any(|error| error.to_string().contains(marker)) + }; + if thrown("subject_questions") { + return Err(AppError::Conflict( + "exam questions still reference this subject — re-tag or delete them first", + )); + } + if thrown("subject_homework") { + return Err(AppError::Conflict( + "homework still references this subject — re-tag or delete it first", + )); + } + if thrown("subject_missing") { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } // Read through the trailing `RETURN`, not a counted slot — see // [`crate::domain::exam::Exam::delete`]. let slot = result.num_statements().saturating_sub(2); diff --git a/src/domain/term.rs b/src/domain/term.rs index 33322a7..6c11bfa 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -7,10 +7,9 @@ //! rule that guards exams/lessons/events deliberately does not apply here. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use tokio::sync::Mutex; use ulid::Ulid; -use crate::constant::{MAX_TERM_NAME_LEN, TERM_TABLE}; +use crate::constant::{COURSE_COUNT_FIELD, MAX_TERM_NAME_LEN, TERM_TABLE}; use crate::database::Database; use crate::domain::field_update::FieldUpdate; use crate::domain::page::PagedList; @@ -18,24 +17,6 @@ use crate::domain::timestamp::{Timestamp, range_error}; use crate::error::{AppError, ValidationError}; use crate::validate::validate_required; -/// Serializes the term delete guard (does any course still link it?) against -/// the course writes that assign a term, so a course can't land on a term that -/// is already on its way out. Course writes take it only when they actually -/// link a term. -/// -/// Two leases remain, both cross-record and both replica-*local*: the delete -/// guard in `web::terms::delete_term`, and the term lookup in -/// `web::courses`' create/update. The range check a PATCH makes is no longer -/// one of them — it is a `WHERE` on the update itself -/// ([`crate::domain::field_update::FieldUpdate::ordered`]), which holds across -/// replicas as this mutex never did. -/// -/// Lock order: no path ever holds this and `ENROLL_LOCK` at the same time — the -/// course writes that take this one touch no roster, and the course delete that -/// takes `ENROLL_LOCK` touches no term — so the two cannot deadlock. Should a -/// future path need both, take `ENROLL_LOCK` first. -pub(crate) static TERM_LOCK: Mutex<()> = Mutex::const_new(()); - #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct TermId(RecordId); @@ -152,22 +133,33 @@ impl Term { .await } - /// True iff any course still links to this term — the delete guard. - pub async fn any_course(id: &TermId, db: &Database) -> Result { + /// Delete the term, but only while no course links it — nothing here + /// unlinks or cascades. `false` = refused, nothing was written. + /// + /// The roster of linking courses is the term's own `course_count` + /// refcount, claimed by [`crate::domain::course::Course::create`] and + /// `update` *before* they write a link, so the check and the delete are one + /// conditional write on one record: a course write racing this either + /// claims first (and the delete is refused) or finds the row gone (and is + /// refused itself, with the same 400 the lookup gives). `Err(NotFound)` + /// keeps the answer a concurrent *delete* used to get. + pub async fn delete(self, db: &Database) -> Result { let mut result = db - .query("SELECT VALUE id FROM course WHERE term = $term LIMIT 1") - .bind(("term", id.record())) + .query(format!( + "DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE" + )) + .bind(("term", self.id.record())) .await? .check()?; - Ok(!result.take::>(0)?.is_empty()) - } - - /// Delete the term. Callers must refuse while [`Term::any_course`] holds — - /// nothing here unlinks or cascades, so a term is only ever dropped once no - /// course points at it. - pub async fn delete(self, db: &Database) -> Result { - let deleted: Option = db.delete(self.id.record()).await?; - deleted.ok_or(AppError::NotFound) + if !result.take::>(0)?.is_empty() { + return Ok(true); + } + // Still linked or already gone: the one statement cannot tell those + // apart, and only the refusal path pays for the read that can. + match Self::read(&self.id, db).await? { + Some(_) => Ok(false), + None => Err(AppError::NotFound), + } } } diff --git a/src/migration_sql.rs b/src/migration_sql.rs index c12070d..ac87aaf 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -180,6 +180,9 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS name ON term TYPE string; DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int; DEFINE FIELD IF NOT EXISTS ends_at ON term TYPE int; + -- Courses still linking this term, the cross-replica delete guard (see + -- `crate::domain::cap`). Absent reads as zero, so no Rust struct needs it. + DEFINE FIELD IF NOT EXISTS course_count ON term TYPE option; DEFINE TABLE IF NOT EXISTS course SCHEMAFULL; DEFINE FIELD IF NOT EXISTS creator ON course TYPE record; @@ -196,6 +199,11 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS course ON subject TYPE record; DEFINE FIELD IF NOT EXISTS name ON subject TYPE string; DEFINE FIELD IF NOT EXISTS description ON subject TYPE string; + -- How many exam questions and how many homework still point here. The + -- delete is conditioned on both reading zero, which is what makes the + -- guard hold against a question created on another replica. + DEFINE FIELD IF NOT EXISTS exam_question_count ON subject TYPE option; + DEFINE FIELD IF NOT EXISTS homework_count ON subject TYPE option; DEFINE INDEX IF NOT EXISTS subject_course ON subject FIELDS course; DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL; @@ -258,6 +266,10 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true; DEFINE FIELD IF NOT EXISTS allow_review ON exam TYPE bool DEFAULT false; DEFINE FIELD IF NOT EXISTS draft ON exam TYPE bool DEFAULT false; + -- How many marks the exam carries (2026-07-27). A kind change is refused + -- against it, and the exam's own compare-and-set pins it, so a grade + -- landing mid-PATCH refuses that save instead of slipping past its gates. + DEFINE FIELD IF NOT EXISTS result_count ON exam TYPE option; DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course; DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL; @@ -469,6 +481,13 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY; DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int; DEFINE FIELD IF NOT EXISTS file_count ON homework_submission TYPE option; + -- The grade that froze this submission, absent while it is still open. The + -- freeze used to be a cross-table read (does a homework_result exist?) + -- followed by a write here, which no lock can hold across replicas; the + -- stamp turns every submission edit into a conditional single-record write + -- (`WHERE graded_by_result = NONE`), the one guard that survives. Set by + -- grading, cleared by un-grading, never by the student. + DEFINE FIELD IF NOT EXISTS graded_by_result ON homework_submission TYPE option>; DEFINE INDEX IF NOT EXISTS homework_submission_homework ON homework_submission FIELDS homework; DEFINE TABLE IF NOT EXISTS homework_file SCHEMAFULL; @@ -493,14 +512,17 @@ pub const MIGRATION: &str = " -- slots, a student or parent books one. `series` groups the occurrences a -- weekly repeat expanded into, so one cancel deletes one row and a series -- delete finds the rest. A booking's live/dead state is the `status` - -- string; occupancy is derived from it under the appointment lock rather - -- than stored, so a rejected or cancelled booking frees its slot again. + -- string; `occupied` is the cap-1 counter that says whether the slot is + -- taken (2026-07-27 — it used to be counted from the booking rows under a + -- process-local lock, which two replicas could each pass), decremented in + -- the same transaction as the reject/cancel that frees it. -- The `proposed_*` fields carry a teacher's counter-proposal on the same - -- row until the requester accepts. No BACKFILL: both tables are new. + -- row until the requester accepts. DEFINE TABLE IF NOT EXISTS appointment_slot SCHEMAFULL; DEFINE FIELD IF NOT EXISTS teacher ON appointment_slot TYPE record; DEFINE FIELD IF NOT EXISTS starts_at ON appointment_slot TYPE int; DEFINE FIELD IF NOT EXISTS ends_at ON appointment_slot TYPE int; + DEFINE FIELD IF NOT EXISTS occupied ON appointment_slot TYPE option; DEFINE FIELD IF NOT EXISTS note ON appointment_slot TYPE option; DEFINE FIELD IF NOT EXISTS series ON appointment_slot TYPE option; DEFINE FIELD IF NOT EXISTS created_at ON appointment_slot TYPE int; @@ -536,6 +558,13 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS date ON menu TYPE string READONLY; DEFINE FIELD IF NOT EXISTS slot ON menu TYPE string READONLY; DEFINE FIELD IF NOT EXISTS capacity ON menu TYPE option; + -- `seats_booked` is the seat cap's counter (see `domain::cap`) and + -- `version` the menu's revision: a booking claims its seat only while the + -- menu still stands at the revision it read the price at, so a dish + -- re-priced mid-booking cannot be billed as the old price. Both absent + -- means zero, which is what `(x ?? 0)` reads on a row written before them. + DEFINE FIELD IF NOT EXISTS seats_booked ON menu TYPE option; + DEFINE FIELD IF NOT EXISTS version ON menu TYPE option; DEFINE FIELD IF NOT EXISTS created_by ON menu TYPE record READONLY; DEFINE FIELD IF NOT EXISTS created_at ON menu TYPE int READONLY; DEFINE INDEX IF NOT EXISTS menu_date_slot ON menu FIELDS date, slot UNIQUE; @@ -600,6 +629,21 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS recorded_by ON meal_ledger TYPE record READONLY; DEFINE FIELD IF NOT EXISTS created_at ON meal_ledger TYPE int READONLY; DEFINE INDEX IF NOT EXISTS meal_ledger_student ON meal_ledger FIELDS student; + + -- Reference counters, one row per *name* the settings offer, keyed by the + -- name itself (2026-07-27). They are how 'a kind nothing is graded under + -- may be removed' survives a second replica: the guard used to be a + -- count-then-write across two tables under a process-wide lock, and the + -- database serializes neither half of that. Both columns are `option<…>` + -- so an absent row reads as zero references, in service — the counter is + -- created by the first claim, never seeded per name. + DEFINE TABLE IF NOT EXISTS kind_ref SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS count ON kind_ref TYPE option; + DEFINE FIELD IF NOT EXISTS retired ON kind_ref TYPE option; + + DEFINE TABLE IF NOT EXISTS slot_ref SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS count ON slot_ref TYPE option; + DEFINE FIELD IF NOT EXISTS retired ON slot_ref TYPE option; "; /// Data backfills for rows written by older binaries. Runs *after* (and apart @@ -742,6 +786,19 @@ pub const BACKFILL: &str = " UPDATE answer_image SET seq = 1 WHERE seq = NONE; UPDATE exam_result SET seq = 1 WHERE seq = NONE; + -- The homework freeze became cross-replica (2026-07-27): a grade that + -- predates the stamp column has to put it on the submission it already + -- froze, or that submission would read as open and be editable again. + -- Result and submission share the deterministic `{homework}_{user}` key, so + -- the owning row is addressed directly rather than searched for; an UPDATE + -- of a record that isn't there (graded absent work) is an empty no-op. The + -- `= NONE` guard keeps it one-time, for the same reason the counters below + -- are one-time — a peer replica is serving while this runs. + FOR $r IN ((SELECT VALUE id FROM homework_result) ?? []) { + UPDATE type::record('homework_submission', record::id($r)) + SET graded_by_result = $r WHERE graded_by_result = NONE; + }; + -- Count caps became cross-replica (2026-07-27): the authority moved from a -- process-wide mutex to a counter column on the parent row, so every parent -- that predates the column is seeded from the children it actually has. @@ -756,6 +813,14 @@ pub const BACKFILL: &str = " }; UPDATE course SET enrollment_count = 0 WHERE enrollment_count = NONE; + -- The one refcount among them: courses per term, not children per parent. + -- Same one-time `= NONE` guard, and `WHERE term != NONE` keeps the + -- unlinked courses out of the group (they would form a NONE bucket). + FOR $row IN ((SELECT term, count() AS n FROM course WHERE term != NONE GROUP BY term) ?? []) { + UPDATE $row.term SET course_count = $row.n WHERE course_count = NONE; + }; + UPDATE term SET course_count = 0 WHERE course_count = NONE; + FOR $row IN ((SELECT event, count() AS n FROM registration GROUP BY event) ?? []) { UPDATE $row.event SET registration_count = $row.n WHERE registration_count = NONE; }; @@ -775,6 +840,71 @@ pub const BACKFILL: &str = " UPDATE $row.user_id SET chatbot_thread_count = $row.n WHERE chatbot_thread_count = NONE; }; UPDATE user SET chatbot_thread_count = 0 WHERE chatbot_thread_count = NONE; + + -- The appointment slot's counter is the odd one out: it counts only the + -- bookings that are still *live*, because a rejected or cancelled one gave + -- the slot back long before this column existed. + FOR $row IN ((SELECT slot, count() AS n FROM appointment + WHERE status IN ['pending', 'approved'] GROUP BY slot) ?? []) { + UPDATE $row.slot SET occupied = $row.n WHERE occupied = NONE; + }; + UPDATE appointment_slot SET occupied = 0 WHERE occupied = NONE; + + -- A menu's seats, counted from the bookings still *held* — a cancelled one + -- gave its seat back before this column existed, exactly like the slot + -- above. `version` gets no pass at all: absent already reads as revision + -- zero everywhere it is compared, so writing it would be a no-op that + -- touches every menu row. + FOR $row IN ((SELECT menu, count() AS n FROM meal_booking + WHERE status = 'booked' GROUP BY menu) ?? []) { + UPDATE $row.menu SET seats_booked = $row.n WHERE seats_booked = NONE; + }; + UPDATE menu SET seats_booked = 0 WHERE seats_booked = NONE; + + -- A subject's two reference counters, seeded from what actually points at + -- it. This must run *after* the legacy sweep above destroys the questions + -- that predate subjects, or a subject would be seeded with rows that are + -- about to vanish and could then never be deleted. No zero pass, for the + -- same reason `version` gets none: absent already reads as zero in the + -- delete's `(count ?? 0) = 0` guard, so writing it would touch every + -- subject row to say what it already says. + FOR $row IN ((SELECT subject, count() AS n FROM exam_question GROUP BY subject) ?? []) { + UPDATE $row.subject SET exam_question_count = $row.n WHERE exam_question_count = NONE; + }; + + FOR $row IN ((SELECT subject, count() AS n FROM homework GROUP BY subject) ?? []) { + UPDATE $row.subject SET homework_count = $row.n WHERE homework_count = NONE; + }; + + -- The settings guards became cross-replica the same way (2026-07-27): an + -- exam kind counts the marks written under it, a meal slot the menus + -- published for it, and a name is removable exactly while its counter reads + -- zero. Rows written before the counters existed are counted once here. + -- + -- Same `= NONE` guard and the same reason as the caps above: a peer replica + -- may already be serving, and recomputing a counter it is incrementing + -- would hand back a reference that is still held. No zero pass either — an + -- absent counter already reads as zero, and a name nobody ever used needs + -- no row at all. + -- + -- Marks predate the counter but so may their *kind*: an exam whose kind was + -- removed from the list long ago is counted too, which only ever refuses a + -- removal that already happened. `slot` is text on the menu, so its group + -- needs no join; `kind` lives on the exam, one hop from the mark. + FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result GROUP BY kind) ?? []) { + UPSERT type::record('kind_ref', $row.kind) SET count = $row.n WHERE count = NONE; + }; + + FOR $row IN ((SELECT slot, count() AS n FROM menu GROUP BY slot) ?? []) { + UPSERT type::record('slot_ref', $row.slot) SET count = $row.n WHERE count = NONE; + }; + + -- Same one-time seeding for the per-exam mark counter: an exam graded by an + -- older binary must read as graded, or its kind could be changed under the + -- marks it already carries. + FOR $row IN ((SELECT exam, count() AS n FROM exam_result GROUP BY exam) ?? []) { + UPDATE $row.exam SET result_count = $row.n WHERE result_count = NONE; + }; "; /// The migration batches, in the order a boot applies them — and the *only* diff --git a/src/web/bank_questions.rs b/src/web/bank_questions.rs index b203ae0..9074b27 100644 --- a/src/web/bank_questions.rs +++ b/src/web/bank_questions.rs @@ -45,22 +45,19 @@ use super::{ remove_blob, serve_inline_blob, set_or_clear, store_blob, }; -/// Serializes bank writes that adopt a `subject` against a concurrent subject -/// delete — the one invariant left here, and a **replica-local** one: it orders -/// requests inside one process, and there are two. Every lease is now a -/// *reader* lease taken across a subject-exists check and the write that adopts -/// it: bank create, bank update, and save-to-bank. (Update used to take the -/// writer lease for its read-modify-write; that is a compare-and-set on the row -/// itself now, which holds across replicas.) The subject delete takes the writer -/// lease across the cascade that clears `subject` off every template, so a -/// template can't land on a subject that vanished mid-flight (it would outlive -/// the sweep) — the bank twin of the -/// [`super::exams::EXAM_LOCK`]/[`super::homework::HOMEWORK_LOCK`] guards. -/// Save-to-bank (`question_to_bank`) takes the same reader lease across its -/// question read and insert: the source question can be re-tagged/deleted, so -/// its subject isn't otherwise pinned. Held after EXAM_LOCK/HOMEWORK_LOCK in -/// the delete path; bank writers take only this one, so no cycle. -pub(crate) static BANK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); +// There is no `BANK_LOCK` any more. It served exactly one pairing — a +// subject-exists check here against the subject delete's cascade that clears +// `subject` off every template — and that delete no longer takes any lock: it +// is a conditional statement on the subject's own reference counters, which +// bank templates deliberately do not hold (blocking on them was a dead end; see +// [`crate::domain::subject::Subject::delete`]). With the writer gone the three +// reader leases guarded nothing, and what they claimed to guard was already +// open in production: the lock ordered one process, and the backend runs two. +// +// The race it leaves is the one the cascade already accepts — a template can +// adopt a subject the same instant it is deleted and be left holding a dangling +// id. Every read tolerates that: `subject_name` resolves to empty, exactly as +// it does for the templates the cascade did clear. pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -435,9 +432,6 @@ async fn create_question( RequireTeacher(user): RequireTeacher, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { - // Reader lease of [`BANK_LOCK`]: the exists-check and the insert are one - // unit, so a subject delete can't slip between them (see the lock's doc). - let _guard = BANK_LOCK.read().await; // Origin metadata only — no course to check it against, but it must exist. let subject = subject_must_exist(&req.subject_id, &st.db).await?; let text = QuestionText::try_new(&req.text)?; @@ -627,14 +621,6 @@ async fn update_question( Path(bid): Path, Json(req): Json, ) -> Result, AppError> { - // Reader lease of [`BANK_LOCK`], exactly like the create path and for the - // one thing it buys: the subject-exists check below is paired with the - // subject delete that sweeps this table (that cascade takes the writer - // lease), so a template cannot be pinned to a subject on its way out. It is - // replica-local, like every lock here. The *writer* lease this used to take - // was aimed at the read-modify-write below, which it only serialized inside - // one process — that is now a compare-and-set on the row itself. - let _guard = BANK_LOCK.read().await; // Read, merge and write again while the row keeps moving underneath: the // guarded write refuses on a snapshot that has gone stale, so both edits // land instead of the later one reverting the earlier. diff --git a/src/web/courses.rs b/src/web/courses.rs index c613db4..582bf59 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -12,7 +12,7 @@ use crate::database::Database; use crate::domain::answer_image::AnswerImage; use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; use crate::domain::course_session::{CourseSession, SessionTopic}; -use crate::domain::enrollment::{ENROLL_LOCK, Enrollment}; +use crate::domain::enrollment::Enrollment; use crate::domain::exam::{ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, @@ -23,13 +23,12 @@ use crate::domain::question_image::QuestionImage; use crate::domain::role::Role; use crate::domain::settings::Settings; use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; -use crate::domain::term::TERM_LOCK; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; -use super::homework::{HOMEWORK_LOCK, description_or_none, resolve_assigned}; +use super::homework::{description_or_none, resolve_assigned}; use super::sessions::resolve_session_teacher; use super::subjects::subject_in_course; use super::terms::resolve_term; @@ -274,13 +273,9 @@ async fn create_course( Some(ref kind) => CourseKind::try_new(kind)?, None => CourseKind::course(), }; - // [`TERM_LOCK`] holds the term lookup and the save together, so the link - // can't be written onto a term a concurrent delete just cleared. Only a - // write that actually links a term needs it. - let _term_guard = match req.term_id { - Some(_) => Some(TERM_LOCK.lock().await), - None => None, - }; + // Pre-flight only: [`Course::create`] claims a reference on the term before + // it writes the link, and a term deleted in between fails that claim with + // this very error — so an unknown id reads the same whichever side wins. let term = resolve_term(req.term_id.as_deref(), &st.db).await?; check_capacity(req.capacity)?; let course = Course::create( @@ -441,12 +436,6 @@ async fn update_course( .map(CourseDescription::try_new) .transpose()?; let kind = req.kind.as_deref().map(CourseKind::try_new).transpose()?; - // Same [`TERM_LOCK`] window as create — held over the lookup and the save - // whenever this PATCH links a term (clearing or omitting needs no guard). - let _term_guard = match req.term_id { - Some(Some(_)) => Some(TERM_LOCK.lock().await), - _ => None, - }; // Both columns are nullable, so both stay clearable: omitted is `None` // (keep), an explicit `null` is `Some(None)` (write `NONE`). let term = match req.term_id { @@ -499,21 +488,18 @@ async fn delete_course( "only the course creator or a manager/admin can delete this course", )); } - // [`ENROLL_LOCK`] holds the roster check and the delete together, so an - // enroll that just passed its capacity check can't land its row on a - // course that vanished mid-flight. - let _guard = ENROLL_LOCK.lock().await; - if Enrollment::any_for_course(course.get_id(), &st.db).await? { - return Err(AppError::Conflict( - "students are still enrolled in this course — remove them first", - )); - } // Rows go first (the delete cascades them), blobs after — a crash in - // between strands at worst an unreachable blob. + // between strands at worst an unreachable blob. The keys are read before + // the delete because it takes their rows with it; a refused delete just + // drops them unused. let image_files = QuestionImage::file_keys_for_course(course.get_id(), &st.db).await?; let answer_image_files = AnswerImage::file_keys_for_course(course.get_id(), &st.db).await?; let homework_files = HomeworkFile::file_keys_for_course(course.get_id(), &st.db).await?; - course.delete(&st.db).await?; + if !course.delete(&st.db).await? { + return Err(AppError::Conflict( + "students are still enrolled in this course — remove them first", + )); + } for file in image_files .iter() .chain(&answer_image_files) @@ -1048,11 +1034,9 @@ async fn create_homework_in_course( }; let due_at = Timestamp::from_millis(req.due_at); check_not_past("due_at", Some(due_at))?; - // Reader lease of [`HOMEWORK_LOCK`], held from the subject check through - // the create: a subject delete (a writer, which checks for homework) can't - // vanish the subject between its validation here and the row landing with - // it. - let _guard = HOMEWORK_LOCK.read().await; + // No lease: the create takes the subject's reference counter in the same + // breath as the row, and the subject delete is refused while that counter + // is non-zero — so the check below is only a pre-flight for the message. let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; let assigned = resolve_assigned(req.assigned, course.get_id(), &st.db).await?; let homework = Homework::create( diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 6bae209..20887f4 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -396,6 +396,13 @@ async fn handle_message( // of [`EXAM_LOCK`] from the gates through the upsert, exactly // like `save_answer_checked` — and dropped before the socket // sends, so a slow client never stalls a writer. + // + // ponytail (accepted race, reviewed): the lease is process-local, + // so across replicas a save already in flight can land on the + // room's sitting just after a retake made it terminal. It writes a + // history row for the old seq; the grade of record (latest seq) is + // untouched. The fix is a `current_seq` claim on every save — the + // hottest path here — so the cost beats the damage and it stays. let guard = EXAM_LOCK.read().await; // Tracks how far the gates got: only once the sitting resolved can // a failure possibly be about this one question rather than about diff --git a/src/web/exams/attempts.rs b/src/web/exams/attempts.rs index 7a577bd..a640a1e 100644 --- a/src/web/exams/attempts.rs +++ b/src/web/exams/attempts.rs @@ -665,6 +665,14 @@ pub(crate) async fn save_answer_checked( // Reader lease of [`EXAM_LOCK`]: the writable gate and the upsert are // one unit, or a retake's wipe-and-create (a writer) slips in between // and this stale save lands on the fresh blank sheet. + // + // ponytail (accepted race, reviewed): the lease is process-local, so with + // more than one replica a save that started just before a retake can still + // stamp its answer onto the *old* seq, milliseconds after that sitting went + // terminal. Damage is confined to a history row — the grade of record is + // the latest seq, which the late write never touches. Closing it needs a + // `current_seq` claim on every answer save, the hottest path in the app; + // cost beats the damage, so it stays open on purpose. let _guard = EXAM_LOCK.read().await; let attempt = writable_attempt(exam, user, db).await?; save_answer_in(exam, &attempt, question_id, selected, text, db).await diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index 96fb081..a7d8c08 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -78,19 +78,22 @@ impl Scheduled for Exam { /// /// Read side — the answer saves (REST and the exam room), from the /// writable-attempt gate through the upsert; the grade write (draft gate -/// through the result upsert); the exam PATCH, whose mode/re-draft gates count -/// attempts and results; and the three question writes that first check a -/// subject belongs to the course. These stay concurrent with each other. +/// through the result upsert); and the exam PATCH, whose mode/re-draft gates +/// count attempts and results. These stay concurrent with each other. /// -/// Write side — attempt starts (the max-attempts count and the retake's answer -/// wipe) and the subject delete's cascade. So a save can never land on a sheet -/// a retake just wiped, a mark can never land on an exam mid-flight into -/// hiding, and a question can never adopt a subject being swept. +/// Write side — attempt starts alone (the max-attempts count and the retake's +/// answer wipe). So a save can never land on a sheet a retake just wiped, and a +/// mark can never land on an exam mid-flight into hiding. /// -/// The question freeze gate is *not* on this list any more: it rides inside -/// each question/image write's own transaction +/// Two rules have left this list. The question freeze gate rides inside each +/// question/image write's own transaction /// ([`crate::domain::exam_attempt::ExamAttempt::unfrozen`]), and the exam PATCH -/// no longer needs the writer lease because its save is a compare-and-set. +/// no longer needs the writer lease because its save is a compare-and-set. The +/// subject delete's cascade — the only writer outside attempt starts, paired +/// with the question writes' subject check — is now a conditional statement on +/// the subject's own reference counter +/// ([`crate::domain::subject::Subject::delete`]), which every question create, +/// re-tag and delete moves. // ponytail: global RwLock, shard per-exam if save latency ever matters. pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); @@ -162,7 +165,9 @@ struct UpdateExam { description: Option, /// The assessment form — one of the school's exam kinds (`GET /settings`). /// Changing it re-weights the exam: the course average uses the kind's - /// settings-configured weight. + /// settings-configured weight. For that reason an exam that already carries + /// marks keeps its kind (`409`) — those marks would silently re-weight, + /// exactly what the settings' kind-removal guard refuses. kind: Option, /// `sync`, `async`, or `open`. Omit to keep the current mode; send `null` /// to turn the exam back into an offline-graded one. Frozen once anyone @@ -385,7 +390,7 @@ async fn get_exam( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (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), + (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), ), )] async fn update_exam( @@ -502,6 +507,19 @@ async fn update_exam( } } + // A graded exam keeps its kind. Moving it re-weights every mark it + // already carries — the same silent re-weighting the settings' removal + // guard refuses — and it would strand those marks' references on the + // kind they were counted under, freeing the kind the exam now claims to + // be. Marks are counted on the exam row, and the save below *pins* that + // counter, so a grade landing between this read and the write refuses + // the save (the loop then re-reads and answers the 409 below). + if kind.as_str() != exam.get_kind().as_str() && exam.get_result_count() > 0 { + return Err(AppError::Conflict( + "cannot change the kind of an exam that already has marks", + )); + } + if let Some(updated) = exam .update_if_unchanged( title, @@ -594,7 +612,7 @@ async fn delete_exam( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse), (status = 404, description = "Exam not found", body = ErrorResponse), - (status = 409, description = "The exam is a draft", body = ErrorResponse), + (status = 409, description = "The exam is a draft, or its kind has been removed from the school's settings", body = ErrorResponse), ), )] async fn grade( @@ -669,7 +687,16 @@ async fn grade( let seq = ExamAttempt::read_latest_for_user(&exam_id, &target, &st.db) .await? .map_or(1, |a| a.get_seq()); - let result = ExamResult::grade(&exam_id, &target, seq, mark, teacher.get_id(), &st.db).await?; + let result = ExamResult::grade( + &exam_id, + &target, + seq, + mark, + teacher.get_id(), + exam.get_kind().as_str(), + &st.db, + ) + .await?; let people = PersonRef::map_of(&[&target_user, &teacher]); Ok(Json(ExamResultResponse::new(&result, &people))) } @@ -790,7 +817,13 @@ async fn remove_result( "only the course creator, an assigned teacher, or a manager/admin can remove results", )); } - let removed = ExamResult::remove(exam.get_id(), &UserId::from_key(&target), &st.db).await?; + let removed = ExamResult::remove( + exam.get_id(), + &UserId::from_key(&target), + exam.get_kind().as_str(), + &st.db, + ) + .await?; if removed.is_none() { return Err(AppError::NotFound); } diff --git a/src/web/exams/questions.rs b/src/web/exams/questions.rs index fe6f488..8fcfbc5 100644 --- a/src/web/exams/questions.rs +++ b/src/web/exams/questions.rs @@ -218,11 +218,10 @@ pub(crate) async fn create_question( "only the course creator, an assigned teacher, or a manager/admin can author questions", )); } - // Reader lease of [`EXAM_LOCK`], for the subject check alone: a subject - // delete (which takes the writer lease) must not invalidate a subject this - // just validated. Replica-local, like every lock here. The freeze gate no - // longer needs the lease — it rides inside the insert's own transaction. - let _guard = EXAM_LOCK.read().await; + // No lease: the subject check below is only a pre-flight for the message, + // and the insert takes the subject's reference counter in the same breath — + // a subject delete lands either wholly before it (400) or is refused. The + // freeze gate rides inside the insert's own transaction. ensure_questions_editable(exam.get_id(), &st.db).await?; let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; @@ -346,9 +345,8 @@ pub(crate) async fn update_question( "only the course creator, an assigned teacher, or a manager/admin can edit questions", )); } - // Reader lease of [`EXAM_LOCK`] for the subject check — see - // `create_question`. The freeze gate rides in the update's transaction. - let _guard = EXAM_LOCK.read().await; + // No lease — see `create_question`; a re-tag moves the subject's reference + // counter, and the freeze gate rides in the update's transaction. ensure_questions_editable(exam.get_id(), &st.db).await?; let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; @@ -504,9 +502,8 @@ pub(crate) async fn question_from_bank( "only the course creator, an assigned teacher, or a manager/admin can author questions", )); } - // Reader lease of [`EXAM_LOCK`] for the subject check — same reasoning as - // `create_question`. The freeze gate rides in the insert's transaction. - let _guard = EXAM_LOCK.read().await; + // No lease — same reasoning as `create_question`. The freeze gate rides in + // the insert's transaction. ensure_questions_editable(exam.get_id(), &st.db).await?; let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; @@ -758,12 +755,9 @@ pub(crate) async fn question_to_bank( "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank", )); } - // Reader lease of [`BANK_LOCK`] across the question read and the insert: the - // template adopts the question's subject, so without it a subject delete - // could slip between the two and leave the fresh template pointing at a - // subject its cascade had already swept (that cascade runs under BANK_LOCK's - // writer lease, so holding the reader lease orders us either side of it). - let _bank_guard = crate::web::bank_questions::BANK_LOCK.read().await; + // No lease: `BANK_LOCK` is gone with the subject delete's writer lease, and + // a template left holding a deleted subject reads as an empty + // `subject_name` either way (see [`crate::web::bank_questions`]). let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; // `create_from_exam` mints its own id and insert (the funnel), fed the @@ -825,9 +819,6 @@ pub(crate) async fn question_to_bank( // template silently vanishing over a metadata write is worse than a // template with no back-link (the next save re-links it). let question_key = question.get_id().key().to_string(); - // The bank lease has done its job (the template is inserted, its subject - // pinned); hand it back before the link write. - drop(_bank_guard); // No exam lease around the back-link any more, and none is needed: this is a // single-column `UPDATE`, and `ExamQuestion::update` no longer re-states // this column from a snapshot (it names the columns it writes), so a diff --git a/src/web/homework.rs b/src/web/homework.rs index 4d779e3..4331e15 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -44,15 +44,31 @@ use super::{ /// Serializes the homework subsystem's cross-record check-then-writes, which /// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as -/// [`crate::web::exams::EXAM_LOCK`]. The class of bug: a submission stays -/// editable only *until a result exists*, so the "no grade yet" read and the -/// submission write that depends on it must not straddle a concurrent grade, -/// and a homework delete must not race a submission landing under it. Read side -/// (steps 3/4): the student's submission and file writes, held from the -/// ungraded gate through the upsert, concurrent with each other. Write side: -/// grade/ungrade (steps 3/4) and the homework-delete cascade here. Lock order, -/// where both are taken: `HOMEWORK_LOCK` before the file-cap `Mutex`, never the -/// reverse. +/// [`crate::web::exams::EXAM_LOCK`]. It is a *within-replica* guard only, so +/// the rule it can no longer be trusted with is the freeze: a graded submission +/// used to stay unedited because the "no grade yet" read and the write it +/// licensed sat under one lease, which two processes never shared. That rule +/// moved into the database — grading stamps +/// [`crate::constant::SUBMISSION_GRADED_FIELD`] on the submission row and every +/// student-side write carries `graded_by_result = NONE` as its own condition. +/// +/// What still leases it, honestly: +/// - Write: the homework PATCH's orphan guard ([`update_homework`]), the +/// homework-delete cascade ([`delete_homework`]), and grade/ungrade — which +/// read the homework itself under the lease so a concurrent delete can't +/// leave a result row under a vanished homework. +/// - Read: the student's submission/file writes, which no longer gate the +/// freeze but still must not land under a PATCH re-scoping the audience out +/// from under them. +/// +/// The subject rule has left: creating a homework and re-tagging one move the +/// subject's reference counter, and the subject delete is refused while that +/// counter is non-zero ([`crate::domain::subject::Subject::delete`]), so +/// neither the create ([`super::courses`]) nor the outside writer the subject +/// delete used to take is on this list any more. +/// +/// Lock order, where both are taken: `HOMEWORK_LOCK` before the counter lock in +/// [`crate::domain::cap`], never the reverse. // ponytail: global RwLock, shard per-homework if write latency ever matters. pub(crate) static HOMEWORK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); @@ -299,8 +315,9 @@ async fn update_homework( // Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the // live submissions and results, and the row write depends on what it saw — // without the lease a submission (a reader) could land between the check - // and the write, orphaned by the narrowing that just missed it. The lease - // also pins the subject re-tag against a concurrent subject delete. + // and the write, orphaned by the narrowing that just missed it. The subject + // re-tag no longer needs it — it moves the two subjects' reference counters + // inside `Homework::update`. let _guard = HOMEWORK_LOCK.write().await; // Only what the request carried: an omitted field stays `None` and is never @@ -609,10 +626,15 @@ async fn submit( Some(ref text) if !text.is_empty() => Some(SubmissionText::try_new(text)?), _ => None, }; - // Reader lease of HOMEWORK_LOCK, held from the graded gate through the write: - // the "no grade yet" read and the upsert that depends on it are one unit, or - // a grade landing between them lets an edit slip onto a frozen submission. + // Reader lease of HOMEWORK_LOCK: no longer the freeze (that is the stamp on + // the row, below), but still the interlock against a PATCH re-scoping this + // homework's audience while the submission lands under it. let _guard = HOMEWORK_LOCK.read().await; + // The graded gate, twice over. This read answers the common case — graded + // minutes ago, and the student who never submitted has no row to carry the + // freeze; the upsert's own `WHERE` (the grade stamp on the row) is what + // holds when the grade lands *while* this request runs, in this replica or + // the other one. if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db) .await? .is_some() @@ -621,13 +643,18 @@ async fn submit( "this homework has been graded — ask the teacher to remove the grade before editing your submission", )); } - // 201-vs-200: a prior read under the lock is exact, where comparing the - // returned stamps would misreport a same-millisecond re-submit as a create. + // 201-vs-200: a prior read is exact, where comparing the returned stamps + // would misreport a same-millisecond re-submit as a create. let existed = HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db) .await? .is_some(); - let submission = - HomeworkSubmission::upsert(homework.get_id(), user.get_id(), text, &st.db).await?; + let Some(submission) = + HomeworkSubmission::upsert(homework.get_id(), user.get_id(), text, &st.db).await? + else { + return Err(AppError::Conflict( + "this homework has been graded — ask the teacher to remove the grade before editing your submission", + )); + }; let files = HomeworkFile::list_for_submission(submission.get_id(), &st.db).await?; let status = if existed { StatusCode::OK @@ -705,6 +732,7 @@ async fn delete_submission( Path(id): Path, ) -> Result { let homework = gate_own_submission(&id, &user, &st.db).await?; + // Reader lease as in `submit` — the audience interlock, not the freeze. let _guard = HOMEWORK_LOCK.read().await; if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db) .await? @@ -720,7 +748,13 @@ async fn delete_submission( // Collect blob names before the cascade (submission.delete wipes the file // rows in the same transaction), then unlink after the rows are gone. let files = HomeworkFile::list_for_submission(submission.get_id(), &st.db).await?; - submission.delete(&st.db).await?; + // The delete carries the freeze as its own condition, so a grade landing + // since the read above refuses it rather than wiping graded work. + if submission.delete(&st.db).await?.is_none() { + return Err(AppError::Conflict( + "this homework has been graded — ask the teacher to remove the grade before deleting your submission", + )); + } for file in &files { remove_blob(&st.files_path, file.get_file()).await; } @@ -799,29 +833,33 @@ async fn upload_submission_file( let name = FileName::try_new(&upload.name.unwrap_or_default())?; let content_type = FileContentType::try_new(&upload.content_type.unwrap_or_default())?; - // Reader lease of HOMEWORK_LOCK, held from the graded gate through the write. + const GRADED: AppError = AppError::Conflict( + "this homework has been graded — ask the teacher to remove the grade before adding files", + ); + // Reader lease as in `submit` — the audience interlock, not the freeze. + // Taken before the cap claim inside `insert`, never after (the lock order + // is HOMEWORK_LOCK, then the counter lock). let _guard = HOMEWORK_LOCK.read().await; + // The common-case gate; the freeze itself rides on the writes below. if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db) .await? .is_some() { - return Err(AppError::Conflict( - "this homework has been graded — ask the teacher to remove the grade before adding files", - )); + return Err(GRADED); } // A submission row must exist to hang the file off; auto-create an empty one // for the photo-only case rather than force a separate text submit first. - let submission = match HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db) - .await? - { - Some(existing) => existing, - None => HomeworkSubmission::upsert(homework.get_id(), user.get_id(), None, &st.db).await?, - }; + let submission = + match HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db).await? { + Some(existing) => existing, + None => HomeworkSubmission::upsert(homework.get_id(), user.get_id(), None, &st.db) + .await? + .ok_or(GRADED)?, + }; // Blob first, row second — a stored row always points at a real blob. The - // 10-file cap is enforced inside `insert` under its own lock (order: - // HOMEWORK_LOCK then the cap Mutex, never reversed). Unlink the fresh blob if - // the row insert loses the cap race. + // 10-file cap and the freeze are one conditional write on the submission row + // inside `insert`. Unlink the fresh blob if the row insert loses either. let file = HomeworkFile::new( submission.get_id(), name, @@ -833,10 +871,12 @@ async fn upload_submission_file( .await .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; let stored = match file.insert(&st.db).await { - Ok(stored) => stored, - Err(err) => { + Ok(Some(stored)) => stored, + // `None` is the freeze biting, an `Err` the file cap (or worse); either + // way the blob just written has no row and must go. + landed => { let _ = tokio::fs::remove_file(&path).await; - return Err(err); + return Err(landed.err().unwrap_or(GRADED)); } }; // A landed file moves the submission's "last touched" clock (the late flag). @@ -923,24 +963,29 @@ async fn delete_submission_file( Path((id, fid)): Path<(String, String)>, ) -> Result { let homework = gate_own_submission(&id, &user, &st.db).await?; + const GRADED: AppError = AppError::Conflict( + "this homework has been graded — ask the teacher to remove the grade before deleting files", + ); + // Reader lease as in `submit` — the audience interlock, not the freeze. let _guard = HOMEWORK_LOCK.read().await; if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db) .await? .is_some() { - return Err(AppError::Conflict( - "this homework has been graded — ask the teacher to remove the grade before deleting files", - )); + return Err(GRADED); } let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id()); let file = HomeworkFile::read_for(&HomeworkFileId::from_key(&fid), &submission, &st.db) .await? .ok_or(AppError::NotFound)?; let blob = file.get_file().to_string(); - file.delete(&st.db).await?; + // The delete's own transaction re-stamps the submission's "last touched" + // clock (the late flag) as its freeze gate, so a refused delete moves + // nothing and no separate touch is owed here. + if file.delete(&st.db).await?.is_none() { + return Err(GRADED); + } remove_blob(&st.files_path, &blob).await; - // A removed file moves the submission's "last touched" clock (the late flag). - HomeworkSubmission::touch(&submission, &st.db).await?; Ok(StatusCode::NO_CONTENT) } diff --git a/src/web/meals.rs b/src/web/meals.rs index cf10f5d..8152e10 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -242,7 +242,7 @@ async fn one_menu( (status = 400, description = "Malformed date, unknown slot, or out-of-range capacity", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), - (status = 409, description = "A menu already exists for that date and slot", body = ErrorResponse), + (status = 409, description = "A menu already exists for that date and slot, or the slot was removed from the settings mid-request", body = ErrorResponse), ), )] async fn create_menu( @@ -371,14 +371,8 @@ async fn delete_menu( let menu = Menu::read(&MenuId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - // [`MENU_LOCK`] holds the seat check and the delete together, so a booking - // cannot land on a menu that is already on its way out. - let _guard = MENU_LOCK.lock().await; - if MealBooking::any_live_for_menu(menu.get_id(), &st.db).await? { - return Err(AppError::Conflict( - "the menu still has live bookings — cancel them first", - )); - } + // The seat check rides in the delete's own `WHERE` (see `Menu::delete`), so + // a booking landing in another replica cannot slip between the two. menu.delete(&st.db).await?; Ok(StatusCode::NO_CONTENT) } @@ -416,15 +410,15 @@ async fn add_dish( .flatten(); let price = DishPrice::try_new(req.price_minor)?; let tags = DishTags::try_new(&req.tags, &Settings::load(&st.db).await?.get_dietary_tags())?; - // Dish writes take [`MENU_LOCK`] because a booking snapshots the menu's - // price under it: a dish landing mid-booking would be stored on the seat as - // "the menu was free", and a held seat is never re-priced. It also makes - // the dish cap a real cap — count-then-write is write-skew otherwise. The - // lock stays a leaf: nothing below here takes another. + // Dish writes take [`MENU_LOCK`] for the dish cap alone: count-then-write + // is write-skew, so the count and the insert have to be one step. The + // *price* no longer needs it — a dish write moves the menu's revision, and + // a booking claims its seat at the revision it priced itself against. + // The lock stays a leaf: nothing below here takes another. let _guard = MENU_LOCK.lock().await; - // The menu is read *inside* the lock, like `MealBooking::book` does: read - // before it, a `DELETE /menus/{id}` running in the gap takes its cascade - // with it and this dish lands on a menu that no longer exists. + // The menu is read *inside* the lock: read before it, a `DELETE /menus/{id}` + // running in the gap takes its cascade with it and this dish lands on a menu + // that no longer exists. let menu = Menu::read(&MenuId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; @@ -810,7 +804,7 @@ async fn booking_target( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not a student booking for themselves, nor a parent booking for a linked student", body = ErrorResponse), (status = 404, description = "No such menu", body = ErrorResponse), - (status = 409, description = "The menu is full, or its cutoff has passed", body = ErrorResponse), + (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), ), )] async fn book_meal( @@ -822,10 +816,10 @@ async fn book_meal( let student = booking_target(&user, req.student_id.as_deref(), &st.db).await?; let cutoff = meal_cutoff(&st.db).await?; let menu = MenuId::from_key(&id); - // Price, seat and charge all land together under `MENU_LOCK`, keyed by - // (seat, attempt) — a double-click books one seat and bills it once, and a - // dish cannot slip in between the price snapshot and the row it is frozen - // onto. + // Price, seat and charge land as one decision (see `MealBooking::book`), + // keyed by (seat, attempt) — a double-click books one seat and bills it + // once, and a dish landing between the price and the seat is refused by the + // claim rather than billed. let booking = MealBooking::book(&menu, &student, user.get_id(), &cutoff, &st.db).await?; let items = booking_responses(std::slice::from_ref(&booking), &st.db).await?; Ok(( @@ -927,7 +921,7 @@ async fn list_menu_bookings( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the booking's student, nor their parent", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "The cutoff has passed", body = ErrorResponse), + (status = 409, description = "The cutoff has passed, or the menu was too contended to free the seat", body = ErrorResponse), ), )] async fn cancel_booking( diff --git a/src/web/settings.rs b/src/web/settings.rs index 2d32920..72839ee 100644 --- a/src/web/settings.rs +++ b/src/web/settings.rs @@ -5,14 +5,17 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; +use surrealdb::types::RecordId; + use crate::constant::CAS_UPDATE_RETRIES; -use crate::domain::exam_result::ExamResult; -use crate::domain::menu::{MENU_LOCK, Menu}; +use crate::database::Database; +use crate::domain::cap; +use crate::domain::exam_result::kind_ref; +use crate::domain::menu::slot_ref; use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings}; use crate::error::{AppError, ErrorResponse}; use crate::state::AppState; -use super::exams::EXAM_LOCK; use super::{CurrentUser, RequireManager, set_or_clear}; pub fn routes() -> OpenApiRouter { @@ -231,7 +234,8 @@ async fn get_settings( /// every exam of that kind. For that reason a kind whose exams already carry /// marks cannot be dropped from the list (409) — those marks would silently /// re-weight to 1; an unmarked kind leaves freely, and an exam whose kind is -/// gone counts with weight 1 until the kind returns. `max_file_bytes` likewise +/// gone counts with weight 1 but cannot be graded (409) until the kind +/// returns — the other end of the same rule. `max_file_bytes` likewise /// applies at upload time only — already-stored files keep their size, and the /// chatbot knobs apply to the next chat request only. `meal_slots` follows the /// exam-kind rule: a slot a menu was already published for cannot be dropped @@ -259,21 +263,6 @@ async fn update_settings( // otherwise a concurrent PATCH of a *different* field would be silently // reverted by whichever whole-row write lands second. A refused save // reloads and re-merges, so both edits land. - // Writer lease of [`EXAM_LOCK`] while the kind list is being replaced: the - // no-marks check below and the save are one unit, so a grade (a reader) - // can't land the first mark of a kind that is being dropped mid-flight. - let _guard = match req.exam_kinds { - Some(_) => Some(EXAM_LOCK.write().await), - None => None, - }; - // Same shape for the slot list: the "was a menu ever published for it?" - // check and the save are one unit, so a publish cannot land on a slot that - // is being dropped mid-flight. Taken after EXAM_LOCK; nothing under - // MENU_LOCK ever takes EXAM_LOCK, so the pair cannot deadlock. - let _menu_guard = match req.meal_slots { - Some(_) => Some(MENU_LOCK.lock().await), - None => None, - }; for _ in 0..CAS_UPDATE_RETRIES { let current = Settings::load(&st.db).await?; @@ -284,26 +273,6 @@ async fn update_settings( .collect::, _>>()?, None => current.get_exam_kinds().to_vec(), }; - // A kind that graded exams still count under cannot leave the list — - // weights are read live, so dropping it would silently re-weight every - // mark of that kind. Re-checked on every retry: the snapshot it is - // diffed against is the one the save is conditioned on. - for gone in current.get_exam_kinds().iter().filter(|kind| { - !exam_kinds - .iter() - .any(|new| new.get_name() == kind.get_name()) - }) { - if ExamResult::any_for_kind(gone.get_name(), &st.db).await? { - return Err(AppError::ConflictOwned(format!( - "exams of kind '{}' are already graded — the kind cannot be removed", - gone.get_name() - ))); - } - } - // Same shape for meal slots: a slot a menu was already published for - // cannot leave the list — the menu snapshotted the name as text, and a - // slot no longer offered would leave that menu unreachable from the - // school's own list. let meal_slots = match &req.meal_slots { Some(slots) => slots .iter() @@ -311,18 +280,6 @@ async fn update_settings( .collect::, _>>()?, None => current.get_meal_slots(), }; - for gone in current.get_meal_slots().iter().filter(|slot| { - !meal_slots - .iter() - .any(|new| new.get_name() == slot.get_name()) - }) { - if Menu::any_for_slot(gone.get_name(), &st.db).await? { - return Err(AppError::ConflictOwned(format!( - "menus are already published for the '{}' slot — it cannot be removed", - gone.get_name() - ))); - } - } let attendance_statuses = req .attendance_statuses .clone() @@ -334,6 +291,13 @@ async fn update_settings( .collect::, _>>()?, None => current.get_grade_bands().to_vec(), }; + // The name lists as they stand and as they would stand, for the removal + // guards below — a list edit is judged by which names it drops. + let was_kinds = kind_names(current.get_exam_kinds()); + let now_kinds = kind_names(&exam_kinds); + let was_slots = slot_names(¤t.get_meal_slots()); + let now_slots = slot_names(&meal_slots); + // Merge over the snapshot's resolved values: an omitted field keeps // whatever the row (or the default behind an unset field) reads as. let mut params = current.params(); @@ -361,11 +325,105 @@ async fn update_settings( .unwrap_or(params.meal_cancel_cutoff_minutes); let settings = Settings::try_new(params)?; - if let Some(saved) = settings.save_if_unchanged(¤t, &st.db).await? { - return Ok(Json(SettingsResponse::new(&saved))); + + // The removal guards. A name leaves a list by being *retired* on its + // reference counter — one conditional write on one record, which lands + // only while nothing references the name and refuses every claim from + // that instant on. That is the whole guard: the check and the removal + // used to be a cross-table count and a save held together by a + // process-wide lock, which the second replica walked straight through. + // + // Retired before the save, never after: the other order leaves a window + // in which a mark lands under a kind the settings no longer list. A save + // that then does not land undoes them (`restore`) before the next try. + let mut retired: Vec = Vec::new(); + let mut refused = None; + for gone in missing(&was_kinds, &now_kinds) { + let counter = kind_ref(&gone); + if !cap::retire(&counter, &st.db).await? { + refused = Some(AppError::ConflictOwned(format!( + "exams of kind '{gone}' are already graded — the kind cannot be removed" + ))); + break; + } + retired.push(counter); + } + // Same shape for meal slots: a slot a menu was already published for + // cannot leave the list — the menu snapshotted the name as text, and a + // slot no longer offered would leave that menu unreachable from the + // school's own list. + if refused.is_none() { + for gone in missing(&was_slots, &now_slots) { + let counter = slot_ref(&gone); + if !cap::retire(&counter, &st.db).await? { + refused = Some(AppError::ConflictOwned(format!( + "menus are already published for the '{gone}' slot — it cannot be removed" + ))); + break; + } + retired.push(counter); + } + } + if let Some(refused) = refused { + restore(&retired, &st.db).await?; + return Err(refused); + } + // A name re-entering a list is back in service: its counter still + // carries the retirement from the edit that dropped it, and a mark (or + // a menu) under a kind the school offers again must not be refused. + for back in missing(&now_kinds, &was_kinds) { + cap::unretire(&kind_ref(&back), &st.db).await?; + } + for back in missing(&now_slots, &was_slots) { + cap::unretire(&slot_ref(&back), &st.db).await?; + } + + match settings.save_if_unchanged(¤t, &st.db).await { + Ok(Some(saved)) => return Ok(Json(SettingsResponse::new(&saved))), + // The row moved under the snapshot these guards were judged against: + // put the names back and re-merge, or the next attempt would decide + // against a list nobody asked for. + Ok(None) => restore(&retired, &st.db).await?, + Err(err) => { + restore(&retired, &st.db).await?; + return Err(err); + } } } Err(AppError::Conflict( "the settings kept changing underneath this update — try again", )) } + +fn kind_names(kinds: &[ExamKindDef]) -> Vec { + kinds + .iter() + .map(|kind| kind.get_name().to_string()) + .collect() +} + +fn slot_names(slots: &[MealSlotDef]) -> Vec { + slots + .iter() + .map(|slot| slot.get_name().to_string()) + .collect() +} + +/// The names `before` carries that `after` does not — a list edit's removals, +/// or its additions with the arguments swapped. +fn missing(before: &[String], after: &[String]) -> Vec { + before + .iter() + .filter(|name| !after.contains(name)) + .cloned() + .collect() +} + +/// Put back every name this attempt retired: the edit that would have removed +/// them did not land, so they are still names the school offers. +async fn restore(names: &[RecordId], db: &Database) -> Result<(), AppError> { + for name in names { + cap::unretire(name, db).await?; + } + Ok(()) +} diff --git a/src/web/subjects.rs b/src/web/subjects.rs index 2a27ff6..3786a0d 100644 --- a/src/web/subjects.rs +++ b/src/web/subjects.rs @@ -8,16 +8,11 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::course::{Course, CourseId}; -use crate::domain::exam_question::ExamQuestion; -use crate::domain::homework::Homework; use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; -use super::bank_questions::BANK_LOCK; use super::courses::{can_manage_course, can_view_course}; -use super::exams::EXAM_LOCK; -use super::homework::HOMEWORK_LOCK; use super::{CurrentUser, RequireTeacher, SubjectResponse}; pub fn routes() -> OpenApiRouter { @@ -194,35 +189,11 @@ async fn delete_subject( "only the course creator, an assigned teacher, or a manager/admin can delete this subject", )); } - // Writer lease of [`EXAM_LOCK`]: the no-questions check and the delete - // are one unit, so a question create/update that just validated this - // subject can't land its row on a subject that vanished mid-flight. - let _guard = EXAM_LOCK.write().await; - if ExamQuestion::any_for_subject(subject.get_id(), &st.db).await? { - return Err(AppError::Conflict( - "exam questions still reference this subject — re-tag or delete them first", - )); - } - // The homework twin of the guard above, under [`HOMEWORK_LOCK`]'s writer - // lease: homework create validates its subject under the read side and the - // PATCH re-tag under the write side, so the no-homework check and the - // delete can't straddle a row that just adopted this subject. This is the - // only place both locks are held; the order is EXAM_LOCK, then - // HOMEWORK_LOCK. - let _homework_guard = HOMEWORK_LOCK.write().await; - if Homework::any_for_subject(subject.get_id(), &st.db).await? { - return Err(AppError::Conflict( - "homework still references this subject — re-tag or delete it first", - )); - } - // Bank templates carry this subject as optional origin metadata, so they - // don't block: `Subject::delete` clears it off them in the delete's own - // transaction. Writer lease of [`BANK_LOCK`] all the same — bank - // create/update validate their subject and write under the reader lease, so - // without it a template could adopt this subject *after* the cascade ran - // and outlive it. Held last; the order is EXAM_LOCK, then HOMEWORK_LOCK, - // then BANK_LOCK. - let _bank_guard = BANK_LOCK.write().await; + // No locks: the two checks *are* the delete's `WHERE`, decided against the + // subject's own reference counters inside one statement. This used to be + // three process-wide locks (the only site that held more than one) around + // two cross-table counts, which served one replica and let the other create + // a question on a subject being deleted. subject.delete(&st.db).await?; Ok(StatusCode::NO_CONTENT) } diff --git a/src/web/terms.rs b/src/web/terms.rs index 91186cd..8b9c8a8 100644 --- a/src/web/terms.rs +++ b/src/web/terms.rs @@ -7,7 +7,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; -use crate::domain::term::{TERM_LOCK, Term, TermId, TermName}; +use crate::domain::term::{Term, TermId, TermName}; use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; @@ -229,14 +229,10 @@ async fn delete_term( let term = Term::read(&TermId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - // [`TERM_LOCK`] holds the link check and the delete together, so a course - // write that just resolved this term can't land its link on a dead row. - let _guard = TERM_LOCK.lock().await; - if Term::any_course(term.get_id(), &st.db).await? { + if !term.delete(&st.db).await? { return Err(AppError::Conflict( "courses are still linked to this term — unlink them first", )); } - term.delete(&st.db).await?; Ok(StatusCode::NO_CONTENT) } diff --git a/tests/integration.rs b/tests/integration.rs index b3302f5..f3cdfdb 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -3331,17 +3331,37 @@ async fn kind_weight_edits_reweight_reports_live() { // The PATCH above also retired `project` (allowed — no marks of that kind // existed yet; a graded kind can't leave at all, see - // `exam_kind_removal_blocks_while_marks_exist`). Its exam lives on and - // counts with weight 1. + // `exam_kind_removal_blocks_while_marks_exist`). Its exam lives on, but a + // retired kind takes no new marks: that is the other end of the same rule, + // and it is what keeps "a kind with marks cannot be removed" true however + // the two writes interleave. + let grade_project = async || { + send( + &app, + "POST", + &format!("/exams/{project}/results"), + Some(&teacher), + Some(json!({ "mark": 60, "user_id": alice_id })), + ) + .await + }; + assert_eq!(grade_project().await.status, StatusCode::CONFLICT); + // Offered again — at weight 1, so the exam counts exactly as an exam of a + // since-removed kind would have. let res = send( &app, - "POST", - &format!("/exams/{project}/results"), - Some(&teacher), - Some(json!({ "mark": 60, "user_id": alice_id })), + "PATCH", + "/settings", + Some(&manager), + Some(json!({ "exam_kinds": [ + {"name": "quiz", "weight": 1}, + {"name": "oral", "weight": 3}, + {"name": "project", "weight": 1}, + ]})), ) .await; assert_eq!(res.status, StatusCode::OK); + assert_eq!(grade_project().await.status, StatusCode::OK); // (40 + 240 + 60) / 5 = 68. let report = send(&app, "GET", "/marks/me", Some(&alice), None).await; assert_eq!(report.body["courses"][0]["average"], 68.0); @@ -4175,11 +4195,11 @@ async fn concurrent_enrolls_never_exceed_course_capacity() { /// be full forever. Stored state is the only witness: the embedded engine can /// tell two racers they both won, so the HTTP statuses prove nothing. // -// ponytail: `ENROLL_LOCK` serializes the enrolls inside one process, so what -// this actually drives is the already-enrolled early return; the `CREATE`-loser -// release only runs when the two racers sit on different replicas. Both paths -// are pinned by the same assertion below (counter == roster), which is the part -// that matters. +// Nothing serializes these any more: the seat and the row are claimed in one +// transaction (`cap::claim_and_create`), so a racer that loses the id has its +// own increment rolled back with the transaction and reads the winner's row +// instead of being told the course is full. Both the early return and that +// rollback are pinned by the assertion below (counter == roster). #[tokio::test] async fn concurrent_enrolls_of_one_pair_claim_one_seat() { let (app, db) = app_and_db().await; @@ -4229,6 +4249,317 @@ async fn concurrent_enrolls_of_one_pair_claim_one_seat() { ); } +/// The same stampede on a course with exactly one seat. Every racer enrolls the +/// *same* student, so between them they owe one seat — but on a cap this tight +/// the claim is the first thing to fail, and answering that with "the course is +/// full" would refuse a student the enrollment that just succeeded on their +/// behalf. So the pair's own row is looked for inside the claim's transaction, +/// before the seat is blamed. Drop that gate and every loser here is a 409. +#[tokio::test(flavor = "multi_thread", worker_threads = 8)] +async fn concurrent_enrolls_of_one_seat_never_refuse_their_own_winner() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "tight_teacher", "teacher").await; + let student = login(&app, "tight_student").await; + let student_id = me_id(&app, &student).await; + let res = send( + &app, + "POST", + "/courses", + Some(&teacher), + Some(json!({ "title": "one seat", "description": "", "capacity": 1 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let course = id_of(&res.body); + let uri = format!("/courses/{course}/enrollments"); + + let mut tasks = Vec::new(); + for _ in 0..8 { + let (app, teacher, uri) = (app.clone(), teacher.clone(), uri.clone()); + let body = json!({ "user_id": student_id }); + tasks.push(tokio::spawn(async move { + send(&app, "POST", &uri, Some(&teacher), Some(body)).await + })); + } + for task in tasks { + let res = task.await.unwrap(); + assert_eq!( + res.status, + StatusCode::OK, + "one student, one seat, no refusal: {}", + res.body + ); + } + + let roster = send(&app, "GET", &uri, Some(&teacher), None).await; + assert_eq!(common::total(&roster.body), 1, "one seat: {}", roster.body); + let mut counted = db + .query("SELECT VALUE enrollment_count FROM type::record('course', $c)") + .bind(("c", course.clone())) + .await + .expect("counter read") + .check() + .expect("counter read"); + assert_eq!( + counted.take::>(0).expect("counter column"), + vec![1], + "and the seat it cost is the one seat the course has" + ); +} + +/// The two reference counters a subject carries — the whole basis of its +/// delete guard — must equal the rows that actually point at it, through every +/// writer: create, re-tag, delete, and the exam cascade. Nothing recomputes +/// them, so a single missed decrement makes a subject undeletable forever. +/// +/// This bites on the halves the HTTP status alone cannot see. Drop the +/// release of the *old* subject from either re-tag and the counter drifts up: +/// the last delete below comes back 409 instead of 204. +#[tokio::test] +async fn subject_reference_counts_track_every_writer() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "refc_t", "teacher").await; + let course = create_course(&app, &teacher, "physics").await; + let from = create_subject(&app, &teacher, &course, "optics").await; + let to = create_subject(&app, &teacher, &course, "waves").await; + let exam = create_exam(&app, &teacher, &course, "midterm", "midterm").await; + let due = Timestamp::now().as_millis() + 86_400_000; + + let counts = async |subject: &str| -> (i64, i64) { + let mut result = db + .query( + "SELECT VALUE [exam_question_count ?? 0, homework_count ?? 0] \ + FROM type::record('subject', $s)", + ) + .bind(("s", subject.to_string())) + .await + .expect("counter read") + .check() + .expect("counter read"); + let pair = result + .take::>>(0) + .expect("counter columns") + .pop() + .expect("the subject row"); + (pair[0], pair[1]) + }; + + let question = create_question( + &app, + &teacher, + &exam, + &from, + json!({ "text": "How fast?", "kind": "text", "points": 10 }), + ) + .await; + let cascaded = create_question( + &app, + &teacher, + &exam, + &from, + json!({ "text": "How bright?", "kind": "text", "points": 10 }), + ) + .await; + let homework = create_homework(&app, &teacher, &course, &from, "lenses", due).await; + assert_eq!(counts(&from).await, (2, 1), "two questions and a homework"); + assert_eq!(counts(&to).await, (0, 0), "the spare subject holds nothing"); + + // A re-tag moves a reference: both ends must move, not just the new one. + let res = send( + &app, + "PATCH", + &format!("/exams/{exam}/questions/{question}"), + Some(&teacher), + Some(json!({ "subject_id": to })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "PATCH", + &format!("/homework/{homework}"), + Some(&teacher), + Some(json!({ "subject_id": to })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(counts(&from).await, (1, 0), "both re-tags must have left"); + assert_eq!(counts(&to).await, (1, 1), "and both must have arrived"); + + // A re-tag back to where it already is moves nothing. + let res = send( + &app, + "PATCH", + &format!("/homework/{homework}"), + Some(&teacher), + Some(json!({ "subject_id": to })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(counts(&to).await, (1, 1), "a no-op re-tag is a no-op"); + + // Deleting the referencing rows gives every reference back — including the + // question the *exam* cascade takes with it, which the row delete never + // sees. + let res = send( + &app, + "DELETE", + &format!("/homework/{homework}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + let res = send( + &app, + "DELETE", + &format!("/exams/{exam}/questions/{question}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + assert_eq!(counts(&to).await, (0, 0), "the new subject is free again"); + assert_eq!( + counts(&from).await, + (1, 0), + "the cascaded question still holds" + ); + assert!(!cascaded.is_empty()); + + let res = send( + &app, + "DELETE", + &format!("/exams/{exam}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + assert_eq!(counts(&from).await, (0, 0), "the exam cascade gave it back"); + + for subject in [&from, &to] { + let res = send( + &app, + "DELETE", + &format!("/subjects/{subject}"), + Some(&teacher), + None, + ) + .await; + assert_eq!( + res.status, + StatusCode::NO_CONTENT, + "an unreferenced subject must delete: {}", + res.body + ); + } +} + +/// A subject delete racing question creates on the same subject. Exactly one +/// outcome is legal, and it is decided by the delete's own `WHERE`: either the +/// subject is gone and *no* question points at it, or it survived and its +/// counter equals the questions that landed. Stored state is the only witness — +/// the embedded engine can tell two racers they both won, so the statuses prove +/// nothing. +/// +/// The count-then-delete this replaced fails here: it reads "no questions", +/// then deletes while a create that already passed its own subject check lands +/// its row on the corpse. +#[tokio::test] +async fn a_subject_delete_racing_question_creates_leaves_no_orphan() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "race_t", "teacher").await; + let course = create_course(&app, &teacher, "chemistry").await; + let subject = create_subject(&app, &teacher, &course, "bonds").await; + let exam = create_exam(&app, &teacher, &course, "quiz", "quiz").await; + // One question already tagged before the race starts, so the delete is + // never legal: whichever way the interleaving falls, it must be refused. + create_question( + &app, + &teacher, + &exam, + &subject, + json!({ "text": "first", "kind": "text", "points": 1 }), + ) + .await; + + let mut handles = Vec::new(); + for i in 0..8 { + let (app, teacher, exam, subject) = + (app.clone(), teacher.clone(), exam.clone(), subject.clone()); + handles.push(tokio::spawn(async move { + let body = json!({ + "text": format!("q{i}"), + "kind": "text", + "points": 1, + "subject_id": subject, + }); + send( + &app, + "POST", + &format!("/exams/{exam}/questions"), + Some(&teacher), + Some(body), + ) + .await + .status + })); + } + let killer = { + let (app, teacher, subject) = (app.clone(), teacher.clone(), subject.clone()); + tokio::spawn(async move { + send( + &app, + "DELETE", + &format!("/subjects/{subject}"), + Some(&teacher), + None, + ) + .await + .status + }) + }; + for handle in handles { + let status = handle.await.unwrap(); + assert!( + status == StatusCode::CREATED || status == StatusCode::BAD_REQUEST, + "a create either lands or is told the subject is gone, got {status}" + ); + } + let killed = killer.await.unwrap(); + + let mut result = db + .query("SELECT VALUE exam_question_count ?? 0 FROM type::record('subject', $s)") + .bind(("s", subject.clone())) + .await + .expect("counter read") + .check() + .expect("counter read"); + let counter = result.take::>(0).expect("counter column"); + let mut rows = db + .query("SELECT VALUE id FROM exam_question WHERE subject = type::record('subject', $s)") + .bind(("s", subject.clone())) + .await + .expect("row read") + .check() + .expect("row read"); + let landed = rows + .take::>(0) + .expect("question rows") + .len() as i64; + assert_eq!( + killed, + StatusCode::CONFLICT, + "a subject a question already points at may never be deleted" + ); + assert_eq!( + counter.first().copied(), + Some(landed), + "the subject must survive with its counter equal to the rows it guards" + ); +} + /// The signup list freezes the moment the event starts — both directions. /// (The create-time no-past grace lets a just-started event exist, which is /// exactly a closed list.) @@ -11235,14 +11566,15 @@ async fn settings_round_trip_the_food_program_knobs() { } // A published menu pins the slot it snapshotted: dropping it is a 409. - db.query( - "CREATE menu SET date = '2026-07-27', slot = 'lunch', - created_by = (SELECT VALUE id FROM user LIMIT 1)[0], created_at = 0", + let menu = send( + &app, + "POST", + "/meals/menus", + Some(&manager), + Some(json!({ "date": "2026-07-27", "slot": "lunch" })), ) - .await - .unwrap() - .check() - .unwrap(); + .await; + assert_eq!(menu.status, StatusCode::CREATED, "{}", menu.body); let res = send( &app, "PATCH", @@ -20939,6 +21271,63 @@ async fn concurrent_meal_bookings_never_exceed_the_capacity() { ) .await; assert_eq!(common::total(&res.body), 3, "and only three rows exist"); + + // The rows are downstream of the counter, so assert the counter itself: + // it is what every replica's `WHERE` compares, and a drift here would open + // the cap on the next booking however tidy the listing looks. + let mut counted = db + .query("SELECT VALUE seats_booked FROM type::record('menu', $m)") + .bind(("m", menu.clone())) + .await + .expect("counter read") + .check() + .expect("counter read"); + assert_eq!( + counted.take::>(0).expect("counter column"), + vec![3], + "the stored seat counter must agree with the seats handed out" + ); +} + +/// Publishing the same day+slot twice at once must be one menu and one 409 — +/// never two rows and never a 500. The day and slot *are* the record id, so the +/// racers collide on a single record inside the database rather than on a +/// check-then-write pair, which is the only form that also holds when the two +/// `POST`s land on different replicas. +#[tokio::test] +async fn concurrent_duplicate_menu_publishes_conflict_not_500() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "publish_race_mgr", "manager").await; + + let mut handles = Vec::new(); + for _ in 0..8 { + let app = app.clone(); + let mgr = mgr.clone(); + handles.push(tokio::spawn(async move { + send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-09-14", "slot": "lunch" })), + ) + .await + .status + })); + } + let mut published = 0; + for h in handles { + let status = h.await.unwrap(); + assert!( + status == StatusCode::CREATED || status == StatusCode::CONFLICT, + "a lost publish must be a 409, never a 500: {status}" + ); + published += i32::from(status == StatusCode::CREATED); + } + assert_eq!(published, 1, "exactly one publish won"); + + let res = send(&app, "GET", "/meals/menus", Some(&mgr), None).await; + assert_eq!(common::total(&res.body), 1, "and exactly one menu exists"); } /// 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() { ); } +/// The same stampede on a menu with exactly one seat. Every racer is the *same* +/// student, so between them they owe one seat — but each claims before it can +/// know another already placed the row, and the losers' claims are refused as +/// "full". Answering that with a 409 would refuse a student the booking that +/// just succeeded on their behalf, so a refused claim looks for this very seat +/// before it blames the cap. +#[tokio::test(flavor = "multi_thread", worker_threads = 8)] +async fn concurrent_bookings_of_one_seat_never_refuse_their_own_winner() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "tight_mgr", "manager").await; + let stu = login(&app, "tight_stu").await; + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 1 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let menu = id_of(&res.body); + + let mut tasks = Vec::new(); + for _ in 0..8 { + let (app, stu, menu) = (app.clone(), stu.clone(), menu.clone()); + tasks.push(tokio::spawn(async move { + send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&stu), + Some(json!({})), + ) + .await + })); + } + for task in tasks { + let res = task.await.unwrap(); + assert_eq!( + res.status, + StatusCode::CREATED, + "one student, one seat, no refusal: {}", + res.body + ); + } + + let res = send(&app, "GET", "/meals/bookings/me", Some(&stu), None).await; + assert_eq!(common::total(&res.body), 1, "one seat: {}", res.body); + let mut counted = db + .query("SELECT VALUE seats_booked FROM type::record('menu', $m)") + .bind(("m", menu.clone())) + .await + .expect("counter read") + .check() + .expect("counter read"); + assert_eq!( + counted.take::>(0).expect("counter column"), + vec![1], + "and the seat it cost is the one seat the menu has" + ); +} + /// A repeat POST racing the cancel. A cancel that reverses whatever charge it /// can find, off a booking row read before the lock, can flip the seat to /// `cancelled` while the charge of a newer attempt stands — the student owes diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs index c208620..c9278f3 100644 --- a/tests/limits_completeness.rs +++ b/tests/limits_completeness.rs @@ -45,6 +45,12 @@ const EXCLUDED: &[(&str, &str)] = &[ "CAP_WRITE_BACKOFF_MS", "internal backoff between cap counter retries", ), + ( + "SUBMISSION_OPEN_GUARD", + "SQL fragment: the condition every homework-submission write carries so \ + a grade freezes it in the database; the client sees the freeze as a 409, \ + never as a number", + ), ( "UPLOAD_BODY_OVERHEAD_BYTES", "multipart headroom over max_file_bytes; the client sizes against \ diff --git a/tests/name_refs.rs b/tests/name_refs.rs new file mode 100644 index 0000000..f630750 --- /dev/null +++ b/tests/name_refs.rs @@ -0,0 +1,400 @@ +//! The settings' two removal guards, now that they are reference counters +//! rather than a count-then-write under a process-wide lock: an exam kind may +//! leave `exam_kinds` only while no mark is written under it, and a meal slot +//! may leave `meal_slots` only while no menu is published for it. +//! +//! Each test below bites on one half of the pair — the retirement's `WHERE` +//! (nothing may leave while it is referenced) or the claim's (nothing may be +//! referenced once it has left). Drop either predicate and a test here fails; +//! that is the point of the suite, because the guard itself is invisible in +//! the happy path. + +mod common; + +use axum::http::StatusCode; +use common::{create_course, create_exam, enroll, login_as, me_id, send}; +use hezarfen_backend::database; +use serde_json::{Value, json}; + +/// The two kinds these tests move in and out of the school's list. +fn kinds(names: &[&str]) -> Value { + json!( + names + .iter() + .map(|name| json!({ "name": name, "weight": 1 })) + .collect::>() + ) +} + +fn slots(names: &[&str]) -> Value { + json!( + names + .iter() + .map(|name| json!({ "name": name, "serving_minute": 720 })) + .collect::>() + ) +} + +fn listed_kinds(body: &Value) -> Vec { + body["exam_kinds"] + .as_array() + .expect("exam_kinds") + .iter() + .map(|kind| kind["name"].as_str().expect("name").to_string()) + .collect() +} + +/// A graded student, an exam of `kind`, and the manager's cookie. +struct School { + app: axum::Router, + db: hezarfen_backend::database::Database, + boss: String, + course: String, + exam: String, + student: String, +} + +async fn school_with_kinds(names: &[&str]) -> School { + let (app, db) = common::app_and_db().await; + let boss = login_as(&app, &db, "boss", "manager").await; + let student_cookie = login_as(&app, &db, "kid", "student").await; + let student = me_id(&app, &student_cookie).await; + let res = send( + &app, + "PATCH", + "/settings", + Some(&boss), + Some(json!({ "exam_kinds": kinds(names) })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "seed exam kinds"); + let course = create_course(&app, &boss, "Maths").await; + enroll(&app, &boss, &course, &student).await; + let exam = create_exam(&app, &boss, &course, "Midterm", names[0]).await; + School { + app, + db, + boss, + course, + exam, + student, + } +} + +impl School { + async fn grade(&self, mark: i64) -> common::Res { + self.grade_exam(&self.exam.clone(), mark).await + } + + async fn grade_exam(&self, exam: &str, mark: i64) -> common::Res { + send( + &self.app, + "POST", + &format!("/exams/{exam}/results"), + Some(&self.boss), + Some(json!({ "user_id": self.student, "mark": mark })), + ) + .await + } + + async fn set_kinds(&self, names: &[&str]) -> common::Res { + send( + &self.app, + "PATCH", + "/settings", + Some(&self.boss), + Some(json!({ "exam_kinds": kinds(names) })), + ) + .await + } + + async fn settings(&self) -> Value { + send(&self.app, "GET", "/settings", Some(&self.boss), None) + .await + .body + } +} + +/// The retirement's `WHERE`: a kind a mark is written under does not leave the +/// list, and the refused edit changes *nothing* — not the stored list, and not +/// the kind's own usability. +#[tokio::test] +async fn a_graded_kind_cannot_be_removed_and_nothing_moves() { + let school = school_with_kinds(&["lab", "quiz"]).await; + assert_eq!(school.grade(80).await.status, StatusCode::OK); + + let res = school.set_kinds(&["quiz"]).await; + assert_eq!(res.status, StatusCode::CONFLICT); + assert_eq!( + res.body["error"], + "exams of kind 'lab' are already graded — the kind cannot be removed" + ); + + // The list the school reads back still carries the kind... + assert_eq!(listed_kinds(&school.settings().await), ["lab", "quiz"]); + // ...and so does the counter: a refused removal must not leave the kind + // retired, or every later grade under it would be refused instead. + assert_eq!(school.grade(90).await.status, StatusCode::OK); +} + +/// A regrade is not a second reference: one mark, one reference, however many +/// times it is overwritten — otherwise the counter would drift upward and the +/// kind could never be removed again. +#[tokio::test] +async fn marks_release_their_kind_when_they_are_deleted() { + let school = school_with_kinds(&["lab", "quiz"]).await; + for mark in [10, 20, 30] { + assert_eq!(school.grade(mark).await.status, StatusCode::OK); + } + + let res = send( + &school.app, + "DELETE", + &format!("/exams/{}/results/{}", school.exam, school.student), + Some(&school.boss), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT); + + // Nothing is graded under it any more, so it leaves freely. + assert_eq!(school.set_kinds(&["quiz"]).await.status, StatusCode::OK); + assert_eq!(listed_kinds(&school.settings().await), ["quiz"]); +} + +/// The claim's `WHERE`, the other half of the same race: once the kind is out +/// of the list, a mark can no longer land under it. Whichever of the two +/// writes reaches the counter first, the other is refused — which is what makes +/// the pair safe with two replicas and no shared lock. +#[tokio::test] +async fn a_removed_kind_refuses_a_grade() { + let school = school_with_kinds(&["lab", "quiz"]).await; + // Nothing graded yet, so the kind leaves — the exam keeps carrying it. + assert_eq!(school.set_kinds(&["quiz"]).await.status, StatusCode::OK); + + let res = school.grade(80).await; + assert_eq!(res.status, StatusCode::CONFLICT); + assert_eq!( + res.body["error"], + "the 'lab' exam kind has been removed from the school's settings — \ + add it back before grading this exam" + ); + + // Adding it back puts it in service again. + assert_eq!( + school.set_kinds(&["quiz", "lab"]).await.status, + StatusCode::OK + ); + assert_eq!(school.grade(80).await.status, StatusCode::OK); +} + +/// An exam's kind is frozen once it carries marks: re-pointing it would +/// re-weight them silently (and strand their references on the kind they were +/// counted under). Ungraded, it moves freely — and its next mark is counted +/// under the kind it moved to. +#[tokio::test] +async fn a_graded_exams_kind_is_frozen() { + let school = school_with_kinds(&["lab", "quiz"]).await; + let repoint = async || { + send( + &school.app, + "PATCH", + &format!("/exams/{}", school.exam), + Some(&school.boss), + Some(json!({ "kind": "quiz" })), + ) + .await + }; + // Ungraded: the move lands. + assert_eq!(repoint().await.status, StatusCode::OK); + assert_eq!(school.grade(80).await.status, StatusCode::OK); + // The mark went to the kind the exam now carries, not the one it left. + assert_eq!(school.set_kinds(&["quiz"]).await.status, StatusCode::OK); + assert_eq!( + school.set_kinds(&["lab", "quiz"]).await.status, + StatusCode::OK + ); + + // Graded: the move is refused, and the exam keeps the kind it had. + let back = send( + &school.app, + "PATCH", + &format!("/exams/{}", school.exam), + Some(&school.boss), + Some(json!({ "kind": "lab" })), + ) + .await; + assert_eq!(back.status, StatusCode::CONFLICT); + assert_eq!( + back.body["error"], + "cannot change the kind of an exam that already has marks" + ); + // Everything else on the exam still edits, marks or no marks. + let title = send( + &school.app, + "PATCH", + &format!("/exams/{}", school.exam), + Some(&school.boss), + Some(json!({ "title": "Midterm II" })), + ) + .await; + assert_eq!(title.status, StatusCode::OK); +} + +/// Deleting an exam frees exactly the marks it cascaded — no more. Two exams +/// share the kind here: releasing one mark too many (the shape a count taken +/// outside the cascade's transaction produces) would read as no marks left and +/// let the kind walk out of the settings while the second exam is still graded. +#[tokio::test] +async fn deleting_one_exam_frees_only_its_own_marks() { + let school = school_with_kinds(&["lab", "quiz"]).await; + let second = create_exam(&school.app, &school.boss, &school.course, "Final", "lab").await; + assert_eq!(school.grade(80).await.status, StatusCode::OK); + assert_eq!(school.grade_exam(&second, 70).await.status, StatusCode::OK); + + let gone = send( + &school.app, + "DELETE", + &format!("/exams/{}", school.exam), + Some(&school.boss), + None, + ) + .await; + assert_eq!(gone.status, StatusCode::NO_CONTENT); + + // The other exam's mark still holds the kind down. + let refused = school.set_kinds(&["quiz"]).await; + assert_eq!(refused.status, StatusCode::CONFLICT); + assert_eq!( + refused.body["error"], + "exams of kind 'lab' are already graded — the kind cannot be removed" + ); + + // Only when the last graded exam goes does the kind go free. + let last = send( + &school.app, + "DELETE", + &format!("/exams/{second}"), + Some(&school.boss), + None, + ) + .await; + assert_eq!(last.status, StatusCode::NO_CONTENT); + assert_eq!(school.set_kinds(&["quiz"]).await.status, StatusCode::OK); +} + +/// A course delete cascades its exams' marks, so it owes their kinds the same +/// references back — otherwise the kind is held down by marks that no longer +/// exist, forever. +#[tokio::test] +async fn deleting_a_course_frees_the_kinds_its_marks_held() { + let school = school_with_kinds(&["lab", "quiz"]).await; + assert_eq!(school.grade(80).await.status, StatusCode::OK); + // A course with a roster refuses the delete; the mark stays either way. + common::unenroll(&school.app, &school.boss, &school.course, &school.student).await; + + let gone = send( + &school.app, + "DELETE", + &format!("/courses/{}", school.course), + Some(&school.boss), + None, + ) + .await; + assert_eq!(gone.status, StatusCode::NO_CONTENT, "{}", gone.body); + + assert_eq!(school.set_kinds(&["quiz"]).await.status, StatusCode::OK); + assert_eq!(listed_kinds(&school.settings().await), ["quiz"]); +} + +/// The same pair for meal slots, whose reference is a published menu. +#[tokio::test] +async fn a_published_menu_pins_its_meal_slot() { + let (app, db) = common::app_and_db().await; + let boss = login_as(&app, &db, "boss", "manager").await; + let set_slots = async |names: &[&str]| { + send( + &app, + "PATCH", + "/settings", + Some(&boss), + Some(json!({ "meal_slots": slots(names) })), + ) + .await + }; + assert_eq!(set_slots(&["lunch", "snack"]).await.status, StatusCode::OK); + + let menu = send( + &app, + "POST", + "/meals/menus", + Some(&boss), + Some(json!({ "date": "2030-01-09", "slot": "lunch" })), + ) + .await; + assert_eq!(menu.status, StatusCode::CREATED); + let menu_id = common::id_of(&menu.body); + + let refused = set_slots(&["snack"]).await; + assert_eq!(refused.status, StatusCode::CONFLICT); + assert_eq!( + refused.body["error"], + "menus are already published for the 'lunch' slot — it cannot be removed" + ); + + // Retire the menu and the slot is free to leave — then no new menu may be + // published under it. + let deleted = send( + &app, + "DELETE", + &format!("/meals/menus/{menu_id}"), + Some(&boss), + None, + ) + .await; + assert_eq!(deleted.status, StatusCode::NO_CONTENT); + assert_eq!(set_slots(&["snack"]).await.status, StatusCode::OK); + + let late = send( + &app, + "POST", + "/meals/menus", + Some(&boss), + Some(json!({ "date": "2030-01-10", "slot": "lunch" })), + ) + .await; + assert_eq!( + late.status, + StatusCode::BAD_REQUEST, + "slot is no longer served" + ); +} + +/// Marks and menus written before the counters existed still hold their name +/// down: the boot backfill counts them once. Aged by deleting the counter rows +/// a live binary keeps — which is exactly the state an older binary's database +/// arrives in. +#[tokio::test] +async fn rows_written_before_the_counters_are_counted_at_boot() { + let school = school_with_kinds(&["lab", "quiz"]).await; + assert_eq!(school.grade(80).await.status, StatusCode::OK); + + school + .db + .query("DELETE kind_ref; DELETE slot_ref;") + .await + .expect("age the database") + .check() + .expect("aged"); + + // Without the backfill the mark is invisible to the guard and the kind + // walks straight out of the list. + database::migrate(&school.db).await.expect("reboot"); + + let res = school.set_kinds(&["quiz"]).await; + assert_eq!(res.status, StatusCode::CONFLICT); + assert_eq!( + res.body["error"], + "exams of kind 'lab' are already graded — the kind cannot be removed" + ); +} diff --git a/tests/persistence.rs b/tests/persistence.rs index 9fec108..ddaba92 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -10,6 +10,7 @@ use axum::Router; use axum::http::StatusCode; use common::{create_course, create_exam, create_subject, enroll, me_id, send, set_role}; use hezarfen_backend::database::Database; +use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::rate_limit::RateLimitConfig; use hezarfen_backend::state::AppState; use hezarfen_backend::{build_router, database}; @@ -1264,3 +1265,342 @@ async fn cap_counters_are_seeded_from_the_rows_that_predate_them() { let up = common::upload_file(&app, &ali, ¬e, "eleventh.txt", "", b"x").await; assert_eq!(up.status, StatusCode::CONFLICT, "{}", up.body); } + +/// The appointment slot's counter is the odd one out: it seeds from the +/// bookings that are still *live*, because a rejected or cancelled one gave the +/// slot back long before the column existed (2026-07-27). A slot aged into the +/// pre-counter shape must come back taken if someone is still waiting on it, +/// and free if nobody is — a flat recount of its rows would get the second case +/// wrong and lock a free slot out of the calendar for good. +#[tokio::test] +async fn slot_occupancy_is_seeded_from_the_bookings_that_are_still_live() { + let (app, db) = common::app_and_db().await; + let teacher = common::login_as(&app, &db, "teacher", "teacher").await; + let veli = common::login(&app, "veli").await; + let ayse = common::login(&app, "ayse").await; + let now = hezarfen_backend::domain::timestamp::Timestamp::now().as_millis(); + let hour = 3_600_000; + + async fn publish(app: &Router, who: &str, starts_at: i64) -> String { + let res = send( + app, + "POST", + "/appointments/slots", + Some(who), + Some(json!({ "starts_at": starts_at, "ends_at": starts_at + 3_600_000 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + common::id_of(&res.body[0]) + } + async fn book(app: &Router, who: &str, slot: &str) -> common::Res { + send( + app, + "POST", + "/appointments", + Some(who), + Some(json!({ "slot": slot, "reason": "görüşme" })), + ) + .await + } + + let taken = publish(&app, &teacher, now + hour).await; + let freed = publish(&app, &teacher, now + 3 * hour).await; + let held = common::id_of(&book(&app, &veli, &taken).await.body); + let gone = common::id_of(&book(&app, &veli, &freed).await.body); + let res = send( + &app, + "PATCH", + &format!("/appointments/{gone}/reject"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // Age both slots into the pre-counter shape. + db.query("UPDATE appointment_slot UNSET occupied;") + .await + .expect("age the rows") + .check() + .expect("age the rows"); + + let app = reboot(&db).await; + + // The still-pending booking keeps its slot; the rejected one's slot is free. + let res = book(&app, &ayse, &taken).await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + let res = book(&app, &ayse, &freed).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + + // And the seeded seat is still a seat, not a stuck flag: cancelling the + // held booking hands it back. + let res = send( + &app, + "PATCH", + &format!("/appointments/{held}/cancel"), + Some(&veli), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = book(&app, &ayse, &taken).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); +} + +/// A submission graded before the freeze moved into the database (2026-07-27) +/// carries no `graded_by_result` stamp, and an absent stamp is exactly what the +/// student's writes now take as "still open" — so without the backfill an +/// upgrade would quietly unfreeze every already-graded submission. The backfill +/// stamps each one from the grade it already has; graded-but-never-submitted +/// work has no row to stamp and must stay that way (the report reads +/// `submitted`/`missing` straight off its absence). +#[tokio::test] +async fn graded_submissions_are_stamped_by_the_backfill() { + let (app, db) = common::app_and_db().await; + let teacher = common::login_as(&app, &db, "teacher", "teacher").await; + let ali = common::login(&app, "ali").await; + let veli = common::login(&app, "veli").await; + let (ali_id, veli_id) = (me_id(&app, &ali).await, me_id(&app, &veli).await); + let course = create_course(&app, &teacher, "math").await; + let subject = create_subject(&app, &teacher, &course, "algebra").await; + enroll(&app, &teacher, &course, &ali_id).await; + enroll(&app, &teacher, &course, &veli_id).await; + let due_at = Timestamp::now().as_millis() + 86_400_000; + let hw = common::create_homework(&app, &teacher, &course, &subject, "essay", due_at).await; + + // Ali hands in and is graded; Veli never hands in and is graded `missing`. + let res = send( + &app, + "POST", + &format!("/homework/{hw}/submission"), + Some(&ali), + Some(json!({ "text": "version A" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + for (user, status) in [(&ali_id, "done"), (&veli_id, "missing")] { + let res = send( + &app, + "POST", + &format!("/homework/{hw}/results"), + Some(&teacher), + Some(json!({ "user": user, "status": status })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + } + + // Age the row into the pre-stamp shape. + db.query("UPDATE homework_submission UNSET graded_by_result;") + .await + .expect("age the row") + .check() + .expect("age the row"); + let app = reboot(&db).await; + + let mut stamps = db + .query("SELECT VALUE graded_by_result FROM homework_submission; SELECT VALUE id FROM homework_submission;") + .await + .expect("read stamps") + .check() + .expect("read stamps"); + let stamped = stamps + .take::>(0) + .expect("graded_by_result"); + let rows = stamps + .take::>(1) + .expect("submission ids"); + assert_eq!(rows.len(), 1, "grading absent work must not conjure a row"); + assert_eq!( + stamped.len(), + 1, + "the surviving submission must come back stamped by its grade" + ); + assert_eq!( + format!("{:?}", stamped[0].key), + format!("{:?}", rows[0].key), + "the stamp must name the grade of that very (homework, user) pair" + ); + assert_eq!( + stamped[0].table.to_string(), + "homework_result", + "the stamp must point at the grade table" + ); + + // And the freeze bites again, which an unstamped row would not have done. + let res = send( + &app, + "POST", + &format!("/homework/{hw}/submission"), + Some(&ali), + Some(json!({ "text": "version B" })), + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + // Veli, graded but never submitted, still reports as not-submitted. + let res = send( + &app, + "GET", + &format!("/homework/{hw}/submission"), + Some(&veli), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); +} + +/// A menu written before the seat counter existed (2026-07-27) carries none, +/// which reads as zero — an uncapped menu for every seat already sold. The +/// backfill seeds it from the bookings that are still *held*: a cancelled one +/// gave its seat back long before the column existed, so counting rows flatly +/// would lock out a seat nobody holds. +#[tokio::test] +async fn menu_seats_are_seeded_from_the_bookings_that_are_still_held() { + let (app, db) = common::app_and_db().await; + let mgr = common::login_as(&app, &db, "seat_mgr", "manager").await; + let ali = common::login(&app, "seat_ali").await; + let veli = common::login(&app, "seat_veli").await; + let ayse = common::login(&app, "seat_ayse").await; + + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 2 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let menu = common::id_of(&res.body); + + let book = async |who: &str| { + send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(who), + Some(json!({})), + ) + .await + }; + let held = book(&ali).await; + assert_eq!(held.status, StatusCode::CREATED, "{}", held.body); + let given_back = common::id_of(&book(&veli).await.body); + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{given_back}"), + Some(&veli), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // Age the menu into the pre-counter shape. + db.query("UPDATE menu UNSET seats_booked;") + .await + .expect("age the row") + .check() + .expect("age the row"); + + // Same database, so the router above keeps serving; what matters is that + // the migration ran again over the aged row. + let _ = reboot(&db).await; + + let mut counted = db + .query("SELECT VALUE seats_booked FROM menu") + .await + .expect("counter read") + .check() + .expect("counter read"); + assert_eq!( + counted.take::>(0).expect("counter column"), + vec![1], + "only the seat still held may be counted back" + ); + + // The seeded counter is a real cap, not a decoration: one seat is left. + assert_eq!(book(&ayse).await.status, StatusCode::CREATED); + assert_eq!(book(&veli).await.status, StatusCode::CONFLICT); +} + +/// A subject written before its two reference counters existed (2026-07-27) +/// carries neither, and an absent counter reads as zero — which is exactly +/// "nothing points at me", so the delete guard would wave through a subject +/// half the school's questions are tagged with. The backfill counts the rows +/// that actually point at each subject, once. +/// +/// The bite is the last assertion: seed the counters wrong (or not at all) and +/// the delete comes back `204` instead of `409`. +#[tokio::test] +async fn subject_reference_counts_are_seeded_from_the_rows_that_predate_them() { + let (app, db) = common::app_and_db().await; + let teacher = common::login_as(&app, &db, "seed_t", "teacher").await; + let course = create_course(&app, &teacher, "biology").await; + let tagged = create_subject(&app, &teacher, &course, "cells").await; + let untouched = create_subject(&app, &teacher, &course, "genes").await; + let exam = create_exam(&app, &teacher, &course, "quiz", "quiz").await; + for text in ["what?", "why?"] { + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions"), + Some(&teacher), + Some(json!({ + "text": text, + "kind": "text", + "points": 1, + "subject_id": tagged, + })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + } + let due = Timestamp::now().as_millis() + 86_400_000; + common::create_homework(&app, &teacher, &course, &tagged, "mitosis", due).await; + + // Age both subjects into the pre-counter shape. + db.query("UPDATE subject UNSET exam_question_count, homework_count;") + .await + .expect("age the rows") + .check() + .expect("age the rows"); + + let app = reboot(&db).await; + + let mut counted = db + .query( + "SELECT VALUE [exam_question_count ?? 0, homework_count ?? 0] \ + FROM subject ORDER BY id ASC", + ) + .await + .expect("counter read") + .check() + .expect("counter read"); + assert_eq!( + counted.take::>>(0).expect("counter columns"), + vec![vec![2, 1], vec![0, 0]], + "each subject must be seeded from the rows that point at it" + ); + + // The seeded counters are the delete guard itself, not a decoration. + let res = send( + &app, + "DELETE", + &format!("/subjects/{tagged}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + let res = send( + &app, + "DELETE", + &format!("/subjects/{untouched}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); +}