From ac70cc0fa4b98d28d6873a4660556b3497b61edb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 30 Jul 2026 07:45:47 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=A7=8A=20freeze=20a=20fee=20plan?= =?UTF-8?q?=20the=20moment=20it=20is=20assigned?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 409 that stops an assigned plan being edited or deleted was a scan followed, some microseconds later, by the write it licensed. An assign landing in that gap left a plan edited and assigned, or deleted with a live assignment still naming it. The comment called it an accepted race and blamed the other replica; there was never another replica, and two concurrent requests in one process were always enough. A plan now carries an assignment refcount. The assign claims it in the same transaction that writes the row, and the edit and the delete are conditional writes that refuse while it stands. The plan freezes at the instant of the claim, so the assign re-reads it afterwards and bills the copy that froze — the refcount alone still let an edit slip in front and bill the snapshot the handler had read. Existing plans are seeded from the assignments they already carry. An absent counter reads as zero, which is the value that licenses an edit, so a plan assigned before this would otherwise have come unfrozen. Two things this uncovered. A cap claim that lost a write conflict was answered as a 500 five times in six: the retryable conflict shared the error batch with the sibling statements it aborted, and an arbitrary one of those was returned. And a guarded write had no retry at all, so a raced PATCH or DELETE failed outright rather than trying again. The race tests run against a real server. On the embedded engine they watched a 45-in-50 failure rate and passed. --- README.md | 29 ++- src/constant.rs | 13 ++ src/database.rs | 156 +++++++++++++++- src/domain/cap.rs | 32 ++-- src/domain/fee_plan.rs | 62 ++++-- src/domain/fee_plan_assignment.rs | 300 ++++++++++++++++++++++++++---- src/domain/field_update.rs | 60 ++++-- src/lib.rs | 2 +- src/migration_sql.rs | 26 +++ src/web/payments.rs | 48 +++-- tests/limits_completeness.rs | 6 + 11 files changed, 618 insertions(+), 116 deletions(-) diff --git a/README.md b/README.md index 7f32488..b3ed172 100644 --- a/README.md +++ b/README.md @@ -1485,6 +1485,27 @@ A plan that has been assigned to anyone can no longer be edited or deleted an edit would only make the plan and the money tell different stories — write a new plan instead. +That freeze is a **counter on the plan row** (`assignment_count`), incremented +in the *same transaction* as the assignment row it counts, and the edit and the +delete are single-record conditional writes against it — the same shape as a +term's `course_count`. It used to be a `SELECT` taken before the write, which a +concurrent assign could land behind, leaving a plan edited *and* assigned, or +deleted with a live assignment naming it. Now the two contend on one record: an +assign either freezes the plan first (and the edit or delete is a `409`) or +arrives after it (and bills the edited plan — the installments a first +assignment charges are re-read from the *stored* plan at the instant it +freezes, never from the copy the request first looked at). A plan deleted out +from under a running batch is `rejected` for that student on, in the same +per-student report as every other outcome — the students it already billed are +never dropped from the answer. A `PATCH` +carrying no field at all writes nothing, so it is not refused. + +Because an assignment is never removed, the counter is only ever claimed and +never released: once assigned, a plan stays frozen for good. Plans written +before the counter existed are seeded from their assignment rows at boot, +before the server accepts a request — an absent counter reads as zero, and a +zero would have re-opened every already-assigned plan on an existing volume. + ### The ledger The money is an **append-only ledger** (`payment_ledger`), exactly like the @@ -2475,9 +2496,13 @@ database itself decides the winner. Three tiers: 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). + link, and give it back when the link moves or the course is deleted). A fee + plan reads the same way — editable *and* deletable while its + `assignment_count` is zero, and frozen for good once it is not, since an + assignment is never taken back. Where the child also carries a deterministic id — one enrollment per - (course, user), one registration per (event, user) — the seat and the row + (course, user), one registration per (event, user), one fee-plan assignment + per (plan, student) — 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: diff --git a/src/constant.rs b/src/constant.rs index d0a0f7a..60ef900 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -686,6 +686,19 @@ pub const REGISTRATION_COUNT_FIELD: &str = "registration_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"; +/// A refcount too, and the whole of the fee-plan edit *and* delete guard: how +/// many students are on this plan. A plan may only be edited or deleted at +/// zero, and the count is claimed in the same transaction as the assignment +/// row, so a manager's edit and a concurrent assign contend on the plan row +/// rather than on a `SELECT` the edit had already outrun. Nothing ever +/// releases it — an assignment is never unassigned, because the charges it +/// raised are history. +pub const FEE_PLAN_ASSIGNMENT_COUNT_FIELD: &str = "assignment_count"; +/// The condition itself, spelled once: a plan is editable and deletable +/// exactly while nobody is on it. The `??` is parenthesized on purpose — +/// `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which is truthy for *every* +/// row and would license editing a plan a family is already being billed for. +pub const FEE_PLAN_UNASSIGNED_GUARD: &str = "(assignment_count ?? 0) = 0"; 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"; diff --git a/src/database.rs b/src/database.rs index b34f5fa..917e952 100644 --- a/src/database.rs +++ b/src/database.rs @@ -5,7 +5,8 @@ use surrealdb::engine::any::Any; use surrealdb::opt::auth::Root; use crate::config::Config; -use crate::constant::CHATBOT_PENDING_STALE_SECS; +use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS}; +use crate::domain::timestamp::Timestamp; use crate::domain::user::{Password, User, Username}; use crate::error::AppError; use crate::migration_sql::MIGRATION_BATCHES; @@ -102,6 +103,51 @@ pub(crate) fn lost_the_race(err: &surrealdb::Error) -> bool { message.contains("already exists") || message.contains("can be retried") } +/// Send one guarded single-statement write, re-sending it while the store +/// answers "conflict, retry", and hand back the rows it returned. +/// +/// The guard on such a statement reads a column a rival writes, so the two +/// contend on one record *by design* — that contention is what makes the guard +/// atomic. Losing a round writes nothing at all, which makes re-sending the +/// whole of the recovery; without it an ordinary raced `PATCH` or `DELETE` +/// answers 500 instead of the 404 or 409 it owes. Only for statements that +/// cannot produce "already exists" (the other thing [`lost_the_race`] matches), +/// so `UPDATE` and `DELETE` and not `CREATE`. +pub(crate) async fn write_with_retry( + db: &Database, + sql: &str, + bindings: &[(String, surrealdb::types::Value)], +) -> Result, AppError> { + let mut last = None; + for attempt in 0..CAP_WRITE_TRIES { + backoff(attempt).await; + let mut query = db.query(sql); + for (name, value) in bindings { + query = query.bind((name.clone(), value.clone())); + } + match async { query.await?.check()?.take::>(0) }.await { + Ok(rows) => return Ok(rows), + Err(err) if lost_the_race(&err) => last = Some(err), + Err(err) => return Err(err.into()), + } + } + Err(last + .map(AppError::from) + .unwrap_or_else(|| AppError::Internal("a guarded 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. +pub(crate) 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; +} + /// Dial the database, retrying until it answers. /// /// Never gives up, because giving up is worse than waiting: the database is @@ -137,6 +183,42 @@ pub async fn init_mem() -> Result { Ok(std::sync::Arc::new(db)) } +/// A handle on a **real** SurrealDB server, in a scratch namespace of its own +/// that is dropped and re-made on every call. For the tests whose subject is +/// the store's own conflict detection, which [`init_mem`]'s embedded engine +/// does not have: it drops one of two concurrent writes to a record and answers +/// `Ok` to both (see [`crate::domain::cap`]), which *forges* the very +/// integrity failure those tests exist to catch — measured 2026-07-30 at 2 +/// failed runs in 36 on `memory`, against 0 in 10 000 rounds here. +/// +/// Every caller is `#[ignore]`d, so a machine with no server prints them as +/// `ignored` rather than passing: this is not a test that may quietly skip. +/// `HEZARFEN_TEST_DB` overrides the address; the credentials are `compose.yaml`'s. +#[cfg(test)] +pub(crate) async fn init_test_server(scratch: &str) -> Database { + let url = + std::env::var("HEZARFEN_TEST_DB").unwrap_or_else(|_| "ws://127.0.0.1:8000".to_string()); + let db = surrealdb::engine::any::connect(url.clone()) + .await + .unwrap_or_else(|err| panic!("no SurrealDB server at {url} ({err})")); + db.signin(Root { + username: "root".into(), + password: "root".into(), + }) + .await + .expect("sign in to the test server"); + let ns = format!("test_{scratch}"); + db.query(format!("REMOVE NAMESPACE IF EXISTS {ns}")) + .await + .expect("clear the scratch namespace") + .check() + .expect("clear the scratch namespace"); + db.use_ns(ns.clone()).use_db(ns).await.expect("scratch ns"); + let db = std::sync::Arc::new(db); + migrate(&db).await.expect("migrate the scratch namespace"); + db +} + /// Apply the schema + backfills. Idempotent — `init` runs it on every boot, /// and tests re-run it on a live handle to simulate a second boot. pub async fn migrate(db: &Surreal) -> Result<(), AppError> { @@ -221,6 +303,78 @@ mod tests { assert!(interrupted["completed_at"].as_i64().unwrap() > 0); } + /// Stale-data path for the 2026-07-30 fee-plan refcount. A dev volume + /// carries plans and assignments written before the counter column existed, + /// and an absent counter reads as **zero** — which is exactly the value + /// that licenses an edit and a delete. Unseeded, every already-assigned + /// plan on every existing volume would go editable and deletable again, so + /// the backfill is the whole of the stale-data story, not a nicety. + #[tokio::test] + async fn a_plan_assigned_before_the_counter_existed_is_still_refused() { + use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName}; + use crate::error::AppError; + + let db = super::init_mem().await.unwrap(); + // The old shape: rows stating every column the older binary knew, and + // no `assignment_count` at all. `used` carries an assignment, `free` + // does not — a plan nobody is on must stay editable. + db.query( + "CREATE user:m SET username = 'm', password_hash = 'x'; + CREATE user:s SET username = 's', password_hash = 'x'; + CREATE fee_plan:used SET name = 'Yearly', + installments = [{ amount_minor: 100, due_at: 1 }], + created_by = user:m, created_at = 1; + CREATE fee_plan:free SET name = 'Unused', + installments = [{ amount_minor: 100, due_at: 1 }], + created_by = user:m, created_at = 1; + CREATE fee_plan_assignment:used_s SET plan = fee_plan:used, + student = user:s, assigned_by = user:m, created_at = 1;", + ) + .await + .unwrap() + .check() + .unwrap(); + + // Twice: every boot runs the backfill, and a second pass must not + // double a counter it already seeded. + super::migrate(&db).await.unwrap(); + super::migrate(&db).await.unwrap(); + + let mut counts = db + .query("SELECT VALUE assignment_count FROM fee_plan ORDER BY id") + .await + .unwrap(); + let counts: Vec> = counts.take(0).unwrap(); + // `free` before `used` by id; the unused plan is deliberately left + // absent, which already reads as zero in the guard. + assert_eq!(counts, vec![None, Some(1)]); + + // The load-bearing half: the seeded plan is frozen, and the untouched + // one is not. + let used = FeePlan::read(&FeePlanId::from_key("used"), &db) + .await + .unwrap() + .unwrap(); + assert!(matches!( + used.clone() + .update(Some(FeePlanName::try_new("Edited").unwrap()), None, &db) + .await, + Err(AppError::Conflict(_)) + )); + assert!(!used.delete(&db).await.unwrap()); + let free = FeePlan::read(&FeePlanId::from_key("free"), &db) + .await + .unwrap() + .unwrap(); + assert!( + free.clone() + .update(Some(FeePlanName::try_new("Edited").unwrap()), None, &db) + .await + .is_ok() + ); + assert!(free.delete(&db).await.unwrap()); + } + #[tokio::test] async fn the_retired_claim_columns_are_dropped_off_a_live_row() { // Stale-data path for the 2026-07-30 removal of the chat claim queue. diff --git a/src/domain/cap.rs b/src/domain/cap.rs index 4499483..1c0b504 100644 --- a/src/domain/cap.rs +++ b/src/domain/cap.rs @@ -29,9 +29,8 @@ use surrealdb::types::{RecordId, SurrealValue}; use tokio::sync::Mutex; -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::constant::{CAP_WRITE_TRIES, REF_COUNT_FIELD, REF_RETIRED_FIELD}; +use crate::database::{Database, backoff, lost_the_race}; use crate::error::AppError; /// One counter writer at a time, over every counter. @@ -196,13 +195,18 @@ pub(crate) async fn claim_and_create( { 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); + // A conflict in *any* slot is the whole batch's verdict, and it is read + // before the arbitrary pick below: the siblings say only "not executed", + // which is the *consequence* of this abort and never a reason of its + // own. Picking one of those out of a `HashMap` — unordered, so it wins + // most rounds — retired a retryable round as a 500. + if errors.values().any(lost_the_race) { + last = errors.drain().map(|(_, error)| error).find(lost_the_race); continue; } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5. return result .take::>(5)? @@ -216,18 +220,6 @@ pub(crate) async fn claim_and_create( .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 diff --git a/src/domain/fee_plan.rs b/src/domain/fee_plan.rs index bca4a8f..c4545d6 100644 --- a/src/domain/fee_plan.rs +++ b/src/domain/fee_plan.rs @@ -16,8 +16,10 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{FEE_PLAN_TABLE, MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN}; -use crate::database::Database; +use crate::constant::{ + FEE_PLAN_TABLE, FEE_PLAN_UNASSIGNED_GUARD, MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN, +}; +use crate::database::{Database, write_with_retry}; use crate::domain::field_update::FieldUpdate; use crate::domain::monotonic_id::next_ulid; use crate::domain::page::PagedList; @@ -169,13 +171,19 @@ impl FeePlan { /// Write only the fields the PATCH carried — `None` means the request /// omitted it, so the column is left alone rather than re-stated from the - /// snapshot this struct was read into. + /// snapshot this struct was read into. `Err(Conflict)` = refused, nothing + /// was written: somebody is already on the plan. /// /// Editing a plan never moves money: charges are frozen copies of the - /// installments as they stood when the plan was assigned. The web layer - /// refuses the edit outright once [`FeePlan::has_assignments`] holds, so a - /// plan and the charges raised from it cannot drift apart in the first - /// place. + /// installments as they stood when the plan was assigned. That is exactly + /// why an assigned plan may not be edited at all — the plan and the charges + /// raised from it would tell different stories. The roster is the plan's own + /// [`crate::constant::FEE_PLAN_ASSIGNMENT_COUNT_FIELD`] refcount, claimed in the same + /// transaction as the assignment row, so the check and the write are one + /// conditional `UPDATE` on one record: an assign racing this either claims + /// first (and the edit is refused) or claims after (and bills the edited + /// plan, which it re-reads). A `SELECT`-then-write could be, and was, + /// stepped over in the gap between the two. pub async fn update( self, name: Option, @@ -188,24 +196,38 @@ impl FeePlan { FieldUpdate::new(self.id.record()) .set("name", name) .set("installments", installments) + .guard( + FEE_PLAN_UNASSIGNED_GUARD, + AppError::Conflict("an assigned plan cannot be edited"), + ) .run::(db) .await } - pub async fn delete(self, db: &Database) -> Result<(), AppError> { - let _: Option = db.delete(self.id.record()).await?; - Ok(()) - } - - /// Has this plan ever been assigned? The 409 guard on edit and delete. + /// Delete the plan, but only while nobody is on it. `false` = refused, + /// nothing was written; `Err(NotFound)` keeps the answer a concurrent + /// *delete* gives. Same one-record guard as [`FeePlan::update`], and the + /// same reason — the charges an assignment raised name this plan, and a + /// school's financial history keeps its references. /// - /// A scan, and deliberately so: it races an assign landing in the gap - /// between this read and the edit it licenses, which can leave a plan edited - /// *and* assigned. Accepted — both versions of the plan were manager-approved, - /// and the charges the assign raised are frozen copies either way, so no - /// money moves behind anyone's back. - pub async fn has_assignments(id: &FeePlanId, db: &Database) -> Result { - crate::domain::fee_plan_assignment::FeePlanAssignment::exists_for_plan(id, db).await + /// Retried while the store answers "conflict, retry": the guard reads a + /// counter an assign *writes*, so the two contend on this one record by + /// design — and a delete that loses that round has written nothing, so + /// re-sending it is the whole of the recovery. Without the retry an + /// ordinary raced delete answers 500 instead of the 404 or 409 it owes. + pub async fn delete(self, db: &Database) -> Result { + let sql = format!("DELETE $plan WHERE {FEE_PLAN_UNASSIGNED_GUARD} RETURN BEFORE"); + let deleted: Vec = + write_with_retry(db, &sql, &[("plan".into(), self.id.record().into_value())]).await?; + if !deleted.is_empty() { + return Ok(true); + } + // Still assigned 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/domain/fee_plan_assignment.rs b/src/domain/fee_plan_assignment.rs index 893d5b9..1e701c4 100644 --- a/src/domain/fee_plan_assignment.rs +++ b/src/domain/fee_plan_assignment.rs @@ -12,12 +12,14 @@ //! //! Nothing is ever edited or deleted: unassigning is not a thing, because the //! charges are already history. A plan raised in error is undone by reversing -//! its charges. +//! its charges. That is also why the plan's assignment refcount is only ever +//! claimed and never released — a plan, once assigned, stays frozen for good. -use surrealdb::types::{AlreadyExistsError, RecordId, RecordIdKey, SurrealValue}; +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::FEE_PLAN_ASSIGNMENT_TABLE; -use crate::database::{Database, lost_the_race}; +use crate::constant::{FEE_PLAN_ASSIGNMENT_COUNT_FIELD, FEE_PLAN_ASSIGNMENT_TABLE}; +use crate::database::Database; +use crate::domain::cap::{self, Claimed}; use crate::domain::fee_plan::{FeePlan, FeePlanId}; use crate::domain::page::PagedList; use crate::domain::payment_ledger::PaymentLedger; @@ -90,6 +92,20 @@ impl FeePlanAssignment { /// whether it was *already* there, so the web layer can answer a replay /// honestly instead of pretending it just happened. /// + /// The row and the plan's assignment refcount are written in **one** + /// transaction ([`cap::claim_and_create`]): that increment is what makes the + /// plan un-editable and un-deletable, and it has to be indivisible from the + /// row it counts, or an edit could slip between the two. A plan the counter + /// cannot be claimed on is one a concurrent delete already removed, which is + /// the same `404` the handler's own lookup would have given. + /// + /// The installments are then re-read **from the stored plan**, not taken + /// from the caller's snapshot: the claim is the moment the plan freezes, and + /// an edit that landed between the handler's read and that claim is + /// legitimate. Billing the snapshot would raise charges from a schedule the + /// plan no longer shows — precisely the divergence the 409 exists to + /// prevent. + /// /// The charges are appended after the row, never before: each one is keyed /// by (assignment, installment number), so this loop is safe to re-enter /// from the top — which is exactly what a repeated assign does, and the @@ -101,30 +117,35 @@ impl FeePlanAssignment { db: &Database, ) -> Result<(FeePlanAssignment, bool), AppError> { let id = FeePlanAssignmentId::composite(plan.get_id(), student); - let (assignment, existed) = match Self::read(&id, db).await? { - Some(existing) => (existing, true), - None => { - let row = FeePlanAssignment { - id: id.clone(), - plan: plan.get_id().clone(), - student: student.clone(), - assigned_by: assigned_by.clone(), - created_at: Timestamp::now(), - }; - match db.create(id.record()).content(row).await { - Ok(Some(created)) => (created, false), - // Someone assigned this pair first, or the write was - // aborted as retryable — either way their row is the - // answer, and the charges below are keyed the same, so - // continuing here can only *complete* the billing. - Ok(None) => (Self::require(&id, db).await?, true), - Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => { - (Self::require(&id, db).await?, true) - } - Err(e) => return Err(e.into()), - } - } + let row = FeePlanAssignment { + id: id.clone(), + plan: plan.get_id().clone(), + student: student.clone(), + assigned_by: assigned_by.clone(), + created_at: Timestamp::now(), + }; + let claimed = cap::claim_and_create( + &plan.get_id().record(), + FEE_PLAN_ASSIGNMENT_COUNT_FIELD, + cap::UNLIMITED, + &id.record(), + &row, + db, + ) + .await?; + let (assignment, existed) = match claimed { + Claimed::Made(created) => (created, false), + // Someone assigned this pair first — their row is the answer, and + // the charges below are keyed the same, so continuing here can only + // *complete* the billing. Their claim already counts this row. + Claimed::Duplicate => (Self::require(&id, db).await?, true), + // The counter is uncapped, so the only miss is a plan that is gone. + Claimed::Full => return Err(AppError::NotFound), }; + // Frozen as of the claim above: no edit can land past it any more. + let plan = FeePlan::read(plan.get_id(), db) + .await? + .ok_or_else(|| AppError::Internal("the assigned fee plan vanished".into()))?; for (index, installment) in plan.get_installments().iter().enumerate() { PaymentLedger::charge_for_installment( &assignment, @@ -170,8 +191,10 @@ impl FeePlanAssignment { .await } - /// Is anybody on this plan? Backs the edit/delete guard — see - /// [`FeePlan::has_assignments`] for the race it accepts. + /// Is anybody on this plan? A scan, and no longer a guard: the edit and + /// delete guards read the plan's own refcount, which no concurrent assign + /// can be behind. Kept because a *test* asserting the rows and the counter + /// agree is the only thing that would catch the counter drifting. pub async fn exists_for_plan(plan: &FeePlanId, db: &Database) -> Result { let mut result = db .query("SELECT VALUE id FROM fee_plan_assignment WHERE plan = $plan LIMIT 1") @@ -198,15 +221,6 @@ impl FeePlanAssignment { } } -/// Did this `CREATE` fail *only* because the row is already there? Same typed -/// match, and the same reasoning, as the ledger's. -fn is_duplicate_record(error: &surrealdb::Error) -> bool { - matches!( - error.already_exists_details(), - Some(AlreadyExistsError::Record { .. }) - ) -} - #[cfg(test)] mod tests { use super::*; @@ -275,4 +289,214 @@ mod tests { .unwrap() ); } + + /// The race the refcount exists for: an edit and an assign, both licensed + /// by the same instant. + /// + /// "Neither lands" is *not* the invariant — the two are legal in one order + /// (edit, then assign the edited plan) and illegal in the other. What may + /// never happen is the money and the plan disagreeing: the charges raised + /// must be copies of the schedule the plan actually ends up carrying, and + /// once anybody is on the plan no further edit or delete may land at all. + /// + /// Asserted against the **stored** state, never against which call returned + /// `Ok`: a winner's word is not evidence about what the store kept. + /// The one thing the *returned* values are good for is the second + /// invariant: neither racer may answer 500. Losing a single-record round to + /// a rival is the ordinary way this guard works, and the loser's recovery is + /// to re-send, not to fail the request. + /// + /// Multi-threaded on purpose: on the single-threaded runtime the two tasks + /// interleave only at await points and the store never reports a conflict at + /// all, which is how a version of this test watched a 45-in-50 500 rate and + /// passed. + /// + /// Real server, and `#[ignore]`d rather than falling back to `init_mem`: + /// the embedded engine drops one of two concurrent writes to a record and + /// answers `Ok` to both, which fails this very assertion out of nowhere + /// (measured 2026-07-30: 2 runs in 36 on `memory` under host load, 0 in + /// 10 000 rounds on the server). See [`crate::database::init_test_server`]. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn an_edit_racing_an_assign_leaves_the_plan_and_the_money_agreeing() { + let db = crate::database::init_test_server("edit_race").await; + let mut reached = 0; + for round in 0..20 { + let manager = UserId::from_key("mgr1"); + let student = UserId::from_key(&format!("stu{round}")); + let plan = FeePlan::create( + FeePlanName::try_new("Yearly").unwrap(), + vec![Installment::new( + LedgerAmount::try_new(100).unwrap(), + Timestamp::from_millis(1_000), + )], + &manager, + &db, + ) + .await + .unwrap(); + + let edit = { + let (plan, db) = (plan.clone(), db.clone()); + tokio::spawn(async move { + plan.update( + None, + Some(vec![Installment::new( + LedgerAmount::try_new(999).unwrap(), + Timestamp::from_millis(2_000), + )]), + &db, + ) + .await + }) + }; + let assign = { + let (plan, db, manager, student) = + (plan.clone(), db.clone(), manager.clone(), student.clone()); + tokio::spawn(async move { + FeePlanAssignment::assign(&plan, &student, &manager, &db).await + }) + }; + let (edit, assign) = (edit.await.unwrap(), assign.await.unwrap()); + assert!( + !matches!(edit, Err(AppError::Db(_))), + "a raced edit must be refused, not 500: {edit:?}" + ); + assert!( + !matches!(assign, Err(AppError::Db(_))), + "a raced assign must retry, not 500: {assign:?}" + ); + + let stored = FeePlan::read(plan.get_id(), &db).await.unwrap().unwrap(); + let assigned = FeePlanAssignment::exists_for_plan(plan.get_id(), &db) + .await + .unwrap(); + if assigned { + reached += 1; + // The counter is what refuses every later edit, so it has to + // agree with the rows it stands for. + let (lines, _) = PaymentLedger::list_for_student(&student, None, 0, &db) + .await + .unwrap(); + assert_eq!(lines.len(), 1, "one installment, one charge"); + assert_eq!( + lines[0].get_amount_minor().as_minor(), + stored.get_installments()[0].get_amount_minor().as_minor(), + "the charge must be a copy of the plan as it now stands" + ); + assert!( + plan.clone().update(None, None, &db).await.is_ok(), + "an empty PATCH writes nothing, so it is not refused" + ); + assert!( + matches!( + plan.clone() + .update(Some(FeePlanName::try_new("Nope").unwrap()), None, &db) + .await, + Err(AppError::Conflict(_)) + ), + "an assigned plan stays frozen afterwards" + ); + assert!( + !plan.clone().delete(&db).await.unwrap(), + "and it cannot be deleted either" + ); + } + } + // Every assertion above sits behind "the assign landed", so a run where + // it never did asserts nothing at all — the failure this counter turns + // into a loud one. + assert!(reached > 0, "no round ever placed the assignment"); + } + + /// The other half, and here "never both" *is* the invariant: a delete and + /// an assign racing must never leave a live assignment — with the charges + /// it billed — pointing at a plan that is gone. Stored state again, and a + /// real server again, for the same reasons. + /// + /// Both orderings are forced, because the interesting one does not happen on + /// its own: with both racers released together the assign wins ~24 rounds in + /// 25, so a run that only ever saw that ordering never tested a delete + /// landing first at all. Half the rounds therefore hold the assign back by a + /// beat, and the two counters below fail the test if either ordering went + /// unseen. Neither racer may answer 500 here either — this is the pair that + /// contends hardest, both writing the plan record itself. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_delete_racing_an_assign_never_orphans_an_assignment() { + let db = crate::database::init_test_server("delete_race").await; + let (mut deleted_first, mut assigned_first) = (0, 0); + for round in 0..20 { + let hold_back_the_assign = round % 2 == 0; + let manager = UserId::from_key("mgr1"); + let student = UserId::from_key(&format!("stu{round}")); + let plan = FeePlan::create( + FeePlanName::try_new("Yearly").unwrap(), + vec![Installment::new( + LedgerAmount::try_new(100).unwrap(), + Timestamp::from_millis(1_000), + )], + &manager, + &db, + ) + .await + .unwrap(); + + let head_start = std::time::Duration::from_millis(5); + let drop_it = { + let (plan, db) = (plan.clone(), db.clone()); + tokio::spawn(async move { + if !hold_back_the_assign { + tokio::time::sleep(head_start).await; + } + plan.delete(&db).await + }) + }; + let assign = { + let (plan, db, manager, student) = + (plan.clone(), db.clone(), manager.clone(), student.clone()); + tokio::spawn(async move { + if hold_back_the_assign { + tokio::time::sleep(head_start).await; + } + FeePlanAssignment::assign(&plan, &student, &manager, &db).await + }) + }; + let (drop_it, assign) = (drop_it.await.unwrap(), assign.await.unwrap()); + assert!( + !matches!(drop_it, Err(AppError::Db(_))), + "a raced delete must retry, not 500: {drop_it:?}" + ); + assert!( + !matches!(assign, Err(AppError::Db(_))), + "a raced assign must retry, not 500: {assign:?}" + ); + + let gone = FeePlan::read(plan.get_id(), &db).await.unwrap().is_none(); + let assigned = FeePlanAssignment::exists_for_plan(plan.get_id(), &db) + .await + .unwrap(); + deleted_first += usize::from(gone); + assigned_first += usize::from(assigned); + assert!( + !(gone && assigned), + "an assignment may not outlive the plan it names" + ); + let (lines, _) = PaymentLedger::list_for_student(&student, None, 0, &db) + .await + .unwrap(); + assert!( + !(gone && !lines.is_empty()), + "and neither may the charges it raised" + ); + } + // The premise, not a nicety: "never both" is trivially true in a run + // where one of the two never landed, so a run that only saw one + // ordering has proven nothing and says so. + assert!(deleted_first > 0, "no round ever let the delete land first"); + assert!( + assigned_first > 0, + "no round ever let the assign land first" + ); + } } diff --git a/src/domain/field_update.rs b/src/domain/field_update.rs index 8695fcd..fa2ea3a 100644 --- a/src/domain/field_update.rs +++ b/src/domain/field_update.rs @@ -24,7 +24,7 @@ use surrealdb::types::{RecordId, SurrealValue, Value}; -use crate::database::Database; +use crate::database::{Database, write_with_retry}; use crate::error::AppError; pub struct FieldUpdate { @@ -34,6 +34,8 @@ pub struct FieldUpdate { bindings: Vec<(String, Value)>, /// `(low, high, refusal)` for [`FieldUpdate::ordered`]. ordered: Option<(&'static str, &'static str, AppError)>, + /// `(condition, refusal)` for [`FieldUpdate::guard`]. + guard: Option<(&'static str, AppError)>, } impl FieldUpdate { @@ -43,6 +45,7 @@ impl FieldUpdate { assignments: Vec::new(), bindings: Vec::new(), ordered: None, + guard: None, } } @@ -77,6 +80,23 @@ impl FieldUpdate { self } + /// Refuse the write unless `condition` — a predicate on this same row — + /// still holds at write time. The [`FieldUpdate::ordered`] guard for a + /// precondition that is not about a range: a handler that read "nothing + /// references this yet" re-asks the database at the instant it writes, so a + /// reference landing in between refuses the edit instead of being edited + /// out from under. `condition` is always an in-crate SQL literal, never + /// user input. + /// + /// A request that carries no field at all emits no `UPDATE`, so it is not + /// refused: it writes nothing, and reading the row back is a truthful + /// answer to a PATCH that asked for no change. + #[must_use] + pub fn guard(mut self, condition: &'static str, refused: AppError) -> Self { + self.guard = Some((condition, refused)); + self + } + /// Run the update and return the stored row. An empty request writes /// nothing at all and reads the row back unchanged. pub async fn run(mut self, db: &Database) -> Result { @@ -84,7 +104,7 @@ impl FieldUpdate { let row: Option = db.select(self.id).await?; return row.ok_or(AppError::NotFound); } - let (guard, mut refused) = match self.ordered.take() { + let (ordered, mut refused) = match self.ordered.take() { // Both ends stored: name the bound variable for an end this request // set, the column for one it left alone. Some((low, high, err)) if self.is_set(low) || self.is_set(high) => { @@ -98,26 +118,38 @@ impl FieldUpdate { let low = side(low, self.is_set(low)); let high = side(high, self.is_set(high)); ( - format!(" WHERE ({low} = NONE OR {high} = NONE OR {low} <= {high})"), + Some(format!( + "({low} = NONE OR {high} = NONE OR {low} <= {high})" + )), Some(err), ) } - _ => (String::new(), None), + _ => (None, None), + }; + // Both guards land on the one `UPDATE`, ANDed. No caller sets both, so + // the refusal is whichever one is there. + let (extra, extra_refused) = match self.guard.take() { + Some((condition, err)) => (Some(condition.to_string()), Some(err)), + None => (None, None), + }; + refused = refused.or(extra_refused); + let conditions: Vec = ordered.into_iter().chain(extra).collect(); + let guard = if conditions.is_empty() { + String::new() + } else { + format!(" WHERE {}", conditions.join(" AND ")) }; let sets = self.assignments.join(", "); - let mut query = db - .query(format!("UPDATE $id SET {sets}{guard} RETURN AFTER")) - .bind(("id", self.id)); - for (name, value) in self.bindings { - query = query.bind((name, value)); - } - let mut result = query.await?.check()?; + let sql = format!("UPDATE $id SET {sets}{guard} RETURN AFTER"); + self.bindings.push(("id".into(), self.id.into_value())); + // Retried on a write conflict: a guarded PATCH contends on the very row + // its guard reads, and the loser wrote nothing, so re-sending it is the + // recovery — see [`write_with_retry`]. + let rows: Vec = write_with_retry(db, &sql, &self.bindings).await?; // No row back means the guard bit (or, in the window after the handler's // read, the row was deleted — the guard cannot tell the two apart, and // reports the refusal it was given). - result - .take::>(0)? - .into_iter() + rows.into_iter() .next() .ok_or_else(|| refused.take().unwrap_or(AppError::NotFound)) } diff --git a/src/lib.rs b/src/lib.rs index ea3fe43..15fb48e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -58,7 +58,7 @@ use crate::state::AppState; (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams — no `mode`, or `open` — drop out); without it the list stays newest-first"), (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` — `date` is text, `YYYY-MM-DD`, and `slot` must be one of the school's `meal_slots` from `GET /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` — edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer — this API never speaks decimals or floats about money. Deleting a menu takes its dishes with it. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` — own always, otherwise teacher+ or a parent link — and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list — the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served); every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) — staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat; a full menu is a `409`, and that cap is serialized in-process, since a cross-record count is not conflict-checked against a concurrent insert. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** — cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. The school's `meal_cancel_cutoff_minutes` closes both ends at once — inside that window neither booking nor cancelling lands (`409`) — measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** — this API stores no school timezone, so staff enter UTC). A slot with no `serving_minute` set falls back to midnight UTC of that date, the pre-serving-time behaviour. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to — the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** — no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row, under the same in-process lock every dish write takes, so no dish can land between the sum and the seat), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once — the charge and its reversal are keyed by (booking, attempt) and written under the same in-process lock as the seat, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge — the charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` — `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked — no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?}`) and is **admin-only**, not manager — the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as teacher+ or as a parent linked to them"), - (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` — a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruş) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. There is no scheduler and no sweep. Assignment is **replay-safe by identity** — an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) — so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree — write a new plan instead. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** — it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) — allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, …}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters — no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `_k_` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice — even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `_r` and so reverses once however often it is retried. Payments and refunds are capped by the line they target (`409` past it) — that cap is a cross-record sum, which the database cannot enforce on its own — it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", …). Every write here is **manager+** — teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope — the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ — **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup — plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) — all folded from the raw lines on every request and stored nowhere"), + (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` — a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruş) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. There is no scheduler and no sweep. Assignment is **replay-safe by identity** — an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) — so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree — write a new plan instead. That freeze is a **counter on the plan row**, incremented in the same transaction as the assignment it counts, and the edit and the delete are conditional writes against it — so a manager editing a plan at the very instant it is being assigned is decided one way or the other by the database, never left half-applied, and the installments a first assignment bills are read back from the stored plan at the moment it freezes. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** — it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) — allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, …}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters — no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `_k_` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice — even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `_r` and so reverses once however often it is retried. Payments and refunds are capped by the line they target (`409` past it) — that cap is a cross-record sum, which the database cannot enforce on its own — it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", …). Every write here is **manager+** — teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope — the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ — **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup — plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) — all folded from the raw lines on every request and stored nowhere"), (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Also the food program: the meal slots menus are published for — each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) — the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` — one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. Read: any authenticated user; edit: manager+"), (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"), diff --git a/src/migration_sql.rs b/src/migration_sql.rs index 98302cd..1a7a54a 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -651,6 +651,12 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS installments.*.due_at ON fee_plan TYPE int; DEFINE FIELD IF NOT EXISTS created_by ON fee_plan TYPE record READONLY; DEFINE FIELD IF NOT EXISTS created_at ON fee_plan TYPE int READONLY; + -- How many students are on the plan. The edit and delete guards read it, + -- an assignment's own transaction increments it, and nothing decrements it + -- (assignments are never removed). `option` and no DEFAULT, like every + -- other counter: no Rust struct carries it, so the plan's create must not + -- be expected to state it. + DEFINE FIELD IF NOT EXISTS assignment_count ON fee_plan TYPE option; -- One plan on one student, keyed `_`: assigning twice is the -- same record id, so a replay writes nothing and an assignment cut short @@ -947,6 +953,26 @@ pub const BACKFILL: &str = " 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 fee-plan guard became a refcount (2026-07-30): editing or deleting a + -- plan is now refused by `(assignment_count ?? 0) = 0` on the plan row + -- itself, instead of by a scan a concurrent assign could land behind. + -- + -- This seeding is what keeps a *stale* volume safe: a plan written by an + -- older binary carries no counter, an absent counter reads as zero, and a + -- zero would make an already-assigned plan editable and deletable again — + -- the exact thing the 409 exists to prevent. Boot seeds it from the + -- assignment rows that actually exist, and `migrate` runs to completion + -- before the router is bound, so no request is ever served against the + -- unseeded shape. `= NONE` keeps it one-time, so a second boot recomputes + -- nothing. + -- + -- No zero pass, for the same reason the subject counters get none: a plan + -- nobody is on has no assignment rows, and absent already reads as zero in + -- the guard — writing it would touch every plan row to say what it says. + FOR $row IN ((SELECT plan, count() AS n FROM fee_plan_assignment GROUP BY plan) ?? []) { + UPDATE $row.plan SET assignment_count = $row.n WHERE assignment_count = NONE; + }; "; /// The migration batches, in the order a boot applies them — and the *only* diff --git a/src/web/payments.rs b/src/web/payments.rs index 7c4230c..1541851 100644 --- a/src/web/payments.rs +++ b/src/web/payments.rs @@ -247,6 +247,12 @@ async fn get_plan( /// been assigned to anyone: those charges are frozen copies of the installments /// as they stood, so editing afterwards would leave the plan and the money /// telling different stories. Write a new plan instead. +/// +/// The refusal is decided by the database as the edit is written, not by a +/// read taken before it, so an assign arriving at the same instant cannot end +/// up on either side of the edit: it either freezes the plan first (and this is +/// a `409`) or bills the edited schedule. A PATCH carrying no field at all +/// writes nothing and returns the plan unchanged, assigned or not. #[utoipa::path( patch, path = "/plans/{id}", @@ -270,7 +276,6 @@ async fn update_plan( Json(req): Json, ) -> Result, AppError> { let plan = require_plan(&id, &st.db).await?; - ensure_unassigned(plan.get_id(), "an assigned plan cannot be edited", &st.db).await?; let name = req.name.as_deref().map(FeePlanName::try_new).transpose()?; let installments = req.installments.map(InstallmentBody::list).transpose()?; let plan = plan.update(name, installments, &st.db).await?; @@ -282,7 +287,9 @@ async fn update_plan( /// Delete a plan. Refused (`409`) once it has been assigned to anyone — the /// charges it raised name it, and a school's financial history keeps its -/// references. +/// references. Decided as the delete is written, the same way the edit is, so a +/// simultaneous assign can never leave a live assignment pointing at a plan +/// that is gone. #[utoipa::path( delete, path = "/plans/{id}", @@ -303,22 +310,10 @@ async fn delete_plan( Path(id): Path, ) -> Result { let plan = require_plan(&id, &st.db).await?; - ensure_unassigned(plan.get_id(), "an assigned plan cannot be deleted", &st.db).await?; - plan.delete(&st.db).await?; - Ok(StatusCode::NO_CONTENT) -} - -/// The shared 409 guard behind editing and deleting a plan. A scan, and -/// deliberately so — see [`FeePlan::has_assignments`] for the race it accepts. -async fn ensure_unassigned( - plan: &FeePlanId, - reason: &'static str, - db: &Database, -) -> Result<(), AppError> { - if FeePlan::has_assignments(plan, db).await? { - return Err(AppError::Conflict(reason)); + if !plan.delete(&st.db).await? { + return Err(AppError::Conflict("an assigned plan cannot be deleted")); } - Ok(()) + Ok(StatusCode::NO_CONTENT) } // ---- assignments ------------------------------------------------------------ @@ -361,6 +356,13 @@ struct FeePlanAssignmentResponse { /// Only students carry a fee record, so any other target is rejected. One bad /// id never loses the rest of the batch: the response reports each student /// separately. +/// +/// Placing the first student **freezes** the plan: it can no longer be edited +/// or deleted. The installments billed are read back from the stored plan at +/// that instant, so an edit that landed a moment earlier is the one billed, +/// never the version this request first looked at. A plan deleted while the +/// batch is running is `rejected` from that student on — a per-student outcome +/// like any other, so the students it already billed stay in the report. #[utoipa::path( post, path = "/plans/{id}/assignments", @@ -398,9 +400,15 @@ async fn assign_plan( .await? .is_some_and(|user| user.get_role() == Role::Student); let (status, reason) = if is_student { - match FeePlanAssignment::assign(&plan, &student, manager.get_id(), &st.db).await? { - (_, true) => ("already_assigned", None), - (_, false) => ("assigned", None), + match FeePlanAssignment::assign(&plan, &student, manager.get_id(), &st.db).await { + Ok((_, true)) => ("already_assigned", None), + Ok((_, false)) => ("assigned", None), + // The plan was deleted mid-batch. That is a per-student outcome + // like any other, not a reason to throw away the report for the + // students this batch already billed — their charges are + // written and the caller has to be told about them. + Err(AppError::NotFound) => ("rejected", Some("no such plan")), + Err(err) => return Err(err), } } else { ("rejected", Some("no such student")) diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs index abaa3b6..77f4b23 100644 --- a/tests/limits_completeness.rs +++ b/tests/limits_completeness.rs @@ -51,6 +51,12 @@ const EXCLUDED: &[(&str, &str)] = &[ a grade freezes it in the database; the client sees the freeze as a 409, \ never as a number", ), + ( + "FEE_PLAN_UNASSIGNED_GUARD", + "SQL fragment: the condition a fee plan's edit and delete carry so an \ + assigned plan freezes 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 \