forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBe2d0e43Ahmet Kaan Gümüş2 months ago397 commits

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