forge
Explore
Log in

Don't you dare go Hollow

🚧 wip: class-pump/meals/homework production fixes + T5 test-port continuation

Browse files at this commit

35683ac646cda318a2272bc1b1507d511cef9e13Ahmet Kaan GümüşParent: af331ec

83 changed files +2227 -1955

src/ai/server.rsmodified+1 -3
@@ -1077,9 +1077,7 @@ mod tests {
10771077 async fn armed(router: axum::Router) -> ApiHandle {
10781078 ApiHandle {
10791079 router,
1080- tenants: crate::database::init_mem_tenants()
1081- .await
1082- .expect("in-memory deployment"),
1080+ tenants: crate::database::init_test_tenants().await,
10831081 files_path: std::env::temp_dir(),
10841082 }
10851083 }
src/db/answer_image.rsmodified+4 -4
@@ -240,12 +240,12 @@ mod tests {
240240 }
241241
242242 fn student() -> UserId {
243- UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA")
243+ UserId::from_key("019732e3-7b00-7000-8000-00000000a11a")
244244 }
245245
246246 #[tokio::test]
247247 async fn upsert_replaces_within_a_sitting_but_not_across_them() {
248- let db = crate::database::init_mem().await.unwrap();
248+ let (db, _leases) = crate::database::init_test_db().await;
249249 let exam = exam_row(&db).await;
250250 let question = ExamQuestionId::generate();
251251 let user = student();
@@ -287,7 +287,7 @@ mod tests {
287287 );
288288
289289 // Another student's drawing for the same question/sitting is its own row.
290- let other = UserId::from_key("01TESTSTUDENTBBBBBBBBBBBBB");
290+ let other = UserId::from_key("019732e3-7b00-7000-8000-00000000b22b");
291291 upsert(&db, AnswerImage::new(&exam, &question, &other, 1, png(), 7))
292292 .await
293293 .unwrap();
@@ -297,7 +297,7 @@ mod tests {
297297
298298 #[tokio::test]
299299 async fn listing_scopes_by_exam_and_user() {
300- let db = crate::database::init_mem().await.unwrap();
300+ let (db, _leases) = crate::database::init_test_db().await;
301301 let exam_a = exam_row(&db).await;
302302 let exam_b = exam_row(&db).await;
303303 let user = student();
src/db/attendance.rsmodified+52 -34
@@ -130,59 +130,77 @@ mod tests {
130130 use crate::domain::settings::Settings;
131131
132132 /// The session twin's race, one table over
133- /// ([`crate::db::session_attendance::mark`]): a
134- /// `DEFINE EVENT` on `event` fires inside the delete's own transaction, and
135- /// the event's delete sweeps its attendance rows before removing the row, so
136- /// the `SLEEP` lands exactly between the sweep and the commit — the window
137- /// where a bare upsert wrote a mark nothing would ever sweep again.
138- ///
139- /// Real server, and `#[ignore]`d for it: the subject is the store's
140- /// conflict detection, which `init_mem`'s embedded engine does not have —
141- /// it commits both writes and answers `Ok` to each, so this passes there on
142- /// broken code. Mutation-tested: turning the claim back into a read
143- /// (`SELECT VALUE id FROM $ev`) turns it red.
133+ /// ([`crate::db::session_attendance::mark`]): the event's delete sweeps its
134+ /// attendance rows and removes the row in one transaction, and a mark that
135+ /// wrote into the gap was a bare upsert nothing would ever sweep again.
136+ /// The mark now writes the event row too (its seats counter), so the two
137+ /// transactions touch one row and Postgres refuses one of them; the barrier
138+ /// releases both sides together so every interleaving gets its chance.
139+ /// Mutation-tested: turning the claim back into a read turns it red.
144140 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
145- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
146141 async fn a_mark_written_inside_a_delete_never_outlives_the_event() {
147- use crate::domain::event::{EventAudience, EventDescription, EventTitle};
148- let (db, _serialized) = crate::database::init_test_server("event_attendance_race").await;
149- db.query(
150- "DEFINE EVENT hold_the_window ON TABLE event WHEN $event = 'DELETE' \
151- THEN { SLEEP 1s; };",
152- )
153- .await
154- .unwrap()
155- .check()
156- .unwrap();
142+ use crate::domain::event::{
143+ EventAudience, EventAudienceKind, EventDescription, EventTitle,
144+ };
157145
146+ // A real `app_user` row: markers, students and event creators are
147+ // foreign keys now.
148+ async fn a_person(db: &Database, label: &str) -> UserId {
149+ let user = UserId::generate();
150+ sqlx::query(
151+ "INSERT INTO app_user (id, username, password_hash, role) \
152+ VALUES ($1, $2, 'x', 'teacher')",
153+ )
154+ .bind(user.uuid())
155+ .bind(format!("{label}-{}", &user.key()[..8]))
156+ .execute(db)
157+ .await
158+ .unwrap();
159+ user
160+ }
161+
162+ let (db, _leases) = crate::database::init_test_db().await;
158163 let allowed: Vec<String> = Settings::defaults().get_attendance_statuses().to_vec();
159- let marker = UserId::from_key("t");
164+ let marker = a_person(&db, "marker").await;
160165 let (mut swept, mut orphans) = (0, 0);
161- for round in 0..4 {
166+ for round in 0..8 {
162167 let event = crate::db::event::create(
163168 &db,
164169 &marker,
165170 EventTitle::try_new("gezi").unwrap(),
166171 EventDescription::try_new("").unwrap(),
167- EventAudience::School,
172+ EventAudience {
173+ kind: EventAudienceKind::School,
174+ role: None,
175+ course: None,
176+ class: None,
177+ capacity: None,
178+ },
168179 None,
169180 None,
170181 )
171182 .await
172183 .unwrap();
173184 let id = event.get_id().clone();
185+
186+ // Delete and mark released together: both write the event row, so
187+ // Postgres serializes them and refuses whichever lost.
188+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
174189 let drop_it = {
175- let db = db.clone();
176- tokio::spawn(async move { crate::db::event::delete(&db, event).await })
190+ let (db, gate, event) = (db.clone(), gate.clone(), event);
191+ tokio::spawn(async move {
192+ gate.wait().await;
193+ crate::db::event::delete(&db, event).await
194+ })
177195 };
178- // The mark starts inside the held window: the sweep has run and the
179- // event row is gone but uncommitted.
180- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
181196 let marked = {
182- let (db, id, marker) = (db.clone(), id.clone(), marker.clone());
183- let student = UserId::from_key(&format!("s{round}"));
197+ let (db, id, marker, gate) = (db.clone(), id.clone(), marker.clone(), gate);
198+ let student = a_person(&db, "student").await;
184199 let status = AttendanceStatus::try_new("present", &allowed).unwrap();
185- tokio::spawn(async move { mark(&db, &id, &student, status, &marker).await })
200+ tokio::spawn(async move {
201+ gate.wait().await;
202+ mark(&db, &id, &student, status, &marker).await
203+ })
186204 };
187205 let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap());
188206 assert!(
@@ -198,7 +216,7 @@ mod tests {
198216 panic!("round {round}: the delete reported success but the event is still there");
199217 }
200218 }
201- eprintln!("Event::delete raced by a mark: {swept}/4 rounds deleted the event");
219+ eprintln!("Event::delete raced by a mark: {swept}/8 rounds deleted the event");
202220 assert!(
203221 swept > 0,
204222 "no round ever deleted the event, so the window was never reached"
src/db/badge.rsmodified+9 -9
@@ -111,7 +111,7 @@ pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> {
111111 SET earned_at = badge_award.earned_at \
112112 WHERE badge_award.earned_at IS NULL"
113113 )))
114- .bind(user.uuid())
114+.bind(user.uuid())
115115 .bind(badge)
116116 .bind(now)
117117 .execute(db)
@@ -124,7 +124,7 @@ pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> {
124124 mod tests {
125125 use super::*;
126126 use crate::constant::BADGE_AWARD_TABLE;
127- use crate::database::init_mem;
127+ use crate::database::init_test_db;
128128 use crate::domain::user::{Password, Username};
129129
130130 async fn a_user(username: &str, db: &Database) -> crate::domain::user::User {
@@ -142,9 +142,9 @@ mod tests {
142142 }
143143
144144 async fn count_awards(db: &Database, user: &UserId) -> i64 {
145- let (count,): (i64,) = sqlx::query_as(&format!(
145+ let (count,): (i64,) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
146146 "SELECT count(*) FROM {BADGE_AWARD_TABLE} WHERE app_user = $1"
147- ))
147+ )))
148148 .bind(user.uuid())
149149 .fetch_one(db)
150150 .await
@@ -161,7 +161,7 @@ mod tests {
161161
162162 #[tokio::test]
163163 async fn load_defaults_every_counter_to_zero() {
164- let db = init_mem().await.unwrap();
164+ let (db, _leases) = init_test_db().await;
165165 let user = a_user("badge-sifir", &db).await;
166166
167167 let stats = load(&db, user.get_id()).await.unwrap();
@@ -177,12 +177,12 @@ mod tests {
177177
178178 #[tokio::test]
179179 async fn sync_is_idempotent_and_keeps_the_first_stamp() {
180- let db = init_mem().await.unwrap();
180+ let (db, _leases) = init_test_db().await;
181181 let user = a_user("badge-ali", &db).await;
182182
183183 // Seed two submitted homeworks: enough for the first badge tier.
184184 sqlx::query("UPDATE app_user SET homework_submitted_total = 2 WHERE id = $1")
185- .bind(user.uuid())
185+ .bind(user.get_id().uuid())
186186 .execute(&db)
187187 .await
188188 .unwrap();
@@ -195,7 +195,7 @@ mod tests {
195195 // A second sync with the counter moved *further* writes nothing: the
196196 // stamps are from the first crossing, and no row is duplicated.
197197 sqlx::query("UPDATE app_user SET homework_submitted_total = 5 WHERE id = $1")
198- .bind(user.uuid())
198+ .bind(user.get_id().uuid())
199199 .execute(&db)
200200 .await
201201 .unwrap();
@@ -218,7 +218,7 @@ mod tests {
218218
219219 #[tokio::test]
220220 async fn sync_writes_nothing_for_a_earned_nothing() {
221- let db = init_mem().await.unwrap();
221+ let (db, _leases) = init_test_db().await;
222222 let user = a_user("badge-bos", &db).await;
223223 sync(&db, user.get_id()).await.unwrap();
224224 assert_eq!(
src/db/bank_question.rsmodified+35 -39
@@ -414,33 +414,33 @@ mod tests {
414414 .unwrap()
415415 }
416416
417- /// A row stored before `visibility` existed has no such key — it must decode
418- /// as `private`, the safe value. Asserted on the decoder itself, so no
419- /// schema DEFAULT can paper over it: a `school` default here would publish
420- /// every pre-existing template in the school at once.
417+ /// A row without a visibility of its own must decode as `private`, the
418+ /// safe value. The old engine could store a row with the field absent;
419+ /// Postgres carries the same guarantee in the schema instead — the column
420+ /// is `NOT NULL DEFAULT 'private'`, so a `school` default here would
421+ /// publish every pre-existing template in the school at once. The insert
422+ /// below is written exactly as a pre-visibility row arrives: no column.
421423 #[tokio::test]
422424 async fn a_row_without_the_field_decodes_private() {
423- use surrealdb::types::Value;
424-
425- let db = crate::database::init_mem().await.unwrap();
426- let question = create(
427- &db,
428- UserId::generate(),
429- SubjectId::generate(),
430- QuestionText::try_new("q").unwrap(),
431- QuestionPoints::try_new(1).unwrap(),
432- spec(),
425+ let (db, _leases) = crate::database::init_test_db().await;
426+ let owner = UserId::generate();
427+ sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'q', 'x')")
428+ .bind(owner.uuid())
429+ .execute(&db)
430+ .await
431+ .unwrap();
432+ let id = BankQuestionId::generate();
433+ sqlx::query(
434+ "INSERT INTO bank_question (id, owner, text, kind, points, created_at) \
435+ VALUES ($1, $2, 'q', 'multiple_choice', 1, 0)",
433436 )
437+ .bind(id.uuid())
438+ .bind(owner.uuid())
439+ .execute(&db)
434440 .await
435441 .unwrap();
436- assert_eq!(question.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE);
437442
438- let mut stored = question.into_value();
439- let Value::Object(map) = &mut stored else {
440- panic!("a bank question serializes to an object");
441- };
442- assert!(map.remove("visibility").is_some());
443- let old = BankQuestion::from_value(stored).unwrap();
443+ let old = read(&db, &id).await.unwrap().expect("the row is there");
444444 assert_eq!(old.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE);
445445 assert!(!old.get_visibility().is_school());
446446 }
@@ -449,7 +449,7 @@ mod tests {
449449 /// page can contain — never someone else's private templates.
450450 #[tokio::test]
451451 async fn list_hides_private_templates_from_others() {
452- let db = crate::database::init_mem().await.unwrap();
452+ let (db, _leases) = crate::database::init_test_db().await;
453453 let owner = UserId::generate();
454454 let other = UserId::generate();
455455 let private = create(
@@ -516,7 +516,7 @@ mod tests {
516516 /// still answer `Ok`.
517517 #[tokio::test]
518518 async fn a_merge_built_on_a_stale_snapshot_is_refused() {
519- let db = crate::database::init_mem().await.unwrap();
519+ let (db, _leases) = crate::database::init_test_db().await;
520520 let owner = UserId::generate();
521521 let stale = create(
522522 &db,
@@ -564,7 +564,7 @@ mod tests {
564564 /// row, and `private` means "my own drafts" for everyone but an admin.
565565 #[tokio::test]
566566 async fn visibility_filter_narrows_never_widens() {
567- let db = crate::database::init_mem().await.unwrap();
567+ let (db, _leases) = crate::database::init_test_db().await;
568568 let owner = UserId::generate();
569569 let other = UserId::generate();
570570 let mine = |text: &str| {
@@ -638,14 +638,10 @@ mod tests {
638638 /// "0"), and questions authored by hand never counted.
639639 #[tokio::test]
640640 async fn usage_counts_tallies_a_page_in_one_statement() {
641- // One statement, so a page costs one round trip — a `;` here would mean
642- // the per-row N+1 crept back in.
643- assert!(
644- !USAGE_COUNTS_SQL.contains(';'),
645- "usage_counts must be one statement"
646- );
647-
648- let db = crate::database::init_mem().await.unwrap();
641+ // One statement, so a page costs one round trip: the tally is a single
642+ // static `query!` (a `GROUP BY` with no loop around it), which the
643+ // compiler now checks the way the old constant asserted.
644+ let (db, _leases) = crate::database::init_test_db().await;
649645 let owner = UserId::generate();
650646 let template = |text: &str| {
651647 create(
@@ -712,10 +708,10 @@ mod tests {
712708
713709 let ids = [used_twice.get_id(), used_once.get_id(), unused.get_id()];
714710 let counts = usage_counts(&db, &ids).await.unwrap();
715- assert_eq!(counts.get(used_twice.get_id().key()).copied(), Some(2));
716- assert_eq!(counts.get(used_once.get_id().key()).copied(), Some(1));
711+ assert_eq!(counts.get(&used_twice.get_id().key()).copied(), Some(2));
712+ assert_eq!(counts.get(&used_once.get_id().key()).copied(), Some(1));
717713 assert_eq!(
718- counts.get(unused.get_id().key()),
714+ counts.get(&unused.get_id().key()),
719715 None,
720716 "unused stays absent"
721717 );
@@ -724,14 +720,14 @@ mod tests {
724720 // A template outside the page is never counted into it.
725721 let narrow = usage_counts(&db, &[used_once.get_id()]).await.unwrap();
726722 assert_eq!(narrow.len(), 1);
727- assert_eq!(narrow.get(used_once.get_id().key()).copied(), Some(1));
723+ assert_eq!(narrow.get(&used_once.get_id().key()).copied(), Some(1));
728724 // An empty page asks nothing at all.
729725 assert!(usage_counts(&db, &[]).await.unwrap().is_empty());
730726 }
731727
732728 #[tokio::test]
733729 async fn list_is_school_wide() {
734- let db = crate::database::init_mem().await.unwrap();
730+ let (db, _leases) = crate::database::init_test_db().await;
735731 for _ in 0..2 {
736732 create(
737733 &db,
@@ -755,7 +751,7 @@ mod tests {
755751 /// The window is SQL, not an in-memory slice, and `total` ignores it.
756752 #[tokio::test]
757753 async fn list_pages_newest_first_and_filters_text() {
758- let db = crate::database::init_mem().await.unwrap();
754+ let (db, _leases) = crate::database::init_test_db().await;
759755 let owner = UserId::generate();
760756 for i in 0..5 {
761757 create(
@@ -806,7 +802,7 @@ mod tests {
806802 /// Turkish `İ`/`ı` must not split the search into two disjoint halves.
807803 #[tokio::test]
808804 async fn list_text_filter_folds_turkish_casing() {
809- let db = crate::database::init_mem().await.unwrap();
805+ let (db, _leases) = crate::database::init_test_db().await;
810806 create(
811807 &db,
812808 UserId::generate(),
src/db/bank_question_image.rsmodified+3 -3
@@ -232,7 +232,7 @@ mod tests {
232232
233233 #[tokio::test]
234234 async fn upsert_replaces_per_slot() {
235- let db = crate::database::init_mem().await.unwrap();
235+ let (db, _leases) = crate::database::init_test_db().await;
236236 let question = a_template(&db).await;
237237
238238 let (first, retired) = upsert(&db, BankQuestionImage::new(&question, None, png(), 3))
@@ -255,7 +255,7 @@ mod tests {
255255 /// picture, and only a removed option's picture goes.
256256 #[tokio::test]
257257 async fn only_the_dropped_options_lose_their_pictures() {
258- let db = crate::database::init_mem().await.unwrap();
258+ let (db, _leases) = crate::database::init_test_db().await;
259259 let question = a_template(&db).await;
260260 let ids = choice_ids();
261261 upsert(&db, BankQuestionImage::new(&question, None, png(), 1))
@@ -278,7 +278,7 @@ mod tests {
278278
279279 #[tokio::test]
280280 async fn an_empty_keep_set_clears_every_option_picture() {
281- let db = crate::database::init_mem().await.unwrap();
281+ let (db, _leases) = crate::database::init_test_db().await;
282282 let question = a_template(&db).await;
283283 let ids = choice_ids();
284284 upsert(&db, BankQuestionImage::new(&question, None, png(), 1))
src/db/board.rsmodified+2 -2
@@ -331,7 +331,7 @@ mod tests {
331331 /// the meantime is a 404 — not a silent success.
332332 #[tokio::test]
333333 async fn field_scoped_writes_return_the_row_and_a_gone_board_refuses() {
334- let db = crate::database::init_mem().await.unwrap();
334+ let (db, _leases) = crate::database::init_test_db().await;
335335 let creator = UserId::generate();
336336 let board = create(
337337 &db,
@@ -362,7 +362,7 @@ mod tests {
362362 /// board row, and deleting a board hands the seat back.
363363 #[tokio::test]
364364 async fn the_cap_refuses_and_delete_releases_the_seat() {
365- let db = crate::database::init_mem().await.unwrap();
365+ let (db, _leases) = crate::database::init_test_db().await;
366366 let creator = UserId::generate();
367367 for index in 0..MAX_BOARDS_PER_CREATOR {
368368 create(
src/db/builder.rsmodified+1 -1
@@ -116,7 +116,7 @@ mod tests {
116116
117117 #[tokio::test]
118118 async fn a_builder_session_round_trips_and_deletes() {
119- let tenants = Tenants::new_mem().await.unwrap();
119+ let tenants = crate::database::init_test_tenants().await;
120120 let control = tenants.control();
121121 builder::ensure(
122122 control,
src/db/chatbot_message.rsmodified+22 -9
@@ -315,16 +315,29 @@ mod tests {
315315 // `id` tie-break decides the thread's order. With a random ULID this
316316 // inverted a fifth of the pairs; here every pair must read back
317317 // question-then-answer, from both read paths.
318- let db = crate::database::init_mem().await.unwrap();
318+ let (db, _leases) = crate::database::init_test_db().await;
319319 // A real thread row: every turn is written through it, so a turn with
320- // no thread is refused (see [`insert`]).
321- db.query("CREATE chatbot_thread:c SET user_id = user:u, created_at = 0, updated_at = 0")
322- .await
323- .unwrap()
324- .check()
325- .unwrap();
326- let thread = ChatbotThreadId::from_key("c");
327- let user = UserId::from_key("u");
320+ // no thread is refused (see [`insert`]). The owner is a foreign key
321+ // now, so both fixture rows are real, under fixed keys.
322+ let user = UserId::from_key("019732e3-7b00-7000-8000-00000000cafe");
323+ let thread = ChatbotThreadId::from_key("019732e3-7b00-7000-8000-00000000beef");
324+ sqlx::query(
325+ "INSERT INTO app_user (id, username, password_hash) \
326+ VALUES ($1, 'chat-fixture', 'x')",
327+ )
328+ .bind(user.uuid())
329+ .execute(&db)
330+ .await
331+ .unwrap();
332+ sqlx::query(
333+ "INSERT INTO chatbot_thread (id, user_id, created_at, updated_at) \
334+ VALUES ($1, $2, 0, 0)",
335+ )
336+ .bind(thread.uuid())
337+ .bind(user.uuid())
338+ .execute(&db)
339+ .await
340+ .unwrap();
328341 const TURNS: usize = 200;
329342
330343 for turn in 0..TURNS {
src/db/chatbot_thread.rsmodified+46 -58
@@ -193,34 +193,41 @@ pub async fn delete(db: &Database, thread: ChatbotThread) -> Result<ChatbotThrea
193193 #[cfg(test)]
194194 mod tests {
195195 use super::*;
196- use surrealdb::types::RecordId;
196+ use sqlx::Row as _;
197197
198198 use crate::db::chatbot_message;
199199 use crate::domain::chatbot_message::ChatContent;
200200 use crate::domain::settings::{Settings, SettingsParams};
201201
202+ /// The fixed fixture person, by a valid id every helper can name.
203+ const U: &str = "019732e3-7b00-7000-8000-00000000aaaa";
204+
202205 /// The owner's counter and the threads it counts, both re-read out of the
203- /// store — never off a return value, which the in-memory engine forges
204- /// wins on (see [`cap`]).
206+ /// store — never off a return value.
205207 async fn stored(db: &Database) -> (i64, usize) {
206- let mut result = db
207- .query("SELECT VALUE (chatbot_thread_count ?? 0) FROM user:u")
208- .query("SELECT VALUE id FROM chatbot_thread")
208+ let counter =
209+ sqlx::query("SELECT chatbot_thread_count FROM app_user WHERE id = $1")
210+ .bind(UserId::from_key(U).uuid())
211+ .fetch_one(db)
212+ .await
213+ .unwrap()
214+ .try_get::<i64, _>(0)
215+ .unwrap();
216+ let rows = sqlx::query("SELECT count(*) FROM chatbot_thread")
217+ .fetch_one(db)
209218 .await
210219 .unwrap()
211- .check()
220+ .try_get::<i64, _>(0)
212221 .unwrap();
213- let counter = result.take::<Vec<i64>>(0).unwrap();
214- let rows = result.take::<Vec<RecordId>>(1).unwrap();
215- (counter[0], rows.len())
222+ (counter, rows as usize)
216223 }
217224
218225 async fn a_user_capped_at(threads: i64) -> Database {
219- let db = crate::database::init_mem().await.unwrap();
220- db.query("CREATE user:u SET username = 'u', password_hash = 'x';")
226+ let (db, _leases) = crate::database::init_test_db().await;
227+ sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'u', 'x')")
228+ .bind(UserId::from_key(U).uuid())
229+ .execute(&db)
221230 .await
222- .unwrap()
223- .check()
224231 .unwrap();
225232 crate::db::settings::save(
226233 &db,
@@ -241,7 +248,7 @@ mod tests {
241248 #[tokio::test]
242249 async fn a_capped_create_moves_the_counter_with_the_row() {
243250 let db = a_user_capped_at(1).await;
244- let user = UserId::from_key("u");
251+ let user = UserId::from_key(U);
245252
246253 create_capped(&db, &user, None).await.expect("first thread");
247254 assert_eq!(stored(&db).await, (1, 1));
@@ -262,7 +269,7 @@ mod tests {
262269 #[tokio::test]
263270 async fn a_turn_writes_its_thread_and_dies_with_it() {
264271 let db = a_user_capped_at(2).await;
265- let user = UserId::from_key("u");
272+ let user = UserId::from_key(U);
266273 let thread = create_capped(&db, &user, None).await.expect("thread");
267274 let opened = thread.get_updated_at().as_millis();
268275
@@ -322,16 +329,15 @@ mod tests {
322329 const LEAD: i64 = 1_000;
323330
324331 let db = a_user_capped_at(1).await;
325- let user = UserId::from_key("u");
332+ let user = UserId::from_key(U);
326333 let thread = create_capped(&db, &user, None).await.expect("thread");
327334
328335 let parked = Timestamp::now().as_millis() + LEAD;
329- db.query("UPDATE $id SET updated_at = $parked")
330- .bind(("id", thread.get_id().record()))
331- .bind(("parked", parked))
336+ sqlx::query("UPDATE chatbot_thread SET updated_at = $1 WHERE id = $2")
337+ .bind(parked)
338+ .bind(thread.get_id().uuid())
339+ .execute(&db)
332340 .await
333- .unwrap()
334- .check()
335341 .unwrap();
336342
337343 for _ in 0..2 {
@@ -377,51 +383,33 @@ mod tests {
377383 /// row ([`touch_and_write`]) instead of reading it — the two transactions
378384 /// then touch one key and the store refuses to commit both.
379385 ///
380- /// The window is opened by the database itself rather than by a lucky
381- /// interleaving: a `DEFINE EVENT` on `chatbot_thread` fires *inside* the
382- /// delete's own transaction, the instant the row goes, so the `SLEEP` lands
383- /// after the message sweep and before the commit every single time.
384- ///
385- /// Real server, and `#[ignore]`d for it: the subject is the store's
386- /// conflict detection, which `init_mem`'s embedded engine does not have —
387- /// it commits both writes and answers `Ok` to each, which would fail this
388- /// test on correct code (see [`crate::database::init_test_server`]).
386+ /// The window the schema event used to force open is the thread row's own
387+ /// lock now: a turn is written *through* the row ([`touch_and_write`]),
388+ /// so a turn racing the delete serializes on that row instead of
389+ /// committing past the sweep. A barrier start lets both orders happen,
390+ /// and the invariant must hold in each.
389391 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
390- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
391392 async fn a_turn_written_inside_a_delete_never_outlives_the_thread() {
392- let (db, _serialized) = crate::database::init_test_server("chat_delete_race").await;
393- db.query("CREATE user:u SET username = 'u', password_hash = 'x';")
394- .await
395- .unwrap()
396- .check()
397- .unwrap();
398- // Hold the delete open for a full second after the thread row is gone,
399- // while its transaction still has to commit.
400- db.query(
401- "DEFINE EVENT hold_the_window ON TABLE chatbot_thread WHEN $event = 'DELETE' \
402- THEN { SLEEP 1s; };",
403- )
404- .await
405- .unwrap()
406- .check()
407- .unwrap();
393+ let db = a_user_capped_at(4).await;
408394
409- let user = UserId::from_key("u");
395+ let user = UserId::from_key(U);
410396 let (mut orphans, mut swept) = (0, 0);
411- for round in 0..4 {
397+ for round in 0..8 {
412398 let thread = create_capped(&db, &user, None).await.expect("thread");
413399 let id = thread.get_id().clone();
414400
401+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
415402 let drop_it = {
416- let db = db.clone();
417- tokio::spawn(async move { delete(&db, thread).await })
403+ let (db, thread, gate) = (db.clone(), thread, gate.clone());
404+ tokio::spawn(async move {
405+ gate.wait().await;
406+ delete(&db, thread).await
407+ })
418408 };
419- // The turn starts inside the held window — the thread row is gone
420- // but uncommitted, which is exactly what a read believes.
421- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
422409 let turn = {
423- let (id, db, user) = (id.clone(), db.clone(), user.clone());
410+ let (id, db, user, gate) = (id.clone(), db.clone(), user.clone(), gate);
424411 tokio::spawn(async move {
412+ gate.wait().await;
425413 chatbot_message::append_user(
426414 &db,
427415 &id,
@@ -451,10 +439,10 @@ mod tests {
451439 panic!("round {round}: the delete reported success but the thread is still there");
452440 }
453441 }
454- eprintln!("chatbot_thread::delete raced by a turn: {swept}/4 rounds deleted the thread");
442+ eprintln!("chatbot_thread::delete raced by a turn: {swept}/8 rounds deleted the thread");
455443 assert!(
456444 swept > 0,
457- "no round ever deleted the thread, so the window was never reached"
445+ "no round ever deleted the thread, so the race never actually ran"
458446 );
459447 assert_eq!(orphans, 0, "a turn outlived its thread");
460448 }
src/db/class_group.rsmodified+89 -81
@@ -292,12 +292,31 @@ pub async fn delete(db: &Database, class: ClassGroup) -> Result<bool, AppError>
292292 #[cfg(test)]
293293 mod tests {
294294 use super::*;
295+ use sqlx::Row as _;
296+
295297 use crate::domain::term::{Term, TermName};
296298
299+ /// A real `app_user` row: creator, teacher, and attached-by are foreign
300+ /// keys now, so every fixture participant is a row, not a fabricated id.
301+ async fn a_named_user(db: &Database, username: &str) -> UserId {
302+ let user = UserId::generate();
303+ sqlx::query(
304+ "INSERT INTO app_user (id, username, password_hash, role) \
305+ VALUES ($1, $2, 'x', 'teacher')",
306+ )
307+ .bind(user.uuid())
308+ .bind(username)
309+ .execute(db)
310+ .await
311+ .unwrap();
312+ user
313+ }
314+
297315 async fn class_on(term: Option<TermId>, db: &Database) -> ClassGroup {
316+ let manager = a_named_user(db, "manager").await;
298317 create(
299318 db,
300- &UserId::from_key("manager"),
319+ &manager,
301320 ClassName::try_new("9-A").unwrap(),
302321 None,
303322 term,
@@ -309,9 +328,10 @@ mod tests {
309328
310329 /// A class with a homeroom teacher, no term.
311330 async fn class_of(teacher: Option<UserId>, db: &Database) -> ClassGroup {
331+ let manager = a_named_user(db, "manager").await;
312332 create(
313333 db,
314- &UserId::from_key("manager"),
334+ &manager,
315335 ClassName::try_new("9-A").unwrap(),
316336 None,
317337 None,
@@ -338,41 +358,30 @@ mod tests {
338358 .unwrap()
339359 }
340360
341- /// The stored counter, re-read — never off a return value, which the
342- /// in-memory engine forges wins on (see [`crate::db::cap`]).
343- async fn stored_count(sql: &str, db: &Database) -> i64 {
344- let mut result = db.query(sql).await.unwrap().check().unwrap();
345- result
346- .take::<Vec<i64>>(0)
361+ /// The single integer `sql` selects — the stored counter, re-read, never
362+ /// off a return value. The SQL is built from literals in this module, so
363+ /// the audit wrapper is a formality.
364+ async fn one_i64(db: &Database, sql: String) -> i64 {
365+ sqlx::query(sqlx::AssertSqlSafe(sql))
366+ .fetch_one(db)
367+ .await
347368 .unwrap()
348- .first()
349- .copied()
369+ .try_get::<i64, _>(0)
350370 .unwrap()
351371 }
352372
353373 /// The stored `class_count` on one term, absent counting as zero.
354374 async fn count_on(term: &TermId, db: &Database) -> i64 {
355- let mut result = db
356- .query(format!(
357- "SELECT VALUE ({TERM_CLASS_COUNT_FIELD} ?? 0) FROM $term"
358- ))
359- .bind(("term", term.record()))
360- .await
361- .unwrap()
362- .check()
363- .unwrap();
364- result
365- .take::<Vec<i64>>(0)
366- .unwrap()
367- .first()
368- .copied()
369- .unwrap_or(0)
375+ one_i64(
376+ db,
377+ format!("SELECT COALESCE(class_count, 0) FROM term WHERE id = '{}'", term.uuid()),
378+ )
379+ .await
370380 }
371381
372- /// How many rows `sql` selects ids for.
373- async fn rows(sql: &str, db: &Database) -> usize {
374- let mut result = db.query(sql).await.unwrap().check().unwrap();
375- result.take::<Vec<RecordId>>(0).unwrap().len()
382+ /// How many rows `table` holds.
383+ async fn row_count(db: &Database, table: &str) -> i64 {
384+ one_i64(db, format!("SELECT count(*) FROM {table}")).await
376385 }
377386
378387 /// The homeroom teacher survives a create, is set and cleared by a PATCH,
@@ -381,9 +390,9 @@ mod tests {
381390 /// no key at all, which must read back as `None`, not fail the decode.
382391 #[tokio::test]
383392 async fn the_homeroom_teacher_is_stored_set_cleared_and_left_alone() {
384- let db = crate::database::init_mem().await.unwrap();
385- let ada = UserId::from_key("ada");
386- let boole = UserId::from_key("boole");
393+ let (db, _leases) = crate::database::init_test_db().await;
394+ let ada = a_named_user(&db, "ada").await;
395+ let boole = a_named_user(&db, "boole").await;
387396
388397 let bare = class_of(None, &db).await;
389398 assert_eq!(teacher_of(bare.get_id(), &db).await, None);
@@ -421,18 +430,18 @@ mod tests {
421430 None,
422431 None,
423432 None,
424- Some(Some(UserId::from_key("ada"))),
433+ Some(Some(a_named_user(&db, "ada").await)),
425434 )
426435 .await
427436 .unwrap();
428437 assert_eq!(again.get_name().as_str(), "9-B");
429438
430- // A row that predates the column: absent key, not NULL.
431- db.query("UPDATE $class UNSET teacher")
432- .bind(("class", bare.get_id().record()))
439+ // A row without a homeroom: the column reads back as NULL, not a
440+ // decode failure.
441+ sqlx::query("UPDATE class_group SET teacher = NULL WHERE id = $1")
442+ .bind(bare.get_id().uuid())
443+ .execute(&db)
433444 .await
434- .unwrap()
435- .check()
436445 .unwrap();
437446 assert_eq!(teacher_of(bare.get_id(), &db).await, None);
438447 }
@@ -441,9 +450,9 @@ mod tests {
441450 /// *every* class they homeroomed, and nobody else's is touched.
442451 #[tokio::test]
443452 async fn unassign_everywhere_clears_only_that_users_classes() {
444- let db = crate::database::init_mem().await.unwrap();
445- let ada = UserId::from_key("ada");
446- let boole = UserId::from_key("boole");
453+ let (db, _leases) = crate::database::init_test_db().await;
454+ let ada = a_named_user(&db, "ada").await;
455+ let boole = a_named_user(&db, "boole").await;
447456 let first = class_of(Some(ada.clone()), &db).await;
448457 let second = class_of(Some(ada.clone()), &db).await;
449458 let other = class_of(Some(boole.clone()), &db).await;
@@ -471,18 +480,18 @@ mod tests {
471480 /// instead would pass the first assert and fail the roundtrip through boot.
472481 #[tokio::test]
473482 async fn a_term_is_deletable_only_once_no_class_links_it() {
474- let db = crate::database::init_mem().await.unwrap();
483+ let (db, _leases) = crate::database::init_test_db().await;
475484 let term = a_term(&db).await;
476485
477486 let linked = class_on(Some(term.get_id().clone()), &db).await;
478487 let patched = class_on(Some(term.get_id().clone()), &db).await;
479488 assert_eq!(
480- stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await,
489+ one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await,
481490 2,
482491 "classes must count on class_count, not course_count"
483492 );
484493 assert_eq!(
485- stored_count("SELECT VALUE course_count ?? 0 FROM term", &db).await,
494+ one_i64(&db, "SELECT COALESCE(course_count, 0) FROM term".to_string()).await,
486495 0,
487496 "the courses' counter is seeded from course rows and must stay untouched"
488497 );
@@ -511,15 +520,16 @@ mod tests {
511520 /// which a refusal that released it would strand.
512521 #[tokio::test]
513522 async fn a_class_with_members_or_courses_refuses_to_delete() {
514- for field in [CLASS_MEMBER_COUNT_FIELD, CLASS_COURSE_COUNT_FIELD] {
515- let db = crate::database::init_mem().await.unwrap();
523+ for field in ["class_member_count", "class_course_count"] {
524+ let (db, _leases) = crate::database::init_test_db().await;
516525 let term = a_term(&db).await;
517526 let class = class_on(Some(term.get_id().clone()), &db).await;
518- db.query(format!("UPDATE $class SET {field} = 1"))
519- .bind(("class", class.get_id().record()))
527+ sqlx::query(sqlx::AssertSqlSafe(format!(
528+ "UPDATE class_group SET {field} = 1 WHERE id = $1"
529+ )))
530+ .bind(class.get_id().uuid())
531+ .execute(&db)
520532 .await
521- .unwrap()
522- .check()
523533 .unwrap();
524534
525535 assert!(
@@ -531,21 +541,22 @@ mod tests {
531541 "a refused delete may write nothing"
532542 );
533543 assert_eq!(
534- stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await,
544+ one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await,
535545 1,
536546 "…the term reference least of all"
537547 );
538548
539549 // Back to zero, and the same class deletes and releases the term.
540- db.query(format!("UPDATE $class SET {field} = 0"))
541- .bind(("class", class.get_id().record()))
550+ sqlx::query(sqlx::AssertSqlSafe(format!(
551+ "UPDATE class_group SET {field} = 0 WHERE id = $1"
552+ )))
553+ .bind(class.get_id().uuid())
554+ .execute(&db)
542555 .await
543- .unwrap()
544- .check()
545556 .unwrap();
546557 assert!(delete(&db, class.clone()).await.unwrap());
547558 assert_eq!(
548- stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await,
559+ one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await,
549560 0
550561 );
551562 let again = delete(&db, class).await;
@@ -561,14 +572,14 @@ mod tests {
561572 /// delete guard reads, so a stray one would make it undeletable forever).
562573 #[tokio::test]
563574 async fn a_refused_create_writes_neither_row_nor_count() {
564- let db = crate::database::init_mem().await.unwrap();
575+ let (db, _leases) = crate::database::init_test_db().await;
565576 let term = a_term(&db).await;
566577 let id = term.get_id().clone();
567578 assert!(crate::db::term::delete(&db, term).await.unwrap());
568579
569580 let error = create(
570581 &db,
571- &UserId::from_key("manager"),
582+ &a_named_user(&db, "manager").await,
572583 ClassName::try_new("9-A").unwrap(),
573584 None,
574585 Some(id),
@@ -578,12 +589,12 @@ mod tests {
578589 .expect_err("a term that is gone must not be linkable");
579590 assert!(error.to_string().contains("term does not exist"));
580591 assert_eq!(
581- rows("SELECT VALUE id FROM class_group", &db).await,
592+ row_count(&db, "class_group").await,
582593 0,
583594 "a refused create may write no row"
584595 );
585596 assert_eq!(
586- rows("SELECT VALUE id FROM term", &db).await,
597+ row_count(&db, "term").await,
587598 0,
588599 "…and least of all a count on a term it just brought back"
589600 );
@@ -596,7 +607,7 @@ mod tests {
596607 /// so the old count would be 0 if the abort did not undo it).
597608 #[tokio::test]
598609 async fn a_class_term_move_moves_both_counts_or_neither() {
599- let db = crate::database::init_mem().await.unwrap();
610+ let (db, _leases) = crate::database::init_test_db().await;
600611 let at = crate::domain::timestamp::Timestamp::from_millis;
601612 let from = a_term(&db).await;
602613 let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200))
@@ -660,7 +671,7 @@ mod tests {
660671 /// with the counts reading as if they never ran.
661672 #[tokio::test]
662673 async fn a_stale_class_term_write_is_refused_and_moves_no_count() {
663- let db = crate::database::init_mem().await.unwrap();
674+ let (db, _leases) = crate::database::init_test_db().await;
664675 let at = crate::domain::timestamp::Timestamp::from_millis;
665676 let from = a_term(&db).await;
666677 let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200))
@@ -738,8 +749,8 @@ mod tests {
738749 async fn deleting_a_course_sweeps_its_class_attachments() {
739750 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
740751
741- let db = crate::database::init_mem().await.unwrap();
742- let manager = UserId::from_key("manager");
752+ let (db, _leases) = crate::database::init_test_db().await;
753+ let manager = a_named_user(&db, "manager").await;
743754 let course = crate::db::course::create(
744755 &db,
745756 &manager,
@@ -752,30 +763,27 @@ mod tests {
752763 .await
753764 .unwrap();
754765 let class = class_on(None, &db).await;
755- db.query(format!(
756- "CREATE class_course SET class = $class, course = $course, attached_by = $usr;
757- UPDATE $class SET {CLASS_COURSE_COUNT_FIELD} = 1;"
758- ))
759- .bind(("class", class.get_id().record()))
760- .bind(("course", course.get_id().record()))
761- .bind(("usr", manager.record()))
762- .await
763- .unwrap()
764- .check()
765- .unwrap();
766+ sqlx::query("INSERT INTO class_course (class, course, attached_by) VALUES ($1, $2, $3)")
767+ .bind(class.get_id().uuid())
768+ .bind(course.get_id().uuid())
769+ .bind(manager.uuid())
770+ .execute(&db)
771+ .await
772+ .unwrap();
773+ sqlx::query("UPDATE class_group SET class_course_count = 1 WHERE id = $1")
774+ .bind(class.get_id().uuid())
775+ .execute(&db)
776+ .await
777+ .unwrap();
766778
767779 assert!(crate::db::course::delete(&db, course).await.unwrap());
768780 assert_eq!(
769- rows("SELECT VALUE id FROM class_course", &db).await,
781+ row_count(&db, "class_course").await,
770782 0,
771783 "the attachment rows must go with the course"
772784 );
773785 assert_eq!(
774- stored_count(
775- &format!("SELECT VALUE {CLASS_COURSE_COUNT_FIELD} ?? 0 FROM class_group"),
776- &db
777- )
778- .await,
786+ one_i64(&db, "SELECT COALESCE(class_course_count, 0) FROM class_group".to_string()).await,
779787 0,
780788 "…and each class must get its count back"
781789 );
src/db/class_member.rsmodified+90 -28
@@ -50,14 +50,41 @@ pub async fn list_for_user(
5050 #[cfg(test)]
5151 pub(crate) mod tests {
5252 use super::*;
53- use crate::domain::class_group::ClassName;
53+ use crate::domain::class_group::{ClassGroupId, ClassName};
5454 use crate::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle};
55- use surrealdb::types::RecordId;
55+ use crate::domain::user::UserId;
56+
57+ /// A real `app_user` row for fixtures, by username — the username is
58+ /// unique, so every call for the same name shares one row, whichever call
59+ /// minted it. Creators, graders, and `added_by` are foreign keys now, so
60+ use sqlx::Row as _;
61+
62+ /// fixture actors are rows, not fabricated ids.
63+ pub(crate) async fn fixture_user(db: &Database, username: &str) -> UserId {
64+ sqlx::query(
65+ "INSERT INTO app_user (id, username, password_hash, role) \
66+ VALUES ($1, $2, 'x', 'student') ON CONFLICT DO NOTHING",
67+ )
68+ .bind(crate::domain::user::UserId::generate().uuid())
69+ .bind(username)
70+ .execute(db)
71+ .await
72+ .unwrap();
73+ let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1")
74+ .bind(username)
75+ .fetch_one(db)
76+ .await
77+ .unwrap()
78+ .try_get(0)
79+ .unwrap();
80+ UserId::from_key(&id.to_string())
81+ }
5682
5783 pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId {
84+ let manager = fixture_user(db, "manager").await;
5885 crate::db::class_group::create(
5986 db,
60- &UserId::from_key("manager"),
87+ &manager,
6188 ClassName::try_new(name).unwrap(),
6289 None,
6390 None,
@@ -70,9 +97,10 @@ pub(crate) mod tests {
7097 }
7198
7299 pub(crate) async fn a_course(title: &str, capacity: Option<i64>, db: &Database) -> CourseId {
100+ let manager = fixture_user(db, "manager").await;
73101 crate::db::course::create(
74102 db,
75- &UserId::from_key("manager"),
103+ &manager,
76104 CourseTitle::try_new(title).unwrap(),
77105 CourseDescription::try_new("").unwrap(),
78106 CourseKind::course(),
@@ -85,40 +113,74 @@ pub(crate) mod tests {
85113 .clone()
86114 }
87115
88- /// A counter, re-read out of the store — never off a return value, which
89- /// the in-memory engine forges wins on (see [`crate::db::cap`]).
90- pub(crate) async fn counter(field: &str, of: RecordId, db: &Database) -> i64 {
91- let mut result = db
92- .query(format!("SELECT VALUE {field} ?? 0 FROM $of"))
93- .bind(("of", of))
116+ /// A counter column on its row, re-read out of the store — never off a
117+ /// return value. The column name picks the table: every `*_count` these
118+ /// suites read lives on exactly one.
119+ pub(crate) async fn counter(field: &str, of: uuid::Uuid, db: &Database) -> i64 {
120+ let table = match field {
121+ "enrollment_count" => "course",
122+ "class_member_count" | "class_course_count" => "class_group",
123+ other => panic!("no table known for the counter {other}"),
124+ };
125+ sqlx::query(sqlx::AssertSqlSafe(format!(
126+ "SELECT COALESCE({field}, 0) FROM {table} WHERE id = $1"
127+ )))
128+ .bind(of)
129+ .fetch_one(db)
94130 .await
95131 .unwrap()
96- .check()
97- .unwrap();
98- result
99- .take::<Vec<i64>>(0)
132+ .try_get::<i64, _>(0)
133+ .unwrap()
134+ }
135+
136+ /// How many rows `table` holds.
137+ pub(crate) async fn rows(table: &str, db: &Database) -> i64 {
138+ sqlx::query(sqlx::AssertSqlSafe(format!("SELECT count(*) FROM {table}")))
139+ .fetch_one(db)
140+ .await
100141 .unwrap()
101- .first()
102- .copied()
142+ .try_get::<i64, _>(0)
103143 .unwrap()
104144 }
105145
106- /// How many rows `sql` selects ids for.
107- pub(crate) async fn rows(sql: &str, db: &Database) -> usize {
108- let mut result = db.query(sql).await.unwrap().check().unwrap();
109- result.take::<Vec<RecordId>>(0).unwrap().len()
146+ /// Whether the course row is still there.
147+ pub(crate) async fn course_exists(course: &CourseId, db: &Database) -> bool {
148+ sqlx::query("SELECT 1 FROM course WHERE id = $1")
149+ .bind(course.uuid())
150+ .fetch_optional(db)
151+ .await
152+ .unwrap()
153+ .is_some()
110154 }
111155
112- /// Whether `id` names a live row.
113- pub(crate) async fn exists(id: RecordId, db: &Database) -> bool {
114- let mut result = db
115- .query("SELECT VALUE id FROM $id")
116- .bind(("id", id))
156+ /// Whether the enrollment pair still has its row.
157+ pub(crate) async fn enrollment_exists(
158+ course: &CourseId,
159+ user: &UserId,
160+ db: &Database,
161+ ) -> bool {
162+ sqlx::query("SELECT 1 FROM enrollment WHERE course = $1 AND app_user = $2")
163+ .bind(course.uuid())
164+ .bind(user.uuid())
165+ .fetch_optional(db)
117166 .await
118167 .unwrap()
119- .check()
120- .unwrap();
121- !result.take::<Vec<RecordId>>(0).unwrap().is_empty()
168+ .is_some()
169+ }
170+
171+ /// Whether the class-course link is still attached.
172+ pub(crate) async fn link_exists(
173+ class: &ClassGroupId,
174+ course: &CourseId,
175+ db: &Database,
176+ ) -> bool {
177+ sqlx::query("SELECT 1 FROM class_course WHERE class = $1 AND course = $2")
178+ .bind(class.uuid())
179+ .bind(course.uuid())
180+ .fetch_optional(db)
181+ .await
182+ .unwrap()
183+ .is_some()
122184 }
123185
124186 /// The class that wrote an enrollment, or `None` for a hand-placed row.
src/db/class_pump.rsmodified+86 -118
@@ -379,7 +379,7 @@ pub(crate) async fn add_member(
379379 let added_at = Timestamp::now();
380380 let class = class.clone();
381381 let (user, by) = (*user, *by);
382- tx_with_retry(db, false, async move |tx| {
382+ let outcome = tx_with_retry(db, false, async move |tx| {
383383 if let Some(early) =
384384 early_verdicts(tx, &class, Axis::Member, Pivot::User(&user), None).await?
385385 {
@@ -439,11 +439,7 @@ pub(crate) async fn add_member(
439439 .fetch_all(&mut *tx)
440440 .await?;
441441 let pairs = courses.into_iter().map(|course| (course, user.uuid()));
442- match enroll_pairs(tx, &class, pairs, &by).await? {
443- Sweep::Done => {}
444- Sweep::CourseGone(course) => return Ok(Attached::CourseGone(course)),
445- Sweep::Full(course) => return Ok(Attached::Full(course)),
446- }
442+ enroll_pairs(tx, &class, pairs, &by).await?;
447443 Ok(Attached::Made(ClassMember {
448444 class: class.clone(),
449445 user,
@@ -451,7 +447,8 @@ pub(crate) async fn add_member(
451447 added_at: Some(added_at),
452448 }))
453449 })
454- .await
450+ .await;
451+ map_sweep_abort(outcome)
455452 }
456453
457454 /// Write the course link and enroll the class's whole roster into it, or
@@ -478,7 +475,7 @@ pub(crate) async fn attach_course(
478475 let course = course.clone();
479476 let by = *by;
480477 let source = source.cloned();
481- tx_with_retry(db, false, async move |tx| {
478+ let outcome = tx_with_retry(db, false, async move |tx| {
482479 if let Some(early) = early_verdicts(
483480 tx,
484481 &class,
@@ -536,11 +533,7 @@ pub(crate) async fn attach_course(
536533 .fetch_all(&mut *tx)
537534 .await?;
538535 let pairs = members.into_iter().map(|user| (course.uuid(), user));
539- match enroll_pairs(tx, &class, pairs, &by).await? {
540- Sweep::Done => {}
541- Sweep::CourseGone(course) => return Ok(Attached::CourseGone(course)),
542- Sweep::Full(course) => return Ok(Attached::Full(course)),
543- }
536+ enroll_pairs(tx, &class, pairs, &by).await?;
544537 Ok(Attached::Made(ClassCourse {
545538 class: class.clone(),
546539 course: course.clone(),
@@ -549,17 +542,31 @@ pub(crate) async fn attach_course(
549542 attached_at: Some(attached_at),
550543 }))
551544 })
552- .await
545+ .await;
546+ map_sweep_abort(outcome)
553547 }
554548
555-/// What the shared enrollment loop settled for its pairs.
556-enum Sweep {
557- /// Every pair holds the row it owes.
558- Done,
559- /// One of the pairs' courses is gone, named by its key: a stale link.
560- CourseGone(String),
561- /// One of the pairs' courses has no free seat, named by its key.
562- Full(String),
549+/// Abort markers the pair loop raises where the old transaction `THROW` did,
550+/// in the [`crate::db::field_update`] style: a refusal found *after* earlier
551+/// pairs wrote must take the whole run down with it — returning it as `Ok`
552+/// would COMMIT the partial enrollment. The marker carries the course's key
553+/// and is mapped back to [`Attached`] right after [`tx_with_retry`] returns
554+/// ([`map_sweep_abort`]); it never reaches the wire.
555+const COURSE_GONE_MARK: &str = "class_pump_course_gone:";
556+const COURSE_FULL_MARK: &str = "class_pump_course_full:";
557+
558+/// The pair loop's abort markers back into their [`Attached`] refusals —
559+/// every other outcome passes through untouched.
560+fn map_sweep_abort<T>(outcome: Result<Attached<T>, AppError>) -> Result<Attached<T>, AppError> {
561+ match outcome {
562+ Err(AppError::Internal(m)) if m.starts_with(COURSE_GONE_MARK) => Ok(Attached::CourseGone(
563+ m[COURSE_GONE_MARK.len()..].to_string(),
564+ )),
565+ Err(AppError::Internal(m)) if m.starts_with(COURSE_FULL_MARK) => {
566+ Ok(Attached::Full(m[COURSE_FULL_MARK.len()..].to_string()))
567+ }
568+ other => other,
569+ }
563570 }
564571
565572 /// Enroll every `(course, user)` pair that has no row yet, each against its
@@ -583,7 +590,7 @@ async fn enroll_pairs(
583590 class: &ClassGroupId,
584591 pairs: impl Iterator<Item = (uuid::Uuid, uuid::Uuid)>,
585592 by: &UserId,
586-) -> Result<Sweep, AppError> {
593+) -> Result<(), AppError> {
587594 for (course, user) in pairs {
588595 let held = sqlx::query_scalar!(
589596 r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#,
@@ -601,7 +608,7 @@ async fn enroll_pairs(
601608 .await?
602609 .is_some();
603610 if !alive {
604- return Ok(Sweep::CourseGone(course.to_string()));
611+ return Err(AppError::Internal(format!("{COURSE_GONE_MARK}{course}")));
605612 }
606613 let seat = sqlx::query_scalar!(
607614 r#"UPDATE course SET enrollment_count = enrollment_count + 1
@@ -614,7 +621,7 @@ async fn enroll_pairs(
614621 .await?
615622 .is_some();
616623 if !seat {
617- return Ok(Sweep::Full(course.to_string()));
624+ return Err(AppError::Internal(format!("{COURSE_FULL_MARK}{course}")));
618625 }
619626 let wrote = sqlx::query_scalar!(
620627 r#"INSERT INTO enrollment (course, app_user, enrolled_by, source)
@@ -655,7 +662,7 @@ async fn enroll_pairs(
655662 Err(e) => return Err(e.into()),
656663 }
657664 }
658- Ok(Sweep::Done)
665+ Ok(())
659666 }
660667
661668 // The sweep a role change *off` `student` owes — every class membership (each
@@ -900,10 +907,8 @@ async fn release(
900907 #[cfg(test)]
901908 mod tests {
902909 use super::*;
903- use crate::constant::{CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE};
904- use crate::db::class_member::tests::{a_class, counter, rows};
910+ use crate::db::class_member::tests::{a_class, counter, fixture_user, rows};
905911 use crate::domain::class_group::ClassGroupId;
906- use crate::domain::user::UserId;
907912 use crate::error::AppError;
908913 use crate::service::{class_course, class_member};
909914
@@ -913,33 +918,32 @@ mod tests {
913918 /// does not exist.
914919 #[tokio::test]
915920 async fn an_attach_onto_a_missing_class_writes_nothing() {
916- let db = crate::database::init_mem().await.unwrap();
917- let ghost = ClassGroupId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");
921+ let (db, _leases) = crate::database::init_test_db().await;
922+ let ghost = ClassGroupId::from_key("019732e3-7b00-7000-8000-00000000dead");
918923
919924 let refused = class_member::add(
920925 &db,
921926 &ghost,
922- &UserId::from_key("student"),
923- &UserId::from_key("manager"),
927+ &fixture_user(&db, "student").await,
928+ &fixture_user(&db, "manager").await,
924929 )
925930 .await;
926931 assert!(
927932 matches!(refused, Err(AppError::NotFound)),
928933 "a class that is gone is a 404, not a counter on nothing: {refused:?}"
929934 );
930- assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);
931- assert_eq!(rows("SELECT VALUE id FROM class_group", &db).await, 0);
935+ assert_eq!(rows("class_member", &db).await, 0);
936+ assert_eq!(rows("class_group", &db).await, 0);
932937 }
933938
934- /// [`detach`] is written to take *many* link rows at once — that is what
935- /// makes a user's whole membership one statement — and every one of them
936- /// releases its own class's counter. Called straight, because the public
937- /// `delete_for_user` throws the count away.
939+ /// The role-change sweep takes a user's whole membership apart, link row
940+ /// by link row (one transaction per pair since the Postgres port), and
941+ /// every one of them releases its own class's counter.
938942 #[tokio::test]
939943 async fn a_detach_releases_every_class_it_unlinked() {
940- let db = crate::database::init_mem().await.unwrap();
941- let manager = UserId::from_key("manager");
942- let student = UserId::from_key("student");
944+ let (db, _leases) = crate::database::init_test_db().await;
945+ let manager = fixture_user(&db, "manager").await;
946+ let student = fixture_user(&db, "student").await;
943947 let classes = [
944948 a_class("9-A", &db).await,
945949 a_class("9-B", &db).await,
@@ -951,37 +955,24 @@ mod tests {
951955 .unwrap();
952956 }
953957
954- let gone = detach(
955- &db,
956- &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),
957- Axis::Member,
958- &[("usr".into(), student.record().into_value())],
959- )
960- .await
961- .unwrap();
962- assert_eq!(
963- gone, 3,
964- "every link row must be counted, not just the first"
965- );
958+ for class in &classes {
959+ class_member::remove(&db, class, &student).await.unwrap();
960+ }
966961 for class in &classes {
967962 assert_eq!(
968- counter(CLASS_MEMBER_COUNT_FIELD, class.record(), &db).await,
963+ counter("class_member_count", class.uuid(), &db).await,
969964 0,
970965 "each class gets its own counter back"
971966 );
972967 }
973968
974- // And a run that unlinks nothing answers zero, which is what turns a
975- // single-pair detach into a 404 instead of a silent success.
976- let again = detach(
977- &db,
978- &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),
979- Axis::Member,
980- &[("usr".into(), student.record().into_value())],
981- )
982- .await
983- .unwrap();
984- assert_eq!(again, 0);
969+ // And unlinking nobody is a 404, not a silent success — the shape a
970+ // single-pair detach answers with.
971+ let again = class_member::remove(&db, &classes[0], &student).await;
972+ assert!(
973+ matches!(again, Err(AppError::NotFound)),
974+ "a second removal is a 404, not a silent no-op: {again:?}"
975+ );
985976 }
986977
987978 /// The heir a sweep hands a shared enrollment to must still hold *both*
@@ -1004,19 +995,19 @@ mod tests {
1004995 /// not have — it commits both sides and answers `Ok` to each, so this passes
1005996 /// there on broken code.
1006997 ///
1007- /// The window is opened by the schema rather than by a lucky interleaving: a
1008- /// `DEFINE EVENT` on `class_course` scoped to the *owner's* link holds that
1009- /// detach open at its first statement, so the heir's two calls land inside
1010- /// its transaction every time — and the heir's own detach, on another class,
1011- /// is not slowed by it.
998+ /// The window the old engine needed a schema event to open is the row
999+ /// lock now: the owner's sweep claims the heir's class row before it
1000+ /// chooses the heir, so the heir's own member/course writes either land
1001+ /// wholly before the sweep reads them or wait behind it — and the
1002+ /// invariant below must hold in both orders. A barrier start lets every
1003+ /// interleaving happen instead of pinning one.
10121004 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1013- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
10141005 async fn a_detached_row_is_never_handed_to_a_class_that_let_it_go() {
1015- use crate::db::class_member::tests::{a_course, source_of};
1006+ use crate::db::class_member::tests::{a_course, fixture_user, source_of};
10161007
1017- let (db, _serialized) = crate::database::init_test_server("class_heir_race").await;
1018- let manager = UserId::from_key("manager");
1019- let student = UserId::from_key("student");
1008+ let (db, _leases) = crate::database::init_test_db().await;
1009+ let manager = fixture_user(&db, "manager").await;
1010+ let student = fixture_user(&db, "student").await;
10201011 let (mut raced, mut stranded) = (0, 0);
10211012 for round in 0..4 {
10221013 let algebra = a_course(&format!("algebra{round}"), None, &db).await;
@@ -1035,31 +1026,29 @@ mod tests {
10351026 Some(Some(owner.clone())),
10361027 "round {round}: the row must start out owned by the first class"
10371028 );
1038- db.query(format!(
1039- "DEFINE EVENT OVERWRITE hold_the_sweep ON TABLE {CLASS_COURSE_TABLE} \
1040- WHEN $event = 'DELETE' THEN {{ IF $before.class = \
1041- type::record('class_group', '{}') {{ SLEEP 2s }} }};",
1042- owner.key()
1043- ))
1044- .await
1045- .unwrap()
1046- .check()
1047- .unwrap();
10481029
1030+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
10491031 let detaching = {
1050- let (db, owner, algebra) = (db.clone(), owner.clone(), algebra.clone());
1051- tokio::spawn(async move { class_course::detach(&db, &owner, &algebra).await })
1032+ let (db, owner, algebra, gate) =
1033+ (db.clone(), owner.clone(), algebra.clone(), gate.clone());
1034+ tokio::spawn(async move {
1035+ gate.wait().await;
1036+ class_course::detach(&db, &owner, &algebra).await
1037+ })
1038+ };
1039+ // The heir lets the row go, twice over, while the sweep is racing
1040+ // it for the same enrollment row.
1041+ let heir_moves = {
1042+ let (db, heir, algebra, gate) =
1043+ (db.clone(), heir.clone(), algebra.clone(), gate);
1044+ tokio::spawn(async move {
1045+ gate.wait().await;
1046+ class_member::remove(&db, &heir, &student).await?;
1047+ class_course::detach(&db, &heir, &algebra).await
1048+ })
10521049 };
1053- tokio::time::sleep(std::time::Duration::from_millis(500)).await;
1054- assert!(
1055- !detaching.is_finished(),
1056- "round {round}: the sweep was over before the heir moved"
1057- );
1058- // The heir lets the row go, twice over, while that sweep is still
1059- // choosing it.
1060- class_member::remove(&db, &heir, &student).await.unwrap();
1061- class_course::detach(&db, &heir, &algebra).await.unwrap();
10621050 let swept = detaching.await.unwrap();
1051+ heir_moves.await.unwrap().unwrap();
10631052 assert!(
10641053 !matches!(swept, Err(AppError::Db(_))),
10651054 "round {round}: a raced detach must be answered, not 500: {swept:?}"
@@ -1081,25 +1070,4 @@ mod tests {
10811070 );
10821071 }
10831072
1084- #[test]
1085- fn a_full_abort_names_its_course() {
1086- assert_eq!(
1087- named_course("An error occurred: class_full:course:01J8XZ0K3Q", FULL_MARK),
1088- Some("course:01J8XZ0K3Q".to_string())
1089- );
1090- assert_eq!(
1091- named_course("class_full:course:algebra'", FULL_MARK),
1092- Some("course:algebra".into())
1093- );
1094- assert_eq!(named_course("class_held", FULL_MARK), None);
1095- assert_eq!(named_course("class_full:", FULL_MARK), None);
1096- // And the stale-link abort reads off the same shape, without the two
1097- // markers ever matching each other's text.
1098- assert_eq!(
1099- named_course("class_no_course:course:algebra'", MISSING_MARK),
1100- Some("course:algebra".into())
1101- );
1102- assert_eq!(named_course("class_no_course:course:a", FULL_MARK), None);
1103- assert_eq!(named_course("class_full:course:a", MISSING_MARK), None);
1104- }
11051073 }
src/db/course.rsmodified+101 -63
@@ -573,9 +573,21 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
573573 /// way a minted subject id already is for an exam question.
574574 #[cfg(test)]
575575 pub(crate) async fn a_test_course(db: &Database) -> CourseId {
576+ // The creator is a foreign key now: a real row, minted per call so
577+ // repeated calls are new people, not the same one.
578+ let creator = UserId::generate();
579+ sqlx::query(
580+ "INSERT INTO app_user (id, username, password_hash, role) \
581+ VALUES ($1, $2, 'x', 'teacher')",
582+ )
583+ .bind(creator.uuid())
584+ .bind(format!("course-fixture-{}", &creator.key()[..8]))
585+ .execute(db)
586+ .await
587+ .unwrap();
576588 create(
577589 db,
578- &UserId::generate(),
590+ &creator,
579591 CourseTitle::try_new("test course").unwrap(),
580592 CourseDescription::try_new("").unwrap(),
581593 CourseKind::course(),
@@ -615,28 +627,26 @@ pub(crate) async fn a_test_course(db: &Database) -> CourseId {
615627 /// on broken code.
616628 #[cfg(test)]
617629 pub(crate) async fn assert_no_child_outlives_a_course_delete(
618- scratch: &str,
619630 table: &str,
620631 make: fn(CourseId, Database) -> tokio::task::JoinHandle<Result<(), AppError>>,
621632 ) {
622- // The guard is held for the whole test: these bursts are sub-millisecond,
623- // and a sibling race test's burst pushes a delete clean out of its window.
624- let (db, _serialized) = crate::database::init_test_server(scratch).await;
625- db.query(
626- "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \
627- THEN { SLEEP 1s; };",
628- )
629- .await
630- .expect("define the window event")
631- .check()
632- .expect("check the window event");
633+ use sqlx::Row as _;
634+
635+ let (db, _leases) = crate::database::init_test_db().await;
633636
634637 let (mut swept, mut orphans) = (0, 0);
635- for round in 0..4 {
638+ for round in 0..8 {
636639 let course = a_test_course(&db).await;
640+ // The old engine needed a schema event to hold the delete's window
641+ // open; Postgres puts the racing create and delete on the same rows
642+ // (the FK claims and the cascade), so a barrier start covers every
643+ // interleaving — and the child may never outlive the course in any
644+ // of them.
645+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
637646 let drop_it = {
638- let (course, db) = (course.clone(), db.clone());
647+ let (course, db, gate) = (course.clone(), db.clone(), gate.clone());
639648 tokio::spawn(async move {
649+ gate.wait().await;
640650 delete(
641651 &db,
642652 read(&db, &course)
@@ -647,9 +657,17 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete(
647657 .await
648658 })
649659 };
650- // The create starts inside the held window.
651- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
652- let child = make(course.clone(), db.clone()).await.unwrap();
660+ let child = {
661+ let (course, db, gate) = (course.clone(), db.clone(), gate);
662+ tokio::spawn(async move {
663+ gate.wait().await;
664+ // The inner task joins here: a `Db` answer stays `Err`, only a
665+ // panic inside `make` (or the outer join) would panic.
666+ make(course, db).await.unwrap()
667+ })
668+ }
669+ .await
670+ .unwrap();
653671 let dropped = drop_it.await.unwrap();
654672
655673 // A 404 for the create, or a refusal for the delete, is a correct
@@ -666,24 +684,23 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete(
666684 // Stored state is the whole verdict; a return value is not evidence.
667685 if read(&db, &course).await.unwrap().is_none() {
668686 swept += 1;
669- let mut left = db
670- .query(format!(
671- "SELECT VALUE id FROM {table} WHERE course = $course"
672- ))
673- .bind(("course", course.record()))
674- .await
675- .unwrap()
676- .check()
677- .unwrap();
678- orphans += left.take::<Vec<RecordId>>(0).unwrap().len();
687+ orphans += sqlx::query(sqlx::AssertSqlSafe(format!(
688+ "SELECT count(*) FROM {table} WHERE course = $1"
689+ )))
690+ .bind(course.uuid())
691+ .fetch_one(&db)
692+ .await
693+ .unwrap()
694+ .try_get::<i64, _>(0)
695+ .unwrap() as usize;
679696 } else if matches!(dropped, Ok(true)) {
680697 panic!("{table} round {round}: the delete reported success, the course is still there");
681698 }
682699 }
683- eprintln!("Course::delete raced by a {table} create: {swept}/4 rounds deleted the course");
700+ eprintln!("Course::delete raced by a {table} create: {swept}/8 rounds deleted the course");
684701 assert!(
685702 swept > 0,
686- "{table}: no round ever deleted the course, so the window was never reached"
703+ "{table}: no round ever deleted the course, so the race never actually ran"
687704 );
688705 assert_eq!(orphans, 0, "{table}: a child outlived its course");
689706 }
@@ -691,12 +708,31 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete(
691708 #[cfg(test)]
692709 mod tests {
693710 use super::*;
711+ use sqlx::Row as _;
694712 use crate::domain::term::{Term, TermName};
695713
714+ /// A real `app_user` row: creators, students and enrollers are foreign
715+ /// keys now. The label names the row's username; the id is minted, so
716+ /// repeated calls are new people, not the same row.
717+ async fn a_person(db: &Database, label: &str, role: &str) -> UserId {
718+ let user = UserId::generate();
719+ sqlx::query(
720+ "INSERT INTO app_user (id, username, password_hash, role) \
721+ VALUES ($1, $2, 'x', $3)",
722+ )
723+ .bind(user.uuid())
724+ .bind(format!("{label}-{}", &user.key()[..8]))
725+ .bind(role)
726+ .execute(db)
727+ .await
728+ .unwrap();
729+ user
730+ }
731+
696732 async fn course_on(term: Option<TermId>, db: &Database) -> Course {
697733 create(
698734 db,
699- &UserId::from_key("teacher"),
735+ &a_person(db, "teacher", "teacher").await,
700736 CourseTitle::try_new("algebra").unwrap(),
701737 CourseDescription::try_new("").unwrap(),
702738 CourseKind::course(),
@@ -713,9 +749,9 @@ mod tests {
713749 /// included. A `>= 0` guard passes the roster branch and fails here.
714750 #[tokio::test]
715751 async fn a_course_with_a_roster_refuses_to_delete() {
716- let db = crate::database::init_mem().await.unwrap();
717- let teacher = UserId::from_key("teacher");
718- let student = UserId::from_key("student");
752+ let (db, _leases) = crate::database::init_test_db().await;
753+ let teacher = a_person(&db, "teacher", "teacher").await;
754+ let student = a_person(&db, "student", "student").await;
719755 let course = course_on(None, &db).await;
720756 crate::db::enrollment::enroll(&db, course.get_id(), &student, &teacher)
721757 .await
@@ -758,7 +794,7 @@ mod tests {
758794 /// back. Dropping the release in `delete` leaves the term deletable never.
759795 #[tokio::test]
760796 async fn a_term_is_deletable_only_once_no_course_links_it() {
761- let db = crate::database::init_mem().await.unwrap();
797+ let (db, _leases) = crate::database::init_test_db().await;
762798 let at = crate::domain::timestamp::Timestamp::from_millis;
763799 let term =
764800 crate::db::term::create(&db, TermName::try_new("2026").unwrap(), at(100), at(200))
@@ -797,10 +833,10 @@ mod tests {
797833 /// web layer's pre-flight lookup gives.
798834 #[tokio::test]
799835 async fn a_course_cannot_link_a_term_that_is_gone() {
800- let db = crate::database::init_mem().await.unwrap();
836+ let (db, _leases) = crate::database::init_test_db().await;
801837 let error = create(
802838 &db,
803- &UserId::from_key("teacher"),
839+ &a_person(&db, "teacher", "teacher").await,
804840 CourseTitle::try_new("algebra").unwrap(),
805841 CourseDescription::try_new("").unwrap(),
806842 CourseKind::course(),
@@ -814,27 +850,23 @@ mod tests {
814850
815851 /// The stored `course_count` on one term, absent counting as zero.
816852 async fn count_on(term: &TermId, db: &Database) -> i64 {
817- let mut result = db
818- .query(format!(
819- "SELECT VALUE ({COURSE_COUNT_FIELD} ?? 0) FROM $term"
820- ))
821- .bind(("term", term.record()))
853+ sqlx::query("SELECT COALESCE(course_count, 0) FROM term WHERE id = $1")
854+ .bind(term.uuid())
855+ .fetch_one(db)
822856 .await
823857 .unwrap()
824- .check()
825- .unwrap();
826- result
827- .take::<Vec<i64>>(0)
858+ .try_get::<i64, _>(0)
828859 .unwrap()
829- .first()
830- .copied()
831- .unwrap_or(0)
832860 }
833861
834862 /// How many rows `sql` selects ids for.
835863 async fn rows(sql: &str, db: &Database) -> usize {
836- let mut result = db.query(sql).await.unwrap().check().unwrap();
837- result.take::<Vec<RecordId>>(0).unwrap().len()
864+ sqlx::query(sqlx::AssertSqlSafe(sql.to_string()))
865+ .fetch_one(db)
866+ .await
867+ .unwrap()
868+ .try_get::<i64, _>(0)
869+ .unwrap() as usize
838870 }
839871
840872 async fn a_term(name: &str, db: &Database) -> Term {
@@ -851,14 +883,14 @@ mod tests {
851883 /// stray one makes the term undeletable forever).
852884 #[tokio::test]
853885 async fn a_refused_create_writes_neither_row_nor_count() {
854- let db = crate::database::init_mem().await.unwrap();
886+ let (db, _leases) = crate::database::init_test_db().await;
855887 let term = a_term("2026", &db).await;
856888 let id = term.get_id().clone();
857889 assert!(crate::db::term::delete(&db, term).await.unwrap());
858890
859891 let error = create(
860892 &db,
861- &UserId::from_key("teacher"),
893+ &a_person(&db, "teacher", "teacher").await,
862894 CourseTitle::try_new("algebra").unwrap(),
863895 CourseDescription::try_new("").unwrap(),
864896 CourseKind::course(),
@@ -884,7 +916,7 @@ mod tests {
884916 /// term's claim and the old term's release with the link itself.
885917 #[tokio::test]
886918 async fn a_term_move_moves_the_count() {
887- let db = crate::database::init_mem().await.unwrap();
919+ let (db, _leases) = crate::database::init_test_db().await;
888920 let from = a_term("2026", &db).await;
889921 let to = a_term("2027", &db).await;
890922 let course = course_on(Some(from.get_id().clone()), &db).await;
@@ -921,7 +953,7 @@ mod tests {
921953 /// counts must read as if it never ran.
922954 #[tokio::test]
923955 async fn a_stale_mover_is_refused_and_claims_nothing() {
924- let db = crate::database::init_mem().await.unwrap();
956+ let (db, _leases) = crate::database::init_test_db().await;
925957 let from = a_term("2026", &db).await;
926958 let to = a_term("2027", &db).await;
927959 let other = a_term("2028", &db).await;
@@ -1012,7 +1044,7 @@ mod tests {
10121044 /// *carrying* the column instead, which is why this is refused.
10131045 #[tokio::test]
10141046 async fn a_stale_re_stater_is_refused_and_reverts_nothing() {
1015- let db = crate::database::init_mem().await.unwrap();
1047+ let (db, _leases) = crate::database::init_test_db().await;
10161048 let from = a_term("2026", &db).await;
10171049 let to = a_term("2027", &db).await;
10181050 let course = course_on(Some(from.get_id().clone()), &db).await;
@@ -1083,7 +1115,7 @@ mod tests {
10831115 /// The title moves in the same PATCH, and must not stick either.
10841116 #[tokio::test]
10851117 async fn a_term_move_to_a_dead_term_leaves_everything_untouched() {
1086- let db = crate::database::init_mem().await.unwrap();
1118+ let (db, _leases) = crate::database::init_test_db().await;
10871119 let from = a_term("2026", &db).await;
10881120 let dead = a_term("2027", &db).await;
10891121 let dead_id = dead.get_id().clone();
@@ -1148,9 +1180,16 @@ mod tests {
11481180 /// current-thread runtime never interleaves the two, and the embedded
11491181 /// engine does not conflict-check concurrent writes to one record at all.
11501182 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1151- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
11521183 async fn a_delete_racing_an_enroll_never_answers_500() {
1153- let (db, _serialized) = crate::database::init_test_server("course_delete_race").await;
1184+ let (db, _leases) = crate::database::init_test_db().await;
1185+ // The roster rows are foreign keys now: the burst's six racers and
1186+ // their enroller are real people, reused every round (each round's
1187+ // delete cascade frees the seats back).
1188+ let mgr = a_person(&db, "mgr", "manager").await;
1189+ let mut students = Vec::new();
1190+ for seat in 0..6 {
1191+ students.push(a_person(&db, &format!("stu{seat}"), "student").await);
1192+ }
11541193 let (mut delete_500, mut enroll_500, mut enrolled) = (0, 0, 0);
11551194 let (mut last_delete, mut last_enroll) = (String::new(), String::new());
11561195 for round in 0..20 {
@@ -1172,11 +1211,10 @@ mod tests {
11721211 };
11731212 let joins: Vec<_> = (0..6)
11741213 .map(|seat| {
1175- let (id, db) = (course.get_id().clone(), db.clone());
1176- let student = UserId::from_key(&format!("stu{round}_{seat}"));
1214+ let (id, db, mgr) = (course.get_id().clone(), db.clone(), mgr.clone());
1215+ let student = students[seat].clone();
11771216 tokio::spawn(async move {
1178- crate::db::enrollment::enroll(&db, &id, &student, &UserId::from_key("mgr"))
1179- .await
1217+ crate::db::enrollment::enroll(&db, &id, &student, &mgr).await
11801218 })
11811219 })
11821220 .collect();
src/db/course_note.rsmodified+1 -1
@@ -157,7 +157,7 @@ mod tests {
157157 /// been taken, which is the row whose blob used to leak.
158158 #[tokio::test]
159159 async fn delete_returns_the_attachment_rows_it_removed() {
160- let db = crate::database::init_mem().await.unwrap();
160+ let (db, _leases) = crate::database::init_test_db().await;
161161 let creator = crate::domain::user::UserId::generate();
162162 let course = crate::db::course::create(
163163 &db,
src/db/course_note_file.rsmodified+2 -2
@@ -192,7 +192,7 @@ mod tests {
192192 /// the count stays at the accepted rows.
193193 #[tokio::test]
194194 async fn insert_refuses_at_the_cap() {
195- let db = crate::database::init_mem().await.unwrap();
195+ let (db, _leases) = crate::database::init_test_db().await;
196196 let note = note_of(&db, "n").await;
197197 for index in 0..MAX_COURSE_NOTE_FILES {
198198 let file = CourseNoteFile::new(
@@ -221,7 +221,7 @@ mod tests {
221221 /// delete hands its slot back to the note.
222222 #[tokio::test]
223223 async fn file_keys_and_delete_slot_release() {
224- let db = crate::database::init_mem().await.unwrap();
224+ let (db, _leases) = crate::database::init_test_db().await;
225225 let note = note_of(&db, "n").await;
226226 let course = note.get_course().clone();
227227 let file = CourseNoteFile::new(
src/db/course_session.rsmodified+13 -8
@@ -171,14 +171,24 @@ mod tests {
171171 /// Mutation-tested: with the bare `db.create` this shipped with, all four
172172 /// rounds orphan.
173173 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
174- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
175174 async fn a_session_never_outlives_its_course() {
176175 fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {
177176 tokio::spawn(async move {
177+ // The creator is a foreign key now: a real `app_user` row.
178+ let creator = UserId::generate();
179+ sqlx::query(
180+ "INSERT INTO app_user (id, username, password_hash, role) \
181+ VALUES ($1, $2, 'x', 'teacher')",
182+ )
183+ .bind(creator.uuid())
184+ .bind(format!("session-race-{}", &creator.key()[..8]))
185+ .execute(&db)
186+ .await
187+ .unwrap();
178188 create(
179189 &db,
180190 &course,
181- &UserId::generate(),
191+ &creator,
182192 SessionTopic::try_new("limits").unwrap(),
183193 Timestamp::from_millis(1),
184194 None,
@@ -187,11 +197,6 @@ mod tests {
187197 .map(|_| ())
188198 })
189199 }
190- crate::db::course::assert_no_child_outlives_a_course_delete(
191- "session_orphan_race",
192- COURSE_SESSION_TABLE,
193- make,
194- )
195- .await;
200+ crate::db::course::assert_no_child_outlives_a_course_delete("session", make).await;
196201 }
197202 }
src/db/enrollment.rsmodified+4 -57
@@ -251,59 +251,6 @@ pub async fn remove(
251251 mod tests {
252252 use super::*;
253253
254- /// The boot repair of `enrollment_count` **against a real server**, and
255- /// `#[ignore]`d for it: the pass counts rows off `enrollment`'s indexed
256- /// `course` field, and an aggregate over an indexed field is exactly where
257- /// the embedded engine and the server are known to differ (`count()` comes
258- /// back `{count: N}` from one and a bare int from the other, which
259- /// `option<int>` would refuse). `array::len` over ids is the spelling that
260- /// dodges it — this is what proves it on the store that bites.
261- ///
262- /// Both halves in one boot: `staff` is the row the sweep deletes (their
263- /// seat must come back), and `empty` is the course a *past* sweep already
264- /// stranded — count above zero with no rows left, so it forms no group and
265- /// only a per-course pass ever visits it. The second `migrate` pins that the
266- /// repair converges rather than overwriting: it must write nothing.
267- #[tokio::test]
268- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
269- async fn the_count_repair_recounts_on_a_real_server() {
270- let (db, _serialized) = crate::database::init_test_server("enrollment_repair").await;
271- db.query(
272- "CREATE user:t SET username = 't', password_hash = 'x', role = 'teacher';
273- CREATE user:a SET username = 'a', password_hash = 'x', role = 'student';
274- CREATE user:b SET username = 'b', password_hash = 'x', role = 'student';
275- CREATE course:live SET creator = user:t, title = 'l', description = '',
276- enrollment_count = 9;
277- CREATE course:empty SET creator = user:t, title = 'e', description = '',
278- enrollment_count = 4;
279- CREATE enrollment:live_a SET course = course:live, user = user:a, enrolled_by = user:t;
280- CREATE enrollment:live_b SET course = course:live, user = user:b, enrolled_by = user:t;
281- CREATE enrollment:live_t SET course = course:live, user = user:t, enrolled_by = user:t;",
282- )
283- .await
284- .unwrap()
285- .check()
286- .unwrap();
287-
288- async fn counts(db: &Database) -> Vec<i64> {
289- let mut result = db
290- .query("SELECT VALUE enrollment_count FROM course ORDER BY id")
291- .await
292- .unwrap()
293- .check()
294- .unwrap();
295- result.take::<Vec<i64>>(0).unwrap()
296- }
297-
298- crate::database::migrate(db.as_ref()).await.unwrap();
299- // `course:empty` sorts before `course:live`: stranded count cleared, and
300- // the live course recounted to its two students — the teacher's row was
301- // swept and handed its seat back in the same boot.
302- assert_eq!(counts(&db).await, vec![0, 2]);
303-
304- crate::database::migrate(db.as_ref()).await.unwrap();
305- assert_eq!(counts(&db).await, vec![0, 2], "the repair converges");
306- }
307254
308255 /// A pumped row that vanishes under the disown — a concurrent unenroll, or
309256 /// the sweep a role change runs — must answer the row the caller was
@@ -312,10 +259,10 @@ mod tests {
312259 /// server error on an ordinary `POST /courses/{id}/enrollments`.
313260 #[tokio::test]
314261 async fn a_vanished_row_is_not_an_internal_error() {
315- let db = crate::database::init_mem().await.unwrap();
262+ let (db, _leases) = crate::database::init_test_db().await;
316263 let class = crate::domain::class_group::ClassGroupId::from_key("9a");
317- let course = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");
318- let student = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U");
264+ let course = CourseId::from_key("019732e3-7b00-7000-8000-00000000dead");
265+ let student = UserId::from_key("019732e3-7b00-7000-8000-00000000deae");
319266 // Never written: the same store state a delete in the window leaves.
320267 let ghost = Enrollment {
321268 id: EnrollmentId::composite(&course, &student),
@@ -337,7 +284,7 @@ mod tests {
337284 async fn a_hand_placed_enrollment_stores_no_source_key() {
338285 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
339286
340- let db = crate::database::init_mem().await.unwrap();
287+ let (db, _leases) = crate::database::init_test_db().await;
341288 let teacher = UserId::from_key("teacher");
342289 let course = crate::db::course::create(
343290 &db,
src/db/event.rsmodified+63 -28
@@ -291,31 +291,61 @@ pub async fn delete(db: &Database, event: Event) -> Result<Event, AppError> {
291291 #[cfg(test)]
292292 mod tests {
293293 use super::*;
294- use crate::constant::REGISTRATION_FROZEN_GUARD;
295- use crate::domain::class_group::ClassGroupId;
294+
295+ /// A real `app_user` row: the creator is a foreign key now.
296+ async fn a_person(db: &Database, label: &str) -> UserId {
297+ let user = UserId::generate();
298+ sqlx::query(
299+ "INSERT INTO app_user (id, username, password_hash, role) \
300+ VALUES ($1, $2, 'x', 'teacher')",
301+ )
302+ .bind(user.uuid())
303+ .bind(format!("{label}-{}", &user.key()[..8]))
304+ .execute(db)
305+ .await
306+ .unwrap();
307+ user
308+ }
296309
297310 /// The forcing function behind the one rule with two spellings: the freeze
298- /// this file decides in Rust ([`Event::registration_capacity`]) and
299- /// [`REGISTRATION_FROZEN_GUARD`], its SurrealQL copy, which
300- /// the role cascade (`service::user::set_role`) carries because it frees a demoted
301- /// parent's seats inside a transaction and cannot call Rust from there.
311+ /// this file decides in Rust ([`Event::registration_capacity`]) and the
312+ /// demotion sweep's SQL predicate, which `service::user::set_role` carries
313+ /// because it frees a demoted parent's seats inside a transaction and
314+ /// cannot call Rust from there. The predicate is copied here test-side on
315+ /// purpose: the sweep lives in user.rs, and this test pins the copy.
302316 ///
303317 /// Every schedule shape is put to both, including the three the SQL is most
304- /// likely to get wrong: the ends_at-only event (`??` must fall through to
318+ /// likely to get wrong: the ends_at-only event (`COALESCE` must fall through to
305319 /// it), the boundary itself (closed *at* the instant, not after it — `>=` in
306- /// Rust, `<=` in SQL, and the two read opposite ways round; `$now` is bound
320+ /// Rust, `<=` in SQL, and the two read opposite ways round; `now` is bound
307321 /// to that exact instant so the boundary is really exercised), and an event
308322 /// that takes no registrations at all, which Rust refuses one arm *earlier*
309323 /// — so the SQL must not report it frozen, or a stray row on it would be
310324 /// preserved forever instead of swept.
311325 #[tokio::test]
312326 async fn the_sql_freeze_guard_matches_the_rust_one() {
313- let db = crate::database::init_mem().await.unwrap();
327+ let (db, _leases) = crate::database::init_test_db().await;
328+ let creator = a_person(&db, "event-guard").await;
329+ // `audience_class` is a foreign key too: the class case needs a real group.
330+ let class = ClassGroupId::generate();
331+ sqlx::query("INSERT INTO class_group (id, name, creator) VALUES ($1, 'g1', $2)")
332+ .bind(class.uuid())
333+ .bind(creator.uuid())
334+ .execute(&db)
335+ .await
336+ .unwrap();
337+ let no_payload = |kind| EventAudience {
338+ kind,
339+ role: None,
340+ course: None,
341+ class: None,
342+ capacity: None,
343+ };
314344 let now = Timestamp::now().as_millis();
315345 let past = Some(Timestamp::from_millis(now - 60_000));
316346 let future = Some(Timestamp::from_millis(now + 3_600_000));
317347 let later = Some(Timestamp::from_millis(now + 7_200_000));
318- let signup = EventAudience::Registration { capacity: None };
348+ let signup = no_payload(EventAudienceKind::Registration);
319349 let cases = [
320350 ("timeless", signup.clone(), None, None),
321351 ("deadline ahead", signup.clone(), None, future),
@@ -331,11 +361,17 @@ mod tests {
331361 ),
332362 // No signup list to freeze: `registration_capacity` refuses these on
333363 // the audience, before it ever looks at the clock.
334- ("started school event", EventAudience::School, past, None),
364+ (
365+ "started school event",
366+ no_payload(EventAudienceKind::School),
367+ past,
368+ None,
369+ ),
335370 (
336371 "started class event",
337- EventAudience::Class {
338- class: ClassGroupId::from_key("g1"),
372+ EventAudience {
373+ class: Some(class),
374+ ..no_payload(EventAudienceKind::Class)
339375 },
340376 past,
341377 None,
@@ -344,7 +380,7 @@ mod tests {
344380 for (name, audience, starts_at, ends_at) in cases {
345381 let event = create(
346382 &db,
347- &UserId::from_key("teacher"),
383+ &creator,
348384 EventTitle::try_new(name).unwrap(),
349385 EventDescription::try_new("").unwrap(),
350386 audience,
@@ -357,20 +393,19 @@ mod tests {
357393 event.registration_capacity(),
358394 Err(AppError::Conflict(_) | AppError::ConflictOwned(_))
359395 );
360- let mut result = db
361- .query(format!(
362- "SELECT VALUE id FROM $ev WHERE {REGISTRATION_FROZEN_GUARD}"
363- ))
364- .bind(("ev", event.get_id().record()))
365- .bind(("now", now))
366- .await
367- .unwrap()
368- .check()
369- .unwrap();
370- let sql = !result
371- .take::<Vec<surrealdb::types::RecordId>>(0)
372- .unwrap()
373- .is_empty();
396+ // Test-side copy of the sweep predicate in `service::user::set_role`
397+ // (src/db/user.rs): frozen == the demotion sweep would leave the row.
398+ let sql = !sqlx::query_scalar::<_, bool>(
399+ "SELECT audience_kind = 'registration' \
400+ AND COALESCE(starts_at, ends_at) IS NOT NULL \
401+ AND COALESCE(starts_at, ends_at) <= $2 \
402+ FROM event WHERE id = $1",
403+ )
404+ .bind(event.get_id().uuid())
405+ .bind(now)
406+ .fetch_one(&db)
407+ .await
408+ .unwrap();
374409 assert_eq!(
375410 sql, rust,
376411 "the SQL freeze guard and registration_capacity disagree on a \
src/db/exam.rsmodified+123 -147
@@ -483,39 +483,20 @@ pub(crate) async fn published_exam(db: &Database) -> Exam {
483483 let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
484484 .get_exam_kinds()
485485 .to_vec();
486- create(
487- db,
488- &UserId::generate(),
489- &crate::db::course::a_test_course(db).await,
490- ExamTitle::try_new("midterm").unwrap(),
491- ExamDescription::try_new("").unwrap(),
492- ExamKind::try_new("midterm", &allowed).unwrap(),
493- ExamSchedule::try_new(None, None, None, None).unwrap(),
494- ExamAttemptLimit::try_new(1).unwrap(),
495- true,
496- false,
497- false,
486+ // The creator is a foreign key now: a real `app_user` row, minted per call.
487+ let creator = UserId::generate();
488+ sqlx::query(
489+ "INSERT INTO app_user (id, username, password_hash, role) \
490+ VALUES ($1, $2, 'x', 'teacher')",
498491 )
492+ .bind(creator.uuid())
493+ .bind(format!("exam-fixture-{}", &creator.key()[..8]))
494+ .execute(db)
499495 .await
500- .unwrap()
501-}
502-
503-#[cfg(test)]
504-use crate::domain::settings::ExamKindDef;
505-
506-/// An unscheduled published exam — the minimum any test that writes a *child*
507-/// of an exam needs, in any module: every such write moves the exam row (see
508-/// [`crate::db::exam_attempt::write_unfrozen_with`]
509-/// and [`crate::db::exam_answer::save`]), so a minted id whose
510-/// row was never created is a 404 rather than a silent orphan.
511-#[cfg(test)]
512-pub(crate) async fn published_exam(db: &Database) -> Exam {
513- let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
514- .get_exam_kinds()
515- .to_vec();
496+ .unwrap();
516497 create(
517498 db,
518- &UserId::generate(),
499+ &creator,
519500 &crate::db::course::a_test_course(db).await,
520501 ExamTitle::try_new("midterm").unwrap(),
521502 ExamDescription::try_new("").unwrap(),
@@ -536,7 +517,6 @@ mod tests {
536517
537518 use super::published_exam as published;
538519
539- use crate::constant::EXAM_TABLE;
540520 use crate::domain::exam::{ExamDuration, ExamMode};
541521 use crate::domain::settings::ExamKindDef;
542522 use crate::domain::timestamp::Timestamp;
@@ -556,16 +536,25 @@ mod tests {
556536 /// Mutation-tested: with the bare `db.create` this shipped with, all four
557537 /// rounds orphan.
558538 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
559- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
560539 async fn an_exam_never_outlives_its_course() {
561540 fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {
562541 tokio::spawn(async move {
563542 let kinds = crate::domain::settings::Settings::defaults()
564543 .get_exam_kinds()
565544 .to_vec();
545+ let creator = UserId::generate();
546+ sqlx::query(
547+ "INSERT INTO app_user (id, username, password_hash, role) \
548+ VALUES ($1, $2, 'x', 'teacher')",
549+ )
550+ .bind(creator.uuid())
551+ .bind(format!("orphan-race-{}", &creator.key()[..8]))
552+ .execute(&db)
553+ .await
554+ .unwrap();
566555 create(
567556 &db,
568- &UserId::generate(),
557+ &creator,
569558 &course,
570559 ExamTitle::try_new("quiz").unwrap(),
571560 ExamDescription::try_new("").unwrap(),
@@ -580,12 +569,25 @@ mod tests {
580569 .map(|_| ())
581570 })
582571 }
583- crate::db::course::assert_no_child_outlives_a_course_delete(
584- "exam_orphan_race",
585- EXAM_TABLE,
586- make,
572+ crate::db::course::assert_no_child_outlives_a_course_delete("exam", make).await;
573+ }
574+
575+ /// A real `app_user` row: students and graders are foreign keys now. The
576+ /// label names the row's username; the id is minted, so repeated calls are
577+ /// new people, not the same row.
578+ async fn a_person(db: &Database, label: &str, role: &str) -> UserId {
579+ let user = UserId::generate();
580+ sqlx::query(
581+ "INSERT INTO app_user (id, username, password_hash, role) \
582+ VALUES ($1, $2, 'x', $3)",
587583 )
588- .await;
584+ .bind(user.uuid())
585+ .bind(format!("{label}-{}", &user.key()[..8]))
586+ .bind(role)
587+ .execute(db)
588+ .await
589+ .unwrap();
590+ user
589591 }
590592
591593 fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) {
@@ -603,7 +605,7 @@ mod tests {
603605 /// written over somebody else's edit. Asserts the *stored* row.
604606 #[tokio::test]
605607 async fn a_merge_built_on_a_stale_snapshot_is_refused() {
606- let db = crate::database::init_mem().await.unwrap();
608+ let (db, _leases) = crate::database::init_test_db().await;
607609 let stale = published(&db).await;
608610 let (_, description, kind, schedule) = edit(&stale);
609611 let landed = update_if_unchanged(
@@ -650,16 +652,17 @@ mod tests {
650652 async fn re_drafting_is_refused_by_the_write_itself_once_a_mark_exists() {
651653 use crate::db::exam_result;
652654 use crate::domain::exam_result::Mark;
653- let db = crate::database::init_mem().await.unwrap();
655+ let (db, _leases) = crate::database::init_test_db().await;
654656 let exam = published(&db).await;
655- let student = UserId::generate();
657+ let student = a_person(&db, "student", "student").await;
658+ let grader = a_person(&db, "teacher", "teacher").await;
656659 exam_result::grade(
657660 &db,
658661 exam.get_id(),
659662 &student,
660663 1,
661664 Mark::try_new(80).unwrap(),
662- &UserId::generate(),
665+ &grader,
663666 exam.get_kind().as_str(),
664667 )
665668 .await
@@ -796,10 +799,9 @@ mod tests {
796799 /// [`crate::db::course::delete`]'s race test for why the rate is
797800 /// counted rather than asserted per round.
798801 ///
799- /// This site has no `THROW` marker at all: it ends `.check()?`, which
800- /// returns the *first* error in the batch, and an aborted transaction
801- /// errors every slot — most of them with a generic "not executed". So a
802- /// genuine conflict can be masked by a sibling, and either way there is no
802+ /// This site has no marker at all: the delete's statements share one
803+ /// transaction whose first failure aborts the rest, so a genuine conflict
804+ /// can be masked by a sibling error, and either way there is no
803805 /// [`crate::database::lost_the_race`] check and no retry.
804806 ///
805807 /// The racer is a mark: [`crate::db::exam_result::grade`] claims the exam's own
@@ -822,11 +824,11 @@ mod tests {
822824 /// cascade (marks either survive whole or are swept whole, never a 500).
823825 /// The retry is measured on [`crate::db::course::delete`].
824826 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
825- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
826827 async fn a_delete_racing_a_mark_never_answers_500() {
827828 use crate::db::exam_result;
828829 use crate::domain::exam_result::Mark;
829- let (db, _serialized) = crate::database::init_test_server("exam_delete_race").await;
830+ let (db, _leases) = crate::database::init_test_db().await;
831+ let teacher = a_person(&db, "teacher", "teacher").await;
830832 let (mut delete_500, mut grade_500) = (0, 0);
831833 let (mut split, mut swept) = (0, 0);
832834 let (mut last_delete, mut last_grade) = (String::new(), String::new());
@@ -850,10 +852,16 @@ mod tests {
850852 delete(&db, exam).await
851853 })
852854 };
855+ // Six real students per round: the mark's app_user is a foreign
856+ // key now.
857+ let mut students = Vec::with_capacity(6);
858+ for _ in 0..6 {
859+ students.push(a_person(&db, "student", "student").await);
860+ }
853861 let marks: Vec<_> = (0..6)
854862 .map(|seat| {
855863 let (id, db, kind) = (exam.get_id().clone(), db.clone(), kind.clone());
856- let student = UserId::from_key(&format!("stu{round}_{seat}"));
864+ let (student, teacher) = (students[seat].clone(), teacher.clone());
857865 tokio::spawn(async move {
858866 exam_result::grade(
859867 &db,
@@ -861,7 +869,7 @@ mod tests {
861869 &student,
862870 1,
863871 Mark::try_new(50).unwrap(),
864- &UserId::from_key("teacher"),
872+ &teacher,
865873 &kind,
866874 )
867875 .await
@@ -871,7 +879,7 @@ mod tests {
871879 let drop_it = drop_it.await.unwrap();
872880 if matches!(drop_it, Err(AppError::Db(_))) {
873881 delete_500 += 1;
874- last_delete = format!("{drop_it:?}");
882+ last_delete = format!("{:?}", drop_it.as_ref().unwrap_err());
875883 }
876884 let mut refused = 0;
877885 for mark in marks {
@@ -972,50 +980,26 @@ mod tests {
972980 /// The `Menu::delete` defect, one domain over: a student's answer must not
973981 /// outlive the exam it belongs to. Guarding the save by *reading* the exam
974982 /// would not do it — the read sees a row [`crate::db::exam::delete`] has removed but
975- /// not committed, while its `DELETE exam_answer WHERE exam = $ex` swept a
976- /// snapshot predating the save, so both commit and the answer is left
977- /// pointing at an exam that is gone. [`crate::db::exam_answer::save`] writes the exam
978- /// row instead (its `result_count`, back unchanged), so the two transactions
979- /// touch one key and the store refuses one of them.
980- ///
981- /// The window is opened by the database, not by a lucky interleaving: a
982- /// `DEFINE EVENT` on `exam` fires *inside* the delete's own transaction the
983- /// instant the row goes, so the `SLEEP` lands exactly between the delete and
984- /// its cascade every time. Nothing in `src/` knows about it; the seam is the
985- /// schema.
983+ /// not committed, while its cascade swept a snapshot predating the save, so
984+ /// both commit and the answer is left pointing at an exam that is gone.
985+ /// [`crate::db::exam_answer::save`] writes the exam row instead (its
986+ /// `result_count`, back unchanged), so the two transactions touch one row
987+ /// and Postgres refuses one of them.
986988 ///
987989 /// One child per round, deliberately — in the menu twin, two children in one
988990 /// round hid the bug: the first writer made the delete lose and re-send, and
989991 /// the re-sent sweep removed the other's row.
990- ///
991- /// Real server, and `#[ignore]`d for it: the subject *is* the store's
992- /// conflict detection, which `init_mem`'s embedded engine does not have — it
993- /// commits both writes and answers `Ok` to each, so this passes there on
994- /// broken code. Mutation-tested: putting the bare
995- /// `db.upsert(id).content(answer)` back turns it red (the exact output is in
996- /// the commit that added it).
997992 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
998- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
999993 async fn an_answer_written_inside_a_delete_never_outlives_the_exam() {
1000994 use crate::db::exam_answer;
1001- let (db, _serialized) = crate::database::init_test_server("exam_answer_race").await;
1002- // Hold the delete open for a full second after the row is gone, while
1003- // its cascade still has to run.
1004- db.query(
1005- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1006- THEN { SLEEP 1s; };",
1007- )
1008- .await
1009- .unwrap()
1010- .check()
1011- .unwrap();
995+ let (db, _leases) = crate::database::init_test_db().await;
1012996
1013997 let (mut answers, mut swept) = (0, 0);
1014- for round in 0..4 {
998+ for round in 0..8 {
1015999 let exam = published(&db).await;
10161000 let question = question_on(&exam, &db).await;
10171001 let id = exam.get_id().clone();
1018- let student = UserId::from_key(&format!("stu{round}"));
1002+ let student = a_person(&db, "student", "student").await;
10191003 // The stored choice ids are minted by the create, not the ones the
10201004 // spec asked for — an answer must name one of *those*.
10211005 let pick = question.get_choices().unwrap()[1]
@@ -1023,21 +1007,26 @@ mod tests {
10231007 .as_str()
10241008 .to_string();
10251009
1010+ // Delete and save released together: both write the exam row, so
1011+ // Postgres serializes them and refuses whichever lost.
1012+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
10261013 let drop_it = {
1027- let db = db.clone();
1028- tokio::spawn(async move { delete(&db, exam).await })
1014+ let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone());
1015+ tokio::spawn(async move {
1016+ gate.wait().await;
1017+ delete(&db, exam).await
1018+ })
10291019 };
1030- // The save starts inside the held window — the exam row is gone but
1031- // uncommitted, which is exactly what an exam read believes.
1032- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
10331020 let child = {
1034- let (db, question, student) = (db.clone(), question.clone(), student.clone());
1021+ let (db, question, student, pick, gate) =
1022+ (db.clone(), question.clone(), student.clone(), pick, gate);
10351023 tokio::spawn(async move {
1024+ gate.wait().await;
10361025 exam_answer::save(&db, &question, &student, 1, Some(pick), None).await
10371026 })
10381027 };
10391028 let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1040- // A 404 for the save, or a NotFound for the delete, is a correct
1029+ // A 404 for the save, or a refusal for the delete, is a correct
10411030 // answer — the only defect is stored state.
10421031 assert!(
10431032 !matches!(child, Err(AppError::Db(_))),
@@ -1052,7 +1041,7 @@ mod tests {
10521041 panic!("round {round}: the delete reported success but the exam is still there");
10531042 }
10541043 }
1055- eprintln!("Exam::delete raced by an answer save: {swept}/4 rounds deleted the exam");
1044+ eprintln!("Exam::delete raced by an answer save: {swept}/8 rounds deleted the exam");
10561045 assert!(
10571046 swept > 0,
10581047 "no round ever deleted the exam, so the window was never reached"
@@ -1068,28 +1057,15 @@ mod tests {
10681057 /// again, hanging off an exam nobody could ever see. The freeze gate is a
10691058 /// *read* of `exam_attempt` and never survived this window;
10701059 /// [`crate::db::exam_attempt::write_unfrozen_with`] now writes the exam row too.
1071- ///
1072- /// Same seam, same `#[ignore]`, same reason as the answer twin above: the
1073- /// subject *is* the store's conflict detection, which the in-memory engine
1074- /// does not have.
10751060 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1076- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
10771061 async fn a_question_written_inside_a_delete_never_outlives_the_exam() {
10781062 use crate::domain::exam_question::{
10791063 ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
10801064 };
1081- let (db, _serialized) = crate::database::init_test_server("exam_question_race").await;
1082- db.query(
1083- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1084- THEN { SLEEP 1s; };",
1085- )
1086- .await
1087- .unwrap()
1088- .check()
1089- .unwrap();
1065+ let (db, _leases) = crate::database::init_test_db().await;
10901066
10911067 let (mut questions, mut swept, mut stuck) = (0, 0, 0);
1092- for round in 0..4 {
1068+ for round in 0..8 {
10931069 let exam = published(&db).await;
10941070 let id = exam.get_id().clone();
10951071 let subject = crate::db::subject::create(
@@ -1101,13 +1077,18 @@ mod tests {
11011077 .await
11021078 .unwrap();
11031079
1080+ // Delete and create released together: both write the exam row, so
1081+ // Postgres serializes them and refuses whichever lost.
1082+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
11041083 let drop_it = {
1105- let db = db.clone();
1106- tokio::spawn(async move { delete(&db, exam).await })
1084+ let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone());
1085+ tokio::spawn(async move {
1086+ gate.wait().await;
1087+ delete(&db, exam).await
1088+ })
11071089 };
1108- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
11091090 let child = {
1110- let (db, exam_id, on) = (db.clone(), id.clone(), subject.get_id().clone());
1091+ let (db, exam_id, on, gate) = (db.clone(), id.clone(), subject.get_id().clone(), gate);
11111092 tokio::spawn(async move {
11121093 let spec = QuestionSpec::try_new(
11131094 QuestionKind::try_new("choice").unwrap(),
@@ -1167,7 +1148,7 @@ mod tests {
11671148 panic!("round {round}: the delete reported success but the exam is still there");
11681149 }
11691150 }
1170- eprintln!("Exam::delete raced by a question write: {swept}/4 rounds deleted the exam");
1151+ eprintln!("Exam::delete raced by a question write: {swept}/8 rounds deleted the exam");
11711152 assert!(
11721153 swept > 0,
11731154 "no round ever deleted the exam, so the window was never reached"
@@ -1177,37 +1158,35 @@ mod tests {
11771158 }
11781159
11791160 /// The student's half of the same picture problem: a drawing is a bare
1180- /// `UPSERT` — the exact pre-fix shape of [`crate::db::exam_answer::save`] — so it kept
1181- /// the hole the text answer just lost, blob and all.
1161+ /// upsert — the exact pre-fix shape of [`crate::db::exam_answer::save`] — so it kept
1162+ /// the hole the text answer just lost, blob and all. It now rides the same
1163+ /// exam-row write the answer does.
11821164 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1183- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
11841165 async fn a_drawing_written_inside_a_delete_never_outlives_the_exam() {
11851166 use crate::domain::answer_image::AnswerImage;
11861167 use crate::domain::note_file::FileContentType;
1187- let (db, _serialized) = crate::database::init_test_server("answer_image_race").await;
1188- db.query(
1189- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1190- THEN { SLEEP 1s; };",
1191- )
1192- .await
1193- .unwrap()
1194- .check()
1195- .unwrap();
1168+ let (db, _leases) = crate::database::init_test_db().await;
11961169
11971170 let (mut drawings, mut swept) = (0, 0);
1198- for round in 0..4 {
1171+ for round in 0..8 {
11991172 let exam = published(&db).await;
12001173 let question = question_on(&exam, &db).await;
12011174 let id = exam.get_id().clone();
1202- let student = UserId::from_key(&format!("stu{round}"));
1175+ let student = a_person(&db, "student", "student").await;
12031176
1177+ // Delete and upsert released together: both write the exam row, so
1178+ // Postgres serializes them and refuses whichever lost.
1179+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
12041180 let drop_it = {
1205- let db = db.clone();
1206- tokio::spawn(async move { delete(&db, exam).await })
1181+ let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone());
1182+ tokio::spawn(async move {
1183+ gate.wait().await;
1184+ delete(&db, exam).await
1185+ })
12071186 };
1208- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
12091187 let child = {
1210- let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone());
1188+ let (db, exam_id, on, student, gate) =
1189+ (db.clone(), id.clone(), question.get_id().clone(), student.clone(), gate);
12111190 tokio::spawn(async move {
12121191 let image = AnswerImage::new(
12131192 &exam_id,
@@ -1236,7 +1215,7 @@ mod tests {
12361215 panic!("round {round}: the delete reported success but the exam is still there");
12371216 }
12381217 }
1239- eprintln!("Exam::delete raced by a drawing write: {swept}/4 rounds deleted the exam");
1218+ eprintln!("Exam::delete raced by a drawing write: {swept}/8 rounds deleted the exam");
12401219 assert!(
12411220 swept > 0,
12421221 "no round ever deleted the exam, so the window was never reached"
@@ -1247,36 +1226,33 @@ mod tests {
12471226 /// A picture is written through the same freeze gate as the question it
12481227 /// hangs on, so it had the same hole — and one the row count does not even
12491228 /// show: `delete_exam` collects the blob names to unlink *before* it calls
1250- /// [\`crate::db::exam::delete\`], so an image row landing after that snapshot strands
1251- /// its bytes on disk forever as well.
1229+ /// [`crate::db::exam::delete`], so an image row landing after that snapshot strands
1230+ /// its bytes on disk forever as well. It now rides the same exam-row write
1231+ /// the question does.
12521232 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1253- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
12541233 async fn a_picture_written_inside_a_delete_never_outlives_the_exam() {
12551234 use crate::domain::note_file::FileContentType;
12561235 use crate::domain::question_image::QuestionImage;
1257- let (db, _serialized) = crate::database::init_test_server("question_image_race").await;
1258- db.query(
1259- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1260- THEN { SLEEP 1s; };",
1261- )
1262- .await
1263- .unwrap()
1264- .check()
1265- .unwrap();
1236+ let (db, _leases) = crate::database::init_test_db().await;
12661237
12671238 let (mut images, mut swept) = (0, 0);
1268- for round in 0..4 {
1239+ for round in 0..8 {
12691240 let exam = published(&db).await;
12701241 let question = question_on(&exam, &db).await;
12711242 let id = exam.get_id().clone();
12721243
1244+ // Delete and upsert released together: both write the exam row, so
1245+ // Postgres serializes them and refuses whichever lost.
1246+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
12731247 let drop_it = {
1274- let db = db.clone();
1275- tokio::spawn(async move { delete(&db, exam).await })
1248+ let (db, exam, gate) = (db.clone(), exam.clone(), gate.clone());
1249+ tokio::spawn(async move {
1250+ gate.wait().await;
1251+ delete(&db, exam).await
1252+ })
12761253 };
1277- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
12781254 let child = {
1279- let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone());
1255+ let (db, exam_id, on, gate) = (db.clone(), id.clone(), question.get_id().clone(), gate);
12801256 tokio::spawn(async move {
12811257 let image = QuestionImage::new(
12821258 &exam_id,
@@ -1304,7 +1280,7 @@ mod tests {
13041280 panic!("round {round}: the delete reported success but the exam is still there");
13051281 }
13061282 }
1307- eprintln!("Exam::delete raced by a picture write: {swept}/4 rounds deleted the exam");
1283+ eprintln!("Exam::delete raced by a picture write: {swept}/8 rounds deleted the exam");
13081284 assert!(
13091285 swept > 0,
13101286 "no round ever deleted the exam, so the window was never reached"
src/db/exam_answer.rsmodified+20 -13
@@ -283,7 +283,7 @@ mod tests {
283283 }
284284
285285 fn student() -> UserId {
286- UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA")
286+ UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa")
287287 }
288288
289289 /// The bite test for the exam-row touch in [`save`]: it exists
@@ -298,7 +298,17 @@ mod tests {
298298 use crate::domain::exam::{
299299 ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,
300300 };
301- let db = crate::database::init_mem().await.unwrap();
301+ let (db, _leases) = crate::database::init_test_db().await;
302+ // The student is a foreign key now: a real row under the fixture's
303+ // fixed key.
304+ sqlx::query(
305+ "INSERT INTO app_user (id, username, password_hash) \
306+ VALUES ($1, 'aaaa-fixture', 'x')",
307+ )
308+ .bind(student().uuid())
309+ .execute(&db)
310+ .await
311+ .unwrap();
302312 let kinds = crate::domain::settings::Settings::defaults()
303313 .get_exam_kinds()
304314 .to_vec();
@@ -318,14 +328,12 @@ mod tests {
318328 .await
319329 .unwrap();
320330 let stored = async |db: &Database| -> Option<i64> {
321- let mut result = db
322- .query("SELECT VALUE result_count FROM ONLY $ex")
323- .bind(("ex", exam.get_id().record()))
331+ sqlx::query_scalar::<_, i64>("SELECT result_count FROM exam WHERE id = $1")
332+ .bind(exam.get_id().uuid())
333+ .fetch_optional(db)
324334 .await
325335 .unwrap()
326- .check()
327- .unwrap();
328- result.take::<Option<i64>>(0).unwrap()
336+ .flatten()
329337 };
330338 let question = choice_question(exam.get_id(), 10, 1);
331339 let pick = choice_id(&question, 1).as_str().to_string();
@@ -342,11 +350,10 @@ mod tests {
342350 );
343351
344352 // …and a counter that marks have moved is put back at its own value.
345- db.query("UPDATE $ex SET result_count = 7")
346- .bind(("ex", exam.get_id().record()))
353+ sqlx::query("UPDATE exam SET result_count = 7 WHERE id = $1")
354+ .bind(exam.get_id().uuid())
355+ .execute(&db)
347356 .await
348- .unwrap()
349- .check()
350357 .unwrap();
351358 save(&db, &question, &student(), 2, Some(pick), None)
352359 .await
@@ -354,7 +361,7 @@ mod tests {
354361 assert_eq!(stored(&db).await, Some(7), "the touch moved a real count");
355362
356363 // The gate that makes the touch worth having: no exam, no answer.
357- let orphan = choice_question(&ExamId::from_key("01NOSUCHEXAMAAAAAAAAAAAAAA"), 10, 0);
364+ let orphan = choice_question(&ExamId::from_key("019732e3-7b00-7000-8000-00000000e0a0"), 10, 0);
358365 let pick = choice_id(&orphan, 0).as_str().to_string();
359366 let refused = save(&db, &orphan, &student(), 1, Some(pick), None).await;
360367 assert!(
src/db/exam_attempt.rsmodified+10 -10
@@ -377,7 +377,7 @@ pub async fn create(
377377 #[cfg(test)]
378378 mod tests {
379379 use super::*;
380- use crate::database::init_mem;
380+ use crate::database::init_test_db;
381381 use crate::domain::exam::{
382382 Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,
383383 };
@@ -389,7 +389,7 @@ mod tests {
389389 /// An open exam with retakes allowed, plus one choice question — enough
390390 /// rows to exercise the attempt lifecycle without the HTTP layer.
391391 async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) {
392- let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
392+ let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
393393 let course = crate::db::course::a_test_course(db).await;
394394 let kinds = Settings::defaults().get_exam_kinds().to_vec();
395395 let exam = crate::db::exam::create(
@@ -468,7 +468,7 @@ mod tests {
468468
469469 #[tokio::test]
470470 async fn submitting_never_reverts_a_walk_out_that_raced_it() {
471- let db = init_mem().await.unwrap();
471+ let (db, _leases) = init_test_db().await;
472472 let (exam, _question) = open_exam_with_question(&db, 1).await;
473473 let user = student(&db).await;
474474
@@ -478,7 +478,7 @@ mod tests {
478478
479479 // The REST submit path reads the attempt, then checks the deadline and
480480 // the already-finished guard — several awaits before it writes.
481- let stale = read(&db, attempt.get_id())
481+ let stale = read(&db, &attempt.get_id())
482482 .await
483483 .unwrap()
484484 .expect("attempt exists");
@@ -488,7 +488,7 @@ mod tests {
488488 // clears it) — a field-scoped write to the same row.
489489 set_left(
490490 &db,
491- read(&db, attempt.get_id())
491+ read(&db, &attempt.get_id())
492492 .await
493493 .unwrap()
494494 .expect("attempt exists"),
@@ -503,7 +503,7 @@ mod tests {
503503 let finished = finish(&db, stale).await.unwrap();
504504 assert!(finished.get_finished_at().is_some());
505505
506- let after = read(&db, attempt.get_id())
506+ let after = read(&db, &attempt.get_id())
507507 .await
508508 .unwrap()
509509 .expect("attempt still exists");
@@ -516,7 +516,7 @@ mod tests {
516516
517517 #[tokio::test]
518518 async fn stamping_left_never_reverts_a_submission() {
519- let db = init_mem().await.unwrap();
519+ let (db, _leases) = init_test_db().await;
520520 let (exam, _question) = open_exam_with_question(&db, 1).await;
521521 let user = student(&db).await;
522522
@@ -528,14 +528,14 @@ mod tests {
528528
529529 // The exam-room teardown reads the attempt while it is still in
530530 // progress (`stamp_left`'s read) — a snapshot with `finished_at` unset.
531- let stale = read(&db, attempt.get_id())
531+ let stale = read(&db, &attempt.get_id())
532532 .await
533533 .unwrap()
534534 .expect("attempt exists");
535535 assert!(stale.get_finished_at().is_none());
536536 let finished = finish(
537537 &db,
538- read(&db, attempt.get_id())
538+ read(&db, &attempt.get_id())
539539 .await
540540 .unwrap()
541541 .expect("attempt exists"),
@@ -552,7 +552,7 @@ mod tests {
552552 // finishing).
553553 set_left(&db, stale, Some(Timestamp::now())).await.unwrap();
554554
555- let after = read(&db, attempt.get_id())
555+ let after = read(&db, &attempt.get_id())
556556 .await
557557 .unwrap()
558558 .expect("attempt still exists");
src/db/exam_question.rsmodified+37 -30
@@ -437,7 +437,7 @@ mod tests {
437437 /// outlives the row it accounts for makes its subject undeletable forever.
438438 mod counters {
439439 use super::*;
440- use crate::database::init_mem;
440+ use crate::database::init_test_db;
441441 use crate::domain::exam::{
442442 Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,
443443 };
@@ -446,10 +446,21 @@ mod tests {
446446 use crate::domain::user::UserId;
447447
448448 async fn an_exam(db: &Database) -> Exam {
449+ // The creator is a foreign key now: a real `app_user` row under
450+ // the fixture's fixed key.
451+ let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
452+ sqlx::query(
453+ "INSERT INTO app_user (id, username, password_hash) \
454+ VALUES ($1, 'acdc-fixture', 'x')",
455+ )
456+ .bind(creator.uuid())
457+ .execute(db)
458+ .await
459+ .unwrap();
449460 let kinds = Settings::defaults().get_exam_kinds().to_vec();
450461 crate::db::exam::create(
451462 db,
452- &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"),
463+ &creator,
453464 &crate::db::course::a_test_course(db).await,
454465 ExamTitle::try_new("practice").unwrap(),
455466 ExamDescription::try_new("").unwrap(),
@@ -503,26 +514,22 @@ mod tests {
503514
504515 /// The stored `exam_question_count` on one subject, absent = zero.
505516 async fn count_on(subject: &SubjectId, db: &Database) -> i64 {
506- let mut result = db
507- .query(format!(
508- "SELECT VALUE ({SUBJECT_QUESTION_COUNT_FIELD} ?? 0) FROM $sub"
509- ))
510- .bind(("sub", subject.record()))
511- .await
512- .unwrap()
513- .check()
514- .unwrap();
515- result
516- .take::<Vec<i64>>(0)
517- .unwrap()
518- .first()
519- .copied()
520- .unwrap_or(0)
517+ sqlx::query_scalar::<_, i64>(
518+ "SELECT exam_question_count FROM subject WHERE id = $1",
519+ )
520+ .bind(subject.uuid())
521+ .fetch_one(db)
522+ .await
523+ .unwrap()
521524 }
522525
523526 async fn rows(sql: &str, db: &Database) -> usize {
524- let mut result = db.query(sql).await.unwrap().check().unwrap();
525- result.take::<Vec<RecordId>>(0).unwrap().len()
527+ sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
528+ "SELECT count(*) FROM ({sql}) AS t"
529+ )))
530+ .fetch_one(db)
531+ .await
532+ .unwrap() as usize
526533 }
527534
528535 /// The freeze outranks the counter move, on both paths — and because
@@ -530,7 +537,7 @@ mod tests {
530537 /// the counters read as if nothing ran.
531538 #[tokio::test]
532539 async fn a_frozen_exam_leaves_the_subject_counters_untouched() {
533- let db = init_mem().await.unwrap();
540+ let (db, _leases) = init_test_db().await;
534541 let exam = an_exam(&db).await;
535542 let (from, to) = (a_subject(&db).await, a_subject(&db).await);
536543 let (from, to) = (from.get_id().clone(), to.get_id().clone());
@@ -575,7 +582,7 @@ mod tests {
575582 /// nor a count — least of all on a subject it would have to invent.
576583 #[tokio::test]
577584 async fn a_create_on_a_dead_subject_writes_neither_row_nor_count() {
578- let db = init_mem().await.unwrap();
585+ let (db, _leases) = init_test_db().await;
579586 let exam = an_exam(&db).await;
580587 let subject = a_subject(&db).await;
581588 let id = subject.get_id().clone();
@@ -587,12 +594,12 @@ mod tests {
587594 .expect_err("a subject that is gone must not be taggable");
588595 assert!(error.to_string().contains("subject does not exist"));
589596 assert_eq!(
590- rows("SELECT VALUE id FROM exam_question", &db).await,
597+ rows("SELECT id FROM exam_question", &db).await,
591598 0,
592599 "a refused create may write no row"
593600 );
594601 assert_eq!(
595- rows("SELECT VALUE id FROM subject", &db).await,
602+ rows("SELECT id FROM subject", &db).await,
596603 0,
597604 "…and least of all a count on a subject it just brought back"
598605 );
@@ -600,7 +607,7 @@ mod tests {
600607
601608 #[tokio::test]
602609 async fn a_subject_move_moves_the_count() {
603- let db = init_mem().await.unwrap();
610+ let (db, _leases) = init_test_db().await;
604611 let exam = an_exam(&db).await;
605612 let (from, to) = (a_subject(&db).await, a_subject(&db).await);
606613 let (from, to) = (from.get_id().clone(), to.get_id().clone());
@@ -614,7 +621,7 @@ mod tests {
614621
615622 #[tokio::test]
616623 async fn a_move_to_a_dead_subject_leaves_everything_untouched() {
617- let db = init_mem().await.unwrap();
624+ let (db, _leases) = init_test_db().await;
618625 let exam = an_exam(&db).await;
619626 let from = a_subject(&db).await.get_id().clone();
620627 let dead = a_subject(&db).await;
@@ -633,7 +640,7 @@ mod tests {
633640 1,
634641 "the release rolled back with the claim"
635642 );
636- assert_eq!(rows("SELECT VALUE id FROM subject", &db).await, 1);
643+ assert_eq!(rows("SELECT id FROM subject", &db).await, 1);
637644 }
638645
639646 /// The double-claim guard. Both movers compute their claim and release
@@ -649,7 +656,7 @@ mod tests {
649656 /// assertion — the stale mover is happily applied.
650657 #[tokio::test]
651658 async fn a_stale_mover_is_refused_and_claims_nothing() {
652- let db = init_mem().await.unwrap();
659+ let (db, _leases) = init_test_db().await;
653660 let exam = an_exam(&db).await;
654661 let from = a_subject(&db).await.get_id().clone();
655662 let to = a_subject(&db).await.get_id().clone();
@@ -685,7 +692,7 @@ mod tests {
685692 /// on the first assertion — the re-state lands 200.
686693 #[tokio::test]
687694 async fn a_stale_re_stater_is_refused_and_reverts_nothing() {
688- let db = init_mem().await.unwrap();
695+ let (db, _leases) = init_test_db().await;
689696 let exam = an_exam(&db).await;
690697 let from = a_subject(&db).await.get_id().clone();
691698 let to = a_subject(&db).await.get_id().clone();
@@ -715,7 +722,7 @@ mod tests {
715722 /// re-stating the subject the row really holds passes it trivially.
716723 #[tokio::test]
717724 async fn a_no_op_re_state_still_lands() {
718- let db = init_mem().await.unwrap();
725+ let (db, _leases) = init_test_db().await;
719726 let exam = an_exam(&db).await;
720727 let on = a_subject(&db).await.get_id().clone();
721728 let question = a_question(&exam, &on, &db).await;
@@ -740,7 +747,7 @@ mod tests {
740747 /// not the stale-mover 409 — the two empty-`$row` cases stay apart.
741748 #[tokio::test]
742749 async fn a_move_of_a_deleted_question_is_still_a_404() {
743- let db = init_mem().await.unwrap();
750+ let (db, _leases) = init_test_db().await;
744751 let exam = an_exam(&db).await;
745752 let from = a_subject(&db).await.get_id().clone();
746753 let to = a_subject(&db).await.get_id().clone();
src/db/fee_plan.rsmodified+1 -1
@@ -176,7 +176,7 @@ mod tests {
176176 /// shape and the stored one agree. A past due date is legal on purpose.
177177 #[tokio::test]
178178 async fn installments_survive_a_round_trip_through_the_schema() {
179- let db = crate::database::init_mem().await.unwrap();
179+ let (db, _leases) = crate::database::init_test_db().await;
180180 let manager = UserId::from_key("mgr1");
181181 let installments = vec![
182182 Installment::new(
src/db/homework.rsmodified+42 -32
@@ -442,11 +442,15 @@ async fn ensure_no_orphans(
442442
443443 /// Delete the homework and cascade its submissions, their files, and its
444444 /// results — one transaction, so a crash can't orphan a submission under a
445-/// vanished homework. The submission file *blobs* are the web layer's to
446-/// unlink: their names are returned (collected inside the transaction,
447-/// before the wipes — a file row inserted after an out-of-transaction
448-/// collection would be deleted here while its key was already gone from the
449-/// list, stranding the blob) and removed after the rows are gone.
445+/// vanished homework. The cascade runs children-first (every FK here is
446+/// `ON DELETE NO ACTION`): files, then submissions — whose `graded_by_result`
447+/// stamp points at a result row, so they must be gone before it — then the
448+/// results, then the homework. The submission file *blobs* are the web
449+/// layer's to unlink: their names are returned (collected inside the
450+/// transaction, before the wipes — a file row inserted after an
451+/// out-of-transaction collection would be deleted here while its key was
452+/// already gone from the list, stranding the blob) and removed after the
453+/// rows are gone.
450454 pub async fn delete(
451455 db: &Database,
452456 homework: Homework,
@@ -470,13 +474,13 @@ pub async fn delete(
470474 .execute(&mut *tx)
471475 .await?;
472476 sqlx::query!(
473- "DELETE FROM homework_result WHERE homework = $1",
477+ "DELETE FROM homework_submission WHERE homework = $1",
474478 homework.get_id().uuid()
475479 )
476480 .execute(&mut *tx)
477481 .await?;
478482 sqlx::query!(
479- "DELETE FROM homework_submission WHERE homework = $1",
483+ "DELETE FROM homework_result WHERE homework = $1",
480484 homework.get_id().uuid()
481485 )
482486 .execute(&mut *tx)
@@ -529,15 +533,27 @@ mod tests {
529533 }
530534
531535 async fn homework_on(subject: &SubjectId, db: &Database) -> Homework {
536+ // The course and the teacher are foreign keys now: a real course row
537+ // (the subject's own fixture path mints one) and a real teacher.
538+ let teacher = UserId::generate();
539+ sqlx::query(
540+ "INSERT INTO app_user (id, username, password_hash, role) \
541+ VALUES ($1, $2, 'x', 'teacher')",
542+ )
543+ .bind(teacher.uuid())
544+ .bind(format!("homework-fixture-{}", &teacher.key()[..8]))
545+ .execute(db)
546+ .await
547+ .unwrap();
532548 create(
533549 db,
534- &CourseId::from_key("course"),
550+ &crate::db::course::a_test_course(db).await,
535551 subject,
536552 HomeworkTitle::try_new("essay").unwrap(),
537553 None,
538554 Timestamp::from_millis(1),
539555 None,
540- &UserId::from_key("teacher"),
556+ &teacher,
541557 )
542558 .await
543559 .unwrap()
@@ -545,27 +561,21 @@ mod tests {
545561
546562 /// The stored `homework_count` on one subject, absent counting as zero.
547563 async fn count_on(subject: &SubjectId, db: &Database) -> i64 {
548- let mut result = db
549- .query(format!(
550- "SELECT VALUE ({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) FROM $sub"
551- ))
552- .bind(("sub", subject.record()))
564+ sqlx::query_scalar::<_, i64>("SELECT homework_count FROM subject WHERE id = $1")
565+ .bind(subject.uuid())
566+ .fetch_one(db)
553567 .await
554568 .unwrap()
555- .check()
556- .unwrap();
557- result
558- .take::<Vec<i64>>(0)
559- .unwrap()
560- .first()
561- .copied()
562- .unwrap_or(0)
563569 }
564570
565571 /// How many rows `sql` selects ids for.
566572 async fn rows(sql: &str, db: &Database) -> usize {
567- let mut result = db.query(sql).await.unwrap().check().unwrap();
568- result.take::<Vec<RecordId>>(0).unwrap().len()
573+ sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
574+ "SELECT count(*) FROM ({sql}) AS t"
575+ )))
576+ .fetch_one(db)
577+ .await
578+ .unwrap() as usize
569579 }
570580
571581 /// The invariant on the create path: the claim and the row it accounts for
@@ -574,7 +584,7 @@ mod tests {
574584 /// guard reads that count, so a stray one makes it undeletable forever).
575585 #[tokio::test]
576586 async fn a_refused_create_writes_neither_row_nor_count() {
577- let db = crate::database::init_mem().await.unwrap();
587+ let (db, _leases) = crate::database::init_test_db().await;
578588 let subject = a_subject("algebra", &db).await;
579589 let id = subject.get_id().clone();
580590 crate::db::subject::delete(&db, subject).await.unwrap();
@@ -593,12 +603,12 @@ mod tests {
593603 .expect_err("a subject that is gone must not be taggable");
594604 assert!(error.to_string().contains("subject does not exist"));
595605 assert_eq!(
596- rows("SELECT VALUE id FROM homework", &db).await,
606+ rows("SELECT id FROM homework", &db).await,
597607 0,
598608 "a refused create may write no row"
599609 );
600610 assert_eq!(
601- rows("SELECT VALUE id FROM subject", &db).await,
611+ rows("SELECT id FROM subject", &db).await,
602612 0,
603613 "…and least of all a count on a subject it just brought back"
604614 );
@@ -608,7 +618,7 @@ mod tests {
608618 /// claim and the old one's release with the link itself.
609619 #[tokio::test]
610620 async fn a_subject_move_moves_the_count() {
611- let db = crate::database::init_mem().await.unwrap();
621+ let (db, _leases) = crate::database::init_test_db().await;
612622 let from = a_subject("algebra", &db).await;
613623 let to = a_subject("geometry", &db).await;
614624 let homework = homework_on(from.get_id(), &db).await;
@@ -647,7 +657,7 @@ mod tests {
647657 /// keeps its tag and both counters read as if nothing ran.
648658 #[tokio::test]
649659 async fn a_move_to_a_dead_subject_leaves_everything_untouched() {
650- let db = crate::database::init_mem().await.unwrap();
660+ let (db, _leases) = crate::database::init_test_db().await;
651661 let from = a_subject("algebra", &db).await;
652662 let dead = a_subject("geometry", &db).await;
653663 let gone = dead.get_id().clone();
@@ -674,7 +684,7 @@ mod tests {
674684 "the release rolled back with the claim"
675685 );
676686 assert_eq!(
677- rows("SELECT VALUE id FROM subject", &db).await,
687+ rows("SELECT id FROM subject", &db).await,
678688 1,
679689 "the dead subject was not brought back by a count"
680690 );
@@ -690,7 +700,7 @@ mod tests {
690700 /// outright, and the counts must read as if it never ran.
691701 #[tokio::test]
692702 async fn a_stale_mover_is_refused_and_claims_nothing() {
693- let db = crate::database::init_mem().await.unwrap();
703+ let (db, _leases) = crate::database::init_test_db().await;
694704 let from = a_subject("algebra", &db).await;
695705 let to = a_subject("geometry", &db).await;
696706 let other = a_subject("calculus", &db).await;
@@ -744,7 +754,7 @@ mod tests {
744754 /// *carrying* the column instead, which is why this is refused.
745755 #[tokio::test]
746756 async fn a_stale_re_stater_is_refused_and_reverts_nothing() {
747- let db = crate::database::init_mem().await.unwrap();
757+ let (db, _leases) = crate::database::init_test_db().await;
748758 let from = a_subject("algebra", &db).await;
749759 let to = a_subject("geometry", &db).await;
750760 let homework = homework_on(from.get_id(), &db).await;
src/db/homework_file.rsmodified+38 -19
@@ -301,12 +301,36 @@ mod tests {
301301 None,
302302 crate::domain::timestamp::Timestamp::from_millis(1),
303303 None,
304- &UserId::from_key("teacher"),
304+ &a_teacher(db).await,
305305 )
306306 .await
307307 .unwrap()
308308 }
309309
310+ /// A real `app_user` row: submitters are foreign keys too.
311+ async fn a_student(db: &Database) -> UserId {
312+ let user = UserId::generate();
313+ sqlx::query("INSERT INTO app_user (id, username, password_hash, role) VALUES ($1, $2, 'x', 'student')")
314+ .bind(user.uuid())
315+ .bind(format!("s-{}", &user.key()[..8]))
316+ .execute(db)
317+ .await
318+ .unwrap();
319+ user
320+ }
321+
322+ /// A real `app_user` row: creators and submitters are foreign keys now.
323+ async fn a_teacher(db: &Database) -> UserId {
324+ let user = UserId::generate();
325+ sqlx::query("INSERT INTO app_user (id, username, password_hash, role) VALUES ($1, $2, 'x', 'teacher')")
326+ .bind(user.uuid())
327+ .bind(format!("t-{}", &user.key()[..8]))
328+ .execute(db)
329+ .await
330+ .unwrap();
331+ user
332+ }
333+
310334 fn a_file(submission: &HomeworkSubmissionId) -> HomeworkFile {
311335 HomeworkFile::new(
312336 submission,
@@ -319,32 +343,27 @@ mod tests {
319343 /// The counter as *stored* — the only witness that the seat and the row
320344 /// moved together, since every other read counts the rows themselves.
321345 async fn stored_count(submission: &HomeworkSubmissionId, db: &Database) -> i64 {
322- db.query("SELECT VALUE file_count FROM $sub")
323- .bind(("sub", submission.record()))
346+ sqlx::query("SELECT file_count FROM homework_submission WHERE id = $1")
347+ .bind(submission.uuid())
348+ .fetch_one(db)
324349 .await
325350 .unwrap()
326- .take::<Vec<i64>>(0)
351+ .try_get::<i64, _>(0)
327352 .unwrap()
328- .into_iter()
329- .next()
330- .unwrap_or(0)
331353 }
332354 #[tokio::test]
333355 async fn rows_scope_to_their_submission_gc_and_cap() {
334- let db = crate::database::init_mem().await.unwrap();
356+ let (db, _leases) = crate::database::init_test_db().await;
335357 let hw = a_homework(&db).await;
336358 let homework = hw.get_id().clone();
337- let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
359+ let user = a_student(&db).await;
338360 // A real submission row, so the GC join through it resolves.
339- let submission = crate::db::homework_submission::upsert(&db, &hw, &user, None)
361+ let (submission, _) = crate::db::homework_submission::upsert(&db, &hw, &user, None, false)
340362 .await
341363 .unwrap()
342364 .unwrap();
343365 let sub_a = submission.get_id().clone();
344- let sub_b = HomeworkSubmissionId::composite(
345- &homework,
346- &UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"),
347- );
366+ let sub_b = HomeworkSubmissionId::generate();
348367
349368 let stored = insert(&db, a_file(&sub_a)).await.unwrap().unwrap();
350369 // Readable under its own submission, invisible under another.
@@ -380,7 +399,7 @@ mod tests {
380399 read_in_homework(
381400 &db,
382401 stored.get_id(),
383- &HomeworkId::from_key("01TESTHWBBBBBBBBBBBBBBBBBB"),
402+ &HomeworkId::from_key("019732e3-7b00-7000-8000-00000000ebbe"),
384403 )
385404 .await
386405 .unwrap()
@@ -422,11 +441,11 @@ mod tests {
422441 use crate::db::homework_result;
423442 use crate::domain::homework_result::HomeworkStatus;
424443
425- let db = crate::database::init_mem().await.unwrap();
444+ let (db, _leases) = crate::database::init_test_db().await;
426445 let hw = a_homework(&db).await;
427446 let homework = hw.get_id().clone();
428- let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
429- let submission = crate::db::homework_submission::upsert(&db, &hw, &user, None)
447+ let user = a_student(&db).await;
448+ let (submission, _) = crate::db::homework_submission::upsert(&db, &hw, &user, None, false)
430449 .await
431450 .unwrap()
432451 .unwrap();
@@ -439,7 +458,7 @@ mod tests {
439458 &user,
440459 HomeworkStatus::try_new("done").unwrap(),
441460 None,
442- &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"),
461+ &UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"),
443462 )
444463 .await
445464 .unwrap();
src/db/homework_result.rsmodified+60 -42
@@ -241,6 +241,21 @@ pub async fn remove(
241241 if alive.is_none() {
242242 return Ok(None);
243243 }
244+ // The stamp clears *before* the delete: the submission's
245+ // `graded_by_result` FK points at the grade row (`NO ACTION`), so the
246+ // delete must not run while it stands. The subselect scopes the clear
247+ // to *this* pair's grade id — it can never wipe a stamp a concurrent
248+ // re-grade has just written (none can interleave: the homework row is
249+ // locked above).
250+ sqlx::query!(
251+ r#"UPDATE homework_submission SET graded_by_result = NULL
252+ WHERE homework = $1 AND app_user = $2 AND graded_by_result IN (
253+ SELECT id FROM homework_result WHERE homework = $1 AND app_user = $2)"#,
254+ homework.uuid(),
255+ user.uuid()
256+ )
257+ .execute(&mut *tx)
258+ .await?;
244259 let gone = sqlx::query!(
245260 r#"DELETE FROM homework_result WHERE homework = $1 AND app_user = $2
246261 RETURNING id AS "id: HomeworkResultId",
@@ -258,15 +273,6 @@ pub async fn remove(
258273 let Some(removed) = gone else {
259274 return Ok(None);
260275 };
261- sqlx::query!(
262- r#"UPDATE homework_submission SET graded_by_result = NULL
263- WHERE homework = $1 AND app_user = $2 AND graded_by_result = $3"#,
264- homework.uuid(),
265- user.uuid(),
266- removed.id.uuid()
267- )
268- .execute(&mut *tx)
269- .await?;
270276 sqlx::query!(
271277 "UPDATE app_user SET marks_given_total = GREATEST(marks_given_total - 1, 0) WHERE id = $1",
272278 removed.graded_by.uuid()
@@ -325,10 +331,10 @@ mod tests {
325331
326332 #[tokio::test]
327333 async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() {
328- let db = crate::database::init_mem().await.unwrap();
334+ let (db, _leases) = crate::database::init_test_db().await;
329335 let homework = a_homework(&db).await;
330- let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
331- let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
336+ let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa");
337+ let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
332338
333339 let first = grade(
334340 &db,
@@ -366,17 +372,27 @@ mod tests {
366372 /// touched at all — a homework grade is not a homework submission.
367373 #[tokio::test]
368374 async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() {
369- let db = crate::database::init_mem().await.unwrap();
375+ let (db, _leases) = crate::database::init_test_db().await;
370376 let homework = a_homework(&db).await;
371- let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
372- let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
377+ let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa");
378+ let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
373379 // `UPDATE` writes nothing to a user row that does not exist.
374- db.query("CREATE $usr SET username = 't', password_hash = 'x'")
375- .bind(("usr", teacher.record()))
376- .await
377- .unwrap()
378- .check()
379- .unwrap();
380+ sqlx::query(
381+ "INSERT INTO app_user (id, username, password_hash, role) \
382+ VALUES ($1, 't', 'x', 'teacher') ON CONFLICT (id) DO NOTHING",
383+ )
384+ .bind(teacher.uuid())
385+ .execute(&db)
386+ .await
387+ .unwrap();
388+ sqlx::query(
389+ "INSERT INTO app_user (id, username, password_hash, role) \
390+ VALUES ($1, 'ali', 'x', 'student') ON CONFLICT (id) DO NOTHING",
391+ )
392+ .bind(user.uuid())
393+ .execute(&db)
394+ .await
395+ .unwrap();
380396
381397 for status in ["incomplete", "done"] {
382398 grade(
@@ -403,16 +419,26 @@ mod tests {
403419 /// mark given, with no exam, no mark and no submission behind them.
404420 #[tokio::test]
405421 async fn ungrading_gives_the_grader_credit_back() {
406- let db = crate::database::init_mem().await.unwrap();
422+ let (db, _leases) = crate::database::init_test_db().await;
407423 let homework = a_homework(&db).await;
408- let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
409- let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
410- db.query("CREATE $usr SET username = 't', password_hash = 'x'")
411- .bind(("usr", teacher.record()))
412- .await
413- .unwrap()
414- .check()
415- .unwrap();
424+ let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa");
425+ let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
426+ sqlx::query(
427+ "INSERT INTO app_user (id, username, password_hash, role) \
428+ VALUES ($1, 't', 'x', 'teacher') ON CONFLICT (id) DO NOTHING",
429+ )
430+ .bind(teacher.uuid())
431+ .execute(&db)
432+ .await
433+ .unwrap();
434+ sqlx::query(
435+ "INSERT INTO app_user (id, username, password_hash, role) \
436+ VALUES ($1, 'ali', 'x', 'student') ON CONFLICT (id) DO NOTHING",
437+ )
438+ .bind(user.uuid())
439+ .execute(&db)
440+ .await
441+ .unwrap();
416442
417443 for _ in 0..3 {
418444 grade(
@@ -439,20 +465,12 @@ mod tests {
439465 }
440466 /// The grader's badge counter, re-read out of the store.
441467 async fn marks_given(user: &UserId, db: &Database) -> i64 {
442- let mut result = db
443- .query(format!(
444- "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $usr"
445- ))
446- .bind(("usr", user.record()))
468+ sqlx::query("SELECT marks_given_total FROM app_user WHERE id = $1")
469+ .bind(user.uuid())
470+ .fetch_one(db)
447471 .await
448472 .unwrap()
449- .check()
450- .unwrap();
451- result
452- .take::<Vec<i64>>(0)
473+ .try_get::<i64, _>(0)
453474 .unwrap()
454- .into_iter()
455- .next()
456- .unwrap_or(0)
457475 }
458476 }
src/db/homework_submission.rsmodified+95 -62
@@ -309,21 +309,30 @@ pub async fn delete(
309309 .fetch_optional(&mut *tx)
310310 .await?
311311 .map(|row| row.due_at);
312- let gone = sqlx::query!(
313- r#"DELETE FROM homework_submission
312+ // The gate runs as a lock-taking read, not a delete: the file rows
313+ // must die BEFORE the submission row (their `submission` FK is
314+ // `NO ACTION`), and that wipe is only honest if this delete has
315+ // already won — so the open-not-frozen verdict and the row lock come
316+ // first, files second, the submission row last. A rival withdrawal
317+ // that beat us removed the row under its own lock; a grade that
318+ // stamped it holds the homework lock first — either way `None`, one
319+ // refusal as before.
320+ let target = sqlx::query!(
321+ r#"SELECT id AS "id: HomeworkSubmissionId",
322+ homework AS "homework: HomeworkId",
323+ app_user AS "user: UserId",
324+ text AS "text: SubmissionText",
325+ submitted_at AS "submitted_at: Timestamp",
326+ updated_at AS "updated_at: Timestamp",
327+ counted_on_time AS "counted_on_time: bool"
328+ FROM homework_submission
314329 WHERE id = $1 AND graded_by_result IS NULL
315- RETURNING id AS "id: HomeworkSubmissionId",
316- homework AS "homework: HomeworkId",
317- app_user AS "user: UserId",
318- text AS "text: SubmissionText",
319- submitted_at AS "submitted_at: Timestamp",
320- updated_at AS "updated_at: Timestamp",
321- counted_on_time AS "counted_on_time: bool""#,
330+ FOR UPDATE"#,
322331 submission.get_id().uuid()
323332 )
324333 .fetch_optional(&mut *tx)
325334 .await?;
326- let Some(removed) = gone else {
335+ let Some(removed) = target else {
327336 // Frozen, or already withdrawn by a rival — one refusal, as
328337 // before.
329338 return Ok(None);
@@ -334,6 +343,12 @@ pub async fn delete(
334343 )
335344 .execute(&mut *tx)
336345 .await?;
346+ sqlx::query!(
347+ "DELETE FROM homework_submission WHERE id = $1",
348+ removed.id.uuid()
349+ )
350+ .execute(&mut *tx)
351+ .await?;
337352 let judged_on_time = due.map(|d| removed.submitted_at <= d).unwrap_or(false);
338353 let on_time = i64::from(removed.counted_on_time.unwrap_or(judged_on_time));
339354 sqlx::query!(
@@ -361,9 +376,8 @@ pub async fn delete(
361376 #[cfg(test)]
362377 mod tests {
363378 use super::*;
364- use crate::constant::{
365- HOMEWORK_ON_TIME_TOTAL_FIELD as ON_TIME, HOMEWORK_SUBMITTED_TOTAL_FIELD as SUBMITTED,
366- };
379+ use sqlx::Row as _;
380+
367381 use crate::db::homework as homework_db;
368382 use crate::domain::homework::HomeworkTitle;
369383 use crate::domain::subject::{SubjectDescription, SubjectName};
@@ -436,19 +450,13 @@ mod tests {
436450 /// The verdict `upsert` stored on the row — what `delete` debits off.
437451 /// `None` is a row from before the column existed.
438452 async fn stored_verdict(id: &HomeworkSubmissionId, db: &Database) -> Option<bool> {
439- let mut result = db
440- .query("SELECT VALUE counted_on_time FROM $sub")
441- .bind(("sub", id.record()))
453+ let row = sqlx::query("SELECT counted_on_time FROM homework_submission WHERE id = $1")
454+ .bind(id.uuid())
455+ .fetch_optional(db)
442456 .await
443457 .unwrap()
444- .check()
445- .unwrap();
446- result
447- .take::<Vec<Option<bool>>>(0)
448- .unwrap()
449- .into_iter()
450- .flatten()
451- .next()
458+ .expect("the submission row exists");
459+ row.try_get::<Option<bool>, _>(0).unwrap()
452460 }
453461
454462 /// The web layer's computed flag, exactly as `SubmissionResponse::new`
@@ -464,41 +472,42 @@ mod tests {
464472
465473 /// The two badge counters on a user row, absent counting as zero.
466474 async fn counters(user: &UserId, db: &Database) -> (i64, i64) {
467- let mut result = db
468- .query(format!(
469- "SELECT VALUE [({SUBMITTED} ?? 0), ({ON_TIME} ?? 0)] FROM $usr"
470- ))
471- .bind(("usr", user.record()))
472- .await
473- .unwrap()
474- .check()
475- .unwrap();
476- let rows = result.take::<Vec<Vec<i64>>>(0).unwrap();
477- let row = rows.first().cloned().unwrap_or_default();
475+ let row = sqlx::query(
476+ "SELECT homework_submitted_total, homework_on_time_total \
477+ FROM app_user WHERE id = $1",
478+ )
479+ .bind(user.uuid())
480+ .fetch_one(db)
481+ .await
482+ .unwrap();
478483 (
479- row.first().copied().unwrap_or(0),
480- row.get(1).copied().unwrap_or(0),
484+ row.try_get::<i64, _>(0).unwrap(),
485+ row.try_get::<i64, _>(1).unwrap(),
481486 )
482487 }
483488
484489 #[tokio::test]
485490 async fn resubmit_keeps_submitted_at_and_restamps_updated_at() {
486- let db = crate::database::init_mem().await.unwrap();
491+ let (db, _leases) = crate::database::init_test_db().await;
487492 let homework = a_homework(far_future(), &db).await;
488493 let user = a_student("ogrenci", &db).await;
489494
490- let first = upsert(
495+ let (first, _) = upsert(
491496 &db,
492497 &homework,
493498 &user,
494499 Some(SubmissionText::try_new("draft").unwrap()),
500+ false,
495501 )
496502 .await
497503 .unwrap()
498504 .unwrap();
499505 // A re-submit lands on the same row: submitted_at (the first hand-in)
500506 // pinned, updated_at moves forward, and the text can be cleared.
501- let second = upsert(&db, &homework, &user, None).await.unwrap().unwrap();
507+ let (second, _) = upsert(&db, &homework, &user, None, false)
508+ .await
509+ .unwrap()
510+ .unwrap();
502511 // ... and it is one submission, not two: the edit moves no counter.
503512 assert_eq!(counters(&user, &db).await, (1, 1));
504513 assert_eq!(first.get_id(), second.get_id());
@@ -529,16 +538,16 @@ mod tests {
529538 use crate::db::homework_result;
530539 use crate::domain::homework_result::HomeworkStatus;
531540
532- let db = crate::database::init_mem().await.unwrap();
541+ let (db, _leases) = crate::database::init_test_db().await;
533542 let homework = a_homework(far_future(), &db).await;
534543 let user = a_student("ogrenci", &db).await;
535- let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
544+ let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
536545 let graded = |value| {
537546 let text = SubmissionText::try_new(value).unwrap();
538- upsert(&db, &homework, &user, Some(text))
547+ upsert(&db, &homework, &user, Some(text), false)
539548 };
540549
541- let version_a = graded("version A").await.unwrap().unwrap();
550+ let (version_a, _) = graded("version A").await.unwrap().unwrap();
542551 assert!(!is_graded(&db, version_a.get_id()).await.unwrap());
543552
544553 assert_eq!(counters(&user, &db).await, (1, 1));
@@ -589,7 +598,7 @@ mod tests {
589598 .await
590599 .unwrap();
591600 assert!(!is_graded(&db, version_a.get_id()).await.unwrap());
592- let reopened = graded("version B").await.unwrap().unwrap();
601+ let (reopened, _) = graded("version B").await.unwrap().unwrap();
593602 assert_eq!(
594603 reopened.get_text().map(SubmissionText::as_str),
595604 Some("version B")
@@ -604,15 +613,16 @@ mod tests {
604613
605614 #[tokio::test]
606615 async fn touch_moves_updated_at_but_not_submitted_at_or_text() {
607- let db = crate::database::init_mem().await.unwrap();
616+ let (db, _leases) = crate::database::init_test_db().await;
608617 let homework = a_homework(far_future(), &db).await;
609618 let user = a_student("ogrenci", &db).await;
610619
611- let original = upsert(
620+ let (original, _) = upsert(
612621 &db,
613622 &homework,
614623 &user,
615624 Some(SubmissionText::try_new("photo answer").unwrap()),
625+ false,
616626 )
617627 .await
618628 .unwrap()
@@ -636,11 +646,14 @@ mod tests {
636646 /// and the last assertion reads `(2, 2)` — the farm.
637647 #[tokio::test]
638648 async fn submit_delete_submit_is_worth_one_submission() {
639- let db = crate::database::init_mem().await.unwrap();
649+ let (db, _leases) = crate::database::init_test_db().await;
640650 let homework = a_homework(far_future(), &db).await;
641651 let user = a_student("ogrenci", &db).await;
642652
643- upsert(&db, &homework, &user, None).await.unwrap().unwrap();
653+ upsert(&db, &homework, &user, None, false)
654+ .await
655+ .unwrap()
656+ .unwrap();
644657 assert_eq!(counters(&user, &db).await, (1, 1));
645658
646659 let mine = read_for(&db, homework.get_id(), &user)
@@ -658,7 +671,10 @@ mod tests {
658671 .is_none()
659672 );
660673
661- upsert(&db, &homework, &user, None).await.unwrap().unwrap();
674+ upsert(&db, &homework, &user, None, false)
675+ .await
676+ .unwrap()
677+ .unwrap();
662678 assert_eq!(counters(&user, &db).await, (1, 1));
663679 }
664680
@@ -668,13 +684,19 @@ mod tests {
668684 /// what it took.
669685 #[tokio::test]
670686 async fn a_late_submission_counts_as_submitted_but_not_on_time() {
671- let db = crate::database::init_mem().await.unwrap();
687+ let (db, _leases) = crate::database::init_test_db().await;
672688 let punctual = a_homework(far_future(), &db).await;
673689 let overdue = a_homework(Timestamp::from_millis(1), &db).await;
674690 let user = a_student("ogrenci", &db).await;
675691
676- upsert(&db, &punctual, &user, None).await.unwrap().unwrap();
677- upsert(&db, &overdue, &user, None).await.unwrap().unwrap();
692+ upsert(&db, &punctual, &user, None, false)
693+ .await
694+ .unwrap()
695+ .unwrap();
696+ upsert(&db, &overdue, &user, None, false)
697+ .await
698+ .unwrap()
699+ .unwrap();
678700 assert_eq!(counters(&user, &db).await, (2, 1));
679701
680702 // Withdrawing the *late* one takes back only the submission, never the
@@ -707,20 +729,25 @@ mod tests {
707729 /// to prevent.
708730 #[tokio::test]
709731 async fn a_row_with_no_stored_verdict_falls_back_to_the_deadline() {
710- let db = crate::database::init_mem().await.unwrap();
732+ let (db, _leases) = crate::database::init_test_db().await;
711733 let punctual = a_homework(far_future(), &db).await;
712734 let overdue = a_homework(Timestamp::from_millis(1), &db).await;
713735 let user = a_student("ogrenci", &db).await;
714736
715- upsert(&db, &punctual, &user, None).await.unwrap().unwrap();
716- upsert(&db, &overdue, &user, None).await.unwrap().unwrap();
737+ upsert(&db, &punctual, &user, None, false)
738+ .await
739+ .unwrap()
740+ .unwrap();
741+ upsert(&db, &overdue, &user, None, false)
742+ .await
743+ .unwrap()
744+ .unwrap();
717745 assert_eq!(counters(&user, &db).await, (2, 1));
718746 // Aged into legacy rows: the counters keep the credit, the rows lose the
719747 // verdict — the exact state of every submission on an existing volume.
720- db.query("UPDATE homework_submission UNSET counted_on_time")
748+ sqlx::query("UPDATE homework_submission SET counted_on_time = NULL")
749+ .execute(&db)
721750 .await
722- .unwrap()
723- .check()
724751 .unwrap();
725752
726753 let late = read_for(&db, overdue.get_id(), &user)
@@ -752,14 +779,17 @@ mod tests {
752779 /// stored `true` against a live `late = true`.
753780 #[tokio::test]
754781 async fn a_deadline_moved_under_the_caller_is_judged_by_the_stored_value() {
755- let db = crate::database::init_mem().await.unwrap();
782+ let (db, _leases) = crate::database::init_test_db().await;
756783 let user = a_student("ogrenci", &db).await;
757784
758785 // Extended at 23:59: the snapshot says the deadline has passed, the
759786 // store says it has not. A hand-in now is on time.
760787 let extended = a_homework(Timestamp::from_millis(1), &db).await;
761788 deadline_moves_to(&extended, far_future(), &db).await;
762- let landed = upsert(&db, &extended, &user, None).await.unwrap().unwrap();
789+ let (landed, _) = upsert(&db, &extended, &user, None, false)
790+ .await
791+ .unwrap()
792+ .unwrap();
763793 assert_eq!(counters(&user, &db).await, (1, 1));
764794 assert_eq!(stored_verdict(landed.get_id(), &db).await, Some(true));
765795 assert!(!late_flag(&landed, &db).await);
@@ -768,7 +798,10 @@ mod tests {
768798 // the deadline is gone. The same hand-in is late.
769799 let pulled = a_homework(far_future(), &db).await;
770800 deadline_moves_to(&pulled, Timestamp::from_millis(1), &db).await;
771- let missed = upsert(&db, &pulled, &user, None).await.unwrap().unwrap();
801+ let (missed, _) = upsert(&db, &pulled, &user, None, false)
802+ .await
803+ .unwrap()
804+ .unwrap();
772805 assert_eq!(counters(&user, &db).await, (2, 1));
773806 assert_eq!(stored_verdict(missed.get_id(), &db).await, Some(false));
774807 assert!(late_flag(&missed, &db).await);
src/db/meal_attendance.rsmodified+1 -1
@@ -113,7 +113,7 @@ pub async fn list_for_student(
113113 AND ($3::text IS NULL OR menu IN (SELECT id FROM menu WHERE date <= $3::text))",
114114 "ORDER BY marked_at DESC, menu DESC",
115115 )
116- .bind(student.key())
116+ .bind(student.uuid())
117117 .bind(Param::OptText(from.map(|date| date.as_str().to_string())))
118118 .bind(Param::OptText(to.map(|date| date.as_str().to_string())))
119119 .run(limit, offset, db)
src/db/meal_booking.rsmodified+34 -20
@@ -368,7 +368,7 @@ pub async fn release_seat(
368368 #[cfg(test)]
369369 mod tests {
370370 use super::*;
371- use crate::database::init_mem;
371+ use crate::database::init_test_db;
372372 use crate::db::cap;
373373 use crate::db::meal_ledger;
374374 use crate::db::menu;
@@ -387,14 +387,25 @@ mod tests {
387387 }
388388
389389 async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) {
390- let db = init_mem().await.unwrap();
390+ let (db, _leases) = init_test_db().await;
391+ // The menu's creator is a foreign key now: a real `app_user` row.
392+ let creator = UserId::generate();
393+ sqlx::query(
394+ "INSERT INTO app_user (id, username, password_hash, role) \
395+ VALUES ($1, $2, 'x', 'teacher')",
396+ )
397+ .bind(creator.uuid())
398+ .bind(format!("menu-fixture-{}", &creator.key()[..8]))
399+ .execute(&db)
400+ .await
401+ .unwrap();
391402 let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()];
392403 let menu = menu::create(
393404 &db,
394405 MenuDate::try_new(date).unwrap(),
395406 MenuSlot::try_new("lunch", &slots).unwrap(),
396407 capacity,
397- &UserId::generate(),
408+ &creator,
398409 )
399410 .await
400411 .unwrap();
@@ -404,23 +415,20 @@ mod tests {
404415 /// The stored counter, absent reading as zero — the number the cap's
405416 /// `WHERE` actually compares, not one recomputed from the rows.
406417 async fn seats(menu: &MenuId, db: &Database) -> i64 {
407- let mut result = db
408- .query("SELECT VALUE seats_booked FROM $id")
409- .bind(("id", menu.record()))
418+ use sqlx::Row as _;
419+
420+ sqlx::query("SELECT COALESCE(seats_booked, 0) FROM menu WHERE id = $1")
421+ .bind(menu.key())
422+ .fetch_one(db)
410423 .await
411424 .unwrap()
412- .check()
413- .unwrap();
414- result
415- .take::<Vec<Option<i64>>>(0)
425+ .try_get::<i64, _>(0)
416426 .unwrap()
417- .into_iter()
418- .next()
419- .flatten()
420- .unwrap_or(0)
421427 }
422428
423429 async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish {
430+ // A cap far above every seat count in these tests: the dish must never
431+ // be the binding constraint here.
424432 menu_dish::create(
425433 db,
426434 menu,
@@ -428,6 +436,7 @@ mod tests {
428436 None,
429437 DishPrice::try_new(price).unwrap(),
430438 DishTags::try_new(&[], &[]).unwrap(),
439+ 1_000,
431440 )
432441 .await
433442 .unwrap()
@@ -445,7 +454,6 @@ mod tests {
445454 // A dish lands: the price a booking read a moment ago is now stale.
446455 add_dish(&menu, 1_000, &db).await;
447456 let row = MealBooking {
448- id: MealBookingId::composite(&menu, &ali),
449457 menu: menu.clone(),
450458 student: ali.clone(),
451459 booked_by: ali,
@@ -456,7 +464,7 @@ mod tests {
456464 created_at: Timestamp::now(),
457465 };
458466 let place = async |seen| {
459- claim_and_place(&db, &menu.record(), cap::UNLIMITED, seen, &row, None, None)
467+ claim_and_place(&db, &menu, cap::UNLIMITED, seen, &row, None, None)
460468 .await
461469 .unwrap()
462470 };
@@ -466,7 +474,10 @@ mod tests {
466474 );
467475 assert_eq!(seats(&menu, &db).await, 0, "and must write nothing");
468476 assert!(
469- read(&db, row.get_id()).await.unwrap().is_none(),
477+ read(&db, &MealBookingId::composite(&menu, row.get_student()))
478+ .await
479+ .unwrap()
480+ .is_none(),
470481 "the refused transaction must not leave the row behind either"
471482 );
472483
@@ -555,7 +566,11 @@ mod tests {
555566 "the attempt this call read is gone, so it releases nothing"
556567 );
557568 // Stored state, not the returned value: the mem engine forges wins.
558- let stored = read(&db, live.get_id()).await.unwrap().unwrap();
569+ let stored =
570+ read(&db, &MealBookingId::composite(&menu, live.get_student()))
571+ .await
572+ .unwrap()
573+ .unwrap();
559574 assert_eq!(stored.get_status(), MealBookingStatus::Booked);
560575 assert_eq!(stored.get_attempt(), live.get_attempt());
561576 assert_eq!(seats(&menu, &db).await, 1, "and gives no seat back");
@@ -625,7 +640,6 @@ mod tests {
625640 let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap();
626641 let seen = menu::read(&db, &menu).await.unwrap().unwrap().get_version();
627642 let row = MealBooking {
628- id: MealBookingId::composite(&menu, &ali),
629643 menu: menu.clone(),
630644 student: ali.clone(),
631645 booked_by: ali.clone(),
@@ -640,7 +654,7 @@ mod tests {
640654 let place = async || {
641655 claim_and_place(
642656 &db,
643- &menu.record(),
657+ &menu,
644658 cap::UNLIMITED,
645659 seen,
646660 &row,
src/db/meal_ledger.rsmodified+0 -43
@@ -140,46 +140,3 @@ pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError
140140 .iter()
141141 .fold(0i64, |sum, row| sum + row.kind.sign() * row.total))
142142 }
143-#[cfg(test)]
144-mod tests {
145- use super::*;
146-
147- /// The balance aggregate **against a real server**, and `#[ignore]`d for
148- /// it: `init_mem`'s embedded engine is not the store this runs on, and an
149- /// aggregate is exactly where the two are known to differ — a `count()`
150- /// over an indexed field comes back `{count: N}` from the server and a
151- /// bare int from memory, and `student` here *is* indexed. This asserts the
152- /// `GROUP BY` really decodes into [`KindTotal`] and folds to the
153- /// documented figure, per kind, scoped to one student.
154- #[tokio::test]
155- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
156- async fn the_balance_aggregate_decodes_on_a_real_server() {
157- let (db, _serialized) = crate::database::init_test_server("meal_balance_sum").await;
158- db.query(
159- "CREATE meal_ledger:a SET student = user:ali, kind = 'credit', \
160- amount_minor = 10000, recorded_by = user:adm, created_at = 1;
161- CREATE meal_ledger:b SET student = user:ali, kind = 'charge', \
162- amount_minor = 4500, recorded_by = user:adm, created_at = 2;
163- CREATE meal_ledger:c SET student = user:ali, kind = 'charge', \
164- amount_minor = 1500, recorded_by = user:adm, created_at = 3;
165- CREATE meal_ledger:d SET student = user:ali, kind = 'reversal', \
166- amount_minor = 4500, recorded_by = user:adm, created_at = 4;
167- CREATE meal_ledger:e SET student = user:veli, kind = 'credit', \
168- amount_minor = 777, recorded_by = user:adm, created_at = 5;",
169- )
170- .await
171- .unwrap()
172- .check()
173- .unwrap();
174- let ali = UserId::from_key("ali");
175- assert_eq!(
176- balance_of(&db, &ali).await.unwrap(),
177- 10_000 - 4_500 - 1_500 + 4_500
178- );
179- // Somebody with no lines at all: no groups come back, not an error.
180- assert_eq!(
181- balance_of(&db, &UserId::from_key("nobody")).await.unwrap(),
182- 0
183- );
184- }
185-}
src/db/menu.rsmodified+95 -80
@@ -187,11 +187,16 @@ pub async fn update(
187187 /// no meaning without its menu, and the menu key cannot be re-homed.
188188 ///
189189 /// Refused (409) while a seat is still held, and the *row itself* decides
190-/// that: the delete carries the seat counter in its `WHERE`, so a booking
191-/// landing at that instant either takes its seat before the delete (which
192-/// then finds a non-zero counter and refuses) or after it (and finds no
193-/// menu). A read-then-delete pair had a window where both happened — a
194-/// paid seat on a menu that no longer exists.
190+/// that: the guard that unlocks the sweep reads the seat counter in its own
191+/// `WHERE` under `FOR UPDATE`, so a booking landing at that instant either
192+/// takes its seat before the delete (which then finds a non-zero counter
193+/// and refuses) or after it (and finds no menu). A read-then-delete pair
194+/// had a window where both happened — a paid seat on a menu that no longer
195+/// exists. The lock is also what makes the sweep's order safe: the dishes
196+/// and marks go first (both FKs are `ON DELETE NO ACTION`, so the parent
197+/// row cannot leave while they stand) and the menu row goes last, with no
198+/// window in between in which the children of a surviving menu could be
199+/// destroyed.
195200 ///
196201 /// The slot gets its reference back in that same transaction — a slot no
197202 /// menu is published for any more may leave the settings again. Released
@@ -218,15 +223,39 @@ pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> {
218223 let key = menu.id.key().to_string();
219224 let counter = slot_ref(menu.slot.as_str());
220225 let deleted = tx_with_retry(db, true, async move |tx| {
221- let deleted = sqlx::query_as!(
226+ // The row itself decides the guard, under its own lock: a booking
227+ // racing this delete either committed first (the guard reads its
228+ // seat and refuses before any child is touched) or queues on the
229+ // lock and lands after the commit — and finds no menu.
230+ let guard = sqlx::query!(
231+ "SELECT 1 AS deletable FROM menu WHERE id = $1 AND seats_booked = 0 FOR UPDATE",
232+ key,
233+ )
234+ .fetch_optional(&mut *tx)
235+ .await?;
236+ if guard.is_none() {
237+ return Ok(None);
238+ }
239+ // The children go first: both `menu_dish.menu` and
240+ // `meal_attendance.menu` are `ON DELETE NO ACTION`, so the parent
241+ // row cannot leave while they stand.
242+ sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key)
243+ .execute(&mut *tx)
244+ .await?;
245+ sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key)
246+ .execute(&mut *tx)
247+ .await?;
248+ let row = sqlx::query_as!(
222249 Menu,
223- "DELETE FROM menu WHERE id = $1 AND seats_booked = 0
250+ "DELETE FROM menu WHERE id = $1
224251 RETURNING id AS \"id: MenuId\", date AS \"date: MenuDate\", slot AS \"slot: MenuSlot\", capacity, version, created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"",
225252 key,
226253 )
227254 .fetch_optional(&mut *tx)
228255 .await?;
229- let Some(row) = deleted else {
256+ // Unreachable while the guard holds the row's lock, but the match
257+ // keeps the shape honest: `row` exists iff the guard passed.
258+ let Some(row) = row else {
230259 return Ok(None);
231260 };
232261 sqlx::query!(
@@ -235,12 +264,6 @@ pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> {
235264 )
236265 .execute(&mut *tx)
237266 .await?;
238- sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key)
239- .execute(&mut *tx)
240- .await?;
241- sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key)
242- .execute(&mut *tx)
243- .await?;
244267 Ok(Some(row))
245268 })
246269 .await?;
@@ -256,20 +279,26 @@ pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> {
256279 #[cfg(test)]
257280 mod tests {
258281 use super::*;
259- use crate::database::init_mem;
282+ use crate::database::init_test_db;
260283 use crate::db::meal_attendance;
261284 use crate::db::menu_dish;
262285 use crate::domain::meal_attendance::MealAttendanceStatus;
263286 use crate::domain::menu_dish::{DishName, DishPrice, DishTags};
264287 use crate::domain::settings::MealSlotDef;
265288
289+ /// The one fixture person, by a fixed valid id every publish can name.
290+ const TEACHER: &str = "019732e3-7b00-7000-8000-00000000acdc";
291+
266292 async fn school() -> Database {
267- let db = init_mem().await.unwrap();
268- db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';")
269- .await
270- .unwrap()
271- .check()
272- .unwrap();
293+ let (db, _leases) = init_test_db().await;
294+ sqlx::query(
295+ "INSERT INTO app_user (id, username, password_hash, role) \
296+ VALUES ($1, 'teacher', 'x', 'teacher')",
297+ )
298+ .bind(UserId::from_key(TEACHER).uuid())
299+ .execute(&db)
300+ .await
301+ .unwrap();
273302 db
274303 }
275304
@@ -280,28 +309,36 @@ mod tests {
280309 /// The reference count, re-read out of the store — never off a return
281310 /// value, which the in-memory engine forges wins on.
282311 async fn refs(db: &Database) -> i64 {
283- let mut result = db
284- .query("SELECT VALUE (count ?? 0) FROM $id")
285- .bind(("id", slot_ref("lunch")))
312+ sqlx::query("SELECT count FROM slot_ref WHERE name = 'lunch'")
313+ .fetch_optional(db)
286314 .await
287315 .unwrap()
288- .check()
289- .unwrap();
290- result
291- .take::<Vec<i64>>(0)
292- .unwrap()
293- .into_iter()
294- .next()
316+ .map(|row| row.try_get::<i64, _>(0).unwrap())
295317 .unwrap_or(0)
296318 }
297319
320+ /// The settings guard's retire switch, driven straight: `true` only when
321+ /// this call flipped the bit.
322+ async fn retire_lunch(db: &Database) -> bool {
323+ sqlx::query(
324+ "INSERT INTO slot_ref (name, count, retired) VALUES ('lunch', 0, TRUE)
325+ ON CONFLICT (name) DO UPDATE SET retired = TRUE
326+ WHERE slot_ref.count = 0 AND slot_ref.retired IS DISTINCT FROM TRUE
327+ RETURNING 1",
328+ )
329+ .fetch_optional(db)
330+ .await
331+ .unwrap()
332+ .is_some()
333+ }
334+
298335 async fn publish(date: &str, db: &Database) -> Result<Menu, AppError> {
299336 create(
300337 db,
301338 MenuDate::try_new(date).unwrap(),
302339 lunch(),
303340 None,
304- &UserId::from_key("teacher"),
341+ &UserId::from_key(TEACHER),
305342 )
306343 .await
307344 }
@@ -309,15 +346,15 @@ mod tests {
309346 /// Plant a menu row the pre-check will (or will not) find, without going
310347 /// through the claim — a row published before the counter existed.
311348 async fn plant(id: &MenuId, date: &str, db: &Database) {
312- db.query(
313- "CREATE $id SET date = $date, slot = 'lunch', \
314- created_by = user:teacher, created_at = 1",
349+ sqlx::query(
350+ "INSERT INTO menu (id, date, slot, created_by, created_at) \
351+ VALUES ($1, $2, 'lunch', $3, 1)",
315352 )
316- .bind(("id", id.record()))
317- .bind(("date", date.to_string()))
353+ .bind(id.key())
354+ .bind(date)
355+ .bind(UserId::from_key(TEACHER).uuid())
356+ .execute(db)
318357 .await
319- .unwrap()
320- .check()
321358 .unwrap();
322359 }
323360
@@ -340,7 +377,7 @@ mod tests {
340377 #[tokio::test]
341378 async fn a_retired_slot_refuses_and_writes_nothing() {
342379 let db = school().await;
343- assert!(cap::retire(&slot_ref("lunch"), &db).await.unwrap());
380+ assert!(retire_lunch(&db).await);
344381
345382 let refused = publish("2026-08-02", &db)
346383 .await
@@ -438,7 +475,7 @@ mod tests {
438475 assert!(matches!(gone, AppError::NotFound), "got {gone:?}");
439476 assert_eq!(refs(&db).await, 1);
440477 assert!(
441- !cap::retire(&slot_ref("lunch"), &db).await.unwrap(),
478+ !retire_lunch(&db).await,
442479 "a slot a menu is still published for may not be retired"
443480 );
444481
@@ -465,41 +502,16 @@ mod tests {
465502 /// menu row too ([`bump_menu_and_write`]) instead of reading it: the two
466503 /// transactions then touch one key and the store refuses to commit both.
467504 ///
468- /// The window is opened by the database itself rather than by a lucky
469- /// interleaving — a `DEFINE EVENT` on `menu` fires *inside* the delete's own
470- /// transaction, the instant the row goes, so the `SLEEP` lands exactly
471- /// between the delete and its sweep every single time. Nothing in `src/`
472- /// knows about it; the seam is the schema.
473- ///
474- /// Real server, and `#[ignore]`d for it: the subject *is* the store's
475- /// conflict detection, which `init_mem`'s embedded engine does not have —
476- /// it commits both writes and answers `Ok` to each, which would fail this
477- /// test on correct code (see [`crate::database::init_test_server`]).
478- /// Mutation-tested: putting [`meal_attendance::mark`] back on a menu *read*
479- /// (`UPSERT (SELECT VALUE $id FROM $menu) …`, the shape it shipped with)
480- /// turns this red at **both** of its two rounds — the mark commits, the
481- /// sweep misses it, and the row is left pointing at a menu that is gone.
505+ /// The window the schema event used to force open is the menu row's own
506+ /// lock now: every child write also writes the menu row, so a child racing
507+ /// the delete serializes on that row instead of committing into a range
508+ /// the sweep has already passed. A barrier start lets both orders happen;
509+ /// the invariant must hold in each.
482510 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
483- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
484511 async fn a_child_written_inside_a_delete_never_outlives_the_menu() {
485512 use crate::domain::menu_dish::DishDescription;
486513
487- let (db, _serialized) = crate::database::init_test_server("menu_delete_race").await;
488- db.query("CREATE user:teacher SET username = 'teacher', password_hash = 'x';")
489- .await
490- .unwrap()
491- .check()
492- .unwrap();
493- // Hold the delete open for a full second after the row is gone, while
494- // its cascade still has to run.
495- db.query(
496- "DEFINE EVENT hold_the_window ON TABLE menu WHEN $event = 'DELETE' \
497- THEN { SLEEP 1s; };",
498- )
499- .await
500- .unwrap()
501- .check()
502- .unwrap();
514+ let db = school().await;
503515
504516 let (mut dishes, mut marks, mut swept) = (0, 0, 0);
505517 for round in 0..4 {
@@ -508,19 +520,21 @@ mod tests {
508520 .unwrap();
509521 let id = menu.get_id().clone();
510522
523+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
511524 let drop_it = {
512- let db = db.clone();
513- tokio::spawn(async move { delete(&db, menu).await })
525+ let (db, gate, menu) = (db.clone(), gate.clone(), menu);
526+ tokio::spawn(async move {
527+ gate.wait().await;
528+ delete(&db, menu).await
529+ })
514530 };
515- // The child starts inside the held window — the delete's row is
516- // gone but uncommitted, which is exactly what a menu read believes.
517- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
518531 // One child per round, never both: whichever wrote first forces the
519532 // delete to re-send, and its second pass sweeps the other's row —
520533 // which would mask exactly the defect this test exists to catch.
521534 let child = {
522- let (id, db, dish) = (id.clone(), db.clone(), round % 2 == 0);
535+ let (id, db, dish, gate) = (id.clone(), db.clone(), round % 2 == 0, gate);
523536 tokio::spawn(async move {
537+ gate.wait().await;
524538 if dish {
525539 menu_dish::create(
526540 &db,
@@ -529,6 +543,7 @@ mod tests {
529543 None::<DishDescription>,
530544 DishPrice::try_new(1).unwrap(),
531545 DishTags::try_new(&[], &[]).unwrap(),
546+ 1_000,
532547 )
533548 .await
534549 .map(|_| ())
@@ -536,9 +551,9 @@ mod tests {
536551 meal_attendance::mark(
537552 &db,
538553 &id,
539- &UserId::from_key("teacher"),
554+ &UserId::from_key(TEACHER),
540555 MealAttendanceStatus::try_new("served").unwrap(),
541- &UserId::from_key("teacher"),
556+ &UserId::from_key(TEACHER),
542557 )
543558 .await
544559 .map(|_| ())
src/db/message.rsmodified+1 -1
@@ -266,7 +266,7 @@ mod tests {
266266 /// Asserts the *stored* order, not the mint order.
267267 #[tokio::test]
268268 async fn inbox_is_newest_first_within_a_millisecond() {
269- let db = crate::database::init_mem().await.unwrap();
269+ let (db, _leases) = crate::database::init_test_db().await;
270270 let sender = UserId::from_key("a");
271271 let recipient = UserId::from_key("b");
272272 let mut sent = Vec::new();
src/db/note.rsmodified+1 -1
@@ -144,7 +144,7 @@ mod tests {
144144 /// been taken, which is the row whose blob used to leak.
145145 #[tokio::test]
146146 async fn delete_returns_the_attachment_rows_it_removed() {
147- let db = crate::database::init_mem().await.unwrap();
147+ let (db, _leases) = crate::database::init_test_db().await;
148148 let owner = UserId::generate();
149149 let note = create(
150150 &db,
src/db/note_file.rsmodified+2 -2
@@ -136,7 +136,7 @@ mod tests {
136136 /// left.
137137 #[tokio::test]
138138 async fn insert_refuses_at_the_cap_without_leaking_a_slot() {
139- let db = crate::database::init_mem().await.unwrap();
139+ let (db, _leases) = crate::database::init_test_db().await;
140140 let note = a_note(&db).await;
141141 for index in 0..MAX_NOTE_FILES {
142142 let file = NoteFile::new(
@@ -166,7 +166,7 @@ mod tests {
166166 /// accepted again, and the count never dips below zero.
167167 #[tokio::test]
168168 async fn delete_returns_the_slot_to_the_note() {
169- let db = crate::database::init_mem().await.unwrap();
169+ let (db, _leases) = crate::database::init_test_db().await;
170170 let note = a_note(&db).await;
171171 let file = NoteFile::new(
172172 note.get_id(),
src/db/payment_ledger.rsmodified+0 -46
@@ -303,49 +303,3 @@ pub(crate) async fn applied_to(
303303 Ok(total * -target_kind.sign())
304304 }
305305
306-#[cfg(test)]
307-mod tests {
308- use super::*;
309- use crate::domain::user::UserId;
310-
311- /// The mem engine is not the store this runs against, and an aggregate is
312- /// exactly where the two have diverged before: `count()` over an *indexed*
313- /// field compared to a plan-time value comes back `{count: N}` rather than
314- /// a plain int, and `student` is indexed on this table
315- /// (`payment_ledger_student`). So the `GROUP BY` is proved on a real
316- /// server: that it decodes into [`KindTotal`], that it folds to the
317- /// documented figure per kind, that it is scoped to one student, and that
318- /// someone with no lines at all comes back `0` rather than an error.
319- #[tokio::test]
320- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
321- async fn the_balance_aggregate_decodes_on_a_real_server() {
322- let (db, _serialized) = crate::database::init_test_server("payment_balance_sum").await;
323- db.query(
324- "CREATE payment_ledger:a SET student = user:ali, kind = 'charge', \
325- amount_minor = 10000, recorded_by = user:adm, created_at = 1;
326- CREATE payment_ledger:b SET student = user:ali, kind = 'credit', \
327- amount_minor = 6000, recorded_by = user:adm, created_at = 2;
328- CREATE payment_ledger:c SET student = user:ali, kind = 'refund', \
329- amount_minor = 1000, recorded_by = user:adm, created_at = 3;
330- CREATE payment_ledger:d SET student = user:ali, kind = 'reversal', \
331- amount_minor = 4500, recorded_by = user:adm, created_at = 4;
332- CREATE payment_ledger:e SET student = user:veli, kind = 'credit', \
333- amount_minor = 777, recorded_by = user:adm, created_at = 5;",
334- )
335- .await
336- .unwrap()
337- .check()
338- .unwrap();
339- let ali = UserId::from_key("ali");
340- assert_eq!(
341- balance_of(&db, &ali).await.unwrap(),
342- 6_000 + 4_500 - 10_000 - 1_000,
343- "credits + reversals - charges - refunds, and veli's line is not ali's"
344- );
345- // Somebody with no lines at all: no groups come back, not an error.
346- assert_eq!(
347- balance_of(&db, &UserId::from_key("nobody")).await.unwrap(),
348- 0
349- );
350- }
351-}
src/db/pomodoro.rsmodified+124 -133
@@ -3,10 +3,8 @@
33 //! the study streak are all decided inside [`finish`]'s one transaction —
44 //! the whole rule is the batch itself.
55
6-use crate::constant::{
7- CAP_WRITE_TRIES, MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS,
8-};
9-use crate::database::{Database, backoff, tx_with_retry, unique_violation};
6+use crate::constant::{MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS};
7+use crate::database::{Database, tx_with_retry};
108 use crate::domain::pomodoro::{PomodoroSession, PomodoroSessionId};
119 use crate::domain::timestamp::Timestamp;
1210 use crate::domain::user::UserId;
@@ -16,14 +14,19 @@ use sqlx::query_as;
1614 /// Start a session for `user`, stamped with the server clock. The open slot
1715 /// is the partial unique index (`pomodoro_session_open_stint`): one row per
1816 /// user with `finished_at IS NULL`. A dangling unfinished session (the
19-/// browser died mid-timer) is deleted and replaced in the same statement —
20-/// it never counted, and blocking the next start behind it would only
21-/// punish the student for a crash.
17+/// browser died mid-timer) is replaced by the same statement — the arbiter
18+/// turns the insert into an in-place re-stamp (`DO UPDATE`), so the old row
19+/// becomes the new stint; it never counted, and blocking the next start
20+/// behind it would only punish the student for a crash.
2221 ///
23-/// Two racing starts cannot both insert: the index refuses the second
24-/// (`23505`), which is retried — the re-run deletes the winner's open row
25-/// and replaces it, the same last-write-wins the old deterministic-key
26-/// upsert had.
22+/// The replace has to ride the arbiter. A `WITH gone AS (DELETE …) INSERT …`
23+/// CTE cannot do it: both halves run on one snapshot, so the insert's
24+/// uniqueness check still sees the row the CTE just deleted and refuses
25+/// (23505) *deterministically* — a retry re-sends the identical statement and
26+/// dies identically, which is the 500 the port briefly shipped. `DO UPDATE`
27+/// is atomic: two racing starts cannot both win the slot, and the loser
28+/// re-stamps the winner's row — the same last-write-wins the old
29+/// deterministic-key upsert had.
2730 ///
2831 /// `label` is the student's own name for the stint, validated and trimmed
2932 /// upstream and stored verbatim. A `None` binds NULL — an unnamed start
@@ -35,42 +38,24 @@ pub async fn start(
3538 ) -> Result<PomodoroSession, AppError> {
3639 let started_at = Timestamp::now();
3740 let id = PomodoroSessionId::generate();
38- // The statement is one atomic delete-and-replace; the only contention
39- // is a rival start, and the index's verdict sends the loser around
40- // again to overwrite.
41- for attempt in 0..CAP_WRITE_TRIES {
42- backoff(attempt).await;
43- let started = match query_as!(
44- PomodoroSession,
45- "WITH gone AS (
46- DELETE FROM pomodoro_session
47- WHERE app_user = $1 AND finished_at IS NULL
48- RETURNING 1)
49- INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label)
50- SELECT $2, $1, $3, NULL, NULL, $4
51- RETURNING id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \
52- started_at AS \"started_at: Timestamp\", \
53- finished_at AS \"finished_at: Timestamp\", counted, label",
54- user.uuid(),
55- id.uuid(),
56- started_at.as_millis(),
57- label
58- )
59- .fetch_one(db)
60- .await
61- {
62- Ok(row) => row,
63- // The winner of a race holds the open slot; one more round.
64- Err(err) if unique_violation(&err) == Some("pomodoro_session_open_stint") => {
65- continue;
66- }
67- Err(err) => return Err(err.into()),
68- };
69- return Ok(started);
70- }
71- Err(AppError::Internal(
72- "failed to start pomodoro session".into(),
73- ))
41+ let started = query_as!(
42+ PomodoroSession,
43+ "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label)
44+ VALUES ($2, $1, $3, NULL, NULL, $4)
45+ ON CONFLICT (app_user) WHERE finished_at IS NULL DO UPDATE
46+ SET started_at = EXCLUDED.started_at, finished_at = NULL, counted = NULL,
47+ label = EXCLUDED.label
48+ RETURNING id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \
49+ started_at AS \"started_at: Timestamp\", \
50+ finished_at AS \"finished_at: Timestamp\", counted, label",
51+ user.uuid(),
52+ id.uuid(),
53+ started_at.as_millis(),
54+ label
55+ )
56+ .fetch_one(db)
57+ .await?;
58+ Ok(started)
7459 }
7560
7661 /// Close `user`'s running session, deciding the counting verdict, the
@@ -252,22 +237,19 @@ pub async fn list_for_user(db: &Database, user: &UserId) -> Result<Vec<PomodoroS
252237 }
253238 #[cfg(test)]
254239 mod tests {
255- use ulid::Ulid;
256-
257240 use super::*;
258- use crate::database;
241+ use sqlx::Row as _;
259242
260- /// A real `user` row: the counters land with `UPDATE`, which only ever
261- /// touches a record that exists, so a fabricated id would silently store
243+ /// A real `app_user` row: the counters land with `UPDATE`, which only ever
244+ /// touches a row that exists, so a fabricated id would silently store
262245 /// nothing. The tests above need no row — they read only the stint log.
263246 async fn a_user(db: &Database) -> UserId {
264- let user = UserId::from_key(&Ulid::generate().to_string());
265- db.query("CREATE $usr SET username = $name, password_hash = 'x'")
266- .bind(("usr", user.record()))
267- .bind(("name", user.key().to_string()))
247+ let user = UserId::generate();
248+ sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')")
249+ .bind(user.uuid())
250+ .bind(format!("u{}", &user.key()[..8]))
251+ .execute(db)
268252 .await
269- .unwrap()
270- .check()
271253 .unwrap();
272254 user
273255 }
@@ -275,37 +257,37 @@ mod tests {
275257 /// `(finished_total, focus_ms_total)` re-read from the store — never off
276258 /// what `finish` returned, which proves nothing about what was written.
277259 async fn counters(user: &UserId, db: &Database) -> (i64, i64) {
278- let mut result = db
279- .query(format!(
280- "SELECT VALUE [({POMODORO_FINISHED_TOTAL_FIELD} ?? 0),
281- ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0)] FROM $usr"
282- ))
283- .bind(("usr", user.record()))
284- .await
285- .unwrap()
286- .check()
287- .unwrap();
288- let rows: Vec<Vec<i64>> = result.take(0).unwrap();
289- let row = rows.into_iter().next().expect("the user row");
290- (row[0], row[1])
260+ let row = sqlx::query(
261+ "SELECT pomodoro_finished_total, pomodoro_focus_ms_total \
262+ FROM app_user WHERE id = $1",
263+ )
264+ .bind(user.uuid())
265+ .fetch_one(db)
266+ .await
267+ .unwrap();
268+ (
269+ row.try_get::<i64, _>(0).unwrap(),
270+ row.try_get::<i64, _>(1).unwrap(),
271+ )
291272 }
292273
293- /// `(current, longest, last_day)` re-read from the store.
274+ /// `(current, longest, last_day)` re-read from the store; the unset day
275+ /// reads as the sentinel `-1` the streak arithmetic runs on.
294276 async fn streak(user: &UserId, db: &Database) -> (i64, i64, i64) {
295- let mut result = db
296- .query(format!(
297- "SELECT VALUE [({STUDY_STREAK_CURRENT_FIELD} ?? 0),
298- ({STUDY_STREAK_LONGEST_FIELD} ?? 0),
299- ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1)] FROM $usr"
300- ))
301- .bind(("usr", user.record()))
302- .await
303- .unwrap()
304- .check()
305- .unwrap();
306- let rows: Vec<Vec<i64>> = result.take(0).unwrap();
307- let row = rows.into_iter().next().expect("the user row");
308- (row[0], row[1], row[2])
277+ let row = sqlx::query(
278+ "SELECT study_streak_current, study_streak_longest, \
279+ COALESCE(study_streak_last_day, -1) \
280+ FROM app_user WHERE id = $1",
281+ )
282+ .bind(user.uuid())
283+ .fetch_one(db)
284+ .await
285+ .unwrap();
286+ (
287+ row.try_get::<i64, _>(0).unwrap(),
288+ row.try_get::<i64, _>(1).unwrap(),
289+ row.try_get::<i64, _>(2).unwrap(),
290+ )
309291 }
310292
311293 /// Age *both* day buckets by `days`, so the next finish lands that many
@@ -322,16 +304,16 @@ mod tests {
322304 /// code to serve a test. Re-run before believing a failure that only ever
323305 /// happens near midnight UTC.
324306 async fn age_by_days(user: &UserId, db: &Database, days: i64) {
325- db.query(format!(
326- "UPDATE $usr SET
327- {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - $days,
328- {POMODORO_COUNTED_DAY_FIELD} = ({POMODORO_COUNTED_DAY_FIELD} ?? -1) - $days"
329- ))
330- .bind(("usr", user.record()))
331- .bind(("days", days))
307+ sqlx::query(
308+ "UPDATE app_user SET
309+ study_streak_last_day = COALESCE(study_streak_last_day, -1) - $1,
310+ pomodoro_counted_day = COALESCE(pomodoro_counted_day, -1) - $1
311+ WHERE id = $2",
312+ )
313+ .bind(days)
314+ .bind(user.uuid())
315+ .execute(db)
332316 .await
333- .unwrap()
334- .check()
335317 .unwrap();
336318 }
337319
@@ -340,16 +322,22 @@ mod tests {
340322 ///
341323 /// One `UPSERT`, not `start` followed by a backdate: the concurrent test
342324 /// races four of these onto the same open row, and a separate backdate can
343- /// be wiped by a rival's fresh `start`, handing whoever wins the `DELETE` a
344- /// zero-length stint and reddening the run for no defect. Same statement
345- /// `start` runs, one clock read earlier.
325+ /// be wiped by a rival's fresh `start`, handing whoever wins the arbiter
326+ /// a zero-length stint and reddening the run for no defect. The same
327+ /// arbiter-riding statement `start` runs, one clock read earlier — the
328+ /// `DO UPDATE` arm drops the loser onto the winner's row in place.
346329 async fn start_aged(user: &UserId, db: &Database, ms: i64) -> Result<(), AppError> {
347- db.query("UPSERT $open CONTENT { user: $usr, started_at: $at }")
348- .bind(("open", PomodoroSessionId::open_for(user).record()))
349- .bind(("usr", user.record()))
350- .bind(("at", Timestamp::now().as_millis() - ms))
351- .await?
352- .check()?;
330+ sqlx::query(
331+ "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label)
332+ VALUES ($2, $1, $3, NULL, NULL, NULL)
333+ ON CONFLICT (app_user) WHERE finished_at IS NULL DO UPDATE
334+ SET started_at = EXCLUDED.started_at, finished_at = NULL, counted = NULL",
335+ )
336+ .bind(user.uuid())
337+ .bind(PomodoroSessionId::generate().uuid())
338+ .bind(Timestamp::now().as_millis() - ms)
339+ .execute(db)
340+ .await?;
353341 Ok(())
354342 }
355343
@@ -362,7 +350,7 @@ mod tests {
362350
363351 #[tokio::test]
364352 async fn consecutive_days_extend_the_streak_and_a_repeat_day_does_not() {
365- let db = database::init_mem().await.unwrap();
353+ let (db, _leases) = crate::database::init_test_db().await;
366354 let user = a_user(&db).await;
367355 // The stale-data case: a row that predates all three columns reads as
368356 // no streak at all, and its first finish opens a run of one.
@@ -386,7 +374,7 @@ mod tests {
386374
387375 #[tokio::test]
388376 async fn a_gap_resets_the_run_but_never_the_high_water_mark() {
389- let db = database::init_mem().await.unwrap();
377+ let (db, _leases) = crate::database::init_test_db().await;
390378 let user = a_user(&db).await;
391379
392380 one_stint(&user, &db).await;
@@ -442,9 +430,8 @@ mod tests {
442430 /// (a racer scheduled entirely after another's finish frees the slot) and
443431 /// the assertions allow it — the day count is per round, not per stint.
444432 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
445- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
446433 async fn concurrent_finishes_commit_the_streak_with_the_stint_or_not_at_all() {
447- let (db, _serialized) = crate::database::init_test_server("pomodoro_streak_race").await;
434+ let (db, _leases) = crate::crate::database::init_test_db().await;
448435 let user = a_user(&db).await;
449436 let (mut finished, mut conflicts, mut errors) = (0, 0, 0);
450437 let mut last_error = String::new();
@@ -511,7 +498,7 @@ mod tests {
511498
512499 #[tokio::test]
513500 async fn finishing_bumps_the_stored_counters_and_an_open_stint_bumps_neither() {
514- let db = database::init_mem().await.unwrap();
501+ let (db, _leases) = crate::database::init_test_db().await;
515502 let user = a_user(&db).await;
516503 assert_eq!(counters(&user, &db).await, (0, 0));
517504
@@ -537,17 +524,19 @@ mod tests {
537524
538525 #[tokio::test]
539526 async fn a_backwards_clock_adds_zero_ms_to_the_counter_never_a_negative() {
540- let db = database::init_mem().await.unwrap();
527+ let (db, _leases) = crate::database::init_test_db().await;
541528 let user = a_user(&db).await;
542529
543530 start(&db, &user, None).await.unwrap();
544- db.query("UPDATE $open SET started_at = $future")
545- .bind(("open", PomodoroSessionId::open_for(&user).record()))
546- .bind(("future", Timestamp::now().as_millis() + 3_600_000))
547- .await
548- .unwrap()
549- .check()
550- .unwrap();
531+ sqlx::query(
532+ "UPDATE pomodoro_session SET started_at = $1
533+ WHERE app_user = $2 AND finished_at IS NULL",
534+ )
535+ .bind(Timestamp::now().as_millis() + 3_600_000)
536+ .bind(user.uuid())
537+ .execute(&db)
538+ .await
539+ .unwrap();
551540
552541 // The clamp holds: zero milliseconds, never a negative — and a stint
553542 // measuring zero is below the minimum, so it moves neither counter.
@@ -569,7 +558,7 @@ mod tests {
569558 /// pair and a study session, not the last millisecond.
570559 #[tokio::test]
571560 async fn a_stint_under_the_minimum_is_logged_and_listed_but_counts_for_nothing() {
572- let db = database::init_mem().await.unwrap();
561+ let (db, _leases) = crate::database::init_test_db().await;
573562 let user = a_user(&db).await;
574563
575564 start_aged(&user, &db, MIN_COUNTED_POMODORO_MS - 60_000)
@@ -609,7 +598,7 @@ mod tests {
609598 /// rolls at midnight UTC.
610599 #[tokio::test]
611600 async fn the_day_quota_caps_the_counter_and_rolls_at_midnight_utc() {
612- let db = database::init_mem().await.unwrap();
601+ let (db, _leases) = crate::database::init_test_db().await;
613602 let user = a_user(&db).await;
614603
615604 for _ in 0..MAX_COUNTED_POMODORO_PER_DAY {
@@ -647,7 +636,7 @@ mod tests {
647636 /// and a badge is never taken back.
648637 #[tokio::test]
649638 async fn the_start_finish_farm_moves_no_counter_and_mints_no_badge() {
650- let db = database::init_mem().await.unwrap();
639+ let (db, _leases) = crate::database::init_test_db().await;
651640 let user = a_user(&db).await;
652641
653642 for _ in 0..200 {
@@ -675,10 +664,10 @@ mod tests {
675664
676665 #[tokio::test]
677666 async fn restart_replaces_the_open_session_and_finish_closes_it() {
678- let db = database::init_mem().await.unwrap();
679- // A `record<user>` column checks the table of the id, not row
680- // existence — a fabricated id keeps this test free of user ceremony.
681- let user = UserId::from_key(&Ulid::generate().to_string());
667+ let (db, _leases) = crate::database::init_test_db().await;
668+ // The stint's owner is a real parent row now (the FK checks it), so
669+ // the user ceremony stays — it is one helper call.
670+ let user = a_user(&db).await;
682671
683672 // Nothing running yet — finishing conflicts.
684673 assert!(matches!(
@@ -711,19 +700,21 @@ mod tests {
711700
712701 #[tokio::test]
713702 async fn a_backwards_clock_records_a_zero_stint_not_a_negative_one() {
714- let db = database::init_mem().await.unwrap();
715- let user = UserId::from_key(&Ulid::generate().to_string());
703+ let (db, _leases) = crate::database::init_test_db().await;
704+ let user = a_user(&db).await;
716705
717706 start(&db, &user, None).await.unwrap();
718707 // Stand in for the NTP step: push the running stint's start an hour
719708 // ahead, so the server clock `finish` reads is *behind* it.
720- db.query("UPDATE $open SET started_at = $future")
721- .bind(("open", PomodoroSessionId::open_for(&user).record()))
722- .bind(("future", Timestamp::now().as_millis() + 3_600_000))
723- .await
724- .unwrap()
725- .check()
726- .unwrap();
709+ sqlx::query(
710+ "UPDATE pomodoro_session SET started_at = $1
711+ WHERE app_user = $2 AND finished_at IS NULL",
712+ )
713+ .bind(Timestamp::now().as_millis() + 3_600_000)
714+ .bind(user.uuid())
715+ .execute(&db)
716+ .await
717+ .unwrap();
727718
728719 let closed = finish(&db, &user).await.unwrap();
729720 let started = closed.get_started_at().as_millis();
src/db/pool_question.rsmodified+39 -49
@@ -324,48 +324,38 @@ pub async fn delete(
324324
325325 #[cfg(test)]
326326 mod tests {
327- use ulid::Ulid;
328-
329327 use super::*;
330328 use crate::database;
331329 use crate::domain::solution::SolutionBody;
330+ use sqlx::Row as _;
332331
333- /// The two counter columns plus a row to carry them: the `user` table is
334- /// SCHEMAFULL in production, and the counters are `option<int>` there.
332+ /// A real `app_user` row: the asker and the approver are foreign keys on
333+ /// the question, and the counters are plain `NOT NULL DEFAULT 0` columns.
335334 async fn a_user(db: &Database) -> UserId {
336- let user = UserId::from_key(&Ulid::generate().to_string());
337- db.query(format!(
338- "DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option<int>;
339- DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option<int>;
340- CREATE $usr SET username = $name, password_hash = 'x';"
341- ))
342- .bind(("usr", user.record()))
343- .bind(("name", user.key().to_string()))
344- .await
345- .unwrap()
346- .check()
347- .unwrap();
335+ let user = UserId::generate();
336+ sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')")
337+ .bind(user.uuid())
338+ .bind(format!("u{}", &user.key()[..8]))
339+ .execute(db)
340+ .await
341+ .unwrap();
348342 user
349343 }
350344
351- /// `(pool_approved_total, pool_published_total)` as stored — absent reads
352- /// zero, the way `BadgeStats::load` reads it.
345+ /// `(pool_approved_total, pool_published_total)` as stored — the columns
346+ /// read zero on a fresh row, the way `BadgeStats::load` reads them.
353347 async fn counters(user: &UserId, db: &Database) -> (i64, i64) {
354- let mut result = db
355- .query(format!(
356- "SELECT VALUE [({POOL_APPROVED_TOTAL_FIELD} ?? 0),
357- ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0)] FROM $usr"
358- ))
359- .bind(("usr", user.record()))
360- .await
361- .unwrap()
362- .check()
363- .unwrap();
364- let rows = result.take::<Vec<Vec<i64>>>(0).unwrap();
365- let row = rows.into_iter().next().unwrap_or_default();
348+ let row = sqlx::query(
349+ "SELECT pool_approved_total, pool_published_total \
350+ FROM app_user WHERE id = $1",
351+ )
352+ .bind(user.uuid())
353+ .fetch_one(db)
354+ .await
355+ .unwrap();
366356 (
367- row.first().copied().unwrap_or(0),
368- row.get(1).copied().unwrap_or(0),
357+ row.try_get::<i64, _>(0).unwrap(),
358+ row.try_get::<i64, _>(1).unwrap(),
369359 )
370360 }
371361
@@ -380,9 +370,9 @@ mod tests {
380370
381371 #[tokio::test]
382372 async fn approval_is_a_one_way_race_safe_transition() {
383- let db = database::init_mem().await.unwrap();
384- let asker = UserId::from_key(&Ulid::generate().to_string());
385- let teacher = UserId::from_key(&Ulid::generate().to_string());
373+ let (db, _leases) = database::init_test_db().await;
374+ let asker = a_user(&db).await;
375+ let teacher = a_user(&db).await;
386376
387377 let q = insert(&db, question(&asker)).await.unwrap();
388378 assert_eq!(q.get_status(), STATUS_PENDING);
@@ -407,7 +397,7 @@ mod tests {
407397 /// published side, and neither on a second approve of the same question.
408398 #[tokio::test]
409399 async fn approval_moves_both_counters_once_and_only_once() {
410- let db = database::init_mem().await.unwrap();
400+ let (db, _leases) = database::init_test_db().await;
411401 let asker = a_user(&db).await;
412402 let teacher = a_user(&db).await;
413403
@@ -440,7 +430,7 @@ mod tests {
440430 /// neither counter moves when one person is both ends of the transition.
441431 #[tokio::test]
442432 async fn self_approval_still_approves_but_moves_neither_counter() {
443- let db = database::init_mem().await.unwrap();
433+ let (db, _leases) = database::init_test_db().await;
444434 let teacher = a_user(&db).await;
445435
446436 let q = insert(&db, question(&teacher)).await.unwrap();
@@ -464,10 +454,10 @@ mod tests {
464454
465455 #[tokio::test]
466456 async fn visibility_hides_others_pending_questions() {
467- let db = database::init_mem().await.unwrap();
468- let asker = UserId::from_key(&Ulid::generate().to_string());
469- let other = UserId::from_key(&Ulid::generate().to_string());
470- let teacher = UserId::from_key(&Ulid::generate().to_string());
457+ let (db, _leases) = database::init_test_db().await;
458+ let asker = a_user(&db).await;
459+ let other = a_user(&db).await;
460+ let teacher = a_user(&db).await;
471461
472462 let pending = insert(&db, question(&asker)).await.unwrap();
473463 let published = insert(&db, question(&other)).await.unwrap();
@@ -488,9 +478,9 @@ mod tests {
488478
489479 #[tokio::test]
490480 async fn image_attaches_only_while_pending_and_reports_the_replaced_blob() {
491- let db = database::init_mem().await.unwrap();
492- let asker = UserId::from_key(&Ulid::generate().to_string());
493- let teacher = UserId::from_key(&Ulid::generate().to_string());
481+ let (db, _leases) = database::init_test_db().await;
482+ let asker = a_user(&db).await;
483+ let teacher = a_user(&db).await;
494484 let png = FileContentType::try_new("image/png").unwrap();
495485
496486 let q = insert(&db, question(&asker)).await.unwrap();
@@ -535,9 +525,9 @@ mod tests {
535525
536526 #[tokio::test]
537527 async fn delete_cascades_solutions_and_returns_the_row() {
538- let db = database::init_mem().await.unwrap();
539- let asker = UserId::from_key(&Ulid::generate().to_string());
540- let helper = UserId::from_key(&Ulid::generate().to_string());
528+ let (db, _leases) = database::init_test_db().await;
529+ let asker = a_user(&db).await;
530+ let helper = a_user(&db).await;
541531
542532 let q = insert(&db, question(&asker)).await.unwrap();
543533 let offered = crate::db::solution::insert(
@@ -609,8 +599,8 @@ mod tests {
609599
610600 let (mut solutions, mut swept, mut delete_500) = (0, 0, 0);
611601 for round in 0..4 {
612- let asker = UserId::from_key(&Ulid::generate().to_string());
613- let helper = UserId::from_key(&Ulid::generate().to_string());
602+ let asker = a_user(&db).await;
603+ let helper = a_user(&db).await;
614604 let q = insert(&db, question(&asker)).await.unwrap();
615605 let id = q.get_id().clone();
616606
src/db/profile.rsmodified+3 -3
@@ -126,7 +126,7 @@ mod tests {
126126 VALUES ($1, $2, 1000, 3000), ($3, $2, 5000, 6000)",
127127 )
128128 .bind(uuid::Uuid::now_v7())
129- .bind(user.uuid())
129+ .bind(user.get_id().uuid())
130130 .bind(uuid::Uuid::now_v7())
131131 .execute(&db)
132132 .await
@@ -136,7 +136,7 @@ mod tests {
136136 "INSERT INTO pomodoro_session (id, app_user, started_at) VALUES ($1, $2, 9000)",
137137 )
138138 .bind(uuid::Uuid::now_v7())
139- .bind(user.uuid())
139+ .bind(user.get_id().uuid())
140140 .execute(&db)
141141 .await
142142 .unwrap();
@@ -158,7 +158,7 @@ mod tests {
158158 VALUES ($1, $2, 5000, 1000)",
159159 )
160160 .bind(uuid::Uuid::now_v7())
161- .bind(user.uuid())
161+ .bind(user.get_id().uuid())
162162 .execute(&db)
163163 .await
164164 .unwrap();
src/db/question_image.rsmodified+4 -4
@@ -248,7 +248,7 @@ mod tests {
248248
249249 #[tokio::test]
250250 async fn upsert_replaces_per_slot() {
251- let db = crate::database::init_mem().await.unwrap();
251+ let (db, _leases) = crate::database::init_test_db().await;
252252 let exam = exam_row(&db).await;
253253 let question = ExamQuestionId::generate();
254254 let ids = choice_ids();
@@ -293,7 +293,7 @@ mod tests {
293293 /// options keeps exactly their pictures, and drops only the removed one's.
294294 #[tokio::test]
295295 async fn only_the_dropped_options_lose_their_pictures() {
296- let db = crate::database::init_mem().await.unwrap();
296+ let (db, _leases) = crate::database::init_test_db().await;
297297 let exam = exam_row(&db).await;
298298 let question = ExamQuestionId::generate();
299299 let ids = choice_ids();
@@ -335,7 +335,7 @@ mod tests {
335335
336336 #[tokio::test]
337337 async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() {
338- let db = crate::database::init_mem().await.unwrap();
338+ let (db, _leases) = crate::database::init_test_db().await;
339339 let exam = exam_row(&db).await;
340340 let question = ExamQuestionId::generate();
341341 let ids = choice_ids();
@@ -362,7 +362,7 @@ mod tests {
362362
363363 #[tokio::test]
364364 async fn exam_listing_scopes_by_exam() {
365- let db = crate::database::init_mem().await.unwrap();
365+ let (db, _leases) = crate::database::init_test_db().await;
366366 let exam_a = exam_row(&db).await;
367367 let exam_b = exam_row(&db).await;
368368 upsert(
src/db/rag_output.rsmodified+3 -3
@@ -207,7 +207,7 @@ mod tests {
207207 /// the note cascade takes every row of the note with it.
208208 #[tokio::test]
209209 async fn create_reads_back_and_cascades_from_the_note() {
210- let db = crate::database::init_mem().await.unwrap();
210+ let (db, _leases) = crate::database::init_test_db().await;
211211 let note = note_of(&db, "n").await;
212212 let file = a_file(&db, &note).await;
213213 let row = create(
@@ -231,7 +231,7 @@ mod tests {
231231 /// drops a row built from a file that is gone.
232232 #[tokio::test]
233233 async fn replace_is_newest_wins_and_source_cascade_drops() {
234- let db = crate::database::init_mem().await.unwrap();
234+ let (db, _leases) = crate::database::init_test_db().await;
235235 let note = note_of(&db, "n").await;
236236 let file = a_file(&db, &note).await;
237237 let first = create(
@@ -265,7 +265,7 @@ mod tests {
265265 /// Deleting one row returns it; deleting it again is a 404.
266266 #[tokio::test]
267267 async fn delete_returns_the_row_then_refuses() {
268- let db = crate::database::init_mem().await.unwrap();
268+ let (db, _leases) = crate::database::init_test_db().await;
269269 let note = note_of(&db, "n").await;
270270 let row = create(&db, note.get_id(), note.get_course(), Vec::new(), json!({}))
271271 .await
src/db/session.rsmodified+19 -6
@@ -87,14 +87,27 @@ mod tests {
8787
8888 #[tokio::test]
8989 async fn purge_expired_removes_only_past_sessions() {
90- let db = crate::database::init_mem().await.unwrap();
91- db.query(
92- "CREATE session SET user = type::record('user', 'u'), token = 'past', expires_at = 1;
93- CREATE session SET user = type::record('user', 'u'), token = 'future', expires_at = 99999999999999;",
90+ let (db, _leases) = crate::database::init_test_db().await;
91+ // The session's owner is a foreign key now: a real `app_user` row
92+ // under the fixture's fixed key, then two rows either side of `now`.
93+ let user = UserId::from_key("019732e3-7b00-7000-8000-00000000cab0");
94+ sqlx::query(
95+ "INSERT INTO app_user (id, username, password_hash) \
96+ VALUES ($1, 'purge-fixture', 'x')",
9497 )
98+ .bind(user.uuid())
99+ .execute(&db)
100+ .await
101+ .unwrap();
102+ sqlx::query(
103+ "INSERT INTO user_session (id, app_user, token, expires_at) \
104+ VALUES ($1, $3, 'past', 1), ($2, $3, 'future', 99999999999999)",
105+ )
106+ .bind(UserId::generate().uuid())
107+ .bind(UserId::generate().uuid())
108+ .bind(user.uuid())
109+ .execute(&db)
95110 .await
96- .unwrap()
97- .check()
98111 .unwrap();
99112
100113 assert_eq!(purge_expired(&db).await.unwrap(), 1);
src/db/session_attendance.rsmodified+28 -27
@@ -299,7 +299,7 @@ pub async fn remove(
299299 mod tests {
300300 use super::*;
301301 use crate::constant::DEFAULT_ATTENDANCE_STATUSES;
302- use crate::database::init_mem;
302+ use crate::database::init_test_db;
303303 use crate::domain::course_session::SessionTopic;
304304 use crate::domain::role::Role;
305305
@@ -307,15 +307,19 @@ mod tests {
307307 /// writes nothing at all to a record that does not exist), and the live
308308 /// role is what decides whether the attended counter moves.
309309 async fn a_user(key: &str, role: Role, db: &Database) -> UserId {
310- let user = UserId::from_key(key);
311- db.query("CREATE $usr SET username = $name, password_hash = 'x', role = $role")
312- .bind(("usr", user.record()))
313- .bind(("name", key.to_string()))
314- .bind(("role", role))
315- .await
316- .unwrap()
317- .check()
318- .unwrap();
310+ // Minted fresh: the id is a real parent row now, and the minted uuid
311+ // keeps repeated calls (same label, new person) collision-free.
312+ let user = UserId::generate();
313+ sqlx::query(
314+ "INSERT INTO app_user (id, username, password_hash, role) \
315+ VALUES ($1, $2, 'x', $3)",
316+ )
317+ .bind(user.uuid())
318+ .bind(format!("{key}-{}", &user.key()[..8]))
319+ .bind(role.as_str())
320+ .execute(db)
321+ .await
322+ .unwrap();
319323 user
320324 }
321325
@@ -376,7 +380,7 @@ mod tests {
376380 /// a re-mark and a swap within the same class are both no-ops.
377381 #[tokio::test]
378382 async fn the_counter_follows_every_crossing_and_no_other_move() {
379- let db = init_mem().await.unwrap();
383+ let (db, _leases) = init_test_db().await;
380384 let teacher = a_teacher("t", &db).await;
381385 let student = a_student("s", &db).await;
382386 let session = a_session(&teacher, &db).await;
@@ -410,7 +414,7 @@ mod tests {
410414 /// once: the whole roster, and every later correction, ride the same stamp.
411415 #[tokio::test]
412416 async fn the_first_roll_call_counts_the_lesson_once() {
413- let db = init_mem().await.unwrap();
417+ let (db, _leases) = init_test_db().await;
414418 let teacher = a_teacher("t", &db).await;
415419 let other = a_teacher("o", &db).await;
416420 let session = a_session(&teacher, &db).await;
@@ -439,7 +443,7 @@ mod tests {
439443 /// two hundred lessons for next week and hold all of them this afternoon.
440444 #[tokio::test]
441445 async fn a_lesson_that_has_not_started_holds_nothing_yet() {
442- let db = init_mem().await.unwrap();
446+ let (db, _leases) = init_test_db().await;
443447 let teacher = a_teacher("t", &db).await;
444448 let student = a_student("s", &db).await;
445449 let next_week =
@@ -474,7 +478,7 @@ mod tests {
474478 /// lesson held.
475479 #[tokio::test]
476480 async fn a_teacher_marked_present_earns_nothing_for_attending() {
477- let db = init_mem().await.unwrap();
481+ let (db, _leases) = init_test_db().await;
478482 let teacher = a_teacher("t", &db).await;
479483 let session = a_session(&teacher, &db).await;
480484
@@ -501,7 +505,7 @@ mod tests {
501505 /// Two lessons are two counts — the counter is per row, not per student.
502506 #[tokio::test]
503507 async fn each_lesson_counts_once_for_the_student_marked() {
504- let db = init_mem().await.unwrap();
508+ let (db, _leases) = init_test_db().await;
505509 let teacher = a_teacher("t", &db).await;
506510 let student = a_student("s", &db).await;
507511 let other = a_student("o", &db).await;
@@ -519,7 +523,7 @@ mod tests {
519523 /// that was counted.
520524 #[tokio::test]
521525 async fn removing_a_row_gives_back_only_what_it_took() {
522- let db = init_mem().await.unwrap();
526+ let (db, _leases) = init_test_db().await;
523527 let teacher = a_teacher("t", &db).await;
524528 let student = a_student("s", &db).await;
525529
@@ -562,7 +566,7 @@ mod tests {
562566 /// a stale row starts from, the counter never goes negative.
563567 #[tokio::test]
564568 async fn the_counter_never_goes_below_zero() {
565- let db = init_mem().await.unwrap();
569+ let (db, _leases) = init_test_db().await;
566570 let teacher = a_teacher("t", &db).await;
567571 let student = a_student("s", &db).await;
568572
@@ -577,14 +581,11 @@ mod tests {
577581 .unwrap();
578582 sessions.push(session);
579583 }
580- db.query(format!(
581- "UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = 0"
582- ))
583- .bind(("usr", student.record()))
584- .await
585- .unwrap()
586- .check()
587- .unwrap();
584+ sqlx::query("UPDATE app_user SET lessons_attended_total = 0 WHERE id = $1")
585+ .bind(student.uuid())
586+ .execute(&db)
587+ .await
588+ .unwrap();
588589
589590 for session in &sessions {
590591 mark(&db, session, &student, status("absent"), &teacher)
@@ -601,7 +602,7 @@ mod tests {
601602 /// the ruling every other counter here carries.
602603 #[tokio::test]
603604 async fn deleting_the_session_leaves_the_counters_alone() {
604- let db = init_mem().await.unwrap();
605+ let (db, _leases) = init_test_db().await;
605606 let teacher = a_teacher("t", &db).await;
606607 let student = a_student("s", &db).await;
607608 let session = a_session(&teacher, &db).await;
@@ -620,7 +621,7 @@ mod tests {
620621 /// a count behind either.
621622 #[tokio::test]
622623 async fn a_refused_mark_moves_nothing() {
623- let db = init_mem().await.unwrap();
624+ let (db, _leases) = init_test_db().await;
624625 let teacher = a_teacher("t", &db).await;
625626 let student = a_student("s", &db).await;
626627 let session = a_session(&teacher, &db).await;
src/db/solution.rsmodified+26 -12
@@ -254,22 +254,36 @@ pub async fn delete(db: &Database, solution: Solution) -> Result<Solution, AppEr
254254
255255 #[cfg(test)]
256256 mod tests {
257- use ulid::Ulid;
258-
259257 use super::*;
260258 use crate::database;
261259 use crate::domain::pool_question::{PoolQuestion, PoolQuestionBody, PoolQuestionTitle};
262260 use crate::domain::timestamp::Timestamp;
263261 use crate::domain::user::UserId;
264262
263+ /// A real `app_user` row: askers and authors are foreign keys now.
264+ async fn a_person(db: &Database, label: &str) -> UserId {
265+ let user = UserId::generate();
266+ sqlx::query(
267+ "INSERT INTO app_user (id, username, password_hash) \
268+ VALUES ($1, $2, 'x')",
269+ )
270+ .bind(user.uuid())
271+ .bind(format!("{label}-{}", &user.key()[..8]))
272+ .execute(db)
273+ .await
274+ .unwrap();
275+ user
276+ }
277+
265278 /// A real question row: offering a solution moves its question's
266279 /// `asked_at` (that is what keeps a solution from outliving its question),
267280 /// so a minted id nothing wrote is a 404.
268281 async fn question_row(db: &Database) -> PoolQuestionId {
282+ let asker = a_person(db, "asker").await;
269283 crate::db::pool_question::insert(
270284 db,
271285 PoolQuestion::new(
272- &UserId::from_key(&Ulid::generate().to_string()),
286+ &asker,
273287 PoolQuestionTitle::try_new("soru").unwrap(),
274288 PoolQuestionBody::try_new("neden").unwrap(),
275289 ),
@@ -282,10 +296,10 @@ mod tests {
282296
283297 #[tokio::test]
284298 async fn rows_scope_to_their_question_and_list_oldest_first() {
285- let db = database::init_mem().await.unwrap();
299+ let (db, _leases) = database::init_test_db().await;
286300 let question_a = question_row(&db).await;
287301 let question_b = question_row(&db).await;
288- let author = UserId::from_key(&Ulid::generate().to_string());
302+ let author = a_person(&db, "author").await;
289303
290304 // Distinct offer times so the assertion pins the real contract —
291305 // older `offered_at` sorts first — not the same-millisecond `id`
@@ -341,7 +355,7 @@ mod tests {
341355
342356 #[tokio::test]
343357 async fn image_set_replace_clear_report_the_replaced_blob() {
344- let db = database::init_mem().await.unwrap();
358+ let (db, _leases) = database::init_test_db().await;
345359 let question = question_row(&db).await;
346360 let author = UserId::from_key(&Ulid::generate().to_string());
347361 let png = FileContentType::try_new("image/png").unwrap();
@@ -402,7 +416,7 @@ mod tests {
402416
403417 #[tokio::test]
404418 async fn set_body_edits_in_place() {
405- let db = database::init_mem().await.unwrap();
419+ let (db, _leases) = database::init_test_db().await;
406420 let question = question_row(&db).await;
407421 let author = UserId::from_key(&Ulid::generate().to_string());
408422
@@ -443,11 +457,11 @@ mod tests {
443457
444458 #[tokio::test]
445459 async fn counts_for_groups_per_question() {
446- let db = database::init_mem().await.unwrap();
460+ let (db, _leases) = database::init_test_db().await;
447461 let two = question_row(&db).await;
448462 let one = question_row(&db).await;
449463 let none = question_row(&db).await;
450- let author = UserId::from_key(&Ulid::generate().to_string());
464+ let author = a_person(&db, "author").await;
451465
452466 for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] {
453467 for body in bodies {
@@ -463,10 +477,10 @@ mod tests {
463477 let counts = counts_for(&db, &[two.clone(), one.clone(), none.clone()])
464478 .await
465479 .unwrap();
466- assert_eq!(counts.get(two.key()), Some(&2));
467- assert_eq!(counts.get(one.key()), Some(&1));
480+ assert_eq!(counts.get(two.key().as_str()), Some(&2));
481+ assert_eq!(counts.get(one.key().as_str()), Some(&1));
468482 // No solutions = no entry; the caller reads the miss as zero.
469- assert_eq!(counts.get(none.key()), None);
483+ assert_eq!(counts.get(none.key().as_str()), None);
470484 assert!(counts_for(&db, &[]).await.unwrap().is_empty());
471485 }
472486 }
src/db/subject.rsmodified+18 -14
@@ -133,7 +133,9 @@ pub async fn update(
133133 /// The bank's subject is optional metadata, and blocking on it was a dead
134134 /// end — only the template's owner may re-tag it, so a manager could never
135135 /// clear their own 409, and a private template raising it leaked its
136-/// existence. Its cascade runs *after* the guarded delete, so a refused
136+/// existence. Its cascade clears the templates before the delete — the FK on
137+/// `bank_question.subject` refuses the parent delete while a template still
138+/// points at it — and the one transaction rolls everything back, so a refused
137139 /// delete leaves every template's subject where it was.
138140 pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError> {
139141 crate::database::tx_with_retry(db, false, async move |tx| {
@@ -157,6 +159,20 @@ pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError
157159 "homework still references this subject — re-tag or delete it first",
158160 ));
159161 }
162+ // The bank's cascade clears the templates *before* the delete:
163+ // `bank_question.subject` carries a real foreign key, so a template
164+ // still pointing at this row makes the `DELETE` itself fail (23503)
165+ // — the old store had no enforced reference to release. The guard
166+ // above has already decided, and the transaction makes the pair
167+ // atomic, so ordering costs nothing: a refused delete (an error
168+ // raised anywhere above) rolls the whole thing back and every
169+ // template's subject stays where it was.
170+ sqlx::query!(
171+ r#"UPDATE bank_question SET subject = NULL WHERE subject = $1"#,
172+ subject.id.uuid(),
173+ )
174+ .execute(&mut *tx)
175+ .await?;
160176 let deleted = sqlx::query_as!(
161177 Subject,
162178 r#"DELETE FROM subject WHERE id = $1
@@ -168,12 +184,6 @@ pub async fn delete(db: &Database, subject: Subject) -> Result<Subject, AppError
168184 )
169185 .fetch_one(&mut *tx)
170186 .await?;
171- sqlx::query!(
172- r#"UPDATE bank_question SET subject = NULL WHERE subject = $1"#,
173- subject.id.uuid(),
174- )
175- .execute(&mut *tx)
176- .await?;
177187 Ok(deleted)
178188 })
179189 .await
@@ -196,7 +206,6 @@ mod tests {
196206 /// Mutation-tested: with the bare `db.create` this shipped with, all four
197207 /// rounds orphan.
198208 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
199- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
200209 async fn a_subject_never_outlives_its_course() {
201210 fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {
202211 tokio::spawn(async move {
@@ -210,12 +219,7 @@ mod tests {
210219 .map(|_| ())
211220 })
212221 }
213- crate::db::course::assert_no_child_outlives_a_course_delete(
214- "subject_orphan_race",
215- SUBJECT_TABLE,
216- make,
217- )
218- .await;
222+ crate::db::course::assert_no_child_outlives_a_course_delete("subject", make).await;
219223 }
220224
221225 /// GUARD, not a retry measurement — read the last paragraph before
src/db/term.rsmodified+2 -2
@@ -173,7 +173,7 @@ mod tests {
173173 /// refuse it with the same error, having written nothing.
174174 #[tokio::test]
175175 async fn a_moved_end_is_refused_against_the_stored_other_end() {
176- let db = crate::database::init_mem().await.unwrap();
176+ let (db, _leases) = crate::database::init_test_db().await;
177177 let at = Timestamp::from_millis;
178178 let term = create(&db, TermName::try_new("2026").unwrap(), at(100), at(200))
179179 .await
@@ -202,7 +202,7 @@ mod tests {
202202 /// tie-break on identical `starts_at` — stored read-back, then page by page.
203203 #[tokio::test]
204204 async fn identical_starts_at_still_pages_each_term_exactly_once() {
205- let db = crate::database::init_mem().await.unwrap();
205+ let (db, _leases) = crate::database::init_test_db().await;
206206 let at = Timestamp::from_millis;
207207 let mut minted = Vec::new();
208208 for i in 0..12 {
src/db/work_entry.rsmodified+11 -7
@@ -195,21 +195,25 @@ pub async fn remove(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>
195195
196196 #[cfg(test)]
197197 mod tests {
198- use ulid::Ulid;
199-
200198 use super::*;
201199 use crate::database;
202200
203201 #[tokio::test]
204202 async fn check_in_is_exclusive_until_check_out() {
205- let db = database::init_mem().await.unwrap();
206- // A `record<user>` column checks the table of the id, not row
207- // existence — a fabricated id keeps this test free of user ceremony.
208- let user = UserId::from_key(&Ulid::generate().to_string());
203+ let (db, _leases) = database::init_test_db().await;
204+ // The stint's owner is a foreign key now: a real `app_user` row.
205+ let user = UserId::generate();
206+ sqlx::query(
207+ "INSERT INTO app_user (id, username, password_hash) \
208+ VALUES ($1, 'work-fixture', 'x')",
209+ )
210+ .bind(user.uuid())
211+ .execute(&db)
212+ .await
213+ .unwrap();
209214
210215 let open = check_in(&db, &user).await.unwrap();
211216 assert!(open.is_open());
212- assert_eq!(open.get_id().key(), format!("open_{}", user.key()));
213217
214218 // Second check-in must not create a second stint or reset the clock.
215219 let dup = check_in(&db, &user).await;
src/service/appointment.rsmodified+9 -9
@@ -392,7 +392,7 @@ fn contended() -> AppError {
392392 #[cfg(test)]
393393 mod tests {
394394 use super::*;
395- use crate::database::{Database, init_mem};
395+ use crate::database::{Database, init_test_db};
396396 use crate::service::appointment_slot;
397397
398398 fn at(millis: i64) -> Timestamp {
@@ -406,7 +406,7 @@ mod tests {
406406
407407 #[tokio::test]
408408 async fn window_prefers_a_proposal_over_the_slot() {
409- let db = init_mem().await.unwrap();
409+ let (db, _leases) = init_test_db().await;
410410 let teacher = UserId::from_key("t1");
411411 let (starts_at, ends_at) = (soon(60_000), soon(120_000));
412412 let slot = appointment_slot::create(&db, &teacher, starts_at, ends_at, None)
@@ -431,7 +431,7 @@ mod tests {
431431 /// to undo the resulting meeting, so the booking would be stuck for good.
432432 #[tokio::test]
433433 async fn a_started_slot_cannot_be_booked() {
434- let db = init_mem().await.unwrap();
434+ let (db, _leases) = init_test_db().await;
435435 let teacher = UserId::from_key("t1");
436436 let reason = || AppointmentReason::try_new("görüşme").unwrap();
437437 let started = appointment_slot::create(&db, &teacher, soon(-30_000), soon(60_000), None)
@@ -456,7 +456,7 @@ mod tests {
456456 /// come and gone cannot be accepted — the meeting would be uncancellable.
457457 #[tokio::test]
458458 async fn a_started_proposal_cannot_be_accepted() {
459- let db = init_mem().await.unwrap();
459+ let (db, _leases) = init_test_db().await;
460460 let teacher = UserId::from_key("t1");
461461 let student = UserId::from_key("s1");
462462 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
@@ -544,7 +544,7 @@ mod tests {
544544 /// primitive itself with the exact stale snapshot the race produces.
545545 #[tokio::test]
546546 async fn a_decision_built_on_a_stale_snapshot_never_lands() {
547- let db = init_mem().await.unwrap();
547+ let (db, _leases) = init_test_db().await;
548548 let teacher = UserId::from_key("t1");
549549 let student = UserId::from_key("s1");
550550 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
@@ -633,7 +633,7 @@ mod tests {
633633 /// second claim succeed and this fail (mutation-proved).
634634 #[tokio::test]
635635 async fn a_concurrent_claim_cannot_take_a_booked_slot() {
636- let db = init_mem().await.unwrap();
636+ let (db, _leases) = init_test_db().await;
637637 let teacher = UserId::from_key("t1");
638638 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
639639 .await
@@ -674,7 +674,7 @@ mod tests {
674674 /// bumped the counter would strand the slot forever.
675675 #[tokio::test]
676676 async fn a_refused_booking_moves_nothing() {
677- let db = init_mem().await.unwrap();
677+ let (db, _leases) = init_test_db().await;
678678 let teacher = UserId::from_key("t1");
679679 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
680680 .await
@@ -711,7 +711,7 @@ mod tests {
711711 /// cancel that moved one without the other would strand the slot forever.
712712 #[tokio::test]
713713 async fn cancelling_hands_the_seat_back_with_the_status() {
714- let db = init_mem().await.unwrap();
714+ let (db, _leases) = init_test_db().await;
715715 let teacher = UserId::from_key("t1");
716716 let student = UserId::from_key("s1");
717717 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
@@ -749,7 +749,7 @@ mod tests {
749749 /// Occupancy frees on reject, so the slot can be re-booked.
750750 #[tokio::test]
751751 async fn rejecting_frees_the_slot_for_re_booking() {
752- let db = init_mem().await.unwrap();
752+ let (db, _leases) = init_test_db().await;
753753 let teacher = UserId::from_key("t1");
754754 let slot = appointment_slot::create(&db, &teacher, soon(60_000), soon(120_000), None)
755755 .await
src/service/appointment_slot.rsmodified+8 -8
@@ -208,7 +208,7 @@ mod tests {
208208
209209 #[tokio::test]
210210 async fn a_publish_shares_one_series_and_orders_its_ids() {
211- let db = crate::database::init_mem().await.unwrap();
211+ let (db, _leases) = crate::database::init_test_db().await;
212212 let teacher = UserId::from_key("t1");
213213 let slots = publish_weekly(
214214 &db,
@@ -236,7 +236,7 @@ mod tests {
236236
237237 #[tokio::test]
238238 async fn overlapping_publish_is_refused_but_touching_is_allowed() {
239- let db = crate::database::init_mem().await.unwrap();
239+ let (db, _leases) = crate::database::init_test_db().await;
240240 let teacher = UserId::from_key("t1");
241241 create(&db, &teacher, at(1_000), at(2_000), None)
242242 .await
@@ -265,7 +265,7 @@ mod tests {
265265
266266 #[tokio::test]
267267 async fn weekly_publish_overlapping_an_existing_slot_writes_nothing() {
268- let db = crate::database::init_mem().await.unwrap();
268+ let (db, _leases) = crate::database::init_test_db().await;
269269 let teacher = UserId::from_key("t1");
270270 // A lone slot on the third week of the coming series.
271271 create(
@@ -301,7 +301,7 @@ mod tests {
301301 /// the batch's boundaries must still be allowed.
302302 #[tokio::test]
303303 async fn the_batch_wide_conflict_read_still_sees_the_last_week_and_lets_touching_through() {
304- let db = crate::database::init_mem().await.unwrap();
304+ let (db, _leases) = crate::database::init_test_db().await;
305305 let teacher = UserId::from_key("t1");
306306 let last = 1_000 + 4 * MILLIS_PER_WEEK;
307307 // Touching both ends of the envelope: ends where the first occurrence
@@ -319,7 +319,7 @@ mod tests {
319319 );
320320
321321 // One millisecond into the last occurrence → the whole publish is 409.
322- let db = crate::database::init_mem().await.unwrap();
322+ let (db, _leases) = crate::database::init_test_db().await;
323323 create(&db, &teacher, at(last + 999), at(last + 3_000), None)
324324 .await
325325 .unwrap();
@@ -339,7 +339,7 @@ mod tests {
339339 /// and the free weeks must survive the refusal.
340340 #[tokio::test]
341341 async fn a_taken_slot_is_never_deleted_and_takes_its_series_with_it() {
342- let db = crate::database::init_mem().await.unwrap();
342+ let (db, _leases) = crate::database::init_test_db().await;
343343 let teacher = UserId::from_key("t1");
344344 let slots = publish_weekly(
345345 &db,
@@ -394,7 +394,7 @@ mod tests {
394394 /// teacher+ passes through untouched.
395395 #[tokio::test]
396396 async fn a_publish_by_someone_who_lost_the_role_is_refused() {
397- let db = crate::database::init_mem().await.unwrap();
397+ let (db, _leases) = crate::database::init_test_db().await;
398398 // Written as a row rather than through `User` — the password hasher is
399399 // private to that module, and the only column this asks about is `role`.
400400 db.query("CREATE user:eski SET username = 'eski', password_hash = 'x', role = 'student'")
@@ -535,7 +535,7 @@ mod tests {
535535
536536 #[tokio::test]
537537 async fn weekly_publish_that_self_overlaps_is_refused() {
538- let db = crate::database::init_mem().await.unwrap();
538+ let (db, _leases) = crate::database::init_test_db().await;
539539 let teacher = UserId::from_key("t1");
540540 // A window longer than the weekly step collides with the next week.
541541 assert!(matches!(
src/service/board.rsmodified+1 -1
@@ -229,7 +229,7 @@ mod tests {
229229 /// participant on the other.
230230 #[tokio::test]
231231 async fn an_outsider_gets_404_and_a_participant_gets_403() {
232- let db = crate::database::init_mem().await.unwrap();
232+ let (db, _leases) = crate::database::init_test_db().await;
233233 // (fixtures rebuilt against Postgres in wave 3)
234234 let _ = &db;
235235 }
src/service/builder.rsmodified+1 -1
@@ -67,7 +67,7 @@ mod tests {
6767
6868 #[tokio::test]
6969 async fn the_seed_is_idempotent_and_never_rewrites_a_credential() {
70- let tenants = Tenants::new_mem().await.unwrap();
70+ let tenants = crate::database::init_test_tenants().await;
7171 let control = tenants.control();
7272 let name = Username::try_new("builder1").unwrap();
7373 ensure(control, name.clone(), Password::try_new("secret1").unwrap())
src/service/class_blueprint.rsmodified+146 -105
@@ -375,9 +375,10 @@ pub async fn status(
375375 #[cfg(test)]
376376 mod tests {
377377 use super::*;
378- use crate::constant::{CLASS_COURSE_COUNT_FIELD, MAX_CLASS_COURSES};
379- use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows};
380- use crate::domain::class_course::ClassCourseId;
378+ use crate::constant::MAX_CLASS_COURSES;
379+ use crate::db::class_member::tests::{
380+ a_class, a_course, counter, fixture_user, link_exists, rows,
381+ };
381382 use crate::domain::class_group::{ClassGroup, ClassName};
382383
383384 /// A section that a pump's own grade loop can actually find — [`a_class`]
@@ -397,9 +398,10 @@ mod tests {
397398
398399 /// A blueprint holding `courses`, at grade "9".
399400 async fn a_blueprint(courses: Vec<CourseId>, db: &Database) -> ClassBlueprint {
401+ let manager = fixture_user(db, "manager").await;
400402 create(
401403 db,
402- &UserId::from_key("manager"),
404+ &manager,
403405 ClassBlueprint::grade_key("9").unwrap(),
404406 courses,
405407 )
@@ -416,22 +418,21 @@ mod tests {
416418 /// really produces it, not from the enum.
417419 #[tokio::test]
418420 async fn a_skip_names_what_actually_failed() {
419- let manager = UserId::from_key("manager");
421+ let (db, _leases) = crate::database::init_test_db().await;
422+ let manager = fixture_user(&db, "manager").await;
420423
421424 // The course is deleted out from under the pump: the pivot claim
422425 // matches nothing.
423- let db = crate::database::init_mem().await.unwrap();
424426 let course = a_course("algebra", None, &db).await;
425427 let class = class_group::read(&db, &a_class("9-A", &db).await)
426428 .await
427429 .unwrap()
428430 .unwrap();
429431 let blueprint = a_blueprint(vec![course.clone()], &db).await;
430- db.query("DELETE $c")
431- .bind(("c", course.record()))
432+ sqlx::query("DELETE FROM course WHERE id = $1")
433+ .bind(course.uuid())
434+ .execute(&db)
432435 .await
433- .unwrap()
434- .check()
435436 .unwrap();
436437 let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap();
437438 assert_eq!(skipped.len(), 1, "{skipped:?}");
@@ -453,18 +454,17 @@ mod tests {
453454
454455 // The class is deleted out from under the pump: the counter claim
455456 // matches nothing and the read that follows finds no row.
456- let db = crate::database::init_mem().await.unwrap();
457+ let (db, _leases) = crate::database::init_test_db().await;
457458 let course = a_course("algebra", None, &db).await;
458459 let class = class_group::read(&db, &a_class("9-A", &db).await)
459460 .await
460461 .unwrap()
461462 .unwrap();
462463 let blueprint = a_blueprint(vec![course.clone()], &db).await;
463- db.query("DELETE $c")
464- .bind(("c", class.get_id().record()))
464+ sqlx::query("DELETE FROM class_group WHERE id = $1")
465+ .bind(class.get_id().uuid())
466+ .execute(&db)
465467 .await
466- .unwrap()
467- .check()
468468 .unwrap();
469469 let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap();
470470 assert_eq!(skipped.len(), 1, "{skipped:?}");
@@ -484,22 +484,22 @@ mod tests {
484484
485485 // The class stands at its own ceiling: the same claim matches nothing,
486486 // but the row is there — and that is the one a manager can act on.
487- let db = crate::database::init_mem().await.unwrap();
487+ let (db, _leases) = crate::database::init_test_db().await;
488488 let course = a_course("algebra", None, &db).await;
489489 let class = class_group::read(&db, &a_class("9-A", &db).await)
490490 .await
491491 .unwrap()
492492 .unwrap();
493493 let blueprint = a_blueprint(vec![course], &db).await;
494- db.query(format!(
495- "UPDATE $c SET {} = $cap",
496- crate::constant::CLASS_COURSE_COUNT_FIELD
497- ))
498- .bind(("c", class.get_id().record()))
499- .bind(("cap", MAX_CLASS_COURSES))
494+ sqlx::query(
495+ sqlx::AssertSqlSafe(format!(
496+ "UPDATE class_group SET class_course_count = {} WHERE id = $1",
497+ MAX_CLASS_COURSES
498+ )),
499+ )
500+ .bind(class.get_id().uuid())
501+ .execute(&db)
500502 .await
501- .unwrap()
502- .check()
503503 .unwrap();
504504 let skipped = apply_to(&db, &blueprint, &class, &manager).await.unwrap();
505505 assert_eq!(skipped.len(), 1, "{skipped:?}");
@@ -518,8 +518,8 @@ mod tests {
518518 /// this caller in, and deterministic where two live requests are not.
519519 #[tokio::test]
520520 async fn a_delete_of_a_list_that_moved_is_a_409_that_writes_nothing() {
521- let db = crate::database::init_mem().await.unwrap();
522- let manager = UserId::from_key("manager");
521+ let (db, _leases) = crate::database::init_test_db().await;
522+ let manager = fixture_user(&db, "manager").await;
523523 let algebra = a_course("algebra", None, &db).await;
524524 let physics = a_course("physics", None, &db).await;
525525 let class = class_group::read(&db, &a_class("9-A", &db).await)
@@ -555,7 +555,7 @@ mod tests {
555555 "the row the caller did not read is still there"
556556 );
557557 assert_eq!(
558- rows("SELECT VALUE id FROM class_course", &db).await,
558+ rows("class_course", &db).await,
559559 2,
560560 "and neither attachment was swept — including the one this handle \
561561 never knew about"
@@ -572,47 +572,71 @@ mod tests {
572572 /// and the delete is watched not-finishing on a timeout.
573573 #[tokio::test]
574574 async fn a_delete_waits_for_an_attach_in_flight() {
575- let db = crate::database::init_mem().await.unwrap();
576- let manager = UserId::from_key("manager");
575+ let (db, _leases) = crate::database::init_test_db().await;
576+ let manager = fixture_user(&db, "manager").await;
577577 let algebra = a_course("algebra", None, &db).await;
578578 let class = class_group::read(&db, &a_class("9-A", &db).await)
579579 .await
580580 .unwrap()
581581 .unwrap();
582- let blueprint = a_blueprint(vec![algebra], &db).await;
582+ let blueprint = a_blueprint(vec![algebra.clone()], &db).await;
583583 apply_to(&db, &blueprint, &class, &manager).await.unwrap();
584584
585- // Stand in for an attach mid-transaction, which is exactly the lease
586- // `apply_to` holds around one course.
587- let attaching = BLUEPRINT_LOCK.read().await;
588- let mut deleting = {
589- let db = db.clone();
590- let blueprint = blueprint.clone();
591- tokio::spawn(async move { delete(&db, blueprint).await })
585+ // The lease is gone with the lock; the whole compare-and-set-plus-
586+ // sweep is one transaction now, and the pump claims the blueprint
587+ // inside its own. A barrier start lets the racing attach and delete
588+ // interleave every which way — in all of them no `class_course` row
589+ // may survive a blueprint that is gone, and no counter may drift.
590+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
591+ let deleting = {
592+ let (db, blueprint, gate) = (db.clone(), blueprint.clone(), gate.clone());
593+ tokio::spawn(async move {
594+ gate.wait().await;
595+ delete(&db, blueprint).await
596+ })
592597 };
593- assert!(
594- tokio::time::timeout(std::time::Duration::from_millis(150), &mut deleting)
595- .await
596- .is_err(),
597- "the delete must not run while an attach is in flight"
598- );
599- assert_eq!(
600- rows("SELECT VALUE id FROM class_blueprint", &db).await,
601- 1,
602- "…and it must not have swept anything either"
603- );
598+ let pumping = {
599+ let (db, class, algebra, manager, gate) =
600+ (db.clone(), class.clone(), algebra.clone(), manager.clone(), gate);
601+ tokio::spawn(async move {
602+ gate.wait().await;
603+ apply_to(&db, &blueprint, &class, &manager).await
604+ })
605+ };
606+ let (deleted, pumped) = (deleting.await.unwrap(), pumping.await.unwrap());
607+ deleted.unwrap();
604608
605- drop(attaching);
606- deleting.await.unwrap().unwrap();
609+ // The delete went through; whatever the pump answered, the stored
610+ // state must agree with itself.
607611 assert_eq!(
608- rows("SELECT VALUE id FROM class_blueprint", &db).await,
612+ rows("class_blueprint", &db).await,
609613 0,
610- "once the attach is done the delete goes through"
614+ "the delete goes through"
611615 );
616+ let skipped = pumped.unwrap();
617+ if skipped.iter().any(|s| s.reason == "blueprint_deleted") {
618+ assert_eq!(
619+ rows("class_course", &db).await,
620+ 0,
621+ "a pump that read a dead blueprint attaches nothing"
622+ );
623+ } else {
624+ // The pump beat the delete to the claim and attached cleanly: its
625+ // rows go with the blueprint the sweep then took.
626+ assert!(
627+ skipped.is_empty(),
628+ "neither a clean attach nor a clean skip: {skipped:?}"
629+ );
630+ assert_eq!(
631+ rows("class_course", &db).await,
632+ 0,
633+ "the sweep took the rows the winning pump had just written"
634+ );
635+ }
612636 assert_eq!(
613- rows("SELECT VALUE id FROM class_course", &db).await,
637+ counter("class_course_count", class.get_id().uuid(), &db).await,
614638 0,
615- "…taking every row carrying its tag with it"
639+ "…and whatever happened, the class's counter is back to zero"
616640 );
617641 }
618642
@@ -636,58 +660,80 @@ mod tests {
636660 /// assertion rather than passing it by default.
637661 #[tokio::test]
638662 async fn a_delete_frees_the_lease_before_its_unbounded_sweep() {
639- let db = crate::database::init_mem().await.unwrap();
640- let manager = UserId::from_key("manager");
663+ let (db, _leases) = crate::database::init_test_db().await;
664+ let manager = fixture_user(&db, "manager").await;
641665 let courses = vec![
642666 a_course("algebra", None, &db).await,
643667 a_course("physics", None, &db).await,
644668 ];
645669 let blueprint = a_blueprint(courses, &db).await;
646- for name in ["9-A", "9-B"] {
670+ let mut classes = Vec::new();
671+ for name in ["9-A", "9-B", "9-C"] {
647672 let class = class_group::read(&db, &a_class(name, &db).await)
648673 .await
649674 .unwrap()
650675 .unwrap();
651- apply_to(&db, &blueprint, &class, &manager).await.unwrap();
676+ if name != "9-C" {
677+ apply_to(&db, &blueprint, &class, &manager).await.unwrap();
678+ }
679+ classes.push(class);
652680 }
653- db.query(
654- "DEFINE EVENT slow_sweep ON TABLE class_course WHEN $event = 'DELETE' \
655- THEN { SLEEP 300ms; };",
656- )
657- .await
658- .unwrap()
659- .check()
660- .unwrap();
661681
682+ // The lock is gone, so there is no lease to free; what still has to
683+ // hold is its point: a pump arriving while the delete's sweep is in
684+ // flight is answered by the database, not parked behind the sweep —
685+ // and the sweep still takes every row carrying the blueprint's tag.
686+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
662687 let deleting = {
663- let (db, blueprint) = (db.clone(), blueprint.clone());
664- tokio::spawn(async move { delete(&db, blueprint).await })
688+ let (db, blueprint, gate) = (db.clone(), blueprint.clone(), gate.clone());
689+ tokio::spawn(async move {
690+ gate.wait().await;
691+ delete(&db, blueprint).await
692+ })
665693 };
666- let beat = std::time::Duration::from_millis(10);
667- // The row is gone the instant the compare-and-set commits, which is
668- // inside the lease this test is about.
669- while rows("SELECT VALUE id FROM class_blueprint", &db).await > 0 {
670- tokio::time::sleep(beat).await;
671- }
672- let mut freed = false;
673- while !deleting.is_finished() {
674- if BLUEPRINT_LOCK.try_read().is_ok() {
675- freed = true;
676- break;
677- }
678- tokio::time::sleep(beat).await;
679- }
694+ let pumping = {
695+ let (db, class, manager, gate, blueprint) = (
696+ db.clone(),
697+ classes[2].clone(),
698+ manager.clone(),
699+ gate.clone(),
700+ blueprint.clone(),
701+ );
702+ tokio::spawn(async move {
703+ gate.wait().await;
704+ apply_to(&db, &blueprint, &class, &manager).await
705+ })
706+ };
707+
708+ // The pump is answered in bounded time even though the delete is
709+ // sweeping two sections' link rows — and answered with one of the two
710+ // honest outcomes, never a 500.
711+ let pumped =
712+ tokio::time::timeout(std::time::Duration::from_secs(10), pumping)
713+ .await
714+ .expect("a pump must not wait behind a delete's unbounded sweep")
715+ .unwrap();
716+ let skipped = pumped.unwrap();
680717 assert!(
681- freed,
682- "a pump may not wait behind a delete's unbounded sweep"
718+ skipped.iter().all(|s| {
719+ s.reason == "blueprint_deleted" || s.reason == "course_deleted"
720+ }) || skipped.is_empty(),
721+ "neither a clean attach nor a clean skip: {skipped:?}"
683722 );
684723
685724 deleting.await.unwrap().unwrap();
686725 assert_eq!(
687- rows("SELECT VALUE id FROM class_course", &db).await,
726+ rows("class_course", &db).await,
688727 0,
689- "…and the sweep it ran lease-free still took every row it owned"
728+ "…and the sweep still took every row it owned"
690729 );
730+ for class in &classes {
731+ assert_eq!(
732+ counter("class_course_count", class.get_id().uuid(), &db).await,
733+ 0,
734+ "…and no counter kept a seat the sweep took back"
735+ );
736+ }
691737 }
692738
693739 /// The other half: a pump holding a handle to a blueprint that has since
@@ -699,8 +745,8 @@ mod tests {
699745 /// reach that row again.
700746 #[tokio::test]
701747 async fn a_pump_whose_blueprint_died_attaches_nothing() {
702- let db = crate::database::init_mem().await.unwrap();
703- let manager = UserId::from_key("manager");
748+ let (db, _leases) = crate::database::init_test_db().await;
749+ let manager = fixture_user(&db, "manager").await;
704750 let algebra = a_course("algebra", None, &db).await;
705751 let class = class_group::read(&db, &a_class("9-A", &db).await)
706752 .await
@@ -718,12 +764,12 @@ mod tests {
718764 "the template went, not the class or the course"
719765 );
720766 assert_eq!(
721- rows("SELECT VALUE id FROM class_course", &db).await,
767+ rows("class_course", &db).await,
722768 0,
723769 "a row tagged with a deleted blueprint is one nothing can sweep"
724770 );
725771 assert_eq!(
726- counter(CLASS_COURSE_COUNT_FIELD, class.get_id().record(), &db).await,
772+ counter("class_course_count", class.get_id().uuid(), &db).await,
727773 0,
728774 "…and no counter moved for it"
729775 );
@@ -738,18 +784,17 @@ mod tests {
738784 /// the links are re-read rather than counted off the return value.
739785 #[tokio::test]
740786 async fn a_dead_course_is_pruned_and_skipped_once_for_the_whole_grade() {
741- let db = crate::database::init_mem().await.unwrap();
742- let manager = UserId::from_key("manager");
787+ let (db, _leases) = crate::database::init_test_db().await;
788+ let manager = fixture_user(&db, "manager").await;
743789 let astronomy = a_course("astronomy", None, &db).await;
744790 let algebra = a_course("algebra", None, &db).await;
745791 let a = a_section("9-A", &db).await;
746792 let b = a_section("9-B", &db).await;
747793 let mut blueprint = a_blueprint(vec![astronomy.clone(), algebra.clone()], &db).await;
748- db.query("DELETE $c")
749- .bind(("c", astronomy.record()))
794+ sqlx::query("DELETE FROM course WHERE id = $1")
795+ .bind(astronomy.uuid())
796+ .execute(&db)
750797 .await
751- .unwrap()
752- .check()
753798 .unwrap();
754799
755800 let Pumped { matched, skipped } = pump(&db, &mut blueprint, &manager).await.unwrap();
@@ -771,17 +816,13 @@ mod tests {
771816 );
772817 for class in [&a, &b] {
773818 assert!(
774- exists(
775- ClassCourseId::composite(class.get_id(), &algebra).record(),
776- &db
777- )
778- .await,
819+ link_exists(class.get_id(), &algebra, &db).await,
779820 "the live course still reached {}",
780821 class.get_name().as_str()
781822 );
782823 }
783824 assert_eq!(
784- rows("SELECT VALUE id FROM class_course", &db).await,
825+ rows("class_course", &db).await,
785826 2,
786827 "…and nothing else was attached"
787828 );
@@ -796,8 +837,8 @@ mod tests {
796837 /// delete landing between the read and the pump leaves this caller in.
797838 #[tokio::test]
798839 async fn a_deleted_blueprint_stops_the_grade_loop_after_one_skip() {
799- let db = crate::database::init_mem().await.unwrap();
800- let manager = UserId::from_key("manager");
840+ let (db, _leases) = crate::database::init_test_db().await;
841+ let manager = fixture_user(&db, "manager").await;
801842 let algebra = a_course("algebra", None, &db).await;
802843 a_section("9-A", &db).await;
803844 a_section("9-B", &db).await;
@@ -818,7 +859,7 @@ mod tests {
818859 "an abort reports the sections it walked, not the two the grade holds"
819860 );
820861 assert_eq!(
821- rows("SELECT VALUE id FROM class_course", &db).await,
862+ rows("class_course", &db).await,
822863 0,
823864 "…and nothing was attached under a blueprint nothing could sweep"
824865 );
src/service/class_course.rsmodified+62 -62
@@ -106,18 +106,22 @@ pub async fn list_for_class(
106106 #[cfg(test)]
107107 mod tests {
108108 use super::*;
109- use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows, source_of};
110- use crate::domain::class_course::ClassCourseId;
109+ use crate::db::class_member::tests::{
110+ a_class, a_course, counter, course_exists, link_exists, rows, source_of,
111+ };
111112 use crate::service::class_member;
112113
113114 /// Attaching seeds the course from the roster the class already holds.
114115 #[tokio::test]
115116 async fn an_attach_enrolls_the_whole_roster() {
116- let db = crate::database::init_mem().await.unwrap();
117- let manager = UserId::from_key("manager");
117+ let (db, _leases) = crate::database::init_test_db().await;
118+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
118119 let class = a_class("9-A", &db).await;
119120 let algebra = a_course("algebra", None, &db).await;
120- let students = [UserId::from_key("a"), UserId::from_key("b")];
121+ let students = [
122+ crate::db::class_member::tests::fixture_user(&db, "a").await,
123+ crate::db::class_member::tests::fixture_user(&db, "b").await,
124+ ];
121125 for student in &students {
122126 class_member::add(&db, &class, student, &manager)
123127 .await
@@ -131,8 +135,8 @@ mod tests {
131135 Some(Some(class.clone()))
132136 );
133137 }
134- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 2);
135- assert_eq!(counter("class_course_count", class.record(), &db).await, 1);
138+ assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 2);
139+ assert_eq!(counter("class_course_count", class.uuid(), &db).await, 1);
136140
137141 let again = attach(&db, &class, &algebra, &manager).await;
138142 assert!(
@@ -145,42 +149,41 @@ mod tests {
145149 /// enrollments, the counter unmoved, and no attachment row.
146150 #[tokio::test]
147151 async fn a_roster_that_does_not_fit_attaches_nothing() {
148- let db = crate::database::init_mem().await.unwrap();
149- let manager = UserId::from_key("manager");
152+ let (db, _leases) = crate::database::init_test_db().await;
153+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
150154 let class = a_class("9-A", &db).await;
151155 let tight = a_course("algebra", Some(2), &db).await;
152- for student in ["a", "b", "c"] {
153- class_member::add(&db, &class, &UserId::from_key(student), &manager)
154- .await
155- .unwrap();
156+ for name in ["a", "b", "c"] {
157+ let student = crate::db::class_member::tests::fixture_user(&db, name).await;
158+ class_member::add(&db, &class, &student, &manager).await.unwrap();
156159 }
157160
158161 let refused = attach(&db, &class, &tight, &manager).await;
159162 assert!(
160163 matches!(refused, Err(AppError::ConflictCoded { code, ref message })
161- if code == "course_full" && message.contains(tight.key())),
164+ if code == "course_full" && message.contains(tight.key().as_str())),
162165 "the refusal must be coded `course_full` and name the course: {refused:?}"
163166 );
164167 assert_eq!(
165- rows("SELECT VALUE id FROM enrollment", &db).await,
168+ rows("enrollment", &db).await,
166169 0,
167170 "the two seats that did fit must be given back with the third"
168171 );
169172 assert_eq!(
170- rows("SELECT VALUE id FROM class_course", &db).await,
173+ rows("class_course", &db).await,
171174 0,
172175 "…and no attachment row may survive"
173176 );
174- assert_eq!(counter("enrollment_count", tight.record(), &db).await, 0);
175- assert_eq!(counter("class_course_count", class.record(), &db).await, 0);
177+ assert_eq!(counter("enrollment_count", tight.uuid(), &db).await, 0);
178+ assert_eq!(counter("class_course_count", class.uuid(), &db).await, 0);
176179 }
177180
178181 /// A hand-placed row is skipped on the way in and left standing on the way
179182 /// out — the class never owned it.
180183 #[tokio::test]
181184 async fn a_hand_placed_row_survives_the_detach() {
182- let db = crate::database::init_mem().await.unwrap();
183- let manager = UserId::from_key("manager");
185+ let (db, _leases) = crate::database::init_test_db().await;
186+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
184187 let student = UserId::from_key("student");
185188 let class = a_class("9-A", &db).await;
186189 let algebra = a_course("algebra", None, &db).await;
@@ -198,14 +201,14 @@ mod tests {
198201 "an attach may not adopt a hand-placed row"
199202 );
200203 assert_eq!(
201- counter("enrollment_count", algebra.record(), &db).await,
204+ counter("enrollment_count", algebra.uuid(), &db).await,
202205 1,
203206 "…nor charge a seat for it"
204207 );
205208
206209 detach(&db, &class, &algebra).await.unwrap();
207210 assert_eq!(source_of(&algebra, &student, &db).await, Some(None));
208- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);
211+ assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1);
209212 let again = detach(&db, &class, &algebra).await;
210213 assert!(
211214 matches!(again, Err(AppError::NotFound)),
@@ -217,8 +220,8 @@ mod tests {
217220 /// seats back.
218221 #[tokio::test]
219222 async fn a_detach_sweeps_the_rows_it_pumped() {
220- let db = crate::database::init_mem().await.unwrap();
221- let manager = UserId::from_key("manager");
223+ let (db, _leases) = crate::database::init_test_db().await;
224+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
222225 let student = UserId::from_key("student");
223226 let class = a_class("9-A", &db).await;
224227 let algebra = a_course("algebra", None, &db).await;
@@ -229,10 +232,10 @@ mod tests {
229232
230233 detach(&db, &class, &algebra).await.unwrap();
231234 assert_eq!(source_of(&algebra, &student, &db).await, None);
232- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);
233- assert_eq!(counter("class_course_count", class.record(), &db).await, 0);
235+ assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 0);
236+ assert_eq!(counter("class_course_count", class.uuid(), &db).await, 0);
234237 assert_eq!(
235- rows("SELECT VALUE id FROM class_member", &db).await,
238+ rows("class_member", &db).await,
236239 1,
237240 "the two axes are independent: dropping the course may not drop \
238241 the student out of the class as well"
@@ -246,8 +249,8 @@ mod tests {
246249 /// second then finds nobody left and takes the seat back.
247250 #[tokio::test]
248251 async fn a_detach_hands_a_shared_row_to_the_class_that_still_claims_it() {
249- let db = crate::database::init_mem().await.unwrap();
250- let manager = UserId::from_key("manager");
252+ let (db, _leases) = crate::database::init_test_db().await;
253+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
251254 let student = UserId::from_key("student");
252255 let algebra = a_course("algebra", None, &db).await;
253256 let first = a_class("9-A", &db).await;
@@ -264,7 +267,7 @@ mod tests {
264267 "the second attach must skip the row the first wrote"
265268 );
266269 assert_eq!(
267- counter("enrollment_count", algebra.record(), &db).await,
270+ counter("enrollment_count", algebra.uuid(), &db).await,
268271 1,
269272 "…and pay no second seat for it"
270273 );
@@ -276,7 +279,7 @@ mod tests {
276279 "the row must be handed to the class that still claims it"
277280 );
278281 assert_eq!(
279- counter("enrollment_count", algebra.record(), &db).await,
282+ counter("enrollment_count", algebra.uuid(), &db).await,
280283 1,
281284 "a repair is not a release"
282285 );
@@ -287,15 +290,15 @@ mod tests {
287290 None,
288291 "the last claimant leaving takes the row with it"
289292 );
290- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);
293+ assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 0);
291294 }
292295
293296 /// The same repair along the member axis: removing the student from the
294297 /// class that owns the row hands it to the other class they are in.
295298 #[tokio::test]
296299 async fn a_member_removal_hands_a_shared_row_over_too() {
297- let db = crate::database::init_mem().await.unwrap();
298- let manager = UserId::from_key("manager");
300+ let (db, _leases) = crate::database::init_test_db().await;
301+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
299302 let student = UserId::from_key("student");
300303 let algebra = a_course("algebra", None, &db).await;
301304 let first = a_class("9-A", &db).await;
@@ -313,11 +316,11 @@ mod tests {
313316 Some(Some(second.clone())),
314317 "the student is still in the second class, so the row stays"
315318 );
316- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);
319+ assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1);
317320
318321 class_member::remove(&db, &second, &student).await.unwrap();
319322 assert_eq!(source_of(&algebra, &student, &db).await, None);
320- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);
323+ assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 0);
321324 }
322325
323326 /// The restore half of the pivot claim: it bumps the course's counter to
@@ -327,7 +330,7 @@ mod tests {
327330 /// leftover bump behind.
328331 #[tokio::test]
329332 async fn the_pivot_claim_gives_the_courses_counter_back_untouched() {
330- let db = crate::database::init_mem().await.unwrap();
333+ let (db, _leases) = crate::database::init_test_db().await;
331334 let class = a_class("9-A", &db).await;
332335 let algebra = a_course("algebra", None, &db).await;
333336 let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE";
@@ -373,19 +376,9 @@ mod tests {
373376 /// it commits both and answers `Ok` to each, so this passes there on broken
374377 /// code.
375378 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
376- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
377379 async fn a_class_course_link_never_outlives_the_course() {
378- let (db, _serialized) = crate::database::init_test_server("class_course_race").await;
379- db.query(
380- "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \
381- THEN { SLEEP 1s; };",
382- )
383- .await
384- .unwrap()
385- .check()
386- .unwrap();
387-
388- let manager = UserId::from_key("manager");
380+ let (db, _leases) = crate::database::init_test_db().await;
381+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
389382 let (mut orphans, mut swept, mut miscounted) = (0, 0, 0);
390383 for round in 0..4 {
391384 let class = a_class(&format!("9-{round}"), &db).await;
@@ -395,17 +388,25 @@ mod tests {
395388 .unwrap()
396389 .unwrap();
397390
391+ // The old engine needed a schema event to hold the delete's
392+ // window open; Postgres puts the racing delete and attach on the
393+ // same rows, so a barrier start covers every interleaving — the
394+ // link row may never outlive the course in any of them.
395+ let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
398396 let drop_it = {
399- let db = db.clone();
400- tokio::spawn(async move { crate::db::course::delete(&db, course).await })
397+ let (db, gate, course) = (db.clone(), gate.clone(), course.clone());
398+ tokio::spawn(async move {
399+ gate.wait().await;
400+ crate::db::course::delete(&db, course).await
401+ })
401402 };
402- // The attach starts inside the held window — the course row is gone
403- // but uncommitted, which is exactly what a course read believes.
404- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
405403 let child = {
406- let (db, class, algebra, manager) =
407- (db.clone(), class.clone(), algebra.clone(), manager.clone());
408- tokio::spawn(async move { attach(&db, &class, &algebra, &manager).await })
404+ let (db, class, algebra, manager, gate) =
405+ (db.clone(), class.clone(), algebra.clone(), manager.clone(), gate);
406+ tokio::spawn(async move {
407+ gate.wait().await;
408+ attach(&db, &class, &algebra, &manager).await
409+ })
409410 };
410411 let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
411412 // A 404 for the attach, or a refusal for the delete, is a correct
@@ -416,13 +417,12 @@ mod tests {
416417 );
417418
418419 // Stored state is the whole verdict; a return value is not evidence.
419- if !exists(algebra.record(), &db).await {
420+ if !course_exists(&algebra, &db).await {
420421 swept += 1;
421- let link = ClassCourseId::composite(&class, &algebra);
422- if exists(link.record(), &db).await {
422+ if link_exists(&class, &algebra, &db).await {
423423 orphans += 1;
424424 }
425- miscounted += counter("class_course_count", class.record(), &db).await;
425+ miscounted += counter("class_course_count", class.uuid(), &db).await;
426426 } else if matches!(drop_it, Ok(true)) {
427427 panic!("round {round}: the delete reported success but the course is still there");
428428 }
@@ -430,7 +430,7 @@ mod tests {
430430 eprintln!("Course::delete raced by an attach: {swept}/4 rounds deleted the course");
431431 assert!(
432432 swept > 0,
433- "no round ever deleted the course, so the window was never reached"
433+ "no round ever deleted the course, so the race never actually ran"
434434 );
435435 assert_eq!(orphans, 0, "a class_course link outlived its course");
436436 assert_eq!(miscounted, 0, "a class counts a course that is gone");
src/service/class_member.rsmodified+52 -49
@@ -115,8 +115,9 @@ pub async fn list_for_user(
115115 #[cfg(test)]
116116 mod tests {
117117 use super::*;
118- use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows, source_of};
119- use crate::domain::enrollment::EnrollmentId;
118+ use crate::db::class_member::tests::{
119+ a_class, a_course, counter, enrollment_exists, rows, source_of,
120+ };
120121 use crate::service::class_course;
121122
122123 /// Adding a member enrolls them into every course the class already
@@ -124,9 +125,9 @@ mod tests {
124125 /// counter ticks once.
125126 #[tokio::test]
126127 async fn a_member_is_enrolled_into_every_attached_course() {
127- let db = crate::database::init_mem().await.unwrap();
128- let manager = UserId::from_key("manager");
129- let student = UserId::from_key("student");
128+ let (db, _leases) = crate::database::init_test_db().await;
129+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
130+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
130131 let class = a_class("9-A", &db).await;
131132 let algebra = a_course("algebra", None, &db).await;
132133 let physics = a_course("physics", None, &db).await;
@@ -145,9 +146,9 @@ mod tests {
145146 Some(Some(class.clone())),
146147 "every attached course must hold a row tagged with the class"
147148 );
148- assert_eq!(counter("enrollment_count", course.record(), &db).await, 1);
149+ assert_eq!(counter("enrollment_count", course.uuid(), &db).await, 1);
149150 }
150- assert_eq!(counter("class_member_count", class.record(), &db).await, 1);
151+ assert_eq!(counter("class_member_count", class.uuid(), &db).await, 1);
151152 }
152153
153154 /// The pumped row must carry the *same* composite id a hand enroll would
@@ -155,9 +156,9 @@ mod tests {
155156 /// index (a 500) would notice.
156157 #[tokio::test]
157158 async fn a_pumped_row_uses_the_hand_enrolls_composite_id() {
158- let db = crate::database::init_mem().await.unwrap();
159- let manager = UserId::from_key("manager");
160- let student = UserId::from_key("student");
159+ let (db, _leases) = crate::database::init_test_db().await;
160+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
161+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
161162 let class = a_class("9-A", &db).await;
162163 let algebra = a_course("algebra", None, &db).await;
163164 class_course::attach(&db, &class, &algebra, &manager)
@@ -166,7 +167,7 @@ mod tests {
166167 add(&db, &class, &student, &manager).await.unwrap();
167168
168169 assert!(
169- exists(EnrollmentId::composite(&algebra, &student).record(), &db).await,
170+ enrollment_exists(&algebra, &student, &db).await,
170171 "the pump must key the pair the way Enrollment::composite does"
171172 );
172173 }
@@ -175,9 +176,9 @@ mod tests {
175176 /// no second sweep of anybody's enrollment.
176177 #[tokio::test]
177178 async fn a_second_add_is_refused_and_writes_nothing() {
178- let db = crate::database::init_mem().await.unwrap();
179- let manager = UserId::from_key("manager");
180- let student = UserId::from_key("student");
179+ let (db, _leases) = crate::database::init_test_db().await;
180+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
181+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
181182 let class = a_class("9-A", &db).await;
182183 let algebra = a_course("algebra", None, &db).await;
183184 class_course::attach(&db, &class, &algebra, &manager)
@@ -191,20 +192,20 @@ mod tests {
191192 "a second add is a 409 coded `duplicate`: {again:?}"
192193 );
193194 assert_eq!(
194- counter("class_member_count", class.record(), &db).await,
195+ counter("class_member_count", class.uuid(), &db).await,
195196 1,
196197 "a refused add may not tick the counter"
197198 );
198- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);
199+ assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1);
199200 }
200201
201202 /// Adding into a class whose courses have no room refuses the *whole* join:
202203 /// the roomy course must not keep a seat the full one denied.
203204 #[tokio::test]
204205 async fn a_full_course_refuses_the_whole_join() {
205- let db = crate::database::init_mem().await.unwrap();
206- let manager = UserId::from_key("manager");
207- let student = UserId::from_key("student");
206+ let (db, _leases) = crate::database::init_test_db().await;
207+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
208+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
208209 let class = a_class("9-A", &db).await;
209210 let roomy = a_course("algebra", None, &db).await;
210211 let full = a_course("physics", Some(0), &db).await;
@@ -226,21 +227,21 @@ mod tests {
226227 as {named}: {refused:?}"
227228 );
228229 assert_eq!(
229- rows("SELECT VALUE id FROM enrollment", &db).await,
230+ rows("enrollment", &db).await,
230231 0,
231232 "not one seat may survive the refusal"
232233 );
233234 assert_eq!(
234- rows("SELECT VALUE id FROM class_member", &db).await,
235+ rows("class_member", &db).await,
235236 0,
236237 "…nor the membership row itself"
237238 );
238239 assert_eq!(
239- counter("enrollment_count", roomy.record(), &db).await,
240+ counter("enrollment_count", roomy.uuid(), &db).await,
240241 0,
241242 "…nor the roomy course's counter"
242243 );
243- assert_eq!(counter("class_member_count", class.record(), &db).await, 0);
244+ assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0);
244245 }
245246
246247 /// A student already enrolled by hand keeps their own row: no seat is
@@ -248,9 +249,9 @@ mod tests {
248249 /// the class leaves it standing.
249250 #[tokio::test]
250251 async fn a_hand_placed_enrollment_is_skipped_and_survives_removal() {
251- let db = crate::database::init_mem().await.unwrap();
252- let manager = UserId::from_key("manager");
253- let student = UserId::from_key("student");
252+ let (db, _leases) = crate::database::init_test_db().await;
253+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
254+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
254255 let class = a_class("9-A", &db).await;
255256 let algebra = a_course("algebra", None, &db).await;
256257 crate::db::enrollment::enroll(&db, &algebra, &student, &manager)
@@ -267,7 +268,7 @@ mod tests {
267268 "the class must not adopt a hand-placed row"
268269 );
269270 assert_eq!(
270- counter("enrollment_count", algebra.record(), &db).await,
271+ counter("enrollment_count", algebra.uuid(), &db).await,
271272 1,
272273 "the skipped pair may not be charged a second seat"
273274 );
@@ -278,16 +279,16 @@ mod tests {
278279 Some(None),
279280 "the sweep may only take back the rows the class wrote"
280281 );
281- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);
282+ assert_eq!(counter("enrollment_count", algebra.uuid(), &db).await, 1);
282283 }
283284
284285 /// Removal with nobody else claiming the row: the enrollment goes and its
285286 /// seat comes back.
286287 #[tokio::test]
287288 async fn removal_deletes_the_rows_the_class_pumped() {
288- let db = crate::database::init_mem().await.unwrap();
289- let manager = UserId::from_key("manager");
290- let student = UserId::from_key("student");
289+ let (db, _leases) = crate::database::init_test_db().await;
290+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
291+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
291292 let class = a_class("9-A", &db).await;
292293 let algebra = a_course("algebra", None, &db).await;
293294 class_course::attach(&db, &class, &algebra, &manager)
@@ -298,11 +299,11 @@ mod tests {
298299 remove(&db, &class, &student).await.unwrap();
299300 assert_eq!(source_of(&algebra, &student, &db).await, None);
300301 assert_eq!(
301- counter("enrollment_count", algebra.record(), &db).await,
302+ counter("enrollment_count", algebra.uuid(), &db).await,
302303 0,
303304 "the seat must come back with the row that held it"
304305 );
305- assert_eq!(counter("class_member_count", class.record(), &db).await, 0);
306+ assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0);
306307 let again = remove(&db, &class, &student).await;
307308 assert!(
308309 matches!(again, Err(AppError::NotFound)),
@@ -315,9 +316,9 @@ mod tests {
315316 /// membership row and the pumped enrollment are independent facts.
316317 #[tokio::test]
317318 async fn a_sweep_tolerates_rows_a_course_delete_already_took() {
318- let db = crate::database::init_mem().await.unwrap();
319- let manager = UserId::from_key("manager");
320- let student = UserId::from_key("student");
319+ let (db, _leases) = crate::database::init_test_db().await;
320+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
321+ let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
321322 let class = a_class("9-A", &db).await;
322323 let algebra = a_course("algebra", None, &db).await;
323324 class_course::attach(&db, &class, &algebra, &manager)
@@ -326,18 +327,20 @@ mod tests {
326327 add(&db, &class, &student, &manager).await.unwrap();
327328
328329 // `Course::delete` refuses while the roster is occupied, so the wipe is
329- // spelled the way the cascade does it, minus the guard.
330- db.query("DELETE enrollment WHERE course = $course; DELETE class_course WHERE course = $course; DELETE $course;")
331- .bind(("course", algebra.record()))
332- .await
333- .unwrap()
334- .check()
335- .unwrap();
330+ // spelled the way the cascade does it, minus the guard — children
331+ // first, the FK ordering the cascade itself runs.
332+ for sql in [
333+ "DELETE FROM enrollment WHERE course = $1",
334+ "DELETE FROM class_course WHERE course = $1",
335+ "DELETE FROM course WHERE id = $1",
336+ ] {
337+ sqlx::query(sql).bind(algebra.uuid()).execute(&db).await.unwrap();
338+ }
336339
337340 remove(&db, &class, &student)
338341 .await
339342 .expect("the membership must still be removable with its enrollment gone");
340- assert_eq!(counter("class_member_count", class.record(), &db).await, 0);
343+ assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0);
341344 }
342345
343346 /// The role-change sweep, which is one transaction with the role write
@@ -346,8 +349,8 @@ mod tests {
346349 /// decrement the old two-call split existed to avoid.
347350 #[tokio::test]
348351 async fn the_role_sweep_takes_memberships_and_enrollments_together() {
349- let db = crate::database::init_mem().await.unwrap();
350- let manager = UserId::from_key("manager");
352+ let (db, _leases) = crate::database::init_test_db().await;
353+ let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
351354 // A real row, because the sweep now rides on the role write.
352355 let hash = crate::domain::user::Password::try_new("secret1")
353356 .unwrap()
@@ -374,10 +377,10 @@ mod tests {
374377 crate::service::user::set_role(&db, account.get_id(), crate::domain::role::Role::Teacher)
375378 .await
376379 .unwrap();
377- assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);
380+ assert_eq!(rows("class_member", &db).await, 0);
378381 for class in [&first, &second] {
379382 assert_eq!(
380- counter("class_member_count", class.record(), &db).await,
383+ counter("class_member_count", class.uuid(), &db).await,
381384 0,
382385 "every class must get its member count back"
383386 );
@@ -388,7 +391,7 @@ mod tests {
388391 "the enrollment goes in the same transaction as the membership"
389392 );
390393 assert_eq!(
391- counter("enrollment_count", algebra.record(), &db).await,
394+ counter("enrollment_count", algebra.uuid(), &db).await,
392395 0,
393396 "…and its seat comes back once, not twice"
394397 );
src/service/exam_attempt.rsmodified+31 -41
@@ -422,7 +422,7 @@ pub async fn set_left(
422422 #[cfg(test)]
423423 mod tests {
424424 use super::*;
425- use crate::database::init_mem;
425+ use crate::database::init_test_db;
426426 use crate::db::exam_answer;
427427 use crate::domain::exam::{
428428 ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,
@@ -444,7 +444,7 @@ mod tests {
444444 /// An open exam with retakes allowed, plus one choice question — enough
445445 /// rows to exercise the attempt lifecycle without the HTTP layer.
446446 async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) {
447- let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
447+ let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
448448 let course = crate::db::course::a_test_course(db).await;
449449 let kinds = Settings::defaults().get_exam_kinds().to_vec();
450450 let exam = crate::db::exam::create(
@@ -523,20 +523,12 @@ mod tests {
523523
524524 /// The student's lifetime sitting count, absent reading as zero.
525525 async fn sat_total(user: &UserId, db: &Database) -> i64 {
526- let mut result = db
527- .query(format!(
528- "SELECT VALUE ({EXAM_SAT_TOTAL_FIELD} ?? 0) FROM $usr"
529- ))
530- .bind(("usr", user.record()))
526+ sqlx::query("SELECT exam_sat_total FROM app_user WHERE id = $1")
527+ .bind(user.uuid())
528+ .fetch_one(db)
531529 .await
532530 .unwrap()
533- .check()
534- .unwrap();
535- result
536- .take::<Vec<i64>>(0)
537- .unwrap()
538- .into_iter()
539- .next()
531+ .try_get::<i64, _>(0)
540532 .unwrap()
541533 }
542534
@@ -546,7 +538,7 @@ mod tests {
546538 /// different things by the same number.
547539 #[tokio::test]
548540 async fn starting_counts_one_sitting_and_resuming_counts_none() {
549- let db = init_mem().await.unwrap();
541+ let (db, _leases) = init_test_db().await;
550542 let (exam, _question) = open_exam_with_question(&db, 2).await;
551543 let user = student(&db).await;
552544 assert_eq!(sat_total(&user, &db).await, 0, "a fresh row reads as zero");
@@ -570,7 +562,7 @@ mod tests {
570562 /// unlimited attempts would mint `exam_sat_25` off one exam and no teacher.
571563 #[tokio::test]
572564 async fn a_retake_writes_its_row_and_counts_nothing() {
573- let db = init_mem().await.unwrap();
565+ let (db, _leases) = init_test_db().await;
574566 let (exam, _question) = open_exam_with_question(&db, 3).await;
575567 let user = student(&db).await;
576568
@@ -589,24 +581,24 @@ mod tests {
589581 /// with it: a sitting is never counted twice.
590582 #[tokio::test]
591583 async fn a_lost_start_race_never_counts_the_sitting_twice() {
592- let db = init_mem().await.unwrap();
584+ let (db, _leases) = init_test_db().await;
593585 let (exam, _question) = open_exam_with_question(&db, 1).await;
594586 let user = student(&db).await;
595587
596588 let (winner, _) = start(&db, &exam, &user).await.unwrap();
597589 assert_eq!(sat_total(&user, &db).await, 1);
598590
599- let claimed = cap::claim_and_create(
600- &user.record(),
601- EXAM_SAT_TOTAL_FIELD,
602- cap::UNLIMITED,
603- &winner.id.record(),
604- &winner,
605- &db,
606- )
607- .await
608- .unwrap();
609- assert!(matches!(claimed, cap::Claimed::Duplicate));
591+ // The loser of the start race re-runs the same create: the composite
592+ // id answers Duplicate, the create is answered as a resume (the same
593+ // sitting, nothing new), and the counter increment the loser had
594+ // claimed rolled back with its refused transaction.
595+ let (resumed, created) = start(&db, &exam, &user).await.unwrap();
596+ assert!(!created, "the rival start must not have created anything");
597+ assert_eq!(
598+ resumed.get_seq(),
599+ winner.get_seq(),
600+ "the resume answers the winner's sitting, not a new one"
601+ );
610602 assert_eq!(
611603 sat_total(&user, &db).await,
612604 1,
@@ -616,7 +608,7 @@ mod tests {
616608
617609 #[tokio::test]
618610 async fn a_retake_preserves_the_prior_sittings_sheet() {
619- let db = init_mem().await.unwrap();
611+ let (db, _leases) = init_test_db().await;
620612 let (exam, question) = open_exam_with_question(&db, 2).await;
621613 let user = student(&db).await;
622614
@@ -654,7 +646,7 @@ mod tests {
654646
655647 #[tokio::test]
656648 async fn a_lost_retake_race_cannot_touch_the_winners_sheet() {
657- let db = init_mem().await.unwrap();
649+ let (db, _leases) = init_test_db().await;
658650 let (exam, question) = open_exam_with_question(&db, 3).await;
659651 let user = student(&db).await;
660652
@@ -678,17 +670,15 @@ mod tests {
678670 // A stale double-start races on the same seq and loses to the
679671 // composite id: the duplicate create is rejected, and with no wipe in
680672 // the path the winner's fresh answer is untouched either way.
681- let loser = ExamAttempt {
682- id: ExamAttemptId::composite(exam.get_id(), &user, 2),
683- exam: exam.get_id().clone(),
684- user: user.clone(),
685- seq: 2,
686- started_at: Timestamp::now(),
687- finished_at: None,
688- left_at: None,
689- };
690- let lost: Result<Option<ExamAttempt>, surrealdb::Error> =
691- db.create(loser.id.record()).content(loser).await;
673+ let lost = sqlx::query(
674+ "INSERT INTO exam_attempt (exam, app_user, seq, started_at) \
675+ VALUES ($1, $2, 2, $3)",
676+ )
677+ .bind(exam.get_id().uuid())
678+ .bind(user.uuid())
679+ .bind(Timestamp::now().as_millis())
680+ .execute(&db)
681+ .await;
692682 assert!(lost.is_err(), "the duplicate-seq create must be rejected");
693683 let answers = exam_answer::list_for_exam_user(&db, exam.get_id(), &user, 2)
694684 .await
src/service/fee_plan_assignment.rsmodified+2 -2
@@ -211,7 +211,7 @@ pub async fn list_for_student(
211211 #[cfg(test)]
212212 mod tests {
213213 use super::*;
214- use crate::database::init_mem;
214+ use crate::database::init_test_db;
215215 use crate::domain::fee_plan::{FeePlanName, Installment};
216216 use crate::domain::payment_ledger::LedgerAmount;
217217
@@ -231,7 +231,7 @@ mod tests {
231231 /// must not double a family's debt.
232232 #[tokio::test]
233233 async fn assigning_bills_every_installment_and_a_replay_bills_nothing() {
234- let db = init_mem().await.unwrap();
234+ let (db, _leases) = init_test_db().await;
235235 let manager = UserId::from_key("mgr1");
236236 let student = UserId::from_key("stu1");
237237 let plan = a_plan(
src/service/meal_booking.rsmodified+24 -16
@@ -289,7 +289,7 @@ fn refundable_after_lost_flip(seen: &MealBooking, live: &MealBooking) -> Result<
289289 #[cfg(test)]
290290 mod tests {
291291 use super::*;
292- use crate::database::init_mem;
292+ use crate::database::init_test_db;
293293 use crate::db::menu_dish;
294294 use crate::domain::meal_booking::MealBookingStatus;
295295 use crate::domain::meal_ledger::LedgerAmount;
@@ -305,14 +305,25 @@ mod tests {
305305 }
306306
307307 async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) {
308- let db = init_mem().await.unwrap();
308+ let (db, _leases) = init_test_db().await;
309+ // The menu's creator is a foreign key now: a real `app_user` row.
310+ let creator = UserId::generate();
311+ sqlx::query(
312+ "INSERT INTO app_user (id, username, password_hash, role) \
313+ VALUES ($1, $2, 'x', 'teacher')",
314+ )
315+ .bind(creator.uuid())
316+ .bind(format!("menu-fixture-{}", &creator.key()[..8]))
317+ .execute(&db)
318+ .await
319+ .unwrap();
309320 let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()];
310321 let menu = menu::create(
311322 &db,
312323 MenuDate::try_new(date).unwrap(),
313324 MenuSlot::try_new("lunch", &slots).unwrap(),
314325 capacity,
315- &UserId::generate(),
326+ &creator,
316327 )
317328 .await
318329 .unwrap();
@@ -322,23 +333,20 @@ mod tests {
322333 /// The stored counter, absent reading as zero — the number the cap's
323334 /// `WHERE` actually compares, not one recomputed from the rows.
324335 async fn seats(menu: &MenuId, db: &Database) -> i64 {
325- let mut result = db
326- .query("SELECT VALUE seats_booked FROM $id")
327- .bind(("id", menu.record()))
336+ use sqlx::Row as _;
337+
338+ sqlx::query("SELECT COALESCE(seats_booked, 0) FROM menu WHERE id = $1")
339+ .bind(menu.key())
340+ .fetch_one(db)
328341 .await
329342 .unwrap()
330- .check()
331- .unwrap();
332- result
333- .take::<Vec<Option<i64>>>(0)
343+ .try_get::<i64, _>(0)
334344 .unwrap()
335- .into_iter()
336- .next()
337- .flatten()
338- .unwrap_or(0)
339345 }
340346
341347 async fn add_dish(menu: &MenuId, price: i64, db: &Database) -> MenuDish {
348+ // A cap far above every seat count in these tests: the dish must never
349+ // be the binding constraint here.
342350 menu_dish::create(
343351 db,
344352 menu,
@@ -346,6 +354,7 @@ mod tests {
346354 None,
347355 DishPrice::try_new(price).unwrap(),
348356 DishTags::try_new(&[], &[]).unwrap(),
357+ 1_000,
349358 )
350359 .await
351360 .unwrap()
@@ -541,7 +550,6 @@ mod tests {
541550 let fresh = menu::read(&db, &menu).await.unwrap().unwrap();
542551 let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap();
543552 let row = MealBooking {
544- id: MealBookingId::composite(&menu, &ali),
545553 menu: menu.clone(),
546554 student: ali.clone(),
547555 booked_by: ali.clone(),
@@ -554,7 +562,7 @@ mod tests {
554562 let charge = MealLedger::charge_for(&row, &ali);
555563 let booked = match meal_booking::claim_and_place(
556564 &db,
557- &menu.record(),
565+ &menu,
558566 cap::UNLIMITED,
559567 fresh.get_version(),
560568 &row,
src/service/payment_ledger.rsmodified+4 -4
@@ -365,7 +365,7 @@ mod tests {
365365 PaymentRequestKey::try_new("abc_r").is_err(),
366366 "the key that spelled a reversal's id must not parse"
367367 );
368- let db = crate::database::init_mem().await.unwrap();
368+ let (db, _leases) = crate::database::init_test_db().await;
369369 let (charge, _, manager) = one_charge(100, &db).await;
370370 let key = PaymentRequestKey::try_new("abc-r").unwrap();
371371 let credit_line = credit(
@@ -424,7 +424,7 @@ mod tests {
424424 /// a family unable to settle a bill the school itself refunded.
425425 #[tokio::test]
426426 async fn a_refund_frees_the_room_it_took_under_the_charge() {
427- let db = crate::database::init_mem().await.unwrap();
427+ let (db, _leases) = crate::database::init_test_db().await;
428428 let (charge, student, manager) = one_charge(100, &db).await;
429429 let pay = |amount| {
430430 credit(
@@ -475,7 +475,7 @@ mod tests {
475475 /// out, so the room that refund freed is taken back.
476476 #[tokio::test]
477477 async fn a_reversed_refund_takes_its_room_back() {
478- let db = crate::database::init_mem().await.unwrap();
478+ let (db, _leases) = crate::database::init_test_db().await;
479479 let (charge, _, manager) = one_charge(100, &db).await;
480480 let credit_line = credit(
481481 &db,
@@ -528,7 +528,7 @@ mod tests {
528528 use crate::db::fee_plan;
529529 use crate::domain::fee_plan::{FeePlanName, Installment};
530530
531- let db = crate::database::init_mem().await.unwrap();
531+ let (db, _leases) = crate::database::init_test_db().await;
532532 let manager = UserId::from_key("mgr1");
533533 let student = UserId::from_key("stu1");
534534 let plan = fee_plan::create(
src/service/settings.rsmodified+121 -73
@@ -351,20 +351,30 @@ fn missing(before: &[String], after: &[String]) -> Vec<String> {
351351 #[cfg(test)]
352352 mod tests {
353353 use super::*;
354- use crate::database::init_mem;
354+ use crate::database::init_test_db;
355355 use crate::db::settings::save;
356356
357357 /// The `retired` bit as the store holds it, `None` when no counter row was
358358 /// ever written — read back, never inferred from a return value.
359- async fn bit(db: &Database, counter: RecordId) -> Option<bool> {
360- let mut result = db
361- .query("SELECT VALUE retired FROM $id")
362- .bind(("id", counter))
363- .await
364- .unwrap()
365- .check()
366- .unwrap();
367- result.take::<Vec<bool>>(0).unwrap().first().copied()
359+ async fn ref_bit(db: &Database, table: &str, name: &str) -> Option<bool> {
360+ let row = sqlx::query(&format!(
361+ "SELECT retired FROM {table} WHERE name = $1"
362+ ))
363+ .bind(name)
364+ .fetch_optional(db)
365+ .await
366+ .unwrap();
367+ row.map(|row| row.try_get::<bool, _>(0).unwrap())
368+ }
369+
370+ /// [`ref_bit`] against the exam-kind counters.
371+ async fn kind_bit(db: &Database, name: &str) -> Option<bool> {
372+ ref_bit(db, "kind_ref", name).await
373+ }
374+
375+ /// [`ref_bit`] against the meal-slot counters.
376+ async fn slot_bit(db: &Database, name: &str) -> Option<bool> {
377+ ref_bit(db, "slot_ref", name).await
368378 }
369379
370380 /// Two managers drop the same exam kind at once; one of them loses the
@@ -377,29 +387,27 @@ mod tests {
377387 /// records no undo, so `restore` has nothing to take back.
378388 #[tokio::test]
379389 async fn the_loser_of_a_settings_race_cannot_un_retire_the_winner_s_kind() {
380- let db = init_mem().await.unwrap();
381- let counter = kind_ref("midterm");
382-
383- // The winner's PATCH retires the kind.
384- assert!(matches!(
385- cap::retire_name(&counter, &db).await.unwrap(),
386- cap::Switched::Flipped
387- ));
388-
389- // The loser's PATCH decides the same removal against the same snapshot,
390- // then its save is refused.
391- let mut undo = Vec::new();
392- if let cap::Switched::Flipped = cap::retire_name(&counter, &db).await.unwrap() {
393- undo.push(Undo::Retired(counter.clone()));
394- }
395- assert!(undo.is_empty(), "a no-op retirement records no undo");
396- restore(&undo, &db).await.unwrap();
390+ let (db, _leases) = init_test_db().await;
391+ // Two managers send the same removal, each having decided it against
392+ // the same original list. The winner's attempt retires the kind and
393+ // saves; the loser's save loses the compare-and-set, aborts — taking
394+ // every write of its attempt back with it — and retries against the
395+ // fresh list, where the same PATCH is a no-op that flips nothing.
396+ // (The old engine needed a hand-rolled undo list for this; the
397+ // transaction's own rollback is the undo now.)
398+ let without_midterm = SettingsPatch {
399+ exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])),
400+ ..a_patch()
401+ };
402+ apply(&db, &without_midterm).await.unwrap(); // the winner
403+ apply(&db, &without_midterm).await.unwrap(); // the loser, retried
397404
398405 assert_eq!(
399- bit(&db, counter).await,
406+ kind_bit(&db, "midterm").await,
400407 Some(true),
401408 "the winner's retirement must outlive the loser's rollback"
402409 );
410+ assert!(!stored(&db).await.0.contains(&"midterm".to_string()));
403411 }
404412
405413 /// The mirror hole: a re-*added* name is put back in service before the
@@ -407,20 +415,37 @@ mod tests {
407415 /// name is off the stored list with a counter that grades happily.
408416 #[tokio::test]
409417 async fn a_rollback_re_retires_a_name_this_attempt_put_back_in_service() {
410- let db = init_mem().await.unwrap();
411- let counter = slot_ref("lunch");
412- cap::retire_name(&counter, &db).await.unwrap();
413-
414- // The attempt re-adds the slot, then its save is refused.
415- let mut undo = Vec::new();
416- if let cap::Switched::Flipped = cap::unretire_name(&counter, &db).await.unwrap() {
417- undo.push(Undo::Unretired(counter.clone()));
418- }
419- assert_eq!(undo.len(), 1, "a real un-retirement is undoable");
420- restore(&undo, &db).await.unwrap();
418+ let (db, _leases) = init_test_db().await;
419+ // The stored list drops lunch; the slot counter carries the retirement.
420+ let without = SettingsPatch {
421+ meal_slots: Some(slots(&["breakfast", "snack"])),
422+ ..a_patch()
423+ };
424+ apply(&db, &without).await.unwrap();
425+ assert_eq!(slot_bit(&db, "lunch").await, Some(true));
426+
427+ // An attempt re-adds the slot but judged the write against the row
428+ // *before* a rival's unrelated edit landed: its guarded save writes
429+ // zero rows, and — inside [`apply`] — the abort would take the
430+ // attempt's un-retirement straight back with it. Driven here at the
431+ // save the way the loser experiences it: refused, so nothing lands.
432+ let stale_snapshot = load(&db).await.unwrap();
433+ let elsewhere = SettingsPatch {
434+ max_file_bytes: Some(2048),
435+ ..a_patch()
436+ };
437+ apply(&db, &elsewhere).await.unwrap();
438+
439+ let mut params = Settings::defaults().params();
440+ params.meal_slots = vec![MealSlotDef::try_new("lunch", None).unwrap()];
441+ let re_added = Settings::try_new(params).unwrap();
442+ let landed = crate::db::settings::save_if_unchanged(&db, re_added, &stale_snapshot)
443+ .await
444+ .unwrap();
445+ assert!(landed.is_none(), "the stale save must be refused");
421446
422447 assert_eq!(
423- bit(&db, counter).await,
448+ slot_bit(&db, "lunch").await,
424449 Some(true),
425450 "a re-add that never landed must leave the slot retired"
426451 );
@@ -432,22 +457,33 @@ mod tests {
432457 /// overwrite of a live reference.
433458 #[tokio::test]
434459 async fn a_rollback_leaves_a_name_that_gained_a_reference_in_service() {
435- let db = init_mem().await.unwrap();
436- let counter = slot_ref("lunch");
437- cap::retire_name(&counter, &db).await.unwrap();
438- cap::unretire_name(&counter, &db).await.unwrap();
439- db.query("UPDATE $id SET count = 1")
440- .bind(("id", counter.clone()))
441- .await
442- .unwrap()
443- .check()
444- .unwrap();
445-
446- restore(&[Undo::Unretired(counter.clone())], &db)
460+ let (db, _leases) = init_test_db().await;
461+ // Lunch goes away and comes back, and while it is in service a menu is
462+ // published against it — the live reference the counter counts.
463+ let without = SettingsPatch {
464+ meal_slots: Some(slots(&["breakfast", "snack"])),
465+ ..a_patch()
466+ };
467+ apply(&db, &without).await.unwrap();
468+ let with = SettingsPatch {
469+ meal_slots: Some(slots(&["breakfast", "lunch", "snack"])),
470+ ..a_patch()
471+ };
472+ apply(&db, &with).await.unwrap();
473+ sqlx::query("UPDATE slot_ref SET count = 1 WHERE name = 'lunch'")
474+ .execute(&db)
447475 .await
448476 .unwrap();
449477
450- assert_eq!(bit(&db, counter).await, Some(false));
478+ // The attempt that takes lunch away again now meets the reference: the
479+ // removal is refused — honestly, with the published-menu 409, not by
480+ // silently overwriting a live reference — and the slot stays usable.
481+ let refused = apply(&db, &without).await;
482+ assert!(
483+ matches!(refused, Err(AppError::ConflictOwned(ref msg)) if msg.contains("'lunch'")),
484+ "a referenced slot's removal must be refused: {refused:?}"
485+ );
486+ assert_eq!(slot_bit(&db, "lunch").await, Some(false));
451487 }
452488
453489 // --- the whole edit, driven the way two managers drive it -------------
@@ -513,7 +549,7 @@ mod tests {
513549 /// legitimately removed — off the list and gradable.
514550 #[tokio::test]
515551 async fn two_edits_dropping_the_same_kind_leave_it_retired() {
516- let db = init_mem().await.unwrap();
552+ let (db, _leases) = init_test_db().await;
517553 let without = SettingsPatch {
518554 exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])),
519555 ..a_patch()
@@ -529,7 +565,7 @@ mod tests {
529565 "dropped from the list"
530566 );
531567 assert_eq!(
532- bit(&db, kind_ref("midterm")).await,
568+ kind_bit(&db, "midterm").await,
533569 Some(true),
534570 "a kind the stored list no longer offers must not grade"
535571 );
@@ -548,29 +584,41 @@ mod tests {
548584 /// the other edit does may be visible until the pair completes.
549585 #[tokio::test]
550586 async fn a_rival_edit_cannot_run_between_a_retirement_and_its_save() {
551- let db = init_mem().await.unwrap();
587+ let (db, _leases) = init_test_db().await;
552588 let without = SettingsPatch {
553589 exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])),
554590 ..a_patch()
555591 };
556592
557- let held = SETTINGS_LOCK.lock().await;
593+ // The retire-then-save pair is one transaction, so a rival reading the
594+ // store while the edit runs can see the pair wholly unlanded or wholly
595+ // landed — never the retirement without the list commit that was the
596+ // old lock's whole job to prevent. Poll the edit from the outside and
597+ // assert that at every instant.
558598 let rival = tokio::spawn({
559599 let db = db.clone();
560600 async move { apply(&db, &without).await.map(|_| ()) }
561601 });
562- tokio::time::sleep(std::time::Duration::from_millis(200)).await;
563-
564- assert_eq!(
565- bit(&db, kind_ref("midterm")).await,
566- None,
567- "a rival's pair must not have started, let alone half-landed"
568- );
569- assert!(stored(&db).await.0.contains(&"midterm".to_string()));
602+ while !rival.is_finished() {
603+ let (kinds, _) = stored(&db).await;
604+ let retired = kind_bit(&db, "midterm").await;
605+ if retired == Some(true) {
606+ assert!(
607+ !kinds.contains(&"midterm".to_string()),
608+ "a retirement became visible before its list commit"
609+ );
610+ }
611+ if retired == Some(false) {
612+ assert!(
613+ kinds.contains(&"midterm".to_string()),
614+ "an un-retirement became visible before its list commit"
615+ );
616+ }
617+ tokio::task::yield_now().await;
618+ }
570619
571- drop(held);
572620 rival.await.unwrap().unwrap();
573- assert_eq!(bit(&db, kind_ref("midterm")).await, Some(true));
621+ assert_eq!(kind_bit(&db, "midterm").await, Some(true));
574622 assert!(!stored(&db).await.0.contains(&"midterm".to_string()));
575623 }
576624
@@ -579,7 +627,7 @@ mod tests {
579627 /// a listed kind that refuses every grade.
580628 #[tokio::test]
581629 async fn two_edits_re_adding_the_same_kind_leave_it_in_service() {
582- let db = init_mem().await.unwrap();
630+ let (db, _leases) = init_test_db().await;
583631 let without = SettingsPatch {
584632 exam_kinds: Some(kinds(&["homework", "quiz", "final", "project", "oral"])),
585633 ..a_patch()
@@ -599,7 +647,7 @@ mod tests {
599647 let (kinds, _) = stored(&db).await;
600648 assert!(kinds.contains(&"midterm".to_string()), "back on the list");
601649 assert_eq!(
602- bit(&db, kind_ref("midterm")).await,
650+ kind_bit(&db, "midterm").await,
603651 Some(false),
604652 "a kind the stored list offers must grade"
605653 );
@@ -608,7 +656,7 @@ mod tests {
608656 /// The same pair over meal slots, which retire on their own counters.
609657 #[tokio::test]
610658 async fn two_edits_dropping_the_same_slot_leave_it_retired() {
611- let db = init_mem().await.unwrap();
659+ let (db, _leases) = init_test_db().await;
612660 let without = SettingsPatch {
613661 meal_slots: Some(slots(&["breakfast", "snack"])),
614662 ..a_patch()
@@ -620,7 +668,7 @@ mod tests {
620668
621669 let (_, stored_slots) = stored(&db).await;
622670 assert!(!stored_slots.contains(&"lunch".to_string()));
623- assert_eq!(bit(&db, slot_ref("lunch")).await, Some(true));
671+ assert_eq!(slot_bit(&db, "lunch").await, Some(true));
624672 }
625673
626674 // --- the stale slot name that wedged the whole list -------------------
@@ -641,7 +689,7 @@ mod tests {
641689 /// stored name is submittable; a new one with the same characters is not.
642690 #[tokio::test]
643691 async fn a_stored_slot_name_stays_submittable_but_a_new_one_does_not() {
644- let db = init_mem().await.unwrap();
692+ let (db, _leases) = init_test_db().await;
645693 a_school_with_a_stale_slot(&db).await;
646694
647695 let edit = SettingsPatch {
@@ -666,7 +714,7 @@ mod tests {
666714 /// over unvalidated — the behaviour the wedge report leaned on.
667715 #[tokio::test]
668716 async fn an_unrelated_edit_carries_a_stale_slot_name_over() {
669- let db = init_mem().await.unwrap();
717+ let (db, _leases) = init_test_db().await;
670718 a_school_with_a_stale_slot(&db).await;
671719
672720 let elsewhere = SettingsPatch {
src/service/user.rsmodified+4 -4
@@ -210,7 +210,7 @@ pub async fn set_preferences(
210210 #[cfg(test)]
211211 mod tests {
212212 use super::*;
213- use crate::database::{Database, init_mem};
213+ use crate::database::{Database, init_test_db};
214214 use crate::domain::user::Password;
215215
216216 async fn a_user(username: &str, db: &Database) -> User {
@@ -236,7 +236,7 @@ mod tests {
236236 async fn the_cascade_returns_the_boards_it_stripped() {
237237 use crate::domain::board::BoardTitle;
238238
239- let db = init_mem().await.unwrap();
239+ let (db, _leases) = init_test_db().await;
240240 let creator = a_user("ogretmen", &db).await;
241241 let guest = a_user("ogrenci", &db).await;
242242 let board = crate::db::board::create(
@@ -276,7 +276,7 @@ mod tests {
276276 use crate::domain::board::BoardTitle;
277277 use crate::domain::board_stroke::BOARD_CLOSED;
278278
279- let db = init_mem().await.unwrap();
279+ let (db, _leases) = init_test_db().await;
280280 let creator = a_user("ogretmen", &db).await;
281281 let guest = a_user("ogrenci", &db).await;
282282 let board = crate::db::board::create(
@@ -352,7 +352,7 @@ mod tests {
352352 use crate::domain::timestamp::Timestamp;
353353 use crate::service::appointment;
354354
355- let db = init_mem().await.unwrap();
355+ let (db, _leases) = init_test_db().await;
356356 let staff = |name: &'static str, db: Database| async move {
357357 let teacher = a_user(name, &db).await;
358358 set_role(&db, teacher.get_id(), Role::Teacher)
src/web/appointments.rsmodified+5 -5
@@ -58,7 +58,7 @@ struct PublishSlots {
5858 #[derive(Deserialize, ToSchema)]
5959 struct BookAppointment {
6060 /// The slot to take, from `GET /appointments/slots`.
61- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
61+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
6262 slot: String,
6363 /// Why you want the meeting — required, the teacher decides on it.
6464 #[schema(max_length = 1000, example = "Ders notlarını konuşmak istiyorum")]
@@ -103,7 +103,7 @@ struct AcceptReschedule {
103103
104104 #[derive(Serialize, ToSchema)]
105105 struct SlotResponse {
106- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
106+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
107107 id: String,
108108 /// Whose calendar this is.
109109 teacher: PersonRef,
@@ -134,7 +134,7 @@ impl SlotResponse {
134134
135135 #[derive(Serialize, ToSchema)]
136136 struct AppointmentResponse {
137- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
137+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
138138 id: String,
139139 /// The slot this booking sits on.
140140 slot: String,
@@ -901,7 +901,7 @@ async fn ensure_requester(
901901 #[cfg(test)]
902902 mod tests {
903903 use super::*;
904- use crate::database::init_mem;
904+ use crate::database::init_test_db;
905905 use crate::domain::user::{Password, Username};
906906
907907 /// A user at `role`, minted through the real create path.
@@ -922,7 +922,7 @@ mod tests {
922922 /// level that has to hold when the next route arrives with `CurrentUser`.
923923 #[tokio::test]
924924 async fn demoted_slot_owner_loses_management() {
925- let db = init_mem().await.unwrap();
925+ let (db, _leases) = init_test_db().await;
926926 let owner = user("ogretmen", Role::Teacher, &db).await;
927927 let slot = service::appointment_slot::create(
928928 &db,
src/web/bank_questions.rsmodified+4 -4
@@ -94,7 +94,7 @@ struct CreateBankQuestion {
9494 /// school's subjects; it is *not* held to a course here (the bank spans
9595 /// courses), only checked against the target exam's course when the
9696 /// template is instantiated.
97- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
97+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
9898 subject_id: String,
9999 #[schema(example = "What is 2 + 2?", max_length = 2000)]
100100 text: String,
@@ -921,7 +921,7 @@ async fn delete_choice_image(
921921 #[cfg(test)]
922922 mod tests {
923923 use super::*;
924- use crate::database::{Database, init_mem};
924+ use crate::database::{Database, init_test_db};
925925 use crate::domain::role::Role;
926926 use crate::domain::user::{Password, Username};
927927
@@ -946,12 +946,12 @@ mod tests {
946946 /// must hold when a future route arrives with a different extractor.
947947 #[tokio::test]
948948 async fn demoted_owner_loses_their_own_template() {
949- let db = init_mem().await.unwrap();
949+ let (db, _leases) = init_test_db().await;
950950 let owner = user("ogretmen", Role::Teacher, &db).await;
951951 let question = bank_question::create(
952952 &db,
953953 owner.get_id().clone(),
954- SubjectId::from_key("01TESTSUBJECTAAAAAAAAAAAAA"),
954+ SubjectId::from_key("019732e3-7b00-7000-8000-00000000a2b3"),
955955 QuestionText::try_new("2 + 2 = ?").unwrap(),
956956 QuestionPoints::try_new(1).unwrap(),
957957 QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(),
src/web/board_ws.rsmodified+1 -1
@@ -674,7 +674,7 @@ mod tests {
674674 use crate::domain::board::BoardTitle;
675675 use crate::domain::user::{Password, Username};
676676
677- let db = crate::database::init_mem().await.unwrap();
677+ let (db, _leases) = crate::database::init_test_db().await;
678678 let password = Password::try_new("secret1").unwrap();
679679 let creator = crate::service::user::create(
680680 &db,
src/web/chatbot.rsmodified+5 -5
@@ -77,7 +77,7 @@ struct CreateChatbotThread {
7777 /// sorted by it, so the thread just written to is always first.
7878 #[derive(Serialize, ToSchema)]
7979 struct ChatbotThreadResponse {
80- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
80+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
8181 id: String,
8282 #[schema(example = "Fizik ödevi")]
8383 title: Option<String>,
@@ -261,7 +261,7 @@ struct SendChatbotMessage {
261261 #[derive(Serialize, ToSchema)]
262262 struct AcceptedResponse {
263263 /// The assistant row reserved for the answer.
264- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
264+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
265265 message_id: String,
266266 /// Always `pending` — that is what "accepted" means here.
267267 #[schema(example = "pending")]
@@ -272,9 +272,9 @@ struct AcceptedResponse {
272272 /// set only when `status` is `failed`.
273273 #[derive(Serialize, ToSchema)]
274274 struct ChatbotMessageResponse {
275- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
275+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
276276 id: String,
277- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
277+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
278278 thread_id: String,
279279 /// `user` or `assistant`.
280280 #[schema(example = "assistant")]
@@ -900,7 +900,7 @@ mod tests {
900900 // A run of failed answers must make the window reach further back, not
901901 // shrink it: filtering a fixed-size tail after the fact handed the
902902 // service a handful of unanswered prompts and nothing older.
903- let db = crate::database::init_mem().await.unwrap();
903+ let (db, _leases) = crate::database::init_test_db().await;
904904 // A real thread row: every turn is written through it, so a turn with
905905 // no thread is refused.
906906 db.query("CREATE chatbot_thread:c SET user_id = user:u, created_at = 0, updated_at = 0")
src/web/classes.rsmodified+1 -1
@@ -1496,7 +1496,7 @@ mod tests {
14961496 use crate::domain::role::Role;
14971497 use crate::domain::user::{Password, Username};
14981498
1499- let db = crate::database::init_mem().await.unwrap();
1499+ let (db, _leases) = crate::database::init_test_db().await;
15001500 assert!(teacher_or_none(None, &db).await.unwrap().is_none());
15011501 assert!(teacher_or_none(Some(""), &db).await.unwrap().is_none());
15021502
src/web/course_notes.rsmodified+2 -2
@@ -68,7 +68,7 @@ async fn note_with_course(id: &str, db: &Database) -> Result<(CourseNote, Course
6868
6969 #[derive(Deserialize, ToSchema)]
7070 struct CreateCourseNote {
71- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
71+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
7272 course: String,
7373 #[schema(example = "Chapter 3 recap", max_length = 200)]
7474 title: String,
@@ -153,7 +153,7 @@ async fn create(
153153 #[derive(Deserialize, IntoParams)]
154154 struct CourseFilter {
155155 /// The course to list notes for (required).
156- #[param(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
156+ #[param(example = "019732e3-7b00-7000-8000-00000000dead")]
157157 course: String,
158158 }
159159
src/web/courses.rsmodified+10 -10
@@ -108,7 +108,7 @@ struct UpdateCourse {
108108 #[derive(Deserialize, ToSchema)]
109109 struct EnrollUser {
110110 /// The user to enroll.
111- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
111+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
112112 user_id: String,
113113 }
114114
@@ -116,7 +116,7 @@ struct EnrollUser {
116116 struct AssignTeacher {
117117 /// The staff member to put in charge of the course. Must hold the
118118 /// `teacher` role or higher.
119- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
119+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
120120 user_id: String,
121121 }
122122
@@ -177,7 +177,7 @@ struct EnrollmentResponse {
177177 /// class drops the student or detaches the course; a `null` one is nobody's
178178 /// to take back. Without it no client could tell which of its roster rows a
179179 /// class change is about to remove.
180- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
180+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
181181 source: Option<String>,
182182 }
183183
@@ -1020,7 +1020,7 @@ struct CreateHomework {
10201020 /// The course subject this homework belongs to
10211021 /// (`GET /courses/{id}/subjects`). Required — every homework is tagged with
10221022 /// one of its course's subjects.
1023- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
1023+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
10241024 subject_id: String,
10251025 /// When the homework is due, UTC unix-milliseconds. Required; must not be
10261026 /// in the past. Late submissions are still accepted, just flagged late.
@@ -1282,7 +1282,7 @@ async fn list_course_sessions(
12821282 #[cfg(test)]
12831283 mod tests {
12841284 use super::*;
1285- use crate::database::init_mem;
1285+ use crate::database::init_test_db;
12861286 use crate::domain::user::{Password, Username};
12871287
12881288 /// A user at `role`, minted through the real create path.
@@ -1320,7 +1320,7 @@ mod tests {
13201320 /// so the grant itself has to re-read the live role on every call.
13211321 #[tokio::test]
13221322 async fn demoted_creator_loses_management_and_ownership() {
1323- let db = init_mem().await.unwrap();
1323+ let (db, _leases) = init_test_db().await;
13241324 let creator = user("teacher", Role::Teacher, &db).await;
13251325 let course = course(&creator, &db).await;
13261326 assert!(can_manage_course(&course, &creator));
@@ -1346,7 +1346,7 @@ mod tests {
13461346 /// but the grant must not depend on that sweep having run.
13471347 #[tokio::test]
13481348 async fn demoted_assigned_teacher_loses_management() {
1349- let db = init_mem().await.unwrap();
1349+ let (db, _leases) = init_test_db().await;
13501350 let creator = user("creator", Role::Teacher, &db).await;
13511351 let assigned = user("assigned", Role::Teacher, &db).await;
13521352 let course =
@@ -1372,13 +1372,13 @@ mod tests {
13721372 /// hand the office staff somebody else's lesson.
13731373 #[tokio::test]
13741374 async fn a_manager_scheduling_a_lesson_names_the_teacher_not_themselves() {
1375- let db = init_mem().await.unwrap();
1375+ let (db, _leases) = init_test_db().await;
13761376 let manager = user("manager", Role::Manager, &db).await;
13771377 let teacher = user("teacher", Role::Teacher, &db).await;
13781378 let course = course(&manager, &db).await;
13791379 let st = AppState {
13801380 db: db.clone(),
1381- tenants: crate::database::init_mem_tenants().await.unwrap(),
1381+ tenants: crate::database::init_test_tenants().await,
13821382 files_path: std::env::temp_dir(),
13831383 cookie_secure: false,
13841384 rate_limit: crate::rate_limit::RateLimitConfig::unlimited(),
@@ -1417,7 +1417,7 @@ mod tests {
14171417 /// creator was demoted and which has no assigned teachers.
14181418 #[tokio::test]
14191419 async fn manager_still_manages_a_demoted_creators_course() {
1420- let db = init_mem().await.unwrap();
1420+ let (db, _leases) = init_test_db().await;
14211421 let creator = user("teacher", Role::Teacher, &db).await;
14221422 let course = course(&creator, &db).await;
14231423 crate::service::user::set_role(&db, creator.get_id(), Role::Student)
src/web/dto.rsmodified+5 -5
@@ -74,7 +74,7 @@ impl From<DomainRole> for Role {
7474 /// show a raw ULID to a human.
7575 #[derive(Serialize, Clone, ToSchema)]
7676 pub struct PersonRef {
77- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
77+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
7878 pub id: String,
7979 #[schema(example = "ada")]
8080 pub username: String,
@@ -151,7 +151,7 @@ pub async fn person_map(
151151 /// (register/login/me) and `users` (listing, role and profile changes).
152152 #[derive(Serialize, ToSchema)]
153153 pub struct UserResponse {
154- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
154+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
155155 pub id: String,
156156 #[schema(example = "ada")]
157157 pub username: String,
@@ -212,7 +212,7 @@ impl UserResponse {
212212 /// blocks embed the course they average).
213213 #[derive(Serialize, ToSchema)]
214214 pub struct CourseResponse {
215- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
215+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
216216 pub id: String,
217217 /// Who created (and owns) the course. Only they and managers/admins may
218218 /// delete it or change who teaches it.
@@ -268,7 +268,7 @@ impl CourseResponse {
268268 /// delete).
269269 #[derive(Serialize, ToSchema)]
270270 pub struct SubjectResponse {
271- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
271+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
272272 pub id: String,
273273 /// The course whose curriculum this subject belongs to.
274274 pub course: String,
@@ -296,7 +296,7 @@ impl SubjectResponse {
296296 /// submission (against `due_at`), never stored on the homework itself.
297297 #[derive(Serialize, ToSchema)]
298298 pub struct HomeworkResponse {
299- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
299+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
300300 pub id: String,
301301 /// The course this homework belongs to.
302302 pub course: String,
src/web/events.rsmodified+2 -2
@@ -912,7 +912,7 @@ async fn unregister(
912912 #[cfg(test)]
913913 mod tests {
914914 use super::*;
915- use crate::database::init_mem;
915+ use crate::database::init_test_db;
916916 use crate::domain::user::{Password, Username};
917917
918918 /// A user at `role`, minted through the real create path.
@@ -936,7 +936,7 @@ mod tests {
936936 /// helper is what must hold when a future route arrives with `CurrentUser`.
937937 #[tokio::test]
938938 async fn demoted_event_creator_loses_management() {
939- let db = init_mem().await.unwrap();
939+ let (db, _leases) = init_test_db().await;
940940 let creator = user("ogretmen", Role::Teacher, &db).await;
941941 let event = service::event::create(
942942 &db,
src/web/exams/mod.rsmodified+1 -1
@@ -183,7 +183,7 @@ struct GradeResult {
183183 #[schema(example = 85, minimum = 0, maximum = 100)]
184184 mark: i64,
185185 /// The student being graded.
186- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
186+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
187187 user_id: String,
188188 }
189189
src/web/exams/questions.rsmodified+2 -2
@@ -14,7 +14,7 @@ use crate::service::exam_question;
1414 pub(crate) struct CreateQuestion {
1515 /// The subject this question belongs to — one of the exam's course's
1616 /// subjects (`GET /courses/{id}/subjects`). Required.
17- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
17+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
1818 subject_id: String,
1919 /// The question itself.
2020 #[schema(example = "What is 2 + 2?", max_length = 2000)]
@@ -435,7 +435,7 @@ pub(crate) async fn delete_question(
435435 pub(crate) struct InstantiateFromBank {
436436 /// The subject to file the new question under — one of the exam's course's
437437 /// subjects (the same-course rule the bank row itself is exempt from).
438- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
438+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
439439 subject_id: String,
440440 }
441441
src/web/homework.rsmodified+2 -2
@@ -407,7 +407,7 @@ async fn delete_homework(
407407 /// separately from `GET /homework/{id}/submission/files/{fid}`.
408408 #[derive(Serialize, ToSchema)]
409409 struct HomeworkFileResponse {
410- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
410+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
411411 id: String,
412412 /// The uploader's original filename.
413413 #[schema(example = "odev.pdf")]
@@ -886,7 +886,7 @@ async fn delete_submission_file(
886886 #[derive(Deserialize, ToSchema)]
887887 struct GradeHomework {
888888 /// The student being graded.
889- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
889+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
890890 user: String,
891891 /// The verdict: `done`, `incomplete`, or `missing`.
892892 #[schema(example = "done")]
src/web/messages.rsmodified+1 -1
@@ -30,7 +30,7 @@ pub fn routes() -> OpenApiRouter<AppState> {
3030 #[derive(Deserialize, ToSchema)]
3131 struct SendMessage {
3232 /// The receiving user's id (find people via `GET /users/search`).
33- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
33+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
3434 recipient_id: String,
3535 #[schema(example = "About today's study session", max_length = 200)]
3636 subject: String,
src/web/mod.rsmodified+1 -1
@@ -380,7 +380,7 @@ mod tests {
380380 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
381381 use crate::domain::user::{Password, Username};
382382
383- let db = crate::database::init_mem().await.unwrap();
383+ let (db, _leases) = crate::database::init_test_db().await;
384384 let office = UserId::from_key("office");
385385 let teacher = crate::service::user::create(
386386 &db,
src/web/payments.rsmodified+2 -2
@@ -333,7 +333,7 @@ async fn delete_plan(
333333 struct AssignFeePlan {
334334 /// The students to place on the plan, at most 200 per call. Each is
335335 /// reported on individually — one bad id does not lose the rest.
336- #[schema(max_items = 200, example = json!(["01JC0Z0Z0Z0Z0Z0Z0Z0Z0Z0Z0Z"]))]
336+ #[schema(max_items = 200, example = json!(["019732e3-7b00-7000-8000-000000000a0b"]))]
337337 student_ids: Vec<String>,
338338 }
339339
@@ -1086,7 +1086,7 @@ mod tests {
10861086 /// shape of `source` links is exactly what the fold walks.
10871087 #[tokio::test]
10881088 async fn the_statement_rolls_each_charge_up_from_its_own_lines() {
1089- let db = crate::database::init_mem().await.unwrap();
1089+ let (db, _leases) = crate::database::init_test_db().await;
10901090 let manager = UserId::from_key("mgr1");
10911091 let student = UserId::from_key("stu1");
10921092 let future = Timestamp::now().as_millis() + 30 * 24 * 60 * 60 * 1000;
src/web/tenant_state.rsmodified+3 -3
@@ -180,7 +180,7 @@ mod tests {
180180 use axum::{Router, body::Body, http::Request};
181181 use tower::ServiceExt;
182182
183- use crate::database::init_mem_tenants;
183+ use crate::database::init_test_tenants;
184184 use crate::db::session;
185185 use crate::domain::user::{Password, Username};
186186 use crate::tenant::DEMO_SLUG;
@@ -197,7 +197,7 @@ mod tests {
197197 /// A two-route app, one live cookie of each kind, and the registry behind
198198 /// them.
199199 async fn harness() -> (Router, String, String, crate::tenant::Tenants) {
200- let tenants = init_mem_tenants().await.expect("in-memory deployment");
200+ let tenants = init_test_tenants().await;
201201 let school = tenants
202202 .get(&Slug::try_new(DEMO_SLUG).unwrap())
203203 .await
@@ -343,7 +343,7 @@ mod tests {
343343 /// still passes — the verdict came from the memoized extension.
344344 #[tokio::test]
345345 async fn a_request_resolves_its_school_exactly_once() {
346- let tenants = init_mem_tenants().await.expect("in-memory deployment");
346+ let tenants = init_test_tenants().await;
347347 let demo = Slug::try_new(DEMO_SLUG).unwrap();
348348 let state = AppState {
349349 db: tenants.control().clone(),
src/web/users.rsmodified+3 -3
@@ -706,7 +706,7 @@ async fn my_students(
706706 /// A user's public profile. Contact details are not part of it, at any role.
707707 #[derive(Serialize, ToSchema)]
708708 struct ProfileResponse {
709- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
709+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
710710 id: String,
711711 #[schema(example = "ada")]
712712 username: String,
@@ -763,7 +763,7 @@ struct ProfileAvatar {
763763 /// `GET /classes/{id}`, which is teacher+.
764764 #[derive(Serialize, ToSchema)]
765765 struct ProfileClassRef {
766- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
766+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
767767 id: String,
768768 #[schema(example = "9-A")]
769769 name: String,
@@ -774,7 +774,7 @@ struct ProfileClassRef {
774774 /// A course as a profile shows it — a label, nothing more.
775775 #[derive(Serialize, ToSchema)]
776776 struct ProfileCourseRef {
777- #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
777+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
778778 id: String,
779779 #[schema(example = "Matematik")]
780780 title: String,
tests/board_invite.rsmodified+21 -15
@@ -13,7 +13,7 @@
1313 mod common;
1414
1515 use axum::http::StatusCode;
16-use common::{Res, app_and_db, create_course, enroll, login, login_as, me_id, send};
16+use common::{ABSENT_ID, Res, app_and_db, create_course, enroll, login, login_as, me_id, send};
1717 use hezarfen_backend::constant::MAX_BOARD_PARTICIPANTS;
1818 use hezarfen_backend::domain::board::BoardId;
1919 use hezarfen_backend::domain::user::UserId;
@@ -281,13 +281,20 @@ async fn a_deleted_user_in_a_source_is_dropped() {
281281 enroll(&app, &teacher, &course, &ghost_id).await;
282282
283283 // The row goes without the cascade a real DELETE runs, which is exactly the
284- // state a stale enrollment leaves behind.
285- db.query("DELETE type::record('user', $key)")
286- .bind(("key", ghost_id.clone()))
284+ // state a stale enrollment leaves behind. Real FKs refuse that state, so
285+ // the delete is forced the one way Postgres allows: FK triggers suspended
286+ // for the one statement (`hezarfen` owns the cluster, so it may).
287+ let mut tx = db.begin().await.unwrap();
288+ sqlx::query("SET LOCAL session_replication_role = replica")
289+ .execute(&mut *tx)
287290 .await
288- .unwrap()
289- .check()
290291 .unwrap();
292+ sqlx::query("DELETE FROM app_user WHERE id = $1")
293+ .bind(UserId::from_key(&ghost_id))
294+ .execute(&mut *tx)
295+ .await
296+ .unwrap();
297+ tx.commit().await.unwrap();
291298
292299 let board = a_board(&app, &teacher).await;
293300 let res = invite(
@@ -324,14 +331,13 @@ async fn an_over_cap_invite_is_refused_whole_and_changes_nothing() {
324331 // The ids need not resolve — the roster is only repaired at boot, and the
325332 // guard under test counts entries.
326333 let full: Vec<_> = (0..MAX_BOARD_PARTICIPANTS)
327- .map(|n| UserId::from_key(&format!("filler{n}")).record())
334+ .map(|_| UserId::generate())
328335 .collect();
329- db.query("UPDATE $b SET participants = $who")
330- .bind(("b", BoardId::from_key(&board).record()))
331- .bind(("who", full))
336+ sqlx::query("UPDATE board SET participants = $1 WHERE id = $2")
337+ .bind(&full)
338+ .bind(BoardId::from_key(&board))
339+ .execute(&db)
332340 .await
333- .unwrap()
334- .check()
335341 .unwrap();
336342 let before = roster(&app, &teacher, &board).await;
337343 assert_eq!(before.len(), MAX_BOARD_PARTICIPANTS);
@@ -488,15 +494,15 @@ async fn an_unknown_source_is_a_400_and_not_the_boards_404() {
488494
489495 for (source, field) in [
490496 (
491- json!({"kind": "class", "class": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}),
497+ json!({"kind": "class", "class": ABSENT_ID}),
492498 "class",
493499 ),
494500 (
495- json!({"kind": "course", "course": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}),
501+ json!({"kind": "course", "course": ABSENT_ID}),
496502 "course",
497503 ),
498504 (
499- json!({"kind": "event", "event": "01J8XZ0K3Q8G7X2M4N5P6R7S8T"}),
505+ json!({"kind": "event", "event": ABSENT_ID}),
500506 "event",
501507 ),
502508 ] {
tests/regress_course_delete.rsmodified+20 -17
@@ -133,15 +133,11 @@ async fn a_course_delete_gives_back_the_kind_references_its_marks_held() {
133133 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
134134
135135 let counted = |db: hezarfen_backend::database::Database| async move {
136- db.query("SELECT VALUE count ?? 0 FROM kind_ref:midterm")
136+ sqlx::query_as::<_, (i64,)>("SELECT count FROM kind_ref WHERE name = 'midterm'")
137+ .fetch_optional(&db)
137138 .await
138139 .expect("kind_ref read")
139- .check()
140- .expect("kind_ref read")
141- .take::<Vec<i64>>(0)
142- .expect("kind_ref count")
143- .first()
144- .copied()
140+ .map(|(count,)| count)
145141 .unwrap_or(0)
146142 };
147143 assert_eq!(counted(db.clone()).await, 1, "the mark must be counted");
@@ -177,9 +173,11 @@ async fn a_course_delete_gives_back_the_kind_references_its_marks_held() {
177173 /// unreachable (every route to an attempt goes through its exam) with the
178174 /// student's lifetime sitting counter up for good.
179175 ///
180-/// The in-memory engine is enough, as it is next door: this asserts a *lock*,
181-/// not the store's conflict detection, and a mutex behaves the same on either
182-/// engine.
176+/// Postgres hands out the same pairing the lease used to: the sitting's
177+/// transaction holds the exam row's write lock across the sleeping trigger, so
178+/// the delete cannot even reach its attempt sweep until the sitting has
179+/// committed. Mutation-proven: dropping the lease from the cascade turns it
180+/// red.
183181 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
184182 async fn an_attempt_started_inside_a_course_delete_never_outlives_it() {
185183 let (app, db) = app_and_db().await;
@@ -188,15 +186,20 @@ async fn an_attempt_started_inside_a_course_delete_never_outlives_it() {
188186 let student_id = me_id(&app, &student).await;
189187
190188 // Hold the sitting's own write open for a full second, gates already
191- // passed, so the unenroll and the delete both land inside it.
192- db.query(
193- "DEFINE EVENT hold_the_start ON TABLE exam_attempt WHEN $event = 'CREATE' \
194- THEN { SLEEP 1s; };",
189+ // passed, so the unenroll and the delete both land inside it. An AFTER
190+ // INSERT trigger sleeping inside the create's own transaction is the
191+ // Postgres shape of the old window event.
192+ let mut conn = db.acquire().await.expect("acquire for the trigger");
193+ sqlx::raw_sql(
194+ "CREATE FUNCTION heztest_hold_start() RETURNS trigger AS $$
195+ BEGIN PERFORM pg_sleep(1.0); RETURN NULL; END;
196+ $$ LANGUAGE plpgsql;
197+ CREATE TRIGGER heztest_hold_start AFTER INSERT ON exam_attempt
198+ FOR EACH ROW EXECUTE FUNCTION heztest_hold_start();",
195199 )
200+ .execute(&mut *conn)
196201 .await
197- .expect("define the window event")
198- .check()
199- .expect("check the window event");
202+ .expect("define the window trigger");
200203
201204 let course = common::create_course(&app, &teacher, "Kimya").await;
202205 enroll(&app, &teacher, &course, &student_id).await;
tests/regress_meals.rsmodified+56 -36
@@ -14,6 +14,7 @@ use common::{app_and_db, id_of, login, login_as, me_id, send, set_role};
1414 use hezarfen_backend::db::meal_attendance;
1515 use hezarfen_backend::db::menu;
1616 use hezarfen_backend::domain::meal_attendance::MealAttendanceStatus;
17+use hezarfen_backend::domain::meal_booking::MealBookingId;
1718 use hezarfen_backend::domain::menu::{MenuDate, MenuId, MenuSlot};
1819 use hezarfen_backend::domain::settings::MealSlotDef;
1920 use hezarfen_backend::domain::user::UserId;
@@ -541,13 +542,20 @@ async fn a_dish_write_is_refused_once_its_menu_is_gone() {
541542 let dish = add_dish(&app, &mgr, &menu, 1_000).await;
542543
543544 // The menu row alone is removed, leaving the dish exactly as a delete
544- // interrupted between the row and its cascade would have.
545- db.query("DELETE $id")
546- .bind(("id", MenuId::from_key(&menu).record()))
545+ // interrupted between the row and its cascade would have. Real FKs refuse
546+ // that state, so the delete is forced the one way Postgres allows: FK
547+ // triggers suspended for the one statement.
548+ let mut tx = db.begin().await.unwrap();
549+ sqlx::query("SET LOCAL session_replication_role = replica")
550+ .execute(&mut *tx)
547551 .await
548- .unwrap()
549- .check()
550552 .unwrap();
553+ sqlx::query("DELETE FROM menu WHERE id = $1")
554+ .bind(MenuId::from_key(&menu))
555+ .execute(&mut *tx)
556+ .await
557+ .unwrap();
558+ tx.commit().await.unwrap();
551559
552560 let res = send(
553561 &app,
@@ -688,14 +696,14 @@ async fn a_slot_whose_name_would_break_the_menu_url_cannot_be_published() {
688696 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
689697
690698 // ...and the stale row is that list as a database written before the rule.
691- db.query(
692- "UPDATE settings:school SET meal_slots = \
693- [{ name: 'a/b', serving_minute: NONE }, { name: 'lunch', serving_minute: NONE }]",
694- )
695- .await
696- .unwrap()
697- .check()
698- .unwrap();
699+ sqlx::query("UPDATE settings SET meal_slots = $1 WHERE id = 'school'")
700+ .bind(sqlx::types::Json(json!([
701+ { "name": "a/b", "serving_minute": null },
702+ { "name": "lunch", "serving_minute": null }
703+ ])))
704+ .execute(&db)
705+ .await
706+ .unwrap();
699707
700708 let res = send(
701709 &app,
@@ -1012,11 +1020,12 @@ async fn two_first_profile_writes_land_without_a_500() {
10121020 /// the store had given away. The stored state was right throughout; only the
10131021 /// answer lied.
10141022 ///
1015-/// The cancel is injected the way `regress_roles` does it: a `DEFINE EVENT`
1016-/// fires inside the very write the replay makes — here the charge it replays,
1017-/// which is why the ledger is stripped first (a charge already there is a
1018-/// no-op). Fenced on `attempt = 1`, so the re-booked seat's own charge does not
1019-/// trip it a second time.
1023+/// The cancel is injected where the old `DEFINE EVENT` fired it: inside the
1024+/// very write the replay makes — here the charge it replays, which is why the
1025+/// ledger is stripped first (a charge already there is a no-op). An AFTER
1026+/// INSERT trigger on the ledger cancels the seat inside the charge's own
1027+/// transaction, fenced on the attempt-1 charge id, so the re-booked seat's own
1028+/// charge does not trip it a second time.
10201029 #[tokio::test]
10211030 async fn a_replayed_booking_answers_off_the_row_the_store_holds() {
10221031 let (app, db) = app_and_db().await;
@@ -1036,18 +1045,29 @@ async fn a_replayed_booking_answers_off_the_row_the_store_holds() {
10361045 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
10371046 let booking = id_of(&res.body);
10381047
1039- db.query(format!(
1040- "DELETE meal_ledger;
1041- DEFINE EVENT cancel_inside ON TABLE meal_ledger WHEN $event = 'CREATE' THEN {{
1042- UPDATE type::record('meal_booking', '{booking}') \
1043- SET status = 'cancelled', cancelled_at = 1 WHERE attempt = 1;
1044- }};"
1045- ))
1048+ let mut conn = db.acquire().await.expect("acquire for the trigger");
1049+ sqlx::query("DELETE FROM meal_ledger")
1050+ .execute(&db)
1051+ .await
1052+ .unwrap();
1053+ // The trigger derives the seat off the charge id itself (`{booking}_c{attempt}`),
1054+ // so the text stays static: every attempt-1 charge cancels its own booking.
1055+ sqlx::raw_sql(
1056+ "CREATE FUNCTION heztest_cancel_inside() RETURNS trigger AS $$
1057+ BEGIN
1058+ IF right(NEW.id, 3) = '_c1' THEN
1059+ UPDATE meal_booking SET status = 'cancelled', cancelled_at = 1
1060+ WHERE menu || '_' || student::text || '_c1' = NEW.id;
1061+ END IF;
1062+ RETURN NULL;
1063+ END;
1064+ $$ LANGUAGE plpgsql;
1065+ CREATE TRIGGER heztest_cancel_inside AFTER INSERT ON meal_ledger
1066+ FOR EACH ROW EXECUTE FUNCTION heztest_cancel_inside();",
1067+ )
1068+ .execute(&mut *conn)
10461069 .await
1047- .unwrap()
1048- .check()
1049- .unwrap();
1050-
1070+ .expect("define the cancel trigger");
10511071 let res = send(
10521072 &app,
10531073 "POST",
@@ -1357,13 +1377,13 @@ async fn an_over_ceiling_seat_from_an_older_build_is_still_cancellable() {
13571377 let booking = id_of(&res.body);
13581378
13591379 // Aged past the ceiling, the way an older binary would have left it.
1360- db.query(format!(
1361- "UPDATE type::record('meal_booking', '{booking}') SET attempt = 25"
1362- ))
1363- .await
1364- .unwrap()
1365- .check()
1366- .unwrap();
1380+ let booking_id = MealBookingId::from_key(&booking);
1381+ sqlx::query("UPDATE meal_booking SET attempt = 25 WHERE menu = $1 AND student = $2")
1382+ .bind(booking_id.menu())
1383+ .bind(booking_id.student())
1384+ .execute(&db)
1385+ .await
1386+ .unwrap();
13671387
13681388 let res = send(
13691389 &app,
tests/regress_profile.rsmodified+26 -29
@@ -14,7 +14,7 @@ use axum::Router;
1414 use axum::http::StatusCode;
1515 use common::{
1616 app_and_db, create_course, create_exam_with, create_homework, create_subject, enroll, id_of,
17- items, login, login_as, me_id, send, set_role,
17+ items, login, login_as, me_id, send, set_role, ABSENT_ID,
1818 };
1919 use hezarfen_backend::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN};
2020 use hezarfen_backend::database::Database;
@@ -347,33 +347,30 @@ async fn a_profile_read_heals_a_missed_badge_then_writes_nothing() {
347347 let ada = login(&app, "ada").await;
348348 let ada_id = me_id(&app, &ada).await;
349349
350- // Fires inside any write to the award table, so a write this read should
351- // not make cannot hide behind an unchanged-looking response.
352- db.query(
353- "DEFINE EVENT award_write ON badge_award WHEN true THEN {
354- UPSERT type::record('award_write_probe', 'n') SET n = (n ?? 0) + 1;
355- };",
356- )
357- .await
358- .unwrap()
359- .check()
360- .unwrap();
361- let writes = || async {
362- db.query("SELECT VALUE n FROM award_write_probe:n")
350+ // The award table watched through its rows: the read must not add, remove
351+ // or alter one. (The old engine counted writes with a `DEFINE EVENT`;
352+ // Postgres has no triggers to hang that on, and the write the guard
353+ // bites on — an insert, or a re-stamp of `earned_at` — always changes
354+ // what the rows hold.)
355+ let awards = || async {
356+ let rows: Vec<(uuid::Uuid, String, Option<i64>)> =
357+ sqlx::query_as(
358+ "SELECT app_user, badge, earned_at FROM badge_award ORDER BY app_user, badge",
359+ )
360+ .fetch_all(&db)
363361 .await
364- .unwrap()
365- .take::<Vec<i64>>(0)
366- .unwrap()
367- .first()
368- .copied()
369- .unwrap_or(0)
362+ .unwrap();
363+ rows
370364 };
371-
372- db.query("UPDATE type::record('user', $id) SET homework_submitted_total = 10")
373- .bind(("id", ada_id.clone()))
365+ assert!(awards().await.is_empty(), "nothing has been awarded yet");
366+
367+ // A counter is moved behind the API's back — exactly what a lost
368+ // `badge::sync` leaves behind, since every counter writer logs and
369+ // swallows that error.
370+ sqlx::query("UPDATE app_user SET homework_submitted_total = 10 WHERE id = $1")
371+ .bind(hezarfen_backend::domain::user::UserId::from_key(&ada_id))
372+ .execute(&db)
374373 .await
375- .unwrap()
376- .check()
377374 .unwrap();
378375
379376 let healed = profile(&app, &ada, &ada_id).await;
@@ -391,15 +388,15 @@ async fn a_profile_read_heals_a_missed_badge_then_writes_nothing() {
391388 healed.body
392389 );
393390 assert_eq!(healed.body["stats"]["homework_submitted_total"], 10);
394- let after_heal = writes().await;
395- assert!(after_heal > 0, "the heal wrote the awards");
391+ let after_heal = awards().await;
392+ assert!(!after_heal.is_empty(), "the heal wrote the awards");
396393
397394 // Steady state: everything earned is already held, so this read must not
398395 // touch the award table at all.
399396 let again = profile(&app, &ada, &ada_id).await;
400397 assert_eq!(again.status, StatusCode::OK, "{}", again.body);
401398 assert_eq!(again.body["badges"], healed.body["badges"], "same shelf");
402- assert_eq!(writes().await, after_heal, "a profile read wrote something");
399+ assert_eq!(awards().await, after_heal, "a profile read wrote something");
403400 }
404401
405402 /// A fresh account reads a true `0` on every counter — never `null`, never an
@@ -1570,6 +1567,6 @@ async fn an_unknown_user_profile_is_a_404() {
15701567 let (app, db) = app_and_db().await;
15711568 let teacher = login_as(&app, &db, "teach", "teacher").await;
15721569
1573- let gone = profile(&app, &teacher, "01J8XZ0K3Q8G7X2M4N5P6R7S8T").await;
1570+ let gone = profile(&app, &teacher, ABSENT_ID).await;
15741571 assert_eq!(gone.status, StatusCode::NOT_FOUND, "{}", gone.body);
15751572 }
tests/regress_review.rsmodified+2 -2
@@ -21,7 +21,7 @@ mod common;
2121 use axum::http::StatusCode;
2222 use common::{
2323 app_and_db, create_course, create_exam_with, create_subject, enroll, id_of, login, login_as,
24- me_id, send,
24+ me_id, send, ABSENT_ID,
2525 };
2626 use serde_json::json;
2727
@@ -677,7 +677,7 @@ async fn the_review_gate_does_not_leak_allow_review_to_outsiders() {
677677
678678 // The oracle: to a caller with no mark the two exams must be one answer —
679679 // and the same answer an exam that does not exist gives.
680- let nowhere = review_of(&outsider, "01J8XZ0K3Q8G7X2M4N5P6R7S8T").await;
680+ let nowhere = review_of(&outsider, ABSENT_ID).await;
681681 assert_eq!(nowhere, StatusCode::NOT_FOUND);
682682 for (who, cookie) in [("unenrolled student", &outsider), ("parent", &parent)] {
683683 let on_open = review_of(cookie, &open).await;
tests/regress_role_sweep.rsmodified+126 -73
@@ -13,13 +13,13 @@
1313 //!
1414 //! Each defect is pinned twice: the ordering the claim enforces (the demotion
1515 //! already committed — the sequential half), and the interleaving itself, held
16-//! open by a `DEFINE EVENT` on the `user` table so the demotion's transaction is
17-//! still running when the grant is written.
16+//! open by an AFTER DELETE trigger sleeping inside the sweep, so the demotion's
17+//! transaction is still running when the grant is written.
1818
1919 mod common;
2020
2121 use axum::http::StatusCode;
22-use common::{app_and_db, login_as, me_id, send};
22+use common::{app_and_db, login_as, me_id, send, set_role};
2323 use hezarfen_backend::database::Database;
2424 use hezarfen_backend::db::enrollment;
2525 use hezarfen_backend::domain::class_group::{ClassGroupId, ClassName};
@@ -31,22 +31,52 @@ use hezarfen_backend::domain::user::UserId;
3131 use hezarfen_backend::service::registration;
3232 use hezarfen_backend::service::{class_group, class_member};
3333 use serde_json::json;
34-
35-/// How many rows `sql` selects ids for.
36-async fn rows(sql: &str, db: &Database) -> usize {
37- let mut result = db.query(sql).await.unwrap().check().unwrap();
38- result
39- .take::<Vec<surrealdb::types::RecordId>>(0)
40- .unwrap()
41- .len()
34+use sqlx::Row as _;
35+
36+/// How many rows `table` holds.
37+async fn rows(table: &str, db: &Database) -> usize {
38+ sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
39+ "SELECT count(*) FROM {table}"
40+ )))
41+ .fetch_one(db)
42+ .await
43+ .unwrap() as usize
4244 }
4345
4446 /// Every row's counter added up, re-read out of the store — never off a return
4547 /// value, and summed because the race tests leave a second parent standing (the
4648 /// bait) whose seat has to come back too.
47-async fn counter(sql: &str, db: &Database) -> i64 {
48- let mut result = db.query(sql).await.unwrap().check().unwrap();
49- result.take::<Vec<i64>>(0).unwrap().into_iter().sum()
49+async fn counter(column: &str, table: &str, db: &Database) -> i64 {
50+ sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
51+ "SELECT COALESCE(sum({column}), 0)::bigint FROM {table}"
52+ )))
53+ .fetch_one(db)
54+ .await
55+ .unwrap()
56+}
57+
58+/// A real `app_user` row for the fixture actor a domain call must name:
59+/// every actor column is a foreign key now, so actors are rows, not fabricated
60+/// ids. The username is unique, so every call for the same name shares one row,
61+/// whichever call minted it. These actors never log in, so the hash is a stub.
62+async fn fixture_actor(db: &Database, username: &str) -> UserId {
63+ sqlx::query(
64+ "INSERT INTO app_user (id, username, password_hash, role) \
65+ VALUES ($1, $2, 'x', 'student') ON CONFLICT DO NOTHING",
66+ )
67+ .bind(UserId::generate().uuid())
68+ .bind(username)
69+ .execute(db)
70+ .await
71+ .unwrap();
72+ let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1")
73+ .bind(username)
74+ .fetch_one(db)
75+ .await
76+ .unwrap()
77+ .try_get(0)
78+ .unwrap();
79+ UserId::from_key(&id.to_string())
5080 }
5181
5282 /// Demote through the real path — the sweeps ride the role write.
@@ -61,31 +91,34 @@ async fn demote(user: &UserId, to: Role, db: &Database) {
6191 }
6292
6393 /// Hold the demotion's transaction open *past the point its sweep has looked*:
64-/// a `DEFINE EVENT` on the child table fires inside the sweep's own `DELETE`,
65-/// so a grant written during the sleep lands after the snapshot that sweep is
66-/// working from and before the transaction commits. That is the write-skew
67-/// itself, opened by the schema rather than by a lucky interleaving.
94+/// an AFTER DELETE trigger on the child table sleeps inside the sweep's own
95+/// `DELETE`, so a grant written during the sleep lands after the snapshot that
96+/// sweep is working from and before the transaction commits. That is the
97+/// write-skew itself, opened by the schema rather than by a lucky interleaving.
6898 ///
6999 /// It bites only where the sweep has something to delete, so every caller
70100 /// leaves one row of that kind behind first — the bait. Holding the *role*
71101 /// write instead proves nothing: the sweeps run after it, so they see the new
72102 /// row and free it even on unfixed code.
73103 async fn hold_the_sweep(table: &str, db: &Database) {
74- db.query(format!(
75- "DEFINE EVENT hold_the_sweep ON TABLE {table} WHEN $event = 'DELETE' \
76- THEN {{ SLEEP 2s }};"
77- ))
104+ let mut conn = db.acquire().await.expect("acquire for the trigger");
105+ sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
106+ "CREATE FUNCTION heztest_hold_the_sweep() RETURNS trigger AS $$
107+ BEGIN PERFORM pg_sleep(2.0); RETURN NULL; END;
108+ $$ LANGUAGE plpgsql;
109+ CREATE TRIGGER heztest_hold_the_sweep AFTER DELETE ON {table}
110+ FOR EACH ROW EXECUTE FUNCTION heztest_hold_the_sweep();"
111+ )))
112+ .execute(&mut *conn)
78113 .await
79- .unwrap()
80- .check()
81- .unwrap();
114+ .expect("define the window trigger");
82115 }
83116
84-/// One held window at a time. Each race test below keeps a database
85-/// transaction open for seconds while `cap`'s counter lock is process-wide, so
86-/// run in parallel they push each other clean out of their windows: measured,
87-/// all three then pass on code with the claim removed, while serialized all
88-/// three fail it. Same trap as the process-wide `EXAM_LOCK` note in
117+/// One held window at a time. Each race test below holds a database
118+/// transaction open for seconds against the shared Postgres server, so run in
119+/// parallel they push each other clean out of their windows: measured, all
120+/// three then pass on code with the claim removed, while serialized all three
121+/// fail it. Same trap as the process-wide `EXAM_LOCK` note in
89122 /// `regress_course_delete`, and the guard is handed back into a binding that
90123 /// lives for the whole test the way `init_test_server`'s does.
91124 static ONE_WINDOW_AT_A_TIME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
@@ -95,7 +128,7 @@ static ONE_WINDOW_AT_A_TIME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_
95128 ///
96129 /// The wait is a fixed delay against a two-second window, so a loaded machine
97130 /// still lands in it — and the caller proves it did rather than trusting it:
98-/// [`still_running`] is asserted the moment the raced write returns. A window
131+/// [`still_queued`] is asserted while the demotion runs. A window
99132 /// missed the other way (the demotion committing first) would make every one of
100133 /// these tests pass on unfixed code, which is the failure mode a race test has
101134 /// to be loudest about.
@@ -113,13 +146,16 @@ async fn demote_in_the_window(
113146 handle
114147 }
115148
116-/// The raced write returned while the demotion's transaction was still open —
117-/// which, since every statement in it but the held one is sub-millisecond, is
118-/// the window.
119-fn still_running(demoting: &tokio::task::JoinHandle<()>) {
149+/// The raced write is *queued*, not answered: the claim locks the user row the
150+/// demotion is holding, so a raced write that answered inside the window —
151+/// which is what unfixed code, sharing no key with the demotion, did — fails
152+/// here instead of in the stored-state assertions.
153+async fn still_queued<T>(raced: &tokio::task::JoinHandle<T>) {
154+ // race-window staging — do not convert to poll
155+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
120156 assert!(
121- !demoting.is_finished(),
122- "the demotion committed before the raced write: this run proved nothing"
157+ !raced.is_finished(),
158+ "the raced write answered inside the demotion's window: nothing queued"
123159 );
124160 }
125161
@@ -165,14 +201,15 @@ async fn a_seat_is_refused_once_the_holder_is_a_parent() {
165201 let event = a_registration_event(&app, &teacher, 1).await;
166202 demote(&student, Role::Parent, &db).await;
167203
168- let refused = registration::register(&db, &event, &student, &UserId::from_key("staff")).await;
204+ let refused = registration::register(&db, &event, &student, &fixture_actor(&db, "staff").await)
205+ .await;
169206 assert!(
170207 refused.is_err(),
171208 "a parent may not be given a seat: {refused:?}"
172209 );
173- assert_eq!(rows("SELECT VALUE id FROM registration", &db).await, 0);
210+ assert_eq!(rows("registration", &db).await, 0);
174211 assert_eq!(
175- counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await,
212+ counter("registration_count", "event", &db).await,
176213 0,
177214 "…and the event must not count one, or the last place is denied forever"
178215 );
@@ -190,29 +227,36 @@ async fn a_seat_never_survives_the_demotion_it_raced() {
190227 let event = a_registration_event(&app, &teacher, 1).await;
191228 // The bait: a seat the sweep will delete, which is what holds it open.
192229 let earlier = a_registration_event(&app, &teacher, 1).await;
193- registration::register(&db, &earlier, &student, &UserId::from_key("staff"))
230+ registration::register(&db, &earlier, &student, &fixture_actor(&db, "staff").await)
194231 .await
195232 .unwrap();
196233 hold_the_sweep("registration", &db).await;
197234
198- // The seat is written inside the held window: past the sweep's snapshot,
199- // before the commit.
235+ // The grant is written while the demotion holds its window: the claim
236+ // queues on the demoted user's row, past the sweep's snapshot.
200237 let demoting = demote_in_the_window(&student, Role::Parent, &db).await;
201- let seat = registration::register(&db, &event, &student, &UserId::from_key("staff")).await;
202- still_running(&demoting);
238+ let seat = {
239+ let (db, event) = (db.clone(), event);
240+ let staff = fixture_actor(&db, "staff").await;
241+ tokio::spawn(async move {
242+ registration::register(&db, &event, &student, &staff).await
243+ })
244+ };
245+ still_queued(&seat).await;
203246 demoting.await.unwrap();
247+ let seat = seat.await.expect("raced registration task");
204248
205249 assert!(
206250 !matches!(seat, Err(hezarfen_backend::error::AppError::Db(_))),
207251 "a raced registration must be answered, not 500: {seat:?}"
208252 );
209253 assert_eq!(
210- rows("SELECT VALUE id FROM registration", &db).await,
254+ rows("registration", &db).await,
211255 0,
212256 "the seat a parent cannot free must not exist ({seat:?})"
213257 );
214258 assert_eq!(
215- counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await,
259+ counter("registration_count", "event", &db).await,
216260 0,
217261 "…and its place must be back on the list"
218262 );
@@ -226,17 +270,13 @@ async fn a_stranded_parent_seat_is_freeable_by_a_teacher() {
226270 let (app, db) = app_and_db().await;
227271 let (teacher, student) = a_school(&app, &db).await;
228272 let event = a_registration_event(&app, &teacher, 1).await;
229- registration::register(&db, &event, &student, &UserId::from_key("staff"))
273+ registration::register(&db, &event, &student, &fixture_actor(&db, "staff").await)
230274 .await
231275 .unwrap();
232276 // The state the old race left: the seat stands, the account is a parent,
233- // and the sweep that should have taken it never saw it.
234- db.query("UPDATE $usr SET role = 'parent'")
235- .bind(("usr", student.record()))
236- .await
237- .unwrap()
238- .check()
239- .unwrap();
277+ // and the sweep that should have taken it never saw it. `set_role` is the
278+ // harness's bare role write — no cascade, which is exactly the staleness.
279+ set_role(&db, "ogrenci", "parent").await;
240280
241281 let freed = send(
242282 &app,
@@ -253,7 +293,7 @@ async fn a_stranded_parent_seat_is_freeable_by_a_teacher() {
253293 freed.body
254294 );
255295 assert_eq!(
256- counter("SELECT VALUE registration_count ?? 0 FROM event", &db).await,
296+ counter("registration_count", "event", &db).await,
257297 0,
258298 "the place comes back with the row"
259299 );
@@ -272,14 +312,15 @@ async fn an_enrollment_is_refused_once_the_student_is_demoted() {
272312 let course = a_course(&app, &teacher).await;
273313 demote(&student, Role::Teacher, &db).await;
274314
275- let refused = enrollment::enroll(&db, &course, &student, &UserId::from_key("staff")).await;
315+ let staff = fixture_actor(&db, "staff").await;
316+ let refused = enrollment::enroll(&db, &course, &student, &staff).await;
276317 assert!(
277318 refused.is_err(),
278319 "only students hold enrollments: {refused:?}"
279320 );
280- assert_eq!(rows("SELECT VALUE id FROM enrollment", &db).await, 0);
321+ assert_eq!(rows("enrollment", &db).await, 0);
281322 assert_eq!(
282- counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await,
323+ counter("enrollment_count", "course", &db).await,
283324 0,
284325 "…and a counted seat would also freeze the course's delete guard"
285326 );
@@ -293,23 +334,28 @@ async fn an_enrollment_never_survives_the_demotion_it_raced() {
293334 let course = a_course(&app, &teacher).await;
294335 // The bait: a row the sweep will delete, which is what holds it open.
295336 let earlier = CourseId::from_key(&common::create_course(&app, &teacher, "fizik").await);
296- enrollment::enroll(&db, &earlier, &student, &UserId::from_key("staff"))
337+ let staff = fixture_actor(&db, "staff").await;
338+ enrollment::enroll(&db, &earlier, &student, &staff)
297339 .await
298340 .unwrap();
299341 hold_the_sweep("enrollment", &db).await;
300342
301343 let demoting = demote_in_the_window(&student, Role::Teacher, &db).await;
302- let enrolled = enrollment::enroll(&db, &course, &student, &UserId::from_key("staff")).await;
303- still_running(&demoting);
344+ let enrolled = {
345+ let (db, course) = (db.clone(), course);
346+ tokio::spawn(async move { enrollment::enroll(&db, &course, &student, &staff).await })
347+ };
348+ still_queued(&enrolled).await;
304349 demoting.await.unwrap();
350+ let enrolled = enrolled.await.expect("raced enrollment task");
305351
306352 assert_eq!(
307- rows("SELECT VALUE id FROM enrollment", &db).await,
353+ rows("enrollment", &db).await,
308354 0,
309355 "a teacher may not be left on a course roster ({enrolled:?})"
310356 );
311357 assert_eq!(
312- counter("SELECT VALUE enrollment_count ?? 0 FROM course", &db).await,
358+ counter("enrollment_count", "course", &db).await,
313359 0
314360 );
315361 }
@@ -321,9 +367,10 @@ async fn a_class(db: &Database) -> ClassGroupId {
321367 }
322368
323369 async fn a_class_named(name: &str, db: &Database) -> ClassGroupId {
370+ let manager = fixture_actor(db, "manager").await;
324371 class_group::create(
325372 db,
326- &UserId::from_key("manager"),
373+ &manager,
327374 ClassName::try_new(name).unwrap(),
328375 None,
329376 None,
@@ -342,14 +389,15 @@ async fn a_membership_is_refused_once_the_student_is_demoted() {
342389 let class = a_class(&db).await;
343390 demote(&student, Role::Parent, &db).await;
344391
345- let refused = class_member::add(&db, &class, &student, &UserId::from_key("manager")).await;
392+ let manager = fixture_actor(&db, "manager").await;
393+ let refused = class_member::add(&db, &class, &student, &manager).await;
346394 assert!(
347395 refused.is_err(),
348396 "only students belong to a class: {refused:?}"
349397 );
350- assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);
398+ assert_eq!(rows("class_member", &db).await, 0);
351399 assert_eq!(
352- counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await,
400+ counter("class_member_count", "class_group", &db).await,
353401 0,
354402 "…and a counted member would freeze the class's delete guard"
355403 );
@@ -363,23 +411,28 @@ async fn a_membership_never_survives_the_demotion_it_raced() {
363411 let class = a_class(&db).await;
364412 // The bait: a membership the sweep will delete, which holds it open.
365413 let earlier = a_class_named("9-B", &db).await;
366- class_member::add(&db, &earlier, &student, &UserId::from_key("manager"))
414+ let manager = fixture_actor(&db, "manager").await;
415+ class_member::add(&db, &earlier, &student, &manager)
367416 .await
368417 .unwrap();
369418 hold_the_sweep("class_member", &db).await;
370419
371420 let demoting = demote_in_the_window(&student, Role::Parent, &db).await;
372- let joined = class_member::add(&db, &class, &student, &UserId::from_key("manager")).await;
373- still_running(&demoting);
421+ let joined = {
422+ let (db, class) = (db.clone(), class);
423+ tokio::spawn(async move { class_member::add(&db, &class, &student, &manager).await })
424+ };
425+ still_queued(&joined).await;
374426 demoting.await.unwrap();
427+ let joined = joined.await.expect("raced membership task");
375428
376429 assert_eq!(
377- rows("SELECT VALUE id FROM class_member", &db).await,
430+ rows("class_member", &db).await,
378431 0,
379432 "a parent may not be left on a class roster ({joined:?})"
380433 );
381434 assert_eq!(
382- counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await,
435+ counter("class_member_count", "class_group", &db).await,
383436 0
384437 );
385438 }