forge
Explore
Log in

Don't you dare go Hollow

Split exam into domain/db/service layers

Browse files at this commit

606085def8a5309407f089f779e97446fd0eac52Ahmet Kaan GümüşParent: ad1326c
  • chore
    • split exam into domain/db/service layers
Show full message
🧹 chore: split exam into domain/db/service layers

26 changed files +1606 -1413

src/db/course.rsmodified+1 -1
@@ -261,7 +261,7 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App
261261 /// **Bank templates** survive it — they are a separate, reusable library
262262 /// spanning every course — so their `source_exam` and `subject` links are
263263 /// cleared instead, in this same transaction, exactly as
264-/// [`crate::domain::exam::Exam::delete`] and
264+/// [`crate::db::exam::delete`] and
265265 /// [`crate::domain::subject::Subject::delete`] clear them one level down.
266266 /// Deleting a course must leave the bank where deleting each of its exams
267267 /// and subjects by hand would have left it, or a template is left pointing
src/db/exam.rsadded+1109 -0
@@ -0,0 +1,1109 @@
1+//! The `exam` table: row reads and listings, the count-and-create that pins
2+//! the exam to a live course row, the compare-and-set every PATCH writes
3+//! through, and the cascading delete. The PATCH re-derive and the delete's
4+//! blob-key collection live in [`crate::service::exam`].
5+
6+use surrealdb::types::{RecordId, SurrealValue};
7+
8+use crate::constant::ENROLLMENT_COUNT_FIELD;
9+use crate::database::{Database, transaction_with_retry};
10+use crate::db::cap;
11+use crate::domain::course::CourseId;
12+use crate::domain::exam::{
13+ Exam, ExamAttemptLimit, ExamDescription, ExamId, ExamKind, ExamSchedule, ExamTitle,
14+ redraft_error,
15+};
16+use crate::domain::user::UserId;
17+use crate::error::AppError;
18+
19+#[expect(
20+ clippy::too_many_arguments,
21+ reason = "mirrors the sibling entities' create(field, field, ..) shape"
22+)]
23+pub async fn create(
24+ db: &Database,
25+ creator: &UserId,
26+ course: &CourseId,
27+ title: ExamTitle,
28+ description: ExamDescription,
29+ kind: ExamKind,
30+ schedule: ExamSchedule,
31+ max_attempts: ExamAttemptLimit,
32+ allow_rejoin: bool,
33+ allow_review: bool,
34+ draft: bool,
35+) -> Result<Exam, AppError> {
36+ let exam = Exam {
37+ id: ExamId::generate(),
38+ creator: creator.clone(),
39+ course: course.clone(),
40+ title,
41+ description,
42+ kind,
43+ mode: schedule.mode,
44+ starts_at: schedule.starts_at,
45+ ends_at: schedule.ends_at,
46+ duration_ms: schedule.duration_ms,
47+ max_attempts,
48+ allow_rejoin,
49+ allow_review,
50+ draft,
51+ result_count: None,
52+ };
53+ // The course row is *written* (bumped and put back), not read: a plain
54+ // read does not survive `Course::delete`'s window, and an exam that
55+ // outlives its course is unreachable for good — every route to one goes
56+ // through `course_of`, which answers a 500 no delete can clear, while
57+ // `GET /exams` still lists it. See [`cap::touch_and_create`].
58+ cap::touch_and_create(
59+ &course.record(),
60+ ENROLLMENT_COUNT_FIELD,
61+ &exam.id.record(),
62+ &exam,
63+ db,
64+ )
65+ .await?
66+ .ok_or(AppError::NotFound)
67+}
68+
69+pub async fn read(db: &Database, id: &ExamId) -> Result<Option<Exam>, AppError> {
70+ Ok(db.select(id.record()).await?)
71+}
72+
73+pub async fn list_all(db: &Database) -> Result<Vec<Exam>, AppError> {
74+ let mut result = db
75+ .query("SELECT * FROM exam ORDER BY id DESC")
76+ .await?
77+ .check()?;
78+ Ok(result.take::<Vec<Exam>>(0)?)
79+}
80+
81+pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Exam>, AppError> {
82+ let mut result = db
83+ .query("SELECT * FROM exam WHERE course = $course ORDER BY id DESC")
84+ .bind(("course", course.record()))
85+ .await?
86+ .check()?;
87+ Ok(result.take::<Vec<Exam>>(0)?)
88+}
89+
90+/// Every exam of every course in `courses` (one query) — the catalog as one
91+/// user sees it.
92+pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result<Vec<Exam>, AppError> {
93+ if courses.is_empty() {
94+ return Ok(Vec::new());
95+ }
96+ let records: Vec<RecordId> = courses.iter().map(CourseId::record).collect();
97+ let mut result = db
98+ .query("SELECT * FROM exam WHERE course IN $courses ORDER BY id DESC")
99+ .bind(("courses", records))
100+ .await?
101+ .check()?;
102+ Ok(result.take::<Vec<Exam>>(0)?)
103+}
104+
105+// `course` is deliberately not updatable — moving an exam between courses
106+// would strand results of students not enrolled in the target course.
107+#[expect(
108+ clippy::too_many_arguments,
109+ reason = "mirrors the sibling entities' update(field, field, ..) shape"
110+)]
111+/// Save the merged exam, but only while the row still reads as the
112+/// snapshot the caller merged over — `None` means a concurrent PATCH
113+/// landed in between and nothing was written: re-read, re-merge, retry.
114+///
115+/// Every column this write replaces is in the guard, which is what makes
116+/// the whole-row `CONTENT` save safe without a lock held across the
117+/// handler's read: the compare-and-set refuses precisely when that save
118+/// would have reverted somebody. `course`/`creator` are not editable and
119+/// ride along unchanged. Same shape as
120+/// [`crate::db::settings::save_if_unchanged`].
121+pub async fn update_if_unchanged(
122+ db: &Database,
123+ mut expected: Exam,
124+ title: ExamTitle,
125+ description: ExamDescription,
126+ kind: ExamKind,
127+ schedule: ExamSchedule,
128+ max_attempts: ExamAttemptLimit,
129+ allow_rejoin: bool,
130+ allow_review: bool,
131+ draft: bool,
132+) -> Result<Option<Exam>, AppError> {
133+ // Re-drafting hides an exam: it must be refused while any sitting or
134+ // mark exists, and that check has to be *in this transaction*. Holding
135+ // it under a lock outside would only order the two writers inside one
136+ // process — and it did not even do that, since grading takes the reader
137+ // lease this write does.
138+ let redraft = draft && !expected.draft;
139+ let was = (
140+ expected.title.clone(),
141+ expected.description.clone(),
142+ expected.kind.clone(),
143+ expected.mode.clone(),
144+ expected.starts_at,
145+ expected.ends_at,
146+ expected.duration_ms,
147+ expected.max_attempts,
148+ expected.allow_rejoin,
149+ expected.allow_review,
150+ expected.draft,
151+ );
152+ expected.title = title;
153+ expected.description = description;
154+ expected.kind = kind;
155+ expected.mode = schedule.mode;
156+ expected.starts_at = schedule.starts_at;
157+ expected.ends_at = schedule.ends_at;
158+ expected.duration_ms = schedule.duration_ms;
159+ expected.max_attempts = max_attempts;
160+ expected.allow_rejoin = allow_rejoin;
161+ expected.allow_review = allow_review;
162+ expected.draft = draft;
163+ // whole-row-save-ok: the WHERE below pins every column this replaces to
164+ // the caller's snapshot, so no concurrent write can be reverted
165+ //
166+ // Sent through the retry loop, not a bare `query`: this row now has a
167+ // hot writer. Every answer save touches it to tie itself to the exam
168+ // ([`crate::domain::exam_answer::ExamAnswer::save`]), so a teacher
169+ // flipping `allow_rejoin` mid-exam can lose a round to a student
170+ // typing — and a lost round is a re-send, never the 500 a bare `?` on
171+ // the conflict would have answered. Re-sending is sound because the
172+ // statement is a compare-and-set: the second pass carries the same
173+ // pinned snapshot, so it lands only if the row is still what the caller
174+ // read, and a rival that really moved it is refused as it was before.
175+ // Admissible for the loop — an `UPDATE`, an `IF`/`THROW` and a `SELECT`
176+ // can never answer "already exists".
177+ let (mut result, mut errors) = transaction_with_retry(
178+ db,
179+ "BEGIN TRANSACTION;
180+ IF $redraft AND (
181+ array::len((SELECT VALUE id FROM exam_attempt WHERE exam = $id LIMIT 1)) > 0
182+ OR array::len((SELECT VALUE id FROM exam_result WHERE exam = $id LIMIT 1)) > 0
183+ ) { THROW 'exam_redraft' };
184+ UPDATE $id CONTENT $new
185+ WHERE title = $was_title AND description = $was_description
186+ AND kind = $was_kind AND mode = $was_mode
187+ AND starts_at = $was_starts AND ends_at = $was_ends
188+ AND duration_ms = $was_duration
189+ AND max_attempts = $was_max_attempts
190+ AND allow_rejoin = $was_allow_rejoin
191+ AND allow_review = $was_allow_review
192+ AND draft = $was_draft
193+ AND (result_count ?? 0) = $was_results
194+ RETURN AFTER;
195+ COMMIT TRANSACTION;",
196+ &[
197+ ("redraft".into(), redraft.into_value()),
198+ ("id".into(), expected.id.record().into_value()),
199+ ("was_title".into(), was.0.into_value()),
200+ ("was_description".into(), was.1.into_value()),
201+ ("was_kind".into(), was.2.into_value()),
202+ ("was_mode".into(), was.3.into_value()),
203+ ("was_starts".into(), was.4.into_value()),
204+ ("was_ends".into(), was.5.into_value()),
205+ ("was_duration".into(), was.6.into_value()),
206+ ("was_max_attempts".into(), was.7.into_value()),
207+ ("was_allow_rejoin".into(), was.8.into_value()),
208+ ("was_allow_review".into(), was.9.into_value()),
209+ ("was_draft".into(), was.10.into_value()),
210+ // The mark counter is pinned like every other column this write
211+ // replaces, and for a sharper reason: a grade increments it, so
212+ // pinning it is what makes "this exam had no marks" — the gate
213+ // the handler refuses a kind change on — true at *write* time
214+ // and not merely at read time. A mark landing in between
215+ // refuses the save.
216+ (
217+ "was_results".into(),
218+ expected.result_count.unwrap_or(0).into_value(),
219+ ),
220+ ("new".into(), expected.into_value()),
221+ ],
222+ &["exam_redraft"],
223+ )
224+ .await?;
225+ // An aborted transaction errors every slot; only the THROW's names the
226+ // marker (the [`crate::db::exam_attempt::write_unfrozen`] treatment).
227+ if errors
228+ .values()
229+ .any(|error| error.to_string().contains("exam_redraft"))
230+ {
231+ return Err(redraft_error());
232+ }
233+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
234+ return Err(error.into());
235+ }
236+ // BEGIN and the IF take a slot each.
237+ Ok(result.take::<Vec<Exam>>(2)?.into_iter().next())
238+}
239+
240+/// Delete the exam and cascade-remove its result, attempt, question,
241+/// answer, question-image, and answer-image rows — all in one transaction,
242+/// so a failure can't leave an emptied-out exam shell behind. The image
243+/// *blobs* (question and answer) are the web layer's to remove — it collects
244+/// their names before calling this.
245+///
246+/// Bank templates saved out of this exam survive it — they are a separate,
247+/// reusable library — so only their `source_exam` provenance link is cleared,
248+/// in the same transaction, never left pointing at a dead exam.
249+///
250+/// The questions about to be cascaded each hold a reference on their
251+/// subject, which is what keeps that subject from being deleted under them.
252+/// They are given back in this same transaction, counted per subject, so
253+/// deleting an exam frees its subjects for deletion and nothing else does.
254+/// The marks give their *kind* references back the same way, and it has to
255+/// be the same way: counted outside the transaction, a mark deleted by a
256+/// concurrent `remove_result` in the gap would be released twice — once by
257+/// each — which on a kind another exam still uses reads as one mark too
258+/// few, and that is a kind wrongly free to leave the settings.
259+pub async fn delete(db: &Database, target: Exam) -> Result<Exam, AppError> {
260+ let (mut result, mut errors) = transaction_with_retry(
261+ db,
262+ "BEGIN TRANSACTION;
263+ FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result
264+ WHERE exam = $ex GROUP BY kind) ?? []) {
265+ UPDATE type::record('kind_ref', $row.kind) SET count =
266+ math::max([(count ?? 0) - $row.n, 0])
267+ };
268+ DELETE exam_result WHERE exam = $ex;
269+ DELETE exam_attempt WHERE exam = $ex;
270+ DELETE exam_answer WHERE exam = $ex;
271+ DELETE answer_image WHERE exam = $ex;
272+ DELETE question_image WHERE exam = $ex;
273+ FOR $row IN ((SELECT subject, count() AS n FROM exam_question
274+ WHERE exam = $ex GROUP BY subject) ?? []) {
275+ UPDATE $row.subject SET exam_question_count =
276+ math::max([(exam_question_count ?? 0) - $row.n, 0])
277+ };
278+ DELETE exam_question WHERE exam = $ex;
279+ UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex;
280+ LET $before = (DELETE $ex RETURN BEFORE);
281+ RETURN $before;
282+ COMMIT TRANSACTION;",
283+ &[("ex".into(), target.id.record().into_value())],
284+ // No THROW of its own: an unconditional cascade, so the only error
285+ // worth telling apart is a lost round, and `check()` — which took
286+ // the *first* error in the batch — could not. It reported a
287+ // sibling's "not executed" and made a retryable round a 500.
288+ &[],
289+ )
290+ .await?;
291+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
292+ return Err(error.into());
293+ }
294+ // The deleted row comes back through the transaction's trailing
295+ // `RETURN`, never a hand-counted slot: the old `take(8)` turned a
296+ // successful delete into a 404 the moment a cascade statement was
297+ // inserted above it (it already had to be bumped once). `RETURN` is
298+ // always the last statement before `COMMIT`, so its slot is derived
299+ // from the statement count and every insertion above it shifts it
300+ // along. `num_statements` counts BEGIN and COMMIT too, hence -2.
301+ let slot = result.num_statements().saturating_sub(2);
302+ let deleted: Option<Exam> = result.take::<Vec<Exam>>(slot)?.into_iter().next();
303+ deleted.ok_or(AppError::NotFound)
304+}
305+#[cfg(test)]
306+use crate::domain::settings::ExamKindDef;
307+
308+/// An unscheduled published exam — the minimum any test that writes a *child*
309+/// of an exam needs, in any module: every such write moves the exam row (see
310+/// [`crate::db::exam_attempt::write_unfrozen_with`]
311+/// and [`crate::domain::exam_answer::ExamAnswer::save`]), so a minted id whose
312+/// row was never created is a 404 rather than a silent orphan.
313+#[cfg(test)]
314+pub(crate) async fn published_exam(db: &Database) -> Exam {
315+ let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
316+ .get_exam_kinds()
317+ .to_vec();
318+ create(
319+ db,
320+ &UserId::generate(),
321+ &crate::db::course::a_test_course(db).await,
322+ ExamTitle::try_new("midterm").unwrap(),
323+ ExamDescription::try_new("").unwrap(),
324+ ExamKind::try_new("midterm", &allowed).unwrap(),
325+ ExamSchedule::try_new(None, None, None, None).unwrap(),
326+ ExamAttemptLimit::try_new(1).unwrap(),
327+ true,
328+ false,
329+ false,
330+ )
331+ .await
332+ .unwrap()
333+}
334+
335+#[cfg(test)]
336+mod tests {
337+ use super::*;
338+
339+ use super::published_exam as published;
340+
341+ use crate::constant::EXAM_TABLE;
342+ use crate::domain::exam::{ExamDuration, ExamMode};
343+ use crate::domain::settings::ExamKindDef;
344+ use crate::domain::timestamp::Timestamp;
345+ use crate::error::ValidationError;
346+
347+ /// An exam must not outlive the course it belongs to. It is the worst of
348+ /// the three children `Course::delete` used to leave behind: every exam
349+ /// route funnels through `course_of`, which answers
350+ /// `Internal("exam references a missing course")`, so an orphan **500s
351+ /// forever** on `GET`/`PATCH`/`DELETE /exams/{id}` — undeletable — while
352+ /// [`crate::db::exam::list_all`] still hands it to every manager+ on `GET /exams`.
353+ ///
354+ /// [`create`] therefore *writes* the course row rather than reading
355+ /// it ([`cap::touch_and_create`]); the harness and the window it races in
356+ /// are documented on
357+ /// [`crate::db::course::assert_no_child_outlives_a_course_delete`].
358+ /// Mutation-tested: with the bare `db.create` this shipped with, all four
359+ /// rounds orphan.
360+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
361+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
362+ async fn an_exam_never_outlives_its_course() {
363+ fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {
364+ tokio::spawn(async move {
365+ let kinds = crate::domain::settings::Settings::defaults()
366+ .get_exam_kinds()
367+ .to_vec();
368+ create(
369+ &db,
370+ &UserId::generate(),
371+ &course,
372+ ExamTitle::try_new("quiz").unwrap(),
373+ ExamDescription::try_new("").unwrap(),
374+ ExamKind::try_new("quiz", &kinds).unwrap(),
375+ ExamSchedule::try_new(None, None, None, None).unwrap(),
376+ ExamAttemptLimit::try_new(1).unwrap(),
377+ true,
378+ false,
379+ false,
380+ )
381+ .await
382+ .map(|_| ())
383+ })
384+ }
385+ crate::db::course::assert_no_child_outlives_a_course_delete(
386+ "exam_orphan_race",
387+ EXAM_TABLE,
388+ make,
389+ )
390+ .await;
391+ }
392+
393+ fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) {
394+ (
395+ exam.get_title().clone(),
396+ exam.get_description().clone(),
397+ exam.get_kind().clone(),
398+ ExamSchedule::try_new(None, None, None, None).unwrap(),
399+ )
400+ }
401+
402+ /// The bite test for the compare-and-set that replaced the writer lease on
403+ /// `PATCH /exams/{id}`: a merge built on a snapshot the row has moved past
404+ /// must be refused (the handler then re-reads and re-merges), never
405+ /// written over somebody else's edit. Asserts the *stored* row.
406+ #[tokio::test]
407+ async fn a_merge_built_on_a_stale_snapshot_is_refused() {
408+ let db = crate::database::init_mem().await.unwrap();
409+ let stale = published(&db).await;
410+ let (_, description, kind, schedule) = edit(&stale);
411+ let landed = update_if_unchanged(
412+ &db,
413+ stale.clone(),
414+ ExamTitle::try_new("theirs").unwrap(),
415+ description,
416+ kind,
417+ schedule,
418+ ExamAttemptLimit::try_new(1).unwrap(),
419+ true,
420+ false,
421+ false,
422+ )
423+ .await
424+ .unwrap();
425+ assert!(landed.is_some(), "the first write is on a fresh snapshot");
426+
427+ let (_, description, kind, schedule) = edit(&stale);
428+ let refused = update_if_unchanged(
429+ &db,
430+ stale,
431+ ExamTitle::try_new("mine").unwrap(),
432+ description,
433+ kind,
434+ schedule,
435+ ExamAttemptLimit::try_new(1).unwrap(),
436+ true,
437+ false,
438+ false,
439+ )
440+ .await
441+ .unwrap();
442+ assert!(refused.is_none(), "a stale merge must not be written");
443+ let stored = read(&db, landed.unwrap().get_id()).await.unwrap().unwrap();
444+ assert_eq!(stored.get_title().as_str(), "theirs");
445+ }
446+
447+ /// The bite test for the re-draft guard now living *inside* the update's
448+ /// transaction: a mark that lands after the handler's pre-flight gate (the
449+ /// grade path is a lock reader, exactly like this one) must still stop the
450+ /// exam from being hidden.
451+ #[tokio::test]
452+ async fn re_drafting_is_refused_by_the_write_itself_once_a_mark_exists() {
453+ use crate::domain::exam_result::{ExamResult, Mark};
454+ let db = crate::database::init_mem().await.unwrap();
455+ let exam = published(&db).await;
456+ let student = UserId::generate();
457+ ExamResult::grade(
458+ exam.get_id(),
459+ &student,
460+ 1,
461+ Mark::try_new(80).unwrap(),
462+ &UserId::generate(),
463+ exam.get_kind().as_str(),
464+ &db,
465+ )
466+ .await
467+ .unwrap();
468+
469+ let (title, description, kind, schedule) = edit(&exam);
470+ let refused = update_if_unchanged(
471+ &db,
472+ exam.clone(),
473+ title,
474+ description,
475+ kind,
476+ schedule,
477+ ExamAttemptLimit::try_new(1).unwrap(),
478+ true,
479+ false,
480+ true,
481+ )
482+ .await
483+ .expect_err("a graded exam cannot be re-drafted");
484+ assert!(refused.to_string().contains("back into a draft"));
485+ let stored = read(&db, exam.get_id()).await.unwrap().unwrap();
486+ assert!(!stored.is_draft(), "nothing may have been written");
487+ }
488+
489+ #[tokio::test]
490+ async fn title_is_required() {
491+ assert!(ExamTitle::try_new("midterm").is_ok());
492+ assert!(ExamTitle::try_new("").is_err());
493+ assert!(ExamTitle::try_new(" ").is_err());
494+ }
495+
496+ #[tokio::test]
497+ async fn description_is_optional() {
498+ assert!(ExamDescription::try_new("").is_ok());
499+ }
500+
501+ #[tokio::test]
502+ async fn kind_must_be_in_the_allowed_list() {
503+ let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
504+ .get_exam_kinds()
505+ .to_vec();
506+ for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] {
507+ assert_eq!(ExamKind::try_new(kind, &allowed).unwrap().as_str(), kind);
508+ }
509+ assert!(ExamKind::try_new("essay", &allowed).is_err());
510+ assert!(ExamKind::try_new("", &allowed).is_err());
511+ // A school-defined list swaps the acceptance set wholesale.
512+ let custom = vec![ExamKindDef::try_new("lab", 2).unwrap()];
513+ assert!(ExamKind::try_new("lab", &custom).is_ok());
514+ assert!(ExamKind::try_new("midterm", &custom).is_err());
515+ // Matching is exact, case included — the settings list is the wire
516+ // truth, not a case-folded suggestion.
517+ assert!(ExamKind::try_new("Lab", &custom).is_err());
518+ }
519+
520+ #[tokio::test]
521+ async fn mode_must_be_known() {
522+ for mode in ["sync", "async", "open"] {
523+ assert_eq!(ExamMode::try_new(mode).unwrap().as_str(), mode);
524+ }
525+ assert!(ExamMode::try_new("live").is_err());
526+ }
527+
528+ #[tokio::test]
529+ async fn attempt_limit_counts_or_never_runs_out() {
530+ let single = ExamAttemptLimit::single();
531+ assert_eq!(single.as_i64(), 1);
532+ assert!(!single.is_unlimited());
533+ assert!(single.allows_another(0));
534+ assert!(!single.allows_another(1));
535+
536+ let three = ExamAttemptLimit::try_new(3).unwrap();
537+ assert!(three.allows_another(2));
538+ assert!(!three.allows_another(3));
539+ assert!(!three.allows_another(4));
540+
541+ let unlimited = ExamAttemptLimit::try_new(0).unwrap();
542+ assert!(unlimited.is_unlimited());
543+ assert!(unlimited.allows_another(0));
544+ assert!(unlimited.allows_another(10_000));
545+
546+ assert!(ExamAttemptLimit::try_new(-1).is_err());
547+ assert!(ExamAttemptLimit::try_new(101).is_err());
548+ }
549+
550+ #[tokio::test]
551+ async fn schedule_invariants_hold() {
552+ let mode = |m| Some(ExamMode::try_new(m).unwrap());
553+ let at = |ms| Some(Timestamp::from_millis(ms));
554+ let dur = Some(ExamDuration::try_new(90 * 60 * 1000).unwrap());
555+
556+ // Unscheduled: nothing set is fine, any time/duration without a mode is not.
557+ assert!(ExamSchedule::try_new(None, None, None, None).is_ok());
558+ assert!(ExamSchedule::try_new(None, at(1), None, None).is_err());
559+ assert!(ExamSchedule::try_new(None, None, at(2), None).is_err());
560+ assert!(ExamSchedule::try_new(None, None, None, dur).is_err());
561+
562+ // Sync: fixed window, no duration.
563+ assert!(ExamSchedule::try_new(mode("sync"), at(1), at(2), None).is_ok());
564+ assert!(ExamSchedule::try_new(mode("sync"), None, at(2), None).is_err());
565+ assert!(ExamSchedule::try_new(mode("sync"), at(1), None, None).is_err());
566+ // Over-long `dur` in a 1ms window, but the root cause is that sync
567+ // takes no duration at all — that message wins over the window one.
568+ assert!(matches!(
569+ ExamSchedule::try_new(mode("sync"), at(1), at(2), dur),
570+ Err(ValidationError::Invalid {
571+ reason: "only async and open exams take a duration",
572+ ..
573+ })
574+ ));
575+
576+ // Async: window plus a per-student duration, which must fit inside it
577+ // (equal to the window is fine; the window `at(1), at(2)` above is
578+ // too narrow for `dur`, so give it one exactly `dur` wide instead).
579+ assert!(ExamSchedule::try_new(mode("async"), at(1), at(1 + 90 * 60 * 1000), dur).is_ok());
580+ assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), dur).is_err());
581+ assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), None).is_err());
582+
583+ // Open: no window, duration optional (limited or unlimited time).
584+ assert!(ExamSchedule::try_new(mode("open"), None, None, None).is_ok());
585+ assert!(ExamSchedule::try_new(mode("open"), None, None, dur).is_ok());
586+ assert!(ExamSchedule::try_new(mode("open"), at(1), None, None).is_err());
587+ assert!(ExamSchedule::try_new(mode("open"), None, at(2), None).is_err());
588+ assert!(ExamSchedule::try_new(mode("open"), at(1), at(2), dur).is_err());
589+
590+ // The window must be a real interval, whatever the mode.
591+ assert!(ExamSchedule::try_new(mode("sync"), at(2), at(2), None).is_err());
592+ assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err());
593+ }
594+
595+ /// GUARD, not a retry measurement — read the last paragraph before
596+ /// trusting this test with the retry. See
597+ /// [`crate::db::course::delete`]'s race test for why the rate is
598+ /// counted rather than asserted per round.
599+ ///
600+ /// This site has no `THROW` marker at all: it ends `.check()?`, which
601+ /// returns the *first* error in the batch, and an aborted transaction
602+ /// errors every slot — most of them with a generic "not executed". So a
603+ /// genuine conflict can be masked by a sibling, and either way there is no
604+ /// [`crate::database::lost_the_race`] check and no retry.
605+ ///
606+ /// The racer is a mark: [`ExamResult::grade`] claims the exam's own
607+ /// `result_count` (and the kind's reference) before writing, so it contends
608+ /// with the `DELETE $ex` and with the kind_ref decrement inside the same
609+ /// transaction. A round where *some* of the six grades 404 and the rest
610+ /// succeed is the witness that the delete landed inside the burst: the 404
611+ /// comes from `write_mark`'s existence gate, so it can only be answered by a
612+ /// grade that reached the store after the row was gone, and its siblings'
613+ /// success says the same burst also had grades that got there first. Stored
614+ /// state cannot say this any more — the gate is what stops a mark outliving
615+ /// its exam, so the sweep now finds nothing to leave behind in *every*
616+ /// round, which is asserted below as a fact rather than read as a signal.
617+ ///
618+ /// It does not prove the retry either: measured at 0 conflicts in 100 raced
619+ /// rounds, and green with
620+ /// [`crate::database::transaction_with_retry`]'s loop cut to a single
621+ /// attempt — the grades serialize behind `cap`'s claim lock, so they mostly
622+ /// queue rather than collide. So this guards the status codes and the
623+ /// cascade (marks either survive whole or are swept whole, never a 500).
624+ /// The retry is measured on [`crate::db::course::delete`].
625+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
626+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
627+ async fn a_delete_racing_a_mark_never_answers_500() {
628+ use crate::domain::exam_result::{ExamResult, Mark};
629+ let (db, _serialized) = crate::database::init_test_server("exam_delete_race").await;
630+ let (mut delete_500, mut grade_500) = (0, 0);
631+ let (mut split, mut swept) = (0, 0);
632+ let (mut last_delete, mut last_grade) = (String::new(), String::new());
633+ for round in 0..20 {
634+ let exam = published(&db).await;
635+ let kind = exam.get_kind().as_str().to_string();
636+
637+ // A burst of marks and a delete held back by a sweeping beat: this
638+ // site has no guard to lose to, so a single racer released with it
639+ // simply finishes on one side of it. Same recipe as
640+ // [`crate::db::course::delete`]'s race test.
641+ let drop_it = {
642+ let (exam, db) = (exam.clone(), db.clone());
643+ // A wide sweep, not the 0-3ms the other three use: each grade
644+ // takes two counter writes serialized behind `cap`'s claim
645+ // lock, so the burst runs tens of milliseconds and a short beat
646+ // always puts the delete in front of all six.
647+ let beat = std::time::Duration::from_millis(round * 2);
648+ tokio::spawn(async move {
649+ tokio::time::sleep(beat).await;
650+ delete(&db, exam).await
651+ })
652+ };
653+ let marks: Vec<_> = (0..6)
654+ .map(|seat| {
655+ let (id, db, kind) = (exam.get_id().clone(), db.clone(), kind.clone());
656+ let student = UserId::from_key(&format!("stu{round}_{seat}"));
657+ tokio::spawn(async move {
658+ ExamResult::grade(
659+ &id,
660+ &student,
661+ 1,
662+ Mark::try_new(50).unwrap(),
663+ &UserId::from_key("teacher"),
664+ &kind,
665+ &db,
666+ )
667+ .await
668+ })
669+ })
670+ .collect();
671+ let drop_it = drop_it.await.unwrap();
672+ if matches!(drop_it, Err(AppError::Db(_))) {
673+ delete_500 += 1;
674+ last_delete = format!("{drop_it:?}");
675+ }
676+ let mut refused = 0;
677+ for mark in marks {
678+ let mark = mark.await.unwrap();
679+ match mark {
680+ // The existence gate: this grade reached the store after
681+ // the row was gone.
682+ Err(AppError::NotFound) => refused += 1,
683+ Err(AppError::Db(_)) => {
684+ grade_500 += 1;
685+ last_grade = format!("{mark:?}");
686+ }
687+ _ => {}
688+ }
689+ }
690+ // Neither end of the burst: some grades beat the delete and some
691+ // lost to it, so the delete landed *between* them. A round that is
692+ // all-refused or all-through is one where it landed outside.
693+ if (1..6).contains(&refused) {
694+ split += 1;
695+ }
696+ if ExamResult::list_for_exam(exam.get_id(), &db)
697+ .await
698+ .unwrap()
699+ .is_empty()
700+ {
701+ swept += 1;
702+ }
703+ }
704+ eprintln!(
705+ "Exam::delete raced: {delete_500}/20 delete 500s, {grade_500} grade 500s, \
706+ {split} rounds split by the delete / {swept} swept clean"
707+ );
708+ assert!(
709+ split > 0,
710+ "the delete never landed inside the burst (0/20 rounds split)"
711+ );
712+ // Not a race signal, an invariant: the gate refuses a mark for an exam
713+ // that is gone, so no round can leave one behind for the next reader.
714+ assert_eq!(
715+ swept,
716+ 20,
717+ "a mark outlived its exam in {} rounds",
718+ 20 - swept
719+ );
720+ assert_eq!(
721+ delete_500, 0,
722+ "a raced delete must not 500: {delete_500}/20 rounds, last {last_delete}"
723+ );
724+ assert_eq!(
725+ grade_500, 0,
726+ "a raced grade must retry, not 500: {grade_500}/20 rounds, last {last_grade}"
727+ );
728+ }
729+
730+ /// One choice question on `exam`, with a real subject row behind it — a
731+ /// question claims a reference on its subject and is refused without one.
732+ async fn question_on(exam: &Exam, db: &Database) -> crate::domain::exam_question::ExamQuestion {
733+ use crate::domain::exam_question::{
734+ ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
735+ };
736+ let spec = QuestionSpec::try_new(
737+ QuestionKind::try_new("choice").unwrap(),
738+ Some(vec![
739+ ChoiceInput {
740+ id: Some("a".into()),
741+ text: "5".into(),
742+ },
743+ ChoiceInput {
744+ id: Some("b".into()),
745+ text: "6".into(),
746+ },
747+ ]),
748+ Some("b".into()),
749+ &[],
750+ )
751+ .unwrap();
752+ let subject = crate::domain::subject::Subject::create(
753+ &crate::db::course::a_test_course(db).await,
754+ crate::domain::subject::SubjectName::try_new("topic").unwrap(),
755+ crate::domain::subject::SubjectDescription::try_new("").unwrap(),
756+ db,
757+ )
758+ .await
759+ .unwrap();
760+ ExamQuestion::create(
761+ exam.get_id(),
762+ subject.get_id().clone(),
763+ QuestionText::try_new("3 + 3?").unwrap(),
764+ QuestionPoints::try_new(5).unwrap(),
765+ spec,
766+ db,
767+ )
768+ .await
769+ .unwrap()
770+ }
771+
772+ /// The `Menu::delete` defect, one domain over: a student's answer must not
773+ /// outlive the exam it belongs to. Guarding the save by *reading* the exam
774+ /// would not do it — the read sees a row [`crate::db::exam::delete`] has removed but
775+ /// not committed, while its `DELETE exam_answer WHERE exam = $ex` swept a
776+ /// snapshot predating the save, so both commit and the answer is left
777+ /// pointing at an exam that is gone. [`ExamAnswer::save`] writes the exam
778+ /// row instead (its `result_count`, back unchanged), so the two transactions
779+ /// touch one key and the store refuses one of them.
780+ ///
781+ /// The window is opened by the database, not by a lucky interleaving: a
782+ /// `DEFINE EVENT` on `exam` fires *inside* the delete's own transaction the
783+ /// instant the row goes, so the `SLEEP` lands exactly between the delete and
784+ /// its cascade every time. Nothing in `src/` knows about it; the seam is the
785+ /// schema.
786+ ///
787+ /// One child per round, deliberately — in the menu twin, two children in one
788+ /// round hid the bug: the first writer made the delete lose and re-send, and
789+ /// the re-sent sweep removed the other's row.
790+ ///
791+ /// Real server, and `#[ignore]`d for it: the subject *is* the store's
792+ /// conflict detection, which `init_mem`'s embedded engine does not have — it
793+ /// commits both writes and answers `Ok` to each, so this passes there on
794+ /// broken code. Mutation-tested: putting the bare
795+ /// `db.upsert(id).content(answer)` back turns it red (the exact output is in
796+ /// the commit that added it).
797+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
798+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
799+ async fn an_answer_written_inside_a_delete_never_outlives_the_exam() {
800+ use crate::domain::exam_answer::ExamAnswer;
801+ let (db, _serialized) = crate::database::init_test_server("exam_answer_race").await;
802+ // Hold the delete open for a full second after the row is gone, while
803+ // its cascade still has to run.
804+ db.query(
805+ "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
806+ THEN { SLEEP 1s; };",
807+ )
808+ .await
809+ .unwrap()
810+ .check()
811+ .unwrap();
812+
813+ let (mut answers, mut swept) = (0, 0);
814+ for round in 0..4 {
815+ let exam = published(&db).await;
816+ let question = question_on(&exam, &db).await;
817+ let id = exam.get_id().clone();
818+ let student = UserId::from_key(&format!("stu{round}"));
819+ // The stored choice ids are minted by the create, not the ones the
820+ // spec asked for — an answer must name one of *those*.
821+ let pick = question.get_choices().unwrap()[1]
822+ .get_id()
823+ .as_str()
824+ .to_string();
825+
826+ let drop_it = {
827+ let db = db.clone();
828+ tokio::spawn(async move { delete(&db, exam).await })
829+ };
830+ // The save starts inside the held window — the exam row is gone but
831+ // uncommitted, which is exactly what an exam read believes.
832+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
833+ let child = {
834+ let (db, question, student) = (db.clone(), question.clone(), student.clone());
835+ tokio::spawn(async move {
836+ ExamAnswer::save(&question, &student, 1, Some(pick), None, &db).await
837+ })
838+ };
839+ let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
840+ // A 404 for the save, or a NotFound for the delete, is a correct
841+ // answer — the only defect is stored state.
842+ assert!(
843+ !matches!(child, Err(AppError::Db(_))),
844+ "round {round}: a raced save must be answered, not 500: {child:?}"
845+ );
846+
847+ // Stored state is the whole verdict; a return value is not evidence.
848+ if read(&db, &id).await.unwrap().is_none() {
849+ swept += 1;
850+ answers += ExamAnswer::list_for_exam(&id, &db).await.unwrap().len();
851+ } else if drop_it.is_ok() {
852+ panic!("round {round}: the delete reported success but the exam is still there");
853+ }
854+ }
855+ eprintln!("Exam::delete raced by an answer save: {swept}/4 rounds deleted the exam");
856+ assert!(
857+ swept > 0,
858+ "no round ever deleted the exam, so the window was never reached"
859+ );
860+ assert_eq!(answers, 0, "an answer outlived its exam");
861+ }
862+
863+ /// The same defect on the teacher's side of the sheet, and a worse one: a
864+ /// question written inside the delete window kept the reference it claimed
865+ /// on its subject (the cascade's per-subject decrement counted only the
866+ /// rows it could see), and [`crate::domain::subject::Subject::delete`] is
867+ /// gated on that count reading zero — a subject nobody could ever delete
868+ /// again, hanging off an exam nobody could ever see. The freeze gate is a
869+ /// *read* of `exam_attempt` and never survived this window;
870+ /// [`crate::db::exam_attempt::write_unfrozen_with`] now writes the exam row too.
871+ ///
872+ /// Same seam, same `#[ignore]`, same reason as the answer twin above: the
873+ /// subject *is* the store's conflict detection, which the in-memory engine
874+ /// does not have.
875+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
876+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
877+ async fn a_question_written_inside_a_delete_never_outlives_the_exam() {
878+ use crate::domain::exam_question::{
879+ ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
880+ };
881+ use crate::domain::subject::Subject;
882+ let (db, _serialized) = crate::database::init_test_server("exam_question_race").await;
883+ db.query(
884+ "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
885+ THEN { SLEEP 1s; };",
886+ )
887+ .await
888+ .unwrap()
889+ .check()
890+ .unwrap();
891+
892+ let (mut questions, mut swept, mut stuck) = (0, 0, 0);
893+ for round in 0..4 {
894+ let exam = published(&db).await;
895+ let id = exam.get_id().clone();
896+ let subject = Subject::create(
897+ &crate::db::course::a_test_course(&db).await,
898+ crate::domain::subject::SubjectName::try_new("topic").unwrap(),
899+ crate::domain::subject::SubjectDescription::try_new("").unwrap(),
900+ &db,
901+ )
902+ .await
903+ .unwrap();
904+
905+ let drop_it = {
906+ let db = db.clone();
907+ tokio::spawn(async move { delete(&db, exam).await })
908+ };
909+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
910+ let child = {
911+ let (db, exam_id, on) = (db.clone(), id.clone(), subject.get_id().clone());
912+ tokio::spawn(async move {
913+ let spec = QuestionSpec::try_new(
914+ QuestionKind::try_new("choice").unwrap(),
915+ Some(vec![
916+ ChoiceInput {
917+ id: Some("a".into()),
918+ text: "5".into(),
919+ },
920+ ChoiceInput {
921+ id: Some("b".into()),
922+ text: "6".into(),
923+ },
924+ ]),
925+ Some("b".into()),
926+ &[],
927+ )
928+ .unwrap();
929+ ExamQuestion::create(
930+ &exam_id,
931+ on,
932+ QuestionText::try_new("3 + 3?").unwrap(),
933+ QuestionPoints::try_new(5).unwrap(),
934+ spec,
935+ &db,
936+ )
937+ .await
938+ })
939+ };
940+ let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
941+ assert!(
942+ !matches!(child, Err(AppError::Db(_))),
943+ "round {round}: a raced question write must be answered, not 500: {child:?}"
944+ );
945+
946+ if read(&db, &id).await.unwrap().is_none() {
947+ swept += 1;
948+ questions += ExamQuestion::list_for_exam(&id, None, 0, &db)
949+ .await
950+ .unwrap()
951+ .0
952+ .len();
953+ // The subject has to be free again: a stranded reference is the
954+ // half of this bug a row count alone would not catch.
955+ if Subject::read(subject.get_id(), &db)
956+ .await
957+ .unwrap()
958+ .unwrap()
959+ .delete(&db)
960+ .await
961+ .is_err()
962+ {
963+ stuck += 1;
964+ }
965+ } else if drop_it.is_ok() {
966+ panic!("round {round}: the delete reported success but the exam is still there");
967+ }
968+ }
969+ eprintln!("Exam::delete raced by a question write: {swept}/4 rounds deleted the exam");
970+ assert!(
971+ swept > 0,
972+ "no round ever deleted the exam, so the window was never reached"
973+ );
974+ assert_eq!(questions, 0, "a question outlived its exam");
975+ assert_eq!(stuck, 0, "an orphan question left its subject undeletable");
976+ }
977+
978+ /// The student's half of the same picture problem: a drawing is a bare
979+ /// `UPSERT` — the exact pre-fix shape of [`ExamAnswer::save`] — so it kept
980+ /// the hole the text answer just lost, blob and all.
981+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
982+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
983+ async fn a_drawing_written_inside_a_delete_never_outlives_the_exam() {
984+ use crate::domain::answer_image::AnswerImage;
985+ use crate::domain::note_file::FileContentType;
986+ let (db, _serialized) = crate::database::init_test_server("answer_image_race").await;
987+ db.query(
988+ "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
989+ THEN { SLEEP 1s; };",
990+ )
991+ .await
992+ .unwrap()
993+ .check()
994+ .unwrap();
995+
996+ let (mut drawings, mut swept) = (0, 0);
997+ for round in 0..4 {
998+ let exam = published(&db).await;
999+ let question = question_on(&exam, &db).await;
1000+ let id = exam.get_id().clone();
1001+ let student = UserId::from_key(&format!("stu{round}"));
1002+
1003+ let drop_it = {
1004+ let db = db.clone();
1005+ tokio::spawn(async move { delete(&db, exam).await })
1006+ };
1007+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1008+ let child = {
1009+ let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone());
1010+ tokio::spawn(async move {
1011+ AnswerImage::new(
1012+ &exam_id,
1013+ &on,
1014+ &student,
1015+ 1,
1016+ FileContentType::try_new("image/png").unwrap(),
1017+ 3,
1018+ )
1019+ .upsert(&db)
1020+ .await
1021+ })
1022+ };
1023+ let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1024+ assert!(
1025+ !matches!(child, Err(AppError::Db(_))),
1026+ "round {round}: a raced drawing write must be answered, not 500: {child:?}"
1027+ );
1028+
1029+ if read(&db, &id).await.unwrap().is_none() {
1030+ swept += 1;
1031+ drawings += AnswerImage::list_for_exam(&id, &db).await.unwrap().len();
1032+ } else if drop_it.is_ok() {
1033+ panic!("round {round}: the delete reported success but the exam is still there");
1034+ }
1035+ }
1036+ eprintln!("Exam::delete raced by a drawing write: {swept}/4 rounds deleted the exam");
1037+ assert!(
1038+ swept > 0,
1039+ "no round ever deleted the exam, so the window was never reached"
1040+ );
1041+ assert_eq!(drawings, 0, "a drawing outlived its exam");
1042+ }
1043+
1044+ /// A picture is written through the same freeze gate as the question it
1045+ /// hangs on, so it had the same hole — and one the row count does not even
1046+ /// show: `delete_exam` collects the blob names to unlink *before* it calls
1047+ /// [\`crate::db::exam::delete\`], so an image row landing after that snapshot strands
1048+ /// its bytes on disk forever as well.
1049+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1050+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1051+ async fn a_picture_written_inside_a_delete_never_outlives_the_exam() {
1052+ use crate::domain::note_file::FileContentType;
1053+ use crate::domain::question_image::QuestionImage;
1054+ let (db, _serialized) = crate::database::init_test_server("question_image_race").await;
1055+ db.query(
1056+ "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1057+ THEN { SLEEP 1s; };",
1058+ )
1059+ .await
1060+ .unwrap()
1061+ .check()
1062+ .unwrap();
1063+
1064+ let (mut images, mut swept) = (0, 0);
1065+ for round in 0..4 {
1066+ let exam = published(&db).await;
1067+ let question = question_on(&exam, &db).await;
1068+ let id = exam.get_id().clone();
1069+
1070+ let drop_it = {
1071+ let db = db.clone();
1072+ tokio::spawn(async move { delete(&db, exam).await })
1073+ };
1074+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1075+ let child = {
1076+ let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone());
1077+ tokio::spawn(async move {
1078+ QuestionImage::new(
1079+ &exam_id,
1080+ &on,
1081+ None,
1082+ FileContentType::try_new("image/png").unwrap(),
1083+ 3,
1084+ )
1085+ .upsert(&db)
1086+ .await
1087+ })
1088+ };
1089+ let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1090+ assert!(
1091+ !matches!(child, Err(AppError::Db(_))),
1092+ "round {round}: a raced picture write must be answered, not 500: {child:?}"
1093+ );
1094+
1095+ if read(&db, &id).await.unwrap().is_none() {
1096+ swept += 1;
1097+ images += QuestionImage::list_for_exam(&id, &db).await.unwrap().len();
1098+ } else if drop_it.is_ok() {
1099+ panic!("round {round}: the delete reported success but the exam is still there");
1100+ }
1101+ }
1102+ eprintln!("Exam::delete raced by a picture write: {swept}/4 rounds deleted the exam");
1103+ assert!(
1104+ swept > 0,
1105+ "no round ever deleted the exam, so the window was never reached"
1106+ );
1107+ assert_eq!(images, 0, "a picture outlived its exam");
1108+ }
1109+}
src/db/exam_attempt.rsmodified+3 -3
@@ -164,7 +164,7 @@ pub async fn any_for_exam(db: &Database, exam: &ExamId) -> Result<bool, AppError
164164 /// The same transaction *writes* the exam row — bumping its mark counter
165165 /// and putting it straight back — which is what ties every child written
166166 /// through here to its exam. The freeze gate only *reads* `exam_attempt`,
167-/// and a read does not survive [`Exam::delete`](crate::domain::exam::Exam::delete)'s
167+/// and a read does not survive [`delete`](crate::db::exam::delete)'s
168168 /// window: a question or picture landing after that delete removed the exam
169169 /// but before it committed reads a row that is still there, while the
170170 /// cascade's `DELETE exam_question WHERE exam = $ex` ran on a snapshot
@@ -307,7 +307,8 @@ mod tests {
307307 let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
308308 let course = crate::db::course::a_test_course(db).await;
309309 let kinds = Settings::defaults().get_exam_kinds().to_vec();
310- let exam = Exam::create(
310+ let exam = crate::db::exam::create(
311+ db,
311312 &creator,
312313 &course,
313314 ExamTitle::try_new("practice").unwrap(),
@@ -319,7 +320,6 @@ mod tests {
319320 true,
320321 false,
321322 false,
322- db,
323323 )
324324 .await
325325 .unwrap();
src/db/mod.rsmodified+1 -0
@@ -3,6 +3,7 @@
33 pub mod appointment;
44 pub mod cap;
55 pub mod course;
6+pub mod exam;
67 pub mod exam_attempt;
78 pub mod field_update;
89 pub mod note;
src/domain/answer_image.rsmodified+2 -5
@@ -139,7 +139,7 @@ impl AnswerImage {
139139 /// write moves the exam's mark counter and puts it straight back, in this
140140 /// one transaction, so the exam's existence is something this write
141141 /// *writes* rather than something a gate read a moment earlier: a bare
142- /// upsert landing after [`Exam::delete`](crate::domain::exam::Exam::delete)
142+ /// upsert landing after [`delete`](crate::db::exam::delete)
143143 /// removed the exam but before it committed was swept by nothing — its
144144 /// `DELETE answer_image WHERE exam = $ex` ran on a snapshot predating this
145145 /// row — and both sides reported success. That stranded the blob as well as
@@ -323,10 +323,7 @@ mod tests {
323323 /// what keeps it from outliving the exam), so a minted id nothing wrote is
324324 /// a 404.
325325 async fn exam_row(db: &Database) -> ExamId {
326- crate::domain::exam::published_exam(db)
327- .await
328- .get_id()
329- .clone()
326+ crate::db::exam::published_exam(db).await.get_id().clone()
330327 }
331328
332329 fn student() -> UserId {
src/domain/bank_question.rsmodified+2 -8
@@ -835,14 +835,8 @@ mod tests {
835835 // Real exam rows: instantiating a template moves the exam's counter
836836 // (what keeps a question from outliving its exam), so a minted id
837837 // nothing wrote is a 404.
838- let exam = crate::domain::exam::published_exam(&db)
839- .await
840- .get_id()
841- .clone();
842- let other_exam = crate::domain::exam::published_exam(&db)
843- .await
844- .get_id()
845- .clone();
838+ let exam = crate::db::exam::published_exam(&db).await.get_id().clone();
839+ let other_exam = crate::db::exam::published_exam(&db).await.get_id().clone();
846840 // A real subject row: an exam question claims a reference on its
847841 // subject, so a minted id it never wrote would be refused.
848842 let subject = crate::domain::subject::Subject::create(
src/domain/course_session.rsmodified+1 -1
@@ -196,7 +196,7 @@ impl CourseSession {
196196 &[("s".into(), self.id.record().into_value())],
197197 // No THROW of its own — an unconditional cascade, so the only
198198 // error worth telling apart is a lost round (see
199- // [`crate::domain::exam::Exam::delete`]).
199+ // [`crate::db::exam::delete`]).
200200 &[],
201201 )
202202 .await?;
src/domain/exam.rsmodified+27 -1118
@@ -1,11 +1,8 @@
11 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
22
33 use crate::constant::{
4- ENROLLMENT_COUNT_FIELD, EXAM_TABLE, MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN,
5- UNLIMITED_EXAM_ATTEMPTS,
4+ EXAM_TABLE, MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS,
65 };
7-use crate::database::{Database, transaction_with_retry};
8-use crate::db::cap;
96 use crate::domain::course::CourseId;
107 use crate::domain::monotonic_id::next_ulid;
118 use crate::domain::settings::ExamKindDef;
@@ -13,9 +10,10 @@ use crate::domain::timestamp::Timestamp;
1310 use crate::domain::user::UserId;
1411 use crate::error::{AppError, ValidationError};
1512
16-/// The one spelling of the re-draft refusal, shared by the handler's
17-/// pre-flight gate and the in-transaction guard that re-makes it at write
18-/// time — a client cannot tell which of the two refused.
13+/// The one spelling of the re-draft refusal, shared by the update workflow's
14+/// pre-flight gate ([`crate::service::exam::update`]) and the in-transaction
15+/// guard that re-makes it at write time — a client cannot tell which of the
16+/// two refused.
1917 pub(crate) fn redraft_error() -> AppError {
2018 AppError::Conflict(
2119 "cannot turn a published exam back into a draft after attempts or results exist",
@@ -31,7 +29,7 @@ pub struct ExamId(RecordId);
3129
3230 impl ExamId {
3331 /// Minted from the process-wide monotonic generator, not `Ulid::new()`:
34- /// exams list `id DESC` (newest first, [`Exam::list_all`]),
32+ /// exams list `id DESC` (newest first, [`crate::db::exam::list_all`]),
3533 /// and a random low half scrambles rows minted in the same millisecond.
3634 pub fn generate() -> Self {
3735 Self(RecordId::new(EXAM_TABLE, next_ulid().to_string()))
@@ -186,10 +184,10 @@ impl ExamAttemptLimit {
186184 /// - `ends_at` strictly after `starts_at` whenever the window exists.
187185 #[derive(Debug, Clone, Default)]
188186 pub struct ExamSchedule {
189- mode: Option<ExamMode>,
190- starts_at: Option<Timestamp>,
191- ends_at: Option<Timestamp>,
192- duration_ms: Option<ExamDuration>,
187+ pub(crate) mode: Option<ExamMode>,
188+ pub(crate) starts_at: Option<Timestamp>,
189+ pub(crate) ends_at: Option<Timestamp>,
190+ pub(crate) duration_ms: Option<ExamDuration>,
193191 }
194192
195193 impl ExamSchedule {
@@ -273,36 +271,37 @@ impl ExamSchedule {
273271
274272 #[derive(Debug, Clone, SurrealValue)]
275273 pub struct Exam {
276- id: ExamId,
277- creator: UserId,
278- course: CourseId,
279- title: ExamTitle,
280- description: ExamDescription,
281- kind: ExamKind,
274+ pub(crate) id: ExamId,
275+ pub(crate) creator: UserId,
276+ pub(crate) course: CourseId,
277+ pub(crate) title: ExamTitle,
278+ pub(crate) description: ExamDescription,
279+ pub(crate) kind: ExamKind,
282280 // The schedule, flattened into columns (SCHEMAFULL keeps them typed).
283281 // Always written through an `ExamSchedule`, so the invariants above hold
284282 // for every stored row; pre-schedule rows read back as all-`None`.
285- mode: Option<ExamMode>,
286- starts_at: Option<Timestamp>,
287- ends_at: Option<Timestamp>,
288- duration_ms: Option<ExamDuration>,
283+ pub(crate) mode: Option<ExamMode>,
284+ pub(crate) starts_at: Option<Timestamp>,
285+ pub(crate) ends_at: Option<Timestamp>,
286+ pub(crate) duration_ms: Option<ExamDuration>,
289287 // Attempt policy. Rows predating these columns are backfilled by the boot
290288 // migration (limit 1, rejoin open), so reads never see them missing.
291- max_attempts: ExamAttemptLimit,
292- allow_rejoin: bool,
293- allow_review: bool,
289+ pub(crate) max_attempts: ExamAttemptLimit,
290+ pub(crate) allow_rejoin: bool,
291+ pub(crate) allow_review: bool,
294292 // Work-in-progress marker: a draft is visible only to its course's
295293 // managers, cannot be sat, and cannot be graded. Rows predating the
296294 // column are backfilled published (`false`).
297- draft: bool,
298- /// How many marks the exam carries — a cap-style counter ([`cap::claim`]
295+ pub(crate) draft: bool,
296+ /// How many marks the exam carries — a cap-style counter
297+ /// ([`crate::db::cap::claim`]
299298 /// from the grade, decremented by every delete of a mark), absent meaning
300299 /// zero. Unlike every other counter it is carried *in the struct*, because
301300 /// the save below is a whole-row `CONTENT` write: a column this type did
302301 /// not know about would be wiped by the next exam PATCH. Being in the row
303302 /// is also what makes it useful — the save pins it, so a grade landing
304303 /// mid-PATCH refuses the save instead of slipping past its gates.
305- result_count: Option<i64>,
304+ pub(crate) result_count: Option<i64>,
306305 }
307306
308307 impl Exam {
@@ -388,1094 +387,4 @@ impl Exam {
388387 pub fn is_creator(&self, user: &UserId) -> bool {
389388 &self.creator == user
390389 }
391-
392- #[expect(
393- clippy::too_many_arguments,
394- reason = "mirrors the sibling entities' create(field, field, ..) shape"
395- )]
396- pub async fn create(
397- creator: &UserId,
398- course: &CourseId,
399- title: ExamTitle,
400- description: ExamDescription,
401- kind: ExamKind,
402- schedule: ExamSchedule,
403- max_attempts: ExamAttemptLimit,
404- allow_rejoin: bool,
405- allow_review: bool,
406- draft: bool,
407- db: &Database,
408- ) -> Result<Exam, AppError> {
409- let exam = Exam {
410- id: ExamId::generate(),
411- creator: creator.clone(),
412- course: course.clone(),
413- title,
414- description,
415- kind,
416- mode: schedule.mode,
417- starts_at: schedule.starts_at,
418- ends_at: schedule.ends_at,
419- duration_ms: schedule.duration_ms,
420- max_attempts,
421- allow_rejoin,
422- allow_review,
423- draft,
424- result_count: None,
425- };
426- // The course row is *written* (bumped and put back), not read: a plain
427- // read does not survive `Course::delete`'s window, and an exam that
428- // outlives its course is unreachable for good — every route to one goes
429- // through `course_of`, which answers a 500 no delete can clear, while
430- // `GET /exams` still lists it. See [`cap::touch_and_create`].
431- cap::touch_and_create(
432- &course.record(),
433- ENROLLMENT_COUNT_FIELD,
434- &exam.id.record(),
435- &exam,
436- db,
437- )
438- .await?
439- .ok_or(AppError::NotFound)
440- }
441-
442- pub async fn read(id: &ExamId, db: &Database) -> Result<Option<Exam>, AppError> {
443- Ok(db.select(id.record()).await?)
444- }
445-
446- pub async fn list_all(db: &Database) -> Result<Vec<Exam>, AppError> {
447- let mut result = db
448- .query("SELECT * FROM exam ORDER BY id DESC")
449- .await?
450- .check()?;
451- Ok(result.take::<Vec<Exam>>(0)?)
452- }
453-
454- pub async fn list_for_course(course: &CourseId, db: &Database) -> Result<Vec<Exam>, AppError> {
455- let mut result = db
456- .query("SELECT * FROM exam WHERE course = $course ORDER BY id DESC")
457- .bind(("course", course.record()))
458- .await?
459- .check()?;
460- Ok(result.take::<Vec<Exam>>(0)?)
461- }
462-
463- /// Every exam of every course in `courses` (one query) — the catalog as one
464- /// user sees it.
465- pub async fn list_for_courses(
466- courses: &[CourseId],
467- db: &Database,
468- ) -> Result<Vec<Exam>, AppError> {
469- if courses.is_empty() {
470- return Ok(Vec::new());
471- }
472- let records: Vec<RecordId> = courses.iter().map(CourseId::record).collect();
473- let mut result = db
474- .query("SELECT * FROM exam WHERE course IN $courses ORDER BY id DESC")
475- .bind(("courses", records))
476- .await?
477- .check()?;
478- Ok(result.take::<Vec<Exam>>(0)?)
479- }
480-
481- // `course` is deliberately not updatable — moving an exam between courses
482- // would strand results of students not enrolled in the target course.
483- #[expect(
484- clippy::too_many_arguments,
485- reason = "mirrors the sibling entities' update(field, field, ..) shape"
486- )]
487- /// Save the merged exam, but only while the row still reads as the
488- /// snapshot the caller merged over — `None` means a concurrent PATCH
489- /// landed in between and nothing was written: re-read, re-merge, retry.
490- ///
491- /// Every column this write replaces is in the guard, which is what makes
492- /// the whole-row `CONTENT` save safe without a lock held across the
493- /// handler's read: the compare-and-set refuses precisely when that save
494- /// would have reverted somebody. `course`/`creator` are not editable and
495- /// ride along unchanged. Same shape as
496- /// [`crate::db::settings::save_if_unchanged`].
497- pub async fn update_if_unchanged(
498- mut self,
499- title: ExamTitle,
500- description: ExamDescription,
501- kind: ExamKind,
502- schedule: ExamSchedule,
503- max_attempts: ExamAttemptLimit,
504- allow_rejoin: bool,
505- allow_review: bool,
506- draft: bool,
507- db: &Database,
508- ) -> Result<Option<Exam>, AppError> {
509- // Re-drafting hides an exam: it must be refused while any sitting or
510- // mark exists, and that check has to be *in this transaction*. Holding
511- // it under a lock outside would only order the two writers inside one
512- // process — and it did not even do that, since grading takes the reader
513- // lease this write does.
514- let redraft = draft && !self.draft;
515- let was = (
516- self.title.clone(),
517- self.description.clone(),
518- self.kind.clone(),
519- self.mode.clone(),
520- self.starts_at,
521- self.ends_at,
522- self.duration_ms,
523- self.max_attempts,
524- self.allow_rejoin,
525- self.allow_review,
526- self.draft,
527- );
528- self.title = title;
529- self.description = description;
530- self.kind = kind;
531- self.mode = schedule.mode;
532- self.starts_at = schedule.starts_at;
533- self.ends_at = schedule.ends_at;
534- self.duration_ms = schedule.duration_ms;
535- self.max_attempts = max_attempts;
536- self.allow_rejoin = allow_rejoin;
537- self.allow_review = allow_review;
538- self.draft = draft;
539- // whole-row-save-ok: the WHERE below pins every column this replaces to
540- // the caller's snapshot, so no concurrent write can be reverted
541- //
542- // Sent through the retry loop, not a bare `query`: this row now has a
543- // hot writer. Every answer save touches it to tie itself to the exam
544- // ([`crate::domain::exam_answer::ExamAnswer::save`]), so a teacher
545- // flipping `allow_rejoin` mid-exam can lose a round to a student
546- // typing — and a lost round is a re-send, never the 500 a bare `?` on
547- // the conflict would have answered. Re-sending is sound because the
548- // statement is a compare-and-set: the second pass carries the same
549- // pinned snapshot, so it lands only if the row is still what the caller
550- // read, and a rival that really moved it is refused as it was before.
551- // Admissible for the loop — an `UPDATE`, an `IF`/`THROW` and a `SELECT`
552- // can never answer "already exists".
553- let (mut result, mut errors) = transaction_with_retry(
554- db,
555- "BEGIN TRANSACTION;
556- IF $redraft AND (
557- array::len((SELECT VALUE id FROM exam_attempt WHERE exam = $id LIMIT 1)) > 0
558- OR array::len((SELECT VALUE id FROM exam_result WHERE exam = $id LIMIT 1)) > 0
559- ) { THROW 'exam_redraft' };
560- UPDATE $id CONTENT $new
561- WHERE title = $was_title AND description = $was_description
562- AND kind = $was_kind AND mode = $was_mode
563- AND starts_at = $was_starts AND ends_at = $was_ends
564- AND duration_ms = $was_duration
565- AND max_attempts = $was_max_attempts
566- AND allow_rejoin = $was_allow_rejoin
567- AND allow_review = $was_allow_review
568- AND draft = $was_draft
569- AND (result_count ?? 0) = $was_results
570- RETURN AFTER;
571- COMMIT TRANSACTION;",
572- &[
573- ("redraft".into(), redraft.into_value()),
574- ("id".into(), self.id.record().into_value()),
575- ("was_title".into(), was.0.into_value()),
576- ("was_description".into(), was.1.into_value()),
577- ("was_kind".into(), was.2.into_value()),
578- ("was_mode".into(), was.3.into_value()),
579- ("was_starts".into(), was.4.into_value()),
580- ("was_ends".into(), was.5.into_value()),
581- ("was_duration".into(), was.6.into_value()),
582- ("was_max_attempts".into(), was.7.into_value()),
583- ("was_allow_rejoin".into(), was.8.into_value()),
584- ("was_allow_review".into(), was.9.into_value()),
585- ("was_draft".into(), was.10.into_value()),
586- // The mark counter is pinned like every other column this write
587- // replaces, and for a sharper reason: a grade increments it, so
588- // pinning it is what makes "this exam had no marks" — the gate
589- // the handler refuses a kind change on — true at *write* time
590- // and not merely at read time. A mark landing in between
591- // refuses the save.
592- (
593- "was_results".into(),
594- self.result_count.unwrap_or(0).into_value(),
595- ),
596- ("new".into(), self.into_value()),
597- ],
598- &["exam_redraft"],
599- )
600- .await?;
601- // An aborted transaction errors every slot; only the THROW's names the
602- // marker (the [`crate::db::exam_attempt::write_unfrozen`] treatment).
603- if errors
604- .values()
605- .any(|error| error.to_string().contains("exam_redraft"))
606- {
607- return Err(redraft_error());
608- }
609- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
610- return Err(error.into());
611- }
612- // BEGIN and the IF take a slot each.
613- Ok(result.take::<Vec<Exam>>(2)?.into_iter().next())
614- }
615-
616- /// Delete the exam and cascade-remove its result, attempt, question,
617- /// answer, question-image, and answer-image rows — all in one transaction,
618- /// so a failure can't leave an emptied-out exam shell behind. The image
619- /// *blobs* (question and answer) are the web layer's to remove — it collects
620- /// their names before calling this.
621- ///
622- /// Bank templates saved out of this exam survive it — they are a separate,
623- /// reusable library — so only their `source_exam` provenance link is cleared,
624- /// in the same transaction, never left pointing at a dead exam.
625- ///
626- /// The questions about to be cascaded each hold a reference on their
627- /// subject, which is what keeps that subject from being deleted under them.
628- /// They are given back in this same transaction, counted per subject, so
629- /// deleting an exam frees its subjects for deletion and nothing else does.
630- /// The marks give their *kind* references back the same way, and it has to
631- /// be the same way: counted outside the transaction, a mark deleted by a
632- /// concurrent `remove_result` in the gap would be released twice — once by
633- /// each — which on a kind another exam still uses reads as one mark too
634- /// few, and that is a kind wrongly free to leave the settings.
635- pub async fn delete(self, db: &Database) -> Result<Exam, AppError> {
636- let (mut result, mut errors) = transaction_with_retry(
637- db,
638- "BEGIN TRANSACTION;
639- FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result
640- WHERE exam = $ex GROUP BY kind) ?? []) {
641- UPDATE type::record('kind_ref', $row.kind) SET count =
642- math::max([(count ?? 0) - $row.n, 0])
643- };
644- DELETE exam_result WHERE exam = $ex;
645- DELETE exam_attempt WHERE exam = $ex;
646- DELETE exam_answer WHERE exam = $ex;
647- DELETE answer_image WHERE exam = $ex;
648- DELETE question_image WHERE exam = $ex;
649- FOR $row IN ((SELECT subject, count() AS n FROM exam_question
650- WHERE exam = $ex GROUP BY subject) ?? []) {
651- UPDATE $row.subject SET exam_question_count =
652- math::max([(exam_question_count ?? 0) - $row.n, 0])
653- };
654- DELETE exam_question WHERE exam = $ex;
655- UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex;
656- LET $before = (DELETE $ex RETURN BEFORE);
657- RETURN $before;
658- COMMIT TRANSACTION;",
659- &[("ex".into(), self.id.record().into_value())],
660- // No THROW of its own: an unconditional cascade, so the only error
661- // worth telling apart is a lost round, and `check()` — which took
662- // the *first* error in the batch — could not. It reported a
663- // sibling's "not executed" and made a retryable round a 500.
664- &[],
665- )
666- .await?;
667- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
668- return Err(error.into());
669- }
670- // The deleted row comes back through the transaction's trailing
671- // `RETURN`, never a hand-counted slot: the old `take(8)` turned a
672- // successful delete into a 404 the moment a cascade statement was
673- // inserted above it (it already had to be bumped once). `RETURN` is
674- // always the last statement before `COMMIT`, so its slot is derived
675- // from the statement count and every insertion above it shifts it
676- // along. `num_statements` counts BEGIN and COMMIT too, hence -2.
677- let slot = result.num_statements().saturating_sub(2);
678- let deleted: Option<Exam> = result.take::<Vec<Exam>>(slot)?.into_iter().next();
679- deleted.ok_or(AppError::NotFound)
680- }
681-}
682-
683-/// An unscheduled published exam — the minimum any test that writes a *child*
684-/// of an exam needs, in any module: every such write moves the exam row (see
685-/// [`crate::db::exam_attempt::write_unfrozen_with`]
686-/// and [`crate::domain::exam_answer::ExamAnswer::save`]), so a minted id whose
687-/// row was never created is a 404 rather than a silent orphan.
688-#[cfg(test)]
689-pub(crate) async fn published_exam(db: &Database) -> Exam {
690- let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
691- .get_exam_kinds()
692- .to_vec();
693- Exam::create(
694- &UserId::generate(),
695- &crate::db::course::a_test_course(db).await,
696- ExamTitle::try_new("midterm").unwrap(),
697- ExamDescription::try_new("").unwrap(),
698- ExamKind::try_new("midterm", &allowed).unwrap(),
699- ExamSchedule::try_new(None, None, None, None).unwrap(),
700- ExamAttemptLimit::try_new(1).unwrap(),
701- true,
702- false,
703- false,
704- db,
705- )
706- .await
707- .unwrap()
708-}
709-
710-#[cfg(test)]
711-mod tests {
712- use super::*;
713-
714- use crate::domain::exam::published_exam as published;
715-
716- /// An exam must not outlive the course it belongs to. It is the worst of
717- /// the three children `Course::delete` used to leave behind: every exam
718- /// route funnels through `course_of`, which answers
719- /// `Internal("exam references a missing course")`, so an orphan **500s
720- /// forever** on `GET`/`PATCH`/`DELETE /exams/{id}` — undeletable — while
721- /// `Exam::list_all` still hands it to every manager+ on `GET /exams`.
722- ///
723- /// [`Exam::create`] therefore *writes* the course row rather than reading
724- /// it ([`cap::touch_and_create`]); the harness and the window it races in
725- /// are documented on
726- /// [`crate::db::course::assert_no_child_outlives_a_course_delete`].
727- /// Mutation-tested: with the bare `db.create` this shipped with, all four
728- /// rounds orphan.
729- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
730- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
731- async fn an_exam_never_outlives_its_course() {
732- fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {
733- tokio::spawn(async move {
734- let kinds = crate::domain::settings::Settings::defaults()
735- .get_exam_kinds()
736- .to_vec();
737- Exam::create(
738- &UserId::generate(),
739- &course,
740- ExamTitle::try_new("quiz").unwrap(),
741- ExamDescription::try_new("").unwrap(),
742- ExamKind::try_new("quiz", &kinds).unwrap(),
743- ExamSchedule::try_new(None, None, None, None).unwrap(),
744- ExamAttemptLimit::try_new(1).unwrap(),
745- true,
746- false,
747- false,
748- &db,
749- )
750- .await
751- .map(|_| ())
752- })
753- }
754- crate::db::course::assert_no_child_outlives_a_course_delete("exam_orphan_race",
755- EXAM_TABLE,
756- make,)
757- .await;
758- }
759-
760- fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) {
761- (
762- exam.get_title().clone(),
763- exam.get_description().clone(),
764- exam.get_kind().clone(),
765- ExamSchedule::try_new(None, None, None, None).unwrap(),
766- )
767- }
768-
769- /// The bite test for the compare-and-set that replaced the writer lease on
770- /// `PATCH /exams/{id}`: a merge built on a snapshot the row has moved past
771- /// must be refused (the handler then re-reads and re-merges), never
772- /// written over somebody else's edit. Asserts the *stored* row.
773- #[tokio::test]
774- async fn a_merge_built_on_a_stale_snapshot_is_refused() {
775- let db = crate::database::init_mem().await.unwrap();
776- let stale = published(&db).await;
777- let (_, description, kind, schedule) = edit(&stale);
778- let landed = stale
779- .clone()
780- .update_if_unchanged(
781- ExamTitle::try_new("theirs").unwrap(),
782- description,
783- kind,
784- schedule,
785- ExamAttemptLimit::try_new(1).unwrap(),
786- true,
787- false,
788- false,
789- &db,
790- )
791- .await
792- .unwrap();
793- assert!(landed.is_some(), "the first write is on a fresh snapshot");
794-
795- let (_, description, kind, schedule) = edit(&stale);
796- let refused = stale
797- .update_if_unchanged(
798- ExamTitle::try_new("mine").unwrap(),
799- description,
800- kind,
801- schedule,
802- ExamAttemptLimit::try_new(1).unwrap(),
803- true,
804- false,
805- false,
806- &db,
807- )
808- .await
809- .unwrap();
810- assert!(refused.is_none(), "a stale merge must not be written");
811- let stored = Exam::read(landed.unwrap().get_id(), &db)
812- .await
813- .unwrap()
814- .unwrap();
815- assert_eq!(stored.get_title().as_str(), "theirs");
816- }
817-
818- /// The bite test for the re-draft guard now living *inside* the update's
819- /// transaction: a mark that lands after the handler's pre-flight gate (the
820- /// grade path is a lock reader, exactly like this one) must still stop the
821- /// exam from being hidden.
822- #[tokio::test]
823- async fn re_drafting_is_refused_by_the_write_itself_once_a_mark_exists() {
824- use crate::domain::exam_result::{ExamResult, Mark};
825- let db = crate::database::init_mem().await.unwrap();
826- let exam = published(&db).await;
827- let student = UserId::generate();
828- ExamResult::grade(
829- exam.get_id(),
830- &student,
831- 1,
832- Mark::try_new(80).unwrap(),
833- &UserId::generate(),
834- exam.get_kind().as_str(),
835- &db,
836- )
837- .await
838- .unwrap();
839-
840- let (title, description, kind, schedule) = edit(&exam);
841- let refused = exam
842- .clone()
843- .update_if_unchanged(
844- title,
845- description,
846- kind,
847- schedule,
848- ExamAttemptLimit::try_new(1).unwrap(),
849- true,
850- false,
851- true,
852- &db,
853- )
854- .await
855- .expect_err("a graded exam cannot be re-drafted");
856- assert!(refused.to_string().contains("back into a draft"));
857- let stored = Exam::read(exam.get_id(), &db).await.unwrap().unwrap();
858- assert!(!stored.is_draft(), "nothing may have been written");
859- }
860-
861- #[tokio::test]
862- async fn title_is_required() {
863- assert!(ExamTitle::try_new("midterm").is_ok());
864- assert!(ExamTitle::try_new("").is_err());
865- assert!(ExamTitle::try_new(" ").is_err());
866- }
867-
868- #[tokio::test]
869- async fn description_is_optional() {
870- assert!(ExamDescription::try_new("").is_ok());
871- }
872-
873- #[tokio::test]
874- async fn kind_must_be_in_the_allowed_list() {
875- let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
876- .get_exam_kinds()
877- .to_vec();
878- for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] {
879- assert_eq!(ExamKind::try_new(kind, &allowed).unwrap().as_str(), kind);
880- }
881- assert!(ExamKind::try_new("essay", &allowed).is_err());
882- assert!(ExamKind::try_new("", &allowed).is_err());
883- // A school-defined list swaps the acceptance set wholesale.
884- let custom = vec![ExamKindDef::try_new("lab", 2).unwrap()];
885- assert!(ExamKind::try_new("lab", &custom).is_ok());
886- assert!(ExamKind::try_new("midterm", &custom).is_err());
887- // Matching is exact, case included — the settings list is the wire
888- // truth, not a case-folded suggestion.
889- assert!(ExamKind::try_new("Lab", &custom).is_err());
890- }
891-
892- #[tokio::test]
893- async fn mode_must_be_known() {
894- for mode in ["sync", "async", "open"] {
895- assert_eq!(ExamMode::try_new(mode).unwrap().as_str(), mode);
896- }
897- assert!(ExamMode::try_new("live").is_err());
898- }
899-
900- #[tokio::test]
901- async fn attempt_limit_counts_or_never_runs_out() {
902- let single = ExamAttemptLimit::single();
903- assert_eq!(single.as_i64(), 1);
904- assert!(!single.is_unlimited());
905- assert!(single.allows_another(0));
906- assert!(!single.allows_another(1));
907-
908- let three = ExamAttemptLimit::try_new(3).unwrap();
909- assert!(three.allows_another(2));
910- assert!(!three.allows_another(3));
911- assert!(!three.allows_another(4));
912-
913- let unlimited = ExamAttemptLimit::try_new(0).unwrap();
914- assert!(unlimited.is_unlimited());
915- assert!(unlimited.allows_another(0));
916- assert!(unlimited.allows_another(10_000));
917-
918- assert!(ExamAttemptLimit::try_new(-1).is_err());
919- assert!(ExamAttemptLimit::try_new(101).is_err());
920- }
921-
922- #[tokio::test]
923- async fn schedule_invariants_hold() {
924- let mode = |m| Some(ExamMode::try_new(m).unwrap());
925- let at = |ms| Some(Timestamp::from_millis(ms));
926- let dur = Some(ExamDuration::try_new(90 * 60 * 1000).unwrap());
927-
928- // Unscheduled: nothing set is fine, any time/duration without a mode is not.
929- assert!(ExamSchedule::try_new(None, None, None, None).is_ok());
930- assert!(ExamSchedule::try_new(None, at(1), None, None).is_err());
931- assert!(ExamSchedule::try_new(None, None, at(2), None).is_err());
932- assert!(ExamSchedule::try_new(None, None, None, dur).is_err());
933-
934- // Sync: fixed window, no duration.
935- assert!(ExamSchedule::try_new(mode("sync"), at(1), at(2), None).is_ok());
936- assert!(ExamSchedule::try_new(mode("sync"), None, at(2), None).is_err());
937- assert!(ExamSchedule::try_new(mode("sync"), at(1), None, None).is_err());
938- // Over-long `dur` in a 1ms window, but the root cause is that sync
939- // takes no duration at all — that message wins over the window one.
940- assert!(matches!(
941- ExamSchedule::try_new(mode("sync"), at(1), at(2), dur),
942- Err(ValidationError::Invalid {
943- reason: "only async and open exams take a duration",
944- ..
945- })
946- ));
947-
948- // Async: window plus a per-student duration, which must fit inside it
949- // (equal to the window is fine; the window `at(1), at(2)` above is
950- // too narrow for `dur`, so give it one exactly `dur` wide instead).
951- assert!(ExamSchedule::try_new(mode("async"), at(1), at(1 + 90 * 60 * 1000), dur).is_ok());
952- assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), dur).is_err());
953- assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), None).is_err());
954-
955- // Open: no window, duration optional (limited or unlimited time).
956- assert!(ExamSchedule::try_new(mode("open"), None, None, None).is_ok());
957- assert!(ExamSchedule::try_new(mode("open"), None, None, dur).is_ok());
958- assert!(ExamSchedule::try_new(mode("open"), at(1), None, None).is_err());
959- assert!(ExamSchedule::try_new(mode("open"), None, at(2), None).is_err());
960- assert!(ExamSchedule::try_new(mode("open"), at(1), at(2), dur).is_err());
961-
962- // The window must be a real interval, whatever the mode.
963- assert!(ExamSchedule::try_new(mode("sync"), at(2), at(2), None).is_err());
964- assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err());
965- }
966-
967- /// GUARD, not a retry measurement — read the last paragraph before
968- /// trusting this test with the retry. See
969- /// [`crate::db::course::delete`]'s race test for why the rate is
970- /// counted rather than asserted per round.
971- ///
972- /// This site has no `THROW` marker at all: it ends `.check()?`, which
973- /// returns the *first* error in the batch, and an aborted transaction
974- /// errors every slot — most of them with a generic "not executed". So a
975- /// genuine conflict can be masked by a sibling, and either way there is no
976- /// [`crate::database::lost_the_race`] check and no retry.
977- ///
978- /// The racer is a mark: [`ExamResult::grade`] claims the exam's own
979- /// `result_count` (and the kind's reference) before writing, so it contends
980- /// with the `DELETE $ex` and with the kind_ref decrement inside the same
981- /// transaction. A round where *some* of the six grades 404 and the rest
982- /// succeed is the witness that the delete landed inside the burst: the 404
983- /// comes from `write_mark`'s existence gate, so it can only be answered by a
984- /// grade that reached the store after the row was gone, and its siblings'
985- /// success says the same burst also had grades that got there first. Stored
986- /// state cannot say this any more — the gate is what stops a mark outliving
987- /// its exam, so the sweep now finds nothing to leave behind in *every*
988- /// round, which is asserted below as a fact rather than read as a signal.
989- ///
990- /// It does not prove the retry either: measured at 0 conflicts in 100 raced
991- /// rounds, and green with
992- /// [`crate::database::transaction_with_retry`]'s loop cut to a single
993- /// attempt — the grades serialize behind `cap`'s claim lock, so they mostly
994- /// queue rather than collide. So this guards the status codes and the
995- /// cascade (marks either survive whole or are swept whole, never a 500).
996- /// The retry is measured on [`crate::db::course::delete`].
997- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
998- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
999- async fn a_delete_racing_a_mark_never_answers_500() {
1000- use crate::domain::exam_result::{ExamResult, Mark};
1001- let (db, _serialized) = crate::database::init_test_server("exam_delete_race").await;
1002- let (mut delete_500, mut grade_500) = (0, 0);
1003- let (mut split, mut swept) = (0, 0);
1004- let (mut last_delete, mut last_grade) = (String::new(), String::new());
1005- for round in 0..20 {
1006- let exam = published(&db).await;
1007- let kind = exam.get_kind().as_str().to_string();
1008-
1009- // A burst of marks and a delete held back by a sweeping beat: this
1010- // site has no guard to lose to, so a single racer released with it
1011- // simply finishes on one side of it. Same recipe as
1012- // [`crate::db::course::delete`]'s race test.
1013- let drop_it = {
1014- let (exam, db) = (exam.clone(), db.clone());
1015- // A wide sweep, not the 0-3ms the other three use: each grade
1016- // takes two counter writes serialized behind `cap`'s claim
1017- // lock, so the burst runs tens of milliseconds and a short beat
1018- // always puts the delete in front of all six.
1019- let beat = std::time::Duration::from_millis(round * 2);
1020- tokio::spawn(async move {
1021- tokio::time::sleep(beat).await;
1022- exam.delete(&db).await
1023- })
1024- };
1025- let marks: Vec<_> = (0..6)
1026- .map(|seat| {
1027- let (id, db, kind) = (exam.get_id().clone(), db.clone(), kind.clone());
1028- let student = UserId::from_key(&format!("stu{round}_{seat}"));
1029- tokio::spawn(async move {
1030- ExamResult::grade(
1031- &id,
1032- &student,
1033- 1,
1034- Mark::try_new(50).unwrap(),
1035- &UserId::from_key("teacher"),
1036- &kind,
1037- &db,
1038- )
1039- .await
1040- })
1041- })
1042- .collect();
1043- let drop_it = drop_it.await.unwrap();
1044- if matches!(drop_it, Err(AppError::Db(_))) {
1045- delete_500 += 1;
1046- last_delete = format!("{drop_it:?}");
1047- }
1048- let mut refused = 0;
1049- for mark in marks {
1050- let mark = mark.await.unwrap();
1051- match mark {
1052- // The existence gate: this grade reached the store after
1053- // the row was gone.
1054- Err(AppError::NotFound) => refused += 1,
1055- Err(AppError::Db(_)) => {
1056- grade_500 += 1;
1057- last_grade = format!("{mark:?}");
1058- }
1059- _ => {}
1060- }
1061- }
1062- // Neither end of the burst: some grades beat the delete and some
1063- // lost to it, so the delete landed *between* them. A round that is
1064- // all-refused or all-through is one where it landed outside.
1065- if (1..6).contains(&refused) {
1066- split += 1;
1067- }
1068- if ExamResult::list_for_exam(exam.get_id(), &db)
1069- .await
1070- .unwrap()
1071- .is_empty()
1072- {
1073- swept += 1;
1074- }
1075- }
1076- eprintln!(
1077- "Exam::delete raced: {delete_500}/20 delete 500s, {grade_500} grade 500s, \
1078- {split} rounds split by the delete / {swept} swept clean"
1079- );
1080- assert!(
1081- split > 0,
1082- "the delete never landed inside the burst (0/20 rounds split)"
1083- );
1084- // Not a race signal, an invariant: the gate refuses a mark for an exam
1085- // that is gone, so no round can leave one behind for the next reader.
1086- assert_eq!(
1087- swept,
1088- 20,
1089- "a mark outlived its exam in {} rounds",
1090- 20 - swept
1091- );
1092- assert_eq!(
1093- delete_500, 0,
1094- "a raced delete must not 500: {delete_500}/20 rounds, last {last_delete}"
1095- );
1096- assert_eq!(
1097- grade_500, 0,
1098- "a raced grade must retry, not 500: {grade_500}/20 rounds, last {last_grade}"
1099- );
1100- }
1101-
1102- /// One choice question on `exam`, with a real subject row behind it — a
1103- /// question claims a reference on its subject and is refused without one.
1104- async fn question_on(exam: &Exam, db: &Database) -> crate::domain::exam_question::ExamQuestion {
1105- use crate::domain::exam_question::{
1106- ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
1107- };
1108- let spec = QuestionSpec::try_new(
1109- QuestionKind::try_new("choice").unwrap(),
1110- Some(vec![
1111- ChoiceInput {
1112- id: Some("a".into()),
1113- text: "5".into(),
1114- },
1115- ChoiceInput {
1116- id: Some("b".into()),
1117- text: "6".into(),
1118- },
1119- ]),
1120- Some("b".into()),
1121- &[],
1122- )
1123- .unwrap();
1124- let subject = crate::domain::subject::Subject::create(
1125- &crate::db::course::a_test_course(db).await,
1126- crate::domain::subject::SubjectName::try_new("topic").unwrap(),
1127- crate::domain::subject::SubjectDescription::try_new("").unwrap(),
1128- db,
1129- )
1130- .await
1131- .unwrap();
1132- ExamQuestion::create(
1133- exam.get_id(),
1134- subject.get_id().clone(),
1135- QuestionText::try_new("3 + 3?").unwrap(),
1136- QuestionPoints::try_new(5).unwrap(),
1137- spec,
1138- db,
1139- )
1140- .await
1141- .unwrap()
1142- }
1143-
1144- /// The `Menu::delete` defect, one domain over: a student's answer must not
1145- /// outlive the exam it belongs to. Guarding the save by *reading* the exam
1146- /// would not do it — the read sees a row [`Exam::delete`] has removed but
1147- /// not committed, while its `DELETE exam_answer WHERE exam = $ex` swept a
1148- /// snapshot predating the save, so both commit and the answer is left
1149- /// pointing at an exam that is gone. [`ExamAnswer::save`] writes the exam
1150- /// row instead (its `result_count`, back unchanged), so the two transactions
1151- /// touch one key and the store refuses one of them.
1152- ///
1153- /// The window is opened by the database, not by a lucky interleaving: a
1154- /// `DEFINE EVENT` on `exam` fires *inside* the delete's own transaction the
1155- /// instant the row goes, so the `SLEEP` lands exactly between the delete and
1156- /// its cascade every time. Nothing in `src/` knows about it; the seam is the
1157- /// schema.
1158- ///
1159- /// One child per round, deliberately — in the menu twin, two children in one
1160- /// round hid the bug: the first writer made the delete lose and re-send, and
1161- /// the re-sent sweep removed the other's row.
1162- ///
1163- /// Real server, and `#[ignore]`d for it: the subject *is* the store's
1164- /// conflict detection, which `init_mem`'s embedded engine does not have — it
1165- /// commits both writes and answers `Ok` to each, so this passes there on
1166- /// broken code. Mutation-tested: putting the bare
1167- /// `db.upsert(id).content(answer)` back turns it red (the exact output is in
1168- /// the commit that added it).
1169- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1170- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1171- async fn an_answer_written_inside_a_delete_never_outlives_the_exam() {
1172- use crate::domain::exam_answer::ExamAnswer;
1173- let (db, _serialized) = crate::database::init_test_server("exam_answer_race").await;
1174- // Hold the delete open for a full second after the row is gone, while
1175- // its cascade still has to run.
1176- db.query(
1177- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1178- THEN { SLEEP 1s; };",
1179- )
1180- .await
1181- .unwrap()
1182- .check()
1183- .unwrap();
1184-
1185- let (mut answers, mut swept) = (0, 0);
1186- for round in 0..4 {
1187- let exam = published(&db).await;
1188- let question = question_on(&exam, &db).await;
1189- let id = exam.get_id().clone();
1190- let student = UserId::from_key(&format!("stu{round}"));
1191- // The stored choice ids are minted by the create, not the ones the
1192- // spec asked for — an answer must name one of *those*.
1193- let pick = question.get_choices().unwrap()[1]
1194- .get_id()
1195- .as_str()
1196- .to_string();
1197-
1198- let drop_it = {
1199- let db = db.clone();
1200- tokio::spawn(async move { exam.delete(&db).await })
1201- };
1202- // The save starts inside the held window — the exam row is gone but
1203- // uncommitted, which is exactly what an exam read believes.
1204- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1205- let child = {
1206- let (db, question, student) = (db.clone(), question.clone(), student.clone());
1207- tokio::spawn(async move {
1208- ExamAnswer::save(&question, &student, 1, Some(pick), None, &db).await
1209- })
1210- };
1211- let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1212- // A 404 for the save, or a NotFound for the delete, is a correct
1213- // answer — the only defect is stored state.
1214- assert!(
1215- !matches!(child, Err(AppError::Db(_))),
1216- "round {round}: a raced save must be answered, not 500: {child:?}"
1217- );
1218-
1219- // Stored state is the whole verdict; a return value is not evidence.
1220- if Exam::read(&id, &db).await.unwrap().is_none() {
1221- swept += 1;
1222- answers += ExamAnswer::list_for_exam(&id, &db).await.unwrap().len();
1223- } else if drop_it.is_ok() {
1224- panic!("round {round}: the delete reported success but the exam is still there");
1225- }
1226- }
1227- eprintln!("Exam::delete raced by an answer save: {swept}/4 rounds deleted the exam");
1228- assert!(
1229- swept > 0,
1230- "no round ever deleted the exam, so the window was never reached"
1231- );
1232- assert_eq!(answers, 0, "an answer outlived its exam");
1233- }
1234-
1235- /// The same defect on the teacher's side of the sheet, and a worse one: a
1236- /// question written inside the delete window kept the reference it claimed
1237- /// on its subject (the cascade's per-subject decrement counted only the
1238- /// rows it could see), and [`crate::domain::subject::Subject::delete`] is
1239- /// gated on that count reading zero — a subject nobody could ever delete
1240- /// again, hanging off an exam nobody could ever see. The freeze gate is a
1241- /// *read* of `exam_attempt` and never survived this window;
1242- /// [`crate::db::exam_attempt::write_unfrozen_with`] now writes the exam row too.
1243- ///
1244- /// Same seam, same `#[ignore]`, same reason as the answer twin above: the
1245- /// subject *is* the store's conflict detection, which the in-memory engine
1246- /// does not have.
1247- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1248- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1249- async fn a_question_written_inside_a_delete_never_outlives_the_exam() {
1250- use crate::domain::exam_question::{
1251- ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
1252- };
1253- use crate::domain::subject::Subject;
1254- let (db, _serialized) = crate::database::init_test_server("exam_question_race").await;
1255- db.query(
1256- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1257- THEN { SLEEP 1s; };",
1258- )
1259- .await
1260- .unwrap()
1261- .check()
1262- .unwrap();
1263-
1264- let (mut questions, mut swept, mut stuck) = (0, 0, 0);
1265- for round in 0..4 {
1266- let exam = published(&db).await;
1267- let id = exam.get_id().clone();
1268- let subject = Subject::create(
1269- &crate::db::course::a_test_course(&db).await,
1270- crate::domain::subject::SubjectName::try_new("topic").unwrap(),
1271- crate::domain::subject::SubjectDescription::try_new("").unwrap(),
1272- &db,
1273- )
1274- .await
1275- .unwrap();
1276-
1277- let drop_it = {
1278- let db = db.clone();
1279- tokio::spawn(async move { exam.delete(&db).await })
1280- };
1281- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1282- let child = {
1283- let (db, exam_id, on) = (db.clone(), id.clone(), subject.get_id().clone());
1284- tokio::spawn(async move {
1285- let spec = QuestionSpec::try_new(
1286- QuestionKind::try_new("choice").unwrap(),
1287- Some(vec![
1288- ChoiceInput {
1289- id: Some("a".into()),
1290- text: "5".into(),
1291- },
1292- ChoiceInput {
1293- id: Some("b".into()),
1294- text: "6".into(),
1295- },
1296- ]),
1297- Some("b".into()),
1298- &[],
1299- )
1300- .unwrap();
1301- ExamQuestion::create(
1302- &exam_id,
1303- on,
1304- QuestionText::try_new("3 + 3?").unwrap(),
1305- QuestionPoints::try_new(5).unwrap(),
1306- spec,
1307- &db,
1308- )
1309- .await
1310- })
1311- };
1312- let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1313- assert!(
1314- !matches!(child, Err(AppError::Db(_))),
1315- "round {round}: a raced question write must be answered, not 500: {child:?}"
1316- );
1317-
1318- if Exam::read(&id, &db).await.unwrap().is_none() {
1319- swept += 1;
1320- questions += ExamQuestion::list_for_exam(&id, None, 0, &db)
1321- .await
1322- .unwrap()
1323- .0
1324- .len();
1325- // The subject has to be free again: a stranded reference is the
1326- // half of this bug a row count alone would not catch.
1327- if Subject::read(subject.get_id(), &db)
1328- .await
1329- .unwrap()
1330- .unwrap()
1331- .delete(&db)
1332- .await
1333- .is_err()
1334- {
1335- stuck += 1;
1336- }
1337- } else if drop_it.is_ok() {
1338- panic!("round {round}: the delete reported success but the exam is still there");
1339- }
1340- }
1341- eprintln!("Exam::delete raced by a question write: {swept}/4 rounds deleted the exam");
1342- assert!(
1343- swept > 0,
1344- "no round ever deleted the exam, so the window was never reached"
1345- );
1346- assert_eq!(questions, 0, "a question outlived its exam");
1347- assert_eq!(stuck, 0, "an orphan question left its subject undeletable");
1348- }
1349-
1350- /// The student's half of the same picture problem: a drawing is a bare
1351- /// `UPSERT` — the exact pre-fix shape of [`ExamAnswer::save`] — so it kept
1352- /// the hole the text answer just lost, blob and all.
1353- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1354- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1355- async fn a_drawing_written_inside_a_delete_never_outlives_the_exam() {
1356- use crate::domain::answer_image::AnswerImage;
1357- use crate::domain::note_file::FileContentType;
1358- let (db, _serialized) = crate::database::init_test_server("answer_image_race").await;
1359- db.query(
1360- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1361- THEN { SLEEP 1s; };",
1362- )
1363- .await
1364- .unwrap()
1365- .check()
1366- .unwrap();
1367-
1368- let (mut drawings, mut swept) = (0, 0);
1369- for round in 0..4 {
1370- let exam = published(&db).await;
1371- let question = question_on(&exam, &db).await;
1372- let id = exam.get_id().clone();
1373- let student = UserId::from_key(&format!("stu{round}"));
1374-
1375- let drop_it = {
1376- let db = db.clone();
1377- tokio::spawn(async move { exam.delete(&db).await })
1378- };
1379- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1380- let child = {
1381- let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone());
1382- tokio::spawn(async move {
1383- AnswerImage::new(
1384- &exam_id,
1385- &on,
1386- &student,
1387- 1,
1388- FileContentType::try_new("image/png").unwrap(),
1389- 3,
1390- )
1391- .upsert(&db)
1392- .await
1393- })
1394- };
1395- let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1396- assert!(
1397- !matches!(child, Err(AppError::Db(_))),
1398- "round {round}: a raced drawing write must be answered, not 500: {child:?}"
1399- );
1400-
1401- if Exam::read(&id, &db).await.unwrap().is_none() {
1402- swept += 1;
1403- drawings += AnswerImage::list_for_exam(&id, &db).await.unwrap().len();
1404- } else if drop_it.is_ok() {
1405- panic!("round {round}: the delete reported success but the exam is still there");
1406- }
1407- }
1408- eprintln!("Exam::delete raced by a drawing write: {swept}/4 rounds deleted the exam");
1409- assert!(
1410- swept > 0,
1411- "no round ever deleted the exam, so the window was never reached"
1412- );
1413- assert_eq!(drawings, 0, "a drawing outlived its exam");
1414- }
1415-
1416- /// A picture is written through the same freeze gate as the question it
1417- /// hangs on, so it had the same hole — and one the row count does not even
1418- /// show: `delete_exam` collects the blob names to unlink *before* it calls
1419- /// [`Exam::delete`], so an image row landing after that snapshot strands
1420- /// its bytes on disk forever as well.
1421- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1422- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
1423- async fn a_picture_written_inside_a_delete_never_outlives_the_exam() {
1424- use crate::domain::note_file::FileContentType;
1425- use crate::domain::question_image::QuestionImage;
1426- let (db, _serialized) = crate::database::init_test_server("question_image_race").await;
1427- db.query(
1428- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \
1429- THEN { SLEEP 1s; };",
1430- )
1431- .await
1432- .unwrap()
1433- .check()
1434- .unwrap();
1435-
1436- let (mut images, mut swept) = (0, 0);
1437- for round in 0..4 {
1438- let exam = published(&db).await;
1439- let question = question_on(&exam, &db).await;
1440- let id = exam.get_id().clone();
1441-
1442- let drop_it = {
1443- let db = db.clone();
1444- tokio::spawn(async move { exam.delete(&db).await })
1445- };
1446- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1447- let child = {
1448- let (db, exam_id, on) = (db.clone(), id.clone(), question.get_id().clone());
1449- tokio::spawn(async move {
1450- QuestionImage::new(
1451- &exam_id,
1452- &on,
1453- None,
1454- FileContentType::try_new("image/png").unwrap(),
1455- 3,
1456- )
1457- .upsert(&db)
1458- .await
1459- })
1460- };
1461- let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
1462- assert!(
1463- !matches!(child, Err(AppError::Db(_))),
1464- "round {round}: a raced picture write must be answered, not 500: {child:?}"
1465- );
1466-
1467- if Exam::read(&id, &db).await.unwrap().is_none() {
1468- swept += 1;
1469- images += QuestionImage::list_for_exam(&id, &db).await.unwrap().len();
1470- } else if drop_it.is_ok() {
1471- panic!("round {round}: the delete reported success but the exam is still there");
1472- }
1473- }
1474- eprintln!("Exam::delete raced by a picture write: {swept}/4 rounds deleted the exam");
1475- assert!(
1476- swept > 0,
1477- "no round ever deleted the exam, so the window was never reached"
1478- );
1479- assert_eq!(images, 0, "a picture outlived its exam");
1480- }
1481390 }
src/domain/exam_answer.rsmodified+7 -7
@@ -173,7 +173,7 @@ impl ExamAnswer {
173173 };
174174 // The save writes the *exam row* as well as the answer, in one
175175 // transaction, and that is what ties the answer's fate to its exam:
176- // reading the exam does not survive [`crate::domain::exam::Exam::delete`]'s
176+ // reading the exam does not survive [`crate::db::exam::delete`]'s
177177 // window — a save landing after its `DELETE exam_answer WHERE exam = $ex`
178178 // but before the commit reads an exam that is still there (uncommitted)
179179 // while the sweep ran on a snapshot predating this row, so both commit
@@ -240,7 +240,7 @@ impl ExamAnswer {
240240 }
241241 // The trailing `RETURN` is the last statement before `COMMIT`, so its
242242 // slot follows the statement count rather than a hand-kept number (the
243- // `Exam::delete` treatment); `num_statements` counts BEGIN and COMMIT.
243+ // `db::exam::delete` treatment); `num_statements` counts BEGIN and COMMIT.
244244 let slot = result.num_statements().saturating_sub(2);
245245 result
246246 .take::<Vec<ExamAnswer>>(slot)?
@@ -491,22 +491,23 @@ mod tests {
491491 }
492492
493493 /// The bite test for the exam-row touch in [`ExamAnswer::save`]: it exists
494- /// to collide with [`crate::domain::exam::Exam::delete`], so it must leave
494+ /// to collide with [`crate::db::exam::delete`], so it must leave
495495 /// the counter it borrows exactly where it found it — absent stays absent
496496 /// (the boot backfill keys on `result_count = NONE`), and a real count is
497497 /// not moved by a student typing. The race half is
498- /// `domain::exam::tests::an_answer_written_inside_a_delete_never_outlives_the_exam`,
498+ /// `db::exam::tests::an_answer_written_inside_a_delete_never_outlives_the_exam`,
499499 /// which needs a real server; this half is the arithmetic and runs anywhere.
500500 #[tokio::test]
501501 async fn a_save_puts_the_exams_mark_counter_back_exactly() {
502502 use crate::domain::exam::{
503- Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,
503+ ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,
504504 };
505505 let db = crate::database::init_mem().await.unwrap();
506506 let kinds = crate::domain::settings::Settings::defaults()
507507 .get_exam_kinds()
508508 .to_vec();
509- let exam = Exam::create(
509+ let exam = crate::db::exam::create(
510+ &db,
510511 &student(),
511512 &crate::db::course::a_test_course(&db).await,
512513 ExamTitle::try_new("quiz").unwrap(),
@@ -517,7 +518,6 @@ mod tests {
517518 true,
518519 false,
519520 false,
520- &db,
521521 )
522522 .await
523523 .unwrap();
src/domain/exam_question.rsmodified+2 -2
@@ -1096,7 +1096,8 @@ mod tests {
10961096
10971097 async fn an_exam(db: &Database) -> Exam {
10981098 let kinds = Settings::defaults().get_exam_kinds().to_vec();
1099- Exam::create(
1099+ crate::db::exam::create(
1100+ db,
11001101 &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"),
11011102 &crate::db::course::a_test_course(db).await,
11021103 ExamTitle::try_new("practice").unwrap(),
@@ -1108,7 +1109,6 @@ mod tests {
11081109 true,
11091110 false,
11101111 false,
1111- db,
11121112 )
11131113 .await
11141114 .unwrap()
src/domain/homework.rsmodified+2 -2
@@ -18,8 +18,8 @@ use crate::constant::{
1818 };
1919 use crate::database::Database;
2020 use crate::db::cap;
21-use crate::domain::course::CourseId;
2221 use crate::db::field_update::FieldUpdate;
22+use crate::domain::course::CourseId;
2323 use crate::domain::monotonic_id::next_ulid;
2424 use crate::domain::subject::SubjectId;
2525 use crate::domain::timestamp::Timestamp;
@@ -370,7 +370,7 @@ impl Homework {
370370 .check()?;
371371 // The subject's reference is given back in this same transaction, off
372372 // what the delete actually removed. Read through the trailing `RETURN`,
373- // not a hand-counted slot — see [`crate::domain::exam::Exam::delete`].
373+ // not a hand-counted slot — see [`crate::db::exam::delete`].
374374 let slot = result.num_statements().saturating_sub(2);
375375 let deleted: Option<Homework> = result.take::<Vec<Homework>>(slot)?.into_iter().next();
376376 deleted.ok_or(AppError::NotFound)
src/domain/question_image.rsmodified+1 -4
@@ -258,10 +258,7 @@ mod tests {
258258 /// keeps a picture from outliving its exam), so a minted id nothing wrote
259259 /// is a 404.
260260 async fn exam_row(db: &Database) -> ExamId {
261- crate::domain::exam::published_exam(db)
262- .await
263- .get_id()
264- .clone()
261+ crate::db::exam::published_exam(db).await.get_id().clone()
265262 }
266263
267264 fn png() -> FileContentType {
src/domain/subject.rsmodified+9 -10
@@ -5,10 +5,10 @@ use crate::constant::{
55 };
66 use crate::database::{Database, transaction_with_retry};
77 use crate::db::cap;
8-use crate::domain::course::CourseId;
98 use crate::db::field_update::FieldUpdate;
10-use crate::domain::monotonic_id::next_ulid;
119 use crate::db::page::PagedList;
10+use crate::domain::course::CourseId;
11+use crate::domain::monotonic_id::next_ulid;
1212 use crate::error::{AppError, ValidationError};
1313 use crate::validate::{validate_optional, validate_required};
1414
@@ -244,7 +244,7 @@ impl Subject {
244244 return Err(error.into());
245245 }
246246 // Read through the trailing `RETURN`, not a counted slot — see
247- // [`crate::domain::exam::Exam::delete`].
247+ // [`crate::db::exam::delete`].
248248 let slot = result.num_statements().saturating_sub(2);
249249 let deleted: Option<Subject> = result.take::<Vec<Subject>>(slot)?.into_iter().next();
250250 deleted.ok_or(AppError::NotFound)
@@ -281,9 +281,11 @@ mod tests {
281281 .map(|_| ())
282282 })
283283 }
284- crate::db::course::assert_no_child_outlives_a_course_delete("subject_orphan_race",
285- SUBJECT_TABLE,
286- make,)
284+ crate::db::course::assert_no_child_outlives_a_course_delete(
285+ "subject_orphan_race",
286+ SUBJECT_TABLE,
287+ make,
288+ )
287289 .await;
288290 }
289291
@@ -356,10 +358,7 @@ mod tests {
356358 // A real exam row per round: a question write moves its exam's
357359 // counter, so a minted id nothing wrote is a 404 and no round would
358360 // reach the subject race this test is about.
359- let exam = crate::domain::exam::published_exam(&db)
360- .await
361- .get_id()
362- .clone();
361+ let exam = crate::db::exam::published_exam(&db).await.get_id().clone();
363362 let subject = Subject::create(
364363 &course,
365364 SubjectName::try_new("Limits").unwrap(),
src/service/course.rsmodified+2 -3
@@ -11,8 +11,8 @@ use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, Cou
1111 use crate::domain::course_note_file::CourseNoteFile;
1212 use crate::domain::homework_file::HomeworkFile;
1313 use crate::domain::question_image::QuestionImage;
14-use crate::domain::term::{self, TermId};
1514 use crate::domain::role::Role;
15+use crate::domain::term::{self, TermId};
1616 use crate::domain::user::{User, UserId};
1717 use crate::error::{AppError, ValidationError};
1818
@@ -138,8 +138,7 @@ pub struct DeleteOutcome {
138138 /// Delete the course: collect the image/homework/note-file blob keys, then
139139 /// run the cascading delete.
140140 ///
141-/// Writer lease of [`crate::web::exams::EXAM_LOCK`] (moving to
142-/// `crate::service::exam_attempt` with the exam lane's split), for
141+/// Writer lease of [`crate::service::exam_attempt::EXAM_LOCK`], for
143142 /// `delete_exam`'s reason: this cascade sweeps the course's exams *and their
144143 /// attempts*, and an attempt is the one exam child whose write cannot
145144 /// collide with the sweep (its claim lands on the student's row, never the
src/service/exam.rsadded+287 -0
@@ -0,0 +1,287 @@
1+//! Exam workflows: the PATCH re-derive — the merge (set / clear / keep per
2+//! field) re-judged against a fresh read every retry round, and the
3+//! mode-freeze, re-draft, and kind gates that guard it — and the delete that
4+//! collects the image blob keys under the writer lease before the cascade.
5+//! The queries live in [`crate::db::exam`]; the sitting workflows next door
6+//! in [`crate::service::exam_attempt`], whose [`EXAM_LOCK`] every path here
7+//! leases.
8+
9+use crate::constant::CAS_UPDATE_RETRIES;
10+use crate::database::Database;
11+use crate::db::exam;
12+use crate::domain::answer_image::AnswerImage;
13+use crate::domain::course::CourseId;
14+use crate::domain::exam::{
15+ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,
16+ ExamSchedule, ExamTitle, redraft_error,
17+};
18+use crate::domain::exam_result::ExamResult;
19+use crate::domain::question_image::QuestionImage;
20+use crate::domain::timestamp::Timestamp;
21+use crate::domain::user::UserId;
22+use crate::error::AppError;
23+use crate::service::course::require_open;
24+use crate::service::exam_attempt::{EXAM_LOCK, any_for_exam, course_of};
25+
26+pub async fn create(
27+ db: &Database,
28+ creator: &UserId,
29+ course: &CourseId,
30+ title: ExamTitle,
31+ description: ExamDescription,
32+ kind: ExamKind,
33+ schedule: ExamSchedule,
34+ max_attempts: ExamAttemptLimit,
35+ allow_rejoin: bool,
36+ allow_review: bool,
37+ draft: bool,
38+) -> Result<Exam, AppError> {
39+ exam::create(
40+ db,
41+ creator,
42+ course,
43+ title,
44+ description,
45+ kind,
46+ schedule,
47+ max_attempts,
48+ allow_rejoin,
49+ allow_review,
50+ draft,
51+ )
52+ .await
53+}
54+
55+/// The exam row, for callers that only inspect it — the web layer's gates
56+/// read through here.
57+pub async fn read(db: &Database, id: &ExamId) -> Result<Option<Exam>, AppError> {
58+ exam::read(db, id).await
59+}
60+
61+pub async fn list_all(db: &Database) -> Result<Vec<Exam>, AppError> {
62+ exam::list_all(db).await
63+}
64+
65+pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Exam>, AppError> {
66+ exam::list_for_course(db, course).await
67+}
68+
69+/// Every exam of every course in `courses` (one query) — the catalog as one
70+/// user sees it.
71+pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result<Vec<Exam>, AppError> {
72+ exam::list_for_courses(db, courses).await
73+}
74+
75+/// A `PATCH /exams/{id}` request after field validation: every value the
76+/// request *set* is already validated (title, description, mode, duration,
77+/// and attempt limit by their newtypes; the kind against the school's
78+/// current list; newly set window ends by the web layer's no-past grace).
79+/// What is *kept* — and whether the merged whole is a legal schedule — are
80+/// the update's own decisions, re-derived against a fresh read every retry
81+/// round, so they live here and not in the web layer. A `None` field keeps
82+/// the stored value; the `Option<Option<..>>` schedule fields carry the
83+/// web DTO's set-or-clear spelling (`Some(None)` = explicit `null`).
84+pub struct ExamPatch {
85+ pub title: Option<ExamTitle>,
86+ pub description: Option<ExamDescription>,
87+ pub kind: Option<ExamKind>,
88+ pub mode: Option<Option<ExamMode>>,
89+ pub starts_at: Option<Option<Timestamp>>,
90+ pub ends_at: Option<Option<Timestamp>>,
91+ pub duration_ms: Option<Option<ExamDuration>>,
92+ pub max_attempts: Option<ExamAttemptLimit>,
93+ pub allow_rejoin: Option<bool>,
94+ pub allow_review: Option<bool>,
95+ pub draft: Option<bool>,
96+}
97+
98+/// Re-derive and save the exam: merge the patch over a fresh read, re-validate
99+/// the schedule as a unit, judge every business gate against that same row,
100+/// and land the whole merge with the compare-and-set — retried while the row
101+/// keeps moving under the snapshot.
102+///
103+/// *Reader* lease of [`EXAM_LOCK`] for exactly one pairing: the mode gate
104+/// below reads `exam_attempt`, and an attempt start takes the *writer*
105+/// lease, so a first sitting still cannot land between that gate and the
106+/// write, as it always did.
107+///
108+/// It buys nothing against grading, which is a reader too: the re-draft gate
109+/// is therefore enforced inside the update's own transaction
110+/// ([`exam::update_if_unchanged`]), where the store decides it. The gate
111+/// below stays as the pre-flight — same error, one round trip earlier.
112+/// Concurrent PATCHes of this exam no longer queue behind each other either:
113+/// the lost update they used to cause is refused by the compare-and-set.
114+pub async fn update(db: &Database, id: &ExamId, patch: &ExamPatch) -> Result<Exam, AppError> {
115+ let _guard = EXAM_LOCK.read().await;
116+ let mut left = CAS_UPDATE_RETRIES;
117+ loop {
118+ let current = exam::read(db, id).await?.ok_or(AppError::NotFound)?;
119+ let course = course_of(&current, db).await?;
120+ require_open(db, &course).await?;
121+
122+ let title = patch
123+ .title
124+ .clone()
125+ .unwrap_or_else(|| current.get_title().clone());
126+ let description = patch
127+ .description
128+ .clone()
129+ .unwrap_or_else(|| current.get_description().clone());
130+ let kind = patch
131+ .kind
132+ .clone()
133+ .unwrap_or_else(|| current.get_kind().clone());
134+
135+ // Merge the schedule (set / clear / keep per field), then re-validate it
136+ // as a unit — a PATCH can't leave a half-schedule behind. Only values this
137+ // request sets are held to the no-past rule: kept ones may legitimately be
138+ // past (a running exam's `starts_at`), and rechecking them would block
139+ // unrelated edits.
140+ let mode = match &patch.mode {
141+ Some(update) => update.clone(),
142+ None => current.get_mode().cloned(),
143+ };
144+ let starts_at = match patch.starts_at {
145+ Some(update) => update,
146+ None => current.get_starts_at(),
147+ };
148+ let ends_at = match patch.ends_at {
149+ Some(update) => update,
150+ None => current.get_ends_at(),
151+ };
152+ let duration_ms = match patch.duration_ms {
153+ Some(update) => update,
154+ None => current.get_duration_ms(),
155+ };
156+ let schedule = ExamSchedule::try_new(mode, starts_at, ends_at, duration_ms)?;
157+ let max_attempts = patch
158+ .max_attempts
159+ .unwrap_or_else(|| current.get_max_attempts());
160+ let allow_rejoin = patch
161+ .allow_rejoin
162+ .unwrap_or_else(|| current.get_allow_rejoin());
163+ let allow_review = patch
164+ .allow_review
165+ .unwrap_or_else(|| current.get_allow_review());
166+ let draft = patch.draft.unwrap_or(current.is_draft());
167+
168+ // Switching sync <-> async <-> open (or back to unscheduled) would
169+ // silently rewrite the deadline rules under students who already sat
170+ // down; extending times, the attempt limit, and the rejoin door are the
171+ // supported live adjustments instead. Gate read and write share the
172+ // call-wide reader lease of [`EXAM_LOCK`], so a first attempt can't
173+ // land in the gap and leave a sat exam's mode flipped under it.
174+ let mode_changed =
175+ schedule.get_mode().map(ExamMode::as_str) != current.get_mode().map(ExamMode::as_str);
176+ if mode_changed && any_for_exam(db, current.get_id()).await? {
177+ return Err(AppError::Conflict(
178+ "cannot change the exam mode after attempts have started",
179+ ));
180+ }
181+ // Re-drafting hides the exam — never out from under a student who
182+ // already sat it or holds a mark on it. Pre-flight only: the write's own
183+ // transaction re-makes this check and answers with the same error, so a
184+ // grade landing after this read still cannot leave a mark on a draft.
185+ if draft && !current.is_draft() {
186+ let sat = any_for_exam(db, current.get_id()).await?;
187+ let graded = !ExamResult::list_for_exam(current.get_id(), db)
188+ .await?
189+ .is_empty();
190+ if sat || graded {
191+ return Err(redraft_error());
192+ }
193+ }
194+
195+ // A graded exam keeps its kind. Moving it re-weights every mark it
196+ // already carries — the same silent re-weighting the settings' removal
197+ // guard refuses — and it would strand those marks' references on the
198+ // kind they were counted under, freeing the kind the exam now claims to
199+ // be. Marks are counted on the exam row, and the save below *pins* that
200+ // counter, so a grade landing between this read and the write refuses
201+ // the save (the loop then re-reads and answers the 409 below).
202+ if kind.as_str() != current.get_kind().as_str() && current.get_result_count() > 0 {
203+ return Err(AppError::Conflict(
204+ "cannot change the kind of an exam that already has marks",
205+ ));
206+ }
207+
208+ if let Some(updated) = exam::update_if_unchanged(
209+ db,
210+ current,
211+ title,
212+ description,
213+ kind,
214+ schedule,
215+ max_attempts,
216+ allow_rejoin,
217+ allow_review,
218+ draft,
219+ )
220+ .await?
221+ {
222+ return Ok(updated);
223+ }
224+ // The row moved under the snapshot every gate above judged: re-read and
225+ // re-merge, so both edits land instead of the later reverting the earlier.
226+ left -= 1;
227+ if left == 0 {
228+ return Err(AppError::Conflict(
229+ "the exam kept changing underneath this update — try again",
230+ ));
231+ }
232+ }
233+}
234+
235+/// What [`delete`] did: the blob keys of the image rows the cascade removed —
236+/// exactly whose files the web layer may unlink.
237+#[derive(Debug)]
238+pub struct DeleteOutcome {
239+ pub image_files: Vec<String>,
240+ pub answer_image_files: Vec<String>,
241+}
242+
243+/// Delete the exam: collect the question/answer image blob keys, then run the
244+/// cascading delete.
245+///
246+/// Writer lease of [`EXAM_LOCK`] across the whole cascade, blob names
247+/// included — the lease `delete_homework` has always held, and its absence
248+/// here is what made a sitting able to start inside this delete. Every other
249+/// child of an exam now writes the exam row in its own transaction, so the
250+/// store refuses the pair; an attempt cannot, because its claim lands on the
251+/// *student's* row (`exam_sat_total`) and touches nothing this delete
252+/// writes. `start_attempt` already takes the writer lease from its exam read
253+/// through the insert, so this one lease is the whole ordering: a start
254+/// either finishes before the sweep (which then takes its row) or reads no
255+/// exam at all and is a 404. Left orphaned, that attempt kept a sitting on
256+/// the student's lifetime counter and could mint a badge — awards are
257+/// add-only and never revoked — for an exam that never existed.
258+///
259+/// It spans the blob names too: they are collected *before* the rows go, so
260+/// an image row written after that snapshot would strand its bytes on disk
261+/// even though the row itself is now refused.
262+///
263+/// corner-cut: process-local, so it holds because the deployment runs one
264+/// process by contract with stop-the-world deploys (two overlapping
265+/// binaries would
266+/// reopen it). Closing it in the store means the `cap` shape the counter
267+/// work already sketched: `claim_and_create` gaining a second record to
268+/// touch, so the attempt writes the exam key as every other child does.
269+pub async fn delete(db: &Database, target: &Exam) -> Result<DeleteOutcome, AppError> {
270+ require_open(db, &course_of(target, db).await?).await?;
271+ let _guard = EXAM_LOCK.write().await;
272+ // Rows go first (the delete cascades them), blobs after — a crash in
273+ // between strands at worst an unreachable blob.
274+ let images = QuestionImage::list_for_exam(target.get_id(), db).await?;
275+ let answer_images = AnswerImage::list_for_exam(target.get_id(), db).await?;
276+ exam::delete(db, target.clone()).await?;
277+ Ok(DeleteOutcome {
278+ image_files: images
279+ .iter()
280+ .map(|image| image.get_file().to_string())
281+ .collect(),
282+ answer_image_files: answer_images
283+ .iter()
284+ .map(|image| image.get_file().to_string())
285+ .collect(),
286+ })
287+}
src/service/exam_attempt.rsmodified+3 -3
@@ -299,7 +299,7 @@ pub async fn start_attempt(
299299 user: &User,
300300 ) -> Result<(Exam, ExamAttempt, bool), AppError> {
301301 let _guard = EXAM_LOCK.write().await;
302- let exam = crate::domain::exam::Exam::read(exam_id, db)
302+ let exam = crate::db::exam::read(db, exam_id)
303303 .await?
304304 .ok_or(AppError::NotFound)?;
305305 ensure_sittable(&exam)?;
@@ -505,7 +505,8 @@ mod tests {
505505 let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
506506 let course = crate::db::course::a_test_course(db).await;
507507 let kinds = Settings::defaults().get_exam_kinds().to_vec();
508- let exam = Exam::create(
508+ let exam = crate::db::exam::create(
509+ db,
509510 &creator,
510511 &course,
511512 ExamTitle::try_new("practice").unwrap(),
@@ -517,7 +518,6 @@ mod tests {
517518 true,
518519 false,
519520 false,
520- db,
521521 )
522522 .await
523523 .unwrap();
src/service/mod.rsmodified+1 -0
@@ -3,6 +3,7 @@
33
44 pub mod appointment;
55 pub mod course;
6+pub mod exam;
67 pub mod exam_attempt;
78 pub mod note;
89 pub mod payment_ledger;
src/web/courses.rsmodified+14 -14
@@ -14,8 +14,7 @@ use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, Cou
1414 use crate::domain::course_session::{CourseSession, SessionTopic};
1515 use crate::domain::enrollment::Enrollment;
1616 use crate::domain::exam::{
17- Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule,
18- ExamTitle,
17+ ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle,
1918 };
2019 use crate::domain::homework::{Homework, HomeworkTitle};
2120 use crate::domain::role::Role;
@@ -265,7 +264,10 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Co
265264 } else {
266265 Vec::new()
267266 };
268- for course in service::course::list_enrolled(db, user.get_id(), None, 0).await?.0 {
267+ for course in service::course::list_enrolled(db, user.get_id(), None, 0)
268+ .await?
269+ .0
270+ {
269271 if !courses
270272 .iter()
271273 .any(|known| known.get_id() == course.get_id())
@@ -401,7 +403,8 @@ async fn my_courses(
401403 Query(page): Query<PageParams>,
402404 ) -> Result<Json<Page<CourseResponse>>, AppError> {
403405 let (limit, offset) = page.resolve()?;
404- let (courses, total) = service::course::list_enrolled(&st.db, user.get_id(), limit, offset).await?;
406+ let (courses, total) =
407+ service::course::list_enrolled(&st.db, user.get_id(), limit, offset).await?;
405408 let people = person_map(courses.iter().flat_map(course_people), &st.db).await?;
406409 let items = courses
407410 .iter()
@@ -865,7 +868,8 @@ async fn create_exam_in_course(
865868 Some(limit) => ExamAttemptLimit::try_new(limit)?,
866869 None => ExamAttemptLimit::single(),
867870 };
868- let exam = Exam::create(
871+ let exam = crate::service::exam::create(
872+ &st.db,
869873 user.get_id(),
870874 course.get_id(),
871875 title,
@@ -876,7 +880,6 @@ async fn create_exam_in_course(
876880 req.allow_rejoin.unwrap_or(true),
877881 req.allow_review.unwrap_or(false),
878882 req.draft.unwrap_or(false),
879- &st.db,
880883 )
881884 .await?;
882885 Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam))))
@@ -916,7 +919,7 @@ async fn list_course_exams(
916919 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course",
917920 ));
918921 }
919- let mut exams = Exam::list_for_course(course.get_id(), &st.db).await?;
922+ let mut exams = crate::service::exam::list_for_course(&st.db, course.get_id()).await?;
920923 // Drafts are the managers' workbench — enrolled students don't see them.
921924 if !can_manage_course(&course, &user) {
922925 exams.retain(|exam| !exam.is_draft());
@@ -1359,13 +1362,10 @@ mod tests {
13591362 let db = init_mem().await.unwrap();
13601363 let creator = user("creator", Role::Teacher, &db).await;
13611364 let assigned = user("assigned", Role::Teacher, &db).await;
1362- let course = service::course::assign_teacher(
1363- &db,
1364- &course(&creator, &db).await,
1365- assigned.get_id(),
1366- )
1367- .await
1368- .unwrap();
1365+ let course =
1366+ service::course::assign_teacher(&db, &course(&creator, &db).await, assigned.get_id())
1367+ .await
1368+ .unwrap();
13691369 // Still teacher+: untouched by the floor.
13701370 assert!(can_manage_course(&course, &assigned));
13711371 // ...but never an owner, assigned or not.
src/web/exam_ws.rsmodified+9 -6
@@ -144,7 +144,7 @@ pub async fn attempt_ws(
144144 Path(id): Path<String>,
145145 ws: WebSocketUpgrade,
146146 ) -> Result<Response, AppError> {
147- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
147+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
148148 .await?
149149 .ok_or(AppError::NotFound)?;
150150 ensure_sittable(&exam)?;
@@ -233,7 +233,7 @@ async fn room(
233233 /// wins. Targeting the sitting by id (never "the latest") means a retake
234234 /// started elsewhere can't be marked as left by an old room's teardown.
235235 async fn stamp_left(exam_id: &ExamId, attempt_id: &ExamAttemptId, db: &Database) {
236- let attempt = match Exam::read(exam_id, db).await {
236+ let attempt = match crate::service::exam::read(db, exam_id).await {
237237 Ok(Some(exam)) => match read(db, attempt_id).await {
238238 Ok(Some(attempt))
239239 if attempt.status(&exam, Timestamp::now()) == AttemptStatus::InProgress =>
@@ -328,7 +328,9 @@ async fn state_frame(
328328 attempt: &ExamAttemptId,
329329 db: &Database,
330330 ) -> Result<(Value, AttemptStatus, Option<i64>), AppError> {
331- let exam = Exam::read(exam, db).await?.ok_or(AppError::NotFound)?;
331+ let exam = crate::service::exam::read(db, exam)
332+ .await?
333+ .ok_or(AppError::NotFound)?;
332334 let attempt = read(db, attempt).await?.ok_or(AppError::NotFound)?;
333335 let now = Timestamp::now();
334336 let status = attempt.status(&exam, now);
@@ -411,7 +413,7 @@ async fn handle_message(
411413 // a failure possibly be about this one question rather than about
412414 // the room. See [`error_frame_for`].
413415 let mut in_save = false;
414- let saved = match Exam::read(exam_id, db).await {
416+ let saved = match crate::service::exam::read(db, exam_id).await {
415417 Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await {
416418 Ok(attempt) => {
417419 in_save = true;
@@ -453,7 +455,7 @@ async fn handle_message(
453455 ClientMessage::Finish => {
454456 // Submit the room's own sitting — a stale room must not submit a
455457 // retake it never hosted.
456- let finished = match Exam::read(exam_id, db).await {
458+ let finished = match crate::service::exam::read(db, exam_id).await {
457459 Ok(Some(exam)) => {
458460 // Its own archived-term gate: `finish` is the one
459461 // sitting-side write that does not go through
@@ -461,7 +463,8 @@ async fn handle_message(
461463 // same error frame as every other conflict.
462464 async {
463465 let attempt = writable_room_attempt(&exam, attempt_id, user, db).await?;
464- crate::service::course::require_open(db, &course_of(&exam, db).await?).await?;
466+ crate::service::course::require_open(db, &course_of(&exam, db).await?)
467+ .await?;
465468 finish(db, attempt).await
466469 }
467470 .await
src/web/exams/attempts.rsmodified+6 -6
@@ -189,7 +189,7 @@ pub(crate) async fn my_attempt(
189189 CurrentUser(user): CurrentUser,
190190 Path(id): Path<String>,
191191 ) -> Result<Json<AttemptResponse>, AppError> {
192- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
192+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
193193 .await?
194194 .ok_or(AppError::NotFound)?;
195195 let attempt = exam_attempt::read_latest_for_user(&st.db, exam.get_id(), user.get_id())
@@ -235,7 +235,7 @@ pub(crate) async fn finish_attempt(
235235 CurrentUser(user): CurrentUser,
236236 Path(id): Path<String>,
237237 ) -> Result<Json<AttemptResponse>, AppError> {
238- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
238+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
239239 .await?
240240 .ok_or(AppError::NotFound)?;
241241 let finished = exam_attempt::finish_attempt(&st.db, &exam, user.get_id()).await?;
@@ -457,7 +457,7 @@ pub(crate) async fn exam_live(
457457 RequireTeacher(user): RequireTeacher,
458458 Path(id): Path<String>,
459459 ) -> Result<Json<ExamLiveResponse>, AppError> {
460- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
460+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
461461 .await?
462462 .ok_or(AppError::NotFound)?;
463463 let course = exam_attempt::course_of(&exam, &st.db).await?;
@@ -571,7 +571,7 @@ pub(crate) async fn attempt_questions(
571571 CurrentUser(user): CurrentUser,
572572 Path(id): Path<String>,
573573 ) -> Result<Json<Vec<AttemptQuestionResponse>>, AppError> {
574- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
574+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
575575 .await?
576576 .ok_or(AppError::NotFound)?;
577577 exam_attempt::ensure_enrolled(&exam, user.get_id(), &st.db).await?;
@@ -657,7 +657,7 @@ pub(crate) async fn save_answer(
657657 Path(id): Path<String>,
658658 Json(req): Json<SaveAnswer>,
659659 ) -> Result<Json<AnswerSavedResponse>, AppError> {
660- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
660+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
661661 .await?
662662 .ok_or(AppError::NotFound)?;
663663 let answer = exam_attempt::save_answer_checked(
@@ -705,7 +705,7 @@ pub(crate) async fn attempt_answers(
705705 RequireTeacher(user): RequireTeacher,
706706 Path((id, target)): Path<(String, String)>,
707707 ) -> Result<Json<AttemptAnswersResponse>, AppError> {
708- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
708+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
709709 .await?
710710 .ok_or(AppError::NotFound)?;
711711 let course = exam_attempt::course_of(&exam, &st.db).await?;
src/web/exams/images.rsmodified+7 -7
@@ -95,7 +95,7 @@ pub(crate) async fn image_managed_exam(
9595 user: &User,
9696 id: &str,
9797 ) -> Result<Exam, AppError> {
98- let exam = Exam::read(&ExamId::from_key(id), &st.db)
98+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(id))
9999 .await?
100100 .ok_or(AppError::NotFound)?;
101101 let course = course_of(&exam, &st.db).await?;
@@ -231,7 +231,7 @@ pub(crate) async fn get_question_image(
231231 CurrentUser(user): CurrentUser,
232232 Path((id, qid)): Path<(String, String)>,
233233 ) -> Result<Response, AppError> {
234- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
234+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
235235 .await?
236236 .ok_or(AppError::NotFound)?;
237237 ensure_question_content_visible(&st, &exam, &user).await?;
@@ -343,7 +343,7 @@ pub(crate) async fn get_choice_image(
343343 CurrentUser(user): CurrentUser,
344344 Path((id, qid, choice_id)): Path<(String, String, String)>,
345345 ) -> Result<Response, AppError> {
346- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
346+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
347347 .await?
348348 .ok_or(AppError::NotFound)?;
349349 ensure_question_content_visible(&st, &exam, &user).await?;
@@ -459,7 +459,7 @@ pub(crate) async fn upload_answer_image(
459459 Path((id, qid)): Path<(String, String)>,
460460 mut multipart: Multipart,
461461 ) -> Result<(StatusCode, Json<ImageMetaResponse>), AppError> {
462- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
462+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
463463 .await?
464464 .ok_or(AppError::NotFound)?;
465465 ensure_student(&user)?;
@@ -541,7 +541,7 @@ pub(crate) async fn delete_answer_image(
541541 CurrentUser(user): CurrentUser,
542542 Path((id, qid)): Path<(String, String)>,
543543 ) -> Result<StatusCode, AppError> {
544- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
544+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
545545 .await?
546546 .ok_or(AppError::NotFound)?;
547547 ensure_student(&user)?;
@@ -594,7 +594,7 @@ pub(crate) async fn get_answer_image(
594594 CurrentUser(user): CurrentUser,
595595 Path((id, qid)): Path<(String, String)>,
596596 ) -> Result<Response, AppError> {
597- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
597+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
598598 .await?
599599 .ok_or(AppError::NotFound)?;
600600 ensure_question_content_visible(&st, &exam, &user).await?;
@@ -634,7 +634,7 @@ pub(crate) async fn get_student_answer_image(
634634 RequireTeacher(user): RequireTeacher,
635635 Path((id, target, qid)): Path<(String, String, String)>,
636636 ) -> Result<Response, AppError> {
637- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
637+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
638638 .await?
639639 .ok_or(AppError::NotFound)?;
640640 let course = course_of(&exam, &st.db).await?;
src/web/exams/mod.rsmodified+92 -189
@@ -10,7 +10,7 @@ use utoipa::ToSchema;
1010 use utoipa_axum::router::OpenApiRouter;
1111 use utoipa_axum::routes;
1212
13-use crate::constant::{CAS_UPDATE_RETRIES, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
13+use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
1414 use crate::database::Database;
1515 use crate::domain::answer_image::AnswerImage;
1616 use crate::domain::badge;
@@ -18,8 +18,7 @@ use crate::domain::bank_question::{BankQuestion, BankQuestionId};
1818 use crate::domain::bank_question_image::BankQuestionImage;
1919 use crate::domain::enrollment::Enrollment;
2020 use crate::domain::exam::{
21- Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,
22- ExamSchedule, ExamTitle,
21+ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, ExamTitle,
2322 };
2423 use crate::domain::exam_answer::{ExamAnswer, auto_score};
2524 use crate::domain::exam_question::{
@@ -33,7 +32,7 @@ use crate::domain::timestamp::Timestamp;
3332 use crate::domain::user::{User, UserId};
3433 use crate::error::{AppError, ErrorResponse, ValidationError};
3534 use crate::service;
36-use crate::service::exam_attempt::{EXAM_LOCK, any_for_exam, course_of, read_latest_for_user};
35+use crate::service::exam_attempt::{EXAM_LOCK, course_of, read_latest_for_user};
3736 use crate::state::AppState;
3837
3938 use super::bank_questions::BankQuestionResponse;
@@ -267,7 +266,7 @@ async fn list_exams(
267266 ) -> Result<Json<Page<ExamResponse>>, AppError> {
268267 let (limit, offset) = page.resolve()?;
269268 let exams = if user.get_role().at_least(Role::Manager) {
270- Exam::list_all(&st.db).await?
269+ service::exam::list_all(&st.db).await?
271270 } else {
272271 let courses = visible_courses(&user, &st.db).await?;
273272 let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect();
@@ -278,7 +277,7 @@ async fn list_exams(
278277 .filter(|c| can_manage_course(c, &user))
279278 .map(|c| c.get_id().key())
280279 .collect();
281- let mut exams = Exam::list_for_courses(&ids, &st.db).await?;
280+ let mut exams = service::exam::list_for_courses(&st.db, &ids).await?;
282281 exams.retain(|exam| !exam.is_draft() || managed.contains(&exam.get_course().key()));
283282 exams
284283 };
@@ -321,7 +320,7 @@ async fn get_exam(
321320 CurrentUser(user): CurrentUser,
322321 Path(id): Path<String>,
323322 ) -> Result<Json<ExamResponse>, AppError> {
324- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
323+ let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
325324 .await?
326325 .ok_or(AppError::NotFound)?;
327326 let course = course_of(&exam, &st.db).await?;
@@ -371,153 +370,82 @@ async fn update_exam(
371370 Path(id): Path<String>,
372371 Json(req): Json<UpdateExam>,
373372 ) -> Result<Json<ExamResponse>, AppError> {
374- // *Reader* lease of [`EXAM_LOCK`] for exactly one pairing: the mode gate
375- // below reads `exam_attempt`, and an attempt start takes the *writer*
376- // lease, so a first sitting still cannot land between that gate and the
377- // write, as it always did.
378- //
379- // It buys nothing against grading, which is a reader too: the re-draft gate
380- // is therefore enforced inside the update's own transaction
381- // (`Exam::update_if_unchanged`), where the store decides it. The gate
382- // below stays as the pre-flight — same error, one round trip earlier.
383- // Concurrent PATCHes of this exam no longer queue behind each other either:
384- // the lost update they used to cause is refused by the compare-and-set.
385- let _guard = EXAM_LOCK.read().await;
386- let mut left = CAS_UPDATE_RETRIES;
387- let exam = loop {
388- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
389- .await?
390- .ok_or(AppError::NotFound)?;
391- let course = course_of(&exam, &st.db).await?;
392- if !can_manage_course(&course, &user) {
393- return Err(AppError::Forbidden(
394- "only the course creator, an assigned teacher, or a manager/admin can edit this exam",
395- ));
396- }
397- crate::service::course::require_open(&st.db, &course).await?;
398-
399- let title = match req.title {
400- Some(ref title) => ExamTitle::try_new(title)?,
401- None => exam.get_title().clone(),
402- };
403- let description = match req.description {
404- Some(ref description) => ExamDescription::try_new(description)?,
405- None => exam.get_description().clone(),
406- };
407- let kind = match req.kind {
408- // Only a kind this request sets is held to the current settings list —
409- // a stored kind survives later list edits, like past times survive
410- // the no-past rule.
411- Some(ref kind) => {
412- let school = service::settings::load(&st.db).await?;
413- ExamKind::try_new(kind, school.get_exam_kinds())?
414- }
415- None => exam.get_kind().clone(),
416- };
417-
418- // Merge the schedule (set / clear / keep per field), then re-validate it
419- // as a unit — a PATCH can't leave a half-schedule behind. Only values this
420- // request sets are held to the no-past rule: kept ones may legitimately be
421- // past (a running exam's `starts_at`), and rechecking them would block
422- // unrelated edits.
423- let mode = match req.mode {
424- Some(ref update) => update.as_deref().map(ExamMode::try_new).transpose()?,
425- None => exam.get_mode().cloned(),
426- };
427- let starts_at = match req.starts_at {
428- Some(update) => {
429- let starts_at = update.map(Timestamp::from_millis);
430- check_not_past("starts_at", starts_at)?;
431- starts_at
432- }
433- None => exam.get_starts_at(),
434- };
435- let ends_at = match req.ends_at {
436- Some(update) => {
437- let ends_at = update.map(Timestamp::from_millis);
438- check_not_past("ends_at", ends_at)?;
439- ends_at
440- }
441- None => exam.get_ends_at(),
442- };
443- let duration_ms = match req.duration_ms {
444- Some(update) => update.map(ExamDuration::try_new).transpose()?,
445- None => exam.get_duration_ms(),
446- };
447- let schedule = ExamSchedule::try_new(mode, starts_at, ends_at, duration_ms)?;
448- let max_attempts = match req.max_attempts {
449- Some(limit) => ExamAttemptLimit::try_new(limit)?,
450- None => exam.get_max_attempts(),
451- };
452- let allow_rejoin = req.allow_rejoin.unwrap_or_else(|| exam.get_allow_rejoin());
453- let allow_review = req.allow_review.unwrap_or_else(|| exam.get_allow_review());
454- let draft = req.draft.unwrap_or_else(|| exam.is_draft());
455-
456- // Switching sync <-> async <-> open (or back to unscheduled) would
457- // silently rewrite the deadline rules under students who already sat
458- // down; extending times, the attempt limit, and the rejoin door are the
459- // supported live adjustments instead. Gate read and write share the
460- // handler-wide writer lease of [`EXAM_LOCK`], so a first attempt can't
461- // land in the gap and leave a sat exam's mode flipped under it.
462- let mode_changed =
463- schedule.get_mode().map(ExamMode::as_str) != exam.get_mode().map(ExamMode::as_str);
464- if mode_changed && any_for_exam(&st.db, exam.get_id()).await? {
465- return Err(AppError::Conflict(
466- "cannot change the exam mode after attempts have started",
467- ));
468- }
469- // Re-drafting hides the exam — never out from under a student who
470- // already sat it or holds a mark on it. Pre-flight only: the write's own
471- // transaction re-makes this check and answers with the same error, so a
472- // grade landing after this read still cannot leave a mark on a draft.
473- if draft && !exam.is_draft() {
474- let sat = any_for_exam(&st.db, exam.get_id()).await?;
475- let graded = !ExamResult::list_for_exam(exam.get_id(), &st.db)
476- .await?
477- .is_empty();
478- if sat || graded {
479- return Err(crate::domain::exam::redraft_error());
480- }
481- }
482-
483- // A graded exam keeps its kind. Moving it re-weights every mark it
484- // already carries — the same silent re-weighting the settings' removal
485- // guard refuses — and it would strand those marks' references on the
486- // kind they were counted under, freeing the kind the exam now claims to
487- // be. Marks are counted on the exam row, and the save below *pins* that
488- // counter, so a grade landing between this read and the write refuses
489- // the save (the loop then re-reads and answers the 409 below).
490- if kind.as_str() != exam.get_kind().as_str() && exam.get_result_count() > 0 {
491- return Err(AppError::Conflict(
492- "cannot change the kind of an exam that already has marks",
493- ));
494- }
373+ let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
374+ .await?
375+ .ok_or(AppError::NotFound)?;
376+ let course = course_of(&exam, &st.db).await?;
377+ if !can_manage_course(&course, &user) {
378+ return Err(AppError::Forbidden(
379+ "only the course creator, an assigned teacher, or a manager/admin can edit this exam",
380+ ));
381+ }
382+ crate::service::course::require_open(&st.db, &course).await?;
495383
496- if let Some(updated) = exam
497- .update_if_unchanged(
498- title,
499- description,
500- kind,
501- schedule,
502- max_attempts,
503- allow_rejoin,
504- allow_review,
505- draft,
506- &st.db,
507- )
508- .await?
509- {
510- break updated;
384+ // Field validation, in the order the request is judged — only values this
385+ // request sets are held to the rules (a stored kind survives list edits,
386+ // kept times may legitimately be past). The merge against the stored row,
387+ // the schedule re-validation as a unit, and the mode-freeze / re-draft /
388+ // kind gates are the workflow's own steps:
389+ // [`crate::service::exam::update`] re-derives them per retry round behind
390+ // the compare-and-set.
391+ let title = req.title.as_deref().map(ExamTitle::try_new).transpose()?;
392+ let description = req
393+ .description
394+ .as_deref()
395+ .map(ExamDescription::try_new)
396+ .transpose()?;
397+ let kind = match &req.kind {
398+ // Only a kind this request sets is held to the current settings list —
399+ // a stored kind survives later list edits, like past times survive
400+ // the no-past rule.
401+ Some(kind) => Some(ExamKind::try_new(
402+ kind,
403+ service::settings::load(&st.db).await?.get_exam_kinds(),
404+ )?),
405+ None => None,
406+ };
407+ let mode = match &req.mode {
408+ Some(update) => Some(update.as_deref().map(ExamMode::try_new).transpose()?),
409+ None => None,
410+ };
411+ let starts_at = match req.starts_at {
412+ Some(update) => {
413+ let starts_at = update.map(Timestamp::from_millis);
414+ check_not_past("starts_at", starts_at)?;
415+ Some(starts_at)
511416 }
512- // The row moved under the snapshot every gate above judged: re-read and
513- // re-merge, so both edits land instead of the later reverting the earlier.
514- left -= 1;
515- if left == 0 {
516- return Err(AppError::Conflict(
517- "the exam kept changing underneath this update — try again",
518- ));
417+ None => None,
418+ };
419+ let ends_at = match req.ends_at {
420+ Some(update) => {
421+ let ends_at = update.map(Timestamp::from_millis);
422+ check_not_past("ends_at", ends_at)?;
423+ Some(ends_at)
519424 }
425+ None => None,
426+ };
427+ let duration_ms = match req.duration_ms {
428+ Some(update) => Some(update.map(ExamDuration::try_new).transpose()?),
429+ None => None,
520430 };
431+ let max_attempts = req
432+ .max_attempts
433+ .map(ExamAttemptLimit::try_new)
434+ .transpose()?;
435+ let patch = service::exam::ExamPatch {
436+ title,
437+ description,
438+ kind,
439+ mode,
440+ starts_at,
441+ ends_at,
442+ duration_ms,
443+ max_attempts,
444+ allow_rejoin: req.allow_rejoin,
445+ allow_review: req.allow_review,
446+ draft: req.draft,
447+ };
448+ let exam = service::exam::update(&st.db, exam.get_id(), &patch).await?;
521449 Ok(Json(ExamResponse::new(&exam)))
522450 }
523451
@@ -543,7 +471,7 @@ async fn delete_exam(
543471 RequireTeacher(user): RequireTeacher,
544472 Path(id): Path<String>,
545473 ) -> Result<StatusCode, AppError> {
546- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
474+ let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
547475 .await?
548476 .ok_or(AppError::NotFound)?;
549477 let course = course_of(&exam, &st.db).await?;
@@ -552,41 +480,16 @@ async fn delete_exam(
552480 "only the course creator, an assigned teacher, or a manager/admin can delete this exam",
553481 ));
554482 }
555- crate::service::course::require_open(&st.db, &course).await?;
556- // *Writer* lease of [`EXAM_LOCK`] across the whole cascade, blob names
557- // included — the lease `delete_homework` has always held, and its absence
558- // here is what made a sitting able to start inside this delete. Every other
559- // child of an exam now writes the exam row in its own transaction, so the
560- // store refuses the pair; an attempt cannot, because its claim lands on the
561- // *student's* row (`exam_sat_total`) and touches nothing this delete
562- // writes. `start_attempt` already takes the writer lease from its exam read
563- // through the insert, so this one lease is the whole ordering: a start
564- // either finishes before the sweep (which then takes its row) or reads no
565- // exam at all and is a 404. Left orphaned, that attempt kept a sitting on
566- // the student's lifetime counter and could mint a badge — awards are
567- // add-only and never revoked — for an exam that never existed.
568- //
569- // It spans the blob names too: they are collected *before* the rows go, so
570- // an image row written after that snapshot would strand its bytes on disk
571- // even though the row itself is now refused.
572- //
573- // corner-cut: process-local, so it holds because the deployment runs one
574- // process by contract with stop-the-world deploys (two overlapping
575- // binaries would
576- // reopen it). Closing it in the store means the `cap` shape the counter
577- // work already sketched: `claim_and_create` gaining a second record to
578- // touch, so the attempt writes the exam key as every other child does.
579- let _guard = EXAM_LOCK.write().await;
580- // Rows go first (the delete cascades them), blobs after — a crash in
581- // between strands at worst an unreachable blob.
582- let images = QuestionImage::list_for_exam(exam.get_id(), &st.db).await?;
583- let answer_images = AnswerImage::list_for_exam(exam.get_id(), &st.db).await?;
584- exam.delete(&st.db).await?;
585- for image in &images {
586- remove_blob(&st.files_path, image.get_file()).await;
483+ // The workflow — the archived-term gate, the *writer* lease of
484+ // [`EXAM_LOCK`] across the cascade, blob-key collection, the delete — is
485+ // [`crate::service::exam::delete`]'s. Blob unlinking stays here because
486+ // only the web layer knows `files_path`.
487+ let outcome = service::exam::delete(&st.db, &exam).await?;
488+ for file in &outcome.image_files {
489+ remove_blob(&st.files_path, file).await;
587490 }
588- for image in &answer_images {
589- remove_blob(&st.files_path, image.get_file()).await;
491+ for file in &outcome.answer_image_files {
492+ remove_blob(&st.files_path, file).await;
590493 }
591494 Ok(StatusCode::NO_CONTENT)
592495 }
@@ -628,7 +531,7 @@ async fn grade(
628531 // results) could slip between them and leave a mark on a hidden exam.
629532 let _guard = EXAM_LOCK.read().await;
630533 // Exam must exist.
631- let exam = Exam::read(&exam_id, &st.db)
534+ let exam = service::exam::read(&st.db, &exam_id)
632535 .await?
633536 .ok_or(AppError::NotFound)?;
634537 let course = course_of(&exam, &st.db).await?;
@@ -753,7 +656,7 @@ async fn list_results(
753656 ) -> Result<Json<Page<ExamResultResponse>>, AppError> {
754657 let (limit, offset) = page.resolve()?;
755658 // Exam must exist — a missing exam is a 404, not an empty result list.
756- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
659+ let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
757660 .await?
758661 .ok_or(AppError::NotFound)?;
759662 let course = course_of(&exam, &st.db).await?;
@@ -835,7 +738,7 @@ async fn remove_result(
835738 RequireTeacher(user): RequireTeacher,
836739 Path((id, target)): Path<(String, String)>,
837740 ) -> Result<StatusCode, AppError> {
838- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
741+ let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
839742 .await?
840743 .ok_or(AppError::NotFound)?;
841744 let course = course_of(&exam, &st.db).await?;
@@ -879,7 +782,7 @@ async fn exam_statistics(
879782 Path(id): Path<String>,
880783 ) -> Result<Json<ExamStatisticsResponse>, AppError> {
881784 // Exam must exist — a missing exam is a 404, not an empty statistic.
882- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
785+ let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
883786 .await?
884787 .ok_or(AppError::NotFound)?;
885788 let course = course_of(&exam, &st.db).await?;
src/web/exams/questions.rsmodified+7 -7
@@ -197,7 +197,7 @@ pub(crate) async fn create_question(
197197 Path(id): Path<String>,
198198 Json(req): Json<CreateQuestion>,
199199 ) -> Result<(StatusCode, Json<QuestionResponse>), AppError> {
200- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
200+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
201201 .await?
202202 .ok_or(AppError::NotFound)?;
203203 let course = course_of(&exam, &st.db).await?;
@@ -258,7 +258,7 @@ pub(crate) async fn list_questions(
258258 Query(page): Query<PageParams>,
259259 ) -> Result<Json<Page<QuestionResponse>>, AppError> {
260260 let (limit, offset) = page.resolve()?;
261- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
261+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
262262 .await?
263263 .ok_or(AppError::NotFound)?;
264264 let course = course_of(&exam, &st.db).await?;
@@ -336,7 +336,7 @@ pub(crate) async fn update_question(
336336 Path((id, qid)): Path<(String, String)>,
337337 Json(req): Json<UpdateQuestion>,
338338 ) -> Result<Json<QuestionResponse>, AppError> {
339- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
339+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
340340 .await?
341341 .ok_or(AppError::NotFound)?;
342342 let course = course_of(&exam, &st.db).await?;
@@ -424,7 +424,7 @@ pub(crate) async fn delete_question(
424424 RequireTeacher(user): RequireTeacher,
425425 Path((id, qid)): Path<(String, String)>,
426426 ) -> Result<StatusCode, AppError> {
427- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
427+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
428428 .await?
429429 .ok_or(AppError::NotFound)?;
430430 let course = course_of(&exam, &st.db).await?;
@@ -496,7 +496,7 @@ pub(crate) async fn question_from_bank(
496496 Path((id, bid)): Path<(String, String)>,
497497 Json(req): Json<InstantiateFromBank>,
498498 ) -> Result<(StatusCode, Json<QuestionResponse>), AppError> {
499- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
499+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
500500 .await?
501501 .ok_or(AppError::NotFound)?;
502502 let course = course_of(&exam, &st.db).await?;
@@ -627,7 +627,7 @@ pub(crate) async fn question_refresh_from_bank(
627627 RequireTeacher(user): RequireTeacher,
628628 Path((id, qid)): Path<(String, String)>,
629629 ) -> Result<Json<QuestionResponse>, AppError> {
630- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
630+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
631631 .await?
632632 .ok_or(AppError::NotFound)?;
633633 let course = course_of(&exam, &st.db).await?;
@@ -752,7 +752,7 @@ pub(crate) async fn question_to_bank(
752752 RequireTeacher(user): RequireTeacher,
753753 Path((id, qid)): Path<(String, String)>,
754754 ) -> Result<(StatusCode, Json<BankQuestionResponse>), AppError> {
755- let exam = Exam::read(&ExamId::from_key(&id), &st.db)
755+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
756756 .await?
757757 .ok_or(AppError::NotFound)?;
758758 let course = course_of(&exam, &st.db).await?;
src/web/exams/review.rsmodified+3 -3
@@ -13,7 +13,7 @@ use crate::service::exam_attempt::{
1313
1414 /// The exam plus the manage-rights check the grading and history reads share.
1515 pub(crate) async fn gradable_exam(st: &AppState, user: &User, id: &str) -> Result<Exam, AppError> {
16- let exam = Exam::read(&ExamId::from_key(id), &st.db)
16+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(id))
1717 .await?
1818 .ok_or(AppError::NotFound)?;
1919 let course = course_of(&exam, &st.db).await?;
@@ -203,7 +203,7 @@ pub(crate) async fn reviewable_exam(
203203 user: &User,
204204 id: &str,
205205 ) -> Result<Exam, AppError> {
206- let exam = Exam::read(&ExamId::from_key(id), &st.db)
206+ let exam = crate::service::exam::read(&st.db, &ExamId::from_key(id))
207207 .await?
208208 .ok_or(AppError::NotFound)?;
209209 if exam.is_draft() {
@@ -268,7 +268,7 @@ async fn live_elsewhere(
268268 let now = Timestamp::now();
269269 let mut live = Vec::new();
270270 for attempt in list_unfinished_for_user(&st.db, user.get_id()).await? {
271- let Some(other) = Exam::read(attempt.get_exam(), &st.db).await? else {
271+ let Some(other) = crate::service::exam::read(&st.db, attempt.get_exam()).await? else {
272272 continue;
273273 };
274274 if attempt.status(&other, now) == AttemptStatus::InProgress {
src/web/marks.rsmodified+1 -1
@@ -107,7 +107,7 @@ async fn build_report(
107107
108108 let mut blocks = Vec::with_capacity(courses.len());
109109 for course in &courses {
110- let exams = Exam::list_for_course(course.get_id(), db).await?;
110+ let exams = crate::service::exam::list_for_course(db, course.get_id()).await?;
111111 let by_key: HashMap<&str, &Exam> = exams.iter().map(|e| (e.get_id().key(), e)).collect();
112112
113113 let results = ExamResult::list_for_user_in_course(course.get_id(), user, db).await?;
tests/regress_course_child_orphans.rsmodified+7 -13
@@ -31,7 +31,7 @@
3131 //!
3232 //! The **race** half drives the real interleaving and lives in-crate, one pin
3333 //! per child beside the create it pins —
34-//! `domain::exam::tests::an_exam_never_outlives_its_course`,
34+//! `db::exam::tests::an_exam_never_outlives_its_course`,
3535 //! `domain::course_session::tests::a_session_never_outlives_its_course`,
3636 //! `domain::subject::tests::a_subject_never_outlives_its_course` — over the
3737 //! shared harness `domain::course::assert_no_child_outlives_a_course_delete`.
@@ -54,7 +54,7 @@ use hezarfen_backend::domain::course_note::{CourseNote, CourseNoteContent, Cours
5454 use hezarfen_backend::domain::course_note_file::{CourseNoteFile, FileContentType, FileName};
5555 use hezarfen_backend::domain::course_session::{CourseSession, SessionTopic};
5656 use hezarfen_backend::domain::exam::{
57- Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,
57+ ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,
5858 };
5959 use hezarfen_backend::domain::settings::Settings;
6060 use hezarfen_backend::domain::subject::{Subject, SubjectDescription, SubjectName};
@@ -102,7 +102,8 @@ async fn drop_course(course: &CourseId, db: &Database) -> Result<bool, AppError>
102102 fn make_exam(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> {
103103 tokio::spawn(async move {
104104 let kinds = Settings::defaults().get_exam_kinds().to_vec();
105- Exam::create(
105+ hezarfen_backend::db::exam::create(
106+ &db,
106107 &teacher(),
107108 &course,
108109 ExamTitle::try_new("quiz").unwrap(),
@@ -113,7 +114,6 @@ fn make_exam(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>>
113114 true,
114115 false,
115116 false,
116- &db,
117117 )
118118 .await
119119 .map(|_| ())
@@ -325,15 +325,9 @@ async fn a_course_note_file_under_a_deleted_note_is_refused() {
325325 .await
326326 .unwrap();
327327 assert!(
328- course::delete(
329- &db,
330- course::read(&db, &course)
331- .await
332- .unwrap()
333- .unwrap()
334- )
335- .await
336- .unwrap(),
328+ course::delete(&db, course::read(&db, &course).await.unwrap().unwrap())
329+ .await
330+ .unwrap(),
337331 "the course, and its note with it, goes"
338332 );
339333