forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB466ea10Ahmet Kaan Gümüş2 months ago341 commits

database.rs1336 lines, 60.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::builder::Builder;
10use crate::domain::timestamp::Timestamp;
11use crate::domain::user::{Password, Username};
12use crate::error::AppError;
13use crate::migration_sql::{BACKFILL, CONTROL_MIGRATION_BATCHES, MIGRATION_BATCHES};
14use crate::tenant::Tenants;
15
16/// The shared database handle.
17///
18/// `Arc` is load-bearing, not decoration. `Surreal`'s own `Clone` mints a
19/// fresh server-side session per clone (`Uuid::new_v4()` + a fire-and-forget
20/// `SessionId::Clone` to the router, SDK `lib.rs:340`), and axum clones the
21/// application state on every request — so a bare `Surreal<Any>` here means a
22/// new session, and a matching `SessionId::Drop`, for each request served.
23/// Under concurrency those lifecycle events race the queries riding on them:
24/// sessions disappear ("Session not found"), and a session whose signin has
25/// not been replayed answers "Anonymous access not allowed" / "Specify a
26/// namespace" — the same strings [`crate::error::is_session_replay_error`]
27/// treats as a transient reconnect, so the failures masquerade as one.
28///
29/// Cloning the `Arc` shares the single session established at boot instead.
30pub type Database = std::sync::Arc<Surreal<Any>>;
31
32/// Connect to the **control** database, sign in as root, apply the control
33/// schema and seed the builder account. School databases are brought up
34/// separately, one per school, by [`crate::tenant::Tenants`].
35pub async fn init(cfg: &Config) -> Result<Tenants, AppError> {
36 // Validated before the connection, not after: half a credential pair is a
37 // deployment mistake, and reporting it only after a successful dial buries
38 // it under an outage that isn't one.
39 let builder = builder_credentials(cfg)?;
40 let db = connect_with_retry(cfg).await;
41 db.signin(Root {
42 username: cfg.db_user.clone(),
43 password: cfg.db_pass.clone(),
44 })
45 .await?;
46 db.use_ns(cfg.db_ns.clone())
47 .use_db(cfg.db_name.clone())
48 .await?;
49 let db = std::sync::Arc::new(db);
50 migrate_control(&db).await?;
51 if let Some((username, password)) = builder {
52 Builder::ensure(username, password, &db).await?;
53 }
54 Ok(Tenants::new_remote(db, cfg))
55}
56
57/// The `BUILDER_USERNAME` / `BUILDER_PASSWORD` bootstrap pair, if configured.
58/// Both-or-neither: half a pair aborts startup rather than silently running
59/// without the seed — and without a builder, a fresh deployment has nobody who
60/// can create the first school.
61fn builder_credentials(cfg: &Config) -> Result<Option<(Username, Password)>, AppError> {
62 match (&cfg.builder_username, &cfg.builder_password) {
63 (Some(username), Some(password)) => Ok(Some((
64 Username::try_new(username)
65 .map_err(|err| AppError::Internal(format!("invalid BUILDER_USERNAME: {err}")))?,
66 Password::try_new(password)
67 .map_err(|err| AppError::Internal(format!("invalid BUILDER_PASSWORD: {err}")))?,
68 ))),
69 (None, None) => Ok(None),
70 _ => Err(AppError::Internal(
71 "BUILDER_USERNAME and BUILDER_PASSWORD must be set together".into(),
72 )),
73 }
74}
75
76/// The two ways a rival's claim shows up as an error on ours: our `CREATE` hit
77/// their row, or the key-value layer aborted our transaction because theirs
78/// touched the same key first.
79///
80/// Read from the *typed* error surface, not the message. Every conflict wording
81/// the storage engines produce — surrealkv's "Transaction conflict: Write
82/// conflict, retry the transaction. This transaction can be retried",
83/// surrealmx's read-conflict variant, RocksDB's `Busy`/`TryAgain` — funnels
84/// through one `KvsError::TransactionConflict` into
85/// `QueryError::TransactionConflict` (surrealdb-core 3.2.3
86/// `err/to_types.rs:295`, `kvs/err.rs:64-179`), and a duplicate record id into
87/// `AlreadyExistsError::Record` (`to_types.rs:206`). So the two checks below
88/// cover all of them, where matching substrings covered only whichever wording
89/// the engine of the day happened to use.
90///
91/// The message fallback stays for one reason: these errors also travel over the
92/// WebSocket, where the SDK rebuilds them from the wire (`Error::from_parts`),
93/// and a server that omitted the typed details would otherwise turn a lost race
94/// into a failed boot. Widest known wordings, cheap, and belt-and-braces.
95pub(crate) fn lost_the_race(err: &surrealdb::Error) -> bool {
96 use surrealdb::types::{ErrorDetails, QueryError};
97 if err.is_already_exists()
98 || matches!(
99 err.details(),
100 ErrorDetails::Query(Some(QueryError::TransactionConflict))
101 )
102 {
103 return true;
104 }
105 let message = err.to_string();
106 message.contains("already exists") || message.contains("can be retried")
107}
108
109/// Send one guarded single-statement write, re-sending it while the store
110/// answers "conflict, retry", and hand back the rows it returned.
111///
112/// The guard on such a statement reads a column a rival writes, so the two
113/// contend on one record *by design* — that contention is what makes the guard
114/// atomic. Losing a round writes nothing at all, which makes re-sending the
115/// whole of the recovery; without it an ordinary raced `PATCH` or `DELETE`
116/// answers 500 instead of the 404 or 409 it owes. Only for statements that
117/// cannot produce "already exists" (the other thing [`lost_the_race`] matches),
118/// so `UPDATE` and `DELETE` and not `CREATE`.
119pub(crate) async fn write_with_retry<T: surrealdb::types::SurrealValue>(
120 db: &Database,
121 sql: &str,
122 bindings: &[(String, surrealdb::types::Value)],
123) -> Result<Vec<T>, AppError> {
124 let mut last = None;
125 for attempt in 0..CAP_WRITE_TRIES {
126 backoff(attempt).await;
127 let mut query = db.query(sql);
128 for (name, value) in bindings {
129 query = query.bind((name.clone(), value.clone()));
130 }
131 match async { query.await?.check()?.take::<Vec<T>>(0) }.await {
132 Ok(rows) => return Ok(rows),
133 Err(err) if lost_the_race(&err) => last = Some(err),
134 Err(err) => return Err(err.into()),
135 }
136 }
137 Err(last
138 .map(AppError::from)
139 .unwrap_or_else(|| AppError::Internal("a guarded write never ran".into())))
140}
141
142/// Send one guarded `BEGIN…COMMIT` cascade, re-sending it while the store
143/// answers "conflict, retry", and hand back both the response and the errors
144/// drained off it.
145///
146/// [`write_with_retry`]'s story, for the cascades that cannot be one statement:
147/// the guard reads a column a rival writes, so the two contend on one record by
148/// design, and a lost round aborts the transaction having written *nothing* —
149/// which is what makes re-sending the whole of the recovery.
150///
151/// Both halves come back because the caller needs both and `take_errors`
152/// consumes: the response carries the result slots, and only the error map can
153/// tell a deliberate `THROW` from a lost round. `refusals` are the caller's
154/// `THROW` markers and they are matched *first* — a `THROW` is a decision, and
155/// it outranks a conflict. Everything after that ordering is why this exists:
156/// an aborted transaction errors *every* slot, and all but the failing one say
157/// a generic "not executed", which is the consequence of the abort and never a
158/// reason of its own. Picking one of those out of the unordered `HashMap` — or
159/// taking the first via `check()` — retired a retryable round as a 500, measured
160/// on `Course::delete` at 1-3 of 20 raced rounds.
161///
162/// [`write_with_retry`]'s restriction carries over, and a cascade makes it
163/// easier to trip: no statement inside may be able to answer "already exists",
164/// because that is the other thing [`lost_the_race`] matches and re-sending it
165/// would just fail the same way until the tries run out — turning a 409 into a
166/// 500, which is the exact defect this exists to prevent. The test to apply to
167/// every statement in the batch is not which verb it uses but whether the store
168/// could *legitimately* answer "already exists" to it — that answer is a
169/// decision, and this loop cannot tell one from a conflict, so it would burn all
170/// the tries re-asking a question already settled. `UPDATE` and `DELETE` never
171/// can. A `CREATE` can, unless the id is unreachable by any rival: a freshly
172/// generated ULID on a table with no `UNIQUE` index is such an id. An `UPSERT`
173/// can, unless its id is *bijective* with every unique tuple its table indexes —
174/// then the index entry can only ever point at the row the id already names, and
175/// the write resolves onto it instead of colliding with it
176/// ([`crate::domain::exam_result::ExamResult`]'s composite id is that shape).
177/// A statement that fails this test belongs in front of the cascade, where its
178/// 409 can be read as the answer it is.
179pub(crate) async fn transaction_with_retry(
180 db: &Database,
181 sql: &str,
182 bindings: &[(String, surrealdb::types::Value)],
183 refusals: &[&str],
184) -> Result<
185 (
186 surrealdb::IndexedResults,
187 std::collections::HashMap<usize, surrealdb::Error>,
188 ),
189 AppError,
190> {
191 let mut last = None;
192 for attempt in 0..CAP_WRITE_TRIES {
193 backoff(attempt).await;
194 let mut query = db.query(sql);
195 for (name, value) in bindings {
196 query = query.bind((name.clone(), value.clone()));
197 }
198 let mut result = match query.await {
199 Ok(result) => result,
200 Err(err) if lost_the_race(&err) => {
201 last = Some(err);
202 continue;
203 }
204 Err(err) => return Err(err.into()),
205 };
206 let mut errors = result.take_errors();
207 let refused = |error: &surrealdb::Error| {
208 let message = error.to_string();
209 refusals.iter().any(|marker| message.contains(marker))
210 };
211 if errors.values().any(refused) || !errors.values().any(lost_the_race) {
212 return Ok((result, errors));
213 }
214 last = errors.drain().map(|(_, error)| error).find(lost_the_race);
215 }
216 Err(last
217 .map(AppError::from)
218 .unwrap_or_else(|| AppError::Internal("a guarded cascade never ran".into())))
219}
220
221/// Wait out one lost round. Exponential with jitter, because racers arrive in
222/// lockstep (one HTTP burst) and a fixed delay would just re-synchronize them.
223/// Attempt zero waits not at all.
224pub(crate) async fn backoff(attempt: usize) {
225 if attempt == 0 {
226 return;
227 }
228 let step = CAP_WRITE_BACKOFF_MS << (attempt - 1);
229 let jitter = Timestamp::now().as_millis().unsigned_abs() % step.max(1);
230 tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await;
231}
232
233/// Dial the database, retrying until it answers.
234///
235/// Never gives up, because giving up is worse than waiting: the database is
236/// normally a sibling container booting in parallel, and a process that exits
237/// on the first refusal gets restarted by the runtime, fails again in ~100ms,
238/// and burns its whole restart budget inside a second — leaving the backend
239/// permanently down over a startup skew that would have cleared on its own.
240///
241/// Only the dial is retried. Bad credentials or a broken migration still fail
242/// hard, since no amount of waiting fixes those.
243async fn connect_with_retry(cfg: &Config) -> Surreal<Any> {
244 let mut backoff = 1;
245 loop {
246 match surrealdb::engine::any::connect(cfg.db_url.clone()).await {
247 Ok(db) => return db,
248 Err(err) => {
249 tracing::warn!(
250 "database at {} unreachable ({err}) — retrying in {backoff}s",
251 cfg.db_url
252 );
253 tokio::time::sleep(std::time::Duration::from_secs(backoff)).await;
254 backoff = (backoff * 2).min(crate::constant::DB_CONNECT_BACKOFF_MAX_SECS);
255 }
256 }
257 }
258}
259
260/// A fresh in-memory **school** database with the school schema applied. For
261/// the unit tests whose subject is one school's own rows; a test that needs the
262/// whole app (control database included) wants [`init_mem_tenants`].
263pub async fn init_mem() -> Result<Database, AppError> {
264 let db = surrealdb::engine::any::connect("memory").await?;
265 db.use_ns("hezarfen").use_db("hezarfen").await?;
266 migrate(&db).await?;
267 Ok(std::sync::Arc::new(db))
268}
269
270/// A fresh in-memory deployment: an empty control database plus one school,
271/// [`crate::tenant::DEMO_SLUG`]. The bootstrap every router-level test uses.
272pub async fn init_mem_tenants() -> Result<Tenants, AppError> {
273 let tenants = Tenants::new_mem().await?;
274 let demo = crate::tenant::Slug::try_new(crate::tenant::DEMO_SLUG)
275 .map_err(|err| AppError::Internal(format!("the demo slug is a slug: {err}")))?;
276 tenants
277 .create(&demo, "Demo School", crate::module::ModuleSet::all())
278 .await?;
279 Ok(tenants)
280}
281
282/// A handle on a **real** SurrealDB server, in a scratch namespace of its own
283/// that is dropped and re-made on every call. For the tests whose subject is
284/// the store's own conflict detection, which [`init_mem`]'s embedded engine
285/// does not have: it drops one of two concurrent writes to a record and answers
286/// `Ok` to both (see [`crate::db::cap`]), which *forges* the very
287/// integrity failure those tests exist to catch — measured 2026-07-30 at 2
288/// failed runs in 36 on `memory`, against 0 in 10 000 rounds here.
289///
290/// Every caller is `#[ignore]`d, so a machine with no server prints them as
291/// `ignored` rather than passing: this is not a test that may quietly skip.
292/// `HEZARFEN_TEST_DB` overrides the address; the credentials are `compose.yaml`'s.
293///
294/// The guard handed back with the handle serializes these tests against each
295/// other and must be held for the whole test — hence the tuple, which cannot be
296/// forgotten the way a separate `lock()` line can. `cargo test -- --ignored`
297/// runs them in parallel, and while each has a namespace to itself they all
298/// burst against the *one* server: their beats are sub-millisecond, so a
299/// sibling's burst pushes a delete clean out of the window it is meant to land
300/// in (measured 4 runs in 4 at 3 of 6 failing their own "the race was reached"
301/// guard). Serialized, the plain documented command works.
302#[cfg(test)]
303mod builder_seed_tests {
304 use super::builder_credentials;
305 use crate::config::Config;
306
307 fn cfg(username: Option<&str>, password: Option<&str>) -> Config {
308 let mut cfg = Config::from_env();
309 cfg.builder_username = username.map(str::to_string);
310 cfg.builder_password = password.map(str::to_string);
311 cfg
312 }
313
314 #[tokio::test]
315 async fn the_builder_seed_is_both_or_neither() {
316 assert!(builder_credentials(&cfg(None, None)).unwrap().is_none());
317 assert!(
318 builder_credentials(&cfg(Some("builder"), Some("secret1")))
319 .unwrap()
320 .is_some()
321 );
322 // Half a pair aborts startup: a deployment with no builder has nobody
323 // who can create the first school, and a silent run would hide that.
324 assert!(builder_credentials(&cfg(Some("builder"), None)).is_err());
325 assert!(builder_credentials(&cfg(None, Some("secret1"))).is_err());
326 // A pair that is set but invalid aborts too, naming the variable.
327 match builder_credentials(&cfg(Some("!"), Some("secret1"))) {
328 Err(err) => assert!(err.to_string().contains("BUILDER_USERNAME"), "{err}"),
329 Ok(_) => panic!("an invalid BUILDER_USERNAME must abort startup"),
330 }
331 }
332}
333
334#[cfg(test)]
335pub(crate) static RACE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
336
337#[cfg(test)]
338pub(crate) async fn init_test_server(
339 scratch: &str,
340) -> (Database, tokio::sync::MutexGuard<'static, ()>) {
341 let serialized = RACE_LOCK.lock().await;
342 let url =
343 std::env::var("HEZARFEN_TEST_DB").unwrap_or_else(|_| "ws://127.0.0.1:8000".to_string());
344 let db = surrealdb::engine::any::connect(url.clone())
345 .await
346 .unwrap_or_else(|err| panic!("no SurrealDB server at {url} ({err})"));
347 db.signin(Root {
348 username: "root".into(),
349 password: "root".into(),
350 })
351 .await
352 .expect("sign in to the test server");
353 let ns = format!("test_{scratch}");
354 db.query(format!("REMOVE NAMESPACE IF EXISTS {ns}"))
355 .await
356 .expect("clear the scratch namespace")
357 .check()
358 .expect("clear the scratch namespace");
359 db.use_ns(ns.clone()).use_db(ns).await.expect("scratch ns");
360 let db = std::sync::Arc::new(db);
361 migrate(&db).await.expect("migrate the scratch namespace");
362 (db, serialized)
363}
364
365/// Apply the schema + backfills. Idempotent — `init` runs it on every boot,
366/// and tests re-run it on a live handle to simulate a second boot.
367pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> {
368 for sql in MIGRATION_BATCHES {
369 let mut query = db.query(sql);
370 for (name, value) in migration_binds() {
371 query = query.bind((name, value));
372 }
373 query.await?.check()?;
374 }
375 Ok(())
376}
377
378/// Apply the **control** schema (schools, builders, the shared rate-limit
379/// window). Idempotent, like [`migrate`].
380pub async fn migrate_control(db: &Surreal<Any>) -> Result<(), AppError> {
381 // The one data-driven parameter in this batch: the module list a school
382 // written before entitlements existed is backfilled to.
383 let all_modules = crate::module::ModuleSet::all().names();
384 for sql in CONTROL_MIGRATION_BATCHES {
385 db.query(sql)
386 .bind(("all_modules", all_modules.clone()))
387 .await?
388 .check()?;
389 }
390 Ok(())
391}
392
393/// Parameters the batches are executed with. Bound, not baked into the SQL
394/// string: a `const` cannot be interpolated into another `const`, and a
395/// hand-copied 300000 would drift silently. The one-time blocks' fingerprints
396/// ride along — see [`marked_blocks`]. Bound to all three batches, which is
397/// free: an unused parameter is not an error.
398fn migration_binds() -> Vec<(String, i64)> {
399 let mut binds = vec![("stale_ms".to_string(), CHATBOT_PENDING_STALE_SECS * 1_000)];
400 binds.extend(marked_blocks());
401 binds
402}
403
404/// The line every one-time block in [`BACKFILL`] opens with. The name straight
405/// after it is the block's `migration_mark` key, and `fp_<name>` is the
406/// parameter its fingerprint is bound to — so a block written in this idiom is
407/// found, hashed and bound with nothing to keep by hand. A block written any
408/// other way silently gets no fingerprint, which is what
409/// `every_one_time_block_is_fingerprinted` exists to catch.
410const MARK_GATE: &str = "IF array::len((SELECT VALUE id FROM migration_mark:";
411
412/// Every one-time block in [`BACKFILL`], as (`fp_<name>`, hash of its own SQL).
413///
414/// A `migration_mark` used to say only *that* a block had run, which made a
415/// marked block's content permanently uncorrectable: an edit to it never ran on
416/// any volume that had booted once. The mark now stores this number and the
417/// gate compares it against the number this binary computes, so an edited block
418/// runs one more time and re-stamps. There is nothing to remember to bump — the
419/// hash comes from the very string the server executes, which is the whole
420/// point: a hand-kept version is the same discipline failure in a new place.
421///
422/// Hashed from the gate through the stamp with comments and indentation
423/// dropped: every re-run costs something (the `profile_counters` block says
424/// what, in its own comment), so re-wording a comment must not trigger one.
425fn marked_blocks() -> Vec<(String, i64)> {
426 let mut blocks = Vec::new();
427 let mut rest = BACKFILL;
428 while let Some(at) = rest.find(MARK_GATE) {
429 let block = &rest[at..];
430 let name: String = block[MARK_GATE.len()..]
431 .chars()
432 .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
433 .collect();
434 let stamp = format!("UPSERT migration_mark:{name}");
435 let end = block
436 .find(&stamp)
437 .and_then(|from| block[from..].find(';').map(|to| from + to + 1))
438 .unwrap_or_else(|| panic!("the `{name}` block never stamps its own mark"));
439 blocks.push((format!("fp_{name}"), block_fingerprint(&block[..end])));
440 rest = &block[end..];
441 }
442 blocks
443}
444
445/// FNV-1a over a block's statements, comments and layout dropped.
446///
447/// Hand-rolled rather than [`std::hash`]: this number is *stored*, so it has to
448/// mean the same thing after a compiler upgrade, and `DefaultHasher` promises
449/// nothing across versions — a hash that drifted on its own would re-run every
450/// one-time block on every volume.
451fn block_fingerprint(block: &str) -> i64 {
452 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
453 for line in block
454 .lines()
455 .map(str::trim)
456 .filter(|line| !line.is_empty() && !line.starts_with("--"))
457 {
458 for byte in line.bytes().chain(std::iter::once(b'\n')) {
459 hash = (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3);
460 }
461 }
462 hash as i64
463}
464
465#[cfg(test)]
466mod tests {
467
468 /// The fingerprint has to move when a *statement* moves and stay put when
469 /// prose does: a re-run is never free (see the `profile_counters` comment),
470 /// and a fingerprint that ignored an edit would put us back where this
471 /// mechanism started — a marked block nobody can correct.
472 #[test]
473 fn a_block_fingerprint_tracks_statements_not_prose() {
474 let block = "IF x = 0 {\n -- why this runs\n UPDATE t SET a = 1;\n};";
475 let reworded = "IF x = 0 {\n -- why this runs, at length\n UPDATE t SET a = 1;\n};";
476 let edited = "IF x = 0 {\n -- why this runs\n UPDATE t SET a = 2;\n};";
477 assert_eq!(
478 super::block_fingerprint(block),
479 super::block_fingerprint(reworded),
480 "a re-worded comment or a re-indent must not re-run a one-time block"
481 );
482 assert_ne!(
483 super::block_fingerprint(block),
484 super::block_fingerprint(edited),
485 "an edited statement must re-run its block"
486 );
487 }
488
489 /// The forcing function: a one-time block written outside the gate idiom
490 /// gets no fingerprint parameter, and its `$fp_…` would bind to nothing — a
491 /// gate that then matches every mark and skips forever. Nothing about the
492 /// compiler notices, so this does.
493 #[test]
494 fn every_one_time_block_is_fingerprinted() {
495 let blocks = super::marked_blocks();
496 let names: Vec<&str> = blocks.iter().map(|(name, _)| name.as_str()).collect();
497 assert_eq!(
498 names,
499 ["fp_board_roster", "fp_profile_counters"],
500 "{names:?}"
501 );
502 assert_ne!(blocks[0].1, blocks[1].1, "two blocks, two fingerprints");
503 // Two mentions of the mark table per block — its gate and its stamp. A
504 // third, or a block gated some other way, means a block the binder
505 // never saw.
506 assert_eq!(
507 super::BACKFILL.matches("migration_mark:").count(),
508 blocks.len() * 2,
509 "a one-time block outside the `{}…` idiom is invisible to the binder",
510 super::MARK_GATE
511 );
512 for (param, _) in &blocks {
513 assert!(
514 super::BACKFILL.contains(&format!("${param}")),
515 "nothing reads ${param}"
516 );
517 }
518 }
519
520 /// The fingerprint the mark for `name` must carry once its block has run.
521 fn expected_fingerprint(name: &str) -> i64 {
522 super::marked_blocks()
523 .into_iter()
524 .find(|(param, _)| *param == format!("fp_{name}"))
525 .unwrap_or_else(|| panic!("no one-time block named {name}"))
526 .1
527 }
528
529 async fn stamped_fingerprint(db: &super::Database, name: &str) -> Vec<Option<i64>> {
530 let mut rows = db
531 .query(format!(
532 "SELECT VALUE fingerprint FROM migration_mark:{name}"
533 ))
534 .await
535 .unwrap();
536 rows.take(0).unwrap()
537 }
538
539 /// The admin seed must not be interruptible into a state no later boot can
540 /// repair. `create` + `set_role` was: killed between the two writes it
541 /// leaves a *student* row holding ADMIN_USERNAME, which `ensure_admin` then
542 /// refuses to promote on every subsequent boot (rightly — it cannot tell
543 /// that row from a stranger who registered the name first). The row is
544 /// therefore minted with its role in one statement, and this pins that.
545 #[test]
546 fn the_admin_seed_mints_the_role_with_the_row() {
547 let source =
548 std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/domain/user.rs"))
549 .expect("read user.rs");
550 let start = source
551 .find("pub async fn ensure_admin")
552 .expect("ensure_admin is declared");
553 let body = &source[start..start + source[start..].find("\n }\n").expect("body ends")];
554 assert!(
555 !body.contains("set_role"),
556 "ensure_admin promotes after creating; an interruption between those two writes \
557 leaves a student account on ADMIN_USERNAME that no boot can heal:\n{body}"
558 );
559 assert!(
560 body.contains("create_with_role"),
561 "the seed must mint the row with Role::Admin in one statement"
562 );
563 }
564
565 #[tokio::test]
566 async fn boot_fails_chatbot_messages_left_pending() {
567 let db = super::init_mem().await.unwrap();
568 db.query(
569 "CREATE user:u SET username = 'u', password_hash = 'x';
570 CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1;
571 CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u,
572 role = 'assistant', content = '', status = 'pending', created_at = 1;
573 CREATE chatbot_message:done SET thread_id = chatbot_thread:c, user_id = user:u,
574 role = 'assistant', content = 'hi', status = 'complete', created_at = 1;",
575 )
576 .await
577 .unwrap()
578 .check()
579 .unwrap();
580
581 // A second boot: the task that would have answered `m` died with the
582 // previous process, so the row is failed rather than left waiting.
583 super::migrate(&db).await.unwrap();
584
585 let mut rows = db
586 .query("SELECT id, status, error_code, completed_at FROM chatbot_message ORDER BY id")
587 .await
588 .unwrap();
589 let rows: Vec<serde_json::Value> = rows.take(0).unwrap();
590 // An already-answered turn is untouched; the pending one is failed.
591 let done = &rows[0];
592 let interrupted = &rows[1];
593 assert_eq!(done["status"], "complete");
594 assert_eq!(done["error_code"], serde_json::Value::Null);
595 assert_eq!(interrupted["status"], "failed");
596 assert_eq!(interrupted["error_code"], "interrupted");
597 assert!(interrupted["completed_at"].as_i64().unwrap() > 0);
598 }
599
600 /// Stale-data path for the 2026-07-30 fee-plan refcount. A dev volume
601 /// carries plans and assignments written before the counter column existed,
602 /// and an absent counter reads as **zero** — which is exactly the value
603 /// that licenses an edit and a delete. Unseeded, every already-assigned
604 /// plan on every existing volume would go editable and deletable again, so
605 /// the backfill is the whole of the stale-data story, not a nicety.
606 #[tokio::test]
607 async fn a_plan_assigned_before_the_counter_existed_is_still_refused() {
608 use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName};
609 use crate::error::AppError;
610
611 let db = super::init_mem().await.unwrap();
612 // The old shape: rows stating every column the older binary knew, and
613 // no `assignment_count` at all. `used` carries an assignment, `free`
614 // does not — a plan nobody is on must stay editable.
615 db.query(
616 "CREATE user:m SET username = 'm', password_hash = 'x';
617 CREATE user:s SET username = 's', password_hash = 'x';
618 CREATE fee_plan:used SET name = 'Yearly',
619 installments = [{ amount_minor: 100, due_at: 1 }],
620 created_by = user:m, created_at = 1;
621 CREATE fee_plan:free SET name = 'Unused',
622 installments = [{ amount_minor: 100, due_at: 1 }],
623 created_by = user:m, created_at = 1;
624 CREATE fee_plan_assignment:used_s SET plan = fee_plan:used,
625 student = user:s, assigned_by = user:m, created_at = 1;",
626 )
627 .await
628 .unwrap()
629 .check()
630 .unwrap();
631
632 // Twice: every boot runs the backfill, and a second pass must not
633 // double a counter it already seeded.
634 super::migrate(&db).await.unwrap();
635 super::migrate(&db).await.unwrap();
636
637 let mut counts = db
638 .query("SELECT VALUE assignment_count FROM fee_plan ORDER BY id")
639 .await
640 .unwrap();
641 let counts: Vec<Option<i64>> = counts.take(0).unwrap();
642 // `free` before `used` by id; the unused plan is deliberately left
643 // absent, which already reads as zero in the guard.
644 assert_eq!(counts, vec![None, Some(1)]);
645
646 // The load-bearing half: the seeded plan is frozen, and the untouched
647 // one is not.
648 let used = FeePlan::read(&FeePlanId::from_key("used"), &db)
649 .await
650 .unwrap()
651 .unwrap();
652 assert!(matches!(
653 used.clone()
654 .update(Some(FeePlanName::try_new("Edited").unwrap()), None, &db)
655 .await,
656 Err(AppError::Conflict(_))
657 ));
658 assert!(!used.delete(&db).await.unwrap());
659 let free = FeePlan::read(&FeePlanId::from_key("free"), &db)
660 .await
661 .unwrap()
662 .unwrap();
663 assert!(
664 free.clone()
665 .update(Some(FeePlanName::try_new("Edited").unwrap()), None, &db)
666 .await
667 .is_ok()
668 );
669 assert!(free.delete(&db).await.unwrap());
670 }
671
672 /// Stale-data path for the 2026-08-02 board-roster repair. `set_role`
673 /// sweeps a demoted user off every board going forward, but an existing
674 /// volume still names parents on rosters — and ids of users deleted before
675 /// any sweep existed. Both freeze the creator's roster `PATCH` at a 400
676 /// (see `web::boards::resolve_participants`), so boot has to clean them.
677 #[tokio::test]
678 async fn a_board_roster_written_before_the_sweep_is_repaired_at_boot() {
679 let db = super::init_mem().await.unwrap();
680 db.query(
681 "CREATE user:s SET username = 's', password_hash = 'x', role = 'student';
682 CREATE user:p SET username = 'p', password_hash = 'x', role = 'parent';
683 CREATE board:keep SET creator = user:s, title = 'B',
684 participants = [user:s, user:p, user:ghost], created_at = 1;
685 CREATE board:gone SET creator = user:s, title = 'C',
686 participants = [user:p], created_at = 1;
687 CREATE board:clean SET creator = user:s, title = 'D',
688 participants = [user:s], created_at = 1;
689 DELETE migration_mark:board_roster;",
690 )
691 .await
692 .unwrap()
693 .check()
694 .unwrap();
695 // `init_mem` boots a *migrated* database, so it has already marked the
696 // repair done on an empty store — which is right, and is exactly why the
697 // mark is dropped here: a volume written before the mark existed carries
698 // stale rosters and no mark at all, and that is the state under test.
699 // A write probe on the table under repair: the event fires *inside* the
700 // UPDATE, so it counts real writes rather than trusting a re-read.
701 db.query(
702 "DEFINE TABLE board_write_probe SCHEMALESS;
703 DEFINE EVENT board_write ON board WHEN $event = 'UPDATE' THEN {
704 UPSERT type::record('board_write_probe', 'n') SET n = (n ?? 0) + 1;
705 };",
706 )
707 .await
708 .unwrap()
709 .check()
710 .unwrap();
711
712 super::migrate(&db).await.unwrap();
713
714 async fn rosters(db: &super::Database) -> Vec<Vec<surrealdb::types::RecordId>> {
715 let mut rows = db
716 .query("SELECT VALUE participants FROM board ORDER BY id")
717 .await
718 .unwrap();
719 rows.take(0).unwrap()
720 }
721 let after_first = rosters(&db).await;
722 let s = surrealdb::types::RecordId::new("user", "s");
723 // `clean`, `gone`, `keep` by id. The parent and the vanished user are
724 // both gone; a board whose whole roster was stale ends empty, which is
725 // the same shape a board opened without invites carries.
726 assert_eq!(
727 after_first,
728 vec![vec![s.clone()], vec![], vec![s.clone()]],
729 "{after_first:?}"
730 );
731
732 async fn writes(db: &super::Database) -> Vec<i64> {
733 let mut rows = db
734 .query("SELECT VALUE n FROM board_write_probe:n")
735 .await
736 .unwrap();
737 rows.take(0).unwrap()
738 }
739 assert_eq!(
740 writes(&db).await,
741 vec![2],
742 "only the two stale rows repaired"
743 );
744
745 // The second boot: every boot runs the backfill, and a converged row
746 // must not be written again.
747 super::migrate(&db).await.unwrap();
748 assert_eq!(rosters(&db).await, after_first);
749 assert_eq!(writes(&db).await, vec![2], "the second pass wrote nothing");
750
751 // …and it did not *look*, either, which is the whole point of the mark:
752 // the repair's cost is a `user` table scan per board, and writing
753 // nothing is not the same as scanning nothing. A roster made stale after
754 // the mark landed is the probe — it survives the next boot untouched,
755 // which no converging `WHERE` could produce.
756 let mut mark = db
757 .query("SELECT VALUE done_at FROM migration_mark:board_roster")
758 .await
759 .unwrap();
760 assert_eq!(
761 mark.take::<Vec<i64>>(0).unwrap().len(),
762 1,
763 "the repair marks itself finished"
764 );
765 // …with the fingerprint of the text it ran, which is what a later edit
766 // to this block is compared against.
767 assert_eq!(
768 stamped_fingerprint(&db, "board_roster").await,
769 vec![Some(expected_fingerprint("board_roster"))]
770 );
771 db.query("CREATE board:late SET creator = user:s, title = 'E', participants = [user:p], created_at = 1")
772 .await
773 .unwrap()
774 .check()
775 .unwrap();
776 super::migrate(&db).await.unwrap();
777 assert_eq!(
778 rosters(&db).await,
779 vec![
780 vec![s.clone()],
781 vec![],
782 vec![s.clone()],
783 vec![surrealdb::types::RecordId::new("user", "p")]
784 ],
785 "a marked database skips the scan entirely"
786 );
787 assert_eq!(writes(&db).await, vec![2]);
788 }
789
790 /// Stale-data path for the 2026-08-04 badge counters. Every account on an
791 /// existing volume predates the columns, and a badge is decided off the
792 /// stored total — so a zero start would not lose a number, it would
793 /// permanently mis-award the student who really did the work. Boot seeds the
794 /// counters from the rows that exist, exactly once.
795 #[tokio::test]
796 async fn the_badge_counters_are_seeded_from_history_exactly_once() {
797 let db = super::init_mem().await.unwrap();
798 db.query(
799 "CREATE user:a SET username = 'a', password_hash = 'x', role = 'student';
800 CREATE user:b SET username = 'b', password_hash = 'x', role = 'student';
801 CREATE user:c SET username = 'c', password_hash = 'x', role = 'student';
802 CREATE homework:h SET course = course:c, subject = subject:s, title = 'H',
803 due_at = 100, created_by = user:a, created_at = 1;
804 -- Three on time (the equal case counts as on time) and one whose
805 -- homework was deleted out from under it: that last one is
806 -- submitted but not on time, because the traversal yields nothing.
807 CREATE homework_submission:s1 SET homework = homework:h, user = user:a,
808 submitted_at = 50, updated_at = 50;
809 CREATE homework_submission:s2 SET homework = homework:h, user = user:a,
810 submitted_at = 60, updated_at = 100;
811 -- Handed in before the deadline, then edited well after it — a
812 -- `touch()` from a single file add does this. On time, because the
813 -- live path credits the hand-in and debits by `submitted_at`; if
814 -- the seed judged this one by `updated_at` a later withdrawal
815 -- would decrement a credit that was never given.
816 CREATE homework_submission:s3 SET homework = homework:h, user = user:a,
817 submitted_at = 70, updated_at = 200;
818 CREATE homework_submission:s4 SET homework = homework:gone, user = user:a,
819 submitted_at = 80, updated_at = 1;
820 CREATE exam_attempt:e1 SET exam = exam:x, user = user:a, seq = 1, started_at = 1;
821 CREATE exam_attempt:e2 SET exam = exam:y, user = user:a, seq = 1, started_at = 2;
822 -- Two finished stints and one still open, which counts for neither.
823 CREATE pomodoro_session:p1 SET user = user:a, started_at = 1000, finished_at = 2000;
824 CREATE pomodoro_session:p2 SET user = user:a, started_at = 5000, finished_at = 7500;
825 CREATE pomodoro_session:p3 SET user = user:a, started_at = 9000;
826 -- One real stint beside one written with a backwards clock. The
827 -- floor is per row, like the live close, so the negative one
828 -- contributes zero and the real 1000ms survives; flooring the
829 -- per-user sum instead would seed 0 and lose the real stint.
830 CREATE pomodoro_session:p4 SET user = user:c, started_at = 0, finished_at = 1000;
831 CREATE pomodoro_session:p5 SET user = user:c, started_at = 9000, finished_at = 3000;
832 DELETE migration_mark:profile_counters;",
833 )
834 .await
835 .unwrap()
836 .check()
837 .unwrap();
838 // `init_mem` boots a *migrated* database, so the seed is already marked
839 // done on an empty store — which is right, and is exactly why the mark is
840 // dropped here: a volume written before the columns existed carries
841 // history and no mark at all, and that is the state under test.
842 // A write probe on the table being seeded: the event fires *inside* the
843 // UPDATE, so it counts real writes rather than trusting a re-read.
844 db.query(
845 "DEFINE TABLE user_write_probe SCHEMALESS;
846 DEFINE EVENT user_write ON user WHEN $event = 'UPDATE' THEN {
847 UPSERT type::record('user_write_probe', 'n') SET n = (n ?? 0) + 1;
848 };",
849 )
850 .await
851 .unwrap()
852 .check()
853 .unwrap();
854
855 super::migrate(&db).await.unwrap();
856
857 async fn counters(db: &super::Database) -> Vec<(i64, i64, i64, i64, i64)> {
858 let mut rows = db
859 .query(
860 "SELECT VALUE [homework_submitted_total, homework_on_time_total,
861 exam_sat_total, pomodoro_finished_total,
862 pomodoro_focus_ms_total]
863 FROM user ORDER BY id",
864 )
865 .await
866 .unwrap();
867 rows.take::<Vec<Vec<i64>>>(0)
868 .unwrap()
869 .into_iter()
870 .map(|row| (row[0], row[1], row[2], row[3], row[4]))
871 .collect()
872 }
873 let after_first = counters(&db).await;
874 // `a`, `b`, `c` by id. `b` has no history at all and reads as a fresh
875 // account; `c` keeps the 1000ms real stint the -6000ms one sits beside.
876 assert_eq!(
877 after_first,
878 vec![(4, 3, 2, 2, 3500), (0, 0, 0, 0, 0), (0, 0, 0, 2, 1000)],
879 "{after_first:?}"
880 );
881
882 // The seed also stamps each submission with the verdict it was counted
883 // under, because `due_at` is mutable: a withdrawal after the teacher
884 // moves the deadline must debit what was credited, not what the
885 // deadline says by then. Asserted through `WHERE` rather than read back
886 // as a column, so an unstamped row would show up as belonging to
887 // neither set instead of deserializing as some default.
888 async fn stamped(db: &super::Database, cond: &str) -> Vec<String> {
889 let mut rows = db
890 .query(format!(
891 "SELECT VALUE record::id(id) FROM homework_submission
892 WHERE {cond} ORDER BY id"
893 ))
894 .await
895 .unwrap();
896 rows.take(0).unwrap()
897 }
898 // s1/s2/s3 beat the deadline (50, 60, 70 vs 100). s4 hangs off a
899 // deleted homework, so `submitted_at <= homework.due_at` compares
900 // against NONE and lands on `false` — which is exactly what the count
901 // above credited it as, so the stamp agrees with the counter rather
902 // than leaving the row to a fallback that could later disagree.
903 assert_eq!(
904 stamped(&db, "counted_on_time = true").await,
905 ["s1", "s2", "s3"]
906 );
907 assert_eq!(stamped(&db, "counted_on_time = false").await, ["s4"]);
908
909 async fn writes(db: &super::Database) -> Vec<i64> {
910 let mut rows = db
911 .query("SELECT VALUE n FROM user_write_probe:n")
912 .await
913 .unwrap();
914 rows.take(0).unwrap()
915 }
916 let first_writes = writes(&db).await;
917 // Pinned non-zero, not just compared: "the second pass wrote nothing"
918 // would hold vacuously if the probe itself stopped firing, and then the
919 // test would pass on a seed that never ran.
920 assert!(
921 matches!(first_writes.as_slice(), [n] if *n > 0),
922 "{first_writes:?}"
923 );
924
925 // The second boot: every boot runs the backfill, and a recount here
926 // would not converge the way the counters above it do — these columns
927 // are maintained by the request path from now on, so a second pass would
928 // overwrite everything earned since. It must not write at all…
929 super::migrate(&db).await.unwrap();
930 assert_eq!(counters(&db).await, after_first);
931 assert_eq!(
932 writes(&db).await,
933 first_writes,
934 "the second pass wrote nothing"
935 );
936
937 // …and it must not *look*, either, which is the whole point of the mark:
938 // writing nothing is not the same as scanning nothing. A submission that
939 // lands after the mark is the probe — its counter stays where the request
940 // path left it, which no recomputing backfill could produce.
941 let mut mark = db
942 .query("SELECT VALUE done_at FROM migration_mark:profile_counters")
943 .await
944 .unwrap();
945 assert_eq!(
946 mark.take::<Vec<i64>>(0).unwrap().len(),
947 1,
948 "the seed marks itself finished"
949 );
950 assert_eq!(
951 stamped_fingerprint(&db, "profile_counters").await,
952 vec![Some(expected_fingerprint("profile_counters"))]
953 );
954 db.query(
955 "CREATE homework_submission:late SET homework = homework:h, user = user:b,
956 submitted_at = 90, updated_at = 90;",
957 )
958 .await
959 .unwrap()
960 .check()
961 .unwrap();
962 super::migrate(&db).await.unwrap();
963 assert_eq!(
964 counters(&db).await,
965 after_first,
966 "a mark carrying this binary's fingerprint skips the seed entirely"
967 );
968 assert_eq!(writes(&db).await, first_writes);
969 }
970
971 /// A marked block's *content* has to be correctable (2026-08-05). The mark
972 /// used to record only that the block had run, so an edit to a marked block
973 /// silently never ran on any volume that had booted once — which is how the
974 /// `exam_sat_total` seed below (fixed to count sittings, not attempts)
975 /// would have reached exactly nobody. The mark carries the fingerprint of
976 /// the text it ran, and a different fingerprint runs the block once more.
977 #[tokio::test]
978 async fn an_edited_one_time_block_runs_once_more_and_restamps() {
979 let db = super::init_mem().await.unwrap();
980 // `init_mem` migrates an empty store, so the seed is already marked
981 // done — the state every booted volume is in. History written *after*
982 // that mark is the probe: a skip has to leave it uncounted, and a
983 // re-run has to pick it up.
984 db.query(
985 "CREATE user:a SET username = 'a', password_hash = 'x', role = 'student';
986 -- One sitting, taken twice. The corrected seed counts the exam,
987 -- not the attempts, exactly as the request path credits it.
988 CREATE exam_attempt:e1 SET exam = exam:x, user = user:a, seq = 1, started_at = 1;
989 CREATE exam_attempt:e2 SET exam = exam:x, user = user:a, seq = 2, started_at = 2;
990 CREATE pomodoro_session:p1 SET user = user:a, started_at = 1000, finished_at = 2000;",
991 )
992 .await
993 .unwrap()
994 .check()
995 .unwrap();
996
997 async fn counters(db: &super::Database) -> Vec<(i64, i64)> {
998 let mut rows = db
999 .query(
1000 // `?? 0`, parenthesized: the columns are `option<int>` and
1001 // a row the seed has not touched holds neither.
1002 "SELECT VALUE [(exam_sat_total ?? 0), (pomodoro_finished_total ?? 0)]
1003 FROM user ORDER BY id",
1004 )
1005 .await
1006 .unwrap();
1007 rows.take::<Vec<Vec<i64>>>(0)
1008 .unwrap()
1009 .into_iter()
1010 .map(|row| (row[0], row[1]))
1011 .collect()
1012 }
1013 let fp = expected_fingerprint("profile_counters");
1014
1015 // Same binary, same fingerprint: the block does not run, and the
1016 // history above stays uncounted. That is the mark still doing its job.
1017 super::migrate(&db).await.unwrap();
1018 assert_eq!(counters(&db).await, vec![(0, 0)]);
1019 assert_eq!(
1020 stamped_fingerprint(&db, "profile_counters").await,
1021 vec![Some(fp)]
1022 );
1023
1024 // A write probe on the seeded table, defined now so it counts only the
1025 // runs under test: the event fires *inside* the UPDATE, so "exactly
1026 // once" is measured rather than inferred from the numbers.
1027 db.query(
1028 "DEFINE TABLE user_write_probe SCHEMALESS;
1029 DEFINE EVENT user_write ON user WHEN $event = 'UPDATE' THEN {
1030 UPSERT type::record('user_write_probe', 'n') SET n = (n ?? 0) + 1;
1031 };
1032 -- A mark written by the binary before fingerprints existed: the
1033 -- row is there, the column is not. This is the live volumes'
1034 -- state, and it must run the corrected block exactly once.
1035 UPDATE migration_mark:profile_counters UNSET fingerprint;",
1036 )
1037 .await
1038 .unwrap()
1039 .check()
1040 .unwrap();
1041 assert_eq!(
1042 stamped_fingerprint(&db, "profile_counters").await,
1043 vec![None]
1044 );
1045
1046 super::migrate(&db).await.unwrap();
1047 // Two attempt rows, one exam: the corrected seed says one sitting, the
1048 // number the request path would have given. The old text said two.
1049 assert_eq!(counters(&db).await, vec![(1, 1)]);
1050 assert_eq!(
1051 stamped_fingerprint(&db, "profile_counters").await,
1052 vec![Some(fp)]
1053 );
1054
1055 async fn writes(db: &super::Database) -> Vec<i64> {
1056 let mut rows = db
1057 .query("SELECT VALUE n FROM user_write_probe:n")
1058 .await
1059 .unwrap();
1060 rows.take(0).unwrap()
1061 }
1062 let one_run = writes(&db).await;
1063 // Pinned non-zero, not merely compared: "it did not run twice" holds
1064 // vacuously if the probe stopped firing, and the test would then pass
1065 // on a mechanism that never runs anything at all.
1066 assert!(matches!(one_run.as_slice(), [n] if *n > 0), "{one_run:?}");
1067
1068 // Once more, not on every boot: the re-run re-stamped, so the next boot
1069 // is a plain skip again.
1070 super::migrate(&db).await.unwrap();
1071 assert_eq!(counters(&db).await, vec![(1, 1)]);
1072 assert_eq!(writes(&db).await, one_run, "the re-run happened once");
1073
1074 // And now the edit this whole mechanism exists for: a mark whose stored
1075 // fingerprint is some *other* text's. The block runs again and lands on
1076 // the same numbers — every SET is absolute, so a re-run converges
1077 // instead of doubling what the first pass wrote.
1078 db.query("UPDATE migration_mark:profile_counters SET fingerprint = 1")
1079 .await
1080 .unwrap()
1081 .check()
1082 .unwrap();
1083 super::migrate(&db).await.unwrap();
1084 assert_eq!(
1085 counters(&db).await,
1086 vec![(1, 1)],
1087 "a re-run recomputes, it does not add to what is there"
1088 );
1089 assert_eq!(
1090 writes(&db).await,
1091 vec![one_run[0] * 2],
1092 "the edited block did the same work a second time, and no more"
1093 );
1094 assert_eq!(
1095 stamped_fingerprint(&db, "profile_counters").await,
1096 vec![Some(fp)]
1097 );
1098 super::migrate(&db).await.unwrap();
1099 assert_eq!(writes(&db).await, vec![one_run[0] * 2], "and stopped again");
1100 }
1101
1102 #[tokio::test]
1103 async fn the_retired_claim_columns_are_dropped_off_a_live_row() {
1104 // Stale-data path for the 2026-07-30 removal of the chat claim queue.
1105 // A dev volume carries `chatbot_message` rows *with* claim values and an
1106 // `ai_worker` table, so the boot has to clear the values while their
1107 // definitions still stand (PRE_REPAIR) and only then retire the columns
1108 // — SCHEMAFULL rejects every write to a row storing a column that no
1109 // longer exists, which would make the row unanswerable forever.
1110 let db = super::init_mem().await.unwrap();
1111 db.query(
1112 "DEFINE FIELD claimed_by ON chatbot_message TYPE option<string>;
1113 DEFINE FIELD claimed_at ON chatbot_message TYPE option<int>;
1114 DEFINE TABLE ai_worker SCHEMAFULL;
1115 DEFINE FIELD seen_at ON ai_worker TYPE int;
1116 DEFINE TABLE migration_lock SCHEMALESS;",
1117 )
1118 .await
1119 .unwrap()
1120 .check()
1121 .unwrap();
1122 db.query(
1123 "CREATE user:u SET username = 'u', password_hash = 'x';
1124 CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1;
1125 CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u,
1126 role = 'assistant', content = '', status = 'pending',
1127 created_at = time::unix(time::now()) * 1000,
1128 claimed_by = 'a-dead-replica', claimed_at = 1;
1129 CREATE ai_worker:w SET seen_at = 1;
1130 CREATE migration_lock:the_lock SET holder = 'a-dead-replica', expires_at = 1;",
1131 )
1132 .await
1133 .unwrap()
1134 .check()
1135 .unwrap();
1136
1137 // Twice: the repair and both removals have to be idempotent, since
1138 // every boot runs them.
1139 super::migrate(&db).await.unwrap();
1140 super::migrate(&db).await.unwrap();
1141
1142 let mut info = db.query("INFO FOR TABLE chatbot_message").await.unwrap();
1143 let table: serde_json::Value = info.take::<Option<serde_json::Value>>(0).unwrap().unwrap();
1144 let fields = table["fields"].as_object().expect("fields");
1145 assert!(!fields.contains_key("claimed_by"), "{table}");
1146 assert!(!fields.contains_key("claimed_at"), "{table}");
1147 let mut tables = db.query("INFO FOR DB").await.unwrap();
1148 let dbinfo: serde_json::Value = tables
1149 .take::<Option<serde_json::Value>>(0)
1150 .unwrap()
1151 .unwrap();
1152 let tables = dbinfo["tables"].as_object().expect("tables");
1153 assert!(!tables.contains_key("ai_worker"), "{dbinfo}");
1154 // Same story one table over: the elected-boot lease, stale leader row
1155 // and all.
1156 assert!(!tables.contains_key("migration_lock"), "{dbinfo}");
1157
1158 // The load-bearing half: the row that carried a claim is still
1159 // writable. A leftover value under no definition fails here.
1160 db.query("UPDATE chatbot_message:m SET status = 'complete', content = 'ok'")
1161 .await
1162 .unwrap()
1163 .check()
1164 .unwrap();
1165 let mut row = db
1166 .query("SELECT * FROM ONLY chatbot_message:m")
1167 .await
1168 .unwrap();
1169 let row: serde_json::Value = row.take::<Option<serde_json::Value>>(0).unwrap().unwrap();
1170 assert_eq!(row["status"], "complete", "{row}");
1171 assert!(row.get("claimed_by").is_none(), "{row}");
1172 }
1173
1174 /// The other half of the sweep: a restart seconds after a dispatch must not
1175 /// kill the turn — the answering task may still be alive on the other side
1176 /// of the bridge, and the row is not yet past the stale horizon.
1177 #[tokio::test]
1178 async fn boot_spares_a_chatbot_message_pending_since_just_now() {
1179 let db = super::init_mem().await.unwrap();
1180 db.query(
1181 "CREATE user:u SET username = 'u', password_hash = 'x';
1182 CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1;
1183 CREATE chatbot_message:fresh SET thread_id = chatbot_thread:c, user_id = user:u,
1184 role = 'assistant', content = '', status = 'pending',
1185 created_at = time::unix(time::now()) * 1000 - 2000;
1186 CREATE chatbot_message:old SET thread_id = chatbot_thread:c, user_id = user:u,
1187 role = 'assistant', content = '', status = 'pending',
1188 created_at = time::unix(time::now()) * 1000
1189 - ($stale + 1) * 1000;",
1190 )
1191 .bind(("stale", crate::constant::CHATBOT_PENDING_STALE_SECS))
1192 .await
1193 .unwrap()
1194 .check()
1195 .unwrap();
1196
1197 super::migrate(&db).await.unwrap();
1198
1199 let mut res = db
1200 .query(
1201 "SELECT status, error_code FROM ONLY chatbot_message:fresh;
1202 SELECT VALUE status FROM ONLY chatbot_message:old;",
1203 )
1204 .await
1205 .unwrap();
1206 let fresh: Option<serde_json::Value> = res.take(0).unwrap();
1207 let fresh = fresh.unwrap();
1208 let old: Option<String> = res.take(1).unwrap();
1209 assert_eq!(
1210 fresh["status"], "pending",
1211 "a two-second-old turn is still being answered"
1212 );
1213 assert_eq!(fresh["error_code"], serde_json::Value::Null);
1214 assert_eq!(old.as_deref(), Some("failed"), "past the horizon it goes");
1215 }
1216
1217 /// A row written before choices had ids survives the retyped columns: it is
1218 /// converted, it is writable again, and its stored *position* still names
1219 /// the same option — a wrong remap here silently regrades exams.
1220 #[tokio::test]
1221 async fn boot_converts_positional_choices_and_keeps_the_same_option() {
1222 let db = super::init_mem().await.unwrap();
1223 // Roll the columns back to their pre-2026-07-24 shapes and write the
1224 // kind of row an older binary left behind, `source_bank` included.
1225 db.query(
1226 "REMOVE FIELD IF EXISTS choices[*].id ON TABLE exam_question;
1227 REMOVE FIELD IF EXISTS choices[*].text ON TABLE exam_question;
1228 REMOVE FIELD IF EXISTS choices[*].id ON TABLE bank_question;
1229 REMOVE FIELD IF EXISTS choices[*].text ON TABLE bank_question;
1230 DEFINE FIELD OVERWRITE choices ON exam_question TYPE option<array<string>>;
1231 DEFINE FIELD OVERWRITE correct ON exam_question TYPE option<int>;
1232 DEFINE FIELD OVERWRITE source_bank ON exam_question TYPE option<string>;
1233 DEFINE FIELD OVERWRITE slot ON question_image TYPE option<int>;
1234 DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option<int>;
1235 DEFINE FIELD OVERWRITE choices ON bank_question TYPE option<array<string>>;
1236 DEFINE FIELD OVERWRITE correct ON bank_question TYPE option<int>;
1237 DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option<int>;",
1238 )
1239 .await
1240 .unwrap()
1241 .check()
1242 .unwrap();
1243 db.query(
1244 "CREATE user:u SET username = 'u', password_hash = 'x';
1245 CREATE exam_question:q SET exam = exam:e, text = 'q', kind = 'multiple',
1246 points = 5, subject = subject:s, choices = ['3', '4', '5'], correct = 1,
1247 source_bank = 'bank_question:b';
1248 CREATE question_image:i SET exam = exam:e, question = exam_question:q, slot = 2,
1249 file = 'f', content_type = 'image/png', size = 1;
1250 CREATE question_image:whole SET exam = exam:e, question = exam_question:q,
1251 file = 'w', content_type = 'image/png', size = 1;
1252 CREATE exam_answer:a SET exam = exam:e, question = exam_question:q, user = user:u,
1253 selected = 2, updated_at = 1;
1254 CREATE bank_question:b SET owner = user:u, text = 'b', kind = 'multiple',
1255 points = 3, choices = ['a', 'b'], correct = 0, created_at = 1;
1256 CREATE bank_question_image:bi SET bank_question = bank_question:b, slot = 1,
1257 file = 'bf', content_type = 'image/png', size = 1;",
1258 )
1259 .await
1260 .unwrap()
1261 .check()
1262 .unwrap();
1263
1264 super::migrate(&db).await.unwrap();
1265
1266 let mut res = db
1267 .query(
1268 "SELECT choices, correct FROM ONLY exam_question:q;
1269 SELECT VALUE slot FROM ONLY question_image:i;
1270 SELECT VALUE slot FROM ONLY question_image:whole;
1271 SELECT VALUE selected FROM ONLY exam_answer:a;
1272 SELECT choices, correct FROM ONLY bank_question:b;
1273 SELECT VALUE slot FROM ONLY bank_question_image:bi;",
1274 )
1275 .await
1276 .unwrap();
1277 let q: Option<serde_json::Value> = res.take(0).unwrap();
1278 let q = q.unwrap();
1279 let img_slot: Option<String> = res.take(1).unwrap();
1280 let whole_slot: Option<String> = res.take(2).unwrap();
1281 let selected: Option<String> = res.take(3).unwrap();
1282 let bank: Option<serde_json::Value> = res.take(4).unwrap();
1283 let bank = bank.unwrap();
1284 let bank_slot: Option<String> = res.take(5).unwrap();
1285
1286 let ids: Vec<&str> = q["choices"]
1287 .as_array()
1288 .unwrap()
1289 .iter()
1290 .map(|c| c["id"].as_str().unwrap())
1291 .collect();
1292 assert_eq!(
1293 q["choices"][0]["text"], "3",
1294 "option order (and so the meaning of every stored index) is preserved"
1295 );
1296 assert_eq!(q["correct"], ids[1], "correct was index 1");
1297 assert_eq!(
1298 img_slot.as_deref(),
1299 Some(ids[2]),
1300 "option picture was slot 2"
1301 );
1302 assert_eq!(selected.as_deref(), Some(ids[2]), "the answer was index 2");
1303 assert_eq!(whole_slot, None, "a question-level picture has no index");
1304 let bank_ids: Vec<&str> = bank["choices"]
1305 .as_array()
1306 .unwrap()
1307 .iter()
1308 .map(|c| c["id"].as_str().unwrap())
1309 .collect();
1310 assert_eq!(bank["correct"], bank_ids[0]);
1311 assert_eq!(bank_slot.as_deref(), Some(bank_ids[1]));
1312
1313 // Writable again — every one of these failed coercion before the
1314 // backfill existed, and `source_bank` outlived its own column.
1315 db.query(
1316 "UPDATE exam_question:q SET points = 7;
1317 UPDATE question_image:i SET size = 2;
1318 UPDATE exam_answer:a SET updated_at = 2;
1319 UPDATE bank_question:b SET points = 4;
1320 UPDATE bank_question_image:bi SET size = 2;",
1321 )
1322 .await
1323 .unwrap()
1324 .check()
1325 .unwrap();
1326
1327 // A second boot re-mints nothing.
1328 super::migrate(&db).await.unwrap();
1329 let mut res = db
1330 .query("SELECT VALUE choices.map(|$c| $c.id) FROM ONLY exam_question:q")
1331 .await
1332 .unwrap();
1333 let again: Vec<String> = res.take(0).unwrap();
1334 assert_eq!(again, ids, "conversion is idempotent");
1335 }
1336}