forge
Explore
Log in

Don't you dare go Hollow

🗳️ elect the boot, and make a chat turn a claimed job

Browse files at this commit

0787b145e9b1733a083a689faca6747d8b9d8081Ahmet Kaan GümüşParent: 57df6b3
  • feat
    • 🗳️ elect the boot, and make a chat turn a claimed job
Show full message
feat: 🗳️ elect the boot, and make a chat turn a claimed job

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.

14 changed files +2001 -114

README.mdmodified+23 -7
@@ -2183,23 +2183,39 @@ agree about `truncated` exactly as they do about every other field.
21832183 | `404` | no such thread or message — or not the caller's |
21842184 | `409` | already at `max_chatbot_threads`; delete a thread first |
21852185 | `429` | over `RATE_LIMIT_CHATBOT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` |
2186-| `503` | no connected service offers `chat.reply` — **nothing was written**, retry later |
2186+| `503` | no service anywhere in the deployment offers `chat.reply` — **nothing was written**, retry later |
21872187
2188-The `503` ordering matters: the bridge is checked before the rows exist, so an
2189-unavailable service leaves no dead `pending` row behind, and the rate limit is
2190-charged before that, so a refused turn leaves no trace at all.
2188+The `503` ordering matters: availability is checked before the rows exist, so
2189+an unavailable service leaves no dead `pending` row behind, and the rate limit
2190+is charged before that, so a refused turn leaves no trace at all. The check
2191+asks two questions — is a `chat.reply` worker connected to *this* backend
2192+process, and failing that, is one connected to any other — so a deployment
2193+running several backends accepts a turn as long as one of them can answer it.
2194+
2195+### A turn is a claimed job
2196+
2197+The `pending` assistant row *is* the work item. Backend processes poll it: a
2198+process holding a `chat.reply` worker claims an unanswered turn, dispatches it
2199+over its own connection, and stamps the result. That is why a `202` is a real
2200+promise — a backend restart no longer strands the turn it had just accepted,
2201+and a turn accepted by a process with no worker of its own is answered by one
2202+that has. The cost is up to ~200 ms before the request leaves for the service.
2203+A claim whose owner disappears is taken back after 90 seconds.
21912204
21922205 ### A turn always settles
21932206
21942207 Once the two rows exist the answer never stays `pending` forever, through
21952208 three independent mechanisms:
21962209
2197-- the answering task stamps `complete` or `failed` itself — the normal path;
2210+- the process that claimed the turn stamps `complete` or `failed` — the normal
2211+ path, and a claim its owner never finishes is retried by another;
21982212 - a reader **projects** a `pending` row older than 300 seconds as
21992213 `failed`/`timed_out` (a read-time projection, not a write — the row is left
22002214 for the task that may still own it);
2201-- a **boot sweep** flips every leftover `pending` to `failed`/`interrupted`,
2202- which is what a process death mid-inference looks like.
2215+- a **boot sweep** flips every leftover `pending` past the 300-second horizon
2216+ to `failed`/`interrupted`, which is what a process death mid-inference looks
2217+ like. It leaves rows another process has claimed recently alone, so a
2218+ restarting backend cannot shoot down a turn its peer is answering.
22032219
22042220 Two more verdicts come from inspecting the answer: an **empty** reply is
22052221 reported as `failed`/`empty_reply` (a blank bubble is indistinguishable from a
src/ai/mod.rsmodified+3 -1
@@ -14,7 +14,8 @@
1414 //! * [`protocol`] — frames on the wire
1515 //! * [`chat`] — the JSON payloads carried for the `chat.reply` capability
1616 //! * [`server`] — the listener, handshake, and [`server::AiBridge::dispatch`]
17-//! * [`registry`] — who is connected and who gets the next request
17+//! * [`registry`] — who is connected here, and who gets the next request
18+//! * [`presence`] — who is connected *anywhere*, for a cross-replica gate
1819 //! * [`tls`] — the listener's certificate
1920 //!
2021 //! The transport is generic; the features land on top of it. So far that is
@@ -22,6 +23,7 @@
2223
2324 pub mod chat;
2425 pub mod error;
26+pub mod presence;
2527 pub mod protocol;
2628 pub mod registry;
2729 pub mod server;
src/ai/presence.rsadded+188 -0
@@ -0,0 +1,188 @@
1+//! Who can serve which AI capability *anywhere in the deployment* — the GATE.
2+//!
3+//! There are two answers to "is an AI service available", and confusing them
4+//! is the one way this module can do damage, so they are named:
5+//!
6+//! * **The gate — this module, the `ai_worker` table.** It answers "could
7+//! anything, anywhere, serve `chat.reply`?". Every replica writes a row for
8+//! each worker whose QUIC connection *it* holds and restamps it every
9+//! [`AI_WORKER_HEARTBEAT_SECS`]; a row unstamped for
10+//! [`AI_WORKER_LEASE_SECS`] is ignored and swept, so a replica that dies
11+//! leaves no permanent phantom. It is a cache of other processes' sockets:
12+//! it lags a registration by up to one heartbeat and a crash by up to one
13+//! lease, in *both* directions. Its only job is to spare a user a 503 on a
14+//! replica that holds no worker itself, because a peer's claim loop will
15+//! answer the turn. It must never guard a write and must never decide a
16+//! dispatch.
17+//! * **The dispatcher — [`crate::ai::registry::Registry`], in process.** It
18+//! owns the sockets. Only it knows whether *this* replica can answer, and it
19+//! is the only thing the chat claim loop consults before taking a turn. A
20+//! claim made on the gate's word would park a turn on a replica with nothing
21+//! to send it to.
22+//!
23+//! The split is why the table is safe to be wrong: nothing downstream of a
24+//! wrong answer is irreversible. A false yes costs one accepted turn that
25+//! settles `failed` (or waits out its staleness window); a false no costs one
26+//! 503 the user can retry.
27+
28+use surrealdb::types::RecordId;
29+
30+use crate::ai::registry::WorkerSnapshot;
31+use crate::constant::{
32+ AI_WORKER_ANNOUNCE, AI_WORKER_LEASE_SECS, AI_WORKER_SERVES, AI_WORKER_SWEEP, AI_WORKER_TABLE,
33+ AI_WORKER_WITHDRAW,
34+};
35+use crate::database::Database;
36+use crate::error::AppError;
37+
38+fn row(id: &str) -> RecordId {
39+ RecordId::new(AI_WORKER_TABLE, id)
40+}
41+
42+/// Publish (or restamp) the workers this replica holds right now.
43+///
44+/// `UPSERT` per worker, and the caller passes the whole live set every
45+/// heartbeat: a row lost to a database blip, or a worker that registered
46+/// before the presence table was attached, heals on the next beat instead of
47+/// staying invisible to every peer forever.
48+pub async fn announce(db: &Database, workers: &[WorkerSnapshot]) -> Result<(), AppError> {
49+ for worker in workers {
50+ db.query(AI_WORKER_ANNOUNCE)
51+ .bind(("id", row(&worker.id)))
52+ .bind(("service", worker.service.clone()))
53+ .bind(("capabilities", worker.capabilities.clone()))
54+ .await?
55+ .check()?;
56+ }
57+ Ok(())
58+}
59+
60+/// Drop a worker that said goodbye. Immediate, so a clean disconnect closes
61+/// the gate now rather than a lease later.
62+pub async fn withdraw(db: &Database, id: &str) -> Result<(), AppError> {
63+ db.query(AI_WORKER_WITHDRAW)
64+ .bind(("id", row(id)))
65+ .await?
66+ .check()?;
67+ Ok(())
68+}
69+
70+/// Forget workers nobody restamped within the lease — their replica died
71+/// without deregistering them. Any replica may run it: the rows are keyed by
72+/// worker, not by owner, and a live worker's row is never stale.
73+pub async fn sweep(db: &Database) -> Result<(), AppError> {
74+ db.query(AI_WORKER_SWEEP)
75+ .bind(("lease_ms", AI_WORKER_LEASE_SECS * 1_000))
76+ .await?
77+ .check()?;
78+ Ok(())
79+}
80+
81+/// The gate read: does *any* replica hold a worker for `capability`?
82+///
83+/// Errors answer "no" rather than propagating. This is consulted on the 503
84+/// path of a request that has not written anything yet, so the worst a
85+/// database hiccup can do is tell one user to retry — turning it into a 500
86+/// would be strictly worse for the same fault.
87+pub async fn serves(db: &Database, capability: &str) -> bool {
88+ let found: Result<Vec<RecordId>, AppError> = async {
89+ Ok(db
90+ .query(AI_WORKER_SERVES)
91+ .bind(("capability", capability.to_string()))
92+ .bind(("lease_ms", AI_WORKER_LEASE_SECS * 1_000))
93+ .await?
94+ .check()?
95+ .take(0)?)
96+ }
97+ .await;
98+ match found {
99+ Ok(rows) => !rows.is_empty(),
100+ Err(err) => {
101+ tracing::warn!("could not read the AI worker gate: {err}");
102+ false
103+ }
104+ }
105+}
106+
107+#[cfg(test)]
108+mod tests {
109+ use super::*;
110+ use crate::constant::AI_CHAT_CAPABILITY;
111+
112+ fn worker(id: &str, capabilities: &[&str]) -> WorkerSnapshot {
113+ WorkerSnapshot {
114+ id: id.to_string(),
115+ service: "tutor".to_string(),
116+ capabilities: capabilities.iter().map(|c| c.to_string()).collect(),
117+ inflight: 0,
118+ max_concurrent: 4,
119+ }
120+ }
121+
122+ #[tokio::test]
123+ async fn a_stale_row_stops_answering_the_gate() {
124+ // The phantom this exists to prevent: a replica that dies leaves its
125+ // row behind, and without the age filter that row would keep every
126+ // peer's chat endpoint reporting a service that is gone.
127+ let db = crate::database::init_mem().await.unwrap();
128+ announce(&db, &[worker("w1", &[AI_CHAT_CAPABILITY])])
129+ .await
130+ .unwrap();
131+ assert!(serves(&db, AI_CHAT_CAPABILITY).await);
132+ assert!(!serves(&db, "ocr.extract").await, "a capability nobody has");
133+
134+ // Age it past the lease, as a dead replica's row ages on its own.
135+ db.query("UPDATE ai_worker SET seen_at = seen_at - $ms")
136+ .bind(("ms", (AI_WORKER_LEASE_SECS + 1) * 1_000))
137+ .await
138+ .unwrap()
139+ .check()
140+ .unwrap();
141+ assert!(
142+ !serves(&db, AI_CHAT_CAPABILITY).await,
143+ "a stale row must not hold the gate open"
144+ );
145+ sweep(&db).await.unwrap();
146+ let rows: Vec<RecordId> = db
147+ .query("SELECT VALUE id FROM ai_worker")
148+ .await
149+ .unwrap()
150+ .check()
151+ .unwrap()
152+ .take(0)
153+ .unwrap();
154+ assert!(rows.is_empty(), "the sweep deletes what the read ignores");
155+ }
156+
157+ #[tokio::test]
158+ async fn announcing_twice_restamps_rather_than_duplicating() {
159+ let db = crate::database::init_mem().await.unwrap();
160+ let live = [worker("w1", &[AI_CHAT_CAPABILITY])];
161+ announce(&db, &live).await.unwrap();
162+ db.query("UPDATE ai_worker SET seen_at = seen_at - $ms")
163+ .bind(("ms", (AI_WORKER_LEASE_SECS + 1) * 1_000))
164+ .await
165+ .unwrap()
166+ .check()
167+ .unwrap();
168+ assert!(!serves(&db, AI_CHAT_CAPABILITY).await);
169+
170+ announce(&db, &live).await.unwrap();
171+ assert!(serves(&db, AI_CHAT_CAPABILITY).await, "the beat healed it");
172+ let rows: Vec<RecordId> = db
173+ .query("SELECT VALUE id FROM ai_worker")
174+ .await
175+ .unwrap()
176+ .check()
177+ .unwrap()
178+ .take(0)
179+ .unwrap();
180+ assert_eq!(rows.len(), 1, "one worker is one row");
181+
182+ withdraw(&db, "w1").await.unwrap();
183+ assert!(
184+ !serves(&db, AI_CHAT_CAPABILITY).await,
185+ "goodbye is immediate"
186+ );
187+ }
188+}
src/ai/server.rsmodified+98 -3
@@ -12,12 +12,14 @@ use serde_json::Value;
1212 use ulid::Ulid;
1313
1414 use crate::ai::error::AiError;
15+use crate::ai::presence;
1516 use crate::ai::protocol::{
1617 Greeting, Hello, RejectCode, Request, Response, protocol_matches, read_frame, write_frame,
1718 };
1819 use crate::ai::registry::{AiRegistry, WorkerSnapshot, clamp_concurrency};
1920 use crate::ai::tls;
2021 use crate::constant::{AI_HANDSHAKE_TIMEOUT_SECS, AI_PROTOCOL};
22+use crate::database::Database;
2123
2224 /// What the bridge needs to come up.
2325 #[derive(Clone, Debug)]
@@ -35,6 +37,13 @@ pub struct BridgeConfig {
3537
3638 struct Inner {
3739 registry: AiRegistry,
40+ /// The database, once [`AiBridge::attach_presence`] has handed it over —
41+ /// used for the `ai_worker` gate and nothing else (see
42+ /// [`crate::ai::presence`]). `OnceLock` because the bridge binds before the
43+ /// router is built, so presence is wired *after* the listener is already
44+ /// accepting: a worker may register before this is set, and the heartbeat
45+ /// republishes the whole live set precisely so that one is not lost.
46+ presence: std::sync::OnceLock<Database>,
3847 /// The leaf certificate this listener presents, kept so it can be shown to
3948 /// an operator (or pinned by an in-process client) without re-reading the
4049 /// PEM off disk.
@@ -77,6 +86,7 @@ impl AiBridge {
7786
7887 let inner = Arc::new(Inner {
7988 registry: AiRegistry::default(),
89+ presence: std::sync::OnceLock::new(),
8090 certificate: bridge_tls.leaf.clone(),
8191 token: config.token,
8292 request_timeout: config.request_timeout,
@@ -114,13 +124,35 @@ impl AiBridge {
114124 self.inner.registry.snapshot()
115125 }
116126
117- /// Is anything connected that can serve `capability`? Callers use this to
118- /// hide a feature in the UI rather than to gate a request — by the time the
119- /// request runs, the answer may have changed either way.
127+ /// Is anything connected *to this process* that can serve `capability`?
128+ ///
129+ /// The DISPATCHER's answer, and the authoritative one: this registry owns
130+ /// the sockets, so only it may decide that this replica can answer a job.
131+ /// Racy in the harmless direction — a worker can vanish between the check
132+ /// and the dispatch — so it still never guards a write. For "can *anyone*
133+ /// serve it", which is a different and weaker question, see
134+ /// [`crate::ai::presence::serves`].
120135 pub fn has_capability(&self, capability: &str) -> bool {
121136 self.inner.registry.has_capability(capability)
122137 }
123138
139+ /// Hand the bridge the database, so the workers it holds become visible to
140+ /// other replicas through the `ai_worker` gate. Returns whether this call
141+ /// was the one that wired it — the caller uses that to start exactly one
142+ /// claim loop per process.
143+ ///
144+ /// Idempotent by construction: a second call is a no-op and returns
145+ /// `false`. Nothing here is required for the bridge to work; a deployment
146+ /// that never attaches presence simply keeps the single-process behaviour,
147+ /// where the in-process registry is the whole truth.
148+ pub fn attach_presence(&self, db: Database) -> bool {
149+ if self.inner.presence.set(db.clone()).is_err() {
150+ return false;
151+ }
152+ heartbeat_presence(Arc::downgrade(&self.inner), db);
153+ true
154+ }
155+
124156 /// Send one request to a service and await its answer.
125157 ///
126158 /// Each call takes a fresh QUIC bidirectional stream, so concurrent calls
@@ -203,6 +235,45 @@ impl AiBridge {
203235 }
204236 }
205237
238+/// Republish this replica's live worker set to the `ai_worker` gate, forever.
239+///
240+/// The whole set every beat rather than deltas: it is the self-healing half of
241+/// the gate (a row lost to a database blip, or a worker registered before
242+/// presence was attached, comes back on the next tick), and the set is a
243+/// handful of rows. The sweep rides along so a replica that died without
244+/// deregistering stops holding anyone's gate open.
245+///
246+/// Holds a `Weak` on the bridge so that *this* task is not itself a reason to
247+/// keep a listener alive. It is not a shutdown mechanism, and in the wired-up
248+/// process it never fires: `chatbot::spawn_claim_loop` owns an `AiBridge` by
249+/// value for the life of the process, so the strong count never reaches zero
250+/// and both tasks run until exit. That is intended for a server — the bridge
251+/// is not restartable — and is only visible in tests, which build many
252+/// bridges. Correct that (a `CancellationToken` on both loops) the day a
253+/// bridge needs to be torn down while the process lives.
254+fn heartbeat_presence(inner: std::sync::Weak<Inner>, db: Database) {
255+ tokio::spawn(async move {
256+ let mut ticker = tokio::time::interval(Duration::from_secs(
257+ crate::constant::AI_WORKER_HEARTBEAT_SECS,
258+ ));
259+ ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
260+ loop {
261+ // The first tick is immediate, so workers registered before the
262+ // database arrived are published now and not one beat late.
263+ ticker.tick().await;
264+ let Some(inner) = inner.upgrade() else { return };
265+ let workers = inner.registry.snapshot();
266+ drop(inner);
267+ if let Err(err) = presence::announce(&db, &workers).await {
268+ tracing::warn!("could not publish the AI worker gate: {err}");
269+ }
270+ if let Err(err) = presence::sweep(&db).await {
271+ tracing::warn!("could not sweep the AI worker gate: {err}");
272+ }
273+ }
274+ });
275+}
276+
206277 /// Accept connections until the endpoint closes. One task per service.
207278 async fn accept_loop(inner: Arc<Inner>) {
208279 while let Some(incoming) = inner.endpoint.accept().await {
@@ -243,6 +314,13 @@ async fn serve_connection(inner: Arc<Inner>, conn: quinn::Connection, remote: So
243314 // dies without saying anything.
244315 let reason = conn.closed().await;
245316 inner.registry.remove(&worker_id);
317+ // The gate closes with the registry, not a lease later — but only after
318+ // the registry, which is the authoritative one (see `presence`).
319+ if let Some(db) = inner.presence.get()
320+ && let Err(err) = presence::withdraw(db, &worker_id).await
321+ {
322+ tracing::warn!("could not withdraw AI worker {worker_id} from the gate: {err}");
323+ }
246324 tracing::info!("AI service `{service}` ({worker_id}) at {remote} disconnected: {reason}");
247325 }
248326
@@ -331,6 +409,23 @@ async fn register(
331409 max_concurrent,
332410 conn.clone(),
333411 );
412+ // …and only then published to the gate, so `ai_worker` can never advertise
413+ // a worker the local dispatcher would refuse to pick.
414+ if let Some(db) = inner.presence.get() {
415+ let announced = WorkerSnapshot {
416+ id: worker_id.clone(),
417+ service: hello.service.clone(),
418+ capabilities: hello.capabilities.clone(),
419+ inflight: 0,
420+ max_concurrent,
421+ };
422+ if let Err(err) = presence::announce(db, &[announced]).await {
423+ // Not fatal, and not a reason to refuse the service: the worker is
424+ // already usable by this replica, and the next heartbeat
425+ // republishes the whole live set.
426+ tracing::warn!("could not publish AI worker {worker_id} to the gate: {err}");
427+ }
428+ }
334429 tracing::info!(
335430 "AI service `{}` ({worker_id}) at {remote} registered: {:?}, max_concurrent {max_concurrent}",
336431 hello.service,
src/config.rsmodified+58 -8
@@ -1,8 +1,8 @@
11 use std::env;
22
33 use crate::constant::{
4- AI_DEFAULT_REQUEST_TIMEOUT_SECS, DEFAULT_API_RATE_LIMIT, DEFAULT_AUTH_RATE_LIMIT,
5- DEFAULT_CHATBOT_RATE_LIMIT,
4+ AI_DEFAULT_REQUEST_TIMEOUT_SECS, AI_MAX_REQUEST_TIMEOUT_SECS, DEFAULT_API_RATE_LIMIT,
5+ DEFAULT_AUTH_RATE_LIMIT, DEFAULT_CHATBOT_RATE_LIMIT,
66 };
77 use crate::rate_limit::RateLimitConfig;
88
@@ -105,14 +105,34 @@ fn parse_limit(value: Option<String>, default: u32) -> u32 {
105105 value.and_then(|v| v.trim().parse().ok()).unwrap_or(default)
106106 }
107107
108-/// Parse a timeout in seconds. Unlike a rate limit, `0` is *not* honoured —
109-/// a zero deadline would fail every AI request instantly, which is never what
110-/// an operator means — so it falls back with the rest of the garbage.
108+/// Parse the AI request deadline in seconds. Unlike a rate limit, `0` is *not*
109+/// honoured — a zero deadline would fail every AI request instantly, which is
110+/// never what an operator means — so it falls back with the rest of the
111+/// garbage.
112+///
113+/// The ceiling is the load-bearing part, and it is enforced here because here
114+/// is the only place the number enters the process. A deadline above
115+/// [`AI_MAX_REQUEST_TIMEOUT_SECS`] lets one dispatch outlive
116+/// `CHATBOT_CLAIM_RECLAIM_SECS`, and the chat claim queue then hands the same
117+/// turn to a second worker while the first is still answering it — two
118+/// inferences for one reply. Clamping at the boundary is what makes that
119+/// unreachable *by configuration*, instead of true only for the default.
111120 fn parse_timeout(value: Option<String>, default: u64) -> u64 {
112- value
121+ let asked = value
113122 .and_then(|v| v.trim().parse().ok())
114123 .filter(|n| *n > 0)
115- .unwrap_or(default)
124+ .unwrap_or(default);
125+ if asked > AI_MAX_REQUEST_TIMEOUT_SECS {
126+ // Loud: the operator asked for something they are not getting, and the
127+ // reason (a queue horizon) is not one they could guess from the name.
128+ tracing::warn!(
129+ "AI_REQUEST_TIMEOUT_SECS={asked} is above the {AI_MAX_REQUEST_TIMEOUT_SECS}s ceiling \
130+ the chat claim queue allows (a longer inference would be reclaimed and re-dispatched \
131+ mid-flight) — using {AI_MAX_REQUEST_TIMEOUT_SECS}s"
132+ );
133+ return AI_MAX_REQUEST_TIMEOUT_SECS;
134+ }
135+ asked
116136 }
117137
118138 /// Parse the `PORT` value, falling back to 8080 when unset or unparseable.
@@ -134,6 +154,9 @@ fn parse_flag(value: Option<String>) -> bool {
134154 #[cfg(test)]
135155 mod tests {
136156 use super::{parse_flag, parse_limit, parse_port, parse_timeout};
157+ use crate::constant::{
158+ AI_DEFAULT_REQUEST_TIMEOUT_SECS, AI_MAX_REQUEST_TIMEOUT_SECS, CHATBOT_CLAIM_RECLAIM_SECS,
159+ };
137160
138161 #[tokio::test]
139162 async fn timeout_falls_back_on_absent_garbage_and_zero() {
@@ -141,7 +164,34 @@ mod tests {
141164 assert_eq!(parse_timeout(Some("nope".into()), 30), 30);
142165 // A zero deadline would time out every AI call before it started.
143166 assert_eq!(parse_timeout(Some("0".into()), 30), 30);
144- assert_eq!(parse_timeout(Some(" 120 ".into()), 30), 120);
167+ // Whitespace is trimmed; the ceiling has its own test below.
168+ assert_eq!(parse_timeout(Some(" 45 ".into()), 30), 45);
169+ }
170+
171+ #[tokio::test]
172+ async fn a_configured_timeout_can_never_outlive_the_chat_claim_horizon() {
173+ // The one double-dispatch an operator could still reach: nothing used
174+ // to stop `AI_REQUEST_TIMEOUT_SECS=120`, and a dispatch outliving
175+ // `CHATBOT_CLAIM_RECLAIM_SECS` has its turn reclaimed and re-sent while
176+ // the first inference is still running — the model answers one turn
177+ // twice. The relationship, not a literal, is what is asserted: raising
178+ // one of the two numbers without the other cannot pass this.
179+ for asked in ["91", "120", "600", "18446744073709551615"] {
180+ let got = parse_timeout(Some(asked.into()), AI_DEFAULT_REQUEST_TIMEOUT_SECS);
181+ assert!(
182+ (got as i64) < CHATBOT_CLAIM_RECLAIM_SECS,
183+ "AI_REQUEST_TIMEOUT_SECS={asked} was honoured as {got}s, at or past the \
184+ {CHATBOT_CLAIM_RECLAIM_SECS}s reclaim horizon"
185+ );
186+ assert_eq!(got, AI_MAX_REQUEST_TIMEOUT_SECS, "clamped to the ceiling");
187+ }
188+ // Everything under the ceiling — the default included — is honoured
189+ // verbatim: this is a ceiling, not a fixed deadline.
190+ assert_eq!(parse_timeout(Some("45".into()), 30), 45);
191+ assert_eq!(
192+ parse_timeout(None, AI_DEFAULT_REQUEST_TIMEOUT_SECS),
193+ AI_DEFAULT_REQUEST_TIMEOUT_SECS
194+ );
145195 }
146196
147197 #[tokio::test]
src/constant.rsmodified+270 -9
@@ -371,6 +371,56 @@ pub const AI_KEEPALIVE_SECS: u64 = 10;
371371 /// chat endpoints report the service as unavailable.
372372 pub const AI_CHAT_CAPABILITY: &str = "chat.reply";
373373
374+// --- AI worker presence: the GATE, never the dispatcher -----------------
375+//
376+// Read `crate::ai::presence` before touching anything below. In one line: the
377+// `ai_worker` table answers "could *anything, anywhere* serve this
378+// capability?" so a POST on a replica holding no worker can still be accepted
379+// (a peer's claim loop will answer it). It is a heartbeated cache of other
380+// processes' sockets and it is allowed to be wrong in both directions. The
381+// in-process `ai::registry::Registry` is the dispatcher and the only thing
382+// that may decide who actually answers.
383+
384+/// The heartbeated presence table. One row per connected worker, written by
385+/// whichever replica owns that worker's QUIC connection.
386+pub const AI_WORKER_TABLE: &str = "ai_worker";
387+
388+/// How often a replica restamps `seen_at` for the workers it holds, and how
389+/// long a row is believed without a restamp. The lease is a comfortable
390+/// multiple of the beat (three), so a single missed heartbeat never hides a
391+/// live worker, and it matches [`AI_IDLE_TIMEOUT_SECS`] — the window in which
392+/// the transport itself notices a dead service — so a replica that dies
393+/// outright leaves a phantom for no longer than a service that dies outright.
394+pub const AI_WORKER_HEARTBEAT_SECS: u64 = 10;
395+pub const AI_WORKER_LEASE_SECS: i64 = 30;
396+
397+/// Write (or restamp) one worker's row. `UPSERT` rather than `CREATE`: the
398+/// heartbeat replays the whole live set every beat, which is what heals a row
399+/// lost to a database blip or written before the presence table was attached.
400+pub const AI_WORKER_ANNOUNCE: &str = "
401+ UPSERT $id CONTENT { service: $service, capabilities: $capabilities,
402+ seen_at: time::unix(time::now()) * 1000 };
403+";
404+
405+/// Drop a worker whose connection closed. Immediate — the gate should not
406+/// hold a door open for a service that has already said goodbye.
407+pub const AI_WORKER_WITHDRAW: &str = "DELETE $id;";
408+
409+/// Forget workers nobody has restamped within the lease: the replica holding
410+/// them died without deregistering. Any replica's heartbeat may run it — the
411+/// rows are keyed by worker, not by owner.
412+pub const AI_WORKER_SWEEP: &str = "
413+ DELETE ai_worker WHERE seen_at < time::unix(time::now()) * 1000 - $lease_ms;
414+";
415+
416+/// The gate read. Age-filtered in the query, not by the sweep, so a phantom
417+/// row is inert the moment it is stale rather than when someone gets round to
418+/// deleting it.
419+pub const AI_WORKER_SERVES: &str = "
420+ SELECT VALUE id FROM ai_worker WHERE $capability IN capabilities
421+ AND seen_at >= time::unix(time::now()) * 1000 - $lease_ms LIMIT 1;
422+";
423+
374424 /// Hard ceiling on one chat message's characters — the newtype bound, above
375425 /// which no school setting can reach. Sized for a pasted question with its
376426 /// working, well under [`AI_MAX_FRAME_BYTES`] once history rides along.
@@ -416,6 +466,93 @@ pub const CHAT_STREAM_POLL_MS: u64 = 200;
416466 /// this only catches the row whose task died with the process.
417467 pub const CHATBOT_PENDING_STALE_SECS: i64 = 300;
418468
469+// --- the chat claim queue ----------------------------------------------
470+
471+/// How often a replica looks for an unanswered turn, and how many it takes in
472+/// one sweep. The poll is what replaces the in-process `tokio::spawn` a POST
473+/// used to do, so it is the answer's added latency floor — matched to
474+/// [`CHAT_STREAM_POLL_MS`], the cadence the client already waits at, so a turn
475+/// is never claimed slower than its own reader refreshes. The batch is small
476+/// on purpose: a claim is a promise to dispatch now, and dispatching more at
477+/// once than a worker's `max_concurrent` would only turn the surplus into
478+/// `busy` failures.
479+pub const CHATBOT_CLAIM_POLL_MS: u64 = 200;
480+pub const CHATBOT_CLAIM_BATCH: i64 = 4;
481+
482+/// How long a claim is believed before another replica may take the turn back.
483+///
484+/// Sized between the two horizons it sits between, and both bounds bite (see
485+/// `the_claim_horizon_sits_between_the_inference_and_the_stale_window`):
486+///
487+/// * **Above the AI request timeout** ([`AI_DEFAULT_REQUEST_TIMEOUT_SECS`],
488+/// 30s), with room to spare, because a reclaim that fires while the first
489+/// claimer is still waiting on a legitimate inference makes two services
490+/// answer the same turn — twice the cost for one reply (the second is then
491+/// discarded by the `status = 'pending'` gate on the settle, so it is waste,
492+/// not corruption). Three times the default leaves margin for the settle
493+/// write and for a moderately raised `AI_REQUEST_TIMEOUT_SECS`.
494+/// * **Below [`CHATBOT_PENDING_STALE_SECS`]** (300s), because a turn is only
495+/// claimable inside that window; a reclaim horizon at or above it would
496+/// never fire before the turn stopped being worth answering, making the
497+/// dead-claimer retry dead code. At 90s a turn survives two lost claimers
498+/// and still gets answered.
499+pub const CHATBOT_CLAIM_RECLAIM_SECS: i64 = 90;
500+
501+/// The largest per-request AI deadline a deployment may configure
502+/// (`AI_REQUEST_TIMEOUT_SECS`). Anything above it is clamped down to it at
503+/// startup, loudly — see [`crate::config`].
504+///
505+/// Not a taste limit; it is the claim queue's arithmetic, and the bound the
506+/// doc above only *asserted* before. A dispatch allowed to outlive
507+/// [`CHATBOT_CLAIM_RECLAIM_SECS`] has its turn reclaimed and re-sent while the
508+/// first inference is still legitimately running, so the model runs twice for
509+/// one reply. (The settle's `status = 'pending'` gate still admits only one
510+/// answer, so it is waste rather than corruption — but a worker with side
511+/// effects makes it worse than waste.) Nothing but the parser stood between an
512+/// operator and that: `AI_REQUEST_TIMEOUT_SECS=120` used to be honoured
513+/// verbatim.
514+///
515+/// Clamped rather than refused, because a slow model is a legitimate thing to
516+/// own and a boot that dies over it helps nobody — and because the ceiling is
517+/// real either way: a reply that arrives after
518+/// [`CHATBOT_PENDING_STALE_SECS`] is discarded by the read-time projection, so
519+/// no deadline near it was ever going to produce an answer a user sees. A
520+/// school that genuinely needs longer raises the horizon and the staleness
521+/// window together, and the ordering tests police the result.
522+///
523+/// Two thirds of the horizon, derived and never hand-kept: raising the horizon
524+/// raises this with it, so the two numbers cannot drift apart. The remaining
525+/// third is the room the reply needs to arrive, be capped and be stamped
526+/// before anyone may reclaim the turn.
527+pub const AI_MAX_REQUEST_TIMEOUT_SECS: u64 = CHATBOT_CLAIM_RECLAIM_SECS as u64 * 2 / 3;
528+
529+/// Take up to [`CHATBOT_CLAIM_BATCH`] unanswered turns for this replica.
530+///
531+/// Two statements because SurrealDB has no `LIMIT` on `UPDATE`: the first
532+/// picks candidates, the second claims them. The pick is advisory — a peer may
533+/// take a row in between — so the `UPDATE` repeats the *whole* guard, and
534+/// per-record `UPDATE ... WHERE` is atomic, so a row claimed by a rival simply
535+/// does not come back in `RETURN AFTER`. Nothing here consults `ai_worker`:
536+/// the caller has already asked its own registry whether it can answer.
537+///
538+/// The guard, term by term: only a reserved assistant row (`pending`), only
539+/// one young enough that somebody is still waiting for it (`$stale_ms` — past
540+/// that a reader already shows it failed, so answering it would resurrect a
541+/// turn the user was told was lost), and only one that is unclaimed *or* whose
542+/// claimer has gone quiet past `$reclaim_ms`. Both disjuncts are required: a
543+/// row whose claimer died must be retried, not left forever.
544+pub const CHATBOT_CLAIM: &str = "
545+ LET $ids = (SELECT VALUE id FROM chatbot_message
546+ WHERE status = 'pending' AND role = 'assistant'
547+ AND created_at >= time::unix(time::now()) * 1000 - $stale_ms
548+ AND (claimed_by = NONE OR claimed_at < time::unix(time::now()) * 1000 - $reclaim_ms)
549+ ORDER BY created_at ASC, id ASC LIMIT $batch);
550+ UPDATE $ids SET claimed_by = $me, claimed_at = time::unix(time::now()) * 1000
551+ WHERE status = 'pending'
552+ AND (claimed_by = NONE OR claimed_at < time::unix(time::now()) * 1000 - $reclaim_ms)
553+ RETURN AFTER;
554+";
555+
419556 /// How long a dialling AI service has to complete its `Hello`/`Welcome`
420557 /// exchange before the connection is dropped. Short: the handshake is one
421558 /// frame each way, and an unauthenticated connection must not be able to
@@ -582,6 +719,87 @@ pub const MEAL_BOOKING_TABLE: &str = "meal_booking";
582719 pub const MEAL_ATTENDANCE_TABLE: &str = "meal_attendance";
583720 pub const MEAL_LEDGER_TABLE: &str = "meal_ledger";
584721
722+// --- boot leader election ----------------------------------------------
723+
724+/// The lock row every booting process races for (see
725+/// [`crate::database::boot_once`]). Its own table, and the only SCHEMALESS one
726+/// in the database: the lock has to be claimable *before* the SCHEMAFULL batch
727+/// that defines every other table has run, so a lock whose own schema needed
728+/// migrating could not guard the migration. `IF NOT EXISTS` makes the
729+/// definition safe for all N processes to issue.
730+pub const MIGRATION_LOCK_TABLE: &str = "migration_lock";
731+pub const MIGRATION_LOCK_DDL: &str = "DEFINE TABLE IF NOT EXISTS migration_lock SCHEMALESS;";
732+
733+/// Claim the lock. A deterministic id is the whole mechanism: SurrealDB v3
734+/// answers a `CREATE` on an existing id with "already exists" rather than
735+/// overwriting it, so of N concurrent processes exactly one gets an `Ok`.
736+/// Returns the holder like the takeover does, so one caller reads both.
737+pub const MIGRATION_LOCK_CLAIM: &str = "
738+ CREATE migration_lock:boot SET holder = $me, claimed_at = time::unix(time::now()) * 1000,
739+ applied_at = NONE, applies = 0 RETURN VALUE holder;
740+";
741+
742+/// What a loser needs to know, decided by the *database's* clock — never the
743+/// process's, since two replicas' clocks disagree and the lease horizon is the
744+/// one thing a wrong clock could turn into a concurrent migration.
745+///
746+/// `applied` means "applied *this* binary's schema": a stamp carries the
747+/// fingerprint of the DDL that produced it, and a peer's stamp with any other
748+/// fingerprint is no evidence about the schema this process is about to write
749+/// (see [`crate::database::migration_fingerprint`]).
750+pub const MIGRATION_LOCK_STATE: &str = "
751+ SELECT holder, applied_at != NONE AND (fingerprint ?? '') = $fingerprint AS applied,
752+ claimed_at >= time::unix(time::now()) * 1000 - $lease_ms AS live
753+ FROM ONLY migration_lock:boot;
754+";
755+
756+/// Take the lock off a holder that cannot be relied on: one that has gone
757+/// silent past the lease horizon (killed mid-migration), or one that finished
758+/// with a *different* schema than ours — a stamp is the last thing a leader
759+/// writes, so a foreign fingerprint means nobody is in the DDL right now and
760+/// this binary's own migration still has to run.
761+///
762+/// Per-record `UPDATE ... WHERE` is atomic, so a second taker re-reads the
763+/// freshly bumped `claimed_at` and is refused (empty result). Clears
764+/// `applied_at` and `fingerprint`: the previous generation's stamp says nothing
765+/// about this one's schema.
766+pub const MIGRATION_LOCK_TAKEOVER: &str = "
767+ UPDATE migration_lock:boot SET holder = $me, claimed_at = time::unix(time::now()) * 1000,
768+ applied_at = NONE, fingerprint = NONE
769+ WHERE claimed_at < time::unix(time::now()) * 1000 - $lease_ms
770+ OR (applied_at != NONE AND (fingerprint ?? '') != $fingerprint)
771+ RETURN VALUE holder;
772+";
773+
774+/// Renew the lease while the migration runs, and stamp it done afterwards.
775+/// Both are `holder`-guarded and both report the holder back, so a leader that
776+/// was declared dead and replaced not only stops being able to write the lock —
777+/// it finds out (an empty result), which is the only way it can learn that a
778+/// peer is now applying the same DDL underneath it.
779+pub const MIGRATION_LOCK_HEARTBEAT: &str = "
780+ UPDATE migration_lock:boot SET claimed_at = time::unix(time::now()) * 1000
781+ WHERE holder = $me RETURN VALUE holder;
782+";
783+pub const MIGRATION_LOCK_STAMP: &str = "
784+ UPDATE migration_lock:boot SET applied_at = time::unix(time::now()) * 1000, applies += 1,
785+ fingerprint = $fingerprint
786+ WHERE holder = $me RETURN VALUE holder;
787+";
788+
789+/// How long a lock may go unrenewed before a peer may take it over. Must stay
790+/// a comfortable multiple of `MIGRATION_LOCK_HEARTBEAT_SECS`: it is the number
791+/// of missed beats that separates "the leader was killed" from "the leader is
792+/// slow", and mistaking the second for the first runs two migrations at once.
793+pub const MIGRATION_LOCK_LEASE_SECS: i64 = 30;
794+pub const MIGRATION_LOCK_HEARTBEAT_SECS: u64 = 5;
795+
796+/// How long a non-leader waits for the leader's `applied_at` before failing the
797+/// boot, and how often it looks. Bounded because a boot that hangs forever is
798+/// indistinguishable from a hung database; loud because the alternative —
799+/// serving on a schema nobody confirmed — is worse.
800+pub const MIGRATION_LOCK_WAIT_SECS: u64 = 180;
801+pub const MIGRATION_LOCK_POLL_MS: u64 = 200;
802+
585803 // --- schema migration SQL ----------------------------------------------
586804
587805 /// Repairs that must run *before* the DDL batch, because the DDL is what makes
@@ -686,8 +904,26 @@ pub const MIGRATION: &str = "
686904 DEFINE FIELD IF NOT EXISTS error_code ON chatbot_message TYPE option<string>;
687905 DEFINE FIELD IF NOT EXISTS created_at ON chatbot_message TYPE int READONLY;
688906 DEFINE FIELD IF NOT EXISTS completed_at ON chatbot_message TYPE option<int>;
907+ -- The claim (2026-07-27): which replica's claim loop owes this turn an
908+ -- answer, and when it said so. Absent = nobody has taken it yet; a claim
909+ -- older than CHATBOT_CLAIM_RECLAIM_SECS is a dead claimer and the turn is
910+ -- taken back (see `CHATBOT_CLAIM`).
911+ DEFINE FIELD IF NOT EXISTS claimed_by ON chatbot_message TYPE option<string>;
912+ DEFINE FIELD IF NOT EXISTS claimed_at ON chatbot_message TYPE option<int>;
689913 DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at;
690914 DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id;
915+ -- The claim loop's sweep: every poll asks for pending rows by age.
916+ DEFINE INDEX IF NOT EXISTS chatbot_message_status_created ON chatbot_message FIELDS status, created_at;
917+
918+ -- Which AI workers are connected to *any* replica (2026-07-27). The GATE
919+ -- and nothing else: a row only says a socket existed somewhere at
920+ -- `seen_at`, so it may spare a user a 503 but must never pick who answers
921+ -- — that is the in-process registry's call. Heartbeated by the replica
922+ -- owning the connection; a stale row is ignored by the read and swept.
923+ DEFINE TABLE IF NOT EXISTS ai_worker SCHEMAFULL;
924+ DEFINE FIELD IF NOT EXISTS service ON ai_worker TYPE string;
925+ DEFINE FIELD IF NOT EXISTS capabilities ON ai_worker TYPE array<string>;
926+ DEFINE FIELD IF NOT EXISTS seen_at ON ai_worker TYPE int;
691927
692928 DEFINE TABLE IF NOT EXISTS event SCHEMAFULL;
693929 DEFINE FIELD IF NOT EXISTS creator ON event TYPE record<user>;
@@ -1190,17 +1426,33 @@ pub const BACKFILL: &str = "
11901426 -- which is what they were presented as all along.
11911427 UPDATE chatbot_message SET truncated = false WHERE truncated = NONE;
11921428
1193- -- An assistant turn is answered by an in-process task, so a restart usually
1194- -- leaves its row `pending` with nobody left to complete it. Only rows past
1195- -- the stale horizon ($stale_ms, from `CHATBOT_PENDING_STALE_SECS`) are
1196- -- certainly abandoned though: a young one may still be being answered on the
1197- -- other side of the AI bridge, and a deploy must not shoot down a turn
1198- -- dispatched seconds ago. Nothing is lost by waiting — a reader already
1199- -- presents an over-age `pending` row as failed, and the next boot sweeps for
1200- -- real whatever crossed the horizon in the meantime.
1429+ -- An assistant turn is answered by a claim loop in some replica's process,
1430+ -- so a restart can leave its row `pending` with nobody left to complete it.
1431+ -- Only rows past the stale horizon ($stale_ms, from
1432+ -- `CHATBOT_PENDING_STALE_SECS`) are certainly abandoned though: a young one
1433+ -- may still be being answered on the other side of the AI bridge, and a
1434+ -- deploy must not shoot down a turn dispatched seconds ago. Nothing is lost
1435+ -- by waiting — a reader already presents an over-age `pending` row as
1436+ -- failed, and the next boot sweeps for real whatever crossed the horizon in
1437+ -- the meantime.
1438+ --
1439+ -- Claim-aware since 2026-07-27, because the sweep is no longer school-wide
1440+ -- truth: under N replicas the row may belong to a *live peer's* claim loop,
1441+ -- and failing it here would shoot down another process's in-flight turn.
1442+ -- So a claim restamped within the window is left alone. Both disjuncts
1443+ -- matter — `claimed_by = NONE` alone would strand every row whose claimer
1444+ -- died, which is the one case the sweep exists for.
1445+ --
1446+ -- The claim age is measured against $stale_ms rather than
1447+ -- CHATBOT_CLAIM_RECLAIM_SECS only because the boot binds one horizon (see
1448+ -- `database::migration_binds`); erring long is the safe direction — the
1449+ -- cost is that a row claimed just before it aged out waits one more boot
1450+ -- for its durable stamp, while readers have shown it failed all along.
12011451 UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted',
12021452 completed_at = time::unix(time::now()) * 1000
1203- WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms;
1453+ WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms
1454+ AND (claimed_by = NONE
1455+ OR claimed_at < time::unix(time::now()) * 1000 - $stale_ms);
12041456
12051457 -- Promotion out of student now deletes the user's enrollments (2026-07-18);
12061458 -- this sweeps rows promoted before that fix. A deleted user reads as
@@ -1265,3 +1517,12 @@ pub const BACKFILL: &str = "
12651517 UPDATE answer_image SET seq = 1 WHERE seq = NONE;
12661518 UPDATE exam_result SET seq = 1 WHERE seq = NONE;
12671519 ";
1520+
1521+/// The migration batches, in the order a boot applies them — and the *only*
1522+/// list of them. [`crate::database::migrate`] runs exactly these and
1523+/// [`crate::database::migration_fingerprint`] hashes exactly these, so a fourth
1524+/// batch cannot be executed without changing the fingerprint that decides
1525+/// whether a peer's schema is ours. They stay three separate queries: statements
1526+/// in one batch see the schema as it stood when the batch started (see
1527+/// `MIGRATION`).
1528+pub const MIGRATION_BATCHES: [&str; 3] = [PRE_REPAIR, MIGRATION, BACKFILL];
src/database.rsmodified+792 -12
@@ -3,9 +3,16 @@
33 use surrealdb::Surreal;
44 use surrealdb::engine::any::Any;
55 use surrealdb::opt::auth::Root;
6+use surrealdb::types::SurrealValue;
67
78 use crate::config::Config;
8-use crate::constant::{BACKFILL, CHATBOT_PENDING_STALE_SECS, MIGRATION, PRE_REPAIR};
9+use crate::constant::{
10+ CHATBOT_PENDING_STALE_SECS, MIGRATION_BATCHES, MIGRATION_LOCK_CLAIM, MIGRATION_LOCK_DDL,
11+ MIGRATION_LOCK_HEARTBEAT, MIGRATION_LOCK_HEARTBEAT_SECS, MIGRATION_LOCK_LEASE_SECS,
12+ MIGRATION_LOCK_POLL_MS, MIGRATION_LOCK_STAMP, MIGRATION_LOCK_STATE, MIGRATION_LOCK_TAKEOVER,
13+ MIGRATION_LOCK_WAIT_SECS,
14+};
15+use crate::domain::user::{Password, User, Username};
916 use crate::error::AppError;
1017
1118 /// The shared database handle.
@@ -24,8 +31,14 @@ use crate::error::AppError;
2431 /// Cloning the `Arc` shares the single session established at boot instead.
2532 pub type Database = std::sync::Arc<Surreal<Any>>;
2633
27-/// Connect to the SurrealDB server, sign in as root, and apply the schema.
34+/// Connect to the SurrealDB server, sign in as root, and apply the schema —
35+/// the latter through the boot election, so that N overlapping processes apply
36+/// it once between them (see [`boot_once`]).
2837 pub async fn init(cfg: &Config) -> Result<Database, AppError> {
38+ // Validated before the connection, not after the election: half a
39+ // credential pair is a deployment mistake, and finding that out only in the
40+ // process that happened to win the lock would make it a coin flip.
41+ let admin = admin_credentials(cfg)?;
2942 let db = connect_with_retry(cfg).await;
3043 db.signin(Root {
3144 username: cfg.db_user.clone(),
@@ -35,8 +48,348 @@ pub async fn init(cfg: &Config) -> Result<Database, AppError> {
3548 db.use_ns(cfg.db_ns.clone())
3649 .use_db(cfg.db_name.clone())
3750 .await?;
38- migrate(&db).await?;
39- Ok(std::sync::Arc::new(db))
51+ let db = std::sync::Arc::new(db);
52+ boot_once(
53+ &db,
54+ admin,
55+ std::time::Duration::from_secs(MIGRATION_LOCK_WAIT_SECS),
56+ )
57+ .await?;
58+ Ok(db)
59+}
60+
61+/// The `ADMIN_USERNAME` / `ADMIN_PASSWORD` bootstrap pair, if configured.
62+/// Both-or-neither: half a pair aborts startup rather than silently running
63+/// without the seed.
64+fn admin_credentials(cfg: &Config) -> Result<Option<(Username, Password)>, AppError> {
65+ match (&cfg.admin_username, &cfg.admin_password) {
66+ (Some(username), Some(password)) => Ok(Some((
67+ Username::try_new(username)
68+ .map_err(|err| AppError::Internal(format!("invalid ADMIN_USERNAME: {err}")))?,
69+ Password::try_new(password)
70+ .map_err(|err| AppError::Internal(format!("invalid ADMIN_PASSWORD: {err}")))?,
71+ ))),
72+ (None, None) => Ok(None),
73+ _ => Err(AppError::Internal(
74+ "ADMIN_USERNAME and ADMIN_PASSWORD must be set together".into(),
75+ )),
76+ }
77+}
78+
79+/// Run the boot work that must happen exactly once — the schema batches and the
80+/// admin seed — under a leader election, and hold every other process at the
81+/// door until it *has* happened. Returns whether we were the leader.
82+///
83+/// Two processes overlap on every rolling restart, long before any replica
84+/// work: they used to race the same SCHEMAFULL DDL, the same data backfills
85+/// (including the chatbot pending sweep, which writes live rows) and the same
86+/// `ensure_admin` read-then-create. The election is a deterministic-id
87+/// `CREATE`: SurrealDB v3 answers a create on an existing id with "already
88+/// exists" instead of overwriting, so of N racing processes exactly one gets an
89+/// `Ok`, and that one is the leader.
90+///
91+/// The lock is a *heartbeated lease*, not a once-only flag, and both halves of
92+/// that are deliberate:
93+///
94+/// * Heartbeated, because a leader killed mid-migration must not wedge every
95+/// future boot, yet a leader that is merely slow must never be overtaken —
96+/// two processes in the DDL at once is the exact race being prevented. The
97+/// leader renews `claimed_at` every `MIGRATION_LOCK_HEARTBEAT_SECS` for as
98+/// long as it works, and a peer takes over only after
99+/// `MIGRATION_LOCK_LEASE_SECS` of silence. The price is that recovery from a
100+/// killed leader waits out the lease; the alternative, a plain age horizon,
101+/// would have to exceed the slowest imaginable migration to be safe.
102+/// * A lease, not a flag, because a boot an hour later may be a new binary with
103+/// new DDL and must re-apply, and because the data backfills (the chatbot
104+/// pending sweep above all) are meant to run on every restart. Only a boot
105+/// *inside* the lease trusts a peer's `applied_at` — i.e. exactly the
106+/// rolling-restart window — and only when that stamp carries this binary's own
107+/// [`migration_fingerprint`], so a mixed-version window cannot make the newer
108+/// process skip its own DDL.
109+///
110+/// `wait` is how long a non-leader keeps polling before it fails the boot; a
111+/// parameter rather than a constant read inline so a test can prove that
112+/// deadline actually bites without sitting out `MIGRATION_LOCK_WAIT_SECS`.
113+async fn boot_once(
114+ db: &Database,
115+ admin: Option<(Username, Password)>,
116+ wait: std::time::Duration,
117+) -> Result<bool, AppError> {
118+ let lease_ms = MIGRATION_LOCK_LEASE_SECS * 1_000;
119+ // Any unique string; the lock only ever compares it for equality.
120+ let me = ulid::Ulid::new().to_string();
121+ // No query deadline anywhere in here on purpose: the SDK parks queries
122+ // while the socket is down instead of failing them, so a timeout would
123+ // report an outage as a dead leader and hand the migration to a second
124+ // process (see `crate::error::AppError::DbTimeout`).
125+ //
126+ // The bootstrap step: the lock's own table has to exist before anyone can
127+ // claim a row in it, so every process defines it (`IF NOT EXISTS`) rather
128+ // than the leader — the leader is not known yet. N processes issuing that
129+ // at once makes the key-value layer abort the losers with a retryable write
130+ // conflict, and a conflict here means a rival committed the very definition
131+ // we wanted, so it counts as success.
132+ if let Err(err) = db
133+ .query(MIGRATION_LOCK_DDL)
134+ .await
135+ .and_then(|response| response.check())
136+ && !lost_the_race(&err)
137+ {
138+ return Err(err.into());
139+ }
140+
141+ let deadline = tokio::time::Instant::now() + wait;
142+ loop {
143+ if claim(db, MIGRATION_LOCK_CLAIM, &me, lease_ms).await? {
144+ return leader_applies(db, &me, admin).await.map(|()| true);
145+ }
146+ let state: Option<LockState> = db
147+ .query(MIGRATION_LOCK_STATE)
148+ .bind(("lease_ms", lease_ms))
149+ .bind(("fingerprint", migration_fingerprint()))
150+ .await?
151+ .check()?
152+ .take(0)?;
153+ match state {
154+ // A live lease, stamped with our own fingerprint: the exact schema
155+ // this process needs is in place, so stop waiting.
156+ Some(state) if state.live && state.applied => {
157+ tracing::info!(leader = %state.holder, "schema applied by another process");
158+ return Ok(false);
159+ }
160+ // Anything else may be takeable — the holder went silent past the
161+ // lease, or it finished but with a different schema than ours. The
162+ // statement's `WHERE` is the arbiter, so a live holder still inside
163+ // the DDL refuses us and we fall through to waiting.
164+ Some(state) if claim(db, MIGRATION_LOCK_TAKEOVER, &me, lease_ms).await? => {
165+ tracing::warn!(
166+ previous = %state.holder,
167+ live = state.live,
168+ "taking over the boot migration lock: the holder went silent or applied \
169+ a different schema"
170+ );
171+ return leader_applies(db, &me, admin).await.map(|()| true);
172+ }
173+ Some(state) => {
174+ tracing::debug!(leader = %state.holder, "waiting for the boot migration");
175+ }
176+ // The row vanished; the next iteration's `CREATE` picks it up.
177+ None => {}
178+ }
179+ if tokio::time::Instant::now() >= deadline {
180+ // Loudly, not optimistically: SCHEMAFULL means an unmigrated
181+ // database fails every write anyway, and it would do so as
182+ // scattered 500s instead of one startup error. Exiting hands the
183+ // retry to the container runtime, which is where boot retries live.
184+ //
185+ // One production sequence reaches this branch: a leader that keeps
186+ // renewing its lease for longer than `wait` without ever stamping —
187+ // a migration slower than `MIGRATION_LOCK_WAIT_SECS`. A leader that
188+ // *stops* renewing never gets here, because the takeover above fires
189+ // a lease (30s) rather than a wait (180s) after the last renewal. So
190+ // the relative size of those two constants is not what selects this
191+ // branch; "the lock stayed live-and-unstamped for the whole wait"
192+ // is — which is precisely the state
193+ // `a_live_lock_is_waited_for_and_the_wait_is_bounded` constructs,
194+ // renewer and all, at a scaled-down wait.
195+ return Err(AppError::Internal(format!(
196+ "the boot migration lock stayed held for {wait:?}; \
197+ refusing to serve on a schema no process has confirmed"
198+ )));
199+ }
200+ tokio::time::sleep(std::time::Duration::from_millis(MIGRATION_LOCK_POLL_MS)).await;
201+ }
202+}
203+
204+/// The lock row as a loser reads it. `live`/`applied` are computed by the
205+/// database so the verdict never depends on this process's clock.
206+#[derive(SurrealValue)]
207+struct LockState {
208+ holder: String,
209+ applied: bool,
210+ live: bool,
211+}
212+
213+/// Run one of the two acquiring statements and report whether we now hold the
214+/// lock — both return our own holder id when we do, and nothing when a rival
215+/// got there first.
216+///
217+/// Two failures mean "not ours", not "broken". "Already exists" is the
218+/// deterministic-id create losing the race, and a key-value *write conflict* is
219+/// the same race decided one layer down: when two processes create the same id
220+/// at genuinely the same instant, the loser's transaction is aborted as
221+/// retryable rather than answered with the duplicate-key message (observed on
222+/// every run of `two_concurrent_boots_apply_the_schema_once`). Either way the
223+/// caller loops, re-reads the lock and finds out who holds it — which is also
224+/// the retry the conflict asks for.
225+async fn claim(db: &Database, sql: &str, me: &str, lease_ms: i64) -> Result<bool, AppError> {
226+ let result = db
227+ .query(sql)
228+ .bind(("me", me.to_string()))
229+ .bind(("lease_ms", lease_ms))
230+ .bind(("fingerprint", migration_fingerprint()))
231+ .await
232+ .and_then(|response| response.check());
233+ match result {
234+ Ok(mut response) => {
235+ let holders: Vec<String> = response.take(0)?;
236+ Ok(holders.iter().any(|holder| holder == me))
237+ }
238+ Err(err) if lost_the_race(&err) => Ok(false),
239+ Err(err) => Err(err.into()),
240+ }
241+}
242+
243+/// The two ways a rival's claim shows up as an error on ours: our `CREATE` hit
244+/// their row, or the key-value layer aborted our transaction because theirs
245+/// touched the same key first.
246+///
247+/// Read from the *typed* error surface, not the message. Every conflict wording
248+/// the storage engines produce — surrealkv's "Transaction conflict: Write
249+/// conflict, retry the transaction. This transaction can be retried",
250+/// surrealmx's read-conflict variant, RocksDB's `Busy`/`TryAgain` — funnels
251+/// through one `KvsError::TransactionConflict` into
252+/// `QueryError::TransactionConflict` (surrealdb-core 3.2.3
253+/// `err/to_types.rs:295`, `kvs/err.rs:64-179`), and a duplicate record id into
254+/// `AlreadyExistsError::Record` (`to_types.rs:206`). So the two checks below
255+/// cover all of them, where matching substrings covered only whichever wording
256+/// the engine of the day happened to use.
257+///
258+/// The message fallback stays for one reason: these errors also travel over the
259+/// WebSocket, where the SDK rebuilds them from the wire (`Error::from_parts`),
260+/// and a server that omitted the typed details would otherwise turn a lost race
261+/// into a failed boot. Widest known wordings, cheap, and belt-and-braces.
262+fn lost_the_race(err: &surrealdb::Error) -> bool {
263+ use surrealdb::types::{ErrorDetails, QueryError};
264+ if err.is_already_exists()
265+ || matches!(
266+ err.details(),
267+ ErrorDetails::Query(Some(QueryError::TransactionConflict))
268+ )
269+ {
270+ return true;
271+ }
272+ let message = err.to_string();
273+ message.contains("already exists") || message.contains("can be retried")
274+}
275+
276+/// A hash of the exact DDL and backfills this binary intends to apply.
277+///
278+/// It is what makes a peer's "applied" stamp trustworthy. Without it, a process
279+/// booting inside the lease window trusts *any* finished predecessor — so a new
280+/// binary starting seconds after an old one stamped would skip its own newer
281+/// DDL and then serve on a schema missing the very fields its handlers write.
282+/// With it, "somebody applied a schema" narrows to "somebody applied *this*
283+/// schema", and anything else is treated as unapplied.
284+///
285+/// Derived from the three SQL constants, never a hand-bumped version number: a
286+/// number nobody remembers to raise is worse than no check at all, while this
287+/// one changes on its own the moment the schema does.
288+fn migration_fingerprint() -> &'static str {
289+ use sha2::{Digest, Sha256};
290+ static FINGERPRINT: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
291+ let mut hasher = Sha256::new();
292+ // Length-prefixed, not concatenated: without a separator, moving a
293+ // statement from one batch into the next leaves the byte stream — and so
294+ // the fingerprint — unchanged, while changing what the boot actually
295+ // does (batch boundaries are what keep the DDL out of the backfills).
296+ for sql in MIGRATION_BATCHES {
297+ hasher.update((sql.len() as u64).to_le_bytes());
298+ hasher.update(sql.as_bytes());
299+ }
300+ for (name, value) in migration_binds() {
301+ hasher.update(name.as_bytes());
302+ hasher.update(value.to_le_bytes());
303+ }
304+ hex::encode(hasher.finalize())
305+ });
306+ &FINGERPRINT
307+}
308+
309+/// Leader path: keep the lease alive, apply everything, then stamp it done.
310+///
311+/// The renewal runs *concurrently with* the work rather than after it, in the
312+/// same task: `select!` polls both, so a lease that cannot be renewed is
313+/// noticed while the DDL is still going instead of at the end.
314+async fn leader_applies(
315+ db: &Database,
316+ me: &str,
317+ admin: Option<(Username, Password)>,
318+) -> Result<(), AppError> {
319+ let apply = async {
320+ migrate(db).await?;
321+ if let Some((username, password)) = admin {
322+ User::ensure_admin(username, password, db).await?;
323+ }
324+ Ok::<(), AppError>(())
325+ };
326+ tokio::select! {
327+ applied = apply => applied?,
328+ lost = renew_lease(db, me) => return Err(lost),
329+ }
330+
331+ let mut response = db
332+ .query(MIGRATION_LOCK_STAMP)
333+ .bind(("me", me.to_string()))
334+ .bind(("fingerprint", migration_fingerprint()))
335+ .await?
336+ .check()?;
337+ let stamped: Vec<String> = response.take(0)?;
338+ if stamped.is_empty() {
339+ // The same verdict as a lost renewal, for the same reason — this is the
340+ // backstop for losing the lock in the window between the last renewal
341+ // and the stamp.
342+ return Err(lost_lease());
343+ }
344+ Ok(())
345+}
346+
347+/// Renew the lease until it can no longer be renewed. Resolves *only* on that
348+/// loss, so it can sit opposite the real work in a `select!`.
349+///
350+/// A refused renewal (empty result) means a peer declared us dead and took the
351+/// lock, so it is now applying the same DDL underneath us. We treat that as
352+/// fatal to this boot and stop: our statements are all idempotent, so there is
353+/// nothing to undo, but continuing would keep two processes writing schema at
354+/// once — the exact race this module exists to prevent — and would leave us
355+/// serving as if we had migrated. Failing hands the retry to the container
356+/// runtime, which re-elects cleanly.
357+///
358+/// A renewal that *errors* is different: the socket may simply be down, and the
359+/// SDK parks queries rather than failing them, so a real error here is rare and
360+/// says nothing definite. Log it and keep trying — if it persists, the lease
361+/// expires, a peer takes over, and the next renewal is refused, which is the
362+/// verdict above. `.check()` is load-bearing: a statement-level failure comes
363+/// back inside an `Ok` response, so without it a renewal could fail forever
364+/// while logging nothing and renewing nothing.
365+async fn renew_lease(db: &Database, me: &str) -> AppError {
366+ let mut interval = tokio::time::interval(std::time::Duration::from_secs(
367+ MIGRATION_LOCK_HEARTBEAT_SECS,
368+ ));
369+ loop {
370+ interval.tick().await;
371+ match db
372+ .query(MIGRATION_LOCK_HEARTBEAT)
373+ .bind(("me", me.to_string()))
374+ .await
375+ .and_then(|response| response.check())
376+ {
377+ Ok(mut response) => match response.take::<Vec<String>>(0) {
378+ Ok(holders) if holders.is_empty() => return lost_lease(),
379+ Ok(_) => tracing::debug!("boot migration lease renewed"),
380+ Err(err) => tracing::warn!("boot lock renewal returned unusable rows: {err}"),
381+ },
382+ Err(err) => tracing::warn!("boot lock renewal failed: {err}"),
383+ }
384+ }
385+}
386+
387+fn lost_lease() -> AppError {
388+ AppError::Internal(
389+ "lost the boot migration lock while applying it — another process took it over and is \
390+ applying the schema, so this boot stops rather than race it"
391+ .into(),
392+ )
40393 }
41394
42395 /// Dial the database, retrying until it answers.
@@ -77,19 +430,446 @@ pub async fn init_mem() -> Result<Database, AppError> {
77430 /// Apply the schema + backfills. Idempotent — `init` runs it on every boot,
78431 /// and tests re-run it on a live handle to simulate a second boot.
79432 pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> {
80- db.query(PRE_REPAIR).await?.check()?;
81- db.query(MIGRATION).await?.check()?;
82- // Bound, not baked into the SQL string: a `const` cannot be interpolated
83- // into another `const`, and a hand-copied 300000 would drift silently.
84- db.query(BACKFILL)
85- .bind(("stale_ms", CHATBOT_PENDING_STALE_SECS * 1_000))
86- .await?
87- .check()?;
433+ for sql in MIGRATION_BATCHES {
434+ let mut query = db.query(sql);
435+ for (name, value) in migration_binds() {
436+ query = query.bind((name, value));
437+ }
438+ query.await?.check()?;
439+ }
88440 Ok(())
89441 }
90442
443+/// Parameters the batches are executed with. Bound, not baked into the SQL
444+/// string: a `const` cannot be interpolated into another `const`, and a
445+/// hand-copied 300000 would drift silently. They are part of what the migration
446+/// *does*, so [`migration_fingerprint`] hashes them alongside the SQL — a
447+/// changed horizon is a changed migration.
448+fn migration_binds() -> [(&'static str, i64); 1] {
449+ [("stale_ms", CHATBOT_PENDING_STALE_SECS * 1_000)]
450+}
451+
91452 #[cfg(test)]
92453 mod tests {
454+ use super::{Database, boot_once};
455+ use crate::constant::{MIGRATION_LOCK_LEASE_SECS, MIGRATION_LOCK_TABLE};
456+ use crate::domain::user::{Password, Username};
457+ use std::time::Duration;
458+
459+ /// An empty in-memory database with *no* schema — what a booting process
460+ /// actually finds. [`super::init_mem`] cannot be used here: it migrates.
461+ async fn unmigrated() -> Database {
462+ let db = surrealdb::engine::any::connect("memory").await.unwrap();
463+ db.use_ns("hezarfen").use_db("hezarfen").await.unwrap();
464+ std::sync::Arc::new(db)
465+ }
466+
467+ fn admin() -> Option<(Username, Password)> {
468+ Some((
469+ Username::try_new("root").unwrap(),
470+ Password::try_new("secret1").unwrap(),
471+ ))
472+ }
473+
474+ /// How many times the lock has been stamped applied — the observable side
475+ /// effect that makes "exactly one process applied" checkable.
476+ async fn applies(db: &Database) -> i64 {
477+ let mut res = db
478+ .query("SELECT VALUE applies FROM ONLY migration_lock:boot")
479+ .await
480+ .unwrap();
481+ res.take::<Option<i64>>(0).unwrap().unwrap()
482+ }
483+
484+ /// How many `root` rows the seed left. Guarded on the table existing: a
485+ /// waiter that failed its boot never ran the DDL, so `user` may be absent,
486+ /// which is an error rather than an empty result.
487+ async fn admin_count(db: &Database) -> i64 {
488+ let mut res = db
489+ .query(
490+ "RETURN IF 'user' IN object::keys((INFO FOR DB).tables) {
491+ array::len((SELECT id FROM user WHERE username = 'root'))
492+ } ELSE { 0 };",
493+ )
494+ .await
495+ .unwrap();
496+ res.take::<Option<i64>>(0).unwrap().unwrap()
497+ }
498+
499+ /// Two processes booting at once — the rolling-restart case, which happens
500+ /// today without any replica work. Exactly one may run the DDL, the
501+ /// backfills and the admin seed; the other has to wait for it and then
502+ /// serve, not repeat it.
503+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
504+ async fn two_concurrent_boots_apply_the_schema_once() {
505+ let db = unmigrated().await;
506+ let (a, b) = (db.clone(), db.clone());
507+ let one =
508+ tokio::spawn(async move { boot_once(&a, admin(), Duration::from_secs(30)).await });
509+ let two =
510+ tokio::spawn(async move { boot_once(&b, admin(), Duration::from_secs(30)).await });
511+ let (one, two) = (one.await.unwrap().unwrap(), two.await.unwrap().unwrap());
512+
513+ assert!(one ^ two, "exactly one process leads the boot: {one}/{two}");
514+ assert_eq!(applies(&db).await, 1, "the migration was applied once");
515+ assert_eq!(admin_count(&db).await, 1, "the admin was seeded once");
516+ // The loser still needs the schema it skipped applying.
517+ assert!(
518+ db.query("CREATE user:x SET username = 'x', password_hash = 'h'")
519+ .await
520+ .unwrap()
521+ .check()
522+ .is_ok(),
523+ "the schema is in place once both boots return"
524+ );
525+ }
526+
527+ /// A leader killed mid-migration leaves its claim behind. Nothing may
528+ /// require a human with a SurrealQL prompt to clear it: the next boot takes
529+ /// the lease over once it has gone unrenewed past the horizon.
530+ #[tokio::test]
531+ async fn an_abandoned_lock_is_taken_over_by_the_next_boot() {
532+ let db = unmigrated().await;
533+ // Exactly what a SIGKILL at the worst moment leaves: claimed, never
534+ // stamped, and no heartbeat since.
535+ db.query(
536+ "DEFINE TABLE migration_lock SCHEMALESS;
537+ CREATE migration_lock:boot SET holder = 'dead', applies = 0,
538+ claimed_at = time::unix(time::now()) * 1000 - ($lease + 1) * 1000;",
539+ )
540+ .bind(("lease", MIGRATION_LOCK_LEASE_SECS))
541+ .await
542+ .unwrap()
543+ .check()
544+ .unwrap();
545+
546+ assert!(
547+ boot_once(&db, admin(), Duration::from_secs(5))
548+ .await
549+ .unwrap(),
550+ "the abandoned lock is taken over, not waited on"
551+ );
552+ assert_eq!(applies(&db).await, 1);
553+ assert_eq!(admin_count(&db).await, 1);
554+ }
555+
556+ /// The other side of that horizon: a lock claimed a moment ago belongs to a
557+ /// process that is probably still working, so it is waited for — and if the
558+ /// wait runs out the boot fails loudly instead of serving on a schema
559+ /// nobody has confirmed.
560+ #[tokio::test]
561+ async fn a_live_lock_is_waited_for_and_the_wait_is_bounded() {
562+ let db = unmigrated().await;
563+ db.query(
564+ "DEFINE TABLE migration_lock SCHEMALESS;
565+ CREATE migration_lock:boot SET holder = 'busy', applies = 0,
566+ claimed_at = time::unix(time::now()) * 1000;",
567+ )
568+ .await
569+ .unwrap()
570+ .check()
571+ .unwrap();
572+
573+ // A real leader renews; without a renewer this would test "the lease
574+ // happened to still be inside its horizon", which is a different branch
575+ // from the one production reaches (a leader slower than the wait).
576+ let renewer = tokio::spawn({
577+ let db = db.clone();
578+ async move {
579+ loop {
580+ db.query(super::MIGRATION_LOCK_HEARTBEAT)
581+ .bind(("me", "busy".to_string()))
582+ .await
583+ .unwrap()
584+ .check()
585+ .unwrap();
586+ tokio::time::sleep(Duration::from_millis(50)).await;
587+ }
588+ }
589+ });
590+ let err = boot_once(&db, admin(), Duration::from_millis(600))
591+ .await
592+ .expect_err("a held, unstamped lock must not let a boot through");
593+ renewer.abort();
594+ assert!(
595+ err.to_string().contains("refusing to serve"),
596+ "the boot fails loudly: {err}"
597+ );
598+ assert_eq!(applies(&db).await, 0, "the waiter applied nothing");
599+ assert_eq!(admin_count(&db).await, 0, "and seeded nothing");
600+ }
601+
602+ /// The rolling-deploy hole the fingerprint exists for: a peer stamped the
603+ /// lock moments ago, inside the lease, so its lease is live and its work is
604+ /// done — but it applied a *different* schema. Trusting that stamp means
605+ /// serving on a database missing the fields this binary's own handlers
606+ /// write. It must be treated as unapplied and taken over.
607+ #[tokio::test]
608+ async fn a_peers_stamp_for_a_different_schema_is_not_trusted() {
609+ let db = unmigrated().await;
610+ db.query(
611+ "DEFINE TABLE migration_lock SCHEMALESS;
612+ CREATE migration_lock:boot SET holder = 'old-binary', applies = 1,
613+ claimed_at = time::unix(time::now()) * 1000,
614+ applied_at = time::unix(time::now()) * 1000,
615+ fingerprint = 'the DDL of some other build';",
616+ )
617+ .await
618+ .unwrap()
619+ .check()
620+ .unwrap();
621+
622+ assert!(
623+ boot_once(&db, admin(), Duration::from_secs(5))
624+ .await
625+ .unwrap(),
626+ "a stamp from a different schema is no evidence about ours"
627+ );
628+ assert_eq!(applies(&db).await, 2, "we applied ours on top");
629+ assert_eq!(admin_count(&db).await, 1);
630+ let mut res = db
631+ .query("SELECT VALUE fingerprint FROM ONLY migration_lock:boot")
632+ .await
633+ .unwrap();
634+ assert_eq!(
635+ res.take::<Option<String>>(0).unwrap().as_deref(),
636+ Some(super::migration_fingerprint()),
637+ "and left our own fingerprint behind"
638+ );
639+ }
640+
641+ /// The same lock, stamped with *our* fingerprint, is the case the skip
642+ /// exists for — otherwise every rolling restart re-runs the whole migration
643+ /// and the peer's boot is pointless.
644+ #[tokio::test]
645+ async fn a_peers_stamp_for_our_own_schema_is_trusted() {
646+ let db = unmigrated().await;
647+ db.query(
648+ "DEFINE TABLE migration_lock SCHEMALESS;
649+ CREATE migration_lock:boot SET holder = 'peer', applies = 1,
650+ claimed_at = time::unix(time::now()) * 1000,
651+ applied_at = time::unix(time::now()) * 1000,
652+ fingerprint = $fingerprint;",
653+ )
654+ .bind(("fingerprint", super::migration_fingerprint()))
655+ .await
656+ .unwrap()
657+ .check()
658+ .unwrap();
659+
660+ assert!(
661+ !boot_once(&db, admin(), Duration::from_secs(5))
662+ .await
663+ .unwrap(),
664+ "the peer applied this very schema, so this process just proceeds"
665+ );
666+ assert_eq!(applies(&db).await, 1, "and applies nothing itself");
667+ }
668+
669+ /// A hash of the same bytes, computed independently: the fingerprint has to
670+ /// cover every batch, every bound value, and the boundaries between them.
671+ /// Any of those left out is a schema change two binaries could disagree on
672+ /// while claiming the same fingerprint.
673+ #[test]
674+ fn the_fingerprint_covers_every_batch_its_binds_and_the_boundaries() {
675+ use sha2::{Digest, Sha256};
676+ let hash = |batches: &[String], binds: &[(&str, i64)]| {
677+ let mut hasher = Sha256::new();
678+ for sql in batches {
679+ hasher.update((sql.len() as u64).to_le_bytes());
680+ hasher.update(sql.as_bytes());
681+ }
682+ for (name, value) in binds {
683+ hasher.update(name.as_bytes());
684+ hasher.update(value.to_le_bytes());
685+ }
686+ hex::encode(hasher.finalize())
687+ };
688+ let batches: Vec<String> = crate::constant::MIGRATION_BATCHES
689+ .iter()
690+ .map(|sql| (*sql).to_string())
691+ .collect();
692+ let binds = super::migration_binds();
693+ assert_eq!(super::migration_fingerprint(), hash(&batches, &binds));
694+
695+ let mut edited = batches.clone();
696+ edited[2].push_str("-- one more backfill\n");
697+ assert_ne!(
698+ super::migration_fingerprint(),
699+ hash(&edited, &binds),
700+ "an edited batch must change the fingerprint"
701+ );
702+ // The boundary itself: the same bytes, one statement moved from the DDL
703+ // batch into the backfill batch. Concatenation without a separator would
704+ // hash these two arrangements identically.
705+ let mut moved = batches.clone();
706+ let at = moved[1].len() - 20;
707+ let tail = moved[1].split_off(at);
708+ moved[2].insert_str(0, &tail);
709+ assert_ne!(
710+ super::migration_fingerprint(),
711+ hash(&moved, &binds),
712+ "moving text across a batch boundary must change the fingerprint"
713+ );
714+ assert_ne!(
715+ super::migration_fingerprint(),
716+ hash(&batches, &[("stale_ms", 1)]),
717+ "a changed bound value is a changed migration"
718+ );
719+ }
720+
721+ /// The forcing function behind all of that: `migrate` and
722+ /// `migration_fingerprint` must read the *same* list. A fourth batch
723+ /// executed by one and not hashed by the other would let two binaries with
724+ /// different schemas claim the same fingerprint — and then skip each other's
725+ /// migration, which is the whole hole the fingerprint was added to close.
726+ #[test]
727+ fn what_the_boot_executes_is_what_the_fingerprint_hashes() {
728+ let source =
729+ std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/database.rs"))
730+ .expect("read database.rs");
731+ let body = |name: &str| {
732+ let start = source.find(name).expect("function is declared");
733+ let rest = &source[start..];
734+ let end = rest.find("\n}\n").expect("function ends");
735+ rest[..end].to_string()
736+ };
737+ for (name, body) in [
738+ ("pub async fn migrate", body("pub async fn migrate")),
739+ ("fn migration_fingerprint", body("fn migration_fingerprint")),
740+ ] {
741+ assert!(
742+ body.contains("MIGRATION_BATCHES") && body.contains("migration_binds()"),
743+ "{name} must derive from MIGRATION_BATCHES + migration_binds(), \
744+ or the executed and the hashed migration can drift apart"
745+ );
746+ }
747+ let executed = body("pub async fn migrate");
748+ assert_eq!(
749+ executed.matches("db.query(").count(),
750+ 1,
751+ "migrate() runs exactly one statement source — the batch list. A second \
752+ `db.query(...)` here is a batch the fingerprint does not hash:\n{executed}"
753+ );
754+ }
755+
756+ /// Path one of two: the renewal itself is refused. Driven straight at
757+ /// `renew_lease` rather than through `leader_applies`, because inside the
758+ /// `select!` a stamp failure would produce the same error and the test would
759+ /// pass without this path working at all.
760+ #[tokio::test]
761+ async fn a_refused_renewal_ends_the_lease_fatally() {
762+ let db = unmigrated().await;
763+ db.query(
764+ "DEFINE TABLE migration_lock SCHEMALESS;
765+ CREATE migration_lock:boot SET holder = 'somebody-else', applies = 0,
766+ claimed_at = time::unix(time::now()) * 1000;",
767+ )
768+ .await
769+ .unwrap()
770+ .check()
771+ .unwrap();
772+
773+ // Only ever resolves on a loss, so reaching this line is the assertion;
774+ // the timeout is there to fail the test instead of hanging it.
775+ let err = tokio::time::timeout(Duration::from_secs(5), super::renew_lease(&db, "me"))
776+ .await
777+ .expect("a renewal refused by the lock must resolve, not keep renewing");
778+ assert!(
779+ err.to_string().contains("lost the boot migration lock"),
780+ "{err}"
781+ );
782+ }
783+
784+ /// Path two: the lock is stolen *after* the last renewal, so nothing refuses
785+ /// us until the stamp. The thief strikes while the DDL is running, far
786+ /// inside the renewal interval, which is exactly the window the stamp
787+ /// backstop exists for.
788+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
789+ async fn a_lock_stolen_after_the_last_renewal_is_caught_by_the_stamp() {
790+ let db = unmigrated().await;
791+ db.query(
792+ "DEFINE TABLE migration_lock SCHEMALESS;
793+ CREATE migration_lock:boot SET holder = 'me', applies = 0,
794+ claimed_at = time::unix(time::now()) * 1000;",
795+ )
796+ .await
797+ .unwrap()
798+ .check()
799+ .unwrap();
800+ let thief = tokio::spawn({
801+ let db = db.clone();
802+ async move {
803+ tokio::time::sleep(Duration::from_millis(5)).await;
804+ db.query("UPDATE migration_lock:boot SET holder = 'thief'")
805+ .await
806+ .unwrap()
807+ .check()
808+ .unwrap();
809+ }
810+ });
811+
812+ let err = super::leader_applies(&db, "me", admin())
813+ .await
814+ .expect_err("a leader that cannot stamp its own lock must not report success");
815+ thief.await.unwrap();
816+ assert!(
817+ err.to_string().contains("lost the boot migration lock"),
818+ "{err}"
819+ );
820+ assert_eq!(
821+ applies(&db).await,
822+ 0,
823+ "and the lock is not stamped as applied by us"
824+ );
825+ }
826+
827+ /// The admin seed must not be interruptible into a state no later boot can
828+ /// repair. `create` + `set_role` was: killed between the two writes it
829+ /// leaves a *student* row holding ADMIN_USERNAME, which `ensure_admin` then
830+ /// refuses to promote on every subsequent boot (rightly — it cannot tell
831+ /// that row from a stranger who registered the name first). The row is
832+ /// therefore minted with its role in one statement, and this pins that.
833+ #[test]
834+ fn the_admin_seed_mints_the_role_with_the_row() {
835+ let source =
836+ std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/domain/user.rs"))
837+ .expect("read user.rs");
838+ let start = source
839+ .find("pub async fn ensure_admin")
840+ .expect("ensure_admin is declared");
841+ let body = &source[start..start + source[start..].find("\n }\n").expect("body ends")];
842+ assert!(
843+ !body.contains("set_role"),
844+ "ensure_admin promotes after creating; an interruption between those two writes \
845+ leaves a student account on ADMIN_USERNAME that no boot can heal:\n{body}"
846+ );
847+ assert!(
848+ body.contains("create_with_role"),
849+ "the seed must mint the row with Role::Admin in one statement"
850+ );
851+ }
852+
853+ /// The lock's table name is spelled in six places (the DDL and every
854+ /// statement), and a rename that misses one would split the election in two
855+ /// silently — every process would then "win" its own lock.
856+ #[test]
857+ fn every_lock_statement_names_the_lock_table() {
858+ for sql in [
859+ crate::constant::MIGRATION_LOCK_DDL,
860+ crate::constant::MIGRATION_LOCK_CLAIM,
861+ crate::constant::MIGRATION_LOCK_STATE,
862+ crate::constant::MIGRATION_LOCK_TAKEOVER,
863+ crate::constant::MIGRATION_LOCK_HEARTBEAT,
864+ crate::constant::MIGRATION_LOCK_STAMP,
865+ ] {
866+ assert!(
867+ sql.contains(MIGRATION_LOCK_TABLE),
868+ "{sql} does not name {MIGRATION_LOCK_TABLE}"
869+ );
870+ }
871+ }
872+
93873 #[tokio::test]
94874 async fn boot_fails_chatbot_messages_left_pending() {
95875 let db = super::init_mem().await.unwrap();
src/domain/chatbot_message.rsmodified+115 -6
@@ -1,9 +1,11 @@
11 //! One turn of a chatbot thread. Both sides are persisted: the user's prompt
22 //! lands `complete`, and the assistant's row is written `pending` *before* the
3-//! AI call so a reload never loses an answer in flight. The task that owns the
4-//! bridge stream then flips it to `complete` (with the text) or `failed` (with
5-//! a code) — and if that task dies with the process, the boot sweep in
6-//! `database.rs` fails the row instead.
3+//! AI call so a reload never loses an answer in flight. A pending row is then
4+//! a durable *job*: whichever replica holds a `chat.reply` worker claims it
5+//! (`claim_pending`), dispatches it, and flips it to `complete` (with the text)
6+//! or `failed` (with a code). A claimer that dies loses its claim to the next
7+//! sweep, and the boot sweep in `database.rs` fails whatever nobody could
8+//! answer inside the staleness window.
79 //!
810 //! `user_id` is duplicated from the thread onto every message so an
911 //! ownership check is one read, with no join.
@@ -14,8 +16,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
1416 use ulid::{Generator, Ulid};
1517
1618 use crate::constant::{
17- CHAT_MESSAGE_TABLE, CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, MAX_ERROR_CODE_LEN,
18- STALE_ERROR_CODE,
19+ CHAT_MESSAGE_TABLE, CHATBOT_CLAIM, CHATBOT_CLAIM_BATCH, CHATBOT_CLAIM_RECLAIM_SECS,
20+ CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, MAX_ERROR_CODE_LEN, STALE_ERROR_CODE,
1921 };
2022 use crate::database::Database;
2123 use crate::domain::chatbot_thread::ChatbotThreadId;
@@ -145,6 +147,15 @@ pub struct ChatbotMessage {
145147 error_code: Option<String>,
146148 created_at: Timestamp,
147149 completed_at: Option<Timestamp>,
150+ /// Which replica's claim loop owes this turn an answer, and when it said
151+ /// so. `None` means nobody has taken it; a claim older than
152+ /// [`CHATBOT_CLAIM_RECLAIM_SECS`] is a claimer that died, and the turn goes
153+ /// back on the queue (see [`ChatbotMessage::claim_pending`]).
154+ ///
155+ /// Never read by an HTTP handler and never in the DTO: whose process is
156+ /// answering is deployment plumbing, not something a client can act on.
157+ claimed_by: Option<String>,
158+ claimed_at: Option<Timestamp>,
148159 }
149160
150161 impl ChatbotMessage {
@@ -233,6 +244,8 @@ impl ChatbotMessage {
233244 error_code: None,
234245 created_at: now,
235246 completed_at: Some(now),
247+ claimed_by: None,
248+ claimed_at: None,
236249 },
237250 db,
238251 )
@@ -258,6 +271,8 @@ impl ChatbotMessage {
258271 error_code: None,
259272 created_at: Timestamp::now(),
260273 completed_at: None,
274+ claimed_by: None,
275+ claimed_at: None,
261276 },
262277 db,
263278 )
@@ -337,6 +352,59 @@ impl ChatbotMessage {
337352 Ok(messages)
338353 }
339354
355+ /// Take up to [`CHATBOT_CLAIM_BATCH`] unanswered turns for the claimant
356+ /// `me`, and hand back the rows now owed an answer by *this* process.
357+ ///
358+ /// The queue read. It is deliberately blind to which capabilities exist
359+ /// anywhere: the caller has already asked its own in-process registry
360+ /// whether it can answer, and that registry — never the `ai_worker` gate —
361+ /// is what makes a claim honest. Claiming a turn this process cannot
362+ /// dispatch would park it for a whole reclaim horizon.
363+ ///
364+ /// A lost race is not an error: the guard is re-evaluated per record inside
365+ /// the `UPDATE`, so a row a peer took simply does not come back. A
366+ /// transaction conflict is the same verdict one layer down and yields an
367+ /// empty batch rather than a failure — the next poll re-reads the queue,
368+ /// which is also the retry the conflict asks for.
369+ pub async fn claim_pending(me: &str, db: &Database) -> Result<Vec<ChatbotMessage>, AppError> {
370+ let result = db
371+ .query(CHATBOT_CLAIM)
372+ .bind(("me", me.to_string()))
373+ .bind(("batch", CHATBOT_CLAIM_BATCH))
374+ .bind(("stale_ms", CHATBOT_PENDING_STALE_SECS * 1_000))
375+ .bind(("reclaim_ms", CHATBOT_CLAIM_RECLAIM_SECS * 1_000))
376+ .await
377+ .and_then(|response| response.check());
378+ match result {
379+ // Statement 0 is the `LET`; the claimed rows are statement 1.
380+ Ok(mut response) => Ok(response.take::<Vec<ChatbotMessage>>(1)?),
381+ Err(err) if lost_the_claim(&err) => Ok(Vec::new()),
382+ Err(err) => Err(err.into()),
383+ }
384+ }
385+
386+ /// The user turn this reserved answer belongs to: the newest `user` row
387+ /// written before it in the same thread.
388+ ///
389+ /// Ordered by `created_at` then `id`, exactly like every other read path —
390+ /// the two rows one POST writes routinely share a millisecond, so the id
391+ /// tie-break is what keeps this from picking the prompt of the *previous*
392+ /// turn (see [`IDS`]).
393+ pub async fn prompt_for(&self, db: &Database) -> Result<Option<ChatbotMessage>, AppError> {
394+ let mut result = db
395+ .query(
396+ "SELECT * FROM chatbot_message WHERE thread_id = $conv AND role = 'user' \
397+ AND (created_at < $at OR (created_at = $at AND id < $id)) \
398+ ORDER BY created_at DESC, id DESC LIMIT 1",
399+ )
400+ .bind(("conv", self.thread_id.record()))
401+ .bind(("at", self.created_at.as_millis()))
402+ .bind(("id", self.id.record()))
403+ .await?
404+ .check()?;
405+ Ok(result.take::<Vec<ChatbotMessage>>(0)?.into_iter().next())
406+ }
407+
340408 /// Read one turn only if `user` owns it — the poll loop's read.
341409 pub async fn read_for(
342410 id: &ChatbotMessageId,
@@ -409,6 +477,23 @@ impl ChatbotMessage {
409477 }
410478 }
411479
480+/// A concurrent claim that the key-value layer decided against us, rather than
481+/// a broken query. Read from the *typed* surface: every engine's conflict
482+/// wording funnels into `QueryError::TransactionConflict` (surrealdb-core
483+/// 3.2.3 `err/to_types.rs:295`), where a substring match covers only whichever
484+/// wording the engine of the day happens to use.
485+///
486+/// Deliberately a second copy of `database::lost_the_race` rather than a shared
487+/// helper: that one is private to the boot election, which is owned elsewhere
488+/// and must not gain a caller. Five lines is the cheaper coupling.
489+fn lost_the_claim(err: &surrealdb::Error) -> bool {
490+ use surrealdb::types::{ErrorDetails, QueryError};
491+ matches!(
492+ err.details(),
493+ ErrorDetails::Query(Some(QueryError::TransactionConflict))
494+ )
495+}
496+
412497 #[cfg(test)]
413498 mod tests {
414499 use super::*;
@@ -478,6 +563,28 @@ mod tests {
478563 }
479564 }
480565
566+ #[test]
567+ fn the_claim_horizon_sits_between_the_inference_and_the_stale_window() {
568+ // Both bounds are load-bearing and neither is decoration:
569+ // below the AI request timeout, a reclaim fires while the first
570+ // claimer is still legitimately waiting and two services answer the
571+ // same turn; at or above the staleness horizon a turn stops being
572+ // claimable before the reclaim could ever fire, so a dead claimer's
573+ // turn is never retried at all.
574+ use crate::constant::AI_DEFAULT_REQUEST_TIMEOUT_SECS;
575+ assert!(
576+ CHATBOT_CLAIM_RECLAIM_SECS > AI_DEFAULT_REQUEST_TIMEOUT_SECS as i64,
577+ "a reclaim inside a legitimate inference double-answers the turn"
578+ );
579+ #[allow(clippy::assertions_on_constants)]
580+ {
581+ assert!(
582+ CHATBOT_CLAIM_RECLAIM_SECS < CHATBOT_PENDING_STALE_SECS,
583+ "a reclaim horizon past the staleness window can never fire"
584+ );
585+ }
586+ }
587+
481588 #[tokio::test]
482589 async fn stale_pending_projects_as_failed() {
483590 let aged = |secs: i64| {
@@ -492,6 +599,8 @@ mod tests {
492599 error_code: None,
493600 created_at: Timestamp::from_millis(Timestamp::now().as_millis() - secs * 1_000),
494601 completed_at: None,
602+ claimed_by: None,
603+ claimed_at: None,
495604 }
496605 .projected()
497606 };
src/domain/user.rsmodified+26 -3
@@ -256,6 +256,21 @@ impl User {
256256 username: Username,
257257 password_hash: PasswordHash,
258258 db: &Database,
259+ ) -> Result<User, AppError> {
260+ Self::create_with_role(username, password_hash, Role::Student, db).await
261+ }
262+
263+ /// The one row-minting path. `role` is written *with* the row rather than
264+ /// patched on afterwards, which is what makes the admin seed atomic: a
265+ /// create-then-promote pair can be interrupted between its halves (a SIGKILL,
266+ /// or a cancelled future), and the row left behind is an ordinary student
267+ /// account that [`User::ensure_admin`] must then refuse to touch — a
268+ /// deployment with no admin and no way for a later boot to repair it.
269+ async fn create_with_role(
270+ username: Username,
271+ password_hash: PasswordHash,
272+ role: Role,
273+ db: &Database,
259274 ) -> Result<User, AppError> {
260275 if Self::find_by_username(username.as_str(), db)
261276 .await?
@@ -267,7 +282,7 @@ impl User {
267282 id: UserId::generate(),
268283 username,
269284 password_hash,
270- role: Role::Student,
285+ role,
271286 name: None,
272287 surname: None,
273288 email: None,
@@ -320,8 +335,16 @@ impl User {
320335 Ok(())
321336 }
322337 None => {
323- let created = Self::create(username, password.hash_async().await?, db).await?;
324- let admin = created.set_role(Role::Admin, db).await?;
338+ // One statement, admin from birth. Never create-then-promote:
339+ // an interruption between those two writes leaves a student row
340+ // holding ADMIN_USERNAME, which the `Some(_)` arm above then
341+ // refuses to promote — forever, on every subsequent boot. There
342+ // is no marker that could tell such a row apart from a stranger
343+ // who registered the name first, so the hole cannot be healed
344+ // later; it has to be impossible to open.
345+ let admin =
346+ Self::create_with_role(username, password.hash_async().await?, Role::Admin, db)
347+ .await?;
325348 tracing::info!(username = admin.username.as_str(), "seeded admin account");
326349 Ok(())
327350 }
src/lib.rsmodified+12 -1
@@ -42,7 +42,7 @@ use crate::state::AppState;
4242 (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)"),
4343 (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"),
4444 (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`"),
45- (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"),
45+ (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"),
4646 (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"),
4747 (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`)"),
4848 (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 {
8686 /// Also serves interactive docs: Swagger UI at `/swagger`, raw spec at
8787 /// `/api-docs/openapi.json`. Root `/` mirrors the health probe.
8888 pub fn build_router(state: AppState) -> Router {
89+ // The AI bridge's two database-backed halves, wired here because this is
90+ // the only place holding the bridge and the database at once: the
91+ // `ai_worker` gate (so peers can see the workers this process holds) and
92+ // this replica's chat claim loop. `attach_presence` returning `true` means
93+ // this call was the first, which is what keeps it to one loop per process.
94+ if let Some(bridge) = state.ai.clone()
95+ && bridge.attach_presence(state.db.clone())
96+ {
97+ web::chatbot::spawn_claim_loop(bridge, state.db.clone());
98+ }
99+
89100 let (router, api) = OpenApiRouter::with_openapi(ApiDoc::openapi())
90101 .route("/", get(health))
91102 .routes(routes!(health))
src/main.rsmodified+3 -21
@@ -1,7 +1,6 @@
11 use anyhow::Context;
22 use hezarfen_backend::config::Config;
33 use hezarfen_backend::database::Database;
4-use hezarfen_backend::domain::user::{Password, User, Username};
54 use hezarfen_backend::rate_limit::UserRateLimiter;
65 use hezarfen_backend::state::{AppState, DbHealth};
76 use hezarfen_backend::{build_router, database};
@@ -17,11 +16,12 @@ async fn main() -> anyhow::Result<()> {
1716 .init();
1817
1918 let cfg = Config::from_env();
20- let db = database::init(&cfg).await?;
2119 // Hash the login decoy now, so the first unknown-username login is not the
2220 // one request that pays for it (see `PasswordHash::prewarm_decoy`).
2321 hezarfen_backend::domain::user::PasswordHash::prewarm_decoy();
24- seed_admin(&cfg, &db).await?;
22+ // Schema *and* the admin seed: both are boot work that must happen once
23+ // across overlapping processes, so both live behind the boot election.
24+ let db = database::init(&cfg).await?;
2525 let db_up = DbHealth::default();
2626 keepalive(db.clone(), db_up.clone());
2727 tokio::fs::create_dir_all(&cfg.files_path)
@@ -94,24 +94,6 @@ fn keepalive(db: Database, health: DbHealth) {
9494 });
9595 }
9696
97-/// Apply the `ADMIN_USERNAME` / `ADMIN_PASSWORD` bootstrap, if configured.
98-/// Both-or-neither: half a credential pair is a deployment mistake, so it
99-/// aborts startup rather than silently running without the seed.
100-async fn seed_admin(cfg: &Config, db: &Database) -> anyhow::Result<()> {
101- match (&cfg.admin_username, &cfg.admin_password) {
102- (Some(username), Some(password)) => {
103- let username = Username::try_new(username).context("invalid ADMIN_USERNAME")?;
104- let password = Password::try_new(password).context("invalid ADMIN_PASSWORD")?;
105- User::ensure_admin(username, password, db)
106- .await
107- .context("failed to seed the admin account")?;
108- Ok(())
109- }
110- (None, None) => Ok(()),
111- _ => anyhow::bail!("ADMIN_USERNAME and ADMIN_PASSWORD must be set together"),
112- }
113-}
114-
11597 /// Resolve on SIGINT (Ctrl-C) or SIGTERM. As PID 1 in a container the process
11698 /// gets no default signal handling, so without this a `podman stop` waits out
11799 /// its grace period and SIGKILLs us — dropping in-flight requests mid-write.
src/web/chatbot.rsmodified+141 -43
@@ -7,10 +7,16 @@
77 //!
88 //! Sending is asynchronous by design. `POST .../messages` writes the user's
99 //! turn plus an empty `pending` assistant row and answers `202` immediately;
10-//! the bridge round trip happens in a spawned task, because an inference can
11-//! outlast the request-timeout layer that guards every HTTP handler. The client
12-//! then either polls `GET .../messages/{mid}` or opens its SSE stream — both
13-//! read the same row, so they can never disagree.
10+//! an inference can outlast the request-timeout layer that guards every HTTP
11+//! handler, so nothing is awaited on the request path. The client then either
12+//! polls `GET .../messages/{mid}` or opens its SSE stream — both read the same
13+//! row, so they can never disagree.
14+//!
15+//! The pending row *is* the job. It used to be answered by a `tokio::spawn`
16+//! from the POST, which meant a restart orphaned every turn in flight; since
17+//! 2026-07-27 it is claimed off the database by [`spawn_claim_loop`], so the
18+//! turn is answered by whichever process holds a `chat.reply` worker — the one
19+//! that accepted it, a peer replica, or the one that comes up after a restart.
1420
1521 use std::time::Duration;
1622
@@ -29,9 +35,10 @@ use utoipa_axum::router::OpenApiRouter;
2935 use utoipa_axum::routes;
3036
3137 use crate::ai::chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn};
32-use crate::ai::{AiBridge, AiError};
38+use crate::ai::{AiBridge, AiError, presence};
3339 use crate::constant::{
34- AI_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN, MIN_CHUNK_CHARS, REPLY_CHUNKS,
40+ AI_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, CHATBOT_CLAIM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN,
41+ MIN_CHUNK_CHARS, REPLY_CHUNKS,
3542 };
3643 use crate::database::Database;
3744 use crate::domain::chatbot_message::{
@@ -345,12 +352,17 @@ async fn list_messages(
345352 /// answer itself lands later, in the reserved assistant row.
346353 ///
347354 /// Order matters and is deliberate: the per-user rate limit is charged
348-/// *before* anything is written, so a refused turn leaves no trace; the AI
349-/// bridge is checked for a `chat.reply` worker *before* the rows exist, so an
350-/// unavailable service produces a `503` and no dead pending row. Once the rows
351-/// are written the turn always settles — the answering task stamps
352-/// `complete`/`failed`, a reader projects a long-stale `pending` as failed, and
353-/// the boot sweep repairs whatever a process death left behind.
355+/// *before* anything is written, so a refused turn leaves no trace;
356+/// availability is checked *before* the rows exist, so an unavailable service
357+/// produces a `503` and no dead pending row.
358+///
359+/// The pending row is a claimed job, not an in-process task: whichever backend
360+/// process holds a `chat.reply` worker picks it up (within ~200ms) and answers
361+/// it, so a restart no longer strands the turn — and a process with no worker
362+/// of its own still accepts turns its peers can answer. The turn always
363+/// settles: the claiming process stamps `complete`/`failed`, a claim its owner
364+/// never finishes is retried, a reader projects a long-stale `pending` as
365+/// failed, and the boot sweep repairs the rest.
354366 #[utoipa::path(
355367 post,
356368 path = "/threads/{id}/messages",
@@ -389,21 +401,32 @@ async fn send_message(
389401 }
390402 let content = ChatContent::try_new(&req.content)?;
391403
392- // The 503 gate, and the only place it is evaluated. `has_capability` is
393- // documented racy — that is fine here: it never guards a write, it only
394- // spares the user a thread full of rows nothing could ever answer.
395- let Some(bridge) = st.ai.clone() else {
404+ // The 503 gate, and the only place it is evaluated. Two questions, asked
405+ // cheapest first, and neither of them guards a write — the gate only
406+ // spares the user a thread full of rows nothing could ever answer:
407+ //
408+ // 1. can *this* replica answer? — the in-process registry, which owns
409+ // the sockets. Authoritative and free, so it is asked first, which is
410+ // also why a single-replica deployment pays no round trip here.
411+ // 2. can any *other* replica? — the heartbeated `ai_worker` table, which
412+ // may lag reality by a heartbeat in either direction. A yes here is
413+ // not a promise that this process can do anything: the turn is
414+ // written and a peer's claim loop picks it up.
415+ //
416+ // Neither answer decides who dispatches. That is the claim loop's own
417+ // registry, every time (see `crate::ai::presence`).
418+ let Some(bridge) = st.ai.as_ref() else {
396419 return Ok(unavailable(
397420 "the AI service is not enabled on this deployment",
398421 ));
399422 };
400- if !bridge.has_capability(AI_CHAT_CAPABILITY) {
423+ if !bridge.has_capability(AI_CHAT_CAPABILITY)
424+ && !presence::serves(&st.db, AI_CHAT_CAPABILITY).await
425+ {
401426 return Ok(unavailable("no AI service is connected right now"));
402427 }
403428
404- let prompt =
405- ChatbotMessage::append_user(thread.get_id(), user.get_id(), content.clone(), &st.db)
406- .await?;
429+ ChatbotMessage::append_user(thread.get_id(), user.get_id(), content, &st.db).await?;
407430 let answer =
408431 ChatbotMessage::append_pending_assistant(thread.get_id(), user.get_id(), &st.db).await?;
409432 // Never fatal: both rows are already written, and failing here would strand
@@ -417,17 +440,11 @@ async fn send_message(
417440 );
418441 }
419442
420- // Never awaited inline: the bridge round trip can outlast the request
421- // timeout that guards every handler, and the POST must return now.
422- tokio::spawn(answer_turn(
423- bridge,
424- st.db.clone(),
425- thread.get_id().clone(),
426- [prompt.get_id().clone(), answer.get_id().clone()],
427- content.as_str().to_string(),
428- settings.get_chatbot_history_turns().max(0) as usize,
429- reply_cap,
430- ));
443+ // Nothing is dispatched here, deliberately. The pending row *is* the job:
444+ // a claim loop — this replica's or a peer's — takes it within one
445+ // `CHATBOT_CLAIM_POLL_MS` tick and answers it. An in-process
446+ // `tokio::spawn` could not survive the restart that orphans the turn,
447+ // which is the whole failure this queue removes.
431448
432449 Ok((
433450 StatusCode::ACCEPTED,
@@ -457,31 +474,112 @@ fn unavailable(message: &str) -> Response {
457474 .into_response()
458475 }
459476
460-/// Fetch one answer and settle its row. Runs detached from the request.
477+/// This replica's share of the chat work queue.
478+///
479+/// One task per process, started by [`crate::build_router`] when a bridge is
480+/// configured. Every [`CHATBOT_CLAIM_POLL_MS`] it asks *its own* registry
481+/// whether it can serve `chat.reply` and, if so, claims a small batch of
482+/// unanswered turns and dispatches them.
483+///
484+/// The registry is the only thing consulted, never the `ai_worker` gate: the
485+/// gate can say a peer has a worker, and claiming on that word would park the
486+/// turn here for a whole reclaim horizon with no socket to send it down (see
487+/// [`crate::ai::presence`]).
488+///
489+/// ponytail: no shutdown handle — the loop runs for the life of the process,
490+/// which is the life of the bridge, and it is idle (one registry read per
491+/// tick, no query) whenever this replica holds no chat worker. Give it a
492+/// `CancellationToken` the day the bridge itself becomes restartable.
493+pub fn spawn_claim_loop(bridge: AiBridge, db: Database) {
494+ // Any unique string. It is only ever compared for equality and read in a
495+ // log line: a claim identifies the *process*, and a claim nobody renews
496+ // expires by age rather than by anyone recognising the claimant.
497+ let me = ulid::Ulid::new().to_string();
498+ tokio::spawn(async move {
499+ let mut ticker = tokio::time::interval(Duration::from_millis(CHATBOT_CLAIM_POLL_MS));
500+ ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
501+ loop {
502+ ticker.tick().await;
503+ // The DISPATCHER's answer, and the gate that matters here.
504+ if !bridge.has_capability(AI_CHAT_CAPABILITY) {
505+ continue;
506+ }
507+ let claimed = match ChatbotMessage::claim_pending(&me, &db).await {
508+ Ok(claimed) => claimed,
509+ Err(err) => {
510+ tracing::warn!("could not claim chat turns: {err}");
511+ continue;
512+ }
513+ };
514+ if claimed.is_empty() {
515+ continue;
516+ }
517+ // Read once per batch, not per turn. Unlike the old in-process
518+ // spawn this is the policy live when the turn is *answered* rather
519+ // than when it was accepted — unavoidable once the answering
520+ // process may not be the accepting one, and the window is one poll
521+ // tick wide in the normal case.
522+ let settings = match Settings::load(&db).await {
523+ Ok(settings) => settings,
524+ Err(err) => {
525+ tracing::warn!("could not load settings for a claimed chat turn: {err}");
526+ continue;
527+ }
528+ };
529+ let reply_cap = content_cap(&settings);
530+ let history_turns = settings.get_chatbot_history_turns().max(0) as usize;
531+ for answer in claimed {
532+ // One task per turn: the bridge round trip can take tens of
533+ // seconds and must not hold up the next poll.
534+ tokio::spawn(answer_turn(
535+ bridge.clone(),
536+ db.clone(),
537+ answer,
538+ history_turns,
539+ reply_cap,
540+ ));
541+ }
542+ }
543+ });
544+}
545+
546+/// Fetch one claimed turn's answer and settle its row.
461547 ///
462548 /// Every path settles: a row left `pending` would show as a spinner forever.
463-/// The settings snapshot is passed in rather than re-read — the whole turn is
464-/// then judged by the policy that was live when it was accepted, and a manager
465-/// editing the limits mid-flight cannot make the answer be measured by a rule
466-/// the prompt never saw (it also saves a database round trip per turn).
467-#[allow(clippy::too_many_arguments)]
468549 async fn answer_turn(
469550 bridge: AiBridge,
470551 db: Database,
471- thread: ChatbotThreadId,
472- // The two rows this turn just wrote; both are excluded from the history.
473- fresh: [ChatbotMessageId; 2],
474- prompt: String,
552+ answer: ChatbotMessage,
475553 history_turns: usize,
476554 reply_cap: usize,
477555 ) {
478- let answer_id = fresh[1].clone();
556+ let answer_id = answer.get_id().clone();
557+ let thread = answer.get_thread_id().clone();
558+ // The question this reserved row was written next to. Recovered from the
559+ // thread rather than carried in memory, because the process that accepted
560+ // the turn may no longer exist.
561+ let prompt = match answer.prompt_for(&db).await {
562+ Ok(Some(prompt)) => prompt,
563+ Ok(None) => {
564+ // A reserved answer with no question before it. Only reachable if
565+ // the user row was deleted out from under it; there is nothing to
566+ // ask, so settle rather than re-claim it every reclaim horizon.
567+ tracing::warn!("chat answer {} has no prompt to send", answer_id.key());
568+ let _ = ChatbotMessage::fail(&answer_id, "internal", &db).await;
569+ return;
570+ }
571+ Err(err) => {
572+ tracing::warn!("could not read the prompt for {}: {err}", answer_id.key());
573+ return;
574+ }
575+ };
576+ let fresh = [prompt.get_id().clone(), answer_id.clone()];
479577 let settled = match fetch_reply(
480578 &bridge,
481579 &db,
482580 &thread,
483581 &fresh,
484- prompt,
582+ prompt.get_content().as_str().to_string(),
485583 history_turns,
486584 reply_cap,
487585 )
tests/ai_bridge.rsmodified+221 -0
@@ -1162,6 +1162,227 @@ async fn a_blank_chat_answer_fails_as_empty_reply() {
11621162 assert_eq!(turn["error_code"], "empty_reply");
11631163 }
11641164
1165+// ----------------------------------------------------------- claim queue --
1166+//
1167+// A pending assistant row is a durable job, not an in-process task. These
1168+// prove the three things that buys: a turn nobody could answer yet is answered
1169+// when a worker appears, a claim whose owner died is taken back, and a turn is
1170+// dispatched exactly once no matter how many replicas are watching the queue.
1171+
1172+use hezarfen_backend::constant::{CHATBOT_CLAIM_POLL_MS, CHATBOT_CLAIM_RECLAIM_SECS};
1173+use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage};
1174+use hezarfen_backend::domain::chatbot_thread::ChatbotThreadId;
1175+use hezarfen_backend::domain::user::UserId;
1176+
1177+/// Write one turn's two rows straight to the queue, bypassing the POST — what
1178+/// a replica that has since died would have left behind. Returns the reserved
1179+/// assistant row's key.
1180+async fn queue_turn(app: &Router, db: &Database, cookie: &str, thread: &str, text: &str) -> String {
1181+ let me = common::send(app, "GET", "/auth/me", Some(cookie), None).await;
1182+ let user = UserId::from_key(me.body["id"].as_str().expect("own id"));
1183+ let thread = ChatbotThreadId::from_key(thread);
1184+ ChatbotMessage::append_user(&thread, &user, ChatContent::try_new(text).unwrap(), db)
1185+ .await
1186+ .expect("the user's turn");
1187+ ChatbotMessage::append_pending_assistant(&thread, &user, db)
1188+ .await
1189+ .expect("the reserved answer")
1190+ .get_id()
1191+ .key()
1192+ .to_string()
1193+}
1194+
1195+/// A turn nobody has claimed, held by `claimant` since `age_secs` ago.
1196+async fn stamp_claim(db: &Database, mid: &str, claimant: &str, age_secs: i64) {
1197+ db.query(
1198+ "UPDATE $id SET claimed_by = $who, claimed_at = time::unix(time::now()) * 1000 - $age",
1199+ )
1200+ .bind(("id", RecordId::new("chatbot_message", mid.to_string())))
1201+ .bind(("who", claimant.to_string()))
1202+ .bind(("age", age_secs * 1_000))
1203+ .await
1204+ .expect("stamp a claim")
1205+ .check()
1206+ .expect("stamp a claim");
1207+}
1208+
1209+async fn status_of(app: &Router, cookie: &str, thread: &str, mid: &str) -> String {
1210+ let res = common::send(
1211+ app,
1212+ "GET",
1213+ &format!("/chatbot/threads/{thread}/messages/{mid}"),
1214+ Some(cookie),
1215+ None,
1216+ )
1217+ .await;
1218+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1219+ res.body["status"].as_str().expect("status").to_string()
1220+}
1221+
1222+#[tokio::test]
1223+async fn a_turn_written_with_no_worker_is_answered_once_one_appears() {
1224+ // The failure this queue removes: the row used to be answered by a task
1225+ // spawned inside the POST, so a turn that outlived its process — or was
1226+ // written while nothing could serve it — settled `failed` at the staleness
1227+ // horizon and never got an answer at all.
1228+ let bridge = bridge().await;
1229+ let (app, db) = chat_app(&bridge).await;
1230+ let (cookie, thread) = chat_user(&app, "ali").await;
1231+
1232+ // Nothing is connected, so the gate refuses the POST outright…
1233+ let res = common::send(
1234+ &app,
1235+ "POST",
1236+ &format!("/chatbot/threads/{thread}/messages"),
1237+ Some(&cookie),
1238+ Some(json!({ "content": "kimse yokken" })),
1239+ )
1240+ .await;
1241+ assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);
1242+
1243+ // …but a row already on the queue (written by a replica that has since
1244+ // gone) must still be picked up.
1245+ let mid = queue_turn(&app, &db, &cookie, &thread, "kimse yokken").await;
1246+ let _service = connect_service(
1247+ &bridge,
1248+ hello("tutor", &[AI_CHAT_CAPABILITY]),
1249+ Behaviour::Reply("geç gelen cevap".into()),
1250+ )
1251+ .await;
1252+ await_workers(&bridge, 1).await;
1253+
1254+ let turn = settled(&app, &cookie, &thread, &mid).await;
1255+ assert_eq!(turn["status"], "complete", "{turn}");
1256+ assert_eq!(turn["content"], "geç gelen cevap");
1257+}
1258+
1259+#[tokio::test]
1260+async fn a_claim_left_by_a_dead_replica_is_taken_back() {
1261+ let bridge = bridge().await;
1262+ let service = connect_service(
1263+ &bridge,
1264+ hello("tutor", &[AI_CHAT_CAPABILITY]),
1265+ Behaviour::Reply("devraldım".into()),
1266+ )
1267+ .await;
1268+ await_workers(&bridge, 1).await;
1269+ let (app, db) = chat_app(&bridge).await;
1270+ let (cookie, thread) = chat_user(&app, "ali").await;
1271+
1272+ // A claim a peer took moments ago is respected: that peer is presumably
1273+ // still waiting on its inference, and answering alongside it would run the
1274+ // model twice for one reply.
1275+ let live = queue_turn(&app, &db, &cookie, &thread, "başkası bakıyor").await;
1276+ stamp_claim(&db, &live, "a-live-peer", 1).await;
1277+ for _ in 0..10 {
1278+ tokio::time::sleep(Duration::from_millis(CHATBOT_CLAIM_POLL_MS)).await;
1279+ }
1280+ assert_eq!(
1281+ status_of(&app, &cookie, &thread, &live).await,
1282+ "pending",
1283+ "a live peer's claim was stolen"
1284+ );
1285+ assert!(service.seen().is_empty(), "{:?}", service.seen());
1286+
1287+ // The same claim, past the reclaim horizon, is a claimant that died. The
1288+ // turn goes back on the queue rather than waiting out its staleness
1289+ // window with nobody answering it.
1290+ stamp_claim(&db, &live, "a-dead-peer", CHATBOT_CLAIM_RECLAIM_SECS + 1).await;
1291+ let turn = settled(&app, &cookie, &thread, &live).await;
1292+ assert_eq!(turn["status"], "complete", "{turn}");
1293+ assert_eq!(turn["content"], "devraldım");
1294+ assert_eq!(service.seen().len(), 1, "{:?}", service.seen());
1295+}
1296+
1297+#[tokio::test]
1298+async fn a_claimed_turn_is_dispatched_exactly_once() {
1299+ // The claim is what stops the poll loop from re-sending a turn every tick
1300+ // while the first inference is still running. A silent service holds the
1301+ // stream open, so every extra dispatch would show up in `seen()`.
1302+ let bridge = bridge_with_timeout(Duration::from_secs(30)).await;
1303+ let service = connect_service(
1304+ &bridge,
1305+ hello("tutor", &[AI_CHAT_CAPABILITY]),
1306+ Behaviour::Silent,
1307+ )
1308+ .await;
1309+ await_workers(&bridge, 1).await;
1310+ let (app, _db) = chat_app(&bridge).await;
1311+ let (cookie, thread) = chat_user(&app, "ali").await;
1312+
1313+ let mid = ask(&app, &cookie, &thread, "uzun sürecek bir soru").await;
1314+ await_inflight(&bridge, 1).await;
1315+ // Ten poll ticks with the answer still outstanding.
1316+ tokio::time::sleep(Duration::from_millis(CHATBOT_CLAIM_POLL_MS * 10)).await;
1317+ assert_eq!(
1318+ service.seen().len(),
1319+ 1,
1320+ "one turn, one dispatch: {:?}",
1321+ service.seen()
1322+ );
1323+ assert_eq!(status_of(&app, &cookie, &thread, &mid).await, "pending");
1324+}
1325+
1326+#[tokio::test]
1327+async fn a_replica_with_no_worker_accepts_a_turn_its_peer_answers() {
1328+ // Two replicas, one database, and the worker dialled into exactly one of
1329+ // them. The other has nothing to dispatch with — its own registry says so
1330+ // — yet it must still accept the turn, because the `ai_worker` gate can
1331+ // see its peer. And exactly one of the two answers it.
1332+ let db = hezarfen_backend::database::init_mem()
1333+ .await
1334+ .expect("mem db");
1335+ let quiet = bridge().await;
1336+ let serving = bridge().await;
1337+ let app_quiet = replica(&quiet, &db);
1338+ let app_serving = replica(&serving, &db);
1339+
1340+ let service = connect_service(
1341+ &serving,
1342+ hello("tutor", &[AI_CHAT_CAPABILITY]),
1343+ Behaviour::Reply("komşudan cevap".into()),
1344+ )
1345+ .await;
1346+ await_workers(&serving, 1).await;
1347+ assert!(!quiet.has_capability(AI_CHAT_CAPABILITY), "no local worker");
1348+ // The gate is heartbeated, so give the serving replica's first beat time
1349+ // to publish its worker before asking the replica that holds none.
1350+ for _ in 0..300 {
1351+ if hezarfen_backend::ai::presence::serves(&db, AI_CHAT_CAPABILITY).await {
1352+ break;
1353+ }
1354+ tokio::time::sleep(Duration::from_millis(10)).await;
1355+ }
1356+
1357+ let (cookie, thread) = chat_user(&app_quiet, "ali").await;
1358+ let mid = ask(&app_quiet, &cookie, &thread, "komşuya soru").await;
1359+ let turn = settled(&app_quiet, &cookie, &thread, &mid).await;
1360+ assert_eq!(turn["status"], "complete", "{turn}");
1361+ assert_eq!(turn["content"], "komşudan cevap");
1362+ assert_eq!(service.seen().len(), 1, "{:?}", service.seen());
1363+ // The answer is one row, so the peer that accepted the turn reads exactly
1364+ // what the peer that answered it wrote.
1365+ assert_eq!(
1366+ status_of(&app_serving, &cookie, &thread, &mid).await,
1367+ "complete"
1368+ );
1369+}
1370+
1371+/// A second process against the same database: its own bridge, its own claim
1372+/// loop, one shared queue.
1373+fn replica(bridge: &AiBridge, db: &Database) -> Router {
1374+ hezarfen_backend::build_router(hezarfen_backend::state::AppState {
1375+ db: db.clone(),
1376+ files_path: common::files_dir(),
1377+ cookie_secure: false,
1378+ rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
1379+ chatbot_limit: Default::default(),
1380+ exam_presence: Default::default(),
1381+ db_up: Default::default(),
1382+ ai: Some(bridge.clone()),
1383+ })
1384+}
1385+
11651386 // ------------------------------------------------------------- boot wiring --
11661387 //
11671388 // `ai::start_bridge` is the seam between deployment config and the listener.
tests/limits_completeness.rsmodified+51 -0
@@ -51,6 +51,10 @@ const EXCLUDED: &[(&str, &str)] = &[
5151 ("AI_ALPN", "QUIC bridge ALPN"),
5252 ("AI_MAX_FRAME_BYTES", "QUIC bridge frame ceiling"),
5353 ("AI_DEFAULT_REQUEST_TIMEOUT_SECS", "AI inference deadline"),
54+ (
55+ "AI_MAX_REQUEST_TIMEOUT_SECS",
56+ "ceiling on the configured AI inference deadline",
57+ ),
5458 ("AI_MAX_CONCURRENT_PER_WORKER", "AI worker concurrency cap"),
5559 (
5660 "AI_DEFAULT_CONCURRENT_PER_WORKER",
@@ -71,6 +75,30 @@ const EXCLUDED: &[(&str, &str)] = &[
7175 "CHATBOT_PENDING_STALE_SECS",
7276 "when a stuck answer is declared failed",
7377 ),
78+ // The AI worker gate (`ai_worker`) and the chat claim queue. Both are
79+ // between-replica plumbing: a browser cannot observe which process holds a
80+ // worker or who claimed its turn, and it already learns everything it can
81+ // act on from the 202/503 and the turn's own `status`.
82+ ("AI_WORKER_TABLE", "AI worker presence table"),
83+ ("AI_WORKER_ANNOUNCE", "AI worker presence upsert"),
84+ ("AI_WORKER_WITHDRAW", "AI worker presence delete"),
85+ ("AI_WORKER_SWEEP", "AI worker presence expiry"),
86+ ("AI_WORKER_SERVES", "AI worker presence read"),
87+ (
88+ "AI_WORKER_HEARTBEAT_SECS",
89+ "how often a replica restamps its AI workers",
90+ ),
91+ (
92+ "AI_WORKER_LEASE_SECS",
93+ "how long an unrestamped AI worker row is believed",
94+ ),
95+ ("CHATBOT_CLAIM", "chat claim-queue statement"),
96+ ("CHATBOT_CLAIM_POLL_MS", "chat claim-loop cadence"),
97+ ("CHATBOT_CLAIM_BATCH", "turns claimed per sweep"),
98+ (
99+ "CHATBOT_CLAIM_RECLAIM_SECS",
100+ "when a dead claimer's turn goes back on the queue",
101+ ),
74102 // Seed data for the settings singleton, not a bound. The live list is on
75103 // `GET /settings`, which is where a client must read it — publishing the
76104 // default too would invite rendering it instead of the school's actual one.
@@ -89,6 +117,29 @@ const EXCLUDED: &[(&str, &str)] = &[
89117 // Schema and query text. `constant.rs` is the single home for every
90118 // constant, so the migration batches live there too — a client never sees
91119 // a byte of SurrealQL.
120+ // The boot leader election. A client never sees the lock, and the timings
121+ // are startup mechanics between processes — publishing them would invite a
122+ // frontend to reason about a boot it cannot observe.
123+ ("MIGRATION_LOCK_DDL", "boot lock table definition"),
124+ ("MIGRATION_LOCK_CLAIM", "boot lock claim statement"),
125+ ("MIGRATION_LOCK_STATE", "boot lock read statement"),
126+ ("MIGRATION_LOCK_TAKEOVER", "boot lock takeover statement"),
127+ ("MIGRATION_LOCK_HEARTBEAT", "boot lock lease renewal"),
128+ ("MIGRATION_LOCK_STAMP", "boot lock completion stamp"),
129+ (
130+ "MIGRATION_LOCK_LEASE_SECS",
131+ "how long an unrenewed boot lock may be taken over after",
132+ ),
133+ ("MIGRATION_LOCK_HEARTBEAT_SECS", "boot lock renewal cadence"),
134+ (
135+ "MIGRATION_LOCK_WAIT_SECS",
136+ "how long a non-leader waits for the boot migration",
137+ ),
138+ ("MIGRATION_LOCK_POLL_MS", "boot lock poll cadence"),
139+ (
140+ "MIGRATION_BATCHES",
141+ "the batch list the boot executes and fingerprints",
142+ ),
92143 ("PRE_REPAIR", "pre-DDL data repair batch"),
93144 ("MIGRATION", "SCHEMAFULL DDL batch"),
94145 ("BACKFILL", "post-DDL data backfill batch"),