From 19ba18aec3eebe1ea1112e011db5bbbc1c749a31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 25 Jul 2026 05:42:54 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=94=92=20drain=20the=20whole-row?= =?UTF-8?q?=20save=20backlog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - a whole-row .content(self) reverts any write that landed between the struct's read and its save; the gate flagged 14 sites and this empties it - course.rs was the only genuinely raceable one, in both directions: teachers[] is written by assign, unassign and the demotion sweep while Course::update rewrites the text columns, so staffing a course reverted a concurrent rename and a rename dropped a concurrent assignment. Both reproduced as failing tests first - assign/unassign now use array::distinct(array::append(...)) and teachers -= $usr rather than rewriting the array from a stale read - session, event, note, term, homework and work-entry updates are each their row's only writer and rewrite every mutable field, so no failing interleaving exists today; converted defensively anyway, following Subject::update, and not test-proven - the five create/upsert sites are annotated instead: each builds its struct in place from the request and never reads it back --- src/domain/answer_image.rs | 1 + src/domain/course.rs | 65 ++++++++++++++----- src/domain/course_session.rs | 24 ++++--- src/domain/event.rs | 26 +++++--- src/domain/homework.rs | 35 +++++++---- src/domain/homework_file.rs | 1 + src/domain/note.rs | 17 +++-- src/domain/note_file.rs | 1 + src/domain/pool_question.rs | 1 + src/domain/solution.rs | 1 + src/domain/term.rs | 23 +++++-- src/domain/work_entry.rs | 17 +++-- tests/integration.rs | 119 +++++++++++++++++++++++++++++++++++ 13 files changed, 271 insertions(+), 60 deletions(-) diff --git a/src/domain/answer_image.rs b/src/domain/answer_image.rs index 565f891..78e6375 100644 --- a/src/domain/answer_image.rs +++ b/src/domain/answer_image.rs @@ -123,6 +123,7 @@ impl AnswerImage { /// deterministic id makes this the whole "one drawing per student per /// question" story. pub async fn upsert(self, db: &Database) -> Result { + // whole-row-save-ok: self is built in place from the request, never read back, and the (question, user, seq) id is deterministic — replacing the row *is* the operation let written: Option = db.upsert(self.id.record()).content(self).await?; written.ok_or_else(|| AppError::Internal("failed to store answer image".into())) } diff --git a/src/domain/course.rs b/src/domain/course.rs index afcc800..5bba5ed 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -227,8 +227,14 @@ impl Course { Ok(result.take::>(0)?) } + /// Field-scoped: `teachers` is written by [`Self::assign_teacher`], + /// [`Self::unassign_teacher`] and the demotion sweep, and nothing guards + /// the course row across the handler's read and this write (its `TERM_LOCK` + /// window guards the *term* it links, and the assign path takes no lock at + /// all) — a whole-row save would revert an assignment that landed in + /// between. pub async fn update( - mut self, + self, title: CourseTitle, description: CourseDescription, kind: CourseKind, @@ -236,43 +242,70 @@ impl Course { capacity: Option, db: &Database, ) -> Result { - self.title = title; - self.description = description; - self.kind = kind; - self.term = term; - self.capacity = capacity; - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.ok_or(AppError::NotFound) + let mut result = db + .query( + "UPDATE $id SET title = $title, description = $description, kind = $kind, + term = $term, capacity = $capacity RETURN AFTER", + ) + .bind(("id", self.id.record())) + .bind(("title", title)) + .bind(("description", description)) + .bind(("kind", kind)) + .bind(("term", term.map(|term| term.record()))) + .bind(("capacity", capacity)) + .await? + .check()?; + result.take::>(0)?.into_iter().next().ok_or(AppError::NotFound) } /// Assign `teacher` to run this course, or return the course untouched if /// they already run it — assignment is idempotent, like enrollment. + /// Field-scoped, and the new list is folded server-side out of the *stored* + /// one: a course PATCH awaits a term lookup between its read and its write, + /// so a whole-row save from either side would revert the other. The + /// `array::distinct` keeps the assignment idempotent even when two requests + /// name the same teacher at once (the early return only sees a stale row). pub async fn assign_teacher( - mut self, + self, teacher: &UserId, db: &Database, ) -> Result { if self.is_assigned(teacher) { return Ok(self); } - self.teachers.push(teacher.clone()); - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.ok_or(AppError::NotFound) + let mut result = db + .query( + "UPDATE $id SET teachers = array::distinct(array::append(teachers, $usr)) + RETURN AFTER", + ) + .bind(("id", self.id.record())) + .bind(("usr", teacher.record())) + .await? + .check()?; + result.take::>(0)?.into_iter().next().ok_or(AppError::NotFound) } /// Drop `teacher` from this course. `None` when they weren't assigned, so /// the web layer can answer 404 instead of pretending it removed someone. pub async fn unassign_teacher( - mut self, + self, teacher: &UserId, db: &Database, ) -> Result, AppError> { if !self.is_assigned(teacher) { return Ok(None); } - self.teachers.retain(|assigned| assigned != teacher); - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.map(Some).ok_or(AppError::NotFound) + // Same field-scoped story as [`Self::assign_teacher`]; `-=` drops the + // one link off the stored list without touching the course's own text. + let mut result = db + .query("UPDATE $id SET teachers -= $usr RETURN AFTER") + .bind(("id", self.id.record())) + .bind(("usr", teacher.record())) + .await? + .check()?; + Ok(Some( + result.take::>(0)?.into_iter().next().ok_or(AppError::NotFound)?, + )) } /// Strip `user` from every course they were assigned to — the sweep for a diff --git a/src/domain/course_session.rs b/src/domain/course_session.rs index fe0c22c..a2f2743 100644 --- a/src/domain/course_session.rs +++ b/src/domain/course_session.rs @@ -134,20 +134,30 @@ impl CourseSession { Ok(result.take::>(0)?) } + /// Field-scoped, like every other save in this codebase: the handler holds + /// no lock across its read and this write, so a whole-row save would carry + /// the whole stale row back over anything that landed in between. pub async fn update( - mut self, + self, teacher: UserId, topic: SessionTopic, starts_at: Timestamp, ends_at: Option, db: &Database, ) -> Result { - self.teacher = teacher; - self.topic = topic; - self.starts_at = starts_at; - self.ends_at = ends_at; - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.ok_or(AppError::NotFound) + let mut result = db + .query( + "UPDATE $id SET teacher = $teacher, topic = $topic, + starts_at = $starts_at, ends_at = $ends_at RETURN AFTER", + ) + .bind(("id", self.id.record())) + .bind(("teacher", teacher.record())) + .bind(("topic", topic)) + .bind(("starts_at", starts_at)) + .bind(("ends_at", ends_at)) + .await? + .check()?; + result.take::>(0)?.into_iter().next().ok_or(AppError::NotFound) } /// Delete the session and cascade-remove its roll-call rows. diff --git a/src/domain/event.rs b/src/domain/event.rs index 352e068..3c51510 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -249,8 +249,11 @@ impl Event { Ok(result.take::>(0)?) } + /// Field-scoped: the handler reads the event, then awaits the clock and a + /// course lookup before saving, holding no lock — a whole-row save would + /// carry the stale `creator` and every other column back over the row. pub async fn update( - mut self, + self, title: EventTitle, description: EventDescription, audience: EventAudience, @@ -258,13 +261,20 @@ impl Event { ends_at: Option, db: &Database, ) -> Result { - self.title = title; - self.description = description; - self.audience = audience; - self.starts_at = starts_at; - self.ends_at = ends_at; - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.ok_or(AppError::NotFound) + let mut result = db + .query( + "UPDATE $id SET title = $title, description = $description, + audience = $audience, starts_at = $starts_at, ends_at = $ends_at RETURN AFTER", + ) + .bind(("id", self.id.record())) + .bind(("title", title)) + .bind(("description", description)) + .bind(("audience", audience)) + .bind(("starts_at", starts_at)) + .bind(("ends_at", ends_at)) + .await? + .check()?; + result.take::>(0)?.into_iter().next().ok_or(AppError::NotFound) } /// Delete the event and cascade-remove its attendance and signup rows. diff --git a/src/domain/homework.rs b/src/domain/homework.rs index 8067c8a..bb2dfea 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -255,13 +255,14 @@ impl Homework { } /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework. - /// `course`, `created_by`, and `created_at` are untouched — the write - /// re-sends them unchanged, which the `READONLY` schema permits (only a - /// *changed* readonly value is refused). The web layer has already - /// re-checked the new `due_at` against now and the new `subject` against - /// the course, and refused a narrowing that would orphan a submission. + /// Field-scoped, so `course`, `created_by`, and `created_at` are never in + /// the write at all — no `READONLY` column is re-sent, and nothing the + /// request didn't name can be carried back from a stale read. The web layer + /// has already re-checked the new `due_at` against now and the new + /// `subject` against the course, and refused a narrowing that would orphan + /// a submission. pub async fn update( - mut self, + self, subject: &SubjectId, title: HomeworkTitle, description: Option, @@ -269,13 +270,21 @@ impl Homework { assigned: Option>, db: &Database, ) -> Result { - self.subject = subject.clone(); - self.title = title; - self.description = description; - self.due_at = due_at; - self.assigned = assigned; - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.ok_or(AppError::NotFound) + let assigned = assigned.map(|users| users.iter().map(UserId::record).collect::>()); + let mut result = db + .query( + "UPDATE $id SET subject = $subject, title = $title, description = $description, + due_at = $due_at, assigned = $assigned RETURN AFTER", + ) + .bind(("id", self.id.record())) + .bind(("subject", subject.record())) + .bind(("title", title)) + .bind(("description", description)) + .bind(("due_at", due_at)) + .bind(("assigned", assigned)) + .await? + .check()?; + result.take::>(0)?.into_iter().next().ok_or(AppError::NotFound) } /// Delete the homework and cascade its submissions, their files, and its diff --git a/src/domain/homework_file.rs b/src/domain/homework_file.rs index 73c36a9..38ae894 100644 --- a/src/domain/homework_file.rs +++ b/src/domain/homework_file.rs @@ -131,6 +131,7 @@ impl HomeworkFile { "the submission already holds the maximum of 10 files — delete one first", )); } + // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber let created: Option = db.create(self.id.record()).content(self).await?; created.ok_or_else(|| AppError::Internal("failed to create homework file".into())) } diff --git a/src/domain/note.rs b/src/domain/note.rs index 652861a..6c20f23 100644 --- a/src/domain/note.rs +++ b/src/domain/note.rs @@ -115,16 +115,23 @@ impl Note { Ok(result.take::>(0)?) } + /// Field-scoped, mirroring [`crate::domain::subject::Subject::update`]: no + /// lock spans the handler's read and this write, so only the two columns + /// the request actually carries are written. pub async fn update( - mut self, + self, title: NoteTitle, content: NoteContent, db: &Database, ) -> Result { - self.title = title; - self.content = content; - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.ok_or(AppError::NotFound) + let mut result = db + .query("UPDATE $id SET title = $title, content = $content RETURN AFTER") + .bind(("id", self.id.record())) + .bind(("title", title)) + .bind(("content", content)) + .await? + .check()?; + result.take::>(0)?.into_iter().next().ok_or(AppError::NotFound) } /// Delete the note and cascade-remove its attachment rows. Blob files on diff --git a/src/domain/note_file.rs b/src/domain/note_file.rs index f66e7ca..0504dfd 100644 --- a/src/domain/note_file.rs +++ b/src/domain/note_file.rs @@ -168,6 +168,7 @@ impl NoteFile { "the note already holds the maximum of 10 files — delete one first", )); } + // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber let created: Option = db.create(self.id.record()).content(self).await?; created.ok_or_else(|| AppError::Internal("failed to create note file".into())) } diff --git a/src/domain/pool_question.rs b/src/domain/pool_question.rs index 720a6ad..f223d8b 100644 --- a/src/domain/pool_question.rs +++ b/src/domain/pool_question.rs @@ -158,6 +158,7 @@ impl PoolQuestion { } pub async fn insert(self, db: &Database) -> Result { + // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber let created: Option = db.create(self.id.record()).content(self).await?; created.ok_or_else(|| AppError::Internal("failed to create pool question".into())) } diff --git a/src/domain/solution.rs b/src/domain/solution.rs index 2616399..880f430 100644 --- a/src/domain/solution.rs +++ b/src/domain/solution.rs @@ -127,6 +127,7 @@ impl Solution { } pub async fn insert(self, db: &Database) -> Result { + // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber let created: Option = db.create(self.id.record()).content(self).await?; created.ok_or_else(|| AppError::Internal("failed to create solution".into())) } diff --git a/src/domain/term.rs b/src/domain/term.rs index 102035d..4ee2f6e 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -121,18 +121,29 @@ impl Term { Ok(result.take::>(0)?) } + /// Field-scoped: the handler reads the term, then awaits validation before + /// saving with no lock held ([`TERM_LOCK`] guards the delete's link check, + /// not this), so the save states its own three columns instead of replaying + /// a whole stale row. pub async fn update( - mut self, + self, name: TermName, starts_at: Timestamp, ends_at: Timestamp, db: &Database, ) -> Result { - self.name = name; - self.starts_at = starts_at; - self.ends_at = ends_at; - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.ok_or(AppError::NotFound) + let mut result = db + .query( + "UPDATE $id SET name = $name, starts_at = $starts_at, + ends_at = $ends_at RETURN AFTER", + ) + .bind(("id", self.id.record())) + .bind(("name", name)) + .bind(("starts_at", starts_at)) + .bind(("ends_at", ends_at)) + .await? + .check()?; + result.take::>(0)?.into_iter().next().ok_or(AppError::NotFound) } /// True iff any course still links to this term — the delete guard. diff --git a/src/domain/work_entry.rs b/src/domain/work_entry.rs index ab44379..bad088e 100644 --- a/src/domain/work_entry.rs +++ b/src/domain/work_entry.rs @@ -157,16 +157,23 @@ impl WorkEntry { /// Persist corrected instants (manager fix-ups on closed entries; the web /// layer validates ordering and rejects open entries). + /// Field-scoped: the stint's `user` is never part of a correction, so it is + /// left out of the write rather than replayed from a struct the handler + /// read before its validation awaits. pub async fn update( - mut self, + self, check_in: Timestamp, check_out: Timestamp, db: &Database, ) -> Result { - self.check_in = check_in; - self.check_out = Some(check_out); - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.ok_or(AppError::NotFound) + let mut result = db + .query("UPDATE $id SET check_in = $check_in, check_out = $check_out RETURN AFTER") + .bind(("id", self.id.record())) + .bind(("check_in", check_in)) + .bind(("check_out", check_out)) + .await? + .check()?; + result.take::>(0)?.into_iter().next().ok_or(AppError::NotFound) } pub async fn remove(id: &WorkEntryId, db: &Database) -> Result, AppError> { diff --git a/tests/integration.rs b/tests/integration.rs index 92bfd6c..6ede277 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -18877,3 +18877,122 @@ async fn refreshing_a_question_recopies_its_template() { .await; assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); } + +/// A course PATCH is a field-scoped write. The handler reads the course, then +/// awaits a term lookup (and its `TERM_LOCK`) before saving, holding nothing +/// over the course row itself — so a manager's teacher assignment can land in +/// that window. A whole-row save from the stale struct would silently revert +/// the staffing. Driven at the domain level: HTTP offers no way to interleave +/// inside the handler. +#[tokio::test] +async fn a_course_patch_does_not_clobber_a_concurrent_teacher_assignment() { + use hezarfen_backend::domain::course::{ + Course, CourseDescription, CourseId, CourseKind, CourseTitle, + }; + + let (app, db) = app_and_db().await; + let owner = login_as(&app, &db, "cclob_o", "teacher").await; + let helper = login_as(&app, &db, "cclob_h", "teacher").await; + let boss = login_as(&app, &db, "cclob_m", "manager").await; + let helper_id = me_id(&app, &helper).await; + let course = create_course(&app, &owner, "cclob_c").await; + + // The handler's read, then the assignment lands mid-window. + let stale = Course::read(&CourseId::from_key(&course), &db) + .await + .unwrap() + .expect("course exists"); + let res = send( + &app, + "POST", + &format!("/courses/{course}/teachers"), + Some(&boss), + Some(json!({ "user_id": helper_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let updated = stale + .update( + CourseTitle::try_new("renamed").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + None, + None, + &db, + ) + .await + .expect("update written"); + assert_eq!(updated.get_teachers().len(), 1, "the assignment was reverted"); + + // The rename landed and the assigned teacher stayed assigned. + let res = send(&app, "GET", &format!("/courses/{course}"), Some(&owner), None).await; + assert_eq!(res.body["title"], "renamed"); + assert_eq!(res.body["teachers"][0]["username"], "cclob_h"); +} + +/// The mirror image: staffing writes only `teachers`. `assign_teacher` reads +/// the course, then awaits the target user's row (a role check) before saving, +/// so a course PATCH can land in between — and a whole-row save would revert +/// the rename. `unassign_teacher` gets the same field-scoped treatment. +#[tokio::test] +async fn staffing_a_course_does_not_clobber_a_concurrent_edit() { + use hezarfen_backend::domain::course::{Course, CourseId}; + use hezarfen_backend::domain::user::UserId; + + let (app, db) = app_and_db().await; + let owner = login_as(&app, &db, "cstaff_o", "teacher").await; + let helper = login_as(&app, &db, "cstaff_h", "teacher").await; + let helper_id = me_id(&app, &helper).await; + let course = create_course(&app, &owner, "cstaff_c").await; + + // The handler's read, then someone else's edit lands mid-window. + let stale = Course::read(&CourseId::from_key(&course), &db) + .await + .unwrap() + .expect("course exists"); + let res = send( + &app, + "PATCH", + &format!("/courses/{course}"), + Some(&owner), + Some(json!({ "title": "edited by someone else", "capacity": 9 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let assigned = stale + .assign_teacher(&UserId::from_key(&helper_id), &db) + .await + .expect("assignment written"); + assert_eq!(assigned.get_title().as_str(), "edited by someone else"); + assert_eq!(assigned.get_capacity(), Some(9)); + assert_eq!(assigned.get_teachers().len(), 1); + + // Unassigning from a struct read before another edit is just as safe. + let stale = Course::read(&CourseId::from_key(&course), &db) + .await + .unwrap() + .expect("course exists"); + let res = send( + &app, + "PATCH", + &format!("/courses/{course}"), + Some(&owner), + Some(json!({ "title": "edited again" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let dropped = stale + .unassign_teacher(&UserId::from_key(&helper_id), &db) + .await + .expect("unassignment written") + .expect("teacher was assigned"); + assert_eq!(dropped.get_title().as_str(), "edited again"); + assert!(dropped.get_teachers().is_empty()); + + let res = send(&app, "GET", &format!("/courses/{course}"), Some(&owner), None).await; + assert_eq!(res.body["title"], "edited again"); + assert_eq!(res.body["capacity"], 9); + assert_eq!(res.body["teachers"].as_array().unwrap().len(), 0); +}