forge
Explore
Log in

Don't you dare go Hollow

Stop a course's children outliving the course

Browse files at this commit

02513644d60b92877cb0356d23bc8b4b6fc09c2bAhmet Kaan GümüşParent: 558c39a
  • fix
    • stop a course's children outliving the course
Show full message
🔗 fix: stop a course's children outliving the course

Exam, CourseSession and Subject creates were bare db.create calls that
wrote no key the delete cascade writes, so a create racing
DELETE /courses/{id} committed alongside it. The orphans were not merely
stray: every exam route funnels through course_of, which answered 500
forever, so the row was undeletable while still listed to manager+.
Sessions and subjects 404'd the same way.

All three now ride cap::touch_and_create against the course row.

Course::delete also skipped the two bank_question cleanups its per-entity
siblings perform, leaving source_exam and subject pointing at deleted
records — contradicting the documented "null once that subject was
deleted".

Real-server measurement: 4/4 rounds orphaned before, 0/4 after.
src/domain/course.rsmodified+134 -0
@@ -400,6 +400,17 @@ impl Course {
400 /// homework-file *blobs* are the web layer's to remove — it collects400 /// homework-file *blobs* are the web layer's to remove — it collects
401 /// their names before calling this.401 /// their names before calling this.
402 ///402 ///
403+ /// **Bank templates** survive it — they are a separate, reusable library
404+ /// spanning every course — so their `source_exam` and `subject` links are
405+ /// cleared instead, in this same transaction, exactly as
406+ /// [`crate::domain::exam::Exam::delete`] and
407+ /// [`crate::domain::subject::Subject::delete`] clear them one level down.
408+ /// Deleting a course must leave the bank where deleting each of its exams
409+ /// and subjects by hand would have left it, or a template is left pointing
410+ /// at a dead exam (permanently: nothing else ever visits that column) and
411+ /// at a dead subject the next `PATCH` omitting `subject_id` writes straight
412+ /// back.
413+ ///
403 /// The **grade blueprints** naming it are swept in that same transaction.414 /// The **grade blueprints** naming it are swept in that same transaction.
404 /// Nothing else can reach them — a blueprint holds its courses as a list on415 /// Nothing else can reach them — a blueprint holds its courses as a list on
405 /// its own row, not as link rows this cascade could delete — and an id left416 /// its own row, not as link rows this cascade could delete — and an id left
@@ -461,8 +472,12 @@ impl Course {
461 DELETE session_attendance WHERE course = $course;472 DELETE session_attendance WHERE course = $course;
462 DELETE course_session WHERE course = $course;473 DELETE course_session WHERE course = $course;
463 DELETE enrollment WHERE course = $course;474 DELETE enrollment WHERE course = $course;
475+ UPDATE bank_question SET subject = NONE
476+ WHERE subject IN (SELECT VALUE id FROM subject WHERE course = $course);
464 DELETE subject WHERE course = $course;477 DELETE subject WHERE course = $course;
465 DELETE homework WHERE course = $course;478 DELETE homework WHERE course = $course;
479+ UPDATE bank_question SET source_exam = NONE
480+ WHERE source_exam IN (SELECT VALUE id FROM exam WHERE course = $course);
466 DELETE exam WHERE course = $course;481 DELETE exam WHERE course = $course;
467 COMMIT TRANSACTION;"482 COMMIT TRANSACTION;"
468 );483 );
@@ -494,6 +509,125 @@ impl Course {
494 }509 }
495 }510 }
496 511
512+/// A real course row, for the tests of every child that must now prove its
513+/// parent exists (`Exam`, `CourseSession`, `Subject` — see
514+/// [`cap::touch_and_create`]). A minted id nothing wrote is a 404 there, the
515+/// way a minted subject id already is for an exam question.
516+#[cfg(test)]
517+pub(crate) async fn a_test_course(db: &Database) -> CourseId {
518+ Course::create(
519+ &UserId::generate(),
520+ CourseTitle::try_new("test course").unwrap(),
521+ CourseDescription::try_new("").unwrap(),
522+ CourseKind::course(),
523+ None,
524+ None,
525+ db,
526+ )
527+ .await
528+ .unwrap()
529+ .id
530+}
531+
532+/// The race half of "a child of a course must not survive its deletion", run
533+/// for one child table: [`Course::delete`] is held open by the schema and
534+/// `make` fires its create inside that window, four rounds.
535+///
536+/// The harness lives here, beside the cascade being raced, and each child names
537+/// its own pin in its own module (`exam`, `course_session`, `subject`) — the
538+/// loop, the window and the verdict are one fact about *this* delete, and three
539+/// copies of it would drift into three different tests of three different
540+/// things. The sequential half — a create against a course that is already gone
541+/// — is `tests/regress_course_child_orphans.rs`, which needs no server.
542+///
543+/// The window is opened by the database rather than by a lucky interleaving: a
544+/// `DEFINE EVENT` on `course` fires *inside* the delete's own transaction the
545+/// instant the row goes, so the `SLEEP` lands between the delete and its
546+/// `DELETE <child> WHERE course = $course` sweep every time — and a create
547+/// fired into it reads a course that is still there (removed, uncommitted)
548+/// while the sweep already ran on a snapshot without its row.
549+///
550+/// One child per round, for the reason the menu and `class_course` twins
551+/// document: a second writer makes the delete lose and re-send, and the re-sent
552+/// sweep clears the evidence.
553+///
554+/// Real server, and every caller is `#[ignore]`d for it: the subject *is* the
555+/// store's conflict detection, which `init_mem`'s embedded engine does not
556+/// have — it commits both sides and answers `Ok` to each, so this passes there
557+/// on broken code.
558+#[cfg(test)]
559+pub(crate) async fn assert_no_child_outlives_a_course_delete(
560+ scratch: &str,
561+ table: &str,
562+ make: fn(CourseId, Database) -> tokio::task::JoinHandle<Result<(), AppError>>,
563+) {
564+ // The guard is held for the whole test: these bursts are sub-millisecond,
565+ // and a sibling race test's burst pushes a delete clean out of its window.
566+ let (db, _serialized) = crate::database::init_test_server(scratch).await;
567+ db.query(
568+ "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \
569+ THEN { SLEEP 1s; };",
570+ )
571+ .await
572+ .expect("define the window event")
573+ .check()
574+ .expect("check the window event");
575+
576+ let (mut swept, mut orphans) = (0, 0);
577+ for round in 0..4 {
578+ let course = a_test_course(&db).await;
579+ let drop_it = {
580+ let (course, db) = (course.clone(), db.clone());
581+ tokio::spawn(async move {
582+ Course::read(&course, &db)
583+ .await
584+ .unwrap()
585+ .expect("the course is there")
586+ .delete(&db)
587+ .await
588+ })
589+ };
590+ // The create starts inside the held window.
591+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
592+ let child = make(course.clone(), db.clone()).await.unwrap();
593+ let dropped = drop_it.await.unwrap();
594+
595+ // A 404 for the create, or a refusal for the delete, is a correct
596+ // answer — the only defect is stored state. Nothing may 500.
597+ assert!(
598+ !matches!(child, Err(AppError::Db(_))),
599+ "{table} round {round}: a raced create must be answered, not 500: {child:?}"
600+ );
601+ assert!(
602+ !matches!(dropped, Err(AppError::Db(_))),
603+ "{table} round {round}: a raced delete must be answered, not 500: {dropped:?}"
604+ );
605+
606+ // Stored state is the whole verdict; a return value is not evidence.
607+ if Course::read(&course, &db).await.unwrap().is_none() {
608+ swept += 1;
609+ let mut left = db
610+ .query(format!(
611+ "SELECT VALUE id FROM {table} WHERE course = $course"
612+ ))
613+ .bind(("course", course.record()))
614+ .await
615+ .unwrap()
616+ .check()
617+ .unwrap();
618+ orphans += left.take::<Vec<RecordId>>(0).unwrap().len();
619+ } else if matches!(dropped, Ok(true)) {
620+ panic!("{table} round {round}: the delete reported success, the course is still there");
621+ }
622+ }
623+ eprintln!("Course::delete raced by a {table} create: {swept}/4 rounds deleted the course");
624+ assert!(
625+ swept > 0,
626+ "{table}: no round ever deleted the course, so the window was never reached"
627+ );
628+ assert_eq!(orphans, 0, "{table}: a child outlived its course");
629+}
630+
497 #[cfg(test)]631 #[cfg(test)]
498 mod tests {632 mod tests {
499 use super::*;633 use super::*;
src/domain/course_session.rsmodified+50 -4
@@ -1,7 +1,8 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3-use crate::constant::{COURSE_SESSION_TABLE, MAX_SESSION_TOPIC_LEN};3+use crate::constant::{COURSE_SESSION_TABLE, ENROLLMENT_COUNT_FIELD, MAX_SESSION_TOPIC_LEN};
4 use crate::database::{Database, transaction_with_retry};4 use crate::database::{Database, transaction_with_retry};
5+use crate::domain::cap;
5 use crate::domain::course::CourseId;6 use crate::domain::course::CourseId;
6 use crate::domain::field_update::FieldUpdate;7 use crate::domain::field_update::FieldUpdate;
7 use crate::domain::monotonic_id::next_ulid;8 use crate::domain::monotonic_id::next_ulid;
@@ -113,9 +114,19 @@ impl CourseSession {
113 starts_at,114 starts_at,
114 ends_at,115 ends_at,
115 };116 };
116- let created: Option<CourseSession> =117+ // The course row is *written* (bumped and put back), not read, so this
117- db.create(session.id.record()).content(session).await?;118+ // collides with `Course::delete`'s cascade: a lesson that outlives its
118- created.ok_or_else(|| AppError::Internal("failed to create session".into()))119+ // course 404s through `session_with_course` forever — unreadable,
120+ // unpatchable, undeletable. See [`cap::touch_and_create`].
121+ cap::touch_and_create(
122+ &course.record(),
123+ ENROLLMENT_COUNT_FIELD,
124+ &session.id.record(),
125+ &session,
126+ db,
127+ )
128+ .await?
129+ .ok_or(AppError::NotFound)
119 }130 }
120 131
121 pub async fn read(132 pub async fn read(
@@ -204,6 +215,41 @@ impl CourseSession {
204 mod tests {215 mod tests {
205 use super::*;216 use super::*;
206 217
218+ /// A lesson must not outlive the course it is a lesson of: an orphan 404s
219+ /// forever through `session_with_course` — unreadable, unpatchable,
220+ /// undeletable.
221+ ///
222+ /// [`CourseSession::create`] therefore *writes* the course row rather than
223+ /// reading it ([`cap::touch_and_create`]); the harness and the window it
224+ /// races in are documented on
225+ /// [`crate::domain::course::assert_no_child_outlives_a_course_delete`].
226+ /// Mutation-tested: with the bare `db.create` this shipped with, all four
227+ /// rounds orphan.
228+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
229+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
230+ async fn a_session_never_outlives_its_course() {
231+ fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {
232+ tokio::spawn(async move {
233+ CourseSession::create(
234+ &course,
235+ &UserId::generate(),
236+ SessionTopic::try_new("limits").unwrap(),
237+ Timestamp::from_millis(1),
238+ None,
239+ &db,
240+ )
241+ .await
242+ .map(|_| ())
243+ })
244+ }
245+ crate::domain::course::assert_no_child_outlives_a_course_delete(
246+ "session_orphan_race",
247+ COURSE_SESSION_TABLE,
248+ make,
249+ )
250+ .await;
251+ }
252+
207 #[tokio::test]253 #[tokio::test]
208 async fn topic_is_optional_but_bounded() {254 async fn topic_is_optional_but_bounded() {
209 assert!(SessionTopic::try_new("").is_ok());255 assert!(SessionTopic::try_new("").is_ok());
src/domain/exam.rsmodified+66 -6
@@ -1,9 +1,11 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3 use crate::constant::{3 use crate::constant::{
4- EXAM_TABLE, MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS,4+ ENROLLMENT_COUNT_FIELD, EXAM_TABLE, MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN,
5+ UNLIMITED_EXAM_ATTEMPTS,
5 };6 };
6 use crate::database::{Database, transaction_with_retry};7 use crate::database::{Database, transaction_with_retry};
8+use crate::domain::cap;
7 use crate::domain::course::CourseId;9 use crate::domain::course::CourseId;
8 use crate::domain::monotonic_id::next_ulid;10 use crate::domain::monotonic_id::next_ulid;
9 use crate::domain::settings::ExamKindDef;11 use crate::domain::settings::ExamKindDef;
@@ -421,8 +423,20 @@ impl Exam {
421 draft,423 draft,
422 result_count: None,424 result_count: None,
423 };425 };
424- let created: Option<Exam> = db.create(exam.id.record()).content(exam).await?;426+ // The course row is *written* (bumped and put back), not read: a plain
425- created.ok_or_else(|| AppError::Internal("failed to create exam".into()))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)
426 }440 }
427 441
428 pub async fn read(id: &ExamId, db: &Database) -> Result<Option<Exam>, AppError> {442 pub async fn read(id: &ExamId, db: &Database) -> Result<Option<Exam>, AppError> {
@@ -678,7 +692,7 @@ pub(crate) async fn published_exam(db: &Database) -> Exam {
678 .to_vec();692 .to_vec();
679 Exam::create(693 Exam::create(
680 &UserId::generate(),694 &UserId::generate(),
681- &CourseId::generate(),695+ &crate::domain::course::a_test_course(db).await,
682 ExamTitle::try_new("midterm").unwrap(),696 ExamTitle::try_new("midterm").unwrap(),
683 ExamDescription::try_new("").unwrap(),697 ExamDescription::try_new("").unwrap(),
684 ExamKind::try_new("midterm", &allowed).unwrap(),698 ExamKind::try_new("midterm", &allowed).unwrap(),
@@ -699,6 +713,52 @@ mod tests {
699 713
700 use crate::domain::exam::published_exam as published;714 use crate::domain::exam::published_exam as published;
701 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::domain::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::domain::course::assert_no_child_outlives_a_course_delete(
755+ "exam_orphan_race",
756+ EXAM_TABLE,
757+ make,
758+ )
759+ .await;
760+ }
761+
702 fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) {762 fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) {
703 (763 (
704 exam.get_title().clone(),764 exam.get_title().clone(),
@@ -1064,7 +1124,7 @@ mod tests {
1064 )1124 )
1065 .unwrap();1125 .unwrap();
1066 let subject = crate::domain::subject::Subject::create(1126 let subject = crate::domain::subject::Subject::create(
1067- &CourseId::generate(),1127+ &crate::domain::course::a_test_course(db).await,
1068 crate::domain::subject::SubjectName::try_new("topic").unwrap(),1128 crate::domain::subject::SubjectName::try_new("topic").unwrap(),
1069 crate::domain::subject::SubjectDescription::try_new("").unwrap(),1129 crate::domain::subject::SubjectDescription::try_new("").unwrap(),
1070 db,1130 db,
@@ -1208,7 +1268,7 @@ mod tests {
1208 let exam = published(&db).await;1268 let exam = published(&db).await;
1209 let id = exam.get_id().clone();1269 let id = exam.get_id().clone();
1210 let subject = Subject::create(1270 let subject = Subject::create(
1211- &CourseId::generate(),1271+ &crate::domain::course::a_test_course(&db).await,
1212 crate::domain::subject::SubjectName::try_new("topic").unwrap(),1272 crate::domain::subject::SubjectName::try_new("topic").unwrap(),
1213 crate::domain::subject::SubjectDescription::try_new("").unwrap(),1273 crate::domain::subject::SubjectDescription::try_new("").unwrap(),
1214 &db,1274 &db,
src/domain/exam_answer.rsmodified+1 -1
@@ -508,7 +508,7 @@ mod tests {
508 .to_vec();508 .to_vec();
509 let exam = Exam::create(509 let exam = Exam::create(
510 &student(),510 &student(),
511- &crate::domain::course::CourseId::generate(),511+ &crate::domain::course::a_test_course(&db).await,
512 ExamTitle::try_new("quiz").unwrap(),512 ExamTitle::try_new("quiz").unwrap(),
513 ExamDescription::try_new("").unwrap(),513 ExamDescription::try_new("").unwrap(),
514 ExamKind::try_new("quiz", &kinds).unwrap(),514 ExamKind::try_new("quiz", &kinds).unwrap(),
src/domain/exam_question.rsmodified+2 -3
@@ -1083,7 +1083,6 @@ mod tests {
1083 mod counters {1083 mod counters {
1084 use super::*;1084 use super::*;
1085 use crate::database::init_mem;1085 use crate::database::init_mem;
1086- use crate::domain::course::CourseId;
1087 use crate::domain::exam::{1086 use crate::domain::exam::{
1088 Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,1087 Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,
1089 };1088 };
@@ -1095,7 +1094,7 @@ mod tests {
1095 let kinds = Settings::defaults().get_exam_kinds().to_vec();1094 let kinds = Settings::defaults().get_exam_kinds().to_vec();
1096 Exam::create(1095 Exam::create(
1097 &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"),1096 &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"),
1098- &CourseId::from_key("01TESTCOURSEAAAAAAAAAAAAAA"),1097+ &crate::domain::course::a_test_course(db).await,
1099 ExamTitle::try_new("practice").unwrap(),1098 ExamTitle::try_new("practice").unwrap(),
1100 ExamDescription::try_new("").unwrap(),1099 ExamDescription::try_new("").unwrap(),
1101 ExamKind::try_new("quiz", &kinds).unwrap(),1100 ExamKind::try_new("quiz", &kinds).unwrap(),
@@ -1113,7 +1112,7 @@ mod tests {
1113 1112
1114 async fn a_subject(db: &Database) -> Subject {1113 async fn a_subject(db: &Database) -> Subject {
1115 Subject::create(1114 Subject::create(
1116- &CourseId::generate(),1115+ &crate::domain::course::a_test_course(db).await,
1117 SubjectName::try_new("topic").unwrap(),1116 SubjectName::try_new("topic").unwrap(),
1118 SubjectDescription::try_new("").unwrap(),1117 SubjectDescription::try_new("").unwrap(),
1119 db,1118 db,
src/domain/subject.rsmodified+53 -4
@@ -1,7 +1,10 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3-use crate::constant::{MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN, SUBJECT_TABLE};3+use crate::constant::{
4+ ENROLLMENT_COUNT_FIELD, MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN, SUBJECT_TABLE,
5+};
4 use crate::database::{Database, transaction_with_retry};6 use crate::database::{Database, transaction_with_retry};
7+use crate::domain::cap;
5 use crate::domain::course::CourseId;8 use crate::domain::course::CourseId;
6 use crate::domain::field_update::FieldUpdate;9 use crate::domain::field_update::FieldUpdate;
7 use crate::domain::monotonic_id::next_ulid;10 use crate::domain::monotonic_id::next_ulid;
@@ -106,8 +109,20 @@ impl Subject {
106 name,109 name,
107 description,110 description,
108 };111 };
109- let created: Option<Subject> = db.create(subject.id.record()).content(subject).await?;112+ // The course row is *written* (bumped and put back), not read, so this
110- created.ok_or_else(|| AppError::Internal("failed to create subject".into()))113+ // collides with `Course::delete`'s cascade: a topic that outlives its
114+ // course 404s through `subject_with_course` forever, while
115+ // `subject_must_exist` still accepts its id — so a bank template can be
116+ // tagged with a subject nobody can reach. See [`cap::touch_and_create`].
117+ cap::touch_and_create(
118+ &course.record(),
119+ ENROLLMENT_COUNT_FIELD,
120+ &subject.id.record(),
121+ &subject,
122+ db,
123+ )
124+ .await?
125+ .ok_or(AppError::NotFound)
111 }126 }
112 127
113 pub async fn read(id: &SubjectId, db: &Database) -> Result<Option<Subject>, AppError> {128 pub async fn read(id: &SubjectId, db: &Database) -> Result<Option<Subject>, AppError> {
@@ -240,6 +255,40 @@ impl Subject {
240 mod tests {255 mod tests {
241 use super::*;256 use super::*;
242 257
258+ /// A curriculum topic must not outlive its course: an orphan 404s through
259+ /// `subject_with_course`, and worse than the sibling cases,
260+ /// `subject_must_exist` still *accepts* its id — so a bank template can be
261+ /// tagged with a subject nobody can reach.
262+ ///
263+ /// [`Subject::create`] therefore *writes* the course row rather than
264+ /// reading it ([`cap::touch_and_create`]); the harness and the window it
265+ /// races in are documented on
266+ /// [`crate::domain::course::assert_no_child_outlives_a_course_delete`].
267+ /// Mutation-tested: with the bare `db.create` this shipped with, all four
268+ /// rounds orphan.
269+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
270+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
271+ async fn a_subject_never_outlives_its_course() {
272+ fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> {
273+ tokio::spawn(async move {
274+ Subject::create(
275+ &course,
276+ SubjectName::try_new("Limits").unwrap(),
277+ SubjectDescription::try_new("").unwrap(),
278+ &db,
279+ )
280+ .await
281+ .map(|_| ())
282+ })
283+ }
284+ crate::domain::course::assert_no_child_outlives_a_course_delete(
285+ "subject_orphan_race",
286+ SUBJECT_TABLE,
287+ make,
288+ )
289+ .await;
290+ }
291+
243 /// A teacher entering a curriculum gets it back in the order they typed it:292 /// A teacher entering a curriculum gets it back in the order they typed it:
244 /// `list_for_course` sorts `id ASC`, so the ids minted inside one293 /// `list_for_course` sorts `id ASC`, so the ids minted inside one
245 /// millisecond have to sort in mint order. Revert `generate` to294 /// millisecond have to sort in mint order. Revert `generate` to
@@ -305,7 +354,7 @@ mod tests {
305 let (mut landed, mut wiped) = (0, 0);354 let (mut landed, mut wiped) = (0, 0);
306 let (mut last_delete, mut last_question) = (String::new(), String::new());355 let (mut last_delete, mut last_question) = (String::new(), String::new());
307 for round in 0..20 {356 for round in 0..20 {
308- let course = CourseId::generate();357+ let course = crate::domain::course::a_test_course(&db).await;
309 // A real exam row per round: a question write moves its exam's358 // A real exam row per round: a question write moves its exam's
310 // counter, so a minted id nothing wrote is a 404 and no round would359 // counter, so a minted id nothing wrote is a 404 and no round would
311 // reach the subject race this test is about.360 // reach the subject race this test is about.
tests/regress_course_child_orphans.rsadded+230 -0
@@ -0,0 +1,230 @@
1+//! A child of a course must not survive that course's deletion.
2+//!
3+//! `Course::delete` cascades with `DELETE <child> WHERE course = $course`, and
4+//! that statement's write set is a *snapshot* of the children that existed when
5+//! it ran. SurrealDB 3.2.3 conflict-checks write sets, not read sets, so a
6+//! create whose only tie to the course was *reading* it committed happily
7+//! alongside the sweep — and the row it left is unreachable for good, because
8+//! every route to it goes through the course:
9+//!
10+//! - an orphan `exam` 500s through `course_of` ("exam references a missing
11+//! course") on `GET`/`PATCH`/`DELETE /exams/{id}` while `GET /exams` still
12+//! lists it to every manager+ — undeletable,
13+//! - an orphan `course_session` 404s forever through `session_with_course`,
14+//! - an orphan `subject` 404s through `subject_with_course`, but
15+//! `subject_must_exist` still accepts its id, so a bank template can be
16+//! tagged with a subject nobody can reach.
17+//!
18+//! All three creates now go through `cap::touch_and_create`, which *moves* the
19+//! course's roster counter (bumped, gated, put back by captured value) inside
20+//! the create's own transaction: the write lands on the very record the delete
21+//! removes, so the store refuses one of the two. `SET x = x` would not do —
22+//! SurrealDB elides an `UPDATE` that leaves the document unchanged, and an
23+//! elided write sits in no write set at all.
24+//!
25+//! Two halves, and they are not interchangeable. **This file is the sequential
26+//! one**: it runs anywhere, on the in-memory engine, and pins the existence
27+//! contract (a create against a course that is already gone must be a 404, not
28+//! an orphan) plus the restore (the borrowed counter comes back exactly as it
29+//! was, or the course is undeletable forever — a worse bug than the one being
30+//! fixed).
31+//!
32+//! The **race** half drives the real interleaving and lives in-crate, one pin
33+//! per child beside the create it pins —
34+//! `domain::exam::tests::an_exam_never_outlives_its_course`,
35+//! `domain::course_session::tests::a_session_never_outlives_its_course`,
36+//! `domain::subject::tests::a_subject_never_outlives_its_course` — over the
37+//! shared harness `domain::course::assert_no_child_outlives_a_course_delete`.
38+//! It is `#[ignore]`d and needs a real server, because the subject there *is*
39+//! the store's conflict detection, which the embedded engine does not have: it
40+//! commits both sides and answers `Ok` to each, so a race test on `memory`
41+//! passes over the hole (same reason `domain::class_course`'s twin is ignored).
42+//! Only in-crate tests can reach `database::init_test_server` and the
43+//! `RACE_LOCK` that serializes them, and a hand-copied bootstrap here would
44+//! drift out of the real one silently.
45+
46+use hezarfen_backend::database::{self, Database};
47+use hezarfen_backend::domain::course::{
48+ Course, CourseDescription, CourseId, CourseKind, CourseTitle,
49+};
50+use hezarfen_backend::domain::course_session::{CourseSession, SessionTopic};
51+use hezarfen_backend::domain::exam::{
52+ Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,
53+};
54+use hezarfen_backend::domain::settings::Settings;
55+use hezarfen_backend::domain::subject::{Subject, SubjectDescription, SubjectName};
56+use hezarfen_backend::domain::timestamp::Timestamp;
57+use hezarfen_backend::domain::user::UserId;
58+use hezarfen_backend::error::AppError;
59+use tokio::task::JoinHandle;
60+
61+fn teacher() -> UserId {
62+ UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA")
63+}
64+
65+async fn a_course(db: &Database) -> CourseId {
66+ Course::create(
67+ &teacher(),
68+ CourseTitle::try_new("Fizik").unwrap(),
69+ CourseDescription::try_new("").unwrap(),
70+ CourseKind::course(),
71+ None,
72+ None,
73+ db,
74+ )
75+ .await
76+ .unwrap()
77+ .get_id()
78+ .clone()
79+}
80+
81+async fn drop_course(course: &CourseId, db: &Database) -> Result<bool, AppError> {
82+ Course::read(course, db)
83+ .await
84+ .unwrap()
85+ .expect("the course is there")
86+ .delete(db)
87+ .await
88+}
89+
90+// --- the three creates, each as one spawnable unit -------------------------
91+// Fn pointers rather than a generic closure: the three take different argument
92+// types and the race harness only ever needs "start it, tell me if it 500s".
93+
94+fn make_exam(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> {
95+ tokio::spawn(async move {
96+ let kinds = Settings::defaults().get_exam_kinds().to_vec();
97+ Exam::create(
98+ &teacher(),
99+ &course,
100+ ExamTitle::try_new("quiz").unwrap(),
101+ ExamDescription::try_new("").unwrap(),
102+ ExamKind::try_new("quiz", &kinds).unwrap(),
103+ ExamSchedule::try_new(None, None, None, None).unwrap(),
104+ ExamAttemptLimit::try_new(1).unwrap(),
105+ true,
106+ false,
107+ false,
108+ &db,
109+ )
110+ .await
111+ .map(|_| ())
112+ })
113+}
114+
115+fn make_session(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> {
116+ tokio::spawn(async move {
117+ CourseSession::create(
118+ &course,
119+ &teacher(),
120+ SessionTopic::try_new("limits").unwrap(),
121+ Timestamp::from_millis(1),
122+ None,
123+ &db,
124+ )
125+ .await
126+ .map(|_| ())
127+ })
128+}
129+
130+fn make_subject(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> {
131+ tokio::spawn(async move {
132+ Subject::create(
133+ &course,
134+ SubjectName::try_new("Limits").unwrap(),
135+ SubjectDescription::try_new("").unwrap(),
136+ &db,
137+ )
138+ .await
139+ .map(|_| ())
140+ })
141+}
142+
143+/// How many rows of `table` name `course`. Stored state, never a return value:
144+/// the whole point is what the store kept.
145+async fn children(table: &str, course: &CourseId, db: &Database) -> usize {
146+ let mut result = db
147+ .query(format!(
148+ "SELECT VALUE id FROM {table} WHERE course = $course"
149+ ))
150+ .bind(("course", course.record()))
151+ .await
152+ .unwrap()
153+ .check()
154+ .unwrap();
155+ result
156+ .take::<Vec<surrealdb::types::RecordId>>(0)
157+ .unwrap()
158+ .len()
159+}
160+
161+// --- the sequential half: the existence contract ---------------------------
162+
163+/// A create against a course that is *already* gone must refuse, having written
164+/// nothing. This is the half of the fix a race cannot show: with the bare
165+/// `db.create` these creates shipped with, every one of them happily wrote a
166+/// row naming a course that does not exist.
167+async fn a_create_against_a_deleted_course_refuses(
168+ table: &str,
169+ make: fn(CourseId, Database) -> JoinHandle<Result<(), AppError>>,
170+) {
171+ let db = database::init_mem().await.unwrap();
172+ let course = a_course(&db).await;
173+ assert!(drop_course(&course, &db).await.unwrap(), "the course goes");
174+
175+ let answer = make(course.clone(), db.clone()).await.unwrap();
176+ assert!(
177+ matches!(answer, Err(AppError::NotFound)),
178+ "{table}: a create under a deleted course must be a 404, not {answer:?}"
179+ );
180+ assert_eq!(
181+ children(table, &course, &db).await,
182+ 0,
183+ "{table}: a refused create left a row naming a course that is gone"
184+ );
185+}
186+
187+#[tokio::test]
188+async fn an_exam_under_a_deleted_course_is_refused() {
189+ a_create_against_a_deleted_course_refuses("exam", make_exam).await;
190+}
191+
192+#[tokio::test]
193+async fn a_session_under_a_deleted_course_is_refused() {
194+ a_create_against_a_deleted_course_refuses("course_session", make_session).await;
195+}
196+
197+#[tokio::test]
198+async fn a_subject_under_a_deleted_course_is_refused() {
199+ a_create_against_a_deleted_course_refuses("subject", make_subject).await;
200+}
201+
202+/// The counter the three creates borrow is *given back* — absent stays absent.
203+/// A bump left behind is not a smaller bug than the orphan it prevents: the
204+/// course's delete guard is `WHERE (enrollment_count ?? 0) = 0`, so a course
205+/// that once had an exam created under it would be undeletable forever, and the
206+/// boot backfill keys on the column being `NONE`.
207+#[tokio::test]
208+async fn the_creates_give_the_courses_roster_counter_back_untouched() {
209+ let db = database::init_mem().await.unwrap();
210+ let course = a_course(&db).await;
211+ let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE";
212+
213+ for make in [make_exam, make_session, make_subject] {
214+ make(course.clone(), db.clone()).await.unwrap().unwrap();
215+ }
216+ let mut result = db.query(absent).await.unwrap().check().unwrap();
217+ assert_eq!(
218+ result
219+ .take::<Vec<surrealdb::types::RecordId>>(0)
220+ .unwrap()
221+ .len(),
222+ 1,
223+ "the borrowed counter must be restored to absent, not to 0"
224+ );
225+ // The proof that matters to a user: the course is still deletable.
226+ assert!(
227+ drop_course(&course, &db).await.unwrap(),
228+ "a course whose children moved its roster counter can never be deleted"
229+ );
230+}
tests/regress_course_delete.rsmodified+133 -1
@@ -14,15 +14,147 @@
14 //! this test is built on stops holding. It was mutation-proven red alone and14 //! this test is built on stops holding. It was mutation-proven red alone and
15 //! green — on the *broken* code — beside that neighbour. Anything else added15 //! green — on the *broken* code — beside that neighbour. Anything else added
16 //! here must not take `EXAM_LOCK` either.16 //! here must not take `EXAM_LOCK` either.
17+//!
18+//! Which is why the two cascade tests below fire the delete at
19+//! [`Course::delete`] rather than at `DELETE /courses/{id}`: the handler takes
20+//! the writer lease, the defects they pin live in that transaction's SQL, and
21+//! neither one needs a race to show.
17 22
18 mod common;23 mod common;
19 24
20 use axum::http::StatusCode;25 use axum::http::StatusCode;
21-use common::{app_and_db, create_exam_with, enroll, id_of, login_as, me_id, send, unenroll};26+use common::{
27+ app_and_db, create_course, create_exam, create_exam_with, create_subject, enroll, id_of, login,
28+ login_as, me_id, send, unenroll,
29+};
30+use hezarfen_backend::domain::course::{Course, CourseId};
22 use hezarfen_backend::domain::exam::ExamId;31 use hezarfen_backend::domain::exam::ExamId;
23 use hezarfen_backend::domain::exam_attempt::ExamAttempt;32 use hezarfen_backend::domain::exam_attempt::ExamAttempt;
24 use serde_json::json;33 use serde_json::json;
25 34
35+/// Delete `course` the way the handler would, minus its `EXAM_LOCK` lease.
36+async fn drop_course(db: &hezarfen_backend::database::Database, course: &str) {
37+ let row = Course::read(&CourseId::from_key(course), db)
38+ .await
39+ .expect("read the course")
40+ .expect("the course exists");
41+ assert!(row.delete(db).await.expect("delete the course"), "refused");
42+}
43+
44+/// A bank template outlives the course it was saved out of — it is a separate,
45+/// school-wide library — so the cascade owes it the same cleanup its children's
46+/// own deletes perform: `Exam::delete` clears `source_exam`, `Subject::delete`
47+/// clears `subject`. The course cascade deleted both rows and neither link,
48+/// leaving a template pointing at two ids that no longer exist — the
49+/// `source_exam` one forever (nothing else ever visits that column) and the
50+/// `subject` one until a `PATCH` omitting `subject_id` writes it back.
51+#[tokio::test]
52+async fn a_course_delete_clears_the_bank_links_its_exams_and_subjects_owed() {
53+ let (app, db) = app_and_db().await;
54+ let teacher = login_as(&app, &db, "banka_ders_sil", "teacher").await;
55+ let course = create_course(&app, &teacher, "Fizik").await;
56+ let subject = create_subject(&app, &teacher, &course, "Optik").await;
57+ let exam = create_exam(&app, &teacher, &course, "quiz", "midterm").await;
58+
59+ let res = send(
60+ &app,
61+ "POST",
62+ &format!("/exams/{exam}/questions"),
63+ Some(&teacher),
64+ Some(json!({
65+ "subject_id": subject, "text": "mercek", "kind": "text", "points": 5
66+ })),
67+ )
68+ .await;
69+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
70+ let question = id_of(&res.body);
71+
72+ let res = send(
73+ &app,
74+ "POST",
75+ &format!("/exams/{exam}/questions/{question}/to-bank"),
76+ Some(&teacher),
77+ None,
78+ )
79+ .await;
80+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
81+ let template = id_of(&res.body);
82+ // Both links are set by the save — the test is worthless if they are not.
83+ assert_eq!(res.body["source_exam"], exam, "{}", res.body);
84+ assert_eq!(res.body["subject"], subject, "{}", res.body);
85+
86+ drop_course(&db, &course).await;
87+
88+ let res = send(
89+ &app,
90+ "GET",
91+ &format!("/bank-questions/{template}"),
92+ Some(&teacher),
93+ None,
94+ )
95+ .await;
96+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
97+ assert_eq!(
98+ (res.body["source_exam"].clone(), res.body["subject"].clone()),
99+ (json!(null), json!(null)),
100+ "the bank must be left where deleting the exam and the subject by hand \
101+ would have left it: {}",
102+ res.body
103+ );
104+}
105+
106+/// The marks the cascade sweeps hold a reference on their exam *kind*, and that
107+/// counter is the only thing standing between a manager and removing a kind the
108+/// school is already graded under. Nothing covered the release on this path —
109+/// only on `Exam::delete`'s and `remove_result`'s — and the `GROUP BY` doing it
110+/// is the shape this store has answered with no rows before.
111+#[tokio::test]
112+async fn a_course_delete_gives_back_the_kind_references_its_marks_held() {
113+ let (app, db) = app_and_db().await;
114+ let teacher = login_as(&app, &db, "kind_ref_ders_sil", "teacher").await;
115+ let student = login(&app, "kind_ref_ogrenci").await;
116+ let student_id = me_id(&app, &student).await;
117+
118+ let course = create_course(&app, &teacher, "Tarih").await;
119+ enroll(&app, &teacher, &course, &student_id).await;
120+ let exam = create_exam(&app, &teacher, &course, "Vize", "midterm").await;
121+ let res = send(
122+ &app,
123+ "POST",
124+ &format!("/exams/{exam}/results"),
125+ Some(&teacher),
126+ Some(json!({ "user_id": student_id, "mark": 70 })),
127+ )
128+ .await;
129+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
130+
131+ let counted = |db: hezarfen_backend::database::Database| async move {
132+ db.query("SELECT VALUE count ?? 0 FROM kind_ref:midterm")
133+ .await
134+ .expect("kind_ref read")
135+ .check()
136+ .expect("kind_ref read")
137+ .take::<Vec<i64>>(0)
138+ .expect("kind_ref count")
139+ .first()
140+ .copied()
141+ .unwrap_or(0)
142+ };
143+ assert_eq!(counted(db.clone()).await, 1, "the mark must be counted");
144+
145+ // The roster has to empty before the delete is admitted at all; the mark
146+ // stays behind, which is precisely why the cascade owes the release.
147+ unenroll(&app, &teacher, &course, &student_id).await;
148+ drop_course(&db, &course).await;
149+
150+ assert_eq!(
151+ counted(db.clone()).await,
152+ 0,
153+ "the swept mark's kind reference was never given back — the kind can \
154+ never leave the school's settings"
155+ );
156+}
157+
26 /// Reaching the window takes one move `regress_exam_delete` does not need,158 /// Reaching the window takes one move `regress_exam_delete` does not need,
27 /// because a course is refused while anyone is enrolled: the sitting has to159 /// because a course is refused while anyone is enrolled: the sitting has to
28 /// pass its enrollment gate and then lose that enrollment while it is still160 /// pass its enrollment gate and then lose that enrollment while it is still