forge
Explore
Log in

Don't you dare go Hollow

Stop capacity over-admit and re-register seat rewrite

Browse files at this commit

9b09fd10cfbd7de14b574a0468a55e30188731eaAhmet Kaan GümüşParent: 022aaaa
  • fix
    • stop capacity over-admit and re-register seat rewrite
Show full message
🐛 fix(events): stop capacity over-admit and re-register seat rewrite

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.rsmodified+30 -38
@@ -1,18 +1,28 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2+use tokio::sync::Mutex;
2 3
3 use crate::database::{Database, REGISTRATION_TABLE};4 use crate::database::{Database, REGISTRATION_TABLE};
4 use crate::domain::event::EventId;5 use crate::domain::event::EventId;
5 use crate::domain::user::UserId;6 use crate::domain::user::UserId;
6 use crate::error::AppError;7 use crate::error::AppError;
7 8
9+/// Serializes seat-taking. A `BEGIN…COMMIT` around the count can't do this:
10+/// SurrealDB transactions don't conflict-check a cross-record `count()`
11+/// against a concurrent insert (write-skew), so two racing registrations both
12+/// saw a free seat and a full event over-admitted. The database is embedded —
13+/// this process is the only writer — so one process-wide lock is sufficient.
14+// ponytail: global lock, per-event locks (or DB-side serialization) if
15+// registration ever sees real contention.
16+static REGISTER_LOCK: Mutex<()> = Mutex::const_new(());
17+
8 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]18 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
9 pub struct RegistrationId(RecordId);19 pub struct RegistrationId(RecordId);
10 20
11 impl RegistrationId {21 impl RegistrationId {
12 /// A deterministic id for the (event, user) pair — the same pair always22 /// A deterministic id for the (event, user) pair — the same pair always
13- /// maps to the same record id, so registering is one atomic UPSERT with23+ /// maps to the same record id, so one-row-per-pair holds by construction
14- /// no find-then-insert race and one-row-per-pair by construction (the24+ /// (the enrollment trick) even if a write ever slipped past the register
15- /// enrollment trick). ULID keys are alphanumeric, so `_` is unambiguous.25+ /// lock. ULID keys are alphanumeric, so `_` is unambiguous.
16 pub fn composite(event: &EventId, user: &UserId) -> Self {26 pub fn composite(event: &EventId, user: &UserId) -> Self {
17 Self(RecordId::new(27 Self(RecordId::new(
18 REGISTRATION_TABLE,28 REGISTRATION_TABLE,
@@ -62,10 +72,10 @@ impl Registration {
62 }72 }
63 73
64 /// Register (idempotently) `user` onto `event`, refusing when a `capacity`74 /// Register (idempotently) `user` onto `event`, refusing when a `capacity`
65- /// cap is set and every seat is taken. The seat count is re-read inside the75+ /// cap is set and every seat is taken. Someone already listed gets their
66- /// transaction and the THROW cancels the UPSERT, so a full event never76+ /// existing row back untouched — a true no-op that never counts against
67- /// over-admits through the check-then-write gap; re-registering someone77+ /// the cap and never rewrites who placed them. The whole check-then-write
68- /// already listed never counts against the cap (and returns their row).78+ /// runs under [`REGISTER_LOCK`], so a full event never over-admits.
69 pub async fn register(79 pub async fn register(
70 event: &EventId,80 event: &EventId,
71 user: &UserId,81 user: &UserId,
@@ -73,44 +83,26 @@ impl Registration {
73 capacity: Option<i64>,83 capacity: Option<i64>,
74 db: &Database,84 db: &Database,
75 ) -> Result<Registration, AppError> {85 ) -> Result<Registration, AppError> {
86+ let _guard = REGISTER_LOCK.lock().await;
87+ if let Some(existing) = Self::read_for_user(event, user, db).await? {
88+ return Ok(existing);
89+ }
90+ if let Some(capacity) = capacity
91+ && Self::list_for_event(event, db).await?.len() as i64 >= capacity
92+ {
93+ return Err(AppError::Conflict("the event is full"));
94+ }
76 let registration = Registration {95 let registration = Registration {
77 id: RegistrationId::composite(event, user),96 id: RegistrationId::composite(event, user),
78 event: event.clone(),97 event: event.clone(),
79 user: user.clone(),98 user: user.clone(),
80 registered_by: registered_by.clone(),99 registered_by: registered_by.clone(),
81 };100 };
82- let mut result = db101+ let created: Option<Registration> = db
83- .query(102+ .create(registration.id.record())
84- "BEGIN TRANSACTION;103+ .content(registration)
85- LET $already = (SELECT VALUE id FROM registration WHERE event = $ev AND user = $usr);
86- LET $count = (SELECT count() FROM registration WHERE event = $ev GROUP ALL)[0].count ?? 0;
87- IF $cap != NONE AND array::len($already) = 0 AND $count >= $cap { THROW 'event_full' };
88- UPSERT $id CONTENT $registration;
89- COMMIT TRANSACTION;",
90- )
91- .bind(("ev", event.record()))
92- .bind(("usr", user.record()))
93- .bind(("cap", capacity))
94- .bind(("id", registration.id.record()))
95- .bind(("registration", registration))
96 .await?;104 .await?;
97- // An aborted transaction errors *every* slot, most with a generic105+ created.ok_or_else(|| AppError::Internal("failed to register user".into()))
98- // "not executed" — only the THROW's own slot names the reason, so scan
99- // them all for the marker instead of trusting the first (`check`-style)
100- // error.
101- let mut errors = result.take_errors();
102- if errors
103- .values()
104- .any(|error| error.to_string().contains("event_full"))
105- {
106- return Err(AppError::Conflict("the event is full"));
107- }
108- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
109- return Err(error.into());
110- }
111- // Statement slots count BEGIN and the LETs too: the UPSERT is slot 4.
112- let saved: Option<Registration> = result.take::<Vec<Registration>>(4)?.into_iter().next();
113- saved.ok_or_else(|| AppError::Internal("failed to register user".into()))
114 }106 }
115 107
116 /// Some(_) iff `user` holds a seat on `event` — the audience point check.108 /// Some(_) iff `user` holds a seat on `event` — the audience point check.
tests/integration.rsmodified+158 -0
@@ -3421,6 +3421,122 @@ async fn event_registration_capacity_caps_seats() {
3421 );3421 );
3422 }3422 }
3423 3423
3424+/// Regression: re-registering an already-seated student used to be an UPSERT
3425+/// that silently rewrote `registered_by` to the second caller. The documented
3426+/// contract is a no-op — the seat and its audit trail come back unchanged.
3427+#[tokio::test]
3428+async fn re_registering_returns_the_seat_untouched() {
3429+ let (app, db) = app_and_db().await;
3430+ let ali = login_as(&app, &db, "ali", "teacher").await;
3431+ let deniz = login_as(&app, &db, "deniz", "teacher").await;
3432+ let veli = login(&app, "veli").await;
3433+ let veli_id = me_id(&app, &veli).await;
3434+ let ali_id = me_id(&app, &ali).await;
3435+
3436+ let res = send(
3437+ &app,
3438+ "POST",
3439+ "/events",
3440+ Some(&ali),
3441+ Some(json!({ "title": "seminar", "audience": { "kind": "registration" } })),
3442+ )
3443+ .await;
3444+ let uri = format!("/events/{}/register", id_of(&res.body));
3445+
3446+ let first = send(
3447+ &app,
3448+ "POST",
3449+ &uri,
3450+ Some(&ali),
3451+ Some(json!({ "user_id": veli_id })),
3452+ )
3453+ .await;
3454+ assert_eq!(first.status, StatusCode::OK);
3455+ assert_eq!(first.body["registered_by"]["id"], ali_id);
3456+
3457+ let second = send(
3458+ &app,
3459+ "POST",
3460+ &uri,
3461+ Some(&deniz),
3462+ Some(json!({ "user_id": veli_id })),
3463+ )
3464+ .await;
3465+ assert_eq!(second.status, StatusCode::OK);
3466+ assert_eq!(
3467+ second.body["registered_by"]["id"], ali_id,
3468+ "re-registering must not rewrite who placed the student"
3469+ );
3470+}
3471+
3472+/// Regression: the capacity check used to run inside a `BEGIN…COMMIT` whose
3473+/// cross-record `count()` SurrealDB does not conflict-check against a
3474+/// concurrent insert (write-skew) — two racing placements both saw the last
3475+/// seat free and a capacity-1 event admitted 2. The register path now
3476+/// serializes the check-then-write, so exactly one wins and the loser gets
3477+/// the same 409 as a sequential over-fill.
3478+#[tokio::test]
3479+async fn concurrent_placements_never_exceed_capacity() {
3480+ let (app, db) = app_and_db().await;
3481+ let ali = login_as(&app, &db, "ali", "teacher").await;
3482+ let veli = login(&app, "veli").await;
3483+ let ayse = login(&app, "ayse").await;
3484+ let veli_id = me_id(&app, &veli).await;
3485+ let ayse_id = me_id(&app, &ayse).await;
3486+
3487+ let res = send(
3488+ &app,
3489+ "POST",
3490+ "/events",
3491+ Some(&ali),
3492+ Some(json!({ "title": "trip", "audience": { "kind": "registration", "capacity": 1 } })),
3493+ )
3494+ .await;
3495+ let ev = id_of(&res.body);
3496+ let uri = format!("/events/{ev}/register");
3497+
3498+ for _round in 0..10 {
3499+ for uid in [&veli_id, &ayse_id] {
3500+ let _ = send(&app, "DELETE", &format!("{uri}/{uid}"), Some(&ali), None).await;
3501+ }
3502+ let (a, b) = tokio::join!(
3503+ send(
3504+ &app,
3505+ "POST",
3506+ &uri,
3507+ Some(&ali),
3508+ Some(json!({ "user_id": veli_id })),
3509+ ),
3510+ send(
3511+ &app,
3512+ "POST",
3513+ &uri,
3514+ Some(&ali),
3515+ Some(json!({ "user_id": ayse_id })),
3516+ ),
3517+ );
3518+ for status in [a.status, b.status] {
3519+ assert!(
3520+ status == StatusCode::OK || status == StatusCode::CONFLICT,
3521+ "a lost capacity race must be a 409, got {status}"
3522+ );
3523+ }
3524+ let roster = send(
3525+ &app,
3526+ "GET",
3527+ &format!("/events/{ev}/roster"),
3528+ Some(&ali),
3529+ None,
3530+ )
3531+ .await;
3532+ assert!(
3533+ common::total(&roster.body) <= 1,
3534+ "capacity 1 must never over-admit, roster={}",
3535+ roster.body
3536+ );
3537+ }
3538+}
3539+
3424 /// The signup list freezes the moment the event starts — both directions.3540 /// The signup list freezes the moment the event starts — both directions.
3425 /// (The create-time no-past grace lets a just-started event exist, which is3541 /// (The create-time no-past grace lets a just-started event exist, which is
3426 /// exactly a closed list.)3542 /// exactly a closed list.)
@@ -9649,6 +9765,48 @@ async fn grade_band_boundary_applies_to_the_weighted_average() {
9649 assert_eq!(res.body["overall_grade"], "AA");9765 assert_eq!(res.body["overall_grade"], "AA");
9650 }9766 }
9651 9767
9768+/// Two managers patch DIFFERENT fields concurrently. Neither edit may be lost
9769+/// and neither request may 500 — the compare-and-set loop absorbs the
9770+/// conflict and re-merges (the guard `save_if_unchanged` exists for).
9771+#[tokio::test]
9772+async fn concurrent_settings_patches_both_land() {
9773+ for _round in 0..10 {
9774+ let (app, db) = app_and_db().await;
9775+ let mavi = login_as(&app, &db, "mavi", "manager").await;
9776+ let kara = login_as(&app, &db, "kara", "manager").await;
9777+
9778+ let (a, b) = tokio::join!(
9779+ send(
9780+ &app,
9781+ "PATCH",
9782+ "/settings",
9783+ Some(&mavi),
9784+ Some(
9785+ json!({ "grade_bands": [ { "min": 0, "label": "F" }, { "min": 50, "label": "P" } ] })
9786+ ),
9787+ ),
9788+ send(
9789+ &app,
9790+ "PATCH",
9791+ "/settings",
9792+ Some(&kara),
9793+ Some(json!({ "max_file_bytes": 4096 })),
9794+ ),
9795+ );
9796+ assert_eq!(a.status, StatusCode::OK, "bands patch: {}", a.body);
9797+ assert_eq!(b.status, StatusCode::OK, "bytes patch: {}", b.body);
9798+
9799+ let after = send(&app, "GET", "/settings", Some(&mavi), None).await;
9800+ assert_eq!(after.body["max_file_bytes"], 4096, "{}", after.body);
9801+ assert_eq!(
9802+ after.body["grade_bands"].as_array().unwrap().len(),
9803+ 2,
9804+ "both concurrent edits must survive: {}",
9805+ after.body
9806+ );
9807+ }
9808+}
9809+
9652 #[tokio::test]9810 #[tokio::test]
9653 async fn settings_accept_admin_edits_trim_entries_and_noop_on_empty_patch() {9811 async fn settings_accept_admin_edits_trim_entries_and_noop_on_empty_patch() {
9654 let (app, db) = app_and_db().await;9812 let (app, db) = app_and_db().await;