forge
Explore
Log in

Don't you dare go Hollow

Close the homework orphan window and the subset roster leak

Browse files at this commit

420deefcc0f6e2a08917280e25824439bacb8deaAhmet Kaan GümüşParent: 33b46b1
  • fix
    • close the homework orphan window and the subset roster leak
Show full message
📝 fix: close the homework orphan window and the subset roster leak

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.rsmodified+1 -1
@@ -422,7 +422,7 @@ mod tests {
422 422
423 async fn a_subject(name: &str, db: &Database) -> Subject {423 async fn a_subject(name: &str, db: &Database) -> Subject {
424 Subject::create(424 Subject::create(
425- &CourseId::from_key("course"),425+ &crate::domain::course::a_test_course(db).await,
426 SubjectName::try_new(name).unwrap(),426 SubjectName::try_new(name).unwrap(),
427 SubjectDescription::try_new("").unwrap(),427 SubjectDescription::try_new("").unwrap(),
428 db,428 db,
src/domain/homework_file.rsmodified+26 -11
@@ -15,7 +15,7 @@ use crate::constant::{
15 HOMEWORK_FILE_TABLE, MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD,15 HOMEWORK_FILE_TABLE, MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD,
16 SUBMISSION_OPEN_GUARD,16 SUBMISSION_OPEN_GUARD,
17 };17 };
18-use crate::database::Database;18+use crate::database::{Database, transaction_with_retry};
19 use crate::domain::cap;19 use crate::domain::cap;
20 use crate::domain::course::CourseId;20 use crate::domain::course::CourseId;
21 use crate::domain::homework::HomeworkId;21 use crate::domain::homework::HomeworkId;
@@ -268,9 +268,19 @@ impl HomeworkFile {
268 /// stamps first (this delete is refused, `Ok(None)`) or stamps after (the268 /// stamps first (this delete is refused, `Ok(None)`) or stamps after (the
269 /// file was already gone when it graded). `Err(NotFound)` still means the269 /// file was already gone when it graded). `Err(NotFound)` still means the
270 /// file row itself had vanished.270 /// file row itself had vanished.
271+ ///
272+ /// Sound to re-send while the store answers "conflict, retry", and it has
273+ /// to be: the gate writes the *submission* row, the very record an upload's
274+ /// [`HomeworkFile::insert`] claims its seat on, and both handlers hold only
275+ /// `HOMEWORK_LOCK.read()` — so a concurrent add and delete of two files of
276+ /// one submission contend by design, and a lost round used to come back as
277+ /// a 500 on a request that had written nothing. Only `UPDATE` and `DELETE`
278+ /// are in the batch, and neither can legitimately answer "already exists",
279+ /// which is what makes the whole of it re-sendable.
271 pub async fn delete(self, db: &Database) -> Result<Option<HomeworkFile>, AppError> {280 pub async fn delete(self, db: &Database) -> Result<Option<HomeworkFile>, AppError> {
272- let mut result = db281+ let (mut result, mut errors) = transaction_with_retry(
273- .query(format!(282+ db,
283+ &format!(
274 "BEGIN TRANSACTION;284 "BEGIN TRANSACTION;
275 LET $open = (UPDATE $sub SET updated_at = $now \285 LET $open = (UPDATE $sub SET updated_at = $now \
276 WHERE {SUBMISSION_OPEN_GUARD} RETURN VALUE id);286 WHERE {SUBMISSION_OPEN_GUARD} RETURN VALUE id);
@@ -278,12 +288,18 @@ impl HomeworkFile {
278 UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]);288 UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]);
279 RETURN {{ open: array::len($open), gone: $gone }};289 RETURN {{ open: array::len($open), gone: $gone }};
280 COMMIT TRANSACTION;"290 COMMIT TRANSACTION;"
281- ))291+ ),
282- .bind(("id", self.id.record()))292+ &[
283- .bind(("sub", self.submission.record()))293+ ("id".into(), self.id.record().into_value()),
284- .bind(("now", Timestamp::now()))294+ ("sub".into(), self.submission.record().into_value()),
285- .await?295+ ("now".into(), Timestamp::now().into_value()),
286- .check()?;296+ ],
297+ &[],
298+ )
299+ .await?;
300+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
301+ return Err(error.into());
302+ }
287 // BEGIN is slot 0, the two LETs slots 1-2 and the counter fix slot 3;303 // BEGIN is slot 0, the two LETs slots 1-2 and the counter fix slot 3;
288 // the RETURN is slot 4.304 // the RETURN is slot 4.
289 let outcome: Option<DeleteOutcome> =305 let outcome: Option<DeleteOutcome> =
@@ -311,11 +327,10 @@ mod tests {
311 /// A real homework row (with the subject it references): `upsert` reads the327 /// A real homework row (with the subject it references): `upsert` reads the
312 /// deadline off the entity now, so a bare id no longer does.328 /// deadline off the entity now, so a bare id no longer does.
313 async fn a_homework(db: &Database) -> crate::domain::homework::Homework {329 async fn a_homework(db: &Database) -> crate::domain::homework::Homework {
314- use crate::domain::course::CourseId;
315 use crate::domain::homework::{Homework, HomeworkTitle};330 use crate::domain::homework::{Homework, HomeworkTitle};
316 use crate::domain::subject::{Subject, SubjectDescription, SubjectName};331 use crate::domain::subject::{Subject, SubjectDescription, SubjectName};
317 332
318- let course = CourseId::from_key("course");333+ let course = crate::domain::course::a_test_course(db).await;
319 let subject = Subject::create(334 let subject = Subject::create(
320 &course,335 &course,
321 SubjectName::try_new("topic").unwrap(),336 SubjectName::try_new("topic").unwrap(),
src/domain/homework_result.rsmodified+95 -22
@@ -172,17 +172,43 @@ impl HomeworkResult {
172 // homework mark is optional and most grades are status-only, so172 // homework mark is optional and most grades are status-only, so
173 // `high_mark` is an exam-only family.173 // `high_mark` is an exam-only family.
174 //174 //
175- // ponytail: this is a plain query, not `transaction_with_retry`, so a175+ // The first three statements are the parent gate, the twin of
176- // store conflict on the grader's row — another domain writing the same176+ // [`crate::domain::homework_submission::HomeworkSubmission::upsert`]'s
177- // user row in the same instant — comes back as a 500 rather than a177+ // and written the same way on purpose: the id is deterministic, so a
178- // re-send. Rare (grading is serialised by `HOMEWORK_LOCK` and a178+ // grade landing inside a homework (or course) delete's window does not
179- // teacher's row moves nowhere else but exam grading), and the upgrade179+ // fail — it *re-creates* a result row under a homework that is gone,
180- // is the shape `HomeworkSubmission::upsert` already uses: the whole180+ // readable ever after at `GET /homework/{id}/result` (no existence check
181- // transaction is re-sendable, since nothing in it can legitimately181+ // there) with a `marks_given_total` no ungrade can reach, because every
182- // answer "already exists".182+ // route to the grade goes through the homework. Reading the homework
183- let mut saved = db183+ // first — which the web layer does, under the lease — cannot close that:
184- .query(format!(184+ // the store conflict-checks write sets, not read sets. So the gate
185+ // *moves* a value on the homework row (`due_at` up by one and straight
186+ // back to the captured value, leaving the row byte-identical) and the
187+ // cascade's delete of that same row is what refuses it. `homework` owns
188+ // no counter column and is SCHEMAFULL, so `due_at` is the one `int` it
189+ // already has; do not invent a second spelling.
190+ //
191+ // Not [`crate::domain::cap::touch_and_create`], which is the same shape
192+ // for a bare `CREATE`: a grade is an UPSERT (a regrade must overwrite),
193+ // and the freeze stamp and the grader's counter have to ride the same
194+ // transaction, which that helper has no room for.
195+ //
196+ // Sound to re-send, which is what the gate needed first — a `THROW`
197+ // inside a plain `db.query` would have turned every lost round into a
198+ // 500. `SELECT`, `UPDATE` and the `IF`/`THROW` can never answer "already
199+ // exists", and the `UPSERT`'s id is bijective with the (homework, user)
200+ // pair the table keys, on a table whose only index is non-unique
201+ // (`homework_result_homework`), so its index entry can only ever point
202+ // at the row the id already names: it resolves onto that row instead of
203+ // colliding with it. A lost round wrote nothing.
204+ let (mut saved, mut errors) = transaction_with_retry(
205+ db,
206+ &format!(
185 "BEGIN TRANSACTION;207 "BEGIN TRANSACTION;
208+ LET $was_due = (SELECT VALUE due_at FROM ONLY $hw);
209+ LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id);
210+ IF array::len($alive) = 0 {{ THROW 'no_homework' }};
211+ UPDATE $hw SET due_at = $was_due;
186 LET $before = (SELECT VALUE id FROM ONLY $id);212 LET $before = (SELECT VALUE id FROM ONLY $id);
187 LET $after = (UPSERT $id CONTENT $row RETURN AFTER);213 LET $after = (UPSERT $id CONTENT $row RETURN AFTER);
188 UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = $id \214 UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = $id \
@@ -193,17 +219,32 @@ impl HomeworkResult {
193 }};219 }};
194 RETURN $after;220 RETURN $after;
195 COMMIT TRANSACTION;"221 COMMIT TRANSACTION;"
196- ))222+ ),
197- .bind(("id", id.record()))223+ &[
198- .bind(("sub", submission.record()))224+ ("hw".into(), homework.record().into_value()),
199- .bind(("grader", graded_by.record()))225+ ("id".into(), id.record().into_value()),
200- .bind(("row", result.into_value()))226+ ("sub".into(), submission.record().into_value()),
201- .await?227+ ("grader".into(), graded_by.record().into_value()),
202- .check()?;228+ ("row".into(), result.into_value()),
229+ ],
230+ &["no_homework"],
231+ )
232+ .await?;
233+ // An aborted transaction errors *every* slot, most with a generic "not
234+ // executed" — only the THROW's own slot names the reason.
235+ if errors
236+ .values()
237+ .any(|error| error.to_string().contains("no_homework"))
238+ {
239+ return Err(AppError::NotFound);
240+ }
241+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
242+ return Err(error.into());
243+ }
203 // The trailing `RETURN` is always the last statement before `COMMIT`,244 // The trailing `RETURN` is always the last statement before `COMMIT`,
204 // so its slot follows the statement count instead of a hand-kept245 // so its slot follows the statement count instead of a hand-kept
205- // number — which the counter statement above would otherwise have246+ // number — which the gate above would otherwise have shifted, silently
206- // shifted, silently handing back the stamp's row.247+ // handing back something else.
207 let slot = saved.num_statements().saturating_sub(2);248 let slot = saved.num_statements().saturating_sub(2);
208 saved249 saved
209 .take::<Vec<HomeworkResult>>(slot)?250 .take::<Vec<HomeworkResult>>(slot)?
@@ -327,6 +368,38 @@ mod tests {
327 use crate::constant::HOMEWORK_STATUSES;368 use crate::constant::HOMEWORK_STATUSES;
328 use surrealdb::types::Value;369 use surrealdb::types::Value;
329 370
371+ /// A real homework row (with the course and subject it needs): the grade now
372+ /// carries a parent gate, so a minted id nothing wrote is a `404` here, the
373+ /// same way it already is for a submission.
374+ async fn a_homework(db: &Database) -> HomeworkId {
375+ use crate::domain::homework::{Homework, HomeworkTitle};
376+ use crate::domain::subject::{Subject, SubjectDescription, SubjectName};
377+
378+ let course = crate::domain::course::a_test_course(db).await;
379+ let subject = Subject::create(
380+ &course,
381+ SubjectName::try_new("topic").unwrap(),
382+ SubjectDescription::try_new("").unwrap(),
383+ db,
384+ )
385+ .await
386+ .unwrap();
387+ Homework::create(
388+ &course,
389+ subject.get_id(),
390+ HomeworkTitle::try_new("essay").unwrap(),
391+ None,
392+ Timestamp::from_millis(1),
393+ None,
394+ &UserId::from_key("teacher"),
395+ db,
396+ )
397+ .await
398+ .unwrap()
399+ .get_id()
400+ .clone()
401+ }
402+
330 #[tokio::test]403 #[tokio::test]
331 async fn status_is_held_to_the_const_and_stores_as_a_bare_string() {404 async fn status_is_held_to_the_const_and_stores_as_a_bare_string() {
332 // Enforcement lives in the newtype against HOMEWORK_STATUSES (the DDL405 // Enforcement lives in the newtype against HOMEWORK_STATUSES (the DDL
@@ -344,7 +417,7 @@ mod tests {
344 #[tokio::test]417 #[tokio::test]
345 async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() {418 async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() {
346 let db = crate::database::init_mem().await.unwrap();419 let db = crate::database::init_mem().await.unwrap();
347- let homework = HomeworkId::from_key("01TESTHWAAAAAAAAAAAAAAAAAA");420+ let homework = a_homework(&db).await;
348 let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");421 let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
349 let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");422 let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
350 423
@@ -406,7 +479,7 @@ mod tests {
406 #[tokio::test]479 #[tokio::test]
407 async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() {480 async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() {
408 let db = crate::database::init_mem().await.unwrap();481 let db = crate::database::init_mem().await.unwrap();
409- let homework = HomeworkId::from_key("01TESTHWBADGEAAAAAAAAAAAAA");482+ let homework = a_homework(&db).await;
410 let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");483 let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
411 let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");484 let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
412 // `UPDATE` writes nothing to a user row that does not exist.485 // `UPDATE` writes nothing to a user row that does not exist.
@@ -443,7 +516,7 @@ mod tests {
443 #[tokio::test]516 #[tokio::test]
444 async fn ungrading_gives_the_grader_credit_back() {517 async fn ungrading_gives_the_grader_credit_back() {
445 let db = crate::database::init_mem().await.unwrap();518 let db = crate::database::init_mem().await.unwrap();
446- let homework = HomeworkId::from_key("01TESTHWUNGRADEAAAAAAAAAAA");519+ let homework = a_homework(&db).await;
447 let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");520 let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
448 let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");521 let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
449 db.query("CREATE $usr SET username = 't', password_hash = 'x'")522 db.query("CREATE $usr SET username = 't', password_hash = 'x'")
src/domain/homework_submission.rsmodified+30 -4
@@ -138,6 +138,21 @@ impl HomeworkSubmission {
138 /// gave back something other than what was taken. Writing the verdict beside138 /// gave back something other than what was taken. Writing the verdict beside
139 /// the counter is what keeps the two from ever disagreeing — read back by139 /// the counter is what keeps the two from ever disagreeing — read back by
140 /// [`HomeworkSubmission::delete`], never re-derived.140 /// [`HomeworkSubmission::delete`], never re-derived.
141+ ///
142+ /// The first three statements are the parent gate, and they are why this
143+ /// write cannot outlive its homework: the id is deterministic, so nothing
144+ /// else here would fail against a homework a cascade already removed — it
145+ /// would simply re-create the row, badge counters and all, unreachable ever
146+ /// after (every route to a submission goes through its homework). A *read*
147+ /// of the homework does not close that, on either side of the call: the
148+ /// store does no read-set conflict detection, so a delete committing
149+ /// alongside is invisible to it. The gate therefore *moves* a value on the
150+ /// homework row — `due_at` up by one and straight back to the captured
151+ /// value, so the row is byte-identical afterwards — because only a write
152+ /// collides, and `SET x = x` is elided and never reaches the write set. It
153+ /// is [`crate::domain::exam_answer::ExamAnswer::save`]'s shape exactly.
154+ /// `Err(NotFound)` means the homework is gone, which is the 404 the web
155+ /// layer's own lookup would have answered.
141 pub async fn upsert(156 pub async fn upsert(
142 homework: &Homework,157 homework: &Homework,
143 user: &UserId,158 user: &UserId,
@@ -149,11 +164,15 @@ impl HomeworkSubmission {
149 let text = text.map(|text| text.as_str().to_string());164 let text = text.map(|text| text.as_str().to_string());
150 // Sound to re-send: the UPSERT is on a deterministic id on a table with165 // Sound to re-send: the UPSERT is on a deterministic id on a table with
151 // no unique index, so it can never legitimately answer "already exists",166 // no unique index, so it can never legitimately answer "already exists",
152- // and the counter UPDATE never can either.167+ // and the counter UPDATEs never can either.
153 let (mut saved, mut errors) = transaction_with_retry(168 let (mut saved, mut errors) = transaction_with_retry(
154 db,169 db,
155 &format!(170 &format!(
156 "BEGIN TRANSACTION;171 "BEGIN TRANSACTION;
172+ LET $was_due = (SELECT VALUE due_at FROM ONLY $hw);
173+ LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id);
174+ IF array::len($alive) = 0 {{ THROW 'no_homework' }};
175+ UPDATE $hw SET due_at = $was_due;
157 LET $before = (SELECT VALUE id FROM ONLY $id);176 LET $before = (SELECT VALUE id FROM ONLY $id);
158 LET $on_time = $now <= $due;177 LET $on_time = $now <= $due;
159 LET $after = (UPSERT $id SET homework = $hw, user = $usr, text = $text,178 LET $after = (UPSERT $id SET homework = $hw, user = $usr, text = $text,
@@ -177,9 +196,17 @@ impl HomeworkSubmission {
177 ("now".into(), now.into_value()),196 ("now".into(), now.into_value()),
178 ("due".into(), homework.get_due_at().into_value()),197 ("due".into(), homework.get_due_at().into_value()),
179 ],198 ],
180- &[],199+ &["no_homework"],
181 )200 )
182 .await?;201 .await?;
202+ // An aborted transaction errors *every* slot, most with a generic "not
203+ // executed" — only the THROW's own slot names the reason.
204+ if errors
205+ .values()
206+ .any(|error| error.to_string().contains("no_homework"))
207+ {
208+ return Err(AppError::NotFound);
209+ }
183 if let Some(error) = errors.drain().map(|(_, error)| error).next() {210 if let Some(error) = errors.drain().map(|(_, error)| error).next() {
184 return Err(error.into());211 return Err(error.into());
185 }212 }
@@ -334,14 +361,13 @@ impl HomeworkSubmission {
334 mod tests {361 mod tests {
335 use super::*;362 use super::*;
336 363
337- use crate::domain::course::CourseId;
338 use crate::domain::homework::HomeworkTitle;364 use crate::domain::homework::HomeworkTitle;
339 use crate::domain::subject::{Subject, SubjectDescription, SubjectName};365 use crate::domain::subject::{Subject, SubjectDescription, SubjectName};
340 366
341 /// A real homework row (and the subject it must reference) due at `due_at` —367 /// A real homework row (and the subject it must reference) due at `due_at` —
342 /// `upsert` now reads the deadline off the entity, so the tests need one.368 /// `upsert` now reads the deadline off the entity, so the tests need one.
343 async fn a_homework(due_at: Timestamp, db: &Database) -> Homework {369 async fn a_homework(due_at: Timestamp, db: &Database) -> Homework {
344- let course = CourseId::from_key("course");370+ let course = crate::domain::course::a_test_course(db).await;
345 let subject = Subject::create(371 let subject = Subject::create(
346 &course,372 &course,
347 SubjectName::try_new("topic").unwrap(),373 SubjectName::try_new("topic").unwrap(),
src/web/courses.rsmodified+25 -6
@@ -535,9 +535,18 @@ async fn delete_course(
535 // the student's row, never the exam's). Narrower here — the delete is535 // the student's row, never the exam's). Narrower here — the delete is
536 // refused while anyone is enrolled, so a start would have to pass its536 // refused while anyone is enrolled, so a start would have to pass its
537 // enrollment gate and then have that enrollment removed under it — but the537 // enrollment gate and then have that enrollment removed under it — but the
538- // hole is the same one and so is the lease. Nothing on this path takes538+ // hole is the same one and so is the lease.
539- // another lock, so it introduces no ordering pair.
540 let _guard = crate::web::exams::EXAM_LOCK.write().await;539 let _guard = crate::web::exams::EXAM_LOCK.write().await;
540+ // And the homework half of the same cascade, for
541+ // [`crate::web::homework::delete_homework`]'s reason: it sweeps the
542+ // course's homework with its submissions, files and results, and grading
543+ // ([`crate::domain::homework_result::HomeworkResult::grade`]) writes a
544+ // result row against a homework it only *read*, which a delete committing
545+ // alongside is invisible to. Without this lease the grade lands behind the
546+ // sweep: an orphan `homework_result` under a vanished homework, plus a
547+ // `marks_given_total` on the grader no ungrade can reach. Lock order here
548+ // is EXAM_LOCK then HOMEWORK_LOCK, the only path that takes both.
549+ let _homework_guard = crate::web::homework::HOMEWORK_LOCK.write().await;
541 // Rows go first (the delete cascades them), blobs after — a crash in550 // Rows go first (the delete cascades them), blobs after — a crash in
542 // between strands at worst an unreachable blob. The keys are read before551 // between strands at worst an unreachable blob. The keys are read before
543 // the delete because it takes their rows with it; a refused delete just552 // the delete because it takes their rows with it; a refused delete just
@@ -1119,7 +1128,8 @@ async fn create_homework_in_course(
1119 /// List a course's homework, newest first, paged via `?limit=&offset=` (omit1128 /// List a course's homework, newest first, paged via `?limit=&offset=` (omit
1120 /// `limit` for all of it). Visible to the course's enrolled users, its creator,1129 /// `limit` for all of it). Visible to the course's enrolled users, its creator,
1121 /// its assigned teachers, and managers/admins — but a student sees only the1130 /// its assigned teachers, and managers/admins — but a student sees only the
1122-/// homework they are assigned (whole-course ones plus subsets that name them).1131+/// homework they are assigned (whole-course ones plus subsets that name them,
1132+/// each with its `assigned` narrowed to themselves).
1123 /// Returns a `{items, total, limit, offset}` envelope.1133 /// Returns a `{items, total, limit, offset}` envelope.
1124 #[utoipa::path(1134 #[utoipa::path(
1125 get,1135 get,
@@ -1153,14 +1163,23 @@ async fn list_course_homework(
1153 }1163 }
1154 let mut homework = Homework::list_for_course(course.get_id(), &st.db).await?;1164 let mut homework = Homework::list_for_course(course.get_id(), &st.db).await?;
1155 // A student sees only the homework they are assigned; managers see all.1165 // A student sees only the homework they are assigned; managers see all.
1156- if !can_manage_course(&course, &user) {1166+ let manages = can_manage_course(&course, &user);
1167+ if !manages {
1157 homework.retain(|hw| hw.student_sees(user.get_id()));1168 homework.retain(|hw| hw.student_sees(user.get_id()));
1158 }1169 }
1159 let total = homework.len() as i64;1170 let total = homework.len() as i64;
1160- // Paged in the web layer: the audience filter above is per-row Rust.1171+ // Paged in the web layer: the audience filter above is per-row Rust. A
1172+ // subset roster goes out whole only to a manager of the course; a student
1173+ // sees themselves in it and no one else.
1161 let items = paginate(&homework, limit, offset)1174 let items = paginate(&homework, limit, offset)
1162 .iter()1175 .iter()
1163- .map(HomeworkResponse::new)1176+ .map(|hw| {
1177+ if manages {
1178+ HomeworkResponse::new(hw)
1179+ } else {
1180+ HomeworkResponse::for_viewer(hw, user.get_id())
1181+ }
1182+ })
1164 .collect();1183 .collect();
1165 Ok(Json(Page::new(items, total, limit, offset)))1184 Ok(Json(Page::new(items, total, limit, offset)))
1166 }1185 }
src/web/dto.rsmodified+16 -1
@@ -270,7 +270,10 @@ pub struct HomeworkResponse {
270 /// When the homework is due, UTC unix-milliseconds.270 /// When the homework is due, UTC unix-milliseconds.
271 #[schema(example = 1_900_000_000_000_i64)]271 #[schema(example = 1_900_000_000_000_i64)]
272 pub due_at: i64,272 pub due_at: i64,
273- /// The assigned student ids, or `null` for the whole enrolled course.273+ /// The assigned student ids, or `null` for the whole enrolled course. Only
274+ /// a viewer who manages the course sees the whole subset; to anyone else it
275+ /// is narrowed to their own id (the course roster is teacher+-only, so a
276+ /// subset assignment must not hand out the names it lists).
274 pub assigned: Option<Vec<String>>,277 pub assigned: Option<Vec<String>>,
275 /// Who assigned the homework.278 /// Who assigned the homework.
276 pub created_by: String,279 pub created_by: String,
@@ -294,6 +297,18 @@ impl HomeworkResponse {
294 created_at: homework.get_created_at().as_millis(),297 created_at: homework.get_created_at().as_millis(),
295 }298 }
296 }299 }
300+
301+ /// The same homework as seen by a viewer who does *not* manage its course.
302+ /// A subset roster is narrowed to `viewer` alone: they learn that they are
303+ /// named — which is why the homework reached them at all — and nothing
304+ /// about who else is. Whole-course (`null`) stays `null`; every read path
305+ /// that uses this has already refused a viewer the subset does not name
306+ /// (404), so a one-element list is never a lie.
307+ pub fn for_viewer(homework: &Homework, viewer: &UserId) -> Self {
308+ let mut response = Self::new(homework);
309+ response.assigned = response.assigned.map(|_| vec![viewer.key().to_string()]);
310+ response
311+ }
297 }312 }
298 313
299 /// Public shape of a course session (one lesson). Shared by `courses`314 /// Public shape of a course session (one lesson). Shared by `courses`
src/web/homework.rsmodified+52 -14
@@ -59,9 +59,13 @@ use super::{
59 ///59 ///
60 /// What still leases it, honestly:60 /// What still leases it, honestly:
61 /// - Write: the homework PATCH's orphan guard ([`update_homework`]), the61 /// - Write: the homework PATCH's orphan guard ([`update_homework`]), the
62-/// homework-delete cascade ([`delete_homework`]), and grade/ungrade — which62+/// homework-delete cascade ([`delete_homework`]), and grade/ungrade — whose
63-/// read the homework itself under the lease so a concurrent delete can't63+/// freeze rule (the stamp landing on a submission that may be written in the
64-/// leave a result row under a vanished homework.64+/// same instant) is the one thing here still resting on the two leases being
65+/// mutually exclusive. The *existence* half has left: a grade now moves a
66+/// value on the homework row inside its own transaction
67+/// ([`crate::domain::homework_result::HomeworkResult::grade`]), so a
68+/// concurrent delete refuses it rather than being read around.
65 /// - Read: the student's submission/file writes, which no longer gate the69 /// - Read: the student's submission/file writes, which no longer gate the
66 /// freeze but still must not land under a PATCH re-scoping the audience out70 /// freeze but still must not land under a PATCH re-scoping the audience out
67 /// from under them.71 /// from under them.
@@ -171,7 +175,8 @@ async fn homework_with_course(id: &str, db: &Database) -> Result<(Homework, Cour
171 /// paged via `?limit=&offset=` (omit `limit` for all of it). Manager+ see every175 /// paged via `?limit=&offset=` (omit `limit` for all of it). Manager+ see every
172 /// course's homework; a teacher sees the homework of courses they run; a176 /// course's homework; a teacher sees the homework of courses they run; a
173 /// student sees only the homework they are assigned (whole-course ones plus any177 /// student sees only the homework they are assigned (whole-course ones plus any
174-/// subset that names them). Returns a `{items, total, limit, offset}` envelope.178+/// subset that names them, each with its `assigned` narrowed to themselves).
179+/// Returns a `{items, total, limit, offset}` envelope.
175 #[utoipa::path(180 #[utoipa::path(
176 get,181 get,
177 path = "/",182 path = "/",
@@ -190,7 +195,11 @@ async fn list_homework(
190 Query(page): Query<PageParams>,195 Query(page): Query<PageParams>,
191 ) -> Result<Json<Page<HomeworkResponse>>, AppError> {196 ) -> Result<Json<Page<HomeworkResponse>>, AppError> {
192 let (limit, offset) = page.resolve()?;197 let (limit, offset) = page.resolve()?;
193- let homework = if user.get_role().at_least(Role::Manager) {198+ // The courses this caller manages — empty for a manager+, who manages all
199+ // of them, and who is told apart by this flag.
200+ let manages_all = user.get_role().at_least(Role::Manager);
201+ let mut managed: Vec<String> = Vec::new();
202+ let homework = if manages_all {
194 Homework::list_all(&st.db).await?203 Homework::list_all(&st.db).await?
195 } else {204 } else {
196 let courses = visible_courses(&user, &st.db).await?;205 let courses = visible_courses(&user, &st.db).await?;
@@ -201,22 +210,31 @@ async fn list_homework(
201 // A student sees only the homework they are assigned; a teacher who210 // A student sees only the homework they are assigned; a teacher who
202 // manages a course sees all of its homework (the manager+ path above211 // manages a course sees all of its homework (the manager+ path above
203 // already saw everything).212 // already saw everything).
204- let managed: Vec<&str> = courses213+ managed = courses
205 .iter()214 .iter()
206 .filter(|course| can_manage_course(course, &user))215 .filter(|course| can_manage_course(course, &user))
207- .map(|course| course.get_id().key())216+ .map(|course| course.get_id().key().to_string())
208 .collect();217 .collect();
209 let mut homework = Homework::list_for_courses(&ids, &st.db).await?;218 let mut homework = Homework::list_for_courses(&ids, &st.db).await?;
210 homework.retain(|hw| {219 homework.retain(|hw| {
211- managed.contains(&hw.get_course().key()) || hw.student_sees(user.get_id())220+ managed.iter().any(|key| key == hw.get_course().key()) || hw.student_sees(user.get_id())
212 });221 });
213 homework222 homework
214 };223 };
215 let total = homework.len() as i64;224 let total = homework.len() as i64;
216- // Paged in the web layer: the audience filter above is per-row Rust.225+ // Paged in the web layer: the audience filter above is per-row Rust. The
226+ // subset roster rides along only for the rows the caller manages — to a
227+ // student it is narrowed to themselves, as it is on the single-homework
228+ // read.
217 let items = paginate(&homework, limit, offset)229 let items = paginate(&homework, limit, offset)
218 .iter()230 .iter()
219- .map(HomeworkResponse::new)231+ .map(|hw| {
232+ if manages_all || managed.iter().any(|key| key == hw.get_course().key()) {
233+ HomeworkResponse::new(hw)
234+ } else {
235+ HomeworkResponse::for_viewer(hw, user.get_id())
236+ }
237+ })
220 .collect();238 .collect();
221 Ok(Json(Page::new(items, total, limit, offset)))239 Ok(Json(Page::new(items, total, limit, offset)))
222 }240 }
@@ -225,7 +243,9 @@ async fn list_homework(
225 /// enrolled users, creator, assigned teachers, and managers/admins). A student243 /// enrolled users, creator, assigned teachers, and managers/admins). A student
226 /// the homework is *not* assigned to gets a 404 — the same no-leak an unseen244 /// the homework is *not* assigned to gets a 404 — the same no-leak an unseen
227 /// exam draft gets, so a subset assignment never reveals itself to the students245 /// exam draft gets, so a subset assignment never reveals itself to the students
228-/// left out of it.246+/// left out of it. To a caller without course-management rights the `assigned`
247+/// subset comes back narrowed to their own id: being named is theirs to know,
248+/// the rest of the roster is not.
229 #[utoipa::path(249 #[utoipa::path(
230 get,250 get,
231 path = "/{id}",251 path = "/{id}",
@@ -252,10 +272,17 @@ async fn get_homework(
252 }272 }
253 // A student the homework is not assigned to must not even learn it exists —273 // A student the homework is not assigned to must not even learn it exists —
254 // 404, not 403, exactly like an exam draft hidden from non-managers.274 // 404, not 403, exactly like an exam draft hidden from non-managers.
255- if !can_manage_course(&course, &user) && !homework.student_sees(user.get_id()) {275+ let manages = can_manage_course(&course, &user);
276+ if !manages && !homework.student_sees(user.get_id()) {
256 return Err(AppError::NotFound);277 return Err(AppError::NotFound);
257 }278 }
258- Ok(Json(HomeworkResponse::new(&homework)))279+ // ... and one it *is* assigned to must not hand them the rest of the
280+ // subset: the same no-leak, one step further in.
281+ Ok(Json(if manages {
282+ HomeworkResponse::new(&homework)
283+ } else {
284+ HomeworkResponse::for_viewer(&homework, user.get_id())
285+ }))
259 }286 }
260 287
261 #[derive(Deserialize, ToSchema)]288 #[derive(Deserialize, ToSchema)]
@@ -851,7 +878,10 @@ async fn upload_submission_file(
851 Path(id): Path<String>,878 Path(id): Path<String>,
852 mut multipart: Multipart,879 mut multipart: Multipart,
853 ) -> Result<(StatusCode, Json<HomeworkFileResponse>), AppError> {880 ) -> Result<(StatusCode, Json<HomeworkFileResponse>), AppError> {
854- let homework = gate_own_submission(&id, &user, &st.db).await?;881+ // Pre-flight, so a caller with no business here is refused before uploading
882+ // 25 MiB; the gate that *licenses the write* is the one under the lease
883+ // below, because this snapshot goes stale while the body streams.
884+ gate_own_submission(&id, &user, &st.db).await?;
855 let limit = Settings::load(&st.db).await?.get_max_file_bytes();885 let limit = Settings::load(&st.db).await?.get_max_file_bytes();
856 // Consume the body before taking the lock — a slow upload must not stall the886 // Consume the body before taking the lock — a slow upload must not stall the
857 // homework subsystem (mirrors the exam/note image uploads).887 // homework subsystem (mirrors the exam/note image uploads).
@@ -866,6 +896,14 @@ async fn upload_submission_file(
866 // Taken before the cap claim inside `insert`, never after (the lock order896 // Taken before the cap claim inside `insert`, never after (the lock order
867 // is HOMEWORK_LOCK, then the counter lock).897 // is HOMEWORK_LOCK, then the counter lock).
868 let _guard = HOMEWORK_LOCK.read().await;898 let _guard = HOMEWORK_LOCK.read().await;
899+ // Re-read the homework *under* the lease. Streaming the body takes as long
900+ // as the client wants it to, and a homework delete (a writer) both takes
901+ // and releases its lease inside that window — so the pre-flight snapshot
902+ // can name a homework that no longer exists, and this handler would then
903+ // auto-create a submission, credit the badge counters and write a file
904+ // under it, all unreachable afterwards. A gate read before the body is a
905+ // pre-flight; a gate read after it is the decision.
906+ let homework = gate_own_submission(&id, &user, &st.db).await?;
869 // The common-case gate; the freeze itself rides on the writes below.907 // The common-case gate; the freeze itself rides on the writes below.
870 if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db)908 if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db)
871 .await?909 .await?
tests/regress_homework_orphans.rsadded+740 -0
@@ -0,0 +1,740 @@
1+//! Regressions for the four holes the 2026-08-05 hunt left on the homework
2+//! surface: a file upload that outlived its homework, a course delete that
3+//! swept homework without holding the homework lease, a subset assignment that
4+//! handed every named student the whole roster, and a file delete that answered
5+//! a lost round with a 500.
6+//!
7+//! Two of them share one root cause and one shape of fix: a child keyed by a
8+//! deterministic id does not fail against a parent a cascade removed, it
9+//! *re-creates* it — so both the submission and the grade now move a value on
10+//! the homework row inside their own transaction, and the two domain-level
11+//! tests here (`a_submission_under_a_vanished_homework_is_refused`,
12+//! `a_grade_under_a_vanished_homework_is_refused`) are what pin those gates.
13+//! The lock-level races pin the handlers.
14+//!
15+//! Every race here is judged on the *store*, never on what a request answered:
16+//! the in-memory engine forges wins under concurrency (src/domain/cap.rs), so a
17+//! 404 or a 204 is evidence of nothing. The windows are opened by the database
18+//! itself — a `DEFINE EVENT` on the table under write fires *inside* the
19+//! writing transaction — rather than by a lucky interleaving.
20+
21+mod common;
22+
23+use axum::http::StatusCode;
24+use common::{
25+ app_and_db, create_course, create_homework, create_homework_with, create_subject, enroll,
26+ id_of, items, login_as, me_id, multipart_file, send, send_raw, unenroll,
27+};
28+use hezarfen_backend::database::Database;
29+use serde_json::{Value, json};
30+use surrealdb::types::RecordId;
31+
32+/// `HOMEWORK_LOCK` is process-wide, and every race below holds a lease of it
33+/// for seconds. Two of them running at once starve each other's window — the
34+/// second one's gates then run *after* the staging meant to happen inside them,
35+/// and the test judges an interleaving that never happened. One at a time; the
36+/// deterministic tests need no ticket.
37+static ONE_RACE_AT_A_TIME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
38+
39+/// A due date comfortably clear of the 60s past-scheduling grace.
40+fn far_future() -> i64 {
41+ hezarfen_backend::domain::timestamp::Timestamp::now().as_millis() + 7_200_000
42+}
43+
44+/// How many rows `sql` selects ids for — the stored state, out of the store.
45+async fn rows(db: &Database, sql: &str) -> usize {
46+ let mut result = db.query(sql).await.unwrap().check().unwrap();
47+ result.take::<Vec<RecordId>>(0).unwrap().len()
48+}
49+
50+/// One integer field off one user row, absent counting as zero.
51+async fn counter(db: &Database, user: &str, field: &str) -> i64 {
52+ let mut result = db
53+ .query(format!(
54+ "SELECT VALUE ({field} ?? 0) FROM type::record('user', $key)"
55+ ))
56+ .bind(("key", user.to_string()))
57+ .await
58+ .unwrap()
59+ .check()
60+ .unwrap();
61+ result
62+ .take::<Vec<i64>>(0)
63+ .unwrap()
64+ .first()
65+ .copied()
66+ .unwrap_or(0)
67+}
68+
69+/// Upload `bytes` onto the caller's submission to `hw` — no assertion.
70+async fn upload_hw_file(app: &axum::Router, cookie: &str, hw: &str) -> StatusCode {
71+ let (status, _, _) = send_raw(
72+ app,
73+ "POST",
74+ &format!("/homework/{hw}/submission/files"),
75+ Some(cookie),
76+ Some("multipart/form-data; boundary=hezarfen-test-boundary"),
77+ multipart_file("odev.pdf", "application/pdf", b"homework bytes"),
78+ )
79+ .await;
80+ status
81+}
82+
83+/// A course with one subject and one enrolled student. Returns
84+/// `(course, subject, student cookie, student id)`.
85+async fn course_with_student(
86+ app: &axum::Router,
87+ db: &Database,
88+ teacher: &str,
89+ name: &str,
90+) -> (String, String, String, String) {
91+ let student = login_as(app, db, &format!("ogrenci_{name}"), "student").await;
92+ let student_id = me_id(app, &student).await;
93+ let course = create_course(app, teacher, name).await;
94+ let subject = create_subject(app, teacher, &course, "konu").await;
95+ enroll(app, teacher, &course, &student_id).await;
96+ (course, subject, student, student_id)
97+}
98+
99+/// The upload streams its body *before* it takes `HOMEWORK_LOCK`, and the
100+/// homework snapshot it acts on was read before that stream — so a delete
101+/// (which takes and releases the write lease inside that window) leaves the
102+/// handler holding a homework that is gone. It then auto-created a submission
103+/// under it, credited both badge counters, wrote a blob and a file row, and
104+/// answered `201`. Every route to any of that goes through the vanished
105+/// homework, so nothing could ever read or delete it again, and the counters
106+/// stayed up for good.
107+///
108+/// The window is the delete's own: a `DEFINE EVENT` on `homework` holds its
109+/// transaction open after the cascade has swept the children, which is exactly
110+/// the interleaving — the upload's gate read lands inside it (the row is
111+/// deleted but uncommitted, so it still reads), and its write lands after. The
112+/// upload's own duration is asserted too: one that arrived after the delete had
113+/// already committed would be answered by a plain lookup and leave this test
114+/// green over the hole.
115+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
116+async fn an_upload_inside_a_homework_delete_never_orphans() {
117+ let _serial = ONE_RACE_AT_A_TIME.lock().await;
118+ let (app, db) = app_and_db().await;
119+ let teacher = login_as(&app, &db, "ogretmen_odev", "teacher").await;
120+ let (course, subject, student, student_id) =
121+ course_with_student(&app, &db, &teacher, "fizik").await;
122+ let hw = create_homework(&app, &teacher, &course, &subject, "deneme", far_future()).await;
123+
124+ // Hold the delete open once the cascade has run but before it commits.
125+ db.query(
126+ "DEFINE EVENT hold_the_window ON TABLE homework WHEN $event = 'DELETE' \
127+ THEN { SLEEP 3s; };",
128+ )
129+ .await
130+ .expect("define the window event")
131+ .check()
132+ .expect("check the window event");
133+
134+ let drop_it = {
135+ let (app, teacher, hw) = (app.clone(), teacher.clone(), hw.clone());
136+ tokio::spawn(async move {
137+ send(
138+ &app,
139+ "DELETE",
140+ &format!("/homework/{hw}"),
141+ Some(&teacher),
142+ None,
143+ )
144+ .await
145+ })
146+ };
147+ // The upload fires inside the held window: its gate reads a homework the
148+ // delete has removed but not committed.
149+ tokio::time::sleep(std::time::Duration::from_millis(1_000)).await;
150+ let uploaded = {
151+ let (app, student, hw) = (app.clone(), student.clone(), hw.clone());
152+ tokio::spawn(async move {
153+ let started = std::time::Instant::now();
154+ (upload_hw_file(&app, &student, &hw).await, started.elapsed())
155+ })
156+ };
157+ let (dropped, (upload_status, took)) = (drop_it.await.unwrap(), uploaded.await.unwrap());
158+
159+ assert!(
160+ took >= std::time::Duration::from_secs(1),
161+ "the upload never contended with the delete ({took:?}): nothing was raced"
162+ );
163+ assert_eq!(
164+ dropped.status,
165+ StatusCode::NO_CONTENT,
166+ "the delete must succeed: {:?}",
167+ dropped.body
168+ );
169+ // A 404 is the correct answer for the upload; the only defect is stored
170+ // state. Nothing may 500 either way.
171+ assert!(
172+ upload_status == StatusCode::NOT_FOUND || upload_status.is_success(),
173+ "a raced upload must be answered, not {upload_status}"
174+ );
175+
176+ // Stored state is the whole verdict.
177+ assert_eq!(
178+ rows(&db, "SELECT VALUE id FROM homework_submission").await,
179+ 0,
180+ "a submission outlived its homework"
181+ );
182+ assert_eq!(
183+ rows(&db, "SELECT VALUE id FROM homework_file").await,
184+ 0,
185+ "a file outlived its homework"
186+ );
187+ assert_eq!(
188+ counter(&db, &student_id, "homework_submitted_total").await,
189+ 0,
190+ "a hand-in nothing can reach still counted"
191+ );
192+ assert_eq!(
193+ counter(&db, &student_id, "homework_on_time_total").await,
194+ 0,
195+ "... and counted as punctual"
196+ );
197+}
198+
199+/// The other half of the same misplaced gate, and the half no domain guard can
200+/// cover: the homework is still there, only the *audience* moved. A PATCH
201+/// re-scoping `assigned` holds the write lease across its orphan check, which
202+/// finds no submission and allows the narrowing; the upload, whose audience
203+/// check ran on a snapshot read before its body streamed, then lands a
204+/// submission and a file for a student the homework no longer names — the exact
205+/// orphan `ensure_no_orphans` exists to refuse.
206+///
207+/// The lease is the interleaving: a `DEFINE EVENT` on `homework` holds the
208+/// PATCH's write open, the upload's pre-flight gate reads the old audience
209+/// inside that window, and its own lease is granted only once the new audience
210+/// is committed.
211+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
212+async fn an_upload_inside_an_audience_patch_is_refused() {
213+ let _serial = ONE_RACE_AT_A_TIME.lock().await;
214+ let (app, db) = app_and_db().await;
215+ let teacher = login_as(&app, &db, "ogretmen_kapsam", "teacher").await;
216+ let course = create_course(&app, &teacher, "Coğrafya").await;
217+ let subject = create_subject(&app, &teacher, &course, "iklim").await;
218+ let dropped_student = login_as(&app, &db, "ogrenci_cikan", "student").await;
219+ let dropped_id = me_id(&app, &dropped_student).await;
220+ let kept = login_as(&app, &db, "ogrenci_kalan", "student").await;
221+ let kept_id = me_id(&app, &kept).await;
222+ enroll(&app, &teacher, &course, &dropped_id).await;
223+ enroll(&app, &teacher, &course, &kept_id).await;
224+ let res = create_homework_with(
225+ &app,
226+ &teacher,
227+ &course,
228+ json!({
229+ "title": "harita",
230+ "subject_id": subject,
231+ "due_at": far_future(),
232+ "assigned": [dropped_id.clone(), kept_id.clone()],
233+ }),
234+ )
235+ .await;
236+ assert_eq!(
237+ res.status,
238+ StatusCode::CREATED,
239+ "create the subset homework"
240+ );
241+ let hw = id_of(&res.body);
242+
243+ db.query(
244+ "DEFINE EVENT hold_the_patch ON TABLE homework WHEN $event = 'UPDATE' \
245+ THEN { SLEEP 3s; };",
246+ )
247+ .await
248+ .expect("define the window event")
249+ .check()
250+ .expect("check the window event");
251+
252+ let narrowing = {
253+ let (app, teacher, hw, kept_id) =
254+ (app.clone(), teacher.clone(), hw.clone(), kept_id.clone());
255+ tokio::spawn(async move {
256+ send(
257+ &app,
258+ "PATCH",
259+ &format!("/homework/{hw}"),
260+ Some(&teacher),
261+ Some(json!({ "assigned": [kept_id] })),
262+ )
263+ .await
264+ })
265+ };
266+ tokio::time::sleep(std::time::Duration::from_millis(1_000)).await;
267+ let uploaded = {
268+ let (app, cookie, hw) = (app.clone(), dropped_student.clone(), hw.clone());
269+ tokio::spawn(async move {
270+ let started = std::time::Instant::now();
271+ (upload_hw_file(&app, &cookie, &hw).await, started.elapsed())
272+ })
273+ };
274+ let (patched, (upload_status, took)) = (narrowing.await.unwrap(), uploaded.await.unwrap());
275+
276+ assert!(
277+ took >= std::time::Duration::from_secs(1),
278+ "the upload never contended with the PATCH ({took:?}): nothing was raced"
279+ );
280+ assert_eq!(
281+ patched.status,
282+ StatusCode::OK,
283+ "the narrowing must land: {:?}",
284+ patched.body
285+ );
286+ assert_eq!(
287+ upload_status,
288+ StatusCode::NOT_FOUND,
289+ "a student the homework no longer names must be answered 404"
290+ );
291+ assert_eq!(
292+ rows(&db, "SELECT VALUE id FROM homework_submission").await,
293+ 0,
294+ "a submission landed for a student outside the audience"
295+ );
296+ assert_eq!(
297+ rows(&db, "SELECT VALUE id FROM homework_file").await,
298+ 0,
299+ "... with a file on it"
300+ );
301+}
302+
303+/// The same hole one layer down, where the lock cannot reach it: a submission
304+/// write must collide with its homework's delete on the *store*, not merely
305+/// read the row first. `HomeworkSubmission::upsert` writes a deterministic id,
306+/// so with the parent gate removed it does not fail against a vanished
307+/// homework — it re-creates the row it was meant to be refused, badge counters
308+/// and all.
309+///
310+/// Driven at the domain layer on purpose: it is the guarantee that survives the
311+/// web layer's lock discipline being loosened again, so no handler may be in
312+/// the way of it. The delete lands first here — the interleaving pinned rather
313+/// than hoped for — which is precisely the state a lease that stops too early
314+/// leaves behind.
315+#[tokio::test]
316+async fn a_submission_under_a_vanished_homework_is_refused() {
317+ use hezarfen_backend::domain::homework::{Homework, HomeworkId};
318+ use hezarfen_backend::domain::homework_submission::HomeworkSubmission;
319+ use hezarfen_backend::domain::user::UserId;
320+
321+ let (app, db) = app_and_db().await;
322+ let teacher = login_as(&app, &db, "ogretmen_alan", "teacher").await;
323+ let (course, subject, student, student_id) =
324+ course_with_student(&app, &db, &teacher, "kimya").await;
325+ let hw = create_homework(&app, &teacher, &course, &subject, "deneme", far_future()).await;
326+ // The stale snapshot a handler would still be holding.
327+ let stale = Homework::read(&HomeworkId::from_key(&hw), &db)
328+ .await
329+ .unwrap()
330+ .expect("the homework exists");
331+ let user = UserId::from_key(&student_id);
332+
333+ let dropped = send(
334+ &app,
335+ "DELETE",
336+ &format!("/homework/{hw}"),
337+ Some(&teacher),
338+ None,
339+ )
340+ .await;
341+ assert_eq!(
342+ dropped.status,
343+ StatusCode::NO_CONTENT,
344+ "delete the homework"
345+ );
346+
347+ let refused = HomeworkSubmission::upsert(&stale, &user, None, &db).await;
348+ assert!(
349+ refused.is_err(),
350+ "a submission to a homework that is gone must be refused, got {refused:?}"
351+ );
352+ assert_eq!(
353+ rows(&db, "SELECT VALUE id FROM homework_submission").await,
354+ 0,
355+ "the refused write must leave no row"
356+ );
357+ assert_eq!(
358+ counter(&db, &student_id, "homework_submitted_total").await,
359+ 0,
360+ "... and no counter"
361+ );
362+ // The student's own route agrees, so the refusal is a 404 and not a 500.
363+ let over_http = send(
364+ &app,
365+ "POST",
366+ &format!("/homework/{hw}/submission"),
367+ Some(&student),
368+ Some(json!({ "text": "geç kaldım" })),
369+ )
370+ .await;
371+ assert_eq!(over_http.status, StatusCode::NOT_FOUND);
372+}
373+
374+/// The grade's own twin of the gate above, and the reason `delete_course`'s
375+/// homework lease is no longer the only thing standing between a grade and an
376+/// orphan: `HomeworkResult::grade` writes a deterministic id too, so against a
377+/// homework a cascade already removed it used to succeed — a `homework_result`
378+/// row nothing can reach (`GET /homework/{id}/result` has no existence check of
379+/// its own) plus a `marks_given_total` on the grader that no ungrade can give
380+/// back, since the ungrade route 404s on the vanished homework first.
381+///
382+/// Domain-level and sequential on purpose: the guarantee under test is the one
383+/// that holds when the lease does not, so no handler may be in the way of it.
384+#[tokio::test]
385+async fn a_grade_under_a_vanished_homework_is_refused() {
386+ use hezarfen_backend::domain::homework::HomeworkId;
387+ use hezarfen_backend::domain::homework_result::{HomeworkResult, HomeworkStatus};
388+ use hezarfen_backend::domain::user::UserId;
389+
390+ let (app, db) = app_and_db().await;
391+ let teacher = login_as(&app, &db, "ogretmen_not", "teacher").await;
392+ let teacher_id = me_id(&app, &teacher).await;
393+ let (course, subject, _student, student_id) =
394+ course_with_student(&app, &db, &teacher, "muzik").await;
395+ let hw = create_homework(&app, &teacher, &course, &subject, "solfej", far_future()).await;
396+
397+ let dropped = send(
398+ &app,
399+ "DELETE",
400+ &format!("/homework/{hw}"),
401+ Some(&teacher),
402+ None,
403+ )
404+ .await;
405+ assert_eq!(
406+ dropped.status,
407+ StatusCode::NO_CONTENT,
408+ "delete the homework"
409+ );
410+
411+ // The ids a handler mid-request would still be carrying.
412+ let refused = HomeworkResult::grade(
413+ &HomeworkId::from_key(&hw),
414+ &UserId::from_key(&student_id),
415+ HomeworkStatus::try_new("done").unwrap(),
416+ None,
417+ &UserId::from_key(&teacher_id),
418+ &db,
419+ )
420+ .await;
421+ assert!(
422+ refused.is_err(),
423+ "a grade on a homework that is gone must be refused, got {refused:?}"
424+ );
425+ assert_eq!(
426+ rows(&db, "SELECT VALUE id FROM homework_result").await,
427+ 0,
428+ "the refused write must leave no row"
429+ );
430+ assert_eq!(
431+ counter(&db, &teacher_id, "marks_given_total").await,
432+ 0,
433+ "... and no credit on the grader"
434+ );
435+ // The teacher's own route agrees: a 404, never a 500.
436+ let over_http = send(
437+ &app,
438+ "POST",
439+ &format!("/homework/{hw}/results"),
440+ Some(&teacher),
441+ Some(json!({ "user": student_id, "status": "done" })),
442+ )
443+ .await;
444+ assert_eq!(over_http.status, StatusCode::NOT_FOUND);
445+}
446+
447+/// `delete_course` took `EXAM_LOCK` and nothing else, while its cascade sweeps
448+/// the course's homework, submissions, files and results. Grading holds
449+/// `HOMEWORK_LOCK.write()` across a transaction that only *reads* the homework,
450+/// and the store conflict-checks write sets rather than read sets — so the
451+/// sweep ran on a snapshot without the grade and both committed: an orphan
452+/// `homework_result` under a vanished homework, readable ever after at
453+/// `GET /homework/{id}/result`, which has no existence check of its own.
454+///
455+/// The window is the grade's, not the delete's: a course delete is refused
456+/// while anyone is enrolled, so the roster has to empty *while* the grade is
457+/// mid-write — a `DEFINE EVENT` on `homework_result` holds it, gates already
458+/// passed, across the unenroll and the delete that follow. The grade's own
459+/// duration is asserted, because a grade that never reached its window would
460+/// leave this suite green over the very hole it exists for.
461+///
462+/// `marks_given_total` is deliberately *not* asserted at zero: no cascade ever
463+/// gives that counter back (the 08-05 sweep left that standing on purpose), so
464+/// a grade this test serializes *ahead* of the delete keeps its credit exactly
465+/// as an uncontested grade followed by a course delete does.
466+///
467+/// What this pins, honestly: **the outcome, not the lease**. With the lease it
468+/// passes because the grade is serialized ahead of the cascade and answered
469+/// `200`; with the lease removed it passes because
470+/// [`HomeworkResult::grade`]'s parent gate refuses the late write and answers
471+/// `404` (measured: 404 after a full 3s window). So removing *either* guard
472+/// alone leaves this green and only removing both turns it red — the same
473+/// belt-and-braces shape the upload race above has. The lease's own mutation
474+/// test died with the gate that replaced it; nothing else pins it, which is
475+/// why it is kept and documented rather than trusted to a red test.
476+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
477+async fn a_grade_inside_a_course_delete_never_orphans() {
478+ let _serial = ONE_RACE_AT_A_TIME.lock().await;
479+ let (app, db) = app_and_db().await;
480+ let teacher = login_as(&app, &db, "ogretmen_ders", "teacher").await;
481+ let (course, subject, _student, student_id) =
482+ course_with_student(&app, &db, &teacher, "tarih").await;
483+ let hw = create_homework(&app, &teacher, &course, &subject, "ödev", far_future()).await;
484+
485+ // Hold the grade's own write open, every gate already cleared. Three
486+ // seconds against a one-second wait below: under a loaded test binary the
487+ // spawned request can take a while to be polled at all, and the window has
488+ // to still be open when it gets there.
489+ db.query(
490+ "DEFINE EVENT hold_the_grade ON TABLE homework_result WHEN $event = 'CREATE' \
491+ THEN { SLEEP 3s; };",
492+ )
493+ .await
494+ .expect("define the window event")
495+ .check()
496+ .expect("check the window event");
497+
498+ let grading = {
499+ let (app, teacher, hw, target) =
500+ (app.clone(), teacher.clone(), hw.clone(), student_id.clone());
501+ tokio::spawn(async move {
502+ let started = std::time::Instant::now();
503+ let res = send(
504+ &app,
505+ "POST",
506+ &format!("/homework/{hw}/results"),
507+ Some(&teacher),
508+ Some(json!({ "user": target, "status": "done", "mark": 90 })),
509+ )
510+ .await;
511+ (res, started.elapsed())
512+ })
513+ };
514+ tokio::time::sleep(std::time::Duration::from_millis(1_000)).await;
515+ // The roster empties mid-grade — the only staging in which the course
516+ // delete is admitted at all.
517+ unenroll(&app, &teacher, &course, &student_id).await;
518+ let dropped = send(
519+ &app,
520+ "DELETE",
521+ &format!("/courses/{course}"),
522+ Some(&teacher),
523+ None,
524+ )
525+ .await;
526+ let (graded, took) = grading.await.unwrap();
527+
528+ assert!(
529+ took >= std::time::Duration::from_secs(3),
530+ "the grade never reached its window ({took:?}, answered {}): nothing was raced",
531+ graded.status
532+ );
533+ assert_eq!(
534+ dropped.status,
535+ StatusCode::NO_CONTENT,
536+ "the course delete must succeed: {:?}",
537+ dropped.body
538+ );
539+ assert!(
540+ graded.status.is_success() || graded.status == StatusCode::NOT_FOUND,
541+ "a raced grade must be answered, not {}: {:?}",
542+ graded.status,
543+ graded.body
544+ );
545+
546+ // Stored state is the whole verdict.
547+ assert_eq!(
548+ rows(&db, "SELECT VALUE id FROM homework").await,
549+ 0,
550+ "the homework survived its course"
551+ );
552+ assert_eq!(
553+ rows(&db, "SELECT VALUE id FROM homework_result").await,
554+ 0,
555+ "a grade outlived the homework it was written against"
556+ );
557+}
558+
559+/// A subset assignment is the one place the homework routes hand a student a
560+/// list of other students. The course roster itself is teacher+-only, and
561+/// `get_homework` already 404s a student the subset does not name "so a subset
562+/// assignment never reveals itself" — but to the students it *does* name it
563+/// used to serialize the whole list. Deterministic, no race: the response body
564+/// is the defect.
565+#[tokio::test]
566+async fn a_student_sees_only_themselves_in_an_assigned_subset() {
567+ let (app, db) = app_and_db().await;
568+ let teacher = login_as(&app, &db, "ogretmen_liste", "teacher").await;
569+ let course = create_course(&app, &teacher, "Biyoloji").await;
570+ let subject = create_subject(&app, &teacher, &course, "hücre").await;
571+ let ali = login_as(&app, &db, "ali", "student").await;
572+ let ali_id = me_id(&app, &ali).await;
573+ let veli = login_as(&app, &db, "veli", "student").await;
574+ let veli_id = me_id(&app, &veli).await;
575+ enroll(&app, &teacher, &course, &ali_id).await;
576+ enroll(&app, &teacher, &course, &veli_id).await;
577+
578+ let res = create_homework_with(
579+ &app,
580+ &teacher,
581+ &course,
582+ json!({
583+ "title": "sunum",
584+ "subject_id": subject,
585+ "due_at": far_future(),
586+ "assigned": [ali_id.clone(), veli_id.clone()],
587+ }),
588+ )
589+ .await;
590+ assert_eq!(
591+ res.status,
592+ StatusCode::CREATED,
593+ "create the subset homework"
594+ );
595+ let hw = id_of(&res.body);
596+
597+ let assigned = |body: &Value| -> Vec<String> {
598+ body["assigned"]
599+ .as_array()
600+ .expect("assigned is a list on a subset homework")
601+ .iter()
602+ .map(|v| v.as_str().unwrap().to_string())
603+ .collect()
604+ };
605+
606+ // The single read.
607+ let mine = send(&app, "GET", &format!("/homework/{hw}"), Some(&ali), None).await;
608+ assert_eq!(mine.status, StatusCode::OK);
609+ assert_eq!(
610+ assigned(&mine.body),
611+ vec![ali_id.clone()],
612+ "a student may learn they are assigned, never who else is"
613+ );
614+
615+ // ... the cross-course list ...
616+ let listed = send(&app, "GET", "/homework", Some(&ali), None).await;
617+ assert_eq!(listed.status, StatusCode::OK);
618+ assert_eq!(assigned(&items(&listed.body)[0]), vec![ali_id.clone()]);
619+
620+ // ... and the per-course one.
621+ let in_course = send(
622+ &app,
623+ "GET",
624+ &format!("/courses/{course}/homework"),
625+ Some(&ali),
626+ None,
627+ )
628+ .await;
629+ assert_eq!(in_course.status, StatusCode::OK);
630+ assert_eq!(assigned(&items(&in_course.body)[0]), vec![ali_id.clone()]);
631+
632+ // The teacher who runs the course still sees the roster whole — narrowing
633+ // it for them would break the audience they just set.
634+ let theirs = send(
635+ &app,
636+ "GET",
637+ &format!("/homework/{hw}"),
638+ Some(&teacher),
639+ None,
640+ )
641+ .await;
642+ assert_eq!(theirs.status, StatusCode::OK);
643+ let mut named = assigned(&theirs.body);
644+ named.sort();
645+ let mut both = vec![ali_id, veli_id];
646+ both.sort();
647+ assert_eq!(named, both, "the assigning teacher keeps the whole subset");
648+}
649+
650+/// A file add and a file delete on one submission write the same row — the
651+/// upload claims its seat on it, the delete re-stamps it — and both handlers
652+/// hold only `HOMEWORK_LOCK.read()`, so they contend by design. The delete sent
653+/// its cascade through a plain `db.query`, unlike every sibling in the module,
654+/// so a lost round came back as a 500 on a request that had written nothing.
655+///
656+/// The window is the *delete's* own — the retry-less side has to be the one
657+/// holding a stale write when the other commits, or nothing it does can be
658+/// answered "conflict, retry": a `DEFINE EVENT` on `homework_file` holds the
659+/// delete's transaction open after it has re-stamped the submission row, and an
660+/// upload lands on that same row inside it. Held short (150ms): the retry
661+/// budget is 8 tries over ~250ms of backoff, so a window wider than the budget
662+/// would fail a *correct* implementation too.
663+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
664+async fn a_file_add_racing_a_file_delete_never_500s() {
665+ let _serial = ONE_RACE_AT_A_TIME.lock().await;
666+ let (app, db) = app_and_db().await;
667+ let teacher = login_as(&app, &db, "ogretmen_dosya", "teacher").await;
668+ let (course, subject, student, _student_id) =
669+ course_with_student(&app, &db, &teacher, "resim").await;
670+ let hw = create_homework(&app, &teacher, &course, &subject, "çizim", far_future()).await;
671+ assert_eq!(
672+ upload_hw_file(&app, &student, &hw).await,
673+ StatusCode::CREATED,
674+ "the first file"
675+ );
676+ let listed = send(
677+ &app,
678+ "GET",
679+ &format!("/homework/{hw}/submission"),
680+ Some(&student),
681+ None,
682+ )
683+ .await;
684+ let first = listed.body["files"][0]["id"].as_str().unwrap().to_string();
685+
686+ db.query(
687+ "DEFINE EVENT hold_the_delete ON TABLE homework_file WHEN $event = 'DELETE' \
688+ THEN { SLEEP 150ms; };",
689+ )
690+ .await
691+ .expect("define the window event")
692+ .check()
693+ .expect("check the window event");
694+
695+ let removing = {
696+ let (app, student, hw, first) = (app.clone(), student.clone(), hw.clone(), first.clone());
697+ tokio::spawn(async move {
698+ send(
699+ &app,
700+ "DELETE",
701+ &format!("/homework/{hw}/submission/files/{first}"),
702+ Some(&student),
703+ None,
704+ )
705+ .await
706+ })
707+ };
708+ // The upload commits on the submission row while the delete is still
709+ // holding its own write of it.
710+ tokio::time::sleep(std::time::Duration::from_millis(40)).await;
711+ let added = upload_hw_file(&app, &student, &hw).await;
712+ let removed = removing.await.unwrap();
713+
714+ assert_ne!(
715+ removed.status,
716+ StatusCode::INTERNAL_SERVER_ERROR,
717+ "a lost round is a re-send, not a 500: {:?}",
718+ removed.body
719+ );
720+ assert_ne!(
721+ added,
722+ StatusCode::INTERNAL_SERVER_ERROR,
723+ "... on either side"
724+ );
725+ // Whatever the order, the stored count matches the stored rows: the
726+ // submission's seat counter is what the cap reads next time.
727+ let files = rows(&db, "SELECT VALUE id FROM homework_file").await;
728+ let mut result = db
729+ .query("SELECT VALUE (file_count ?? 0) FROM homework_submission")
730+ .await
731+ .unwrap()
732+ .check()
733+ .unwrap();
734+ let counted: Vec<i64> = result.take(0).unwrap();
735+ assert_eq!(
736+ counted.first().copied().unwrap_or(0),
737+ files as i64,
738+ "the seat counter drifted from the rows"
739+ );
740+}