From 9b09fd10cfbd7de14b574a0468a55e30188731ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 17 Jul 2026 22:17:52 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(events):=20stop=20capacity?= =?UTF-8?q?=20over-admit=20and=20re-register=20seat=20rewrite?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The capacity check ran inside BEGIN/COMMIT, but SurrealDB does not conflict-check a cross-record count() against a concurrent insert (write-skew) — two racing placements both saw the last seat free and a capacity-1 event admitted 2. Serialize the check-then-write under a process-wide lock instead (embedded DB, single writer) and drop the transaction plus its error-scan/slot arithmetic. Re-registering an already-seated student was an UPSERT that silently rewrote registered_by to the second caller; the documented contract is a no-op. Return the existing row untouched and CREATE only new seats. Regression tests: concurrent placements never exceed capacity, re-register returns the seat untouched, concurrent settings PATCHes both land (the same write-skew probe against the CAS loop — it held). --- src/domain/registration.rs | 68 +++++++--------- tests/integration.rs | 158 +++++++++++++++++++++++++++++++++++++ 2 files changed, 188 insertions(+), 38 deletions(-) diff --git a/src/domain/registration.rs b/src/domain/registration.rs index 0536136..bdbfdc4 100644 --- a/src/domain/registration.rs +++ b/src/domain/registration.rs @@ -1,18 +1,28 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use tokio::sync::Mutex; use crate::database::{Database, REGISTRATION_TABLE}; use crate::domain::event::EventId; use crate::domain::user::UserId; use crate::error::AppError; +/// Serializes seat-taking. A `BEGIN…COMMIT` around the count can't do this: +/// SurrealDB transactions don't conflict-check a cross-record `count()` +/// against a concurrent insert (write-skew), so two racing registrations both +/// saw a free seat and a full event over-admitted. The database is embedded — +/// this process is the only writer — so one process-wide lock is sufficient. +// ponytail: global lock, per-event locks (or DB-side serialization) if +// registration ever sees real contention. +static REGISTER_LOCK: Mutex<()> = Mutex::const_new(()); + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct RegistrationId(RecordId); impl RegistrationId { /// A deterministic id for the (event, user) pair — the same pair always - /// maps to the same record id, so registering is one atomic UPSERT with - /// no find-then-insert race and one-row-per-pair by construction (the - /// enrollment trick). ULID keys are alphanumeric, so `_` is unambiguous. + /// maps to the same record id, so one-row-per-pair holds by construction + /// (the enrollment trick) even if a write ever slipped past the register + /// lock. ULID keys are alphanumeric, so `_` is unambiguous. pub fn composite(event: &EventId, user: &UserId) -> Self { Self(RecordId::new( REGISTRATION_TABLE, @@ -62,10 +72,10 @@ impl Registration { } /// Register (idempotently) `user` onto `event`, refusing when a `capacity` - /// cap is set and every seat is taken. The seat count is re-read inside the - /// transaction and the THROW cancels the UPSERT, so a full event never - /// over-admits through the check-then-write gap; re-registering someone - /// already listed never counts against the cap (and returns their row). + /// cap is set and every seat is taken. Someone already listed gets their + /// existing row back untouched — a true no-op that never counts against + /// the cap and never rewrites who placed them. The whole check-then-write + /// runs under [`REGISTER_LOCK`], so a full event never over-admits. pub async fn register( event: &EventId, user: &UserId, @@ -73,44 +83,26 @@ impl Registration { capacity: Option, db: &Database, ) -> Result { + let _guard = REGISTER_LOCK.lock().await; + if let Some(existing) = Self::read_for_user(event, user, db).await? { + return Ok(existing); + } + if let Some(capacity) = capacity + && Self::list_for_event(event, db).await?.len() as i64 >= capacity + { + 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 mut result = db - .query( - "BEGIN TRANSACTION; - LET $already = (SELECT VALUE id FROM registration WHERE event = $ev AND user = $usr); - LET $count = (SELECT count() FROM registration WHERE event = $ev GROUP ALL)[0].count ?? 0; - IF $cap != NONE AND array::len($already) = 0 AND $count >= $cap { THROW 'event_full' }; - UPSERT $id CONTENT $registration; - COMMIT TRANSACTION;", - ) - .bind(("ev", event.record())) - .bind(("usr", user.record())) - .bind(("cap", capacity)) - .bind(("id", registration.id.record())) - .bind(("registration", registration)) + let created: Option = db + .create(registration.id.record()) + .content(registration) .await?; - // An aborted transaction errors *every* slot, most with a generic - // "not executed" — only the THROW's own slot names the reason, so scan - // them all for the marker instead of trusting the first (`check`-style) - // error. - let mut errors = result.take_errors(); - if errors - .values() - .any(|error| error.to_string().contains("event_full")) - { - return Err(AppError::Conflict("the event is full")); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Statement slots count BEGIN and the LETs too: the UPSERT is slot 4. - let saved: Option = result.take::>(4)?.into_iter().next(); - saved.ok_or_else(|| AppError::Internal("failed to register user".into())) + created.ok_or_else(|| AppError::Internal("failed to register user".into())) } /// Some(_) iff `user` holds a seat on `event` — the audience point check. diff --git a/tests/integration.rs b/tests/integration.rs index 317ff6f..b83564d 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -3421,6 +3421,122 @@ async fn event_registration_capacity_caps_seats() { ); } +/// Regression: re-registering an already-seated student used to be an UPSERT +/// that silently rewrote `registered_by` to the second caller. The documented +/// contract is a no-op — the seat and its audit trail come back unchanged. +#[tokio::test] +async fn re_registering_returns_the_seat_untouched() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + let deniz = login_as(&app, &db, "deniz", "teacher").await; + let veli = login(&app, "veli").await; + let veli_id = me_id(&app, &veli).await; + let ali_id = me_id(&app, &ali).await; + + let res = send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "seminar", "audience": { "kind": "registration" } })), + ) + .await; + let uri = format!("/events/{}/register", id_of(&res.body)); + + let first = send( + &app, + "POST", + &uri, + Some(&ali), + Some(json!({ "user_id": veli_id })), + ) + .await; + assert_eq!(first.status, StatusCode::OK); + assert_eq!(first.body["registered_by"]["id"], ali_id); + + let second = send( + &app, + "POST", + &uri, + Some(&deniz), + Some(json!({ "user_id": veli_id })), + ) + .await; + assert_eq!(second.status, StatusCode::OK); + assert_eq!( + second.body["registered_by"]["id"], ali_id, + "re-registering must not rewrite who placed the student" + ); +} + +/// Regression: the capacity check used to run inside a `BEGIN…COMMIT` whose +/// cross-record `count()` SurrealDB does not conflict-check against a +/// concurrent insert (write-skew) — two racing placements both saw the last +/// seat free and a capacity-1 event admitted 2. The register path now +/// serializes the check-then-write, so exactly one wins and the loser gets +/// the same 409 as a sequential over-fill. +#[tokio::test] +async fn concurrent_placements_never_exceed_capacity() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + let veli = login(&app, "veli").await; + let ayse = login(&app, "ayse").await; + let veli_id = me_id(&app, &veli).await; + let ayse_id = me_id(&app, &ayse).await; + + let res = send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "trip", "audience": { "kind": "registration", "capacity": 1 } })), + ) + .await; + let ev = id_of(&res.body); + let uri = format!("/events/{ev}/register"); + + for _round in 0..10 { + for uid in [&veli_id, &ayse_id] { + let _ = send(&app, "DELETE", &format!("{uri}/{uid}"), Some(&ali), None).await; + } + let (a, b) = tokio::join!( + send( + &app, + "POST", + &uri, + Some(&ali), + Some(json!({ "user_id": veli_id })), + ), + send( + &app, + "POST", + &uri, + Some(&ali), + Some(json!({ "user_id": ayse_id })), + ), + ); + for status in [a.status, b.status] { + assert!( + status == StatusCode::OK || status == StatusCode::CONFLICT, + "a lost capacity race must be a 409, got {status}" + ); + } + let roster = send( + &app, + "GET", + &format!("/events/{ev}/roster"), + Some(&ali), + None, + ) + .await; + assert!( + common::total(&roster.body) <= 1, + "capacity 1 must never over-admit, roster={}", + roster.body + ); + } +} + /// 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.) @@ -9649,6 +9765,48 @@ async fn grade_band_boundary_applies_to_the_weighted_average() { assert_eq!(res.body["overall_grade"], "AA"); } +/// Two managers patch DIFFERENT fields concurrently. Neither edit may be lost +/// and neither request may 500 — the compare-and-set loop absorbs the +/// conflict and re-merges (the guard `save_if_unchanged` exists for). +#[tokio::test] +async fn concurrent_settings_patches_both_land() { + for _round in 0..10 { + let (app, db) = app_and_db().await; + let mavi = login_as(&app, &db, "mavi", "manager").await; + let kara = login_as(&app, &db, "kara", "manager").await; + + let (a, b) = tokio::join!( + send( + &app, + "PATCH", + "/settings", + Some(&mavi), + Some( + json!({ "grade_bands": [ { "min": 0, "label": "F" }, { "min": 50, "label": "P" } ] }) + ), + ), + send( + &app, + "PATCH", + "/settings", + Some(&kara), + Some(json!({ "max_file_bytes": 4096 })), + ), + ); + assert_eq!(a.status, StatusCode::OK, "bands patch: {}", a.body); + assert_eq!(b.status, StatusCode::OK, "bytes patch: {}", b.body); + + let after = send(&app, "GET", "/settings", Some(&mavi), None).await; + assert_eq!(after.body["max_file_bytes"], 4096, "{}", after.body); + assert_eq!( + after.body["grade_bands"].as_array().unwrap().len(), + 2, + "both concurrent edits must survive: {}", + after.body + ); + } +} + #[tokio::test] async fn settings_accept_admin_edits_trim_entries_and_noop_on_empty_patch() { let (app, db) = app_and_db().await;