From 5ff42c5aa60b45bf3f15e5b371da5bf166c6634a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 14 Sep 2026 16:39:32 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=9D=20docs:=20drop=20stale=20process-l?= =?UTF-8?q?ock=20comments?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PRESENCE_LOCK and the other named process locks are gone. Comments and README still talked as if they serialized writes. --- README.md | 29 +++++++++++++-------------- src/db/course.rs | 4 ++-- src/service/settings.rs | 10 ++++----- src/state.rs | 8 ++++---- tests/integration.rs | 19 +++++++++--------- tests/partial_patch_bank_questions.rs | 4 ++-- tests/regress_appointments.rs | 2 +- tests/regress_bank_images.rs | 8 ++++---- tests/regress_course_delete.rs | 26 +++++++++--------------- tests/regress_exam_delete.rs | 13 ++++++------ tests/regress_homework_orphans.rs | 25 ++++++++++++----------- tests/regress_role_sweep.rs | 7 ++++--- 12 files changed, 74 insertions(+), 81 deletions(-) diff --git a/README.md b/README.md index 2706be8..00a6ab3 100644 --- a/README.md +++ b/README.md @@ -3678,14 +3678,12 @@ and pumps it while the delete runs would otherwise leave rows tagged with a blueprint that no longer exists, and since the grade label *is* the record id, nothing could ever reach them again. The pump carries the other half of that — an attach whose blueprint was deleted mid-run writes nothing and is reported as -`blueprint_deleted`. Those two narrow the window rather than close it — a pump -that read the template alive can still commit its link after the sweep has run, -since a read of one record and a write of another are not serialized against -each other — so the delete and each individual attach are also serialized in -process: the delete holds a write lease across its compare-and-set and its -sweep, and a pump takes a read lease one course at a time, so a delete never -waits behind a whole grade. The backend runs as a single process by decision, which -is what makes an in-process lock the complete answer. The delete is also a +`blueprint_deleted`. The attach's in-transaction claim is a `FOR KEY SHARE` +row lock on `class_blueprint` — the one strength a `DELETE` of the row +cannot take — so a sourced attach that started first holds the row and the +delete waits behind it; an attach starting after the delete finds no row +and writes nothing. A pump takes that lock one course at a time, so a +delete never waits behind a whole grade. The delete is also a compare-and-set on the list the call read: a `409` means somebody edited the template in between, and nothing was written — though a template deleted and recreated at the same grade with the same list satisfies that comparison, which @@ -4679,11 +4677,12 @@ database itself decides the winner. Three tiers: in flight lets that one write through. Damage: one write on a just-archived term; nothing corrupts, and every later write is refused. -One in-process lock remains, and it is a *second* line, never the guarantee: -`PRESENCE_LOCK` guards the exam-room presence map (in-process socket state; -there is no row to conditional-write). The other two are gone with the old -store: `CLAIM_LOCK` tamed a retry loop that `tx_with_retry` now owns, and -what `APPOINTMENT_LOCK` serialized is three database guarantees — the seat +No process-wide domain lock remains. Exam-room presence is an in-process +map (`ExamPresence` in `src/state.rs`; the mutex never spans an await). +There is no row to conditional-write for socket counts; the paired +`left_at` stamp is an idempotent statement on the sitting. `CLAIM_LOCK` +tamed a retry loop that `tx_with_retry` now owns, and what +`APPOINTMENT_LOCK` serialized is three database guarantees — the seat claim's one-statement write, the publish-overlap exclusion constraint, and the serializable approval. @@ -4850,8 +4849,8 @@ src/ recurring publish is expanded into rows sharing a series id) appointment.rs AppointmentId · AppointmentStatus · AppointmentReason · Appointment (a booking on a slot; occupancy is the slot's - stored `occupied` cap-1 counter, overlap is derived under - APPOINTMENT_LOCK) + seat claim, publish overlap is the exclusion constraint, + approval overlap is SERIALIZABLE) pomodoro.rs PomodoroSessionId · PomodoroSession (student focus log) pool_question.rs PoolQuestionId · PoolQuestionTitle · PoolQuestionBody · PoolQuestion (student-asked question; teacher-approved into diff --git a/src/db/course.rs b/src/db/course.rs index f0500af..b13a57d 100644 --- a/src/db/course.rs +++ b/src/db/course.rs @@ -261,8 +261,8 @@ pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result, } /// Field-scoped: 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) — so a field the request omitted +/// and this write (the term it links is guarded by its own refcount write, +/// and the assign path takes no lock at all) — so a field the request omitted /// (`None`) is not written at all. Sending the snapshot's value back /// instead would revert a concurrent edit of that field; scoping the `SET` /// alone does not stop that, the values have to come from the request. diff --git a/src/service/settings.rs b/src/service/settings.rs index b4b6236..5b11c94 100644 --- a/src/service/settings.rs +++ b/src/service/settings.rs @@ -557,11 +557,11 @@ mod tests { /// the list the store actually holds. /// /// One of the two decides the removal, retires the kind and saves; the - /// other cannot even see the old list, because the whole snapshot-retire- - /// save pair is serialized (`SETTINGS_LOCK`). Interleaved, the second - /// attempt would be told "already retired", record no undo, win the - /// compare-and-set, and leave the first attempt un-retiring the kind it had - /// legitimately removed — off the list and gradable. + /// other cannot even see the old list, because retirement and save share + /// one transaction. Interleaved, the second attempt would be told "already + /// retired", record no undo, win the compare-and-set, and leave the first + /// attempt un-retiring the kind it had legitimately removed — off the list + /// and gradable. #[tokio::test] async fn two_edits_dropping_the_same_kind_leave_it_retired() { let (db, _leases) = init_test_db().await; diff --git a/src/state.rs b/src/state.rs index f1720f9..93cfd1e 100644 --- a/src/state.rs +++ b/src/state.rs @@ -68,10 +68,10 @@ pub fn scoped_key(slug: &Slug, key: &str) -> String { /// closing one of two tabs never counts as having left the exam. /// /// The inner mutex only guards the map (never held across an await — keep it -/// that way). Each count transition and its matching `left_at` DB write are -/// serialized as one critical section by the exam room's `PRESENCE_LOCK` -/// (see `web::exam_ws`), so "clear on join" and "stamp on last-out" stay -/// atomic with the counts they depend on. +/// that way). The matching `left_at` writes are idempotent single statements +/// against the sitting's own row (see `web::exam_ws`): join clears the marker; +/// last socket out stamps it only while `left_at IS NULL`. Concurrent last-outs +/// are harmless — only the first stamp lands. #[derive(Clone, Default)] pub struct ExamPresence(Arc>>); diff --git a/tests/integration.rs b/tests/integration.rs index 601df8b..6ced6ac 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -21343,11 +21343,11 @@ async fn refreshing_a_question_recopies_its_template() { } /// 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. +/// awaits a term lookup 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::db::course; @@ -22235,11 +22235,10 @@ async fn concurrent_duplicate_menu_publishes_conflict_not_500() { assert_eq!(common::total(&res.body), 1, "and exactly one menu exists"); } -/// Two appends of one ledger id must both succeed: the id is the idempotence -/// key, so the loser reads back the winner's line instead of surfacing the -/// duplicate-key error as a 500. Driven at the domain level on purpose — every -/// HTTP path into the ledger runs under `MENU_LOCK`, which serializes the two -/// writers before they can ever collide. +/// Two appends of one ledger id must both succeed: the id is the store's +/// idempotence key, so the loser reads back the winner's line instead of +/// surfacing the duplicate-key error as a 500. Driven at the domain level +/// because that is the collision, not HTTP. #[tokio::test] async fn concurrent_ledger_appends_of_one_id_write_one_line_not_a_500() { use hezarfen_backend::db::meal_ledger; diff --git a/tests/partial_patch_bank_questions.rs b/tests/partial_patch_bank_questions.rs index 9c031ed..a17bca3 100644 --- a/tests/partial_patch_bank_questions.rs +++ b/tests/partial_patch_bank_questions.rs @@ -1,8 +1,8 @@ //! A bank-template PATCH is a read-modify-write: the kind/choices/correct trio //! has to be re-submitted as a unit (choices carry their ids, and their //! pictures hang off those ids), so the row read, the merge and the write are -//! held together under the *writer* lease of `BANK_LOCK`. Without that, two -//! concurrent partial PATCHes revert each other. +//! a compare-and-set on the stored snapshot. Without that, two concurrent +//! partial PATCHes revert each other. mod common; diff --git a/tests/regress_appointments.rs b/tests/regress_appointments.rs index 83519a3..a99cf11 100644 --- a/tests/regress_appointments.rs +++ b/tests/regress_appointments.rs @@ -333,6 +333,6 @@ async fn an_answer_resolves_its_own_prompt_across_an_interleave() { } // --------------------------------------------------------------------------- -// The store property behind `APPOINTMENT_LOCK`. +// The store property that replaced `APPOINTMENT_LOCK`. // --------------------------------------------------------------------------- diff --git a/tests/regress_bank_images.rs b/tests/regress_bank_images.rs index 2c3f7fc..56548ea 100644 --- a/tests/regress_bank_images.rs +++ b/tests/regress_bank_images.rs @@ -17,10 +17,10 @@ //! //! These two need no server, so they run in CI by default. The *raced* halves //! of the same three holes live beside the code they test, in -//! `bank_question_image`'s own test module, where `init_test_server` and -//! `RACE_LOCK` are in reach: the store's conflict detection is their subject, -//! and re-spelling the real bootstrap out here would be a hand-kept copy that -//! drifts silently the first time migration or router construction changes. +//! `bank_question_image`'s own test module, where `init_test_server` is in +//! reach: the store's conflict detection is their subject, and re-spelling +//! the real bootstrap out here would be a hand-kept copy that drifts silently +//! the first time migration or router construction changes. mod common; diff --git a/tests/regress_course_delete.rs b/tests/regress_course_delete.rs index 62a4d04..ce23f33 100644 --- a/tests/regress_course_delete.rs +++ b/tests/regress_course_delete.rs @@ -1,24 +1,16 @@ //! A course delete must take every attempt under it with it — the same hole -//! `regress_exam_delete` pins one level down, and the same lease. +//! `regress_exam_delete` pins one level down. //! //! `delete_course` cascades the course's exams *and their attempts*, and an //! attempt is still the one exam child whose write cannot collide with that -//! sweep: its create rides `cap::claim_and_create` against the *student's* row, -//! which this cascade never touches. So the sweep and a start in flight can -//! both commit, and only `EXAM_LOCK.write()` keeps them apart. +//! sweep on a key: its create rides `cap::claim_and_create` against the +//! *student's* row, which this cascade never touches. The exam row lock +//! (`FOR UPDATE` on start, `DELETE` waiting behind it) is what keeps the +//! sweep and a start from both committing. //! -//! **Its own test binary on purpose.** `EXAM_LOCK` is process-wide, so this -//! test and `regress_exam_delete`'s share it across two unrelated databases -//! when they run in one binary: the neighbour holds the writer lease through -//! its own one-second window, the start here queues behind it, and the timeline -//! this test is built on stops holding. It was mutation-proven red alone and -//! green — on the *broken* code — beside that neighbour. Anything else added -//! here must not take `EXAM_LOCK` either. -//! -//! Which is why the two cascade tests below fire the delete at -//! [`Course::delete`] rather than at `DELETE /courses/{id}`: the handler takes -//! the writer lease, the defects they pin live in that transaction's SQL, and -//! neither one needs a race to show. +//! The two cascade tests below fire the delete at [`Course::delete`] rather +//! than at `DELETE /courses/{id}`: the defects they pin live in that +//! transaction's SQL, and neither one needs a race to show. mod common; @@ -33,7 +25,7 @@ use hezarfen_backend::domain::course::CourseId; use hezarfen_backend::domain::exam::ExamId; use serde_json::json; -/// Delete `course` the way the handler would, minus its `EXAM_LOCK` lease. +/// Delete `course` at the store, bypassing HTTP. async fn drop_course(db: &hezarfen_backend::database::Database, course: &str) { let row = course::read(db, &CourseId::from_key(course)) .await diff --git a/tests/regress_exam_delete.rs b/tests/regress_exam_delete.rs index 771fe6f..c9966ae 100644 --- a/tests/regress_exam_delete.rs +++ b/tests/regress_exam_delete.rs @@ -6,13 +6,14 @@ //! contends on a single key and the store aborts a side. An attempt cannot do //! that: its create rides `cap::claim_and_create` against the *student's* row //! (`exam_sat_total`), which this delete never touches, so nothing collides and -//! the freeze/existence gate is a plain read. `start_attempt` has always held -//! `EXAM_LOCK.write()` from its exam read through the insert; `delete_exam` -//! held nothing at all, and that asymmetry is what let a sitting start inside -//! the delete window and outlive the exam. +//! the freeze/existence gate is a plain read. The start path now takes +//! `FOR UPDATE` on the exam row from the exam read through the insert, so a +//! delete waits behind an in-flight start and a start after the delete finds +//! no row. The old hole was that `start_attempt` held a process +//! `EXAM_LOCK.write()` while `delete_exam` held nothing. //! -//! This suite drives the real handlers, because the lease being tested lives in -//! the web layer and no domain call can observe it. +//! This suite drives the real handlers: the gates live on the HTTP path as +//! well as the store. mod common; diff --git a/tests/regress_homework_orphans.rs b/tests/regress_homework_orphans.rs index 4946f6e..a19065f 100644 --- a/tests/regress_homework_orphans.rs +++ b/tests/regress_homework_orphans.rs @@ -83,9 +83,9 @@ async fn course_with_student( (course, subject, student, student_id) } -/// The upload streams its body *before* it takes `HOMEWORK_LOCK`, and the -/// homework snapshot it acts on was read before that stream — so a delete -/// (which takes and releases the write lease inside that window) leaves the +/// The upload used to stream its body *before* it took `HOMEWORK_LOCK`, and +/// the homework snapshot it acted on was read before that stream — so a delete +/// (which took and released the write lease inside that window) left the /// handler holding a homework that is gone. It then auto-created a submission /// under it, credited both badge counters, wrote a blob and a file row, and /// answered `201`. Every route to any of that goes through the vanished @@ -440,12 +440,12 @@ async fn a_grade_under_a_vanished_homework_is_refused() { assert_eq!(over_http.status, StatusCode::NOT_FOUND); } -/// `delete_course` took `EXAM_LOCK` and nothing else, while its cascade sweeps -/// the course's homework, submissions, files and results. Grading holds -/// `HOMEWORK_LOCK.write()` across a transaction that only *reads* the homework, -/// and the store conflict-checks write sets rather than read sets — so the -/// sweep ran on a snapshot without the grade and both committed: an orphan -/// `homework_result` under a vanished homework, readable ever after at +/// `delete_course` used to take `EXAM_LOCK` and nothing else, while its cascade +/// swept the course's homework, submissions, files and results. Grading used +/// to hold `HOMEWORK_LOCK.write()` across a transaction that only *read* the +/// homework, and the store conflict-checked write sets rather than read sets — +/// so the sweep ran on a snapshot without the grade and both committed: an +/// orphan `homework_result` under a vanished homework, readable ever after at /// `GET /homework/{id}/result`, which has no existence check of its own. /// /// The window is the grade's, not the delete's: a course delete is refused @@ -648,9 +648,10 @@ async fn a_student_sees_only_themselves_in_an_assigned_subset() { /// A file add and a file delete on one submission write the same row — the /// upload claims its seat on it, the delete re-stamps it — and both handlers -/// hold only `HOMEWORK_LOCK.read()`, so they contend by design. The delete sent -/// its cascade through a plain `db.query`, unlike every sibling in the module, -/// so a lost round came back as a 500 on a request that had written nothing. +/// used to hold only `HOMEWORK_LOCK.read()`, so they contended by design. The +/// delete sent its cascade through a plain `db.query`, unlike every sibling in +/// the module, so a lost round came back as a 500 on a request that had written +/// nothing. /// /// The window is the *delete's* own — the retry-less side has to be the one /// holding a stale write when the other commits, or nothing it does can be diff --git a/tests/regress_role_sweep.rs b/tests/regress_role_sweep.rs index 1ff610b..8b4e130 100644 --- a/tests/regress_role_sweep.rs +++ b/tests/regress_role_sweep.rs @@ -118,9 +118,10 @@ async fn hold_the_sweep(table: &str, db: &Database) { /// transaction open for seconds against the shared Postgres server, so run in /// parallel they push each other clean out of their windows: measured, all /// three then pass on code with the claim removed, while serialized all three -/// fail it. Same trap as the process-wide `EXAM_LOCK` note in -/// `regress_course_delete`, and the guard is handed back into a binding that -/// lives for the whole test the way `init_test_server`'s does. +/// fail it. Same trap as two race suites sharing one process-wide lock across +/// unrelated databases: the neighbour holds the lease through its window, this +/// start queues, and the timeline stops holding. The guard is handed back into +/// a binding that lives for the whole test the way `init_test_server`'s does. static ONE_WINDOW_AT_A_TIME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); /// Start the demotion and wait until it is *inside* the held window, then hand