diff --git a/src/domain/course.rs b/src/domain/course.rs index 6336d66..a836877 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -400,6 +400,17 @@ impl Course { /// homework-file *blobs* are the web layer's to remove — it collects /// their names before calling this. /// + /// **Bank templates** survive it — they are a separate, reusable library + /// spanning every course — so their `source_exam` and `subject` links are + /// cleared instead, in this same transaction, exactly as + /// [`crate::domain::exam::Exam::delete`] and + /// [`crate::domain::subject::Subject::delete`] clear them one level down. + /// Deleting a course must leave the bank where deleting each of its exams + /// and subjects by hand would have left it, or a template is left pointing + /// at a dead exam (permanently: nothing else ever visits that column) and + /// at a dead subject the next `PATCH` omitting `subject_id` writes straight + /// back. + /// /// The **grade blueprints** naming it are swept in that same transaction. /// Nothing else can reach them — a blueprint holds its courses as a list on /// its own row, not as link rows this cascade could delete — and an id left @@ -461,8 +472,12 @@ impl Course { DELETE session_attendance WHERE course = $course; DELETE course_session WHERE course = $course; DELETE enrollment WHERE course = $course; + UPDATE bank_question SET subject = NONE + WHERE subject IN (SELECT VALUE id FROM subject WHERE course = $course); DELETE subject WHERE course = $course; DELETE homework WHERE course = $course; + UPDATE bank_question SET source_exam = NONE + WHERE source_exam IN (SELECT VALUE id FROM exam WHERE course = $course); DELETE exam WHERE course = $course; COMMIT TRANSACTION;" ); @@ -494,6 +509,125 @@ impl Course { } } +/// A real course row, for the tests of every child that must now prove its +/// parent exists (`Exam`, `CourseSession`, `Subject` — see +/// [`cap::touch_and_create`]). A minted id nothing wrote is a 404 there, the +/// way a minted subject id already is for an exam question. +#[cfg(test)] +pub(crate) async fn a_test_course(db: &Database) -> CourseId { + Course::create( + &UserId::generate(), + CourseTitle::try_new("test course").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + None, + None, + db, + ) + .await + .unwrap() + .id +} + +/// The race half of "a child of a course must not survive its deletion", run +/// for one child table: [`Course::delete`] is held open by the schema and +/// `make` fires its create inside that window, four rounds. +/// +/// The harness lives here, beside the cascade being raced, and each child names +/// its own pin in its own module (`exam`, `course_session`, `subject`) — the +/// loop, the window and the verdict are one fact about *this* delete, and three +/// copies of it would drift into three different tests of three different +/// things. The sequential half — a create against a course that is already gone +/// — is `tests/regress_course_child_orphans.rs`, which needs no server. +/// +/// The window is opened by the database rather than by a lucky interleaving: a +/// `DEFINE EVENT` on `course` fires *inside* the delete's own transaction the +/// instant the row goes, so the `SLEEP` lands between the delete and its +/// `DELETE WHERE course = $course` sweep every time — and a create +/// fired into it reads a course that is still there (removed, uncommitted) +/// while the sweep already ran on a snapshot without its row. +/// +/// One child per round, for the reason the menu and `class_course` twins +/// document: a second writer makes the delete lose and re-send, and the re-sent +/// sweep clears the evidence. +/// +/// Real server, and every caller is `#[ignore]`d for it: the subject *is* the +/// store's conflict detection, which `init_mem`'s embedded engine does not +/// have — it commits both sides and answers `Ok` to each, so this passes there +/// on broken code. +#[cfg(test)] +pub(crate) async fn assert_no_child_outlives_a_course_delete( + scratch: &str, + table: &str, + make: fn(CourseId, Database) -> tokio::task::JoinHandle>, +) { + // The guard is held for the whole test: these bursts are sub-millisecond, + // and a sibling race test's burst pushes a delete clean out of its window. + let (db, _serialized) = crate::database::init_test_server(scratch).await; + db.query( + "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .expect("define the window event") + .check() + .expect("check the window event"); + + let (mut swept, mut orphans) = (0, 0); + for round in 0..4 { + let course = a_test_course(&db).await; + let drop_it = { + let (course, db) = (course.clone(), db.clone()); + tokio::spawn(async move { + Course::read(&course, &db) + .await + .unwrap() + .expect("the course is there") + .delete(&db) + .await + }) + }; + // The create starts inside the held window. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let child = make(course.clone(), db.clone()).await.unwrap(); + let dropped = drop_it.await.unwrap(); + + // A 404 for the create, or a refusal for the delete, is a correct + // answer — the only defect is stored state. Nothing may 500. + assert!( + !matches!(child, Err(AppError::Db(_))), + "{table} round {round}: a raced create must be answered, not 500: {child:?}" + ); + assert!( + !matches!(dropped, Err(AppError::Db(_))), + "{table} round {round}: a raced delete must be answered, not 500: {dropped:?}" + ); + + // Stored state is the whole verdict; a return value is not evidence. + if Course::read(&course, &db).await.unwrap().is_none() { + swept += 1; + let mut left = db + .query(format!( + "SELECT VALUE id FROM {table} WHERE course = $course" + )) + .bind(("course", course.record())) + .await + .unwrap() + .check() + .unwrap(); + orphans += left.take::>(0).unwrap().len(); + } else if matches!(dropped, Ok(true)) { + panic!("{table} round {round}: the delete reported success, the course is still there"); + } + } + eprintln!("Course::delete raced by a {table} create: {swept}/4 rounds deleted the course"); + assert!( + swept > 0, + "{table}: no round ever deleted the course, so the window was never reached" + ); + assert_eq!(orphans, 0, "{table}: a child outlived its course"); +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/domain/course_session.rs b/src/domain/course_session.rs index e70f6cd..c6a5e98 100644 --- a/src/domain/course_session.rs +++ b/src/domain/course_session.rs @@ -1,7 +1,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{COURSE_SESSION_TABLE, MAX_SESSION_TOPIC_LEN}; +use crate::constant::{COURSE_SESSION_TABLE, ENROLLMENT_COUNT_FIELD, MAX_SESSION_TOPIC_LEN}; use crate::database::{Database, transaction_with_retry}; +use crate::domain::cap; use crate::domain::course::CourseId; use crate::domain::field_update::FieldUpdate; use crate::domain::monotonic_id::next_ulid; @@ -113,9 +114,19 @@ impl CourseSession { starts_at, ends_at, }; - let created: Option = - db.create(session.id.record()).content(session).await?; - created.ok_or_else(|| AppError::Internal("failed to create session".into())) + // The course row is *written* (bumped and put back), not read, so this + // collides with `Course::delete`'s cascade: a lesson that outlives its + // course 404s through `session_with_course` forever — unreadable, + // unpatchable, undeletable. See [`cap::touch_and_create`]. + cap::touch_and_create( + &course.record(), + ENROLLMENT_COUNT_FIELD, + &session.id.record(), + &session, + db, + ) + .await? + .ok_or(AppError::NotFound) } pub async fn read( @@ -204,6 +215,41 @@ impl CourseSession { mod tests { use super::*; + /// A lesson must not outlive the course it is a lesson of: an orphan 404s + /// forever through `session_with_course` — unreadable, unpatchable, + /// undeletable. + /// + /// [`CourseSession::create`] therefore *writes* the course row rather than + /// reading it ([`cap::touch_and_create`]); the harness and the window it + /// races in are documented on + /// [`crate::domain::course::assert_no_child_outlives_a_course_delete`]. + /// Mutation-tested: with the bare `db.create` this shipped with, all four + /// rounds orphan. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_session_never_outlives_its_course() { + fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle> { + tokio::spawn(async move { + CourseSession::create( + &course, + &UserId::generate(), + SessionTopic::try_new("limits").unwrap(), + Timestamp::from_millis(1), + None, + &db, + ) + .await + .map(|_| ()) + }) + } + crate::domain::course::assert_no_child_outlives_a_course_delete( + "session_orphan_race", + COURSE_SESSION_TABLE, + make, + ) + .await; + } + #[tokio::test] async fn topic_is_optional_but_bounded() { assert!(SessionTopic::try_new("").is_ok()); diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 2fea2fe..313c554 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -1,9 +1,11 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ - EXAM_TABLE, MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS, + ENROLLMENT_COUNT_FIELD, EXAM_TABLE, MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, + UNLIMITED_EXAM_ATTEMPTS, }; use crate::database::{Database, transaction_with_retry}; +use crate::domain::cap; use crate::domain::course::CourseId; use crate::domain::monotonic_id::next_ulid; use crate::domain::settings::ExamKindDef; @@ -421,8 +423,20 @@ impl Exam { draft, result_count: None, }; - let created: Option = db.create(exam.id.record()).content(exam).await?; - created.ok_or_else(|| AppError::Internal("failed to create exam".into())) + // The course row is *written* (bumped and put back), not read: a plain + // read does not survive `Course::delete`'s window, and an exam that + // outlives its course is unreachable for good — every route to one goes + // through `course_of`, which answers a 500 no delete can clear, while + // `GET /exams` still lists it. See [`cap::touch_and_create`]. + cap::touch_and_create( + &course.record(), + ENROLLMENT_COUNT_FIELD, + &exam.id.record(), + &exam, + db, + ) + .await? + .ok_or(AppError::NotFound) } pub async fn read(id: &ExamId, db: &Database) -> Result, AppError> { @@ -678,7 +692,7 @@ pub(crate) async fn published_exam(db: &Database) -> Exam { .to_vec(); Exam::create( &UserId::generate(), - &CourseId::generate(), + &crate::domain::course::a_test_course(db).await, ExamTitle::try_new("midterm").unwrap(), ExamDescription::try_new("").unwrap(), ExamKind::try_new("midterm", &allowed).unwrap(), @@ -699,6 +713,52 @@ mod tests { use crate::domain::exam::published_exam as published; + /// An exam must not outlive the course it belongs to. It is the worst of + /// the three children `Course::delete` used to leave behind: every exam + /// route funnels through `course_of`, which answers + /// `Internal("exam references a missing course")`, so an orphan **500s + /// forever** on `GET`/`PATCH`/`DELETE /exams/{id}` — undeletable — while + /// `Exam::list_all` still hands it to every manager+ on `GET /exams`. + /// + /// [`Exam::create`] therefore *writes* the course row rather than reading + /// it ([`cap::touch_and_create`]); the harness and the window it races in + /// are documented on + /// [`crate::domain::course::assert_no_child_outlives_a_course_delete`]. + /// Mutation-tested: with the bare `db.create` this shipped with, all four + /// rounds orphan. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn an_exam_never_outlives_its_course() { + fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle> { + tokio::spawn(async move { + let kinds = crate::domain::settings::Settings::defaults() + .get_exam_kinds() + .to_vec(); + Exam::create( + &UserId::generate(), + &course, + ExamTitle::try_new("quiz").unwrap(), + ExamDescription::try_new("").unwrap(), + ExamKind::try_new("quiz", &kinds).unwrap(), + ExamSchedule::try_new(None, None, None, None).unwrap(), + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + false, + &db, + ) + .await + .map(|_| ()) + }) + } + crate::domain::course::assert_no_child_outlives_a_course_delete( + "exam_orphan_race", + EXAM_TABLE, + make, + ) + .await; + } + fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) { ( exam.get_title().clone(), @@ -1064,7 +1124,7 @@ mod tests { ) .unwrap(); let subject = crate::domain::subject::Subject::create( - &CourseId::generate(), + &crate::domain::course::a_test_course(db).await, crate::domain::subject::SubjectName::try_new("topic").unwrap(), crate::domain::subject::SubjectDescription::try_new("").unwrap(), db, @@ -1208,7 +1268,7 @@ mod tests { let exam = published(&db).await; let id = exam.get_id().clone(); let subject = Subject::create( - &CourseId::generate(), + &crate::domain::course::a_test_course(&db).await, crate::domain::subject::SubjectName::try_new("topic").unwrap(), crate::domain::subject::SubjectDescription::try_new("").unwrap(), &db, diff --git a/src/domain/exam_answer.rs b/src/domain/exam_answer.rs index 299c48c..38ba7dc 100644 --- a/src/domain/exam_answer.rs +++ b/src/domain/exam_answer.rs @@ -508,7 +508,7 @@ mod tests { .to_vec(); let exam = Exam::create( &student(), - &crate::domain::course::CourseId::generate(), + &crate::domain::course::a_test_course(&db).await, ExamTitle::try_new("quiz").unwrap(), ExamDescription::try_new("").unwrap(), ExamKind::try_new("quiz", &kinds).unwrap(), diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index e9b9db2..6a066ff 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -1083,7 +1083,6 @@ mod tests { mod counters { use super::*; use crate::database::init_mem; - use crate::domain::course::CourseId; use crate::domain::exam::{ Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, }; @@ -1095,7 +1094,7 @@ mod tests { let kinds = Settings::defaults().get_exam_kinds().to_vec(); Exam::create( &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), - &CourseId::from_key("01TESTCOURSEAAAAAAAAAAAAAA"), + &crate::domain::course::a_test_course(db).await, ExamTitle::try_new("practice").unwrap(), ExamDescription::try_new("").unwrap(), ExamKind::try_new("quiz", &kinds).unwrap(), @@ -1113,7 +1112,7 @@ mod tests { async fn a_subject(db: &Database) -> Subject { Subject::create( - &CourseId::generate(), + &crate::domain::course::a_test_course(db).await, SubjectName::try_new("topic").unwrap(), SubjectDescription::try_new("").unwrap(), db, diff --git a/src/domain/subject.rs b/src/domain/subject.rs index 51d8886..a80a10d 100644 --- a/src/domain/subject.rs +++ b/src/domain/subject.rs @@ -1,7 +1,10 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN, SUBJECT_TABLE}; +use crate::constant::{ + ENROLLMENT_COUNT_FIELD, MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN, SUBJECT_TABLE, +}; use crate::database::{Database, transaction_with_retry}; +use crate::domain::cap; use crate::domain::course::CourseId; use crate::domain::field_update::FieldUpdate; use crate::domain::monotonic_id::next_ulid; @@ -106,8 +109,20 @@ impl Subject { name, description, }; - let created: Option = db.create(subject.id.record()).content(subject).await?; - created.ok_or_else(|| AppError::Internal("failed to create subject".into())) + // The course row is *written* (bumped and put back), not read, so this + // collides with `Course::delete`'s cascade: a topic that outlives its + // course 404s through `subject_with_course` forever, while + // `subject_must_exist` still accepts its id — so a bank template can be + // tagged with a subject nobody can reach. See [`cap::touch_and_create`]. + cap::touch_and_create( + &course.record(), + ENROLLMENT_COUNT_FIELD, + &subject.id.record(), + &subject, + db, + ) + .await? + .ok_or(AppError::NotFound) } pub async fn read(id: &SubjectId, db: &Database) -> Result, AppError> { @@ -240,6 +255,40 @@ impl Subject { mod tests { use super::*; + /// A curriculum topic must not outlive its course: an orphan 404s through + /// `subject_with_course`, and worse than the sibling cases, + /// `subject_must_exist` still *accepts* its id — so a bank template can be + /// tagged with a subject nobody can reach. + /// + /// [`Subject::create`] therefore *writes* the course row rather than + /// reading it ([`cap::touch_and_create`]); the harness and the window it + /// races in are documented on + /// [`crate::domain::course::assert_no_child_outlives_a_course_delete`]. + /// Mutation-tested: with the bare `db.create` this shipped with, all four + /// rounds orphan. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_subject_never_outlives_its_course() { + fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle> { + tokio::spawn(async move { + Subject::create( + &course, + SubjectName::try_new("Limits").unwrap(), + SubjectDescription::try_new("").unwrap(), + &db, + ) + .await + .map(|_| ()) + }) + } + crate::domain::course::assert_no_child_outlives_a_course_delete( + "subject_orphan_race", + SUBJECT_TABLE, + make, + ) + .await; + } + /// A teacher entering a curriculum gets it back in the order they typed it: /// `list_for_course` sorts `id ASC`, so the ids minted inside one /// millisecond have to sort in mint order. Revert `generate` to @@ -305,7 +354,7 @@ mod tests { let (mut landed, mut wiped) = (0, 0); let (mut last_delete, mut last_question) = (String::new(), String::new()); for round in 0..20 { - let course = CourseId::generate(); + let course = crate::domain::course::a_test_course(&db).await; // A real exam row per round: a question write moves its exam's // counter, so a minted id nothing wrote is a 404 and no round would // reach the subject race this test is about. diff --git a/tests/regress_course_child_orphans.rs b/tests/regress_course_child_orphans.rs new file mode 100644 index 0000000..83c0474 --- /dev/null +++ b/tests/regress_course_child_orphans.rs @@ -0,0 +1,230 @@ +//! A child of a course must not survive that course's deletion. +//! +//! `Course::delete` cascades with `DELETE WHERE course = $course`, and +//! that statement's write set is a *snapshot* of the children that existed when +//! it ran. SurrealDB 3.2.3 conflict-checks write sets, not read sets, so a +//! create whose only tie to the course was *reading* it committed happily +//! alongside the sweep — and the row it left is unreachable for good, because +//! every route to it goes through the course: +//! +//! - an orphan `exam` 500s through `course_of` ("exam references a missing +//! course") on `GET`/`PATCH`/`DELETE /exams/{id}` while `GET /exams` still +//! lists it to every manager+ — undeletable, +//! - an orphan `course_session` 404s forever through `session_with_course`, +//! - an orphan `subject` 404s through `subject_with_course`, but +//! `subject_must_exist` still accepts its id, so a bank template can be +//! tagged with a subject nobody can reach. +//! +//! All three creates now go through `cap::touch_and_create`, which *moves* the +//! course's roster counter (bumped, gated, put back by captured value) inside +//! the create's own transaction: the write lands on the very record the delete +//! removes, so the store refuses one of the two. `SET x = x` would not do — +//! SurrealDB elides an `UPDATE` that leaves the document unchanged, and an +//! elided write sits in no write set at all. +//! +//! Two halves, and they are not interchangeable. **This file is the sequential +//! one**: it runs anywhere, on the in-memory engine, and pins the existence +//! contract (a create against a course that is already gone must be a 404, not +//! an orphan) plus the restore (the borrowed counter comes back exactly as it +//! was, or the course is undeletable forever — a worse bug than the one being +//! fixed). +//! +//! The **race** half drives the real interleaving and lives in-crate, one pin +//! per child beside the create it pins — +//! `domain::exam::tests::an_exam_never_outlives_its_course`, +//! `domain::course_session::tests::a_session_never_outlives_its_course`, +//! `domain::subject::tests::a_subject_never_outlives_its_course` — over the +//! shared harness `domain::course::assert_no_child_outlives_a_course_delete`. +//! It is `#[ignore]`d and needs a real server, because the subject there *is* +//! the store's conflict detection, which the embedded engine does not have: it +//! commits both sides and answers `Ok` to each, so a race test on `memory` +//! passes over the hole (same reason `domain::class_course`'s twin is ignored). +//! Only in-crate tests can reach `database::init_test_server` and the +//! `RACE_LOCK` that serializes them, and a hand-copied bootstrap here would +//! drift out of the real one silently. + +use hezarfen_backend::database::{self, Database}; +use hezarfen_backend::domain::course::{ + Course, CourseDescription, CourseId, CourseKind, CourseTitle, +}; +use hezarfen_backend::domain::course_session::{CourseSession, SessionTopic}; +use hezarfen_backend::domain::exam::{ + Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, +}; +use hezarfen_backend::domain::settings::Settings; +use hezarfen_backend::domain::subject::{Subject, SubjectDescription, SubjectName}; +use hezarfen_backend::domain::timestamp::Timestamp; +use hezarfen_backend::domain::user::UserId; +use hezarfen_backend::error::AppError; +use tokio::task::JoinHandle; + +fn teacher() -> UserId { + UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA") +} + +async fn a_course(db: &Database) -> CourseId { + Course::create( + &teacher(), + CourseTitle::try_new("Fizik").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + None, + None, + db, + ) + .await + .unwrap() + .get_id() + .clone() +} + +async fn drop_course(course: &CourseId, db: &Database) -> Result { + Course::read(course, db) + .await + .unwrap() + .expect("the course is there") + .delete(db) + .await +} + +// --- the three creates, each as one spawnable unit ------------------------- +// Fn pointers rather than a generic closure: the three take different argument +// types and the race harness only ever needs "start it, tell me if it 500s". + +fn make_exam(course: CourseId, db: Database) -> JoinHandle> { + tokio::spawn(async move { + let kinds = Settings::defaults().get_exam_kinds().to_vec(); + Exam::create( + &teacher(), + &course, + ExamTitle::try_new("quiz").unwrap(), + ExamDescription::try_new("").unwrap(), + ExamKind::try_new("quiz", &kinds).unwrap(), + ExamSchedule::try_new(None, None, None, None).unwrap(), + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + false, + &db, + ) + .await + .map(|_| ()) + }) +} + +fn make_session(course: CourseId, db: Database) -> JoinHandle> { + tokio::spawn(async move { + CourseSession::create( + &course, + &teacher(), + SessionTopic::try_new("limits").unwrap(), + Timestamp::from_millis(1), + None, + &db, + ) + .await + .map(|_| ()) + }) +} + +fn make_subject(course: CourseId, db: Database) -> JoinHandle> { + tokio::spawn(async move { + Subject::create( + &course, + SubjectName::try_new("Limits").unwrap(), + SubjectDescription::try_new("").unwrap(), + &db, + ) + .await + .map(|_| ()) + }) +} + +/// How many rows of `table` name `course`. Stored state, never a return value: +/// the whole point is what the store kept. +async fn children(table: &str, course: &CourseId, db: &Database) -> usize { + let mut result = db + .query(format!( + "SELECT VALUE id FROM {table} WHERE course = $course" + )) + .bind(("course", course.record())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .len() +} + +// --- the sequential half: the existence contract --------------------------- + +/// A create against a course that is *already* gone must refuse, having written +/// nothing. This is the half of the fix a race cannot show: with the bare +/// `db.create` these creates shipped with, every one of them happily wrote a +/// row naming a course that does not exist. +async fn a_create_against_a_deleted_course_refuses( + table: &str, + make: fn(CourseId, Database) -> JoinHandle>, +) { + let db = database::init_mem().await.unwrap(); + let course = a_course(&db).await; + assert!(drop_course(&course, &db).await.unwrap(), "the course goes"); + + let answer = make(course.clone(), db.clone()).await.unwrap(); + assert!( + matches!(answer, Err(AppError::NotFound)), + "{table}: a create under a deleted course must be a 404, not {answer:?}" + ); + assert_eq!( + children(table, &course, &db).await, + 0, + "{table}: a refused create left a row naming a course that is gone" + ); +} + +#[tokio::test] +async fn an_exam_under_a_deleted_course_is_refused() { + a_create_against_a_deleted_course_refuses("exam", make_exam).await; +} + +#[tokio::test] +async fn a_session_under_a_deleted_course_is_refused() { + a_create_against_a_deleted_course_refuses("course_session", make_session).await; +} + +#[tokio::test] +async fn a_subject_under_a_deleted_course_is_refused() { + a_create_against_a_deleted_course_refuses("subject", make_subject).await; +} + +/// The counter the three creates borrow is *given back* — absent stays absent. +/// A bump left behind is not a smaller bug than the orphan it prevents: the +/// course's delete guard is `WHERE (enrollment_count ?? 0) = 0`, so a course +/// that once had an exam created under it would be undeletable forever, and the +/// boot backfill keys on the column being `NONE`. +#[tokio::test] +async fn the_creates_give_the_courses_roster_counter_back_untouched() { + let db = database::init_mem().await.unwrap(); + let course = a_course(&db).await; + let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE"; + + for make in [make_exam, make_session, make_subject] { + make(course.clone(), db.clone()).await.unwrap().unwrap(); + } + let mut result = db.query(absent).await.unwrap().check().unwrap(); + assert_eq!( + result + .take::>(0) + .unwrap() + .len(), + 1, + "the borrowed counter must be restored to absent, not to 0" + ); + // The proof that matters to a user: the course is still deletable. + assert!( + drop_course(&course, &db).await.unwrap(), + "a course whose children moved its roster counter can never be deleted" + ); +} diff --git a/tests/regress_course_delete.rs b/tests/regress_course_delete.rs index b744184..ed30838 100644 --- a/tests/regress_course_delete.rs +++ b/tests/regress_course_delete.rs @@ -14,15 +14,147 @@ //! this test is built on stops holding. It was mutation-proven red alone and //! green — on the *broken* code — beside that neighbour. Anything else added //! here must not take `EXAM_LOCK` either. +//! +//! Which is why the two cascade tests below fire the delete at +//! [`Course::delete`] rather than at `DELETE /courses/{id}`: the handler takes +//! the writer lease, the defects they pin live in that transaction's SQL, and +//! neither one needs a race to show. mod common; use axum::http::StatusCode; -use common::{app_and_db, create_exam_with, enroll, id_of, login_as, me_id, send, unenroll}; +use common::{ + app_and_db, create_course, create_exam, create_exam_with, create_subject, enroll, id_of, login, + login_as, me_id, send, unenroll, +}; +use hezarfen_backend::domain::course::{Course, CourseId}; use hezarfen_backend::domain::exam::ExamId; use hezarfen_backend::domain::exam_attempt::ExamAttempt; use serde_json::json; +/// Delete `course` the way the handler would, minus its `EXAM_LOCK` lease. +async fn drop_course(db: &hezarfen_backend::database::Database, course: &str) { + let row = Course::read(&CourseId::from_key(course), db) + .await + .expect("read the course") + .expect("the course exists"); + assert!(row.delete(db).await.expect("delete the course"), "refused"); +} + +/// A bank template outlives the course it was saved out of — it is a separate, +/// school-wide library — so the cascade owes it the same cleanup its children's +/// own deletes perform: `Exam::delete` clears `source_exam`, `Subject::delete` +/// clears `subject`. The course cascade deleted both rows and neither link, +/// leaving a template pointing at two ids that no longer exist — the +/// `source_exam` one forever (nothing else ever visits that column) and the +/// `subject` one until a `PATCH` omitting `subject_id` writes it back. +#[tokio::test] +async fn a_course_delete_clears_the_bank_links_its_exams_and_subjects_owed() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "banka_ders_sil", "teacher").await; + let course = create_course(&app, &teacher, "Fizik").await; + let subject = create_subject(&app, &teacher, &course, "Optik").await; + let exam = create_exam(&app, &teacher, &course, "quiz", "midterm").await; + + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions"), + Some(&teacher), + Some(json!({ + "subject_id": subject, "text": "mercek", "kind": "text", "points": 5 + })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let question = id_of(&res.body); + + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/{question}/to-bank"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let template = id_of(&res.body); + // Both links are set by the save — the test is worthless if they are not. + assert_eq!(res.body["source_exam"], exam, "{}", res.body); + assert_eq!(res.body["subject"], subject, "{}", res.body); + + drop_course(&db, &course).await; + + let res = send( + &app, + "GET", + &format!("/bank-questions/{template}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!( + (res.body["source_exam"].clone(), res.body["subject"].clone()), + (json!(null), json!(null)), + "the bank must be left where deleting the exam and the subject by hand \ + would have left it: {}", + res.body + ); +} + +/// The marks the cascade sweeps hold a reference on their exam *kind*, and that +/// counter is the only thing standing between a manager and removing a kind the +/// school is already graded under. Nothing covered the release on this path — +/// only on `Exam::delete`'s and `remove_result`'s — and the `GROUP BY` doing it +/// is the shape this store has answered with no rows before. +#[tokio::test] +async fn a_course_delete_gives_back_the_kind_references_its_marks_held() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "kind_ref_ders_sil", "teacher").await; + let student = login(&app, "kind_ref_ogrenci").await; + let student_id = me_id(&app, &student).await; + + let course = create_course(&app, &teacher, "Tarih").await; + enroll(&app, &teacher, &course, &student_id).await; + let exam = create_exam(&app, &teacher, &course, "Vize", "midterm").await; + let res = send( + &app, + "POST", + &format!("/exams/{exam}/results"), + Some(&teacher), + Some(json!({ "user_id": student_id, "mark": 70 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let counted = |db: hezarfen_backend::database::Database| async move { + db.query("SELECT VALUE count ?? 0 FROM kind_ref:midterm") + .await + .expect("kind_ref read") + .check() + .expect("kind_ref read") + .take::>(0) + .expect("kind_ref count") + .first() + .copied() + .unwrap_or(0) + }; + assert_eq!(counted(db.clone()).await, 1, "the mark must be counted"); + + // The roster has to empty before the delete is admitted at all; the mark + // stays behind, which is precisely why the cascade owes the release. + unenroll(&app, &teacher, &course, &student_id).await; + drop_course(&db, &course).await; + + assert_eq!( + counted(db.clone()).await, + 0, + "the swept mark's kind reference was never given back — the kind can \ + never leave the school's settings" + ); +} + /// Reaching the window takes one move `regress_exam_delete` does not need, /// because a course is refused while anyone is enrolled: the sitting has to /// pass its enrollment gate and then lose that enrollment while it is still