forge
Explore
Log in

Don't you dare go Hollow

Port regress_payments + regress_event_class_audience, deflake exam mark race

Browse files at this commit

67fae199bca631d20dea851e6fbc4a526ca4d558Ahmet Kaan GümüşParent: 70ccd66
  • test
    • port regress_payments + regress_event_class_audience, deflake exam mark race
Show full message
🧪 test: port regress_payments + regress_event_class_audience, deflake exam mark race
.sqlx/query-c1882912be92000ba3fd8525a22ddc8db38c05a71a6d61b2ab5e4e3885b32fc2.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE event SET audience_class = NULL WHERE audience_class = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "c1882912be92000ba3fd8525a22ddc8db38c05a71a6d61b2ab5e4e3885b32fc2"
14+}
src/db/class_group.rsmodified+14 -3
@@ -237,10 +237,12 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App
237237 Ok(())
238238 }
239239
240-/// Delete the class and give its term reference back. Nothing cascades: a
241-/// class that still holds students or courses is refused outright, because
240+/// Delete the class and give its term reference back. Nothing else cascades:
241+/// a class that still holds students or courses is refused outright, because
242242 /// dropping it silently would leave the enrollments it pumped behind with
243-/// nothing left to sweep them.
243+/// nothing left to sweep them. An event aimed at the class keeps standing
244+/// with `audience_class` cleared — the course twin's documented outcome
245+/// (`db::course::delete`): the roster resolves live, so it simply reads empty.
244246 ///
245247 /// `false` = refused, nothing was written. Both counts are read off the
246248 /// 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
249251 /// `Err(NotFound)` keeps the answer a concurrent *delete* used to get.
250252 pub async fn delete(db: &Database, class: ClassGroup) -> Result<bool, AppError> {
251253 tx_with_retry(db, false, async move |tx| {
254+ // Events aimed at this class keep standing, audience cleared — the
255+ // hard FK on `event.audience_class` would otherwise refuse the delete
256+ // outright, and a dangling audience resolves to an empty roster.
257+ sqlx::query!(
258+ r#"UPDATE event SET audience_class = NULL WHERE audience_class = $1"#,
259+ class.id.uuid()
260+ )
261+ .execute(&mut *tx)
262+ .await?;
252263 let gone = sqlx::query!(
253264 r#"DELETE FROM class_group
254265 WHERE id = $1
src/db/exam.rsmodified+27 -17
@@ -807,14 +807,18 @@ mod tests {
807807 /// The racer is a mark: [`crate::db::exam_result::grade`] claims the exam's own
808808 /// `result_count` (and the kind's reference) before writing, so it contends
809809 /// with the `DELETE $ex` and with the kind_ref decrement inside the same
810- /// transaction. A round where *some* of the six grades 404 and the rest
811- /// succeed is the witness that the delete landed inside the burst: the 404
812- /// comes from `write_mark`'s existence gate, so it can only be answered by a
813- /// grade that reached the store after the row was gone, and its siblings'
814- /// success says the same burst also had grades that got there first. Stored
815- /// state cannot say this any more — the gate is what stops a mark outliving
816- /// its exam, so the sweep now finds nothing to leave behind in *every*
817- /// round, which is asserted below as a fact rather than read as a signal.
810+ /// transaction. The witness that the site is genuinely raced is read per
811+ /// round and asserted over the whole run — the subject twin's shape. A
812+ /// grade answered 404 says the delete landed before it (`write_mark`'s
813+ /// existence gate is the only thing that can answer that); a grade going
814+ /// through says that grade beat the delete. Which side wins a *round* is
815+ /// load luck: under a busy machine the delete lands wholly on one side of
816+ /// the burst in every round (measured 0/20 same-round splits, 3 runs in 5
817+ /// red, with the integration suite running concurrently), so a same-round
818+ /// split must not be the gate. Stored state cannot witness the straddle —
819+ /// the gate is what stops a mark outliving its exam, so the sweep now
820+ /// finds nothing to leave behind in *every* round, which is asserted
821+ /// below as a fact rather than read as a signal.
818822 ///
819823 /// It does not prove the retry either: measured at 0 conflicts in 100 raced
820824 /// rounds, and green with
@@ -830,7 +834,7 @@ mod tests {
830834 let (db, _leases) = crate::database::init_test_db().await;
831835 let teacher = a_person(&db, "teacher", "teacher").await;
832836 let (mut delete_500, mut grade_500) = (0, 0);
833- let (mut split, mut swept) = (0, 0);
837+ let (mut delete_first, mut grade_first, mut swept) = (0, 0, 0);
834838 let (mut last_delete, mut last_grade) = (String::new(), String::new());
835839 for round in 0..20 {
836840 let exam = published(&db).await;
@@ -895,11 +899,15 @@ mod tests {
895899 _ => {}
896900 }
897901 }
898- // Neither end of the burst: some grades beat the delete and some
899- // lost to it, so the delete landed *between* them. A round that is
900- // all-refused or all-through is one where it landed outside.
901- if (1..6).contains(&refused) {
902- split += 1;
902+ // Which side won, read per round and asserted over the whole run:
903+ // a round with a refused grade saw the delete land first, a round
904+ // with a grade through saw a grade land first. One round can be
905+ // both — that is the same-round split, welcome but not required.
906+ if refused > 0 {
907+ delete_first += 1;
908+ }
909+ if refused < 6 {
910+ grade_first += 1;
903911 }
904912 if exam_result::list_for_exam(&db, exam.get_id())
905913 .await
@@ -911,11 +919,13 @@ mod tests {
911919 }
912920 eprintln!(
913921 "Exam::delete raced: {delete_500}/20 delete 500s, {grade_500} grade 500s, \
914- {split} rounds split by the delete / {swept} swept clean"
922+ {delete_first} rounds with a grade refused / {grade_first} with one through, \
923+ {swept} swept clean"
915924 );
916925 assert!(
917- split > 0,
918- "the delete never landed inside the burst (0/20 rounds split)"
926+ delete_first > 0 && grade_first > 0,
927+ "the sweep never crossed the window ({delete_first} rounds with a grade \
928+ refused / {grade_first} with one through)"
919929 );
920930 // Not a race signal, an invariant: the gate refuses a mark for an exam
921931 // that is gone, so no round can leave one behind for the next reader.
tests/regress_payments.rsmodified+30 -2
@@ -15,6 +15,7 @@ mod common;
1515 use axum::http::StatusCode;
1616 use common::{app_and_db, id_of, login, login_as, me_id, send};
1717 use hezarfen_backend::constant::{MAX_FEE_PLAN_ASSIGN_WRITES, MAX_LEDGER_APPLIED_LINES};
18+use hezarfen_backend::database::Database;
1819 use hezarfen_backend::db::fee_plan;
1920 use hezarfen_backend::domain::fee_plan::{FeePlanName, Installment};
2021 use hezarfen_backend::domain::payment_ledger::LedgerAmount;
@@ -23,6 +24,7 @@ use hezarfen_backend::domain::user::UserId;
2324 use hezarfen_backend::error::AppError;
2425 use hezarfen_backend::service::fee_plan_assignment;
2526 use serde_json::{Value, json};
27+use sqlx::Row as _;
2628
2729 /// A plan of `installments`, as the manager writes it.
2830 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<Value> {
5254 common::items(&res.body).clone()
5355 }
5456
57+/// A real `app_user` row for the creator or assignee a domain call must
58+/// name: those columns are foreign keys now, so they are rows, not
59+/// fabricated ids. The username is unique, so every call for the same name
60+/// shares one row, whichever call minted it. These rows never log in, so the
61+/// hash is a stub.
62+async fn fixture_user(db: &Database, username: &str) -> UserId {
63+ sqlx::query(
64+ "INSERT INTO app_user (id, username, password_hash, role) \
65+ VALUES ($1, $2, 'x', 'student') ON CONFLICT DO NOTHING",
66+ )
67+ .bind(UserId::generate().uuid())
68+ .bind(username)
69+ .execute(db)
70+ .await
71+ .unwrap();
72+ let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1")
73+ .bind(username)
74+ .fetch_one(db)
75+ .await
76+ .unwrap()
77+ .try_get(0)
78+ .unwrap();
79+ UserId::from_key(&id.to_string())
80+}
81+
5582 /// The `balance_minor` a statement reports must be folded from the very lines
5683 /// its per-charge rollup walked. It was folded from a *second*, later read of
5784 /// 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() {
227254 #[tokio::test]
228255 async fn editing_a_plan_deleted_since_it_was_read_is_a_404_not_a_409() {
229256 let (_app, db) = app_and_db().await;
230- let manager = UserId::from_key("del_mgr");
257+ let manager = fixture_user(&db, "del_mgr").await;
231258 let one = || {
232259 vec![Installment::new(
233260 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() {
272299 )
273300 .await
274301 .unwrap();
275- fee_plan_assignment::assign(&db, &plan, &UserId::from_key("del_stu"), &manager)
302+ let student = fixture_user(&db, "del_stu").await;
303+ fee_plan_assignment::assign(&db, &plan, &student, &manager)
276304 .await
277305 .unwrap();
278306 let refused = fee_plan::update(