forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB0346717Ahmet Kaan Gümüş3 months ago230 commits

database.rs995 lines, 45.1 KiBHistoryRawDownload
1//! SurrealDB connection (WebSocket to a server; in-memory for tests) + schema.
2
3use surrealdb::Surreal;
4use surrealdb::engine::any::Any;
5use surrealdb::opt::auth::Root;
6
7use crate::config::Config;
8use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS};
9use crate::domain::timestamp::Timestamp;
10use crate::domain::user::{Password, User, Username};
11use crate::error::AppError;
12use crate::migration_sql::MIGRATION_BATCHES;
13
14/// The shared database handle.
15///
16/// `Arc` is load-bearing, not decoration. `Surreal`'s own `Clone` mints a
17/// fresh server-side session per clone (`Uuid::new_v4()` + a fire-and-forget
18/// `SessionId::Clone` to the router, SDK `lib.rs:340`), and axum clones the
19/// application state on every request — so a bare `Surreal<Any>` here means a
20/// new session, and a matching `SessionId::Drop`, for each request served.
21/// Under concurrency those lifecycle events race the queries riding on them:
22/// sessions disappear ("Session not found"), and a session whose signin has
23/// not been replayed answers "Anonymous access not allowed" / "Specify a
24/// namespace" — the same strings [`crate::error::is_session_replay_error`]
25/// treats as a transient reconnect, so the failures masquerade as one.
26///
27/// Cloning the `Arc` shares the single session established at boot instead.
28pub type Database = std::sync::Arc<Surreal<Any>>;
29
30/// Connect to the SurrealDB server, sign in as root, apply the schema and seed
31/// the admin. One process, one database, stop-the-world deploys — so all of it
32/// runs unconditionally on every boot.
33pub async fn init(cfg: &Config) -> Result<Database, AppError> {
34 // Validated before the connection, not after: half a credential pair is a
35 // deployment mistake, and reporting it only after a successful dial buries
36 // it under an outage that isn't one.
37 let admin = admin_credentials(cfg)?;
38 let db = connect_with_retry(cfg).await;
39 db.signin(Root {
40 username: cfg.db_user.clone(),
41 password: cfg.db_pass.clone(),
42 })
43 .await?;
44 db.use_ns(cfg.db_ns.clone())
45 .use_db(cfg.db_name.clone())
46 .await?;
47 let db = std::sync::Arc::new(db);
48 migrate(&db).await?;
49 if let Some((username, password)) = admin {
50 User::ensure_admin(username, password, &db).await?;
51 }
52 Ok(db)
53}
54
55/// The `ADMIN_USERNAME` / `ADMIN_PASSWORD` bootstrap pair, if configured.
56/// Both-or-neither: half a pair aborts startup rather than silently running
57/// without the seed.
58fn admin_credentials(cfg: &Config) -> Result<Option<(Username, Password)>, AppError> {
59 match (&cfg.admin_username, &cfg.admin_password) {
60 (Some(username), Some(password)) => Ok(Some((
61 Username::try_new(username)
62 .map_err(|err| AppError::Internal(format!("invalid ADMIN_USERNAME: {err}")))?,
63 Password::try_new(password)
64 .map_err(|err| AppError::Internal(format!("invalid ADMIN_PASSWORD: {err}")))?,
65 ))),
66 (None, None) => Ok(None),
67 _ => Err(AppError::Internal(
68 "ADMIN_USERNAME and ADMIN_PASSWORD must be set together".into(),
69 )),
70 }
71}
72
73/// The two ways a rival's claim shows up as an error on ours: our `CREATE` hit
74/// their row, or the key-value layer aborted our transaction because theirs
75/// touched the same key first.
76///
77/// Read from the *typed* error surface, not the message. Every conflict wording
78/// the storage engines produce — surrealkv's "Transaction conflict: Write
79/// conflict, retry the transaction. This transaction can be retried",
80/// surrealmx's read-conflict variant, RocksDB's `Busy`/`TryAgain` — funnels
81/// through one `KvsError::TransactionConflict` into
82/// `QueryError::TransactionConflict` (surrealdb-core 3.2.3
83/// `err/to_types.rs:295`, `kvs/err.rs:64-179`), and a duplicate record id into
84/// `AlreadyExistsError::Record` (`to_types.rs:206`). So the two checks below
85/// cover all of them, where matching substrings covered only whichever wording
86/// the engine of the day happened to use.
87///
88/// The message fallback stays for one reason: these errors also travel over the
89/// WebSocket, where the SDK rebuilds them from the wire (`Error::from_parts`),
90/// and a server that omitted the typed details would otherwise turn a lost race
91/// into a failed boot. Widest known wordings, cheap, and belt-and-braces.
92pub(crate) fn lost_the_race(err: &surrealdb::Error) -> bool {
93 use surrealdb::types::{ErrorDetails, QueryError};
94 if err.is_already_exists()
95 || matches!(
96 err.details(),
97 ErrorDetails::Query(Some(QueryError::TransactionConflict))
98 )
99 {
100 return true;
101 }
102 let message = err.to_string();
103 message.contains("already exists") || message.contains("can be retried")
104}
105
106/// Send one guarded single-statement write, re-sending it while the store
107/// answers "conflict, retry", and hand back the rows it returned.
108///
109/// The guard on such a statement reads a column a rival writes, so the two
110/// contend on one record *by design* — that contention is what makes the guard
111/// atomic. Losing a round writes nothing at all, which makes re-sending the
112/// whole of the recovery; without it an ordinary raced `PATCH` or `DELETE`
113/// answers 500 instead of the 404 or 409 it owes. Only for statements that
114/// cannot produce "already exists" (the other thing [`lost_the_race`] matches),
115/// so `UPDATE` and `DELETE` and not `CREATE`.
116pub(crate) async fn write_with_retry<T: surrealdb::types::SurrealValue>(
117 db: &Database,
118 sql: &str,
119 bindings: &[(String, surrealdb::types::Value)],
120) -> Result<Vec<T>, AppError> {
121 let mut last = None;
122 for attempt in 0..CAP_WRITE_TRIES {
123 backoff(attempt).await;
124 let mut query = db.query(sql);
125 for (name, value) in bindings {
126 query = query.bind((name.clone(), value.clone()));
127 }
128 match async { query.await?.check()?.take::<Vec<T>>(0) }.await {
129 Ok(rows) => return Ok(rows),
130 Err(err) if lost_the_race(&err) => last = Some(err),
131 Err(err) => return Err(err.into()),
132 }
133 }
134 Err(last
135 .map(AppError::from)
136 .unwrap_or_else(|| AppError::Internal("a guarded write never ran".into())))
137}
138
139/// Send one guarded `BEGIN…COMMIT` cascade, re-sending it while the store
140/// answers "conflict, retry", and hand back both the response and the errors
141/// drained off it.
142///
143/// [`write_with_retry`]'s story, for the cascades that cannot be one statement:
144/// the guard reads a column a rival writes, so the two contend on one record by
145/// design, and a lost round aborts the transaction having written *nothing* —
146/// which is what makes re-sending the whole of the recovery.
147///
148/// Both halves come back because the caller needs both and `take_errors`
149/// consumes: the response carries the result slots, and only the error map can
150/// tell a deliberate `THROW` from a lost round. `refusals` are the caller's
151/// `THROW` markers and they are matched *first* — a `THROW` is a decision, and
152/// it outranks a conflict. Everything after that ordering is why this exists:
153/// an aborted transaction errors *every* slot, and all but the failing one say
154/// a generic "not executed", which is the consequence of the abort and never a
155/// reason of its own. Picking one of those out of the unordered `HashMap` — or
156/// taking the first via `check()` — retired a retryable round as a 500, measured
157/// on `Course::delete` at 1-3 of 20 raced rounds.
158///
159/// [`write_with_retry`]'s restriction carries over, and a cascade makes it
160/// easier to trip: no statement inside may be able to answer "already exists",
161/// because that is the other thing [`lost_the_race`] matches and re-sending it
162/// would just fail the same way until the tries run out — turning a 409 into a
163/// 500, which is the exact defect this exists to prevent. The test to apply to
164/// every statement in the batch is not which verb it uses but whether the store
165/// could *legitimately* answer "already exists" to it — that answer is a
166/// decision, and this loop cannot tell one from a conflict, so it would burn all
167/// the tries re-asking a question already settled. `UPDATE` and `DELETE` never
168/// can. A `CREATE` can, unless the id is unreachable by any rival: a freshly
169/// generated ULID on a table with no `UNIQUE` index is such an id. An `UPSERT`
170/// can, unless its id is *bijective* with every unique tuple its table indexes —
171/// then the index entry can only ever point at the row the id already names, and
172/// the write resolves onto it instead of colliding with it
173/// ([`crate::domain::exam_result::ExamResult`]'s composite id is that shape).
174/// A statement that fails this test belongs in front of the cascade, where its
175/// 409 can be read as the answer it is.
176pub(crate) async fn transaction_with_retry(
177 db: &Database,
178 sql: &str,
179 bindings: &[(String, surrealdb::types::Value)],
180 refusals: &[&str],
181) -> Result<
182 (
183 surrealdb::IndexedResults,
184 std::collections::HashMap<usize, surrealdb::Error>,
185 ),
186 AppError,
187> {
188 let mut last = None;
189 for attempt in 0..CAP_WRITE_TRIES {
190 backoff(attempt).await;
191 let mut query = db.query(sql);
192 for (name, value) in bindings {
193 query = query.bind((name.clone(), value.clone()));
194 }
195 let mut result = match query.await {
196 Ok(result) => result,
197 Err(err) if lost_the_race(&err) => {
198 last = Some(err);
199 continue;
200 }
201 Err(err) => return Err(err.into()),
202 };
203 let mut errors = result.take_errors();
204 let refused = |error: &surrealdb::Error| {
205 let message = error.to_string();
206 refusals.iter().any(|marker| message.contains(marker))
207 };
208 if errors.values().any(refused) || !errors.values().any(lost_the_race) {
209 return Ok((result, errors));
210 }
211 last = errors.drain().map(|(_, error)| error).find(lost_the_race);
212 }
213 Err(last
214 .map(AppError::from)
215 .unwrap_or_else(|| AppError::Internal("a guarded cascade never ran".into())))
216}
217
218/// Wait out one lost round. Exponential with jitter, because racers arrive in
219/// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them.
220/// Attempt zero waits not at all.
221pub(crate) async fn backoff(attempt: usize) {
222 if attempt == 0 {
223 return;
224 }
225 let step = CAP_WRITE_BACKOFF_MS << (attempt - 1);
226 let jitter = Timestamp::now().as_millis().unsigned_abs() % step.max(1);
227 tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await;
228}
229
230/// Dial the database, retrying until it answers.
231///
232/// Never gives up, because giving up is worse than waiting: the database is
233/// normally a sibling container booting in parallel, and a process that exits
234/// on the first refusal gets restarted by the runtime, fails again in ~100ms,
235/// and burns its whole restart budget inside a second — leaving the backend
236/// permanently down over a startup skew that would have cleared on its own.
237///
238/// Only the dial is retried. Bad credentials or a broken migration still fail
239/// hard, since no amount of waiting fixes those.
240async fn connect_with_retry(cfg: &Config) -> Surreal<Any> {
241 let mut backoff = 1;
242 loop {
243 match surrealdb::engine::any::connect(cfg.db_url.clone()).await {
244 Ok(db) => return db,
245 Err(err) => {
246 tracing::warn!(
247 "database at {} unreachable ({err}) — retrying in {backoff}s",
248 cfg.db_url
249 );
250 tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
251 backoff = (backoff * 2).min(crate::constant::DB_CONNECT_BACKOFF_MAX_SECS);
252 }
253 }
254 }
255}
256
257/// A fresh in-memory database with the schema applied. For tests.
258pub async fn init_mem() -> Result<Database, AppError> {
259 let db = surrealdb::engine::any::connect("memory").await?;
260 db.use_ns("hezarfen").use_db("hezarfen").await?;
261 migrate(&db).await?;
262 Ok(std::sync::Arc::new(db))
263}
264
265/// A handle on a **real** SurrealDB server, in a scratch namespace of its own
266/// that is dropped and re-made on every call. For the tests whose subject is
267/// the store's own conflict detection, which [`init_mem`]'s embedded engine
268/// does not have: it drops one of two concurrent writes to a record and answers
269/// `Ok` to both (see [`crate::domain::cap`]), which *forges* the very
270/// integrity failure those tests exist to catch — measured 2026-07-30 at 2
271/// failed runs in 36 on `memory`, against 0 in 10 000 rounds here.
272///
273/// Every caller is `#[ignore]`d, so a machine with no server prints them as
274/// `ignored` rather than passing: this is not a test that may quietly skip.
275/// `HEZARFEN_TEST_DB` overrides the address; the credentials are `compose.yaml`'s.
276///
277/// The guard handed back with the handle serializes these tests against each
278/// other and must be held for the whole test — hence the tuple, which cannot be
279/// forgotten the way a separate `lock()` line can. `cargo test -- --ignored`
280/// runs them in parallel, and while each has a namespace to itself they all
281/// burst against the *one* server: their beats are sub-millisecond, so a
282/// sibling's burst pushes a delete clean out of the window it is meant to land
283/// in (measured 4 runs in 4 at 3 of 6 failing their own "the race was reached"
284/// guard). Serialized, the plain documented command works.
285#[cfg(test)]
286pub(crate) static RACE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
287
288#[cfg(test)]
289pub(crate) async fn init_test_server(
290 scratch: &str,
291) -> (Database, tokio::sync::MutexGuard<'static, ()>) {
292 let serialized = RACE_LOCK.lock().await;
293 let url =
294 std::env::var("HEZARFEN_TEST_DB").unwrap_or_else(|_| "ws://127.0.0.1:8000".to_string());
295 let db = surrealdb::engine::any::connect(url.clone())
296 .await
297 .unwrap_or_else(|err| panic!("no SurrealDB server at {url} ({err})"));
298 db.signin(Root {
299 username: "root".into(),
300 password: "root".into(),
301 })
302 .await
303 .expect("sign in to the test server");
304 let ns = format!("test_{scratch}");
305 db.query(format!("REMOVE NAMESPACE IF EXISTS {ns}"))
306 .await
307 .expect("clear the scratch namespace")
308 .check()
309 .expect("clear the scratch namespace");
310 db.use_ns(ns.clone()).use_db(ns).await.expect("scratch ns");
311 let db = std::sync::Arc::new(db);
312 migrate(&db).await.expect("migrate the scratch namespace");
313 (db, serialized)
314}
315
316/// Apply the schema + backfills. Idempotent — `init` runs it on every boot,
317/// and tests re-run it on a live handle to simulate a second boot.
318pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> {
319 for sql in MIGRATION_BATCHES {
320 let mut query = db.query(sql);
321 for (name, value) in migration_binds() {
322 query = query.bind((name, value));
323 }
324 query.await?.check()?;
325 }
326 Ok(())
327}
328
329/// Parameters the batches are executed with. Bound, not baked into the SQL
330/// string: a `const` cannot be interpolated into another `const`, and a
331/// hand-copied 300000 would drift silently.
332fn migration_binds() -> [(&'static str, i64); 1] {
333 [("stale_ms", CHATBOT_PENDING_STALE_SECS * 1_000)]
334}
335
336#[cfg(test)]
337mod tests {
338
339 /// The admin seed must not be interruptible into a state no later boot can
340 /// repair. `create` + `set_role` was: killed between the two writes it
341 /// leaves a *student* row holding ADMIN_USERNAME, which `ensure_admin` then
342 /// refuses to promote on every subsequent boot (rightly — it cannot tell
343 /// that row from a stranger who registered the name first). The row is
344 /// therefore minted with its role in one statement, and this pins that.
345 #[test]
346 fn the_admin_seed_mints_the_role_with_the_row() {
347 let source =
348 std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/domain/user.rs"))
349 .expect("read user.rs");
350 let start = source
351 .find("pub async fn ensure_admin")
352 .expect("ensure_admin is declared");
353 let body = &source[start..start + source[start..].find("\n }\n").expect("body ends")];
354 assert!(
355 !body.contains("set_role"),
356 "ensure_admin promotes after creating; an interruption between those two writes \
357 leaves a student account on ADMIN_USERNAME that no boot can heal:\n{body}"
358 );
359 assert!(
360 body.contains("create_with_role"),
361 "the seed must mint the row with Role::Admin in one statement"
362 );
363 }
364
365 #[tokio::test]
366 async fn boot_fails_chatbot_messages_left_pending() {
367 let db = super::init_mem().await.unwrap();
368 db.query(
369 "CREATE user:u SET username = 'u', password_hash = 'x';
370 CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1;
371 CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u,
372 role = 'assistant', content = '', status = 'pending', created_at = 1;
373 CREATE chatbot_message:done SET thread_id = chatbot_thread:c, user_id = user:u,
374 role = 'assistant', content = 'hi', status = 'complete', created_at = 1;",
375 )
376 .await
377 .unwrap()
378 .check()
379 .unwrap();
380
381 // A second boot: the task that would have answered `m` died with the
382 // previous process, so the row is failed rather than left waiting.
383 super::migrate(&db).await.unwrap();
384
385 let mut rows = db
386 .query("SELECT id, status, error_code, completed_at FROM chatbot_message ORDER BY id")
387 .await
388 .unwrap();
389 let rows: Vec<serde_json::Value> = rows.take(0).unwrap();
390 // An already-answered turn is untouched; the pending one is failed.
391 let done = &rows[0];
392 let interrupted = &rows[1];
393 assert_eq!(done["status"], "complete");
394 assert_eq!(done["error_code"], serde_json::Value::Null);
395 assert_eq!(interrupted["status"], "failed");
396 assert_eq!(interrupted["error_code"], "interrupted");
397 assert!(interrupted["completed_at"].as_i64().unwrap() > 0);
398 }
399
400 /// Stale-data path for the 2026-07-30 fee-plan refcount. A dev volume
401 /// carries plans and assignments written before the counter column existed,
402 /// and an absent counter reads as **zero** — which is exactly the value
403 /// that licenses an edit and a delete. Unseeded, every already-assigned
404 /// plan on every existing volume would go editable and deletable again, so
405 /// the backfill is the whole of the stale-data story, not a nicety.
406 #[tokio::test]
407 async fn a_plan_assigned_before_the_counter_existed_is_still_refused() {
408 use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName};
409 use crate::error::AppError;
410
411 let db = super::init_mem().await.unwrap();
412 // The old shape: rows stating every column the older binary knew, and
413 // no `assignment_count` at all. `used` carries an assignment, `free`
414 // does not — a plan nobody is on must stay editable.
415 db.query(
416 "CREATE user:m SET username = 'm', password_hash = 'x';
417 CREATE user:s SET username = 's', password_hash = 'x';
418 CREATE fee_plan:used SET name = 'Yearly',
419 installments = [{ amount_minor: 100, due_at: 1 }],
420 created_by = user:m, created_at = 1;
421 CREATE fee_plan:free SET name = 'Unused',
422 installments = [{ amount_minor: 100, due_at: 1 }],
423 created_by = user:m, created_at = 1;
424 CREATE fee_plan_assignment:used_s SET plan = fee_plan:used,
425 student = user:s, assigned_by = user:m, created_at = 1;",
426 )
427 .await
428 .unwrap()
429 .check()
430 .unwrap();
431
432 // Twice: every boot runs the backfill, and a second pass must not
433 // double a counter it already seeded.
434 super::migrate(&db).await.unwrap();
435 super::migrate(&db).await.unwrap();
436
437 let mut counts = db
438 .query("SELECT VALUE assignment_count FROM fee_plan ORDER BY id")
439 .await
440 .unwrap();
441 let counts: Vec<Option<i64>> = counts.take(0).unwrap();
442 // `free` before `used` by id; the unused plan is deliberately left
443 // absent, which already reads as zero in the guard.
444 assert_eq!(counts, vec![None, Some(1)]);
445
446 // The load-bearing half: the seeded plan is frozen, and the untouched
447 // one is not.
448 let used = FeePlan::read(&FeePlanId::from_key("used"), &db)
449 .await
450 .unwrap()
451 .unwrap();
452 assert!(matches!(
453 used.clone()
454 .update(Some(FeePlanName::try_new("Edited").unwrap()), None, &db)
455 .await,
456 Err(AppError::Conflict(_))
457 ));
458 assert!(!used.delete(&db).await.unwrap());
459 let free = FeePlan::read(&FeePlanId::from_key("free"), &db)
460 .await
461 .unwrap()
462 .unwrap();
463 assert!(
464 free.clone()
465 .update(Some(FeePlanName::try_new("Edited").unwrap()), None, &db)
466 .await
467 .is_ok()
468 );
469 assert!(free.delete(&db).await.unwrap());
470 }
471
472 /// Stale-data path for the 2026-08-02 board-roster repair. `set_role`
473 /// sweeps a demoted user off every board going forward, but an existing
474 /// volume still names parents on rosters — and ids of users deleted before
475 /// any sweep existed. Both freeze the creator's roster `PATCH` at a 400
476 /// (see `web::boards::resolve_participants`), so boot has to clean them.
477 #[tokio::test]
478 async fn a_board_roster_written_before_the_sweep_is_repaired_at_boot() {
479 let db = super::init_mem().await.unwrap();
480 db.query(
481 "CREATE user:s SET username = 's', password_hash = 'x', role = 'student';
482 CREATE user:p SET username = 'p', password_hash = 'x', role = 'parent';
483 CREATE board:keep SET creator = user:s, title = 'B',
484 participants = [user:s, user:p, user:ghost], created_at = 1;
485 CREATE board:gone SET creator = user:s, title = 'C',
486 participants = [user:p], created_at = 1;
487 CREATE board:clean SET creator = user:s, title = 'D',
488 participants = [user:s], created_at = 1;
489 DELETE migration_mark:board_roster;",
490 )
491 .await
492 .unwrap()
493 .check()
494 .unwrap();
495 // `init_mem` boots a *migrated* database, so it has already marked the
496 // repair done on an empty store — which is right, and is exactly why the
497 // mark is dropped here: a volume written before the mark existed carries
498 // stale rosters and no mark at all, and that is the state under test.
499 // A write probe on the table under repair: the event fires *inside* the
500 // UPDATE, so it counts real writes rather than trusting a re-read.
501 db.query(
502 "DEFINE TABLE board_write_probe SCHEMALESS;
503 DEFINE EVENT board_write ON board WHEN $event = 'UPDATE' THEN {
504 UPSERT type::record('board_write_probe', 'n') SET n = (n ?? 0) + 1;
505 };",
506 )
507 .await
508 .unwrap()
509 .check()
510 .unwrap();
511
512 super::migrate(&db).await.unwrap();
513
514 async fn rosters(db: &super::Database) -> Vec<Vec<surrealdb::types::RecordId>> {
515 let mut rows = db
516 .query("SELECT VALUE participants FROM board ORDER BY id")
517 .await
518 .unwrap();
519 rows.take(0).unwrap()
520 }
521 let after_first = rosters(&db).await;
522 let s = surrealdb::types::RecordId::new("user", "s");
523 // `clean`, `gone`, `keep` by id. The parent and the vanished user are
524 // both gone; a board whose whole roster was stale ends empty, which is
525 // the same shape a board opened without invites carries.
526 assert_eq!(
527 after_first,
528 vec![vec![s.clone()], vec![], vec![s.clone()]],
529 "{after_first:?}"
530 );
531
532 async fn writes(db: &super::Database) -> Vec<i64> {
533 let mut rows = db
534 .query("SELECT VALUE n FROM board_write_probe:n")
535 .await
536 .unwrap();
537 rows.take(0).unwrap()
538 }
539 assert_eq!(
540 writes(&db).await,
541 vec![2],
542 "only the two stale rows repaired"
543 );
544
545 // The second boot: every boot runs the backfill, and a converged row
546 // must not be written again.
547 super::migrate(&db).await.unwrap();
548 assert_eq!(rosters(&db).await, after_first);
549 assert_eq!(writes(&db).await, vec![2], "the second pass wrote nothing");
550
551 // …and it did not *look*, either, which is the whole point of the mark:
552 // the repair's cost is a `user` table scan per board, and writing
553 // nothing is not the same as scanning nothing. A roster made stale after
554 // the mark landed is the probe — it survives the next boot untouched,
555 // which no converging `WHERE` could produce.
556 let mut mark = db
557 .query("SELECT VALUE done_at FROM migration_mark:board_roster")
558 .await
559 .unwrap();
560 assert_eq!(
561 mark.take::<Vec<i64>>(0).unwrap().len(),
562 1,
563 "the repair marks itself finished"
564 );
565 db.query("CREATE board:late SET creator = user:s, title = 'E', participants = [user:p], created_at = 1")
566 .await
567 .unwrap()
568 .check()
569 .unwrap();
570 super::migrate(&db).await.unwrap();
571 assert_eq!(
572 rosters(&db).await,
573 vec![
574 vec![s.clone()],
575 vec![],
576 vec![s.clone()],
577 vec![surrealdb::types::RecordId::new("user", "p")]
578 ],
579 "a marked database skips the scan entirely"
580 );
581 assert_eq!(writes(&db).await, vec![2]);
582 }
583
584 /// Stale-data path for the 2026-08-04 badge counters. Every account on an
585 /// existing volume predates the columns, and a badge is decided off the
586 /// stored total — so a zero start would not lose a number, it would
587 /// permanently mis-award the student who really did the work. Boot seeds the
588 /// counters from the rows that exist, exactly once.
589 #[tokio::test]
590 async fn the_badge_counters_are_seeded_from_history_exactly_once() {
591 let db = super::init_mem().await.unwrap();
592 db.query(
593 "CREATE user:a SET username = 'a', password_hash = 'x', role = 'student';
594 CREATE user:b SET username = 'b', password_hash = 'x', role = 'student';
595 CREATE user:c SET username = 'c', password_hash = 'x', role = 'student';
596 CREATE homework:h SET course = course:c, subject = subject:s, title = 'H',
597 due_at = 100, created_by = user:a, created_at = 1;
598 -- Three on time (the equal case counts as on time) and one whose
599 -- homework was deleted out from under it: that last one is
600 -- submitted but not on time, because the traversal yields nothing.
601 CREATE homework_submission:s1 SET homework = homework:h, user = user:a,
602 submitted_at = 50, updated_at = 50;
603 CREATE homework_submission:s2 SET homework = homework:h, user = user:a,
604 submitted_at = 60, updated_at = 100;
605 -- Handed in before the deadline, then edited well after it — a
606 -- `touch()` from a single file add does this. On time, because the
607 -- live path credits the hand-in and debits by `submitted_at`; if
608 -- the seed judged this one by `updated_at` a later withdrawal
609 -- would decrement a credit that was never given.
610 CREATE homework_submission:s3 SET homework = homework:h, user = user:a,
611 submitted_at = 70, updated_at = 200;
612 CREATE homework_submission:s4 SET homework = homework:gone, user = user:a,
613 submitted_at = 80, updated_at = 1;
614 CREATE exam_attempt:e1 SET exam = exam:x, user = user:a, seq = 1, started_at = 1;
615 CREATE exam_attempt:e2 SET exam = exam:y, user = user:a, seq = 1, started_at = 2;
616 -- Two finished stints and one still open, which counts for neither.
617 CREATE pomodoro_session:p1 SET user = user:a, started_at = 1000, finished_at = 2000;
618 CREATE pomodoro_session:p2 SET user = user:a, started_at = 5000, finished_at = 7500;
619 CREATE pomodoro_session:p3 SET user = user:a, started_at = 9000;
620 -- One real stint beside one written with a backwards clock. The
621 -- floor is per row, like the live close, so the negative one
622 -- contributes zero and the real 1000ms survives; flooring the
623 -- per-user sum instead would seed 0 and lose the real stint.
624 CREATE pomodoro_session:p4 SET user = user:c, started_at = 0, finished_at = 1000;
625 CREATE pomodoro_session:p5 SET user = user:c, started_at = 9000, finished_at = 3000;
626 DELETE migration_mark:profile_counters;",
627 )
628 .await
629 .unwrap()
630 .check()
631 .unwrap();
632 // `init_mem` boots a *migrated* database, so the seed is already marked
633 // done on an empty store — which is right, and is exactly why the mark is
634 // dropped here: a volume written before the columns existed carries
635 // history and no mark at all, and that is the state under test.
636 // A write probe on the table being seeded: the event fires *inside* the
637 // UPDATE, so it counts real writes rather than trusting a re-read.
638 db.query(
639 "DEFINE TABLE user_write_probe SCHEMALESS;
640 DEFINE EVENT user_write ON user WHEN $event = 'UPDATE' THEN {
641 UPSERT type::record('user_write_probe', 'n') SET n = (n ?? 0) + 1;
642 };",
643 )
644 .await
645 .unwrap()
646 .check()
647 .unwrap();
648
649 super::migrate(&db).await.unwrap();
650
651 async fn counters(db: &super::Database) -> Vec<(i64, i64, i64, i64, i64)> {
652 let mut rows = db
653 .query(
654 "SELECT VALUE [homework_submitted_total, homework_on_time_total,
655 exam_sat_total, pomodoro_finished_total,
656 pomodoro_focus_ms_total]
657 FROM user ORDER BY id",
658 )
659 .await
660 .unwrap();
661 rows.take::<Vec<Vec<i64>>>(0)
662 .unwrap()
663 .into_iter()
664 .map(|row| (row[0], row[1], row[2], row[3], row[4]))
665 .collect()
666 }
667 let after_first = counters(&db).await;
668 // `a`, `b`, `c` by id. `b` has no history at all and reads as a fresh
669 // account; `c` keeps the 1000ms real stint the -6000ms one sits beside.
670 assert_eq!(
671 after_first,
672 vec![(4, 3, 2, 2, 3500), (0, 0, 0, 0, 0), (0, 0, 0, 2, 1000)],
673 "{after_first:?}"
674 );
675
676 // The seed also stamps each submission with the verdict it was counted
677 // under, because `due_at` is mutable: a withdrawal after the teacher
678 // moves the deadline must debit what was credited, not what the
679 // deadline says by then. Asserted through `WHERE` rather than read back
680 // as a column, so an unstamped row would show up as belonging to
681 // neither set instead of deserializing as some default.
682 async fn stamped(db: &super::Database, cond: &str) -> Vec<String> {
683 let mut rows = db
684 .query(format!(
685 "SELECT VALUE record::id(id) FROM homework_submission
686 WHERE {cond} ORDER BY id"
687 ))
688 .await
689 .unwrap();
690 rows.take(0).unwrap()
691 }
692 // s1/s2/s3 beat the deadline (50, 60, 70 vs 100). s4 hangs off a
693 // deleted homework, so `submitted_at <= homework.due_at` compares
694 // against NONE and lands on `false` — which is exactly what the count
695 // above credited it as, so the stamp agrees with the counter rather
696 // than leaving the row to a fallback that could later disagree.
697 assert_eq!(
698 stamped(&db, "counted_on_time = true").await,
699 ["s1", "s2", "s3"]
700 );
701 assert_eq!(stamped(&db, "counted_on_time = false").await, ["s4"]);
702
703 async fn writes(db: &super::Database) -> Vec<i64> {
704 let mut rows = db
705 .query("SELECT VALUE n FROM user_write_probe:n")
706 .await
707 .unwrap();
708 rows.take(0).unwrap()
709 }
710 let first_writes = writes(&db).await;
711 // Pinned non-zero, not just compared: "the second pass wrote nothing"
712 // would hold vacuously if the probe itself stopped firing, and then the
713 // test would pass on a seed that never ran.
714 assert!(
715 matches!(first_writes.as_slice(), [n] if *n > 0),
716 "{first_writes:?}"
717 );
718
719 // The second boot: every boot runs the backfill, and a recount here
720 // would not converge the way the counters above it do — these columns
721 // are maintained by the request path from now on, so a second pass would
722 // overwrite everything earned since. It must not write at all…
723 super::migrate(&db).await.unwrap();
724 assert_eq!(counters(&db).await, after_first);
725 assert_eq!(
726 writes(&db).await,
727 first_writes,
728 "the second pass wrote nothing"
729 );
730
731 // …and it must not *look*, either, which is the whole point of the mark:
732 // writing nothing is not the same as scanning nothing. A submission that
733 // lands after the mark is the probe — its counter stays where the request
734 // path left it, which no recomputing backfill could produce.
735 let mut mark = db
736 .query("SELECT VALUE done_at FROM migration_mark:profile_counters")
737 .await
738 .unwrap();
739 assert_eq!(
740 mark.take::<Vec<i64>>(0).unwrap().len(),
741 1,
742 "the seed marks itself finished"
743 );
744 db.query(
745 "CREATE homework_submission:late SET homework = homework:h, user = user:b,
746 submitted_at = 90, updated_at = 90;",
747 )
748 .await
749 .unwrap()
750 .check()
751 .unwrap();
752 super::migrate(&db).await.unwrap();
753 assert_eq!(
754 counters(&db).await,
755 after_first,
756 "a marked database skips the seed entirely"
757 );
758 assert_eq!(writes(&db).await, first_writes);
759 }
760
761 #[tokio::test]
762 async fn the_retired_claim_columns_are_dropped_off_a_live_row() {
763 // Stale-data path for the 2026-07-30 removal of the chat claim queue.
764 // A dev volume carries `chatbot_message` rows *with* claim values and an
765 // `ai_worker` table, so the boot has to clear the values while their
766 // definitions still stand (PRE_REPAIR) and only then retire the columns
767 // — SCHEMAFULL rejects every write to a row storing a column that no
768 // longer exists, which would make the row unanswerable forever.
769 let db = super::init_mem().await.unwrap();
770 db.query(
771 "DEFINE FIELD claimed_by ON chatbot_message TYPE option<string>;
772 DEFINE FIELD claimed_at ON chatbot_message TYPE option<int>;
773 DEFINE TABLE ai_worker SCHEMAFULL;
774 DEFINE FIELD seen_at ON ai_worker TYPE int;
775 DEFINE TABLE migration_lock SCHEMALESS;",
776 )
777 .await
778 .unwrap()
779 .check()
780 .unwrap();
781 db.query(
782 "CREATE user:u SET username = 'u', password_hash = 'x';
783 CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1;
784 CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u,
785 role = 'assistant', content = '', status = 'pending',
786 created_at = time::unix(time::now()) * 1000,
787 claimed_by = 'a-dead-replica', claimed_at = 1;
788 CREATE ai_worker:w SET seen_at = 1;
789 CREATE migration_lock:the_lock SET holder = 'a-dead-replica', expires_at = 1;",
790 )
791 .await
792 .unwrap()
793 .check()
794 .unwrap();
795
796 // Twice: the repair and both removals have to be idempotent, since
797 // every boot runs them.
798 super::migrate(&db).await.unwrap();
799 super::migrate(&db).await.unwrap();
800
801 let mut info = db.query("INFO FOR TABLE chatbot_message").await.unwrap();
802 let table: serde_json::Value = info.take::<Option<serde_json::Value>>(0).unwrap().unwrap();
803 let fields = table["fields"].as_object().expect("fields");
804 assert!(!fields.contains_key("claimed_by"), "{table}");
805 assert!(!fields.contains_key("claimed_at"), "{table}");
806 let mut tables = db.query("INFO FOR DB").await.unwrap();
807 let dbinfo: serde_json::Value = tables
808 .take::<Option<serde_json::Value>>(0)
809 .unwrap()
810 .unwrap();
811 let tables = dbinfo["tables"].as_object().expect("tables");
812 assert!(!tables.contains_key("ai_worker"), "{dbinfo}");
813 // Same story one table over: the elected-boot lease, stale leader row
814 // and all.
815 assert!(!tables.contains_key("migration_lock"), "{dbinfo}");
816
817 // The load-bearing half: the row that carried a claim is still
818 // writable. A leftover value under no definition fails here.
819 db.query("UPDATE chatbot_message:m SET status = 'complete', content = 'ok'")
820 .await
821 .unwrap()
822 .check()
823 .unwrap();
824 let mut row = db
825 .query("SELECT * FROM ONLY chatbot_message:m")
826 .await
827 .unwrap();
828 let row: serde_json::Value = row.take::<Option<serde_json::Value>>(0).unwrap().unwrap();
829 assert_eq!(row["status"], "complete", "{row}");
830 assert!(row.get("claimed_by").is_none(), "{row}");
831 }
832
833 /// The other half of the sweep: a restart seconds after a dispatch must not
834 /// kill the turn — the answering task may still be alive on the other side
835 /// of the bridge, and the row is not yet past the stale horizon.
836 #[tokio::test]
837 async fn boot_spares_a_chatbot_message_pending_since_just_now() {
838 let db = super::init_mem().await.unwrap();
839 db.query(
840 "CREATE user:u SET username = 'u', password_hash = 'x';
841 CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1;
842 CREATE chatbot_message:fresh SET thread_id = chatbot_thread:c, user_id = user:u,
843 role = 'assistant', content = '', status = 'pending',
844 created_at = time::unix(time::now()) * 1000 - 2000;
845 CREATE chatbot_message:old SET thread_id = chatbot_thread:c, user_id = user:u,
846 role = 'assistant', content = '', status = 'pending',
847 created_at = time::unix(time::now()) * 1000
848 - ($stale + 1) * 1000;",
849 )
850 .bind(("stale", crate::constant::CHATBOT_PENDING_STALE_SECS))
851 .await
852 .unwrap()
853 .check()
854 .unwrap();
855
856 super::migrate(&db).await.unwrap();
857
858 let mut res = db
859 .query(
860 "SELECT status, error_code FROM ONLY chatbot_message:fresh;
861 SELECT VALUE status FROM ONLY chatbot_message:old;",
862 )
863 .await
864 .unwrap();
865 let fresh: Option<serde_json::Value> = res.take(0).unwrap();
866 let fresh = fresh.unwrap();
867 let old: Option<String> = res.take(1).unwrap();
868 assert_eq!(
869 fresh["status"], "pending",
870 "a two-second-old turn is still being answered"
871 );
872 assert_eq!(fresh["error_code"], serde_json::Value::Null);
873 assert_eq!(old.as_deref(), Some("failed"), "past the horizon it goes");
874 }
875
876 /// A row written before choices had ids survives the retyped columns: it is
877 /// converted, it is writable again, and its stored *position* still names
878 /// the same option — a wrong remap here silently regrades exams.
879 #[tokio::test]
880 async fn boot_converts_positional_choices_and_keeps_the_same_option() {
881 let db = super::init_mem().await.unwrap();
882 // Roll the columns back to their pre-2026-07-24 shapes and write the
883 // kind of row an older binary left behind, `source_bank` included.
884 db.query(
885 "REMOVE FIELD IF EXISTS choices[*].id ON TABLE exam_question;
886 REMOVE FIELD IF EXISTS choices[*].text ON TABLE exam_question;
887 REMOVE FIELD IF EXISTS choices[*].id ON TABLE bank_question;
888 REMOVE FIELD IF EXISTS choices[*].text ON TABLE bank_question;
889 DEFINE FIELD OVERWRITE choices ON exam_question TYPE option<array<string>>;
890 DEFINE FIELD OVERWRITE correct ON exam_question TYPE option<int>;
891 DEFINE FIELD OVERWRITE source_bank ON exam_question TYPE option<string>;
892 DEFINE FIELD OVERWRITE slot ON question_image TYPE option<int>;
893 DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option<int>;
894 DEFINE FIELD OVERWRITE choices ON bank_question TYPE option<array<string>>;
895 DEFINE FIELD OVERWRITE correct ON bank_question TYPE option<int>;
896 DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option<int>;",
897 )
898 .await
899 .unwrap()
900 .check()
901 .unwrap();
902 db.query(
903 "CREATE user:u SET username = 'u', password_hash = 'x';
904 CREATE exam_question:q SET exam = exam:e, text = 'q', kind = 'multiple',
905 points = 5, subject = subject:s, choices = ['3', '4', '5'], correct = 1,
906 source_bank = 'bank_question:b';
907 CREATE question_image:i SET exam = exam:e, question = exam_question:q, slot = 2,
908 file = 'f', content_type = 'image/png', size = 1;
909 CREATE question_image:whole SET exam = exam:e, question = exam_question:q,
910 file = 'w', content_type = 'image/png', size = 1;
911 CREATE exam_answer:a SET exam = exam:e, question = exam_question:q, user = user:u,
912 selected = 2, updated_at = 1;
913 CREATE bank_question:b SET owner = user:u, text = 'b', kind = 'multiple',
914 points = 3, choices = ['a', 'b'], correct = 0, created_at = 1;
915 CREATE bank_question_image:bi SET bank_question = bank_question:b, slot = 1,
916 file = 'bf', content_type = 'image/png', size = 1;",
917 )
918 .await
919 .unwrap()
920 .check()
921 .unwrap();
922
923 super::migrate(&db).await.unwrap();
924
925 let mut res = db
926 .query(
927 "SELECT choices, correct FROM ONLY exam_question:q;
928 SELECT VALUE slot FROM ONLY question_image:i;
929 SELECT VALUE slot FROM ONLY question_image:whole;
930 SELECT VALUE selected FROM ONLY exam_answer:a;
931 SELECT choices, correct FROM ONLY bank_question:b;
932 SELECT VALUE slot FROM ONLY bank_question_image:bi;",
933 )
934 .await
935 .unwrap();
936 let q: Option<serde_json::Value> = res.take(0).unwrap();
937 let q = q.unwrap();
938 let img_slot: Option<String> = res.take(1).unwrap();
939 let whole_slot: Option<String> = res.take(2).unwrap();
940 let selected: Option<String> = res.take(3).unwrap();
941 let bank: Option<serde_json::Value> = res.take(4).unwrap();
942 let bank = bank.unwrap();
943 let bank_slot: Option<String> = res.take(5).unwrap();
944
945 let ids: Vec<&str> = q["choices"]
946 .as_array()
947 .unwrap()
948 .iter()
949 .map(|c| c["id"].as_str().unwrap())
950 .collect();
951 assert_eq!(
952 q["choices"][0]["text"], "3",
953 "option order (and so the meaning of every stored index) is preserved"
954 );
955 assert_eq!(q["correct"], ids[1], "correct was index 1");
956 assert_eq!(
957 img_slot.as_deref(),
958 Some(ids[2]),
959 "option picture was slot 2"
960 );
961 assert_eq!(selected.as_deref(), Some(ids[2]), "the answer was index 2");
962 assert_eq!(whole_slot, None, "a question-level picture has no index");
963 let bank_ids: Vec<&str> = bank["choices"]
964 .as_array()
965 .unwrap()
966 .iter()
967 .map(|c| c["id"].as_str().unwrap())
968 .collect();
969 assert_eq!(bank["correct"], bank_ids[0]);
970 assert_eq!(bank_slot.as_deref(), Some(bank_ids[1]));
971
972 // Writable again — every one of these failed coercion before the
973 // backfill existed, and `source_bank` outlived its own column.
974 db.query(
975 "UPDATE exam_question:q SET points = 7;
976 UPDATE question_image:i SET size = 2;
977 UPDATE exam_answer:a SET updated_at = 2;
978 UPDATE bank_question:b SET points = 4;
979 UPDATE bank_question_image:bi SET size = 2;",
980 )
981 .await
982 .unwrap()
983 .check()
984 .unwrap();
985
986 // A second boot re-mints nothing.
987 super::migrate(&db).await.unwrap();
988 let mut res = db
989 .query("SELECT VALUE choices.map(|$c| $c.id) FROM ONLY exam_question:q")
990 .await
991 .unwrap();
992 let again: Vec<String> = res.take(0).unwrap();
993 assert_eq!(again, ids, "conversion is idempotent");
994 }
995}