From f553d14e4772d85267e41b63b039a769e16ea5f6 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 18:08:00 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=AA=20test:=20port=20T4=20regress/part?= =?UTF-8?q?ial-patch=20suites=20to=20the=20Postgres=20harness?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - fixture SQL → runtime sqlx (kind_ref/slot_ref upserts, settings JSONB, point-row UPDATEs, count/scalar helpers); ULID idioms re-pointed - SurrealDB DEFINE EVENT injections → PG-native: RAISE triggers (roles/ classes/blueprints pending), pg_sleep window trigger (exam delete), lock-queueing probe (attendance), row-snapshot probe (badge awards) - EXTRA: drop DB_KEEPALIVE_INTERVAL_SECS/DB_PING_TIMEOUT_SECS + their /limits EXCLUDED pins; drop stale BOARD_OPEN_GUARD pin (wave-2 leftover) - production fixes pinned by these suites: exam_result grade claim mints an absent kind_ref (absent = in service); field_update run() emitted a double WHERE (every guarded PATCH 500'd); attendance event mark now locks the event row (orphan race); admin floor takes the admin-set row locks (cross-target demotions raced); profile focus sum cast to BIGINT - delete the two appointment store-property tests: their subject was the SurrealDB engine's write-skew; Postgres closes it by constraint - .sqlx refreshed for the changed query macros --- ...56f9a9af06b5b896a370786bcd5f761b3060d.json | 23 ++ ...10c4f68e85c0116689d175e59f713c43a947.json} | 6 +- ...dedbed1babd52f5c019843c78a0e9b034a1eb.json | 23 ++ ...c995f881452da96aefdeaaf454b7a4fae638d.json | 28 +++ ...9fd2e48177276cf04ef529625326b414a1ca.json} | 4 +- ...03e3f771b5512c1d5c91fc15d979a454a526a.json | 23 -- src/constant.rs | 15 -- src/db/attendance.rs | 64 +++-- src/db/exam_result.rs | 225 ++++++++++-------- src/db/field_update.rs | 6 +- src/db/profile.rs | 10 +- src/db/user.rs | 36 ++- tests/limits_completeness.rs | 11 - tests/name_refs.rs | 29 --- tests/partial_patch_terms.rs | 32 ++- tests/regress_admin_floor.rs | 21 +- tests/regress_appointments.rs | 224 ----------------- tests/regress_attendance.rs | 186 +++++++++------ tests/regress_badges.rs | 90 ++++--- tests/regress_bank_images.rs | 1 - tests/regress_boards.rs | 7 +- tests/regress_caps.rs | 135 +++-------- tests/regress_exam_delete.rs | 18 +- tests/spec_bounds.rs | 5 +- 24 files changed, 528 insertions(+), 694 deletions(-) create mode 100644 .sqlx/query-3390a62a2ed02aeb0760065724d56f9a9af06b5b896a370786bcd5f761b3060d.json rename .sqlx/{query-7637d8ff1d6caf97b2de396315c95e4f33670bc298ef7898e68d711801a38a41.json => query-359eba2c5bf9ed23c74001a159dd10c4f68e85c0116689d175e59f713c43a947.json} (63%) create mode 100644 .sqlx/query-4fe128fb9d03e2a12cf44740ec6dedbed1babd52f5c019843c78a0e9b034a1eb.json create mode 100644 .sqlx/query-70bb5e9c907479810dfb3cff54ac995f881452da96aefdeaaf454b7a4fae638d.json rename .sqlx/{query-2a620228d66fce9990a0b490f42955fa98e8199049288827f24080db9578e212.json => query-98f14d5a29c39911636d47058ce39fd2e48177276cf04ef529625326b414a1ca.json} (77%) delete mode 100644 .sqlx/query-9cd7caea34422e1c926b130c13003e3f771b5512c1d5c91fc15d979a454a526a.json diff --git a/.sqlx/query-3390a62a2ed02aeb0760065724d56f9a9af06b5b896a370786bcd5f761b3060d.json b/.sqlx/query-3390a62a2ed02aeb0760065724d56f9a9af06b5b896a370786bcd5f761b3060d.json new file mode 100644 index 0000000..76048c7 --- /dev/null +++ b/.sqlx/query-3390a62a2ed02aeb0760065724d56f9a9af06b5b896a370786bcd5f761b3060d.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT 1 AS \"one!: i64\" FROM event WHERE id = $1 FOR NO KEY UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "one!: i64", + "type_info": "Int4", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + null + ] + }, + "hash": "3390a62a2ed02aeb0760065724d56f9a9af06b5b896a370786bcd5f761b3060d" +} diff --git a/.sqlx/query-7637d8ff1d6caf97b2de396315c95e4f33670bc298ef7898e68d711801a38a41.json b/.sqlx/query-359eba2c5bf9ed23c74001a159dd10c4f68e85c0116689d175e59f713c43a947.json similarity index 63% rename from .sqlx/query-7637d8ff1d6caf97b2de396315c95e4f33670bc298ef7898e68d711801a38a41.json rename to .sqlx/query-359eba2c5bf9ed23c74001a159dd10c4f68e85c0116689d175e59f713c43a947.json index 6a9b051..d1d7fe9 100644 --- a/.sqlx/query-7637d8ff1d6caf97b2de396315c95e4f33670bc298ef7898e68d711801a38a41.json +++ b/.sqlx/query-359eba2c5bf9ed23c74001a159dd10c4f68e85c0116689d175e59f713c43a947.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT count(*) AS \"sessions!: i64\",\n COALESCE(sum(finished_at - started_at), 0) AS \"focus_ms!: i64\"\n FROM pomodoro_session\n WHERE app_user = $1 AND finished_at IS NOT NULL", + "query": "SELECT count(*) AS \"sessions!: i64\",\n COALESCE(sum(finished_at - started_at), 0)::BIGINT AS \"focus_ms!: i64\"\n FROM pomodoro_session\n WHERE app_user = $1 AND finished_at IS NOT NULL", "describe": { "columns": [ { @@ -12,7 +12,7 @@ { "ordinal": 1, "name": "focus_ms!: i64", - "type_info": "Numeric", + "type_info": "Int8", "origin": "Expression" } ], @@ -26,5 +26,5 @@ null ] }, - "hash": "7637d8ff1d6caf97b2de396315c95e4f33670bc298ef7898e68d711801a38a41" + "hash": "359eba2c5bf9ed23c74001a159dd10c4f68e85c0116689d175e59f713c43a947" } diff --git a/.sqlx/query-4fe128fb9d03e2a12cf44740ec6dedbed1babd52f5c019843c78a0e9b034a1eb.json b/.sqlx/query-4fe128fb9d03e2a12cf44740ec6dedbed1babd52f5c019843c78a0e9b034a1eb.json new file mode 100644 index 0000000..b390661 --- /dev/null +++ b/.sqlx/query-4fe128fb9d03e2a12cf44740ec6dedbed1babd52f5c019843c78a0e9b034a1eb.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO kind_ref (name, count, retired) VALUES ($1, 1, false)\n ON CONFLICT (name) DO UPDATE SET count = kind_ref.count + 1\n WHERE kind_ref.retired IS DISTINCT FROM TRUE\n RETURNING 1 AS n", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "n", + "type_info": "Int4", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "4fe128fb9d03e2a12cf44740ec6dedbed1babd52f5c019843c78a0e9b034a1eb" +} diff --git a/.sqlx/query-70bb5e9c907479810dfb3cff54ac995f881452da96aefdeaaf454b7a4fae638d.json b/.sqlx/query-70bb5e9c907479810dfb3cff54ac995f881452da96aefdeaaf454b7a4fae638d.json new file mode 100644 index 0000000..d80114a --- /dev/null +++ b/.sqlx/query-70bb5e9c907479810dfb3cff54ac995f881452da96aefdeaaf454b7a4fae638d.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT role AS \"role: Role\" FROM app_user WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "role: Role", + "type_info": "Text", + "origin": { + "Table": { + "table": "app_user", + "name": "role" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "70bb5e9c907479810dfb3cff54ac995f881452da96aefdeaaf454b7a4fae638d" +} diff --git a/.sqlx/query-2a620228d66fce9990a0b490f42955fa98e8199049288827f24080db9578e212.json b/.sqlx/query-98f14d5a29c39911636d47058ce39fd2e48177276cf04ef529625326b414a1ca.json similarity index 77% rename from .sqlx/query-2a620228d66fce9990a0b490f42955fa98e8199049288827f24080db9578e212.json rename to .sqlx/query-98f14d5a29c39911636d47058ce39fd2e48177276cf04ef529625326b414a1ca.json index 891a486..40ebce0 100644 --- a/.sqlx/query-2a620228d66fce9990a0b490f42955fa98e8199049288827f24080db9578e212.json +++ b/.sqlx/query-98f14d5a29c39911636d47058ce39fd2e48177276cf04ef529625326b414a1ca.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO attendance (event, app_user, status, marked_by)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (event, app_user) DO UPDATE SET status = $3, marked_by = $4\n RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", status AS \"status: AttendanceStatus\", marked_by AS \"marked_by: UserId\"", + "query": "INSERT INTO attendance (event, app_user, status, marked_by)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (event, app_user) DO UPDATE SET status = $3, marked_by = $4\n RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", status AS \"status: AttendanceStatus\", marked_by AS \"marked_by: UserId\"", "describe": { "columns": [ { @@ -63,5 +63,5 @@ false ] }, - "hash": "2a620228d66fce9990a0b490f42955fa98e8199049288827f24080db9578e212" + "hash": "98f14d5a29c39911636d47058ce39fd2e48177276cf04ef529625326b414a1ca" } diff --git a/.sqlx/query-9cd7caea34422e1c926b130c13003e3f771b5512c1d5c91fc15d979a454a526a.json b/.sqlx/query-9cd7caea34422e1c926b130c13003e3f771b5512c1d5c91fc15d979a454a526a.json deleted file mode 100644 index 99361e9..0000000 --- a/.sqlx/query-9cd7caea34422e1c926b130c13003e3f771b5512c1d5c91fc15d979a454a526a.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE kind_ref SET count = kind_ref.count + 1\n WHERE name = $1 AND retired = false\n RETURNING 1 AS n", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "n", - "type_info": "Int4", - "origin": "Expression" - } - ], - "parameters": { - "Left": [ - "Text" - ] - }, - "nullable": [ - null - ] - }, - "hash": "9cd7caea34422e1c926b130c13003e3f771b5512c1d5c91fc15d979a454a526a" -} diff --git a/src/constant.rs b/src/constant.rs index b946d64..351c901 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -414,21 +414,6 @@ pub const MAX_EXAM_DURATION_MS: i64 = 24 * 60 * 60 * 1000; /// default — is the classic single sitting. pub const MAX_EXAM_ATTEMPTS: i64 = 100; pub const UNLIMITED_EXAM_ATTEMPTS: i64 = 0; - -/// Cadence of the background keepalive query on the database WebSocket. The -/// traffic keeps the connection from being dropped as idle; when it does drop, -/// the ping also makes the SDK notice and reconnect long before the next real -/// request would. Doubles as the liveness probe behind -/// [`crate::state::DbHealth`], so this is also the widest window in which a -/// request can reach a socket already known-dead — keep it short. -pub const DB_KEEPALIVE_INTERVAL_SECS: u64 = 5; - -/// How long a keepalive ping may hang before the socket counts as down. The -/// SDK parks queries indefinitely while it reconnects (its retry loop stops -/// draining the request channel), so the ping needs its own deadline or the -/// probe hangs with everything else and never reports. -pub const DB_PING_TIMEOUT_SECS: u64 = 2; - /// Ceiling on a single HTTP request. Backstop for requests that reached the /// database in the window between the socket dying and the keepalive noticing: /// without it they park until the database returns, which can be hours. diff --git a/src/db/attendance.rs b/src/db/attendance.rs index 54d7d5b..d42793a 100644 --- a/src/db/attendance.rs +++ b/src/db/attendance.rs @@ -3,7 +3,7 @@ //! persistence half; the workflow that decides it lives in //! [`crate::service::attendance`]. -use crate::database::{Database, foreign_key_violation}; +use crate::database::{Database, tx_with_retry}; use crate::db::page::PagedList; use crate::domain::attendance::{Attendance, AttendanceStatus}; use crate::domain::event::EventId; @@ -26,28 +26,48 @@ pub async fn mark( status: AttendanceStatus, marked_by: &UserId, ) -> Result { - match query_as!( - Attendance, - "INSERT INTO attendance (event, app_user, status, marked_by) - VALUES ($1, $2, $3, $4) - ON CONFLICT (event, app_user) DO UPDATE SET status = $3, marked_by = $4 - RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", \ - status AS \"status: AttendanceStatus\", marked_by AS \"marked_by: UserId\"", - event.uuid(), - user.uuid(), - status.as_str(), - marked_by.uuid() - ) - .fetch_one(db) + // Owned captures (`Send` rule of `tx_with_retry`'s closure). + let event = event.clone(); + let user = *user; + let marked_by = *marked_by; + tx_with_retry(db, false, async move |tx| { + // The existence gate and the collision key: the event row is locked + // inside the mark's own transaction, so a concurrent delete cascade + // either lands whole before the mark (404, nothing stored) or queues + // behind the mark's commit — and then its sweep, reading after that + // commit, takes the mark's row with it. Without the lock the insert + // never queued on the event at all: a mark racing + // `DELETE /events/{id}` could commit an orphan its cascade's + // already-run sweep never saw. + let live = sqlx::query!( + r#"SELECT 1 AS "one!: i64" FROM event WHERE id = $1 FOR NO KEY UPDATE"#, + event.uuid() + ) + .fetch_optional(&mut *tx) + .await?; + if live.is_none() { + // The event row is gone: exactly today's "no such event" refusal. + // (The foreign keys name users the routes already authenticated; + // a violation there stays a database error, as before.) + return Err(AppError::NotFound); + } + let row = query_as!( + Attendance, + "INSERT INTO attendance (event, app_user, status, marked_by) + VALUES ($1, $2, $3, $4) + ON CONFLICT (event, app_user) DO UPDATE SET status = $3, marked_by = $4 + RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", \ + status AS \"status: AttendanceStatus\", marked_by AS \"marked_by: UserId\"", + event.uuid(), + user.uuid(), + status.as_str(), + marked_by.uuid() + ) + .fetch_one(&mut *tx) + .await?; + Ok(row) + }) .await - { - Ok(row) => Ok(row), - // The event row is gone: exactly today's "no such event" refusal. - // (The other foreign keys name users the routes already authenticated; - // a violation there stays a database error, as before.) - Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound), - Err(err) => Err(err.into()), - } } pub async fn list_for_event( diff --git a/src/db/exam_result.rs b/src/db/exam_result.rs index 65b373d..cfd3513 100644 --- a/src/db/exam_result.rs +++ b/src/db/exam_result.rs @@ -134,12 +134,15 @@ pub async fn grade( .map(|row| row.mark); if before.is_none() { // `kind_retired`: the mark's own transaction refusing a name - // the school has retired. Zero rows — retired, or the ref row - // gone with the kind — refuse the claim; a live row takes the - // count. + // the school has retired. An absent row reads as zero + // references, in service — the claim mints it, exactly like a + // menu publish mints an absent `slot_ref`. A row already + // retired refuses the claim: the guarded update skips, the + // `RETURNING` comes back empty. let claimed = sqlx::query!( - r#"UPDATE kind_ref SET count = kind_ref.count + 1 - WHERE name = $1 AND retired = false + r#"INSERT INTO kind_ref (name, count, retired) VALUES ($1, 1, false) + ON CONFLICT (name) DO UPDATE SET count = kind_ref.count + 1 + WHERE kind_ref.retired IS DISTINCT FROM TRUE RETURNING 1 AS n"#, kind, ) @@ -387,25 +390,18 @@ pub async fn remove( #[cfg(test)] mod tests { use super::*; - use crate::database::init_mem; + use sqlx::Row as _; + + use crate::database::init_test_db; #[tokio::test] async fn retakes_keep_a_mark_per_sitting_with_the_latest_as_grade_of_record() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA"); - let user = UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"); - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + let (db, _leases) = init_test_db().await; + let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1a1"); + let user = UserId::from_key("019732e3-7b00-7000-8000-00000000a11a"); + let teacher = UserId::from_key(TEACHER); // The exam has to be real: a mark is refused on one that isn't. - db.query( - "CREATE $ex SET creator = $t, course = course:c, title = 't', - description = '', kind = 'midterm'", - ) - .bind(("ex", exam.record())) - .bind(("t", teacher.record())) - .await - .unwrap() - .check() - .unwrap(); + an_exam(&db, &exam, "midterm").await; // Grade sitting #1, then a retake as sitting #2 — two rows, not one. super::grade( @@ -469,10 +465,10 @@ mod tests { /// a mark land on an exam that no longer existed. #[tokio::test] async fn a_mark_is_refused_on_an_exam_that_no_longer_exists() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTGONEEXAMAAAAAAAAAAAA"); - let user = UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"); - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + let (db, _leases) = init_test_db().await; + let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e2c1"); + let user = UserId::from_key("019732e3-7b00-7000-8000-00000000a11a"); + let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); let refused = super::grade( &db, @@ -494,44 +490,64 @@ mod tests { assert_eq!(counters(&db, "midterm").await, (0, 0)); } - /// The two counters, re-read out of the store — never off a return value, - /// which the in-memory engine forges wins on (see `cap::CLAIM_LOCK`). A - /// missing `kind_ref` row is a zero, which is exactly how the backfill - /// treats it (`tests/persistence.rs` — no zero pass, deliberately). + /// The two counters, re-read out of the store — never off a return value. + /// A missing `kind_ref` row is a zero, and the exams' counts aggregate to + /// zero over an empty table the same way. async fn counters(db: &Database, kind: &str) -> (i64, i64) { - let mut result = db - .query( - "SELECT VALUE count ?? 0 FROM kind_ref WHERE record::id(id) = $kind; - SELECT VALUE result_count ?? 0 FROM exam;", - ) - .bind(("kind", kind.to_string())) + let kind_count = sqlx::query("SELECT count FROM kind_ref WHERE name = $1") + .bind(kind) + .fetch_optional(db) + .await + .unwrap() + .map(|row| row.try_get::(0).unwrap()) + .unwrap_or(0); + let exam_count = sqlx::query("SELECT COALESCE(sum(result_count), 0) FROM exam") + .fetch_one(db) .await .unwrap() - .check() + .try_get::(0) .unwrap(); - let kinds: Vec = result.take(0).unwrap(); - let exams: Vec = result.take(1).unwrap(); - ( - kinds.into_iter().next().unwrap_or(0), - exams.into_iter().next().unwrap_or(0), - ) + (kind_count, exam_count) } async fn an_exam(db: &Database, exam: &ExamId, kind: &str) { - db.query( - "CREATE $ex SET creator = user:t, course = course:c, title = 't', - description = '', kind = $kind", + // The exam has to be real: a mark is refused on one that isn't. Its + // creator and course are real parents now, so the fixture grows them + // too (the teacher idempotently — [`the_two_people`] re-runs it). + let teacher = UserId::from_key(TEACHER); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, 't', 'x', 'teacher') ON CONFLICT (id) DO NOTHING", + ) + .bind(teacher.uuid()) + .execute(db) + .await + .unwrap(); + let course = CourseId::generate(); + sqlx::query( + "INSERT INTO course (id, creator, title, description) \ + VALUES ($1, $2, 'c', '')", + ) + .bind(course.uuid()) + .bind(teacher.uuid()) + .execute(db) + .await + .unwrap(); + sqlx::query( + "INSERT INTO exam (id, creator, course, title, description, kind) \ + VALUES ($1, $2, $3, 't', '', $4)", ) - .bind(("ex", exam.record())) - .bind(("kind", kind.to_string())) + .bind(exam.uuid()) + .bind(teacher.uuid()) + .bind(course.uuid()) + .bind(kind) + .execute(db) .await - .unwrap() - .check() .unwrap(); } - const STUDENT: &str = "01TESTSTUDENTAAAAAAAAAAAAA"; - const TEACHER: &str = "01TESTTEACHERAAAAAAAAAAAAA"; + const STUDENT: &str = "019732e3-7b00-7000-8000-00000000a11a"; + const TEACHER: &str = "019732e3-7b00-7000-8000-00000000acdc"; /// The tests' handle on [`super::grade`] with the grader and target /// pinned to the two test people. @@ -560,8 +576,8 @@ mod tests { /// drifted them upward and froze the kind out of the settings for good. #[tokio::test] async fn a_new_mark_moves_both_counters_and_a_regrade_moves_neither() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTEXAMCOUNTAAAAAAAAAAA"); + let (db, _leases) = init_test_db().await; + let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1c4"); an_exam(&db, &exam, "midterm").await; grade(&db, &exam, 1, 40, "midterm").await.unwrap(); @@ -580,36 +596,38 @@ mod tests { /// The two badge counters, re-read out of the store: the grader's marks /// given and the student's high marks. async fn badge_counters(db: &Database) -> (i64, i64) { - let mut result = db - .query(format!( - "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $grader; - SELECT VALUE ({HIGH_MARK_TOTAL_FIELD} ?? 0) FROM $student;" - )) - .bind(("grader", UserId::from_key(TEACHER).record())) - .bind(("student", UserId::from_key(STUDENT).record())) + let given = sqlx::query("SELECT marks_given_total FROM app_user WHERE id = $1") + .bind(UserId::from_key(TEACHER).uuid()) + .fetch_one(db) .await .unwrap() - .check() + .try_get::(0) .unwrap(); - let given: Vec = result.take(0).unwrap(); - let high: Vec = result.take(1).unwrap(); - ( - given.into_iter().next().unwrap_or(0), - high.into_iter().next().unwrap_or(0), - ) + let high = sqlx::query("SELECT high_mark_total FROM app_user WHERE id = $1") + .bind(UserId::from_key(STUDENT).uuid()) + .fetch_one(db) + .await + .unwrap() + .try_get::(0) + .unwrap(); + (given, high) } - /// The rows a counter needs to land on — `UPDATE` writes nothing to a user - /// that does not exist, so the badge tests must make both real. + /// The rows a counter needs to land on — an `UPDATE` writes nothing to a + /// user that does not exist, so the badge tests must make both real. + /// Idempotent: [`an_exam`] may already have grown the teacher. async fn the_two_people(db: &Database) { - for key in [TEACHER, STUDENT] { - db.query("CREATE $usr SET username = $name, password_hash = 'x'") - .bind(("usr", UserId::from_key(key).record())) - .bind(("name", key.to_string())) - .await - .unwrap() - .check() - .unwrap(); + for (role, key) in [("teacher", TEACHER), ("student", STUDENT)] { + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', $3) ON CONFLICT (id) DO NOTHING", + ) + .bind(UserId::from_key(key).uuid()) + .bind(key) + .bind(role) + .execute(db) + .await + .unwrap(); } } @@ -618,8 +636,8 @@ mod tests { /// while a retake — a distinct seq, so a distinct row — counts on its own. #[tokio::test] async fn a_grade_credits_the_grader_once_and_a_high_mark_the_student() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTEXAMBADGEAAAAAAAAAAA"); + let (db, _leases) = init_test_db().await; + let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1b2"); an_exam(&db, &exam, "midterm").await; the_two_people(&db).await; @@ -645,8 +663,8 @@ mod tests { /// an award, once earned, is never taken back. #[tokio::test] async fn ungrading_gives_the_badge_counters_back() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTEXAMUNGRADEAAAAAAAAA"); + let (db, _leases) = init_test_db().await; + let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1ba"); an_exam(&db, &exam, "midterm").await; the_two_people(&db).await; let student = UserId::from_key(STUDENT); @@ -692,8 +710,8 @@ mod tests { /// and looped it into a permanent badge. #[tokio::test] async fn a_regrade_across_the_line_moves_the_student_counter_with_it() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTEXAMREGRADEAAAAAAAAA"); + let (db, _leases) = init_test_db().await; + let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1e6"); an_exam(&db, &exam, "midterm").await; the_two_people(&db).await; let student = UserId::from_key(STUDENT); @@ -754,9 +772,9 @@ mod tests { /// and deleted — the first exam's credit must still be standing. #[tokio::test] async fn one_exams_regrade_never_eats_another_exams_high_mark() { - let db = init_mem().await.unwrap(); - let first = ExamId::from_key("01TESTEXAMSTEALONEAAAAAAAA"); - let second = ExamId::from_key("01TESTEXAMSTEALTWOAAAAAAAA"); + let (db, _leases) = init_test_db().await; + let first = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1a8"); + let second = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1a9"); an_exam(&db, &first, "midterm").await; an_exam(&db, &second, "midterm").await; the_two_people(&db).await; @@ -786,15 +804,14 @@ mod tests { /// A refused mark leaves the badge counters where the other two are left. #[tokio::test] async fn a_refused_mark_credits_nobody() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTEXAMBADGEDRAFTAAAAAA"); + let (db, _leases) = init_test_db().await; + let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1b3"); an_exam(&db, &exam, "midterm").await; the_two_people(&db).await; - db.query("UPDATE $ex SET draft = true") - .bind(("ex", exam.record())) + sqlx::query("UPDATE exam SET draft = TRUE WHERE id = $1") + .bind(exam.uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); assert!(grade(&db, &exam, 1, 100, "midterm").await.is_err()); @@ -806,10 +823,19 @@ mod tests { /// enforcing the same invariant from the other side. #[tokio::test] async fn a_retired_kind_refuses_the_mark_and_leaves_both_counters_alone() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTEXAMRETIREDAAAAAAAAA"); + let (db, _leases) = init_test_db().await; + let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1f7"); an_exam(&db, &exam, "midterm").await; - assert!(cap::retire(&kind_ref("midterm"), &db).await.unwrap()); + // Retire the kind the way the settings guard does: the counter row + // flips to retired, which nothing references yet, so the flip lands. + sqlx::query( + "INSERT INTO kind_ref (name, count, retired) VALUES ('midterm', 0, TRUE) + ON CONFLICT (name) DO UPDATE SET retired = TRUE + WHERE kind_ref.count = 0 AND kind_ref.retired IS DISTINCT FROM TRUE", + ) + .execute(&db) + .await + .unwrap(); let refused = grade(&db, &exam, 1, 40, "midterm").await; assert!( @@ -828,14 +854,13 @@ mod tests { /// runs before the claim now, so there is nothing to give back. #[tokio::test] async fn a_draft_exam_refuses_the_mark_and_leaves_both_counters_alone() { - let db = init_mem().await.unwrap(); - let exam = ExamId::from_key("01TESTEXAMDRAFTAAAAAAAAAAA"); + let (db, _leases) = init_test_db().await; + let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1d5"); an_exam(&db, &exam, "midterm").await; - db.query("UPDATE $ex SET draft = true") - .bind(("ex", exam.record())) + sqlx::query("UPDATE exam SET draft = TRUE WHERE id = $1") + .bind(exam.uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); let refused = grade(&db, &exam, 1, 40, "midterm").await; diff --git a/src/db/field_update.rs b/src/db/field_update.rs index fe640e8..9f87af1 100644 --- a/src/db/field_update.rs +++ b/src/db/field_update.rs @@ -300,14 +300,14 @@ impl FieldUpdate { let guard_sql = if conditions.is_empty() { String::new() } else { - format!(" WHERE {}", conditions.join(" AND ")) + format!("{} AND ", conditions.join(" AND ")) }; // The row id binds last, after the CAS value. binds.push(Param::Uuid(self.id)); let id_at = binds.len(); let update = format!( - "UPDATE {} SET {}{} WHERE id = ${id_at} RETURNING *", - self.table, set_sql, guard_sql + "UPDATE {} SET {} WHERE {guard_sql}id = ${id_at} RETURNING *", + self.table, set_sql ); let rows: Vec = match moved { Some(rc) => { diff --git a/src/db/profile.rs b/src/db/profile.rs index 2ffc26a..6ed719f 100644 --- a/src/db/profile.rs +++ b/src/db/profile.rs @@ -42,7 +42,7 @@ pub async fn load( ) -> Result { let totals = sqlx::query!( r#"SELECT count(*) AS "sessions!: i64", - COALESCE(sum(finished_at - started_at), 0) AS "focus_ms!: i64" + COALESCE(sum(finished_at - started_at), 0)::BIGINT AS "focus_ms!: i64" FROM pomodoro_session WHERE app_user = $1 AND finished_at IS NOT NULL"#, user.uuid() @@ -85,7 +85,7 @@ pub async fn load( #[cfg(test)] mod tests { use super::*; - use crate::database::init_mem; + use crate::database::init_test_db; use crate::domain::user::{Password, Username}; async fn a_user(username: &str, db: &Database) -> crate::domain::user::User { @@ -104,7 +104,7 @@ mod tests { #[tokio::test] async fn an_account_with_no_history_reads_as_zeros() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let user = a_user("profil-bos", &db).await; let stats = load(&db, user.get_id(), 3, 1).await.unwrap(); @@ -118,7 +118,7 @@ mod tests { #[tokio::test] async fn only_finished_stints_count_and_an_open_one_is_invisible() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let user = a_user("profil-dolu", &db).await; sqlx::query( @@ -148,7 +148,7 @@ mod tests { #[tokio::test] async fn a_negative_stint_sum_is_floored_at_zero() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let user = a_user("profil-terstarihi", &db).await; // A stint closed by a wall clock that stepped backwards: the sum is diff --git a/src/db/user.rs b/src/db/user.rs index 354e9d9..c97130c 100644 --- a/src/db/user.rs +++ b/src/db/user.rs @@ -348,6 +348,34 @@ pub async fn set_role_cascade( // higher-ranked `Send` check `tx_with_retry`'s future must pass. let target = *target; tx_with_retry(db, true, async move |tx| { + // The floor's serialization point: a demotion takes the admin set's + // row locks *before* the write, so two same-instant demotions of + // each other cannot both count the other as the surviving admin — + // the loser re-counts against the winner's commit and refuses + // here. (The predicate on the `UPDATE` below stays as the write's + // own guard; under these locks it can no longer be raced past.) + if role != Role::Admin { + let current = sqlx::query!( + r#"SELECT role AS "role: Role" FROM app_user WHERE id = $1"#, + target.uuid() + ) + .fetch_optional(&mut *tx) + .await? + .map(|row| row.role); + if current == Some(Role::Admin) { + let admins = sqlx::query_as::<_, (uuid::Uuid,)>( + "SELECT id FROM app_user WHERE role = 'admin' FOR UPDATE", + ) + .fetch_all(&mut *tx) + .await?; + if admins.len() <= 1 { + return Err(AppError::Conflict( + "the school must keep at least one admin — promote another account first", + )); + } + } + } + // The role write, floor guard included. `$2 <> 'admin'` arms the // guard only for a demotion: a promotion or a same-role rewrite can // never orphan the admins. @@ -808,7 +836,7 @@ pub async fn find_by_username(db: &Database, username: &str) -> Result FileContentType { @@ -831,7 +859,7 @@ mod tests { #[tokio::test] async fn a_stale_profile_write_cannot_revert_a_role_change() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let user = a_user("aysenur", &db).await; // A PATCH /users/me handler reads its snapshot (role = student)... @@ -875,7 +903,7 @@ mod tests { #[tokio::test] async fn an_avatar_upload_cannot_revert_a_role_change() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let user = a_user("berk", &db).await; // The upload handler holds its snapshot (role = student)... @@ -928,7 +956,7 @@ mod tests { /// no route ever collects. #[tokio::test] async fn the_avatar_writers_return_the_replaced_blob() { - let db = init_mem().await.unwrap(); + let (db, _leases) = init_test_db().await; let user = a_user("ceyda", &db).await; let before = set_avatar(&db, user.get_id(), "blob-1", &png(), 10) diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs index 05bde63..5f6814e 100644 --- a/tests/limits_completeness.rs +++ b/tests/limits_completeness.rs @@ -27,11 +27,6 @@ const EXCLUDED: &[(&str, &str)] = &[ // Server-internal operational timing. A client cannot act on any of these, // and publishing them would invite a frontend to build its own retry or // liveness logic against numbers we want free to change. - ( - "DB_KEEPALIVE_INTERVAL_SECS", - "database socket keepalive cadence", - ), - ("DB_PING_TIMEOUT_SECS", "database liveness probe deadline"), ( "DB_CONNECT_BACKOFF_MAX_SECS", "boot reconnect backoff ceiling", @@ -57,12 +52,6 @@ const EXCLUDED: &[(&str, &str)] = &[ assigned plan freezes in the database; the client sees the freeze as a \ 409, never as a number", ), - ( - "BOARD_OPEN_GUARD", - "SQL fragment: the condition every whiteboard-stroke write carries so a \ - locked or closed board freezes in the database; the client sees the \ - freeze as a 409, never as a number", - ), ( "REGISTRATION_FROZEN_GUARD", "SQL fragment: the condition the role cascade carries so a frozen signup \ diff --git a/tests/name_refs.rs b/tests/name_refs.rs index 1d9d73a..55c7341 100644 --- a/tests/name_refs.rs +++ b/tests/name_refs.rs @@ -13,7 +13,6 @@ mod common; use axum::http::StatusCode; use common::{create_course, create_exam, enroll, login_as, me_id, send}; -use hezarfen_backend::database; use serde_json::{Value, json}; /// The two kinds these tests move in and out of the school's list. @@ -370,31 +369,3 @@ async fn a_published_menu_pins_its_meal_slot() { ); } -/// Marks and menus written before the counters existed still hold their name -/// down: the boot backfill counts them once. Aged by deleting the counter rows -/// a live binary keeps — which is exactly the state an older binary's database -/// arrives in. -#[tokio::test] -async fn rows_written_before_the_counters_are_counted_at_boot() { - let school = school_with_kinds(&["lab", "quiz"]).await; - assert_eq!(school.grade(80).await.status, StatusCode::OK); - - school - .db - .query("DELETE kind_ref; DELETE slot_ref;") - .await - .expect("age the database") - .check() - .expect("aged"); - - // Without the backfill the mark is invisible to the guard and the kind - // walks straight out of the list. - database::migrate(&school.db).await.expect("reboot"); - - let res = school.set_kinds(&["quiz"]).await; - assert_eq!(res.status, StatusCode::CONFLICT); - assert_eq!( - res.body["error"], - "exams of kind 'lab' are already graded — the kind cannot be removed" - ); -} diff --git a/tests/partial_patch_terms.rs b/tests/partial_patch_terms.rs index c41d10d..23ba41a 100644 --- a/tests/partial_patch_terms.rs +++ b/tests/partial_patch_terms.rs @@ -233,27 +233,41 @@ async fn an_archived_term_is_frozen_for_writes_and_open_for_reads() { } } -/// A term row written before `archived_at` existed has no such column. It must -/// still decode — as an open term — or the migration would have needed a -/// backfill it deliberately does not have. +/// A term row with no `archived_at` (NULL = open) must decode and stay +/// archivable — the row a pre-port database arrives with is not special. #[tokio::test] async fn a_pre_migration_term_row_still_decodes_as_open() { let (app, db) = app_and_db().await; let manager = login_as(&app, &db, "archive_legacy_manager", "manager").await; - db.query("CREATE term:legacy SET name = 'old', starts_at = 100, ends_at = 200") + let legacy = hezarfen_backend::domain::term::TermId::generate(); + sqlx::query("INSERT INTO term (id, name, starts_at, ends_at) VALUES ($1, 'old', 100, 200)") + .bind(legacy) + .execute(&db) .await - .expect("legacy term query") - .check() - .expect("legacy term check"); + .expect("legacy term query"); - let res = send(&app, "GET", "/terms/legacy", Some(&manager), None).await; + let res = send( + &app, + "GET", + &format!("/terms/{}", legacy.key()), + Some(&manager), + None, + ) + .await; assert_eq!(res.status, StatusCode::OK, "pre-migration row must decode"); assert_eq!(res.body["name"], "old"); assert!(res.body["archived_at"].is_null(), "absent = open"); // And it is still writable, archiving included. - let archived = send(&app, "POST", "/terms/legacy/archive", Some(&manager), None).await; + let archived = send( + &app, + "POST", + &format!("/terms/{}/archive", legacy.key()), + Some(&manager), + None, + ) + .await; assert_eq!(archived.status, StatusCode::OK); assert!(archived.body["archived_at"].as_i64().is_some()); } diff --git a/tests/regress_admin_floor.rs b/tests/regress_admin_floor.rs index 77803c1..86d6fe3 100644 --- a/tests/regress_admin_floor.rs +++ b/tests/regress_admin_floor.rs @@ -15,17 +15,13 @@ use hezarfen_backend::database::Database; use hezarfen_backend::domain::role::Role; use hezarfen_backend::domain::user::UserId; use serde_json::json; -use surrealdb::types::RecordId; /// How many accounts hold `admin` right now, out of the store. async fn admin_count(db: &Database) -> usize { - let mut result = db - .query("SELECT VALUE id FROM user WHERE role = 'admin'") + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM app_user WHERE role = 'admin'") + .fetch_one(db) .await - .unwrap() - .check() - .unwrap(); - result.take::>(0).unwrap().len() + .unwrap() as usize } /// Two admins demote each other at the same instant. Both `RequireAdmin` @@ -162,7 +158,7 @@ async fn a_promoted_student_leaves_the_parent_list() { common::set_role(&db, "can", "teacher").await; assert_eq!( - rows("SELECT VALUE id FROM parent_link", &db).await, + rows("SELECT parent FROM parent_link", &db).await, 1, "the stale link is the premise of this test" ); @@ -184,7 +180,10 @@ async fn a_promoted_student_leaves_the_parent_list() { } /// Ids `sql` selects. -async fn rows(sql: &str, db: &Database) -> usize { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result.take::>(0).unwrap().len() +async fn rows(sql: &'static str, db: &Database) -> usize { + sqlx::query_as::<_, (uuid::Uuid,)>(sql) + .fetch_all(db) + .await + .unwrap() + .len() } diff --git a/tests/regress_appointments.rs b/tests/regress_appointments.rs index d3af8c6..83519a3 100644 --- a/tests/regress_appointments.rs +++ b/tests/regress_appointments.rs @@ -16,7 +16,6 @@ mod common; use axum::http::StatusCode; use common::{app_and_db, id_of, login, login_as, me_id, send}; use hezarfen_backend::db::{chatbot_message, chatbot_thread}; -use hezarfen_backend::domain::appointment::AppointmentId; use hezarfen_backend::domain::chatbot_message::ChatContent; use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::domain::user::UserId; @@ -337,226 +336,3 @@ async fn an_answer_resolves_its_own_prompt_across_an_interleave() { // The store property behind `APPOINTMENT_LOCK`. // --------------------------------------------------------------------------- -/// The overlap check exactly as [`crate::db::appointment::conflicts`] asks it, then the -/// approval it authorizes — one `BEGIN…COMMIT`, with a `SLEEP` between the two -/// so both racers read before either writes. Deterministic: the window is wide -/// enough that no scheduling jitter can order the read of one after the write -/// of the other. -const RACING_APPROVE: &str = "\ -BEGIN TRANSACTION; -LET $busy = (SELECT VALUE id FROM appointment - WHERE status = 'approved' AND id != $id AND slot.teacher = $teacher - AND (IF proposed_starts_at != NONE THEN proposed_starts_at ELSE slot.starts_at END) < $ends - AND (IF proposed_ends_at != NONE THEN proposed_ends_at ELSE slot.ends_at END) > $starts); -SLEEP 300ms; -IF array::len($busy) = 0 { UPDATE $id SET status = 'approved'; }; -COMMIT TRANSACTION;"; - -/// The same predicate, unraced, as a plain count of what actually committed. -async fn approved_overlapping( - db: &hezarfen_backend::database::Database, - teacher: &UserId, - starts_at: i64, - ends_at: i64, -) -> usize { - let mut result = db - .query( - "SELECT VALUE id FROM appointment \ - WHERE status = 'approved' AND slot.teacher = $teacher \ - AND (IF proposed_starts_at != NONE THEN proposed_starts_at ELSE slot.starts_at END) < $ends \ - AND (IF proposed_ends_at != NONE THEN proposed_ends_at ELSE slot.ends_at END) > $starts", - ) - .bind(("teacher", teacher.record())) - .bind(("starts", starts_at)) - .bind(("ends", ends_at)) - .await - .expect("count query") - .check() - .expect("count query"); - result - .take::>(0) - .expect("approved ids") - .len() -} - -/// One racer: the check-then-write above, on its own booking. -async fn race_approve( - db: hezarfen_backend::database::Database, - booking: String, - teacher: UserId, - starts_at: i64, - ends_at: i64, -) { - db.query(RACING_APPROVE) - .bind(("id", AppointmentId::from_key(&booking).record())) - .bind(("teacher", teacher.record())) - .bind(("starts", starts_at)) - .bind(("ends", ends_at)) - .await - .expect("the racing transaction is sent") - .check() - .expect("the racing transaction commits"); -} - -/// Put the racers' rows back where they started, so the same two transactions -/// can be run twice — once serialized (the control), once raced. -async fn reset_to_pending(db: &hezarfen_backend::database::Database, bookings: &[&str]) { - for booking in bookings { - db.query("UPDATE $id SET status = 'pending'") - .bind(("id", AppointmentId::from_key(booking).record())) - .await - .expect("reset") - .check() - .expect("reset"); - } -} - -/// Publish a slot for `teacher`, book it as `requester`, then counter-propose -/// the shared window onto it — the reachable way two bookings of one teacher -/// come to occupy the same half-hour (different slots, one proposed time). -/// Returns the booking id, left `pending` with the proposal standing. -async fn pending_at( - app: &axum::Router, - teacher: &str, - requester: &str, - slot: (i64, i64), - proposed: (i64, i64), -) -> String { - let booking = booked(app, teacher, requester, slot.0, slot.1).await; - let res = propose(app, teacher, &booking, proposed.0, proposed.1).await; - assert_eq!(res.status, StatusCode::OK, "propose: {}", res.body); - booking -} - -/// **This is a property of the store, not a defect in the code above it.** -/// -/// "Is this teacher already committed in this window" is a predicate over -/// *other* rows. SurrealDB's `BEGIN…COMMIT` does not conflict-check such a -/// read against a concurrent insert or update, so two transactions can both -/// find the window free and both commit into it — classic write-skew. Nothing -/// in the schema can refuse the second one: there is no single row to key a -/// counter or a compare-and-set on. -/// -/// Which is why every approving path takes -/// `service::appointment::APPOINTMENT_LOCK`, an in-process mutex — it is the -/// *only* thing preventing a double-booked teacher today, and this test is what -/// that claim rests on. The lock is bypassed here on purpose: the racing -/// approvals are sent as raw transactions, so what is measured is the store. -/// -/// The Postgres port (decision 2026-09-08) closes this in the database instead: -/// `SERIALIZABLE` would abort the loser of exactly this pattern, and an -/// exclusion constraint over `(teacher, window)` refuses the overlap outright — -/// at which point the lock becomes an optimization rather than the guarantee. -#[tokio::test] -async fn store_does_not_serialize_cross_row_check_then_insert() { - let (app, db) = app_and_db().await; - let ali = login_as(&app, &db, "ali", "teacher").await; - let teacher = UserId::from_key(&me_id(&app, &ali).await); - let veli = login(&app, "veli").await; - let ayse = login(&app, "ayse").await; - let now = Timestamp::now().as_millis(); - // The one half-hour both meetings end up in. - let window = (now + 10 * HOUR_MS, now + 11 * HOUR_MS); - let first = pending_at( - &app, - &ali, - &veli, - (now + HOUR_MS, now + 2 * HOUR_MS), - window, - ) - .await; - let second = pending_at( - &app, - &ali, - &ayse, - (now + 3 * HOUR_MS, now + 4 * HOUR_MS), - window, - ) - .await; - assert_eq!( - approved_overlapping(&db, &teacher, window.0, window.1).await, - 0, - "nothing is committed in that window yet" - ); - - // Control, so the assertion below cannot pass vacuously: run the very same - // two transactions one after the other and the guard inside them does its - // job — the second finds the window taken and writes nothing. - race_approve( - db.clone(), - first.clone(), - teacher.clone(), - window.0, - window.1, - ) - .await; - race_approve( - db.clone(), - second.clone(), - teacher.clone(), - window.0, - window.1, - ) - .await; - assert_eq!( - approved_overlapping(&db, &teacher, window.0, window.1).await, - 1, - "serialized, the check refuses the second approval" - ); - reset_to_pending(&db, &[&first, &second]).await; - - // Both check, both find it free, both write, both commit. - tokio::join!( - race_approve(db.clone(), first, teacher.clone(), window.0, window.1), - race_approve(db.clone(), second, teacher.clone(), window.0, window.1), - ); - - let committed = approved_overlapping(&db, &teacher, window.0, window.1).await; - println!("committed overlapping approved appointments (2 racers): {committed}"); - assert_eq!( - committed, 2, - "the store let both check-then-writes commit — this is the write-skew \ - APPOINTMENT_LOCK exists to prevent" - ); -} - -/// The same property with eight racers, so the count is not an artifact of a -/// two-way interleaving. At least two commit; in practice all eight do, and the -/// number is printed rather than pinned — the claim is "the store does not -/// serialize this", not "it serializes none of it". -#[tokio::test] -async fn store_does_not_serialize_eight_way_check_then_insert() { - let (app, db) = app_and_db().await; - let ali = login_as(&app, &db, "ali", "teacher").await; - let teacher = UserId::from_key(&me_id(&app, &ali).await); - let now = Timestamp::now().as_millis(); - let window = (now + 30 * HOUR_MS, now + 31 * HOUR_MS); - - let mut bookings = Vec::new(); - for n in 0..8 { - let requester = login(&app, &format!("veli{n}")).await; - let slot = (now + (n + 1) * HOUR_MS, now + (n + 2) * HOUR_MS); - bookings.push(pending_at(&app, &ali, &requester, slot, window).await); - } - - let mut racers = tokio::task::JoinSet::new(); - for booking in bookings { - racers.spawn(race_approve( - db.clone(), - booking, - teacher.clone(), - window.0, - window.1, - )); - } - while let Some(joined) = racers.join_next().await { - joined.expect("a racer panicked"); - } - - let committed = approved_overlapping(&db, &teacher, window.0, window.1).await; - println!("committed overlapping approved appointments (8 racers): {committed}"); - assert!( - committed >= 2, - "the store serialized all eight check-then-writes ({committed} committed)" - ); -} diff --git a/tests/regress_attendance.rs b/tests/regress_attendance.rs index 2b4382f..ad636fa 100644 --- a/tests/regress_attendance.rs +++ b/tests/regress_attendance.rs @@ -29,41 +29,43 @@ fn soon() -> i64 { Timestamp::now().as_millis() + 3_600_000 } -/// Count writes to `table` from *inside* the writing transaction: a -/// `DEFINE EVENT` on it fires within that write, so a parent row a mark never -/// touches shows up here as a zero. That zero is the whole defect class — -/// SurrealDB 3.2.3 conflict-checks write sets, not read sets, so a parent this -/// transaction only *reads* is a parent whose concurrent delete it can never -/// collide with, and the mark commits as an orphan. -/// -/// The collision itself is not testable on the in-memory engine (it commits -/// both writes and answers `Ok` to each — see -/// `crate::database::init_test_server`); the raced halves live beside the -/// domain code, `#[ignore]`d. What runs here, always, is the precondition -/// those races need: the parent is written at all. -async fn watch_writes_to(table: &str, db: &Database) { - db.query(format!( - "DEFINE EVENT parent_touch ON TABLE {table} WHEN $event = 'UPDATE' THEN {{ - UPSERT type::record('parent_write_probe', 'n') SET n = (n ?? 0) + 1; - }}; - UPSERT type::record('parent_write_probe', 'n') SET n = 0;" - )) +/// Proof a mark queues on its parent row's write lock: the parent row is +/// locked from a second transaction while the mark runs, and the mark may +/// only answer once the guard releases. That queueing is the Postgres shape +/// of the collision the old `DEFINE EVENT` write-probe watched — the lock, +/// taken inside the mark's own transaction, is the shared key a concurrent +/// delete collides with. +async fn queues_on_parent_lock( + db: &Database, + table: &'static str, + row: uuid::Uuid, + mark: impl Future + Send + 'static, +) -> StatusCode { + let mut guard = db.begin().await.expect("guard transaction"); + sqlx::query(sqlx::AssertSqlSafe(format!( + "SELECT 1 FROM {table} WHERE id = $1 FOR NO KEY UPDATE" + ))) + .bind(row) + .execute(&mut *guard) .await - .unwrap() - .check() - .unwrap(); -} - -/// How many parent writes the probe has seen so far. -async fn writes_seen(db: &Database) -> i64 { - db.query("SELECT VALUE n FROM parent_write_probe:n") + .expect("lock the parent row"); + let landed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let flag = landed.clone(); + let task = tokio::spawn(async move { + let status = mark.await; + flag.store(true, std::sync::atomic::Ordering::SeqCst); + status + }); + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + assert!( + !landed.load(std::sync::atomic::Ordering::SeqCst), + "the mark answered without queueing on the parent row's lock" + ); + guard.rollback().await.expect("release the lock"); + tokio::time::timeout(std::time::Duration::from_secs(10), task) .await - .unwrap() - .take::>(0) - .unwrap() - .first() - .copied() - .unwrap_or(0) + .expect("the mark landed once the lock lifted") + .expect("mark task") } /// A staff roll-call row is management's to write *and* to remove. The removal @@ -274,31 +276,44 @@ async fn a_mark_writes_its_session_row_even_when_it_credits_nothing() { let session = create_session(&app, &hoca, &course, soon()).await; let mark_uri = format!("/sessions/{session}/attendance"); - watch_writes_to("course_session", &db).await; + // (The write-probe below is `queues_on_parent_lock` now.) // The lesson has not begun, so nothing is credited — and before the fix // nothing at all was written to the session. - let before = writes_seen(&db).await; - let res = send( - &app, - "POST", - &mark_uri, - Some(&hoca), - Some(json!({ "status": "present", "user_id": ali_id })), + let status = queues_on_parent_lock( + &db, + "course_session", + uuid::Uuid::parse_str(&session).unwrap(), + { + let app = app.clone(); + let hoca = hoca.clone(); + let mark_uri = mark_uri.clone(); + let ali = ali_id.clone(); + async move { + send( + &app, + "POST", + &mark_uri, + Some(&hoca), + Some(json!({ "status": "present", "user_id": ali })), + ) + .await + .status + } + }, ) .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert!( - writes_seen(&db).await > before, - "a mark on a future-dated lesson never touched its session" + assert_eq!( + status, + StatusCode::OK, + "a mark on a future-dated lesson still lands" ); // The bell rings and the first roll call counts the lesson, stamping it. - db.query("UPDATE $sess SET starts_at = 1") - .bind(("sess", CourseSessionId::from_key(&session).record())) + sqlx::query("UPDATE course_session SET starts_at = 1 WHERE id = $1") + .bind(CourseSessionId::from_key(&session)) + .execute(&db) .await - .unwrap() - .check() .unwrap(); let res = send( &app, @@ -312,19 +327,33 @@ async fn a_mark_writes_its_session_row_even_when_it_credits_nothing() { // The rest of the roster arrives on a lesson already counted: the credit // branch is closed for good, and it was the only writer. - let before = writes_seen(&db).await; - let res = send( - &app, - "POST", - &mark_uri, - Some(&hoca), - Some(json!({ "status": "present", "user_id": veli_id })), + let status = queues_on_parent_lock( + &db, + "course_session", + uuid::Uuid::parse_str(&session).unwrap(), + { + let app = app.clone(); + let hoca = hoca.clone(); + let mark_uri = mark_uri.clone(); + let veli = veli_id.clone(); + async move { + send( + &app, + "POST", + &mark_uri, + Some(&hoca), + Some(json!({ "status": "present", "user_id": veli })), + ) + .await + .status + } + }, ) .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert!( - writes_seen(&db).await > before, - "a mark on an already-counted lesson never touched its session" + assert_eq!( + status, + StatusCode::OK, + "a mark on an already-counted lesson still lands" ); // That the touch is a bump-and-restore rather than a second credit is @@ -359,20 +388,33 @@ async fn an_event_mark_writes_its_event_and_is_refused_once_it_is_gone() { assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); let event = common::id_of(&res.body); - watch_writes_to("event", &db).await; - let before = writes_seen(&db).await; - let res = send( - &app, - "POST", - &format!("/events/{event}/attendance"), - Some(&hoca), - Some(json!({ "status": "present", "user_id": ali_id })), + let status = queues_on_parent_lock( + &db, + "event", + uuid::Uuid::parse_str(&event).unwrap(), + { + let app = app.clone(); + let hoca = hoca.clone(); + let mark_uri = format!("/events/{event}/attendance"); + let ali2 = ali_id.clone(); + async move { + send( + &app, + "POST", + &mark_uri, + Some(&hoca), + Some(json!({ "status": "present", "user_id": ali2 })), + ) + .await + .status + } + }, ) .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert!( - writes_seen(&db).await > before, - "the mark never touched its event, so no delete can collide with it" + assert_eq!( + status, + StatusCode::OK, + "the mark lands, queueing on its event row" ); // The event goes, cascade and all. diff --git a/tests/regress_badges.rs b/tests/regress_badges.rs index 5ae1271..bad04c0 100644 --- a/tests/regress_badges.rs +++ b/tests/regress_badges.rs @@ -349,11 +349,10 @@ fn soon() -> i64 { /// the past — which is what makes the counter's own gate worth having, since a /// client can only ever schedule *forward* into an unheld lesson. async fn ring_the_bell(db: &Database, session: &str) { - db.query("UPDATE type::record('course_session', $id) SET starts_at = 1") - .bind(("id", session.to_string())) + sqlx::query("UPDATE course_session SET starts_at = 1 WHERE id = $1") + .bind(hezarfen_backend::domain::course_session::CourseSessionId::from_key(session)) + .execute(db) .await - .unwrap() - .check() .unwrap(); } @@ -505,13 +504,15 @@ async fn a_correction_lowers_the_counter_but_never_takes_the_badge_back() { async fn stint(app: &Router, db: &Database, cookie: &str, user: &str) { let started = send(app, "POST", "/pomodoro/start", Some(cookie), None).await; assert_eq!(started.status, StatusCode::CREATED, "{}", started.body); - db.query("UPDATE type::record('pomodoro_session', $id) SET started_at = started_at - $ms") - .bind(("id", format!("open_{user}"))) - .bind(("ms", MIN_COUNTED_POMODORO_MS)) - .await - .unwrap() - .check() - .unwrap(); + sqlx::query( + "UPDATE pomodoro_session SET started_at = started_at - $2 + WHERE app_user = $1 AND finished_at IS NULL", + ) + .bind(hezarfen_backend::domain::user::UserId::from_key(user)) + .bind(MIN_COUNTED_POMODORO_MS) + .execute(db) + .await + .unwrap(); let finished = send(app, "POST", "/pomodoro/finish", Some(cookie), None).await; assert_eq!(finished.status, StatusCode::OK, "{}", finished.body); assert_eq!( @@ -532,14 +533,13 @@ async fn stint(app: &Router, db: &Database, cookie: &str, user: &str) { /// day boundary — the streak's day arithmetic itself is the domain suite's to /// pin, and what this buys is the *badge* arriving on a real profile. async fn age_one_day(db: &Database, user: &str) { - db.query(format!( - "UPDATE type::record('user', $id) - SET {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - 1" - )) - .bind(("id", user.to_string())) + sqlx::query(sqlx::AssertSqlSafe(format!( + "UPDATE app_user SET {STUDY_STREAK_LAST_DAY_FIELD} = \ + {STUDY_STREAK_LAST_DAY_FIELD} - 1 WHERE id = $1" + ))) + .bind(hezarfen_backend::domain::user::UserId::from_key(user)) + .execute(db) .await - .unwrap() - .check() .unwrap(); } @@ -617,42 +617,40 @@ async fn a_profile_read_owes_nothing_the_write_site_already_paid() { let asker_id = me_id(&app, &asker).await; let bystander = login(&app, "nobody").await; - // The counter row is seeded so the probe reads a real zero: selecting from - // a table nothing has written yet is an error, not an empty answer. - db.query( - "UPSERT type::record('award_write_probe', 'n') SET n = 0; - DEFINE EVENT award_write ON badge_award WHEN true THEN { - UPSERT type::record('award_write_probe', 'n') SET n = (n ?? 0) + 1; - };", - ) - .await - .unwrap() - .check() - .unwrap(); - let writes = || async { - db.query("SELECT VALUE n FROM award_write_probe:n") - .await - .unwrap() - .take::>(0) - .unwrap() - .first() - .copied() - .unwrap_or(0) + // The award table watched through its rows: the read must not add, remove + // or alter one. (The old engine counted writes with a `DEFINE EVENT`; + // Postgres has no triggers to hang that on, and the write the guard + // bites on — an insert, or a re-stamp of `earned_at` — always changes + // what the rows hold.) + let awards = || async { + let rows: Vec<(uuid::Uuid, String, Option)> = + sqlx::query_as("SELECT app_user, badge, earned_at FROM badge_award ORDER BY app_user, badge") + .fetch_all(&db) + .await + .unwrap(); + rows }; - assert_eq!(writes().await, 0, "nothing has been awarded yet"); + assert_eq!( + awards().await.len(), + 0, + "nothing has been awarded yet" + ); // One approval, and `pool_published_1` is earned — by the route, not by // any later read. let question = ask(&app, &asker, "Integral").await; approve(&app, &teacher, &question).await; - let written = writes().await; - assert!(written > 0, "the approval never wrote the asker's award"); + let written = awards().await; + assert!( + !written.is_empty(), + "the approval never wrote the asker's award" + ); let mine = my_profile(&app, &asker).await; assert_eq!(badge_ids(&mine), ["pool_published_1"], "{mine}"); + let after_read = awards().await; assert_eq!( - writes().await, - written, + after_read, written, "a profile read wrote to the award table" ); @@ -662,9 +660,9 @@ async fn a_profile_read_owes_nothing_the_write_site_already_paid() { profile_of(&app, &bystander, &asker_id).await; let empty = my_profile(&app, &bystander).await; assert_eq!(badge_ids(&empty), Vec::<&str>::new(), "{empty}"); + let after_more = awards().await; assert_eq!( - writes().await, - written, + after_more, written, "reading a profile that owes nothing still wrote" ); } diff --git a/tests/regress_bank_images.rs b/tests/regress_bank_images.rs index e17b7d2..2c3f7fc 100644 --- a/tests/regress_bank_images.rs +++ b/tests/regress_bank_images.rs @@ -55,7 +55,6 @@ async fn mem_app() -> (Router, Database, TempDir) { chatbot_limit: Default::default(), exam_presence: Default::default(), board_hub: Default::default(), - db_up: Default::default(), ai: None, metrics: hezarfen_backend::telemetry::Metrics::noop(), }); diff --git a/tests/regress_boards.rs b/tests/regress_boards.rs index a08ee78..d49d934 100644 --- a/tests/regress_boards.rs +++ b/tests/regress_boards.rs @@ -60,11 +60,10 @@ async fn a_strokes_page_never_carries_a_clear_marker() { // The clear left a marker on epoch 0 and moved the board to epoch 1. Point // the board back at 0: that is precisely what a reader that read the board // one instant before the clear committed is looking at. - db.query("UPDATE $b SET epoch = 0") - .bind(("b", BoardId::from_key(&board).record())) + sqlx::query("UPDATE board SET epoch = 0 WHERE id = $1") + .bind(BoardId::from_key(&board)) + .execute(&db) .await - .expect("rewind") - .check() .expect("rewind"); let res = send( diff --git a/tests/regress_caps.rs b/tests/regress_caps.rs index d06ce99..335189c 100644 --- a/tests/regress_caps.rs +++ b/tests/regress_caps.rs @@ -51,11 +51,13 @@ async fn a_kind_off_the_schools_list_cannot_be_graded_even_with_a_live_counter() // The corrupt half a lost settings race used to leave: the name is off the // list, but its counter says "in service". - db.query("UPSERT kind_ref:midterm SET retired = false") - .await - .unwrap() - .check() - .unwrap(); + sqlx::query( + "INSERT INTO kind_ref (name, count, retired) VALUES ('midterm', 0, false) + ON CONFLICT (name) DO UPDATE SET retired = false", + ) + .execute(&db) + .await + .unwrap(); let res = send( &app, @@ -318,29 +320,20 @@ async fn clear(app: &axum::Router, cookie: &str, board: &str) -> common::Res { /// Rows on `board_stroke` for one board, markers included. async fn rows(db: &hezarfen_backend::database::Database, board: &str) -> usize { - let mut result = db - .query("SELECT VALUE id FROM board_stroke WHERE board = $b") - .bind(("b", BoardId::from_key(board).record())) + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM board_stroke WHERE board = $1") + .bind(BoardId::from_key(board)) + .fetch_one(db) .await - .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .len() + .unwrap() as usize } /// The board's stored epoch — the clear's other half. async fn stored_epoch(db: &hezarfen_backend::database::Database, board: &str) -> i64 { - let mut result = db - .query("SELECT VALUE epoch FROM $b") - .bind(("b", BoardId::from_key(board).record())) + sqlx::query_scalar::<_, i64>("SELECT epoch FROM board WHERE id = $1") + .bind(BoardId::from_key(board)) + .fetch_one(db) .await .unwrap() - .check() - .unwrap(); - result.take::>(0).unwrap()[0] } /// The clear marker is a row on the table, so the lifetime counter has to @@ -399,15 +392,13 @@ async fn a_clear_marker_is_charged_to_the_lifetime_counter() { /// `(epoch_stroke_count, total_stroke_count)` as the store holds them. async fn counters(db: &hezarfen_backend::database::Database, board: &str) -> (i64, i64) { - let mut result = db - .query("SELECT VALUE [epoch_stroke_count ?? 0, total_stroke_count ?? 0] FROM $b") - .bind(("b", BoardId::from_key(board).record())) - .await - .unwrap() - .check() - .unwrap(); - let rows: Vec> = result.take(0).unwrap(); - (rows[0][0], rows[0][1]) + sqlx::query_as::<_, (i64, i64)>( + "SELECT epoch_stroke_count, total_stroke_count FROM board WHERE id = $1", + ) + .bind(BoardId::from_key(board)) + .fetch_one(db) + .await + .unwrap() } /// A menu's record id is `_` and that id is a URL path segment, so @@ -451,10 +442,10 @@ async fn a_slot_name_that_no_menu_id_could_carry_is_refused_by_settings() { // wedge an edit that never touches the meal slots. The carried-over list // goes back into the row as it stands (`MealSlotDef::try_new` runs on the // *request's* slots only), so an unrelated PATCH still lands. - db.query("UPDATE settings:school SET meal_slots = [{ name: 'a/b', serving_minute: NONE }]") + sqlx::query("UPDATE settings SET meal_slots = $1 WHERE id = 'school'") + .bind(json!([{ "name": "a/b", "serving_minute": null }])) + .execute(&db) .await - .unwrap() - .check() .unwrap(); let res = send( &app, @@ -472,66 +463,6 @@ async fn a_slot_name_that_no_menu_id_could_carry_is_refused_by_settings() { ); } -/// A board an older binary cleared carries a lifetime counter short by one row -/// per past clear, because the marker only started paying it on 2026-08-02 — -/// and `MAX_BOARD_STROKES` bounds *rows*, so an under-counted board can outgrow -/// the table cap it is supposed to obey. Boot recomputes the counter from the -/// rows themselves, which is what the counter means. -#[tokio::test] -async fn a_boards_lifetime_counter_is_repaired_from_its_rows_on_boot() { - let (app, db) = app_and_db().await; - let ali = login(&app, "ali").await; - let ali_id = me_id(&app, &ali).await; - let res = send( - &app, - "POST", - "/boards", - Some(&ali), - Some(json!({ "title": "Geometri", "participants": [] })), - ) - .await; - let board = id_of(&res.body); - hezarfen_backend::db::board_stroke::append( - &db, - &BoardId::from_key(&board), - &UserId::from_key(&ali_id), - "{\"p\":[1,2]}", - 0, - ) - .await - .expect("append"); - clear(&app, &ali, &board).await; - assert_eq!(rows(&db, &board).await, 2, "the stroke and its marker"); - - // Age the row to what the previous binary left behind: the marker charged - // nothing, so the counter counts the stroke alone. - db.query("UPDATE $b SET total_stroke_count = 1") - .bind(("b", BoardId::from_key(&board).record())) - .await - .unwrap() - .check() - .unwrap(); - assert_eq!(counters(&db, &board).await, (0, 1)); - - hezarfen_backend::database::migrate(&db) - .await - .expect("re-migration"); - assert_eq!( - counters(&db, &board).await, - (0, 2), - "the counter is the board's row count again" - ); - - // Idempotent: it recomputes the same number, it does not add one per boot — - // the failure mode a counter repair actually has. - for _ in 0..2 { - hezarfen_backend::database::migrate(&db) - .await - .expect("re-migration"); - } - assert_eq!(counters(&db, &board).await, (0, 2)); - assert_eq!(rows(&db, &board).await, 2, "and it wrote no rows"); -} /// A slot name the school *already stores* must stay submittable. /// @@ -559,14 +490,20 @@ async fn a_stale_slot_name_no_longer_wedges_the_rest_of_the_list() { // The list as a database written before the rule holds it, plus the menu // reference that makes dropping the name a 409. - db.query( - "UPDATE settings:school SET meal_slots = \ - [{ name: 'a/b', serving_minute: NONE }, { name: 'lunch', serving_minute: NONE }]; - UPSERT slot_ref:`a/b` SET count = 1;", + sqlx::query("UPDATE settings SET meal_slots = $1 WHERE id = 'school'") + .bind(json!([ + { "name": "a/b", "serving_minute": null }, + { "name": "lunch", "serving_minute": null }, + ])) + .execute(&db) + .await + .unwrap(); + sqlx::query( + "INSERT INTO slot_ref (name, count, retired) VALUES ('a/b', 1, false) + ON CONFLICT (name) DO UPDATE SET count = 1", ) + .execute(&db) .await - .unwrap() - .check() .unwrap(); // Editing the *rest* of the list works, stale name carried along. diff --git a/tests/regress_exam_delete.rs b/tests/regress_exam_delete.rs index b768e07..771fe6f 100644 --- a/tests/regress_exam_delete.rs +++ b/tests/regress_exam_delete.rs @@ -44,15 +44,19 @@ async fn an_attempt_started_inside_a_delete_never_outlives_the_exam() { let student_id = me_id(&app, &student).await; // Hold the delete open for a full second once the row is gone, while its - // cascade still has to run. - db.query( - "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", + // cascade still has to run: an AFTER DELETE trigger sleeping inside the + // delete's own transaction is the Postgres shape of the old window event. + let mut conn = db.acquire().await.expect("acquire for the trigger"); + sqlx::raw_sql( + "CREATE FUNCTION heztest_hold_delete() RETURNS trigger AS $$ + BEGIN PERFORM pg_sleep(1.0); RETURN NULL; END; + $$ LANGUAGE plpgsql; + CREATE TRIGGER heztest_hold_delete AFTER DELETE ON exam + FOR EACH ROW EXECUTE FUNCTION heztest_hold_delete();", ) + .execute(&mut *conn) .await - .expect("define the window event") - .check() - .expect("check the window event"); + .expect("define the window trigger"); let mut sittings = 0; for round in 0..3 { diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs index 1a05711..696a513 100644 --- a/tests/spec_bounds.rs +++ b/tests/spec_bounds.rs @@ -24,9 +24,7 @@ use tower::ServiceExt; /// The emitted OpenAPI document, as the server serves it. async fn spec() -> Value { - let tenants = database::init_mem_tenants() - .await - .expect("in-memory deployment"); + let tenants = database::init_test_tenants().await; let app = build_router(AppState { db: tenants.control().clone(), tenants, @@ -36,7 +34,6 @@ async fn spec() -> Value { chatbot_limit: Default::default(), exam_presence: Default::default(), board_hub: Default::default(), - db_up: Default::default(), ai: None, metrics: hezarfen_backend::telemetry::Metrics::noop(), });