forge
Explore
Log in

Don't you dare go Hollow

Port T4 regress/partial-patch suites to the Postgres harness

Browse files at this commit

f553d14e4772d85267e41b63b039a769e16ea5f6Ahmet Kaan GümüşParent: e0e3597
  • test
    • port T4 regress/partial-patch suites to the Postgres harness
Show full message
🧪 test: port T4 regress/partial-patch suites to the Postgres harness

- 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
.sqlx/query-3390a62a2ed02aeb0760065724d56f9a9af06b5b896a370786bcd5f761b3060d.jsonadded+23 -0
@@ -0,0 +1,23 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT 1 AS \"one!: i64\" FROM event WHERE id = $1 FOR NO KEY UPDATE",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "one!: i64",
9+ "type_info": "Int4",
10+ "origin": "Expression"
11+ }
12+ ],
13+ "parameters": {
14+ "Left": [
15+ "Uuid"
16+ ]
17+ },
18+ "nullable": [
19+ null
20+ ]
21+ },
22+ "hash": "3390a62a2ed02aeb0760065724d56f9a9af06b5b896a370786bcd5f761b3060d"
23+}
.sqlx/query-7637d8ff1d6caf97b2de396315c95e4f33670bc298ef7898e68d711801a38a41.json → .sqlx/query-359eba2c5bf9ed23c74001a159dd10c4f68e85c0116689d175e59f713c43a947.jsonrenamed+3 -3
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "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",3+ "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",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -12,7 +12,7 @@
12 {12 {
13 "ordinal": 1,13 "ordinal": 1,
14 "name": "focus_ms!: i64",14 "name": "focus_ms!: i64",
15- "type_info": "Numeric",15+ "type_info": "Int8",
16 "origin": "Expression"16 "origin": "Expression"
17 }17 }
18 ],18 ],
@@ -26,5 +26,5 @@
26 null26 null
27 ]27 ]
28 },28 },
29- "hash": "7637d8ff1d6caf97b2de396315c95e4f33670bc298ef7898e68d711801a38a41"29+ "hash": "359eba2c5bf9ed23c74001a159dd10c4f68e85c0116689d175e59f713c43a947"
30 }30 }
.sqlx/query-4fe128fb9d03e2a12cf44740ec6dedbed1babd52f5c019843c78a0e9b034a1eb.jsonadded+23 -0
@@ -0,0 +1,23 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "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",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "n",
9+ "type_info": "Int4",
10+ "origin": "Expression"
11+ }
12+ ],
13+ "parameters": {
14+ "Left": [
15+ "Text"
16+ ]
17+ },
18+ "nullable": [
19+ null
20+ ]
21+ },
22+ "hash": "4fe128fb9d03e2a12cf44740ec6dedbed1babd52f5c019843c78a0e9b034a1eb"
23+}
.sqlx/query-70bb5e9c907479810dfb3cff54ac995f881452da96aefdeaaf454b7a4fae638d.jsonadded+28 -0
@@ -0,0 +1,28 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT role AS \"role: Role\" FROM app_user WHERE id = $1",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "role: Role",
9+ "type_info": "Text",
10+ "origin": {
11+ "Table": {
12+ "table": "app_user",
13+ "name": "role"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Uuid"
21+ ]
22+ },
23+ "nullable": [
24+ false
25+ ]
26+ },
27+ "hash": "70bb5e9c907479810dfb3cff54ac995f881452da96aefdeaaf454b7a4fae638d"
28+}
.sqlx/query-2a620228d66fce9990a0b490f42955fa98e8199049288827f24080db9578e212.json → .sqlx/query-98f14d5a29c39911636d47058ce39fd2e48177276cf04ef529625326b414a1ca.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "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\"",3+ "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\"",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -63,5 +63,5 @@
63 false63 false
64 ]64 ]
65 },65 },
66- "hash": "2a620228d66fce9990a0b490f42955fa98e8199049288827f24080db9578e212"66+ "hash": "98f14d5a29c39911636d47058ce39fd2e48177276cf04ef529625326b414a1ca"
67 }67 }
.sqlx/query-9cd7caea34422e1c926b130c13003e3f771b5512c1d5c91fc15d979a454a526a.jsondeleted+0 -23
@@ -1,23 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE kind_ref SET count = kind_ref.count + 1\n WHERE name = $1 AND retired = false\n RETURNING 1 AS n",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "n",
9- "type_info": "Int4",
10- "origin": "Expression"
11- }
12- ],
13- "parameters": {
14- "Left": [
15- "Text"
16- ]
17- },
18- "nullable": [
19- null
20- ]
21- },
22- "hash": "9cd7caea34422e1c926b130c13003e3f771b5512c1d5c91fc15d979a454a526a"
23-}
src/constant.rsmodified+0 -15
@@ -414,21 +414,6 @@ pub const MAX_EXAM_DURATION_MS: i64 = 24 * 60 * 60 * 1000;
414 /// default — is the classic single sitting.414 /// default — is the classic single sitting.
415 pub const MAX_EXAM_ATTEMPTS: i64 = 100;415 pub const MAX_EXAM_ATTEMPTS: i64 = 100;
416 pub const UNLIMITED_EXAM_ATTEMPTS: i64 = 0;416 pub const UNLIMITED_EXAM_ATTEMPTS: i64 = 0;
417-
418-/// Cadence of the background keepalive query on the database WebSocket. The
419-/// traffic keeps the connection from being dropped as idle; when it does drop,
420-/// the ping also makes the SDK notice and reconnect long before the next real
421-/// request would. Doubles as the liveness probe behind
422-/// [`crate::state::DbHealth`], so this is also the widest window in which a
423-/// request can reach a socket already known-dead — keep it short.
424-pub const DB_KEEPALIVE_INTERVAL_SECS: u64 = 5;
425-
426-/// How long a keepalive ping may hang before the socket counts as down. The
427-/// SDK parks queries indefinitely while it reconnects (its retry loop stops
428-/// draining the request channel), so the ping needs its own deadline or the
429-/// probe hangs with everything else and never reports.
430-pub const DB_PING_TIMEOUT_SECS: u64 = 2;
431-
432 /// Ceiling on a single HTTP request. Backstop for requests that reached the417 /// Ceiling on a single HTTP request. Backstop for requests that reached the
433 /// database in the window between the socket dying and the keepalive noticing:418 /// database in the window between the socket dying and the keepalive noticing:
434 /// without it they park until the database returns, which can be hours.419 /// without it they park until the database returns, which can be hours.
src/db/attendance.rsmodified+42 -22
@@ -3,7 +3,7 @@
3 //! persistence half; the workflow that decides it lives in3 //! persistence half; the workflow that decides it lives in
4 //! [`crate::service::attendance`].4 //! [`crate::service::attendance`].
5 5
6-use crate::database::{Database, foreign_key_violation};6+use crate::database::{Database, tx_with_retry};
7 use crate::db::page::PagedList;7 use crate::db::page::PagedList;
8 use crate::domain::attendance::{Attendance, AttendanceStatus};8 use crate::domain::attendance::{Attendance, AttendanceStatus};
9 use crate::domain::event::EventId;9 use crate::domain::event::EventId;
@@ -26,28 +26,48 @@ pub async fn mark(
26 status: AttendanceStatus,26 status: AttendanceStatus,
27 marked_by: &UserId,27 marked_by: &UserId,
28 ) -> Result<Attendance, AppError> {28 ) -> Result<Attendance, AppError> {
29- match query_as!(29+ // Owned captures (`Send` rule of `tx_with_retry`'s closure).
30- Attendance,30+ let event = event.clone();
31- "INSERT INTO attendance (event, app_user, status, marked_by)31+ let user = *user;
32- VALUES ($1, $2, $3, $4)32+ let marked_by = *marked_by;
33- ON CONFLICT (event, app_user) DO UPDATE SET status = $3, marked_by = $433+ tx_with_retry(db, false, async move |tx| {
34- RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", \34+ // The existence gate and the collision key: the event row is locked
35- status AS \"status: AttendanceStatus\", marked_by AS \"marked_by: UserId\"",35+ // inside the mark's own transaction, so a concurrent delete cascade
36- event.uuid(),36+ // either lands whole before the mark (404, nothing stored) or queues
37- user.uuid(),37+ // behind the mark's commit — and then its sweep, reading after that
38- status.as_str(),38+ // commit, takes the mark's row with it. Without the lock the insert
39- marked_by.uuid()39+ // never queued on the event at all: a mark racing
40- )40+ // `DELETE /events/{id}` could commit an orphan its cascade's
41- .fetch_one(db)41+ // already-run sweep never saw.
42+ let live = sqlx::query!(
43+ r#"SELECT 1 AS "one!: i64" FROM event WHERE id = $1 FOR NO KEY UPDATE"#,
44+ event.uuid()
45+ )
46+ .fetch_optional(&mut *tx)
47+ .await?;
48+ if live.is_none() {
49+ // The event row is gone: exactly today's "no such event" refusal.
50+ // (The foreign keys name users the routes already authenticated;
51+ // a violation there stays a database error, as before.)
52+ return Err(AppError::NotFound);
53+ }
54+ let row = query_as!(
55+ Attendance,
56+ "INSERT INTO attendance (event, app_user, status, marked_by)
57+ VALUES ($1, $2, $3, $4)
58+ ON CONFLICT (event, app_user) DO UPDATE SET status = $3, marked_by = $4
59+ RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", \
60+ status AS \"status: AttendanceStatus\", marked_by AS \"marked_by: UserId\"",
61+ event.uuid(),
62+ user.uuid(),
63+ status.as_str(),
64+ marked_by.uuid()
65+ )
66+ .fetch_one(&mut *tx)
67+ .await?;
68+ Ok(row)
69+ })
42 .await70 .await
43- {
44- Ok(row) => Ok(row),
45- // The event row is gone: exactly today's "no such event" refusal.
46- // (The other foreign keys name users the routes already authenticated;
47- // a violation there stays a database error, as before.)
48- Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound),
49- Err(err) => Err(err.into()),
50- }
51 }71 }
52 72
53 pub async fn list_for_event(73 pub async fn list_for_event(
src/db/exam_result.rsmodified+125 -100
@@ -134,12 +134,15 @@ pub async fn grade(
134 .map(|row| row.mark);134 .map(|row| row.mark);
135 if before.is_none() {135 if before.is_none() {
136 // `kind_retired`: the mark's own transaction refusing a name136 // `kind_retired`: the mark's own transaction refusing a name
137- // the school has retired. Zero rows — retired, or the ref row137+ // the school has retired. An absent row reads as zero
138- // gone with the kind — refuse the claim; a live row takes the138+ // references, in service — the claim mints it, exactly like a
139- // count.139+ // menu publish mints an absent `slot_ref`. A row already
140+ // retired refuses the claim: the guarded update skips, the
141+ // `RETURNING` comes back empty.
140 let claimed = sqlx::query!(142 let claimed = sqlx::query!(
141- r#"UPDATE kind_ref SET count = kind_ref.count + 1143+ r#"INSERT INTO kind_ref (name, count, retired) VALUES ($1, 1, false)
142- WHERE name = $1 AND retired = false144+ ON CONFLICT (name) DO UPDATE SET count = kind_ref.count + 1
145+ WHERE kind_ref.retired IS DISTINCT FROM TRUE
143 RETURNING 1 AS n"#,146 RETURNING 1 AS n"#,
144 kind,147 kind,
145 )148 )
@@ -387,25 +390,18 @@ pub async fn remove(
387 #[cfg(test)]390 #[cfg(test)]
388 mod tests {391 mod tests {
389 use super::*;392 use super::*;
390- use crate::database::init_mem;393+ use sqlx::Row as _;
394+
395+ use crate::database::init_test_db;
391 396
392 #[tokio::test]397 #[tokio::test]
393 async fn retakes_keep_a_mark_per_sitting_with_the_latest_as_grade_of_record() {398 async fn retakes_keep_a_mark_per_sitting_with_the_latest_as_grade_of_record() {
394- let db = init_mem().await.unwrap();399+ let (db, _leases) = init_test_db().await;
395- let exam = ExamId::from_key("01TESTEXAMAAAAAAAAAAAAAAAA");400+ let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1a1");
396- let user = UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA");401+ let user = UserId::from_key("019732e3-7b00-7000-8000-00000000a11a");
397- let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");402+ let teacher = UserId::from_key(TEACHER);
398 // The exam has to be real: a mark is refused on one that isn't.403 // The exam has to be real: a mark is refused on one that isn't.
399- db.query(404+ an_exam(&db, &exam, "midterm").await;
400- "CREATE $ex SET creator = $t, course = course:c, title = 't',
401- description = '', kind = 'midterm'",
402- )
403- .bind(("ex", exam.record()))
404- .bind(("t", teacher.record()))
405- .await
406- .unwrap()
407- .check()
408- .unwrap();
409 405
410 // Grade sitting #1, then a retake as sitting #2 — two rows, not one.406 // Grade sitting #1, then a retake as sitting #2 — two rows, not one.
411 super::grade(407 super::grade(
@@ -469,10 +465,10 @@ mod tests {
469 /// a mark land on an exam that no longer existed.465 /// a mark land on an exam that no longer existed.
470 #[tokio::test]466 #[tokio::test]
471 async fn a_mark_is_refused_on_an_exam_that_no_longer_exists() {467 async fn a_mark_is_refused_on_an_exam_that_no_longer_exists() {
472- let db = init_mem().await.unwrap();468+ let (db, _leases) = init_test_db().await;
473- let exam = ExamId::from_key("01TESTGONEEXAMAAAAAAAAAAAA");469+ let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e2c1");
474- let user = UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA");470+ let user = UserId::from_key("019732e3-7b00-7000-8000-00000000a11a");
475- let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");471+ let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
476 472
477 let refused = super::grade(473 let refused = super::grade(
478 &db,474 &db,
@@ -494,44 +490,64 @@ mod tests {
494 assert_eq!(counters(&db, "midterm").await, (0, 0));490 assert_eq!(counters(&db, "midterm").await, (0, 0));
495 }491 }
496 492
497- /// The two counters, re-read out of the store — never off a return value,493+ /// The two counters, re-read out of the store — never off a return value.
498- /// which the in-memory engine forges wins on (see `cap::CLAIM_LOCK`). A494+ /// A missing `kind_ref` row is a zero, and the exams' counts aggregate to
499- /// missing `kind_ref` row is a zero, which is exactly how the backfill495+ /// zero over an empty table the same way.
500- /// treats it (`tests/persistence.rs` — no zero pass, deliberately).
501 async fn counters(db: &Database, kind: &str) -> (i64, i64) {496 async fn counters(db: &Database, kind: &str) -> (i64, i64) {
502- let mut result = db497+ let kind_count = sqlx::query("SELECT count FROM kind_ref WHERE name = $1")
503- .query(498+ .bind(kind)
504- "SELECT VALUE count ?? 0 FROM kind_ref WHERE record::id(id) = $kind;499+ .fetch_optional(db)
505- SELECT VALUE result_count ?? 0 FROM exam;",500+ .await
506- )501+ .unwrap()
507- .bind(("kind", kind.to_string()))502+ .map(|row| row.try_get::<i64, _>(0).unwrap())
503+ .unwrap_or(0);
504+ let exam_count = sqlx::query("SELECT COALESCE(sum(result_count), 0) FROM exam")
505+ .fetch_one(db)
508 .await506 .await
509 .unwrap()507 .unwrap()
510- .check()508+ .try_get::<i64, _>(0)
511 .unwrap();509 .unwrap();
512- let kinds: Vec<i64> = result.take(0).unwrap();510+ (kind_count, exam_count)
513- let exams: Vec<i64> = result.take(1).unwrap();
514- (
515- kinds.into_iter().next().unwrap_or(0),
516- exams.into_iter().next().unwrap_or(0),
517- )
518 }511 }
519 512
520 async fn an_exam(db: &Database, exam: &ExamId, kind: &str) {513 async fn an_exam(db: &Database, exam: &ExamId, kind: &str) {
521- db.query(514+ // The exam has to be real: a mark is refused on one that isn't. Its
522- "CREATE $ex SET creator = user:t, course = course:c, title = 't',515+ // creator and course are real parents now, so the fixture grows them
523- description = '', kind = $kind",516+ // too (the teacher idempotently — [`the_two_people`] re-runs it).
517+ let teacher = UserId::from_key(TEACHER);
518+ sqlx::query(
519+ "INSERT INTO app_user (id, username, password_hash, role) \
520+ VALUES ($1, 't', 'x', 'teacher') ON CONFLICT (id) DO NOTHING",
521+ )
522+ .bind(teacher.uuid())
523+ .execute(db)
524+ .await
525+ .unwrap();
526+ let course = CourseId::generate();
527+ sqlx::query(
528+ "INSERT INTO course (id, creator, title, description) \
529+ VALUES ($1, $2, 'c', '')",
530+ )
531+ .bind(course.uuid())
532+ .bind(teacher.uuid())
533+ .execute(db)
534+ .await
535+ .unwrap();
536+ sqlx::query(
537+ "INSERT INTO exam (id, creator, course, title, description, kind) \
538+ VALUES ($1, $2, $3, 't', '', $4)",
524 )539 )
525- .bind(("ex", exam.record()))540+ .bind(exam.uuid())
526- .bind(("kind", kind.to_string()))541+ .bind(teacher.uuid())
542+ .bind(course.uuid())
543+ .bind(kind)
544+ .execute(db)
527 .await545 .await
528- .unwrap()
529- .check()
530 .unwrap();546 .unwrap();
531 }547 }
532 548
533- const STUDENT: &str = "01TESTSTUDENTAAAAAAAAAAAAA";549+ const STUDENT: &str = "019732e3-7b00-7000-8000-00000000a11a";
534- const TEACHER: &str = "01TESTTEACHERAAAAAAAAAAAAA";550+ const TEACHER: &str = "019732e3-7b00-7000-8000-00000000acdc";
535 551
536 /// The tests' handle on [`super::grade`] with the grader and target552 /// The tests' handle on [`super::grade`] with the grader and target
537 /// pinned to the two test people.553 /// pinned to the two test people.
@@ -560,8 +576,8 @@ mod tests {
560 /// drifted them upward and froze the kind out of the settings for good.576 /// drifted them upward and froze the kind out of the settings for good.
561 #[tokio::test]577 #[tokio::test]
562 async fn a_new_mark_moves_both_counters_and_a_regrade_moves_neither() {578 async fn a_new_mark_moves_both_counters_and_a_regrade_moves_neither() {
563- let db = init_mem().await.unwrap();579+ let (db, _leases) = init_test_db().await;
564- let exam = ExamId::from_key("01TESTEXAMCOUNTAAAAAAAAAAA");580+ let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1c4");
565 an_exam(&db, &exam, "midterm").await;581 an_exam(&db, &exam, "midterm").await;
566 582
567 grade(&db, &exam, 1, 40, "midterm").await.unwrap();583 grade(&db, &exam, 1, 40, "midterm").await.unwrap();
@@ -580,36 +596,38 @@ mod tests {
580 /// The two badge counters, re-read out of the store: the grader's marks596 /// The two badge counters, re-read out of the store: the grader's marks
581 /// given and the student's high marks.597 /// given and the student's high marks.
582 async fn badge_counters(db: &Database) -> (i64, i64) {598 async fn badge_counters(db: &Database) -> (i64, i64) {
583- let mut result = db599+ let given = sqlx::query("SELECT marks_given_total FROM app_user WHERE id = $1")
584- .query(format!(600+ .bind(UserId::from_key(TEACHER).uuid())
585- "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $grader;601+ .fetch_one(db)
586- SELECT VALUE ({HIGH_MARK_TOTAL_FIELD} ?? 0) FROM $student;"
587- ))
588- .bind(("grader", UserId::from_key(TEACHER).record()))
589- .bind(("student", UserId::from_key(STUDENT).record()))
590 .await602 .await
591 .unwrap()603 .unwrap()
592- .check()604+ .try_get::<i64, _>(0)
593 .unwrap();605 .unwrap();
594- let given: Vec<i64> = result.take(0).unwrap();606+ let high = sqlx::query("SELECT high_mark_total FROM app_user WHERE id = $1")
595- let high: Vec<i64> = result.take(1).unwrap();607+ .bind(UserId::from_key(STUDENT).uuid())
596- (608+ .fetch_one(db)
597- given.into_iter().next().unwrap_or(0),609+ .await
598- high.into_iter().next().unwrap_or(0),610+ .unwrap()
599- )611+ .try_get::<i64, _>(0)
612+ .unwrap();
613+ (given, high)
600 }614 }
601 615
602- /// The rows a counter needs to land on — `UPDATE` writes nothing to a user616+ /// The rows a counter needs to land on — an `UPDATE` writes nothing to a
603- /// that does not exist, so the badge tests must make both real.617+ /// user that does not exist, so the badge tests must make both real.
618+ /// Idempotent: [`an_exam`] may already have grown the teacher.
604 async fn the_two_people(db: &Database) {619 async fn the_two_people(db: &Database) {
605- for key in [TEACHER, STUDENT] {620+ for (role, key) in [("teacher", TEACHER), ("student", STUDENT)] {
606- db.query("CREATE $usr SET username = $name, password_hash = 'x'")621+ sqlx::query(
607- .bind(("usr", UserId::from_key(key).record()))622+ "INSERT INTO app_user (id, username, password_hash, role) \
608- .bind(("name", key.to_string()))623+ VALUES ($1, $2, 'x', $3) ON CONFLICT (id) DO NOTHING",
609- .await624+ )
610- .unwrap()625+ .bind(UserId::from_key(key).uuid())
611- .check()626+ .bind(key)
612- .unwrap();627+ .bind(role)
628+ .execute(db)
629+ .await
630+ .unwrap();
613 }631 }
614 }632 }
615 633
@@ -618,8 +636,8 @@ mod tests {
618 /// while a retake — a distinct seq, so a distinct row — counts on its own.636 /// while a retake — a distinct seq, so a distinct row — counts on its own.
619 #[tokio::test]637 #[tokio::test]
620 async fn a_grade_credits_the_grader_once_and_a_high_mark_the_student() {638 async fn a_grade_credits_the_grader_once_and_a_high_mark_the_student() {
621- let db = init_mem().await.unwrap();639+ let (db, _leases) = init_test_db().await;
622- let exam = ExamId::from_key("01TESTEXAMBADGEAAAAAAAAAAA");640+ let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1b2");
623 an_exam(&db, &exam, "midterm").await;641 an_exam(&db, &exam, "midterm").await;
624 the_two_people(&db).await;642 the_two_people(&db).await;
625 643
@@ -645,8 +663,8 @@ mod tests {
645 /// an award, once earned, is never taken back.663 /// an award, once earned, is never taken back.
646 #[tokio::test]664 #[tokio::test]
647 async fn ungrading_gives_the_badge_counters_back() {665 async fn ungrading_gives_the_badge_counters_back() {
648- let db = init_mem().await.unwrap();666+ let (db, _leases) = init_test_db().await;
649- let exam = ExamId::from_key("01TESTEXAMUNGRADEAAAAAAAAA");667+ let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1ba");
650 an_exam(&db, &exam, "midterm").await;668 an_exam(&db, &exam, "midterm").await;
651 the_two_people(&db).await;669 the_two_people(&db).await;
652 let student = UserId::from_key(STUDENT);670 let student = UserId::from_key(STUDENT);
@@ -692,8 +710,8 @@ mod tests {
692 /// and looped it into a permanent badge.710 /// and looped it into a permanent badge.
693 #[tokio::test]711 #[tokio::test]
694 async fn a_regrade_across_the_line_moves_the_student_counter_with_it() {712 async fn a_regrade_across_the_line_moves_the_student_counter_with_it() {
695- let db = init_mem().await.unwrap();713+ let (db, _leases) = init_test_db().await;
696- let exam = ExamId::from_key("01TESTEXAMREGRADEAAAAAAAAA");714+ let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1e6");
697 an_exam(&db, &exam, "midterm").await;715 an_exam(&db, &exam, "midterm").await;
698 the_two_people(&db).await;716 the_two_people(&db).await;
699 let student = UserId::from_key(STUDENT);717 let student = UserId::from_key(STUDENT);
@@ -754,9 +772,9 @@ mod tests {
754 /// and deleted — the first exam's credit must still be standing.772 /// and deleted — the first exam's credit must still be standing.
755 #[tokio::test]773 #[tokio::test]
756 async fn one_exams_regrade_never_eats_another_exams_high_mark() {774 async fn one_exams_regrade_never_eats_another_exams_high_mark() {
757- let db = init_mem().await.unwrap();775+ let (db, _leases) = init_test_db().await;
758- let first = ExamId::from_key("01TESTEXAMSTEALONEAAAAAAAA");776+ let first = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1a8");
759- let second = ExamId::from_key("01TESTEXAMSTEALTWOAAAAAAAA");777+ let second = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1a9");
760 an_exam(&db, &first, "midterm").await;778 an_exam(&db, &first, "midterm").await;
761 an_exam(&db, &second, "midterm").await;779 an_exam(&db, &second, "midterm").await;
762 the_two_people(&db).await;780 the_two_people(&db).await;
@@ -786,15 +804,14 @@ mod tests {
786 /// A refused mark leaves the badge counters where the other two are left.804 /// A refused mark leaves the badge counters where the other two are left.
787 #[tokio::test]805 #[tokio::test]
788 async fn a_refused_mark_credits_nobody() {806 async fn a_refused_mark_credits_nobody() {
789- let db = init_mem().await.unwrap();807+ let (db, _leases) = init_test_db().await;
790- let exam = ExamId::from_key("01TESTEXAMBADGEDRAFTAAAAAA");808+ let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1b3");
791 an_exam(&db, &exam, "midterm").await;809 an_exam(&db, &exam, "midterm").await;
792 the_two_people(&db).await;810 the_two_people(&db).await;
793- db.query("UPDATE $ex SET draft = true")811+ sqlx::query("UPDATE exam SET draft = TRUE WHERE id = $1")
794- .bind(("ex", exam.record()))812+ .bind(exam.uuid())
813+ .execute(&db)
795 .await814 .await
796- .unwrap()
797- .check()
798 .unwrap();815 .unwrap();
799 816
800 assert!(grade(&db, &exam, 1, 100, "midterm").await.is_err());817 assert!(grade(&db, &exam, 1, 100, "midterm").await.is_err());
@@ -806,10 +823,19 @@ mod tests {
806 /// enforcing the same invariant from the other side.823 /// enforcing the same invariant from the other side.
807 #[tokio::test]824 #[tokio::test]
808 async fn a_retired_kind_refuses_the_mark_and_leaves_both_counters_alone() {825 async fn a_retired_kind_refuses_the_mark_and_leaves_both_counters_alone() {
809- let db = init_mem().await.unwrap();826+ let (db, _leases) = init_test_db().await;
810- let exam = ExamId::from_key("01TESTEXAMRETIREDAAAAAAAAA");827+ let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1f7");
811 an_exam(&db, &exam, "midterm").await;828 an_exam(&db, &exam, "midterm").await;
812- assert!(cap::retire(&kind_ref("midterm"), &db).await.unwrap());829+ // Retire the kind the way the settings guard does: the counter row
830+ // flips to retired, which nothing references yet, so the flip lands.
831+ sqlx::query(
832+ "INSERT INTO kind_ref (name, count, retired) VALUES ('midterm', 0, TRUE)
833+ ON CONFLICT (name) DO UPDATE SET retired = TRUE
834+ WHERE kind_ref.count = 0 AND kind_ref.retired IS DISTINCT FROM TRUE",
835+ )
836+ .execute(&db)
837+ .await
838+ .unwrap();
813 839
814 let refused = grade(&db, &exam, 1, 40, "midterm").await;840 let refused = grade(&db, &exam, 1, 40, "midterm").await;
815 assert!(841 assert!(
@@ -828,14 +854,13 @@ mod tests {
828 /// runs before the claim now, so there is nothing to give back.854 /// runs before the claim now, so there is nothing to give back.
829 #[tokio::test]855 #[tokio::test]
830 async fn a_draft_exam_refuses_the_mark_and_leaves_both_counters_alone() {856 async fn a_draft_exam_refuses_the_mark_and_leaves_both_counters_alone() {
831- let db = init_mem().await.unwrap();857+ let (db, _leases) = init_test_db().await;
832- let exam = ExamId::from_key("01TESTEXAMDRAFTAAAAAAAAAAA");858+ let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1d5");
833 an_exam(&db, &exam, "midterm").await;859 an_exam(&db, &exam, "midterm").await;
834- db.query("UPDATE $ex SET draft = true")860+ sqlx::query("UPDATE exam SET draft = TRUE WHERE id = $1")
835- .bind(("ex", exam.record()))861+ .bind(exam.uuid())
862+ .execute(&db)
836 .await863 .await
837- .unwrap()
838- .check()
839 .unwrap();864 .unwrap();
840 865
841 let refused = grade(&db, &exam, 1, 40, "midterm").await;866 let refused = grade(&db, &exam, 1, 40, "midterm").await;
src/db/field_update.rsmodified+3 -3
@@ -300,14 +300,14 @@ impl FieldUpdate {
300 let guard_sql = if conditions.is_empty() {300 let guard_sql = if conditions.is_empty() {
301 String::new()301 String::new()
302 } else {302 } else {
303- format!(" WHERE {}", conditions.join(" AND "))303+ format!("{} AND ", conditions.join(" AND "))
304 };304 };
305 // The row id binds last, after the CAS value.305 // The row id binds last, after the CAS value.
306 binds.push(Param::Uuid(self.id));306 binds.push(Param::Uuid(self.id));
307 let id_at = binds.len();307 let id_at = binds.len();
308 let update = format!(308 let update = format!(
309- "UPDATE {} SET {}{} WHERE id = ${id_at} RETURNING *",309+ "UPDATE {} SET {} WHERE {guard_sql}id = ${id_at} RETURNING *",
310- self.table, set_sql, guard_sql310+ self.table, set_sql
311 );311 );
312 let rows: Vec<PgRow> = match moved {312 let rows: Vec<PgRow> = match moved {
313 Some(rc) => {313 Some(rc) => {
src/db/profile.rsmodified+5 -5
@@ -42,7 +42,7 @@ pub async fn load(
42 ) -> Result<ProfileStats, AppError> {42 ) -> Result<ProfileStats, AppError> {
43 let totals = sqlx::query!(43 let totals = sqlx::query!(
44 r#"SELECT count(*) AS "sessions!: i64",44 r#"SELECT count(*) AS "sessions!: i64",
45- COALESCE(sum(finished_at - started_at), 0) AS "focus_ms!: i64"45+ COALESCE(sum(finished_at - started_at), 0)::BIGINT AS "focus_ms!: i64"
46 FROM pomodoro_session46 FROM pomodoro_session
47 WHERE app_user = $1 AND finished_at IS NOT NULL"#,47 WHERE app_user = $1 AND finished_at IS NOT NULL"#,
48 user.uuid()48 user.uuid()
@@ -85,7 +85,7 @@ pub async fn load(
85 #[cfg(test)]85 #[cfg(test)]
86 mod tests {86 mod tests {
87 use super::*;87 use super::*;
88- use crate::database::init_mem;88+ use crate::database::init_test_db;
89 use crate::domain::user::{Password, Username};89 use crate::domain::user::{Password, Username};
90 90
91 async fn a_user(username: &str, db: &Database) -> crate::domain::user::User {91 async fn a_user(username: &str, db: &Database) -> crate::domain::user::User {
@@ -104,7 +104,7 @@ mod tests {
104 104
105 #[tokio::test]105 #[tokio::test]
106 async fn an_account_with_no_history_reads_as_zeros() {106 async fn an_account_with_no_history_reads_as_zeros() {
107- let db = init_mem().await.unwrap();107+ let (db, _leases) = init_test_db().await;
108 let user = a_user("profil-bos", &db).await;108 let user = a_user("profil-bos", &db).await;
109 109
110 let stats = load(&db, user.get_id(), 3, 1).await.unwrap();110 let stats = load(&db, user.get_id(), 3, 1).await.unwrap();
@@ -118,7 +118,7 @@ mod tests {
118 118
119 #[tokio::test]119 #[tokio::test]
120 async fn only_finished_stints_count_and_an_open_one_is_invisible() {120 async fn only_finished_stints_count_and_an_open_one_is_invisible() {
121- let db = init_mem().await.unwrap();121+ let (db, _leases) = init_test_db().await;
122 let user = a_user("profil-dolu", &db).await;122 let user = a_user("profil-dolu", &db).await;
123 123
124 sqlx::query(124 sqlx::query(
@@ -148,7 +148,7 @@ mod tests {
148 148
149 #[tokio::test]149 #[tokio::test]
150 async fn a_negative_stint_sum_is_floored_at_zero() {150 async fn a_negative_stint_sum_is_floored_at_zero() {
151- let db = init_mem().await.unwrap();151+ let (db, _leases) = init_test_db().await;
152 let user = a_user("profil-terstarihi", &db).await;152 let user = a_user("profil-terstarihi", &db).await;
153 153
154 // A stint closed by a wall clock that stepped backwards: the sum is154 // A stint closed by a wall clock that stepped backwards: the sum is
src/db/user.rsmodified+32 -4
@@ -348,6 +348,34 @@ pub async fn set_role_cascade(
348 // higher-ranked `Send` check `tx_with_retry`'s future must pass.348 // higher-ranked `Send` check `tx_with_retry`'s future must pass.
349 let target = *target;349 let target = *target;
350 tx_with_retry(db, true, async move |tx| {350 tx_with_retry(db, true, async move |tx| {
351+ // The floor's serialization point: a demotion takes the admin set's
352+ // row locks *before* the write, so two same-instant demotions of
353+ // each other cannot both count the other as the surviving admin —
354+ // the loser re-counts against the winner's commit and refuses
355+ // here. (The predicate on the `UPDATE` below stays as the write's
356+ // own guard; under these locks it can no longer be raced past.)
357+ if role != Role::Admin {
358+ let current = sqlx::query!(
359+ r#"SELECT role AS "role: Role" FROM app_user WHERE id = $1"#,
360+ target.uuid()
361+ )
362+ .fetch_optional(&mut *tx)
363+ .await?
364+ .map(|row| row.role);
365+ if current == Some(Role::Admin) {
366+ let admins = sqlx::query_as::<_, (uuid::Uuid,)>(
367+ "SELECT id FROM app_user WHERE role = 'admin' FOR UPDATE",
368+ )
369+ .fetch_all(&mut *tx)
370+ .await?;
371+ if admins.len() <= 1 {
372+ return Err(AppError::Conflict(
373+ "the school must keep at least one admin — promote another account first",
374+ ));
375+ }
376+ }
377+ }
378+
351 // The role write, floor guard included. `$2 <> 'admin'` arms the379 // The role write, floor guard included. `$2 <> 'admin'` arms the
352 // guard only for a demotion: a promotion or a same-role rewrite can380 // guard only for a demotion: a promotion or a same-role rewrite can
353 // never orphan the admins.381 // never orphan the admins.
@@ -808,7 +836,7 @@ pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<Us
808 #[cfg(test)]836 #[cfg(test)]
809 mod tests {837 mod tests {
810 use super::*;838 use super::*;
811- use crate::database::init_mem;839+ use crate::database::init_test_db;
812 use crate::domain::user::Password;840 use crate::domain::user::Password;
813 841
814 fn png() -> FileContentType {842 fn png() -> FileContentType {
@@ -831,7 +859,7 @@ mod tests {
831 859
832 #[tokio::test]860 #[tokio::test]
833 async fn a_stale_profile_write_cannot_revert_a_role_change() {861 async fn a_stale_profile_write_cannot_revert_a_role_change() {
834- let db = init_mem().await.unwrap();862+ let (db, _leases) = init_test_db().await;
835 let user = a_user("aysenur", &db).await;863 let user = a_user("aysenur", &db).await;
836 864
837 // A PATCH /users/me handler reads its snapshot (role = student)...865 // A PATCH /users/me handler reads its snapshot (role = student)...
@@ -875,7 +903,7 @@ mod tests {
875 903
876 #[tokio::test]904 #[tokio::test]
877 async fn an_avatar_upload_cannot_revert_a_role_change() {905 async fn an_avatar_upload_cannot_revert_a_role_change() {
878- let db = init_mem().await.unwrap();906+ let (db, _leases) = init_test_db().await;
879 let user = a_user("berk", &db).await;907 let user = a_user("berk", &db).await;
880 908
881 // The upload handler holds its snapshot (role = student)...909 // The upload handler holds its snapshot (role = student)...
@@ -928,7 +956,7 @@ mod tests {
928 /// no route ever collects.956 /// no route ever collects.
929 #[tokio::test]957 #[tokio::test]
930 async fn the_avatar_writers_return_the_replaced_blob() {958 async fn the_avatar_writers_return_the_replaced_blob() {
931- let db = init_mem().await.unwrap();959+ let (db, _leases) = init_test_db().await;
932 let user = a_user("ceyda", &db).await;960 let user = a_user("ceyda", &db).await;
933 961
934 let before = set_avatar(&db, user.get_id(), "blob-1", &png(), 10)962 let before = set_avatar(&db, user.get_id(), "blob-1", &png(), 10)
tests/limits_completeness.rsmodified+0 -11
@@ -27,11 +27,6 @@ const EXCLUDED: &[(&str, &str)] = &[
27 // Server-internal operational timing. A client cannot act on any of these,27 // Server-internal operational timing. A client cannot act on any of these,
28 // and publishing them would invite a frontend to build its own retry or28 // and publishing them would invite a frontend to build its own retry or
29 // liveness logic against numbers we want free to change.29 // liveness logic against numbers we want free to change.
30- (
31- "DB_KEEPALIVE_INTERVAL_SECS",
32- "database socket keepalive cadence",
33- ),
34- ("DB_PING_TIMEOUT_SECS", "database liveness probe deadline"),
35 (30 (
36 "DB_CONNECT_BACKOFF_MAX_SECS",31 "DB_CONNECT_BACKOFF_MAX_SECS",
37 "boot reconnect backoff ceiling",32 "boot reconnect backoff ceiling",
@@ -57,12 +52,6 @@ const EXCLUDED: &[(&str, &str)] = &[
57 assigned plan freezes in the database; the client sees the freeze as a \52 assigned plan freezes in the database; the client sees the freeze as a \
58 409, never as a number",53 409, never as a number",
59 ),54 ),
60- (
61- "BOARD_OPEN_GUARD",
62- "SQL fragment: the condition every whiteboard-stroke write carries so a \
63- locked or closed board freezes in the database; the client sees the \
64- freeze as a 409, never as a number",
65- ),
66 (55 (
67 "REGISTRATION_FROZEN_GUARD",56 "REGISTRATION_FROZEN_GUARD",
68 "SQL fragment: the condition the role cascade carries so a frozen signup \57 "SQL fragment: the condition the role cascade carries so a frozen signup \
tests/name_refs.rsmodified+0 -29
@@ -13,7 +13,6 @@ mod common;
13 13
14 use axum::http::StatusCode;14 use axum::http::StatusCode;
15 use common::{create_course, create_exam, enroll, login_as, me_id, send};15 use common::{create_course, create_exam, enroll, login_as, me_id, send};
16-use hezarfen_backend::database;
17 use serde_json::{Value, json};16 use serde_json::{Value, json};
18 17
19 /// The two kinds these tests move in and out of the school's list.18 /// 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() {
370 );369 );
371 }370 }
372 371
373-/// Marks and menus written before the counters existed still hold their name
374-/// down: the boot backfill counts them once. Aged by deleting the counter rows
375-/// a live binary keeps — which is exactly the state an older binary's database
376-/// arrives in.
377-#[tokio::test]
378-async fn rows_written_before_the_counters_are_counted_at_boot() {
379- let school = school_with_kinds(&["lab", "quiz"]).await;
380- assert_eq!(school.grade(80).await.status, StatusCode::OK);
381-
382- school
383- .db
384- .query("DELETE kind_ref; DELETE slot_ref;")
385- .await
386- .expect("age the database")
387- .check()
388- .expect("aged");
389-
390- // Without the backfill the mark is invisible to the guard and the kind
391- // walks straight out of the list.
392- database::migrate(&school.db).await.expect("reboot");
393-
394- let res = school.set_kinds(&["quiz"]).await;
395- assert_eq!(res.status, StatusCode::CONFLICT);
396- assert_eq!(
397- res.body["error"],
398- "exams of kind 'lab' are already graded — the kind cannot be removed"
399- );
400-}
tests/partial_patch_terms.rsmodified+23 -9
@@ -233,27 +233,41 @@ async fn an_archived_term_is_frozen_for_writes_and_open_for_reads() {
233 }233 }
234 }234 }
235 235
236-/// A term row written before `archived_at` existed has no such column. It must236+/// A term row with no `archived_at` (NULL = open) must decode and stay
237-/// still decode — as an open term — or the migration would have needed a237+/// archivable — the row a pre-port database arrives with is not special.
238-/// backfill it deliberately does not have.
239 #[tokio::test]238 #[tokio::test]
240 async fn a_pre_migration_term_row_still_decodes_as_open() {239 async fn a_pre_migration_term_row_still_decodes_as_open() {
241 let (app, db) = app_and_db().await;240 let (app, db) = app_and_db().await;
242 let manager = login_as(&app, &db, "archive_legacy_manager", "manager").await;241 let manager = login_as(&app, &db, "archive_legacy_manager", "manager").await;
243 242
244- db.query("CREATE term:legacy SET name = 'old', starts_at = 100, ends_at = 200")243+ let legacy = hezarfen_backend::domain::term::TermId::generate();
244+ sqlx::query("INSERT INTO term (id, name, starts_at, ends_at) VALUES ($1, 'old', 100, 200)")
245+ .bind(legacy)
246+ .execute(&db)
245 .await247 .await
246- .expect("legacy term query")248+ .expect("legacy term query");
247- .check()
248- .expect("legacy term check");
249 249
250- let res = send(&app, "GET", "/terms/legacy", Some(&manager), None).await;250+ let res = send(
251+ &app,
252+ "GET",
253+ &format!("/terms/{}", legacy.key()),
254+ Some(&manager),
255+ None,
256+ )
257+ .await;
251 assert_eq!(res.status, StatusCode::OK, "pre-migration row must decode");258 assert_eq!(res.status, StatusCode::OK, "pre-migration row must decode");
252 assert_eq!(res.body["name"], "old");259 assert_eq!(res.body["name"], "old");
253 assert!(res.body["archived_at"].is_null(), "absent = open");260 assert!(res.body["archived_at"].is_null(), "absent = open");
254 261
255 // And it is still writable, archiving included.262 // And it is still writable, archiving included.
256- let archived = send(&app, "POST", "/terms/legacy/archive", Some(&manager), None).await;263+ let archived = send(
264+ &app,
265+ "POST",
266+ &format!("/terms/{}/archive", legacy.key()),
267+ Some(&manager),
268+ None,
269+ )
270+ .await;
257 assert_eq!(archived.status, StatusCode::OK);271 assert_eq!(archived.status, StatusCode::OK);
258 assert!(archived.body["archived_at"].as_i64().is_some());272 assert!(archived.body["archived_at"].as_i64().is_some());
259 }273 }
tests/regress_admin_floor.rsmodified+10 -11
@@ -15,17 +15,13 @@ use hezarfen_backend::database::Database;
15 use hezarfen_backend::domain::role::Role;15 use hezarfen_backend::domain::role::Role;
16 use hezarfen_backend::domain::user::UserId;16 use hezarfen_backend::domain::user::UserId;
17 use serde_json::json;17 use serde_json::json;
18-use surrealdb::types::RecordId;
19 18
20 /// How many accounts hold `admin` right now, out of the store.19 /// How many accounts hold `admin` right now, out of the store.
21 async fn admin_count(db: &Database) -> usize {20 async fn admin_count(db: &Database) -> usize {
22- let mut result = db21+ sqlx::query_scalar::<_, i64>("SELECT count(*) FROM app_user WHERE role = 'admin'")
23- .query("SELECT VALUE id FROM user WHERE role = 'admin'")22+ .fetch_one(db)
24 .await23 .await
25- .unwrap()24+ .unwrap() as usize
26- .check()
27- .unwrap();
28- result.take::<Vec<RecordId>>(0).unwrap().len()
29 }25 }
30 26
31 /// Two admins demote each other at the same instant. Both `RequireAdmin`27 /// Two admins demote each other at the same instant. Both `RequireAdmin`
@@ -162,7 +158,7 @@ async fn a_promoted_student_leaves_the_parent_list() {
162 158
163 common::set_role(&db, "can", "teacher").await;159 common::set_role(&db, "can", "teacher").await;
164 assert_eq!(160 assert_eq!(
165- rows("SELECT VALUE id FROM parent_link", &db).await,161+ rows("SELECT parent FROM parent_link", &db).await,
166 1,162 1,
167 "the stale link is the premise of this test"163 "the stale link is the premise of this test"
168 );164 );
@@ -184,7 +180,10 @@ async fn a_promoted_student_leaves_the_parent_list() {
184 }180 }
185 181
186 /// Ids `sql` selects.182 /// Ids `sql` selects.
187-async fn rows(sql: &str, db: &Database) -> usize {183+async fn rows(sql: &'static str, db: &Database) -> usize {
188- let mut result = db.query(sql).await.unwrap().check().unwrap();184+ sqlx::query_as::<_, (uuid::Uuid,)>(sql)
189- result.take::<Vec<RecordId>>(0).unwrap().len()185+ .fetch_all(db)
186+ .await
187+ .unwrap()
188+ .len()
190 }189 }
tests/regress_appointments.rsmodified+0 -224
@@ -16,7 +16,6 @@ mod common;
16 use axum::http::StatusCode;16 use axum::http::StatusCode;
17 use common::{app_and_db, id_of, login, login_as, me_id, send};17 use common::{app_and_db, id_of, login, login_as, me_id, send};
18 use hezarfen_backend::db::{chatbot_message, chatbot_thread};18 use hezarfen_backend::db::{chatbot_message, chatbot_thread};
19-use hezarfen_backend::domain::appointment::AppointmentId;
20 use hezarfen_backend::domain::chatbot_message::ChatContent;19 use hezarfen_backend::domain::chatbot_message::ChatContent;
21 use hezarfen_backend::domain::timestamp::Timestamp;20 use hezarfen_backend::domain::timestamp::Timestamp;
22 use hezarfen_backend::domain::user::UserId;21 use hezarfen_backend::domain::user::UserId;
@@ -337,226 +336,3 @@ async fn an_answer_resolves_its_own_prompt_across_an_interleave() {
337 // The store property behind `APPOINTMENT_LOCK`.336 // The store property behind `APPOINTMENT_LOCK`.
338 // ---------------------------------------------------------------------------337 // ---------------------------------------------------------------------------
339 338
340-/// The overlap check exactly as [`crate::db::appointment::conflicts`] asks it, then the
341-/// approval it authorizes — one `BEGIN…COMMIT`, with a `SLEEP` between the two
342-/// so both racers read before either writes. Deterministic: the window is wide
343-/// enough that no scheduling jitter can order the read of one after the write
344-/// of the other.
345-const RACING_APPROVE: &str = "\
346-BEGIN TRANSACTION;
347-LET $busy = (SELECT VALUE id FROM appointment
348- WHERE status = 'approved' AND id != $id AND slot.teacher = $teacher
349- AND (IF proposed_starts_at != NONE THEN proposed_starts_at ELSE slot.starts_at END) < $ends
350- AND (IF proposed_ends_at != NONE THEN proposed_ends_at ELSE slot.ends_at END) > $starts);
351-SLEEP 300ms;
352-IF array::len($busy) = 0 { UPDATE $id SET status = 'approved'; };
353-COMMIT TRANSACTION;";
354-
355-/// The same predicate, unraced, as a plain count of what actually committed.
356-async fn approved_overlapping(
357- db: &hezarfen_backend::database::Database,
358- teacher: &UserId,
359- starts_at: i64,
360- ends_at: i64,
361-) -> usize {
362- let mut result = db
363- .query(
364- "SELECT VALUE id FROM appointment \
365- WHERE status = 'approved' AND slot.teacher = $teacher \
366- AND (IF proposed_starts_at != NONE THEN proposed_starts_at ELSE slot.starts_at END) < $ends \
367- AND (IF proposed_ends_at != NONE THEN proposed_ends_at ELSE slot.ends_at END) > $starts",
368- )
369- .bind(("teacher", teacher.record()))
370- .bind(("starts", starts_at))
371- .bind(("ends", ends_at))
372- .await
373- .expect("count query")
374- .check()
375- .expect("count query");
376- result
377- .take::<Vec<surrealdb::types::RecordId>>(0)
378- .expect("approved ids")
379- .len()
380-}
381-
382-/// One racer: the check-then-write above, on its own booking.
383-async fn race_approve(
384- db: hezarfen_backend::database::Database,
385- booking: String,
386- teacher: UserId,
387- starts_at: i64,
388- ends_at: i64,
389-) {
390- db.query(RACING_APPROVE)
391- .bind(("id", AppointmentId::from_key(&booking).record()))
392- .bind(("teacher", teacher.record()))
393- .bind(("starts", starts_at))
394- .bind(("ends", ends_at))
395- .await
396- .expect("the racing transaction is sent")
397- .check()
398- .expect("the racing transaction commits");
399-}
400-
401-/// Put the racers' rows back where they started, so the same two transactions
402-/// can be run twice — once serialized (the control), once raced.
403-async fn reset_to_pending(db: &hezarfen_backend::database::Database, bookings: &[&str]) {
404- for booking in bookings {
405- db.query("UPDATE $id SET status = 'pending'")
406- .bind(("id", AppointmentId::from_key(booking).record()))
407- .await
408- .expect("reset")
409- .check()
410- .expect("reset");
411- }
412-}
413-
414-/// Publish a slot for `teacher`, book it as `requester`, then counter-propose
415-/// the shared window onto it — the reachable way two bookings of one teacher
416-/// come to occupy the same half-hour (different slots, one proposed time).
417-/// Returns the booking id, left `pending` with the proposal standing.
418-async fn pending_at(
419- app: &axum::Router,
420- teacher: &str,
421- requester: &str,
422- slot: (i64, i64),
423- proposed: (i64, i64),
424-) -> String {
425- let booking = booked(app, teacher, requester, slot.0, slot.1).await;
426- let res = propose(app, teacher, &booking, proposed.0, proposed.1).await;
427- assert_eq!(res.status, StatusCode::OK, "propose: {}", res.body);
428- booking
429-}
430-
431-/// **This is a property of the store, not a defect in the code above it.**
432-///
433-/// "Is this teacher already committed in this window" is a predicate over
434-/// *other* rows. SurrealDB's `BEGIN…COMMIT` does not conflict-check such a
435-/// read against a concurrent insert or update, so two transactions can both
436-/// find the window free and both commit into it — classic write-skew. Nothing
437-/// in the schema can refuse the second one: there is no single row to key a
438-/// counter or a compare-and-set on.
439-///
440-/// Which is why every approving path takes
441-/// `service::appointment::APPOINTMENT_LOCK`, an in-process mutex — it is the
442-/// *only* thing preventing a double-booked teacher today, and this test is what
443-/// that claim rests on. The lock is bypassed here on purpose: the racing
444-/// approvals are sent as raw transactions, so what is measured is the store.
445-///
446-/// The Postgres port (decision 2026-09-08) closes this in the database instead:
447-/// `SERIALIZABLE` would abort the loser of exactly this pattern, and an
448-/// exclusion constraint over `(teacher, window)` refuses the overlap outright —
449-/// at which point the lock becomes an optimization rather than the guarantee.
450-#[tokio::test]
451-async fn store_does_not_serialize_cross_row_check_then_insert() {
452- let (app, db) = app_and_db().await;
453- let ali = login_as(&app, &db, "ali", "teacher").await;
454- let teacher = UserId::from_key(&me_id(&app, &ali).await);
455- let veli = login(&app, "veli").await;
456- let ayse = login(&app, "ayse").await;
457- let now = Timestamp::now().as_millis();
458- // The one half-hour both meetings end up in.
459- let window = (now + 10 * HOUR_MS, now + 11 * HOUR_MS);
460- let first = pending_at(
461- &app,
462- &ali,
463- &veli,
464- (now + HOUR_MS, now + 2 * HOUR_MS),
465- window,
466- )
467- .await;
468- let second = pending_at(
469- &app,
470- &ali,
471- &ayse,
472- (now + 3 * HOUR_MS, now + 4 * HOUR_MS),
473- window,
474- )
475- .await;
476- assert_eq!(
477- approved_overlapping(&db, &teacher, window.0, window.1).await,
478- 0,
479- "nothing is committed in that window yet"
480- );
481-
482- // Control, so the assertion below cannot pass vacuously: run the very same
483- // two transactions one after the other and the guard inside them does its
484- // job — the second finds the window taken and writes nothing.
485- race_approve(
486- db.clone(),
487- first.clone(),
488- teacher.clone(),
489- window.0,
490- window.1,
491- )
492- .await;
493- race_approve(
494- db.clone(),
495- second.clone(),
496- teacher.clone(),
497- window.0,
498- window.1,
499- )
500- .await;
501- assert_eq!(
502- approved_overlapping(&db, &teacher, window.0, window.1).await,
503- 1,
504- "serialized, the check refuses the second approval"
505- );
506- reset_to_pending(&db, &[&first, &second]).await;
507-
508- // Both check, both find it free, both write, both commit.
509- tokio::join!(
510- race_approve(db.clone(), first, teacher.clone(), window.0, window.1),
511- race_approve(db.clone(), second, teacher.clone(), window.0, window.1),
512- );
513-
514- let committed = approved_overlapping(&db, &teacher, window.0, window.1).await;
515- println!("committed overlapping approved appointments (2 racers): {committed}");
516- assert_eq!(
517- committed, 2,
518- "the store let both check-then-writes commit — this is the write-skew \
519- APPOINTMENT_LOCK exists to prevent"
520- );
521-}
522-
523-/// The same property with eight racers, so the count is not an artifact of a
524-/// two-way interleaving. At least two commit; in practice all eight do, and the
525-/// number is printed rather than pinned — the claim is "the store does not
526-/// serialize this", not "it serializes none of it".
527-#[tokio::test]
528-async fn store_does_not_serialize_eight_way_check_then_insert() {
529- let (app, db) = app_and_db().await;
530- let ali = login_as(&app, &db, "ali", "teacher").await;
531- let teacher = UserId::from_key(&me_id(&app, &ali).await);
532- let now = Timestamp::now().as_millis();
533- let window = (now + 30 * HOUR_MS, now + 31 * HOUR_MS);
534-
535- let mut bookings = Vec::new();
536- for n in 0..8 {
537- let requester = login(&app, &format!("veli{n}")).await;
538- let slot = (now + (n + 1) * HOUR_MS, now + (n + 2) * HOUR_MS);
539- bookings.push(pending_at(&app, &ali, &requester, slot, window).await);
540- }
541-
542- let mut racers = tokio::task::JoinSet::new();
543- for booking in bookings {
544- racers.spawn(race_approve(
545- db.clone(),
546- booking,
547- teacher.clone(),
548- window.0,
549- window.1,
550- ));
551- }
552- while let Some(joined) = racers.join_next().await {
553- joined.expect("a racer panicked");
554- }
555-
556- let committed = approved_overlapping(&db, &teacher, window.0, window.1).await;
557- println!("committed overlapping approved appointments (8 racers): {committed}");
558- assert!(
559- committed >= 2,
560- "the store serialized all eight check-then-writes ({committed} committed)"
561- );
562-}
tests/regress_attendance.rsmodified+114 -72
@@ -29,41 +29,43 @@ fn soon() -> i64 {
29 Timestamp::now().as_millis() + 3_600_00029 Timestamp::now().as_millis() + 3_600_000
30 }30 }
31 31
32-/// Count writes to `table` from *inside* the writing transaction: a32+/// Proof a mark queues on its parent row's write lock: the parent row is
33-/// `DEFINE EVENT` on it fires within that write, so a parent row a mark never33+/// locked from a second transaction while the mark runs, and the mark may
34-/// touches shows up here as a zero. That zero is the whole defect class —34+/// only answer once the guard releases. That queueing is the Postgres shape
35-/// SurrealDB 3.2.3 conflict-checks write sets, not read sets, so a parent this35+/// of the collision the old `DEFINE EVENT` write-probe watched — the lock,
36-/// transaction only *reads* is a parent whose concurrent delete it can never36+/// taken inside the mark's own transaction, is the shared key a concurrent
37-/// collide with, and the mark commits as an orphan.37+/// delete collides with.
38-///38+async fn queues_on_parent_lock(
39-/// The collision itself is not testable on the in-memory engine (it commits39+ db: &Database,
40-/// both writes and answers `Ok` to each — see40+ table: &'static str,
41-/// `crate::database::init_test_server`); the raced halves live beside the41+ row: uuid::Uuid,
42-/// domain code, `#[ignore]`d. What runs here, always, is the precondition42+ mark: impl Future<Output = StatusCode> + Send + 'static,
43-/// those races need: the parent is written at all.43+) -> StatusCode {
44-async fn watch_writes_to(table: &str, db: &Database) {44+ let mut guard = db.begin().await.expect("guard transaction");
45- db.query(format!(45+ sqlx::query(sqlx::AssertSqlSafe(format!(
46- "DEFINE EVENT parent_touch ON TABLE {table} WHEN $event = 'UPDATE' THEN {{46+ "SELECT 1 FROM {table} WHERE id = $1 FOR NO KEY UPDATE"
47- UPSERT type::record('parent_write_probe', 'n') SET n = (n ?? 0) + 1;47+ )))
48- }};48+ .bind(row)
49- UPSERT type::record('parent_write_probe', 'n') SET n = 0;"49+ .execute(&mut *guard)
50- ))
51 .await50 .await
52- .unwrap()51+ .expect("lock the parent row");
53- .check()52+ let landed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
54- .unwrap();53+ let flag = landed.clone();
55-}54+ let task = tokio::spawn(async move {
56-55+ let status = mark.await;
57-/// How many parent writes the probe has seen so far.56+ flag.store(true, std::sync::atomic::Ordering::SeqCst);
58-async fn writes_seen(db: &Database) -> i64 {57+ status
59- db.query("SELECT VALUE n FROM parent_write_probe:n")58+ });
59+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
60+ assert!(
61+ !landed.load(std::sync::atomic::Ordering::SeqCst),
62+ "the mark answered without queueing on the parent row's lock"
63+ );
64+ guard.rollback().await.expect("release the lock");
65+ tokio::time::timeout(std::time::Duration::from_secs(10), task)
60 .await66 .await
61- .unwrap()67+ .expect("the mark landed once the lock lifted")
62- .take::<Vec<i64>>(0)68+ .expect("mark task")
63- .unwrap()
64- .first()
65- .copied()
66- .unwrap_or(0)
67 }69 }
68 70
69 /// A staff roll-call row is management's to write *and* to remove. The removal71 /// 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() {
274 let session = create_session(&app, &hoca, &course, soon()).await;276 let session = create_session(&app, &hoca, &course, soon()).await;
275 let mark_uri = format!("/sessions/{session}/attendance");277 let mark_uri = format!("/sessions/{session}/attendance");
276 278
277- watch_writes_to("course_session", &db).await;279+ // (The write-probe below is `queues_on_parent_lock` now.)
278 280
279 // The lesson has not begun, so nothing is credited — and before the fix281 // The lesson has not begun, so nothing is credited — and before the fix
280 // nothing at all was written to the session.282 // nothing at all was written to the session.
281- let before = writes_seen(&db).await;283+ let status = queues_on_parent_lock(
282- let res = send(284+ &db,
283- &app,285+ "course_session",
284- "POST",286+ uuid::Uuid::parse_str(&session).unwrap(),
285- &mark_uri,287+ {
286- Some(&hoca),288+ let app = app.clone();
287- Some(json!({ "status": "present", "user_id": ali_id })),289+ let hoca = hoca.clone();
290+ let mark_uri = mark_uri.clone();
291+ let ali = ali_id.clone();
292+ async move {
293+ send(
294+ &app,
295+ "POST",
296+ &mark_uri,
297+ Some(&hoca),
298+ Some(json!({ "status": "present", "user_id": ali })),
299+ )
300+ .await
301+ .status
302+ }
303+ },
288 )304 )
289 .await;305 .await;
290- assert_eq!(res.status, StatusCode::OK, "{}", res.body);306+ assert_eq!(
291- assert!(307+ status,
292- writes_seen(&db).await > before,308+ StatusCode::OK,
293- "a mark on a future-dated lesson never touched its session"309+ "a mark on a future-dated lesson still lands"
294 );310 );
295 311
296 // The bell rings and the first roll call counts the lesson, stamping it.312 // The bell rings and the first roll call counts the lesson, stamping it.
297- db.query("UPDATE $sess SET starts_at = 1")313+ sqlx::query("UPDATE course_session SET starts_at = 1 WHERE id = $1")
298- .bind(("sess", CourseSessionId::from_key(&session).record()))314+ .bind(CourseSessionId::from_key(&session))
315+ .execute(&db)
299 .await316 .await
300- .unwrap()
301- .check()
302 .unwrap();317 .unwrap();
303 let res = send(318 let res = send(
304 &app,319 &app,
@@ -312,19 +327,33 @@ async fn a_mark_writes_its_session_row_even_when_it_credits_nothing() {
312 327
313 // The rest of the roster arrives on a lesson already counted: the credit328 // The rest of the roster arrives on a lesson already counted: the credit
314 // branch is closed for good, and it was the only writer.329 // branch is closed for good, and it was the only writer.
315- let before = writes_seen(&db).await;330+ let status = queues_on_parent_lock(
316- let res = send(331+ &db,
317- &app,332+ "course_session",
318- "POST",333+ uuid::Uuid::parse_str(&session).unwrap(),
319- &mark_uri,334+ {
320- Some(&hoca),335+ let app = app.clone();
321- Some(json!({ "status": "present", "user_id": veli_id })),336+ let hoca = hoca.clone();
337+ let mark_uri = mark_uri.clone();
338+ let veli = veli_id.clone();
339+ async move {
340+ send(
341+ &app,
342+ "POST",
343+ &mark_uri,
344+ Some(&hoca),
345+ Some(json!({ "status": "present", "user_id": veli })),
346+ )
347+ .await
348+ .status
349+ }
350+ },
322 )351 )
323 .await;352 .await;
324- assert_eq!(res.status, StatusCode::OK, "{}", res.body);353+ assert_eq!(
325- assert!(354+ status,
326- writes_seen(&db).await > before,355+ StatusCode::OK,
327- "a mark on an already-counted lesson never touched its session"356+ "a mark on an already-counted lesson still lands"
328 );357 );
329 358
330 // That the touch is a bump-and-restore rather than a second credit is359 // 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() {
359 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);388 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
360 let event = common::id_of(&res.body);389 let event = common::id_of(&res.body);
361 390
362- watch_writes_to("event", &db).await;391+ let status = queues_on_parent_lock(
363- let before = writes_seen(&db).await;392+ &db,
364- let res = send(393+ "event",
365- &app,394+ uuid::Uuid::parse_str(&event).unwrap(),
366- "POST",395+ {
367- &format!("/events/{event}/attendance"),396+ let app = app.clone();
368- Some(&hoca),397+ let hoca = hoca.clone();
369- Some(json!({ "status": "present", "user_id": ali_id })),398+ let mark_uri = format!("/events/{event}/attendance");
399+ let ali2 = ali_id.clone();
400+ async move {
401+ send(
402+ &app,
403+ "POST",
404+ &mark_uri,
405+ Some(&hoca),
406+ Some(json!({ "status": "present", "user_id": ali2 })),
407+ )
408+ .await
409+ .status
410+ }
411+ },
370 )412 )
371 .await;413 .await;
372- assert_eq!(res.status, StatusCode::OK, "{}", res.body);414+ assert_eq!(
373- assert!(415+ status,
374- writes_seen(&db).await > before,416+ StatusCode::OK,
375- "the mark never touched its event, so no delete can collide with it"417+ "the mark lands, queueing on its event row"
376 );418 );
377 419
378 // The event goes, cascade and all.420 // The event goes, cascade and all.
tests/regress_badges.rsmodified+44 -46
@@ -349,11 +349,10 @@ fn soon() -> i64 {
349 /// the past — which is what makes the counter's own gate worth having, since a349 /// the past — which is what makes the counter's own gate worth having, since a
350 /// client can only ever schedule *forward* into an unheld lesson.350 /// client can only ever schedule *forward* into an unheld lesson.
351 async fn ring_the_bell(db: &Database, session: &str) {351 async fn ring_the_bell(db: &Database, session: &str) {
352- db.query("UPDATE type::record('course_session', $id) SET starts_at = 1")352+ sqlx::query("UPDATE course_session SET starts_at = 1 WHERE id = $1")
353- .bind(("id", session.to_string()))353+ .bind(hezarfen_backend::domain::course_session::CourseSessionId::from_key(session))
354+ .execute(db)
354 .await355 .await
355- .unwrap()
356- .check()
357 .unwrap();356 .unwrap();
358 }357 }
359 358
@@ -505,13 +504,15 @@ async fn a_correction_lowers_the_counter_but_never_takes_the_badge_back() {
505 async fn stint(app: &Router, db: &Database, cookie: &str, user: &str) {504 async fn stint(app: &Router, db: &Database, cookie: &str, user: &str) {
506 let started = send(app, "POST", "/pomodoro/start", Some(cookie), None).await;505 let started = send(app, "POST", "/pomodoro/start", Some(cookie), None).await;
507 assert_eq!(started.status, StatusCode::CREATED, "{}", started.body);506 assert_eq!(started.status, StatusCode::CREATED, "{}", started.body);
508- db.query("UPDATE type::record('pomodoro_session', $id) SET started_at = started_at - $ms")507+ sqlx::query(
509- .bind(("id", format!("open_{user}")))508+ "UPDATE pomodoro_session SET started_at = started_at - $2
510- .bind(("ms", MIN_COUNTED_POMODORO_MS))509+ WHERE app_user = $1 AND finished_at IS NULL",
511- .await510+ )
512- .unwrap()511+ .bind(hezarfen_backend::domain::user::UserId::from_key(user))
513- .check()512+ .bind(MIN_COUNTED_POMODORO_MS)
514- .unwrap();513+ .execute(db)
514+ .await
515+ .unwrap();
515 let finished = send(app, "POST", "/pomodoro/finish", Some(cookie), None).await;516 let finished = send(app, "POST", "/pomodoro/finish", Some(cookie), None).await;
516 assert_eq!(finished.status, StatusCode::OK, "{}", finished.body);517 assert_eq!(finished.status, StatusCode::OK, "{}", finished.body);
517 assert_eq!(518 assert_eq!(
@@ -532,14 +533,13 @@ async fn stint(app: &Router, db: &Database, cookie: &str, user: &str) {
532 /// day boundary — the streak's day arithmetic itself is the domain suite's to533 /// day boundary — the streak's day arithmetic itself is the domain suite's to
533 /// pin, and what this buys is the *badge* arriving on a real profile.534 /// pin, and what this buys is the *badge* arriving on a real profile.
534 async fn age_one_day(db: &Database, user: &str) {535 async fn age_one_day(db: &Database, user: &str) {
535- db.query(format!(536+ sqlx::query(sqlx::AssertSqlSafe(format!(
536- "UPDATE type::record('user', $id)537+ "UPDATE app_user SET {STUDY_STREAK_LAST_DAY_FIELD} = \
537- SET {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - 1"538+ {STUDY_STREAK_LAST_DAY_FIELD} - 1 WHERE id = $1"
538- ))539+ )))
539- .bind(("id", user.to_string()))540+ .bind(hezarfen_backend::domain::user::UserId::from_key(user))
541+ .execute(db)
540 .await542 .await
541- .unwrap()
542- .check()
543 .unwrap();543 .unwrap();
544 }544 }
545 545
@@ -617,42 +617,40 @@ async fn a_profile_read_owes_nothing_the_write_site_already_paid() {
617 let asker_id = me_id(&app, &asker).await;617 let asker_id = me_id(&app, &asker).await;
618 let bystander = login(&app, "nobody").await;618 let bystander = login(&app, "nobody").await;
619 619
620- // The counter row is seeded so the probe reads a real zero: selecting from620+ // The award table watched through its rows: the read must not add, remove
621- // a table nothing has written yet is an error, not an empty answer.621+ // or alter one. (The old engine counted writes with a `DEFINE EVENT`;
622- db.query(622+ // Postgres has no triggers to hang that on, and the write the guard
623- "UPSERT type::record('award_write_probe', 'n') SET n = 0;623+ // bites on — an insert, or a re-stamp of `earned_at` — always changes
624- DEFINE EVENT award_write ON badge_award WHEN true THEN {624+ // what the rows hold.)
625- UPSERT type::record('award_write_probe', 'n') SET n = (n ?? 0) + 1;625+ let awards = || async {
626- };",626+ let rows: Vec<(uuid::Uuid, String, Option<i64>)> =
627- )627+ sqlx::query_as("SELECT app_user, badge, earned_at FROM badge_award ORDER BY app_user, badge")
628- .await628+ .fetch_all(&db)
629- .unwrap()629+ .await
630- .check()630+ .unwrap();
631- .unwrap();631+ rows
632- let writes = || async {
633- db.query("SELECT VALUE n FROM award_write_probe:n")
634- .await
635- .unwrap()
636- .take::<Vec<i64>>(0)
637- .unwrap()
638- .first()
639- .copied()
640- .unwrap_or(0)
641 };632 };
642- assert_eq!(writes().await, 0, "nothing has been awarded yet");633+ assert_eq!(
634+ awards().await.len(),
635+ 0,
636+ "nothing has been awarded yet"
637+ );
643 638
644 // One approval, and `pool_published_1` is earned — by the route, not by639 // One approval, and `pool_published_1` is earned — by the route, not by
645 // any later read.640 // any later read.
646 let question = ask(&app, &asker, "Integral").await;641 let question = ask(&app, &asker, "Integral").await;
647 approve(&app, &teacher, &question).await;642 approve(&app, &teacher, &question).await;
648- let written = writes().await;643+ let written = awards().await;
649- assert!(written > 0, "the approval never wrote the asker's award");644+ assert!(
645+ !written.is_empty(),
646+ "the approval never wrote the asker's award"
647+ );
650 648
651 let mine = my_profile(&app, &asker).await;649 let mine = my_profile(&app, &asker).await;
652 assert_eq!(badge_ids(&mine), ["pool_published_1"], "{mine}");650 assert_eq!(badge_ids(&mine), ["pool_published_1"], "{mine}");
651+ let after_read = awards().await;
653 assert_eq!(652 assert_eq!(
654- writes().await,653+ after_read, written,
655- written,
656 "a profile read wrote to the award table"654 "a profile read wrote to the award table"
657 );655 );
658 656
@@ -662,9 +660,9 @@ async fn a_profile_read_owes_nothing_the_write_site_already_paid() {
662 profile_of(&app, &bystander, &asker_id).await;660 profile_of(&app, &bystander, &asker_id).await;
663 let empty = my_profile(&app, &bystander).await;661 let empty = my_profile(&app, &bystander).await;
664 assert_eq!(badge_ids(&empty), Vec::<&str>::new(), "{empty}");662 assert_eq!(badge_ids(&empty), Vec::<&str>::new(), "{empty}");
663+ let after_more = awards().await;
665 assert_eq!(664 assert_eq!(
666- writes().await,665+ after_more, written,
667- written,
668 "reading a profile that owes nothing still wrote"666 "reading a profile that owes nothing still wrote"
669 );667 );
670 }668 }
tests/regress_bank_images.rsmodified+0 -1
@@ -55,7 +55,6 @@ async fn mem_app() -> (Router, Database, TempDir) {
55 chatbot_limit: Default::default(),55 chatbot_limit: Default::default(),
56 exam_presence: Default::default(),56 exam_presence: Default::default(),
57 board_hub: Default::default(),57 board_hub: Default::default(),
58- db_up: Default::default(),
59 ai: None,58 ai: None,
60 metrics: hezarfen_backend::telemetry::Metrics::noop(),59 metrics: hezarfen_backend::telemetry::Metrics::noop(),
61 });60 });
tests/regress_boards.rsmodified+3 -4
@@ -60,11 +60,10 @@ async fn a_strokes_page_never_carries_a_clear_marker() {
60 // The clear left a marker on epoch 0 and moved the board to epoch 1. Point60 // The clear left a marker on epoch 0 and moved the board to epoch 1. Point
61 // the board back at 0: that is precisely what a reader that read the board61 // the board back at 0: that is precisely what a reader that read the board
62 // one instant before the clear committed is looking at.62 // one instant before the clear committed is looking at.
63- db.query("UPDATE $b SET epoch = 0")63+ sqlx::query("UPDATE board SET epoch = 0 WHERE id = $1")
64- .bind(("b", BoardId::from_key(&board).record()))64+ .bind(BoardId::from_key(&board))
65+ .execute(&db)
65 .await66 .await
66- .expect("rewind")
67- .check()
68 .expect("rewind");67 .expect("rewind");
69 68
70 let res = send(69 let res = send(
tests/regress_caps.rsmodified+36 -99
@@ -51,11 +51,13 @@ async fn a_kind_off_the_schools_list_cannot_be_graded_even_with_a_live_counter()
51 51
52 // The corrupt half a lost settings race used to leave: the name is off the52 // The corrupt half a lost settings race used to leave: the name is off the
53 // list, but its counter says "in service".53 // list, but its counter says "in service".
54- db.query("UPSERT kind_ref:midterm SET retired = false")54+ sqlx::query(
55- .await55+ "INSERT INTO kind_ref (name, count, retired) VALUES ('midterm', 0, false)
56- .unwrap()56+ ON CONFLICT (name) DO UPDATE SET retired = false",
57- .check()57+ )
58- .unwrap();58+ .execute(&db)
59+ .await
60+ .unwrap();
59 61
60 let res = send(62 let res = send(
61 &app,63 &app,
@@ -318,29 +320,20 @@ async fn clear(app: &axum::Router, cookie: &str, board: &str) -> common::Res {
318 320
319 /// Rows on `board_stroke` for one board, markers included.321 /// Rows on `board_stroke` for one board, markers included.
320 async fn rows(db: &hezarfen_backend::database::Database, board: &str) -> usize {322 async fn rows(db: &hezarfen_backend::database::Database, board: &str) -> usize {
321- let mut result = db323+ sqlx::query_scalar::<_, i64>("SELECT count(*) FROM board_stroke WHERE board = $1")
322- .query("SELECT VALUE id FROM board_stroke WHERE board = $b")324+ .bind(BoardId::from_key(board))
323- .bind(("b", BoardId::from_key(board).record()))325+ .fetch_one(db)
324 .await326 .await
325- .unwrap()327+ .unwrap() as usize
326- .check()
327- .unwrap();
328- result
329- .take::<Vec<surrealdb::types::RecordId>>(0)
330- .unwrap()
331- .len()
332 }328 }
333 329
334 /// The board's stored epoch — the clear's other half.330 /// The board's stored epoch — the clear's other half.
335 async fn stored_epoch(db: &hezarfen_backend::database::Database, board: &str) -> i64 {331 async fn stored_epoch(db: &hezarfen_backend::database::Database, board: &str) -> i64 {
336- let mut result = db332+ sqlx::query_scalar::<_, i64>("SELECT epoch FROM board WHERE id = $1")
337- .query("SELECT VALUE epoch FROM $b")333+ .bind(BoardId::from_key(board))
338- .bind(("b", BoardId::from_key(board).record()))334+ .fetch_one(db)
339 .await335 .await
340 .unwrap()336 .unwrap()
341- .check()
342- .unwrap();
343- result.take::<Vec<i64>>(0).unwrap()[0]
344 }337 }
345 338
346 /// The clear marker is a row on the table, so the lifetime counter has to339 /// 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() {
399 392
400 /// `(epoch_stroke_count, total_stroke_count)` as the store holds them.393 /// `(epoch_stroke_count, total_stroke_count)` as the store holds them.
401 async fn counters(db: &hezarfen_backend::database::Database, board: &str) -> (i64, i64) {394 async fn counters(db: &hezarfen_backend::database::Database, board: &str) -> (i64, i64) {
402- let mut result = db395+ sqlx::query_as::<_, (i64, i64)>(
403- .query("SELECT VALUE [epoch_stroke_count ?? 0, total_stroke_count ?? 0] FROM $b")396+ "SELECT epoch_stroke_count, total_stroke_count FROM board WHERE id = $1",
404- .bind(("b", BoardId::from_key(board).record()))397+ )
405- .await398+ .bind(BoardId::from_key(board))
406- .unwrap()399+ .fetch_one(db)
407- .check()400+ .await
408- .unwrap();401+ .unwrap()
409- let rows: Vec<Vec<i64>> = result.take(0).unwrap();
410- (rows[0][0], rows[0][1])
411 }402 }
412 403
413 /// A menu's record id is `<date>_<slot>` and that id is a URL path segment, so404 /// A menu's record id is `<date>_<slot>` 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() {
451 // wedge an edit that never touches the meal slots. The carried-over list442 // wedge an edit that never touches the meal slots. The carried-over list
452 // goes back into the row as it stands (`MealSlotDef::try_new` runs on the443 // goes back into the row as it stands (`MealSlotDef::try_new` runs on the
453 // *request's* slots only), so an unrelated PATCH still lands.444 // *request's* slots only), so an unrelated PATCH still lands.
454- db.query("UPDATE settings:school SET meal_slots = [{ name: 'a/b', serving_minute: NONE }]")445+ sqlx::query("UPDATE settings SET meal_slots = $1 WHERE id = 'school'")
446+ .bind(json!([{ "name": "a/b", "serving_minute": null }]))
447+ .execute(&db)
455 .await448 .await
456- .unwrap()
457- .check()
458 .unwrap();449 .unwrap();
459 let res = send(450 let res = send(
460 &app,451 &app,
@@ -472,66 +463,6 @@ async fn a_slot_name_that_no_menu_id_could_carry_is_refused_by_settings() {
472 );463 );
473 }464 }
474 465
475-/// A board an older binary cleared carries a lifetime counter short by one row
476-/// per past clear, because the marker only started paying it on 2026-08-02 —
477-/// and `MAX_BOARD_STROKES` bounds *rows*, so an under-counted board can outgrow
478-/// the table cap it is supposed to obey. Boot recomputes the counter from the
479-/// rows themselves, which is what the counter means.
480-#[tokio::test]
481-async fn a_boards_lifetime_counter_is_repaired_from_its_rows_on_boot() {
482- let (app, db) = app_and_db().await;
483- let ali = login(&app, "ali").await;
484- let ali_id = me_id(&app, &ali).await;
485- let res = send(
486- &app,
487- "POST",
488- "/boards",
489- Some(&ali),
490- Some(json!({ "title": "Geometri", "participants": [] })),
491- )
492- .await;
493- let board = id_of(&res.body);
494- hezarfen_backend::db::board_stroke::append(
495- &db,
496- &BoardId::from_key(&board),
497- &UserId::from_key(&ali_id),
498- "{\"p\":[1,2]}",
499- 0,
500- )
501- .await
502- .expect("append");
503- clear(&app, &ali, &board).await;
504- assert_eq!(rows(&db, &board).await, 2, "the stroke and its marker");
505-
506- // Age the row to what the previous binary left behind: the marker charged
507- // nothing, so the counter counts the stroke alone.
508- db.query("UPDATE $b SET total_stroke_count = 1")
509- .bind(("b", BoardId::from_key(&board).record()))
510- .await
511- .unwrap()
512- .check()
513- .unwrap();
514- assert_eq!(counters(&db, &board).await, (0, 1));
515-
516- hezarfen_backend::database::migrate(&db)
517- .await
518- .expect("re-migration");
519- assert_eq!(
520- counters(&db, &board).await,
521- (0, 2),
522- "the counter is the board's row count again"
523- );
524-
525- // Idempotent: it recomputes the same number, it does not add one per boot —
526- // the failure mode a counter repair actually has.
527- for _ in 0..2 {
528- hezarfen_backend::database::migrate(&db)
529- .await
530- .expect("re-migration");
531- }
532- assert_eq!(counters(&db, &board).await, (0, 2));
533- assert_eq!(rows(&db, &board).await, 2, "and it wrote no rows");
534-}
535 466
536 /// A slot name the school *already stores* must stay submittable.467 /// A slot name the school *already stores* must stay submittable.
537 ///468 ///
@@ -559,14 +490,20 @@ async fn a_stale_slot_name_no_longer_wedges_the_rest_of_the_list() {
559 490
560 // The list as a database written before the rule holds it, plus the menu491 // The list as a database written before the rule holds it, plus the menu
561 // reference that makes dropping the name a 409.492 // reference that makes dropping the name a 409.
562- db.query(493+ sqlx::query("UPDATE settings SET meal_slots = $1 WHERE id = 'school'")
563- "UPDATE settings:school SET meal_slots = \494+ .bind(json!([
564- [{ name: 'a/b', serving_minute: NONE }, { name: 'lunch', serving_minute: NONE }];495+ { "name": "a/b", "serving_minute": null },
565- UPSERT slot_ref:`a/b` SET count = 1;",496+ { "name": "lunch", "serving_minute": null },
497+ ]))
498+ .execute(&db)
499+ .await
500+ .unwrap();
501+ sqlx::query(
502+ "INSERT INTO slot_ref (name, count, retired) VALUES ('a/b', 1, false)
503+ ON CONFLICT (name) DO UPDATE SET count = 1",
566 )504 )
505+ .execute(&db)
567 .await506 .await
568- .unwrap()
569- .check()
570 .unwrap();507 .unwrap();
571 508
572 // Editing the *rest* of the list works, stale name carried along.509 // Editing the *rest* of the list works, stale name carried along.
tests/regress_exam_delete.rsmodified+11 -7
@@ -44,15 +44,19 @@ async fn an_attempt_started_inside_a_delete_never_outlives_the_exam() {
44 let student_id = me_id(&app, &student).await;44 let student_id = me_id(&app, &student).await;
45 45
46 // Hold the delete open for a full second once the row is gone, while its46 // Hold the delete open for a full second once the row is gone, while its
47- // cascade still has to run.47+ // cascade still has to run: an AFTER DELETE trigger sleeping inside the
48- db.query(48+ // delete's own transaction is the Postgres shape of the old window event.
49- "DEFINE EVENT hold_the_window ON TABLE exam WHEN $event = 'DELETE' \49+ let mut conn = db.acquire().await.expect("acquire for the trigger");
50- THEN { SLEEP 1s; };",50+ sqlx::raw_sql(
51+ "CREATE FUNCTION heztest_hold_delete() RETURNS trigger AS $$
52+ BEGIN PERFORM pg_sleep(1.0); RETURN NULL; END;
53+ $$ LANGUAGE plpgsql;
54+ CREATE TRIGGER heztest_hold_delete AFTER DELETE ON exam
55+ FOR EACH ROW EXECUTE FUNCTION heztest_hold_delete();",
51 )56 )
57+ .execute(&mut *conn)
52 .await58 .await
53- .expect("define the window event")59+ .expect("define the window trigger");
54- .check()
55- .expect("check the window event");
56 60
57 let mut sittings = 0;61 let mut sittings = 0;
58 for round in 0..3 {62 for round in 0..3 {
tests/spec_bounds.rsmodified+1 -4
@@ -24,9 +24,7 @@ use tower::ServiceExt;
24 24
25 /// The emitted OpenAPI document, as the server serves it.25 /// The emitted OpenAPI document, as the server serves it.
26 async fn spec() -> Value {26 async fn spec() -> Value {
27- let tenants = database::init_mem_tenants()27+ let tenants = database::init_test_tenants().await;
28- .await
29- .expect("in-memory deployment");
30 let app = build_router(AppState {28 let app = build_router(AppState {
31 db: tenants.control().clone(),29 db: tenants.control().clone(),
32 tenants,30 tenants,
@@ -36,7 +34,6 @@ async fn spec() -> Value {
36 chatbot_limit: Default::default(),34 chatbot_limit: Default::default(),
37 exam_presence: Default::default(),35 exam_presence: Default::default(),
38 board_hub: Default::default(),36 board_hub: Default::default(),
39- db_up: Default::default(),
40 ai: None,37 ai: None,
41 metrics: hezarfen_backend::telemetry::Metrics::noop(),38 metrics: hezarfen_backend::telemetry::Metrics::noop(),
42 });39 });