From 420deefcc0f6e2a08917280e25824439bacb8dea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 5 Aug 2026 21:04:51 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=9D=20fix:=20close=20the=20homework=20?= =?UTF-8?q?orphan=20window=20and=20the=20subset=20roster=20leak?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit upload_submission_file streamed the whole multipart body before taking HOMEWORK_LOCK, and HomeworkSubmission::upsert had no parent gate, so a DELETE /homework/{id} inside that multi-second window let the late write recreate submission, file, blob and badge credit under vanished homework — all unreachable afterwards. Both halves are fixed: the gate re-runs under the lease, and the upsert now moves a value on the homework row. HomeworkResult::grade gets the same treatment, in the order its own ponytail asked for: transaction_with_retry first, then the parent gate. delete_course now takes HOMEWORK_LOCK as well as EXAM_LOCK. HomeworkResponse.assigned returned the full subset roster to every assigned student, while the course roster itself is teacher+ only — the opposite of what the code comment says it intends. It is now narrowed to the viewer. HomeworkFile::delete moves to transaction_with_retry like its siblings. --- src/domain/homework.rs | 2 +- src/domain/homework_file.rs | 37 +- src/domain/homework_result.rs | 117 ++++- src/domain/homework_submission.rs | 34 +- src/web/courses.rs | 31 +- src/web/dto.rs | 17 +- src/web/homework.rs | 66 ++- tests/regress_homework_orphans.rs | 740 ++++++++++++++++++++++++++++++ 8 files changed, 985 insertions(+), 59 deletions(-) create mode 100644 tests/regress_homework_orphans.rs diff --git a/src/domain/homework.rs b/src/domain/homework.rs index 93d2823..dc83337 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -422,7 +422,7 @@ mod tests { async fn a_subject(name: &str, db: &Database) -> Subject { Subject::create( - &CourseId::from_key("course"), + &crate::domain::course::a_test_course(db).await, SubjectName::try_new(name).unwrap(), SubjectDescription::try_new("").unwrap(), db, diff --git a/src/domain/homework_file.rs b/src/domain/homework_file.rs index 15ea743..7708634 100644 --- a/src/domain/homework_file.rs +++ b/src/domain/homework_file.rs @@ -15,7 +15,7 @@ use crate::constant::{ HOMEWORK_FILE_TABLE, MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD, SUBMISSION_OPEN_GUARD, }; -use crate::database::Database; +use crate::database::{Database, transaction_with_retry}; use crate::domain::cap; use crate::domain::course::CourseId; use crate::domain::homework::HomeworkId; @@ -268,9 +268,19 @@ impl HomeworkFile { /// stamps first (this delete is refused, `Ok(None)`) or stamps after (the /// file was already gone when it graded). `Err(NotFound)` still means the /// file row itself had vanished. + /// + /// Sound to re-send while the store answers "conflict, retry", and it has + /// to be: the gate writes the *submission* row, the very record an upload's + /// [`HomeworkFile::insert`] claims its seat on, and both handlers hold only + /// `HOMEWORK_LOCK.read()` — so a concurrent add and delete of two files of + /// one submission contend by design, and a lost round used to come back as + /// a 500 on a request that had written nothing. Only `UPDATE` and `DELETE` + /// are in the batch, and neither can legitimately answer "already exists", + /// which is what makes the whole of it re-sendable. pub async fn delete(self, db: &Database) -> Result, AppError> { - let mut result = db - .query(format!( + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( "BEGIN TRANSACTION; LET $open = (UPDATE $sub SET updated_at = $now \ WHERE {SUBMISSION_OPEN_GUARD} RETURN VALUE id); @@ -278,12 +288,18 @@ impl HomeworkFile { UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); RETURN {{ open: array::len($open), gone: $gone }}; COMMIT TRANSACTION;" - )) - .bind(("id", self.id.record())) - .bind(("sub", self.submission.record())) - .bind(("now", Timestamp::now())) - .await? - .check()?; + ), + &[ + ("id".into(), self.id.record().into_value()), + ("sub".into(), self.submission.record().into_value()), + ("now".into(), Timestamp::now().into_value()), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } // BEGIN is slot 0, the two LETs slots 1-2 and the counter fix slot 3; // the RETURN is slot 4. let outcome: Option = @@ -311,11 +327,10 @@ mod tests { /// A real homework row (with the subject it references): `upsert` reads the /// deadline off the entity now, so a bare id no longer does. async fn a_homework(db: &Database) -> crate::domain::homework::Homework { - use crate::domain::course::CourseId; use crate::domain::homework::{Homework, HomeworkTitle}; use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; - let course = CourseId::from_key("course"); + let course = crate::domain::course::a_test_course(db).await; let subject = Subject::create( &course, SubjectName::try_new("topic").unwrap(), diff --git a/src/domain/homework_result.rs b/src/domain/homework_result.rs index e99da96..48ab520 100644 --- a/src/domain/homework_result.rs +++ b/src/domain/homework_result.rs @@ -172,17 +172,43 @@ impl HomeworkResult { // homework mark is optional and most grades are status-only, so // `high_mark` is an exam-only family. // - // ponytail: this is a plain query, not `transaction_with_retry`, so a - // store conflict on the grader's row — another domain writing the same - // user row in the same instant — comes back as a 500 rather than a - // re-send. Rare (grading is serialised by `HOMEWORK_LOCK` and a - // teacher's row moves nowhere else but exam grading), and the upgrade - // is the shape `HomeworkSubmission::upsert` already uses: the whole - // transaction is re-sendable, since nothing in it can legitimately - // answer "already exists". - let mut saved = db - .query(format!( + // The first three statements are the parent gate, the twin of + // [`crate::domain::homework_submission::HomeworkSubmission::upsert`]'s + // and written the same way on purpose: the id is deterministic, so a + // grade landing inside a homework (or course) delete's window does not + // fail — it *re-creates* a result row under a homework that is gone, + // readable ever after at `GET /homework/{id}/result` (no existence check + // there) with a `marks_given_total` no ungrade can reach, because every + // route to the grade goes through the homework. Reading the homework + // first — which the web layer does, under the lease — cannot close that: + // the store conflict-checks write sets, not read sets. So the gate + // *moves* a value on the homework row (`due_at` up by one and straight + // back to the captured value, leaving the row byte-identical) and the + // cascade's delete of that same row is what refuses it. `homework` owns + // no counter column and is SCHEMAFULL, so `due_at` is the one `int` it + // already has; do not invent a second spelling. + // + // Not [`crate::domain::cap::touch_and_create`], which is the same shape + // for a bare `CREATE`: a grade is an UPSERT (a regrade must overwrite), + // and the freeze stamp and the grader's counter have to ride the same + // transaction, which that helper has no room for. + // + // Sound to re-send, which is what the gate needed first — a `THROW` + // inside a plain `db.query` would have turned every lost round into a + // 500. `SELECT`, `UPDATE` and the `IF`/`THROW` can never answer "already + // exists", and the `UPSERT`'s id is bijective with the (homework, user) + // pair the table keys, on a table whose only index is non-unique + // (`homework_result_homework`), so its index entry can only ever point + // at the row the id already names: it resolves onto that row instead of + // colliding with it. A lost round wrote nothing. + let (mut saved, mut errors) = transaction_with_retry( + db, + &format!( "BEGIN TRANSACTION; + LET $was_due = (SELECT VALUE due_at FROM ONLY $hw); + LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id); + IF array::len($alive) = 0 {{ THROW 'no_homework' }}; + UPDATE $hw SET due_at = $was_due; LET $before = (SELECT VALUE id FROM ONLY $id); LET $after = (UPSERT $id CONTENT $row RETURN AFTER); UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = $id \ @@ -193,17 +219,32 @@ impl HomeworkResult { }}; RETURN $after; COMMIT TRANSACTION;" - )) - .bind(("id", id.record())) - .bind(("sub", submission.record())) - .bind(("grader", graded_by.record())) - .bind(("row", result.into_value())) - .await? - .check()?; + ), + &[ + ("hw".into(), homework.record().into_value()), + ("id".into(), id.record().into_value()), + ("sub".into(), submission.record().into_value()), + ("grader".into(), graded_by.record().into_value()), + ("row".into(), result.into_value()), + ], + &["no_homework"], + ) + .await?; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the reason. + if errors + .values() + .any(|error| error.to_string().contains("no_homework")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } // The trailing `RETURN` is always the last statement before `COMMIT`, // so its slot follows the statement count instead of a hand-kept - // number — which the counter statement above would otherwise have - // shifted, silently handing back the stamp's row. + // number — which the gate above would otherwise have shifted, silently + // handing back something else. let slot = saved.num_statements().saturating_sub(2); saved .take::>(slot)? @@ -327,6 +368,38 @@ mod tests { use crate::constant::HOMEWORK_STATUSES; use surrealdb::types::Value; + /// A real homework row (with the course and subject it needs): the grade now + /// carries a parent gate, so a minted id nothing wrote is a `404` here, the + /// same way it already is for a submission. + async fn a_homework(db: &Database) -> HomeworkId { + use crate::domain::homework::{Homework, HomeworkTitle}; + use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; + + let course = crate::domain::course::a_test_course(db).await; + let subject = Subject::create( + &course, + SubjectName::try_new("topic").unwrap(), + SubjectDescription::try_new("").unwrap(), + db, + ) + .await + .unwrap(); + Homework::create( + &course, + subject.get_id(), + HomeworkTitle::try_new("essay").unwrap(), + None, + Timestamp::from_millis(1), + None, + &UserId::from_key("teacher"), + db, + ) + .await + .unwrap() + .get_id() + .clone() + } + #[tokio::test] async fn status_is_held_to_the_const_and_stores_as_a_bare_string() { // Enforcement lives in the newtype against HOMEWORK_STATUSES (the DDL @@ -344,7 +417,7 @@ mod tests { #[tokio::test] async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() { let db = crate::database::init_mem().await.unwrap(); - let homework = HomeworkId::from_key("01TESTHWAAAAAAAAAAAAAAAAAA"); + let homework = a_homework(&db).await; let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); @@ -406,7 +479,7 @@ mod tests { #[tokio::test] async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() { let db = crate::database::init_mem().await.unwrap(); - let homework = HomeworkId::from_key("01TESTHWBADGEAAAAAAAAAAAAA"); + let homework = a_homework(&db).await; let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); // `UPDATE` writes nothing to a user row that does not exist. @@ -443,7 +516,7 @@ mod tests { #[tokio::test] async fn ungrading_gives_the_grader_credit_back() { let db = crate::database::init_mem().await.unwrap(); - let homework = HomeworkId::from_key("01TESTHWUNGRADEAAAAAAAAAAA"); + let homework = a_homework(&db).await; let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); db.query("CREATE $usr SET username = 't', password_hash = 'x'") diff --git a/src/domain/homework_submission.rs b/src/domain/homework_submission.rs index e787f86..e02b3ab 100644 --- a/src/domain/homework_submission.rs +++ b/src/domain/homework_submission.rs @@ -138,6 +138,21 @@ impl HomeworkSubmission { /// gave back something other than what was taken. Writing the verdict beside /// the counter is what keeps the two from ever disagreeing — read back by /// [`HomeworkSubmission::delete`], never re-derived. + /// + /// The first three statements are the parent gate, and they are why this + /// write cannot outlive its homework: the id is deterministic, so nothing + /// else here would fail against a homework a cascade already removed — it + /// would simply re-create the row, badge counters and all, unreachable ever + /// after (every route to a submission goes through its homework). A *read* + /// of the homework does not close that, on either side of the call: the + /// store does no read-set conflict detection, so a delete committing + /// alongside is invisible to it. The gate therefore *moves* a value on the + /// homework row — `due_at` up by one and straight back to the captured + /// value, so the row is byte-identical afterwards — because only a write + /// collides, and `SET x = x` is elided and never reaches the write set. It + /// is [`crate::domain::exam_answer::ExamAnswer::save`]'s shape exactly. + /// `Err(NotFound)` means the homework is gone, which is the 404 the web + /// layer's own lookup would have answered. pub async fn upsert( homework: &Homework, user: &UserId, @@ -149,11 +164,15 @@ impl HomeworkSubmission { let text = text.map(|text| text.as_str().to_string()); // Sound to re-send: the UPSERT is on a deterministic id on a table with // no unique index, so it can never legitimately answer "already exists", - // and the counter UPDATE never can either. + // and the counter UPDATEs never can either. let (mut saved, mut errors) = transaction_with_retry( db, &format!( "BEGIN TRANSACTION; + LET $was_due = (SELECT VALUE due_at FROM ONLY $hw); + LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id); + IF array::len($alive) = 0 {{ THROW 'no_homework' }}; + UPDATE $hw SET due_at = $was_due; LET $before = (SELECT VALUE id FROM ONLY $id); LET $on_time = $now <= $due; LET $after = (UPSERT $id SET homework = $hw, user = $usr, text = $text, @@ -177,9 +196,17 @@ impl HomeworkSubmission { ("now".into(), now.into_value()), ("due".into(), homework.get_due_at().into_value()), ], - &[], + &["no_homework"], ) .await?; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the reason. + if errors + .values() + .any(|error| error.to_string().contains("no_homework")) + { + return Err(AppError::NotFound); + } if let Some(error) = errors.drain().map(|(_, error)| error).next() { return Err(error.into()); } @@ -334,14 +361,13 @@ impl HomeworkSubmission { mod tests { use super::*; - use crate::domain::course::CourseId; use crate::domain::homework::HomeworkTitle; use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; /// A real homework row (and the subject it must reference) due at `due_at` — /// `upsert` now reads the deadline off the entity, so the tests need one. async fn a_homework(due_at: Timestamp, db: &Database) -> Homework { - let course = CourseId::from_key("course"); + let course = crate::domain::course::a_test_course(db).await; let subject = Subject::create( &course, SubjectName::try_new("topic").unwrap(), diff --git a/src/web/courses.rs b/src/web/courses.rs index 48157fe..b360b5a 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -535,9 +535,18 @@ async fn delete_course( // the student's row, never the exam's). Narrower here — the delete is // refused while anyone is enrolled, so a start would have to pass its // enrollment gate and then have that enrollment removed under it — but the - // hole is the same one and so is the lease. Nothing on this path takes - // another lock, so it introduces no ordering pair. + // hole is the same one and so is the lease. let _guard = crate::web::exams::EXAM_LOCK.write().await; + // And the homework half of the same cascade, for + // [`crate::web::homework::delete_homework`]'s reason: it sweeps the + // course's homework with its submissions, files and results, and grading + // ([`crate::domain::homework_result::HomeworkResult::grade`]) writes a + // result row against a homework it only *read*, which a delete committing + // alongside is invisible to. Without this lease the grade lands behind the + // sweep: an orphan `homework_result` under a vanished homework, plus a + // `marks_given_total` on the grader no ungrade can reach. Lock order here + // is EXAM_LOCK then HOMEWORK_LOCK, the only path that takes both. + let _homework_guard = crate::web::homework::HOMEWORK_LOCK.write().await; // Rows go first (the delete cascades them), blobs after — a crash in // between strands at worst an unreachable blob. The keys are read before // the delete because it takes their rows with it; a refused delete just @@ -1119,7 +1128,8 @@ async fn create_homework_in_course( /// List a course's homework, newest first, paged via `?limit=&offset=` (omit /// `limit` for all of it). Visible to the course's enrolled users, its creator, /// its assigned teachers, and managers/admins — but a student sees only the -/// homework they are assigned (whole-course ones plus subsets that name them). +/// homework they are assigned (whole-course ones plus subsets that name them, +/// each with its `assigned` narrowed to themselves). /// Returns a `{items, total, limit, offset}` envelope. #[utoipa::path( get, @@ -1153,14 +1163,23 @@ async fn list_course_homework( } let mut homework = Homework::list_for_course(course.get_id(), &st.db).await?; // A student sees only the homework they are assigned; managers see all. - if !can_manage_course(&course, &user) { + let manages = can_manage_course(&course, &user); + if !manages { homework.retain(|hw| hw.student_sees(user.get_id())); } let total = homework.len() as i64; - // Paged in the web layer: the audience filter above is per-row Rust. + // Paged in the web layer: the audience filter above is per-row Rust. A + // subset roster goes out whole only to a manager of the course; a student + // sees themselves in it and no one else. let items = paginate(&homework, limit, offset) .iter() - .map(HomeworkResponse::new) + .map(|hw| { + if manages { + HomeworkResponse::new(hw) + } else { + HomeworkResponse::for_viewer(hw, user.get_id()) + } + }) .collect(); Ok(Json(Page::new(items, total, limit, offset))) } diff --git a/src/web/dto.rs b/src/web/dto.rs index 2ff241a..5540ecf 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -270,7 +270,10 @@ pub struct HomeworkResponse { /// When the homework is due, UTC unix-milliseconds. #[schema(example = 1_900_000_000_000_i64)] pub due_at: i64, - /// The assigned student ids, or `null` for the whole enrolled course. + /// The assigned student ids, or `null` for the whole enrolled course. Only + /// a viewer who manages the course sees the whole subset; to anyone else it + /// is narrowed to their own id (the course roster is teacher+-only, so a + /// subset assignment must not hand out the names it lists). pub assigned: Option>, /// Who assigned the homework. pub created_by: String, @@ -294,6 +297,18 @@ impl HomeworkResponse { created_at: homework.get_created_at().as_millis(), } } + + /// The same homework as seen by a viewer who does *not* manage its course. + /// A subset roster is narrowed to `viewer` alone: they learn that they are + /// named — which is why the homework reached them at all — and nothing + /// about who else is. Whole-course (`null`) stays `null`; every read path + /// that uses this has already refused a viewer the subset does not name + /// (404), so a one-element list is never a lie. + pub fn for_viewer(homework: &Homework, viewer: &UserId) -> Self { + let mut response = Self::new(homework); + response.assigned = response.assigned.map(|_| vec![viewer.key().to_string()]); + response + } } /// Public shape of a course session (one lesson). Shared by `courses` diff --git a/src/web/homework.rs b/src/web/homework.rs index 7a68697..f421aa1 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -59,9 +59,13 @@ use super::{ /// /// What still leases it, honestly: /// - Write: the homework PATCH's orphan guard ([`update_homework`]), the -/// homework-delete cascade ([`delete_homework`]), and grade/ungrade — which -/// read the homework itself under the lease so a concurrent delete can't -/// leave a result row under a vanished homework. +/// homework-delete cascade ([`delete_homework`]), and grade/ungrade — whose +/// freeze rule (the stamp landing on a submission that may be written in the +/// same instant) is the one thing here still resting on the two leases being +/// mutually exclusive. The *existence* half has left: a grade now moves a +/// value on the homework row inside its own transaction +/// ([`crate::domain::homework_result::HomeworkResult::grade`]), so a +/// concurrent delete refuses it rather than being read around. /// - Read: the student's submission/file writes, which no longer gate the /// freeze but still must not land under a PATCH re-scoping the audience out /// from under them. @@ -171,7 +175,8 @@ async fn homework_with_course(id: &str, db: &Database) -> Result<(Homework, Cour /// paged via `?limit=&offset=` (omit `limit` for all of it). Manager+ see every /// course's homework; a teacher sees the homework of courses they run; a /// student sees only the homework they are assigned (whole-course ones plus any -/// subset that names them). Returns a `{items, total, limit, offset}` envelope. +/// subset that names them, each with its `assigned` narrowed to themselves). +/// Returns a `{items, total, limit, offset}` envelope. #[utoipa::path( get, path = "/", @@ -190,7 +195,11 @@ async fn list_homework( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let homework = if user.get_role().at_least(Role::Manager) { + // The courses this caller manages — empty for a manager+, who manages all + // of them, and who is told apart by this flag. + let manages_all = user.get_role().at_least(Role::Manager); + let mut managed: Vec = Vec::new(); + let homework = if manages_all { Homework::list_all(&st.db).await? } else { let courses = visible_courses(&user, &st.db).await?; @@ -201,22 +210,31 @@ async fn list_homework( // A student sees only the homework they are assigned; a teacher who // manages a course sees all of its homework (the manager+ path above // already saw everything). - let managed: Vec<&str> = courses + managed = courses .iter() .filter(|course| can_manage_course(course, &user)) - .map(|course| course.get_id().key()) + .map(|course| course.get_id().key().to_string()) .collect(); let mut homework = Homework::list_for_courses(&ids, &st.db).await?; homework.retain(|hw| { - managed.contains(&hw.get_course().key()) || hw.student_sees(user.get_id()) + managed.iter().any(|key| key == hw.get_course().key()) || hw.student_sees(user.get_id()) }); homework }; let total = homework.len() as i64; - // Paged in the web layer: the audience filter above is per-row Rust. + // Paged in the web layer: the audience filter above is per-row Rust. The + // subset roster rides along only for the rows the caller manages — to a + // student it is narrowed to themselves, as it is on the single-homework + // read. let items = paginate(&homework, limit, offset) .iter() - .map(HomeworkResponse::new) + .map(|hw| { + if manages_all || managed.iter().any(|key| key == hw.get_course().key()) { + HomeworkResponse::new(hw) + } else { + HomeworkResponse::for_viewer(hw, user.get_id()) + } + }) .collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -225,7 +243,9 @@ async fn list_homework( /// enrolled users, creator, assigned teachers, and managers/admins). A student /// the homework is *not* assigned to gets a 404 — the same no-leak an unseen /// exam draft gets, so a subset assignment never reveals itself to the students -/// left out of it. +/// left out of it. To a caller without course-management rights the `assigned` +/// subset comes back narrowed to their own id: being named is theirs to know, +/// the rest of the roster is not. #[utoipa::path( get, path = "/{id}", @@ -252,10 +272,17 @@ async fn get_homework( } // A student the homework is not assigned to must not even learn it exists — // 404, not 403, exactly like an exam draft hidden from non-managers. - if !can_manage_course(&course, &user) && !homework.student_sees(user.get_id()) { + let manages = can_manage_course(&course, &user); + if !manages && !homework.student_sees(user.get_id()) { return Err(AppError::NotFound); } - Ok(Json(HomeworkResponse::new(&homework))) + // ... and one it *is* assigned to must not hand them the rest of the + // subset: the same no-leak, one step further in. + Ok(Json(if manages { + HomeworkResponse::new(&homework) + } else { + HomeworkResponse::for_viewer(&homework, user.get_id()) + })) } #[derive(Deserialize, ToSchema)] @@ -851,7 +878,10 @@ async fn upload_submission_file( Path(id): Path, mut multipart: Multipart, ) -> Result<(StatusCode, Json), AppError> { - let homework = gate_own_submission(&id, &user, &st.db).await?; + // Pre-flight, so a caller with no business here is refused before uploading + // 25 MiB; the gate that *licenses the write* is the one under the lease + // below, because this snapshot goes stale while the body streams. + gate_own_submission(&id, &user, &st.db).await?; let limit = Settings::load(&st.db).await?.get_max_file_bytes(); // Consume the body before taking the lock — a slow upload must not stall the // homework subsystem (mirrors the exam/note image uploads). @@ -866,6 +896,14 @@ async fn upload_submission_file( // Taken before the cap claim inside `insert`, never after (the lock order // is HOMEWORK_LOCK, then the counter lock). let _guard = HOMEWORK_LOCK.read().await; + // Re-read the homework *under* the lease. Streaming the body takes as long + // as the client wants it to, and a homework delete (a writer) both takes + // and releases its lease inside that window — so the pre-flight snapshot + // can name a homework that no longer exists, and this handler would then + // auto-create a submission, credit the badge counters and write a file + // under it, all unreachable afterwards. A gate read before the body is a + // pre-flight; a gate read after it is the decision. + let homework = gate_own_submission(&id, &user, &st.db).await?; // The common-case gate; the freeze itself rides on the writes below. if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db) .await? diff --git a/tests/regress_homework_orphans.rs b/tests/regress_homework_orphans.rs new file mode 100644 index 0000000..343ad40 --- /dev/null +++ b/tests/regress_homework_orphans.rs @@ -0,0 +1,740 @@ +//! Regressions for the four holes the 2026-08-05 hunt left on the homework +//! surface: a file upload that outlived its homework, a course delete that +//! swept homework without holding the homework lease, a subset assignment that +//! handed every named student the whole roster, and a file delete that answered +//! a lost round with a 500. +//! +//! Two of them share one root cause and one shape of fix: a child keyed by a +//! deterministic id does not fail against a parent a cascade removed, it +//! *re-creates* it — so both the submission and the grade now move a value on +//! the homework row inside their own transaction, and the two domain-level +//! tests here (`a_submission_under_a_vanished_homework_is_refused`, +//! `a_grade_under_a_vanished_homework_is_refused`) are what pin those gates. +//! The lock-level races pin the handlers. +//! +//! Every race here is judged on the *store*, never on what a request answered: +//! the in-memory engine forges wins under concurrency (src/domain/cap.rs), so a +//! 404 or a 204 is evidence of nothing. The windows are opened by the database +//! itself — a `DEFINE EVENT` on the table under write fires *inside* the +//! writing transaction — rather than by a lucky interleaving. + +mod common; + +use axum::http::StatusCode; +use common::{ + app_and_db, create_course, create_homework, create_homework_with, create_subject, enroll, + id_of, items, login_as, me_id, multipart_file, send, send_raw, unenroll, +}; +use hezarfen_backend::database::Database; +use serde_json::{Value, json}; +use surrealdb::types::RecordId; + +/// `HOMEWORK_LOCK` is process-wide, and every race below holds a lease of it +/// for seconds. Two of them running at once starve each other's window — the +/// second one's gates then run *after* the staging meant to happen inside them, +/// and the test judges an interleaving that never happened. One at a time; the +/// deterministic tests need no ticket. +static ONE_RACE_AT_A_TIME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +/// A due date comfortably clear of the 60s past-scheduling grace. +fn far_future() -> i64 { + hezarfen_backend::domain::timestamp::Timestamp::now().as_millis() + 7_200_000 +} + +/// How many rows `sql` selects ids for — the stored state, out of the store. +async fn rows(db: &Database, sql: &str) -> usize { + let mut result = db.query(sql).await.unwrap().check().unwrap(); + result.take::>(0).unwrap().len() +} + +/// One integer field off one user row, absent counting as zero. +async fn counter(db: &Database, user: &str, field: &str) -> i64 { + let mut result = db + .query(format!( + "SELECT VALUE ({field} ?? 0) FROM type::record('user', $key)" + )) + .bind(("key", user.to_string())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap_or(0) +} + +/// Upload `bytes` onto the caller's submission to `hw` — no assertion. +async fn upload_hw_file(app: &axum::Router, cookie: &str, hw: &str) -> StatusCode { + let (status, _, _) = send_raw( + app, + "POST", + &format!("/homework/{hw}/submission/files"), + Some(cookie), + Some("multipart/form-data; boundary=hezarfen-test-boundary"), + multipart_file("odev.pdf", "application/pdf", b"homework bytes"), + ) + .await; + status +} + +/// A course with one subject and one enrolled student. Returns +/// `(course, subject, student cookie, student id)`. +async fn course_with_student( + app: &axum::Router, + db: &Database, + teacher: &str, + name: &str, +) -> (String, String, String, String) { + let student = login_as(app, db, &format!("ogrenci_{name}"), "student").await; + let student_id = me_id(app, &student).await; + let course = create_course(app, teacher, name).await; + let subject = create_subject(app, teacher, &course, "konu").await; + enroll(app, teacher, &course, &student_id).await; + (course, subject, student, student_id) +} + +/// The upload streams its body *before* it takes `HOMEWORK_LOCK`, and the +/// homework snapshot it acts on was read before that stream — so a delete +/// (which takes and releases the write lease inside that window) leaves the +/// handler holding a homework that is gone. It then auto-created a submission +/// under it, credited both badge counters, wrote a blob and a file row, and +/// answered `201`. Every route to any of that goes through the vanished +/// homework, so nothing could ever read or delete it again, and the counters +/// stayed up for good. +/// +/// The window is the delete's own: a `DEFINE EVENT` on `homework` holds its +/// transaction open after the cascade has swept the children, which is exactly +/// the interleaving — the upload's gate read lands inside it (the row is +/// deleted but uncommitted, so it still reads), and its write lands after. The +/// upload's own duration is asserted too: one that arrived after the delete had +/// already committed would be answered by a plain lookup and leave this test +/// green over the hole. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_upload_inside_a_homework_delete_never_orphans() { + let _serial = ONE_RACE_AT_A_TIME.lock().await; + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ogretmen_odev", "teacher").await; + let (course, subject, student, student_id) = + course_with_student(&app, &db, &teacher, "fizik").await; + let hw = create_homework(&app, &teacher, &course, &subject, "deneme", far_future()).await; + + // Hold the delete open once the cascade has run but before it commits. + db.query( + "DEFINE EVENT hold_the_window ON TABLE homework WHEN $event = 'DELETE' \ + THEN { SLEEP 3s; };", + ) + .await + .expect("define the window event") + .check() + .expect("check the window event"); + + let drop_it = { + let (app, teacher, hw) = (app.clone(), teacher.clone(), hw.clone()); + tokio::spawn(async move { + send( + &app, + "DELETE", + &format!("/homework/{hw}"), + Some(&teacher), + None, + ) + .await + }) + }; + // The upload fires inside the held window: its gate reads a homework the + // delete has removed but not committed. + tokio::time::sleep(std::time::Duration::from_millis(1_000)).await; + let uploaded = { + let (app, student, hw) = (app.clone(), student.clone(), hw.clone()); + tokio::spawn(async move { + let started = std::time::Instant::now(); + (upload_hw_file(&app, &student, &hw).await, started.elapsed()) + }) + }; + let (dropped, (upload_status, took)) = (drop_it.await.unwrap(), uploaded.await.unwrap()); + + assert!( + took >= std::time::Duration::from_secs(1), + "the upload never contended with the delete ({took:?}): nothing was raced" + ); + assert_eq!( + dropped.status, + StatusCode::NO_CONTENT, + "the delete must succeed: {:?}", + dropped.body + ); + // A 404 is the correct answer for the upload; the only defect is stored + // state. Nothing may 500 either way. + assert!( + upload_status == StatusCode::NOT_FOUND || upload_status.is_success(), + "a raced upload must be answered, not {upload_status}" + ); + + // Stored state is the whole verdict. + assert_eq!( + rows(&db, "SELECT VALUE id FROM homework_submission").await, + 0, + "a submission outlived its homework" + ); + assert_eq!( + rows(&db, "SELECT VALUE id FROM homework_file").await, + 0, + "a file outlived its homework" + ); + assert_eq!( + counter(&db, &student_id, "homework_submitted_total").await, + 0, + "a hand-in nothing can reach still counted" + ); + assert_eq!( + counter(&db, &student_id, "homework_on_time_total").await, + 0, + "... and counted as punctual" + ); +} + +/// The other half of the same misplaced gate, and the half no domain guard can +/// cover: the homework is still there, only the *audience* moved. A PATCH +/// re-scoping `assigned` holds the write lease across its orphan check, which +/// finds no submission and allows the narrowing; the upload, whose audience +/// check ran on a snapshot read before its body streamed, then lands a +/// submission and a file for a student the homework no longer names — the exact +/// orphan `ensure_no_orphans` exists to refuse. +/// +/// The lease is the interleaving: a `DEFINE EVENT` on `homework` holds the +/// PATCH's write open, the upload's pre-flight gate reads the old audience +/// inside that window, and its own lease is granted only once the new audience +/// is committed. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_upload_inside_an_audience_patch_is_refused() { + let _serial = ONE_RACE_AT_A_TIME.lock().await; + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ogretmen_kapsam", "teacher").await; + let course = create_course(&app, &teacher, "Coğrafya").await; + let subject = create_subject(&app, &teacher, &course, "iklim").await; + let dropped_student = login_as(&app, &db, "ogrenci_cikan", "student").await; + let dropped_id = me_id(&app, &dropped_student).await; + let kept = login_as(&app, &db, "ogrenci_kalan", "student").await; + let kept_id = me_id(&app, &kept).await; + enroll(&app, &teacher, &course, &dropped_id).await; + enroll(&app, &teacher, &course, &kept_id).await; + let res = create_homework_with( + &app, + &teacher, + &course, + json!({ + "title": "harita", + "subject_id": subject, + "due_at": far_future(), + "assigned": [dropped_id.clone(), kept_id.clone()], + }), + ) + .await; + assert_eq!( + res.status, + StatusCode::CREATED, + "create the subset homework" + ); + let hw = id_of(&res.body); + + db.query( + "DEFINE EVENT hold_the_patch ON TABLE homework WHEN $event = 'UPDATE' \ + THEN { SLEEP 3s; };", + ) + .await + .expect("define the window event") + .check() + .expect("check the window event"); + + let narrowing = { + let (app, teacher, hw, kept_id) = + (app.clone(), teacher.clone(), hw.clone(), kept_id.clone()); + tokio::spawn(async move { + send( + &app, + "PATCH", + &format!("/homework/{hw}"), + Some(&teacher), + Some(json!({ "assigned": [kept_id] })), + ) + .await + }) + }; + tokio::time::sleep(std::time::Duration::from_millis(1_000)).await; + let uploaded = { + let (app, cookie, hw) = (app.clone(), dropped_student.clone(), hw.clone()); + tokio::spawn(async move { + let started = std::time::Instant::now(); + (upload_hw_file(&app, &cookie, &hw).await, started.elapsed()) + }) + }; + let (patched, (upload_status, took)) = (narrowing.await.unwrap(), uploaded.await.unwrap()); + + assert!( + took >= std::time::Duration::from_secs(1), + "the upload never contended with the PATCH ({took:?}): nothing was raced" + ); + assert_eq!( + patched.status, + StatusCode::OK, + "the narrowing must land: {:?}", + patched.body + ); + assert_eq!( + upload_status, + StatusCode::NOT_FOUND, + "a student the homework no longer names must be answered 404" + ); + assert_eq!( + rows(&db, "SELECT VALUE id FROM homework_submission").await, + 0, + "a submission landed for a student outside the audience" + ); + assert_eq!( + rows(&db, "SELECT VALUE id FROM homework_file").await, + 0, + "... with a file on it" + ); +} + +/// The same hole one layer down, where the lock cannot reach it: a submission +/// write must collide with its homework's delete on the *store*, not merely +/// read the row first. `HomeworkSubmission::upsert` writes a deterministic id, +/// so with the parent gate removed it does not fail against a vanished +/// homework — it re-creates the row it was meant to be refused, badge counters +/// and all. +/// +/// Driven at the domain layer on purpose: it is the guarantee that survives the +/// web layer's lock discipline being loosened again, so no handler may be in +/// the way of it. The delete lands first here — the interleaving pinned rather +/// than hoped for — which is precisely the state a lease that stops too early +/// leaves behind. +#[tokio::test] +async fn a_submission_under_a_vanished_homework_is_refused() { + use hezarfen_backend::domain::homework::{Homework, HomeworkId}; + use hezarfen_backend::domain::homework_submission::HomeworkSubmission; + use hezarfen_backend::domain::user::UserId; + + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ogretmen_alan", "teacher").await; + let (course, subject, student, student_id) = + course_with_student(&app, &db, &teacher, "kimya").await; + let hw = create_homework(&app, &teacher, &course, &subject, "deneme", far_future()).await; + // The stale snapshot a handler would still be holding. + let stale = Homework::read(&HomeworkId::from_key(&hw), &db) + .await + .unwrap() + .expect("the homework exists"); + let user = UserId::from_key(&student_id); + + let dropped = send( + &app, + "DELETE", + &format!("/homework/{hw}"), + Some(&teacher), + None, + ) + .await; + assert_eq!( + dropped.status, + StatusCode::NO_CONTENT, + "delete the homework" + ); + + let refused = HomeworkSubmission::upsert(&stale, &user, None, &db).await; + assert!( + refused.is_err(), + "a submission to a homework that is gone must be refused, got {refused:?}" + ); + assert_eq!( + rows(&db, "SELECT VALUE id FROM homework_submission").await, + 0, + "the refused write must leave no row" + ); + assert_eq!( + counter(&db, &student_id, "homework_submitted_total").await, + 0, + "... and no counter" + ); + // The student's own route agrees, so the refusal is a 404 and not a 500. + let over_http = send( + &app, + "POST", + &format!("/homework/{hw}/submission"), + Some(&student), + Some(json!({ "text": "geç kaldım" })), + ) + .await; + assert_eq!(over_http.status, StatusCode::NOT_FOUND); +} + +/// The grade's own twin of the gate above, and the reason `delete_course`'s +/// homework lease is no longer the only thing standing between a grade and an +/// orphan: `HomeworkResult::grade` writes a deterministic id too, so against a +/// homework a cascade already removed it used to succeed — a `homework_result` +/// row nothing can reach (`GET /homework/{id}/result` has no existence check of +/// its own) plus a `marks_given_total` on the grader that no ungrade can give +/// back, since the ungrade route 404s on the vanished homework first. +/// +/// Domain-level and sequential on purpose: the guarantee under test is the one +/// that holds when the lease does not, so no handler may be in the way of it. +#[tokio::test] +async fn a_grade_under_a_vanished_homework_is_refused() { + use hezarfen_backend::domain::homework::HomeworkId; + use hezarfen_backend::domain::homework_result::{HomeworkResult, HomeworkStatus}; + use hezarfen_backend::domain::user::UserId; + + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ogretmen_not", "teacher").await; + let teacher_id = me_id(&app, &teacher).await; + let (course, subject, _student, student_id) = + course_with_student(&app, &db, &teacher, "muzik").await; + let hw = create_homework(&app, &teacher, &course, &subject, "solfej", far_future()).await; + + let dropped = send( + &app, + "DELETE", + &format!("/homework/{hw}"), + Some(&teacher), + None, + ) + .await; + assert_eq!( + dropped.status, + StatusCode::NO_CONTENT, + "delete the homework" + ); + + // The ids a handler mid-request would still be carrying. + let refused = HomeworkResult::grade( + &HomeworkId::from_key(&hw), + &UserId::from_key(&student_id), + HomeworkStatus::try_new("done").unwrap(), + None, + &UserId::from_key(&teacher_id), + &db, + ) + .await; + assert!( + refused.is_err(), + "a grade on a homework that is gone must be refused, got {refused:?}" + ); + assert_eq!( + rows(&db, "SELECT VALUE id FROM homework_result").await, + 0, + "the refused write must leave no row" + ); + assert_eq!( + counter(&db, &teacher_id, "marks_given_total").await, + 0, + "... and no credit on the grader" + ); + // The teacher's own route agrees: a 404, never a 500. + let over_http = send( + &app, + "POST", + &format!("/homework/{hw}/results"), + Some(&teacher), + Some(json!({ "user": student_id, "status": "done" })), + ) + .await; + assert_eq!(over_http.status, StatusCode::NOT_FOUND); +} + +/// `delete_course` took `EXAM_LOCK` and nothing else, while its cascade sweeps +/// the course's homework, submissions, files and results. Grading holds +/// `HOMEWORK_LOCK.write()` across a transaction that only *reads* the homework, +/// and the store conflict-checks write sets rather than read sets — so the +/// sweep ran on a snapshot without the grade and both committed: an orphan +/// `homework_result` under a vanished homework, readable ever after at +/// `GET /homework/{id}/result`, which has no existence check of its own. +/// +/// The window is the grade's, not the delete's: a course delete is refused +/// while anyone is enrolled, so the roster has to empty *while* the grade is +/// mid-write — a `DEFINE EVENT` on `homework_result` holds it, gates already +/// passed, across the unenroll and the delete that follow. The grade's own +/// duration is asserted, because a grade that never reached its window would +/// leave this suite green over the very hole it exists for. +/// +/// `marks_given_total` is deliberately *not* asserted at zero: no cascade ever +/// gives that counter back (the 08-05 sweep left that standing on purpose), so +/// a grade this test serializes *ahead* of the delete keeps its credit exactly +/// as an uncontested grade followed by a course delete does. +/// +/// What this pins, honestly: **the outcome, not the lease**. With the lease it +/// passes because the grade is serialized ahead of the cascade and answered +/// `200`; with the lease removed it passes because +/// [`HomeworkResult::grade`]'s parent gate refuses the late write and answers +/// `404` (measured: 404 after a full 3s window). So removing *either* guard +/// alone leaves this green and only removing both turns it red — the same +/// belt-and-braces shape the upload race above has. The lease's own mutation +/// test died with the gate that replaced it; nothing else pins it, which is +/// why it is kept and documented rather than trusted to a red test. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_grade_inside_a_course_delete_never_orphans() { + let _serial = ONE_RACE_AT_A_TIME.lock().await; + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ogretmen_ders", "teacher").await; + let (course, subject, _student, student_id) = + course_with_student(&app, &db, &teacher, "tarih").await; + let hw = create_homework(&app, &teacher, &course, &subject, "ödev", far_future()).await; + + // Hold the grade's own write open, every gate already cleared. Three + // seconds against a one-second wait below: under a loaded test binary the + // spawned request can take a while to be polled at all, and the window has + // to still be open when it gets there. + db.query( + "DEFINE EVENT hold_the_grade ON TABLE homework_result WHEN $event = 'CREATE' \ + THEN { SLEEP 3s; };", + ) + .await + .expect("define the window event") + .check() + .expect("check the window event"); + + let grading = { + let (app, teacher, hw, target) = + (app.clone(), teacher.clone(), hw.clone(), student_id.clone()); + tokio::spawn(async move { + let started = std::time::Instant::now(); + let res = send( + &app, + "POST", + &format!("/homework/{hw}/results"), + Some(&teacher), + Some(json!({ "user": target, "status": "done", "mark": 90 })), + ) + .await; + (res, started.elapsed()) + }) + }; + tokio::time::sleep(std::time::Duration::from_millis(1_000)).await; + // The roster empties mid-grade — the only staging in which the course + // delete is admitted at all. + unenroll(&app, &teacher, &course, &student_id).await; + let dropped = send( + &app, + "DELETE", + &format!("/courses/{course}"), + Some(&teacher), + None, + ) + .await; + let (graded, took) = grading.await.unwrap(); + + assert!( + took >= std::time::Duration::from_secs(3), + "the grade never reached its window ({took:?}, answered {}): nothing was raced", + graded.status + ); + assert_eq!( + dropped.status, + StatusCode::NO_CONTENT, + "the course delete must succeed: {:?}", + dropped.body + ); + assert!( + graded.status.is_success() || graded.status == StatusCode::NOT_FOUND, + "a raced grade must be answered, not {}: {:?}", + graded.status, + graded.body + ); + + // Stored state is the whole verdict. + assert_eq!( + rows(&db, "SELECT VALUE id FROM homework").await, + 0, + "the homework survived its course" + ); + assert_eq!( + rows(&db, "SELECT VALUE id FROM homework_result").await, + 0, + "a grade outlived the homework it was written against" + ); +} + +/// A subset assignment is the one place the homework routes hand a student a +/// list of other students. The course roster itself is teacher+-only, and +/// `get_homework` already 404s a student the subset does not name "so a subset +/// assignment never reveals itself" — but to the students it *does* name it +/// used to serialize the whole list. Deterministic, no race: the response body +/// is the defect. +#[tokio::test] +async fn a_student_sees_only_themselves_in_an_assigned_subset() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ogretmen_liste", "teacher").await; + let course = create_course(&app, &teacher, "Biyoloji").await; + let subject = create_subject(&app, &teacher, &course, "hücre").await; + let ali = login_as(&app, &db, "ali", "student").await; + let ali_id = me_id(&app, &ali).await; + let veli = login_as(&app, &db, "veli", "student").await; + let veli_id = me_id(&app, &veli).await; + enroll(&app, &teacher, &course, &ali_id).await; + enroll(&app, &teacher, &course, &veli_id).await; + + let res = create_homework_with( + &app, + &teacher, + &course, + json!({ + "title": "sunum", + "subject_id": subject, + "due_at": far_future(), + "assigned": [ali_id.clone(), veli_id.clone()], + }), + ) + .await; + assert_eq!( + res.status, + StatusCode::CREATED, + "create the subset homework" + ); + let hw = id_of(&res.body); + + let assigned = |body: &Value| -> Vec { + body["assigned"] + .as_array() + .expect("assigned is a list on a subset homework") + .iter() + .map(|v| v.as_str().unwrap().to_string()) + .collect() + }; + + // The single read. + let mine = send(&app, "GET", &format!("/homework/{hw}"), Some(&ali), None).await; + assert_eq!(mine.status, StatusCode::OK); + assert_eq!( + assigned(&mine.body), + vec![ali_id.clone()], + "a student may learn they are assigned, never who else is" + ); + + // ... the cross-course list ... + let listed = send(&app, "GET", "/homework", Some(&ali), None).await; + assert_eq!(listed.status, StatusCode::OK); + assert_eq!(assigned(&items(&listed.body)[0]), vec![ali_id.clone()]); + + // ... and the per-course one. + let in_course = send( + &app, + "GET", + &format!("/courses/{course}/homework"), + Some(&ali), + None, + ) + .await; + assert_eq!(in_course.status, StatusCode::OK); + assert_eq!(assigned(&items(&in_course.body)[0]), vec![ali_id.clone()]); + + // The teacher who runs the course still sees the roster whole — narrowing + // it for them would break the audience they just set. + let theirs = send( + &app, + "GET", + &format!("/homework/{hw}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(theirs.status, StatusCode::OK); + let mut named = assigned(&theirs.body); + named.sort(); + let mut both = vec![ali_id, veli_id]; + both.sort(); + assert_eq!(named, both, "the assigning teacher keeps the whole subset"); +} + +/// A file add and a file delete on one submission write the same row — the +/// upload claims its seat on it, the delete re-stamps it — and both handlers +/// hold only `HOMEWORK_LOCK.read()`, so they contend by design. The delete sent +/// its cascade through a plain `db.query`, unlike every sibling in the module, +/// so a lost round came back as a 500 on a request that had written nothing. +/// +/// The window is the *delete's* own — the retry-less side has to be the one +/// holding a stale write when the other commits, or nothing it does can be +/// answered "conflict, retry": a `DEFINE EVENT` on `homework_file` holds the +/// delete's transaction open after it has re-stamped the submission row, and an +/// upload lands on that same row inside it. Held short (150ms): the retry +/// budget is 8 tries over ~250ms of backoff, so a window wider than the budget +/// would fail a *correct* implementation too. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_file_add_racing_a_file_delete_never_500s() { + let _serial = ONE_RACE_AT_A_TIME.lock().await; + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ogretmen_dosya", "teacher").await; + let (course, subject, student, _student_id) = + course_with_student(&app, &db, &teacher, "resim").await; + let hw = create_homework(&app, &teacher, &course, &subject, "çizim", far_future()).await; + assert_eq!( + upload_hw_file(&app, &student, &hw).await, + StatusCode::CREATED, + "the first file" + ); + let listed = send( + &app, + "GET", + &format!("/homework/{hw}/submission"), + Some(&student), + None, + ) + .await; + let first = listed.body["files"][0]["id"].as_str().unwrap().to_string(); + + db.query( + "DEFINE EVENT hold_the_delete ON TABLE homework_file WHEN $event = 'DELETE' \ + THEN { SLEEP 150ms; };", + ) + .await + .expect("define the window event") + .check() + .expect("check the window event"); + + let removing = { + let (app, student, hw, first) = (app.clone(), student.clone(), hw.clone(), first.clone()); + tokio::spawn(async move { + send( + &app, + "DELETE", + &format!("/homework/{hw}/submission/files/{first}"), + Some(&student), + None, + ) + .await + }) + }; + // The upload commits on the submission row while the delete is still + // holding its own write of it. + tokio::time::sleep(std::time::Duration::from_millis(40)).await; + let added = upload_hw_file(&app, &student, &hw).await; + let removed = removing.await.unwrap(); + + assert_ne!( + removed.status, + StatusCode::INTERNAL_SERVER_ERROR, + "a lost round is a re-send, not a 500: {:?}", + removed.body + ); + assert_ne!( + added, + StatusCode::INTERNAL_SERVER_ERROR, + "... on either side" + ); + // Whatever the order, the stored count matches the stored rows: the + // submission's seat counter is what the cap reads next time. + let files = rows(&db, "SELECT VALUE id FROM homework_file").await; + let mut result = db + .query("SELECT VALUE (file_count ?? 0) FROM homework_submission") + .await + .unwrap() + .check() + .unwrap(); + let counted: Vec = result.take(0).unwrap(); + assert_eq!( + counted.first().copied().unwrap_or(0), + files as i64, + "the seat counter drifted from the rows" + ); +}