forge
Explore
Log in

Don't you dare go Hollow

Port homework to sqlx/Postgres

Browse files at this commit

67f014aa940a28b4a72c33cb38669361e27718d1Ahmet Kaan GümüşParent: 68db815
  • feat
    • port homework to sqlx/Postgres
Show full message
🗃️ feat!: port homework to sqlx/Postgres

11 changed files +1175 -866

src/db/homework.rsmodified+403 -139
@@ -1,25 +1,22 @@
1-//! The `homework` table: row reads and listings, the count-and-create that
2-//! pins a homework to a live subject row, the reference-counting PATCH, and
3-//! the cascading delete. The PATCH's orphan guard and the audience gate live
4-//! in [`crate::service::homework`].
1+//! The `homework` table: row reads and listings, the subject-counter claim
2+//! that pins a homework to a live subject row, the reference-counting PATCH —
3+//! whose audience-narrowing orphan guard is one transaction with the write,
4+//! serialized on the homework row's `FOR UPDATE` lock — and the cascading
5+//! delete.
56
6-use surrealdb::types::RecordId;
7-
8-use crate::constant::SUBJECT_HOMEWORK_COUNT_FIELD;
9-use crate::database::Database;
10-use crate::db::cap;
11-use crate::db::field_update::FieldUpdate;
7+use crate::database::{Database, tx_with_retry};
128 use crate::domain::course::CourseId;
139 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};
1410 use crate::domain::subject::SubjectId;
1511 use crate::domain::timestamp::Timestamp;
1612 use crate::domain::user::UserId;
1713 use crate::error::{AppError, ValidationError};
14+use sqlx::PgConnection;
1815
1916 /// The answer a link to a subject that is not there gets, on create and on
20-/// re-tag alike — both claims are conditional writes on the subject row, so a
21-/// subject a delete already removed matches nothing and the caller says exactly
22-/// what the web layer's pre-flight lookup would have.
17+/// re-tag alike — the conditional claim on the subject row matches nothing,
18+/// and the caller says exactly what the web layer's pre-flight lookup would
19+/// have.
2320 fn subject_gone() -> AppError {
2421 AppError::Validation(ValidationError::Invalid {
2522 field: "subject_id",
@@ -27,6 +24,12 @@ fn subject_gone() -> AppError {
2724 })
2825 }
2926
27+/// What a stale re-tag answers. The shared PATCH builder
28+/// ([`crate::db::field_update`]) carries the same refusal; the homework PATCH
29+/// keeps its own copy because its orphan guard needs the row lock the generic
30+/// builder cannot take.
31+const STALE_MOVE: &str = "the link this update moves changed since it was read; re-read and retry";
32+
3033 #[expect(
3134 clippy::too_many_arguments,
3235 reason = "mirrors the sibling entities' create(field, field, ..) shape"
@@ -41,16 +44,14 @@ pub async fn create(
4144 assigned: Option<Vec<UserId>>,
4245 created_by: &UserId,
4346 ) -> Result<Homework, AppError> {
44- // The subject's reference is taken in the very transaction that writes
45- // the row — the exam question's twin
46- // ([`crate::db::exam_question`]): the subject delete
47- // is refused while this counter is non-zero, so the create and the
48- // delete contend on the subject record rather than on a cross-table
49- // count neither of them sees the other move, and a crash can no longer
50- // strand a claim that would make the subject undeletable forever. A
51- // refused claim means the subject is already gone, which is the 400 the
52- // web layer's pre-flight check answers with.
53- let counted = subject.record();
47+ // The subject's reference is taken in the very statement that writes the
48+ // row — the exam question's twin ([`crate::db::exam_question`]): the
49+ // claim (`UPDATE subject … +1`) and the insert are one CTE, so a subject
50+ // a delete already removed matches nothing and nothing is written, which
51+ // is the 400 the web layer's pre-flight check answers with. The subject
52+ // delete is refused while this counter is non-zero, so the two writers
53+ // contend on the subject row itself, and a crash cannot strand a claim
54+ // that would make the subject undeletable forever.
5455 let homework = Homework {
5556 id: HomeworkId::generate(),
5657 course: course.clone(),
@@ -62,46 +63,111 @@ pub async fn create(
6263 created_by: created_by.clone(),
6364 created_at: Timestamp::now(),
6465 };
65- let id = homework.id.record();
66- match cap::claim_and_create(
67- &counted,
68- SUBJECT_HOMEWORK_COUNT_FIELD,
69- cap::UNLIMITED,
70- &id,
71- &homework,
72- db,
66+ let assigned_values = homework.assigned.clone().unwrap_or_default();
67+ // The fresh v7 id cannot collide, so the pair-unique answer has no rival
68+ // here; the mapping is kept for symmetry with the other claim sites.
69+ let created = sqlx::query_as!(
70+ Homework,
71+ r#"WITH seat AS (
72+ UPDATE subject SET homework_count = homework_count + 1
73+ WHERE id = $1
74+ RETURNING 1
75+ )
76+ INSERT INTO homework (id, course, subject, title, description, due_at, assigned, created_by, created_at)
77+ SELECT $2, $3, $1, $4, $5, $6, $7, $8, $9 WHERE EXISTS (SELECT 1 FROM seat)
78+ RETURNING id AS "id: HomeworkId",
79+ course AS "course: CourseId",
80+ subject AS "subject: SubjectId",
81+ title AS "title: HomeworkTitle",
82+ description AS "description: Option<HomeworkDescription>",
83+ due_at AS "due_at: Timestamp",
84+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
85+ AS "assigned: Option<Vec<UserId>>",
86+ created_by AS "created_by: UserId",
87+ created_at AS "created_at: Timestamp""#,
88+ subject,
89+ homework.id,
90+ course,
91+ homework.title,
92+ homework.description,
93+ homework.due_at,
94+ assigned_values,
95+ homework.created_by,
96+ homework.created_at,
7397 )
74- .await?
75- {
76- cap::Claimed::Made(created) => Ok(created),
77- cap::Claimed::Full => Err(subject_gone()),
78- cap::Claimed::Duplicate => Err(AppError::Internal("failed to create homework".into())),
79- }
98+ .fetch_optional(db)
99+ .await
100+ .map_err(|err| {
101+ if crate::database::unique_violation(&err).is_some() {
102+ AppError::Internal("failed to create homework".into())
103+ } else {
104+ AppError::from(err)
105+ }
106+ })?;
107+ created.ok_or_else(subject_gone)
80108 }
81109
82110 pub async fn read(db: &Database, id: &HomeworkId) -> Result<Option<Homework>, AppError> {
83- Ok(db.select(id.record()).await?)
111+ Ok(sqlx::query_as!(
112+ Homework,
113+ r#"SELECT id AS "id: HomeworkId",
114+ course AS "course: CourseId",
115+ subject AS "subject: SubjectId",
116+ title AS "title: HomeworkTitle",
117+ description AS "description: Option<HomeworkDescription>",
118+ due_at AS "due_at: Timestamp",
119+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
120+ AS "assigned: Option<Vec<UserId>>",
121+ created_by AS "created_by: UserId",
122+ created_at AS "created_at: Timestamp"
123+ FROM homework WHERE id = $1"#,
124+ id
125+ )
126+ .fetch_optional(db)
127+ .await?)
84128 }
85129
86-/// The course's homework, newest first (ULID ids sort by creation). The web
130+/// The course's homework, newest first (v7 ids sort by creation). The web
87131 /// layer retains only the rows a given student `student_sees`.
88132 pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Homework>, AppError> {
89- let mut result = db
90- .query("SELECT * FROM homework WHERE course = $course ORDER BY id DESC")
91- .bind(("course", course.record()))
92- .await?
93- .check()?;
94- Ok(result.take::<Vec<Homework>>(0)?)
133+ Ok(sqlx::query_as!(
134+ Homework,
135+ r#"SELECT id AS "id: HomeworkId",
136+ course AS "course: CourseId",
137+ subject AS "subject: SubjectId",
138+ title AS "title: HomeworkTitle",
139+ description AS "description: Option<HomeworkDescription>",
140+ due_at AS "due_at: Timestamp",
141+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
142+ AS "assigned: Option<Vec<UserId>>",
143+ created_by AS "created_by: UserId",
144+ created_at AS "created_at: Timestamp"
145+ FROM homework WHERE course = $1 ORDER BY id DESC"#,
146+ course
147+ )
148+ .fetch_all(db)
149+ .await?)
95150 }
96151
97152 /// Every homework in the system, newest first — the manager+ view of the
98153 /// cross-course "my homework" list.
99154 pub async fn list_all(db: &Database) -> Result<Vec<Homework>, AppError> {
100- let mut result = db
101- .query("SELECT * FROM homework ORDER BY id DESC")
102- .await?
103- .check()?;
104- Ok(result.take::<Vec<Homework>>(0)?)
155+ Ok(sqlx::query_as!(
156+ Homework,
157+ r#"SELECT id AS "id: HomeworkId",
158+ course AS "course: CourseId",
159+ subject AS "subject: SubjectId",
160+ title AS "title: HomeworkTitle",
161+ description AS "description: Option<HomeworkDescription>",
162+ due_at AS "due_at: Timestamp",
163+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
164+ AS "assigned: Option<Vec<UserId>>",
165+ created_by AS "created_by: UserId",
166+ created_at AS "created_at: Timestamp"
167+ FROM homework ORDER BY id DESC"#,
168+ )
169+ .fetch_all(db)
170+ .await?)
105171 }
106172
107173 /// Every homework of every course in `courses`, newest first (one query) —
@@ -115,51 +181,71 @@ pub async fn list_for_courses(
115181 if courses.is_empty() {
116182 return Ok(Vec::new());
117183 }
118- let records: Vec<RecordId> = courses.iter().map(CourseId::record).collect();
119- let mut result = db
120- .query("SELECT * FROM homework WHERE course IN $courses ORDER BY id DESC")
121- .bind(("courses", records))
122- .await?
123- .check()?;
124- Ok(result.take::<Vec<Homework>>(0)?)
184+ let ids: Vec<CourseId> = courses.to_vec();
185+ Ok(sqlx::query_as!(
186+ Homework,
187+ r#"SELECT id AS "id: HomeworkId",
188+ course AS "course: CourseId",
189+ subject AS "subject: SubjectId",
190+ title AS "title: HomeworkTitle",
191+ description AS "description: Option<HomeworkDescription>",
192+ due_at AS "due_at: Timestamp",
193+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
194+ AS "assigned: Option<Vec<UserId>>",
195+ created_by AS "created_by: UserId",
196+ created_at AS "created_at: Timestamp"
197+ FROM homework WHERE course = ANY($1) ORDER BY id DESC"#,
198+ ids
199+ )
200+ .fetch_all(db)
201+ .await?)
125202 }
126203
127204 /// The homework of `course` that `user` is meant to see — whole-course ones
128205 /// plus any subset that names them — newest first. Backs a student's (or an
129206 /// observer's) per-course homework report; mirrors
130207 /// [`Homework::student_sees`](crate::domain::homework::Homework::student_sees)
131-/// in SurQL so the filter runs in the database.
208+/// in SQL so the filter runs in the database.
132209 pub async fn list_for_user_in_course(
133210 db: &Database,
134211 course: &CourseId,
135212 user: &UserId,
136213 ) -> Result<Vec<Homework>, AppError> {
137- let mut result = db
138- .query(
139- "SELECT * FROM homework
140- WHERE course = $course
141- AND (assigned = NONE OR assigned = [] OR $usr IN assigned)
142- ORDER BY id DESC",
143- )
144- .bind(("course", course.record()))
145- .bind(("usr", user.record()))
146- .await?
147- .check()?;
148- Ok(result.take::<Vec<Homework>>(0)?)
214+ Ok(sqlx::query_as!(
215+ Homework,
216+ r#"SELECT id AS "id: HomeworkId",
217+ course AS "course: CourseId",
218+ subject AS "subject: SubjectId",
219+ title AS "title: HomeworkTitle",
220+ description AS "description: Option<HomeworkDescription>",
221+ due_at AS "due_at: Timestamp",
222+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
223+ AS "assigned: Option<Vec<UserId>>",
224+ created_by AS "created_by: UserId",
225+ created_at AS "created_at: Timestamp"
226+ FROM homework
227+ WHERE course = $1 AND (cardinality(assigned) = 0 OR $2 = ANY(assigned))
228+ ORDER BY id DESC"#,
229+ course,
230+ user
231+ )
232+ .fetch_all(db)
233+ .await?)
149234 }
150235
151236 /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework.
152237 /// Request-scoped: every parameter is `Option`, `None` meaning the PATCH
153238 /// did not carry that field, so it is not written at all. Handing the
154239 /// snapshot's value back instead would revert a concurrent edit of that
155-/// field — scoping the `SET` alone does not prevent that, the *values* must
156-/// come from the request. `course`, `created_by`, and `created_at` are
157-/// `READONLY` and never appear in the write.
240+/// field — under the row lock below, an uncarried field keeps the value read
241+/// *under that lock*, never the handler's snapshot. `course`, `created_by`,
242+/// and `created_at` are readonly and never appear in the write.
158243 ///
159-/// `description` and `assigned` are nullable columns, so they take a
160-/// `NONE` (clear the description / widen back to the whole course). The web
161-/// layer has already re-checked a new `due_at` against now, a new `subject`
162-/// against the course, and refused a narrowing that would orphan work.
244+/// `description` takes `Some(None)` to clear; `assigned` takes `Some(None)`
245+/// to widen back to the whole course (stored as `'{}'`, read back as `None`).
246+/// The web layer has already re-checked a new `due_at` against now, a new
247+/// `subject` against the course, and — inside the transaction here — the
248+/// narrowing against the work that would be orphaned by it.
163249 pub async fn update(
164250 db: &Database,
165251 homework: Homework,
@@ -169,75 +255,250 @@ pub async fn update(
169255 due_at: Option<Timestamp>,
170256 assigned: Option<Option<Vec<UserId>>>,
171257 ) -> Result<Homework, AppError> {
172- let assigned = assigned
173- .map(|subset| subset.map(|users| users.iter().map(UserId::record).collect::<Vec<_>>()));
174- // A re-tag moves a reference: the new subject's claim and the old one's
175- // release ride the same transaction as the link write, so no crash can
176- // leave a count without its link (the subject would be undeletable
177- // forever) or a link without its count. `subject` is required, so the
178- // snapshot's value is always the CAS expectation — two PATCHes moving
179- // the same homework off the same subject would otherwise both claim
180- // their target, and the loser is refused with a 409 instead. The
181- // `.refcount` call is unconditional: the CAS is armed by the request
182- // *carrying* `subject_id`, not by a counter moving, so a PATCH that
183- // re-states the tag its snapshot showed — shifting no counter at all —
184- // is still refused when a rival moved the tag in between. A PATCH that
185- // carried no `subject_id` arms nothing and writes what it always did.
186- let (claim, release) = subject
187- .as_ref()
188- .filter(|next| **next != homework.subject)
189- .map(|next| (next.record(), homework.subject.record()))
190- .unzip();
191- FieldUpdate::new(homework.id.record())
192- .set("subject", subject.map(|subject| subject.record()))
193- .set("title", title)
194- .set("description", description)
195- .set("due_at", due_at)
196- .set("assigned", assigned)
197- .refcount(
198- SUBJECT_HOMEWORK_COUNT_FIELD,
199- "subject",
200- Some(homework.subject.record()),
201- claim,
202- release,
203- subject_gone(),
258+ tx_with_retry(db, false, async |tx| {
259+ // The homework row's lock. The orphan guard's reads and the write
260+ // below are one transaction with it, so a submission — whose own
261+ // transaction locks this very row before writing — cannot land
262+ // between the check and the narrowing, orphaned by an audience change
263+ // that just missed it. The lock also replaces the old CAS's row read:
264+ // the re-tag check below compares the handler's snapshot against the
265+ // row as it is *locked*, not as it was first read.
266+ let current = sqlx::query_as!(
267+ Homework,
268+ r#"SELECT id AS "id: HomeworkId",
269+ course AS "course: CourseId",
270+ subject AS "subject: SubjectId",
271+ title AS "title: HomeworkTitle",
272+ description AS "description: Option<HomeworkDescription>",
273+ due_at AS "due_at: Timestamp",
274+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
275+ AS "assigned: Option<Vec<UserId>>",
276+ created_by AS "created_by: UserId",
277+ created_at AS "created_at: Timestamp"
278+ FROM homework WHERE id = $1 FOR UPDATE"#,
279+ homework.get_id()
204280 )
205- .run::<Homework>(db)
206- .await
281+ .fetch_optional(&mut *tx)
282+ .await?
283+ .ok_or(AppError::NotFound)?;
284+
285+ // The orphan guard runs on exactly the requests that re-scope the
286+ // audience. An absent `assigned` writes nothing, so the stored subset
287+ // is untouched and no narrowing can happen behind the guard's back.
288+ if let Some(resolved) = assigned.as_ref() {
289+ ensure_no_orphans(&current, resolved.as_deref(), tx).await?;
290+ }
291+
292+ // A re-tag moves a reference: the new subject's claim and the old
293+ // one's release ride the same transaction as the link write, so no
294+ // crash can leave a count without its link (the subject would be
295+ // undeletable forever) or a link without its count. The release goes
296+ // first and the claim refuses on a gone row, so a move to a deleted
297+ // subject is a rolled-back no-op — every abort takes the whole move
298+ // back with it.
299+ let moving = subject.as_ref().filter(|next| **next != homework.subject);
300+ if let Some(next) = moving {
301+ sqlx::query!(
302+ "UPDATE subject SET homework_count = GREATEST(homework_count - 1, 0) WHERE id = $1",
303+ current.subject
304+ )
305+ .execute(&mut *tx)
306+ .await?;
307+ let seat = sqlx::query!(
308+ r#"UPDATE subject SET homework_count = homework_count + 1
309+ WHERE id = $1 RETURNING 1 AS "seat: i32""#,
310+ next
311+ )
312+ .fetch_optional(&mut *tx)
313+ .await?;
314+ if seat.is_none() {
315+ return Err(subject_gone());
316+ }
317+ }
318+
319+ // The stale-re-tag check. Armed by the request *carrying* the subject
320+ // — even when it re-states the tag its snapshot showed, shifting no
321+ // counter — so two PATCHes moving the same homework off the same
322+ // subject cannot both claim their target: the loser's snapshot says
323+ // A, the locked row says B, and the refusal is the 409 the generic
324+ // PATCH builder has always answered with.
325+ if subject.is_some() && current.subject != homework.subject {
326+ return Err(AppError::Conflict(STALE_MOVE.to_string()));
327+ }
328+
329+ // What the PATCH carried is written; what it did not carry keeps the
330+ // value just read under the lock. Under that lock this resolved
331+ // full-row write is exactly the request-scoped SET the old builder
332+ // emitted — except it is one static statement instead of a runtime
333+ // build.
334+ let new_subject = subject.clone().unwrap_or_else(|| current.subject.clone());
335+ let new_title = title.unwrap_or_else(|| current.title.clone());
336+ let new_description = match description {
337+ None => current.description.clone(),
338+ Some(None) => None,
339+ Some(Some(text)) => Some(text),
340+ };
341+ let new_due_at = due_at.unwrap_or(current.due_at);
342+ let new_assigned = match assigned {
343+ None => current.assigned.clone(),
344+ // Clear = the whole course, stored as `'{}'`.
345+ Some(None) => None,
346+ Some(Some(subset)) => Some(subset),
347+ };
348+ let assigned_values = new_assigned.unwrap_or_default();
349+ sqlx::query_as!(
350+ Homework,
351+ r#"UPDATE homework SET subject = $2, title = $3, description = $4,
352+ due_at = $5, assigned = $6
353+ WHERE id = $1
354+ RETURNING id AS "id: HomeworkId",
355+ course AS "course: CourseId",
356+ subject AS "subject: SubjectId",
357+ title AS "title: HomeworkTitle",
358+ description AS "description: Option<HomeworkDescription>",
359+ due_at AS "due_at: Timestamp",
360+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
361+ AS "assigned: Option<Vec<UserId>>",
362+ created_by AS "created_by: UserId",
363+ created_at AS "created_at: Timestamp""#,
364+ homework.get_id(),
365+ new_subject,
366+ new_title,
367+ new_description,
368+ new_due_at,
369+ assigned_values,
370+ )
371+ .fetch_optional(&mut *tx)
372+ .await?
373+ .ok_or(AppError::NotFound)
374+ })
375+ .await
376+}
377+
378+/// Refuse (409) a PATCH that would narrow `homework`'s audience so a student
379+/// who already submitted or was graded falls outside it — their work would be
380+/// stranded. `new_assigned` is the proposed subset (`None` = whole course, in
381+/// which case no one can be orphaned). The blocking students are named in the
382+/// message so the teacher knows whose work to clear (or whom to keep assigned)
383+/// first.
384+///
385+/// Runs inside the caller's transaction, under the homework row's lock, so
386+/// the check and the narrowing cannot be driven through by a submission.
387+async fn ensure_no_orphans(
388+ homework: &Homework,
389+ new_assigned: Option<&[UserId]>,
390+ tx: &mut PgConnection,
391+) -> Result<(), AppError> {
392+ // Whole-course covers everyone — no narrowing, no orphans.
393+ let Some(subset) = new_assigned else {
394+ return Ok(());
395+ };
396+ let submitted: Vec<UserId> = sqlx::query!(
397+ r#"SELECT app_user AS "user: UserId" FROM homework_submission WHERE homework = $1"#,
398+ homework.get_id()
399+ )
400+ .fetch_all(&mut *tx)
401+ .await?
402+ .into_iter()
403+ .map(|row| row.user)
404+ .collect();
405+ let graded: Vec<UserId> = sqlx::query!(
406+ r#"SELECT app_user AS "user: UserId" FROM homework_result WHERE homework = $1"#,
407+ homework.get_id()
408+ )
409+ .fetch_all(&mut *tx)
410+ .await?
411+ .into_iter()
412+ .map(|row| row.user)
413+ .collect();
414+ let mut blocked: Vec<String> = Vec::new();
415+ for user in submitted.iter().chain(graded.iter()) {
416+ let key = user.key().to_string();
417+ if !subset.contains(user) && !blocked.contains(&key) {
418+ blocked.push(key);
419+ }
420+ }
421+ if blocked.is_empty() {
422+ Ok(())
423+ } else {
424+ Err(AppError::ConflictOwned(format!(
425+ "narrowing the assigned list would orphan existing work by {} student(s): {}",
426+ blocked.len(),
427+ blocked.join(", ")
428+ )))
429+ }
207430 }
208431
209432 /// Delete the homework and cascade its submissions, their files, and its
210433 /// results — one transaction, so a crash can't orphan a submission under a
211434 /// vanished homework. The submission file *blobs* are the web layer's to
212-/// unlink: it collects their names via
213-/// [`crate::db::homework_file::file_keys_for_homework`]
214-/// before calling this, and removes them after the rows are gone.
215-pub async fn delete(db: &Database, homework: Homework) -> Result<Homework, AppError> {
216- let mut result = db
217- .query(
218- format!(
219- "BEGIN TRANSACTION;
220- DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw);
221- DELETE homework_submission WHERE homework = $hw;
222- DELETE homework_result WHERE homework = $hw;
223- LET $gone = (DELETE $hw RETURN BEFORE);
224- FOR $sub IN ($gone.subject ?? []) {{
225- UPDATE $sub SET {SUBJECT_HOMEWORK_COUNT_FIELD} =
226- math::max([({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) - 1, 0])
227- }};
228- RETURN $gone;
229- COMMIT TRANSACTION;"
230- ),
435+/// unlink: their names are returned (collected inside the transaction,
436+/// before the wipes — a file row inserted after an out-of-transaction
437+/// collection would be deleted here while its key was already gone from the
438+/// list, stranding the blob) and removed after the rows are gone.
439+pub async fn delete(
440+ db: &Database,
441+ homework: Homework,
442+) -> Result<(Homework, Vec<String>), AppError> {
443+ tx_with_retry(db, true, async |tx| {
444+ let blob_keys: Vec<String> = sqlx::query!(
445+ r#"SELECT file FROM homework_file
446+ WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#,
447+ homework.get_id()
231448 )
232- .bind(("hw", homework.id.record()))
449+ .fetch_all(&mut *tx)
233450 .await?
234- .check()?;
235- // The subject's reference is given back in this same transaction, off
236- // what the delete actually removed. Read through the trailing `RETURN`,
237- // not a hand-counted slot — see [`crate::db::exam::delete`].
238- let slot = result.num_statements().saturating_sub(2);
239- let deleted: Option<Homework> = result.take::<Vec<Homework>>(slot)?.into_iter().next();
240- deleted.ok_or(AppError::NotFound)
451+ .into_iter()
452+ .map(|row| row.file)
453+ .collect();
454+ sqlx::query!(
455+ r#"DELETE FROM homework_file
456+ WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#,
457+ homework.get_id()
458+ )
459+ .execute(&mut *tx)
460+ .await?;
461+ sqlx::query!(
462+ "DELETE FROM homework_result WHERE homework = $1",
463+ homework.get_id()
464+ )
465+ .execute(&mut *tx)
466+ .await?;
467+ sqlx::query!(
468+ "DELETE FROM homework_submission WHERE homework = $1",
469+ homework.get_id()
470+ )
471+ .execute(&mut *tx)
472+ .await?;
473+ let deleted = sqlx::query_as!(
474+ Homework,
475+ r#"DELETE FROM homework WHERE id = $1
476+ RETURNING id AS "id: HomeworkId",
477+ course AS "course: CourseId",
478+ subject AS "subject: SubjectId",
479+ title AS "title: HomeworkTitle",
480+ description AS "description: Option<HomeworkDescription>",
481+ due_at AS "due_at: Timestamp",
482+ CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END
483+ AS "assigned: Option<Vec<UserId>>",
484+ created_by AS "created_by: UserId",
485+ created_at AS "created_at: Timestamp""#,
486+ homework.get_id()
487+ )
488+ .fetch_optional(&mut *tx)
489+ .await?
490+ .ok_or(AppError::NotFound)?;
491+ // The subject's reference is given back in this same transaction, off
492+ // the row the delete actually removed.
493+ sqlx::query!(
494+ "UPDATE subject SET homework_count = GREATEST(homework_count - 1, 0) WHERE id = $1",
495+ deleted.subject
496+ )
497+ .execute(&mut *tx)
498+ .await?;
499+ Ok((deleted, blob_keys))
500+ })
501+ .await
241502 }
242503
243504 #[cfg(test)]
@@ -360,7 +621,10 @@ mod tests {
360621 "the old subject is free"
361622 );
362623 assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not");
363- assert!(crate::db::subject::delete(&db, from).await.is_ok(), "no reference left");
624+ assert!(
625+ crate::db::subject::delete(&db, from).await.is_ok(),
626+ "no reference left"
627+ );
364628 assert!(
365629 crate::db::subject::delete(&db, to).await.is_err(),
366630 "the reference moved here refuses the delete"
src/db/homework_file.rsmodified+183 -133
@@ -4,56 +4,70 @@
44 //! their validated fields live in [`crate::domain::homework_file`]; the
55 //! upload workflow around them in [`crate::service::homework_file`].
66
7-use surrealdb::types::SurrealValue;
8-
9-use crate::constant::{
10- MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD, SUBMISSION_OPEN_GUARD,
11-};
12-use crate::database::{Database, transaction_with_retry};
13-use crate::db::cap;
7+use crate::constant::MAX_HOMEWORK_FILES_PER_SUBMISSION;
8+use crate::database::{Database, tx_with_retry};
149 use crate::domain::course::CourseId;
1510 use crate::domain::homework::HomeworkId;
1611 use crate::domain::homework_file::HomeworkFile;
12+use crate::domain::homework_file::HomeworkFileId;
13+use crate::domain::homework_submission::HomeworkSubmissionId;
14+use crate::domain::note_file::{FileContentType, FileName};
1715 use crate::domain::timestamp::Timestamp;
1816 use crate::error::AppError;
1917
20-/// What [`delete`]'s transaction reports: whether the submission
21-/// was still open (`open` = 1, the gate bit) and the row it then removed. Two
22-/// answers in one object because an empty `gone` alone cannot say whether the
23-/// delete was refused or the file had simply vanished.
24-#[derive(Debug, SurrealValue)]
25-struct DeleteOutcome {
26- open: i64,
27- gone: Vec<HomeworkFile>,
28-}
29-
3018 /// Persist the row assembled by
3119 /// [`HomeworkFile::new`](crate::domain::homework_file::HomeworkFile::new),
3220 /// refusing once its submission already holds
3321 /// [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`)
3422 /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own
35-/// wording). Both are decided by one [`cap::claim_when_and_create`] on the
36-/// submission row — the seat and the file row commit together, so a crash
37-/// between them can no longer leave a slot claimed by a file that does not
38-/// exist, and a losing upload never has to be un-counted. Which of the two
39-/// conditions refused it is read back afterwards, off the losing path only,
40-/// and only to pick the message: `Claimed::Full` says "full *or* graded *or*
41-/// the submission is gone".
23+/// wording). Both are decided by one guarded insert on the submission row —
24+/// the seat (`UPDATE … file_count + 1 WHERE file_count < $cap AND
25+/// graded_by_result IS NULL`) and the file row commit together in one CTE, so
26+/// a crash between them can no longer leave a slot claimed by a file that
27+/// does not exist, and a losing upload never has to be un-counted. Which of
28+/// the two conditions refused it is read back afterwards, off the losing
29+/// path only, and only to pick the message: zero rows says "full *or* graded
30+/// *or* the submission is gone".
4231 pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> {
43- // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber
44- match cap::claim_when_and_create(
45- &file.submission.record(),
46- SUBMISSION_FILE_COUNT_FIELD,
32+ let created = sqlx::query_as!(
33+ HomeworkFile,
34+ r#"WITH seat AS (
35+ UPDATE homework_submission SET file_count = file_count + 1
36+ WHERE id = $2 AND file_count < $1 AND graded_by_result IS NULL
37+ RETURNING 1
38+ )
39+ INSERT INTO homework_file (id, submission, name, content_type, size, file, created_at)
40+ SELECT $3, $2, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat)
41+ RETURNING id AS "id: HomeworkFileId",
42+ submission AS "submission: HomeworkSubmissionId",
43+ name AS "name: FileName",
44+ content_type AS "content_type: FileContentType",
45+ size,
46+ file,
47+ created_at AS "created_at: Timestamp""#,
4748 MAX_HOMEWORK_FILES_PER_SUBMISSION as i64,
48- SUBMISSION_OPEN_GUARD,
49- &file.id.record(),
50- &file,
51- db,
49+ file.submission,
50+ file.id,
51+ file.name,
52+ file.content_type,
53+ file.size,
54+ file.file,
55+ file.created_at,
5256 )
53- .await?
54- {
55- cap::Claimed::Made(created) => Ok(Some(created)),
56- cap::Claimed::Full => {
57+ .fetch_optional(db)
58+ .await
59+ .map_err(|err| {
60+ // The id is a fresh v7 minted by `new`, so a row already holding it
61+ // is a collision, not a re-upload.
62+ if crate::database::unique_violation(&err).is_some() {
63+ AppError::Internal("homework file id collided".into())
64+ } else {
65+ AppError::from(err)
66+ }
67+ })?;
68+ match created {
69+ Some(row) => Ok(Some(row)),
70+ None => {
5771 if super::homework_submission::is_graded(db, &file.submission).await? {
5872 return Ok(None);
5973 }
@@ -61,9 +75,6 @@ pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<Homework
6175 "the submission already holds the maximum of 10 files — delete one first",
6276 ))
6377 }
64- // The id is a fresh ULID minted by `new`, so a row already holding it
65- // is a collision, not a re-upload.
66- cap::Claimed::Duplicate => Err(AppError::Internal("homework file id collided".into())),
6778 }
6879 }
6980
@@ -74,8 +85,21 @@ pub async fn read_for(
7485 id: &crate::domain::homework_file::HomeworkFileId,
7586 submission: &crate::domain::homework_submission::HomeworkSubmissionId,
7687 ) -> Result<Option<HomeworkFile>, AppError> {
77- let file: Option<HomeworkFile> = db.select(id.record()).await?;
78- Ok(file.filter(|file| &file.submission == submission))
88+ Ok(sqlx::query_as!(
89+ HomeworkFile,
90+ r#"SELECT id AS "id: HomeworkFileId",
91+ submission AS "submission: HomeworkSubmissionId",
92+ name AS "name: FileName",
93+ content_type AS "content_type: FileContentType",
94+ size,
95+ file,
96+ created_at AS "created_at: Timestamp"
97+ FROM homework_file WHERE id = $1 AND submission = $2"#,
98+ id,
99+ submission
100+ )
101+ .fetch_optional(db)
102+ .await?)
79103 }
80104
81105 /// Read a file by id only if it hangs off a submission to `homework` — the
@@ -89,16 +113,23 @@ pub async fn read_in_homework(
89113 id: &crate::domain::homework_file::HomeworkFileId,
90114 homework: &HomeworkId,
91115 ) -> Result<Option<HomeworkFile>, AppError> {
92- let mut result = db
93- .query(
94- "SELECT * FROM homework_file WHERE id = $id AND submission IN \
95- (SELECT VALUE id FROM homework_submission WHERE homework = $hw)",
96- )
97- .bind(("id", id.record()))
98- .bind(("hw", homework.record()))
99- .await?
100- .check()?;
101- Ok(result.take::<Vec<HomeworkFile>>(0)?.into_iter().next())
116+ Ok(sqlx::query_as!(
117+ HomeworkFile,
118+ r#"SELECT id AS "id: HomeworkFileId",
119+ submission AS "submission: HomeworkSubmissionId",
120+ name AS "name: FileName",
121+ content_type AS "content_type: FileContentType",
122+ size,
123+ file,
124+ created_at AS "created_at: Timestamp"
125+ FROM homework_file
126+ WHERE id = $1
127+ AND submission IN (SELECT id FROM homework_submission WHERE homework = $2)"#,
128+ id,
129+ homework
130+ )
131+ .fetch_optional(db)
132+ .await?)
102133 }
103134
104135 /// All of `submission`'s files, newest first.
@@ -106,40 +137,56 @@ pub async fn list_for_submission(
106137 db: &Database,
107138 submission: &crate::domain::homework_submission::HomeworkSubmissionId,
108139 ) -> Result<Vec<HomeworkFile>, AppError> {
109- let mut result = db
110- .query("SELECT * FROM homework_file WHERE submission = $sub ORDER BY id DESC")
111- .bind(("sub", submission.record()))
112- .await?
113- .check()?;
114- Ok(result.take::<Vec<HomeworkFile>>(0)?)
140+ Ok(sqlx::query_as!(
141+ HomeworkFile,
142+ r#"SELECT id AS "id: HomeworkFileId",
143+ submission AS "submission: HomeworkSubmissionId",
144+ name AS "name: FileName",
145+ content_type AS "content_type: FileContentType",
146+ size,
147+ file,
148+ created_at AS "created_at: Timestamp"
149+ FROM homework_file WHERE submission = $1 ORDER BY id DESC"#,
150+ submission
151+ )
152+ .fetch_all(db)
153+ .await?)
115154 }
116155
117-/// How many files `submission` holds — the cap check reads this under the
118-/// lock. Counting via the rows (not a `count()` query) keeps it identical
119-/// to `NoteFile`'s proven cap check; at a ceiling of 10 the cost is nil.
156+/// How many files `submission` holds. Counting the rows (not the counter
157+/// column) keeps it identical to `NoteFile`'s proven cap check; at a ceiling
158+/// of 10 the cost is nil.
120159 pub async fn count_for_submission(
121160 db: &Database,
122161 submission: &crate::domain::homework_submission::HomeworkSubmissionId,
123162 ) -> Result<usize, AppError> {
124- Ok(list_for_submission(db, submission).await?.len())
163+ let row = sqlx::query!(
164+ r#"SELECT count(*) AS "count: i64" FROM homework_file WHERE submission = $1"#,
165+ submission
166+ )
167+ .fetch_one(db)
168+ .await?;
169+ Ok(row.count as usize)
125170 }
126171
127172 /// The blob names behind every file of every submission to `homework` —
128-/// collected *before* the homework-delete cascade wipes the rows, so the
129-/// web layer can unlink them once the rows are gone.
173+/// the GC keys of a homework delete (collected inside the delete's own
174+/// transaction by [`crate::db::homework::delete`]; this read backs it and
175+/// the tests).
130176 pub async fn file_keys_for_homework(
131177 db: &Database,
132178 homework: &HomeworkId,
133179 ) -> Result<Vec<String>, AppError> {
134- let mut result = db
135- .query(
136- "SELECT VALUE file FROM homework_file \
137- WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw)",
138- )
139- .bind(("hw", homework.record()))
140- .await?
141- .check()?;
142- Ok(result.take::<Vec<String>>(0)?)
180+ Ok(sqlx::query!(
181+ r#"SELECT file FROM homework_file
182+ WHERE submission IN (SELECT id FROM homework_submission WHERE homework = $1)"#,
183+ homework
184+ )
185+ .fetch_all(db)
186+ .await?
187+ .into_iter()
188+ .map(|row| row.file)
189+ .collect())
143190 }
144191
145192 /// The blob names behind every homework file of `course` — collected
@@ -148,17 +195,19 @@ pub async fn file_keys_for_course(
148195 db: &Database,
149196 course: &CourseId,
150197 ) -> Result<Vec<String>, AppError> {
151- let mut result = db
152- .query(
153- "SELECT VALUE file FROM homework_file WHERE submission IN ( \
154- SELECT VALUE id FROM homework_submission \
155- WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course) \
156- )",
157- )
158- .bind(("course", course.record()))
159- .await?
160- .check()?;
161- Ok(result.take::<Vec<String>>(0)?)
198+ Ok(sqlx::query!(
199+ r#"SELECT file FROM homework_file
200+ WHERE submission IN (
201+ SELECT id FROM homework_submission
202+ WHERE homework IN (SELECT id FROM homework WHERE course = $1)
203+ )"#,
204+ course
205+ )
206+ .fetch_all(db)
207+ .await?
208+ .into_iter()
209+ .map(|row| row.file)
210+ .collect())
162211 }
163212
164213 /// Delete the row and give its slot back in the same transaction. The
@@ -167,57 +216,58 @@ pub async fn file_keys_for_course(
167216 ///
168217 /// The gate is the first statement: a conditional write on the *submission*
169218 /// row — the "last touched" re-stamp a file delete owes the late flag
170-/// anyway — carrying [`SUBMISSION_OPEN_GUARD`]. Nothing else in the
171-/// transaction runs unless it bit, so a grade landing concurrently either
172-/// stamps first (this delete is refused, `Ok(None)`) or stamps after (the
173-/// file was already gone when it graded). `Err(NotFound)` still means the
174-/// file row itself had vanished.
175-///
176-/// Sound to re-send while the store answers "conflict, retry", and it has
177-/// to be: the gate writes the *submission* row, the very record an upload's
178-/// [`insert`] claims its seat on, and both handlers hold only
179-/// `HOMEWORK_LOCK.read()` — so a concurrent add and delete of two files of
180-/// one submission contend by design, and a lost round used to come back as
181-/// a 500 on a request that had written nothing. Only `UPDATE` and `DELETE`
182-/// are in the batch, and neither can legitimately answer "already exists",
183-/// which is what makes the whole of it re-sendable.
219+/// anyway. Its row lock is also the serialization point against an upload's
220+/// seat claim on the same row: one of the two waits, and the winner re-reads
221+/// the counter before moving it, so no lost round and no 500 — a grade
222+/// landing concurrently either stamps first (this delete is refused,
223+/// `Ok(None)`) or stamps after (the file was already gone when it graded).
224+/// `Err(NotFound)` still means the file row itself had vanished.
184225 pub async fn delete(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> {
185- let (mut result, mut errors) = transaction_with_retry(
186- db,
187- &format!(
188- "BEGIN TRANSACTION;
189- LET $open = (UPDATE $sub SET updated_at = $now \
190- WHERE {SUBMISSION_OPEN_GUARD} RETURN VALUE id);
191- LET $gone = IF array::len($open) > 0 {{ (DELETE $id RETURN BEFORE) }} ELSE {{ [] }};
192- UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]);
193- RETURN {{ open: array::len($open), gone: $gone }};
194- COMMIT TRANSACTION;"
195- ),
196- &[
197- ("id".into(), file.id.record().into_value()),
198- ("sub".into(), file.submission.record().into_value()),
199- ("now".into(), Timestamp::now().into_value()),
200- ],
201- &[],
202- )
203- .await?;
204- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
205- return Err(error.into());
206- }
207- // BEGIN is slot 0, the two LETs slots 1-2 and the counter fix slot 3;
208- // the RETURN is slot 4.
209- let outcome: Option<DeleteOutcome> = result.take::<Vec<DeleteOutcome>>(4)?.into_iter().next();
210- let outcome =
211- outcome.ok_or_else(|| AppError::Internal("failed to delete homework file".into()))?;
212- if outcome.open == 0 {
213- return Ok(None);
214- }
215- outcome
216- .gone
217- .into_iter()
218- .next()
219- .map(Some)
220- .ok_or(AppError::NotFound)
226+ let now = Timestamp::now();
227+ tx_with_retry(db, false, async |tx| {
228+ let open = sqlx::query!(
229+ r#"UPDATE homework_submission SET updated_at = $2
230+ WHERE id = $1 AND graded_by_result IS NULL
231+ RETURNING 1 AS "open: i32""#,
232+ file.submission,
233+ now
234+ )
235+ .fetch_optional(&mut *tx)
236+ .await?;
237+ if open.is_none() {
238+ return Ok(None);
239+ }
240+ let gone = sqlx::query_as!(
241+ HomeworkFile,
242+ r#"DELETE FROM homework_file WHERE id = $1 AND submission = $2
243+ RETURNING id AS "id: HomeworkFileId",
244+ submission AS "submission: HomeworkSubmissionId",
245+ name AS "name: FileName",
246+ content_type AS "content_type: FileContentType",
247+ size,
248+ file,
249+ created_at AS "created_at: Timestamp""#,
250+ file.id,
251+ file.submission
252+ )
253+ .fetch_optional(&mut *tx)
254+ .await?;
255+ match gone {
256+ Some(row) => {
257+ sqlx::query!(
258+ "UPDATE homework_submission SET file_count = GREATEST(file_count - 1, 0)
259+ WHERE id = $1",
260+ file.submission
261+ )
262+ .execute(&mut *tx)
263+ .await?;
264+ Ok(Some(row))
265+ }
266+ // The submission was open but the file had already vanished.
267+ None => Err(AppError::NotFound),
268+ }
269+ })
270+ .await
221271 }
222272
223273 #[cfg(test)]
src/db/homework_result.rsmodified+206 -188
@@ -5,48 +5,51 @@
55 //! validated status and mark types in
66 //! [`crate::domain::homework_result`].
77
8-use crate::constant::{MARKS_GIVEN_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD};
9-use crate::database::{Database, transaction_with_retry};
8+use crate::database::{Database, tx_with_retry};
109 use crate::domain::course::CourseId;
1110 use crate::domain::exam_result::Mark;
1211 use crate::domain::homework::HomeworkId;
1312 use crate::domain::homework_result::{HomeworkResult, HomeworkResultId, HomeworkStatus};
14-use crate::domain::homework_submission::HomeworkSubmissionId;
1513 use crate::domain::timestamp::Timestamp;
1614 use crate::domain::user::UserId;
1715 use crate::error::AppError;
18-use surrealdb::types::SurrealValue;
1916
20-/// Record (or overwrite) the grade for (homework, user). One row per pair,
21-/// keyed by the deterministic composite id, so this is a single atomic
22-/// UPSERT — concurrent grades for the same pair converge on one row instead
23-/// of racing a unique index into a 500. Grading before the due date, or
24-/// before any submission exists, is allowed (the caller's policy call).
17+/// Record (or overwrite) the grade for (homework, user). One row per pair by
18+/// the pair's UNIQUE constraint, so grading is one atomic UPSERT —
19+/// concurrent grades for the same pair converge on one row instead of
20+/// racing a duplicate into a 500. Grading before the due date, or before any
21+/// submission exists, is allowed (the caller's policy call).
2522 ///
2623 /// In the same transaction the grade *stamps* the student's submission
27-/// ([`crate::constant::SUBMISSION_GRADED_FIELD`]), which is what freezes it:
28-/// every student-side write to that row then fails its own
29-/// `graded_by_result = NONE` condition, with no cross-table read for a
30-/// concurrent write to slip past. A submission that does not exist yet is
31-/// left alone — grading absent work must not conjure a hand-in (the report reads
32-/// `submitted`/`missing`/`late` straight off that row).
24+/// (`graded_by_result`), which is what freezes it: every student-side write
25+/// to that row then fails its own `graded_by_result IS NULL` condition, with
26+/// no cross-table read for a concurrent write to slip past. A submission
27+/// that does not exist yet is left alone — grading absent work must not
28+/// conjure a hand-in (the report reads `submitted`/`missing`/`late` straight
29+/// off that row).
3330 ///
34-/// That one case is where this function stops defending itself: a student's
31+/// That one case is where this statement stops defending itself: a student's
3532 /// *first* hand-in committing between this grade and nothing-to-stamp would
36-/// land unstamped, leaving a grade beside an editable submission. Nothing
37-/// here forbids it — what forbids it is the caller. Grading holds
38-/// `HOMEWORK_LOCK` (see [`crate::service::homework`]) for writing across this
39-/// whole transaction while every student-side write holds it for reading across
40-/// its own, and the two leases are mutually exclusive in the one process
41-/// this backend runs as, so the interleaving never gets a window.
42-//
43-// corner-cut: that makes the freeze depend on lock discipline at the call
44-// sites, not on this row. Moving a student write's lease to *after* its
45-// database write — or sharding HOMEWORK_LOCK per homework — reopens the
46-// window with nothing to catch it. Closing it in the db layer needs a
47-// record both sides own (a per-(homework, user) row the grade can always
48-// stamp); a tombstone submission is not it, since every read path would
49-// have to learn to ignore it and one missed filter fabricates a hand-in.
33+/// land unstamped, leaving a grade beside an editable submission. What
34+/// forbids it here is the homework row's lock: every student-side write
35+/// locks the homework row across its write, and so does this transaction, so
36+/// the interleaving is ordered away instead of leased away — either the
37+/// grade saw the row to stamp, or the submission saw no grade and created
38+/// under a lock this transaction already held.
39+///
40+/// Whether the pair was already graded is read one statement ahead of the
41+/// write, under the same lock — it is what keeps a regrade from crediting
42+/// the grader a second time. No mark counter here: a homework mark is
43+/// optional and most grades are status-only, so `high_mark` is an exam-only
44+/// family.
45+///
46+/// The homework row's `FOR UPDATE` is also the parent gate: the id is minted
47+/// fresh, so a grade landing inside a homework (or course) delete's window
48+/// would otherwise *re-create* a result row under a homework that is gone,
49+/// readable ever after at `GET /homework/{id}/result` (no existence check
50+/// there) with a `marks_given_total` no ungrade can reach, because every
51+/// route to the grade goes through the homework. A vanished row answers
52+/// `Err(NotFound)` — the 404 the web layer's own lookup would have answered.
5053 pub async fn grade(
5154 db: &Database,
5255 homework: &HomeworkId,
@@ -55,102 +58,73 @@ pub async fn grade(
5558 mark: Option<Mark>,
5659 graded_by: &UserId,
5760 ) -> Result<HomeworkResult, AppError> {
58- let id = HomeworkResultId::composite(homework, user);
59- let submission = HomeworkSubmissionId::composite(homework, user);
60- let result = HomeworkResult {
61- id: id.clone(),
62- homework: homework.clone(),
63- user: user.clone(),
64- status,
65- mark,
66- graded_by: graded_by.clone(),
67- created_at: Timestamp::now(),
68- };
69- // Whether the pair was already graded is read one statement ahead of
70- // the write, inside the same transaction — it is what keeps a regrade
71- // from crediting the grader a second time. No mark counter here: a
72- // homework mark is optional and most grades are status-only, so
73- // `high_mark` is an exam-only family.
74- //
75- // The first three statements are the parent gate, the twin of
76- // [`crate::db::homework_submission::upsert`]'s
77- // and written the same way on purpose: the id is deterministic, so a
78- // grade landing inside a homework (or course) delete's window does not
79- // fail — it *re-creates* a result row under a homework that is gone,
80- // readable ever after at `GET /homework/{id}/result` (no existence check
81- // there) with a `marks_given_total` no ungrade can reach, because every
82- // route to the grade goes through the homework. Reading the homework
83- // first — which the web layer does, under the lease — cannot close that:
84- // the store conflict-checks write sets, not read sets. So the gate
85- // *moves* a value on the homework row (`due_at` up by one and straight
86- // back to the captured value, leaving the row byte-identical) and the
87- // cascade's delete of that same row is what refuses it. `homework` owns
88- // no counter column and is SCHEMAFULL, so `due_at` is the one `int` it
89- // already has; do not invent a second spelling.
90- //
91- // Not [`crate::db::cap::touch_and_create`], which is the same shape
92- // for a bare `CREATE`: a grade is an UPSERT (a regrade must overwrite),
93- // and the freeze stamp and the grader's counter have to ride the same
94- // transaction, which that helper has no room for.
95- //
96- // Sound to re-send, which is what the gate needed first — a `THROW`
97- // inside a plain `db.query` would have turned every lost round into a
98- // 500. `SELECT`, `UPDATE` and the `IF`/`THROW` can never answer "already
99- // exists", and the `UPSERT`'s id is bijective with the (homework, user)
100- // pair the table keys, on a table whose only index is non-unique
101- // (`homework_result_homework`), so its index entry can only ever point
102- // at the row the id already names: it resolves onto that row instead of
103- // colliding with it. A lost round wrote nothing.
104- let (mut saved, mut errors) = transaction_with_retry(
105- db,
106- &format!(
107- "BEGIN TRANSACTION;
108- LET $was_due = (SELECT VALUE due_at FROM ONLY $hw);
109- LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id);
110- IF array::len($alive) = 0 {{ THROW 'no_homework' }};
111- UPDATE $hw SET due_at = $was_due;
112- LET $before = (SELECT VALUE id FROM ONLY $id);
113- LET $after = (UPSERT $id CONTENT $row RETURN AFTER);
114- UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = $id \
115- WHERE {SUBMISSION_OPEN_GUARD};
116- IF $before = NONE {{
117- UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} =
118- ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1
119- }};
120- RETURN $after;
121- COMMIT TRANSACTION;"
122- ),
123- &[
124- ("hw".into(), homework.record().into_value()),
125- ("id".into(), id.record().into_value()),
126- ("sub".into(), submission.record().into_value()),
127- ("grader".into(), graded_by.record().into_value()),
128- ("row".into(), result.into_value()),
129- ],
130- &["no_homework"],
131- )
132- .await?;
133- // An aborted transaction errors *every* slot, most with a generic "not
134- // executed" — only the THROW's own slot names the reason.
135- if errors
136- .values()
137- .any(|error| error.to_string().contains("no_homework"))
138- {
139- return Err(AppError::NotFound);
140- }
141- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
142- return Err(error.into());
143- }
144- // The trailing `RETURN` is always the last statement before `COMMIT`,
145- // so its slot follows the statement count instead of a hand-kept
146- // number — which the gate above would otherwise have shifted, silently
147- // handing back something else.
148- let slot = saved.num_statements().saturating_sub(2);
149- saved
150- .take::<Vec<HomeworkResult>>(slot)?
151- .into_iter()
152- .next()
153- .ok_or_else(|| AppError::Internal("failed to record homework result".into()))
61+ let id = HomeworkResultId::generate();
62+ let now = Timestamp::now();
63+ tx_with_retry(db, false, async |tx| {
64+ let alive = sqlx::query!(
65+ r#"SELECT 1 AS "row: i32" FROM homework WHERE id = $1 FOR UPDATE"#,
66+ homework
67+ )
68+ .fetch_optional(&mut *tx)
69+ .await?;
70+ if alive.is_none() {
71+ return Err(AppError::NotFound);
72+ }
73+ let before = sqlx::query!(
74+ r#"SELECT 1 AS "row: i32" FROM homework_result
75+ WHERE homework = $1 AND app_user = $2 FOR UPDATE"#,
76+ homework,
77+ user
78+ )
79+ .fetch_optional(&mut *tx)
80+ .await?
81+ .is_some();
82+ // A regrade overwrites status, mark, grader and stamp — `id` and
83+ // `homework`/`app_user` are the row's identity and stay.
84+ let graded = sqlx::query_as!(
85+ HomeworkResult,
86+ r#"INSERT INTO homework_result (id, homework, app_user, status, mark, graded_by, created_at)
87+ VALUES ($1, $2, $3, $4, $5, $6, $7)
88+ ON CONFLICT (homework, app_user) DO UPDATE
89+ SET status = EXCLUDED.status, mark = EXCLUDED.mark,
90+ graded_by = EXCLUDED.graded_by, created_at = EXCLUDED.created_at
91+ RETURNING id AS "id: HomeworkResultId",
92+ homework AS "homework: HomeworkId",
93+ app_user AS "user: UserId",
94+ status AS "status: HomeworkStatus",
95+ mark AS "mark: Option<Mark>",
96+ graded_by AS "graded_by: UserId",
97+ created_at AS "created_at: Timestamp""#,
98+ id,
99+ homework,
100+ user,
101+ status,
102+ mark,
103+ graded_by,
104+ now,
105+ )
106+ .fetch_one(&mut *tx)
107+ .await?;
108+ sqlx::query!(
109+ r#"UPDATE homework_submission SET graded_by_result = $3
110+ WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL"#,
111+ homework,
112+ user,
113+ graded.id
114+ )
115+ .execute(&mut *tx)
116+ .await?;
117+ if !before {
118+ sqlx::query!(
119+ "UPDATE app_user SET marks_given_total = marks_given_total + 1 WHERE id = $1",
120+ graded_by
121+ )
122+ .execute(&mut *tx)
123+ .await?;
124+ }
125+ Ok(graded)
126+ })
127+ .await
154128 }
155129
156130 /// `user`'s grade for `homework`, if graded.
@@ -159,9 +133,21 @@ pub async fn read_for(
159133 homework: &HomeworkId,
160134 user: &UserId,
161135 ) -> Result<Option<HomeworkResult>, AppError> {
162- Ok(db
163- .select(HomeworkResultId::composite(homework, user).record())
164- .await?)
136+ Ok(sqlx::query_as!(
137+ HomeworkResult,
138+ r#"SELECT id AS "id: HomeworkResultId",
139+ homework AS "homework: HomeworkId",
140+ app_user AS "user: UserId",
141+ status AS "status: HomeworkStatus",
142+ mark AS "mark: Option<Mark>",
143+ graded_by AS "graded_by: UserId",
144+ created_at AS "created_at: Timestamp"
145+ FROM homework_result WHERE homework = $1 AND app_user = $2"#,
146+ homework,
147+ user
148+ )
149+ .fetch_optional(db)
150+ .await?)
165151 }
166152
167153 /// Every grade for `homework` — the roster joins these onto the submissions.
@@ -169,12 +155,20 @@ pub async fn list_for_homework(
169155 db: &Database,
170156 homework: &HomeworkId,
171157 ) -> Result<Vec<HomeworkResult>, AppError> {
172- let mut result = db
173- .query("SELECT * FROM homework_result WHERE homework = $hw ORDER BY id DESC")
174- .bind(("hw", homework.record()))
175- .await?
176- .check()?;
177- Ok(result.take::<Vec<HomeworkResult>>(0)?)
158+ Ok(sqlx::query_as!(
159+ HomeworkResult,
160+ r#"SELECT id AS "id: HomeworkResultId",
161+ homework AS "homework: HomeworkId",
162+ app_user AS "user: UserId",
163+ status AS "status: HomeworkStatus",
164+ mark AS "mark: Option<Mark>",
165+ graded_by AS "graded_by: UserId",
166+ created_at AS "created_at: Timestamp"
167+ FROM homework_result WHERE homework = $1 ORDER BY id DESC"#,
168+ homework
169+ )
170+ .fetch_all(db)
171+ .await?)
178172 }
179173
180174 /// `user`'s homework grades across one course — the raw rows behind the
@@ -185,17 +179,24 @@ pub async fn list_for_user_in_course(
185179 course: &CourseId,
186180 user: &UserId,
187181 ) -> Result<Vec<HomeworkResult>, AppError> {
188- let mut result = db
189- .query(
190- "SELECT * FROM homework_result WHERE user = $usr
191- AND homework IN (SELECT VALUE id FROM homework WHERE course = $course)
192- ORDER BY id DESC",
193- )
194- .bind(("usr", user.record()))
195- .bind(("course", course.record()))
196- .await?
197- .check()?;
198- Ok(result.take::<Vec<HomeworkResult>>(0)?)
182+ Ok(sqlx::query_as!(
183+ HomeworkResult,
184+ r#"SELECT id AS "id: HomeworkResultId",
185+ homework AS "homework: HomeworkId",
186+ app_user AS "user: UserId",
187+ status AS "status: HomeworkStatus",
188+ mark AS "mark: Option<Mark>",
189+ graded_by AS "graded_by: UserId",
190+ created_at AS "created_at: Timestamp"
191+ FROM homework_result
192+ WHERE app_user = $1
193+ AND homework IN (SELECT id FROM homework WHERE course = $2)
194+ ORDER BY id DESC"#,
195+ user,
196+ course
197+ )
198+ .fetch_all(db)
199+ .await?)
199200 }
200201
201202 /// Un-grade (homework, user), returning the removed row (`None` if there
@@ -212,53 +213,70 @@ pub async fn list_for_user_in_course(
212213 /// submission behind it — permanently, since an award is never revoked.
213214 /// Given back to the *removed row's own* grader, not the caller: a manager
214215 /// may un-grade what a teacher graded, and the credit is the teacher's.
215-///
216-/// Sound to re-send while the store answers "conflict, retry" — this is the
217-/// upgrade `grade` still wants, taken here because the counter above is what
218-/// makes it necessary: the grader's row is written by exam grading too, so
219-/// the delete now contends with another domain, and only `DELETE`/`UPDATE`
220-/// are in the batch, none of which can legitimately answer "already exists".
221216 pub async fn remove(
222217 db: &Database,
223218 homework: &HomeworkId,
224219 user: &UserId,
225220 ) -> Result<Option<HomeworkResult>, AppError> {
226- let id = HomeworkResultId::composite(homework, user);
227- let (mut result, mut errors) = transaction_with_retry(
228- db,
229- &format!(
230- "BEGIN TRANSACTION;
231- LET $gone = (DELETE $id RETURN BEFORE);
232- UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = NONE \
233- WHERE {SUBMISSION_GRADED_FIELD} = $id;
234- IF array::len($gone) > 0 {{
235- LET $grader = $gone[0].graded_by;
236- UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} =
237- math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0])
238- }};
239- RETURN $gone;
240- COMMIT TRANSACTION;"
241- ),
242- &[
243- ("id".into(), id.record().into_value()),
244- (
245- "sub".into(),
246- HomeworkSubmissionId::composite(homework, user)
247- .record()
248- .into_value(),
249- ),
250- ],
251- &[],
252- )
253- .await?;
254- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
255- return Err(error.into());
256- }
257- // The trailing `RETURN` is always the last statement before `COMMIT`, so
258- // its slot follows the statement count — the hand-kept "slot 1" this
259- // replaces was one added statement away from handing back the unstamp.
260- let slot = result.num_statements().saturating_sub(2);
261- Ok(result.take::<Vec<HomeworkResult>>(slot)?.into_iter().next())
221+ tx_with_retry(db, false, async |tx| {
222+ // The homework row's lock orders this against a concurrent grade
223+ // (which locks the same row before inserting): either this delete
224+ // wins and the re-grade lands after as a fresh grade, or the grade
225+ // lands first and this removes *it*. A homework already cascaded
226+ // away left no result rows behind — `None`, the 404 the web layer
227+ // answers.
228+ let alive = sqlx::query!(
229+ r#"SELECT 1 AS "row: i32" FROM homework WHERE id = $1 FOR UPDATE"#,
230+ homework
231+ )
232+ .fetch_optional(&mut *tx)
233+ .await?;
234+ if alive.is_none() {
235+ return Ok(None);
236+ }
237+ let gone = sqlx::query!(
238+ r#"DELETE FROM homework_result WHERE homework = $1 AND app_user = $2
239+ RETURNING id AS "id: HomeworkResultId",
240+ homework AS "homework: HomeworkId",
241+ app_user AS "user: UserId",
242+ status AS "status: HomeworkStatus",
243+ mark AS "mark: Option<Mark>",
244+ graded_by AS "graded_by: UserId",
245+ created_at AS "created_at: Timestamp""#,
246+ homework,
247+ user
248+ )
249+ .fetch_optional(&mut *tx)
250+ .await?;
251+ let Some(removed) = gone else {
252+ return Ok(None);
253+ };
254+ sqlx::query!(
255+ r#"UPDATE homework_submission SET graded_by_result = NULL
256+ WHERE homework = $1 AND app_user = $2 AND graded_by_result = $3"#,
257+ homework,
258+ user,
259+ removed.id
260+ )
261+ .execute(&mut *tx)
262+ .await?;
263+ sqlx::query!(
264+ "UPDATE app_user SET marks_given_total = GREATEST(marks_given_total - 1, 0) WHERE id = $1",
265+ removed.graded_by
266+ )
267+ .execute(&mut *tx)
268+ .await?;
269+ Ok(Some(HomeworkResult {
270+ id: removed.id,
271+ homework: removed.homework,
272+ user: removed.user,
273+ status: removed.status,
274+ mark: removed.mark,
275+ graded_by: removed.graded_by,
276+ created_at: removed.created_at,
277+ }))
278+ })
279+ .await
262280 }
263281
264282 #[cfg(test)]
src/db/homework_submission.rsmodified+266 -197
@@ -5,186 +5,217 @@
55 //! [`crate::service::homework_submission`]; the validated text type in
66 //! [`crate::domain::homework_submission`].
77
8-use crate::constant::{
9- HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMITTED_TOTAL_FIELD, SUBMISSION_GRADED_FIELD,
10- SUBMISSION_OPEN_GUARD,
11-};
12-use crate::database::{Database, transaction_with_retry};
8+use crate::database::{Database, tx_with_retry};
139 use crate::domain::homework::Homework;
10+use crate::domain::homework::HomeworkId;
1411 use crate::domain::homework_submission::{
1512 HomeworkSubmission, HomeworkSubmissionId, SubmissionText,
1613 };
1714 use crate::domain::timestamp::Timestamp;
1815 use crate::domain::user::UserId;
1916 use crate::error::AppError;
20-use surrealdb::types::SurrealValue;
2117
2218 /// Create or re-stamp `user`'s submission to `homework`, unless a grade has
2319 /// frozen it — `None` means frozen, and the caller answers 409. `updated_at`
24-/// moves to now every time; `submitted_at` (readonly, the first-submit stamp)
25-/// is kept on an existing row and set only on a fresh one.
20+/// moves to now every time; `submitted_at` (the first-submit stamp) is kept
21+/// on an existing row and set only on a fresh one. Returns the row plus
22+/// whether it existed before this call (the web layer's 200-vs-201, and the
23+/// only-a-first-hand-in-earns-badges rule).
2624 ///
27-/// Hand-written rather than `.content()` on purpose: `.content()` re-sends
28-/// the whole row, so it would carry a `submitted_at`, and any value differing
29-/// from the stored one trips the readonly guard. The
30-/// `submitted_at = submitted_at ?? $now` expression preserves it inside the
31-/// one UPSERT statement — race-free without a lock, where a read-then-content
32-/// could let two concurrent first-submits pick different stamps and 500.
25+/// `preserve_text` is the photo-upload auto-create's switch: an existing row
26+/// keeps its text (and its stamp moves, as any touch), because the upload
27+/// never offered a text to replace it. A submit passes `false` — an absent
28+/// text clears, as on the wire.
3329 ///
34-/// The `WHERE` is the freeze: [`SUBMISSION_OPEN_GUARD`] makes "not graded
35-/// yet" a condition of this very write instead of a read a concurrent grade
36-/// can land behind. An absent row satisfies it (the stamp is `NONE` there
37-/// too), so a first submit still creates.
30+/// The `graded_by_result IS NULL` predicate is the freeze: "not graded yet"
31+/// is a condition of the write itself, so a refused write answers `None`
32+/// instead of wiping graded work. An absent row satisfies it trivially, so a
33+/// first submit still creates.
3834 ///
3935 /// The badge counters on the student's user row move in this very
40-/// transaction, and the order is load-bearing: the increment sits *after*
41-/// the UPSERT and is conditional on it having matched a row, because a
42-/// frozen row makes that `WHERE` match nothing **silently** (unlike
43-/// [`crate::db::homework_result::grade`], which `THROW`s) — put
44-/// first, it would count a submission the freeze refused. `$before = NONE`
45-/// keeps it to a genuine first create, so an edit moves neither counter,
46-/// which is what makes the live count mean the same thing the one-time
47-/// backfill seeded (one per row; on time judged against `due_at`, equal
48-/// counting as on time).
36+/// transaction, and only on the create arm — an edit moves neither counter,
37+/// which is what makes the live count mean one per row.
4938 ///
50-/// `counted_on_time` is stamped on the row from the *same* `$on_time`
51-/// expression the increment adds, in the same statement block: the deadline
52-/// is mutable, so a withdrawal that re-judged it against the live `due_at`
53-/// gave back something other than what was taken. Writing the verdict beside
54-/// the counter is what keeps the two from ever disagreeing — read back by
39+/// `counted_on_time` is stamped on the row from the same `on_time` verdict
40+/// the increment adds, in the same transaction: the deadline is mutable, so
41+/// a withdrawal that re-judged it against the live `due_at` gave back
42+/// something other than what was taken. Writing the verdict beside the
43+/// counter is what keeps the two from ever disagreeing — read back by
5544 /// [`delete`], never re-derived.
5645 ///
57-/// That deadline is `$was_due`, the one the gate below already read *inside
58-/// this transaction* — never the caller's [`Homework`] snapshot, which was
59-/// read before the lease and is exactly one `PATCH due_at` old in the
60-/// "teacher extends the deadline at 23:59 while the class submits" moment.
61-/// Judging on the snapshot stored a verdict the web layer's own `late` flag
62-/// (`updated_at > due_at`, re-derived live on every read) then contradicted
63-/// forever, in both directions. An in-process lock cannot fix this — it
64-/// orders two handlers, not two store transactions — so the comparison has
65-/// to live where the write does. The whole entity is still taken (both
66-/// callers hold the row, and the id comes off it); its `due_at` must not be.
67-///
68-/// The first three statements are the parent gate, and they are why this
69-/// write cannot outlive its homework: the id is deterministic, so nothing
70-/// else here would fail against a homework a cascade already removed — it
71-/// would simply re-create the row, badge counters and all, unreachable ever
72-/// after (every route to a submission goes through its homework). A *read*
73-/// of the homework does not close that, on either side of the call: the
74-/// store does no read-set conflict detection, so a delete committing
75-/// alongside is invisible to it. The gate therefore *moves* a value on the
76-/// homework row — `due_at` up by one and straight back to the captured
77-/// value, so the row is byte-identical afterwards — because only a write
78-/// collides, and `SET x = x` is elided and never reaches the write set. It
79-/// is [`crate::domain::exam_answer::ExamAnswer::save`]'s shape exactly.
80-/// `Err(NotFound)` means the homework is gone, which is the 404 the web
81-/// layer's own lookup would have answered.
46+/// That deadline is `was_due`, the one read *inside this transaction* under
47+/// the homework row's lock — never the caller's [`Homework`] snapshot, which
48+/// was read before the request's gates and is exactly one `PATCH due_at` old
49+/// in the "teacher extends the deadline at 23:59 while the class submits"
50+/// moment. The lock is also the serialization point: grading locks the same
51+/// row before stamping, the audience-narrowing PATCH before its orphan
52+/// check, and a rival first hand-in before its own insert — so the
53+/// read-then-write below cannot interleave with any of them. (The pair's
54+/// UNIQUE constraint backs this up; under the lock it can never fire.)
8255 pub async fn upsert(
8356 db: &Database,
8457 homework: &Homework,
8558 user: &UserId,
8659 text: Option<SubmissionText>,
87-) -> Result<Option<HomeworkSubmission>, AppError> {
88- let id = HomeworkSubmissionId::composite(homework.get_id(), user);
60+ preserve_text: bool,
61+) -> Result<Option<(HomeworkSubmission, bool)>, AppError> {
8962 let now = Timestamp::now();
90- let text = text.map(|text| text.as_str().to_string());
91- // Sound to re-send: the UPSERT is on a deterministic id on a table with
92- // no unique index, so it can never legitimately answer "already exists",
93- // and the counter UPDATEs never can either.
94- let (mut saved, mut errors) = transaction_with_retry(
95- db,
96- &format!(
97- "BEGIN TRANSACTION;
98- LET $was_due = (SELECT VALUE due_at FROM ONLY $hw);
99- LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id);
100- IF array::len($alive) = 0 {{ THROW 'no_homework' }};
101- UPDATE $hw SET due_at = $was_due;
102- LET $before = (SELECT VALUE id FROM ONLY $id);
103- LET $on_time = $now <= $was_due;
104- LET $after = (UPSERT $id SET homework = $hw, user = $usr, text = $text,
105- updated_at = $now, submitted_at = submitted_at ?? $now
106- WHERE {SUBMISSION_OPEN_GUARD} RETURN AFTER);
107- IF $before = NONE AND array::len($after) > 0 {{
108- UPDATE $id SET counted_on_time = $on_time;
109- UPDATE $usr SET
110- {HOMEWORK_SUBMITTED_TOTAL_FIELD} = ({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) + 1,
111- {HOMEWORK_ON_TIME_TOTAL_FIELD} = ({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0)
112- + IF $on_time {{ 1 }} ELSE {{ 0 }}
113- }};
114- RETURN $after;
115- COMMIT TRANSACTION;"
116- ),
117- &[
118- ("id".into(), id.record().into_value()),
119- ("hw".into(), homework.get_id().record().into_value()),
120- ("usr".into(), user.record().into_value()),
121- ("text".into(), text.into_value()),
122- ("now".into(), now.into_value()),
123- ],
124- &["no_homework"],
125- )
126- .await?;
127- // An aborted transaction errors *every* slot, most with a generic "not
128- // executed" — only the THROW's own slot names the reason.
129- if errors
130- .values()
131- .any(|error| error.to_string().contains("no_homework"))
132- {
133- return Err(AppError::NotFound);
134- }
135- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
136- return Err(error.into());
137- }
138- // The trailing `RETURN` is always the last statement before `COMMIT`, so
139- // its slot follows the statement count rather than a hand-kept number.
140- // It returns the whole array, never `$after[0]`: a refused write makes
141- // that `NONE`, which fails to deserialize ("expected object, got none")
142- // instead of reading as the "frozen" the caller answers 409 to.
143- let slot = saved.num_statements().saturating_sub(2);
144- Ok(saved
145- .take::<Vec<HomeworkSubmission>>(slot)?
146- .into_iter()
147- .next())
63+ tx_with_retry(db, false, async |tx| {
64+ // The parent gate: the homework row is locked and its deadline read
65+ // in the very transaction that writes the submission. The id is
66+ // minted fresh, so nothing else here would fail against a homework a
67+ // cascade already removed — it would simply create a row under it,
68+ // badge counters and all, unreachable ever after (every route to a
69+ // submission goes through its homework). `Err(NotFound)` means the
70+ // homework is gone, which is the 404 the web layer's own lookup
71+ // would have answered.
72+ let was_due = sqlx::query!(
73+ "SELECT due_at FROM homework WHERE id = $1 FOR UPDATE",
74+ homework.get_id()
75+ )
76+ .fetch_optional(&mut *tx)
77+ .await?
78+ .map(|row| row.due_at);
79+ let Some(was_due) = was_due else {
80+ return Err(AppError::NotFound);
81+ };
82+ // Equal counts as on time, exactly as the deadline has always been
83+ // judged.
84+ let on_time = i64::from(now <= was_due);
85+
86+ // The row, read under the homework's lock: its existence decides the
87+ // arm (and the counters).
88+ let existing = sqlx::query!(
89+ r#"SELECT 1 AS "row: i32" FROM homework_submission
90+ WHERE homework = $1 AND app_user = $2 FOR UPDATE"#,
91+ homework.get_id(),
92+ user
93+ )
94+ .fetch_optional(&mut *tx)
95+ .await?
96+ .is_some();
97+
98+ if existing {
99+ // Re-submit: text is replaced (unless the upload auto-create is
100+ // asking — it has no text to replace), `updated_at` moves, and
101+ // `submitted_at` is left alone. A frozen row matches nothing and
102+ // answers `None`, the caller's 409.
103+ let updated = if preserve_text {
104+ sqlx::query_as!(
105+ HomeworkSubmission,
106+ r#"UPDATE homework_submission SET updated_at = $3
107+ WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL
108+ RETURNING id AS "id: HomeworkSubmissionId",
109+ homework AS "homework: HomeworkId",
110+ app_user AS "user: UserId",
111+ text AS "text: Option<SubmissionText>",
112+ submitted_at AS "submitted_at: Timestamp",
113+ updated_at AS "updated_at: Timestamp""#,
114+ homework.get_id(),
115+ user,
116+ now
117+ )
118+ .fetch_optional(&mut *tx)
119+ .await?
120+ } else {
121+ sqlx::query_as!(
122+ HomeworkSubmission,
123+ r#"UPDATE homework_submission SET text = $3, updated_at = $4
124+ WHERE homework = $1 AND app_user = $2 AND graded_by_result IS NULL
125+ RETURNING id AS "id: HomeworkSubmissionId",
126+ homework AS "homework: HomeworkId",
127+ app_user AS "user: UserId",
128+ text AS "text: Option<SubmissionText>",
129+ submitted_at AS "submitted_at: Timestamp",
130+ updated_at AS "updated_at: Timestamp""#,
131+ homework.get_id(),
132+ user,
133+ text,
134+ now
135+ )
136+ .fetch_optional(&mut *tx)
137+ .await?
138+ };
139+ return Ok(updated.map(|submission| (submission, existing)));
140+ }
141+
142+ // First hand-in: the verdict is stored beside the counter it credits,
143+ // so the two can never disagree.
144+ let created = sqlx::query_as!(
145+ HomeworkSubmission,
146+ r#"INSERT INTO homework_submission
147+ (id, homework, app_user, text, submitted_at, updated_at, file_count, counted_on_time)
148+ VALUES ($1, $2, $3, $4, $5, $5, 0, $6)
149+ RETURNING id AS "id: HomeworkSubmissionId",
150+ homework AS "homework: HomeworkId",
151+ app_user AS "user: UserId",
152+ text AS "text: Option<SubmissionText>",
153+ submitted_at AS "submitted_at: Timestamp",
154+ updated_at AS "updated_at: Timestamp""#,
155+ HomeworkSubmissionId::generate(),
156+ homework.get_id(),
157+ user,
158+ text,
159+ now,
160+ on_time != 0,
161+ )
162+ .fetch_optional(&mut *tx)
163+ .await?;
164+ sqlx::query!(
165+ r#"UPDATE app_user SET
166+ homework_submitted_total = homework_submitted_total + 1,
167+ homework_on_time_total = homework_on_time_total + $2
168+ WHERE id = $1"#,
169+ user,
170+ on_time
171+ )
172+ .execute(&mut *tx)
173+ .await?;
174+ Ok(created.map(|submission| (submission, existing)))
175+ })
176+ .await
148177 }
149178
150179 /// Re-stamp a submission's `updated_at` to now, leaving its text and files
151180 /// alone. A file add or delete modifies the submission as a whole, so its
152181 /// "last touched" clock — which drives the computed late flag — must move
153-/// even though the text row is unchanged. Free-standing because the file
154-/// paths hold the composite id, not always the row. A targeted single-field
155-/// UPDATE, so the `READONLY` `submitted_at` is never re-sent (a `.content()`
156-/// would trip its guard). Returns the re-stamped row, or a 404 if it has
157-/// since vanished.
182+/// even though the text row is unchanged. A targeted single-field UPDATE, so
183+/// the readonly `submitted_at` is never re-sent. Returns the re-stamped row,
184+/// or a 404 if it has since vanished.
158185 pub async fn touch(
159186 db: &Database,
160187 id: &HomeworkSubmissionId,
161188 ) -> Result<HomeworkSubmission, AppError> {
162189 let now = Timestamp::now();
163- let mut result = db
164- .query("UPDATE $id SET updated_at = $now RETURN AFTER")
165- .bind(("id", id.record()))
166- .bind(("now", now))
167- .await?
168- .check()?;
169- result
170- .take::<Vec<HomeworkSubmission>>(0)?
171- .into_iter()
172- .next()
173- .ok_or(AppError::NotFound)
190+ sqlx::query_as!(
191+ HomeworkSubmission,
192+ r#"UPDATE homework_submission SET updated_at = $2 WHERE id = $1
193+ RETURNING id AS "id: HomeworkSubmissionId",
194+ homework AS "homework: HomeworkId",
195+ app_user AS "user: UserId",
196+ text AS "text: Option<SubmissionText>",
197+ submitted_at AS "submitted_at: Timestamp",
198+ updated_at AS "updated_at: Timestamp""#,
199+ id,
200+ now
201+ )
202+ .fetch_optional(db)
203+ .await?
204+ .ok_or(AppError::NotFound)
174205 }
175206
176207 /// Whether a grade has frozen this submission. Only ever read to tell two
177208 /// refusals apart *after* a conditional write has already refused one — the
178209 /// stamp on the row, never this read, is what decides.
179210 pub async fn is_graded(db: &Database, id: &HomeworkSubmissionId) -> Result<bool, AppError> {
180- let mut result = db
181- .query(format!(
182- "SELECT VALUE id FROM $id WHERE {SUBMISSION_GRADED_FIELD} != NONE"
183- ))
184- .bind(("id", id.record()))
185- .await?
186- .check()?;
187- Ok(!result.take::<Vec<HomeworkSubmissionId>>(0)?.is_empty())
211+ let row = sqlx::query!(
212+ r#"SELECT EXISTS(SELECT 1 FROM homework_submission
213+ WHERE id = $1 AND graded_by_result IS NOT NULL) AS "graded""#,
214+ id
215+ )
216+ .fetch_one(db)
217+ .await?;
218+ Ok(row.graded)
188219 }
189220
190221 /// `user`'s submission to `homework`, if they have one.
@@ -193,23 +224,40 @@ pub async fn read_for(
193224 homework: &crate::domain::homework::HomeworkId,
194225 user: &UserId,
195226 ) -> Result<Option<HomeworkSubmission>, AppError> {
196- Ok(db
197- .select(HomeworkSubmissionId::composite(homework, user).record())
198- .await?)
227+ Ok(sqlx::query_as!(
228+ HomeworkSubmission,
229+ r#"SELECT id AS "id: HomeworkSubmissionId",
230+ homework AS "homework: HomeworkId",
231+ app_user AS "user: UserId",
232+ text AS "text: Option<SubmissionText>",
233+ submitted_at AS "submitted_at: Timestamp",
234+ updated_at AS "updated_at: Timestamp"
235+ FROM homework_submission WHERE homework = $1 AND app_user = $2"#,
236+ homework,
237+ user
238+ )
239+ .fetch_optional(db)
240+ .await?)
199241 }
200242
201-/// Every submission to `homework`, in student (composite-id) order — the
202-/// roster's raw rows.
243+/// Every submission to `homework`, in creation order — the roster's raw rows.
203244 pub async fn list_for_homework(
204245 db: &Database,
205246 homework: &crate::domain::homework::HomeworkId,
206247 ) -> Result<Vec<HomeworkSubmission>, AppError> {
207- let mut result = db
208- .query("SELECT * FROM homework_submission WHERE homework = $hw ORDER BY id ASC")
209- .bind(("hw", homework.record()))
210- .await?
211- .check()?;
212- Ok(result.take::<Vec<HomeworkSubmission>>(0)?)
248+ Ok(sqlx::query_as!(
249+ HomeworkSubmission,
250+ r#"SELECT id AS "id: HomeworkSubmissionId",
251+ homework AS "homework: HomeworkId",
252+ app_user AS "user: UserId",
253+ text AS "text: Option<SubmissionText>",
254+ submitted_at AS "submitted_at: Timestamp",
255+ updated_at AS "updated_at: Timestamp"
256+ FROM homework_submission WHERE homework = $1 ORDER BY id ASC"#,
257+ homework
258+ )
259+ .fetch_all(db)
260+ .await?)
213261 }
214262
215263 /// Delete this submission and its files in one transaction — so a crash
@@ -217,9 +265,8 @@ pub async fn list_for_homework(
217265 /// are the web layer's to unlink: it lists them
218266 /// ([`crate::db::homework_file::list_for_submission`])
219267 /// before calling this. `None` means a grade froze the row (the caller
220-/// answers 409): the submission's own delete carries
221-/// [`SUBMISSION_OPEN_GUARD`], and the file wipe is conditional on it having
222-/// bitten, so a refused delete leaves the children standing too.
268+/// answers 409): the delete carries `graded_by_result IS NULL` as its own
269+/// condition, so a refused delete leaves the files standing too.
223270 ///
224271 /// The one place either badge counter comes back down, and deliberately the
225272 /// only one: this route is student-callable on their own row, so without it
@@ -234,12 +281,10 @@ pub async fn list_for_homework(
234281 /// and gave back something other than what was taken — extend it after a
235282 /// late hand-in and this debited a credit that was never given; pull it back
236283 /// after a punctual one and it debited nothing, leaving `on_time` above
237-/// `submitted`. A row from before the column exists carries no verdict, and
238-/// cannot be given one for a credit that already happened, so it falls back
239-/// to the old cut (`submitted_at`, the readonly stamp the increment judged,
240-/// against the live deadline); a dangling `homework` link leaves `$due`
241-/// `NONE` there, which compares false and so counts as late, matching the
242-/// backfill. Floored at zero: a row that predates the columns has none.
284+/// `submitted`. A row with no stored verdict falls back to the old cut
285+/// (`submitted_at`, the stamp the increment judged, against the deadline
286+/// read here); a homework already gone counts as late, matching the
287+/// backfill. Floored at zero.
243288 ///
244289 /// Badges already earned are never taken away — [`crate::domain::badge`] is
245290 /// add-only, which is where that permanence lives.
@@ -247,42 +292,66 @@ pub async fn delete(
247292 db: &Database,
248293 submission: HomeworkSubmission,
249294 ) -> Result<Option<HomeworkSubmission>, AppError> {
250- // Sound to re-send: DELETE and UPDATE can never answer "already exists".
251- let (mut result, mut errors) = transaction_with_retry(
252- db,
253- &format!(
254- "BEGIN TRANSACTION;
255- LET $due = (SELECT VALUE homework.due_at FROM ONLY $sub);
256- LET $gone = (DELETE $sub WHERE {SUBMISSION_OPEN_GUARD} RETURN BEFORE);
257- IF array::len($gone) > 0 {{
258- DELETE homework_file WHERE submission = $sub;
259- LET $on_time = IF ($gone[0].counted_on_time
260- ?? ($gone[0].submitted_at <= $due)) {{ 1 }} ELSE {{ 0 }};
261- UPDATE $usr SET
262- {HOMEWORK_SUBMITTED_TOTAL_FIELD} =
263- math::max([({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) - 1, 0]),
264- {HOMEWORK_ON_TIME_TOTAL_FIELD} =
265- math::max([({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) - $on_time, 0])
266- }};
267- RETURN $gone;
268- COMMIT TRANSACTION;"
269- ),
270- &[
271- ("sub".into(), submission.id.record().into_value()),
272- ("usr".into(), submission.user.record().into_value()),
273- ],
274- &[],
275- )
276- .await?;
277- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
278- return Err(error.into());
279- }
280- // The trailing `RETURN` is always the last statement before `COMMIT`.
281- let slot = result.num_statements().saturating_sub(2);
282- Ok(result
283- .take::<Vec<HomeworkSubmission>>(slot)?
284- .into_iter()
285- .next())
295+ tx_with_retry(db, false, async |tx| {
296+ // The homework row's lock is the serialization point against grading:
297+ // a grade locks the same row before it stamps, so either this delete
298+ // refuses off the stamp, or the grade landed on a row that is now
299+ // gone — grading absent work, which is allowed. Its `due_at` read is
300+ // also the replay fallback's deadline.
301+ let due = sqlx::query!(
302+ "SELECT due_at FROM homework WHERE id = $1 FOR UPDATE",
303+ submission.get_homework()
304+ )
305+ .fetch_optional(&mut *tx)
306+ .await?
307+ .map(|row| row.due_at);
308+ let gone = sqlx::query!(
309+ r#"DELETE FROM homework_submission
310+ WHERE id = $1 AND graded_by_result IS NULL
311+ RETURNING id AS "id: HomeworkSubmissionId",
312+ homework AS "homework: HomeworkId",
313+ app_user AS "user: UserId",
314+ text AS "text: Option<SubmissionText>",
315+ submitted_at AS "submitted_at: Timestamp",
316+ updated_at AS "updated_at: Timestamp",
317+ counted_on_time AS "counted_on_time: Option<bool>""#,
318+ submission.get_id()
319+ )
320+ .fetch_optional(&mut *tx)
321+ .await?;
322+ let Some(removed) = gone else {
323+ // Frozen, or already withdrawn by a rival — one refusal, as
324+ // before.
325+ return Ok(None);
326+ };
327+ sqlx::query!(
328+ "DELETE FROM homework_file WHERE submission = $1",
329+ removed.id
330+ )
331+ .execute(&mut *tx)
332+ .await?;
333+ let judged_on_time = due.map(|d| removed.submitted_at <= d).unwrap_or(false);
334+ let on_time = i64::from(removed.counted_on_time.unwrap_or(judged_on_time));
335+ sqlx::query!(
336+ r#"UPDATE app_user SET
337+ homework_submitted_total = GREATEST(homework_submitted_total - 1, 0),
338+ homework_on_time_total = GREATEST(homework_on_time_total - $2, 0)
339+ WHERE id = $1"#,
340+ removed.user,
341+ on_time
342+ )
343+ .execute(&mut *tx)
344+ .await?;
345+ Ok(Some(HomeworkSubmission {
346+ id: removed.id,
347+ homework: removed.homework,
348+ user: removed.user,
349+ text: removed.text,
350+ submitted_at: removed.submitted_at,
351+ updated_at: removed.updated_at,
352+ }))
353+ })
354+ .await
286355 }
287356
288357 #[cfg(test)]
src/domain/homework_result.rsmodified+1 -0
@@ -76,6 +76,7 @@ impl HomeworkStatus {
7676 pub struct HomeworkResult {
7777 pub(crate) id: HomeworkResultId,
7878 pub(crate) homework: HomeworkId,
79+ #[sqlx(rename = "app_user")]
7980 pub(crate) user: UserId,
8081 pub(crate) status: HomeworkStatus,
8182 pub(crate) mark: Option<Mark>,
src/domain/homework_submission.rsmodified+1 -0
@@ -70,6 +70,7 @@ impl SubmissionText {
7070 pub struct HomeworkSubmission {
7171 pub(crate) id: HomeworkSubmissionId,
7272 pub(crate) homework: HomeworkId,
73+ #[sqlx(rename = "app_user")]
7374 pub(crate) user: UserId,
7475 pub(crate) text: Option<SubmissionText>,
7576 pub(crate) submitted_at: Timestamp,
src/service/homework.rsmodified+21 -110
@@ -1,63 +1,26 @@
1-//! Homework workflows: the PATCH re-scope with its orphan guard, the
2-//! cascading delete, and the shared student-side wall
1+//! Homework workflows: the cascading delete and the shared student-side wall
32 //! ([`gate_own_submission`]) every submission path walks. Row reads and
43 //! listings pass through to [`crate::db::homework`]; the submission, file,
5-//! and grade workflows live in the sibling `service::homework_*` modules,
6-//! whose every locked path leases [`HOMEWORK_LOCK`].
4+//! and grade workflows live in the sibling `service::homework_*` modules.
5+//!
6+//! There is no homework subsystem lock any more: the writes that used to
7+//! serialize on one — the PATCH's orphan guard, the delete cascade, grading,
8+//! and every student-side write — now contend on the *homework row itself*
9+//! (`SELECT … FOR UPDATE` inside each transaction), so the ordering they
10+//! need survives a multi-process deployment. See
11+//! [`crate::db::homework::update`] and
12+//! [`crate::db::homework_result::grade`].
713
814 use crate::database::Database;
915 use crate::db::homework;
10-use crate::db::homework_file;
11-use crate::db::homework_result;
12-use crate::db::homework_submission;
1316 use crate::domain::course::CourseId;
1417 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};
15-use crate::domain::homework_result::HomeworkResult;
16-use crate::domain::homework_submission::HomeworkSubmission;
1718 use crate::domain::role::Role;
1819 use crate::domain::subject::SubjectId;
1920 use crate::domain::timestamp::Timestamp;
2021 use crate::domain::user::{User, UserId};
2122 use crate::error::AppError;
2223
23-/// Serializes the homework subsystem's cross-record check-then-writes, which
24-/// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as
25-/// [`crate::service::exam_attempt::EXAM_LOCK`]. Every lease below is held across the
26-/// database write it guards, so within this one process it does order a full
27-/// round trip — but the freeze no longer *rests* on that: a graded submission
28-/// used to stay unedited only because the "no grade yet" read and the write it
29-/// licensed sat under one lease. That rule now lives in the database too —
30-/// grading stamps [`crate::constant::SUBMISSION_GRADED_FIELD`] on the
31-/// submission row and every student-side write carries `graded_by_result =
32-/// NONE` as its own condition. The one case the stamp cannot cover — grading
33-/// work with no submission row yet — falls back to the lease pair, so a write
34-/// lease must never stop spanning its own database call (see
35-/// [`crate::db::homework_result::grade`]).
36-///
37-/// What still leases it, honestly:
38-/// - Write: the homework PATCH's orphan guard ([`update`]), the
39-/// homework-delete cascade ([`delete`]), and grade/ungrade — whose
40-/// freeze rule (the stamp landing on a submission that may be written in the
41-/// same instant) is the one thing here still resting on the two leases being
42-/// mutually exclusive. The *existence* half has left: a grade now moves a
43-/// value on the homework row inside its own transaction
44-/// ([`crate::db::homework_result::grade`]), so a
45-/// concurrent delete refuses it rather than being read around.
46-/// - Read: the student's submission/file writes, which no longer gate the
47-/// freeze but still must not land under a PATCH re-scoping the audience out
48-/// from under them.
49-///
50-/// The subject rule has left: creating a homework and re-tagging one move the
51-/// subject's reference counter, and the subject delete is refused while that
52-/// counter is non-zero ([`crate::domain::subject::Subject::delete`]), so
53-/// neither the create (in `web::courses`) nor the outside writer the subject
54-/// delete used to take is on this list any more.
55-///
56-/// Lock order, where both are taken: `HOMEWORK_LOCK` before the counter lock in
57-/// [`crate::db::cap`], never the reverse.
58-// corner-cut: global RwLock, shard per-homework if write latency ever matters.
59-pub(crate) static HOMEWORK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
60-
6124 #[expect(
6225 clippy::too_many_arguments,
6326 reason = "mirrors the sibling entities' create(field, field, ..) shape"
@@ -120,17 +83,10 @@ pub async fn list_for_user_in_course(
12083
12184 /// Re-scope (or re-tag, re-title, re-describe, re-schedule) the homework.
12285 ///
123-/// Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the
124-/// live submissions and results, and the row write depends on what it saw —
125-/// without the lease a submission (a reader) could land between the check
126-/// and the write, orphaned by the narrowing that just missed it. The subject
127-/// re-tag no longer needs it — it moves the two subjects' reference counters
128-/// inside [`homework::update`].
129-///
130-/// The orphan guard runs on exactly the requests that re-scope the audience.
131-/// An absent `assigned` writes nothing, so the stored subset is untouched and
132-/// no narrowing can happen behind the guard's back — which the old "carry the
133-/// snapshot back" branch could do, re-narrowing over a concurrent widening.
86+/// The audience-narrowing orphan guard and the stale-re-tag refusal are one
87+/// transaction with the write in [`homework::update`], under the homework
88+/// row's lock — a submission (which locks the same row before writing)
89+/// cannot land between the check and the narrowing it would have refused.
13490 pub async fn update(
13591 db: &Database,
13692 homework: Homework,
@@ -140,62 +96,17 @@ pub async fn update(
14096 due_at: Option<Timestamp>,
14197 assigned: Option<Option<Vec<UserId>>>,
14298 ) -> Result<Homework, AppError> {
143- let _guard = HOMEWORK_LOCK.write().await;
144- if let Some(resolved) = assigned.as_ref() {
145- ensure_no_orphans(&homework, resolved.as_deref(), db).await?;
146- }
14799 homework::update(db, homework, subject, title, description, due_at, assigned).await
148100 }
149101
150-/// Refuse (409) a PATCH that would narrow `homework`'s audience so a student
151-/// who already submitted or was graded falls outside it — their work would be
152-/// stranded. `new_assigned` is the proposed subset (`None` = whole course, in
153-/// which case no one can be orphaned). The blocking students are named in the
154-/// message so the teacher knows whose work to clear (or whom to keep assigned)
155-/// first.
156-async fn ensure_no_orphans(
157- homework: &Homework,
158- new_assigned: Option<&[UserId]>,
159- db: &Database,
160-) -> Result<(), AppError> {
161- // Whole-course covers everyone — no narrowing, no orphans.
162- let Some(subset) = new_assigned else {
163- return Ok(());
164- };
165- let submissions = homework_submission::list_for_homework(db, homework.get_id()).await?;
166- let results = homework_result::list_for_homework(db, homework.get_id()).await?;
167- let mut blocked: Vec<String> = Vec::new();
168- for user in submissions
169- .iter()
170- .map(HomeworkSubmission::get_user)
171- .chain(results.iter().map(HomeworkResult::get_user))
172- {
173- let key = user.key().to_string();
174- if !subset.contains(user) && !blocked.contains(&key) {
175- blocked.push(key);
176- }
177- }
178- if blocked.is_empty() {
179- Ok(())
180- } else {
181- Err(AppError::ConflictOwned(format!(
182- "narrowing the assigned list would orphan existing work by {} student(s): {}",
183- blocked.len(),
184- blocked.join(", ")
185- )))
186- }
187-}
188-
189-/// Delete the homework: collect the submission-file blob keys, then run the
190-/// cascading delete under [`HOMEWORK_LOCK`]'s write lease
191-/// so no submission can land under the homework mid-delete; the blob names are
192-/// collected before the rows are wiped (the cascade is one transaction, children
193-/// first) and removed after, so a crash in between strands at worst an
194-/// unreachable file.
102+/// Delete the homework: run the cascading delete (submissions, their files,
103+/// results, then the row — one transaction, children first) and return the
104+/// submission-file blob keys, which the transaction collected before the
105+/// wipes so no file added mid-delete can strand its blob. The web layer
106+/// unlinks the blobs once the rows are gone; a crash in between strands at
107+/// worst an unreachable file.
195108 pub async fn delete(db: &Database, homework: Homework) -> Result<Vec<String>, AppError> {
196- let _guard = HOMEWORK_LOCK.write().await;
197- let blob_keys = homework_file::file_keys_for_homework(db, homework.get_id()).await?;
198- homework::delete(db, homework).await?;
109+ let (_, blob_keys) = homework::delete(db, homework).await?;
199110 Ok(blob_keys)
200111 }
201112
src/service/homework_file.rsmodified+17 -13
@@ -2,9 +2,8 @@
22 //! submission (the graded gate plus the auto-created seat it hangs off) and
33 //! the pass-through reads the download paths scope through. The blob bytes
44 //! and their ordering (blob before row on upload, row before blob on delete)
5-//! stay the web layer's — it owns `files_path` — but every lease holder is
6-//! [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK)'s reader side.
7-//! The row writes live in [`crate::db::homework_file`].
5+//! stay the web layer's — it owns `files_path`. The row writes live in
6+//! [`crate::db::homework_file`].
87
98 use crate::database::Database;
109 use crate::db::homework_file;
@@ -18,10 +17,11 @@ use crate::error::AppError;
1817
1918 /// The submission the file will hang off, created if absent — a photo-only
2019 /// homework never types text, so an upload auto-creates an empty submission
21-/// to carry the file (an existing one's text is preserved). A photo-only
22-/// hand-in is a hand-in: it creates the row, so it moves the counters, so it
23-/// earns badges exactly as a text submit does. Refused (409) when a grade
24-/// has frozen the homework.
20+/// to carry the file (an existing one's text is preserved — `upsert` is
21+/// called with `preserve_text`, so even a rival hand-in landing mid-request
22+/// keeps its text). A photo-only hand-in is a hand-in: it creates the row,
23+/// so it moves the counters, so it earns badges exactly as a text submit
24+/// does. Refused (409) when a grade has frozen the homework.
2525 pub async fn ensure_can_attach(
2626 db: &Database,
2727 user: &User,
@@ -30,7 +30,7 @@ pub async fn ensure_can_attach(
3030 const GRADED: AppError = AppError::Conflict(
3131 "this homework has been graded — ask the teacher to remove the grade before adding files",
3232 );
33- // The common-case gate; the freeze itself rides on the writes below.
33+ // The common-case gate; the freeze itself rides on the write below.
3434 if crate::db::homework_result::read_for(db, homework.get_id(), user.get_id())
3535 .await?
3636 .is_some()
@@ -40,17 +40,21 @@ pub async fn ensure_can_attach(
4040 match homework_submission::read_for(db, homework.get_id(), user.get_id()).await? {
4141 Some(existing) => Ok(existing),
4242 None => {
43- let created = homework_submission::upsert(db, homework, user.get_id(), None)
44- .await?
45- .ok_or(GRADED)?;
46- crate::service::homework::award_badges(user.get_id(), db).await;
43+ let Some((created, fresh)) =
44+ homework_submission::upsert(db, homework, user.get_id(), None, true).await?
45+ else {
46+ return Err(GRADED);
47+ };
48+ if fresh {
49+ crate::service::homework::award_badges(user.get_id(), db).await;
50+ }
4751 Ok(created)
4852 }
4953 }
5054 }
5155
5256 /// Persist the assembled row — the seat claim and the freeze in one
53-/// conditional write (see [`homework_file::insert`]). `Ok(None)` is the
57+/// guarded insert (see [`homework_file::insert`]). `Ok(None)` is the
5458 /// freeze; the web layer keeps its own wording and unlinks the blob it wrote.
5559 pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> {
5660 homework_file::insert(db, file).await
src/service/homework_result.rsmodified+7 -10
@@ -1,10 +1,9 @@
11 //! Homework grading workflows: the policy gates around the atomic grade —
22 //! nobody grades themselves, the target must be a live enrolled student in
33 //! the homework's audience — and the un-grade. The freeze-stamping
4-//! transaction lives in [`crate::db::homework_result`]; grading holds
5-//! [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK)'s writer lease
6-//! across its gates and the write, the reader side of every student write's
7-//! lease pair.
4+//! transaction lives in [`crate::db::homework_result`]; it locks the
5+//! homework row across the stamp, which is what orders a grade against every
6+//! student-side write — there is no subsystem lock here any more.
87
98 use crate::database::Database;
109 use crate::db::homework;
@@ -20,11 +19,11 @@ use crate::error::{AppError, ValidationError};
2019 /// Record (or overwrite) `target`'s grade for the homework. The web layer
2120 /// has already read the homework, checked course-management rights, walled
2221 /// the archived term, and validated the status and mark; everything here is
23-/// re-run or decided under the writer lease:
22+/// re-run or decided against the row the grade transaction locks:
2423 ///
25-/// - the homework is re-read (a homework delete is a fellow writer — its
26-/// lease excludes this one, so a grade cannot resurrect a result row under
27-/// a vanished homework; the vanished row answers 404);
24+/// - the homework is re-read (a homework delete is a fellow writer — both
25+/// contend on the homework row's lock, so a grade cannot resurrect a
26+/// result row under a vanished homework; the vanished row answers 404);
2827 /// - grading never targets oneself — no grader, whatever their role, may
2928 /// write their own grade;
3029 /// - the target user must exist, and only students carry homework grades —
@@ -40,7 +39,6 @@ pub async fn grade(
4039 mark: Option<Mark>,
4140 target: &UserId,
4241 ) -> Result<HomeworkResult, AppError> {
43- let _guard = crate::service::homework::HOMEWORK_LOCK.write().await;
4442 let homework = homework::read(db, id).await?.ok_or(AppError::NotFound)?;
4543
4644 // Grading never targets oneself.
@@ -100,7 +98,6 @@ pub async fn ungrade(
10098 id: &HomeworkId,
10199 target: &UserId,
102100 ) -> Result<Option<HomeworkResult>, AppError> {
103- let _guard = crate::service::homework::HOMEWORK_LOCK.write().await;
104101 homework_result::remove(db, id, target).await
105102 }
106103
src/service/homework_submission.rsmodified+18 -26
@@ -1,8 +1,9 @@
1-//! Homework submission workflows: the student's submit (the lease-to-write
2-//! window that keeps a PATCH's audience re-scope from stranding a hand-in)
3-//! and the withdrawal that gives the badge counters back. The row writes
4-//! live in [`crate::db::homework_submission`]; every locked path here
5-//! leases [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK).
1+//! Homework submission workflows: the student's submit (the graded gate and
2+//! the audience interlock around the guarded upsert) and the withdrawal that
3+//! gives the badge counters back. The row writes live in
4+//! [`crate::db::homework_submission`]; the freeze itself is a condition of
5+//! those writes, and the homework row's lock is what orders them against
6+//! grading — there is no subsystem lock here any more.
67
78 use crate::database::Database;
89 use crate::db::homework_file;
@@ -23,29 +24,22 @@ pub struct Submitted {
2324 }
2425
2526 /// Submit (or re-submit) the caller's own work for a homework. The graded
26-/// gate and the audience interlock are the reader lease's — taken *before*
27-/// the gate read: read first and the audience this gate approved is one
28-/// committed PATCH old, so the narrowing that just passed the orphan guard
29-/// (no submission yet) is followed by the very submission it would have
30-/// refused. Holding the lease across gate *and* write is what makes the
31-/// PATCH wait and then see the row.
27+/// read below answers the common case — graded minutes ago, and the student
28+/// who never submitted has no row to carry the freeze; the upsert's own
29+/// `graded_by_result IS NULL` condition is what holds when the grade lands
30+/// *while* this request runs (grade and write serialize on the homework
31+/// row's lock).
3232 ///
33-/// `None` from [`homework_submission::upsert`] is a grade landing mid-request
34-/// (the stamp on the row refusing the write); the graded read above answers
35-/// the common case, and both return the same 409.
33+/// `None` from [`homework_submission::upsert`] is that freeze biting; both
34+/// refusals return the same 409.
3635 pub async fn submit(
3736 db: &Database,
3837 user: &User,
3938 id: &str,
4039 text: Option<SubmissionText>,
4140 ) -> Result<Submitted, AppError> {
42- let _guard = crate::service::homework::HOMEWORK_LOCK.read().await;
4341 let homework = crate::service::homework::gate_own_submission(id, user, db).await?;
4442 crate::service::homework::require_open_term(&homework, db).await?;
45- // The graded gate, twice over. This read answers the common case — graded
46- // minutes ago, and the student who never submitted has no row to carry the
47- // freeze; the upsert's own `WHERE` (the grade stamp on the row) is what
48- // holds when the grade lands *while* this request runs.
4943 const GRADED: AppError = AppError::Conflict(
5044 "this homework has been graded — ask the teacher to remove the grade before editing your submission",
5145 );
@@ -55,12 +49,11 @@ pub async fn submit(
5549 {
5650 return Err(GRADED);
5751 }
58- // 201-vs-200: a prior read is exact, where comparing the returned stamps
59- // would misreport a same-millisecond re-submit as a create.
60- let existed = homework_submission::read_for(db, homework.get_id(), user.get_id())
61- .await?
62- .is_some();
63- let Some(submission) = homework_submission::upsert(db, &homework, user.get_id(), text).await?
52+ // `existed` comes back from the transaction itself, so the 201-vs-200
53+ // answer and the badge rule are exact even against a rival first
54+ // hand-in.
55+ let Some((submission, existed)) =
56+ homework_submission::upsert(db, &homework, user.get_id(), text, false).await?
6457 else {
6558 return Err(GRADED);
6659 };
@@ -85,7 +78,6 @@ pub async fn submit(
8578 pub async fn delete(db: &Database, user: &User, id: &str) -> Result<Vec<HomeworkFile>, AppError> {
8679 let homework = crate::service::homework::gate_own_submission(id, user, db).await?;
8780 crate::service::homework::require_open_term(&homework, db).await?;
88- let _guard = crate::service::homework::HOMEWORK_LOCK.read().await;
8981 const GRADED: AppError = AppError::Conflict(
9082 "this homework has been graded — ask the teacher to remove the grade before deleting your submission",
9183 );
src/web/homework.rsmodified+52 -50
@@ -4,8 +4,9 @@
44 //! and the per-course listing live under `/courses/{id}/homework` (see
55 //! [`super::courses`]); everything shares the visibility rule
66 //! ([`Homework::student_sees`](crate::domain::homework::Homework::student_sees))
7-//! and the [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK), whose
8-//! leases the workflows take in [`crate::service::homework`] and its siblings.
7+//! The freeze and the audience interlock are conditions of the writes
8+//! themselves ([`crate::db::homework_submission`]), serialized on the
9+//! homework row's lock inside each transaction.
910
1011 use crate::web::tenant_state::State;
1112 use axum::Json;
@@ -26,9 +27,7 @@ use crate::domain::exam_result::Mark;
2627 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};
2728 use crate::domain::homework_file::{HomeworkFile, HomeworkFileId};
2829 use crate::domain::homework_result::{HomeworkResult, HomeworkStatus};
29-use crate::domain::homework_submission::{
30- HomeworkSubmission, HomeworkSubmissionId, SubmissionText,
31-};
30+use crate::domain::homework_submission::{HomeworkSubmission, SubmissionText};
3231 use crate::domain::note_file::{FileContentType, FileName};
3332 use crate::domain::role::Role;
3433 use crate::domain::timestamp::Timestamp;
@@ -310,11 +309,11 @@ async fn update_homework(
310309 }
311310 crate::service::course::require_open(&st.db, &course).await?;
312311
313- // The writer lease of [`HOMEWORK_LOCK`], the orphan guard, and the write
314- // are one unit in [`service::homework::update`]: the guard reads the live
315- // submissions and results, and the row write depends on what it saw —
316- // without the lease a submission (a reader) could land between the check
317- // and the write, orphaned by the narrowing that just missed it.
312+ // The orphan guard and the write are one unit in
313+ // [`service::homework::update`]: the guard reads the live submissions and
314+ // results inside the write's transaction, under the homework row's lock —
315+ // a submission (which locks the same row before writing) cannot land
316+ // between the check and the narrowing that just missed it.
318317
319318 // Only what the request carried: an omitted field stays `None` and is never
320319 // written, so a concurrent PATCH of another field survives. The two
@@ -333,7 +332,9 @@ async fn update_homework(
333332 // A kept (absent) due date may already be past; a newly set one may not be.
334333 check_not_past("due_at", due_at)?;
335334 let subject = match &req.subject_id {
336- Some(subject_id) => Some(crate::service::subject::in_course(&st.db, subject_id, course.get_id()).await?),
335+ Some(subject_id) => {
336+ Some(crate::service::subject::in_course(&st.db, subject_id, course.get_id()).await?)
337+ }
337338 None => None,
338339 };
339340 // The orphan guard runs on exactly the requests that re-scope the audience.
@@ -360,11 +361,11 @@ async fn update_homework(
360361
361362 /// Delete a homework and everything under it — submissions, their files, and
362363 /// results — then unlink the file blobs from disk. Requires teacher+ and
363-/// management rights over its course. Held under [`HOMEWORK_LOCK`]'s write lease
364-/// so no submission can land under the homework mid-delete; the blob names are
365-/// collected before the rows are wiped (the cascade is one transaction, children
366-/// first) and removed after, so a crash in between strands at worst an
367-/// unreachable file.
364+/// management rights over its course. The cascade is one transaction whose
365+/// homework-row lock keeps a submission from landing under the homework
366+/// mid-delete; the blob names are collected inside that transaction, before
367+/// the rows are wiped, and removed after, so a crash in between strands at
368+/// worst an unreachable file.
368369 #[utoipa::path(
369370 delete,
370371 path = "/{id}",
@@ -391,7 +392,7 @@ async fn delete_homework(
391392 ));
392393 }
393394 crate::service::course::require_open(&st.db, &course).await?;
394- // The writer lease, the blob-key collection, and the cascade are
395+ // The blob-key collection and the cascade are
395396 // [`service::homework::delete`]'s; unlinking the blobs stays here because
396397 // only the web layer knows `files_path`.
397398 let blob_keys = service::homework::delete(&st.db, homework).await?;
@@ -548,10 +549,9 @@ async fn submit(
548549 Some(text) if !text.is_empty() => Some(SubmissionText::try_new(text)?),
549550 _ => None,
550551 };
551- // The reader lease of [`HOMEWORK_LOCK`], the gate, the term wall, the
552- // graded check, and the upsert are one unit in
553- // [`service::homework_submission::submit`] — the audience interlock, not
554- // the freeze (that is the stamp on the row).
552+ // The gate, the term wall, the graded check, and the upsert are one
553+ // unit in [`service::homework_submission::submit`] — the audience
554+ // interlock, not the freeze (that is the stamp on the row).
555555 let landed = service::homework_submission::submit(&st.db, &user, &id, text).await?;
556556 let files =
557557 service::homework_file::list_for_submission(&st.db, landed.submission.get_id()).await?;
@@ -721,19 +721,15 @@ async fn upload_submission_file(
721721 const GRADED: AppError = AppError::Conflict(
722722 "this homework has been graded — ask the teacher to remove the grade before adding files",
723723 );
724- // Reader lease as in `submit` — the audience interlock, not the freeze.
725- // Taken before the cap claim inside the insert, never after (the lock
726- // order is HOMEWORK_LOCK, then the counter lock). The lock lives in
727- // [`service::homework`]; the blob write stays here, inside the lease,
728- // because the row's "stored row points at a real blob" ordering does.
729- let _guard = service::homework::HOMEWORK_LOCK.read().await;
730- // Re-read the homework *under* the lease. Streaming the body takes as long
731- // as the client wants it to, and a homework delete (a writer) both takes
732- // and releases its lease inside that window — so the pre-flight snapshot
733- // can name a homework that no longer exists, and this handler would then
734- // auto-create a submission, credit the badge counters and write a file
735- // under it, all unreachable afterwards. A gate read before the body is a
736- // pre-flight; a gate read after it is the decision.
724+ // Re-read the homework. Streaming the body takes as long as the client
725+ // wants it to, and a homework delete can commit inside that window — so
726+ // the pre-flight snapshot can name a homework that no longer exists, and
727+ // this handler would then auto-create a submission, credit the badge
728+ // counters and write a file under it, all unreachable afterwards. A gate
729+ // read before the body is a pre-flight; a gate read after it is the
730+ // decision. The writes below are still ordered against a delete, a grade
731+ // and a PATCH narrowing the audience — each contends on the homework
732+ // row's lock inside its own transaction.
737733 let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?;
738734 // Re-walled too: the term can be archived while the body streams.
739735 service::homework::require_open_term(&homework, &st.db).await?;
@@ -801,8 +797,11 @@ async fn download_submission_file(
801797 let file = if user.get_role() == Role::Student {
802798 // Student: only their own file, behind the full submission gate.
803799 let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?;
804- let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id());
805- service::homework_file::read_for(&st.db, &file_id, &submission)
800+ let submission =
801+ service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id())
802+ .await?
803+ .ok_or(AppError::NotFound)?;
804+ service::homework_file::read_for(&st.db, &file_id, submission.get_id())
806805 .await?
807806 .ok_or(AppError::NotFound)?
808807 } else {
@@ -850,19 +849,23 @@ async fn delete_submission_file(
850849 const GRADED: AppError = AppError::Conflict(
851850 "this homework has been graded — ask the teacher to remove the grade before deleting files",
852851 );
853- // Reader lease as in `submit` — the audience interlock, not the freeze.
854- let _guard = service::homework::HOMEWORK_LOCK.read().await;
855852 if service::homework_result::read_for(&st.db, homework.get_id(), user.get_id())
856853 .await?
857854 .is_some()
858855 {
859856 return Err(GRADED);
860857 }
861- let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id());
862- let file =
863- service::homework_file::read_for(&st.db, &HomeworkFileId::from_key(&fid), &submission)
858+ let submission =
859+ service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id())
864860 .await?
865861 .ok_or(AppError::NotFound)?;
862+ let file = service::homework_file::read_for(
863+ &st.db,
864+ &HomeworkFileId::from_key(&fid),
865+ submission.get_id(),
866+ )
867+ .await?
868+ .ok_or(AppError::NotFound)?;
866869 let blob = file.get_file().to_string();
867870 // The delete's own transaction re-stamps the submission's "last touched"
868871 // clock (the late flag) as its freeze gate, so a refused delete moves
@@ -923,12 +926,11 @@ async fn grade_homework(
923926 Path(id): Path<String>,
924927 Json(req): Json<GradeHomework>,
925928 ) -> Result<Json<HomeworkResultResponse>, AppError> {
926- // The grading gates and the writer lease of [`HOMEWORK_LOCK`] live in
927- // [`service::homework_result::grade`]: a grade is what freezes a
928- // submission, so it must not interleave with the read side's
929- // gate-through-write submission edits — and the homework is re-read under
930- // the lease there, which keeps a homework delete (a fellow writer) from
931- // letting the upsert resurrect a result row under a vanished homework.
929+ // The grading gates live in [`service::homework_result::grade`]; the
930+ // grade transaction locks the homework row across the freeze stamp, which
931+ // orders it against every student-side write — and keeps a homework
932+ // delete from letting the upsert resurrect a result row under a vanished
933+ // homework (the vanished row answers 404).
932934 let (homework, course) = homework_with_course(&id, &st.db).await?;
933935 if !can_manage_course(&course, &teacher) {
934936 return Err(AppError::Forbidden(
@@ -974,9 +976,9 @@ async fn remove_homework_result(
974976 RequireTeacher(user): RequireTeacher,
975977 Path((id, target)): Path<(String, String)>,
976978 ) -> Result<StatusCode, AppError> {
977- // The writer lease of [`HOMEWORK_LOCK`] is [`service::homework_result::ungrade`]'s
978- // — removing the grade is what unfreezes the submission, so it must not
979- // straddle the read side's gate-through-write edits either.
979+ // Removing the grade is what unfreezes the submission; the un-grade's
980+ // transaction takes the homework row's lock, so it cannot straddle a
981+ // student-side write either.
980982 let (homework, course) = homework_with_course(&id, &st.db).await?;
981983 if !can_manage_course(&course, &user) {
982984 return Err(AppError::Forbidden(