forge
Explore
Log in

Don't you dare go Hollow

🧩 finish the partial-PATCH sweep — 4 more handlers lost writes

Browse files at this commit

d773e7e4f308dee7d06b46f93199da14291c7d16Ahmet Kaan GümüşParent: 50966f8
  • fix
    • 🧩 finish the partial-PATCH sweep — 4 more handlers lost writes
Show full message
fix: 🧩 finish the partial-PATCH sweep — 4 more handlers lost writes

32bca26 routed six resources through `FieldUpdate` so a PATCH writes only
the fields it was given. It stopped at six of ten. The remaining four
still read the row unguarded and then wrote a field-scoped `SET` bound to
that stale snapshot, so two concurrent PATCHes of different fields
reverted each other, 200 OK, silently:

- subjects and the two user routes (`apply_profile`/`apply_preferences`,
  four endpoints) move to `FieldUpdate`. No lock needed — neither has a
  cross-field check, so request-scoped values alone close it
- course sessions get `SESSION_LOCK`, taken *before* the row read
  whenever `starts_at`/`ends_at` arrives, with the range merged and
  revalidated against the stored other end. The lock is not optional:
  converting to `FieldUpdate` without it re-introduces 9e25e0c, verified
  by disabling it and watching a one-ended PATCH store
  `starts_at > ends_at` with both requests answering 200
- bank questions instead take `BANK_LOCK.write()` before `owned_question`.
  This one is a genuine read-modify-write — the kind/choices/correct
  trio must merge from the stored row because choice ids carry the option
  pictures — so an exclusive lease over read+merge+write is the fix, the
  same shape as the exam PATCH. Per-field writes cannot express it
- `subject.rs` also mints ids via `monotonic_id::next_ulid()` now, since
  subjects list `ORDER BY id ASC`; `bank_questions.rs` rustdoc stops
  calling a choice id a position

Also verified safe and left alone: the exam and exam-question PATCHes
already hold `EXAM_LOCK.write()` across read and write, settings uses a
CAS retry, and messages/chatbot/questions/appointments write single
fields.

Each new suite races 20 rounds and reads the row back; every one fails if
the stale refill is restored.
src/domain/course_session.rsmodified+34 -24
@@ -1,14 +1,30 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2+use tokio::sync::Mutex;
2 use ulid::Ulid;3 use ulid::Ulid;
3 4
4 use crate::constant::MAX_SESSION_TOPIC_LEN;5 use crate::constant::MAX_SESSION_TOPIC_LEN;
5 use crate::database::{COURSE_SESSION_TABLE, Database};6 use crate::database::{COURSE_SESSION_TABLE, Database};
6 use crate::domain::course::CourseId;7 use crate::domain::course::CourseId;
8+use crate::domain::field_update::FieldUpdate;
7 use crate::domain::timestamp::Timestamp;9 use crate::domain::timestamp::Timestamp;
8 use crate::domain::user::UserId;10 use crate::domain::user::UserId;
9 use crate::error::{AppError, ValidationError};11 use crate::error::{AppError, ValidationError};
10 use crate::validate::validate_optional;12 use crate::validate::validate_optional;
11 13
14+/// Serializes a lesson's time-range check against the write it guards, exactly
15+/// as [`crate::domain::event::EVENT_LOCK`] does for events: `starts_at <=
16+/// ends_at` is a cross-field check, so a PATCH carrying one end validates it
17+/// against the *stored* other end — two such PATCHes, each fine on its own
18+/// snapshot, would otherwise commit an inverted lesson between them. A PATCH
19+/// that moves neither end checks nothing cross-field and stays lock-free.
20+///
21+/// Lock order: this is a leaf — the only path that takes it (`PATCH
22+/// /sessions/{id}`) takes no other lock, and no path holding `EXAM_LOCK`,
23+/// `BANK_LOCK`, `HOMEWORK_LOCK`, `ENROLL_LOCK` or any other takes this one, so
24+/// it cannot sit in a cycle. Should a future path need both, take the other
25+/// lock first and this one innermost.
26+pub(crate) static SESSION_LOCK: Mutex<()> = Mutex::const_new(());
27+
12 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]28 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
13 pub struct CourseSessionId(RecordId);29 pub struct CourseSessionId(RecordId);
14 30
@@ -134,34 +150,28 @@ impl CourseSession {
134 Ok(result.take::<Vec<CourseSession>>(0)?)150 Ok(result.take::<Vec<CourseSession>>(0)?)
135 }151 }
136 152
137- /// Field-scoped, like every other save in this codebase: the handler holds153+ /// Request-scoped: the handler holds no lock across its read and this write
138- /// no lock across its read and this write, so a whole-row save would carry154+ /// unless a schedule end arrives ([`SESSION_LOCK`]), so a field the request
139- /// the whole stale row back over anything that landed in between.155+ /// omitted (`None`) is not written at all. Re-sending the snapshot's value
156+ /// instead would revert a concurrent PATCH of that field — scoping the
157+ /// `SET` alone does not stop that, the values have to come from the
158+ /// request. `ends_at` is nullable, so it takes the outer/inner
159+ /// `Option<Option<_>>`: `None` = omitted (keep), `Some(None)` = clear.
140 pub async fn update(160 pub async fn update(
141 self,161 self,
142- teacher: UserId,162+ teacher: Option<UserId>,
143- topic: SessionTopic,163+ topic: Option<SessionTopic>,
144- starts_at: Timestamp,164+ starts_at: Option<Timestamp>,
145- ends_at: Option<Timestamp>,165+ ends_at: Option<Option<Timestamp>>,
146 db: &Database,166 db: &Database,
147 ) -> Result<CourseSession, AppError> {167 ) -> Result<CourseSession, AppError> {
148- let mut result = db168+ FieldUpdate::new(self.id.record())
149- .query(169+ .set("teacher", teacher.map(|teacher| teacher.record()))
150- "UPDATE $id SET teacher = $teacher, topic = $topic,170+ .set("topic", topic)
151- starts_at = $starts_at, ends_at = $ends_at RETURN AFTER",171+ .set("starts_at", starts_at)
152- )172+ .set("ends_at", ends_at)
153- .bind(("id", self.id.record()))173+ .run::<CourseSession>(db)
154- .bind(("teacher", teacher.record()))174+ .await
155- .bind(("topic", topic))
156- .bind(("starts_at", starts_at))
157- .bind(("ends_at", ends_at))
158- .await?
159- .check()?;
160- result
161- .take::<Vec<CourseSession>>(0)?
162- .into_iter()
163- .next()
164- .ok_or(AppError::NotFound)
165 }175 }
166 176
167 /// Delete the session and cascade-remove its roll-call rows.177 /// Delete the session and cascade-remove its roll-call rows.
src/domain/field_update.rsmodified+2 -2
@@ -4,8 +4,8 @@
4 //! WHY: a handler reads the row, then writes. Filling a field the request4 //! WHY: a handler reads the row, then writes. Filling a field the request
5 //! omitted from that snapshot re-sends a value the client never gave, so a5 //! omitted from that snapshot re-sends a value the client never gave, so a
6 //! concurrent PATCH of the *other* field that landed in between is silently6 //! concurrent PATCH of the *other* field that landed in between is silently
7-//! reverted — the same lost update the whole-row-save gate bans, just spelled7+//! reverted — the same lost update a whole-row `.content(self)` save causes,
8-//! field by field. Scoping the `SET` is not enough; the *values* must come8+//! just spelled field by field. Scoping the `SET` is not enough; the *values* must come
9 //! from the request, so an absent field is never written at all.9 //! from the request, so an absent field is never written at all.
10 //!10 //!
11 //! Callers therefore take `Option<T>` per field (`None` = absent, keep) and11 //! Callers therefore take `Option<T>` per field (`None` = absent, keep) and
src/domain/subject.rsmodified+35 -19
@@ -1,9 +1,10 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2-use ulid::Ulid;
3 2
4 use crate::constant::{MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN};3 use crate::constant::{MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN};
5 use crate::database::{Database, SUBJECT_TABLE};4 use crate::database::{Database, SUBJECT_TABLE};
6 use crate::domain::course::CourseId;5 use crate::domain::course::CourseId;
6+use crate::domain::field_update::FieldUpdate;
7+use crate::domain::monotonic_id::next_ulid;
7 use crate::error::{AppError, ValidationError};8 use crate::error::{AppError, ValidationError};
8 use crate::validate::{validate_optional, validate_required};9 use crate::validate::{validate_optional, validate_required};
9 10
@@ -11,8 +12,12 @@ use crate::validate::{validate_optional, validate_required};
11 pub struct SubjectId(RecordId);12 pub struct SubjectId(RecordId);
12 13
13 impl SubjectId {14 impl SubjectId {
15+ /// Minted from the process-wide monotonic generator, not `Ulid::new()`: the
16+ /// id *is* the curriculum's order ([`Subject::list_for_course`] sorts
17+ /// `id ASC`), and a random low half scrambles a burst of saves that lands
18+ /// inside one millisecond.
14 pub fn generate() -> Self {19 pub fn generate() -> Self {
15- Self(RecordId::new(SUBJECT_TABLE, Ulid::new().to_string()))20+ Self(RecordId::new(SUBJECT_TABLE, next_ulid().to_string()))
16 }21 }
17 22
18 pub fn from_key(key: &str) -> Self {23 pub fn from_key(key: &str) -> Self {
@@ -136,27 +141,23 @@ impl Subject {
136 Ok(result.take::<Vec<Subject>>(0)?)141 Ok(result.take::<Vec<Subject>>(0)?)
137 }142 }
138 143
144+ /// Request-scoped: no lock spans the handler's read and this write, so an
145+ /// omitted field (`None`) is not written at all. Passing the snapshot's
146+ /// value back instead would revert a concurrent edit of that field —
147+ /// scoping the `SET` alone does not prevent that, the values have to come
148+ /// from the request. Neither column is nullable, so plain `Option` per
149+ /// field says everything there is to say.
139 pub async fn update(150 pub async fn update(
140 self,151 self,
141- name: SubjectName,152+ name: Option<SubjectName>,
142- description: SubjectDescription,153+ description: Option<SubjectDescription>,
143 db: &Database,154 db: &Database,
144 ) -> Result<Subject, AppError> {155 ) -> Result<Subject, AppError> {
145- // Field-scoped: the handler holds no lock across its read and this156+ FieldUpdate::new(self.id.record())
146- // write, so a whole-row save would revert a concurrent edit of the157+ .set("name", name)
147- // other field.158+ .set("description", description)
148- let mut result = db159+ .run::<Subject>(db)
149- .query("UPDATE $id SET name = $name, description = $description RETURN AFTER")160+ .await
150- .bind(("id", self.id.record()))
151- .bind(("name", name))
152- .bind(("description", description))
153- .await?
154- .check()?;
155- result
156- .take::<Vec<Subject>>(0)?
157- .into_iter()
158- .next()
159- .ok_or(AppError::NotFound)
160 }161 }
161 162
162 /// Delete the subject and clear it off every bank template that carried it163 /// Delete the subject and clear it off every bank template that carried it
@@ -193,6 +194,21 @@ impl Subject {
193 mod tests {194 mod tests {
194 use super::*;195 use super::*;
195 196
197+ /// A teacher entering a curriculum gets it back in the order they typed it:
198+ /// `list_for_course` sorts `id ASC`, so the ids minted inside one
199+ /// millisecond have to sort in mint order. Revert `generate` to
200+ /// `Ulid::new()` and this fails — the low 80 bits are redrawn per id, so a
201+ /// same-tick burst comes out shuffled.
202+ #[tokio::test]
203+ async fn ids_sort_in_creation_order() {
204+ let ids: Vec<String> = (0..500)
205+ .map(|_| SubjectId::generate().key().to_string())
206+ .collect();
207+ let mut sorted = ids.clone();
208+ sorted.sort();
209+ assert_eq!(ids, sorted);
210+ }
211+
196 #[tokio::test]212 #[tokio::test]
197 async fn name_is_required() {213 async fn name_is_required() {
198 assert!(SubjectName::try_new("Limits").is_ok());214 assert!(SubjectName::try_new("Limits").is_ok());
src/domain/user.rsmodified+36 -48
@@ -6,6 +6,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
6 use ulid::Ulid;6 use ulid::Ulid;
7 7
8 use crate::database::{Database, USER_TABLE};8 use crate::database::{Database, USER_TABLE};
9+use crate::domain::field_update::FieldUpdate;
9 use crate::domain::preferences::{Language, Theme};10 use crate::domain::preferences::{Language, Theme};
10 use crate::domain::profile::{BirthDate, Email, PersonName, Phone};11 use crate::domain::profile::{BirthDate, Email, PersonName, Phone};
11 use crate::domain::role::Role;12 use crate::domain::role::Role;
@@ -396,63 +397,50 @@ impl User {
396 .ok_or(AppError::NotFound)397 .ok_or(AppError::NotFound)
397 }398 }
398 399
399- /// Overwrite the personal-info fields wholesale. Each argument is the final400+ /// Write the personal-info fields the request actually carried. Every
400- /// value (`None` clears); merging "keep what wasn't sent" against the401+ /// column is nullable, so each argument is an outer/inner `Option`: `None`
401- /// current row is the HTTP layer's job. The caller authorizes. Writes only402+ /// = omitted (not written at all), `Some(None)` = cleared, `Some(Some(v))`
402- /// the five profile fields — see [`User::set_role`] for why the writers403+ /// = set. Merging the request against the current row is the HTTP layer's
403- /// are field-scoped.404+ /// job; the caller authorizes.
405+ ///
406+ /// Request-scoped, not merely field-scoped: nothing guards the row across
407+ /// the handler's read and this write, so re-sending the snapshot's value
408+ /// for an omitted field would revert a concurrent PATCH of that field —
409+ /// two profile edits (a name and a phone) used to lose each other. See
410+ /// [`User::set_role`] for why no writer here touches the whole row.
404 pub async fn set_profile(411 pub async fn set_profile(
405 self,412 self,
406- name: Option<PersonName>,413+ name: Option<Option<PersonName>>,
407- surname: Option<PersonName>,414+ surname: Option<Option<PersonName>>,
408- email: Option<Email>,415+ email: Option<Option<Email>>,
409- phone: Option<Phone>,416+ phone: Option<Option<Phone>>,
410- birth_date: Option<BirthDate>,417+ birth_date: Option<Option<BirthDate>>,
411 db: &Database,418 db: &Database,
412 ) -> Result<User, AppError> {419 ) -> Result<User, AppError> {
413- let mut result = db420+ FieldUpdate::new(self.id.record())
414- .query(421+ .set("name", name)
415- "UPDATE $id SET name = $name, surname = $surname, email = $email, \422+ .set("surname", surname)
416- phone = $phone, birth_date = $birth_date RETURN AFTER",423+ .set("email", email)
417- )424+ .set("phone", phone)
418- .bind(("id", self.id.record()))425+ .set("birth_date", birth_date)
419- .bind(("name", name))426+ .run::<User>(db)
420- .bind(("surname", surname))427+ .await
421- .bind(("email", email))
422- .bind(("phone", phone))
423- .bind(("birth_date", birth_date))
424- .await?
425- .check()?;
426- result
427- .take::<Vec<User>>(0)?
428- .into_iter()
429- .next()
430- .ok_or(AppError::NotFound)
431 }428 }
432 429
433- /// Overwrite the UI-preference fields wholesale. Same contract as430+ /// Write the UI-preference fields the request actually carried. Same
434- /// [`User::set_profile`]: each argument is the final value (`None` clears431+ /// contract as [`User::set_profile`]: `None` = omitted (not written),
435- /// back to "never chose"), merging is the HTTP layer's job, the caller432+ /// `Some(None)` = cleared back to "never chose", `Some(Some(v))` = set.
436- /// authorizes. Writes only `theme` and `language` — see [`User::set_role`]
437- /// for why the writers are field-scoped.
438 pub async fn set_preferences(433 pub async fn set_preferences(
439 self,434 self,
440- theme: Option<Theme>,435+ theme: Option<Option<Theme>>,
441- language: Option<Language>,436+ language: Option<Option<Language>>,
442 db: &Database,437 db: &Database,
443 ) -> Result<User, AppError> {438 ) -> Result<User, AppError> {
444- let mut result = db439+ FieldUpdate::new(self.id.record())
445- .query("UPDATE $id SET theme = $theme, language = $language RETURN AFTER")440+ .set("theme", theme)
446- .bind(("id", self.id.record()))441+ .set("language", language)
447- .bind(("theme", theme))442+ .run::<User>(db)
448- .bind(("language", language))443+ .await
449- .await?
450- .check()?;
451- result
452- .take::<Vec<User>>(0)?
453- .into_iter()
454- .next()
455- .ok_or(AppError::NotFound)
456 }444 }
457 445
458 pub async fn find_by_username(username: &str, db: &Database) -> Result<Option<User>, AppError> {446 pub async fn find_by_username(username: &str, db: &Database) -> Result<Option<User>, AppError> {
@@ -498,7 +486,7 @@ mod tests {
498 // admin's change.486 // admin's change.
499 let name = PersonName::try_new("name", "Ayşenur").unwrap();487 let name = PersonName::try_new("name", "Ayşenur").unwrap();
500 stale488 stale
501- .set_profile(Some(name.clone()), None, None, None, None, &db)489+ .set_profile(Some(Some(name.clone())), None, None, None, None, &db)
502 .await490 .await
503 .unwrap();491 .unwrap();
504 492
src/web/bank_questions.rsmodified+23 -9
@@ -47,8 +47,11 @@ use super::{
47 };47 };
48 48
49 /// Serializes bank writes that adopt a `subject` against a concurrent subject49 /// Serializes bank writes that adopt a `subject` against a concurrent subject
50-/// delete. Bank create/update take the reader lease across their50+/// delete. Bank create takes the reader lease across its
51-/// subject-exists check and the write; the subject delete takes the writer51+/// subject-exists check and the write; the *update* takes the writer lease
52+/// instead, because it is a read-modify-write of the whole template, so its row
53+/// read must be serialized against another update and not merely against the
54+/// delete cascade; the subject delete takes the writer
52 /// lease across the cascade that clears `subject` off every template, so a55 /// lease across the cascade that clears `subject` off every template, so a
53 /// template can't land on a subject that vanished mid-flight (it would outlive56 /// template can't land on a subject that vanished mid-flight (it would outlive
54 /// the sweep) — the bank twin of the57 /// the sweep) — the bank twin of the
@@ -419,7 +422,7 @@ pub(crate) async fn store_image(
419 /// Add a template to the bank. Requires teacher+. `subject_id` is origin422 /// Add a template to the bank. Requires teacher+. `subject_id` is origin
420 /// metadata (any subject — the same-course rule lives at instantiate time),423 /// metadata (any subject — the same-course rule lives at instantiate time),
421 /// so it need only exist (an unknown subject is a `400`). `choice` templates424 /// so it need only exist (an unknown subject is a `400`). `choice` templates
422-/// carry 2–10 `choices` plus the `correct` index; `text` templates carry425+/// carry 2–10 `choices` plus `correct` naming one of them by id; `text` templates carry
423 /// neither. The caller becomes the owner.426 /// neither. The caller becomes the owner.
424 #[utoipa::path(427 #[utoipa::path(
425 post,428 post,
@@ -628,11 +631,21 @@ async fn update_question(
628 Path(bid): Path<String>,631 Path(bid): Path<String>,
629 Json(req): Json<UpdateBankQuestion>,632 Json(req): Json<UpdateBankQuestion>,
630 ) -> Result<Json<BankQuestionResponse>, AppError> {633 ) -> Result<Json<BankQuestionResponse>, AppError> {
634+ // *Writer* lease of [`BANK_LOCK`], taken before the row is read: this is a
635+ // read-modify-write, not a per-field write. Omitted fields are refilled from
636+ // the snapshot below, and the kind/choices/correct trio genuinely has to be
637+ // (a text-only edit re-submits the stored options *with their ids* so every
638+ // choice keeps its picture), so the read, the merge and the write must be
639+ // one unit or a concurrent PATCH of another field is silently reverted. The
640+ // reader lease this used to take was both shared *and* acquired after the
641+ // read, so it serialized nothing; it only ever covered the subject-exists
642+ // check against a subject delete, which the writer lease still covers.
643+ // Exclusive means bank writes queue behind each other — they are rare
644+ // teacher edits, and the per-field alternative cannot express the
645+ // choice-identity merge. Still the only lock this path takes, so the
646+ // documented EXAM → BANK order is unaffected.
647+ let _guard = BANK_LOCK.write().await;
631 let question = owned_question(&st, &user, &bid).await?;648 let question = owned_question(&st, &user, &bid).await?;
632-
633- // Reader lease of [`BANK_LOCK`] across the exists-check and the update, so a
634- // re-tag to a subject that's being deleted can't straddle the delete-guard.
635- let _guard = BANK_LOCK.read().await;
636 // Omitted keeps the stored subject — which may already be `None`, cleared649 // Omitted keeps the stored subject — which may already be `None`, cleared
637 // by that subject's delete.650 // by that subject's delete.
638 let subject = match req.subject_id {651 let subject = match req.subject_id {
@@ -818,8 +831,9 @@ async fn delete_question_image(
818 831
819 /// Attach (or replace) one option's picture on a `choice` template. Owner only832 /// Attach (or replace) one option's picture on a `choice` template. Owner only
820 /// (admins aside). Same form, limits, and rules as the illustration upload;833 /// (admins aside). Same form, limits, and rules as the illustration upload;
821-/// `index` is the option's zero-based position. Replacing the `choices` list834+/// `choice_id` is the `id` carried on that choice, as returned in the
822-/// drops all its option pictures.835+/// template's `choices` (not a position — an unknown id is a `400`). Replacing
836+/// the `choices` list drops all its option pictures.
823 #[utoipa::path(837 #[utoipa::path(
824 post,838 post,
825 path = "/{bid}/choices/{choice_id}/image",839 path = "/{bid}/choices/{choice_id}/image",
src/web/sessions.rsmodified+38 -31
@@ -11,7 +11,7 @@ use utoipa_axum::routes;
11 use crate::database::Database;11 use crate::database::Database;
12 use crate::domain::attendance::AttendanceStatus;12 use crate::domain::attendance::AttendanceStatus;
13 use crate::domain::course::Course;13 use crate::domain::course::Course;
14-use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic};14+use crate::domain::course_session::{CourseSession, CourseSessionId, SESSION_LOCK, SessionTopic};
15 use crate::domain::enrollment::Enrollment;15 use crate::domain::enrollment::Enrollment;
16 use crate::domain::role::Role;16 use crate::domain::role::Role;
17 use crate::domain::session_attendance::SessionAttendance;17 use crate::domain::session_attendance::SessionAttendance;
@@ -186,6 +186,25 @@ async fn update_session(
186 Path(id): Path<String>,186 Path(id): Path<String>,
187 Json(req): Json<UpdateSession>,187 Json(req): Json<UpdateSession>,
188 ) -> Result<Json<SessionResponse>, AppError> {188 ) -> Result<Json<SessionResponse>, AppError> {
189+ // Only values this request sets are held to the no-past rule — a kept
190+ // `starts_at` of a lesson already underway is legitimately past. A provided
191+ // `ends_at` sets the field, an explicit `null` clears it, an omitted one is
192+ // left alone.
193+ let starts_at = req.starts_at.map(Timestamp::from_millis);
194+ check_not_past("starts_at", starts_at)?;
195+ let ends_at = req.ends_at.map(|update| update.map(Timestamp::from_millis));
196+ if let Some(ends_at) = ends_at {
197+ check_not_past("ends_at", ends_at)?;
198+ }
199+ // Only the range check needs the stored row, and only it can race: it
200+ // validates an arriving end against the other end as stored, so the read,
201+ // the check and the write are held together under [`SESSION_LOCK`]. A PATCH
202+ // that moves neither end pays nothing.
203+ let _guard = match (starts_at, ends_at) {
204+ (None, None) => None,
205+ _ => Some(SESSION_LOCK.lock().await),
206+ };
207+
189 let (session, course) = session_with_course(&id, &st.db).await?;208 let (session, course) = session_with_course(&id, &st.db).await?;
190 if !can_manage_course(&course, &user) {209 if !can_manage_course(&course, &user) {
191 return Err(AppError::Forbidden(210 return Err(AppError::Forbidden(
@@ -193,38 +212,26 @@ async fn update_session(
193 ));212 ));
194 }213 }
195 214
196- let topic = match req.topic {215+ let topic = req
197- Some(ref topic) => SessionTopic::try_new(topic)?,216+ .topic
198- None => session.get_topic().clone(),217+ .as_deref()
199- };218+ .map(SessionTopic::try_new)
219+ .transpose()?;
200 let teacher = match req.teacher_id {220 let teacher = match req.teacher_id {
201- Some(ref key) => resolve_session_teacher(Some(key), &user, &st.db)221+ Some(ref key) => Some(
202- .await?222+ resolve_session_teacher(Some(key), &user, &st.db)
203- .get_id()223+ .await?
204- .clone(),224+ .get_id()
205- None => session.get_teacher().clone(),225+ .clone(),
206- };226+ ),
207- // Only values this request sets are held to the no-past rule — a kept227+ None => None,
208- // `starts_at` of a lesson already underway is legitimately past.
209- let starts_at = match req.starts_at {
210- Some(millis) => {
211- let starts_at = Timestamp::from_millis(millis);
212- check_not_past("starts_at", Some(starts_at))?;
213- starts_at
214- }
215- None => session.get_starts_at(),
216- };
217- // A provided value sets the field, an explicit `null` clears it, and an
218- // omitted one keeps the current value.
219- let ends_at = match req.ends_at {
220- Some(update) => {
221- let ends_at = update.map(Timestamp::from_millis);
222- check_not_past("ends_at", ends_at)?;
223- ends_at
224- }
225- None => session.get_ends_at(),
226 };228 };
227- check_time_range(Some(starts_at), ends_at)?;229+ // The end this request left out is only *read* for the range check — it is
230+ // never written back, so a concurrent move of it survives.
231+ check_time_range(
232+ Some(starts_at.unwrap_or_else(|| session.get_starts_at())),
233+ ends_at.unwrap_or_else(|| session.get_ends_at()),
234+ )?;
228 235
229 let updated = session236 let updated = session
230 .update(teacher, topic, starts_at, ends_at, &st.db)237 .update(teacher, topic, starts_at, ends_at, &st.db)
src/web/subjects.rsmodified+9 -8
@@ -143,14 +143,15 @@ async fn update_subject(
143 ));143 ));
144 }144 }
145 145
146- let name = match req.name {146+ // Only what the request actually carried is validated and written — an
147- Some(ref name) => SubjectName::try_new(name)?,147+ // omitted field stays `None` so the save never re-sends this snapshot's
148- None => subject.get_name().clone(),148+ // value over a concurrent PATCH of the other field.
149- };149+ let name = req.name.as_deref().map(SubjectName::try_new).transpose()?;
150- let description = match req.description {150+ let description = req
151- Some(ref description) => SubjectDescription::try_new(description)?,151+ .description
152- None => subject.get_description().clone(),152+ .as_deref()
153- };153+ .map(SubjectDescription::try_new)
154+ .transpose()?;
154 155
155 let updated = subject.update(name, description, &st.db).await?;156 let updated = subject.update(name, description, &st.db).await?;
156 Ok(Json(SubjectResponse::new(&updated)))157 Ok(Json(SubjectResponse::new(&updated)))
src/web/users.rsmodified+22 -31
@@ -76,48 +76,45 @@ struct UpdatePreferences {
76 language: Option<String>,76 language: Option<String>,
77 }77 }
78 78
79-/// Resolve one patched field: absent keeps the current value, `""` clears it,79+/// Resolve one patched field into what the save should write: absent (or
80-/// anything else must parse into the domain newtype.80+/// `null`) is `None` — the column is not written at all, so a concurrent PATCH
81-fn merge_field<T: Clone>(81+/// of it survives; `""` is `Some(None)`, an explicit clear; anything else must
82- current: Option<&T>,82+/// parse into the domain newtype, exactly as a create would.
83+fn merge_field<T>(
83 patch: Option<&str>,84 patch: Option<&str>,
84 parse: impl Fn(&str) -> Result<T, ValidationError>,85 parse: impl Fn(&str) -> Result<T, ValidationError>,
85-) -> Result<Option<T>, ValidationError> {86+) -> Result<Option<Option<T>>, ValidationError> {
86 match patch {87 match patch {
87- None => Ok(current.cloned()),88+ None => Ok(None),
88- Some("") => Ok(None),89+ Some("") => Ok(Some(None)),
89- Some(value) => Ok(Some(parse(value)?)),90+ Some(value) => Ok(Some(Some(parse(value)?))),
90 }91 }
91 }92 }
92 93
93-/// Merge `req` over `user`'s current info and persist. Shared by the94+/// Validate and persist exactly the info fields `req` carried — nothing is
94-/// self-service and admin profile endpoints — they differ only in whose row95+/// merged from `user`'s snapshot, so a concurrent PATCH of another field is not
95-/// they load and who may call them.96+/// reverted. Shared by the self-service and admin profile endpoints — they
97+/// differ only in whose row they load and who may call them.
96 async fn apply_profile(98 async fn apply_profile(
97 user: User,99 user: User,
98 req: &UpdateProfile,100 req: &UpdateProfile,
99 db: &Database,101 db: &Database,
100 ) -> Result<UserResponse, AppError> {102 ) -> Result<UserResponse, AppError> {
101- let name = merge_field(user.get_name(), req.name.as_deref(), |v| {103+ let name = merge_field(req.name.as_deref(), |v| PersonName::try_new("name", v))?;
102- PersonName::try_new("name", v)104+ let surname = merge_field(req.surname.as_deref(), |v| {
103- })?;
104- let surname = merge_field(user.get_surname(), req.surname.as_deref(), |v| {
105 PersonName::try_new("surname", v)105 PersonName::try_new("surname", v)
106 })?;106 })?;
107- let email = merge_field(user.get_email(), req.email.as_deref(), Email::try_new)?;107+ let email = merge_field(req.email.as_deref(), Email::try_new)?;
108- let phone = merge_field(user.get_phone(), req.phone.as_deref(), Phone::try_new)?;108+ let phone = merge_field(req.phone.as_deref(), Phone::try_new)?;
109- let birth_date = merge_field(109+ let birth_date = merge_field(req.birth_date.as_deref(), BirthDate::try_new)?;
110- user.get_birth_date(),
111- req.birth_date.as_deref(),
112- BirthDate::try_new,
113- )?;
114 let updated = user110 let updated = user
115 .set_profile(name, surname, email, phone, birth_date, db)111 .set_profile(name, surname, email, phone, birth_date, db)
116 .await?;112 .await?;
117 Ok(UserResponse::new(&updated))113 Ok(UserResponse::new(&updated))
118 }114 }
119 115
120-/// Merge `req` over `user`'s current preferences and persist. Shared by the116+/// Validate and persist exactly the preference fields `req` carried — same
117+/// no-merge reasoning as [`apply_profile`]. Shared by the
121 /// self-service and admin preference endpoints — they differ only in whose row118 /// self-service and admin preference endpoints — they differ only in whose row
122 /// they load and who may call them.119 /// they load and who may call them.
123 async fn apply_preferences(120 async fn apply_preferences(
@@ -125,14 +122,8 @@ async fn apply_preferences(
125 req: &UpdatePreferences,122 req: &UpdatePreferences,
126 db: &Database,123 db: &Database,
127 ) -> Result<UserResponse, AppError> {124 ) -> Result<UserResponse, AppError> {
128- let theme = merge_field(user.get_theme().as_ref(), req.theme.as_deref(), |v| {125+ let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?;
129- Theme::try_from_str(v)126+ let language = merge_field(req.language.as_deref(), Language::try_from_str)?;
130- })?;
131- let language = merge_field(
132- user.get_language().as_ref(),
133- req.language.as_deref(),
134- Language::try_from_str,
135- )?;
136 let updated = user.set_preferences(theme, language, db).await?;127 let updated = user.set_preferences(theme, language, db).await?;
137 Ok(UserResponse::new(&updated))128 Ok(UserResponse::new(&updated))
138 }129 }
tests/partial_patch_bank_questions.rsadded+166 -0
@@ -0,0 +1,166 @@
1+//! A bank-template PATCH is a read-modify-write: the kind/choices/correct trio
2+//! has to be re-submitted as a unit (choices carry their ids, and their
3+//! pictures hang off those ids), so the row read, the merge and the write are
4+//! held together under the *writer* lease of `BANK_LOCK`. Without that, two
5+//! concurrent partial PATCHes revert each other.
6+
7+mod common;
8+
9+use axum::http::StatusCode;
10+use common::*;
11+use serde_json::json;
12+
13+async fn template(app: &axum::Router, who: &str, subject: &str) -> String {
14+ let created = send(
15+ app,
16+ "POST",
17+ "/bank-questions",
18+ Some(who),
19+ Some(json!({ "subject_id": subject, "text": "old text",
20+ "kind": "text", "points": 1 })),
21+ )
22+ .await;
23+ assert_eq!(created.status, StatusCode::CREATED, "{}", created.body);
24+ id_of(&created.body)
25+}
26+
27+#[tokio::test]
28+async fn concurrent_partial_patches_keep_both_fields() {
29+ let (app, db) = app_and_db().await;
30+ let who = login_as(&app, &db, "ali", "teacher").await;
31+ let course = create_course(&app, &who, "math").await;
32+ let subject = create_subject(&app, &who, &course, "algebra").await;
33+
34+ for round in 0..20 {
35+ let uri = format!("/bank-questions/{}", template(&app, &who, &subject).await);
36+
37+ let (a, b) = tokio::join!(
38+ send(
39+ &app,
40+ "PATCH",
41+ &uri,
42+ Some(&who),
43+ Some(json!({ "text": "new text" })),
44+ ),
45+ send(
46+ &app,
47+ "PATCH",
48+ &uri,
49+ Some(&who),
50+ Some(json!({ "points": 7 })),
51+ ),
52+ );
53+ assert_eq!(a.status, StatusCode::OK, "round {round} text patch");
54+ assert_eq!(b.status, StatusCode::OK, "round {round} points patch");
55+
56+ let after = send(&app, "GET", &uri, Some(&who), None).await.body;
57+ assert_eq!(after["text"], "new text", "round {round}: text reverted");
58+ assert_eq!(after["points"], 7, "round {round}: points reverted");
59+ }
60+}
61+
62+/// The visibility switch races a text edit: publishing must not be undone by an
63+/// edit that never mentioned `visibility`, and vice versa.
64+#[tokio::test]
65+async fn publishing_survives_a_concurrent_text_edit() {
66+ let (app, db) = app_and_db().await;
67+ let who = login_as(&app, &db, "veli", "teacher").await;
68+ let course = create_course(&app, &who, "physics").await;
69+ let subject = create_subject(&app, &who, &course, "optics").await;
70+
71+ for round in 0..20 {
72+ let uri = format!("/bank-questions/{}", template(&app, &who, &subject).await);
73+
74+ let (a, b) = tokio::join!(
75+ send(
76+ &app,
77+ "PATCH",
78+ &uri,
79+ Some(&who),
80+ Some(json!({ "visibility": "school" })),
81+ ),
82+ send(
83+ &app,
84+ "PATCH",
85+ &uri,
86+ Some(&who),
87+ Some(json!({ "text": "edited" })),
88+ ),
89+ );
90+ assert_eq!(a.status, StatusCode::OK, "round {round} publish");
91+ assert_eq!(b.status, StatusCode::OK, "round {round} text patch");
92+
93+ let after = send(&app, "GET", &uri, Some(&who), None).await.body;
94+ assert_eq!(
95+ after["visibility"], "school",
96+ "round {round}: publish reverted"
97+ );
98+ assert_eq!(after["text"], "edited", "round {round}: text reverted");
99+ }
100+}
101+
102+/// The kind-dependent trio is still merged and re-validated as a unit, and the
103+/// choice ids (which the pictures hang off) survive a text-only edit.
104+#[tokio::test]
105+async fn choice_identity_and_unit_validation_survive() {
106+ let (app, db) = app_and_db().await;
107+ let who = login_as(&app, &db, "ayse", "teacher").await;
108+ let course = create_course(&app, &who, "math").await;
109+ let subject = create_subject(&app, &who, &course, "algebra").await;
110+
111+ let created = send(
112+ &app,
113+ "POST",
114+ "/bank-questions",
115+ Some(&who),
116+ Some(
117+ json!({ "subject_id": subject, "text": "2 + 2?", "kind": "choice",
118+ "points": 10,
119+ "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}],
120+ "correct": "c1" }),
121+ ),
122+ )
123+ .await;
124+ assert_eq!(created.status, StatusCode::CREATED, "{}", created.body);
125+ let ids: Vec<String> = created.body["choices"]
126+ .as_array()
127+ .expect("choices")
128+ .iter()
129+ .map(|c| c["id"].as_str().expect("choice id").to_string())
130+ .collect();
131+ let uri = format!("/bank-questions/{}", id_of(&created.body));
132+
133+ let edited = send(
134+ &app,
135+ "PATCH",
136+ &uri,
137+ Some(&who),
138+ Some(json!({ "text": "two plus two?" })),
139+ )
140+ .await;
141+ assert_eq!(edited.status, StatusCode::OK);
142+ let after_ids: Vec<String> = edited.body["choices"]
143+ .as_array()
144+ .expect("choices")
145+ .iter()
146+ .map(|c| c["id"].as_str().expect("choice id").to_string())
147+ .collect();
148+ assert_eq!(after_ids, ids, "a text edit kept every choice id");
149+ assert_eq!(edited.body["correct"], ids[1], "correct kept");
150+
151+ // Switching to a text template while keeping the stored choices is still a
152+ // unit-validation failure — a PATCH cannot land a half-question.
153+ let bad = send(
154+ &app,
155+ "PATCH",
156+ &uri,
157+ Some(&who),
158+ Some(json!({ "kind": "text" })),
159+ )
160+ .await;
161+ assert_eq!(
162+ bad.status,
163+ StatusCode::BAD_REQUEST,
164+ "text kind with stored choices refused"
165+ );
166+}
tests/partial_patch_sessions.rsadded+173 -0
@@ -0,0 +1,173 @@
1+//! Two concurrent partial PATCHes on the same session must not revert each
2+//! other, and — since only the fields a request carried are written — the
3+//! `starts_at`/`ends_at` pair must not be invertible by two one-ended PATCHes
4+//! either (that is what `SESSION_LOCK` is for).
5+
6+mod common;
7+
8+use axum::http::StatusCode;
9+use common::*;
10+use serde_json::json;
11+
12+const FUTURE: i64 = 1_900_000_000_000;
13+
14+#[tokio::test]
15+async fn concurrent_partial_patches_keep_both_fields() {
16+ let (app, db) = app_and_db().await;
17+ let who = login_as(&app, &db, "ali", "teacher").await;
18+ let course = create_course(&app, &who, "math").await;
19+
20+ for round in 0..20 {
21+ let created = send(
22+ &app,
23+ "POST",
24+ &format!("/courses/{course}/sessions"),
25+ Some(&who),
26+ Some(json!({ "topic": "old topic", "starts_at": FUTURE })),
27+ )
28+ .await;
29+ assert_eq!(created.status, StatusCode::CREATED, "round {round} create");
30+ let uri = format!("/sessions/{}", id_of(&created.body));
31+
32+ // `topic` races `ends_at`: different fields, neither may lose.
33+ let (a, b) = tokio::join!(
34+ send(
35+ &app,
36+ "PATCH",
37+ &uri,
38+ Some(&who),
39+ Some(json!({ "topic": "new topic" })),
40+ ),
41+ send(
42+ &app,
43+ "PATCH",
44+ &uri,
45+ Some(&who),
46+ Some(json!({ "ends_at": FUTURE + 3_600_000 })),
47+ ),
48+ );
49+ assert_eq!(a.status, StatusCode::OK, "round {round} topic patch");
50+ assert_eq!(b.status, StatusCode::OK, "round {round} ends_at patch");
51+
52+ let after = send(&app, "GET", &uri, Some(&who), None).await.body;
53+ assert_eq!(after["topic"], "new topic", "round {round}: topic reverted");
54+ assert_eq!(
55+ after["ends_at"],
56+ FUTURE + 3_600_000,
57+ "round {round}: ends_at reverted"
58+ );
59+ }
60+}
61+
62+/// Each end moved *just inside* the other is valid on its own snapshot, so two
63+/// concurrent one-ended PATCHes could each pass their check against the stored
64+/// row and still commit an inverted lesson between them. Whatever each request
65+/// returns (200/400 are both fine), the stored pair must stay ordered.
66+#[tokio::test]
67+async fn concurrent_range_patches_never_invert_the_stored_row() {
68+ let (app, db) = app_and_db().await;
69+ let who = login_as(&app, &db, "range", "teacher").await;
70+ let course = create_course(&app, &who, "math").await;
71+ let ends = FUTURE + 3_600_000;
72+
73+ for round in 0..20 {
74+ let created = send(
75+ &app,
76+ "POST",
77+ &format!("/courses/{course}/sessions"),
78+ Some(&who),
79+ Some(json!({ "starts_at": FUTURE, "ends_at": ends })),
80+ )
81+ .await;
82+ assert_eq!(created.status, StatusCode::CREATED, "round {round} create");
83+ let uri = format!("/sessions/{}", id_of(&created.body));
84+
85+ let (a, b) = tokio::join!(
86+ send(
87+ &app,
88+ "PATCH",
89+ &uri,
90+ Some(&who),
91+ Some(json!({ "starts_at": ends - 1000 })),
92+ ),
93+ send(
94+ &app,
95+ "PATCH",
96+ &uri,
97+ Some(&who),
98+ Some(json!({ "ends_at": FUTURE + 1000 })),
99+ ),
100+ );
101+
102+ let after = send(&app, "GET", &uri, Some(&who), None).await.body;
103+ let stored_starts = after["starts_at"].as_i64().expect("starts_at");
104+ let stored_ends = after["ends_at"].as_i64().expect("ends_at");
105+ assert!(
106+ stored_starts <= stored_ends,
107+ "round {round}: stored inverted lesson starts_at={stored_starts} \
108+ ends_at={stored_ends} (statuses {} {})",
109+ a.status,
110+ b.status
111+ );
112+ }
113+}
114+
115+/// `ends_at` stays genuinely nullable: omitted keeps it, an explicit `null`
116+/// clears it — and a one-ended PATCH is still checked against the stored other
117+/// end (read for the check, never written back).
118+#[tokio::test]
119+async fn ends_at_stays_clearable_and_range_checked() {
120+ let (app, db) = app_and_db().await;
121+ let who = login_as(&app, &db, "veli", "teacher").await;
122+ let course = create_course(&app, &who, "physics").await;
123+ let session = create_session(&app, &who, &course, FUTURE).await;
124+ let uri = format!("/sessions/{session}");
125+
126+ let set = send(
127+ &app,
128+ "PATCH",
129+ &uri,
130+ Some(&who),
131+ Some(json!({ "ends_at": FUTURE + 1_000 })),
132+ )
133+ .await;
134+ assert_eq!(set.status, StatusCode::OK);
135+ assert_eq!(set.body["ends_at"], FUTURE + 1_000);
136+
137+ let kept = send(
138+ &app,
139+ "PATCH",
140+ &uri,
141+ Some(&who),
142+ Some(json!({ "topic": "kept ends" })),
143+ )
144+ .await;
145+ assert_eq!(kept.status, StatusCode::OK);
146+ assert_eq!(kept.body["starts_at"], FUTURE, "omitted starts_at kept");
147+ assert_eq!(kept.body["ends_at"], FUTURE + 1_000, "omitted ends_at kept");
148+
149+ let bad = send(
150+ &app,
151+ "PATCH",
152+ &uri,
153+ Some(&who),
154+ Some(json!({ "ends_at": FUTURE - 1_000 })),
155+ )
156+ .await;
157+ assert_eq!(
158+ bad.status,
159+ StatusCode::BAD_REQUEST,
160+ "ends_at before stored starts_at"
161+ );
162+
163+ let cleared = send(
164+ &app,
165+ "PATCH",
166+ &uri,
167+ Some(&who),
168+ Some(json!({ "ends_at": null })),
169+ )
170+ .await;
171+ assert_eq!(cleared.status, StatusCode::OK);
172+ assert_eq!(cleared.body["ends_at"], json!(null), "ends_at not cleared");
173+}
tests/partial_patch_subjects.rsadded+89 -0
@@ -0,0 +1,89 @@
1+//! Two concurrent partial PATCHes on the same subject must not revert each
2+//! other. A handler that fills omitted fields from its own stale read writes
3+//! back a value the client never sent, so whichever request lands last wipes
4+//! the other's field.
5+
6+mod common;
7+
8+use axum::http::StatusCode;
9+use common::*;
10+use serde_json::json;
11+
12+#[tokio::test]
13+async fn concurrent_partial_patches_keep_both_fields() {
14+ let (app, db) = app_and_db().await;
15+ let who = login_as(&app, &db, "ali", "teacher").await;
16+ let course = create_course(&app, &who, "math").await;
17+
18+ for round in 0..20 {
19+ let created = send(
20+ &app,
21+ "POST",
22+ &format!("/courses/{course}/subjects"),
23+ Some(&who),
24+ Some(json!({ "name": "old name", "description": "old description" })),
25+ )
26+ .await;
27+ assert_eq!(created.status, StatusCode::CREATED, "round {round} create");
28+ let uri = format!("/subjects/{}", id_of(&created.body));
29+
30+ let (a, b) = tokio::join!(
31+ send(
32+ &app,
33+ "PATCH",
34+ &uri,
35+ Some(&who),
36+ Some(json!({ "name": "new name" })),
37+ ),
38+ send(
39+ &app,
40+ "PATCH",
41+ &uri,
42+ Some(&who),
43+ Some(json!({ "description": "new description" })),
44+ ),
45+ );
46+ assert_eq!(a.status, StatusCode::OK, "round {round} name patch");
47+ assert_eq!(b.status, StatusCode::OK, "round {round} description patch");
48+
49+ let after = send(&app, "GET", &uri, Some(&who), None).await.body;
50+ assert_eq!(after["name"], "new name", "round {round}: name reverted");
51+ assert_eq!(
52+ after["description"], "new description",
53+ "round {round}: description reverted"
54+ );
55+ }
56+}
57+
58+/// Omitting a field keeps it, and a PATCH still cannot land a value a POST
59+/// would reject.
60+#[tokio::test]
61+async fn omitted_keeps_and_validation_still_bites() {
62+ let (app, db) = app_and_db().await;
63+ let who = login_as(&app, &db, "veli", "teacher").await;
64+ let course = create_course(&app, &who, "physics").await;
65+ let subject = create_subject(&app, &who, &course, "kept name").await;
66+ let uri = format!("/subjects/{subject}");
67+
68+ let kept = send(
69+ &app,
70+ "PATCH",
71+ &uri,
72+ Some(&who),
73+ Some(json!({ "description": "only this" })),
74+ )
75+ .await;
76+ assert_eq!(kept.status, StatusCode::OK);
77+ assert_eq!(kept.body["name"], "kept name", "omitted name kept");
78+ assert_eq!(kept.body["description"], "only this");
79+
80+ // An empty PATCH writes nothing at all and reads the row back unchanged.
81+ let empty = send(&app, "PATCH", &uri, Some(&who), Some(json!({}))).await;
82+ assert_eq!(empty.status, StatusCode::OK);
83+ assert_eq!(empty.body["name"], "kept name");
84+ assert_eq!(empty.body["description"], "only this");
85+
86+ // A blank name is required at create, so it stays refused at patch.
87+ let bad = send(&app, "PATCH", &uri, Some(&who), Some(json!({ "name": "" }))).await;
88+ assert_eq!(bad.status, StatusCode::BAD_REQUEST, "blank name refused");
89+}
tests/partial_patch_users.rsadded+160 -0
@@ -0,0 +1,160 @@
1+//! Two concurrent partial PATCHes on the same user row must not revert each
2+//! other. The profile and preference handlers merged the request over their own
3+//! stale read and wrote every column, so a name edit racing a surname edit lost
4+//! one of them — both 200.
5+
6+mod common;
7+
8+use axum::http::StatusCode;
9+use common::*;
10+use serde_json::json;
11+
12+#[tokio::test]
13+async fn concurrent_profile_patches_keep_both_fields() {
14+ let (app, db) = app_and_db().await;
15+ let who = login_as(&app, &db, "ali", "student").await;
16+
17+ for round in 0..20 {
18+ let name = format!("name{round}");
19+ let surname = format!("surname{round}");
20+ let (a, b) = tokio::join!(
21+ send(
22+ &app,
23+ "PATCH",
24+ "/users/me",
25+ Some(&who),
26+ Some(json!({ "name": name })),
27+ ),
28+ send(
29+ &app,
30+ "PATCH",
31+ "/users/me",
32+ Some(&who),
33+ Some(json!({ "surname": surname })),
34+ ),
35+ );
36+ assert_eq!(a.status, StatusCode::OK, "round {round} name patch");
37+ assert_eq!(b.status, StatusCode::OK, "round {round} surname patch");
38+
39+ // `/auth/me` is the self-read (there is no `GET /users/me`).
40+ let after = send(&app, "GET", "/auth/me", Some(&who), None).await.body;
41+ assert_eq!(after["name"], name, "round {round}: name reverted");
42+ assert_eq!(after["surname"], surname, "round {round}: surname reverted");
43+ }
44+}
45+
46+#[tokio::test]
47+async fn concurrent_preference_patches_keep_both_fields() {
48+ let (app, db) = app_and_db().await;
49+ let who = login_as(&app, &db, "veli", "student").await;
50+
51+ for round in 0..20 {
52+ // Alternate both values so a revert to the previous round is visible.
53+ let (theme, language) = if round % 2 == 0 {
54+ ("dark", "tr")
55+ } else {
56+ ("light", "en")
57+ };
58+ let (a, b) = tokio::join!(
59+ send(
60+ &app,
61+ "PATCH",
62+ "/users/me/preferences",
63+ Some(&who),
64+ Some(json!({ "theme": theme })),
65+ ),
66+ send(
67+ &app,
68+ "PATCH",
69+ "/users/me/preferences",
70+ Some(&who),
71+ Some(json!({ "language": language })),
72+ ),
73+ );
74+ assert_eq!(a.status, StatusCode::OK, "round {round} theme patch");
75+ assert_eq!(b.status, StatusCode::OK, "round {round} language patch");
76+
77+ let after = send(&app, "GET", "/auth/me", Some(&who), None).await.body;
78+ assert_eq!(after["theme"], theme, "round {round}: theme reverted");
79+ assert_eq!(
80+ after["language"], language,
81+ "round {round}: language reverted"
82+ );
83+ }
84+}
85+
86+/// The field semantics are unchanged: omitted (and `null`) keeps, `""` clears,
87+/// and anything else runs through the same validators a create would use.
88+#[tokio::test]
89+async fn omitted_keeps_empty_clears_and_validation_still_bites() {
90+ let (app, db) = app_and_db().await;
91+ let who = login_as(&app, &db, "ayse", "student").await;
92+
93+ let set = send(
94+ &app,
95+ "PATCH",
96+ "/users/me",
97+ Some(&who),
98+ Some(json!({ "name": "Ada", "surname": "Lovelace", "email": "ada@example.com" })),
99+ )
100+ .await;
101+ assert_eq!(set.status, StatusCode::OK, "{}", set.body);
102+
103+ // Omitted keeps, and an explicit null keeps too (the documented contract).
104+ let kept = send(
105+ &app,
106+ "PATCH",
107+ "/users/me",
108+ Some(&who),
109+ Some(json!({ "surname": null })),
110+ )
111+ .await;
112+ assert_eq!(kept.status, StatusCode::OK);
113+ assert_eq!(kept.body["name"], "Ada", "omitted name kept");
114+ assert_eq!(kept.body["surname"], "Lovelace", "null keeps surname");
115+ assert_eq!(kept.body["email"], "ada@example.com");
116+
117+ // An empty request writes nothing at all.
118+ let empty = send(&app, "PATCH", "/users/me", Some(&who), Some(json!({}))).await;
119+ assert_eq!(empty.status, StatusCode::OK);
120+ assert_eq!(empty.body["name"], "Ada");
121+ assert_eq!(empty.body["email"], "ada@example.com");
122+
123+ // `""` clears — and only the field it was sent for.
124+ let cleared = send(
125+ &app,
126+ "PATCH",
127+ "/users/me",
128+ Some(&who),
129+ Some(json!({ "email": "" })),
130+ )
131+ .await;
132+ assert_eq!(cleared.status, StatusCode::OK);
133+ assert_eq!(cleared.body["email"], json!(null), "email not cleared");
134+ assert_eq!(cleared.body["name"], "Ada", "name lost to the clear");
135+
136+ // A malformed value is refused, exactly as at create.
137+ let bad = send(
138+ &app,
139+ "PATCH",
140+ "/users/me",
141+ Some(&who),
142+ Some(json!({ "email": "not-an-email" })),
143+ )
144+ .await;
145+ assert_eq!(bad.status, StatusCode::BAD_REQUEST, "bad email refused");
146+
147+ let bad_theme = send(
148+ &app,
149+ "PATCH",
150+ "/users/me/preferences",
151+ Some(&who),
152+ Some(json!({ "theme": "chartreuse" })),
153+ )
154+ .await;
155+ assert_eq!(
156+ bad_theme.status,
157+ StatusCode::BAD_REQUEST,
158+ "bad theme refused"
159+ );
160+}