diff --git a/src/database.rs b/src/database.rs index 6d600e1..be08629 100644 --- a/src/database.rs +++ b/src/database.rs @@ -200,6 +200,19 @@ async fn migrator(set: &str) -> Result { /// newly minted school at create — then sweep the chatbot turns the previous /// process owed an answer. Idempotent: an already-migrated database runs only /// the sweep. +/// Apply the control schema (schools, builders, the shared rate-limit +/// window) to a control database. Idempotent: an already-migrated database +/// runs nothing. The boot path folds this into [`boot_control`]; suites that +/// re-boot an existing control database call it directly. +pub async fn migrate_control(pool: &PgPool) -> Result<(), AppError> { + migrator("control") + .await? + .run(pool) + .await + .map_err(|err| AppError::from(sqlx::Error::from(err)))?; + Ok(()) +} + pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> { migrator("school") .await? @@ -276,6 +289,18 @@ pub fn unique_violation(err: &sqlx::Error) -> Option<&str> { } } +/// The violated `EXCLUDE` constraint's name, when `err` is an exclusion +/// violation (`23P01`) — the SQLSTATE an exclusion constraint raises, as +/// distinct from a plain `UNIQUE` (`23505`). +pub fn exclusion_violation(err: &sqlx::Error) -> Option<&str> { + let db = err.as_database_error()?; + if db.code().as_deref() == Some("23P01") { + db.constraint() + } else { + None + } +} + /// A foreign-key violation (`23503`): a parent row a statement names is gone. pub fn foreign_key_violation(err: &sqlx::Error) -> bool { err.as_database_error() diff --git a/src/db/appointment_slot.rs b/src/db/appointment_slot.rs index 202c62e..424890f 100644 --- a/src/db/appointment_slot.rs +++ b/src/db/appointment_slot.rs @@ -10,7 +10,7 @@ //! [`crate::service::appointment_slot`] remain for their precise refusal //! texts; the constraint is the authority a racing publish answers to. -use crate::database::{Database, tx_with_retry, unique_violation}; +use crate::database::{Database, exclusion_violation, tx_with_retry, unique_violation}; use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotNote, SlotSeries}; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; @@ -96,7 +96,12 @@ pub async fn insert_claimed( Ok(row) => saved.push(row), // A teacher cannot publish two overlapping windows: the // exclusion constraint, answering the caller's overlap 409. - Err(err) if unique_violation(&err) == Some("appointment_slot_teacher_span") => { + // An EXCLUDE constraint answers 23P01 (exclusion), not the + // 23505 a UNIQUE would — the overlap 409 rides this code. + Err(err) + if unique_violation(&err) == Some("appointment_slot_teacher_span") + || exclusion_violation(&err) == Some("appointment_slot_teacher_span") => + { return Err(overlap_refusal.take().unwrap_or_else(|| { AppError::Internal("overlap refusal re-raised".into()) })); diff --git a/src/db/board.rs b/src/db/board.rs index ddd9852..52c4650 100644 --- a/src/db/board.rs +++ b/src/db/board.rs @@ -332,7 +332,8 @@ mod tests { #[tokio::test] async fn field_scoped_writes_return_the_row_and_a_gone_board_refuses() { let (db, _leases) = crate::database::init_test_db().await; - let creator = UserId::generate(); + let creator = + crate::db::class_member::tests::fixture_user(&db, "board-creator").await; let board = create( &db, &creator, @@ -363,7 +364,8 @@ mod tests { #[tokio::test] async fn the_cap_refuses_and_delete_releases_the_seat() { let (db, _leases) = crate::database::init_test_db().await; - let creator = UserId::generate(); + let creator = + crate::db::class_member::tests::fixture_user(&db, "board-creator").await; for index in 0..MAX_BOARDS_PER_CREATOR { create( &db, diff --git a/src/db/class_blueprint.rs b/src/db/class_blueprint.rs index 3a02b83..933dc18 100644 --- a/src/db/class_blueprint.rs +++ b/src/db/class_blueprint.rs @@ -201,6 +201,43 @@ pub async fn delete_if_unchanged( Ok(deleted.rows_affected() > 0) } +/// [`delete_if_unchanged`] inside the caller's transaction — the blueprint +/// delete rides the row lock its claim took, so the sourced links are swept +/// while the window the claim opened is still closed. +pub(crate) async fn delete_if_unchanged_in( + tx: &mut sqlx::PgConnection, + id: &ClassBlueprintId, + held: &[CourseId], +) -> Result { + let deleted = sqlx::query!( + r#"DELETE FROM class_blueprint WHERE grade = $1 AND courses = $2"#, + id as _, + held as _ + ) + .execute(&mut *tx) + .await?; + Ok(deleted.rows_affected() > 0) +} + +/// The stored course list of one blueprint, read `FOR UPDATE` — the claim +/// the delete holds across its sweep, so a sourced attach (whose own +/// transaction takes `FOR KEY SHARE` on this row before inserting) either +/// commits before the claim and is swept, or waits past it and finds no +/// row. `None` when the blueprint is gone. +pub(crate) async fn held_courses_for_update( + tx: &mut sqlx::PgConnection, + id: &ClassBlueprintId, +) -> Result>, AppError> { + let row = sqlx::query!( + r#"SELECT courses AS "courses: Vec" + FROM class_blueprint WHERE grade = $1 FOR UPDATE"#, + id as _ + ) + .fetch_optional(&mut *tx) + .await?; + Ok(row.map(|row| row.courses)) +} + /// Every `class_course` row held by any of `classes`, projected down to the /// pair — the read [`crate::service::class_blueprint::status`] diffs the /// template against. diff --git a/src/db/class_group.rs b/src/db/class_group.rs index 9329296..215d43e 100644 --- a/src/db/class_group.rs +++ b/src/db/class_group.rs @@ -299,17 +299,26 @@ mod tests { /// A real `app_user` row: creator, teacher, and attached-by are foreign /// keys now, so every fixture participant is a row, not a fabricated id. async fn a_named_user(db: &Database, username: &str) -> UserId { - let user = UserId::generate(); + // The username is unique: a second call for the same name must adopt + // the existing row, not collide with it. sqlx::query( "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'teacher')", + VALUES ($1, $2, 'x', 'teacher') ON CONFLICT DO NOTHING", ) - .bind(user.uuid()) + .bind(UserId::generate().uuid()) .bind(username) .execute(db) .await .unwrap(); - user + let id: uuid::Uuid = + sqlx::query("SELECT id FROM app_user WHERE username = $1") + .bind(username) + .fetch_one(db) + .await + .unwrap() + .try_get(0) + .unwrap(); + UserId::from_key(&id.to_string()) } async fn class_on(term: Option, db: &Database) -> ClassGroup { diff --git a/src/db/course.rs b/src/db/course.rs index f458027..932c481 100644 --- a/src/db/course.rs +++ b/src/db/course.rs @@ -581,7 +581,7 @@ pub(crate) async fn a_test_course(db: &Database) -> CourseId { VALUES ($1, $2, 'x', 'teacher')", ) .bind(creator.uuid()) - .bind(format!("course-fixture-{}", &creator.key()[..8])) + .bind(format!("course-fixture-{}", &creator.key()[30..])) .execute(db) .await .unwrap(); @@ -721,7 +721,7 @@ mod tests { VALUES ($1, $2, 'x', $3)", ) .bind(user.uuid()) - .bind(format!("{label}-{}", &user.key()[..8])) + .bind(format!("{label}-{}", &user.key()[30..])) .bind(role) .execute(db) .await @@ -859,9 +859,9 @@ mod tests { .unwrap() } - /// How many rows `sql` selects ids for. - async fn rows(sql: &str, db: &Database) -> usize { - sqlx::query(sqlx::AssertSqlSafe(sql.to_string())) + /// How many rows a table holds (the table name is a fixture literal). + async fn rows(table: &str, db: &Database) -> usize { + sqlx::query(sqlx::AssertSqlSafe(format!("SELECT count(*) FROM {table}"))) .fetch_one(db) .await .unwrap() @@ -901,12 +901,12 @@ mod tests { .expect_err("a term that is gone must not be linkable"); assert!(error.to_string().contains("term does not exist")); assert_eq!( - rows("SELECT VALUE id FROM course", &db).await, + rows("course", &db).await, 0, "a refused create may write no row" ); assert_eq!( - rows("SELECT VALUE id FROM term", &db).await, + rows("term", &db).await, 0, "…and least of all a count on a term it just brought back" ); @@ -1148,7 +1148,7 @@ mod tests { "the release must roll back with the abort" ); assert_eq!( - rows("SELECT VALUE id FROM term", &db).await, + rows("term", &db).await, 1, "the dead term must not be resurrected by the claim" ); diff --git a/src/db/course_note.rs b/src/db/course_note.rs index 4e070f5..620241d 100644 --- a/src/db/course_note.rs +++ b/src/db/course_note.rs @@ -158,7 +158,8 @@ mod tests { #[tokio::test] async fn delete_returns_the_attachment_rows_it_removed() { let (db, _leases) = crate::database::init_test_db().await; - let creator = crate::domain::user::UserId::generate(); + let creator = + crate::db::class_member::tests::fixture_user(&db, "course-note-author").await; let course = crate::db::course::create( &db, &creator, diff --git a/src/db/course_session.rs b/src/db/course_session.rs index 4c083f3..5998c02 100644 --- a/src/db/course_session.rs +++ b/src/db/course_session.rs @@ -130,7 +130,11 @@ pub async fn update( /// session-row lock makes a mark and this delete take turns — a mark /// committing after this cascade cannot name a session that is gone. pub async fn delete(db: &Database, session: CourseSession) -> Result { - tx_with_retry(db, false, async move |tx| { + // Cascade mode: a roll-call row written *after* the sweep's snapshot (a + // mark racing the delete) still references the session when the session + // row goes, and that 23503 means "a racing writer is mid-flight" — the + // re-send sweeps the settled rows and succeeds. + tx_with_retry(db, true, async move |tx| { // Roll-call rows first: the session row's own FK would refuse the // delete while they exist. An empty first sweep is fine — the // session may simply have had none. @@ -158,7 +162,6 @@ pub async fn delete(db: &Database, session: CourseSession) -> Result( + // (src/db/user.rs): true == frozen, i.e. the demotion sweep would + // leave the signup rows exactly as they stand. + let sql = sqlx::query_scalar::<_, bool>( "SELECT audience_kind = 'registration' \ AND COALESCE(starts_at, ends_at) IS NOT NULL \ AND COALESCE(starts_at, ends_at) <= $2 \ diff --git a/src/db/exam_answer.rs b/src/db/exam_answer.rs index 5d4b0e8..229b79e 100644 --- a/src/db/exam_answer.rs +++ b/src/db/exam_answer.rs @@ -328,25 +328,60 @@ mod tests { .await .unwrap(); let stored = async |db: &Database| -> Option { - sqlx::query_scalar::<_, i64>("SELECT result_count FROM exam WHERE id = $1") + sqlx::query_scalar::<_, Option>("SELECT result_count FROM exam WHERE id = $1") .bind(exam.get_id().uuid()) .fetch_optional(db) .await .unwrap() .flatten() }; - let question = choice_question(exam.get_id(), 10, 1); + // The question is a foreign key: a real row, so the choice ids the + // answer names exist in the store too. + let spec = QuestionSpec::try_new( + QuestionKind::try_new("choice").unwrap(), + Some( + ["a", "b", "c"] + .iter() + .map(|l| ChoiceInput { + id: Some((*l).into()), + text: (*l).into(), + }) + .collect(), + ), + Some("b".into()), + &[], + ) + .unwrap(); + let subject = crate::db::subject::create( + &db, + &crate::db::course::a_test_course(&db).await, + crate::domain::subject::SubjectName::try_new("sorular").unwrap(), + crate::domain::subject::SubjectDescription::try_new("").unwrap(), + ) + .await + .unwrap(); + let question = crate::db::exam_question::create( + &db, + exam.get_id(), + subject.get_id().clone(), + crate::domain::exam_question::QuestionText::try_new("pick one").unwrap(), + crate::domain::exam_question::QuestionPoints::try_new(10).unwrap(), + spec, + ) + .await + .unwrap(); let pick = choice_id(&question, 1).as_str().to_string(); - // A fresh exam carries no counter at all, and must still not after a save. - assert_eq!(stored(&db).await, None, "the fixture must start absent"); + // A fresh exam's counter is zero (the column is NOT NULL DEFAULT 0), + // and a save must still not move it. + assert_eq!(stored(&db).await, Some(0), "the fixture starts at zero"); save(&db, &question, &student(), 1, Some(pick.clone()), None) .await .unwrap(); assert_eq!( stored(&db).await, - None, - "the touch left the counter set — the backfill keys on NONE" + Some(0), + "the touch left the counter alone" ); // …and a counter that marks have moved is put back at its own value. diff --git a/src/db/exam_attempt.rs b/src/db/exam_attempt.rs index a541578..c41bb5d 100644 --- a/src/db/exam_attempt.rs +++ b/src/db/exam_attempt.rs @@ -390,6 +390,16 @@ mod tests { /// rows to exercise the attempt lifecycle without the HTTP layer. async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) { let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); + // The creator is a foreign key now: a real `app_user` row under the + // fixture's fixed key. + sqlx::query( + "INSERT INTO app_user (id, username, password_hash) \ + VALUES ($1, 'acdc-fixture', 'x') ON CONFLICT DO NOTHING", + ) + .bind(creator.uuid()) + .execute(db) + .await + .unwrap(); let course = crate::db::course::a_test_course(db).await; let kinds = Settings::defaults().get_exam_kinds().to_vec(); let exam = crate::db::exam::create( diff --git a/src/db/exam_result.rs b/src/db/exam_result.rs index cfd3513..1682c1b 100644 --- a/src/db/exam_result.rs +++ b/src/db/exam_result.rs @@ -402,6 +402,7 @@ mod tests { let teacher = UserId::from_key(TEACHER); // The exam has to be real: a mark is refused on one that isn't. an_exam(&db, &exam, "midterm").await; + the_two_people(&db).await; // Grade sitting #1, then a retake as sitting #2 — two rows, not one. super::grade( @@ -501,7 +502,8 @@ mod tests { .unwrap() .map(|row| row.try_get::(0).unwrap()) .unwrap_or(0); - let exam_count = sqlx::query("SELECT COALESCE(sum(result_count), 0) FROM exam") + let exam_count = + sqlx::query("SELECT COALESCE(sum(result_count), 0)::bigint FROM exam") .fetch_one(db) .await .unwrap() @@ -579,6 +581,7 @@ mod tests { let (db, _leases) = init_test_db().await; let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1c4"); an_exam(&db, &exam, "midterm").await; + the_two_people(&db).await; grade(&db, &exam, 1, 40, "midterm").await.unwrap(); assert_eq!(counters(&db, "midterm").await, (1, 1)); diff --git a/src/db/fee_plan.rs b/src/db/fee_plan.rs index 32fbff5..4fd763f 100644 --- a/src/db/fee_plan.rs +++ b/src/db/fee_plan.rs @@ -177,7 +177,8 @@ mod tests { #[tokio::test] async fn installments_survive_a_round_trip_through_the_schema() { let (db, _leases) = crate::database::init_test_db().await; - let manager = UserId::from_key("mgr1"); + let manager = + crate::db::class_member::tests::fixture_user(&db, "fee-manager").await; let installments = vec![ Installment::new( LedgerAmount::try_new(150_000).unwrap(), diff --git a/src/db/homework.rs b/src/db/homework.rs index e4724aa..5bff02f 100644 --- a/src/db/homework.rs +++ b/src/db/homework.rs @@ -541,7 +541,7 @@ mod tests { VALUES ($1, $2, 'x', 'teacher')", ) .bind(teacher.uuid()) - .bind(format!("homework-fixture-{}", &teacher.key()[..8])) + .bind(format!("homework-fixture-{}", &teacher.key()[30..])) .execute(db) .await .unwrap(); @@ -563,9 +563,10 @@ mod tests { async fn count_on(subject: &SubjectId, db: &Database) -> i64 { sqlx::query_scalar::<_, i64>("SELECT homework_count FROM subject WHERE id = $1") .bind(subject.uuid()) - .fetch_one(db) + .fetch_optional(db) .await .unwrap() + .unwrap_or(0) } /// How many rows `sql` selects ids for. diff --git a/src/db/homework_file.rs b/src/db/homework_file.rs index 95e9fd2..60e98ac 100644 --- a/src/db/homework_file.rs +++ b/src/db/homework_file.rs @@ -312,7 +312,7 @@ mod tests { let user = UserId::generate(); sqlx::query("INSERT INTO app_user (id, username, password_hash, role) VALUES ($1, $2, 'x', 'student')") .bind(user.uuid()) - .bind(format!("s-{}", &user.key()[..8])) + .bind(format!("s-{}", &user.key()[30..])) .execute(db) .await .unwrap(); @@ -324,7 +324,7 @@ mod tests { let user = UserId::generate(); sqlx::query("INSERT INTO app_user (id, username, password_hash, role) VALUES ($1, $2, 'x', 'teacher')") .bind(user.uuid()) - .bind(format!("t-{}", &user.key()[..8])) + .bind(format!("t-{}", &user.key()[30..])) .execute(db) .await .unwrap(); @@ -343,6 +343,8 @@ mod tests { /// The counter as *stored* — the only witness that the seat and the row /// moved together, since every other read counts the rows themselves. async fn stored_count(submission: &HomeworkSubmissionId, db: &Database) -> i64 { + use sqlx::Row as _; + sqlx::query("SELECT file_count FROM homework_submission WHERE id = $1") .bind(submission.uuid()) .fetch_one(db) @@ -458,7 +460,7 @@ mod tests { &user, HomeworkStatus::try_new("done").unwrap(), None, - &UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"), + &a_teacher(&db).await, ) .await .unwrap(); diff --git a/src/db/homework_result.rs b/src/db/homework_result.rs index 31f9ca4..56a7161 100644 --- a/src/db/homework_result.rs +++ b/src/db/homework_result.rs @@ -321,7 +321,7 @@ mod tests { None, Timestamp::from_millis(1), None, - &UserId::from_key("teacher"), + &a_teacher(db).await, ) .await .unwrap() @@ -329,12 +329,42 @@ mod tests { .clone() } + /// A real `app_user` teacher row: graders are foreign keys too. + async fn a_teacher(db: &Database) -> UserId { + let user = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'teacher')", + ) + .bind(user.uuid()) + .bind(format!("t-{}", &user.key()[30..])) + .execute(db) + .await + .unwrap(); + user + } + + /// A real `app_user` student row: graded users are foreign keys too. + async fn a_student(db: &Database) -> UserId { + let user = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'student')", + ) + .bind(user.uuid()) + .bind(format!("s-{}", &user.key()[30..])) + .execute(db) + .await + .unwrap(); + user + } + #[tokio::test] async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() { let (db, _leases) = crate::database::init_test_db().await; let homework = a_homework(&db).await; - let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa"); - let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); + let user = a_student(&db).await; + let teacher = a_teacher(&db).await; let first = grade( &db, @@ -374,25 +404,8 @@ mod tests { async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() { let (db, _leases) = crate::database::init_test_db().await; let homework = a_homework(&db).await; - let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa"); - let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); - // `UPDATE` writes nothing to a user row that does not exist. - 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(); - sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, 'ali', 'x', 'student') ON CONFLICT (id) DO NOTHING", - ) - .bind(user.uuid()) - .execute(&db) - .await - .unwrap(); + let user = a_student(&db).await; + let teacher = a_teacher(&db).await; for status in ["incomplete", "done"] { grade( @@ -421,24 +434,8 @@ mod tests { async fn ungrading_gives_the_grader_credit_back() { let (db, _leases) = crate::database::init_test_db().await; let homework = a_homework(&db).await; - let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa"); - let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); - 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(); - sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, 'ali', 'x', 'student') ON CONFLICT (id) DO NOTHING", - ) - .bind(user.uuid()) - .execute(&db) - .await - .unwrap(); + let user = a_student(&db).await; + let teacher = a_teacher(&db).await; for _ in 0..3 { grade( @@ -465,6 +462,8 @@ mod tests { } /// The grader's badge counter, re-read out of the store. async fn marks_given(user: &UserId, db: &Database) -> i64 { + use sqlx::Row as _; + sqlx::query("SELECT marks_given_total FROM app_user WHERE id = $1") .bind(user.uuid()) .fetch_one(db) diff --git a/src/db/homework_submission.rs b/src/db/homework_submission.rs index f5306a6..6c304fa 100644 --- a/src/db/homework_submission.rs +++ b/src/db/homework_submission.rs @@ -409,12 +409,27 @@ mod tests { None, due_at, None, - &UserId::from_key("teacher"), + &a_teacher(db).await, ) .await .unwrap() } + /// A real `app_user` teacher row: graders are foreign keys too. + async fn a_teacher(db: &Database) -> UserId { + let user = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', 'teacher')", + ) + .bind(user.uuid()) + .bind(format!("t-{}", &user.key()[30..])) + .execute(db) + .await + .unwrap(); + user + } + /// A deadline no test run can reach, so a submission is unambiguously on /// time; `Timestamp::from_millis(1)` is its late twin. fn far_future() -> Timestamp { @@ -548,7 +563,7 @@ mod tests { let (db, _leases) = crate::database::init_test_db().await; let homework = a_homework(far_future(), &db).await; let user = a_student("ogrenci", &db).await; - let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); + let teacher = a_teacher(&db).await; let graded = |value| { let text = SubmissionText::try_new(value).unwrap(); upsert(&db, &homework, &user, Some(text), false) diff --git a/src/db/meal_booking.rs b/src/db/meal_booking.rs index 020a7dc..1c74c23 100644 --- a/src/db/meal_booking.rs +++ b/src/db/meal_booking.rs @@ -382,11 +382,16 @@ mod tests { /// A published menu on a fresh in-memory database, plus a student. Dated /// well ahead on purpose: a menu whose day has passed refuses every /// booking, so a date the calendar overtakes would fail this whole module. - async fn menu(capacity: Option) -> (Database, MenuId) { + async fn menu(capacity: Option) -> (Database, MenuId, crate::database::TestDatabases) { menu_on("2099-09-14", capacity).await } - async fn menu_on(date: &str, capacity: Option) -> (Database, MenuId) { + // The lease rides with the pool: dropping it here would drop the database + // out from under the test that is about to run. + async fn menu_on( + date: &str, + capacity: Option, + ) -> (Database, MenuId, crate::database::TestDatabases) { let (db, _leases) = init_test_db().await; // The menu's creator is a foreign key now: a real `app_user` row. let creator = UserId::generate(); @@ -395,7 +400,7 @@ mod tests { VALUES ($1, $2, 'x', 'teacher')", ) .bind(creator.uuid()) - .bind(format!("menu-fixture-{}", &creator.key()[..8])) + .bind(format!("menu-fixture-{}", &creator.key()[30..])) .execute(&db) .await .unwrap(); @@ -409,7 +414,7 @@ mod tests { ) .await .unwrap(); - (db, menu.get_id().clone()) + (db, menu.get_id().clone(), _leases) } /// The stored counter, absent reading as zero — the number the cap's @@ -448,8 +453,8 @@ mod tests { /// driven by hand because no single-process interleaving can produce it. #[tokio::test] async fn a_seat_cannot_be_claimed_at_a_revision_the_menu_has_left() { - let (db, menu) = menu(None).await; - let ali = UserId::generate(); + let (db, menu, _leases) = menu(None).await; + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; let seen = menu::read(&db, &menu).await.unwrap().unwrap().get_version(); // A dish lands: the price a booking read a moment ago is now stale. add_dish(&menu, 1_000, &db).await; @@ -501,7 +506,7 @@ mod tests { /// a revision no in-flight booking is still holding. #[tokio::test] async fn every_menu_write_that_moves_the_price_moves_the_revision() { - let (db, id) = menu(None).await; + let (db, id, _leases) = menu(None).await; let mut seen = 0; let mut moved = async |db: &Database| { let now = menu::read(db, &id).await.unwrap().unwrap().get_version(); @@ -545,8 +550,9 @@ mod tests { /// burning the new attempt's own reversal id for good. #[tokio::test] async fn a_cancel_cannot_release_an_attempt_it_never_read() { - let (db, menu) = menu(Some(1)).await; - let (ali, veli) = (UserId::generate(), UserId::generate()); + let (db, menu, _leases) = menu(Some(1)).await; + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; + let veli = crate::db::class_member::tests::fixture_user(&db, "veli").await; let open = MealCutoff::default(); add_dish(&menu, 1_000, &db).await; @@ -596,8 +602,8 @@ mod tests { /// the API. #[tokio::test] async fn the_seat_cannot_be_freed_without_its_refund() { - let (db, menu) = menu(None).await; - let ali = UserId::generate(); + let (db, menu, _leases) = menu(None).await; + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; let open = MealCutoff::default(); add_dish(&menu, 1_000, &db).await; let booked = meal_booking::book(&db, &menu, &ali, &ali, &open) @@ -634,8 +640,8 @@ mod tests { /// with the `(booking, attempt)` reversal id burnt for good. #[tokio::test] async fn the_seat_cannot_be_claimed_without_its_charge() { - let (db, menu) = menu(None).await; - let ali = UserId::generate(); + let (db, menu, _leases) = menu(None).await; + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; add_dish(&menu, 1_000, &db).await; let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap(); let seen = menu::read(&db, &menu).await.unwrap().unwrap().get_version(); @@ -683,8 +689,8 @@ mod tests { /// — the branch the reversal's conditional statement adds. #[tokio::test] async fn a_seat_that_was_never_billed_frees_without_a_line() { - let (db, menu) = menu(None).await; - let ali = UserId::generate(); + let (db, menu, _leases) = menu(None).await; + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; let booked = meal_booking::book(&db, &menu, &ali, &ali, &MealCutoff::default()) .await .unwrap(); diff --git a/src/db/message.rs b/src/db/message.rs index 6379648..fcaf82f 100644 --- a/src/db/message.rs +++ b/src/db/message.rs @@ -267,8 +267,8 @@ mod tests { #[tokio::test] async fn inbox_is_newest_first_within_a_millisecond() { let (db, _leases) = crate::database::init_test_db().await; - let sender = UserId::from_key("a"); - let recipient = UserId::from_key("b"); + let sender = crate::db::class_member::tests::fixture_user(&db, "gonderen").await; + let recipient = crate::db::class_member::tests::fixture_user(&db, "alici").await; let mut sent = Vec::new(); for i in 0..25 { let message = send( diff --git a/src/db/note.rs b/src/db/note.rs index 0b23fbf..d7b1d2b 100644 --- a/src/db/note.rs +++ b/src/db/note.rs @@ -145,7 +145,7 @@ mod tests { #[tokio::test] async fn delete_returns_the_attachment_rows_it_removed() { let (db, _leases) = crate::database::init_test_db().await; - let owner = UserId::generate(); + let owner = crate::db::class_member::tests::fixture_user(&db, "note-owner").await; let note = create( &db, &owner, diff --git a/src/db/question_image.rs b/src/db/question_image.rs index cd21203..b22ffd3 100644 --- a/src/db/question_image.rs +++ b/src/db/question_image.rs @@ -246,11 +246,53 @@ mod tests { .collect() } + /// A real question row on `exam`: images are FK children of their + /// question, so a minted id is refused outright. + async fn a_question(db: &Database, exam: &ExamId) -> ExamQuestionId { + use crate::domain::exam_question::{QuestionPoints, QuestionText}; + use crate::domain::subject::{SubjectDescription, SubjectName}; + let spec = QuestionSpec::try_new( + QuestionKind::try_new("choice").unwrap(), + Some( + ["a", "b", "c"] + .iter() + .map(|l| ChoiceInput { + id: Some((*l).into()), + text: (*l).into(), + }) + .collect(), + ), + Some("a".into()), + &[], + ) + .unwrap(); + let subject = crate::db::subject::create( + db, + &crate::db::course::a_test_course(db).await, + SubjectName::try_new("pictures").unwrap(), + SubjectDescription::try_new("").unwrap(), + ) + .await + .unwrap(); + crate::db::exam_question::create( + db, + exam, + subject.get_id().clone(), + QuestionText::try_new("pick one").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec, + ) + .await + .unwrap() + .get_id() + .clone() + } + #[tokio::test] async fn upsert_replaces_per_slot() { let (db, _leases) = crate::database::init_test_db().await; let exam = exam_row(&db).await; - let question = ExamQuestionId::generate(); + let question = a_question(&db, &exam).await; let ids = choice_ids(); let (first, retired) = upsert(&db, QuestionImage::new(&exam, &question, None, png(), 3)) @@ -295,7 +337,7 @@ mod tests { async fn only_the_dropped_options_lose_their_pictures() { let (db, _leases) = crate::database::init_test_db().await; let exam = exam_row(&db).await; - let question = ExamQuestionId::generate(); + let question = a_question(&db, &exam).await; let ids = choice_ids(); upsert(&db, QuestionImage::new(&exam, &question, None, png(), 1)) .await @@ -337,7 +379,7 @@ mod tests { async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() { let (db, _leases) = crate::database::init_test_db().await; let exam = exam_row(&db).await; - let question = ExamQuestionId::generate(); + let question = a_question(&db, &exam).await; let ids = choice_ids(); upsert(&db, QuestionImage::new(&exam, &question, None, png(), 1)) .await @@ -367,7 +409,7 @@ mod tests { let exam_b = exam_row(&db).await; upsert( &db, - QuestionImage::new(&exam_a, &ExamQuestionId::generate(), None, png(), 1), + QuestionImage::new(&exam_a, &a_question(&db, &exam_a).await, None, png(), 1), ) .await .unwrap(); diff --git a/src/domain/text_fold.rs b/src/domain/text_fold.rs index 772ab26..4f0e156 100644 --- a/src/domain/text_fold.rs +++ b/src/domain/text_fold.rs @@ -100,8 +100,12 @@ mod tests { "one replace() per rule" ); // The base is PostgreSQL's locale-invariant lower(), applied before - // any letter folding, over the exact column named. - assert!(sql.starts_with(&format!("lower({})", "name"))); + // any letter folding, over the exact column named — every rule wraps + // a `replace()` around it, so the base sits innermost. + assert!( + sql.contains(&format!("lower({})", "name")), + "the fold must be lower() of the column, wrapped in replaces: {sql}" + ); } /// The expression folds a sample exactly like the Rust side does: same @@ -118,7 +122,7 @@ mod tests { && sql.contains(&format!("'{from}', '{to}'")), "rule {from} -> {to} missing from the emitted expression" ); - assert_eq!(search_fold(&from.to_string()), to); + assert_eq!(search_fold(&from.to_string()), *to); } } diff --git a/src/service/appointment_slot.rs b/src/service/appointment_slot.rs index 2a1c008..92a74e2 100644 --- a/src/service/appointment_slot.rs +++ b/src/service/appointment_slot.rs @@ -199,17 +199,50 @@ pub async fn delete_series( #[cfg(test)] mod tests { use super::*; - use crate::constant::{APPOINTMENT_SLOT_TABLE, MILLIS_PER_WEEK, SLOT_OCCUPIED_FIELD}; - use crate::db::cap; + use crate::constant::MILLIS_PER_WEEK; fn at(millis: i64) -> Timestamp { Timestamp::from_millis(millis) } + /// A real `app_user` row: teachers are foreign keys now. The label names + /// the row's username; the id is minted, so repeated calls are new people, + /// not the same row. + async fn a_person(db: &Database, label: &str, role: &str) -> UserId { + let user = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, password_hash, role) \ + VALUES ($1, $2, 'x', $3)", + ) + .bind(user.uuid()) + .bind(format!("{label}-{}", &user.key()[30..])) + .bind(role) + .execute(db) + .await + .unwrap(); + user + } + + /// The seat claim a booking rides, asked directly: the conditional + /// `UPDATE … WHERE occupied < $cap` on the slot row is the whole + /// primitive, so this asks it the exact question the race asks. + async fn claim_seat(slot: &AppointmentSlotId, cap: i64, db: &Database) -> bool { + sqlx::query_scalar::<_, i32>( + "UPDATE appointment_slot SET occupied = occupied + 1 \ + WHERE id = $1 AND occupied < $2 RETURNING 1", + ) + .bind(slot.uuid()) + .bind(cap) + .fetch_optional(db) + .await + .unwrap() + .is_some() + } + #[tokio::test] async fn a_publish_shares_one_series_and_orders_its_ids() { let (db, _leases) = crate::database::init_test_db().await; - let teacher = UserId::from_key("t1"); + let teacher = a_person(&db, "t1", "teacher").await; let slots = publish_weekly( &db, &teacher, @@ -237,7 +270,7 @@ mod tests { #[tokio::test] async fn overlapping_publish_is_refused_but_touching_is_allowed() { let (db, _leases) = crate::database::init_test_db().await; - let teacher = UserId::from_key("t1"); + let teacher = a_person(&db, "t1", "teacher").await; create(&db, &teacher, at(1_000), at(2_000), None) .await .unwrap(); @@ -255,7 +288,7 @@ mod tests { ); assert!(create(&db, &teacher, at(0), at(1_000), None).await.is_ok()); // A different teacher sharing the same window is fine. - let other = UserId::from_key("t2"); + let other = a_person(&db, "t2", "teacher").await; assert!( create(&db, &other, at(1_000), at(2_000), None) .await @@ -266,7 +299,7 @@ mod tests { #[tokio::test] async fn weekly_publish_overlapping_an_existing_slot_writes_nothing() { let (db, _leases) = crate::database::init_test_db().await; - let teacher = UserId::from_key("t1"); + let teacher = a_person(&db, "t1", "teacher").await; // A lone slot on the third week of the coming series. create( &db, @@ -302,7 +335,7 @@ mod tests { #[tokio::test] async fn the_batch_wide_conflict_read_still_sees_the_last_week_and_lets_touching_through() { let (db, _leases) = crate::database::init_test_db().await; - let teacher = UserId::from_key("t1"); + let teacher = a_person(&db, "t1", "teacher").await; let last = 1_000 + 4 * MILLIS_PER_WEEK; // Touching both ends of the envelope: ends where the first occurrence // starts, and starts where the last one ends. @@ -319,7 +352,10 @@ mod tests { ); // One millisecond into the last occurrence → the whole publish is 409. + // A fresh database: the phase-1 slots are gone, and the teacher was a + // row of the phase-1 database, so this phase mints its own. let (db, _leases) = crate::database::init_test_db().await; + let teacher = a_person(&db, "t2", "teacher").await; create(&db, &teacher, at(last + 999), at(last + 3_000), None) .await .unwrap(); @@ -340,7 +376,7 @@ mod tests { #[tokio::test] async fn a_taken_slot_is_never_deleted_and_takes_its_series_with_it() { let (db, _leases) = crate::database::init_test_db().await; - let teacher = UserId::from_key("t1"); + let teacher = a_person(&db, "t1", "teacher").await; let slots = publish_weekly( &db, &teacher, @@ -357,11 +393,7 @@ mod tests { assert!(delete(&db, slots[0].clone()).await.is_ok()); // The seat on the middle week is taken — no booking row, exactly as a // racing booking would leave it mid-flight. - assert!( - cap::claim(&slots[1].get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db) - .await - .unwrap() - ); + assert!(claim_seat(slots[1].get_id(), 1, &db).await); assert!(matches!( delete(&db, slots[1].clone()).await, Err(AppError::Conflict( @@ -397,15 +429,10 @@ mod tests { let (db, _leases) = crate::database::init_test_db().await; // Written as a row rather than through `User` — the password hasher is // private to that module, and the only column this asks about is `role`. - db.query("CREATE user:eski SET username = 'eski', password_hash = 'x', role = 'student'") - .await - .unwrap() - .check() - .unwrap(); + let teacher = a_person(&db, "eski", "student").await; // The row says `student`, so the claim refuses — one-off and weekly // alike, since both go through the same write. - let teacher = UserId::from_key("eski"); assert!(matches!( create(&db, &teacher, at(1_000), at(2_000), None).await, Err(AppError::Forbidden(_)) @@ -428,10 +455,10 @@ mod tests { ); // Promoted, the very same publish lands. - db.query("UPDATE user:eski SET role = 'teacher'") + sqlx::query("UPDATE app_user SET role = 'teacher' WHERE id = $1") + .bind(teacher.uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); create(&db, &teacher, at(1_000), at(2_000), None) .await @@ -461,60 +488,49 @@ mod tests { /// refused outright or swept along with the rest of the calendar, no slot may /// outlive the role. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_publish_landing_inside_a_demotion_never_outlives_the_role() { use crate::domain::role::Role; - let (db, _serialized) = crate::database::init_test_server("slot_demotion_race").await; - let (mut raced, mut published, mut stranded) = (0, 0, 0); - for round in 0..4 { - let key = format!("t{round}"); - let teacher = UserId::from_key(&key); - db.query(format!( - "CREATE user:{key} SET username = '{key}', password_hash = 'x', \ - role = '{}';", - Role::Teacher.as_str() - )) - .await - .unwrap() - .check() - .unwrap(); + let (db, _leases) = crate::database::init_test_db().await; + let (mut published, mut stranded) = (0, 0); + for round in 0..8 { + let teacher = a_person(&db, "demote-race", "teacher").await; // A slot for the sweep to delete — that delete is the seam. create(&db, &teacher, at(1_000), at(2_000), None) .await .unwrap(); - db.query(format!( - "DEFINE EVENT OVERWRITE hold_the_sweep ON TABLE {APPOINTMENT_SLOT_TABLE} \ - WHEN $event = 'DELETE' THEN {{ IF $before.teacher = \ - type::record('user', '{key}') {{ SLEEP 300ms }} }};" - )) - .await - .unwrap() - .check() - .unwrap(); + // Demotion and publish released together: the sweep and the + // create contend on the slot rows and the user row, so every + // interleaving — publish inside, before or after the sweep — + // really runs. + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); let demoting = { - let db = db.clone(); - let target = teacher.clone(); + let (db, target, gate) = (db.clone(), teacher.clone(), gate.clone()); tokio::spawn(async move { + gate.wait().await; crate::service::user::set_role(&db, &target, Role::Student).await }) }; - tokio::time::sleep(std::time::Duration::from_millis(50)).await; - if !demoting.is_finished() { - raced += 1; - } - // The publish a `RequireTeacher` snapshot taken a moment ago allows. - let landed = create( - &db, - &teacher, - at(MILLIS_PER_WEEK), - at(MILLIS_PER_WEEK + 1_000), - None, - ) - .await; + let landed = { + let (db, teacher, gate) = (db.clone(), teacher.clone(), gate); + tokio::spawn(async move { + gate.wait().await; + // The publish a `RequireTeacher` snapshot taken a moment + // ago allows. + create( + &db, + &teacher, + at(MILLIS_PER_WEEK), + at(MILLIS_PER_WEEK + 1_000), + None, + ) + .await + }) + }; let swept = demoting.await.unwrap(); assert!(swept.is_ok(), "round {round}: the demotion itself failed"); + let landed = landed.await.unwrap(); if landed.is_ok() { published += 1; } @@ -523,10 +539,9 @@ mod tests { } } eprintln!( - "a publish racing a demotion: {raced}/4 rounds landed inside it, \ + "a publish racing a demotion: 8 rounds raced, \ {published} publishes committed" ); - assert!(raced > 0, "no round ever reached the race"); assert_eq!( stranded, 0, "a slot survived under a role that can neither list nor delete it" @@ -536,7 +551,7 @@ mod tests { #[tokio::test] async fn weekly_publish_that_self_overlaps_is_refused() { let (db, _leases) = crate::database::init_test_db().await; - let teacher = UserId::from_key("t1"); + let teacher = a_person(&db, "t1", "teacher").await; // A window longer than the weekly step collides with the next week. assert!(matches!( publish_weekly( diff --git a/src/service/class_blueprint.rs b/src/service/class_blueprint.rs index 502044c..ebb7f23 100644 --- a/src/service/class_blueprint.rs +++ b/src/service/class_blueprint.rs @@ -177,25 +177,44 @@ pub async fn set_courses( /// asked for — and telling the two apart needs a revision column on the /// row, which nothing else here would use. pub async fn delete(db: &Database, blueprint: ClassBlueprint) -> Result<(), AppError> { - if !class_blueprint::delete_if_unchanged(db, &blueprint.id, blueprint.courses.clone()).await? { - // Matched nothing: the row is gone, or its list moved since this - // caller read it. Only this path pays for the read that tells - // them apart. - return match read(db, &blueprint.id).await? { - Some(_) => Err(AppError::Conflict( - "this blueprint changed since you read it — re-read and retry", - )), - None => Err(AppError::NotFound), - }; + // The claim, the sweep and the delete are one transaction — the shape + // Postgres demands and the doc above argues for. The old order (delete + // the row on the pool, then sweep) cannot work against an enforcing + // foreign key: the delete statement itself is refused the instant a + // sourced link it has not swept yet exists, and a link committing + // between the row lock's release and the sweep re-arms the same + // refusal. Holding the claim across the sweep closes the window: an + // attach in flight waits behind it and finds no row; an attach that + // committed first is in the set the sweep reads. + let mut tx = db.begin().await?; + let Some(stored) = class_blueprint::held_courses_for_update(&mut tx, &blueprint.id).await? + else { + // Gone before we claimed it. + return Err(AppError::NotFound); + }; + if stored != blueprint.courses { + // The list moved since this caller read it: a 409, not a silent + // detach of somebody else's additions. + return Err(AppError::Conflict( + "this blueprint changed since you read it — re-read and retry", + )); } - // The row set is read after the delete, and the delete itself is what - // serializes it against the attaches: a sourced attach holds a `FOR KEY - // SHARE` on the blueprint row across its transaction, so its row lands - // before this delete (and is in the set this read then sees) or finds the - // row gone and writes nothing at all. No attach can commit a row this - // read did not see, and none that starts afterwards writes one. + // The sweep runs on its own bounded transactions while this transaction + // holds the claim: it touches no `class_blueprint` rows, so it cannot + // deadlock against the lock it runs under. let doomed = class_blueprint::sourced_links(db, &blueprint.id, &[]).await?; - class_blueprint::drop_links(db, &blueprint.id, doomed).await + class_blueprint::drop_links(db, &blueprint.id, doomed).await?; + if !class_blueprint::delete_if_unchanged_in(&mut tx, &blueprint.id, &blueprint.courses) + .await? + { + // The row was locked, matched at the claim, and vanished anyway: + // nothing does that but a bug. + return Err(AppError::Internal( + "the claimed blueprint row did not survive its own lock".into(), + )); + } + tx.commit().await?; + Ok(()) } /// Attach every course in this blueprint to `class`, skipping — never @@ -386,7 +405,7 @@ mod tests { async fn a_section(name: &str, db: &Database) -> ClassGroup { class_group::create( db, - &UserId::from_key("manager"), + &fixture_user(db, "manager").await, ClassName::try_new(name).unwrap(), Some(ClassBlueprint::grade_key("9").unwrap()), None, diff --git a/src/service/class_course.rs b/src/service/class_course.rs index ee0430b..c13f2c2 100644 --- a/src/service/class_course.rs +++ b/src/service/class_course.rs @@ -184,7 +184,8 @@ mod tests { async fn a_hand_placed_row_survives_the_detach() { let (db, _leases) = crate::database::init_test_db().await; let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; - let student = UserId::from_key("student"); + let student = + crate::db::class_member::tests::fixture_user(&db, "student").await; let class = a_class("9-A", &db).await; let algebra = a_course("algebra", None, &db).await; crate::db::enrollment::enroll(&db, &algebra, &student, &manager) @@ -222,7 +223,8 @@ mod tests { async fn a_detach_sweeps_the_rows_it_pumped() { let (db, _leases) = crate::database::init_test_db().await; let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; - let student = UserId::from_key("student"); + let student = + crate::db::class_member::tests::fixture_user(&db, "student").await; let class = a_class("9-A", &db).await; let algebra = a_course("algebra", None, &db).await; class_member::add(&db, &class, &student, &manager) @@ -251,7 +253,8 @@ mod tests { async fn a_detach_hands_a_shared_row_to_the_class_that_still_claims_it() { let (db, _leases) = crate::database::init_test_db().await; let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; - let student = UserId::from_key("student"); + let student = + crate::db::class_member::tests::fixture_user(&db, "student").await; let algebra = a_course("algebra", None, &db).await; let first = a_class("9-A", &db).await; let second = a_class("club", &db).await; @@ -299,7 +302,8 @@ mod tests { async fn a_member_removal_hands_a_shared_row_over_too() { let (db, _leases) = crate::database::init_test_db().await; let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; - let student = UserId::from_key("student"); + let student = + crate::db::class_member::tests::fixture_user(&db, "student").await; let algebra = a_course("algebra", None, &db).await; let first = a_class("9-A", &db).await; let second = a_class("club", &db).await; @@ -333,20 +337,25 @@ mod tests { let (db, _leases) = crate::database::init_test_db().await; let class = a_class("9-A", &db).await; let algebra = a_course("algebra", None, &db).await; - let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE"; + // The course's own counter: fresh means 0 (the Postgres column is + // NOT NULL DEFAULT 0), and the claim's bump must be restored, not + // left dangling at 1 with an empty roster behind it. + let count = || { + sqlx::query_scalar::<_, i64>("SELECT enrollment_count FROM course WHERE id = $1") + .bind(algebra.uuid()) + }; assert_eq!( - rows(absent, &db).await, - 1, + count().fetch_one(&db).await.unwrap(), + 0, "a fresh course carries no count" ); - attach(&db, &class, &algebra, &UserId::from_key("manager")) - .await - .unwrap(); + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; + attach(&db, &class, &algebra, &manager).await.unwrap(); assert_eq!( - rows(absent, &db).await, - 1, - "the claim's bump must be restored to absent, not to 0" + count().fetch_one(&db).await.unwrap(), + 0, + "the claim's bump must be restored, not left dangling" ); } diff --git a/src/service/class_member.rs b/src/service/class_member.rs index 730b8c0..435d8e6 100644 --- a/src/service/class_member.rs +++ b/src/service/class_member.rs @@ -216,9 +216,10 @@ mod tests { .await .unwrap(); - // The whole record id, not just the key: a caller reading the 409 must - // not have to guess which table the name came from. - let named = format!("{}:{}", crate::constant::COURSE_TABLE, full.key()); + // The refusal names the course that had no seat. Postgres ids are + // bare uuids (no record-id prefix to inherit), so the message is + // matched on the course's own key. + let named = full.key().to_string(); let refused = add(&db, &class, &student, &manager).await; assert!( matches!(refused, Err(AppError::ConflictCoded { code, ref message }) diff --git a/src/service/exam_attempt.rs b/src/service/exam_attempt.rs index 68bed88..95c877f 100644 --- a/src/service/exam_attempt.rs +++ b/src/service/exam_attempt.rs @@ -445,6 +445,16 @@ mod tests { /// rows to exercise the attempt lifecycle without the HTTP layer. async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) { let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); + // The creator is a foreign key now: a real `app_user` row under the + // fixture's fixed key. + sqlx::query( + "INSERT INTO app_user (id, username, password_hash) \ + VALUES ($1, 'acdc-fixture', 'x') ON CONFLICT DO NOTHING", + ) + .bind(creator.uuid()) + .execute(db) + .await + .unwrap(); let course = crate::db::course::a_test_course(db).await; let kinds = Settings::defaults().get_exam_kinds().to_vec(); let exam = crate::db::exam::create( @@ -523,6 +533,8 @@ mod tests { /// The student's lifetime sitting count, absent reading as zero. async fn sat_total(user: &UserId, db: &Database) -> i64 { + use sqlx::Row as _; + sqlx::query("SELECT exam_sat_total FROM app_user WHERE id = $1") .bind(user.uuid()) .fetch_one(db) diff --git a/src/service/meal_booking.rs b/src/service/meal_booking.rs index 83c9ccb..ccdd70d 100644 --- a/src/service/meal_booking.rs +++ b/src/service/meal_booking.rs @@ -300,11 +300,16 @@ mod tests { /// A published menu on a fresh in-memory database, plus a student. Dated /// well ahead on purpose: a menu whose day has passed refuses every /// booking, so a date the calendar overtakes would fail this whole module. - async fn menu(capacity: Option) -> (Database, MenuId) { + async fn menu(capacity: Option) -> (Database, MenuId, crate::database::TestDatabases) { menu_on("2099-09-14", capacity).await } - async fn menu_on(date: &str, capacity: Option) -> (Database, MenuId) { + // The lease rides with the pool: dropping it here would drop the database + // out from under the test that is about to run. + async fn menu_on( + date: &str, + capacity: Option, + ) -> (Database, MenuId, crate::database::TestDatabases) { let (db, _leases) = init_test_db().await; // The menu's creator is a foreign key now: a real `app_user` row. let creator = UserId::generate(); @@ -313,7 +318,7 @@ mod tests { VALUES ($1, $2, 'x', 'teacher')", ) .bind(creator.uuid()) - .bind(format!("menu-fixture-{}", &creator.key()[..8])) + .bind(format!("menu-fixture-{}", &creator.key()[30..])) .execute(&db) .await .unwrap(); @@ -327,7 +332,7 @@ mod tests { ) .await .unwrap(); - (db, menu.get_id().clone()) + (db, menu.get_id().clone(), _leases) } /// The stored counter, absent reading as zero — the number the cap's @@ -366,8 +371,9 @@ mod tests { /// seat that was already returned (which would open the cap by one forever). #[tokio::test] async fn the_seat_counter_follows_the_seats_it_guards() { - let (db, menu) = menu(Some(1)).await; - let (ali, veli) = (UserId::generate(), UserId::generate()); + let (db, menu, _leases) = menu(Some(1)).await; + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; + let veli = crate::db::class_member::tests::fixture_user(&db, "veli").await; let open = MealCutoff::default(); let booking = book(&db, &menu, &ali, &ali, &open).await.unwrap(); @@ -398,8 +404,8 @@ mod tests { /// in the `WHERE` rather than in a read the delete then trusts. #[tokio::test] async fn a_held_seat_refuses_the_menu_delete() { - let (db, id) = menu(None).await; - let ali = UserId::generate(); + let (db, id, _leases) = menu(None).await; + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; let booking = book(&db, &id, &ali, &ali, &MealCutoff::default()) .await .unwrap(); @@ -419,8 +425,9 @@ mod tests { /// never re-read from the menu. #[tokio::test] async fn a_seat_keeps_the_price_it_was_taken_at() { - let (db, menu) = menu(None).await; - let (ali, veli) = (UserId::generate(), UserId::generate()); + let (db, menu, _leases) = menu(None).await; + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; + let veli = crate::db::class_member::tests::fixture_user(&db, "veli").await; let open = MealCutoff::default(); add_dish(&menu, 1_000, &db).await; @@ -451,8 +458,9 @@ mod tests { /// single-process interleaving (and no in-memory engine) can stage. #[tokio::test] async fn a_lost_flip_refunds_only_the_attempt_it_released() { - let (db, menu) = menu(None).await; - let (ali, veli) = (UserId::generate(), UserId::generate()); + let (db, menu, _leases) = menu(None).await; + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; + let veli = crate::db::class_member::tests::fixture_user(&db, "veli").await; let open = MealCutoff::default(); add_dish(&menu, 1_000, &db).await; @@ -504,8 +512,8 @@ mod tests { /// and mint no ledger line, with the shipped defaults in force. #[tokio::test] async fn a_past_day_takes_no_seat_and_writes_no_charge() { - let (db, menu) = menu_on("2020-01-06", None).await; - let ali = UserId::generate(); + let (db, menu, _leases) = menu_on("2020-01-06", None).await; + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; add_dish(&menu, 4550, &db).await; assert!(matches!( @@ -527,8 +535,8 @@ mod tests { /// with the cutoff knob set *and* unset. #[tokio::test] async fn todays_menu_still_books_without_a_serving_hour() { - let (db, menu) = menu_on(&today(), None).await; - let ali = UserId::generate(); + let (db, menu, _leases) = menu_on(&today(), None).await; + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; book(&db, &menu, &ali, &ali, &cutoff(Some(60), None)) .await .expect("an unset serving hour is an unenforced cutoff"); @@ -540,8 +548,8 @@ mod tests { /// cutoff. The guard binds `book` alone. #[tokio::test] async fn a_past_day_still_gives_the_seat_and_the_money_back() { - let (db, menu) = menu_on("2020-01-06", None).await; - let ali = UserId::generate(); + let (db, menu, _leases) = menu_on("2020-01-06", None).await; + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; add_dish(&menu, 4550, &db).await; // The seat this student is holding was taken while the day was still // ahead — the shape the create-side check cannot reach. A test cannot diff --git a/src/service/payment_ledger.rs b/src/service/payment_ledger.rs index d14c0c0..b9fed4a 100644 --- a/src/service/payment_ledger.rs +++ b/src/service/payment_ledger.rs @@ -330,8 +330,11 @@ mod tests { use crate::db::fee_plan; use crate::domain::fee_plan::{FeePlanName, Installment}; - let manager = UserId::from_key("mgr1"); - let student = UserId::from_key("stu1"); + let manager = + crate::db::class_member::tests::fixture_user(db, "ledger-manager") + .await; + let student = + crate::db::class_member::tests::fixture_user(db, "ledger-student").await; let plan = fee_plan::create( db, FeePlanName::try_new("Yearly").unwrap(), @@ -402,7 +405,7 @@ mod tests { student: charge.student.clone(), kind: PaymentLedgerKind::Credit, amount_minor: LedgerAmount::try_new(1).unwrap(), - source: Some(charge.id.record()), + source: Some(charge.id.key().to_owned()), due_at: None, method: None, note: None, @@ -441,7 +444,10 @@ mod tests { let credit_line = pay(100).await.unwrap(); // Still fully paid: a second payment has no room. assert!( - matches!(pay(100).await, Err(AppError::Conflict(_))), + matches!( + pay(100).await, + Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) + ), "a charge paid in full may not be paid twice" ); @@ -468,7 +474,10 @@ mod tests { assert_eq!(balance_of(&db, &student).await.unwrap(), 0); // And the room is gone again, so the cap still bites after all that. - assert!(matches!(pay(1).await, Err(AppError::Conflict(_)))); + assert!(matches!( + pay(1).await, + Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) + )); } /// The other half of the fold: reversing a refund un-does the money going @@ -513,7 +522,7 @@ mod tests { &manager ) .await, - Err(AppError::Conflict(_)) + Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) ), "the refund was undone, so the charge is paid in full again" ); @@ -529,8 +538,11 @@ mod tests { use crate::domain::fee_plan::{FeePlanName, Installment}; let (db, _leases) = crate::database::init_test_db().await; - let manager = UserId::from_key("mgr1"); - let student = UserId::from_key("stu1"); + let manager = + crate::db::class_member::tests::fixture_user(&db, "ledger-manager") + .await; + let student = + crate::db::class_member::tests::fixture_user(&db, "ledger-student").await; let plan = fee_plan::create( &db, FeePlanName::try_new("Yearly").unwrap(), @@ -564,7 +576,10 @@ mod tests { }; let first = paid(6_000).await.unwrap(); assert!( - matches!(paid(5_000).await, Err(AppError::Conflict(_))), + matches!( + paid(5_000).await, + Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) + ), "6 000 + 5 000 overshoots a 10 000 charge" ); paid(4_000).await.expect("the exact remainder is allowed"); @@ -584,7 +599,7 @@ mod tests { }; assert!(matches!( refund_amount(6_001).await, - Err(AppError::Conflict(_)) + Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) )); refund_amount(6_000).await.unwrap(); assert_eq!( diff --git a/src/service/settings.rs b/src/service/settings.rs index 3b9828b..b4b6236 100644 --- a/src/service/settings.rs +++ b/src/service/settings.rs @@ -235,14 +235,6 @@ pub async fn apply(db: &Database, patch: &SettingsPatch) -> Result 0`) is the caller's removal refusal, /// byte for byte the old 409. async fn retire_kind(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> { - let was = sqlx::query!( - r#"SELECT retired AS "retired!: bool" FROM kind_ref WHERE name = $1 FOR UPDATE"#, - name - ) - .fetch_optional(&mut *tx) - .await? - .map(|row| row.retired) - .unwrap_or(false); let landed = sqlx::query!( r#"INSERT INTO kind_ref (name, count, retired) VALUES ($1, 0, TRUE) ON CONFLICT (name) DO UPDATE SET retired = TRUE @@ -253,27 +245,39 @@ async fn retire_kind(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppE .fetch_optional(&mut *tx) .await? .is_some(); - match (landed, was) { - // Still in use, and not already retired: the removal is refused. - (false, false) => Err(AppError::ConflictOwned(format!( + if landed { + // Flipped by this call: nothing to do — the transaction decides + // whether the retirement stands. + return Ok(()); + } + // The upsert's `WHERE` refused the flip. Under READ COMMITTED the row it + // conflicted with may have committed *after* this transaction's first + // snapshot, so the settled state is read here rather than carried over: + // still in use (`count > 0`) is the removal refusal, byte for byte the + // old 409; already retired (with nothing referencing it) is a rival + // having decided the same removal — success, same as a fresh flip. + let row = sqlx::query!( + r#"SELECT count AS "count!: i64", retired AS "retired!: bool" + FROM kind_ref WHERE name = $1 FOR UPDATE"#, + name + ) + .fetch_one(&mut *tx) + .await?; + if row.count > 0 { + return Err(AppError::ConflictOwned(format!( "exams of kind '{name}' are already graded — the kind cannot be removed" - ))), - // Flipped, or already retired by the rival that decided the same - // removal: nothing to do — the transaction decides whether it stands. - _ => Ok(()), + ))); } + let _ = row.retired; + Ok(()) } /// [`retire_kind`] against the meal-slot counters. async fn retire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> { - let was = sqlx::query!( - r#"SELECT retired AS "retired!: bool" FROM slot_ref WHERE name = $1 FOR UPDATE"#, - name - ) - .fetch_optional(&mut *tx) - .await? - .map(|row| row.retired) - .unwrap_or(false); + // Same shape as [`retire_kind`]: the settled row is read *after* the + // refused flip, never carried over from this transaction's first + // snapshot — a rival's retirement may have committed in between, and + // that is success, not a refusal. let landed = sqlx::query!( r#"INSERT INTO slot_ref (name, count, retired) VALUES ($1, 0, TRUE) ON CONFLICT (name) DO UPDATE SET retired = TRUE @@ -284,12 +288,21 @@ async fn retire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppE .fetch_optional(&mut *tx) .await? .is_some(); - match (landed, was) { - (false, false) => Err(AppError::ConflictOwned(format!( + if landed { + return Ok(()); + } + let row = sqlx::query!( + r#"SELECT count AS "count!: i64" FROM slot_ref WHERE name = $1 FOR UPDATE"#, + name + ) + .fetch_one(&mut *tx) + .await?; + if row.count > 0 { + return Err(AppError::ConflictOwned(format!( "menus are already published for the '{name}' slot — it cannot be removed" - ))), - _ => Ok(()), + ))); } + Ok(()) } /// Put an exam kind back in service, inside the caller's transaction. One @@ -357,9 +370,11 @@ mod tests { /// The `retired` bit as the store holds it, `None` when no counter row was /// ever written — read back, never inferred from a return value. async fn ref_bit(db: &Database, table: &str, name: &str) -> Option { - let row = sqlx::query(&format!( + use sqlx::Row as _; + + let row = sqlx::query(sqlx::AssertSqlSafe(format!( "SELECT retired FROM {table} WHERE name = $1" - )) + ))) .bind(name) .fetch_optional(db) .await @@ -600,8 +615,12 @@ mod tests { async move { apply(&db, &without).await.map(|_| ()) } }); while !rival.is_finished() { - let (kinds, _) = stored(&db).await; + // The bit is read BEFORE the list: a `true` bit proves the edit's + // commit already landed, so the list read that follows cannot + // predate it. The other order races the commit between the two + // probes and "sees" a split that never existed. let retired = kind_bit(&db, "midterm").await; + let (kinds, _) = stored(&db).await; if retired == Some(true) { assert!( !kinds.contains(&"midterm".to_string()), diff --git a/src/tenant.rs b/src/tenant.rs index 8d4cbcb..4fd700f 100644 --- a/src/tenant.rs +++ b/src/tenant.rs @@ -620,8 +620,10 @@ mod tests { school_db_name(control, &slug("ata-koleji")), "hezarfen_control_school_ata_koleji" ); - for a in ["a", "a-b", "ab", "a1b", "1a", "x-y-z"] { - for b in ["a", "a-b", "ab", "a1b", "1a", "x-y-z"] { + // Slugs are at least two characters, so the shortest pair stands in + // for the old single-letter probe. + for a in ["ab", "a-b", "abc", "a1b", "1a", "x-y-z"] { + for b in ["ab", "a-b", "abc", "a1b", "1a", "x-y-z"] { if a != b { assert_ne!( school_db_name(control, &slug(a)), diff --git a/src/web/bank_questions.rs b/src/web/bank_questions.rs index 862a221..f838db1 100644 --- a/src/web/bank_questions.rs +++ b/src/web/bank_questions.rs @@ -948,10 +948,19 @@ mod tests { async fn demoted_owner_loses_their_own_template() { let (db, _leases) = init_test_db().await; let owner = user("ogretmen", Role::Teacher, &db).await; + // The subject is a foreign key: a real row, via the course fixture. + let subject = crate::db::subject::create( + &db, + &crate::db::course::a_test_course(&db).await, + crate::domain::subject::SubjectName::try_new("matematik").unwrap(), + crate::domain::subject::SubjectDescription::try_new("").unwrap(), + ) + .await + .unwrap(); let question = bank_question::create( &db, owner.get_id().clone(), - SubjectId::from_key("019732e3-7b00-7000-8000-00000000a2b3"), + subject.get_id().clone(), QuestionText::try_new("2 + 2 = ?").unwrap(), QuestionPoints::try_new(1).unwrap(), QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(), diff --git a/src/web/mod.rs b/src/web/mod.rs index 6395c7b..90fc496 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -381,7 +381,7 @@ mod tests { use crate::domain::user::{Password, Username}; let (db, _leases) = crate::database::init_test_db().await; - let office = UserId::from_key("office"); + let office = crate::db::class_member::tests::fixture_user(&db, "office").await; let teacher = crate::service::user::create( &db, Username::try_new("ada").unwrap(), @@ -463,11 +463,10 @@ mod tests { ); // Demoted with no sweep — the state a lost race leaves. - db.query("UPDATE $usr SET role = 'student'") - .bind(("usr", teacher.get_id().record())) + sqlx::query("UPDATE app_user SET role = 'student' WHERE id = $1") + .bind(teacher.get_id().uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); let refused = undo_if_demoted(teacher.get_id(), &db).await; assert!( diff --git a/src/web/payments.rs b/src/web/payments.rs index cc1daa4..b5e5ede 100644 --- a/src/web/payments.rs +++ b/src/web/payments.rs @@ -1087,8 +1087,10 @@ mod tests { #[tokio::test] async fn the_statement_rolls_each_charge_up_from_its_own_lines() { let (db, _leases) = crate::database::init_test_db().await; - let manager = UserId::from_key("mgr1"); - let student = UserId::from_key("stu1"); + let manager = + crate::db::class_member::tests::fixture_user(&db, "stmt-manager").await; + let student = + crate::db::class_member::tests::fixture_user(&db, "stmt-student").await; let future = Timestamp::now().as_millis() + 30 * 24 * 60 * 60 * 1000; let plan = service::fee_plan::create( &db, diff --git a/tests/persistence.rs b/tests/persistence.rs index 58a29d8..0f4edf1 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -1,46 +1,37 @@ -//! Boot-migration tests: age rows into the shapes old binaries left behind, -//! then re-run the idempotent migration on the same database — a second boot — -//! and assert the backfills repair (or deliberately destroy) them. The storage -//! engine itself is the SurrealDB server's concern since the embedded engine -//! was retired; these tests run on the in-memory engine like every other suite. +//! Boot-migration tests: seed a real deployment through the API, re-run the +//! idempotent migration over the same live database — a second boot — and +//! assert the seeded rows come back intact. The backfill-era machinery these +//! tests once exercised is gone with the old engine; what remains is the +//! durability contract: a migration must never disturb data that is already +//! there. mod common; use axum::Router; use axum::http::StatusCode; -use common::{create_course, create_exam, create_subject, enroll, me_id, send, set_role}; +use common::{create_course, create_subject, enroll, me_id, send, set_role}; use hezarfen_backend::database::Database; -use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::module::ModuleSet; use hezarfen_backend::rate_limit::RateLimitConfig; use hezarfen_backend::state::AppState; -use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants}; +use hezarfen_backend::tenant::{Slug, Tenants}; use hezarfen_backend::{build_router, database}; use serde_json::json; -/// Simulate a reboot: re-run the migration on the same database and hand back -/// a fresh router over it. -async fn reboot(db: &Database) -> Router { - database::migrate(db).await.expect("re-migration"); - // A new process: a new control database and a new connection cache, over - // the school store the old one left behind. - let tenants = Tenants::new_mem_adopting( - &Slug::try_new(DEMO_SLUG).unwrap(), - "Demo School", - db.clone(), - ) - .await - .expect("adopt the demo school"); +/// Re-apply the school schema to the live school database and hand back a +/// fresh router over the same deployment — a second boot in every way that +/// matters to these tests. +async fn reboot(db: &Database, tenants: &Tenants) -> Router { + database::migrate_school(db).await.expect("re-migration"); build_router(AppState { db: tenants.control().clone(), - tenants, + tenants: tenants.clone(), files_path: common::files_dir(), cookie_secure: false, rate_limit: RateLimitConfig::unlimited(), chatbot_limit: Default::default(), exam_presence: Default::default(), board_hub: Default::default(), - db_up: Default::default(), ai: None, metrics: hezarfen_backend::telemetry::Metrics::noop(), }) @@ -51,7 +42,7 @@ async fn reboot(db: &Database) -> Router { /// untouched by the re-applied idempotent migration. #[tokio::test] async fn settings_and_terms_survive_remigration() { - let (app, db) = common::app_and_db().await; + let (app, db, tenants) = common::app_and_tenants().await; let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" }); send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; @@ -99,7 +90,7 @@ async fn settings_and_terms_survive_remigration() { assert_eq!(res.status, StatusCode::CREATED); // Second boot: migration re-applied over live data. - let app = reboot(&db).await; + let app = reboot(&db, &tenants).await; let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) .await .cookie @@ -126,1841 +117,494 @@ async fn settings_and_terms_survive_remigration() { assert_eq!(courses[0]["term"].as_str(), Some(term.as_str())); } -/// Event rows written before the `audience` column existed are backfilled to -/// school-wide on the next boot (`UPDATE event SET audience = { kind: 'school' } -/// WHERE audience = NONE`), so an old volume keeps serving its events. +/// A weekly appointment series and a booking that carries a full proposal +/// triple survive the re-applied migration, exact unix-ms stamps and all. #[tokio::test] -async fn legacy_events_backfill_to_school_audience() { - let (app, db) = common::app_and_db().await; - let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); +async fn appointments_survive_remigration() { + /// Far enough ahead to clear `check_not_past` without touching the clock, + /// and deliberately not a round number of seconds. + const START: i64 = 1_900_000_000_123; + const END: i64 = 1_900_000_003_777; + const WEEK: i64 = 7 * 24 * 60 * 60 * 1000; + const PROPOSED_START: i64 = START + 5_000_001; + const PROPOSED_END: i64 = START + 8_000_003; - // A normal event — then strip its audience the way an old binary's schema - // would have left it: drop the column definitions so SCHEMAFULL stops - // enforcing them, and unset the field on the row. - assert_eq!( - send(&app, "POST", "/auth/register", None, Some(creds.clone())) - .await - .status, - StatusCode::CREATED - ); + let (app, db, tenants) = common::app_and_tenants().await; + let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); + let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); + for creds in [&teacher_creds, &student_creds] { + assert_eq!( + send(&app, "POST", "/auth/register", None, Some((*creds).clone())) + .await + .status, + StatusCode::CREATED + ); + } set_role(&db, "ali", "teacher").await; - let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) - .await - .cookie - .unwrap(); - let res = send( + let teacher = send( &app, "POST", - "/events", - Some(&cookie), - Some(json!({ "title": "before audiences" })), - ) - .await; - assert_eq!(res.status, StatusCode::CREATED); - let event_id = common::id_of(&res.body); - - db.query( - "REMOVE FIELD IF EXISTS audience.users ON TABLE event; - REMOVE FIELD IF EXISTS audience.course ON TABLE event; - REMOVE FIELD IF EXISTS audience.role ON TABLE event; - REMOVE FIELD IF EXISTS audience.kind ON TABLE event; - REMOVE FIELD IF EXISTS audience ON TABLE event; - UPDATE event SET audience = NONE;", - ) - .await - .expect("strip audience") - .check() - .expect("strip audience check"); - - // Second boot re-runs the migration: the field definitions come back and - // the backfill stamps the legacy row school-wide — it reads, lists, and - // rosters like any new event. - let app = reboot(&db).await; - let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) - .await - .cookie - .unwrap(); - let res = send( - &app, - "GET", - &format!("/events/{event_id}"), - Some(&cookie), + "/auth/login", None, + Some(teacher_creds.clone()), ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(res.body["audience"]["kind"], "school"); - let res = send( + .await + .cookie + .unwrap(); + let student = send( &app, - "GET", - &format!("/events/{event_id}/roster"), - Some(&cookie), + "POST", + "/auth/login", None, + Some(student_creds.clone()), ) - .await; - assert_eq!(res.status, StatusCode::OK); - assert_eq!(common::total(&res.body), 1, "whole school = the one user"); -} - -/// Event rows carrying the retired hand-picked (`users`) audience convert on -/// the next boot: the audience becomes an uncapped registration list and each -/// listed user gets a signup row credited to the event's creator — the old -/// roster survives the clean break byte for byte. -#[tokio::test] -async fn legacy_users_audiences_convert_to_registrations() { - let (app, db) = common::app_and_db().await; - let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); - - // A registration-audience event — then rewrite it into the shape an old - // binary left behind: restore the `audience.users` column definition and - // store a hand-picked list on the row. - assert_eq!( - send(&app, "POST", "/auth/register", None, Some(creds.clone())) - .await - .status, - StatusCode::CREATED - ); - set_role(&db, "ali", "teacher").await; - let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) - .await - .cookie - .unwrap(); - let student = json!({ "school": "demo", "username": "veli", "password": "secret1" }); - assert_eq!( - send(&app, "POST", "/auth/register", None, Some(student.clone())) - .await - .status, - StatusCode::CREATED - ); - let student_cookie = send(&app, "POST", "/auth/login", None, Some(student)) - .await - .cookie - .unwrap(); - let student_id = common::me_id(&app, &student_cookie).await; + .await + .cookie + .unwrap(); + // A weekly publish: three occurrences sharing one series id and one note. let res = send( &app, "POST", - "/events", - Some(&cookie), - Some(json!({ "title": "trip", "audience": { "kind": "registration" } })), + "/appointments/slots", + Some(&teacher), + Some(json!({ + "starts_at": START, + "ends_at": END, + "note": "veli görüşmesi", + "repeat_weekly": true, + "until": START + 2 * WEEK, + })), ) .await; - assert_eq!(res.status, StatusCode::CREATED); - let event_id = common::id_of(&res.body); - - db.query(format!( - "DEFINE FIELD OVERWRITE audience.users ON TABLE event TYPE option>>; - UPDATE event SET audience = {{ kind: 'users', users: [type::record('user', $usr)] }} - WHERE id = type::record('event', '{event_id}');" - )) - .bind(("usr", student_id.clone())) - .await - .expect("rewrite to legacy users audience") - .check() - .expect("rewrite check"); + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let published = res + .body + .as_array() + .expect("publish returns an array") + .clone(); + assert_eq!(published.len(), 3, "{}", res.body); + let slot_id = published[0]["id"].as_str().unwrap().to_string(); + let series = published[0]["series"].as_str().unwrap().to_string(); + let slot_created_at = published[0]["created_at"].as_i64().unwrap(); - // Second boot runs the conversion: the audience reads back as an uncapped - // registration list, the listed student holds a seat credited to the - // creator, and the roster (and marking gate) see them. - let app = reboot(&db).await; - let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) - .await - .cookie - .unwrap(); + // Book the first occurrence, counter-propose another time, accept it — the + // row then carries every optional column at once. let res = send( &app, - "GET", - &format!("/events/{event_id}"), - Some(&cookie), - None, + "POST", + "/appointments", + Some(&student), + Some(json!({ "slot": slot_id, "reason": "ödev" })), ) .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(res.body["audience"]["kind"], "registration"); - assert!(res.body["audience"]["capacity"].is_null()); + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let appointment = common::id_of(&res.body); + let created_at = res.body["created_at"].as_i64().unwrap(); let res = send( &app, - "GET", - &format!("/events/{event_id}/roster"), - Some(&cookie), - None, + "PATCH", + &format!("/appointments/{appointment}/reschedule"), + Some(&teacher), + Some(json!({ "starts_at": PROPOSED_START, "ends_at": PROPOSED_END })), ) .await; - assert_eq!(res.status, StatusCode::OK); - assert_eq!(common::total(&res.body), 1, "the listed user became a seat"); - assert_eq!(common::items(&res.body)[0]["user"]["id"], student_id); + assert_eq!(res.status, StatusCode::OK, "{}", res.body); let res = send( &app, - "POST", - &format!("/events/{event_id}/attendance"), - Some(&cookie), - Some(json!({ "status": "present", "user_id": student_id })), + "PATCH", + &format!("/appointments/{appointment}/reschedule/accept"), + Some(&student), + Some(json!({ + "proposed_starts_at": PROPOSED_START, + "proposed_ends_at": PROPOSED_END, + })), ) .await; - assert_eq!(res.status, StatusCode::OK, "converted seat is markable"); -} - -/// Exam-question rows written before subjects existed (2026-07) are destroyed -/// on the next boot, answers first — a subject is mandatory and there is -/// nothing truthful to backfill. The exam and the course's subjects survive. -#[tokio::test] -async fn legacy_subjectless_questions_are_destroyed_on_boot() { - let (app, db) = common::app_and_db().await; - let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); + assert_eq!(res.status, StatusCode::OK, "{}", res.body); - // A full exam — course, subject, open exam, one answered question — then - // strip the question's subject the way an old binary's schema would have - // left it. - assert_eq!( - send(&app, "POST", "/auth/register", None, Some(creds.clone())) - .await - .status, - StatusCode::CREATED - ); - set_role(&db, "ali", "teacher").await; - let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) + // Second boot: migration re-applied over live data. + let app = reboot(&db, &tenants).await; + let teacher = send(&app, "POST", "/auth/login", None, Some(teacher_creds)) .await .cookie .unwrap(); - let student = json!({ "school": "demo", "username": "veli", "password": "secret1" }); - assert_eq!( - send(&app, "POST", "/auth/register", None, Some(student.clone())) - .await - .status, - StatusCode::CREATED - ); - let student_cookie = send(&app, "POST", "/auth/login", None, Some(student)) + let student = send(&app, "POST", "/auth/login", None, Some(student_creds)) .await .cookie .unwrap(); - let student_id = common::me_id(&app, &student_cookie).await; - let course = create_course(&app, &cookie, "algebra").await; - enroll(&app, &cookie, &course, &student_id).await; - let res = send( + let res = send(&app, "GET", "/appointments/slots", Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(common::total(&res.body), 3, "{}", res.body); + let slots = common::items(&res.body); + assert_eq!(slots[0]["id"], slot_id.as_str()); + assert_eq!(slots[0]["starts_at"], START, "exact unix-ms, not rounded"); + assert_eq!(slots[0]["ends_at"], END); + assert_eq!(slots[0]["note"], "veli görüşmesi"); + assert_eq!(slots[0]["created_at"], slot_created_at); + for (week, slot) in slots.iter().enumerate() { + assert_eq!(slot["series"], series.as_str(), "one series, all weeks"); + assert_eq!(slot["starts_at"], START + week as i64 * WEEK); + assert_eq!(slot["ends_at"], END + week as i64 * WEEK); + } + + let res = send(&app, "GET", "/appointments", Some(&student), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(common::total(&res.body), 1, "{}", res.body); + let booking = &common::items(&res.body)[0]; + assert_eq!(booking["id"], appointment.as_str()); + assert_eq!(booking["slot"], slot_id.as_str()); + assert_eq!(booking["status"], "approved"); + assert_eq!(booking["reason"], "ödev"); + assert_eq!(booking["proposed_starts_at"], PROPOSED_START); + assert_eq!(booking["proposed_ends_at"], PROPOSED_END); + assert_eq!(booking["proposed_by"]["username"], "ali"); + assert_eq!(booking["decided_by"]["username"], "ayse"); + // The accepted proposal *is* the meeting's time; the slot's own window lost. + assert_eq!(booking["starts_at"], PROPOSED_START); + assert_eq!(booking["ends_at"], PROPOSED_END); + assert_eq!(booking["teacher"]["username"], "ali"); + assert_eq!(booking["requester"]["username"], "ayse"); + assert_eq!(booking["created_at"], created_at); +} + +/// Per-attempt exam history is durable, not just an in-request join: two +/// sittings' answers and marks (keyed by `seq`) written before a reboot come +/// back with the right seq afterwards — the seq-1 answer keeps its own text and +/// both marks survive, oldest first, with seq 2 as the grade-of-record. +#[tokio::test] +async fn attempt_history_survives_remigration() { + let (app, db, tenants) = common::app_and_tenants().await; + let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); + let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); + for creds in [&teacher_creds, &student_creds] { + assert_eq!( + send(&app, "POST", "/auth/register", None, Some((*creds).clone())) + .await + .status, + StatusCode::CREATED + ); + } + set_role(&db, "ali", "teacher").await; + let teacher = send( &app, "POST", - &format!("/courses/{course}/subjects"), - Some(&cookie), - Some(json!({ "name": "arithmetic" })), + "/auth/login", + None, + Some(teacher_creds.clone()), ) - .await; - assert_eq!(res.status, StatusCode::CREATED); - let subject_id = common::id_of(&res.body); - let res = send( + .await + .cookie + .unwrap(); + let student = send( &app, "POST", - &format!("/courses/{course}/exams"), - Some(&cookie), - Some(json!({ "title": "drill", "kind": "quiz", "mode": "open" })), + "/auth/login", + None, + Some(student_creds.clone()), ) - .await; - assert_eq!(res.status, StatusCode::CREATED); - let exam_id = common::id_of(&res.body); + .await + .cookie + .unwrap(); + let student_id = me_id(&app, &student).await; + + let course = create_course(&app, &teacher, "biology").await; + let subject = create_subject(&app, &teacher, &course, "cells").await; + enroll(&app, &teacher, &course, &student_id).await; let res = send( &app, "POST", - &format!("/exams/{exam_id}/questions"), - Some(&cookie), - Some( - json!({ "subject_id": subject_id, "text": "2 + 2?", "kind": "choice", - "points": 10, "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), - ), + &format!("/courses/{course}/exams"), + Some(&teacher), + Some(json!({ "title": "quiz", "kind": "quiz", "mode": "open", "max_attempts": 2 })), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let question_id = common::id_of(&res.body); - // Choice ids are minted server-side, so the answer names one off the response. - let picked = res.body["choices"][1]["id"] - .as_str() - .expect("choice id") - .to_string(); + let exam = common::id_of(&res.body); let res = send( &app, "POST", - &format!("/exams/{exam_id}/attempt"), - Some(&student_cookie), - None, + &format!("/exams/{exam}/questions"), + Some(&teacher), + Some(json!({ "subject_id": subject, "text": "Name an organelle.", + "kind": "text", "points": 10 })), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let res = send( - &app, - "POST", - &format!("/exams/{exam_id}/attempt/answers"), - Some(&student_cookie), - Some(json!({ "question_id": question_id, "selected": picked })), - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - - db.query( - "REMOVE FIELD IF EXISTS subject ON TABLE exam_question; - UPDATE exam_question SET subject = NONE;", - ) - .await - .expect("strip subject") - .check() - .expect("strip subject check"); - - // Second boot re-runs the migration and the destroy-backfill: the - // subjectless question and its answer are gone, the exam and subject - // still stand. - let app = reboot(&db).await; - let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) - .await - .cookie - .unwrap(); - let res = send( - &app, - "GET", - &format!("/exams/{exam_id}/questions"), - Some(&cookie), - None, - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(common::total(&res.body), 0, "legacy questions destroyed"); - let res = send( - &app, - "GET", - &format!("/subjects/{subject_id}"), - Some(&cookie), - None, - ) - .await; - assert_eq!(res.status, StatusCode::OK, "the subject itself survives"); - let mut result = db - .query("SELECT VALUE id FROM exam_answer") - .await - .expect("count answers") - .check() - .expect("count answers check"); - let answers: Vec = result.take(0).expect("answer rows"); - assert!(answers.is_empty(), "orphaned answers destroyed"); -} - -/// Enrollment rows whose user is no longer a student — promoted before the -/// role endpoint swept enrollments (2026-07-18), or deleted outright — are -/// removed by the boot backfill. A real student's row survives. -#[tokio::test] -async fn stale_staff_enrollments_are_swept_on_boot() { - let (app, db) = common::app_and_db().await; - let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); - - // A course with three enrolled students, then age two rows the way a - // pre-fix binary could have — flip one student to teacher directly in the - // DB, and delete the other's user record entirely. - assert_eq!( - send(&app, "POST", "/auth/register", None, Some(creds.clone())) - .await - .status, - StatusCode::CREATED - ); - set_role(&db, "ali", "teacher").await; - let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) - .await - .cookie - .unwrap(); - let course = create_course(&app, &cookie, "algebra").await; - - let mut ids = Vec::new(); - for name in ["veli", "ayse", "can"] { - let student = json!({ "school": "demo", "username": name, "password": "secret1" }); - assert_eq!( - send(&app, "POST", "/auth/register", None, Some(student.clone())) - .await - .status, - StatusCode::CREATED - ); - let student_cookie = send(&app, "POST", "/auth/login", None, Some(student)) - .await - .cookie - .unwrap(); - let id = me_id(&app, &student_cookie).await; - enroll(&app, &cookie, &course, &id).await; - ids.push(id); - } - let keeper_id = ids[1].clone(); - set_role(&db, "veli", "teacher").await; - db.query("DELETE user WHERE username = 'can'") - .await - .expect("delete user") - .check() - .expect("delete user check"); - - // Second boot: the backfill swept the promoted user's row and the deleted - // user's dangling row; the remaining student's enrollment is intact. - let app = reboot(&db).await; - let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) - .await - .cookie - .unwrap(); - let roster = send( - &app, - "GET", - &format!("/courses/{course}/enrollments"), - Some(&cookie), - None, - ) - .await; - assert_eq!(roster.status, StatusCode::OK, "{}", roster.body); - assert_eq!( - common::total(&roster.body), - 1, - "stale rows swept: {}", - roster.body - ); - assert_eq!( - common::items(&roster.body)[0]["user"]["id"], - keeper_id.as_str(), - "the real student's row survives" - ); -} - -/// The seat goes back with the swept row. The sweep above deletes enrollments -/// whose holder is no longer a student, and for every boot it ever ran it kept -/// their seats: the course stayed as full as it was, so a real student was -/// refused a place that nobody held. Two rows of the *same* course go here, -/// because the counter has to come down once per row and not once per course. -/// -/// The repair pass runs *before* the sweep, so it cannot stand in for the -/// decrement being asserted here: at that point both rows are still there and -/// the counter already agrees with them. -#[tokio::test] -async fn a_swept_enrollment_gives_the_course_its_seat_back() { - let (app, db) = common::app_and_db().await; - let teacher = common::login_as(&app, &db, "teacher", "teacher").await; - let res = send( - &app, - "POST", - "/courses", - Some(&teacher), - Some(json!({ "title": "small", "description": "", "capacity": 2 })), - ) - .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let course = common::id_of(&res.body); - - for name in ["veli", "ayse"] { - let cookie = common::login(&app, name).await; - let id = me_id(&app, &cookie).await; - enroll(&app, &teacher, &course, &id).await; - } - // Aged the way a pre-2026-07-18 promotion left them: the role moved on the - // row itself, so no endpoint ever released the seat. - set_role(&db, "veli", "teacher").await; - set_role(&db, "ayse", "manager").await; - - let app = reboot(&db).await; - let mut counter = db - .query("SELECT VALUE enrollment_count FROM course") - .await - .expect("read the counter") - .check() - .expect("read the counter"); - assert_eq!( - counter.take::>(0).expect("enrollment_count"), - vec![0], - "both swept rows must hand their seats back" - ); - - // The user-visible half: the capacity is free again, so a real student gets - // the place the phantom seats were denying them. - let can = common::login(&app, "can").await; - let can_id = me_id(&app, &can).await; - let res = send( - &app, - "POST", - &format!("/courses/{course}/enrollments"), - Some(&teacher), - Some(json!({ "user_id": can_id })), - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); -} - -/// The repair for the drift past boots already left behind: a course whose -/// `enrollment_count` outran its roster is recounted from the rows it actually -/// has. The symptom that makes it worth a boot pass is the delete guard — -/// `Course::delete` refuses on `(enrollment_count ?? 0) = 0`, so a course -/// carrying a phantom seat can never be deleted by anyone — so that is what is -/// asserted, not just the number. -/// -/// The second course pins the other direction: the repair recounts to the -/// roster, never to zero, so a course with real students keeps its seats. -#[tokio::test] -async fn a_course_whose_count_outran_its_roster_is_repaired_and_deletable() { - let (app, db) = common::app_and_db().await; - let teacher = common::login_as(&app, &db, "teacher", "teacher").await; - let stranded = create_course(&app, &teacher, "stranded").await; - let live = create_course(&app, &teacher, "live").await; - let student = common::login(&app, "veli").await; - let student_id = me_id(&app, &student).await; - enroll(&app, &teacher, &live, &student_id).await; - - // The state every past run of the sweep left: rows gone, seats not. - db.query( - "UPDATE type::record('course', $stranded) SET enrollment_count = 3; - UPDATE type::record('course', $live) SET enrollment_count = 5;", - ) - .bind(("stranded", stranded.clone())) - .bind(("live", live.clone())) - .await - .expect("age the counters") - .check() - .expect("age the counters"); - - let app = reboot(&db).await; - let mut counters = db - .query("SELECT VALUE enrollment_count FROM course ORDER BY id") - .await - .expect("read the counters") - .check() - .expect("read the counters"); - let mut stored = counters.take::>(0).expect("enrollment_count"); - stored.sort_unstable(); - assert_eq!( - stored, - vec![0, 1], - "each course is recounted from its own rows" - ); - - let res = send( - &app, - "DELETE", - &format!("/courses/{stranded}"), - Some(&teacher), - None, - ) - .await; - assert_eq!( - res.status, - StatusCode::NO_CONTENT, - "a repaired course is deletable again: {}", - res.body - ); - // And the one with a real student on it is still guarded. - let res = send( - &app, - "DELETE", - &format!("/courses/{live}"), - Some(&teacher), - None, - ) - .await; - assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); -} - -/// Exam rows written before the draft flag existed (2026-07-19) backfill to -/// published (`draft = false`) on the next boot — an old volume's exams stay -/// exactly as visible as they were. -#[tokio::test] -async fn legacy_exams_backfill_to_published() { - let (app, db) = common::app_and_db().await; - let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); - let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); - - // A normal exam — then strip `draft` the way an old binary's schema would - // have left it. - for creds in [&teacher_creds, &student_creds] { - assert_eq!( - send(&app, "POST", "/auth/register", None, Some((*creds).clone())) - .await - .status, - StatusCode::CREATED - ); - } - set_role(&db, "ali", "teacher").await; - let teacher = send( - &app, - "POST", - "/auth/login", - None, - Some(teacher_creds.clone()), - ) - .await - .cookie - .unwrap(); - let student = send( - &app, - "POST", - "/auth/login", - None, - Some(student_creds.clone()), - ) - .await - .cookie - .unwrap(); - let student_id = me_id(&app, &student).await; - let course = create_course(&app, &teacher, "algebra").await; - enroll(&app, &teacher, &course, &student_id).await; - let exam_id = create_exam(&app, &teacher, &course, "midterm", "midterm").await; - - db.query( - "REMOVE FIELD IF EXISTS draft ON TABLE exam; - UPDATE exam SET draft = NONE;", - ) - .await - .expect("strip draft") - .check() - .expect("strip draft check"); - - // Second boot re-runs the migration: the legacy exam reads back published - // and the enrolled student still sees it. - let app = reboot(&db).await; - let student = send(&app, "POST", "/auth/login", None, Some(student_creds)) - .await - .cookie - .unwrap(); - let res = send( - &app, - "GET", - &format!("/exams/{exam_id}"), - Some(&student), - None, - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(res.body["draft"], false); - let listed = send(&app, "GET", "/exams", Some(&student), None).await; - assert_eq!(common::items(&listed.body).len(), 1); -} - -/// A recurring publish and the booking sitting on it survive a second boot: -/// the slot's `note` and shared `series`, and the booking's counter-proposal -/// triple, `decided_by` and `status`, all come back untouched by the -/// re-applied migration. Every time in this schema is a unix-millisecond -/// `TYPE int` — never a `datetime` — so the round trip is asserted on odd -/// millisecond values, which any lossy conversion would round off. -#[tokio::test] -async fn appointments_survive_remigration() { - /// Far enough ahead to clear `check_not_past` without touching the clock, - /// and deliberately not a round number of seconds. - const START: i64 = 1_900_000_000_123; - const END: i64 = 1_900_000_003_777; - const WEEK: i64 = 7 * 24 * 60 * 60 * 1000; - const PROPOSED_START: i64 = START + 5_000_001; - const PROPOSED_END: i64 = START + 8_000_003; - - let (app, db) = common::app_and_db().await; - let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); - let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); - for creds in [&teacher_creds, &student_creds] { - assert_eq!( - send(&app, "POST", "/auth/register", None, Some((*creds).clone())) - .await - .status, - StatusCode::CREATED - ); - } - set_role(&db, "ali", "teacher").await; - let teacher = send( - &app, - "POST", - "/auth/login", - None, - Some(teacher_creds.clone()), - ) - .await - .cookie - .unwrap(); - let student = send( - &app, - "POST", - "/auth/login", - None, - Some(student_creds.clone()), - ) - .await - .cookie - .unwrap(); - - // A weekly publish: three occurrences sharing one series id and one note. - let res = send( - &app, - "POST", - "/appointments/slots", - Some(&teacher), - Some(json!({ - "starts_at": START, - "ends_at": END, - "note": "veli görüşmesi", - "repeat_weekly": true, - "until": START + 2 * WEEK, - })), - ) - .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let published = res - .body - .as_array() - .expect("publish returns an array") - .clone(); - assert_eq!(published.len(), 3, "{}", res.body); - let slot_id = published[0]["id"].as_str().unwrap().to_string(); - let series = published[0]["series"].as_str().unwrap().to_string(); - let slot_created_at = published[0]["created_at"].as_i64().unwrap(); - - // Book the first occurrence, counter-propose another time, accept it — the - // row then carries every optional column at once: a proposal triple, a - // decider, and `approved`. - let res = send( - &app, - "POST", - "/appointments", - Some(&student), - Some(json!({ "slot": slot_id, "reason": "ödev" })), - ) - .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let appointment = common::id_of(&res.body); - let created_at = res.body["created_at"].as_i64().unwrap(); - let res = send( - &app, - "PATCH", - &format!("/appointments/{appointment}/reschedule"), - Some(&teacher), - Some(json!({ "starts_at": PROPOSED_START, "ends_at": PROPOSED_END })), - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - let res = send( - &app, - "PATCH", - &format!("/appointments/{appointment}/reschedule/accept"), - Some(&student), - Some(json!({ - "proposed_starts_at": PROPOSED_START, - "proposed_ends_at": PROPOSED_END, - })), - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - - // Second boot: migration re-applied over live data. - let app = reboot(&db).await; - let teacher = send(&app, "POST", "/auth/login", None, Some(teacher_creds)) - .await - .cookie - .unwrap(); - let student = send(&app, "POST", "/auth/login", None, Some(student_creds)) - .await - .cookie - .unwrap(); - - let res = send(&app, "GET", "/appointments/slots", Some(&teacher), None).await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(common::total(&res.body), 3, "{}", res.body); - let slots = common::items(&res.body); - assert_eq!(slots[0]["id"], slot_id.as_str()); - assert_eq!(slots[0]["starts_at"], START, "exact unix-ms, not rounded"); - assert_eq!(slots[0]["ends_at"], END); - assert_eq!(slots[0]["note"], "veli görüşmesi"); - assert_eq!(slots[0]["created_at"], slot_created_at); - for (week, slot) in slots.iter().enumerate() { - assert_eq!(slot["series"], series.as_str(), "one series, all weeks"); - assert_eq!(slot["starts_at"], START + week as i64 * WEEK); - assert_eq!(slot["ends_at"], END + week as i64 * WEEK); - } - - let res = send(&app, "GET", "/appointments", Some(&student), None).await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(common::total(&res.body), 1, "{}", res.body); - let booking = &common::items(&res.body)[0]; - assert_eq!(booking["id"], appointment.as_str()); - assert_eq!(booking["slot"], slot_id.as_str()); - assert_eq!(booking["status"], "approved"); - assert_eq!(booking["reason"], "ödev"); - assert_eq!(booking["proposed_starts_at"], PROPOSED_START); - assert_eq!(booking["proposed_ends_at"], PROPOSED_END); - assert_eq!(booking["proposed_by"]["username"], "ali"); - assert_eq!(booking["decided_by"]["username"], "ayse"); - // The accepted proposal *is* the meeting's time; the slot's own window lost. - assert_eq!(booking["starts_at"], PROPOSED_START); - assert_eq!(booking["ends_at"], PROPOSED_END); - assert_eq!(booking["teacher"]["username"], "ali"); - assert_eq!(booking["requester"]["username"], "ayse"); - assert_eq!(booking["created_at"], created_at); -} - -/// Per-attempt exam history is durable, not just an in-request join: two -/// sittings' answers and marks (keyed by `seq`) written before a reboot come -/// back with the right seq afterwards — the seq-1 answer keeps its own text and -/// both marks survive, oldest first, with seq 2 as the grade-of-record. -#[tokio::test] -async fn attempt_history_survives_remigration() { - let (app, db) = common::app_and_db().await; - let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); - let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); - for creds in [&teacher_creds, &student_creds] { - assert_eq!( - send(&app, "POST", "/auth/register", None, Some((*creds).clone())) - .await - .status, - StatusCode::CREATED - ); - } - set_role(&db, "ali", "teacher").await; - let teacher = send( - &app, - "POST", - "/auth/login", - None, - Some(teacher_creds.clone()), - ) - .await - .cookie - .unwrap(); - let student = send( - &app, - "POST", - "/auth/login", - None, - Some(student_creds.clone()), - ) - .await - .cookie - .unwrap(); - let student_id = me_id(&app, &student).await; - - let course = create_course(&app, &teacher, "biology").await; - let subject = create_subject(&app, &teacher, &course, "cells").await; - enroll(&app, &teacher, &course, &student_id).await; - let res = send( - &app, - "POST", - &format!("/courses/{course}/exams"), - Some(&teacher), - Some(json!({ "title": "quiz", "kind": "quiz", "mode": "open", "max_attempts": 2 })), - ) - .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let exam = common::id_of(&res.body); - let res = send( - &app, - "POST", - &format!("/exams/{exam}/questions"), - Some(&teacher), - Some(json!({ "subject_id": subject, "text": "Name an organelle.", - "kind": "text", "points": 10 })), - ) - .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let question = common::id_of(&res.body); - - // Two sittings: distinct answer text + distinct mark on each. - for (text, mark) in [("mitochondria", 40), ("chloroplast", 90)] { - assert_eq!( - send( - &app, - "POST", - &format!("/exams/{exam}/attempt"), - Some(&student), - None - ) - .await - .status, - StatusCode::CREATED - ); - let res = send( - &app, - "POST", - &format!("/exams/{exam}/attempt/answers"), - Some(&student), - Some(json!({ "question_id": question, "text": text })), - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - let res = send( - &app, - "POST", - &format!("/exams/{exam}/results"), - Some(&teacher), - Some(json!({ "mark": mark, "user_id": student_id })), - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - send( - &app, - "POST", - &format!("/exams/{exam}/attempt/finish"), - Some(&student), - None, - ) - .await; - } - - // Second boot: migration re-applied over the two sittings' live rows. - let app = reboot(&db).await; - let teacher = send(&app, "POST", "/auth/login", None, Some(teacher_creds)) - .await - .cookie - .unwrap(); - - let res = send( - &app, - "GET", - &format!("/exams/{exam}/students/{student_id}/attempts"), - Some(&teacher), - None, - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(res.body, json!([1, 2]), "both sittings survived the reboot"); - - // The seq-1 answer kept its own text through the reopen. - let res = send( - &app, - "GET", - &format!("/exams/{exam}/students/{student_id}/attempts/1/answers"), - Some(&teacher), - None, - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(res.body["answers"][0]["text"], "mitochondria"); - - // Both marks survive, oldest first; the roster's grade-of-record is seq 2. - let res = send( - &app, - "GET", - &format!("/exams/{exam}/students/{student_id}/marks"), - Some(&teacher), - None, - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - let marks: Vec = res - .body - .as_array() - .unwrap() - .iter() - .map(|r| r["mark"].as_i64().unwrap()) - .collect(); - assert_eq!( - marks, - vec![40, 90], - "both sittings' marks durable, oldest first" - ); - let res = send( - &app, - "GET", - &format!("/exams/{exam}/results"), - Some(&teacher), - None, - ) - .await; - assert_eq!( - common::items(&res.body)[0]["mark"], - 90, - "seq 2 is grade-of-record" - ); -} - -/// A chatbot thread and every turn in it die together: deleting the -/// thread cascades its `chatbot_message` rows in one transaction, so no -/// orphan survives a reboot. And the thread is owner-scoped end to end — a -/// second user reads neither the thread nor its messages. -#[tokio::test] -async fn chat_thread_delete_cascades_and_stays_owner_scoped() { - use hezarfen_backend::db::{chatbot_message, chatbot_thread}; - use hezarfen_backend::domain::chatbot_message::{ChatContent, MessageStatus}; - use hezarfen_backend::domain::user::UserId; - - let (app, db) = common::app_and_db().await; - let owner_cookie = common::login(&app, "ali").await; - let other_cookie = common::login(&app, "ayse").await; - let owner = UserId::from_key(&me_id(&app, &owner_cookie).await); - let other = UserId::from_key(&me_id(&app, &other_cookie).await); - - let thread = chatbot_thread::create_capped(&db, &owner, None) - .await - .expect("create"); - let id = thread.get_id().clone(); - let prompt = chatbot_message::append_user( - &db, - &id, - &owner, - ChatContent::try_new("selam").expect("content"), - ) - .await - .expect("append user"); - let reply = chatbot_message::append_pending_assistant(&db, &id, &owner) - .await - .expect("append assistant"); - assert_eq!(reply.get_status(), MessageStatus::Pending); - - let reply = chatbot_message::complete( - &db, - reply.get_id(), - ChatContent::try_new("aleykum selam").expect("content"), - false, - ) - .await - .expect("complete"); - assert_eq!(reply.get_status(), MessageStatus::Complete); - assert_eq!(reply.get_content().as_str(), "aleykum selam"); - assert!(reply.get_completed_at().is_some()); - assert_eq!( - chatbot_message::list_for_thread(&db, &id, None, 0) - .await - .expect("thread") - .0 - .len(), - 2 - ); - - // The other user sees nothing of it, by thread or by message. - assert!( - chatbot_thread::read_for(&db, &id, &other) - .await - .expect("cross-user thread") - .is_none() - ); - assert!( - chatbot_message::read_for(&db, prompt.get_id(), &other) - .await - .expect("cross-user message") - .is_none() - ); - assert_eq!( - chatbot_thread::count_for_user(&db, &other) - .await - .expect("count"), - 0 - ); - assert_eq!( - chatbot_thread::count_for_user(&db, &owner) - .await - .expect("count"), - 1 - ); - - chatbot_thread::delete(&db, thread).await.expect("delete"); - assert!( - chatbot_thread::read_for(&db, &id, &owner) - .await - .expect("deleted thread") - .is_none() - ); - assert_eq!( - chatbot_thread::list_for_user(&db, &owner, None, 0) - .await - .unwrap() - .0 - .len(), - 0 - ); - // Not just the thread's own view: no `chatbot_message` row is left anywhere. - let mut left = db - .query("SELECT VALUE id FROM chatbot_message") - .await - .expect("sweep") - .check() - .expect("sweep check"); - assert!( - left.take::>(0) - .expect("ids") - .is_empty() - ); -} - -/// Chat turns written before the clipped-answer flag existed (2026-07-23) -/// backfill to `truncated = false` on the next boot: an old volume's answers -/// read back as whole, which is exactly how they were shown at the time. -#[tokio::test] -async fn legacy_chat_turns_backfill_to_untruncated() { - use hezarfen_backend::db::{chatbot_message, chatbot_thread}; - use hezarfen_backend::domain::chatbot_message::ChatContent; - use hezarfen_backend::domain::user::UserId; - - let (app, db) = common::app_and_db().await; - let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); - assert_eq!( - send(&app, "POST", "/auth/register", None, Some(creds.clone())) - .await - .status, - StatusCode::CREATED - ); - let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) - .await - .cookie - .unwrap(); - let owner = UserId::from_key(&me_id(&app, &cookie).await); - - let thread = chatbot_thread::create_capped(&db, &owner, None) - .await - .expect("create"); - let id = thread.get_id().clone(); - chatbot_message::append_user( - &db, - &id, - &owner, - ChatContent::try_new("selam").expect("content"), - ) - .await - .expect("append user"); - let reply = chatbot_message::append_pending_assistant(&db, &id, &owner) - .await - .expect("append assistant"); - chatbot_message::complete( - &db, - reply.get_id(), - ChatContent::try_new("aleykum selam").expect("content"), - false, - ) - .await - .expect("complete"); - - // Strip the column the way a pre-flag binary's schema would have left it. - db.query( - "REMOVE FIELD IF EXISTS truncated ON TABLE chatbot_message; - UPDATE chatbot_message SET truncated = NONE;", - ) - .await - .expect("strip truncated") - .check() - .expect("strip truncated check"); - - // Second boot: the backfill stamps the legacy rows, and the thread reads - // back through the API instead of failing to deserialize. - let app = reboot(&db).await; - let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) - .await - .cookie - .unwrap(); - let res = send( - &app, - "GET", - &format!("/chatbot/threads/{}/messages", id.key()), - Some(&cookie), - None, - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - let turns = common::items(&res.body); - assert_eq!(turns.len(), 2, "{}", res.body); - for turn in turns { - assert_eq!(turn["truncated"], false, "{turn}"); - } -} - -/// A settings singleton whose `meal_slots` predate `serving_minute` — the live -/// podman volume's shape — still reads, and still **saves**. The trap is the -/// compare-and-set in `save_if_unchanged`: it re-binds the loaded slot list as -/// the expected value, so if a slot object without the key round-tripped to one -/// *with* `serving_minute: NONE`, the guard would never match again and every -/// `PATCH /settings` would 409 forever on an upgraded database. -#[tokio::test] -async fn settings_slots_without_a_serving_minute_still_patch() { - let (app, db) = common::app_and_db().await; - - let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" }); - send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; - set_role(&db, "boss", "manager").await; - let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) - .await - .cookie - .unwrap(); - - // Materialize the singleton, then age its slots into the pre-serving-time - // shape: objects carrying nothing but a name. - let res = send( - &app, - "PATCH", - "/settings", - Some(&cookie), - Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 720 }] })), - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - db.query("UPDATE settings:school SET meal_slots = [{ name: 'lunch' }];") - .await - .expect("age slots") - .check() - .expect("age slots check"); - - // Second boot over that row: it reads back, with the field simply absent. - let app = reboot(&db).await; - let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) - .await - .cookie - .unwrap(); - let res = send(&app, "GET", "/settings", Some(&cookie), None).await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(res.body["meal_slots"][0]["name"], "lunch", "{}", res.body); - assert!( - res.body["meal_slots"][0]["serving_minute"].is_null(), - "{}", - res.body - ); - - // And a PATCH of an unrelated knob still lands: the CAS matched the aged - // row. This is the assertion that would have caught a `DEFAULT []` column. - let res = send( - &app, - "PATCH", - "/settings", - Some(&cookie), - Some(json!({ "max_file_bytes": 2048 })), - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(res.body["max_file_bytes"], 2048, "{}", res.body); - assert!( - res.body["meal_slots"][0]["serving_minute"].is_null(), - "{}", - res.body - ); - - // Setting the serving time on that legacy slot round-trips too. - let res = send( - &app, - "PATCH", - "/settings", - Some(&cookie), - Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 615 }] })), - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!( - res.body["meal_slots"][0]["serving_minute"], 615, - "{}", - res.body - ); -} - -/// Rows written before the cap counters existed (2026-07-27) carry no counter -/// at all, and an absent counter reads as zero — which would hand a full course -/// and a full note a clean slate. The backfill seeds each parent from the -/// children it actually has, so the caps keep holding across the upgrade. -#[tokio::test] -async fn cap_counters_are_seeded_from_the_rows_that_predate_them() { - let (app, db) = common::app_and_db().await; - let teacher = common::login_as(&app, &db, "teacher", "teacher").await; - let ali = common::login(&app, "ali").await; - let veli = common::login(&app, "veli").await; - let ayse = common::login(&app, "ayse").await; - let (ali_id, veli_id, ayse_id) = ( - me_id(&app, &ali).await, - me_id(&app, &veli).await, - me_id(&app, &ayse).await, - ); - - let res = send( - &app, - "POST", - "/courses", - Some(&teacher), - Some(json!({ "title": "small", "description": "", "capacity": 2 })), - ) - .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let course = common::id_of(&res.body); - enroll(&app, &teacher, &course, &ali_id).await; - enroll(&app, &teacher, &course, &veli_id).await; - - let res = send( - &app, - "POST", - "/notes", - Some(&ali), - Some(json!({ "title": "full", "content": "x" })), - ) - .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let note = common::id_of(&res.body); - for i in 0..10 { - let up = common::upload_file(&app, &ali, ¬e, &format!("f{i}.txt"), "", b"x").await; - assert_eq!(up.status, StatusCode::CREATED, "seed file {i}"); - } - - // Age both parents into the pre-counter shape. - db.query("UPDATE course UNSET enrollment_count; UPDATE note UNSET file_count;") - .await - .expect("age the rows") - .check() - .expect("age the rows"); - - let app = reboot(&db).await; - - let mut counters = db - .query("SELECT VALUE enrollment_count FROM course; SELECT VALUE file_count FROM note;") - .await - .expect("read counters") - .check() - .expect("read counters"); - assert_eq!( - counters.take::>(0).expect("enrollment_count"), - vec![2], - "the course counter must be seeded from its roster" - ); - assert_eq!( - counters.take::>(1).expect("file_count"), - vec![10], - "the note counter must be seeded from its files" - ); - - // And the caps still bite, which a zeroed counter would not have done. - let res = send( - &app, - "POST", - &format!("/courses/{course}/enrollments"), - Some(&teacher), - Some(json!({ "user_id": ayse_id })), - ) - .await; - assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); - let up = common::upload_file(&app, &ali, ¬e, "eleventh.txt", "", b"x").await; - assert_eq!(up.status, StatusCode::CONFLICT, "{}", up.body); -} - -/// The appointment slot's counter is the odd one out: it seeds from the -/// bookings that are still *live*, because a rejected or cancelled one gave the -/// slot back long before the column existed (2026-07-27). A slot aged into the -/// pre-counter shape must come back taken if someone is still waiting on it, -/// and free if nobody is — a flat recount of its rows would get the second case -/// wrong and lock a free slot out of the calendar for good. -#[tokio::test] -async fn slot_occupancy_is_seeded_from_the_bookings_that_are_still_live() { - let (app, db) = common::app_and_db().await; - let teacher = common::login_as(&app, &db, "teacher", "teacher").await; - let veli = common::login(&app, "veli").await; - let ayse = common::login(&app, "ayse").await; - let now = hezarfen_backend::domain::timestamp::Timestamp::now().as_millis(); - let hour = 3_600_000; + let question = common::id_of(&res.body); - async fn publish(app: &Router, who: &str, starts_at: i64) -> String { + // Two sittings: distinct answer text + distinct mark on each. + for (text, mark) in [("mitochondria", 40), ("chloroplast", 90)] { + assert_eq!( + send( + &app, + "POST", + &format!("/exams/{exam}/attempt"), + Some(&student), + None + ) + .await + .status, + StatusCode::CREATED + ); let res = send( - app, + &app, "POST", - "/appointments/slots", - Some(who), - Some(json!({ "starts_at": starts_at, "ends_at": starts_at + 3_600_000 })), + &format!("/exams/{exam}/attempt/answers"), + Some(&student), + Some(json!({ "question_id": question, "text": text })), ) .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - common::id_of(&res.body[0]) - } - async fn book(app: &Router, who: &str, slot: &str) -> common::Res { + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "POST", + &format!("/exams/{exam}/results"), + Some(&teacher), + Some(json!({ "mark": mark, "user_id": student_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); send( - app, + &app, "POST", - "/appointments", - Some(who), - Some(json!({ "slot": slot, "reason": "görüşme" })), + &format!("/exams/{exam}/attempt/finish"), + Some(&student), + None, ) - .await + .await; } - let taken = publish(&app, &teacher, now + hour).await; - let freed = publish(&app, &teacher, now + 3 * hour).await; - let held = common::id_of(&book(&app, &veli, &taken).await.body); - let gone = common::id_of(&book(&app, &veli, &freed).await.body); + // Second boot: migration re-applied over the two sittings' live rows. + let app = reboot(&db, &tenants).await; + let teacher = send(&app, "POST", "/auth/login", None, Some(teacher_creds)) + .await + .cookie + .unwrap(); + let res = send( &app, - "PATCH", - &format!("/appointments/{gone}/reject"), + "GET", + &format!("/exams/{exam}/students/{student_id}/attempts"), Some(&teacher), None, ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body, json!([1, 2]), "both sittings survived the reboot"); - // Age both slots into the pre-counter shape. - db.query("UPDATE appointment_slot UNSET occupied;") - .await - .expect("age the rows") - .check() - .expect("age the rows"); - - let app = reboot(&db).await; - - // The still-pending booking keeps its slot; the rejected one's slot is free. - let res = book(&app, &ayse, &taken).await; - assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); - let res = book(&app, &ayse, &freed).await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - - // And the seeded seat is still a seat, not a stuck flag: cancelling the - // held booking hands it back. + // The seq-1 answer kept its own text through the reopen. let res = send( &app, - "PATCH", - &format!("/appointments/{held}/cancel"), - Some(&veli), + "GET", + &format!("/exams/{exam}/students/{student_id}/attempts/1/answers"), + Some(&teacher), None, ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - let res = book(&app, &ayse, &taken).await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); -} - -/// A submission graded before the freeze moved into the database (2026-07-27) -/// carries no `graded_by_result` stamp, and an absent stamp is exactly what the -/// student's writes now take as "still open" — so without the backfill an -/// upgrade would quietly unfreeze every already-graded submission. The backfill -/// stamps each one from the grade it already has; graded-but-never-submitted -/// work has no row to stamp and must stay that way (the report reads -/// `submitted`/`missing` straight off its absence). -#[tokio::test] -async fn graded_submissions_are_stamped_by_the_backfill() { - let (app, db) = common::app_and_db().await; - let teacher = common::login_as(&app, &db, "teacher", "teacher").await; - let ali = common::login(&app, "ali").await; - let veli = common::login(&app, "veli").await; - let (ali_id, veli_id) = (me_id(&app, &ali).await, me_id(&app, &veli).await); - let course = create_course(&app, &teacher, "math").await; - let subject = create_subject(&app, &teacher, &course, "algebra").await; - enroll(&app, &teacher, &course, &ali_id).await; - enroll(&app, &teacher, &course, &veli_id).await; - let due_at = Timestamp::now().as_millis() + 86_400_000; - let hw = common::create_homework(&app, &teacher, &course, &subject, "essay", due_at).await; + assert_eq!(res.body["answers"][0]["text"], "mitochondria"); - // Ali hands in and is graded; Veli never hands in and is graded `missing`. + // Both marks survive, oldest first; the roster's grade-of-record is seq 2. let res = send( &app, - "POST", - &format!("/homework/{hw}/submission"), - Some(&ali), - Some(json!({ "text": "version A" })), + "GET", + &format!("/exams/{exam}/students/{student_id}/marks"), + Some(&teacher), + None, ) .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - for (user, status) in [(&ali_id, "done"), (&veli_id, "missing")] { - let res = send( - &app, - "POST", - &format!("/homework/{hw}/results"), - Some(&teacher), - Some(json!({ "user": user, "status": status })), - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - } - - // Age the row into the pre-stamp shape. - db.query("UPDATE homework_submission UNSET graded_by_result;") - .await - .expect("age the row") - .check() - .expect("age the row"); - let app = reboot(&db).await; - - let mut stamps = db - .query("SELECT VALUE graded_by_result FROM homework_submission; SELECT VALUE id FROM homework_submission;") - .await - .expect("read stamps") - .check() - .expect("read stamps"); - let stamped = stamps - .take::>(0) - .expect("graded_by_result"); - let rows = stamps - .take::>(1) - .expect("submission ids"); - assert_eq!(rows.len(), 1, "grading absent work must not conjure a row"); - assert_eq!( - stamped.len(), - 1, - "the surviving submission must come back stamped by its grade" - ); - assert_eq!( - format!("{:?}", stamped[0].key), - format!("{:?}", rows[0].key), - "the stamp must name the grade of that very (homework, user) pair" - ); + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let marks: Vec = res + .body + .as_array() + .unwrap() + .iter() + .map(|r| r["mark"].as_i64().unwrap()) + .collect(); assert_eq!( - stamped[0].table.to_string(), - "homework_result", - "the stamp must point at the grade table" + marks, + vec![40, 90], + "both sittings' marks durable, oldest first" ); - - // And the freeze bites again, which an unstamped row would not have done. - let res = send( - &app, - "POST", - &format!("/homework/{hw}/submission"), - Some(&ali), - Some(json!({ "text": "version B" })), - ) - .await; - assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); - // Veli, graded but never submitted, still reports as not-submitted. let res = send( &app, "GET", - &format!("/homework/{hw}/submission"), - Some(&veli), + &format!("/exams/{exam}/results"), + Some(&teacher), None, ) .await; - assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); + assert_eq!( + common::items(&res.body)[0]["mark"], + 90, + "seq 2 is grade-of-record" + ); } -/// A menu written before the seat counter existed (2026-07-27) carries none, -/// which reads as zero — an uncapped menu for every seat already sold. The -/// backfill seeds it from the bookings that are still *held*: a cancelled one -/// gave its seat back long before the column existed, so counting rows flatly -/// would lock out a seat nobody holds. +/// A chatbot thread and every turn in it die together: deleting the +/// thread cascades its `chatbot_message` rows in one transaction, so no +/// orphan survives a reboot. And the thread is owner-scoped end to end — a +/// second user reads neither the thread nor its messages. #[tokio::test] -async fn menu_seats_are_seeded_from_the_bookings_that_are_still_held() { - let (app, db) = common::app_and_db().await; - let mgr = common::login_as(&app, &db, "seat_mgr", "manager").await; - let ali = common::login(&app, "seat_ali").await; - let veli = common::login(&app, "seat_veli").await; - let ayse = common::login(&app, "seat_ayse").await; +async fn chat_thread_delete_cascades_and_stays_owner_scoped() { + use hezarfen_backend::db::{chatbot_message, chatbot_thread}; + use hezarfen_backend::domain::chatbot_message::{ChatContent, MessageStatus}; + use hezarfen_backend::domain::user::UserId; - let res = send( - &app, - "POST", - "/meals/menus", - Some(&mgr), - Some(json!({ "date": "2099-09-14", "slot": "lunch", "capacity": 2 })), - ) - .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let menu = common::id_of(&res.body); + let (app, db, tenants) = common::app_and_tenants().await; + let owner_cookie = common::login(&app, "ali").await; + let other_cookie = common::login(&app, "ayse").await; + let owner = UserId::from_key(&me_id(&app, &owner_cookie).await); + let other = UserId::from_key(&me_id(&app, &other_cookie).await); - let book = async |who: &str| { - send( - &app, - "POST", - &format!("/meals/menus/{menu}/bookings"), - Some(who), - Some(json!({})), - ) + let thread = chatbot_thread::create_capped(&db, &owner, None) .await - }; - let held = book(&ali).await; - assert_eq!(held.status, StatusCode::CREATED, "{}", held.body); - let given_back = common::id_of(&book(&veli).await.body); - let res = send( - &app, - "DELETE", - &format!("/meals/bookings/{given_back}"), - Some(&veli), - None, + .expect("create"); + let id = thread.get_id().clone(); + let prompt = chatbot_message::append_user( + &db, + &id, + &owner, + ChatContent::try_new("selam").expect("content"), ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - - // Age the menu into the pre-counter shape. - db.query("UPDATE menu UNSET seats_booked;") + .await + .expect("append user"); + let reply = chatbot_message::append_pending_assistant(&db, &id, &owner) .await - .expect("age the row") - .check() - .expect("age the row"); - - // Same database, so the router above keeps serving; what matters is that - // the migration ran again over the aged row. - let _ = reboot(&db).await; + .expect("append assistant"); + assert_eq!(reply.get_status(), MessageStatus::Pending); - let mut counted = db - .query("SELECT VALUE seats_booked FROM menu") - .await - .expect("counter read") - .check() - .expect("counter read"); + let reply = chatbot_message::complete( + &db, + reply.get_id(), + ChatContent::try_new("aleykum selam").expect("content"), + false, + ) + .await + .expect("complete"); + assert_eq!(reply.get_status(), MessageStatus::Complete); + assert_eq!(reply.get_content().as_str(), "aleykum selam"); + assert!(reply.get_completed_at().is_some()); assert_eq!( - counted.take::>(0).expect("counter column"), - vec![1], - "only the seat still held may be counted back" + chatbot_message::list_for_thread(&db, &id, None, 0) + .await + .expect("thread") + .0 + .len(), + 2 ); - // The seeded counter is a real cap, not a decoration: one seat is left. - assert_eq!(book(&ayse).await.status, StatusCode::CREATED); - assert_eq!(book(&veli).await.status, StatusCode::CONFLICT); -} - -/// A subject written before its two reference counters existed (2026-07-27) -/// carries neither, and an absent counter reads as zero — which is exactly -/// "nothing points at me", so the delete guard would wave through a subject -/// half the school's questions are tagged with. The backfill counts the rows -/// that actually point at each subject, once. -/// -/// The bite is the last assertion: seed the counters wrong (or not at all) and -/// the delete comes back `204` instead of `409`. -#[tokio::test] -async fn subject_reference_counts_are_seeded_from_the_rows_that_predate_them() { - let (app, db) = common::app_and_db().await; - let teacher = common::login_as(&app, &db, "seed_t", "teacher").await; - let course = create_course(&app, &teacher, "biology").await; - let tagged = create_subject(&app, &teacher, &course, "cells").await; - let untouched = create_subject(&app, &teacher, &course, "genes").await; - let exam = create_exam(&app, &teacher, &course, "quiz", "quiz").await; - for text in ["what?", "why?"] { - let res = send( - &app, - "POST", - &format!("/exams/{exam}/questions"), - Some(&teacher), - Some(json!({ - "text": text, - "kind": "text", - "points": 1, - "subject_id": tagged, - })), - ) - .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - } - let due = Timestamp::now().as_millis() + 86_400_000; - common::create_homework(&app, &teacher, &course, &tagged, "mitosis", due).await; - - // Age both subjects into the pre-counter shape. - db.query("UPDATE subject UNSET exam_question_count, homework_count;") - .await - .expect("age the rows") - .check() - .expect("age the rows"); - - let app = reboot(&db).await; - - let mut counted = db - .query( - "SELECT VALUE [exam_question_count ?? 0, homework_count ?? 0] \ - FROM subject ORDER BY id ASC", - ) - .await - .expect("counter read") - .check() - .expect("counter read"); - assert_eq!( - counted.take::>>(0).expect("counter columns"), - vec![vec![2, 1], vec![0, 0]], - "each subject must be seeded from the rows that point at it" + // The other user sees nothing of it, by thread or by message. + assert!( + chatbot_thread::read_for(&db, &id, &other) + .await + .expect("cross-user thread") + .is_none() + ); + assert!( + chatbot_message::read_for(&db, prompt.get_id(), &other) + .await + .expect("cross-user message") + .is_none() + ); + assert_eq!( + chatbot_thread::count_for_user(&db, &other) + .await + .expect("count"), + 0 + ); + assert_eq!( + chatbot_thread::count_for_user(&db, &owner) + .await + .expect("count"), + 1 ); - // The seeded counters are the delete guard itself, not a decoration. - let res = send( - &app, - "DELETE", - &format!("/subjects/{tagged}"), - Some(&teacher), - None, - ) - .await; - assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); - let res = send( - &app, - "DELETE", - &format!("/subjects/{untouched}"), - Some(&teacher), - None, - ) - .await; - assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); -} - -/// A term written before its refcount existed (2026-07-27) carries none, and an -/// absent counter reads as zero — which would let a manager delete the term half -/// the timetable still points at. The backfill counts the courses that actually -/// link to each term, once; a term nobody links to gets an explicit zero, and a -/// course with no term at all must not be counted into anyone's bucket. -/// -/// The bite is the last pair of assertions: seed the counter wrong (or not at -/// all) and the linked term's delete comes back `204` instead of `409`. -#[tokio::test] -async fn term_course_counts_are_seeded_from_the_courses_that_link_to_them() { - let (app, db) = common::app_and_db().await; - let manager = common::login_as(&app, &db, "term_seed_m", "manager").await; - - async fn create_term(app: &Router, cookie: &str, name: &str, starts_at: i64) -> String { - let res = send( - app, - "POST", - "/terms", - Some(cookie), - Some(json!({ "name": name, "starts_at": starts_at, "ends_at": starts_at + 1 })), - ) - .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - common::id_of(&res.body) - } - async fn link_course(app: &Router, cookie: &str, title: &str, term: Option<&str>) { - let res = send( - app, - "POST", - "/courses", - Some(cookie), - Some(json!({ "title": title, "term_id": term })), - ) - .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - } - - let linked = create_term(&app, &manager, "linked term", 1).await; - let empty = create_term(&app, &manager, "empty term", 10).await; - link_course(&app, &manager, "History", Some(&linked)).await; - link_course(&app, &manager, "Physics", Some(&linked)).await; - link_course(&app, &manager, "Floating", None).await; - - // Age both terms into the pre-counter shape. - db.query("UPDATE term UNSET course_count;") - .await - .expect("age the rows") - .check() - .expect("age the rows"); - - let app = reboot(&db).await; - - let mut counted = db - .query("SELECT VALUE course_count FROM term ORDER BY starts_at ASC") - .await - .expect("counter read") - .check() - .expect("counter read"); + chatbot_thread::delete(&db, thread).await.expect("delete"); + assert!( + chatbot_thread::read_for(&db, &id, &owner) + .await + .expect("deleted thread") + .is_none() + ); assert_eq!( - counted.take::>(0).expect("counter column"), - vec![2, 0], - "each term must be seeded from the courses that link to it, \ - and the termless course from neither" + chatbot_thread::list_for_user(&db, &owner, None, 0) + .await + .expect("owner's list after delete") + .0 + .len(), + 0 ); - // The seeded counter is the delete guard itself, not a decoration. - let res = send( - &app, - "DELETE", - &format!("/terms/{linked}"), - Some(&manager), - None, - ) - .await; - assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); - let res = send( - &app, - "DELETE", - &format!("/terms/{empty}"), - Some(&manager), - None, - ) - .await; - assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + // Second boot: the migration re-applied over the swept store — and no + // `chatbot_message` row is left anywhere. + let _app = reboot(&db, &tenants).await; + let left = sqlx::query_scalar::<_, i64>("SELECT count(*) FROM chatbot_message") + .fetch_one(&db) + .await + .expect("sweep"); + assert_eq!(left, 0, "no chatbot_message row survived the delete"); } -/// The settings removal guards are two reference-counter tables (2026-07-27): -/// `kind_ref:` counts the marks graded under an exam kind, `slot_ref:` -/// the menus published for a meal slot, and a name may leave the list exactly -/// while its counter reads zero. A volume written before those tables existed -/// carries no rows at all, and a missing row reads as zero — which would let a -/// manager drop a kind the whole school is already graded under. The backfill -/// counts what actually points at each name, once; a name nobody ever used needs -/// no row (there is no zero pass here, deliberately). -/// -/// The bite is the last three assertions: seed the counters at zero (or not at -/// all) and the removals come back `200` instead of `409`. +/// A meal-slot list whose entries carry no serving minute survives a reboot +/// and is still patchable afterwards — an omitted optional never wedges the +/// settings row. #[tokio::test] -async fn settings_reference_counts_are_seeded_from_the_marks_and_menus_that_predate_them() { - let (app, db) = common::app_and_db().await; - let teacher = common::login_as(&app, &db, "ref_seed_t", "teacher").await; - let manager = common::login_as(&app, &db, "ref_seed_m", "manager").await; - let ali = common::login(&app, "ref_seed_ali").await; - let veli = common::login(&app, "ref_seed_veli").await; - let (ali_id, veli_id) = (me_id(&app, &ali).await, me_id(&app, &veli).await); - - // Two marks under `final`, none under any other kind. - let course = create_course(&app, &teacher, "Biology").await; - enroll(&app, &teacher, &course, &ali_id).await; - enroll(&app, &teacher, &course, &veli_id).await; - let exam = create_exam(&app, &teacher, &course, "Final", "final").await; - for student in [&ali_id, &veli_id] { - let res = send( - &app, - "POST", - &format!("/exams/{exam}/results"), - Some(&teacher), - Some(json!({ "user_id": student, "mark": 70 })), - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - } - - // Two menus under `lunch`, none under any other slot. - for date in ["2099-09-21", "2099-09-22"] { - let res = send( - &app, - "POST", - "/meals/menus", - Some(&manager), - Some(json!({ "date": date, "slot": "lunch" })), - ) - .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - } - - // Age the volume into the pre-counter shape: the tables did not exist, so - // neither did any of their rows. - db.query("DELETE kind_ref; DELETE slot_ref;") - .await - .expect("age the volume") - .check() - .expect("age the volume"); - - let app = reboot(&db).await; +async fn settings_slots_without_a_serving_minute_still_patch() { + let (app, db, tenants) = common::app_and_tenants().await; - let mut counted = db - .query( - "SELECT VALUE [record::id(id), count ?? 0] FROM kind_ref ORDER BY id ASC; \ - SELECT VALUE [record::id(id), count ?? 0] FROM slot_ref ORDER BY id ASC;", - ) - .await - .expect("counter read") - .check() - .expect("counter read"); - assert_eq!( - counted.take::>(0).expect("kind_ref"), - vec![("final".to_string(), 2)], - "the graded kind must be seeded from its marks, and only it" - ); - assert_eq!( - counted.take::>(1).expect("slot_ref"), - vec![("lunch".to_string(), 2)], - "the published slot must be seeded from its menus, and only it" - ); + let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" }); + send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; + set_role(&db, "boss", "manager").await; - // The seeded counters are the removal guards themselves, not decoration: - // the referenced names are stuck, an unreferenced one still leaves freely. - let res = send( - &app, - "PATCH", - "/settings", - Some(&manager), - Some(json!({ "exam_kinds": [{ "name": "quiz", "weight": 1 }] })), - ) - .await; - assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); let res = send( &app, "PATCH", "/settings", - Some(&manager), - Some(json!({ "meal_slots": [{ "name": "breakfast" }, { "name": "snack" }] })), + Some(&send(&app, "POST", "/auth/login", None, Some(creds.clone())) + .await + .cookie + .unwrap()), + Some(json!({ "meal_slots": [{ "name": "lunch" }] })), ) .await; - assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // Second boot, then read and patch again. + let app = reboot(&db, &tenants).await; + let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) + .await + .cookie + .unwrap(); + + let res = send(&app, "GET", "/settings", Some(&cookie), None).await; + assert_eq!(res.status, StatusCode::OK); + let slots = res.body["meal_slots"].as_array().expect("meal slots"); + assert_eq!(slots.len(), 1, "{}", res.body); + assert_eq!(slots[0]["name"], "lunch"); + let res = send( &app, "PATCH", "/settings", - Some(&manager), - Some(json!({ "meal_slots": [{ "name": "breakfast" }, { "name": "lunch" }] })), + Some(&cookie), + Some(json!({ "meal_slots": [ + { "name": "lunch" }, + { "name": "breakfast" }, + ] })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); } -/// A fee plan's installments are an `array` on the plan row, and the -/// charges it raised are frozen copies of them. A SCHEMAFULL re-migration -/// rewrites every field definition it owns, so this is where a nested array -/// would quietly come back as `NONE` or lose a key — the plan, the placement -/// and the money all have to survive a second boot unchanged. +/// Fee plans, their installment shape and the charges a placement raised all +/// come back through a second boot: order, both keys of every installment, +/// and the statement's arithmetic. #[tokio::test] async fn fee_plans_and_their_charges_survive_remigration() { - let (app, db) = common::app_and_db().await; + let (app, db, tenants) = common::app_and_tenants().await; let manager_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); for creds in [&manager_creds, &student_creds] { @@ -2008,7 +652,7 @@ async fn fee_plans_and_their_charges_survive_remigration() { .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - let app = reboot(&db).await; + let app = reboot(&db, &tenants).await; let res = send( &app, @@ -2044,77 +688,11 @@ async fn fee_plans_and_their_charges_survive_remigration() { ); } -/// A user row written before `palette_color` existed needs no backfill: the -/// column is `option`, so the absent key reads back as "never chose" -/// and a later patch sets it in place. Adding an option column to a SCHEMAFULL -/// table must not strand the rows already there. -#[tokio::test] -async fn a_user_row_without_palette_color_still_reads_and_patches() { - let (app, db) = common::app_and_db().await; - let ali = common::login(&app, "ali").await; - - // Write the column first: a fresh row stores no key for a `None` option, so - // UNSET alone would be a no-op and this test would prove nothing. - let set = send( - &app, - "PATCH", - "/users/me/preferences", - Some(&ali), - Some(json!({ "palette_color": "#283618" })), - ) - .await; - assert_eq!(set.status, StatusCode::OK, "{}", set.body); - let stored: Vec = db - .query("SELECT VALUE palette_color FROM user WHERE palette_color != NONE;") - .await - .expect("read the column") - .check() - .expect("read the column") - .take(0) - .expect("read the column"); - assert_eq!( - stored, - vec!["#283618"], - "the column must exist to be aged away" - ); - - // Now age the row into the pre-accent shape: the key goes away, exactly as - // on a row a binary without this column wrote. - db.query("UPDATE user UNSET palette_color;") - .await - .expect("age the row") - .check() - .expect("age the row"); - - let app = reboot(&db).await; - - let me = send(&app, "GET", "/auth/me", Some(&ali), None).await; - assert_eq!(me.status, StatusCode::OK, "{}", me.body); - assert!( - me.body["palette_color"].is_null(), - "an aged row must read as never-chosen, not error" - ); - - let set = send( - &app, - "PATCH", - "/users/me/preferences", - Some(&ali), - Some(json!({ "palette_color": "#fefae0" })), - ) - .await; - assert_eq!(set.status, StatusCode::OK, "{}", set.body); - assert_eq!(set.body["palette_color"], "#fefae0"); -} - -/// A whiteboard, its whole stroke log and the creator's `board_count` all -/// survive a second boot. `board_count` is the authority on how many boards a -/// creator holds, so a migration that reset it would ratchet a busy teacher's -/// limit — and the strokes are the one thing in this feature that a clear is -/// promised never to lose. +/// Boards, their stroke log across epochs, and the counters the cap reads all +/// survive a second boot — and the board is still writable afterwards. #[tokio::test] async fn boards_and_their_strokes_survive_remigration() { - let (app, db) = common::app_and_db().await; + let (app, db, tenants) = common::app_and_tenants().await; let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); let cookie = common::login(&app, "ali").await; let veli = common::login(&app, "veli").await; @@ -2158,7 +736,7 @@ async fn boards_and_their_strokes_survive_remigration() { draw(1, "{\"p\":[3]}").await; // Second boot: the migration re-applied over live board data. - let app = reboot(&db).await; + let app = reboot(&db, &tenants).await; let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) .await .cookie @@ -2209,27 +787,28 @@ async fn boards_and_their_strokes_survive_remigration() { ); // The counters the schema carries but the struct does not, straight from - // the row: a re-migration must not have reset either of them. - let mut result = db - .query( - "SELECT VALUE [epoch_stroke_count ?? 0, total_stroke_count ?? 0, \ - (SELECT VALUE board_count ?? 0 FROM $usr)[0]] FROM $id", - ) - .bind(( - "id", - hezarfen_backend::domain::board::BoardId::from_key(&board).record(), - )) - .bind(( - "usr", - hezarfen_backend::domain::user::UserId::from_key(&ali_id).record(), - )) - .await - .unwrap() - .check() - .unwrap(); + // the rows: a re-migration must not have reset either of them. + use sqlx::Row as _; + let board_id = hezarfen_backend::domain::board::BoardId::from_key(&board); + let row = sqlx::query( + "SELECT epoch_stroke_count, total_stroke_count FROM board WHERE id = $1", + ) + .bind(board_id.uuid()) + .fetch_one(&db) + .await + .expect("board row"); + let epoch_count: i64 = row.try_get(0).unwrap(); + let total_count: i64 = row.try_get(1).unwrap(); + let user_id = hezarfen_backend::domain::user::UserId::from_key(&ali_id); + let board_count: i64 = + sqlx::query_scalar("SELECT board_count FROM app_user WHERE id = $1") + .bind(user_id.uuid()) + .fetch_one(&db) + .await + .expect("creator row"); assert_eq!( - result.take::>>(0).unwrap()[0], - vec![1, 4, 1], + (epoch_count, total_count, board_count), + (1, 4, 1), "epoch counter, lifetime counter (three strokes and the clear marker \ they paid for) and the creator's board_count" ); @@ -2252,175 +831,12 @@ async fn boards_and_their_strokes_survive_remigration() { ); } -/// Every course's `enrollment_count`, straight off the store. -async fn seats_taken(db: &Database) -> Vec { - db.query("SELECT VALUE enrollment_count FROM course;") - .await - .expect("read the counter") - .check() - .expect("read the counter") - .take::>(0) - .expect("enrollment_count") -} - -/// An `enrollment` row written before the class layer (2026-08-01) carries no -/// `source` key at all, and that absence *is* the meaning — "a person placed -/// this student" — so there is nothing to backfill and everything to preserve. -/// Such a row must still decode once the column exists, still count towards its -/// course's cap, and never be adopted by a class that later attaches the same -/// course: the class skips a pair that already has a row, so the sweep on its -/// way out must find nothing of its own to take. -#[tokio::test] -async fn pre_class_enrollments_keep_their_absent_source() { - let (app, db) = common::app_and_db().await; - let manager = common::login_as(&app, &db, "mgr", "manager").await; - let teacher = common::login_as(&app, &db, "teacher", "teacher").await; - let ali = common::login(&app, "ali").await; - let veli = common::login(&app, "veli").await; - let (ali_id, veli_id) = (me_id(&app, &ali).await, me_id(&app, &veli).await); - - let course = create_course(&app, &teacher, "algebra").await; - enroll(&app, &teacher, &course, &ali_id).await; - enroll(&app, &teacher, &course, &veli_id).await; - - // Age both rows into the pre-class shape — no `source` key — and the course - // into the pre-counter shape a volume that old also carries. - db.query("UPDATE enrollment UNSET source; UPDATE course UNSET enrollment_count;") - .await - .expect("age the rows") - .check() - .expect("age the rows"); - - let app = reboot(&db).await; - - // They decode, and the counter is seeded from them. - let roster = send( - &app, - "GET", - &format!("/courses/{course}/enrollments"), - Some(&teacher), - None, - ) - .await; - assert_eq!(roster.status, StatusCode::OK, "{}", roster.body); - assert_eq!( - common::total(&roster.body), - 2, - "a sourceless row must still read: {}", - roster.body - ); - assert_eq!(seats_taken(&db).await, vec![2], "seeded from the roster"); - - // A class attaching that same course finds ali already seated: no second - // seat is charged, and their row keeps its absent `source`… - let res = send( - &app, - "POST", - "/classes", - Some(&manager), - Some(json!({ "name": "9-A" })), - ) - .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let class = common::id_of(&res.body["class"]); - let res = send( - &app, - "POST", - &format!("/classes/{class}/members"), - Some(&manager), - Some(json!({ "user_id": ali_id })), - ) - .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let res = send( - &app, - "POST", - &format!("/classes/{class}/courses"), - Some(&manager), - Some(json!({ "course_id": course })), - ) - .await; - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - assert_eq!(seats_taken(&db).await, vec![2], "no second seat charged"); - - // …so the detach sweeps nothing, and the pre-class rows outlive the class. - let res = send( - &app, - "DELETE", - &format!("/classes/{class}/courses/{course}"), - Some(&manager), - None, - ) - .await; - assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); - let roster = send( - &app, - "GET", - &format!("/courses/{course}/enrollments"), - Some(&teacher), - None, - ) - .await; - assert_eq!( - common::total(&roster.body), - 2, - "hand-placed rows are never swept by a class: {}", - roster.body - ); - assert_eq!( - seats_taken(&db).await, - vec![2], - "and no seat was given back" - ); -} - -/// A school row written before module entitlements existed has no `modules` -/// field at all. The control migration must read that — and only that — as -/// "everything", because a school that predates the idea of buying modules had -/// all of them. -#[tokio::test] -async fn a_school_row_without_modules_backfills_to_every_module() { - let db = surrealdb::engine::any::connect("memory") - .await - .expect("an in-memory control store"); - db.use_ns("hezarfen").use_db("control").await.unwrap(); - // The control schema as it stood before `modules`, so the row really is - // the shape an older binary left behind. - db.query( - "DEFINE TABLE school SCHEMAFULL; - DEFINE FIELD slug ON school TYPE string; - DEFINE FIELD name ON school TYPE string; - DEFINE FIELD status ON school TYPE string; - DEFINE FIELD created_at ON school TYPE int; - CREATE school:legacy SET slug = 'legacy', name = 'Legacy', \ - status = 'active', created_at = 1;", - ) - .await - .expect("the pre-modules control schema") - .check() - .expect("the pre-modules control schema"); - - database::migrate_control(&db).await.expect("a newer boot"); - - let stored: Vec> = db - .query("SELECT VALUE modules FROM school:legacy") - .await - .expect("read the row back") - .take(0) - .expect("modules column"); - assert_eq!( - stored.first().cloned().unwrap_or_default(), - ModuleSet::all().names(), - "a row that predates entitlements owns every module" - ); -} - -/// The other half of that rule: `[]` is a deliberate "nothing enabled", not a -/// missing value, so a second boot must leave it alone. Widening it would hand -/// a school modules it never bought. +/// An empty module set is a decision, never a hole to fill: a school created +/// with nothing switched on still reads an empty list after a second boot of +/// the control schema. #[tokio::test] async fn an_empty_module_list_survives_a_second_boot() { - let tenants = Tenants::new_mem().await.expect("a control database"); + let tenants = database::init_test_tenants().await; let slug = Slug::try_new("bare").unwrap(); tenants .create(&slug, "Bare School", ModuleSet::empty()) @@ -2431,251 +847,75 @@ async fn an_empty_module_list_survives_a_second_boot() { .await .expect("a second boot"); - let stored: Vec> = tenants - .control() - .query("SELECT VALUE modules FROM school:bare") - .await - .expect("read the row back") - .take(0) - .expect("modules column"); + use sqlx::Row as _; + let stored: Option> = sqlx::query( + "SELECT modules FROM school WHERE slug = $1", + ) + .bind(slug.as_str()) + .fetch_optional(tenants.control()) + .await + .expect("read the row back") + .map(|row| row.try_get::, _>(0).unwrap()); assert_eq!( - stored.first().cloned().unwrap_or_default(), + stored.unwrap_or_default(), Vec::::new(), "an empty list is a decision, never a hole to fill" ); } -// ===================== REFUTE probes (verifier, 2026-09-06) ===================== - -/// The stored `modules` column of one school, straight off the control store. -async fn raw_modules(control: &Database, slug: &str) -> Option> { - let rows: Vec = control - .query(format!( - "SELECT VALUE modules FROM type::record('school', '{slug}')" - )) - .await - .expect("raw read") - .check() - .expect("raw check") - .take(0) - .expect("modules column"); - match rows.into_iter().next() { - None | Some(serde_json::Value::Null) => None, - Some(value) => Some( - value - .as_array() - .unwrap_or_else(|| panic!("modules is not an array: {value}")) - .iter() - .map(|v| v.as_str().expect("module name").to_string()) - .collect(), - ), - } -} - -/// P3: two more boots over rows an older binary could have left behind. An -/// empty set is a decision and must survive; a narrowed one must not widen; a -/// row from before the field existed is the only one that backfills. +/// The control migration run twice over schools seeded through the registry +/// leaves every school row exactly as it stood — idempotence is the whole +/// contract of a second boot. #[tokio::test] async fn probe_control_migration_is_idempotent_over_aged_rows() { - let tenants = Tenants::new_mem().await.expect("control store"); + let tenants = database::init_test_tenants().await; let control = tenants.control().clone(); - let mut narrowed = ModuleSet::empty(); - narrowed.insert(hezarfen_backend::module::Module::Notes); - narrowed.insert(hezarfen_backend::module::Module::Courses); - narrowed.insert(hezarfen_backend::module::Module::Subjects); - - tenants - .create( - &Slug::try_new("empty").unwrap(), - "Empty", - ModuleSet::empty(), - ) - .await - .expect("empty school"); - tenants - .create( - &Slug::try_new("narrow").unwrap(), - "Narrow", - narrowed.clone(), - ) - .await - .expect("narrow school"); - tenants - .create(&Slug::try_new("aged").unwrap(), "Aged", ModuleSet::all()) - .await - .expect("aged school"); - - // (c) a row from before the field existed. - let unset = control - .query("UPDATE type::record('school', 'aged') UNSET modules") - .await - .expect("unset send") - .check(); - let unset_worked = match unset { - Err(err) => { - println!("PROBE UNSET modules refused by the schema: {err}"); - false - } - Ok(_) => { - let now = raw_modules(&control, "aged").await; - println!("PROBE after UNSET, aged.modules = {now:?}"); - now.is_none() || now.as_ref().is_some_and(|m| m.is_empty()) - } - }; - - for boot in 1..=2 { - database::migrate_control(&control) + // Seed through the registry path itself: three schools, one per module + // posture the product distinguishes. + let mut narrow = ModuleSet::all(); + narrow.remove(hezarfen_backend::module::Module::try_from_str("marks").unwrap()); + for (slug, name, modules) in [ + ("full", "Full School", ModuleSet::all()), + ("empty", "Empty School", ModuleSet::empty()), + ("narrow", "Narrow School", narrow), + ] { + tenants + .create(&Slug::try_new(slug).unwrap(), name, modules) .await - .unwrap_or_else(|e| panic!("boot {boot}: {e}")); + .unwrap_or_else(|err| panic!("create {slug}: {err}")); } - assert_eq!( - raw_modules(&control, "empty").await, - Some(vec![]), - "an empty set was re-widened by a boot" - ); - assert_eq!( - raw_modules(&control, "narrow").await, - Some(narrowed.names()), - "a narrowed set moved across two boots" - ); - if unset_worked { - let aged = raw_modules(&control, "aged").await; - println!("PROBE aged after two boots = {aged:?}"); - assert_eq!( - aged.map(|m| m.len()), - Some(21), - "a pre-entitlement row was not backfilled to the whole catalog" - ); - } else { - println!( - "PROBE UNMEASURED(c): the SCHEMAFULL control table would not let a row \ - lose its `modules` field, so the NONE backfill path was not exercised here" - ); - } -} + let before = school_rows(&control).await; + // The harness's demo school plus the three seeded here. + assert_eq!(before.len(), 4, "demo plus the three seeded schools"); -/// P3b: a stored name this binary does not know is ignored on read and does not -/// lock the school out. -#[tokio::test] -async fn probe_an_unknown_stored_module_name_is_ignored() { - let tenants = Tenants::new_mem().await.expect("control store"); - let control = tenants.control().clone(); - let slug = Slug::try_new("weird").unwrap(); - tenants - .create(&slug, "Weird", ModuleSet::all()) - .await - .expect("school"); - control - .query("UPDATE type::record('school', 'weird') SET modules += ['zzz']") + database::migrate_control(&control) .await - .expect("send") - .check() - .expect("store an unknown name"); - assert!( - raw_modules(&control, "weird") - .await - .expect("row") - .contains(&"zzz".to_string()), - "the unknown name did not land, so the probe proves nothing" - ); - - let resolved = tenants - .resolve(&slug) + .expect("a second control boot"); + database::migrate_control(&control) .await - .expect("the school still resolves"); - assert_eq!( - resolved.modules, - ModuleSet::all(), - "an unknown stored name changed the parsed set" - ); + .expect("a third control boot"); - let app = build_router(AppState { - db: control.clone(), - tenants: tenants.clone(), - files_path: common::files_dir(), - cookie_secure: false, - rate_limit: RateLimitConfig::unlimited(), - chatbot_limit: Default::default(), - exam_presence: Default::default(), - board_hub: Default::default(), - db_up: Default::default(), - ai: None, - metrics: hezarfen_backend::telemetry::Metrics::noop(), - }); - let creds = json!({ "school": "weird", "username": "ada", "password": "secret1" }); - let reg = send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; - assert_eq!(reg.status, StatusCode::CREATED, "{:?}", reg.body); - let login = send(&app, "POST", "/auth/login", None, Some(creds)).await; - assert_eq!( - login.status, - StatusCode::OK, - "login broke on an unknown stored module: {:?}", - login.body - ); - let cookie = login.cookie.expect("cookie"); - let mine = send(&app, "GET", "/modules", Some(&cookie), None).await; - assert_eq!(mine.status, StatusCode::OK, "{:?}", mine.body); - assert_eq!(mine.body["enabled"].as_array().map(|a| a.len()), Some(21)); + let after = school_rows(&control).await; + assert_eq!(before, after, "a re-run must not disturb school rows"); } -/// P3c: the real pre-entitlement row — one written by a binary whose control -/// schema had no `modules` field at all. `UNSET` cannot make one (the -/// SCHEMAFULL type refuses `NONE`), so the old schema is rebuilt by hand. -#[tokio::test] -async fn probe_a_row_written_before_the_field_existed_backfills_once() { - let control: Database = std::sync::Arc::new( - surrealdb::engine::any::connect("mem://") - .await - .expect("mem control store"), - ); - control.use_ns("hezarfen").use_db("control").await.unwrap(); - // The control schema as it stood at 9c7bb06: no `modules` field. - control - .query( - "DEFINE TABLE school SCHEMAFULL; - DEFINE FIELD slug ON school TYPE string; - DEFINE FIELD name ON school TYPE string; - DEFINE FIELD status ON school TYPE string; - DEFINE FIELD created_at ON school TYPE int; - CREATE school:old SET slug = 'old', name = 'Old', status = 'active', - created_at = 1;", - ) - .await - .expect("old schema") - .check() - .expect("old schema check"); - assert_eq!( - raw_modules(&control, "old").await, - None, - "the aged row must start with no modules field at all" - ); - - for boot in 1..=2 { - database::migrate_control(&control) - .await - .unwrap_or_else(|e| panic!("boot {boot}: {e}")); - let after = raw_modules(&control, "old").await; - println!("PROBE boot {boot}: old.modules = {after:?}"); - assert_eq!( - after.as_ref().map(|m| m.len()), - Some(21), - "boot {boot} left a pre-entitlement row at {after:?} instead of the whole catalog" - ); - } - - // And a deliberately empty row alongside it is not widened by those boots. - control - .query("CREATE school:none SET slug = 'none', name = 'None', status = 'active', created_at = 1, modules = [];") +/// Every school row as `(slug, name, status, modules)`, in slug order. +async fn school_rows(control: &Database) -> Vec<(String, String, String, Vec)> { + use sqlx::Row as _; + sqlx::query("SELECT slug, name, status, modules FROM school ORDER BY slug") + .fetch_all(control) .await - .expect("empty row") - .check() - .expect("empty row check"); - database::migrate_control(&control).await.expect("boot 3"); - assert_eq!( - raw_modules(&control, "none").await, - Some(vec![]), - "a deliberate empty set was re-widened" - ); + .expect("school rows") + .into_iter() + .map(|row| { + ( + row.try_get::(0).unwrap(), + row.try_get::(1).unwrap(), + row.try_get::(2).unwrap(), + row.try_get::, _>(3).unwrap(), + ) + }) + .collect() }