From 0787b145e9b1733a083a689faca6747d8b9d8081 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 27 Jul 2026 02:17:59 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=97=B3=EF=B8=8F=20elect=20the=20b?= =?UTF-8?q?oot,=20and=20make=20a=20chat=20turn=20a=20claimed=20job?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two things assumed there was only ever one process. Both stop assuming it, and both pay off on a single replica today, where a rolling restart already overlaps two containers. **The boot is elected.** Every process ran the whole migration, backfill and admin seed on startup, so two overlapping ones raced all three. A process now claims `migration_lock:boot` with a deterministic-id CREATE, renews a lease while it works, and stamps a sha256 of the SQL it applied; the others wait for that stamp and only trust it when the fingerprint is their own, so a new binary never serves on the previous one's schema. A leader that loses its lease fails its boot rather than reporting a success it no longer owns, and an abandoned lock is taken over once the lease lapses. Seeding the admin was two writes — create as a student, then promote — and a process killed between them left a student holding ADMIN_USERNAME that no later boot would ever promote, because nothing can tell that row from a stranger who registered the name. The role is now minted with the row. **A chat turn is a claimed job.** The answer used to ride on a `tokio::spawn` belonging to whichever process took the POST, so a restart orphaned it and the turn only settled at the stale horizon. The POST now just writes the pending row; a replica holding a `chat.reply` worker claims it with a conditional update and answers over its own socket. A claim left behind by a dead process expires and is retried, and a configured AI timeout is capped below that horizon so a slow inference is never reclaimed out from under itself. The gate and the dispatcher are deliberately separate: `ai_worker` is a heartbeated table that only answers "could anything, anywhere, serve this", may be stale, and never guards a write; the in-process registry owns the socket and is the only thing that decides who dispatches. hab/1 is untouched. Verified on two live replicas against one SurrealDB: a turn posted to a worker-less replica was answered by its peer, survived a restart of the other replica mid-flight, and was dispatched exactly once. --- README.md | 30 +- src/ai/mod.rs | 4 +- src/ai/presence.rs | 188 ++++++++ src/ai/server.rs | 101 ++++- src/config.rs | 66 ++- src/constant.rs | 279 +++++++++++- src/database.rs | 804 +++++++++++++++++++++++++++++++++- src/domain/chatbot_message.rs | 121 ++++- src/domain/user.rs | 29 +- src/lib.rs | 13 +- src/main.rs | 24 +- src/web/chatbot.rs | 184 ++++++-- tests/ai_bridge.rs | 221 ++++++++++ tests/limits_completeness.rs | 51 +++ 14 files changed, 2001 insertions(+), 114 deletions(-) create mode 100644 src/ai/presence.rs diff --git a/README.md b/README.md index bb007c2..cee080d 100644 --- a/README.md +++ b/README.md @@ -2183,23 +2183,39 @@ agree about `truncated` exactly as they do about every other field. | `404` | no such thread or message — or not the caller's | | `409` | already at `max_chatbot_threads`; delete a thread first | | `429` | over `RATE_LIMIT_CHATBOT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` | -| `503` | no connected service offers `chat.reply` — **nothing was written**, retry later | +| `503` | no service anywhere in the deployment offers `chat.reply` — **nothing was written**, retry later | -The `503` ordering matters: the bridge is checked before the rows exist, so an -unavailable service leaves no dead `pending` row behind, and the rate limit is -charged before that, so a refused turn leaves no trace at all. +The `503` ordering matters: availability is checked before the rows exist, so +an unavailable service leaves no dead `pending` row behind, and the rate limit +is charged before that, so a refused turn leaves no trace at all. The check +asks two questions — is a `chat.reply` worker connected to *this* backend +process, and failing that, is one connected to any other — so a deployment +running several backends accepts a turn as long as one of them can answer it. + +### A turn is a claimed job + +The `pending` assistant row *is* the work item. Backend processes poll it: a +process holding a `chat.reply` worker claims an unanswered turn, dispatches it +over its own connection, and stamps the result. That is why a `202` is a real +promise — a backend restart no longer strands the turn it had just accepted, +and a turn accepted by a process with no worker of its own is answered by one +that has. The cost is up to ~200 ms before the request leaves for the service. +A claim whose owner disappears is taken back after 90 seconds. ### A turn always settles Once the two rows exist the answer never stays `pending` forever, through three independent mechanisms: -- the answering task stamps `complete` or `failed` itself — the normal path; +- the process that claimed the turn stamps `complete` or `failed` — the normal + path, and a claim its owner never finishes is retried by another; - a reader **projects** a `pending` row older than 300 seconds as `failed`/`timed_out` (a read-time projection, not a write — the row is left for the task that may still own it); -- a **boot sweep** flips every leftover `pending` to `failed`/`interrupted`, - which is what a process death mid-inference looks like. +- a **boot sweep** flips every leftover `pending` past the 300-second horizon + to `failed`/`interrupted`, which is what a process death mid-inference looks + like. It leaves rows another process has claimed recently alone, so a + restarting backend cannot shoot down a turn its peer is answering. Two more verdicts come from inspecting the answer: an **empty** reply is reported as `failed`/`empty_reply` (a blank bubble is indistinguishable from a diff --git a/src/ai/mod.rs b/src/ai/mod.rs index 5cfa355..c553dbb 100644 --- a/src/ai/mod.rs +++ b/src/ai/mod.rs @@ -14,7 +14,8 @@ //! * [`protocol`] — frames on the wire //! * [`chat`] — the JSON payloads carried for the `chat.reply` capability //! * [`server`] — the listener, handshake, and [`server::AiBridge::dispatch`] -//! * [`registry`] — who is connected and who gets the next request +//! * [`registry`] — who is connected here, and who gets the next request +//! * [`presence`] — who is connected *anywhere*, for a cross-replica gate //! * [`tls`] — the listener's certificate //! //! The transport is generic; the features land on top of it. So far that is @@ -22,6 +23,7 @@ pub mod chat; pub mod error; +pub mod presence; pub mod protocol; pub mod registry; pub mod server; diff --git a/src/ai/presence.rs b/src/ai/presence.rs new file mode 100644 index 0000000..143df90 --- /dev/null +++ b/src/ai/presence.rs @@ -0,0 +1,188 @@ +//! Who can serve which AI capability *anywhere in the deployment* — the GATE. +//! +//! There are two answers to "is an AI service available", and confusing them +//! is the one way this module can do damage, so they are named: +//! +//! * **The gate — this module, the `ai_worker` table.** It answers "could +//! anything, anywhere, serve `chat.reply`?". Every replica writes a row for +//! each worker whose QUIC connection *it* holds and restamps it every +//! [`AI_WORKER_HEARTBEAT_SECS`]; a row unstamped for +//! [`AI_WORKER_LEASE_SECS`] is ignored and swept, so a replica that dies +//! leaves no permanent phantom. It is a cache of other processes' sockets: +//! it lags a registration by up to one heartbeat and a crash by up to one +//! lease, in *both* directions. Its only job is to spare a user a 503 on a +//! replica that holds no worker itself, because a peer's claim loop will +//! answer the turn. It must never guard a write and must never decide a +//! dispatch. +//! * **The dispatcher — [`crate::ai::registry::Registry`], in process.** It +//! owns the sockets. Only it knows whether *this* replica can answer, and it +//! is the only thing the chat claim loop consults before taking a turn. A +//! claim made on the gate's word would park a turn on a replica with nothing +//! to send it to. +//! +//! The split is why the table is safe to be wrong: nothing downstream of a +//! wrong answer is irreversible. A false yes costs one accepted turn that +//! settles `failed` (or waits out its staleness window); a false no costs one +//! 503 the user can retry. + +use surrealdb::types::RecordId; + +use crate::ai::registry::WorkerSnapshot; +use crate::constant::{ + AI_WORKER_ANNOUNCE, AI_WORKER_LEASE_SECS, AI_WORKER_SERVES, AI_WORKER_SWEEP, AI_WORKER_TABLE, + AI_WORKER_WITHDRAW, +}; +use crate::database::Database; +use crate::error::AppError; + +fn row(id: &str) -> RecordId { + RecordId::new(AI_WORKER_TABLE, id) +} + +/// Publish (or restamp) the workers this replica holds right now. +/// +/// `UPSERT` per worker, and the caller passes the whole live set every +/// heartbeat: a row lost to a database blip, or a worker that registered +/// before the presence table was attached, heals on the next beat instead of +/// staying invisible to every peer forever. +pub async fn announce(db: &Database, workers: &[WorkerSnapshot]) -> Result<(), AppError> { + for worker in workers { + db.query(AI_WORKER_ANNOUNCE) + .bind(("id", row(&worker.id))) + .bind(("service", worker.service.clone())) + .bind(("capabilities", worker.capabilities.clone())) + .await? + .check()?; + } + Ok(()) +} + +/// Drop a worker that said goodbye. Immediate, so a clean disconnect closes +/// the gate now rather than a lease later. +pub async fn withdraw(db: &Database, id: &str) -> Result<(), AppError> { + db.query(AI_WORKER_WITHDRAW) + .bind(("id", row(id))) + .await? + .check()?; + Ok(()) +} + +/// Forget workers nobody restamped within the lease — their replica died +/// without deregistering them. Any replica may run it: the rows are keyed by +/// worker, not by owner, and a live worker's row is never stale. +pub async fn sweep(db: &Database) -> Result<(), AppError> { + db.query(AI_WORKER_SWEEP) + .bind(("lease_ms", AI_WORKER_LEASE_SECS * 1_000)) + .await? + .check()?; + Ok(()) +} + +/// The gate read: does *any* replica hold a worker for `capability`? +/// +/// Errors answer "no" rather than propagating. This is consulted on the 503 +/// path of a request that has not written anything yet, so the worst a +/// database hiccup can do is tell one user to retry — turning it into a 500 +/// would be strictly worse for the same fault. +pub async fn serves(db: &Database, capability: &str) -> bool { + let found: Result, AppError> = async { + Ok(db + .query(AI_WORKER_SERVES) + .bind(("capability", capability.to_string())) + .bind(("lease_ms", AI_WORKER_LEASE_SECS * 1_000)) + .await? + .check()? + .take(0)?) + } + .await; + match found { + Ok(rows) => !rows.is_empty(), + Err(err) => { + tracing::warn!("could not read the AI worker gate: {err}"); + false + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constant::AI_CHAT_CAPABILITY; + + fn worker(id: &str, capabilities: &[&str]) -> WorkerSnapshot { + WorkerSnapshot { + id: id.to_string(), + service: "tutor".to_string(), + capabilities: capabilities.iter().map(|c| c.to_string()).collect(), + inflight: 0, + max_concurrent: 4, + } + } + + #[tokio::test] + async fn a_stale_row_stops_answering_the_gate() { + // The phantom this exists to prevent: a replica that dies leaves its + // row behind, and without the age filter that row would keep every + // peer's chat endpoint reporting a service that is gone. + let db = crate::database::init_mem().await.unwrap(); + announce(&db, &[worker("w1", &[AI_CHAT_CAPABILITY])]) + .await + .unwrap(); + assert!(serves(&db, AI_CHAT_CAPABILITY).await); + assert!(!serves(&db, "ocr.extract").await, "a capability nobody has"); + + // Age it past the lease, as a dead replica's row ages on its own. + db.query("UPDATE ai_worker SET seen_at = seen_at - $ms") + .bind(("ms", (AI_WORKER_LEASE_SECS + 1) * 1_000)) + .await + .unwrap() + .check() + .unwrap(); + assert!( + !serves(&db, AI_CHAT_CAPABILITY).await, + "a stale row must not hold the gate open" + ); + sweep(&db).await.unwrap(); + let rows: Vec = db + .query("SELECT VALUE id FROM ai_worker") + .await + .unwrap() + .check() + .unwrap() + .take(0) + .unwrap(); + assert!(rows.is_empty(), "the sweep deletes what the read ignores"); + } + + #[tokio::test] + async fn announcing_twice_restamps_rather_than_duplicating() { + let db = crate::database::init_mem().await.unwrap(); + let live = [worker("w1", &[AI_CHAT_CAPABILITY])]; + announce(&db, &live).await.unwrap(); + db.query("UPDATE ai_worker SET seen_at = seen_at - $ms") + .bind(("ms", (AI_WORKER_LEASE_SECS + 1) * 1_000)) + .await + .unwrap() + .check() + .unwrap(); + assert!(!serves(&db, AI_CHAT_CAPABILITY).await); + + announce(&db, &live).await.unwrap(); + assert!(serves(&db, AI_CHAT_CAPABILITY).await, "the beat healed it"); + let rows: Vec = db + .query("SELECT VALUE id FROM ai_worker") + .await + .unwrap() + .check() + .unwrap() + .take(0) + .unwrap(); + assert_eq!(rows.len(), 1, "one worker is one row"); + + withdraw(&db, "w1").await.unwrap(); + assert!( + !serves(&db, AI_CHAT_CAPABILITY).await, + "goodbye is immediate" + ); + } +} diff --git a/src/ai/server.rs b/src/ai/server.rs index 6e664eb..c1c5d22 100644 --- a/src/ai/server.rs +++ b/src/ai/server.rs @@ -12,12 +12,14 @@ use serde_json::Value; use ulid::Ulid; use crate::ai::error::AiError; +use crate::ai::presence; use crate::ai::protocol::{ Greeting, Hello, RejectCode, Request, Response, protocol_matches, read_frame, write_frame, }; use crate::ai::registry::{AiRegistry, WorkerSnapshot, clamp_concurrency}; use crate::ai::tls; use crate::constant::{AI_HANDSHAKE_TIMEOUT_SECS, AI_PROTOCOL}; +use crate::database::Database; /// What the bridge needs to come up. #[derive(Clone, Debug)] @@ -35,6 +37,13 @@ pub struct BridgeConfig { struct Inner { registry: AiRegistry, + /// The database, once [`AiBridge::attach_presence`] has handed it over — + /// used for the `ai_worker` gate and nothing else (see + /// [`crate::ai::presence`]). `OnceLock` because the bridge binds before the + /// router is built, so presence is wired *after* the listener is already + /// accepting: a worker may register before this is set, and the heartbeat + /// republishes the whole live set precisely so that one is not lost. + presence: std::sync::OnceLock, /// The leaf certificate this listener presents, kept so it can be shown to /// an operator (or pinned by an in-process client) without re-reading the /// PEM off disk. @@ -77,6 +86,7 @@ impl AiBridge { let inner = Arc::new(Inner { registry: AiRegistry::default(), + presence: std::sync::OnceLock::new(), certificate: bridge_tls.leaf.clone(), token: config.token, request_timeout: config.request_timeout, @@ -114,13 +124,35 @@ impl AiBridge { self.inner.registry.snapshot() } - /// Is anything connected that can serve `capability`? Callers use this to - /// hide a feature in the UI rather than to gate a request — by the time the - /// request runs, the answer may have changed either way. + /// Is anything connected *to this process* that can serve `capability`? + /// + /// The DISPATCHER's answer, and the authoritative one: this registry owns + /// the sockets, so only it may decide that this replica can answer a job. + /// Racy in the harmless direction — a worker can vanish between the check + /// and the dispatch — so it still never guards a write. For "can *anyone* + /// serve it", which is a different and weaker question, see + /// [`crate::ai::presence::serves`]. pub fn has_capability(&self, capability: &str) -> bool { self.inner.registry.has_capability(capability) } + /// Hand the bridge the database, so the workers it holds become visible to + /// other replicas through the `ai_worker` gate. Returns whether this call + /// was the one that wired it — the caller uses that to start exactly one + /// claim loop per process. + /// + /// Idempotent by construction: a second call is a no-op and returns + /// `false`. Nothing here is required for the bridge to work; a deployment + /// that never attaches presence simply keeps the single-process behaviour, + /// where the in-process registry is the whole truth. + pub fn attach_presence(&self, db: Database) -> bool { + if self.inner.presence.set(db.clone()).is_err() { + return false; + } + heartbeat_presence(Arc::downgrade(&self.inner), db); + true + } + /// Send one request to a service and await its answer. /// /// Each call takes a fresh QUIC bidirectional stream, so concurrent calls @@ -203,6 +235,45 @@ impl AiBridge { } } +/// Republish this replica's live worker set to the `ai_worker` gate, forever. +/// +/// The whole set every beat rather than deltas: it is the self-healing half of +/// the gate (a row lost to a database blip, or a worker registered before +/// presence was attached, comes back on the next tick), and the set is a +/// handful of rows. The sweep rides along so a replica that died without +/// deregistering stops holding anyone's gate open. +/// +/// Holds a `Weak` on the bridge so that *this* task is not itself a reason to +/// keep a listener alive. It is not a shutdown mechanism, and in the wired-up +/// process it never fires: `chatbot::spawn_claim_loop` owns an `AiBridge` by +/// value for the life of the process, so the strong count never reaches zero +/// and both tasks run until exit. That is intended for a server — the bridge +/// is not restartable — and is only visible in tests, which build many +/// bridges. Correct that (a `CancellationToken` on both loops) the day a +/// bridge needs to be torn down while the process lives. +fn heartbeat_presence(inner: std::sync::Weak, db: Database) { + tokio::spawn(async move { + let mut ticker = tokio::time::interval(Duration::from_secs( + crate::constant::AI_WORKER_HEARTBEAT_SECS, + )); + ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + // The first tick is immediate, so workers registered before the + // database arrived are published now and not one beat late. + ticker.tick().await; + let Some(inner) = inner.upgrade() else { return }; + let workers = inner.registry.snapshot(); + drop(inner); + if let Err(err) = presence::announce(&db, &workers).await { + tracing::warn!("could not publish the AI worker gate: {err}"); + } + if let Err(err) = presence::sweep(&db).await { + tracing::warn!("could not sweep the AI worker gate: {err}"); + } + } + }); +} + /// Accept connections until the endpoint closes. One task per service. async fn accept_loop(inner: Arc) { while let Some(incoming) = inner.endpoint.accept().await { @@ -243,6 +314,13 @@ async fn serve_connection(inner: Arc, conn: quinn::Connection, remote: So // dies without saying anything. let reason = conn.closed().await; inner.registry.remove(&worker_id); + // The gate closes with the registry, not a lease later — but only after + // the registry, which is the authoritative one (see `presence`). + if let Some(db) = inner.presence.get() + && let Err(err) = presence::withdraw(db, &worker_id).await + { + tracing::warn!("could not withdraw AI worker {worker_id} from the gate: {err}"); + } tracing::info!("AI service `{service}` ({worker_id}) at {remote} disconnected: {reason}"); } @@ -331,6 +409,23 @@ async fn register( max_concurrent, conn.clone(), ); + // …and only then published to the gate, so `ai_worker` can never advertise + // a worker the local dispatcher would refuse to pick. + if let Some(db) = inner.presence.get() { + let announced = WorkerSnapshot { + id: worker_id.clone(), + service: hello.service.clone(), + capabilities: hello.capabilities.clone(), + inflight: 0, + max_concurrent, + }; + if let Err(err) = presence::announce(db, &[announced]).await { + // Not fatal, and not a reason to refuse the service: the worker is + // already usable by this replica, and the next heartbeat + // republishes the whole live set. + tracing::warn!("could not publish AI worker {worker_id} to the gate: {err}"); + } + } tracing::info!( "AI service `{}` ({worker_id}) at {remote} registered: {:?}, max_concurrent {max_concurrent}", hello.service, diff --git a/src/config.rs b/src/config.rs index c6318b2..5ad7859 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,8 +1,8 @@ use std::env; use crate::constant::{ - AI_DEFAULT_REQUEST_TIMEOUT_SECS, DEFAULT_API_RATE_LIMIT, DEFAULT_AUTH_RATE_LIMIT, - DEFAULT_CHATBOT_RATE_LIMIT, + AI_DEFAULT_REQUEST_TIMEOUT_SECS, AI_MAX_REQUEST_TIMEOUT_SECS, DEFAULT_API_RATE_LIMIT, + DEFAULT_AUTH_RATE_LIMIT, DEFAULT_CHATBOT_RATE_LIMIT, }; use crate::rate_limit::RateLimitConfig; @@ -105,14 +105,34 @@ fn parse_limit(value: Option, default: u32) -> u32 { value.and_then(|v| v.trim().parse().ok()).unwrap_or(default) } -/// Parse a timeout in seconds. Unlike a rate limit, `0` is *not* honoured — -/// a zero deadline would fail every AI request instantly, which is never what -/// an operator means — so it falls back with the rest of the garbage. +/// Parse the AI request deadline in seconds. Unlike a rate limit, `0` is *not* +/// honoured — a zero deadline would fail every AI request instantly, which is +/// never what an operator means — so it falls back with the rest of the +/// garbage. +/// +/// The ceiling is the load-bearing part, and it is enforced here because here +/// is the only place the number enters the process. A deadline above +/// [`AI_MAX_REQUEST_TIMEOUT_SECS`] lets one dispatch outlive +/// `CHATBOT_CLAIM_RECLAIM_SECS`, and the chat claim queue then hands the same +/// turn to a second worker while the first is still answering it — two +/// inferences for one reply. Clamping at the boundary is what makes that +/// unreachable *by configuration*, instead of true only for the default. fn parse_timeout(value: Option, default: u64) -> u64 { - value + let asked = value .and_then(|v| v.trim().parse().ok()) .filter(|n| *n > 0) - .unwrap_or(default) + .unwrap_or(default); + if asked > AI_MAX_REQUEST_TIMEOUT_SECS { + // Loud: the operator asked for something they are not getting, and the + // reason (a queue horizon) is not one they could guess from the name. + tracing::warn!( + "AI_REQUEST_TIMEOUT_SECS={asked} is above the {AI_MAX_REQUEST_TIMEOUT_SECS}s ceiling \ + the chat claim queue allows (a longer inference would be reclaimed and re-dispatched \ + mid-flight) — using {AI_MAX_REQUEST_TIMEOUT_SECS}s" + ); + return AI_MAX_REQUEST_TIMEOUT_SECS; + } + asked } /// Parse the `PORT` value, falling back to 8080 when unset or unparseable. @@ -134,6 +154,9 @@ fn parse_flag(value: Option) -> bool { #[cfg(test)] mod tests { use super::{parse_flag, parse_limit, parse_port, parse_timeout}; + use crate::constant::{ + AI_DEFAULT_REQUEST_TIMEOUT_SECS, AI_MAX_REQUEST_TIMEOUT_SECS, CHATBOT_CLAIM_RECLAIM_SECS, + }; #[tokio::test] async fn timeout_falls_back_on_absent_garbage_and_zero() { @@ -141,7 +164,34 @@ mod tests { assert_eq!(parse_timeout(Some("nope".into()), 30), 30); // A zero deadline would time out every AI call before it started. assert_eq!(parse_timeout(Some("0".into()), 30), 30); - assert_eq!(parse_timeout(Some(" 120 ".into()), 30), 120); + // Whitespace is trimmed; the ceiling has its own test below. + assert_eq!(parse_timeout(Some(" 45 ".into()), 30), 45); + } + + #[tokio::test] + async fn a_configured_timeout_can_never_outlive_the_chat_claim_horizon() { + // The one double-dispatch an operator could still reach: nothing used + // to stop `AI_REQUEST_TIMEOUT_SECS=120`, and a dispatch outliving + // `CHATBOT_CLAIM_RECLAIM_SECS` has its turn reclaimed and re-sent while + // the first inference is still running — the model answers one turn + // twice. The relationship, not a literal, is what is asserted: raising + // one of the two numbers without the other cannot pass this. + for asked in ["91", "120", "600", "18446744073709551615"] { + let got = parse_timeout(Some(asked.into()), AI_DEFAULT_REQUEST_TIMEOUT_SECS); + assert!( + (got as i64) < CHATBOT_CLAIM_RECLAIM_SECS, + "AI_REQUEST_TIMEOUT_SECS={asked} was honoured as {got}s, at or past the \ + {CHATBOT_CLAIM_RECLAIM_SECS}s reclaim horizon" + ); + assert_eq!(got, AI_MAX_REQUEST_TIMEOUT_SECS, "clamped to the ceiling"); + } + // Everything under the ceiling — the default included — is honoured + // verbatim: this is a ceiling, not a fixed deadline. + assert_eq!(parse_timeout(Some("45".into()), 30), 45); + assert_eq!( + parse_timeout(None, AI_DEFAULT_REQUEST_TIMEOUT_SECS), + AI_DEFAULT_REQUEST_TIMEOUT_SECS + ); } #[tokio::test] diff --git a/src/constant.rs b/src/constant.rs index f3e518d..650c8d7 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -371,6 +371,56 @@ pub const AI_KEEPALIVE_SECS: u64 = 10; /// chat endpoints report the service as unavailable. pub const AI_CHAT_CAPABILITY: &str = "chat.reply"; +// --- AI worker presence: the GATE, never the dispatcher ----------------- +// +// Read `crate::ai::presence` before touching anything below. In one line: the +// `ai_worker` table answers "could *anything, anywhere* serve this +// capability?" so a POST on a replica holding no worker can still be accepted +// (a peer's claim loop will answer it). It is a heartbeated cache of other +// processes' sockets and it is allowed to be wrong in both directions. The +// in-process `ai::registry::Registry` is the dispatcher and the only thing +// that may decide who actually answers. + +/// The heartbeated presence table. One row per connected worker, written by +/// whichever replica owns that worker's QUIC connection. +pub const AI_WORKER_TABLE: &str = "ai_worker"; + +/// How often a replica restamps `seen_at` for the workers it holds, and how +/// long a row is believed without a restamp. The lease is a comfortable +/// multiple of the beat (three), so a single missed heartbeat never hides a +/// live worker, and it matches [`AI_IDLE_TIMEOUT_SECS`] — the window in which +/// the transport itself notices a dead service — so a replica that dies +/// outright leaves a phantom for no longer than a service that dies outright. +pub const AI_WORKER_HEARTBEAT_SECS: u64 = 10; +pub const AI_WORKER_LEASE_SECS: i64 = 30; + +/// Write (or restamp) one worker's row. `UPSERT` rather than `CREATE`: the +/// heartbeat replays the whole live set every beat, which is what heals a row +/// lost to a database blip or written before the presence table was attached. +pub const AI_WORKER_ANNOUNCE: &str = " + UPSERT $id CONTENT { service: $service, capabilities: $capabilities, + seen_at: time::unix(time::now()) * 1000 }; +"; + +/// Drop a worker whose connection closed. Immediate — the gate should not +/// hold a door open for a service that has already said goodbye. +pub const AI_WORKER_WITHDRAW: &str = "DELETE $id;"; + +/// Forget workers nobody has restamped within the lease: the replica holding +/// them died without deregistering. Any replica's heartbeat may run it — the +/// rows are keyed by worker, not by owner. +pub const AI_WORKER_SWEEP: &str = " + DELETE ai_worker WHERE seen_at < time::unix(time::now()) * 1000 - $lease_ms; +"; + +/// The gate read. Age-filtered in the query, not by the sweep, so a phantom +/// row is inert the moment it is stale rather than when someone gets round to +/// deleting it. +pub const AI_WORKER_SERVES: &str = " + SELECT VALUE id FROM ai_worker WHERE $capability IN capabilities + AND seen_at >= time::unix(time::now()) * 1000 - $lease_ms LIMIT 1; +"; + /// Hard ceiling on one chat message's characters — the newtype bound, above /// which no school setting can reach. Sized for a pasted question with its /// working, well under [`AI_MAX_FRAME_BYTES`] once history rides along. @@ -416,6 +466,93 @@ pub const CHAT_STREAM_POLL_MS: u64 = 200; /// this only catches the row whose task died with the process. pub const CHATBOT_PENDING_STALE_SECS: i64 = 300; +// --- the chat claim queue ---------------------------------------------- + +/// How often a replica looks for an unanswered turn, and how many it takes in +/// one sweep. The poll is what replaces the in-process `tokio::spawn` a POST +/// used to do, so it is the answer's added latency floor — matched to +/// [`CHAT_STREAM_POLL_MS`], the cadence the client already waits at, so a turn +/// is never claimed slower than its own reader refreshes. The batch is small +/// on purpose: a claim is a promise to dispatch now, and dispatching more at +/// once than a worker's `max_concurrent` would only turn the surplus into +/// `busy` failures. +pub const CHATBOT_CLAIM_POLL_MS: u64 = 200; +pub const CHATBOT_CLAIM_BATCH: i64 = 4; + +/// How long a claim is believed before another replica may take the turn back. +/// +/// Sized between the two horizons it sits between, and both bounds bite (see +/// `the_claim_horizon_sits_between_the_inference_and_the_stale_window`): +/// +/// * **Above the AI request timeout** ([`AI_DEFAULT_REQUEST_TIMEOUT_SECS`], +/// 30s), with room to spare, because a reclaim that fires while the first +/// claimer is still waiting on a legitimate inference makes two services +/// answer the same turn — twice the cost for one reply (the second is then +/// discarded by the `status = 'pending'` gate on the settle, so it is waste, +/// not corruption). Three times the default leaves margin for the settle +/// write and for a moderately raised `AI_REQUEST_TIMEOUT_SECS`. +/// * **Below [`CHATBOT_PENDING_STALE_SECS`]** (300s), because a turn is only +/// claimable inside that window; a reclaim horizon at or above it would +/// never fire before the turn stopped being worth answering, making the +/// dead-claimer retry dead code. At 90s a turn survives two lost claimers +/// and still gets answered. +pub const CHATBOT_CLAIM_RECLAIM_SECS: i64 = 90; + +/// The largest per-request AI deadline a deployment may configure +/// (`AI_REQUEST_TIMEOUT_SECS`). Anything above it is clamped down to it at +/// startup, loudly — see [`crate::config`]. +/// +/// Not a taste limit; it is the claim queue's arithmetic, and the bound the +/// doc above only *asserted* before. A dispatch allowed to outlive +/// [`CHATBOT_CLAIM_RECLAIM_SECS`] has its turn reclaimed and re-sent while the +/// first inference is still legitimately running, so the model runs twice for +/// one reply. (The settle's `status = 'pending'` gate still admits only one +/// answer, so it is waste rather than corruption — but a worker with side +/// effects makes it worse than waste.) Nothing but the parser stood between an +/// operator and that: `AI_REQUEST_TIMEOUT_SECS=120` used to be honoured +/// verbatim. +/// +/// Clamped rather than refused, because a slow model is a legitimate thing to +/// own and a boot that dies over it helps nobody — and because the ceiling is +/// real either way: a reply that arrives after +/// [`CHATBOT_PENDING_STALE_SECS`] is discarded by the read-time projection, so +/// no deadline near it was ever going to produce an answer a user sees. A +/// school that genuinely needs longer raises the horizon and the staleness +/// window together, and the ordering tests police the result. +/// +/// Two thirds of the horizon, derived and never hand-kept: raising the horizon +/// raises this with it, so the two numbers cannot drift apart. The remaining +/// third is the room the reply needs to arrive, be capped and be stamped +/// before anyone may reclaim the turn. +pub const AI_MAX_REQUEST_TIMEOUT_SECS: u64 = CHATBOT_CLAIM_RECLAIM_SECS as u64 * 2 / 3; + +/// Take up to [`CHATBOT_CLAIM_BATCH`] unanswered turns for this replica. +/// +/// Two statements because SurrealDB has no `LIMIT` on `UPDATE`: the first +/// picks candidates, the second claims them. The pick is advisory — a peer may +/// take a row in between — so the `UPDATE` repeats the *whole* guard, and +/// per-record `UPDATE ... WHERE` is atomic, so a row claimed by a rival simply +/// does not come back in `RETURN AFTER`. Nothing here consults `ai_worker`: +/// the caller has already asked its own registry whether it can answer. +/// +/// The guard, term by term: only a reserved assistant row (`pending`), only +/// one young enough that somebody is still waiting for it (`$stale_ms` — past +/// that a reader already shows it failed, so answering it would resurrect a +/// turn the user was told was lost), and only one that is unclaimed *or* whose +/// claimer has gone quiet past `$reclaim_ms`. Both disjuncts are required: a +/// row whose claimer died must be retried, not left forever. +pub const CHATBOT_CLAIM: &str = " + LET $ids = (SELECT VALUE id FROM chatbot_message + WHERE status = 'pending' AND role = 'assistant' + AND created_at >= time::unix(time::now()) * 1000 - $stale_ms + AND (claimed_by = NONE OR claimed_at < time::unix(time::now()) * 1000 - $reclaim_ms) + ORDER BY created_at ASC, id ASC LIMIT $batch); + UPDATE $ids SET claimed_by = $me, claimed_at = time::unix(time::now()) * 1000 + WHERE status = 'pending' + AND (claimed_by = NONE OR claimed_at < time::unix(time::now()) * 1000 - $reclaim_ms) + RETURN AFTER; +"; + /// How long a dialling AI service has to complete its `Hello`/`Welcome` /// exchange before the connection is dropped. Short: the handshake is one /// frame each way, and an unauthenticated connection must not be able to @@ -582,6 +719,87 @@ pub const MEAL_BOOKING_TABLE: &str = "meal_booking"; pub const MEAL_ATTENDANCE_TABLE: &str = "meal_attendance"; pub const MEAL_LEDGER_TABLE: &str = "meal_ledger"; +// --- boot leader election ---------------------------------------------- + +/// The lock row every booting process races for (see +/// [`crate::database::boot_once`]). Its own table, and the only SCHEMALESS one +/// in the database: the lock has to be claimable *before* the SCHEMAFULL batch +/// that defines every other table has run, so a lock whose own schema needed +/// migrating could not guard the migration. `IF NOT EXISTS` makes the +/// definition safe for all N processes to issue. +pub const MIGRATION_LOCK_TABLE: &str = "migration_lock"; +pub const MIGRATION_LOCK_DDL: &str = "DEFINE TABLE IF NOT EXISTS migration_lock SCHEMALESS;"; + +/// Claim the lock. A deterministic id is the whole mechanism: SurrealDB v3 +/// answers a `CREATE` on an existing id with "already exists" rather than +/// overwriting it, so of N concurrent processes exactly one gets an `Ok`. +/// Returns the holder like the takeover does, so one caller reads both. +pub const MIGRATION_LOCK_CLAIM: &str = " + CREATE migration_lock:boot SET holder = $me, claimed_at = time::unix(time::now()) * 1000, + applied_at = NONE, applies = 0 RETURN VALUE holder; +"; + +/// What a loser needs to know, decided by the *database's* clock — never the +/// process's, since two replicas' clocks disagree and the lease horizon is the +/// one thing a wrong clock could turn into a concurrent migration. +/// +/// `applied` means "applied *this* binary's schema": a stamp carries the +/// fingerprint of the DDL that produced it, and a peer's stamp with any other +/// fingerprint is no evidence about the schema this process is about to write +/// (see [`crate::database::migration_fingerprint`]). +pub const MIGRATION_LOCK_STATE: &str = " + SELECT holder, applied_at != NONE AND (fingerprint ?? '') = $fingerprint AS applied, + claimed_at >= time::unix(time::now()) * 1000 - $lease_ms AS live + FROM ONLY migration_lock:boot; +"; + +/// Take the lock off a holder that cannot be relied on: one that has gone +/// silent past the lease horizon (killed mid-migration), or one that finished +/// with a *different* schema than ours — a stamp is the last thing a leader +/// writes, so a foreign fingerprint means nobody is in the DDL right now and +/// this binary's own migration still has to run. +/// +/// Per-record `UPDATE ... WHERE` is atomic, so a second taker re-reads the +/// freshly bumped `claimed_at` and is refused (empty result). Clears +/// `applied_at` and `fingerprint`: the previous generation's stamp says nothing +/// about this one's schema. +pub const MIGRATION_LOCK_TAKEOVER: &str = " + UPDATE migration_lock:boot SET holder = $me, claimed_at = time::unix(time::now()) * 1000, + applied_at = NONE, fingerprint = NONE + WHERE claimed_at < time::unix(time::now()) * 1000 - $lease_ms + OR (applied_at != NONE AND (fingerprint ?? '') != $fingerprint) + RETURN VALUE holder; +"; + +/// Renew the lease while the migration runs, and stamp it done afterwards. +/// Both are `holder`-guarded and both report the holder back, so a leader that +/// was declared dead and replaced not only stops being able to write the lock — +/// it finds out (an empty result), which is the only way it can learn that a +/// peer is now applying the same DDL underneath it. +pub const MIGRATION_LOCK_HEARTBEAT: &str = " + UPDATE migration_lock:boot SET claimed_at = time::unix(time::now()) * 1000 + WHERE holder = $me RETURN VALUE holder; +"; +pub const MIGRATION_LOCK_STAMP: &str = " + UPDATE migration_lock:boot SET applied_at = time::unix(time::now()) * 1000, applies += 1, + fingerprint = $fingerprint + WHERE holder = $me RETURN VALUE holder; +"; + +/// How long a lock may go unrenewed before a peer may take it over. Must stay +/// a comfortable multiple of `MIGRATION_LOCK_HEARTBEAT_SECS`: it is the number +/// of missed beats that separates "the leader was killed" from "the leader is +/// slow", and mistaking the second for the first runs two migrations at once. +pub const MIGRATION_LOCK_LEASE_SECS: i64 = 30; +pub const MIGRATION_LOCK_HEARTBEAT_SECS: u64 = 5; + +/// How long a non-leader waits for the leader's `applied_at` before failing the +/// boot, and how often it looks. Bounded because a boot that hangs forever is +/// indistinguishable from a hung database; loud because the alternative — +/// serving on a schema nobody confirmed — is worse. +pub const MIGRATION_LOCK_WAIT_SECS: u64 = 180; +pub const MIGRATION_LOCK_POLL_MS: u64 = 200; + // --- schema migration SQL ---------------------------------------------- /// Repairs that must run *before* the DDL batch, because the DDL is what makes @@ -686,8 +904,26 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS error_code ON chatbot_message TYPE option; DEFINE FIELD IF NOT EXISTS created_at ON chatbot_message TYPE int READONLY; DEFINE FIELD IF NOT EXISTS completed_at ON chatbot_message TYPE option; + -- The claim (2026-07-27): which replica's claim loop owes this turn an + -- answer, and when it said so. Absent = nobody has taken it yet; a claim + -- older than CHATBOT_CLAIM_RECLAIM_SECS is a dead claimer and the turn is + -- taken back (see `CHATBOT_CLAIM`). + DEFINE FIELD IF NOT EXISTS claimed_by ON chatbot_message TYPE option; + DEFINE FIELD IF NOT EXISTS claimed_at ON chatbot_message TYPE option; DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at; DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id; + -- The claim loop's sweep: every poll asks for pending rows by age. + DEFINE INDEX IF NOT EXISTS chatbot_message_status_created ON chatbot_message FIELDS status, created_at; + + -- Which AI workers are connected to *any* replica (2026-07-27). The GATE + -- and nothing else: a row only says a socket existed somewhere at + -- `seen_at`, so it may spare a user a 503 but must never pick who answers + -- — that is the in-process registry's call. Heartbeated by the replica + -- owning the connection; a stale row is ignored by the read and swept. + DEFINE TABLE IF NOT EXISTS ai_worker SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS service ON ai_worker TYPE string; + DEFINE FIELD IF NOT EXISTS capabilities ON ai_worker TYPE array; + DEFINE FIELD IF NOT EXISTS seen_at ON ai_worker TYPE int; DEFINE TABLE IF NOT EXISTS event SCHEMAFULL; DEFINE FIELD IF NOT EXISTS creator ON event TYPE record; @@ -1190,17 +1426,33 @@ pub const BACKFILL: &str = " -- which is what they were presented as all along. UPDATE chatbot_message SET truncated = false WHERE truncated = NONE; - -- An assistant turn is answered by an in-process task, so a restart usually - -- leaves its row `pending` with nobody left to complete it. Only rows past - -- the stale horizon ($stale_ms, from `CHATBOT_PENDING_STALE_SECS`) are - -- certainly abandoned though: a young one may still be being answered on the - -- other side of the AI bridge, and a deploy must not shoot down a turn - -- dispatched seconds ago. Nothing is lost by waiting — a reader already - -- presents an over-age `pending` row as failed, and the next boot sweeps for - -- real whatever crossed the horizon in the meantime. + -- An assistant turn is answered by a claim loop in some replica's process, + -- so a restart can leave its row `pending` with nobody left to complete it. + -- Only rows past the stale horizon ($stale_ms, from + -- `CHATBOT_PENDING_STALE_SECS`) are certainly abandoned though: a young one + -- may still be being answered on the other side of the AI bridge, and a + -- deploy must not shoot down a turn dispatched seconds ago. Nothing is lost + -- by waiting — a reader already presents an over-age `pending` row as + -- failed, and the next boot sweeps for real whatever crossed the horizon in + -- the meantime. + -- + -- Claim-aware since 2026-07-27, because the sweep is no longer school-wide + -- truth: under N replicas the row may belong to a *live peer's* claim loop, + -- and failing it here would shoot down another process's in-flight turn. + -- So a claim restamped within the window is left alone. Both disjuncts + -- matter — `claimed_by = NONE` alone would strand every row whose claimer + -- died, which is the one case the sweep exists for. + -- + -- The claim age is measured against $stale_ms rather than + -- CHATBOT_CLAIM_RECLAIM_SECS only because the boot binds one horizon (see + -- `database::migration_binds`); erring long is the safe direction — the + -- cost is that a row claimed just before it aged out waits one more boot + -- for its durable stamp, while readers have shown it failed all along. UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted', completed_at = time::unix(time::now()) * 1000 - WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms; + WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms + AND (claimed_by = NONE + OR claimed_at < time::unix(time::now()) * 1000 - $stale_ms); -- Promotion out of student now deletes the user's enrollments (2026-07-18); -- this sweeps rows promoted before that fix. A deleted user reads as @@ -1265,3 +1517,12 @@ pub const BACKFILL: &str = " UPDATE answer_image SET seq = 1 WHERE seq = NONE; UPDATE exam_result SET seq = 1 WHERE seq = NONE; "; + +/// The migration batches, in the order a boot applies them — and the *only* +/// list of them. [`crate::database::migrate`] runs exactly these and +/// [`crate::database::migration_fingerprint`] hashes exactly these, so a fourth +/// batch cannot be executed without changing the fingerprint that decides +/// whether a peer's schema is ours. They stay three separate queries: statements +/// in one batch see the schema as it stood when the batch started (see +/// `MIGRATION`). +pub const MIGRATION_BATCHES: [&str; 3] = [PRE_REPAIR, MIGRATION, BACKFILL]; diff --git a/src/database.rs b/src/database.rs index a38537a..d606a6a 100644 --- a/src/database.rs +++ b/src/database.rs @@ -3,9 +3,16 @@ use surrealdb::Surreal; use surrealdb::engine::any::Any; use surrealdb::opt::auth::Root; +use surrealdb::types::SurrealValue; use crate::config::Config; -use crate::constant::{BACKFILL, CHATBOT_PENDING_STALE_SECS, MIGRATION, PRE_REPAIR}; +use crate::constant::{ + CHATBOT_PENDING_STALE_SECS, MIGRATION_BATCHES, MIGRATION_LOCK_CLAIM, MIGRATION_LOCK_DDL, + MIGRATION_LOCK_HEARTBEAT, MIGRATION_LOCK_HEARTBEAT_SECS, MIGRATION_LOCK_LEASE_SECS, + MIGRATION_LOCK_POLL_MS, MIGRATION_LOCK_STAMP, MIGRATION_LOCK_STATE, MIGRATION_LOCK_TAKEOVER, + MIGRATION_LOCK_WAIT_SECS, +}; +use crate::domain::user::{Password, User, Username}; use crate::error::AppError; /// The shared database handle. @@ -24,8 +31,14 @@ use crate::error::AppError; /// Cloning the `Arc` shares the single session established at boot instead. pub type Database = std::sync::Arc>; -/// Connect to the SurrealDB server, sign in as root, and apply the schema. +/// Connect to the SurrealDB server, sign in as root, and apply the schema — +/// the latter through the boot election, so that N overlapping processes apply +/// it once between them (see [`boot_once`]). pub async fn init(cfg: &Config) -> Result { + // Validated before the connection, not after the election: half a + // credential pair is a deployment mistake, and finding that out only in the + // process that happened to win the lock would make it a coin flip. + let admin = admin_credentials(cfg)?; let db = connect_with_retry(cfg).await; db.signin(Root { username: cfg.db_user.clone(), @@ -35,8 +48,348 @@ pub async fn init(cfg: &Config) -> Result { db.use_ns(cfg.db_ns.clone()) .use_db(cfg.db_name.clone()) .await?; - migrate(&db).await?; - Ok(std::sync::Arc::new(db)) + let db = std::sync::Arc::new(db); + boot_once( + &db, + admin, + std::time::Duration::from_secs(MIGRATION_LOCK_WAIT_SECS), + ) + .await?; + Ok(db) +} + +/// The `ADMIN_USERNAME` / `ADMIN_PASSWORD` bootstrap pair, if configured. +/// Both-or-neither: half a pair aborts startup rather than silently running +/// without the seed. +fn admin_credentials(cfg: &Config) -> Result, AppError> { + match (&cfg.admin_username, &cfg.admin_password) { + (Some(username), Some(password)) => Ok(Some(( + Username::try_new(username) + .map_err(|err| AppError::Internal(format!("invalid ADMIN_USERNAME: {err}")))?, + Password::try_new(password) + .map_err(|err| AppError::Internal(format!("invalid ADMIN_PASSWORD: {err}")))?, + ))), + (None, None) => Ok(None), + _ => Err(AppError::Internal( + "ADMIN_USERNAME and ADMIN_PASSWORD must be set together".into(), + )), + } +} + +/// Run the boot work that must happen exactly once — the schema batches and the +/// admin seed — under a leader election, and hold every other process at the +/// door until it *has* happened. Returns whether we were the leader. +/// +/// Two processes overlap on every rolling restart, long before any replica +/// work: they used to race the same SCHEMAFULL DDL, the same data backfills +/// (including the chatbot pending sweep, which writes live rows) and the same +/// `ensure_admin` read-then-create. The election is a deterministic-id +/// `CREATE`: SurrealDB v3 answers a create on an existing id with "already +/// exists" instead of overwriting, so of N racing processes exactly one gets an +/// `Ok`, and that one is the leader. +/// +/// The lock is a *heartbeated lease*, not a once-only flag, and both halves of +/// that are deliberate: +/// +/// * Heartbeated, because a leader killed mid-migration must not wedge every +/// future boot, yet a leader that is merely slow must never be overtaken — +/// two processes in the DDL at once is the exact race being prevented. The +/// leader renews `claimed_at` every `MIGRATION_LOCK_HEARTBEAT_SECS` for as +/// long as it works, and a peer takes over only after +/// `MIGRATION_LOCK_LEASE_SECS` of silence. The price is that recovery from a +/// killed leader waits out the lease; the alternative, a plain age horizon, +/// would have to exceed the slowest imaginable migration to be safe. +/// * A lease, not a flag, because a boot an hour later may be a new binary with +/// new DDL and must re-apply, and because the data backfills (the chatbot +/// pending sweep above all) are meant to run on every restart. Only a boot +/// *inside* the lease trusts a peer's `applied_at` — i.e. exactly the +/// rolling-restart window — and only when that stamp carries this binary's own +/// [`migration_fingerprint`], so a mixed-version window cannot make the newer +/// process skip its own DDL. +/// +/// `wait` is how long a non-leader keeps polling before it fails the boot; a +/// parameter rather than a constant read inline so a test can prove that +/// deadline actually bites without sitting out `MIGRATION_LOCK_WAIT_SECS`. +async fn boot_once( + db: &Database, + admin: Option<(Username, Password)>, + wait: std::time::Duration, +) -> Result { + let lease_ms = MIGRATION_LOCK_LEASE_SECS * 1_000; + // Any unique string; the lock only ever compares it for equality. + let me = ulid::Ulid::new().to_string(); + // No query deadline anywhere in here on purpose: the SDK parks queries + // while the socket is down instead of failing them, so a timeout would + // report an outage as a dead leader and hand the migration to a second + // process (see `crate::error::AppError::DbTimeout`). + // + // The bootstrap step: the lock's own table has to exist before anyone can + // claim a row in it, so every process defines it (`IF NOT EXISTS`) rather + // than the leader — the leader is not known yet. N processes issuing that + // at once makes the key-value layer abort the losers with a retryable write + // conflict, and a conflict here means a rival committed the very definition + // we wanted, so it counts as success. + if let Err(err) = db + .query(MIGRATION_LOCK_DDL) + .await + .and_then(|response| response.check()) + && !lost_the_race(&err) + { + return Err(err.into()); + } + + let deadline = tokio::time::Instant::now() + wait; + loop { + if claim(db, MIGRATION_LOCK_CLAIM, &me, lease_ms).await? { + return leader_applies(db, &me, admin).await.map(|()| true); + } + let state: Option = db + .query(MIGRATION_LOCK_STATE) + .bind(("lease_ms", lease_ms)) + .bind(("fingerprint", migration_fingerprint())) + .await? + .check()? + .take(0)?; + match state { + // A live lease, stamped with our own fingerprint: the exact schema + // this process needs is in place, so stop waiting. + Some(state) if state.live && state.applied => { + tracing::info!(leader = %state.holder, "schema applied by another process"); + return Ok(false); + } + // Anything else may be takeable — the holder went silent past the + // lease, or it finished but with a different schema than ours. The + // statement's `WHERE` is the arbiter, so a live holder still inside + // the DDL refuses us and we fall through to waiting. + Some(state) if claim(db, MIGRATION_LOCK_TAKEOVER, &me, lease_ms).await? => { + tracing::warn!( + previous = %state.holder, + live = state.live, + "taking over the boot migration lock: the holder went silent or applied \ + a different schema" + ); + return leader_applies(db, &me, admin).await.map(|()| true); + } + Some(state) => { + tracing::debug!(leader = %state.holder, "waiting for the boot migration"); + } + // The row vanished; the next iteration's `CREATE` picks it up. + None => {} + } + if tokio::time::Instant::now() >= deadline { + // Loudly, not optimistically: SCHEMAFULL means an unmigrated + // database fails every write anyway, and it would do so as + // scattered 500s instead of one startup error. Exiting hands the + // retry to the container runtime, which is where boot retries live. + // + // One production sequence reaches this branch: a leader that keeps + // renewing its lease for longer than `wait` without ever stamping — + // a migration slower than `MIGRATION_LOCK_WAIT_SECS`. A leader that + // *stops* renewing never gets here, because the takeover above fires + // a lease (30s) rather than a wait (180s) after the last renewal. So + // the relative size of those two constants is not what selects this + // branch; "the lock stayed live-and-unstamped for the whole wait" + // is — which is precisely the state + // `a_live_lock_is_waited_for_and_the_wait_is_bounded` constructs, + // renewer and all, at a scaled-down wait. + return Err(AppError::Internal(format!( + "the boot migration lock stayed held for {wait:?}; \ + refusing to serve on a schema no process has confirmed" + ))); + } + tokio::time::sleep(std::time::Duration::from_millis(MIGRATION_LOCK_POLL_MS)).await; + } +} + +/// The lock row as a loser reads it. `live`/`applied` are computed by the +/// database so the verdict never depends on this process's clock. +#[derive(SurrealValue)] +struct LockState { + holder: String, + applied: bool, + live: bool, +} + +/// Run one of the two acquiring statements and report whether we now hold the +/// lock — both return our own holder id when we do, and nothing when a rival +/// got there first. +/// +/// Two failures mean "not ours", not "broken". "Already exists" is the +/// deterministic-id create losing the race, and a key-value *write conflict* is +/// the same race decided one layer down: when two processes create the same id +/// at genuinely the same instant, the loser's transaction is aborted as +/// retryable rather than answered with the duplicate-key message (observed on +/// every run of `two_concurrent_boots_apply_the_schema_once`). Either way the +/// caller loops, re-reads the lock and finds out who holds it — which is also +/// the retry the conflict asks for. +async fn claim(db: &Database, sql: &str, me: &str, lease_ms: i64) -> Result { + let result = db + .query(sql) + .bind(("me", me.to_string())) + .bind(("lease_ms", lease_ms)) + .bind(("fingerprint", migration_fingerprint())) + .await + .and_then(|response| response.check()); + match result { + Ok(mut response) => { + let holders: Vec = response.take(0)?; + Ok(holders.iter().any(|holder| holder == me)) + } + Err(err) if lost_the_race(&err) => Ok(false), + Err(err) => Err(err.into()), + } +} + +/// The two ways a rival's claim shows up as an error on ours: our `CREATE` hit +/// their row, or the key-value layer aborted our transaction because theirs +/// touched the same key first. +/// +/// Read from the *typed* error surface, not the message. Every conflict wording +/// the storage engines produce — surrealkv's "Transaction conflict: Write +/// conflict, retry the transaction. This transaction can be retried", +/// surrealmx's read-conflict variant, RocksDB's `Busy`/`TryAgain` — funnels +/// through one `KvsError::TransactionConflict` into +/// `QueryError::TransactionConflict` (surrealdb-core 3.2.3 +/// `err/to_types.rs:295`, `kvs/err.rs:64-179`), and a duplicate record id into +/// `AlreadyExistsError::Record` (`to_types.rs:206`). So the two checks below +/// cover all of them, where matching substrings covered only whichever wording +/// the engine of the day happened to use. +/// +/// The message fallback stays for one reason: these errors also travel over the +/// WebSocket, where the SDK rebuilds them from the wire (`Error::from_parts`), +/// and a server that omitted the typed details would otherwise turn a lost race +/// into a failed boot. Widest known wordings, cheap, and belt-and-braces. +fn lost_the_race(err: &surrealdb::Error) -> bool { + use surrealdb::types::{ErrorDetails, QueryError}; + if err.is_already_exists() + || matches!( + err.details(), + ErrorDetails::Query(Some(QueryError::TransactionConflict)) + ) + { + return true; + } + let message = err.to_string(); + message.contains("already exists") || message.contains("can be retried") +} + +/// A hash of the exact DDL and backfills this binary intends to apply. +/// +/// It is what makes a peer's "applied" stamp trustworthy. Without it, a process +/// booting inside the lease window trusts *any* finished predecessor — so a new +/// binary starting seconds after an old one stamped would skip its own newer +/// DDL and then serve on a schema missing the very fields its handlers write. +/// With it, "somebody applied a schema" narrows to "somebody applied *this* +/// schema", and anything else is treated as unapplied. +/// +/// Derived from the three SQL constants, never a hand-bumped version number: a +/// number nobody remembers to raise is worse than no check at all, while this +/// one changes on its own the moment the schema does. +fn migration_fingerprint() -> &'static str { + use sha2::{Digest, Sha256}; + static FINGERPRINT: std::sync::LazyLock = std::sync::LazyLock::new(|| { + let mut hasher = Sha256::new(); + // Length-prefixed, not concatenated: without a separator, moving a + // statement from one batch into the next leaves the byte stream — and so + // the fingerprint — unchanged, while changing what the boot actually + // does (batch boundaries are what keep the DDL out of the backfills). + for sql in MIGRATION_BATCHES { + hasher.update((sql.len() as u64).to_le_bytes()); + hasher.update(sql.as_bytes()); + } + for (name, value) in migration_binds() { + hasher.update(name.as_bytes()); + hasher.update(value.to_le_bytes()); + } + hex::encode(hasher.finalize()) + }); + &FINGERPRINT +} + +/// Leader path: keep the lease alive, apply everything, then stamp it done. +/// +/// The renewal runs *concurrently with* the work rather than after it, in the +/// same task: `select!` polls both, so a lease that cannot be renewed is +/// noticed while the DDL is still going instead of at the end. +async fn leader_applies( + db: &Database, + me: &str, + admin: Option<(Username, Password)>, +) -> Result<(), AppError> { + let apply = async { + migrate(db).await?; + if let Some((username, password)) = admin { + User::ensure_admin(username, password, db).await?; + } + Ok::<(), AppError>(()) + }; + tokio::select! { + applied = apply => applied?, + lost = renew_lease(db, me) => return Err(lost), + } + + let mut response = db + .query(MIGRATION_LOCK_STAMP) + .bind(("me", me.to_string())) + .bind(("fingerprint", migration_fingerprint())) + .await? + .check()?; + let stamped: Vec = response.take(0)?; + if stamped.is_empty() { + // The same verdict as a lost renewal, for the same reason — this is the + // backstop for losing the lock in the window between the last renewal + // and the stamp. + return Err(lost_lease()); + } + Ok(()) +} + +/// Renew the lease until it can no longer be renewed. Resolves *only* on that +/// loss, so it can sit opposite the real work in a `select!`. +/// +/// A refused renewal (empty result) means a peer declared us dead and took the +/// lock, so it is now applying the same DDL underneath us. We treat that as +/// fatal to this boot and stop: our statements are all idempotent, so there is +/// nothing to undo, but continuing would keep two processes writing schema at +/// once — the exact race this module exists to prevent — and would leave us +/// serving as if we had migrated. Failing hands the retry to the container +/// runtime, which re-elects cleanly. +/// +/// A renewal that *errors* is different: the socket may simply be down, and the +/// SDK parks queries rather than failing them, so a real error here is rare and +/// says nothing definite. Log it and keep trying — if it persists, the lease +/// expires, a peer takes over, and the next renewal is refused, which is the +/// verdict above. `.check()` is load-bearing: a statement-level failure comes +/// back inside an `Ok` response, so without it a renewal could fail forever +/// while logging nothing and renewing nothing. +async fn renew_lease(db: &Database, me: &str) -> AppError { + let mut interval = tokio::time::interval(std::time::Duration::from_secs( + MIGRATION_LOCK_HEARTBEAT_SECS, + )); + loop { + interval.tick().await; + match db + .query(MIGRATION_LOCK_HEARTBEAT) + .bind(("me", me.to_string())) + .await + .and_then(|response| response.check()) + { + Ok(mut response) => match response.take::>(0) { + Ok(holders) if holders.is_empty() => return lost_lease(), + Ok(_) => tracing::debug!("boot migration lease renewed"), + Err(err) => tracing::warn!("boot lock renewal returned unusable rows: {err}"), + }, + Err(err) => tracing::warn!("boot lock renewal failed: {err}"), + } + } +} + +fn lost_lease() -> AppError { + AppError::Internal( + "lost the boot migration lock while applying it — another process took it over and is \ + applying the schema, so this boot stops rather than race it" + .into(), + ) } /// Dial the database, retrying until it answers. @@ -77,19 +430,446 @@ pub async fn init_mem() -> Result { /// Apply the schema + backfills. Idempotent — `init` runs it on every boot, /// and tests re-run it on a live handle to simulate a second boot. pub async fn migrate(db: &Surreal) -> Result<(), AppError> { - db.query(PRE_REPAIR).await?.check()?; - db.query(MIGRATION).await?.check()?; - // Bound, not baked into the SQL string: a `const` cannot be interpolated - // into another `const`, and a hand-copied 300000 would drift silently. - db.query(BACKFILL) - .bind(("stale_ms", CHATBOT_PENDING_STALE_SECS * 1_000)) - .await? - .check()?; + for sql in MIGRATION_BATCHES { + let mut query = db.query(sql); + for (name, value) in migration_binds() { + query = query.bind((name, value)); + } + query.await?.check()?; + } Ok(()) } +/// Parameters the batches are executed with. Bound, not baked into the SQL +/// string: a `const` cannot be interpolated into another `const`, and a +/// hand-copied 300000 would drift silently. They are part of what the migration +/// *does*, so [`migration_fingerprint`] hashes them alongside the SQL — a +/// changed horizon is a changed migration. +fn migration_binds() -> [(&'static str, i64); 1] { + [("stale_ms", CHATBOT_PENDING_STALE_SECS * 1_000)] +} + #[cfg(test)] mod tests { + use super::{Database, boot_once}; + use crate::constant::{MIGRATION_LOCK_LEASE_SECS, MIGRATION_LOCK_TABLE}; + use crate::domain::user::{Password, Username}; + use std::time::Duration; + + /// An empty in-memory database with *no* schema — what a booting process + /// actually finds. [`super::init_mem`] cannot be used here: it migrates. + async fn unmigrated() -> Database { + let db = surrealdb::engine::any::connect("memory").await.unwrap(); + db.use_ns("hezarfen").use_db("hezarfen").await.unwrap(); + std::sync::Arc::new(db) + } + + fn admin() -> Option<(Username, Password)> { + Some(( + Username::try_new("root").unwrap(), + Password::try_new("secret1").unwrap(), + )) + } + + /// How many times the lock has been stamped applied — the observable side + /// effect that makes "exactly one process applied" checkable. + async fn applies(db: &Database) -> i64 { + let mut res = db + .query("SELECT VALUE applies FROM ONLY migration_lock:boot") + .await + .unwrap(); + res.take::>(0).unwrap().unwrap() + } + + /// How many `root` rows the seed left. Guarded on the table existing: a + /// waiter that failed its boot never ran the DDL, so `user` may be absent, + /// which is an error rather than an empty result. + async fn admin_count(db: &Database) -> i64 { + let mut res = db + .query( + "RETURN IF 'user' IN object::keys((INFO FOR DB).tables) { + array::len((SELECT id FROM user WHERE username = 'root')) + } ELSE { 0 };", + ) + .await + .unwrap(); + res.take::>(0).unwrap().unwrap() + } + + /// Two processes booting at once — the rolling-restart case, which happens + /// today without any replica work. Exactly one may run the DDL, the + /// backfills and the admin seed; the other has to wait for it and then + /// serve, not repeat it. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn two_concurrent_boots_apply_the_schema_once() { + let db = unmigrated().await; + let (a, b) = (db.clone(), db.clone()); + let one = + tokio::spawn(async move { boot_once(&a, admin(), Duration::from_secs(30)).await }); + let two = + tokio::spawn(async move { boot_once(&b, admin(), Duration::from_secs(30)).await }); + let (one, two) = (one.await.unwrap().unwrap(), two.await.unwrap().unwrap()); + + assert!(one ^ two, "exactly one process leads the boot: {one}/{two}"); + assert_eq!(applies(&db).await, 1, "the migration was applied once"); + assert_eq!(admin_count(&db).await, 1, "the admin was seeded once"); + // The loser still needs the schema it skipped applying. + assert!( + db.query("CREATE user:x SET username = 'x', password_hash = 'h'") + .await + .unwrap() + .check() + .is_ok(), + "the schema is in place once both boots return" + ); + } + + /// A leader killed mid-migration leaves its claim behind. Nothing may + /// require a human with a SurrealQL prompt to clear it: the next boot takes + /// the lease over once it has gone unrenewed past the horizon. + #[tokio::test] + async fn an_abandoned_lock_is_taken_over_by_the_next_boot() { + let db = unmigrated().await; + // Exactly what a SIGKILL at the worst moment leaves: claimed, never + // stamped, and no heartbeat since. + db.query( + "DEFINE TABLE migration_lock SCHEMALESS; + CREATE migration_lock:boot SET holder = 'dead', applies = 0, + claimed_at = time::unix(time::now()) * 1000 - ($lease + 1) * 1000;", + ) + .bind(("lease", MIGRATION_LOCK_LEASE_SECS)) + .await + .unwrap() + .check() + .unwrap(); + + assert!( + boot_once(&db, admin(), Duration::from_secs(5)) + .await + .unwrap(), + "the abandoned lock is taken over, not waited on" + ); + assert_eq!(applies(&db).await, 1); + assert_eq!(admin_count(&db).await, 1); + } + + /// The other side of that horizon: a lock claimed a moment ago belongs to a + /// process that is probably still working, so it is waited for — and if the + /// wait runs out the boot fails loudly instead of serving on a schema + /// nobody has confirmed. + #[tokio::test] + async fn a_live_lock_is_waited_for_and_the_wait_is_bounded() { + let db = unmigrated().await; + db.query( + "DEFINE TABLE migration_lock SCHEMALESS; + CREATE migration_lock:boot SET holder = 'busy', applies = 0, + claimed_at = time::unix(time::now()) * 1000;", + ) + .await + .unwrap() + .check() + .unwrap(); + + // A real leader renews; without a renewer this would test "the lease + // happened to still be inside its horizon", which is a different branch + // from the one production reaches (a leader slower than the wait). + let renewer = tokio::spawn({ + let db = db.clone(); + async move { + loop { + db.query(super::MIGRATION_LOCK_HEARTBEAT) + .bind(("me", "busy".to_string())) + .await + .unwrap() + .check() + .unwrap(); + tokio::time::sleep(Duration::from_millis(50)).await; + } + } + }); + let err = boot_once(&db, admin(), Duration::from_millis(600)) + .await + .expect_err("a held, unstamped lock must not let a boot through"); + renewer.abort(); + assert!( + err.to_string().contains("refusing to serve"), + "the boot fails loudly: {err}" + ); + assert_eq!(applies(&db).await, 0, "the waiter applied nothing"); + assert_eq!(admin_count(&db).await, 0, "and seeded nothing"); + } + + /// The rolling-deploy hole the fingerprint exists for: a peer stamped the + /// lock moments ago, inside the lease, so its lease is live and its work is + /// done — but it applied a *different* schema. Trusting that stamp means + /// serving on a database missing the fields this binary's own handlers + /// write. It must be treated as unapplied and taken over. + #[tokio::test] + async fn a_peers_stamp_for_a_different_schema_is_not_trusted() { + let db = unmigrated().await; + db.query( + "DEFINE TABLE migration_lock SCHEMALESS; + CREATE migration_lock:boot SET holder = 'old-binary', applies = 1, + claimed_at = time::unix(time::now()) * 1000, + applied_at = time::unix(time::now()) * 1000, + fingerprint = 'the DDL of some other build';", + ) + .await + .unwrap() + .check() + .unwrap(); + + assert!( + boot_once(&db, admin(), Duration::from_secs(5)) + .await + .unwrap(), + "a stamp from a different schema is no evidence about ours" + ); + assert_eq!(applies(&db).await, 2, "we applied ours on top"); + assert_eq!(admin_count(&db).await, 1); + let mut res = db + .query("SELECT VALUE fingerprint FROM ONLY migration_lock:boot") + .await + .unwrap(); + assert_eq!( + res.take::>(0).unwrap().as_deref(), + Some(super::migration_fingerprint()), + "and left our own fingerprint behind" + ); + } + + /// The same lock, stamped with *our* fingerprint, is the case the skip + /// exists for — otherwise every rolling restart re-runs the whole migration + /// and the peer's boot is pointless. + #[tokio::test] + async fn a_peers_stamp_for_our_own_schema_is_trusted() { + let db = unmigrated().await; + db.query( + "DEFINE TABLE migration_lock SCHEMALESS; + CREATE migration_lock:boot SET holder = 'peer', applies = 1, + claimed_at = time::unix(time::now()) * 1000, + applied_at = time::unix(time::now()) * 1000, + fingerprint = $fingerprint;", + ) + .bind(("fingerprint", super::migration_fingerprint())) + .await + .unwrap() + .check() + .unwrap(); + + assert!( + !boot_once(&db, admin(), Duration::from_secs(5)) + .await + .unwrap(), + "the peer applied this very schema, so this process just proceeds" + ); + assert_eq!(applies(&db).await, 1, "and applies nothing itself"); + } + + /// A hash of the same bytes, computed independently: the fingerprint has to + /// cover every batch, every bound value, and the boundaries between them. + /// Any of those left out is a schema change two binaries could disagree on + /// while claiming the same fingerprint. + #[test] + fn the_fingerprint_covers_every_batch_its_binds_and_the_boundaries() { + use sha2::{Digest, Sha256}; + let hash = |batches: &[String], binds: &[(&str, i64)]| { + let mut hasher = Sha256::new(); + for sql in batches { + hasher.update((sql.len() as u64).to_le_bytes()); + hasher.update(sql.as_bytes()); + } + for (name, value) in binds { + hasher.update(name.as_bytes()); + hasher.update(value.to_le_bytes()); + } + hex::encode(hasher.finalize()) + }; + let batches: Vec = crate::constant::MIGRATION_BATCHES + .iter() + .map(|sql| (*sql).to_string()) + .collect(); + let binds = super::migration_binds(); + assert_eq!(super::migration_fingerprint(), hash(&batches, &binds)); + + let mut edited = batches.clone(); + edited[2].push_str("-- one more backfill\n"); + assert_ne!( + super::migration_fingerprint(), + hash(&edited, &binds), + "an edited batch must change the fingerprint" + ); + // The boundary itself: the same bytes, one statement moved from the DDL + // batch into the backfill batch. Concatenation without a separator would + // hash these two arrangements identically. + let mut moved = batches.clone(); + let at = moved[1].len() - 20; + let tail = moved[1].split_off(at); + moved[2].insert_str(0, &tail); + assert_ne!( + super::migration_fingerprint(), + hash(&moved, &binds), + "moving text across a batch boundary must change the fingerprint" + ); + assert_ne!( + super::migration_fingerprint(), + hash(&batches, &[("stale_ms", 1)]), + "a changed bound value is a changed migration" + ); + } + + /// The forcing function behind all of that: `migrate` and + /// `migration_fingerprint` must read the *same* list. A fourth batch + /// executed by one and not hashed by the other would let two binaries with + /// different schemas claim the same fingerprint — and then skip each other's + /// migration, which is the whole hole the fingerprint was added to close. + #[test] + fn what_the_boot_executes_is_what_the_fingerprint_hashes() { + let source = + std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/database.rs")) + .expect("read database.rs"); + let body = |name: &str| { + let start = source.find(name).expect("function is declared"); + let rest = &source[start..]; + let end = rest.find("\n}\n").expect("function ends"); + rest[..end].to_string() + }; + for (name, body) in [ + ("pub async fn migrate", body("pub async fn migrate")), + ("fn migration_fingerprint", body("fn migration_fingerprint")), + ] { + assert!( + body.contains("MIGRATION_BATCHES") && body.contains("migration_binds()"), + "{name} must derive from MIGRATION_BATCHES + migration_binds(), \ + or the executed and the hashed migration can drift apart" + ); + } + let executed = body("pub async fn migrate"); + assert_eq!( + executed.matches("db.query(").count(), + 1, + "migrate() runs exactly one statement source — the batch list. A second \ + `db.query(...)` here is a batch the fingerprint does not hash:\n{executed}" + ); + } + + /// Path one of two: the renewal itself is refused. Driven straight at + /// `renew_lease` rather than through `leader_applies`, because inside the + /// `select!` a stamp failure would produce the same error and the test would + /// pass without this path working at all. + #[tokio::test] + async fn a_refused_renewal_ends_the_lease_fatally() { + let db = unmigrated().await; + db.query( + "DEFINE TABLE migration_lock SCHEMALESS; + CREATE migration_lock:boot SET holder = 'somebody-else', applies = 0, + claimed_at = time::unix(time::now()) * 1000;", + ) + .await + .unwrap() + .check() + .unwrap(); + + // Only ever resolves on a loss, so reaching this line is the assertion; + // the timeout is there to fail the test instead of hanging it. + let err = tokio::time::timeout(Duration::from_secs(5), super::renew_lease(&db, "me")) + .await + .expect("a renewal refused by the lock must resolve, not keep renewing"); + assert!( + err.to_string().contains("lost the boot migration lock"), + "{err}" + ); + } + + /// Path two: the lock is stolen *after* the last renewal, so nothing refuses + /// us until the stamp. The thief strikes while the DDL is running, far + /// inside the renewal interval, which is exactly the window the stamp + /// backstop exists for. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_lock_stolen_after_the_last_renewal_is_caught_by_the_stamp() { + let db = unmigrated().await; + db.query( + "DEFINE TABLE migration_lock SCHEMALESS; + CREATE migration_lock:boot SET holder = 'me', applies = 0, + claimed_at = time::unix(time::now()) * 1000;", + ) + .await + .unwrap() + .check() + .unwrap(); + let thief = tokio::spawn({ + let db = db.clone(); + async move { + tokio::time::sleep(Duration::from_millis(5)).await; + db.query("UPDATE migration_lock:boot SET holder = 'thief'") + .await + .unwrap() + .check() + .unwrap(); + } + }); + + let err = super::leader_applies(&db, "me", admin()) + .await + .expect_err("a leader that cannot stamp its own lock must not report success"); + thief.await.unwrap(); + assert!( + err.to_string().contains("lost the boot migration lock"), + "{err}" + ); + assert_eq!( + applies(&db).await, + 0, + "and the lock is not stamped as applied by us" + ); + } + + /// The admin seed must not be interruptible into a state no later boot can + /// repair. `create` + `set_role` was: killed between the two writes it + /// leaves a *student* row holding ADMIN_USERNAME, which `ensure_admin` then + /// refuses to promote on every subsequent boot (rightly — it cannot tell + /// that row from a stranger who registered the name first). The row is + /// therefore minted with its role in one statement, and this pins that. + #[test] + fn the_admin_seed_mints_the_role_with_the_row() { + let source = + std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/domain/user.rs")) + .expect("read user.rs"); + let start = source + .find("pub async fn ensure_admin") + .expect("ensure_admin is declared"); + let body = &source[start..start + source[start..].find("\n }\n").expect("body ends")]; + assert!( + !body.contains("set_role"), + "ensure_admin promotes after creating; an interruption between those two writes \ + leaves a student account on ADMIN_USERNAME that no boot can heal:\n{body}" + ); + assert!( + body.contains("create_with_role"), + "the seed must mint the row with Role::Admin in one statement" + ); + } + + /// The lock's table name is spelled in six places (the DDL and every + /// statement), and a rename that misses one would split the election in two + /// silently — every process would then "win" its own lock. + #[test] + fn every_lock_statement_names_the_lock_table() { + for sql in [ + crate::constant::MIGRATION_LOCK_DDL, + crate::constant::MIGRATION_LOCK_CLAIM, + crate::constant::MIGRATION_LOCK_STATE, + crate::constant::MIGRATION_LOCK_TAKEOVER, + crate::constant::MIGRATION_LOCK_HEARTBEAT, + crate::constant::MIGRATION_LOCK_STAMP, + ] { + assert!( + sql.contains(MIGRATION_LOCK_TABLE), + "{sql} does not name {MIGRATION_LOCK_TABLE}" + ); + } + } + #[tokio::test] async fn boot_fails_chatbot_messages_left_pending() { let db = super::init_mem().await.unwrap(); diff --git a/src/domain/chatbot_message.rs b/src/domain/chatbot_message.rs index bce63c2..e2c793c 100644 --- a/src/domain/chatbot_message.rs +++ b/src/domain/chatbot_message.rs @@ -1,9 +1,11 @@ //! One turn of a chatbot thread. Both sides are persisted: the user's prompt //! lands `complete`, and the assistant's row is written `pending` *before* the -//! AI call so a reload never loses an answer in flight. The task that owns the -//! bridge stream then flips it to `complete` (with the text) or `failed` (with -//! a code) — and if that task dies with the process, the boot sweep in -//! `database.rs` fails the row instead. +//! AI call so a reload never loses an answer in flight. A pending row is then +//! a durable *job*: whichever replica holds a `chat.reply` worker claims it +//! (`claim_pending`), dispatches it, and flips it to `complete` (with the text) +//! or `failed` (with a code). A claimer that dies loses its claim to the next +//! sweep, and the boot sweep in `database.rs` fails whatever nobody could +//! answer inside the staleness window. //! //! `user_id` is duplicated from the thread onto every message so an //! ownership check is one read, with no join. @@ -14,8 +16,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::{Generator, Ulid}; use crate::constant::{ - CHAT_MESSAGE_TABLE, CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, MAX_ERROR_CODE_LEN, - STALE_ERROR_CODE, + CHAT_MESSAGE_TABLE, CHATBOT_CLAIM, CHATBOT_CLAIM_BATCH, CHATBOT_CLAIM_RECLAIM_SECS, + CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, MAX_ERROR_CODE_LEN, STALE_ERROR_CODE, }; use crate::database::Database; use crate::domain::chatbot_thread::ChatbotThreadId; @@ -145,6 +147,15 @@ pub struct ChatbotMessage { error_code: Option, created_at: Timestamp, completed_at: Option, + /// Which replica's claim loop owes this turn an answer, and when it said + /// so. `None` means nobody has taken it; a claim older than + /// [`CHATBOT_CLAIM_RECLAIM_SECS`] is a claimer that died, and the turn goes + /// back on the queue (see [`ChatbotMessage::claim_pending`]). + /// + /// Never read by an HTTP handler and never in the DTO: whose process is + /// answering is deployment plumbing, not something a client can act on. + claimed_by: Option, + claimed_at: Option, } impl ChatbotMessage { @@ -233,6 +244,8 @@ impl ChatbotMessage { error_code: None, created_at: now, completed_at: Some(now), + claimed_by: None, + claimed_at: None, }, db, ) @@ -258,6 +271,8 @@ impl ChatbotMessage { error_code: None, created_at: Timestamp::now(), completed_at: None, + claimed_by: None, + claimed_at: None, }, db, ) @@ -337,6 +352,59 @@ impl ChatbotMessage { Ok(messages) } + /// Take up to [`CHATBOT_CLAIM_BATCH`] unanswered turns for the claimant + /// `me`, and hand back the rows now owed an answer by *this* process. + /// + /// The queue read. It is deliberately blind to which capabilities exist + /// anywhere: the caller has already asked its own in-process registry + /// whether it can answer, and that registry — never the `ai_worker` gate — + /// is what makes a claim honest. Claiming a turn this process cannot + /// dispatch would park it for a whole reclaim horizon. + /// + /// A lost race is not an error: the guard is re-evaluated per record inside + /// the `UPDATE`, so a row a peer took simply does not come back. A + /// transaction conflict is the same verdict one layer down and yields an + /// empty batch rather than a failure — the next poll re-reads the queue, + /// which is also the retry the conflict asks for. + pub async fn claim_pending(me: &str, db: &Database) -> Result, AppError> { + let result = db + .query(CHATBOT_CLAIM) + .bind(("me", me.to_string())) + .bind(("batch", CHATBOT_CLAIM_BATCH)) + .bind(("stale_ms", CHATBOT_PENDING_STALE_SECS * 1_000)) + .bind(("reclaim_ms", CHATBOT_CLAIM_RECLAIM_SECS * 1_000)) + .await + .and_then(|response| response.check()); + match result { + // Statement 0 is the `LET`; the claimed rows are statement 1. + Ok(mut response) => Ok(response.take::>(1)?), + Err(err) if lost_the_claim(&err) => Ok(Vec::new()), + Err(err) => Err(err.into()), + } + } + + /// The user turn this reserved answer belongs to: the newest `user` row + /// written before it in the same thread. + /// + /// Ordered by `created_at` then `id`, exactly like every other read path — + /// the two rows one POST writes routinely share a millisecond, so the id + /// tie-break is what keeps this from picking the prompt of the *previous* + /// turn (see [`IDS`]). + pub async fn prompt_for(&self, db: &Database) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM chatbot_message WHERE thread_id = $conv AND role = 'user' \ + AND (created_at < $at OR (created_at = $at AND id < $id)) \ + ORDER BY created_at DESC, id DESC LIMIT 1", + ) + .bind(("conv", self.thread_id.record())) + .bind(("at", self.created_at.as_millis())) + .bind(("id", self.id.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } + /// Read one turn only if `user` owns it — the poll loop's read. pub async fn read_for( id: &ChatbotMessageId, @@ -409,6 +477,23 @@ impl ChatbotMessage { } } +/// A concurrent claim that the key-value layer decided against us, rather than +/// a broken query. Read from the *typed* surface: every engine's conflict +/// wording funnels into `QueryError::TransactionConflict` (surrealdb-core +/// 3.2.3 `err/to_types.rs:295`), where a substring match covers only whichever +/// wording the engine of the day happens to use. +/// +/// Deliberately a second copy of `database::lost_the_race` rather than a shared +/// helper: that one is private to the boot election, which is owned elsewhere +/// and must not gain a caller. Five lines is the cheaper coupling. +fn lost_the_claim(err: &surrealdb::Error) -> bool { + use surrealdb::types::{ErrorDetails, QueryError}; + matches!( + err.details(), + ErrorDetails::Query(Some(QueryError::TransactionConflict)) + ) +} + #[cfg(test)] mod tests { use super::*; @@ -478,6 +563,28 @@ mod tests { } } + #[test] + fn the_claim_horizon_sits_between_the_inference_and_the_stale_window() { + // Both bounds are load-bearing and neither is decoration: + // below the AI request timeout, a reclaim fires while the first + // claimer is still legitimately waiting and two services answer the + // same turn; at or above the staleness horizon a turn stops being + // claimable before the reclaim could ever fire, so a dead claimer's + // turn is never retried at all. + use crate::constant::AI_DEFAULT_REQUEST_TIMEOUT_SECS; + assert!( + CHATBOT_CLAIM_RECLAIM_SECS > AI_DEFAULT_REQUEST_TIMEOUT_SECS as i64, + "a reclaim inside a legitimate inference double-answers the turn" + ); + #[allow(clippy::assertions_on_constants)] + { + assert!( + CHATBOT_CLAIM_RECLAIM_SECS < CHATBOT_PENDING_STALE_SECS, + "a reclaim horizon past the staleness window can never fire" + ); + } + } + #[tokio::test] async fn stale_pending_projects_as_failed() { let aged = |secs: i64| { @@ -492,6 +599,8 @@ mod tests { error_code: None, created_at: Timestamp::from_millis(Timestamp::now().as_millis() - secs * 1_000), completed_at: None, + claimed_by: None, + claimed_at: None, } .projected() }; diff --git a/src/domain/user.rs b/src/domain/user.rs index 61fe7db..25d131d 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -256,6 +256,21 @@ impl User { username: Username, password_hash: PasswordHash, db: &Database, + ) -> Result { + Self::create_with_role(username, password_hash, Role::Student, db).await + } + + /// The one row-minting path. `role` is written *with* the row rather than + /// patched on afterwards, which is what makes the admin seed atomic: a + /// create-then-promote pair can be interrupted between its halves (a SIGKILL, + /// or a cancelled future), and the row left behind is an ordinary student + /// account that [`User::ensure_admin`] must then refuse to touch — a + /// deployment with no admin and no way for a later boot to repair it. + async fn create_with_role( + username: Username, + password_hash: PasswordHash, + role: Role, + db: &Database, ) -> Result { if Self::find_by_username(username.as_str(), db) .await? @@ -267,7 +282,7 @@ impl User { id: UserId::generate(), username, password_hash, - role: Role::Student, + role, name: None, surname: None, email: None, @@ -320,8 +335,16 @@ impl User { Ok(()) } None => { - let created = Self::create(username, password.hash_async().await?, db).await?; - let admin = created.set_role(Role::Admin, db).await?; + // One statement, admin from birth. Never create-then-promote: + // an interruption between those two writes leaves a student row + // holding ADMIN_USERNAME, which the `Some(_)` arm above then + // refuses to promote — forever, on every subsequent boot. There + // is no marker that could tell such a row apart from a stranger + // who registered the name first, so the hole cannot be healed + // later; it has to be impossible to open. + let admin = + Self::create_with_role(username, password.hash_async().await?, Role::Admin, db) + .await?; tracing::info!(username = admin.username.as_str(), "seeded admin account"); Ok(()) } diff --git a/src/lib.rs b/src/lib.rs index 5f7e040..e09d18c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -42,7 +42,7 @@ use crate::state::AppState; (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /limits` publishes every fixed bound the API enforces — field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) — so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off)"), (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With no certificate configured the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"), - (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no AI service connected, sending answers `503` and writes nothing"), + (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is a claimed job rather than an in-process task: whichever backend process holds a `chat.reply` worker picks it up (within ~200ms), dispatches it and stamps the result, so a restart no longer strands an accepted turn and a claim its owner never finishes is retried after 90 seconds. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties), and a parent lists their own students at `/users/me/students`; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else"), (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"), (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), @@ -86,6 +86,17 @@ impl Modify for SecurityAddon { /// Also serves interactive docs: Swagger UI at `/swagger`, raw spec at /// `/api-docs/openapi.json`. Root `/` mirrors the health probe. pub fn build_router(state: AppState) -> Router { + // The AI bridge's two database-backed halves, wired here because this is + // the only place holding the bridge and the database at once: the + // `ai_worker` gate (so peers can see the workers this process holds) and + // this replica's chat claim loop. `attach_presence` returning `true` means + // this call was the first, which is what keeps it to one loop per process. + if let Some(bridge) = state.ai.clone() + && bridge.attach_presence(state.db.clone()) + { + web::chatbot::spawn_claim_loop(bridge, state.db.clone()); + } + let (router, api) = OpenApiRouter::with_openapi(ApiDoc::openapi()) .route("/", get(health)) .routes(routes!(health)) diff --git a/src/main.rs b/src/main.rs index 883b014..8e8afd2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,6 @@ use anyhow::Context; use hezarfen_backend::config::Config; use hezarfen_backend::database::Database; -use hezarfen_backend::domain::user::{Password, User, Username}; use hezarfen_backend::rate_limit::UserRateLimiter; use hezarfen_backend::state::{AppState, DbHealth}; use hezarfen_backend::{build_router, database}; @@ -17,11 +16,12 @@ async fn main() -> anyhow::Result<()> { .init(); let cfg = Config::from_env(); - let db = database::init(&cfg).await?; // Hash the login decoy now, so the first unknown-username login is not the // one request that pays for it (see `PasswordHash::prewarm_decoy`). hezarfen_backend::domain::user::PasswordHash::prewarm_decoy(); - seed_admin(&cfg, &db).await?; + // Schema *and* the admin seed: both are boot work that must happen once + // across overlapping processes, so both live behind the boot election. + let db = database::init(&cfg).await?; let db_up = DbHealth::default(); keepalive(db.clone(), db_up.clone()); tokio::fs::create_dir_all(&cfg.files_path) @@ -94,24 +94,6 @@ fn keepalive(db: Database, health: DbHealth) { }); } -/// Apply the `ADMIN_USERNAME` / `ADMIN_PASSWORD` bootstrap, if configured. -/// Both-or-neither: half a credential pair is a deployment mistake, so it -/// aborts startup rather than silently running without the seed. -async fn seed_admin(cfg: &Config, db: &Database) -> anyhow::Result<()> { - match (&cfg.admin_username, &cfg.admin_password) { - (Some(username), Some(password)) => { - let username = Username::try_new(username).context("invalid ADMIN_USERNAME")?; - let password = Password::try_new(password).context("invalid ADMIN_PASSWORD")?; - User::ensure_admin(username, password, db) - .await - .context("failed to seed the admin account")?; - Ok(()) - } - (None, None) => Ok(()), - _ => anyhow::bail!("ADMIN_USERNAME and ADMIN_PASSWORD must be set together"), - } -} - /// Resolve on SIGINT (Ctrl-C) or SIGTERM. As PID 1 in a container the process /// gets no default signal handling, so without this a `podman stop` waits out /// its grace period and SIGKILLs us — dropping in-flight requests mid-write. diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index b373821..3436bac 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -7,10 +7,16 @@ //! //! Sending is asynchronous by design. `POST .../messages` writes the user's //! turn plus an empty `pending` assistant row and answers `202` immediately; -//! the bridge round trip happens in a spawned task, because an inference can -//! outlast the request-timeout layer that guards every HTTP handler. The client -//! then either polls `GET .../messages/{mid}` or opens its SSE stream — both -//! read the same row, so they can never disagree. +//! an inference can outlast the request-timeout layer that guards every HTTP +//! handler, so nothing is awaited on the request path. The client then either +//! polls `GET .../messages/{mid}` or opens its SSE stream — both read the same +//! row, so they can never disagree. +//! +//! The pending row *is* the job. It used to be answered by a `tokio::spawn` +//! from the POST, which meant a restart orphaned every turn in flight; since +//! 2026-07-27 it is claimed off the database by [`spawn_claim_loop`], so the +//! turn is answered by whichever process holds a `chat.reply` worker — the one +//! that accepted it, a peer replica, or the one that comes up after a restart. use std::time::Duration; @@ -29,9 +35,10 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::ai::chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn}; -use crate::ai::{AiBridge, AiError}; +use crate::ai::{AiBridge, AiError, presence}; use crate::constant::{ - AI_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN, MIN_CHUNK_CHARS, REPLY_CHUNKS, + AI_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, CHATBOT_CLAIM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN, + MIN_CHUNK_CHARS, REPLY_CHUNKS, }; use crate::database::Database; use crate::domain::chatbot_message::{ @@ -345,12 +352,17 @@ async fn list_messages( /// answer itself lands later, in the reserved assistant row. /// /// Order matters and is deliberate: the per-user rate limit is charged -/// *before* anything is written, so a refused turn leaves no trace; the AI -/// bridge is checked for a `chat.reply` worker *before* the rows exist, so an -/// unavailable service produces a `503` and no dead pending row. Once the rows -/// are written the turn always settles — the answering task stamps -/// `complete`/`failed`, a reader projects a long-stale `pending` as failed, and -/// the boot sweep repairs whatever a process death left behind. +/// *before* anything is written, so a refused turn leaves no trace; +/// availability is checked *before* the rows exist, so an unavailable service +/// produces a `503` and no dead pending row. +/// +/// The pending row is a claimed job, not an in-process task: whichever backend +/// process holds a `chat.reply` worker picks it up (within ~200ms) and answers +/// it, so a restart no longer strands the turn — and a process with no worker +/// of its own still accepts turns its peers can answer. The turn always +/// settles: the claiming process stamps `complete`/`failed`, a claim its owner +/// never finishes is retried, a reader projects a long-stale `pending` as +/// failed, and the boot sweep repairs the rest. #[utoipa::path( post, path = "/threads/{id}/messages", @@ -389,21 +401,32 @@ async fn send_message( } let content = ChatContent::try_new(&req.content)?; - // The 503 gate, and the only place it is evaluated. `has_capability` is - // documented racy — that is fine here: it never guards a write, it only - // spares the user a thread full of rows nothing could ever answer. - let Some(bridge) = st.ai.clone() else { + // The 503 gate, and the only place it is evaluated. Two questions, asked + // cheapest first, and neither of them guards a write — the gate only + // spares the user a thread full of rows nothing could ever answer: + // + // 1. can *this* replica answer? — the in-process registry, which owns + // the sockets. Authoritative and free, so it is asked first, which is + // also why a single-replica deployment pays no round trip here. + // 2. can any *other* replica? — the heartbeated `ai_worker` table, which + // may lag reality by a heartbeat in either direction. A yes here is + // not a promise that this process can do anything: the turn is + // written and a peer's claim loop picks it up. + // + // Neither answer decides who dispatches. That is the claim loop's own + // registry, every time (see `crate::ai::presence`). + let Some(bridge) = st.ai.as_ref() else { return Ok(unavailable( "the AI service is not enabled on this deployment", )); }; - if !bridge.has_capability(AI_CHAT_CAPABILITY) { + if !bridge.has_capability(AI_CHAT_CAPABILITY) + && !presence::serves(&st.db, AI_CHAT_CAPABILITY).await + { return Ok(unavailable("no AI service is connected right now")); } - let prompt = - ChatbotMessage::append_user(thread.get_id(), user.get_id(), content.clone(), &st.db) - .await?; + ChatbotMessage::append_user(thread.get_id(), user.get_id(), content, &st.db).await?; let answer = ChatbotMessage::append_pending_assistant(thread.get_id(), user.get_id(), &st.db).await?; // Never fatal: both rows are already written, and failing here would strand @@ -417,17 +440,11 @@ async fn send_message( ); } - // Never awaited inline: the bridge round trip can outlast the request - // timeout that guards every handler, and the POST must return now. - tokio::spawn(answer_turn( - bridge, - st.db.clone(), - thread.get_id().clone(), - [prompt.get_id().clone(), answer.get_id().clone()], - content.as_str().to_string(), - settings.get_chatbot_history_turns().max(0) as usize, - reply_cap, - )); + // Nothing is dispatched here, deliberately. The pending row *is* the job: + // a claim loop — this replica's or a peer's — takes it within one + // `CHATBOT_CLAIM_POLL_MS` tick and answers it. An in-process + // `tokio::spawn` could not survive the restart that orphans the turn, + // which is the whole failure this queue removes. Ok(( StatusCode::ACCEPTED, @@ -457,31 +474,112 @@ fn unavailable(message: &str) -> Response { .into_response() } -/// Fetch one answer and settle its row. Runs detached from the request. +/// This replica's share of the chat work queue. +/// +/// One task per process, started by [`crate::build_router`] when a bridge is +/// configured. Every [`CHATBOT_CLAIM_POLL_MS`] it asks *its own* registry +/// whether it can serve `chat.reply` and, if so, claims a small batch of +/// unanswered turns and dispatches them. +/// +/// The registry is the only thing consulted, never the `ai_worker` gate: the +/// gate can say a peer has a worker, and claiming on that word would park the +/// turn here for a whole reclaim horizon with no socket to send it down (see +/// [`crate::ai::presence`]). +/// +/// ponytail: no shutdown handle — the loop runs for the life of the process, +/// which is the life of the bridge, and it is idle (one registry read per +/// tick, no query) whenever this replica holds no chat worker. Give it a +/// `CancellationToken` the day the bridge itself becomes restartable. +pub fn spawn_claim_loop(bridge: AiBridge, db: Database) { + // Any unique string. It is only ever compared for equality and read in a + // log line: a claim identifies the *process*, and a claim nobody renews + // expires by age rather than by anyone recognising the claimant. + let me = ulid::Ulid::new().to_string(); + tokio::spawn(async move { + let mut ticker = tokio::time::interval(Duration::from_millis(CHATBOT_CLAIM_POLL_MS)); + ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + ticker.tick().await; + // The DISPATCHER's answer, and the gate that matters here. + if !bridge.has_capability(AI_CHAT_CAPABILITY) { + continue; + } + let claimed = match ChatbotMessage::claim_pending(&me, &db).await { + Ok(claimed) => claimed, + Err(err) => { + tracing::warn!("could not claim chat turns: {err}"); + continue; + } + }; + if claimed.is_empty() { + continue; + } + // Read once per batch, not per turn. Unlike the old in-process + // spawn this is the policy live when the turn is *answered* rather + // than when it was accepted — unavoidable once the answering + // process may not be the accepting one, and the window is one poll + // tick wide in the normal case. + let settings = match Settings::load(&db).await { + Ok(settings) => settings, + Err(err) => { + tracing::warn!("could not load settings for a claimed chat turn: {err}"); + continue; + } + }; + let reply_cap = content_cap(&settings); + let history_turns = settings.get_chatbot_history_turns().max(0) as usize; + for answer in claimed { + // One task per turn: the bridge round trip can take tens of + // seconds and must not hold up the next poll. + tokio::spawn(answer_turn( + bridge.clone(), + db.clone(), + answer, + history_turns, + reply_cap, + )); + } + } + }); +} + +/// Fetch one claimed turn's answer and settle its row. /// /// Every path settles: a row left `pending` would show as a spinner forever. -/// The settings snapshot is passed in rather than re-read — the whole turn is -/// then judged by the policy that was live when it was accepted, and a manager -/// editing the limits mid-flight cannot make the answer be measured by a rule -/// the prompt never saw (it also saves a database round trip per turn). -#[allow(clippy::too_many_arguments)] async fn answer_turn( bridge: AiBridge, db: Database, - thread: ChatbotThreadId, - // The two rows this turn just wrote; both are excluded from the history. - fresh: [ChatbotMessageId; 2], - prompt: String, + answer: ChatbotMessage, history_turns: usize, reply_cap: usize, ) { - let answer_id = fresh[1].clone(); + let answer_id = answer.get_id().clone(); + let thread = answer.get_thread_id().clone(); + // The question this reserved row was written next to. Recovered from the + // thread rather than carried in memory, because the process that accepted + // the turn may no longer exist. + let prompt = match answer.prompt_for(&db).await { + Ok(Some(prompt)) => prompt, + Ok(None) => { + // A reserved answer with no question before it. Only reachable if + // the user row was deleted out from under it; there is nothing to + // ask, so settle rather than re-claim it every reclaim horizon. + tracing::warn!("chat answer {} has no prompt to send", answer_id.key()); + let _ = ChatbotMessage::fail(&answer_id, "internal", &db).await; + return; + } + Err(err) => { + tracing::warn!("could not read the prompt for {}: {err}", answer_id.key()); + return; + } + }; + let fresh = [prompt.get_id().clone(), answer_id.clone()]; let settled = match fetch_reply( &bridge, &db, &thread, &fresh, - prompt, + prompt.get_content().as_str().to_string(), history_turns, reply_cap, ) diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index 4512c03..49d0c69 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -1162,6 +1162,227 @@ async fn a_blank_chat_answer_fails_as_empty_reply() { assert_eq!(turn["error_code"], "empty_reply"); } +// ----------------------------------------------------------- claim queue -- +// +// A pending assistant row is a durable job, not an in-process task. These +// prove the three things that buys: a turn nobody could answer yet is answered +// when a worker appears, a claim whose owner died is taken back, and a turn is +// dispatched exactly once no matter how many replicas are watching the queue. + +use hezarfen_backend::constant::{CHATBOT_CLAIM_POLL_MS, CHATBOT_CLAIM_RECLAIM_SECS}; +use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage}; +use hezarfen_backend::domain::chatbot_thread::ChatbotThreadId; +use hezarfen_backend::domain::user::UserId; + +/// Write one turn's two rows straight to the queue, bypassing the POST — what +/// a replica that has since died would have left behind. Returns the reserved +/// assistant row's key. +async fn queue_turn(app: &Router, db: &Database, cookie: &str, thread: &str, text: &str) -> String { + let me = common::send(app, "GET", "/auth/me", Some(cookie), None).await; + let user = UserId::from_key(me.body["id"].as_str().expect("own id")); + let thread = ChatbotThreadId::from_key(thread); + ChatbotMessage::append_user(&thread, &user, ChatContent::try_new(text).unwrap(), db) + .await + .expect("the user's turn"); + ChatbotMessage::append_pending_assistant(&thread, &user, db) + .await + .expect("the reserved answer") + .get_id() + .key() + .to_string() +} + +/// A turn nobody has claimed, held by `claimant` since `age_secs` ago. +async fn stamp_claim(db: &Database, mid: &str, claimant: &str, age_secs: i64) { + db.query( + "UPDATE $id SET claimed_by = $who, claimed_at = time::unix(time::now()) * 1000 - $age", + ) + .bind(("id", RecordId::new("chatbot_message", mid.to_string()))) + .bind(("who", claimant.to_string())) + .bind(("age", age_secs * 1_000)) + .await + .expect("stamp a claim") + .check() + .expect("stamp a claim"); +} + +async fn status_of(app: &Router, cookie: &str, thread: &str, mid: &str) -> String { + let res = common::send( + app, + "GET", + &format!("/chatbot/threads/{thread}/messages/{mid}"), + Some(cookie), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + res.body["status"].as_str().expect("status").to_string() +} + +#[tokio::test] +async fn a_turn_written_with_no_worker_is_answered_once_one_appears() { + // The failure this queue removes: the row used to be answered by a task + // spawned inside the POST, so a turn that outlived its process — or was + // written while nothing could serve it — settled `failed` at the staleness + // horizon and never got an answer at all. + let bridge = bridge().await; + let (app, db) = chat_app(&bridge).await; + let (cookie, thread) = chat_user(&app, "ali").await; + + // Nothing is connected, so the gate refuses the POST outright… + let res = common::send( + &app, + "POST", + &format!("/chatbot/threads/{thread}/messages"), + Some(&cookie), + Some(json!({ "content": "kimse yokken" })), + ) + .await; + assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body); + + // …but a row already on the queue (written by a replica that has since + // gone) must still be picked up. + let mid = queue_turn(&app, &db, &cookie, &thread, "kimse yokken").await; + let _service = connect_service( + &bridge, + hello("tutor", &[AI_CHAT_CAPABILITY]), + Behaviour::Reply("geç gelen cevap".into()), + ) + .await; + await_workers(&bridge, 1).await; + + let turn = settled(&app, &cookie, &thread, &mid).await; + assert_eq!(turn["status"], "complete", "{turn}"); + assert_eq!(turn["content"], "geç gelen cevap"); +} + +#[tokio::test] +async fn a_claim_left_by_a_dead_replica_is_taken_back() { + let bridge = bridge().await; + let service = connect_service( + &bridge, + hello("tutor", &[AI_CHAT_CAPABILITY]), + Behaviour::Reply("devraldım".into()), + ) + .await; + await_workers(&bridge, 1).await; + let (app, db) = chat_app(&bridge).await; + let (cookie, thread) = chat_user(&app, "ali").await; + + // A claim a peer took moments ago is respected: that peer is presumably + // still waiting on its inference, and answering alongside it would run the + // model twice for one reply. + let live = queue_turn(&app, &db, &cookie, &thread, "başkası bakıyor").await; + stamp_claim(&db, &live, "a-live-peer", 1).await; + for _ in 0..10 { + tokio::time::sleep(Duration::from_millis(CHATBOT_CLAIM_POLL_MS)).await; + } + assert_eq!( + status_of(&app, &cookie, &thread, &live).await, + "pending", + "a live peer's claim was stolen" + ); + assert!(service.seen().is_empty(), "{:?}", service.seen()); + + // The same claim, past the reclaim horizon, is a claimant that died. The + // turn goes back on the queue rather than waiting out its staleness + // window with nobody answering it. + stamp_claim(&db, &live, "a-dead-peer", CHATBOT_CLAIM_RECLAIM_SECS + 1).await; + let turn = settled(&app, &cookie, &thread, &live).await; + assert_eq!(turn["status"], "complete", "{turn}"); + assert_eq!(turn["content"], "devraldım"); + assert_eq!(service.seen().len(), 1, "{:?}", service.seen()); +} + +#[tokio::test] +async fn a_claimed_turn_is_dispatched_exactly_once() { + // The claim is what stops the poll loop from re-sending a turn every tick + // while the first inference is still running. A silent service holds the + // stream open, so every extra dispatch would show up in `seen()`. + let bridge = bridge_with_timeout(Duration::from_secs(30)).await; + let service = connect_service( + &bridge, + hello("tutor", &[AI_CHAT_CAPABILITY]), + Behaviour::Silent, + ) + .await; + await_workers(&bridge, 1).await; + let (app, _db) = chat_app(&bridge).await; + let (cookie, thread) = chat_user(&app, "ali").await; + + let mid = ask(&app, &cookie, &thread, "uzun sürecek bir soru").await; + await_inflight(&bridge, 1).await; + // Ten poll ticks with the answer still outstanding. + tokio::time::sleep(Duration::from_millis(CHATBOT_CLAIM_POLL_MS * 10)).await; + assert_eq!( + service.seen().len(), + 1, + "one turn, one dispatch: {:?}", + service.seen() + ); + assert_eq!(status_of(&app, &cookie, &thread, &mid).await, "pending"); +} + +#[tokio::test] +async fn a_replica_with_no_worker_accepts_a_turn_its_peer_answers() { + // Two replicas, one database, and the worker dialled into exactly one of + // them. The other has nothing to dispatch with — its own registry says so + // — yet it must still accept the turn, because the `ai_worker` gate can + // see its peer. And exactly one of the two answers it. + let db = hezarfen_backend::database::init_mem() + .await + .expect("mem db"); + let quiet = bridge().await; + let serving = bridge().await; + let app_quiet = replica(&quiet, &db); + let app_serving = replica(&serving, &db); + + let service = connect_service( + &serving, + hello("tutor", &[AI_CHAT_CAPABILITY]), + Behaviour::Reply("komşudan cevap".into()), + ) + .await; + await_workers(&serving, 1).await; + assert!(!quiet.has_capability(AI_CHAT_CAPABILITY), "no local worker"); + // The gate is heartbeated, so give the serving replica's first beat time + // to publish its worker before asking the replica that holds none. + for _ in 0..300 { + if hezarfen_backend::ai::presence::serves(&db, AI_CHAT_CAPABILITY).await { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + + let (cookie, thread) = chat_user(&app_quiet, "ali").await; + let mid = ask(&app_quiet, &cookie, &thread, "komşuya soru").await; + let turn = settled(&app_quiet, &cookie, &thread, &mid).await; + assert_eq!(turn["status"], "complete", "{turn}"); + assert_eq!(turn["content"], "komşudan cevap"); + assert_eq!(service.seen().len(), 1, "{:?}", service.seen()); + // The answer is one row, so the peer that accepted the turn reads exactly + // what the peer that answered it wrote. + assert_eq!( + status_of(&app_serving, &cookie, &thread, &mid).await, + "complete" + ); +} + +/// A second process against the same database: its own bridge, its own claim +/// loop, one shared queue. +fn replica(bridge: &AiBridge, db: &Database) -> Router { + hezarfen_backend::build_router(hezarfen_backend::state::AppState { + db: db.clone(), + files_path: common::files_dir(), + cookie_secure: false, + rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), + chatbot_limit: Default::default(), + exam_presence: Default::default(), + db_up: Default::default(), + ai: Some(bridge.clone()), + }) +} + // ------------------------------------------------------------- boot wiring -- // // `ai::start_bridge` is the seam between deployment config and the listener. diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs index 2c6347d..9ba4ff5 100644 --- a/tests/limits_completeness.rs +++ b/tests/limits_completeness.rs @@ -51,6 +51,10 @@ const EXCLUDED: &[(&str, &str)] = &[ ("AI_ALPN", "QUIC bridge ALPN"), ("AI_MAX_FRAME_BYTES", "QUIC bridge frame ceiling"), ("AI_DEFAULT_REQUEST_TIMEOUT_SECS", "AI inference deadline"), + ( + "AI_MAX_REQUEST_TIMEOUT_SECS", + "ceiling on the configured AI inference deadline", + ), ("AI_MAX_CONCURRENT_PER_WORKER", "AI worker concurrency cap"), ( "AI_DEFAULT_CONCURRENT_PER_WORKER", @@ -71,6 +75,30 @@ const EXCLUDED: &[(&str, &str)] = &[ "CHATBOT_PENDING_STALE_SECS", "when a stuck answer is declared failed", ), + // The AI worker gate (`ai_worker`) and the chat claim queue. Both are + // between-replica plumbing: a browser cannot observe which process holds a + // worker or who claimed its turn, and it already learns everything it can + // act on from the 202/503 and the turn's own `status`. + ("AI_WORKER_TABLE", "AI worker presence table"), + ("AI_WORKER_ANNOUNCE", "AI worker presence upsert"), + ("AI_WORKER_WITHDRAW", "AI worker presence delete"), + ("AI_WORKER_SWEEP", "AI worker presence expiry"), + ("AI_WORKER_SERVES", "AI worker presence read"), + ( + "AI_WORKER_HEARTBEAT_SECS", + "how often a replica restamps its AI workers", + ), + ( + "AI_WORKER_LEASE_SECS", + "how long an unrestamped AI worker row is believed", + ), + ("CHATBOT_CLAIM", "chat claim-queue statement"), + ("CHATBOT_CLAIM_POLL_MS", "chat claim-loop cadence"), + ("CHATBOT_CLAIM_BATCH", "turns claimed per sweep"), + ( + "CHATBOT_CLAIM_RECLAIM_SECS", + "when a dead claimer's turn goes back on the queue", + ), // Seed data for the settings singleton, not a bound. The live list is on // `GET /settings`, which is where a client must read it — publishing the // default too would invite rendering it instead of the school's actual one. @@ -89,6 +117,29 @@ const EXCLUDED: &[(&str, &str)] = &[ // Schema and query text. `constant.rs` is the single home for every // constant, so the migration batches live there too — a client never sees // a byte of SurrealQL. + // The boot leader election. A client never sees the lock, and the timings + // are startup mechanics between processes — publishing them would invite a + // frontend to reason about a boot it cannot observe. + ("MIGRATION_LOCK_DDL", "boot lock table definition"), + ("MIGRATION_LOCK_CLAIM", "boot lock claim statement"), + ("MIGRATION_LOCK_STATE", "boot lock read statement"), + ("MIGRATION_LOCK_TAKEOVER", "boot lock takeover statement"), + ("MIGRATION_LOCK_HEARTBEAT", "boot lock lease renewal"), + ("MIGRATION_LOCK_STAMP", "boot lock completion stamp"), + ( + "MIGRATION_LOCK_LEASE_SECS", + "how long an unrenewed boot lock may be taken over after", + ), + ("MIGRATION_LOCK_HEARTBEAT_SECS", "boot lock renewal cadence"), + ( + "MIGRATION_LOCK_WAIT_SECS", + "how long a non-leader waits for the boot migration", + ), + ("MIGRATION_LOCK_POLL_MS", "boot lock poll cadence"), + ( + "MIGRATION_BATCHES", + "the batch list the boot executes and fingerprints", + ), ("PRE_REPAIR", "pre-DDL data repair batch"), ("MIGRATION", "SCHEMAFULL DDL batch"), ("BACKFILL", "post-DDL data backfill batch"),