forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

course.rs1252 lines, 50.6 KiBHistoryRawDownload
1//! The `course` table: the school-level catalog exams, sessions, subjects and
2//! enrollments hang off *through their instances* ([`crate::db::class_course`]).
3//! Listed newest first; deleted with its whole subtree in one guarded cascade.
4//!
5//! The catalog is a template since the K12 remodel (D1): the academic work —
6//! roster, exams, timetable, teachers — lives on the instances a section attaches,
7//! so this row carries only what every instance shares (title, description,
8//! kind) and two counters. The catalog is Manager+-owned (D6): there is no
9//! per-teacher ownership list, and the two counters are the delete guard.
10
11use crate::constant::COURSE_TABLE;
12use crate::database::{Database, tx_with_retry, unique_violation};
13use crate::db::page::{PagedList, Param};
14use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};
15use crate::domain::text_fold::{search_fold, search_fold_sql};
16use crate::domain::user::UserId;
17use crate::error::AppError;
18use sqlx::PgConnection;
19
20/// The stored columns of a `course` row — the whole row. The assigned-teacher
21/// list this struct used to join on moved to the instances
22/// ([`crate::db::class_course_teacher`]), so a course read is one statement
23/// again.
24#[derive(Debug, sqlx::FromRow)]
25struct CourseRow {
26 id: CourseId,
27 creator: UserId,
28 title: CourseTitle,
29 description: CourseDescription,
30 kind: CourseKind,
31 class_course_count: i64,
32 course_membership_count: i64,
33}
34
35impl CourseRow {
36 fn into_course(self) -> Course {
37 Course {
38 id: self.id,
39 creator: self.creator,
40 title: self.title,
41 description: self.description,
42 kind: self.kind,
43 class_course_count: self.class_course_count,
44 course_membership_count: self.course_membership_count,
45 }
46 }
47}
48
49/// Mint a catalog course. No term is claimed any more: the catalog is not
50/// bound to a term (exams are, through their instance), and no capacity is
51/// stored — the roster counter lives on the instance and gates nothing.
52pub async fn create(
53 db: &Database,
54 creator: &UserId,
55 title: CourseTitle,
56 description: CourseDescription,
57 kind: CourseKind,
58) -> Result<Course, AppError> {
59 let id = CourseId::generate();
60 let created = sqlx::query_as!(
61 CourseRow,
62 r#"INSERT INTO course (id, creator, title, description, kind)
63 VALUES ($1, $2, $3, $4, $5)
64 RETURNING id AS "id: CourseId", creator AS "creator: UserId",
65 title AS "title: CourseTitle",
66 description AS "description: CourseDescription",
67 kind AS "kind: CourseKind", class_course_count, course_membership_count"#,
68 id.uuid(),
69 creator.uuid(),
70 title.as_str(),
71 description.as_str(),
72 kind.as_str(),
73 )
74 .fetch_one(db)
75 .await;
76 match created {
77 Ok(created) => Ok(created.into_course()),
78 // The creator is a foreign key: a gone account is the same `NotFound`
79 // the web layer's own read answers with, never an orphan row.
80 Err(err) if crate::database::foreign_key_violation(&err) => Err(AppError::NotFound),
81 // Unreachable: the id was minted above.
82 Err(err) if unique_violation(&err).is_some() => {
83 Err(AppError::Internal("failed to create course".into()))
84 }
85 Err(err) => Err(err.into()),
86 }
87}
88
89async fn read_row(db: &Database, id: &CourseId) -> Result<Option<CourseRow>, AppError> {
90 sqlx::query_as!(
91 CourseRow,
92 r#"SELECT id AS "id: CourseId", creator AS "creator: UserId",
93 title AS "title: CourseTitle",
94 description AS "description: CourseDescription",
95 kind AS "kind: CourseKind", class_course_count, course_membership_count
96 FROM course WHERE id = $1"#,
97 id.uuid(),
98 )
99 .fetch_optional(db)
100 .await
101 .map_err(Into::into)
102}
103
104pub async fn read(db: &Database, id: &CourseId) -> Result<Option<Course>, AppError> {
105 Ok(read_row(db, id).await?.map(CourseRow::into_course))
106}
107
108pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> {
109 let rows = sqlx::query_as!(
110 CourseRow,
111 r#"SELECT id AS "id: CourseId", creator AS "creator: UserId",
112 title AS "title: CourseTitle",
113 description AS "description: CourseDescription",
114 kind AS "kind: CourseKind", class_course_count, course_membership_count
115 FROM course ORDER BY id DESC"#,
116 )
117 .fetch_all(db)
118 .await?;
119 Ok(rows.into_iter().map(CourseRow::into_course).collect())
120}
121
122/// The catalog the visible list's manager arm serves — the whole table,
123/// newest first — with the `GET /courses` optional filters pushed into the
124/// SQL `WHERE`, so listing one kind (or searching, or the taught/untaught
125/// axis) is not a full-catalog pull the caller then throws most of away.
126/// `kind` is the exact flavor; `q` is a case- and diacritic-insensitive
127/// fragment of the title or the description (blank = no text filter): needle
128/// and columns both go through [`crate::domain::text_fold`], so `satranc`
129/// finds `Satranç` and back. `position` rather than `LIKE` keeps the needle
130/// a *literal* substring — no `%`/`_` wildcard surprises. `taught` keys on
131/// the row's own attachment counter: `true` keeps the courses a class
132/// section teaches (`class_course_count > 0`), `false` the ones nothing
133/// attaches yet. Every filter is part of the one `WHERE` the window and any
134/// count share ([`PagedList`]), so a filtered total can never disagree with
135/// the rows it counts.
136pub async fn list_filtered(
137 db: &Database,
138 kind: Option<CourseKind>,
139 q: Option<&str>,
140 taught: Option<bool>,
141) -> Result<Vec<Course>, AppError> {
142 let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty());
143 let mut clauses: Vec<String> = Vec::new();
144 let mut binds: Vec<Param> = Vec::new();
145 if let Some(kind) = &kind {
146 binds.push(Param::Text(kind.as_str().to_string()));
147 clauses.push(format!("kind = ${}", binds.len()));
148 }
149 if let Some(taught) = taught {
150 binds.push(Param::I64(0));
151 clauses.push(format!(
152 "class_course_count {} ${}",
153 if taught { ">" } else { "=" },
154 binds.len()
155 ));
156 }
157 if let Some(needle) = &needle {
158 binds.push(Param::Text(needle.clone()));
159 let at = binds.len();
160 clauses.push(format!(
161 "(position(${at} in {}) > 0 OR position(${at} in {}) > 0)",
162 search_fold_sql("title"),
163 search_fold_sql("description"),
164 ));
165 }
166 let from_where = if clauses.is_empty() {
167 "course WHERE true".to_string()
168 } else {
169 format!("course WHERE {}", clauses.join(" AND "))
170 };
171 let mut page = PagedList::new(from_where, "ORDER BY id DESC");
172 for bind in binds {
173 page = page.bind(bind);
174 }
175 let (rows, _) = page.run::<CourseRow>(None, 0, db).await?;
176 Ok(rows.into_iter().map(CourseRow::into_course).collect())
177}
178
179/// The courses `user` is enrolled in — read through the *instances* their
180/// enrollments name, since an enrollment keys on the class×course instance.
181/// The spine of `/courses/me` and the marks report.
182pub async fn list_enrolled(
183 db: &Database,
184 user: &UserId,
185 limit: Option<i64>,
186 offset: i64,
187) -> Result<(Vec<Course>, i64), AppError> {
188 let (rows, total) = PagedList::new(
189 "course WHERE id IN (
190 SELECT cc.course FROM enrollment e
191 JOIN class_course cc ON cc.id = e.class_course
192 WHERE e.app_user = $1)",
193 "ORDER BY id DESC",
194 )
195 .bind(user.uuid())
196 .run::<CourseRow>(limit, offset, db)
197 .await?;
198 Ok((
199 rows.into_iter().map(CourseRow::into_course).collect(),
200 total,
201 ))
202}
203
204/// The courses `user` teaches somewhere — the ones a manager assigned them to
205/// on some instance. A teacher's slice of the catalog.
206///
207/// It reads `class_course_teacher` by its `teacher` index and follows each
208/// assignment to the catalog course its instance teaches: a teacher who runs
209/// 5-A's Matematik sees Matematik. The old creator-membership half is gone
210/// with D6 — the catalog is Manager+ owned.
211pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<Course>, AppError> {
212 let rows = sqlx::query_as!(
213 CourseRow,
214 r#"SELECT id AS "id: CourseId", creator AS "creator: UserId",
215 title AS "title: CourseTitle",
216 description AS "description: CourseDescription",
217 kind AS "kind: CourseKind", class_course_count, course_membership_count
218 FROM course WHERE id IN (
219 SELECT cc.course FROM class_course_teacher t
220 JOIN class_course cc ON cc.id = t.class_course
221 WHERE t.teacher = $1)
222 ORDER BY id DESC"#,
223 user.uuid(),
224 )
225 .fetch_all(db)
226 .await?;
227 Ok(rows.into_iter().map(CourseRow::into_course).collect())
228}
229
230/// Load every course behind `ids` (one query) — the join half of the
231/// attendance and marks reports' per-course blocks.
232pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result<Vec<Course>, AppError> {
233 if ids.is_empty() {
234 return Ok(Vec::new());
235 }
236 let keys: Vec<uuid::Uuid> = ids.iter().map(CourseId::uuid).collect();
237 let rows = sqlx::query_as!(
238 CourseRow,
239 r#"SELECT id AS "id: CourseId", creator AS "creator: UserId",
240 title AS "title: CourseTitle",
241 description AS "description: CourseDescription",
242 kind AS "kind: CourseKind", class_course_count, course_membership_count
243 FROM course WHERE id = ANY($1)"#,
244 &keys,
245 )
246 .fetch_all(db)
247 .await?;
248 Ok(rows.into_iter().map(CourseRow::into_course).collect())
249}
250
251/// Field-scoped: a field the request omitted (`None`) is not written at all.
252/// Sending the snapshot's value back instead would revert a concurrent edit of
253/// that field; scoping the `SET` alone does not stop that, the values have to
254/// come from the request.
255///
256/// The two counters and `creator` are not editable: the counters are what the
257/// delete guard reads (a PATCH is not a roster change), and the creator is the
258/// catalog's of record.
259pub async fn update(
260 db: &Database,
261 course: Course,
262 title: Option<CourseTitle>,
263 description: Option<CourseDescription>,
264 kind: Option<CourseKind>,
265) -> Result<Course, AppError> {
266 let row = crate::db::field_update::FieldUpdate::new(COURSE_TABLE, course.id.uuid())
267 .set("title", title.map(|title| title.as_str().to_owned()))
268 .set(
269 "description",
270 description.map(|description| description.as_str().to_owned()),
271 )
272 .set("kind", kind.map(|kind| kind.as_str().to_owned()))
273 .run::<CourseRow>(db)
274 .await?;
275 Ok(row.into_course())
276}
277
278/// Delete the course and cascade-remove everything inside it *through its
279/// instances*: results, attempts, answers, and question/answer images of
280/// their exams, their homework with submissions, submission files, and
281/// grades, their enrollments, their sessions with their roll call, their
282/// teachers, and — last — the `class_course` rows themselves (each class
283/// getting its attachment counter back, or it would be undeletable over rows
284/// pointing at nothing). The children go in one transaction so a crash can't
285/// leave an exam pointing at a deleted course. The image and homework-file
286/// *blobs* are the web layer's to remove — it collects their names before
287/// calling this.
288///
289/// The guard is the two counters on the locked row (D5/D6): an instance still
290/// teaching this course refuses the delete, and so does an individual club
291/// membership, because nothing here unlinks either. Detach the instances and
292/// empty the memberships first — a catalog course whose last instance goes is
293/// then deletable, which is the whole point of the catalog being a template.
294///
295/// **Bank templates** survive it — they are a separate, reusable library
296/// spanning every course — so their `source_exam` and `subject` links are
297/// cleared instead, in this same transaction, exactly as
298/// [`crate::db::exam::delete`] and [`crate::db::subject::delete`]
299/// clear them one level down. Deleting a course must leave the bank where
300/// deleting each of its exams and subjects by hand would have left it, or
301/// a template is left pointing at a dead exam (permanently: nothing else
302/// ever visits that column) and at a dead subject the next `PATCH`
303/// omitting `subject_id` writes straight back.
304///
305/// The **grade blueprints** naming it are swept in that same transaction —
306/// their `blueprint_course` link rows are FK children now, deleted right
307/// here like any other link, so a template stops naming a course the
308/// instant that course goes (the old `teachers`-style array made the id a
309/// permanent dangling value only the pump's [`crate::db::class_blueprint::
310/// prune`] could chase). The same transaction takes the instances'
311/// `class_course_teacher` assignment rows: an assigned teacher loses the
312/// instance with it.
313///
314/// The **derived AI rows** (`rag_output` carries a denormalized `course`
315/// besides its note link) and the event **audience links** are FK children
316/// the old store let dangle: `rag_output` is disposable and dies here, and
317/// an event whose audience was "this course's students" keeps standing with
318/// `audience_course` cleared — an empty roster, exactly the documented
319/// outcome of the class twin (`ClassGroup::delete` never touched `event`;
320/// it still doesn't delete one).
321///
322/// The marks going with it give their exam kinds' references back, counted
323/// per kind inside this same transaction — the mirror of `Exam::delete`.
324/// Skipping it would leave every kind the course graded under counted
325/// forever, and a counted kind can never leave the school's settings.
326///
327/// **Order is the foreign-key graph, children first**: exam results/attempts/
328/// answers/audiences/images and question images before `exam_question`;
329/// `exam_question` before `exam`; homework files before submissions before
330/// results before `homework`; roll-call rows before `course_session`;
331/// enrollment / teacher / audience rows before `class_course`; note files and
332/// rag rows before `course_note`; `blueprint_course`, `course_membership` and
333/// `class_course` before the `course` row itself, whose `NO ACTION` FKs are
334/// checked the moment the final `DELETE` runs.
335///
336/// `false` = refused, nothing was written: a class still teaches it, or
337/// someone still holds a membership. The guard locks the course row
338/// (`FOR UPDATE`) and reads its own counters, so an attach or a join racing
339/// this either claims first (and the delete is refused) or finds the row gone
340/// (and is refused itself). `Err(NotFound)` keeps the answer a concurrent
341/// *delete* used to get — and unlike the old one-statement guard, this one
342/// tells the two apart without a second read.
343pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
344 tx_with_retry(db, true, async move |tx| {
345 // The guard and the lock: the row (and its two counters) cannot
346 // change under this transaction, and every attach or membership
347 // claim contends on this very row, so check and cascade are one
348 // decision.
349 let guard = sqlx::query!(
350 r#"SELECT class_course_count, course_membership_count FROM course
351 WHERE id = $1 FOR UPDATE"#,
352 course.id.uuid(),
353 )
354 .fetch_optional(&mut *tx)
355 .await?;
356 let Some(guard) = guard else {
357 return Err(AppError::NotFound);
358 };
359 if guard.class_course_count != 0 || guard.course_membership_count != 0 {
360 return Ok(false);
361 }
362 // Events aimed at this course keep standing, audience cleared.
363 sqlx::query!(
364 r#"UPDATE event SET audience_course = NULL WHERE audience_course = $1"#,
365 course.id.uuid(),
366 )
367 .execute(&mut *tx)
368 .await?;
369 // The instances and everything under them. The guard above refuses a
370 // course that still carries one, so this sweep is defensive: a counter
371 // is the guard's *input*, and a guard reading a stale number is
372 // exactly the shape this exists to survive. The blob keys it returns
373 // are already collected by the caller (`file_keys_for_course`), which
374 // reads them before the rows go, so they are dropped here.
375 let instances: Vec<uuid::Uuid> = sqlx::query_scalar!(
376 r#"SELECT id AS "id: uuid::Uuid" FROM class_course WHERE course = $1"#,
377 course.id.uuid(),
378 )
379 .fetch_all(&mut *tx)
380 .await?;
381 for instance in &instances {
382 let _blobs = sweep_instance_subtree(&mut *tx, *instance).await?;
383 }
384 // Derived AI rows for this course's notes — links before the rows
385 // (`ON DELETE NO ACTION`).
386 sqlx::query!(
387 r#"DELETE FROM rag_output_source WHERE output IN (
388 SELECT id FROM rag_output WHERE course = $1)"#,
389 course.id.uuid(),
390 )
391 .execute(&mut *tx)
392 .await?;
393 sqlx::query!(
394 r#"DELETE FROM rag_output WHERE course = $1"#,
395 course.id.uuid()
396 )
397 .execute(&mut *tx)
398 .await?;
399 // Notes: files before their notes.
400 sqlx::query!(
401 r#"DELETE FROM course_note_file WHERE course_note IN (
402 SELECT id FROM course_note WHERE course = $1)"#,
403 course.id.uuid(),
404 )
405 .execute(&mut *tx)
406 .await?;
407 sqlx::query!(
408 r#"DELETE FROM course_note WHERE course = $1"#,
409 course.id.uuid()
410 )
411 .execute(&mut *tx)
412 .await?;
413 // The instances, each class handed its attachment counter back in
414 // the same statement.
415 sqlx::query!(
416 r#"WITH detached AS (
417 DELETE FROM class_course WHERE course = $1 RETURNING class)
418 UPDATE class_group g
419 SET class_course_count = GREATEST(g.class_course_count - 1, 0)
420 FROM detached WHERE g.id = detached.class"#,
421 course.id.uuid(),
422 )
423 .execute(&mut *tx)
424 .await?;
425 sqlx::query!(
426 r#"DELETE FROM course_membership WHERE course = $1"#,
427 course.id.uuid(),
428 )
429 .execute(&mut *tx)
430 .await?;
431 sqlx::query!(
432 r#"DELETE FROM blueprint_course WHERE course = $1"#,
433 course.id.uuid(),
434 )
435 .execute(&mut *tx)
436 .await?;
437 // The bank keeps its templates; their links to this course's
438 // content go first, so the subject delete below cannot trip a
439 // foreign key behind them.
440 sqlx::query!(
441 r#"UPDATE bank_question SET subject = NULL
442 WHERE subject IN (SELECT id FROM subject WHERE course = $1)"#,
443 course.id.uuid(),
444 )
445 .execute(&mut *tx)
446 .await?;
447 sqlx::query!(r#"DELETE FROM subject WHERE course = $1"#, course.id.uuid())
448 .execute(&mut *tx)
449 .await?;
450 // Last: the course itself, now FK-silent.
451 sqlx::query!(r#"DELETE FROM course WHERE id = $1"#, course.id.uuid())
452 .execute(&mut *tx)
453 .await?;
454 Ok(true)
455 })
456 .await
457}
458
459/// Everything hanging off one instance, deleted children-first with the
460/// counters it holds refunded — the sweep both [`crate::db::class_pump::
461/// detach_course`] and [`delete`] run, and the only place the instance's
462/// foreign-key graph is spelled.
463///
464/// The order is the graph: exam results/attempts/answers/audiences and
465/// question/answer images before `exam_question`; the question rows give their
466/// subjects' `exam_question_count` back and the results their kinds'
467/// `kind_ref` count; bank templates keep standing with `source_exam` cleared;
468/// homework files before submissions (whose `grad_by_result` stamp points at a
469/// result row) before results before assignments before `homework`; roll-call
470/// rows before `course_session`; then the roster, the teacher links and the
471/// audience rows, and the caller takes the instance row itself last.
472///
473/// Returns the blob keys of the image and homework-file rows it removed, so a
474/// caller whose web route unlinks bytes can do it after the commit; a caller
475/// that collected them beforehand ([`crate::service::course::delete`]) drops
476/// them.
477///
478/// **Every reference counter it gives back is driven by the rows a
479/// `DELETE … RETURNING` actually removed** — `exam`→`term.exam_count`,
480/// `exam_result`→`kind_ref.count`, `exam_question`→`subject.exam_question_count`,
481/// `homework`→`subject.homework_count` — never by a count taken off a
482/// statement-start snapshot. The difference is a race: `Exam::delete` and
483/// `remove_result` release some of these counters themselves, so a
484/// count-then-subtract pair would hand one row's reference back twice (a
485/// counter one low, permanently — `GREATEST` only floors at zero), and a kind
486/// still carrying marks could then be retired from settings. Fused this way an
487/// interleaving is exact from either side: the loser's `DELETE` simply does
488/// not return the row the winner took.
489///
490/// The row locks it takes are the ones the children's own writers take (the
491/// instance row `FOR UPDATE` is the caller's, before this runs), so a grade or
492/// an upload racing the sweep either lands before it (and is swept) or finds
493/// its parent gone and is refused.
494pub(crate) async fn sweep_instance_subtree(
495 tx: &mut PgConnection,
496 instance: uuid::Uuid,
497) -> Result<Vec<String>, AppError> {
498 let exams: Vec<uuid::Uuid> = sqlx::query_scalar!(
499 r#"SELECT id AS "id: uuid::Uuid" FROM exam WHERE class_course = $1"#,
500 instance,
501 )
502 .fetch_all(&mut *tx)
503 .await?;
504 // Every release below is driven by the rows a `DELETE … RETURNING`
505 // actually removed, in the shape [`crate::db::exam_result::remove`] uses,
506 // and never by a count taken off a statement-start snapshot: a concurrent
507 // `Exam::delete` or `remove_result` releases the same counters itself, so
508 // a count-then-subtract pair would release its row twice — a `kind_ref`
509 // one low permanently (GREATEST only floors at zero), which then lets a
510 // kind still carrying marks be retired from settings.
511 let image_files: Vec<String> = sqlx::query_scalar!(
512 r#"SELECT file FROM question_image WHERE exam = ANY($1)"#,
513 &exams,
514 )
515 .fetch_all(&mut *tx)
516 .await?;
517 let answer_image_files: Vec<String> = sqlx::query_scalar!(
518 r#"SELECT file FROM answer_image WHERE exam = ANY($1)"#,
519 &exams,
520 )
521 .fetch_all(&mut *tx)
522 .await?;
523 // Both directions of the audience table, and each has to go before the
524 // row it names. The rows *addressed to* this instance (an exam owned by
525 // another instance may be announced here — a shared exam) reference the
526 // `class_course` row the caller deletes right after this sweep and would
527 // otherwise refuse it with a `23503`. The rows *of* the exams this sweep
528 // deletes reference *those* exams the same way (`exam_audience.exam` is
529 // `NO ACTION` too), so they block the `DELETE FROM exam` below wherever
530 // they point — an audience of a swept exam in a section that is *not* being
531 // detached included.
532 //
533 // The instance row is held `FOR UPDATE` by the caller from before this
534 // sweep, and an insert into `exam_audience` takes that row's
535 // `FOR KEY SHARE` through its foreign key, so no audience *addressed to*
536 // this instance can land under the sweep: the `add` blocks behind the
537 // detach and, on the settled state, finds the instance gone (`404`). An
538 // audience of one of the swept *exams* rides that exam's own key-share
539 // lock instead; if it commits between this delete and the exam delete
540 // below, the `exam_audience_exam_fkey` refusal that follows is what the
541 // detach's `cascade` retry re-runs on — the second round sees the
542 // settled row and takes it.
543 sqlx::query!(
544 r#"DELETE FROM exam_audience WHERE class_course = $1 OR exam = ANY($2)"#,
545 instance,
546 &exams,
547 )
548 .execute(&mut *tx)
549 .await?;
550 // Every mark this sweep takes gives its exam kind's reference back, per
551 // kind, off the rows this statement removed. The kind rides the exam row —
552 // `exam_result` names its exam, not its kind — so the deleted rows are
553 // joined back to the exam they named *before* it goes (the exam row is
554 // still there: this runs ahead of the `DELETE FROM exam` at the end).
555 sqlx::query!(
556 r#"WITH gone AS (
557 DELETE FROM exam_result WHERE exam = ANY($1)
558 RETURNING exam),
559 kinds AS (
560 SELECT e.kind AS kind, count(*) AS n
561 FROM gone g JOIN exam e ON e.id = g.exam
562 GROUP BY e.kind)
563 UPDATE kind_ref k SET count = GREATEST(k.count - c.n, 0)
564 FROM kinds c WHERE k.name = c.kind"#,
565 &exams,
566 )
567 .execute(&mut *tx)
568 .await?;
569 sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = ANY($1)"#, &exams)
570 .execute(&mut *tx)
571 .await?;
572 sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = ANY($1)"#, &exams)
573 .execute(&mut *tx)
574 .await?;
575 sqlx::query!(r#"DELETE FROM answer_image WHERE exam = ANY($1)"#, &exams)
576 .execute(&mut *tx)
577 .await?;
578 sqlx::query!(r#"DELETE FROM question_image WHERE exam = ANY($1)"#, &exams)
579 .execute(&mut *tx)
580 .await?;
581 // The cascaded questions give their subject references back off the rows
582 // this statement removed, per subject — released with the delete, never
583 // counted ahead of it.
584 sqlx::query!(
585 r#"WITH gone AS (
586 DELETE FROM exam_question WHERE exam = ANY($1)
587 RETURNING subject),
588 subs AS (
589 SELECT subject, count(*) AS n FROM gone GROUP BY subject)
590 UPDATE subject s SET exam_question_count = GREATEST(s.exam_question_count - c.n, 0)
591 FROM subs c WHERE s.id = c.subject"#,
592 &exams,
593 )
594 .execute(&mut *tx)
595 .await?;
596 // Bank templates survive the exam they were saved from — only the
597 // provenance link is cleared.
598 sqlx::query!(
599 r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = ANY($1)"#,
600 &exams,
601 )
602 .execute(&mut *tx)
603 .await?;
604 // The swept exams give their term's reference back off the rows this
605 // statement removed, per term (the mirror of `Exam::delete`'s
606 // single-exam release): `db::exam::create` claimed `term.exam_count` for
607 // each of them, and a claim nothing releases leaves the term's
608 // `exam_count = 0` delete guard permanently failing — which takes the
609 // term, and the academic year whose own guard counts its terms, down
610 // with it. Fused with the delete for the same reason the two releases
611 // above are: a concurrent single-exam delete releases its own claim, so a
612 // count taken before this statement could give one back twice.
613 sqlx::query!(
614 r#"WITH gone AS (
615 DELETE FROM exam WHERE class_course = $1
616 RETURNING term),
617 terms AS (
618 SELECT term, count(*) AS n FROM gone GROUP BY term)
619 UPDATE term t SET exam_count = GREATEST(t.exam_count - c.n, 0)
620 FROM terms c WHERE t.id = c.term"#,
621 instance,
622 )
623 .execute(&mut *tx)
624 .await?;
625 let homework_files: Vec<String> = sqlx::query_scalar!(
626 r#"SELECT file FROM homework_file
627 WHERE submission IN (SELECT id FROM homework_submission WHERE homework IN (
628 SELECT id FROM homework WHERE class_course = $1))"#,
629 instance,
630 )
631 .fetch_all(&mut *tx)
632 .await?;
633 sqlx::query!(
634 r#"DELETE FROM homework_file
635 WHERE submission IN (SELECT id FROM homework_submission WHERE homework IN (
636 SELECT id FROM homework WHERE class_course = $1))"#,
637 instance,
638 )
639 .execute(&mut *tx)
640 .await?;
641 sqlx::query!(
642 r#"DELETE FROM homework_submission WHERE homework IN (
643 SELECT id FROM homework WHERE class_course = $1)"#,
644 instance,
645 )
646 .execute(&mut *tx)
647 .await?;
648 sqlx::query!(
649 r#"DELETE FROM homework_result WHERE homework IN (
650 SELECT id FROM homework WHERE class_course = $1)"#,
651 instance,
652 )
653 .execute(&mut *tx)
654 .await?;
655 sqlx::query!(
656 r#"DELETE FROM homework_assignment WHERE homework IN (
657 SELECT id FROM homework WHERE class_course = $1)"#,
658 instance,
659 )
660 .execute(&mut *tx)
661 .await?;
662 // The homework rows give their subjects' counters back off the rows this
663 // statement removed, per subject — the same fused shape as the two above.
664 sqlx::query!(
665 r#"WITH gone AS (
666 DELETE FROM homework WHERE class_course = $1
667 RETURNING subject),
668 subs AS (
669 SELECT subject, count(*) AS n FROM gone GROUP BY subject)
670 UPDATE subject s SET homework_count = GREATEST(s.homework_count - c.n, 0)
671 FROM subs c WHERE s.id = c.subject"#,
672 instance,
673 )
674 .execute(&mut *tx)
675 .await?;
676 sqlx::query!(
677 r#"DELETE FROM session_attendance WHERE class_course = $1"#,
678 instance
679 )
680 .execute(&mut *tx)
681 .await?;
682 sqlx::query!(
683 r#"DELETE FROM course_session WHERE class_course = $1"#,
684 instance
685 )
686 .execute(&mut *tx)
687 .await?;
688 // The roster: every enrollment row of the instance, hand-placed included —
689 // the instance is the row's own parent key, so none can outlive it.
690 sqlx::query!(
691 r#"DELETE FROM enrollment WHERE class_course = $1"#,
692 instance
693 )
694 .execute(&mut *tx)
695 .await?;
696 sqlx::query!(
697 r#"DELETE FROM class_course_teacher WHERE class_course = $1"#,
698 instance
699 )
700 .execute(&mut *tx)
701 .await?;
702 let mut blobs = image_files;
703 blobs.extend(answer_image_files);
704 blobs.extend(homework_files);
705 Ok(blobs)
706}
707
708/// A real course row, for the tests of every child that must now prove its
709/// parent exists. A minted id nothing wrote is a 404 there, the way a minted
710/// subject id already is for an exam question.
711#[cfg(test)]
712pub(crate) async fn a_test_course(db: &Database) -> CourseId {
713 // The creator is a foreign key now: a real row, minted per call so
714 // repeated calls are new people, not the same one.
715 let creator = UserId::generate();
716 sqlx::query(
717 "INSERT INTO app_user (id, username, created_at, role) \
718 VALUES ($1, $2, 0, 'teacher')",
719 )
720 .bind(creator.uuid())
721 .bind(format!("course-fixture-{}", &creator.key()[30..]))
722 .execute(db)
723 .await
724 .unwrap();
725 create(
726 db,
727 &creator,
728 CourseTitle::try_new("test course").unwrap(),
729 CourseDescription::try_new("").unwrap(),
730 CourseKind::course(),
731 )
732 .await
733 .unwrap()
734 .id
735}
736
737/// A real *instance* of that course, attached to a fresh class — the parent
738/// every re-keyed child (exam, session, homework, enrollment) now hangs off,
739/// for the tests of those children.
740///
741/// Returned as a pair because a child write that names the instance usually
742/// also wants the catalog course (a subject's `course`, a marks read's
743/// course grouping); both are real rows, minted per call.
744#[cfg(test)]
745pub(crate) async fn a_test_instance(
746 db: &Database,
747) -> (crate::domain::class_course::ClassCourseId, CourseId) {
748 use crate::domain::class_group::ClassName;
749
750 let manager = UserId::generate();
751 sqlx::query(
752 "INSERT INTO app_user (id, username, created_at, role) \
753 VALUES ($1, $2, 0, 'manager')",
754 )
755 .bind(manager.uuid())
756 .bind(format!("instance-fixture-{}", &manager.key()[30..]))
757 .execute(db)
758 .await
759 .unwrap();
760 let class = crate::db::class_group::create(
761 db,
762 &manager,
763 ClassName::try_new("9-A").unwrap(),
764 crate::domain::grade::GradeLevel::new(9).unwrap(),
765 None,
766 None,
767 )
768 .await
769 .unwrap();
770 let course = a_test_course(db).await;
771 let attached = crate::service::class_course::attach(db, class.get_id(), &course, &manager)
772 .await
773 .unwrap();
774 (attached.get_id().clone(), course)
775}
776
777/// The race half of "a child of a course must not survive its deletion", run
778/// for one child table.
779///
780/// The harness lives here, beside the cascade being raced, and each child names
781/// its own pin in its own module (`exam`, `course_session`, `subject`) — the
782/// orders, the window and the verdict are one fact about *this* delete, and
783/// three copies of it would drift into three different tests of three different
784/// things. The sequential half — a create against a course that is already gone
785/// — is `tests/regress_course_child_orphans.rs`, which needs no server.
786///
787/// The orphan query is the caller's, because the child's key to the course is
788/// not: `subject` still names the course directly, while an exam or a session
789/// hangs off an *instance* ([`crate::db::class_course`]) and reaches the course
790/// through it. Either way it takes the course uuid as `$1`.
791///
792/// Both orders are forced by awaiting one side to completion before the other
793/// starts. A barrier is a coin toss under load: whichever side is marginally
794/// faster takes every overlapped round, and requiring the delete to win one of
795/// them fails a run that never let it. A few rounds still start together; those
796/// may all lose the delete, and that is not a failure. A rival that claims an
797/// instance (a session, an exam) makes the write-first delete a refusal — the
798/// course a class still teaches is not deletable — so that round asserts the
799/// refusal, not a sweep. The sweep is the delete-first round, and any round
800/// whose course is actually gone.
801///
802/// One child per round, for the reason the menu and `class_course` twins
803/// document: a second writer makes the delete lose and re-send, and the re-sent
804/// sweep clears the evidence.
805///
806/// Real server: the subject is the store's conflict detection, which an
807/// embedded engine does not have.
808#[cfg(test)]
809pub(crate) async fn assert_no_child_outlives_a_course_delete(
810 table: &str,
811 orphan_count_sql: &str,
812 make: fn(CourseId, Database) -> tokio::task::JoinHandle<Result<(), AppError>>,
813) {
814
815 async fn child_rows(db: &Database, sql: &str, course: &CourseId) -> usize {
816 use sqlx::Row as _;
817 sqlx::query(sqlx::AssertSqlSafe(sql.to_string()))
818 .bind(course.uuid())
819 .fetch_one(db)
820 .await
821 .unwrap()
822 .try_get::<i64, _>(0)
823 .unwrap() as usize
824 }
825
826 let (db, _leases) = crate::database::init_test_db().await;
827
828 // Delete-first: the course is gone before the child starts.
829 {
830 let course = a_test_course(&db).await;
831 let dropped = delete(
832 &db,
833 read(&db, &course)
834 .await
835 .unwrap()
836 .expect("the course is there"),
837 )
838 .await;
839 assert!(
840 matches!(dropped, Ok(true)),
841 "{table} delete-first: an empty course must delete, not {dropped:?}"
842 );
843 assert!(
844 read(&db, &course).await.unwrap().is_none(),
845 "{table} delete-first: the course is still there"
846 );
847 let child = make(course.clone(), db.clone()).await.unwrap();
848 assert!(
849 !matches!(child, Err(AppError::Db(_))),
850 "{table} delete-first: a create must be answered, not 500: {child:?}"
851 );
852 assert_eq!(
853 child_rows(&db, orphan_count_sql, &course).await,
854 0,
855 "{table}: a child outlived its course"
856 );
857 }
858
859 // Write-first: the child lands, then the delete. A rival that claimed an
860 // instance makes this a refusal — the course stays, and that is correct.
861 // A rival that did not (a subject) is swept: the course is gone and the
862 // child count is 0.
863 {
864 let course = a_test_course(&db).await;
865 let child = make(course.clone(), db.clone()).await.unwrap();
866 assert!(
867 child.is_ok(),
868 "{table} write-first: the child must land before the delete: {child:?}"
869 );
870 let row = read(&db, &course).await.unwrap().expect(
871 "{table} write-first: the course vanished before the delete",
872 );
873 let dropped = delete(&db, row).await;
874 assert!(
875 !matches!(dropped, Err(AppError::Db(_))),
876 "{table} write-first: a delete must be answered, not 500: {dropped:?}"
877 );
878 let gone = read(&db, &course).await.unwrap().is_none();
879 if matches!(dropped, Ok(true)) && !gone {
880 panic!(
881 "{table} write-first: the delete reported success, the course is still there"
882 );
883 }
884 if gone {
885 assert_eq!(
886 child_rows(&db, orphan_count_sql, &course).await,
887 0,
888 "{table}: a child outlived its course"
889 );
890 }
891 }
892
893 // Overlapped rounds. Delete may lose every one of them.
894 let mut swept = 0;
895 for round in 0..4 {
896 let course = a_test_course(&db).await;
897 let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
898 let drop_it = {
899 let (course, db, gate) = (course.clone(), db.clone(), gate.clone());
900 tokio::spawn(async move {
901 gate.wait().await;
902 delete(
903 &db,
904 read(&db, &course)
905 .await
906 .unwrap()
907 .expect("the course is there"),
908 )
909 .await
910 })
911 };
912 let child = {
913 let (course, db, gate) = (course.clone(), db.clone(), gate);
914 tokio::spawn(async move {
915 gate.wait().await;
916 make(course, db).await.unwrap()
917 })
918 }
919 .await
920 .unwrap();
921 let dropped = drop_it.await.unwrap();
922 assert!(
923 !matches!(child, Err(AppError::Db(_))),
924 "{table} round {round}: a raced create must be answered, not 500: {child:?}"
925 );
926 assert!(
927 !matches!(dropped, Err(AppError::Db(_))),
928 "{table} round {round}: a raced delete must be answered, not 500: {dropped:?}"
929 );
930 if read(&db, &course).await.unwrap().is_none() {
931 swept += 1;
932 assert_eq!(
933 child_rows(&db, orphan_count_sql, &course).await,
934 0,
935 "{table} round {round}: a child outlived its course"
936 );
937 } else if matches!(dropped, Ok(true)) {
938 panic!(
939 "{table} round {round}: the delete reported success, the course is still there"
940 );
941 }
942 }
943 eprintln!(
944 "Course::delete raced by a {table} create: {swept}/4 concurrent rounds deleted the course"
945 );
946}
947
948#[cfg(test)]
949mod tests {
950 use super::*;
951 use sqlx::Row as _;
952
953 /// A real `app_user` row: creators, attached-bys and managers are foreign
954 /// keys now. The label names the row's username; the id is minted, so
955 /// repeated calls are new people, not the same row.
956 async fn a_person(db: &Database, label: &str, role: &str) -> UserId {
957 let user = UserId::generate();
958 sqlx::query(
959 "INSERT INTO app_user (id, username, created_at, role) \
960 VALUES ($1, $2, 0, $3)",
961 )
962 .bind(user.uuid())
963 .bind(format!("{label}-{}", &user.key()[30..]))
964 .bind(role)
965 .execute(db)
966 .await
967 .unwrap();
968 user
969 }
970
971 /// A catalog course, minted per call. The catalog is a school-wide
972 /// template since the remodel: no term to link, no capacity to store.
973 async fn a_course(db: &Database) -> Course {
974 create(
975 db,
976 &a_person(db, "teacher", "teacher").await,
977 CourseTitle::try_new("algebra").unwrap(),
978 CourseDescription::try_new("").unwrap(),
979 CourseKind::course(),
980 )
981 .await
982 .unwrap()
983 }
984
985 /// A section, for the tests that need an instance attached to it.
986 async fn a_class(
987 on: &UserId,
988 name: &str,
989 db: &Database,
990 ) -> crate::domain::class_group::ClassGroup {
991 crate::db::class_group::create(
992 db,
993 on,
994 crate::domain::class_group::ClassName::try_new(name).unwrap(),
995 crate::domain::grade::GradeLevel::new(9).unwrap(),
996 None,
997 None,
998 )
999 .await
1000 .unwrap()
1001 }
1002
1003 /// The instances a course is attached through, re-read from storage —
1004 /// never off a return value.
1005 async fn instance_rows(course: &CourseId, db: &Database) -> i64 {
1006 sqlx::query("SELECT count(*) FROM class_course WHERE course = $1")
1007 .bind(course.uuid())
1008 .fetch_one(db)
1009 .await
1010 .unwrap()
1011 .try_get::<i64, _>(0)
1012 .unwrap()
1013 }
1014
1015 /// How many rows a table holds (the table name is a fixture literal).
1016 async fn rows(table: &str, db: &Database) -> usize {
1017 sqlx::query(sqlx::AssertSqlSafe(format!("SELECT count(*) FROM {table}")))
1018 .fetch_one(db)
1019 .await
1020 .unwrap()
1021 .try_get::<i64, _>(0)
1022 .unwrap() as usize
1023 }
1024
1025 /// The bite test for the delete guard that replaced `ENROLL_LOCK`: the
1026 /// guard is the two counters on the locked course row, so the anchor's
1027 /// refusal is a live instance — and it must refuse having written
1028 /// nothing, the instance least of all. A `>= 0` guard passes the guard
1029 /// branch and fails here by deleting the course out from under its class.
1030 #[tokio::test]
1031 async fn a_course_an_instance_still_teaches_refuses_to_delete() {
1032 let (db, _leases) = crate::database::init_test_db().await;
1033 let manager = a_person(&db, "manager", "manager").await;
1034 let course = a_course(&db).await;
1035 let class = a_class(&manager, "9-A", &db).await;
1036 let instance =
1037 crate::service::class_course::attach(&db, class.get_id(), course.get_id(), &manager)
1038 .await
1039 .unwrap();
1040
1041 assert!(
1042 !delete(&db, course.clone()).await.unwrap(),
1043 "a course a class still teaches must refuse the delete"
1044 );
1045 assert!(
1046 read(&db, course.get_id()).await.unwrap().is_some(),
1047 "a refused delete may write nothing"
1048 );
1049 assert!(
1050 crate::db::class_course::read(&db, instance.get_id())
1051 .await
1052 .unwrap()
1053 .is_some(),
1054 "…the instance least of all"
1055 );
1056
1057 // Detaching the last instance frees the row: the catalog is a
1058 // template, and the template whose last class let it go is deletable.
1059 crate::service::class_course::detach(&db, class.get_id(), course.get_id())
1060 .await
1061 .unwrap();
1062 assert!(delete(&db, course.clone()).await.unwrap());
1063 assert!(read(&db, course.get_id()).await.unwrap().is_none());
1064
1065 // …and the counter the guard read is back to zero with it, not left
1066 // stranded by the cascade.
1067 assert_eq!(
1068 instance_rows(course.get_id(), &db).await,
1069 0,
1070 "the instance rows must go with the course"
1071 );
1072 assert_eq!(
1073 rows("course", &db).await,
1074 0,
1075 "no row may outlive the delete"
1076 );
1077 }
1078
1079 /// MEASUREMENT — the one race test for `Course::delete`, and the only
1080 /// test that measures `tx_with_retry` on this path at all.
1081 ///
1082 /// [`delete`] is one `BEGIN…COMMIT` whose guard locks the course row the
1083 /// very counter an attach claims, so the two contend by design: the
1084 /// attach is several statements long (the early verdicts, the counter
1085 /// claim, the roster pump) and the delete's cascade is longer, so a
1086 /// rival's write lands mid-transaction. Losing that round writes nothing,
1087 /// which is what makes re-sending it the recovery. Without
1088 /// [`crate::database::transaction_with_retry`] a lost round comes out as
1089 /// a 500: mutation-tested by cutting that retry loop to one attempt, which
1090 /// turns this test red at 1-2 of 20 rounds (3 runs in 5 — the window is
1091 /// real but narrow, so a single green run under the mutation means
1092 /// nothing).
1093 ///
1094 /// A refusal (`Ok(false)`) or an `Err(NotFound)` is *correct* here and
1095 /// must not fail this test: the only defect is `AppError::Db`. The stored
1096 /// half of the verdict is the orphan check — an instance may never name a
1097 /// course that is gone, whichever side of the race it was on.
1098 ///
1099 /// The 500s are counted over the overlapped rounds instead of asserted at
1100 /// the first hit, so a lost retry reports how often it happened. Those
1101 /// rounds do not have to observe both verdicts: a 2ms head start is still
1102 /// a coin toss under pool contention. Delete-first and attach-first below
1103 /// force the two orders by awaiting one side to completion. A delete that
1104 /// reports success (`Ok(true)`) while the course remains is still a bug.
1105 ///
1106 /// Multi-threaded and on a real server: the current-thread runtime never
1107 /// interleaves the two, and an embedded engine does not conflict-check
1108 /// concurrent writes at all.
1109 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1110 async fn a_delete_racing_an_attach_never_answers_500() {
1111 let (db, _leases) = crate::database::init_test_db().await;
1112 let manager = a_person(&db, "mgr", "manager").await;
1113 // One section per racer; each round attaches them all into one fresh
1114 // catalog course, so the round's delete has six rival claims to meet.
1115 let mut classes = Vec::new();
1116 for seat in 0..6 {
1117 classes.push(a_class(&manager, &format!("9-{seat}"), &db).await);
1118 }
1119
1120 // Delete-first: the course is gone before any attach starts.
1121 {
1122 let course = a_course(&db).await;
1123 let dropped = delete(&db, course.clone()).await;
1124 assert!(
1125 matches!(dropped, Ok(true)),
1126 "delete-first: an empty course must delete, not {dropped:?}"
1127 );
1128 assert!(
1129 read(&db, course.get_id()).await.unwrap().is_none(),
1130 "delete-first: the course is still there"
1131 );
1132 for class in &classes {
1133 let attached = crate::service::class_course::attach(
1134 &db,
1135 class.get_id(),
1136 course.get_id(),
1137 &manager,
1138 )
1139 .await;
1140 assert!(
1141 !matches!(attached, Err(AppError::Db(_))),
1142 "delete-first: an attach must be answered, not 500: {attached:?}"
1143 );
1144 }
1145 assert_eq!(
1146 instance_rows(course.get_id(), &db).await,
1147 0,
1148 "an instance outlived the course"
1149 );
1150 }
1151
1152 // Attach-first: the guard must refuse. The course stays; that is the
1153 // verdict, not a missed sweep.
1154 {
1155 let course = a_course(&db).await;
1156 for class in &classes {
1157 let attached = crate::service::class_course::attach(
1158 &db,
1159 class.get_id(),
1160 course.get_id(),
1161 &manager,
1162 )
1163 .await;
1164 assert!(
1165 attached.is_ok(),
1166 "attach-first: the attach must land before the delete: {attached:?}"
1167 );
1168 }
1169 let dropped = delete(&db, course.clone()).await;
1170 assert!(
1171 !matches!(dropped, Err(AppError::Db(_))),
1172 "attach-first: a delete must be answered, not 500: {dropped:?}"
1173 );
1174 assert!(
1175 matches!(dropped, Ok(false)),
1176 "attach-first: a course a class still teaches must refuse, not {dropped:?}"
1177 );
1178 assert!(
1179 read(&db, course.get_id()).await.unwrap().is_some(),
1180 "attach-first: the refused delete removed the course"
1181 );
1182 assert!(
1183 instance_rows(course.get_id(), &db).await > 0,
1184 "attach-first: the landed instances are gone"
1185 );
1186 }
1187
1188 // Overlapped rounds keep the retry measurement. Delete may lose all
1189 // of them.
1190 let (mut delete_500, mut attach_500, mut swept) = (0, 0, 0);
1191 let (mut last_delete, mut last_attach) = (String::new(), String::new());
1192 for round in 0..20 {
1193 let course = a_course(&db).await;
1194 let drop_it = {
1195 let (course, db) = (course.clone(), db.clone());
1196 tokio::spawn(async move { delete(&db, course).await })
1197 };
1198 let joins: Vec<_> = classes
1199 .iter()
1200 .map(|class| {
1201 let (class, course, db, mgr) = (
1202 class.get_id().clone(),
1203 course.get_id().clone(),
1204 db.clone(),
1205 manager,
1206 );
1207 tokio::spawn(async move {
1208 crate::service::class_course::attach(&db, &class, &course, &mgr).await
1209 })
1210 })
1211 .collect();
1212 let drop_it = drop_it.await.unwrap();
1213 if matches!(drop_it, Err(AppError::Db(_))) {
1214 delete_500 += 1;
1215 last_delete = format!("{drop_it:?}");
1216 }
1217 for join in joins {
1218 let join = join.await.unwrap();
1219 if matches!(join, Err(AppError::Db(_))) {
1220 attach_500 += 1;
1221 last_attach = format!("{join:?}");
1222 }
1223 }
1224 let live = instance_rows(course.get_id(), &db).await;
1225 let gone = read(&db, course.get_id()).await.unwrap().is_none();
1226 if matches!(drop_it, Ok(true)) && !gone {
1227 panic!(
1228 "round {round}: the delete reported success, the course is still there"
1229 );
1230 }
1231 if gone {
1232 swept += 1;
1233 assert_eq!(
1234 live, 0,
1235 "round {round}: an instance outlived the course it names"
1236 );
1237 }
1238 }
1239 eprintln!(
1240 "Course::delete raced: {delete_500}/20 delete 500s, {attach_500} attach 500s, \
1241 {swept} rounds the course went"
1242 );
1243 assert_eq!(
1244 delete_500, 0,
1245 "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}"
1246 );
1247 assert_eq!(
1248 attach_500, 0,
1249 "a raced attach must be answered, not 500: {attach_500}/20 rounds, last {last_attach}"
1250 );
1251 }
1252}