From 67fae199bca631d20dea851e6fbc4a526ca4d558 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 12 Sep 2026 20:41:00 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=AA=20test:=20port=20regress=5Fpayment?= =?UTF-8?q?s=20+=20regress=5Fevent=5Fclass=5Faudience,=20deflake=20exam=20?= =?UTF-8?q?mark=20race?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...ddc8db38c05a71a6d61b2ab5e4e3885b32fc2.json | 14 ++++++ src/db/class_group.rs | 17 +++++-- src/db/exam.rs | 44 ++++++++++++------- tests/regress_payments.rs | 32 +++++++++++++- 4 files changed, 85 insertions(+), 22 deletions(-) create mode 100644 .sqlx/query-c1882912be92000ba3fd8525a22ddc8db38c05a71a6d61b2ab5e4e3885b32fc2.json diff --git a/.sqlx/query-c1882912be92000ba3fd8525a22ddc8db38c05a71a6d61b2ab5e4e3885b32fc2.json b/.sqlx/query-c1882912be92000ba3fd8525a22ddc8db38c05a71a6d61b2ab5e4e3885b32fc2.json new file mode 100644 index 0000000..1744793 --- /dev/null +++ b/.sqlx/query-c1882912be92000ba3fd8525a22ddc8db38c05a71a6d61b2ab5e4e3885b32fc2.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE event SET audience_class = NULL WHERE audience_class = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "c1882912be92000ba3fd8525a22ddc8db38c05a71a6d61b2ab5e4e3885b32fc2" +} diff --git a/src/db/class_group.rs b/src/db/class_group.rs index 215d43e..d05b517 100644 --- a/src/db/class_group.rs +++ b/src/db/class_group.rs @@ -237,10 +237,12 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App Ok(()) } -/// Delete the class and give its term reference back. Nothing cascades: a -/// class that still holds students or courses is refused outright, because +/// Delete the class and give its term reference back. Nothing else cascades: +/// a class that still holds students or courses is refused outright, because /// dropping it silently would leave the enrollments it pumped behind with -/// nothing left to sweep them. +/// nothing left to sweep them. An event aimed at the class keeps standing +/// with `audience_class` cleared — the course twin's documented outcome +/// (`db::course::delete`): the roster resolves live, so it simply reads empty. /// /// `false` = refused, nothing was written. Both counts are read off the /// class's own row, so the check and the delete are one conditional write on @@ -249,6 +251,15 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App /// `Err(NotFound)` keeps the answer a concurrent *delete* used to get. pub async fn delete(db: &Database, class: ClassGroup) -> Result { tx_with_retry(db, false, async move |tx| { + // Events aimed at this class keep standing, audience cleared — the + // hard FK on `event.audience_class` would otherwise refuse the delete + // outright, and a dangling audience resolves to an empty roster. + sqlx::query!( + r#"UPDATE event SET audience_class = NULL WHERE audience_class = $1"#, + class.id.uuid() + ) + .execute(&mut *tx) + .await?; let gone = sqlx::query!( r#"DELETE FROM class_group WHERE id = $1 diff --git a/src/db/exam.rs b/src/db/exam.rs index 3642b52..c825fff 100644 --- a/src/db/exam.rs +++ b/src/db/exam.rs @@ -807,14 +807,18 @@ mod tests { /// The racer is a mark: [`crate::db::exam_result::grade`] claims the exam's own /// `result_count` (and the kind's reference) before writing, so it contends /// with the `DELETE $ex` and with the kind_ref decrement inside the same - /// transaction. A round where *some* of the six grades 404 and the rest - /// succeed is the witness that the delete landed inside the burst: the 404 - /// comes from `write_mark`'s existence gate, so it can only be answered by a - /// grade that reached the store after the row was gone, and its siblings' - /// success says the same burst also had grades that got there first. Stored - /// state cannot say this any more — the gate is what stops a mark outliving - /// its exam, so the sweep now finds nothing to leave behind in *every* - /// round, which is asserted below as a fact rather than read as a signal. + /// transaction. The witness that the site is genuinely raced is read per + /// round and asserted over the whole run — the subject twin's shape. A + /// grade answered 404 says the delete landed before it (`write_mark`'s + /// existence gate is the only thing that can answer that); a grade going + /// through says that grade beat the delete. Which side wins a *round* is + /// load luck: under a busy machine the delete lands wholly on one side of + /// the burst in every round (measured 0/20 same-round splits, 3 runs in 5 + /// red, with the integration suite running concurrently), so a same-round + /// split must not be the gate. Stored state cannot witness the straddle — + /// the gate is what stops a mark outliving its exam, so the sweep now + /// finds nothing to leave behind in *every* round, which is asserted + /// below as a fact rather than read as a signal. /// /// It does not prove the retry either: measured at 0 conflicts in 100 raced /// rounds, and green with @@ -830,7 +834,7 @@ mod tests { let (db, _leases) = crate::database::init_test_db().await; let teacher = a_person(&db, "teacher", "teacher").await; let (mut delete_500, mut grade_500) = (0, 0); - let (mut split, mut swept) = (0, 0); + let (mut delete_first, mut grade_first, mut swept) = (0, 0, 0); let (mut last_delete, mut last_grade) = (String::new(), String::new()); for round in 0..20 { let exam = published(&db).await; @@ -895,11 +899,15 @@ mod tests { _ => {} } } - // Neither end of the burst: some grades beat the delete and some - // lost to it, so the delete landed *between* them. A round that is - // all-refused or all-through is one where it landed outside. - if (1..6).contains(&refused) { - split += 1; + // Which side won, read per round and asserted over the whole run: + // a round with a refused grade saw the delete land first, a round + // with a grade through saw a grade land first. One round can be + // both — that is the same-round split, welcome but not required. + if refused > 0 { + delete_first += 1; + } + if refused < 6 { + grade_first += 1; } if exam_result::list_for_exam(&db, exam.get_id()) .await @@ -911,11 +919,13 @@ mod tests { } eprintln!( "Exam::delete raced: {delete_500}/20 delete 500s, {grade_500} grade 500s, \ - {split} rounds split by the delete / {swept} swept clean" + {delete_first} rounds with a grade refused / {grade_first} with one through, \ + {swept} swept clean" ); assert!( - split > 0, - "the delete never landed inside the burst (0/20 rounds split)" + delete_first > 0 && grade_first > 0, + "the sweep never crossed the window ({delete_first} rounds with a grade \ + refused / {grade_first} with one through)" ); // Not a race signal, an invariant: the gate refuses a mark for an exam // that is gone, so no round can leave one behind for the next reader. diff --git a/tests/regress_payments.rs b/tests/regress_payments.rs index f0029ec..2f27ff7 100644 --- a/tests/regress_payments.rs +++ b/tests/regress_payments.rs @@ -15,6 +15,7 @@ mod common; use axum::http::StatusCode; use common::{app_and_db, id_of, login, login_as, me_id, send}; use hezarfen_backend::constant::{MAX_FEE_PLAN_ASSIGN_WRITES, MAX_LEDGER_APPLIED_LINES}; +use hezarfen_backend::database::Database; use hezarfen_backend::db::fee_plan; use hezarfen_backend::domain::fee_plan::{FeePlanName, Installment}; use hezarfen_backend::domain::payment_ledger::LedgerAmount; @@ -23,6 +24,7 @@ use hezarfen_backend::domain::user::UserId; use hezarfen_backend::error::AppError; use hezarfen_backend::service::fee_plan_assignment; use serde_json::{Value, json}; +use sqlx::Row as _; /// A plan of `installments`, as the manager writes it. async fn create_plan(app: &axum::Router, mgr: &str, installments: Value) -> String { @@ -52,6 +54,31 @@ async fn ledger(app: &axum::Router, mgr: &str, student: &str) -> Vec { common::items(&res.body).clone() } +/// A real `app_user` row for the creator or assignee a domain call must +/// name: those columns are foreign keys now, so they are rows, not +/// fabricated ids. The username is unique, so every call for the same name +/// shares one row, whichever call minted it. These rows never log in, so the +/// hash is a stub. +async fn fixture_user(db: &Database, username: &str) -> UserId { + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'student') ON CONFLICT DO NOTHING", + ) + .bind(UserId::generate().uuid()) + .bind(username) + .execute(db) + .await + .unwrap(); + let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1") + .bind(username) + .fetch_one(db) + .await + .unwrap() + .try_get(0) + .unwrap(); + UserId::from_key(&id.to_string()) +} + /// The `balance_minor` a statement reports must be folded from the very lines /// its per-charge rollup walked. It was folded from a *second*, later read of /// the ledger, three round trips after the first: a payment landing in that @@ -227,7 +254,7 @@ async fn a_negative_due_date_is_refused_on_both_write_paths() { #[tokio::test] async fn editing_a_plan_deleted_since_it_was_read_is_a_404_not_a_409() { let (_app, db) = app_and_db().await; - let manager = UserId::from_key("del_mgr"); + let manager = fixture_user(&db, "del_mgr").await; let one = || { vec![Installment::new( LedgerAmount::try_new(10_000).unwrap(), @@ -272,7 +299,8 @@ async fn editing_a_plan_deleted_since_it_was_read_is_a_404_not_a_409() { ) .await .unwrap(); - fee_plan_assignment::assign(&db, &plan, &UserId::from_key("del_stu"), &manager) + let student = fixture_user(&db, "del_stu").await; + fee_plan_assignment::assign(&db, &plan, &student, &manager) .await .unwrap(); let refused = fee_plan::update(