forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBc9b707aAhmet Kaan Gümüş4 months ago189 commits

database.rs706 lines, 31.8 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 #[tokio::test]
473 async fn the_retired_claim_columns_are_dropped_off_a_live_row() {
474 // Stale-data path for the 2026-07-30 removal of the chat claim queue.
475 // A dev volume carries `chatbot_message` rows *with* claim values and an
476 // `ai_worker` table, so the boot has to clear the values while their
477 // definitions still stand (PRE_REPAIR) and only then retire the columns
478 // — SCHEMAFULL rejects every write to a row storing a column that no
479 // longer exists, which would make the row unanswerable forever.
480 let db = super::init_mem().await.unwrap();
481 db.query(
482 "DEFINE FIELD claimed_by ON chatbot_message TYPE option<string>;
483 DEFINE FIELD claimed_at ON chatbot_message TYPE option<int>;
484 DEFINE TABLE ai_worker SCHEMAFULL;
485 DEFINE FIELD seen_at ON ai_worker TYPE int;
486 DEFINE TABLE migration_lock SCHEMALESS;",
487 )
488 .await
489 .unwrap()
490 .check()
491 .unwrap();
492 db.query(
493 "CREATE user:u SET username = 'u', password_hash = 'x';
494 CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1;
495 CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u,
496 role = 'assistant', content = '', status = 'pending',
497 created_at = time::unix(time::now()) * 1000,
498 claimed_by = 'a-dead-replica', claimed_at = 1;
499 CREATE ai_worker:w SET seen_at = 1;
500 CREATE migration_lock:the_lock SET holder = 'a-dead-replica', expires_at = 1;",
501 )
502 .await
503 .unwrap()
504 .check()
505 .unwrap();
506
507 // Twice: the repair and both removals have to be idempotent, since
508 // every boot runs them.
509 super::migrate(&db).await.unwrap();
510 super::migrate(&db).await.unwrap();
511
512 let mut info = db.query("INFO FOR TABLE chatbot_message").await.unwrap();
513 let table: serde_json::Value = info.take::<Option<serde_json::Value>>(0).unwrap().unwrap();
514 let fields = table["fields"].as_object().expect("fields");
515 assert!(!fields.contains_key("claimed_by"), "{table}");
516 assert!(!fields.contains_key("claimed_at"), "{table}");
517 let mut tables = db.query("INFO FOR DB").await.unwrap();
518 let dbinfo: serde_json::Value = tables
519 .take::<Option<serde_json::Value>>(0)
520 .unwrap()
521 .unwrap();
522 let tables = dbinfo["tables"].as_object().expect("tables");
523 assert!(!tables.contains_key("ai_worker"), "{dbinfo}");
524 // Same story one table over: the elected-boot lease, stale leader row
525 // and all.
526 assert!(!tables.contains_key("migration_lock"), "{dbinfo}");
527
528 // The load-bearing half: the row that carried a claim is still
529 // writable. A leftover value under no definition fails here.
530 db.query("UPDATE chatbot_message:m SET status = 'complete', content = 'ok'")
531 .await
532 .unwrap()
533 .check()
534 .unwrap();
535 let mut row = db
536 .query("SELECT * FROM ONLY chatbot_message:m")
537 .await
538 .unwrap();
539 let row: serde_json::Value = row.take::<Option<serde_json::Value>>(0).unwrap().unwrap();
540 assert_eq!(row["status"], "complete", "{row}");
541 assert!(row.get("claimed_by").is_none(), "{row}");
542 }
543
544 /// The other half of the sweep: a restart seconds after a dispatch must not
545 /// kill the turn — the answering task may still be alive on the other side
546 /// of the bridge, and the row is not yet past the stale horizon.
547 #[tokio::test]
548 async fn boot_spares_a_chatbot_message_pending_since_just_now() {
549 let db = super::init_mem().await.unwrap();
550 db.query(
551 "CREATE user:u SET username = 'u', password_hash = 'x';
552 CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1;
553 CREATE chatbot_message:fresh SET thread_id = chatbot_thread:c, user_id = user:u,
554 role = 'assistant', content = '', status = 'pending',
555 created_at = time::unix(time::now()) * 1000 - 2000;
556 CREATE chatbot_message:old SET thread_id = chatbot_thread:c, user_id = user:u,
557 role = 'assistant', content = '', status = 'pending',
558 created_at = time::unix(time::now()) * 1000
559 - ($stale + 1) * 1000;",
560 )
561 .bind(("stale", crate::constant::CHATBOT_PENDING_STALE_SECS))
562 .await
563 .unwrap()
564 .check()
565 .unwrap();
566
567 super::migrate(&db).await.unwrap();
568
569 let mut res = db
570 .query(
571 "SELECT status, error_code FROM ONLY chatbot_message:fresh;
572 SELECT VALUE status FROM ONLY chatbot_message:old;",
573 )
574 .await
575 .unwrap();
576 let fresh: Option<serde_json::Value> = res.take(0).unwrap();
577 let fresh = fresh.unwrap();
578 let old: Option<String> = res.take(1).unwrap();
579 assert_eq!(
580 fresh["status"], "pending",
581 "a two-second-old turn is still being answered"
582 );
583 assert_eq!(fresh["error_code"], serde_json::Value::Null);
584 assert_eq!(old.as_deref(), Some("failed"), "past the horizon it goes");
585 }
586
587 /// A row written before choices had ids survives the retyped columns: it is
588 /// converted, it is writable again, and its stored *position* still names
589 /// the same option — a wrong remap here silently regrades exams.
590 #[tokio::test]
591 async fn boot_converts_positional_choices_and_keeps_the_same_option() {
592 let db = super::init_mem().await.unwrap();
593 // Roll the columns back to their pre-2026-07-24 shapes and write the
594 // kind of row an older binary left behind, `source_bank` included.
595 db.query(
596 "REMOVE FIELD IF EXISTS choices[*].id ON TABLE exam_question;
597 REMOVE FIELD IF EXISTS choices[*].text ON TABLE exam_question;
598 REMOVE FIELD IF EXISTS choices[*].id ON TABLE bank_question;
599 REMOVE FIELD IF EXISTS choices[*].text ON TABLE bank_question;
600 DEFINE FIELD OVERWRITE choices ON exam_question TYPE option<array<string>>;
601 DEFINE FIELD OVERWRITE correct ON exam_question TYPE option<int>;
602 DEFINE FIELD OVERWRITE source_bank ON exam_question TYPE option<string>;
603 DEFINE FIELD OVERWRITE slot ON question_image TYPE option<int>;
604 DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option<int>;
605 DEFINE FIELD OVERWRITE choices ON bank_question TYPE option<array<string>>;
606 DEFINE FIELD OVERWRITE correct ON bank_question TYPE option<int>;
607 DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option<int>;",
608 )
609 .await
610 .unwrap()
611 .check()
612 .unwrap();
613 db.query(
614 "CREATE user:u SET username = 'u', password_hash = 'x';
615 CREATE exam_question:q SET exam = exam:e, text = 'q', kind = 'multiple',
616 points = 5, subject = subject:s, choices = ['3', '4', '5'], correct = 1,
617 source_bank = 'bank_question:b';
618 CREATE question_image:i SET exam = exam:e, question = exam_question:q, slot = 2,
619 file = 'f', content_type = 'image/png', size = 1;
620 CREATE question_image:whole SET exam = exam:e, question = exam_question:q,
621 file = 'w', content_type = 'image/png', size = 1;
622 CREATE exam_answer:a SET exam = exam:e, question = exam_question:q, user = user:u,
623 selected = 2, updated_at = 1;
624 CREATE bank_question:b SET owner = user:u, text = 'b', kind = 'multiple',
625 points = 3, choices = ['a', 'b'], correct = 0, created_at = 1;
626 CREATE bank_question_image:bi SET bank_question = bank_question:b, slot = 1,
627 file = 'bf', content_type = 'image/png', size = 1;",
628 )
629 .await
630 .unwrap()
631 .check()
632 .unwrap();
633
634 super::migrate(&db).await.unwrap();
635
636 let mut res = db
637 .query(
638 "SELECT choices, correct FROM ONLY exam_question:q;
639 SELECT VALUE slot FROM ONLY question_image:i;
640 SELECT VALUE slot FROM ONLY question_image:whole;
641 SELECT VALUE selected FROM ONLY exam_answer:a;
642 SELECT choices, correct FROM ONLY bank_question:b;
643 SELECT VALUE slot FROM ONLY bank_question_image:bi;",
644 )
645 .await
646 .unwrap();
647 let q: Option<serde_json::Value> = res.take(0).unwrap();
648 let q = q.unwrap();
649 let img_slot: Option<String> = res.take(1).unwrap();
650 let whole_slot: Option<String> = res.take(2).unwrap();
651 let selected: Option<String> = res.take(3).unwrap();
652 let bank: Option<serde_json::Value> = res.take(4).unwrap();
653 let bank = bank.unwrap();
654 let bank_slot: Option<String> = res.take(5).unwrap();
655
656 let ids: Vec<&str> = q["choices"]
657 .as_array()
658 .unwrap()
659 .iter()
660 .map(|c| c["id"].as_str().unwrap())
661 .collect();
662 assert_eq!(
663 q["choices"][0]["text"], "3",
664 "option order (and so the meaning of every stored index) is preserved"
665 );
666 assert_eq!(q["correct"], ids[1], "correct was index 1");
667 assert_eq!(
668 img_slot.as_deref(),
669 Some(ids[2]),
670 "option picture was slot 2"
671 );
672 assert_eq!(selected.as_deref(), Some(ids[2]), "the answer was index 2");
673 assert_eq!(whole_slot, None, "a question-level picture has no index");
674 let bank_ids: Vec<&str> = bank["choices"]
675 .as_array()
676 .unwrap()
677 .iter()
678 .map(|c| c["id"].as_str().unwrap())
679 .collect();
680 assert_eq!(bank["correct"], bank_ids[0]);
681 assert_eq!(bank_slot.as_deref(), Some(bank_ids[1]));
682
683 // Writable again — every one of these failed coercion before the
684 // backfill existed, and `source_bank` outlived its own column.
685 db.query(
686 "UPDATE exam_question:q SET points = 7;
687 UPDATE question_image:i SET size = 2;
688 UPDATE exam_answer:a SET updated_at = 2;
689 UPDATE bank_question:b SET points = 4;
690 UPDATE bank_question_image:bi SET size = 2;",
691 )
692 .await
693 .unwrap()
694 .check()
695 .unwrap();
696
697 // A second boot re-mints nothing.
698 super::migrate(&db).await.unwrap();
699 let mut res = db
700 .query("SELECT VALUE choices.map(|$c| $c.id) FROM ONLY exam_question:q")
701 .await
702 .unwrap();
703 let again: Vec<String> = res.take(0).unwrap();
704 assert_eq!(again, ids, "conversion is idempotent");
705 }
706}