diff --git a/README.md b/README.md index bf82194..7f32488 100644 --- a/README.md +++ b/README.md @@ -408,14 +408,14 @@ student's budget on another's. `0` disables it like the other two. It is charged before anything is written, so a `429` leaves no trace (see "Chatbot"). -All three tiers are **fleet-wide, not per replica**. Admission stays in memory -(no request ever waits on the database to be let in), and a background task in -each replica folds its new admits into one shared `rate_limit` row per tier + -client + minute every 2 seconds, then caps itself by the total that comes back. -Two replicas therefore enforce one budget, with one caveat: within a single -2-second interval a client that reaches both can spend up to the tier's budget -on each before the shared total tightens them. If the database is down the -tiers simply fall back to their own local budgets — nobody is refused for it. +All three tiers admit from memory — no request ever waits on the database to be +let in — but the window **outlives the process**. A background task folds each +tier's new admits into one shared `rate_limit` row per tier + client + minute +every 2 seconds, then caps the in-memory bucket by the total that comes back, +so a restart mid-minute does not hand every client a fresh budget. One caveat: +a just-started process can spend up to the tier's budget in the 2 seconds +before its first fold tightens it. If the database is down the tiers simply +fall back to their own local budgets — nobody is refused for it. Behind a reverse proxy every connection carries the proxy's address, so also set `TRUST_PROXY=true` to key clients by the rightmost `X-Forwarded-For` entry @@ -1006,8 +1006,8 @@ A booking is `pending`, `approved`, `rejected`, or `cancelled`. The first two are **live** and hold the slot; rejecting or cancelling frees it for someone else immediately (the slot carries an `occupied` counter, taken by a booking and handed back in the same transaction as the reject or cancel that settles -it, so the guard holds across replicas). The -decisions: +it, so the seat is decided by the database rather than by a count two +concurrent bookings can both read as free). The decisions: - `PATCH /{id}/approve` — the slot's teacher (or manager+) confirms. Refused (`409`) when the effective window has already started. @@ -1547,14 +1547,14 @@ account. room back and the charge **can be paid again** — and reversing that refund takes the room back with it. Money that came back out is not money the school still holds. -- **The over-payment cap is advisory.** The `409` past a charge's or a credit's - worth is a cross-record fold taken under a process-local lock, and with two - replicas serving, two payments recorded in the same instant can together - overshoot. That is accepted deliberately: this is human data entry at an - office desk, not a concurrent machine load, the outcome is an over-paid - charge that is plainly visible in the statement, and it is undone by - appending a refund. Both lines are true records of money that really - arrived — refusing them would be the worse lie. +- **The over-payment cap is not the database's.** The `409` past a charge's or + a credit's worth is a cross-record fold, which SurrealDB cannot enforce on + its own; it holds because the backend is one process and the fold, and the + append it authorizes, are taken under one lock. Should an over-payment ever + be recorded anyway it is not a crisis: this is human data entry at an office + desk, the outcome is an over-paid charge that is plainly visible in the + statement, and it is undone by appending a refund. Both lines are true + records of money that really arrived — refusing them would be the worse lie. - **There is no payment gateway and no card data, ever**, and none is planned: nothing here talks to a bank, a PSP, or a card network. `method` is free text ("cash", "havale", …) describing how money that already arrived was handed @@ -2376,39 +2376,32 @@ agree about `truncated` exactly as they do about every other field. | `404` | no such thread or message — or not the caller's | | `409` | already at `max_chatbot_threads`; delete a thread first | | `429` | over `RATE_LIMIT_CHATBOT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` | -| `503` | no service anywhere in the deployment offers `chat.reply` — **nothing was written**, retry later | +| `503` | no connected service offers `chat.reply` — **nothing was written**, retry later | The `503` ordering matters: availability is checked before the rows exist, so an unavailable service leaves no dead `pending` row behind, and the rate limit -is charged before that, so a refused turn leaves no trace at all. The check -asks two questions — is a `chat.reply` worker connected to *this* backend -process, and failing that, is one connected to any other — so a deployment -running several backends accepts a turn as long as one of them can answer it. - -### A turn is a claimed job - -The `pending` assistant row *is* the work item. Backend processes poll it: a -process holding a `chat.reply` worker claims an unanswered turn, dispatches it -over its own connection, and stamps the result. That is why a `202` is a real -promise — a backend restart no longer strands the turn it had just accepted, -and a turn accepted by a process with no worker of its own is answered by one -that has. The cost is up to ~200 ms before the request leaves for the service. -A claim whose owner disappears is taken back after 90 seconds. +is charged before that, so a refused turn leaves no trace at all. The check is +the backend's own worker registry, which owns the QUIC sockets and is therefore +the whole truth about what can be answered. ### A turn always settles Once the two rows exist the answer never stays `pending` forever, through three independent mechanisms: -- the process that claimed the turn stamps `complete` or `failed` — the normal - path, and a claim its owner never finishes is retried by another; +- the task that owns the bridge round trip stamps `complete` or `failed` — + the normal path; - a reader **projects** a `pending` row older than 300 seconds as `failed`/`timed_out` (a read-time projection, not a write — the row is left for the task that may still own it); - a **boot sweep** flips every leftover `pending` past the 300-second horizon to `failed`/`interrupted`, which is what a process death mid-inference looks - like. It leaves rows another process has claimed recently alone, so a - restarting backend cannot shoot down a turn its peer is answering. + like. Younger rows are left alone, since one may still be in flight. + +A restart therefore loses a turn that was in flight: it settles +`failed`/`interrupted` rather than being answered. Accepted — the backend is a +single process with stop-the-world deploys, so there is no peer that could have +taken it over. Two more verdicts come from inspecting the answer: an **empty** reply is reported as `failed`/`empty_reply` (a blank bubble is indistinguishable from a @@ -2460,13 +2453,21 @@ context without either end having to be redeployed in lockstep. ## Concurrency model -The backend runs as more than one replica against one database, so every -invariant is guarded where all replicas can see it. Three tiers: +The backend runs as **one process against one database**, and that buys less +than it sounds like: every request is an async task, dozens are in flight at +once, and each of them awaits the database in the middle of its work. So +"read, decide, write" is never safe on its own — SurrealDB does not +conflict-check a cross-record `count()` against a concurrent insert +(write-skew), and that fires between two tasks in one process exactly as it +would between two machines. The mutex-only design this replaced was already +losing races at one process. Every invariant is therefore guarded where the +database itself decides the winner. Three tiers: 1. **Single-row conditional writes** — compare-and-set (`save_if_unchanged`), - `UPDATE … WHERE`, stored counters (`domain::cap`), leases. These hold - *across replicas*: the database decides the winner, the loser retries or - gets a 409. + `UPDATE … WHERE`, stored counters (`domain::cap`). A single-record write is + atomic, so of N concurrent tasks exactly the allowed number get a non-empty + result: the database decides the winner, the loser retries + (`CAS_UPDATE_RETRIES`) or gets a 409. 2. **In-transaction `IF … THROW` gates** — the check runs inside the same statement as the write it authorizes, so it is atomic with it. Used where the rule reads the row being written (state machines, delete guards). @@ -2480,24 +2481,32 @@ invariant is guarded where all replicas can see it. Three tiers: are claimed in one transaction (`cap::claim_and_create`), so a duplicate `CREATE` rolls its own seat back instead of costing a stranger their place. 3. **Two accepted races**, reviewed and deliberately left open: - - *Attempt-seq late save* — a save racing a retake can stamp an answer onto - the just-terminal previous sitting. Damage: one history row; the grade of - record (latest `seq`) is never touched. - - *Approved-overlap* — two replicas approving in the same instant can + - *Attempt-seq late save* — an exam-room socket writes into the sitting it + joined with, a choice made before any lock is taken, so a save racing a + retake can stamp an answer onto the just-terminal previous sitting. + Damage: one history row; the grade of record (latest `seq`) is never + touched. + - *Approved-overlap* — two approvals landing in the same instant can double-book a teacher. Damage: one overlapping half-hour, visible to both parties, fixable by cancelling either side. -In-process locks that remain do so for reasons a database write cannot serve: -`PRESENCE_LOCK` guards in-process socket state, `CLAIM_LOCK` keeps one -counter writer per process (the `WHERE` clause is the cap — the lock only -tames the retry loop, and keeps the tests' in-memory engine deterministic), -`APPOINTMENT_LOCK` still collapses the common within-replica overlap case. - -Deployment contract: a release that adds or renames a stored counter must -restart *all* replicas together (`podman compose down` + `up`), never rolling. -An old binary writes rows without touching the new counters, the `= NONE` -backfill guard (correctly) refuses to re-seed, and the resulting permanent -under-count lets a guard approve exactly what it exists to refuse. +In-process locks remain, and they are a *second* line, never the guarantee: +`PRESENCE_LOCK` guards in-process socket state (there is no row to conditional +-write), `CLAIM_LOCK` keeps one counter writer at a time (the `WHERE` clause is +the cap — the lock only tames the retry loop, and keeps the tests' in-memory +engine deterministic), `APPOINTMENT_LOCK` collapses the common overlap case in +front of a rule no single-record write can express. Removing one of them costs +throughput or an accepted race; removing the conditional write behind it costs +the invariant. + +Boot is unconditional: the schema batches, the backfills and the admin seed all +run on every start, because exactly one process ever starts. Deployment is +stop-the-world — `podman compose down` then `up`, never overlapping — and a +release that adds or renames a stored counter *requires* it. An old binary +writes rows without touching the new counter, the `= NONE` backfill guard +(correctly) refuses to re-seed, and the resulting permanent under-count lets a +guard approve exactly what it exists to refuse. In-flight work does not survive +a restart either: a chatbot turn mid-inference settles `failed`/`interrupted`. ## Layout @@ -2532,10 +2541,10 @@ src/ Generator, so same-millisecond rows never scramble key.rs sitting(): the deterministic per-sitting record key shared by attempts, answers, answer images and results (seq 1 stays bare) - cap.rs claim()/release(): the cross-replica count caps — an atomic - `UPDATE parent SET n += 1 WHERE n < cap` on a counter column - of the parent row, replacing the per-process mutexes that - only held while one instance owned the database; + cap.rs claim()/release(): the count caps the database enforces — an + atomic `UPDATE parent SET n += 1 WHERE n < cap` on a counter + column of the parent row, replacing count-then-write mutexes + that could not see a concurrent insert; claim_and_create() commits that seat and the child row in one transaction, for children with a deterministic id text_fold.rs case- and diacritic-insensitive folding for search, shared by @@ -2647,7 +2656,7 @@ src/ Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory db), rate-limit (both tiers, proxy-header and peer-address keying, shipped -limits over every route, two "replicas" sharing one budget over one db), e2e +limits over every route, two limiters sharing one budget over one db), e2e (real TCP + reqwest cookie jar), persistence (tempfile file engine, including close + reopen), ai-bridge (real QUIC on loopback against a fake AI service), ai-protocol (the `hab/1` wire contract, diff --git a/src/ai/mod.rs b/src/ai/mod.rs index c553dbb..3425eaa 100644 --- a/src/ai/mod.rs +++ b/src/ai/mod.rs @@ -15,7 +15,6 @@ //! * [`chat`] — the JSON payloads carried for the `chat.reply` capability //! * [`server`] — the listener, handshake, and [`server::AiBridge::dispatch`] //! * [`registry`] — who is connected here, and who gets the next request -//! * [`presence`] — who is connected *anywhere*, for a cross-replica gate //! * [`tls`] — the listener's certificate //! //! The transport is generic; the features land on top of it. So far that is @@ -23,7 +22,6 @@ pub mod chat; pub mod error; -pub mod presence; pub mod protocol; pub mod registry; pub mod server; diff --git a/src/ai/presence.rs b/src/ai/presence.rs deleted file mode 100644 index 143df90..0000000 --- a/src/ai/presence.rs +++ /dev/null @@ -1,188 +0,0 @@ -//! Who can serve which AI capability *anywhere in the deployment* — the GATE. -//! -//! There are two answers to "is an AI service available", and confusing them -//! is the one way this module can do damage, so they are named: -//! -//! * **The gate — this module, the `ai_worker` table.** It answers "could -//! anything, anywhere, serve `chat.reply`?". Every replica writes a row for -//! each worker whose QUIC connection *it* holds and restamps it every -//! [`AI_WORKER_HEARTBEAT_SECS`]; a row unstamped for -//! [`AI_WORKER_LEASE_SECS`] is ignored and swept, so a replica that dies -//! leaves no permanent phantom. It is a cache of other processes' sockets: -//! it lags a registration by up to one heartbeat and a crash by up to one -//! lease, in *both* directions. Its only job is to spare a user a 503 on a -//! replica that holds no worker itself, because a peer's claim loop will -//! answer the turn. It must never guard a write and must never decide a -//! dispatch. -//! * **The dispatcher — [`crate::ai::registry::Registry`], in process.** It -//! owns the sockets. Only it knows whether *this* replica can answer, and it -//! is the only thing the chat claim loop consults before taking a turn. A -//! claim made on the gate's word would park a turn on a replica with nothing -//! to send it to. -//! -//! The split is why the table is safe to be wrong: nothing downstream of a -//! wrong answer is irreversible. A false yes costs one accepted turn that -//! settles `failed` (or waits out its staleness window); a false no costs one -//! 503 the user can retry. - -use surrealdb::types::RecordId; - -use crate::ai::registry::WorkerSnapshot; -use crate::constant::{ - AI_WORKER_ANNOUNCE, AI_WORKER_LEASE_SECS, AI_WORKER_SERVES, AI_WORKER_SWEEP, AI_WORKER_TABLE, - AI_WORKER_WITHDRAW, -}; -use crate::database::Database; -use crate::error::AppError; - -fn row(id: &str) -> RecordId { - RecordId::new(AI_WORKER_TABLE, id) -} - -/// Publish (or restamp) the workers this replica holds right now. -/// -/// `UPSERT` per worker, and the caller passes the whole live set every -/// heartbeat: a row lost to a database blip, or a worker that registered -/// before the presence table was attached, heals on the next beat instead of -/// staying invisible to every peer forever. -pub async fn announce(db: &Database, workers: &[WorkerSnapshot]) -> Result<(), AppError> { - for worker in workers { - db.query(AI_WORKER_ANNOUNCE) - .bind(("id", row(&worker.id))) - .bind(("service", worker.service.clone())) - .bind(("capabilities", worker.capabilities.clone())) - .await? - .check()?; - } - Ok(()) -} - -/// Drop a worker that said goodbye. Immediate, so a clean disconnect closes -/// the gate now rather than a lease later. -pub async fn withdraw(db: &Database, id: &str) -> Result<(), AppError> { - db.query(AI_WORKER_WITHDRAW) - .bind(("id", row(id))) - .await? - .check()?; - Ok(()) -} - -/// Forget workers nobody restamped within the lease — their replica died -/// without deregistering them. Any replica may run it: the rows are keyed by -/// worker, not by owner, and a live worker's row is never stale. -pub async fn sweep(db: &Database) -> Result<(), AppError> { - db.query(AI_WORKER_SWEEP) - .bind(("lease_ms", AI_WORKER_LEASE_SECS * 1_000)) - .await? - .check()?; - Ok(()) -} - -/// The gate read: does *any* replica hold a worker for `capability`? -/// -/// Errors answer "no" rather than propagating. This is consulted on the 503 -/// path of a request that has not written anything yet, so the worst a -/// database hiccup can do is tell one user to retry — turning it into a 500 -/// would be strictly worse for the same fault. -pub async fn serves(db: &Database, capability: &str) -> bool { - let found: Result, AppError> = async { - Ok(db - .query(AI_WORKER_SERVES) - .bind(("capability", capability.to_string())) - .bind(("lease_ms", AI_WORKER_LEASE_SECS * 1_000)) - .await? - .check()? - .take(0)?) - } - .await; - match found { - Ok(rows) => !rows.is_empty(), - Err(err) => { - tracing::warn!("could not read the AI worker gate: {err}"); - false - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::constant::AI_CHAT_CAPABILITY; - - fn worker(id: &str, capabilities: &[&str]) -> WorkerSnapshot { - WorkerSnapshot { - id: id.to_string(), - service: "tutor".to_string(), - capabilities: capabilities.iter().map(|c| c.to_string()).collect(), - inflight: 0, - max_concurrent: 4, - } - } - - #[tokio::test] - async fn a_stale_row_stops_answering_the_gate() { - // The phantom this exists to prevent: a replica that dies leaves its - // row behind, and without the age filter that row would keep every - // peer's chat endpoint reporting a service that is gone. - let db = crate::database::init_mem().await.unwrap(); - announce(&db, &[worker("w1", &[AI_CHAT_CAPABILITY])]) - .await - .unwrap(); - assert!(serves(&db, AI_CHAT_CAPABILITY).await); - assert!(!serves(&db, "ocr.extract").await, "a capability nobody has"); - - // Age it past the lease, as a dead replica's row ages on its own. - db.query("UPDATE ai_worker SET seen_at = seen_at - $ms") - .bind(("ms", (AI_WORKER_LEASE_SECS + 1) * 1_000)) - .await - .unwrap() - .check() - .unwrap(); - assert!( - !serves(&db, AI_CHAT_CAPABILITY).await, - "a stale row must not hold the gate open" - ); - sweep(&db).await.unwrap(); - let rows: Vec = db - .query("SELECT VALUE id FROM ai_worker") - .await - .unwrap() - .check() - .unwrap() - .take(0) - .unwrap(); - assert!(rows.is_empty(), "the sweep deletes what the read ignores"); - } - - #[tokio::test] - async fn announcing_twice_restamps_rather_than_duplicating() { - let db = crate::database::init_mem().await.unwrap(); - let live = [worker("w1", &[AI_CHAT_CAPABILITY])]; - announce(&db, &live).await.unwrap(); - db.query("UPDATE ai_worker SET seen_at = seen_at - $ms") - .bind(("ms", (AI_WORKER_LEASE_SECS + 1) * 1_000)) - .await - .unwrap() - .check() - .unwrap(); - assert!(!serves(&db, AI_CHAT_CAPABILITY).await); - - announce(&db, &live).await.unwrap(); - assert!(serves(&db, AI_CHAT_CAPABILITY).await, "the beat healed it"); - let rows: Vec = db - .query("SELECT VALUE id FROM ai_worker") - .await - .unwrap() - .check() - .unwrap() - .take(0) - .unwrap(); - assert_eq!(rows.len(), 1, "one worker is one row"); - - withdraw(&db, "w1").await.unwrap(); - assert!( - !serves(&db, AI_CHAT_CAPABILITY).await, - "goodbye is immediate" - ); - } -} diff --git a/src/ai/server.rs b/src/ai/server.rs index c1c5d22..a4b4eae 100644 --- a/src/ai/server.rs +++ b/src/ai/server.rs @@ -12,14 +12,12 @@ use serde_json::Value; use ulid::Ulid; use crate::ai::error::AiError; -use crate::ai::presence; use crate::ai::protocol::{ Greeting, Hello, RejectCode, Request, Response, protocol_matches, read_frame, write_frame, }; use crate::ai::registry::{AiRegistry, WorkerSnapshot, clamp_concurrency}; use crate::ai::tls; use crate::constant::{AI_HANDSHAKE_TIMEOUT_SECS, AI_PROTOCOL}; -use crate::database::Database; /// What the bridge needs to come up. #[derive(Clone, Debug)] @@ -37,13 +35,6 @@ pub struct BridgeConfig { struct Inner { registry: AiRegistry, - /// The database, once [`AiBridge::attach_presence`] has handed it over — - /// used for the `ai_worker` gate and nothing else (see - /// [`crate::ai::presence`]). `OnceLock` because the bridge binds before the - /// router is built, so presence is wired *after* the listener is already - /// accepting: a worker may register before this is set, and the heartbeat - /// republishes the whole live set precisely so that one is not lost. - presence: std::sync::OnceLock, /// The leaf certificate this listener presents, kept so it can be shown to /// an operator (or pinned by an in-process client) without re-reading the /// PEM off disk. @@ -86,7 +77,6 @@ impl AiBridge { let inner = Arc::new(Inner { registry: AiRegistry::default(), - presence: std::sync::OnceLock::new(), certificate: bridge_tls.leaf.clone(), token: config.token, request_timeout: config.request_timeout, @@ -124,35 +114,15 @@ impl AiBridge { self.inner.registry.snapshot() } - /// Is anything connected *to this process* that can serve `capability`? + /// Is anything connected that can serve `capability`? /// - /// The DISPATCHER's answer, and the authoritative one: this registry owns - /// the sockets, so only it may decide that this replica can answer a job. - /// Racy in the harmless direction — a worker can vanish between the check - /// and the dispatch — so it still never guards a write. For "can *anyone* - /// serve it", which is a different and weaker question, see - /// [`crate::ai::presence::serves`]. + /// This registry owns the sockets, so it is the whole truth about what the + /// backend can answer. Racy in the harmless direction — a worker can vanish + /// between the check and the dispatch — so it never guards a write. pub fn has_capability(&self, capability: &str) -> bool { self.inner.registry.has_capability(capability) } - /// Hand the bridge the database, so the workers it holds become visible to - /// other replicas through the `ai_worker` gate. Returns whether this call - /// was the one that wired it — the caller uses that to start exactly one - /// claim loop per process. - /// - /// Idempotent by construction: a second call is a no-op and returns - /// `false`. Nothing here is required for the bridge to work; a deployment - /// that never attaches presence simply keeps the single-process behaviour, - /// where the in-process registry is the whole truth. - pub fn attach_presence(&self, db: Database) -> bool { - if self.inner.presence.set(db.clone()).is_err() { - return false; - } - heartbeat_presence(Arc::downgrade(&self.inner), db); - true - } - /// Send one request to a service and await its answer. /// /// Each call takes a fresh QUIC bidirectional stream, so concurrent calls @@ -235,45 +205,6 @@ impl AiBridge { } } -/// Republish this replica's live worker set to the `ai_worker` gate, forever. -/// -/// The whole set every beat rather than deltas: it is the self-healing half of -/// the gate (a row lost to a database blip, or a worker registered before -/// presence was attached, comes back on the next tick), and the set is a -/// handful of rows. The sweep rides along so a replica that died without -/// deregistering stops holding anyone's gate open. -/// -/// Holds a `Weak` on the bridge so that *this* task is not itself a reason to -/// keep a listener alive. It is not a shutdown mechanism, and in the wired-up -/// process it never fires: `chatbot::spawn_claim_loop` owns an `AiBridge` by -/// value for the life of the process, so the strong count never reaches zero -/// and both tasks run until exit. That is intended for a server — the bridge -/// is not restartable — and is only visible in tests, which build many -/// bridges. Correct that (a `CancellationToken` on both loops) the day a -/// bridge needs to be torn down while the process lives. -fn heartbeat_presence(inner: std::sync::Weak, db: Database) { - tokio::spawn(async move { - let mut ticker = tokio::time::interval(Duration::from_secs( - crate::constant::AI_WORKER_HEARTBEAT_SECS, - )); - ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); - loop { - // The first tick is immediate, so workers registered before the - // database arrived are published now and not one beat late. - ticker.tick().await; - let Some(inner) = inner.upgrade() else { return }; - let workers = inner.registry.snapshot(); - drop(inner); - if let Err(err) = presence::announce(&db, &workers).await { - tracing::warn!("could not publish the AI worker gate: {err}"); - } - if let Err(err) = presence::sweep(&db).await { - tracing::warn!("could not sweep the AI worker gate: {err}"); - } - } - }); -} - /// Accept connections until the endpoint closes. One task per service. async fn accept_loop(inner: Arc) { while let Some(incoming) = inner.endpoint.accept().await { @@ -314,13 +245,6 @@ async fn serve_connection(inner: Arc, conn: quinn::Connection, remote: So // dies without saying anything. let reason = conn.closed().await; inner.registry.remove(&worker_id); - // The gate closes with the registry, not a lease later — but only after - // the registry, which is the authoritative one (see `presence`). - if let Some(db) = inner.presence.get() - && let Err(err) = presence::withdraw(db, &worker_id).await - { - tracing::warn!("could not withdraw AI worker {worker_id} from the gate: {err}"); - } tracing::info!("AI service `{service}` ({worker_id}) at {remote} disconnected: {reason}"); } @@ -409,23 +333,6 @@ async fn register( max_concurrent, conn.clone(), ); - // …and only then published to the gate, so `ai_worker` can never advertise - // a worker the local dispatcher would refuse to pick. - if let Some(db) = inner.presence.get() { - let announced = WorkerSnapshot { - id: worker_id.clone(), - service: hello.service.clone(), - capabilities: hello.capabilities.clone(), - inflight: 0, - max_concurrent, - }; - if let Err(err) = presence::announce(db, &[announced]).await { - // Not fatal, and not a reason to refuse the service: the worker is - // already usable by this replica, and the next heartbeat - // republishes the whole live set. - tracing::warn!("could not publish AI worker {worker_id} to the gate: {err}"); - } - } tracing::info!( "AI service `{}` ({worker_id}) at {remote} registered: {:?}, max_concurrent {max_concurrent}", hello.service, diff --git a/src/config.rs b/src/config.rs index 5ad7859..e0266a2 100644 --- a/src/config.rs +++ b/src/config.rs @@ -110,13 +110,11 @@ fn parse_limit(value: Option, default: u32) -> u32 { /// never what an operator means — so it falls back with the rest of the /// garbage. /// -/// The ceiling is the load-bearing part, and it is enforced here because here -/// is the only place the number enters the process. A deadline above -/// [`AI_MAX_REQUEST_TIMEOUT_SECS`] lets one dispatch outlive -/// `CHATBOT_CLAIM_RECLAIM_SECS`, and the chat claim queue then hands the same -/// turn to a second worker while the first is still answering it — two -/// inferences for one reply. Clamping at the boundary is what makes that -/// unreachable *by configuration*, instead of true only for the default. +/// The ceiling is enforced here because here is the only place the number +/// enters the process. A deadline above [`AI_MAX_REQUEST_TIMEOUT_SECS`] keeps +/// a task and a worker slot busy past the point where the answer could still +/// be shown to anyone (see that constant), so it is clamped rather than +/// honoured. fn parse_timeout(value: Option, default: u64) -> u64 { let asked = value .and_then(|v| v.trim().parse().ok()) @@ -127,8 +125,8 @@ fn parse_timeout(value: Option, default: u64) -> u64 { // reason (a queue horizon) is not one they could guess from the name. tracing::warn!( "AI_REQUEST_TIMEOUT_SECS={asked} is above the {AI_MAX_REQUEST_TIMEOUT_SECS}s ceiling \ - the chat claim queue allows (a longer inference would be reclaimed and re-dispatched \ - mid-flight) — using {AI_MAX_REQUEST_TIMEOUT_SECS}s" + (a reply that late is discarded as stale before anyone sees it) — using \ + {AI_MAX_REQUEST_TIMEOUT_SECS}s" ); return AI_MAX_REQUEST_TIMEOUT_SECS; } @@ -155,7 +153,7 @@ fn parse_flag(value: Option) -> bool { mod tests { use super::{parse_flag, parse_limit, parse_port, parse_timeout}; use crate::constant::{ - AI_DEFAULT_REQUEST_TIMEOUT_SECS, AI_MAX_REQUEST_TIMEOUT_SECS, CHATBOT_CLAIM_RECLAIM_SECS, + AI_DEFAULT_REQUEST_TIMEOUT_SECS, AI_MAX_REQUEST_TIMEOUT_SECS, CHATBOT_PENDING_STALE_SECS, }; #[tokio::test] @@ -169,19 +167,18 @@ mod tests { } #[tokio::test] - async fn a_configured_timeout_can_never_outlive_the_chat_claim_horizon() { - // The one double-dispatch an operator could still reach: nothing used - // to stop `AI_REQUEST_TIMEOUT_SECS=120`, and a dispatch outliving - // `CHATBOT_CLAIM_RECLAIM_SECS` has its turn reclaimed and re-sent while - // the first inference is still running — the model answers one turn - // twice. The relationship, not a literal, is what is asserted: raising - // one of the two numbers without the other cannot pass this. - for asked in ["91", "120", "600", "18446744073709551615"] { + async fn a_configured_timeout_is_clamped_below_the_stale_horizon() { + // Nothing used to stop `AI_REQUEST_TIMEOUT_SECS=600`, and a dispatch + // that outlives `CHATBOT_PENDING_STALE_SECS` holds a worker slot for an + // answer every reader has already been shown as failed. The + // relationship, not a literal, is what is asserted: raising the ceiling + // past the staleness window cannot pass this. + for asked in ["61", "120", "600", "18446744073709551615"] { let got = parse_timeout(Some(asked.into()), AI_DEFAULT_REQUEST_TIMEOUT_SECS); assert!( - (got as i64) < CHATBOT_CLAIM_RECLAIM_SECS, + (got as i64) < CHATBOT_PENDING_STALE_SECS, "AI_REQUEST_TIMEOUT_SECS={asked} was honoured as {got}s, at or past the \ - {CHATBOT_CLAIM_RECLAIM_SECS}s reclaim horizon" + {CHATBOT_PENDING_STALE_SECS}s staleness horizon" ); assert_eq!(got, AI_MAX_REQUEST_TIMEOUT_SECS, "clamped to the ceiling"); } diff --git a/src/constant.rs b/src/constant.rs index 3b50a66..d0a0f7a 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -402,56 +402,6 @@ pub const AI_KEEPALIVE_SECS: u64 = 10; /// chat endpoints report the service as unavailable. pub const AI_CHAT_CAPABILITY: &str = "chat.reply"; -// --- AI worker presence: the GATE, never the dispatcher ----------------- -// -// Read `crate::ai::presence` before touching anything below. In one line: the -// `ai_worker` table answers "could *anything, anywhere* serve this -// capability?" so a POST on a replica holding no worker can still be accepted -// (a peer's claim loop will answer it). It is a heartbeated cache of other -// processes' sockets and it is allowed to be wrong in both directions. The -// in-process `ai::registry::Registry` is the dispatcher and the only thing -// that may decide who actually answers. - -/// The heartbeated presence table. One row per connected worker, written by -/// whichever replica owns that worker's QUIC connection. -pub const AI_WORKER_TABLE: &str = "ai_worker"; - -/// How often a replica restamps `seen_at` for the workers it holds, and how -/// long a row is believed without a restamp. The lease is a comfortable -/// multiple of the beat (three), so a single missed heartbeat never hides a -/// live worker, and it matches [`AI_IDLE_TIMEOUT_SECS`] — the window in which -/// the transport itself notices a dead service — so a replica that dies -/// outright leaves a phantom for no longer than a service that dies outright. -pub const AI_WORKER_HEARTBEAT_SECS: u64 = 10; -pub const AI_WORKER_LEASE_SECS: i64 = 30; - -/// Write (or restamp) one worker's row. `UPSERT` rather than `CREATE`: the -/// heartbeat replays the whole live set every beat, which is what heals a row -/// lost to a database blip or written before the presence table was attached. -pub const AI_WORKER_ANNOUNCE: &str = " - UPSERT $id CONTENT { service: $service, capabilities: $capabilities, - seen_at: time::unix(time::now()) * 1000 }; -"; - -/// Drop a worker whose connection closed. Immediate — the gate should not -/// hold a door open for a service that has already said goodbye. -pub const AI_WORKER_WITHDRAW: &str = "DELETE $id;"; - -/// Forget workers nobody has restamped within the lease: the replica holding -/// them died without deregistering. Any replica's heartbeat may run it — the -/// rows are keyed by worker, not by owner. -pub const AI_WORKER_SWEEP: &str = " - DELETE ai_worker WHERE seen_at < time::unix(time::now()) * 1000 - $lease_ms; -"; - -/// The gate read. Age-filtered in the query, not by the sweep, so a phantom -/// row is inert the moment it is stale rather than when someone gets round to -/// deleting it. -pub const AI_WORKER_SERVES: &str = " - SELECT VALUE id FROM ai_worker WHERE $capability IN capabilities - AND seen_at >= time::unix(time::now()) * 1000 - $lease_ms LIMIT 1; -"; - /// Hard ceiling on one chat message's characters — the newtype bound, above /// which no school setting can reach. Sized for a pasted question with its /// working, well under [`AI_MAX_FRAME_BYTES`] once history rides along. @@ -497,92 +447,17 @@ pub const CHAT_STREAM_POLL_MS: u64 = 200; /// this only catches the row whose task died with the process. pub const CHATBOT_PENDING_STALE_SECS: i64 = 300; -// --- the chat claim queue ---------------------------------------------- - -/// How often a replica looks for an unanswered turn, and how many it takes in -/// one sweep. The poll is what replaces the in-process `tokio::spawn` a POST -/// used to do, so it is the answer's added latency floor — matched to -/// [`CHAT_STREAM_POLL_MS`], the cadence the client already waits at, so a turn -/// is never claimed slower than its own reader refreshes. The batch is small -/// on purpose: a claim is a promise to dispatch now, and dispatching more at -/// once than a worker's `max_concurrent` would only turn the surplus into -/// `busy` failures. -pub const CHATBOT_CLAIM_POLL_MS: u64 = 200; -pub const CHATBOT_CLAIM_BATCH: i64 = 4; - -/// How long a claim is believed before another replica may take the turn back. -/// -/// Sized between the two horizons it sits between, and both bounds bite (see -/// `the_claim_horizon_sits_between_the_inference_and_the_stale_window`): -/// -/// * **Above the AI request timeout** ([`AI_DEFAULT_REQUEST_TIMEOUT_SECS`], -/// 30s), with room to spare, because a reclaim that fires while the first -/// claimer is still waiting on a legitimate inference makes two services -/// answer the same turn — twice the cost for one reply (the second is then -/// discarded by the `status = 'pending'` gate on the settle, so it is waste, -/// not corruption). Three times the default leaves margin for the settle -/// write and for a moderately raised `AI_REQUEST_TIMEOUT_SECS`. -/// * **Below [`CHATBOT_PENDING_STALE_SECS`]** (300s), because a turn is only -/// claimable inside that window; a reclaim horizon at or above it would -/// never fire before the turn stopped being worth answering, making the -/// dead-claimer retry dead code. At 90s a turn survives two lost claimers -/// and still gets answered. -pub const CHATBOT_CLAIM_RECLAIM_SECS: i64 = 90; - /// The largest per-request AI deadline a deployment may configure /// (`AI_REQUEST_TIMEOUT_SECS`). Anything above it is clamped down to it at /// startup, loudly — see [`crate::config`]. /// -/// Not a taste limit; it is the claim queue's arithmetic, and the bound the -/// doc above only *asserted* before. A dispatch allowed to outlive -/// [`CHATBOT_CLAIM_RECLAIM_SECS`] has its turn reclaimed and re-sent while the -/// first inference is still legitimately running, so the model runs twice for -/// one reply. (The settle's `status = 'pending'` gate still admits only one -/// answer, so it is waste rather than corruption — but a worker with side -/// effects makes it worse than waste.) Nothing but the parser stood between an -/// operator and that: `AI_REQUEST_TIMEOUT_SECS=120` used to be honoured -/// verbatim. -/// -/// Clamped rather than refused, because a slow model is a legitimate thing to -/// own and a boot that dies over it helps nobody — and because the ceiling is -/// real either way: a reply that arrives after -/// [`CHATBOT_PENDING_STALE_SECS`] is discarded by the read-time projection, so -/// no deadline near it was ever going to produce an answer a user sees. A -/// school that genuinely needs longer raises the horizon and the staleness -/// window together, and the ordering tests police the result. -/// -/// Two thirds of the horizon, derived and never hand-kept: raising the horizon -/// raises this with it, so the two numbers cannot drift apart. The remaining -/// third is the room the reply needs to arrive, be capped and be stamped -/// before anyone may reclaim the turn. -pub const AI_MAX_REQUEST_TIMEOUT_SECS: u64 = CHATBOT_CLAIM_RECLAIM_SECS as u64 * 2 / 3; - -/// Take up to [`CHATBOT_CLAIM_BATCH`] unanswered turns for this replica. -/// -/// Two statements because SurrealDB has no `LIMIT` on `UPDATE`: the first -/// picks candidates, the second claims them. The pick is advisory — a peer may -/// take a row in between — so the `UPDATE` repeats the *whole* guard, and -/// per-record `UPDATE ... WHERE` is atomic, so a row claimed by a rival simply -/// does not come back in `RETURN AFTER`. Nothing here consults `ai_worker`: -/// the caller has already asked its own registry whether it can answer. -/// -/// The guard, term by term: only a reserved assistant row (`pending`), only -/// one young enough that somebody is still waiting for it (`$stale_ms` — past -/// that a reader already shows it failed, so answering it would resurrect a -/// turn the user was told was lost), and only one that is unclaimed *or* whose -/// claimer has gone quiet past `$reclaim_ms`. Both disjuncts are required: a -/// row whose claimer died must be retried, not left forever. -pub const CHATBOT_CLAIM: &str = " - LET $ids = (SELECT VALUE id FROM chatbot_message - WHERE status = 'pending' AND role = 'assistant' - AND created_at >= time::unix(time::now()) * 1000 - $stale_ms - AND (claimed_by = NONE OR claimed_at < time::unix(time::now()) * 1000 - $reclaim_ms) - ORDER BY created_at ASC, id ASC LIMIT $batch); - UPDATE $ids SET claimed_by = $me, claimed_at = time::unix(time::now()) * 1000 - WHERE status = 'pending' - AND (claimed_by = NONE OR claimed_at < time::unix(time::now()) * 1000 - $reclaim_ms) - RETURN AFTER; -"; +/// A sanity ceiling, well under [`CHATBOT_PENDING_STALE_SECS`]: a reply that +/// arrives after the staleness window is discarded by the read-time +/// projection, so a deadline anywhere near it could never produce an answer a +/// user sees — it would only hold a task and a worker slot open for nothing. +/// A school that genuinely needs longer raises this and the staleness window +/// together. +pub const AI_MAX_REQUEST_TIMEOUT_SECS: u64 = 60; /// How long a dialling AI service has to complete its `Hello`/`Welcome` /// exchange before the connection is dropped. Short: the handshake is one @@ -605,13 +480,13 @@ pub const DEFAULT_CHATBOT_RATE_LIMIT: u32 = 20; /// swept out on the next check. Keeps memory bounded without a reaper task. pub const PURGE_AT: usize = 10_000; -/// The shared counter every replica folds its local admits into, so N replicas -/// enforce one budget instead of N (see [`crate::rate_limit`]). +/// The shared counter the limiter folds its local admits into, so a window's +/// budget survives a restart (see [`crate::rate_limit`]). pub const RATE_LIMIT_TABLE: &str = "rate_limit"; -/// How often a limiter pushes its admits and reads the fleet's total back. -/// The knob that decides the worst case: within one interval a replica can -/// admit up to its full local budget before the shared total tightens it, so +/// How often a limiter pushes its admits and reads the window's total back. +/// The knob that decides the worst case: within one interval a just-started +/// process can admit up to its full local budget before the total tightens it, so /// short enough to matter and long enough to stay one query per tier per tick. pub const RATE_SYNC_INTERVAL_SECS: u64 = 2; @@ -794,12 +669,13 @@ pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger"; pub const KIND_REF_TABLE: &str = "kind_ref"; pub const SLOT_REF_TABLE: &str = "slot_ref"; -// --- cross-replica cap counters ---------------------------------------- +// --- stored cap counters ------------------------------------------------- /// The counter columns behind the count caps (see [`crate::domain::cap`]). /// Each one lives on the *parent* row, because a single-record conditional -/// `UPDATE` is the only guard that holds when the writers are in different -/// processes. Spelled here rather than at the call site so the field a claim +/// `UPDATE` is the only guard a concurrent writer cannot outrun (a lock is +/// released around the round trip). Spelled here rather than at the call site +/// so the field a claim /// increments and the field a delete decrements cannot drift apart; the /// definitions themselves are in `MIGRATION`, and a typo there is caught by /// SCHEMAFULL refusing the write. @@ -821,8 +697,8 @@ pub const SLOT_OCCUPIED_FIELD: &str = "occupied"; /// Not caps either, and uncapped by design: how many exam questions and how /// many homework still point at a subject. A subject may be deleted exactly /// while both read zero, so the delete's own `WHERE` decides it — the -/// cross-table "does anything reference this?" count it replaces served one -/// replica only. +/// cross-table "does anything reference this?" count it replaces was already +/// stale when the delete landed. pub const SUBJECT_QUESTION_COUNT_FIELD: &str = "exam_question_count"; pub const SUBJECT_HOMEWORK_COUNT_FIELD: &str = "homework_count"; /// How many marks an exam carries. Uncapped too, and the only counter its @@ -848,7 +724,7 @@ pub const MENU_VERSION_FIELD: &str = "version"; /// the submission is still open. Every student-side write to a submission (its /// text, its files) carries `graded_by_result = NONE` as a condition, so the /// "not graded yet" decision and the write it licenses are one conditional -/// single-record write rather than a cross-table read a peer replica can +/// single-record write rather than a cross-table read a concurrent grade can /// outrun. Set by grading, cleared by un-grading, never by the student. pub const SUBMISSION_GRADED_FIELD: &str = "graded_by_result"; /// The condition itself, spelled once: a submission is writable exactly while @@ -863,84 +739,3 @@ pub const SUBMISSION_OPEN_GUARD: &str = "graded_by_result = NONE"; /// parent: seven doublings from 2ms is a quarter of a second of patience. pub const CAP_WRITE_TRIES: usize = 8; pub const CAP_WRITE_BACKOFF_MS: u64 = 2; - -// --- boot leader election ---------------------------------------------- - -/// The lock row every booting process races for (see -/// [`crate::database::boot_once`]). Its own table, and the only SCHEMALESS one -/// in the database: the lock has to be claimable *before* the SCHEMAFULL batch -/// that defines every other table has run, so a lock whose own schema needed -/// migrating could not guard the migration. `IF NOT EXISTS` makes the -/// definition safe for all N processes to issue. -pub const MIGRATION_LOCK_TABLE: &str = "migration_lock"; -pub const MIGRATION_LOCK_DDL: &str = "DEFINE TABLE IF NOT EXISTS migration_lock SCHEMALESS;"; - -/// Claim the lock. A deterministic id is the whole mechanism: SurrealDB v3 -/// answers a `CREATE` on an existing id with "already exists" rather than -/// overwriting it, so of N concurrent processes exactly one gets an `Ok`. -/// Returns the holder like the takeover does, so one caller reads both. -pub const MIGRATION_LOCK_CLAIM: &str = " - CREATE migration_lock:boot SET holder = $me, claimed_at = time::unix(time::now()) * 1000, - applied_at = NONE, applies = 0 RETURN VALUE holder; -"; - -/// What a loser needs to know, decided by the *database's* clock — never the -/// process's, since two replicas' clocks disagree and the lease horizon is the -/// one thing a wrong clock could turn into a concurrent migration. -/// -/// `applied` means "applied *this* binary's schema": a stamp carries the -/// fingerprint of the DDL that produced it, and a peer's stamp with any other -/// fingerprint is no evidence about the schema this process is about to write -/// (see [`crate::database::migration_fingerprint`]). -pub const MIGRATION_LOCK_STATE: &str = " - SELECT holder, applied_at != NONE AND (fingerprint ?? '') = $fingerprint AS applied, - claimed_at >= time::unix(time::now()) * 1000 - $lease_ms AS live - FROM ONLY migration_lock:boot; -"; - -/// Take the lock off a holder that cannot be relied on: one that has gone -/// silent past the lease horizon (killed mid-migration), or one that finished -/// with a *different* schema than ours — a stamp is the last thing a leader -/// writes, so a foreign fingerprint means nobody is in the DDL right now and -/// this binary's own migration still has to run. -/// -/// Per-record `UPDATE ... WHERE` is atomic, so a second taker re-reads the -/// freshly bumped `claimed_at` and is refused (empty result). Clears -/// `applied_at` and `fingerprint`: the previous generation's stamp says nothing -/// about this one's schema. -pub const MIGRATION_LOCK_TAKEOVER: &str = " - UPDATE migration_lock:boot SET holder = $me, claimed_at = time::unix(time::now()) * 1000, - applied_at = NONE, fingerprint = NONE - WHERE claimed_at < time::unix(time::now()) * 1000 - $lease_ms - OR (applied_at != NONE AND (fingerprint ?? '') != $fingerprint) - RETURN VALUE holder; -"; - -/// Renew the lease while the migration runs, and stamp it done afterwards. -/// Both are `holder`-guarded and both report the holder back, so a leader that -/// was declared dead and replaced not only stops being able to write the lock — -/// it finds out (an empty result), which is the only way it can learn that a -/// peer is now applying the same DDL underneath it. -pub const MIGRATION_LOCK_HEARTBEAT: &str = " - UPDATE migration_lock:boot SET claimed_at = time::unix(time::now()) * 1000 - WHERE holder = $me RETURN VALUE holder; -"; -pub const MIGRATION_LOCK_STAMP: &str = " - UPDATE migration_lock:boot SET applied_at = time::unix(time::now()) * 1000, applies += 1, - fingerprint = $fingerprint - WHERE holder = $me RETURN VALUE holder; -"; - -/// How long a lock may go unrenewed before a peer may take it over. Must stay -/// a comfortable multiple of `MIGRATION_LOCK_HEARTBEAT_SECS`: it is the number -/// of missed beats that separates "the leader was killed" from "the leader is -/// slow", and mistaking the second for the first runs two migrations at once. -pub const MIGRATION_LOCK_LEASE_SECS: i64 = 30; -pub const MIGRATION_LOCK_HEARTBEAT_SECS: u64 = 5; - -/// How long a non-leader waits for the leader's `applied_at` before failing the -/// boot, and how often it looks. Bounded because a boot that hangs forever is -/// indistinguishable from a hung database; loud because the alternative — -/// serving on a schema nobody confirmed — is worse. -pub const MIGRATION_LOCK_WAIT_SECS: u64 = 180; -pub const MIGRATION_LOCK_POLL_MS: u64 = 200; diff --git a/src/database.rs b/src/database.rs index 2d7f316..b34f5fa 100644 --- a/src/database.rs +++ b/src/database.rs @@ -3,15 +3,9 @@ use surrealdb::Surreal; use surrealdb::engine::any::Any; use surrealdb::opt::auth::Root; -use surrealdb::types::SurrealValue; use crate::config::Config; -use crate::constant::{ - CAS_UPDATE_RETRIES, CHATBOT_PENDING_STALE_SECS, MIGRATION_LOCK_CLAIM, MIGRATION_LOCK_DDL, - MIGRATION_LOCK_HEARTBEAT, MIGRATION_LOCK_HEARTBEAT_SECS, MIGRATION_LOCK_LEASE_SECS, - MIGRATION_LOCK_POLL_MS, MIGRATION_LOCK_STAMP, MIGRATION_LOCK_STATE, MIGRATION_LOCK_TAKEOVER, - MIGRATION_LOCK_WAIT_SECS, -}; +use crate::constant::CHATBOT_PENDING_STALE_SECS; use crate::domain::user::{Password, User, Username}; use crate::error::AppError; use crate::migration_sql::MIGRATION_BATCHES; @@ -32,13 +26,13 @@ use crate::migration_sql::MIGRATION_BATCHES; /// Cloning the `Arc` shares the single session established at boot instead. pub type Database = std::sync::Arc>; -/// Connect to the SurrealDB server, sign in as root, and apply the schema — -/// the latter through the boot election, so that N overlapping processes apply -/// it once between them (see [`boot_once`]). +/// Connect to the SurrealDB server, sign in as root, apply the schema and seed +/// the admin. One process, one database, stop-the-world deploys — so all of it +/// runs unconditionally on every boot. pub async fn init(cfg: &Config) -> Result { - // Validated before the connection, not after the election: half a - // credential pair is a deployment mistake, and finding that out only in the - // process that happened to win the lock would make it a coin flip. + // Validated before the connection, not after: half a credential pair is a + // deployment mistake, and reporting it only after a successful dial buries + // it under an outage that isn't one. let admin = admin_credentials(cfg)?; let db = connect_with_retry(cfg).await; db.signin(Root { @@ -50,12 +44,10 @@ pub async fn init(cfg: &Config) -> Result { .use_db(cfg.db_name.clone()) .await?; let db = std::sync::Arc::new(db); - boot_once( - &db, - admin, - std::time::Duration::from_secs(MIGRATION_LOCK_WAIT_SECS), - ) - .await?; + migrate(&db).await?; + if let Some((username, password)) = admin { + User::ensure_admin(username, password, &db).await?; + } Ok(db) } @@ -77,181 +69,6 @@ fn admin_credentials(cfg: &Config) -> Result, AppEr } } -/// Run the boot work that must happen exactly once — the schema batches and the -/// admin seed — under a leader election, and hold every other process at the -/// door until it *has* happened. Returns whether we were the leader. -/// -/// Two processes overlap on every rolling restart, long before any replica -/// work: they used to race the same SCHEMAFULL DDL, the same data backfills -/// (including the chatbot pending sweep, which writes live rows) and the same -/// `ensure_admin` read-then-create. The election is a deterministic-id -/// `CREATE`: SurrealDB v3 answers a create on an existing id with "already -/// exists" instead of overwriting, so of N racing processes exactly one gets an -/// `Ok`, and that one is the leader. -/// -/// The lock is a *heartbeated lease*, not a once-only flag, and both halves of -/// that are deliberate: -/// -/// * Heartbeated, because a leader killed mid-migration must not wedge every -/// future boot, yet a leader that is merely slow must never be overtaken — -/// two processes in the DDL at once is the exact race being prevented. The -/// leader renews `claimed_at` every `MIGRATION_LOCK_HEARTBEAT_SECS` for as -/// long as it works, and a peer takes over only after -/// `MIGRATION_LOCK_LEASE_SECS` of silence. The price is that recovery from a -/// killed leader waits out the lease; the alternative, a plain age horizon, -/// would have to exceed the slowest imaginable migration to be safe. -/// * A lease, not a flag, because a boot an hour later may be a new binary with -/// new DDL and must re-apply, and because the data backfills (the chatbot -/// pending sweep above all) are meant to run on every restart. Only a boot -/// *inside* the lease trusts a peer's `applied_at` — i.e. exactly the -/// rolling-restart window — and only when that stamp carries this binary's own -/// [`migration_fingerprint`], so a mixed-version window cannot make the newer -/// process skip its own DDL. -/// -/// `wait` is how long a non-leader keeps polling before it fails the boot; a -/// parameter rather than a constant read inline so a test can prove that -/// deadline actually bites without sitting out `MIGRATION_LOCK_WAIT_SECS`. -async fn boot_once( - db: &Database, - admin: Option<(Username, Password)>, - wait: std::time::Duration, -) -> Result { - let lease_ms = MIGRATION_LOCK_LEASE_SECS * 1_000; - // Any unique string; the lock only ever compares it for equality. - let me = ulid::Ulid::new().to_string(); - // No query deadline anywhere in here on purpose: the SDK parks queries - // while the socket is down instead of failing them, so a timeout would - // report an outage as a dead leader and hand the migration to a second - // process (see `crate::error::AppError::DbTimeout`). - // - // The bootstrap step: the lock's own table has to exist before anyone can - // claim a row in it, so every process defines it (`IF NOT EXISTS`) rather - // than the leader — the leader is not known yet. N processes issuing that - // at once makes the key-value layer abort the losers with a retryable write - // conflict, and a conflict here means a rival committed the very definition - // we wanted, so it counts as success. - if let Err(err) = db - .query(MIGRATION_LOCK_DDL) - .await - .and_then(|response| response.check()) - && !lost_the_race(&err) - { - return Err(err.into()); - } - - let deadline = tokio::time::Instant::now() + wait; - loop { - if claim(db, MIGRATION_LOCK_CLAIM, &me, lease_ms).await? { - return leader_applies(db, &me, admin).await.map(|()| true); - } - let read = db - .query(MIGRATION_LOCK_STATE) - .bind(("lease_ms", lease_ms)) - .bind(("fingerprint", migration_fingerprint())) - .await - .and_then(|response| response.check()) - .and_then(|mut response| response.take::>(0)); - let state = match read { - Ok(state) => state, - // The leader heartbeats this very row every few seconds and rivals - // take it over, so a read of it can be aborted as retryable — which - // is not an error about the lock, just "no answer this round". This - // poll loop, with its deadline, *is* the bounded retry the conflict - // asks for, so treat it like a missing row and look again. Retrying - // a `SELECT` is free of side effects by construction. - Err(err) if lost_the_race(&err) => None, - Err(err) => return Err(err.into()), - }; - match state { - // A live lease, stamped with our own fingerprint: the exact schema - // this process needs is in place, so stop waiting. - Some(state) if state.live && state.applied => { - tracing::info!(leader = %state.holder, "schema applied by another process"); - return Ok(false); - } - // Anything else may be takeable — the holder went silent past the - // lease, or it finished but with a different schema than ours. The - // statement's `WHERE` is the arbiter, so a live holder still inside - // the DDL refuses us and we fall through to waiting. - Some(state) if claim(db, MIGRATION_LOCK_TAKEOVER, &me, lease_ms).await? => { - tracing::warn!( - previous = %state.holder, - live = state.live, - "taking over the boot migration lock: the holder went silent or applied \ - a different schema" - ); - return leader_applies(db, &me, admin).await.map(|()| true); - } - Some(state) => { - tracing::debug!(leader = %state.holder, "waiting for the boot migration"); - } - // The row vanished; the next iteration's `CREATE` picks it up. - None => {} - } - if tokio::time::Instant::now() >= deadline { - // Loudly, not optimistically: SCHEMAFULL means an unmigrated - // database fails every write anyway, and it would do so as - // scattered 500s instead of one startup error. Exiting hands the - // retry to the container runtime, which is where boot retries live. - // - // One production sequence reaches this branch: a leader that keeps - // renewing its lease for longer than `wait` without ever stamping — - // a migration slower than `MIGRATION_LOCK_WAIT_SECS`. A leader that - // *stops* renewing never gets here, because the takeover above fires - // a lease (30s) rather than a wait (180s) after the last renewal. So - // the relative size of those two constants is not what selects this - // branch; "the lock stayed live-and-unstamped for the whole wait" - // is — which is precisely the state - // `a_live_lock_is_waited_for_and_the_wait_is_bounded` constructs, - // renewer and all, at a scaled-down wait. - return Err(AppError::Internal(format!( - "the boot migration lock stayed held for {wait:?}; \ - refusing to serve on a schema no process has confirmed" - ))); - } - tokio::time::sleep(std::time::Duration::from_millis(MIGRATION_LOCK_POLL_MS)).await; - } -} - -/// The lock row as a loser reads it. `live`/`applied` are computed by the -/// database so the verdict never depends on this process's clock. -#[derive(SurrealValue)] -struct LockState { - holder: String, - applied: bool, - live: bool, -} - -/// Run one of the two acquiring statements and report whether we now hold the -/// lock — both return our own holder id when we do, and nothing when a rival -/// got there first. -/// -/// Two failures mean "not ours", not "broken". "Already exists" is the -/// deterministic-id create losing the race, and a key-value *write conflict* is -/// the same race decided one layer down: when two processes create the same id -/// at genuinely the same instant, the loser's transaction is aborted as -/// retryable rather than answered with the duplicate-key message (observed on -/// every run of `two_concurrent_boots_apply_the_schema_once`). Either way the -/// caller loops, re-reads the lock and finds out who holds it — which is also -/// the retry the conflict asks for. -async fn claim(db: &Database, sql: &str, me: &str, lease_ms: i64) -> Result { - let result = db - .query(sql) - .bind(("me", me.to_string())) - .bind(("lease_ms", lease_ms)) - .bind(("fingerprint", migration_fingerprint())) - .await - .and_then(|response| response.check()); - match result { - Ok(mut response) => { - let holders: Vec = response.take(0)?; - Ok(holders.iter().any(|holder| holder == me)) - } - Err(err) if lost_the_race(&err) => Ok(false), - Err(err) => Err(err.into()), - } -} - /// The two ways a rival's claim shows up as an error on ours: our `CREATE` hit /// their row, or the key-value layer aborted our transaction because theirs /// touched the same key first. @@ -285,146 +102,6 @@ pub(crate) fn lost_the_race(err: &surrealdb::Error) -> bool { message.contains("already exists") || message.contains("can be retried") } -/// A hash of the exact DDL and backfills this binary intends to apply. -/// -/// It is what makes a peer's "applied" stamp trustworthy. Without it, a process -/// booting inside the lease window trusts *any* finished predecessor — so a new -/// binary starting seconds after an old one stamped would skip its own newer -/// DDL and then serve on a schema missing the very fields its handlers write. -/// With it, "somebody applied a schema" narrows to "somebody applied *this* -/// schema", and anything else is treated as unapplied. -/// -/// Derived from the three SQL constants, never a hand-bumped version number: a -/// number nobody remembers to raise is worse than no check at all, while this -/// one changes on its own the moment the schema does. -fn migration_fingerprint() -> &'static str { - use sha2::{Digest, Sha256}; - static FINGERPRINT: std::sync::LazyLock = std::sync::LazyLock::new(|| { - let mut hasher = Sha256::new(); - // Length-prefixed, not concatenated: without a separator, moving a - // statement from one batch into the next leaves the byte stream — and so - // the fingerprint — unchanged, while changing what the boot actually - // does (batch boundaries are what keep the DDL out of the backfills). - for sql in MIGRATION_BATCHES { - hasher.update((sql.len() as u64).to_le_bytes()); - hasher.update(sql.as_bytes()); - } - for (name, value) in migration_binds() { - hasher.update(name.as_bytes()); - hasher.update(value.to_le_bytes()); - } - hex::encode(hasher.finalize()) - }); - &FINGERPRINT -} - -/// Leader path: keep the lease alive, apply everything, then stamp it done. -/// -/// The renewal runs *concurrently with* the work rather than after it, in the -/// same task: `select!` polls both, so a lease that cannot be renewed is -/// noticed while the DDL is still going instead of at the end. -async fn leader_applies( - db: &Database, - me: &str, - admin: Option<(Username, Password)>, -) -> Result<(), AppError> { - let apply = async { - migrate(db).await?; - if let Some((username, password)) = admin { - User::ensure_admin(username, password, db).await?; - } - Ok::<(), AppError>(()) - }; - tokio::select! { - applied = apply => applied?, - lost = renew_lease(db, me) => return Err(lost), - } - - // The stamp is the one write in this path with nothing above it to retry - // it: waiters are polling the same row and taking it over, so the - // key-value layer can abort ours as retryable, and an escaping conflict - // fails a boot that had already migrated everything. Repeating it is safe - // despite `applies += 1` — a conflicted transaction commits nothing, and - // the statement's `holder` guard turns a *genuine* takeover into an empty - // result rather than a second count. Bounded, because a conflict that - // never clears is a real failure and must stay one. - let mut stamped: Vec = Vec::new(); - for attempt in 0..CAS_UPDATE_RETRIES { - let attempted = db - .query(MIGRATION_LOCK_STAMP) - .bind(("me", me.to_string())) - .bind(("fingerprint", migration_fingerprint())) - .await - .and_then(|response| response.check()); - match attempted { - Ok(mut response) => { - stamped = response.take(0)?; - break; - } - Err(err) if lost_the_race(&err) && attempt + 1 < CAS_UPDATE_RETRIES => { - tracing::warn!("stamping the boot migration lock conflicted ({err}) — retrying"); - tokio::time::sleep(std::time::Duration::from_millis(MIGRATION_LOCK_POLL_MS)).await; - } - Err(err) => return Err(err.into()), - } - } - if stamped.is_empty() { - // The same verdict as a lost renewal, for the same reason — this is the - // backstop for losing the lock in the window between the last renewal - // and the stamp. - return Err(lost_lease()); - } - Ok(()) -} - -/// Renew the lease until it can no longer be renewed. Resolves *only* on that -/// loss, so it can sit opposite the real work in a `select!`. -/// -/// A refused renewal (empty result) means a peer declared us dead and took the -/// lock, so it is now applying the same DDL underneath us. We treat that as -/// fatal to this boot and stop: our statements are all idempotent, so there is -/// nothing to undo, but continuing would keep two processes writing schema at -/// once — the exact race this module exists to prevent — and would leave us -/// serving as if we had migrated. Failing hands the retry to the container -/// runtime, which re-elects cleanly. -/// -/// A renewal that *errors* is different: the socket may simply be down, and the -/// SDK parks queries rather than failing them, so a real error here is rare and -/// says nothing definite. Log it and keep trying — if it persists, the lease -/// expires, a peer takes over, and the next renewal is refused, which is the -/// verdict above. `.check()` is load-bearing: a statement-level failure comes -/// back inside an `Ok` response, so without it a renewal could fail forever -/// while logging nothing and renewing nothing. -async fn renew_lease(db: &Database, me: &str) -> AppError { - let mut interval = tokio::time::interval(std::time::Duration::from_secs( - MIGRATION_LOCK_HEARTBEAT_SECS, - )); - loop { - interval.tick().await; - match db - .query(MIGRATION_LOCK_HEARTBEAT) - .bind(("me", me.to_string())) - .await - .and_then(|response| response.check()) - { - Ok(mut response) => match response.take::>(0) { - Ok(holders) if holders.is_empty() => return lost_lease(), - Ok(_) => tracing::debug!("boot migration lease renewed"), - Err(err) => tracing::warn!("boot lock renewal returned unusable rows: {err}"), - }, - Err(err) => tracing::warn!("boot lock renewal failed: {err}"), - } - } -} - -fn lost_lease() -> AppError { - AppError::Internal( - "lost the boot migration lock while applying it — another process took it over and is \ - applying the schema, so this boot stops rather than race it" - .into(), - ) -} - /// Dial the database, retrying until it answers. /// /// Never gives up, because giving up is worse than waiting: the database is @@ -475,419 +152,13 @@ pub async fn migrate(db: &Surreal) -> Result<(), AppError> { /// Parameters the batches are executed with. Bound, not baked into the SQL /// string: a `const` cannot be interpolated into another `const`, and a -/// hand-copied 300000 would drift silently. They are part of what the migration -/// *does*, so [`migration_fingerprint`] hashes them alongside the SQL — a -/// changed horizon is a changed migration. +/// hand-copied 300000 would drift silently. fn migration_binds() -> [(&'static str, i64); 1] { [("stale_ms", CHATBOT_PENDING_STALE_SECS * 1_000)] } #[cfg(test)] mod tests { - use super::{Database, boot_once}; - use crate::constant::{MIGRATION_LOCK_LEASE_SECS, MIGRATION_LOCK_TABLE}; - use crate::domain::user::{Password, Username}; - use std::time::Duration; - - /// An empty in-memory database with *no* schema — what a booting process - /// actually finds. [`super::init_mem`] cannot be used here: it migrates. - async fn unmigrated() -> Database { - let db = surrealdb::engine::any::connect("memory").await.unwrap(); - db.use_ns("hezarfen").use_db("hezarfen").await.unwrap(); - std::sync::Arc::new(db) - } - - fn admin() -> Option<(Username, Password)> { - Some(( - Username::try_new("root").unwrap(), - Password::try_new("secret1").unwrap(), - )) - } - - /// How many times the lock has been stamped applied — the observable side - /// effect that makes "exactly one process applied" checkable. - async fn applies(db: &Database) -> i64 { - let mut res = db - .query("SELECT VALUE applies FROM ONLY migration_lock:boot") - .await - .unwrap(); - res.take::>(0).unwrap().unwrap() - } - - /// How many `root` rows the seed left. Guarded on the table existing: a - /// waiter that failed its boot never ran the DDL, so `user` may be absent, - /// which is an error rather than an empty result. - async fn admin_count(db: &Database) -> i64 { - let mut res = db - .query( - "RETURN IF 'user' IN object::keys((INFO FOR DB).tables) { - array::len((SELECT id FROM user WHERE username = 'root')) - } ELSE { 0 };", - ) - .await - .unwrap(); - res.take::>(0).unwrap().unwrap() - } - - /// Two processes booting at once — the rolling-restart case, which happens - /// today without any replica work. Exactly one may run the DDL, the - /// backfills and the admin seed; the other has to wait for it and then - /// serve, not repeat it. - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn two_concurrent_boots_apply_the_schema_once() { - let db = unmigrated().await; - let (a, b) = (db.clone(), db.clone()); - let one = - tokio::spawn(async move { boot_once(&a, admin(), Duration::from_secs(30)).await }); - let two = - tokio::spawn(async move { boot_once(&b, admin(), Duration::from_secs(30)).await }); - let (one, two) = (one.await.unwrap().unwrap(), two.await.unwrap().unwrap()); - - assert!(one ^ two, "exactly one process leads the boot: {one}/{two}"); - assert_eq!(applies(&db).await, 1, "the migration was applied once"); - assert_eq!(admin_count(&db).await, 1, "the admin was seeded once"); - // The loser still needs the schema it skipped applying. - assert!( - db.query("CREATE user:x SET username = 'x', password_hash = 'h'") - .await - .unwrap() - .check() - .is_ok(), - "the schema is in place once both boots return" - ); - } - - /// The same race with enough processes in it to actually hit the - /// key-value layer's retryable aborts: eight boots contending for one lock - /// row collide on the losers' state read and the leader's stamp, which with - /// two boots surfaces only once in a few full-suite runs. - /// - /// What it asserts is deliberately narrow: no boot may fail with a - /// *retryable* conflict. A conflict is the layer asking to be asked again, - /// so one reaching the caller is always a missing retry — while the other - /// outcomes of a crowded election (a leader that loses its lease to a - /// taker) are documented behaviour, not bugs, and asserting against them - /// here would only make this flaky. Exactly-once stays the two-boot test's - /// job. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn a_crowd_of_boots_never_surfaces_a_retryable_conflict() { - let db = unmigrated().await; - let boots: Vec<_> = (0..8) - .map(|_| { - let db = db.clone(); - tokio::spawn(async move { boot_once(&db, admin(), Duration::from_secs(30)).await }) - }) - .collect(); - for boot in boots { - if let Err(err) = boot.await.unwrap() { - let message = err.to_string(); - assert!( - !message.contains("can be retried") && !message.contains("conflict"), - "a retryable conflict escaped boot_once instead of being retried: {message}" - ); - } - } - } - - /// A leader killed mid-migration leaves its claim behind. Nothing may - /// require a human with a SurrealQL prompt to clear it: the next boot takes - /// the lease over once it has gone unrenewed past the horizon. - #[tokio::test] - async fn an_abandoned_lock_is_taken_over_by_the_next_boot() { - let db = unmigrated().await; - // Exactly what a SIGKILL at the worst moment leaves: claimed, never - // stamped, and no heartbeat since. - db.query( - "DEFINE TABLE migration_lock SCHEMALESS; - CREATE migration_lock:boot SET holder = 'dead', applies = 0, - claimed_at = time::unix(time::now()) * 1000 - ($lease + 1) * 1000;", - ) - .bind(("lease", MIGRATION_LOCK_LEASE_SECS)) - .await - .unwrap() - .check() - .unwrap(); - - assert!( - boot_once(&db, admin(), Duration::from_secs(5)) - .await - .unwrap(), - "the abandoned lock is taken over, not waited on" - ); - assert_eq!(applies(&db).await, 1); - assert_eq!(admin_count(&db).await, 1); - } - - /// The other side of that horizon: a lock claimed a moment ago belongs to a - /// process that is probably still working, so it is waited for — and if the - /// wait runs out the boot fails loudly instead of serving on a schema - /// nobody has confirmed. - #[tokio::test] - async fn a_live_lock_is_waited_for_and_the_wait_is_bounded() { - let db = unmigrated().await; - db.query( - "DEFINE TABLE migration_lock SCHEMALESS; - CREATE migration_lock:boot SET holder = 'busy', applies = 0, - claimed_at = time::unix(time::now()) * 1000;", - ) - .await - .unwrap() - .check() - .unwrap(); - - // A real leader renews; without a renewer this would test "the lease - // happened to still be inside its horizon", which is a different branch - // from the one production reaches (a leader slower than the wait). - let renewer = tokio::spawn({ - let db = db.clone(); - async move { - loop { - db.query(super::MIGRATION_LOCK_HEARTBEAT) - .bind(("me", "busy".to_string())) - .await - .unwrap() - .check() - .unwrap(); - tokio::time::sleep(Duration::from_millis(50)).await; - } - } - }); - let err = boot_once(&db, admin(), Duration::from_millis(600)) - .await - .expect_err("a held, unstamped lock must not let a boot through"); - renewer.abort(); - assert!( - err.to_string().contains("refusing to serve"), - "the boot fails loudly: {err}" - ); - assert_eq!(applies(&db).await, 0, "the waiter applied nothing"); - assert_eq!(admin_count(&db).await, 0, "and seeded nothing"); - } - - /// The rolling-deploy hole the fingerprint exists for: a peer stamped the - /// lock moments ago, inside the lease, so its lease is live and its work is - /// done — but it applied a *different* schema. Trusting that stamp means - /// serving on a database missing the fields this binary's own handlers - /// write. It must be treated as unapplied and taken over. - #[tokio::test] - async fn a_peers_stamp_for_a_different_schema_is_not_trusted() { - let db = unmigrated().await; - db.query( - "DEFINE TABLE migration_lock SCHEMALESS; - CREATE migration_lock:boot SET holder = 'old-binary', applies = 1, - claimed_at = time::unix(time::now()) * 1000, - applied_at = time::unix(time::now()) * 1000, - fingerprint = 'the DDL of some other build';", - ) - .await - .unwrap() - .check() - .unwrap(); - - assert!( - boot_once(&db, admin(), Duration::from_secs(5)) - .await - .unwrap(), - "a stamp from a different schema is no evidence about ours" - ); - assert_eq!(applies(&db).await, 2, "we applied ours on top"); - assert_eq!(admin_count(&db).await, 1); - let mut res = db - .query("SELECT VALUE fingerprint FROM ONLY migration_lock:boot") - .await - .unwrap(); - assert_eq!( - res.take::>(0).unwrap().as_deref(), - Some(super::migration_fingerprint()), - "and left our own fingerprint behind" - ); - } - - /// The same lock, stamped with *our* fingerprint, is the case the skip - /// exists for — otherwise every rolling restart re-runs the whole migration - /// and the peer's boot is pointless. - #[tokio::test] - async fn a_peers_stamp_for_our_own_schema_is_trusted() { - let db = unmigrated().await; - db.query( - "DEFINE TABLE migration_lock SCHEMALESS; - CREATE migration_lock:boot SET holder = 'peer', applies = 1, - claimed_at = time::unix(time::now()) * 1000, - applied_at = time::unix(time::now()) * 1000, - fingerprint = $fingerprint;", - ) - .bind(("fingerprint", super::migration_fingerprint())) - .await - .unwrap() - .check() - .unwrap(); - - assert!( - !boot_once(&db, admin(), Duration::from_secs(5)) - .await - .unwrap(), - "the peer applied this very schema, so this process just proceeds" - ); - assert_eq!(applies(&db).await, 1, "and applies nothing itself"); - } - - /// A hash of the same bytes, computed independently: the fingerprint has to - /// cover every batch, every bound value, and the boundaries between them. - /// Any of those left out is a schema change two binaries could disagree on - /// while claiming the same fingerprint. - #[test] - fn the_fingerprint_covers_every_batch_its_binds_and_the_boundaries() { - use sha2::{Digest, Sha256}; - let hash = |batches: &[String], binds: &[(&str, i64)]| { - let mut hasher = Sha256::new(); - for sql in batches { - hasher.update((sql.len() as u64).to_le_bytes()); - hasher.update(sql.as_bytes()); - } - for (name, value) in binds { - hasher.update(name.as_bytes()); - hasher.update(value.to_le_bytes()); - } - hex::encode(hasher.finalize()) - }; - let batches: Vec = crate::migration_sql::MIGRATION_BATCHES - .iter() - .map(|sql| (*sql).to_string()) - .collect(); - let binds = super::migration_binds(); - assert_eq!(super::migration_fingerprint(), hash(&batches, &binds)); - - let mut edited = batches.clone(); - edited[2].push_str("-- one more backfill\n"); - assert_ne!( - super::migration_fingerprint(), - hash(&edited, &binds), - "an edited batch must change the fingerprint" - ); - // The boundary itself: the same bytes, one statement moved from the DDL - // batch into the backfill batch. Concatenation without a separator would - // hash these two arrangements identically. - let mut moved = batches.clone(); - let at = moved[1].len() - 20; - let tail = moved[1].split_off(at); - moved[2].insert_str(0, &tail); - assert_ne!( - super::migration_fingerprint(), - hash(&moved, &binds), - "moving text across a batch boundary must change the fingerprint" - ); - assert_ne!( - super::migration_fingerprint(), - hash(&batches, &[("stale_ms", 1)]), - "a changed bound value is a changed migration" - ); - } - - /// The forcing function behind all of that: `migrate` and - /// `migration_fingerprint` must read the *same* list. A fourth batch - /// executed by one and not hashed by the other would let two binaries with - /// different schemas claim the same fingerprint — and then skip each other's - /// migration, which is the whole hole the fingerprint was added to close. - #[test] - fn what_the_boot_executes_is_what_the_fingerprint_hashes() { - let source = - std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/database.rs")) - .expect("read database.rs"); - let body = |name: &str| { - let start = source.find(name).expect("function is declared"); - let rest = &source[start..]; - let end = rest.find("\n}\n").expect("function ends"); - rest[..end].to_string() - }; - for (name, body) in [ - ("pub async fn migrate", body("pub async fn migrate")), - ("fn migration_fingerprint", body("fn migration_fingerprint")), - ] { - assert!( - body.contains("MIGRATION_BATCHES") && body.contains("migration_binds()"), - "{name} must derive from MIGRATION_BATCHES + migration_binds(), \ - or the executed and the hashed migration can drift apart" - ); - } - let executed = body("pub async fn migrate"); - assert_eq!( - executed.matches("db.query(").count(), - 1, - "migrate() runs exactly one statement source — the batch list. A second \ - `db.query(...)` here is a batch the fingerprint does not hash:\n{executed}" - ); - } - - /// Path one of two: the renewal itself is refused. Driven straight at - /// `renew_lease` rather than through `leader_applies`, because inside the - /// `select!` a stamp failure would produce the same error and the test would - /// pass without this path working at all. - #[tokio::test] - async fn a_refused_renewal_ends_the_lease_fatally() { - let db = unmigrated().await; - db.query( - "DEFINE TABLE migration_lock SCHEMALESS; - CREATE migration_lock:boot SET holder = 'somebody-else', applies = 0, - claimed_at = time::unix(time::now()) * 1000;", - ) - .await - .unwrap() - .check() - .unwrap(); - - // Only ever resolves on a loss, so reaching this line is the assertion; - // the timeout is there to fail the test instead of hanging it. - let err = tokio::time::timeout(Duration::from_secs(5), super::renew_lease(&db, "me")) - .await - .expect("a renewal refused by the lock must resolve, not keep renewing"); - assert!( - err.to_string().contains("lost the boot migration lock"), - "{err}" - ); - } - - /// Path two: the lock is stolen *after* the last renewal, so nothing refuses - /// us until the stamp. The thief strikes while the DDL is running, far - /// inside the renewal interval, which is exactly the window the stamp - /// backstop exists for. - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn a_lock_stolen_after_the_last_renewal_is_caught_by_the_stamp() { - let db = unmigrated().await; - db.query( - "DEFINE TABLE migration_lock SCHEMALESS; - CREATE migration_lock:boot SET holder = 'me', applies = 0, - claimed_at = time::unix(time::now()) * 1000;", - ) - .await - .unwrap() - .check() - .unwrap(); - let thief = tokio::spawn({ - let db = db.clone(); - async move { - tokio::time::sleep(Duration::from_millis(5)).await; - db.query("UPDATE migration_lock:boot SET holder = 'thief'") - .await - .unwrap() - .check() - .unwrap(); - } - }); - - let err = super::leader_applies(&db, "me", admin()) - .await - .expect_err("a leader that cannot stamp its own lock must not report success"); - thief.await.unwrap(); - assert!( - err.to_string().contains("lost the boot migration lock"), - "{err}" - ); - assert_eq!( - applies(&db).await, - 0, - "and the lock is not stamped as applied by us" - ); - } /// The admin seed must not be interruptible into a state no later boot can /// repair. `create` + `set_role` was: killed between the two writes it @@ -915,26 +186,6 @@ mod tests { ); } - /// The lock's table name is spelled in six places (the DDL and every - /// statement), and a rename that misses one would split the election in two - /// silently — every process would then "win" its own lock. - #[test] - fn every_lock_statement_names_the_lock_table() { - for sql in [ - crate::constant::MIGRATION_LOCK_DDL, - crate::constant::MIGRATION_LOCK_CLAIM, - crate::constant::MIGRATION_LOCK_STATE, - crate::constant::MIGRATION_LOCK_TAKEOVER, - crate::constant::MIGRATION_LOCK_HEARTBEAT, - crate::constant::MIGRATION_LOCK_STAMP, - ] { - assert!( - sql.contains(MIGRATION_LOCK_TABLE), - "{sql} does not name {MIGRATION_LOCK_TABLE}" - ); - } - } - #[tokio::test] async fn boot_fails_chatbot_messages_left_pending() { let db = super::init_mem().await.unwrap(); @@ -970,6 +221,78 @@ mod tests { assert!(interrupted["completed_at"].as_i64().unwrap() > 0); } + #[tokio::test] + async fn the_retired_claim_columns_are_dropped_off_a_live_row() { + // Stale-data path for the 2026-07-30 removal of the chat claim queue. + // A dev volume carries `chatbot_message` rows *with* claim values and an + // `ai_worker` table, so the boot has to clear the values while their + // definitions still stand (PRE_REPAIR) and only then retire the columns + // — SCHEMAFULL rejects every write to a row storing a column that no + // longer exists, which would make the row unanswerable forever. + let db = super::init_mem().await.unwrap(); + db.query( + "DEFINE FIELD claimed_by ON chatbot_message TYPE option; + DEFINE FIELD claimed_at ON chatbot_message TYPE option; + DEFINE TABLE ai_worker SCHEMAFULL; + DEFINE FIELD seen_at ON ai_worker TYPE int; + DEFINE TABLE migration_lock SCHEMALESS;", + ) + .await + .unwrap() + .check() + .unwrap(); + db.query( + "CREATE user:u SET username = 'u', password_hash = 'x'; + CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1; + CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u, + role = 'assistant', content = '', status = 'pending', + created_at = time::unix(time::now()) * 1000, + claimed_by = 'a-dead-replica', claimed_at = 1; + CREATE ai_worker:w SET seen_at = 1; + CREATE migration_lock:the_lock SET holder = 'a-dead-replica', expires_at = 1;", + ) + .await + .unwrap() + .check() + .unwrap(); + + // Twice: the repair and both removals have to be idempotent, since + // every boot runs them. + super::migrate(&db).await.unwrap(); + super::migrate(&db).await.unwrap(); + + let mut info = db.query("INFO FOR TABLE chatbot_message").await.unwrap(); + let table: serde_json::Value = info.take::>(0).unwrap().unwrap(); + let fields = table["fields"].as_object().expect("fields"); + assert!(!fields.contains_key("claimed_by"), "{table}"); + assert!(!fields.contains_key("claimed_at"), "{table}"); + let mut tables = db.query("INFO FOR DB").await.unwrap(); + let dbinfo: serde_json::Value = tables + .take::>(0) + .unwrap() + .unwrap(); + let tables = dbinfo["tables"].as_object().expect("tables"); + assert!(!tables.contains_key("ai_worker"), "{dbinfo}"); + // Same story one table over: the elected-boot lease, stale leader row + // and all. + assert!(!tables.contains_key("migration_lock"), "{dbinfo}"); + + // The load-bearing half: the row that carried a claim is still + // writable. A leftover value under no definition fails here. + db.query("UPDATE chatbot_message:m SET status = 'complete', content = 'ok'") + .await + .unwrap() + .check() + .unwrap(); + let mut row = db + .query("SELECT * FROM ONLY chatbot_message:m") + .await + .unwrap(); + let row: serde_json::Value = row.take::>(0).unwrap().unwrap(); + assert_eq!(row["status"], "complete", "{row}"); + assert!(row.get("claimed_by").is_none(), "{row}"); + } + /// The other half of the sweep: a restart seconds after a dispatch must not /// kill the turn — the answering task may still be alive on the other side /// of the bridge, and the row is not yet past the stale horizon. diff --git a/src/domain/appointment.rs b/src/domain/appointment.rs index 128457b..48a4a08 100644 --- a/src/domain/appointment.rs +++ b/src/domain/appointment.rs @@ -8,26 +8,26 @@ //! [`cap`](crate::domain::cap) of one. Booking [`claim`](cap::claim)s it; //! rejecting or cancelling gives it back in the *same transaction* as the //! status flip, so the slot frees itself with nothing to sweep. Both are -//! single-record conditional writes, so this invariant holds across replicas. +//! single-record conditional writes, so the store decides it, not a lock. //! - **No double-booked person.** An approved meeting may not overlap another //! approved meeting of the same teacher *or* of the same requester. That is a //! count-then-write over *many* rows, which a `BEGIN…COMMIT` does not //! serialize in SurrealDB (write-skew), so it stays under -//! [`APPOINTMENT_LOCK`] — and stays replica-local. +//! [`APPOINTMENT_LOCK`], which is the whole guarantee behind it. //! //! The *single-row* invariant — a decision must be written onto the state it -//! was validated against — is **not** the lock's job, and never was: the lock -//! is process-local, so two replicas each take their own copy of it and a -//! whole-row save would silently drop the other's decision. That one is a -//! compare-and-set ([`Appointment::save_if_unchanged`]), which holds across -//! replicas. +//! was validated against — is **not** the lock's job, and never was: a +//! whole-row save built on a snapshot read before the lock was taken would +//! silently drop whatever landed in between. That one is a compare-and-set +//! ([`Appointment::save_if_unchanged`]), decided by the store. //! -//! Overlap is a **documented accepted race** (reviewed, not an oversight): -//! it is a predicate over *other* rows with no single row to key a counter or -//! a CAS on, so across replicas two approvals decided in the same instant can -//! both land. Damage is one double-booked half-hour, visible to both parties -//! and fixable by cancelling either side — no money, no grade, no data loss. -//! Closing it would need a lease row per teacher taken on every approval. +//! Overlap therefore rests on the lock alone — it is a predicate over *other* +//! rows, with no single row to key a counter or a CAS on. That holds while +//! every approving write takes [`APPOINTMENT_LOCK`]; one that skips it puts two +//! meetings in one half-hour, so the rule is stated here rather than left to be +//! noticed. The damage if it ever happens is one double-booked half-hour, +//! visible to both parties and fixable by cancelling either side — no money, no +//! grade, no data loss. use std::sync::LazyLock; @@ -51,13 +51,12 @@ use crate::validate::validate_required; /// "Is this teacher (or this requester) already committed at that time" is a /// predicate over other appointment rows, and SurrealDB does not conflict-check /// a cross-record read against a concurrent insert, so the check and its write -/// have to be one atomic step *within this process*. Occupancy is no longer its -/// business: that is the slot's `occupied` counter, a conditional single-record -/// write that holds between replicas too. +/// have to be one atomic step, and this lock is the only thing that makes them +/// one. Occupancy is no longer its business: that is the slot's `occupied` +/// counter, a conditional single-record write the store decides. /// -/// Which leaves the accepted race the module doc records: this lock is -/// process-local, so two replicas can each approve an overlapping meeting in -/// the same instant. Visible to both parties, undone by cancelling either side. +/// So this is load-bearing, not a convenience: an approval path that does not +/// take it can double-book a teacher, as the module doc records. /// /// Lock order: taken *before* `cap`'s `CLAIM_LOCK` (booking claims a slot while /// holding this) and never the other way round. No path ever holds this @@ -323,8 +322,8 @@ impl Appointment { /// already taken, or when the requester is already committed elsewhere at /// that time. The slot is taken by [`cap::claim`] on the slot row — a /// conditional single-record write, so two racing requests cannot both find - /// it free however many replicas they arrive at; the requester's own overlap - /// is the lock's part. + /// it free however they interleave; the requester's own overlap is the + /// lock's part. pub async fn book( slot: &AppointmentSlotId, requester: &UserId, @@ -876,15 +875,15 @@ mod tests { assert_eq!(accepted.get_status(), AppointmentStatus::Approved); } - /// The compare-and-set every decision writes through. `APPOINTMENT_LOCK` is - /// process-local, so with two replicas serving, nothing else stands between - /// an approval and a counter-proposal landing on the same booking — and the - /// interleaving that matters is the one a status-only guard would miss, - /// since `propose` leaves a pending booking pending. + /// The compare-and-set every decision writes through — the guard against a + /// decision built on a snapshot that has since moved, which no lock taken + /// after the read can catch. The interleaving that matters is the one a + /// status-only guard would miss, since `propose` leaves a pending booking + /// pending. /// /// Deliberately sequential: the mem engine answers `Ok` to a write it then /// drops, so a `join!` of two decisions proves nothing. This drives the - /// primitive itself with the exact snapshot a second replica would hold. + /// primitive itself with the exact stale snapshot the race produces. #[tokio::test] async fn a_decision_built_on_a_stale_snapshot_never_lands() { let db = crate::database::init_mem().await.unwrap(); @@ -947,7 +946,7 @@ mod tests { } /// What the slot row itself says about being taken — the authority every - /// gate now reads, in any replica. + /// gate now reads. async fn occupied(slot: &AppointmentSlotId, db: &Database) -> i64 { let mut result = db .query("SELECT VALUE (occupied ?? 0) FROM $slot") @@ -959,9 +958,9 @@ mod tests { result.take::>(0).unwrap()[0] } - /// The double-book race, as the *other replica* runs it: `APPOINTMENT_LOCK` - /// is process-local, so a second process's booking arrives at the database - /// with nothing between it and the slot but the claim's own `WHERE`. Driven + /// The double-book race with the lock taken out of the picture: a second + /// booking arrives at the database with nothing between it and the slot but + /// the claim's own `WHERE`, which is what must refuse it. Driven /// through [`cap::claim`] directly rather than through a `join!`, since the /// in-memory engine can drop one of two concurrent writes to a record and /// still answer `Ok` — this asks the primitive the exact question the race diff --git a/src/domain/appointment_slot.rs b/src/domain/appointment_slot.rs index 4b64965..4739699 100644 --- a/src/domain/appointment_slot.rs +++ b/src/domain/appointment_slot.rs @@ -5,7 +5,7 @@ //! cancel that settles it — so the slot frees itself again, and unlike a UNIQUE //! index it does not keep a dead booking's seat. Stored rather than counted //! from the [`Appointment`] rows because a conditional write on one row is the -//! only guard that survives a second replica. +//! only guard a concurrent booking cannot outrun. //! //! A recurring publish is expanded into concrete rows here, at write time, //! sharing one `series` id — no recurrence rule is ever evaluated at read @@ -434,7 +434,7 @@ impl AppointmentSlot { /// going away, so they cascade out with it, like [`Event::delete`]'s rows. /// /// The guard is the delete's own `WHERE`, so no booking can land between a - /// check and the row going away — in this replica or another. + /// check and the row going away. pub async fn delete(self, db: &Database) -> Result { Self::delete_free(std::slice::from_ref(&self.id), db).await?; Ok(self) @@ -459,7 +459,7 @@ impl AppointmentSlot { /// Shared body of both deletes: drop every named slot, but only while its /// `occupied` counter says nobody is waiting on it — the delete's own /// `WHERE` is the guard, which is what makes it hold against a booking - /// landing in another replica (a separate read-then-delete could not). + /// landing in the middle of it (a separate read-then-delete could not). /// /// All-or-nothing across the whole list: if fewer rows go than were named, /// the transaction is thrown away, so a series never loses its free weeks @@ -753,10 +753,10 @@ mod tests { ); } - /// The delete-vs-book race: a booking that lands in another replica between - /// this delete's read and its write must still keep the slot alive, so the - /// guard has to be the delete's own `WHERE` — here driven by taking the seat - /// the way that replica would, with no booking row to read. + /// The delete-vs-book race: a booking that lands between this delete's read + /// and its write must still keep the slot alive, so the guard has to be the + /// delete's own `WHERE` — here driven by taking the seat the way that + /// booking would, with no booking row to read. /// /// A series is all-or-nothing: one taken week refuses the whole publish, /// and the free weeks must survive the refusal. @@ -779,7 +779,7 @@ mod tests { // A free slot goes, and its series is deletable while every week is free. assert!(slots[0].clone().delete(&db).await.is_ok()); // The seat on the middle week is taken — no booking row, exactly as a - // racing replica would leave it mid-flight. + // racing booking would leave it mid-flight. assert!( cap::claim(&slots[1].get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db) .await diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index a96123c..a40e96f 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -387,8 +387,9 @@ impl BankQuestion { /// field is re-stated from the snapshot, and the kind/choices/correct trio /// has to be (a text-only edit re-submits the stored options *with their /// ids* so each keeps its picture) — so without the compare-and-set the - /// later writer silently reverts the earlier one. An in-process `RwLock` - /// only stopped that between requests of *one* replica. + /// later writer silently reverts the earlier one — and the window is a + /// database round trip wide, which is exactly how far apart two concurrent + /// requests to this one process can sit. /// /// Every field the merge re-states is in the guard, which is the same list /// the `SET` writes. `choices` is compared whole: its objects carry two diff --git a/src/domain/cap.rs b/src/domain/cap.rs index 6436392..4499483 100644 --- a/src/domain/cap.rs +++ b/src/domain/cap.rs @@ -1,17 +1,17 @@ -//! Count caps that hold across replicas. +//! Count caps the database enforces, not the process. //! //! Every "at most N children per parent" rule used to be a count-then-write //! under a process-wide `Mutex`, because a `BEGIN…COMMIT` cannot enforce it: //! SurrealDB does not conflict-check a cross-record `count()` against a //! concurrent insert (write-skew), so two racing writers both saw a free slot. -//! A mutex only serializes the writers *inside one process*, and the backend -//! now runs as two replicas against one database — so every one of those caps -//! was open again. +//! A mutex serializes the writers, but only around whatever it wraps: every +//! one of those caps held a lock across a database round trip, and the count it +//! was protecting was already a guess by the time the insert landed. //! //! The guard that does survive is a single-record conditional write: an //! `UPDATE … SET n += 1 WHERE n < cap` on the *parent* row is atomic, so of N //! concurrent claimers exactly `cap` get a non-empty result and the rest are -//! refused, whatever process they run in. The counter is therefore the +//! refused, with no lock and no window. The counter is therefore the //! authority on how many slots are taken, and the child rows follow it: //! [`claim`] before the insert, [`release`] if the insert then fails, and a //! decrement in the *same transaction* as every delete of a child row. @@ -34,14 +34,13 @@ use crate::database::{Database, lost_the_race}; use crate::domain::timestamp::Timestamp; use crate::error::AppError; -/// One writer per process at a time, over every counter. +/// One counter writer at a time, over every counter. /// /// Not the cap — the `WHERE` clause is the cap, and it holds with or without -/// this. What the lock buys is that a replica sends its counter writes one at a -/// time, so the only contention the database ever sees on a parent row is -/// between replicas: at most as many concurrent writers as there are processes, -/// instead of as many as there are in-flight requests. That keeps the optimistic -/// retry loop below to a beat or two rather than a storm. +/// this. What the lock buys is that the process sends its counter writes one at +/// a time, so the database never sees a parent row contended by every in-flight +/// request at once. That keeps the optimistic retry loop below to a beat or two +/// rather than a storm. /// /// It is also what keeps the test suite deterministic. The embedded in-memory /// engine the tests run on does *not* have the real server's conflict @@ -75,7 +74,8 @@ pub(crate) async fn claim( /// [`claim`], but only while `guard` — an extra predicate on that same parent /// row — also holds. A caller whose insert has a second precondition (a homework /// submission's file add is refused once the work is graded) gets both decided -/// by the one conditional write, instead of by a read a peer replica can outrun. +/// by the one conditional write, instead of by a read a concurrent write can +/// outrun. /// A miss is either "full" *or* "the guard failed"; the caller re-reads to tell /// them apart, and only to pick the message. `guard` is always an in-crate SQL /// literal, never user input. @@ -131,11 +131,11 @@ pub(crate) enum Claimed { /// carries a deterministic id (one row per pair), two writers placing the *same* /// pair both pass the claim — neither row exists yet — so on a tight cap the /// second is told "full" for a seat it was never going to need, and a release -/// afterwards is too late to unsay it. A process-wide mutex hid that inside one -/// process and hid nothing between two. Here the duplicate `CREATE` aborts the -/// transaction, which takes its own increment with it, and the caller reads the -/// winner's row back — so the counter never counts a row that does not exist, -/// in any replica. +/// afterwards is too late to unsay it. A process-wide mutex could not hide that +/// either: it is released around the very round trip the two writes race in. +/// Here the duplicate `CREATE` aborts the transaction, which takes its own +/// increment with it, and the caller reads the winner's row back — so the +/// counter never counts a row that does not exist. /// /// The row is looked for *before* the seat is claimed, in that same /// transaction, because on a tight cap the claim is the first thing to fail: a diff --git a/src/domain/chatbot_message.rs b/src/domain/chatbot_message.rs index e48f860..990a453 100644 --- a/src/domain/chatbot_message.rs +++ b/src/domain/chatbot_message.rs @@ -1,11 +1,9 @@ //! One turn of a chatbot thread. Both sides are persisted: the user's prompt //! lands `complete`, and the assistant's row is written `pending` *before* the -//! AI call so a reload never loses an answer in flight. A pending row is then -//! a durable *job*: whichever replica holds a `chat.reply` worker claims it -//! (`claim_pending`), dispatches it, and flips it to `complete` (with the text) -//! or `failed` (with a code). A claimer that dies loses its claim to the next -//! sweep, and the boot sweep in `database.rs` fails whatever nobody could -//! answer inside the staleness window. +//! AI call so a reload never loses an answer in flight. The task that owns the +//! bridge round trip then flips it to `complete` (with the text) or `failed` +//! (with a code), and the boot sweep in `database.rs` fails whatever a process +//! death left behind past the staleness window. //! //! `user_id` is duplicated from the thread onto every message so an //! ownership check is one read, with no join. @@ -16,8 +14,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::{Generator, Ulid}; use crate::constant::{ - CHAT_MESSAGE_TABLE, CHATBOT_CLAIM, CHATBOT_CLAIM_BATCH, CHATBOT_CLAIM_RECLAIM_SECS, - CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, MAX_ERROR_CODE_LEN, STALE_ERROR_CODE, + CHAT_MESSAGE_TABLE, CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, MAX_ERROR_CODE_LEN, + STALE_ERROR_CODE, }; use crate::database::Database; use crate::domain::chatbot_thread::ChatbotThreadId; @@ -148,15 +146,6 @@ pub struct ChatbotMessage { error_code: Option, created_at: Timestamp, completed_at: Option, - /// Which replica's claim loop owes this turn an answer, and when it said - /// so. `None` means nobody has taken it; a claim older than - /// [`CHATBOT_CLAIM_RECLAIM_SECS`] is a claimer that died, and the turn goes - /// back on the queue (see [`ChatbotMessage::claim_pending`]). - /// - /// Never read by an HTTP handler and never in the DTO: whose process is - /// answering is deployment plumbing, not something a client can act on. - claimed_by: Option, - claimed_at: Option, } impl ChatbotMessage { @@ -245,8 +234,6 @@ impl ChatbotMessage { error_code: None, created_at: now, completed_at: Some(now), - claimed_by: None, - claimed_at: None, }, db, ) @@ -272,8 +259,6 @@ impl ChatbotMessage { error_code: None, created_at: Timestamp::now(), completed_at: None, - claimed_by: None, - claimed_at: None, }, db, ) @@ -353,37 +338,6 @@ impl ChatbotMessage { Ok(messages) } - /// Take up to [`CHATBOT_CLAIM_BATCH`] unanswered turns for the claimant - /// `me`, and hand back the rows now owed an answer by *this* process. - /// - /// The queue read. It is deliberately blind to which capabilities exist - /// anywhere: the caller has already asked its own in-process registry - /// whether it can answer, and that registry — never the `ai_worker` gate — - /// is what makes a claim honest. Claiming a turn this process cannot - /// dispatch would park it for a whole reclaim horizon. - /// - /// A lost race is not an error: the guard is re-evaluated per record inside - /// the `UPDATE`, so a row a peer took simply does not come back. A - /// transaction conflict is the same verdict one layer down and yields an - /// empty batch rather than a failure — the next poll re-reads the queue, - /// which is also the retry the conflict asks for. - pub async fn claim_pending(me: &str, db: &Database) -> Result, AppError> { - let result = db - .query(CHATBOT_CLAIM) - .bind(("me", me.to_string())) - .bind(("batch", CHATBOT_CLAIM_BATCH)) - .bind(("stale_ms", CHATBOT_PENDING_STALE_SECS * 1_000)) - .bind(("reclaim_ms", CHATBOT_CLAIM_RECLAIM_SECS * 1_000)) - .await - .and_then(|response| response.check()); - match result { - // Statement 0 is the `LET`; the claimed rows are statement 1. - Ok(mut response) => Ok(response.take::>(1)?), - Err(err) if lost_the_claim(&err) => Ok(Vec::new()), - Err(err) => Err(err.into()), - } - } - /// The user turn this reserved answer belongs to: the newest `user` row /// written before it in the same thread. /// @@ -478,23 +432,6 @@ impl ChatbotMessage { } } -/// A concurrent claim that the key-value layer decided against us, rather than -/// a broken query. Read from the *typed* surface: every engine's conflict -/// wording funnels into `QueryError::TransactionConflict` (surrealdb-core -/// 3.2.3 `err/to_types.rs:295`), where a substring match covers only whichever -/// wording the engine of the day happens to use. -/// -/// Deliberately a second copy of `database::lost_the_race` rather than a shared -/// helper: that one is private to the boot election, which is owned elsewhere -/// and must not gain a caller. Five lines is the cheaper coupling. -fn lost_the_claim(err: &surrealdb::Error) -> bool { - use surrealdb::types::{ErrorDetails, QueryError}; - matches!( - err.details(), - ErrorDetails::Query(Some(QueryError::TransactionConflict)) - ) -} - #[cfg(test)] mod tests { use super::*; @@ -566,28 +503,6 @@ mod tests { } } - #[test] - fn the_claim_horizon_sits_between_the_inference_and_the_stale_window() { - // Both bounds are load-bearing and neither is decoration: - // below the AI request timeout, a reclaim fires while the first - // claimer is still legitimately waiting and two services answer the - // same turn; at or above the staleness horizon a turn stops being - // claimable before the reclaim could ever fire, so a dead claimer's - // turn is never retried at all. - use crate::constant::AI_DEFAULT_REQUEST_TIMEOUT_SECS; - assert!( - CHATBOT_CLAIM_RECLAIM_SECS > AI_DEFAULT_REQUEST_TIMEOUT_SECS as i64, - "a reclaim inside a legitimate inference double-answers the turn" - ); - #[allow(clippy::assertions_on_constants)] - { - assert!( - CHATBOT_CLAIM_RECLAIM_SECS < CHATBOT_PENDING_STALE_SECS, - "a reclaim horizon past the staleness window can never fire" - ); - } - } - #[tokio::test] async fn stale_pending_projects_as_failed() { let aged = |secs: i64| { @@ -602,8 +517,6 @@ mod tests { error_code: None, created_at: Timestamp::from_millis(Timestamp::now().as_millis() - secs * 1_000), completed_at: None, - claimed_by: None, - claimed_at: None, } .projected() }; diff --git a/src/domain/chatbot_thread.rs b/src/domain/chatbot_thread.rs index 915232a..a986d4b 100644 --- a/src/domain/chatbot_thread.rs +++ b/src/domain/chatbot_thread.rs @@ -107,7 +107,7 @@ impl ChatbotThread { /// Start a thread unless `user` is already at the school's /// `max_chatbot_threads`. The slot is taken by [`cap::claim`] on the user - /// row — an atomic single-record write, so two replicas racing the same + /// row — an atomic single-record write, so two requests racing the same /// user's last slot cannot both win, and the cap is read fresh so a /// concurrent settings PATCH is respected. pub async fn create_capped( diff --git a/src/domain/course.rs b/src/domain/course.rs index 9a06a29..07e5e41 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -164,8 +164,8 @@ impl Course { /// Create the course, claiming a reference on the term it links (if any) /// *before* the row is written: the claim is a conditional write on the /// term row, so it fails when the term is already gone and it makes the - /// term undeletable the instant this link exists — across replicas, which - /// the mutex it replaced could not do inside one process. + /// term undeletable the instant this link exists, which the count-then-write + /// mutex it replaced could not do. pub async fn create( creator: &UserId, title: CourseTitle, @@ -401,7 +401,7 @@ impl Course { /// roster is read off the course's own `enrollment_count`, so the check and /// the delete are one conditional write on one record — an enroll racing /// this either takes its seat first (and the delete is refused) or finds - /// the row gone (and is refused itself), in any replica. `Err(NotFound)` + /// the row gone (and is refused itself). `Err(NotFound)` /// keeps the answer a concurrent *delete* used to get. pub async fn delete(self, db: &Database) -> Result { let mut result = db diff --git a/src/domain/enrollment.rs b/src/domain/enrollment.rs index c88a849..9b5338b 100644 --- a/src/domain/enrollment.rs +++ b/src/domain/enrollment.rs @@ -68,8 +68,8 @@ impl Enrollment { /// the loser of the `CREATE` reads the winner's row back and returns it. /// When the course carries a capacity, a full roster refuses new members /// (409) — the seat is taken by [`cap::claim`] on the course row, an atomic - /// single-record conditional write, so the cap holds across replicas and - /// against a concurrent capacity PATCH alike. An already enrolled user is + /// single-record conditional write, so the cap holds against concurrent + /// enrolls and a concurrent capacity PATCH alike. An already enrolled user is /// returned as-is even when the roster is full, and never charged a seat. /// The same claim is the delete guard's other half: it is refused outright /// once the course row is gone, and while it holds a seat the course cannot diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs index 842f52c..cebe86c 100644 --- a/src/domain/exam_attempt.rs +++ b/src/domain/exam_attempt.rs @@ -321,9 +321,10 @@ impl ExamAttempt { /// [`Self::FROZEN_SLOT`] onwards (`BEGIN` and the `IF` take a slot each). /// /// This replaces a process-wide `EXAM_LOCK.write()` held across the check - /// and the write. That lock served one process; the gate serves the - /// database, so a question edit on replica A can no longer sail past an - /// attempt started on replica B. + /// and the write. That lock ordered the two requests but still read the + /// attempt table a round trip before it wrote; the gate checks inside the + /// writing statement, so a question edit can no longer sail past an attempt + /// that started in that gap. // // ponytail: the count and a concurrent `CREATE exam_attempt` are still not // serialized against each other — SurrealDB does not conflict-check a diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index f189427..0539642 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -398,7 +398,7 @@ impl ExamQuestion { // is claimed before the child it caps ([`cap::claim`], here uncapped): // the subject delete is conditioned on that counter reading zero, so // the two contend on the subject record and a question can no longer - // land on a subject another replica is deleting. A miss means the + // land on a subject a concurrent request is deleting. A miss means the // subject is already gone — the same 400 the web layer's pre-flight // check answers with. let counted = subject.record(); @@ -423,7 +423,7 @@ impl ExamQuestion { }; // The freeze gate rides in the same transaction as the insert: a // question cannot appear under an exam somebody has already started, - // whichever replica the two requests hit. + // however the two requests interleave. let inserted = async { let mut result = db .query(ExamAttempt::unfrozen("CREATE $id CONTENT $question;")) diff --git a/src/domain/exam_result.rs b/src/domain/exam_result.rs index d44917e..f0f54c4 100644 --- a/src/domain/exam_result.rs +++ b/src/domain/exam_result.rs @@ -24,7 +24,8 @@ pub(crate) fn draft_error() -> AppError { /// that name, and whether the school has retired it (see /// [`crate::domain::cap`]). Keyed by the name itself: the kind is snapshotted /// text on the exam, and this row is what makes "a kind nothing is graded under -/// may be removed" a decision two replicas can share. +/// may be removed" a decision the database takes, not a count a concurrent mark +/// can invalidate. pub(crate) fn kind_ref(kind: &str) -> RecordId { RecordId::new(KIND_REF_TABLE, kind) } diff --git a/src/domain/fee_plan.rs b/src/domain/fee_plan.rs index 92908ce..bca4a8f 100644 --- a/src/domain/fee_plan.rs +++ b/src/domain/fee_plan.rs @@ -199,9 +199,9 @@ impl FeePlan { /// Has this plan ever been assigned? The 409 guard on edit and delete. /// - /// A scan, and deliberately so: it races an assign landing in the same - /// instant on the other replica, which can leave a plan edited *and* - /// assigned. Accepted — both versions of the plan were manager-approved, + /// A scan, and deliberately so: it races an assign landing in the gap + /// between this read and the edit it licenses, which can leave a plan edited + /// *and* assigned. Accepted — both versions of the plan were manager-approved, /// and the charges the assign raised are frozen copies either way, so no /// money moves behind anyone's back. pub async fn has_assignments(id: &FeePlanId, db: &Database) -> Result { diff --git a/src/domain/fee_plan_assignment.rs b/src/domain/fee_plan_assignment.rs index b503fd3..893d5b9 100644 --- a/src/domain/fee_plan_assignment.rs +++ b/src/domain/fee_plan_assignment.rs @@ -4,8 +4,8 @@ //! //! The row is keyed `_`, and every charge it raises is keyed //! from that same key plus the installment number, so the whole operation is -//! idempotent **by identity**: assigning twice writes nothing the second time -//! (on this replica or the other one), and an assign cut short after three of +//! idempotent **by identity**: assigning twice writes nothing the second time, +//! however the two requests interleave, and an assign cut short after three of //! twelve charges landed completes itself when it is repeated. No scan decides //! "has this been billed yet?" — a scan can be slipped past by a concurrent //! writer, and the cost of that mistake here is a double-billed family. diff --git a/src/domain/field_update.rs b/src/domain/field_update.rs index 37256aa..8695fcd 100644 --- a/src/domain/field_update.rs +++ b/src/domain/field_update.rs @@ -63,7 +63,8 @@ impl FieldUpdate { /// handler made against its snapshot is re-made by the database at write /// time, against the row as it is *then*: two PATCHes each moving one end, /// each fine on its own, cannot commit an inverted range between them. That - /// is what an in-process `Mutex` used to buy, and this holds across replicas. + /// is what an in-process `Mutex` used to buy, without a window between the + /// snapshot and the write for a concurrent request to slip into. /// /// Call it after the `.set()`s of both fields. A PATCH that moves neither /// end emits no guard at all (nothing to race), matching the lock window it diff --git a/src/domain/homework.rs b/src/domain/homework.rs index adbc0c0..136b759 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -164,7 +164,7 @@ impl Homework { // question's twin ([`crate::domain::exam_question::ExamQuestion`]): the // subject delete is refused while this counter is non-zero, so the // create and the delete contend on the subject record rather than on a - // cross-table count only one replica could see. A miss means the + // cross-table count neither of them sees the other move. A miss means the // subject is already gone, which is the 400 the web layer's pre-flight // check answers with. let counted = subject.record(); diff --git a/src/domain/homework_file.rs b/src/domain/homework_file.rs index 04793b8..ce1db2c 100644 --- a/src/domain/homework_file.rs +++ b/src/domain/homework_file.rs @@ -126,7 +126,7 @@ impl HomeworkFile { /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own /// wording). Both are decided by one [`cap::claim_when`] on the submission /// row — a conditional single-record write, the only guard that holds when - /// the racing writers are in two replicas, the same story as + /// two uploads race, the same story as /// `NoteFile::insert`. Which of the two conditions failed is read back /// afterwards, off the losing path only, and only to pick the message. pub async fn insert(self, db: &Database) -> Result, AppError> { diff --git a/src/domain/homework_result.rs b/src/domain/homework_result.rs index c965d4b..a9f2438 100644 --- a/src/domain/homework_result.rs +++ b/src/domain/homework_result.rs @@ -124,9 +124,9 @@ impl HomeworkResult { /// In the same transaction the grade *stamps* the student's submission /// ([`crate::constant::SUBMISSION_GRADED_FIELD`]), which is what freezes it: /// every student-side write to that row then fails its own - /// `graded_by_result = NONE` condition, with no cross-table read for a peer - /// replica to slip past. A submission that does not exist yet is left alone - /// — grading absent work must not conjure a hand-in (the report reads + /// `graded_by_result = NONE` condition, with no cross-table read for a + /// concurrent write to slip past. A submission that does not exist yet is + /// left alone — grading absent work must not conjure a hand-in (the report reads /// `submitted`/`missing`/`late` straight off that row). // // ponytail: that one case keeps a residual race — a student's *first* hand-in diff --git a/src/domain/homework_submission.rs b/src/domain/homework_submission.rs index 79ed7d1..bfd13d3 100644 --- a/src/domain/homework_submission.rs +++ b/src/domain/homework_submission.rs @@ -116,7 +116,7 @@ impl HomeworkSubmission { /// could let two concurrent first-submits pick different stamps and 500. /// /// The `WHERE` is the freeze: [`SUBMISSION_OPEN_GUARD`] makes "not graded - /// yet" a condition of this very write instead of a read the grading replica + /// yet" a condition of this very write instead of a read a concurrent grade /// can land behind. An absent row satisfies it (the stamp is `NONE` there /// too), so a first submit still creates. pub async fn upsert( @@ -285,7 +285,7 @@ mod tests { /// The freeze, as stored state rather than as a race: the grade stamps the /// submission row, and from then on the submission's own writes fail their /// condition — no read of `homework_result` involved, which is what makes it - /// hold when the grader is in the other replica. Un-grading clears the stamp + /// hold when the grade lands mid-request. Un-grading clears the stamp /// and the row is writable again. /// /// Bite check: drop `WHERE graded_by_result = NONE` from diff --git a/src/domain/meal_booking.rs b/src/domain/meal_booking.rs index fdc370e..4825039 100644 --- a/src/domain/meal_booking.rs +++ b/src/domain/meal_booking.rs @@ -14,7 +14,7 @@ //! conditional single-record write ([`cap`]). Counting the rows instead is //! write-skew — SurrealDB does not conflict-check a cross-record count //! against a concurrent insert — and a process-wide lock around that count -//! only holds inside one replica, which the school no longer runs one of. +//! is released around the very round trip the racing insert lands in. //! Cancelling gives the seat back in the *same transaction* as the flip. //! - **The price is claimed, not just read.** The seat is taken at the menu //! revision the price was read at, in the same transaction as the row @@ -159,8 +159,8 @@ impl MealBooking { /// at, so a dish added, re-priced or removed in that gap loses the claim and /// the whole decision is made again on fresh figures. What is frozen onto /// the row is therefore always a price the menu genuinely carried at the - /// instant the seat was taken — the guarantee a lock could only give inside - /// one replica. + /// instant the seat was taken — a guarantee a lock around the read could + /// not give, since the price is read a round trip before the claim. /// /// The charge is appended after, keyed by (seat, attempt): eight concurrent /// `POST`s of one seat hold one seat and write one charge line. The price is diff --git a/src/domain/menu.rs b/src/domain/menu.rs index 3e7cb5a..e98fd15 100644 --- a/src/domain/menu.rs +++ b/src/domain/menu.rs @@ -31,12 +31,13 @@ use crate::error::{AppError, ValidationError}; /// conflict-check). Publishing no longer needs it — the day+slot *is* the /// record id — and neither does a booking, a menu delete, or the settings /// slot-removal guard: those went to conditional single-record writes -/// ([`crate::domain::cap`]), which hold across replicas as this lock cannot. +/// ([`crate::domain::cap`]), which the store decides as this lock cannot. // -// ponytail: the dish cap is therefore still replica-local — two replicas can -// each add the 50th dish. Closing it is another `cap` counter (`dish_count` on -// the menu row) plus its backfill; the ceiling is 51 dishes on a menu, not -// money or a seat, so it was not worth the column here. +// ponytail: the dish cap therefore rests on this lock alone — a dish write +// added without taking it reopens the count-then-write hole silently. Closing +// it properly is another `cap` counter (`dish_count` on the menu row) plus its +// backfill; the ceiling is 51 dishes on a menu, not money or a seat, so it was +// not worth the column here. /// /// A leaf: nothing held under it takes another lock. pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(()); @@ -46,7 +47,7 @@ pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(()); /// [`crate::domain::cap`]). The mirror of /// [`kind_ref`](crate::domain::exam_result::kind_ref) for exam kinds: the slot /// is snapshotted text on the menu, so this row is the only place the two -/// tables' relationship is a single record two replicas can contend on. +/// tables' relationship is a single record concurrent writes can contend on. pub(crate) fn slot_ref(slot: &str) -> RecordId { RecordId::new(SLOT_REF_TABLE, slot) } @@ -56,7 +57,7 @@ pub struct MenuId(RecordId); impl MenuId { /// The one id a menu for this day and slot can have. Deterministic on - /// purpose (the `EnrollmentId` trick): two replicas publishing the same + /// purpose (the `EnrollmentId` trick): two requests publishing the same /// meal race on a single record instead of writing two rows, so the loser /// is told "already exists" by the store and answered the same 409 the /// pre-check gives. `date` is fixed-width `YYYY-MM-DD`, so the `_` joiner @@ -209,8 +210,8 @@ impl Menu { /// Publish a menu. Refused (409) when the day+slot already carries one. /// /// The day and slot *are* the record id ([`MenuId::for_slot`]), so the - /// refusal is decided by the store rather than by a check a peer replica can - /// outrun: two publishes of the same meal write one id, and the loser's + /// refusal is decided by the store rather than by a check a concurrent + /// publish can outrun: two publishes of the same meal write one id, and the loser's /// "already exists" becomes the same 409. The pre-check stays for the /// ordinary case — and for menus published before ids were derived, whose /// ULID key no new publish can collide with. @@ -326,7 +327,7 @@ impl Menu { /// /// Refused (409) while a seat is still held, and the *row itself* decides /// that: the delete carries the seat counter in its `WHERE`, so a booking - /// landing in another replica at that instant either takes its seat before + /// landing at that instant either takes its seat before /// the delete (which then finds a non-zero counter and refuses) or after it /// (and finds no menu). A read-then-delete pair had a window where both /// happened — a paid seat on a menu that no longer exists. diff --git a/src/domain/note_file.rs b/src/domain/note_file.rs index 6d8fe98..1bcc3f9 100644 --- a/src/domain/note_file.rs +++ b/src/domain/note_file.rs @@ -157,8 +157,9 @@ impl NoteFile { /// already holds [`MAX_NOTE_FILES`]. The slot is taken by [`cap::claim`] on /// the note row: a `BEGIN…COMMIT` around a count can't enforce the cap /// (SurrealDB doesn't conflict-check a cross-record count against a - /// concurrent insert) and a process-wide mutex can't either once the - /// backend runs as two replicas — a conditional single-record write can. + /// concurrent insert) and a process-wide mutex can't either, since it is + /// released around the very round trip the insert races — a conditional + /// single-record write can. pub async fn insert(self, db: &Database) -> Result { let note = self.note.record(); if !cap::claim(¬e, NOTE_FILE_COUNT_FIELD, MAX_NOTE_FILES as i64, db).await? { diff --git a/src/domain/payment_ledger.rs b/src/domain/payment_ledger.rs index c56bb5a..877f930 100644 --- a/src/domain/payment_ledger.rs +++ b/src/domain/payment_ledger.rs @@ -53,7 +53,7 @@ //! amount or against a *different* line is a `409`, never the stored line — //! returning it would hide a client bug behind a `201`. //! -//! **The over-payment cap is ADVISORY (accepted race).** [`PaymentLedger::credit`] +//! **The over-payment cap is the lock's, not the database's.** [`PaymentLedger::credit`] //! and [`PaymentLedger::refund`] refuse to take more than the line they target //! is worth, by folding that line's whole subtree under [`PAYMENT_LOCK`]. The //! fold, rather than a sum of the direct children, because money handed back @@ -63,22 +63,26 @@ //! landing between a payment's fold and its append would admit the payment //! against room it no longer has. //! -//! That check is a count-then-write across rows, and SurrealDB does not conflict-check -//! a cross-record read against a concurrent insert (the write-skew this repo has -//! hit before), while the lock is *process-local* and **two replicas serve in -//! production** — so two payments recorded in the same instant on different -//! replicas can together overshoot a charge. Accepted deliberately: the outcome -//! is an over-paid charge, visible in the statement and undone by a refund, -//! and both entries are true records of money that really arrived. A CAS -//! counter row was rejected — refunding would have to decrement it, which is a -//! stored derived balance by another name. +//! The lock is what makes that check mean anything, and it is load-bearing: +//! the fold is a count-then-write across rows, and SurrealDB does not +//! conflict-check a cross-record read against a concurrent insert (the +//! write-skew this repo has hit before), so a fold left unserialized would let +//! two payments both see room and both take it. Running as one process buys +//! nothing on its own — two request tasks interleave across the fold's `await` +//! exactly as two machines would. The cap therefore holds only for as long as +//! *every* write that moves this arithmetic is taken under [`PAYMENT_LOCK`]; +//! a future append that skips it re-opens the hole silently, which is why the +//! rule is stated here rather than left to be noticed. If an over-payment ever +//! does land it is not a crisis — an over-paid charge is plainly visible in the +//! statement and undone by appending a refund, and both entries are true +//! records of money that really arrived. A CAS counter row was rejected — +//! refunding would have to decrement it, which is a stored derived balance by +//! another name. //! -//! The same replica boundary bounds the `request_key` mismatch `409`: it is a -//! read-then-compare, so if two *first-time* posts of one key with different -//! amounts land on two replicas at once, the loser is handed the winner's line -//! as a `201` instead of the conflict. One line, one amount, no double charge — -//! the guarantee that matters holds; only the "you reused a key" diagnostic is -//! best-effort, and every retry after either has landed reports it correctly. +//! The `request_key` mismatch `409` rides on the same lock: it is a +//! read-then-compare, and it is read *inside* the lock, so two first-time posts +//! of one key with different amounts cannot both walk past it. One line, one +//! amount, no double charge, and the "you reused a key" diagnostic is exact. use surrealdb::types::{AlreadyExistsError, RecordId, RecordIdKey, SurrealValue}; use tokio::sync::Mutex; @@ -97,11 +101,12 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -/// Serializes the advisory over-payment check, the append it authorizes, and -/// every other append that changes the arithmetic that check does — nothing -/// else. Process-local, hence the accepted cross-replica race the module doc -/// records. Held across no other lock, and no other lock is taken while it is -/// held. +/// Serializes the over-payment check, the append it authorizes, and every +/// other append that changes the arithmetic that check does — nothing else. +/// It is the whole guarantee behind that cap, not a convenience: the fold it +/// protects is a cross-record read the database will not conflict-check +/// against a concurrent insert. Held across no other lock, and no other lock is +/// taken while it is held. pub(crate) static PAYMENT_LOCK: Mutex<()> = Mutex::const_new(()); #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -132,7 +137,7 @@ impl PaymentLedgerId { } /// The one reversal a line may ever have — a retried undo appends nothing - /// the second time, on this replica or any other. + /// the second time — the id decides that, not a scan. pub fn for_reversal(line: &PaymentLedgerId) -> Self { Self(RecordId::new( PAYMENT_LEDGER_TABLE, @@ -569,7 +574,7 @@ impl PaymentLedger { /// subtree [`PaymentLedger::applied_to`] folds, so one landing between a /// concurrent payment's fold and its append would let that payment be /// admitted against room it no longer has. The lock is what makes the cap - /// exact within a replica, which is the promise this module's doc makes. + /// exact, which is the promise this module's doc makes. pub async fn reversal( line: &PaymentLedger, note: Option, diff --git a/src/domain/registration.rs b/src/domain/registration.rs index 662e2a3..79340ca 100644 --- a/src/domain/registration.rs +++ b/src/domain/registration.rs @@ -68,8 +68,8 @@ impl Registration { /// existing row back untouched — a true no-op that never counts against /// the cap and never rewrites who placed them. The seat is taken by /// [`cap::claim`] on the event row — an atomic single-record conditional - /// write, so neither a racing registration in another replica nor a - /// concurrent capacity/audience/schedule PATCH can over-admit. + /// write, so neither a racing registration nor a concurrent + /// capacity/audience/schedule PATCH can over-admit. pub async fn register( event: &EventId, user: &UserId, diff --git a/src/domain/subject.rs b/src/domain/subject.rs index b47091c..609119f 100644 --- a/src/domain/subject.rs +++ b/src/domain/subject.rs @@ -170,10 +170,10 @@ impl Subject { /// delete with a 409. That refusal is the delete's own `WHERE`, read off the /// two reference counters this row carries /// ([`crate::constant::SUBJECT_QUESTION_COUNT_FIELD`] and its homework - /// twin), which is what makes it hold when the question is created on - /// another replica — the cross-table `SELECT … LIMIT 1` it replaces was a - /// count-then-delete no transaction serializes, pinned by three - /// process-wide locks that only ever served one process. + /// twin), which is what makes it hold against a question created by a + /// request racing this one — the cross-table `SELECT … LIMIT 1` it replaces + /// was a count-then-delete no transaction serializes, pinned by three + /// process-wide locks that could not cover the round trip between them. /// /// Which of the two blocked is read off the counters *before* the delete, /// purely to pick the message; the decision itself was already made by the diff --git a/src/lib.rs b/src/lib.rs index 37e85a0..ea3fe43 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -58,7 +58,7 @@ use crate::state::AppState; (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams — no `mode`, or `open` — drop out); without it the list stays newest-first"), (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` — `date` is text, `YYYY-MM-DD`, and `slot` must be one of the school's `meal_slots` from `GET /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` — edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer — this API never speaks decimals or floats about money. Deleting a menu takes its dishes with it. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` — own always, otherwise teacher+ or a parent link — and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list — the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served); every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) — staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat; a full menu is a `409`, and that cap is serialized in-process, since a cross-record count is not conflict-checked against a concurrent insert. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** — cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. The school's `meal_cancel_cutoff_minutes` closes both ends at once — inside that window neither booking nor cancelling lands (`409`) — measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** — this API stores no school timezone, so staff enter UTC). A slot with no `serving_minute` set falls back to midnight UTC of that date, the pre-serving-time behaviour. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to — the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** — no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row, under the same in-process lock every dish write takes, so no dish can land between the sum and the seat), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once — the charge and its reversal are keyed by (booking, attempt) and written under the same in-process lock as the seat, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge — the charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` — `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked — no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?}`) and is **admin-only**, not manager — the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as teacher+ or as a parent linked to them"), - (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` — a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruş) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. There is no scheduler and no sweep. Assignment is **replay-safe by identity** — an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) — so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree — write a new plan instead. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** — it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) — allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, …}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters — no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `_k_` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice — even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `_r` and so reverses once however often it is retried. Payments and refunds are capped by the line they target (`409` past it) — that cap is **advisory**: it is a cross-record sum taken under a process-local lock, and with two replicas serving, two payments recorded in the same instant can together overshoot a charge. Accepted deliberately: the outcome is an over-paid charge, visible in the statement and undone by a refund, and both lines are true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", …). Every write here is **manager+** — teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope — the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ — **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup — plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) — all folded from the raw lines on every request and stored nowhere"), + (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` — a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruş) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. There is no scheduler and no sweep. Assignment is **replay-safe by identity** — an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) — so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree — write a new plan instead. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** — it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) — allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, …}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters — no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `_k_` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice — even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `_r` and so reverses once however often it is retried. Payments and refunds are capped by the line they target (`409` past it) — that cap is a cross-record sum, which the database cannot enforce on its own — it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", …). Every write here is **manager+** — teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope — the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ — **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup — plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) — all folded from the raw lines on every request and stored nowhere"), (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Also the food program: the meal slots menus are published for — each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) — the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` — one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. Read: any authenticated user; edit: manager+"), (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"), @@ -88,17 +88,6 @@ impl Modify for SecurityAddon { /// Also serves interactive docs: Swagger UI at `/swagger`, raw spec at /// `/api-docs/openapi.json`. Root `/` mirrors the health probe. pub fn build_router(state: AppState) -> Router { - // The AI bridge's two database-backed halves, wired here because this is - // the only place holding the bridge and the database at once: the - // `ai_worker` gate (so peers can see the workers this process holds) and - // this replica's chat claim loop. `attach_presence` returning `true` means - // this call was the first, which is what keeps it to one loop per process. - if let Some(bridge) = state.ai.clone() - && bridge.attach_presence(state.db.clone()) - { - web::chatbot::spawn_claim_loop(bridge, state.db.clone()); - } - let (router, api) = OpenApiRouter::with_openapi(ApiDoc::openapi()) .route("/", get(health)) .routes(routes!(health)) @@ -136,9 +125,9 @@ pub fn build_router(state: AppState) -> Router { state.rate_limit.api_per_minute, state.rate_limit.trust_proxy, ); - // Every tier's budget is fleet-wide, not per process (see + // Every tier's budget outlives the process it was spent in (see // [`rate_limit::RateLimiter::share`]). The chatbot tier is shared here too - // rather than in `main`, so it holds in every process that serves it. + // rather than in `main`, so a router built anywhere gets the same behaviour. api_limiter.share("api", state.db.clone(), state.db_up.clone()); state .chatbot_limit diff --git a/src/main.rs b/src/main.rs index 8e8afd2..48d3a43 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,8 +19,8 @@ async fn main() -> anyhow::Result<()> { // Hash the login decoy now, so the first unknown-username login is not the // one request that pays for it (see `PasswordHash::prewarm_decoy`). hezarfen_backend::domain::user::PasswordHash::prewarm_decoy(); - // Schema *and* the admin seed: both are boot work that must happen once - // across overlapping processes, so both live behind the boot election. + // Connects, migrates the schema and seeds the admin — all of it idempotent + // and unconditional on every boot. let db = database::init(&cfg).await?; let db_up = DbHealth::default(); keepalive(db.clone(), db_up.clone()); diff --git a/src/migration_sql.rs b/src/migration_sql.rs index ae5c4f7..98302cd 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -4,8 +4,8 @@ //! ~700 lines of schema, and left in the constants file they buried the //! validation bounds that file exists to hold. Nothing else changed — they are //! still `pub const`, still the only migration text, and -//! [`crate::database::migrate`] and [`crate::database::migration_fingerprint`] -//! still both read [`MIGRATION_BATCHES`] and nothing else. +//! [`crate::database::migrate`] still reads [`MIGRATION_BATCHES`] and nothing +//! else. //! //! Numbers stay in `constant.rs`: `tests/limits_completeness.rs` sweeps `src/` //! for stray bounds, and a bound hidden here would reach neither `GET /limits` @@ -20,6 +20,9 @@ /// UNSET included. So the value has to go while its definition is still /// standing. Runs as its own query for the usual reason (see `MIGRATION`). /// +/// `chatbot_message.claimed_by` / `claimed_at` (retired 2026-07-30 with the +/// chat claim queue) are the same story, one table over. +/// /// The table-exists guard is load-bearing: on a fresh database `MIGRATION` has /// not run yet, and an UPDATE against an undefined table is an error, not an /// empty result. On a database that has the table but never had the column the @@ -28,6 +31,10 @@ pub const PRE_REPAIR: &str = " IF 'exam_question' IN object::keys((INFO FOR DB).tables) { UPDATE exam_question UNSET source_bank WHERE source_bank != NONE }; + IF 'chatbot_message' IN object::keys((INFO FOR DB).tables) { + UPDATE chatbot_message UNSET claimed_by, claimed_at + WHERE claimed_by != NONE OR claimed_at != NONE + }; "; /// SCHEMAFULL schema: every column is typed, references use `record<..>`. @@ -116,26 +123,26 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS error_code ON chatbot_message TYPE option; DEFINE FIELD IF NOT EXISTS created_at ON chatbot_message TYPE int READONLY; DEFINE FIELD IF NOT EXISTS completed_at ON chatbot_message TYPE option; - -- The claim (2026-07-27): which replica's claim loop owes this turn an - -- answer, and when it said so. Absent = nobody has taken it yet; a claim - -- older than CHATBOT_CLAIM_RECLAIM_SECS is a dead claimer and the turn is - -- taken back (see `CHATBOT_CLAIM`). - DEFINE FIELD IF NOT EXISTS claimed_by ON chatbot_message TYPE option; - DEFINE FIELD IF NOT EXISTS claimed_at ON chatbot_message TYPE option; + -- The chat claim queue is gone (2026-07-30): one process answers its own + -- turns, so nothing claims them. PRE_REPAIR clears the values first — + -- SCHEMAFULL rejects every write to a row still storing a column that no + -- longer exists. + REMOVE FIELD IF EXISTS claimed_by ON TABLE chatbot_message; + REMOVE FIELD IF EXISTS claimed_at ON TABLE chatbot_message; DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at; DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id; - -- The claim loop's sweep: every poll asks for pending rows by age. + -- The boot sweep asks for pending rows by age. DEFINE INDEX IF NOT EXISTS chatbot_message_status_created ON chatbot_message FIELDS status, created_at; - -- Which AI workers are connected to *any* replica (2026-07-27). The GATE - -- and nothing else: a row only says a socket existed somewhere at - -- `seen_at`, so it may spare a user a 503 but must never pick who answers - -- — that is the in-process registry's call. Heartbeated by the replica - -- owning the connection; a stale row is ignored by the read and swept. - DEFINE TABLE IF NOT EXISTS ai_worker SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS service ON ai_worker TYPE string; - DEFINE FIELD IF NOT EXISTS capabilities ON ai_worker TYPE array; - DEFINE FIELD IF NOT EXISTS seen_at ON ai_worker TYPE int; + -- The AI worker presence table is gone (2026-07-30): one process holds + -- every worker socket, so its in-process registry is the whole truth and + -- nothing needed publishing. + REMOVE TABLE IF EXISTS ai_worker; + + -- The elected-boot lease is gone with it (2026-07-30): one process migrates, + -- so nothing takes the lock. SCHEMALESS and read by nobody, so unlike the + -- claim columns it needs no PRE_REPAIR — the table just goes. + REMOVE TABLE IF EXISTS migration_lock; -- How much of a rate-limit budget the whole fleet has spent in one wall -- window (2026-07-27). One row per tier+client+window, id-keyed so every @@ -740,33 +747,23 @@ pub const BACKFILL: &str = " -- which is what they were presented as all along. UPDATE chatbot_message SET truncated = false WHERE truncated = NONE; - -- An assistant turn is answered by a claim loop in some replica's process, - -- so a restart can leave its row `pending` with nobody left to complete it. - -- Only rows past the stale horizon ($stale_ms, from - -- `CHATBOT_PENDING_STALE_SECS`) are certainly abandoned though: a young one - -- may still be being answered on the other side of the AI bridge, and a - -- deploy must not shoot down a turn dispatched seconds ago. Nothing is lost - -- by waiting — a reader already presents an over-age `pending` row as - -- failed, and the next boot sweeps for real whatever crossed the horizon in - -- the meantime. - -- - -- Claim-aware since 2026-07-27, because the sweep is no longer school-wide - -- truth: under N replicas the row may belong to a *live peer's* claim loop, - -- and failing it here would shoot down another process's in-flight turn. - -- So a claim restamped within the window is left alone. Both disjuncts - -- matter — `claimed_by = NONE` alone would strand every row whose claimer - -- died, which is the one case the sweep exists for. + -- An assistant turn is answered by a task in this process, so a restart can + -- leave its row `pending` with nobody left to complete it. Only rows past + -- the stale horizon ($stale_ms, from `CHATBOT_PENDING_STALE_SECS`) are + -- certainly abandoned though: a young one may still be being answered on + -- the other side of the AI bridge, and a deploy must not shoot down a turn + -- dispatched seconds ago. Nothing is lost by waiting — a reader already + -- presents an over-age `pending` row as failed, and the next boot sweeps + -- for real whatever crossed the horizon in the meantime. -- - -- The claim age is measured against $stale_ms rather than - -- CHATBOT_CLAIM_RECLAIM_SECS only because the boot binds one horizon (see - -- `database::migration_binds`); erring long is the safe direction — the - -- cost is that a row claimed just before it aged out waits one more boot - -- for its durable stamp, while readers have shown it failed all along. + -- The claim half of this guard went with the claim queue (2026-07-30): it + -- only ever spared a row a *live peer* was answering, and there is no peer. + -- The rows selected are otherwise the same ones — an unclaimed row past the + -- horizon was always swept, and a claim of this process's own could not + -- outlive the process whose boot is running this. UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted', completed_at = time::unix(time::now()) * 1000 - WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms - AND (claimed_by = NONE - OR claimed_at < time::unix(time::now()) * 1000 - $stale_ms); + WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms; -- Promotion out of student now deletes the user's enrollments (2026-07-18); -- this sweeps rows promoted before that fix. A deleted user reads as @@ -953,10 +950,7 @@ pub const BACKFILL: &str = " "; /// The migration batches, in the order a boot applies them — and the *only* -/// list of them. [`crate::database::migrate`] runs exactly these and -/// [`crate::database::migration_fingerprint`] hashes exactly these, so a fourth -/// batch cannot be executed without changing the fingerprint that decides -/// whether a peer's schema is ours. They stay three separate queries: statements -/// in one batch see the schema as it stood when the batch started (see -/// `MIGRATION`). +/// list of them. [`crate::database::migrate`] runs exactly these. They stay +/// three separate queries: statements in one batch see the schema as it stood +/// when the batch started (see `MIGRATION`). pub const MIGRATION_BATCHES: [&str; 3] = [PRE_REPAIR, MIGRATION, BACKFILL]; diff --git a/src/rate_limit.rs b/src/rate_limit.rs index cf66ad3..54c00a5 100644 --- a/src/rate_limit.rs +++ b/src/rate_limit.rs @@ -25,23 +25,22 @@ //! an accepted trade-off for an implementation simple enough to read in one //! sitting; argon2 keeps each allowed login attempt expensive anyway. //! -//! # Across replicas +//! # The shared window //! -//! The counters above are per process, and the backend runs as two replicas — -//! so a client hitting both got twice its budget. [`RateLimiter::share`] closes -//! that: a background task folds each bucket's new admits into one shared row -//! per tier + client + wall window (`rate_limit`, see +//! The counters above are per process. [`RateLimiter::share`] also carries them +//! through the process: a background task folds each bucket's new admits into +//! one shared row per tier + client + wall window (`rate_limit`, see //! [`crate::constant::RATE_LIMIT_TABLE`]) every -//! [`crate::constant::RATE_SYNC_INTERVAL_SECS`], and the fleet-wide total that -//! comes back caps what the local bucket admits for the rest of that window. +//! [`crate::constant::RATE_SYNC_INTERVAL_SECS`], and the stored total that +//! comes back caps what the local bucket admits for the rest of that window — +//! so a restart mid-window does not hand every client a fresh budget. //! //! Admission itself stays in memory and stays synchronous — no request ever //! waits on the database to be let in, and a database that is down or slow //! costs nothing but the sharing (the tiers fall back to their local budgets -//! rather than failing anyone). The cost is a lag: within one interval a -//! replica can spend up to its own full budget before the shared total tells -//! it to stop, so the fleet's worst case is `replicas × max` for one interval -//! and `max` from then on. +//! rather than failing anyone). The cost is a lag: a process that has just +//! started can spend up to its own full budget for one interval before the +//! shared total tells it to stop. use std::collections::HashMap; use std::hash::Hash; @@ -111,7 +110,7 @@ struct Bucket { /// row. Never above `count`, so `count - pushed` is what is still ours to /// report. pushed: u32, - /// The fleet-wide total the last sync read back — everyone's admits, + /// The stored total the last sync read back — every admit in this window, /// `pushed` included. Zero until a sync lands, which is what makes an /// unshared limiter behave exactly like the local-only one it replaced. remote: u32, @@ -133,9 +132,9 @@ impl Bucket { } } - /// Requests the whole fleet has spent in this window as far as this process - /// can tell: what every replica had reported at the last sync, plus our own - /// admits since. Equals `count` until a sync lands. + /// Requests spent in this window as far as this process can tell: what the + /// shared row held at the last sync — this process's earlier life included — + /// plus our own admits since. Equals `count` until a sync lands. fn spent(&self) -> u32 { self.remote.saturating_add(self.count - self.pushed) } @@ -259,9 +258,9 @@ impl RateLimiter where K: Eq + Hash + Clone + std::fmt::Display + Send + Sync + 'static, { - /// Make this tier's budget fleet-wide: every - /// [`RATE_SYNC_INTERVAL_SECS`] a background task reports what this replica - /// has admitted and reads back what everyone has, which caps further local + /// Make this tier's budget outlive the process: every + /// [`RATE_SYNC_INTERVAL_SECS`] a background task reports what this limiter + /// has admitted and reads back the window's total, which caps further local /// admits in the same window (see the module docs). /// /// `tier` names the counter's namespace in the shared table — two limiters @@ -309,7 +308,7 @@ where } /// Fold every live bucket's new admits into its shared row and take the -/// fleet-wide total back. +/// window's total back. /// /// One statement per bucket in one query, and each statement is its own /// transaction — so a statement that loses a write race fails alone. Its bucket @@ -392,9 +391,9 @@ async fn sync_once( } } -/// The wall-clock window a shared row is keyed by, aligned so every replica -/// agrees on it — the local windows cannot be used for this, since each one -/// starts whenever that client's first request happened to land. +/// The wall-clock window a shared row is keyed by, aligned so a restarted +/// process lands on the same one — the local windows cannot be used for this, +/// since each starts whenever that client's first request happened to land. fn current_epoch(window: Duration) -> i64 { let ms = i64::try_from(window.as_millis()).unwrap_or(i64::MAX).max(1); Timestamp::now().as_millis().div_euclid(ms) * ms diff --git a/src/web/auth.rs b/src/web/auth.rs index 4c9d985..dbb7539 100644 --- a/src/web/auth.rs +++ b/src/web/auth.rs @@ -27,8 +27,8 @@ pub fn routes(state: &AppState) -> OpenApiRouter { // over the auth limit must never block an intentional logout. let rate_limit: &RateLimitConfig = &state.rate_limit; let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy); - // One budget across replicas, not one per process — the tier only means - // something if a brute-forcer cannot get it twice by hitting both. + // The budget survives a restart — the tier only means something if a + // brute-forcer cannot reset it by waiting out a deploy. limiter.share("auth", state.db.clone(), state.db_up.clone()); OpenApiRouter::new() .routes(routes!(register)) diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index 0f7d093..fcec303 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -12,11 +12,11 @@ //! polls `GET .../messages/{mid}` or opens its SSE stream — both read the same //! row, so they can never disagree. //! -//! The pending row *is* the job. It used to be answered by a `tokio::spawn` -//! from the POST, which meant a restart orphaned every turn in flight; since -//! 2026-07-27 it is claimed off the database by [`spawn_claim_loop`], so the -//! turn is answered by whichever process holds a `chat.reply` worker — the one -//! that accepted it, a peer replica, or the one that comes up after a restart. +//! The bridge round trip runs in a `tokio::spawn` the POST leaves behind. A +//! restart therefore orphans a turn in flight: its row stays `pending` until a +//! reader projects it failed, and the boot sweep stamps that verdict durably. +//! Acceptable because the backend is one process with stop-the-world deploys — +//! there is no peer that could have picked the turn up anyway. use std::time::Duration; @@ -35,10 +35,9 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::ai::chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn}; -use crate::ai::{AiBridge, AiError, presence}; +use crate::ai::{AiBridge, AiError}; use crate::constant::{ - AI_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, CHATBOT_CLAIM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN, - MIN_CHUNK_CHARS, REPLY_CHUNKS, + AI_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN, MIN_CHUNK_CHARS, REPLY_CHUNKS, }; use crate::database::Database; use crate::domain::chatbot_message::{ @@ -348,15 +347,10 @@ async fn list_messages( /// Order matters and is deliberate: the per-user rate limit is charged /// *before* anything is written, so a refused turn leaves no trace; /// availability is checked *before* the rows exist, so an unavailable service -/// produces a `503` and no dead pending row. -/// -/// The pending row is a claimed job, not an in-process task: whichever backend -/// process holds a `chat.reply` worker picks it up (within ~200ms) and answers -/// it, so a restart no longer strands the turn — and a process with no worker -/// of its own still accepts turns its peers can answer. The turn always -/// settles: the claiming process stamps `complete`/`failed`, a claim its owner -/// never finishes is retried, a reader projects a long-stale `pending` as -/// failed, and the boot sweep repairs the rest. +/// produces a `503` and no dead pending row. Once the rows are written the turn +/// always settles — the answering task stamps `complete`/`failed`, a reader +/// projects a long-stale `pending` as failed, and the boot sweep repairs +/// whatever a process death left behind. #[utoipa::path( post, path = "/threads/{id}/messages", @@ -395,28 +389,15 @@ async fn send_message( } let content = ChatContent::try_new(&req.content)?; - // The 503 gate, and the only place it is evaluated. Two questions, asked - // cheapest first, and neither of them guards a write — the gate only - // spares the user a thread full of rows nothing could ever answer: - // - // 1. can *this* replica answer? — the in-process registry, which owns - // the sockets. Authoritative and free, so it is asked first, which is - // also why a single-replica deployment pays no round trip here. - // 2. can any *other* replica? — the heartbeated `ai_worker` table, which - // may lag reality by a heartbeat in either direction. A yes here is - // not a promise that this process can do anything: the turn is - // written and a peer's claim loop picks it up. - // - // Neither answer decides who dispatches. That is the claim loop's own - // registry, every time (see `crate::ai::presence`). - let Some(bridge) = st.ai.as_ref() else { + // The 503 gate, and the only place it is evaluated. `has_capability` is + // documented racy — that is fine here: it never guards a write, it only + // spares the user a thread full of rows nothing could ever answer. + let Some(bridge) = st.ai.clone() else { return Ok(unavailable( "the AI service is not enabled on this deployment", )); }; - if !bridge.has_capability(AI_CHAT_CAPABILITY) - && !presence::serves(&st.db, AI_CHAT_CAPABILITY).await - { + if !bridge.has_capability(AI_CHAT_CAPABILITY) { return Ok(unavailable("no AI service is connected right now")); } @@ -434,16 +415,23 @@ async fn send_message( ); } - // Nothing is dispatched here, deliberately. The pending row *is* the job: - // a claim loop — this replica's or a peer's — takes it within one - // `CHATBOT_CLAIM_POLL_MS` tick and answers it. An in-process - // `tokio::spawn` could not survive the restart that orphans the turn, - // which is the whole failure this queue removes. + let message_id = answer.get_id().key().to_string(); + // Never awaited inline: the bridge round trip can outlast the request + // timeout that guards every handler, and the POST must return now. The + // settings snapshot goes with it, so the whole turn is judged by the policy + // that was live when it was accepted. + tokio::spawn(answer_turn( + bridge, + st.db.clone(), + answer, + settings.get_chatbot_history_turns().max(0) as usize, + reply_cap, + )); Ok(( StatusCode::ACCEPTED, Json(AcceptedResponse { - message_id: answer.get_id().key().to_string(), + message_id, status: MessageStatus::Pending.as_str().to_string(), }), ) @@ -468,76 +456,7 @@ fn unavailable(message: &str) -> Response { .into_response() } -/// This replica's share of the chat work queue. -/// -/// One task per process, started by [`crate::build_router`] when a bridge is -/// configured. Every [`CHATBOT_CLAIM_POLL_MS`] it asks *its own* registry -/// whether it can serve `chat.reply` and, if so, claims a small batch of -/// unanswered turns and dispatches them. -/// -/// The registry is the only thing consulted, never the `ai_worker` gate: the -/// gate can say a peer has a worker, and claiming on that word would park the -/// turn here for a whole reclaim horizon with no socket to send it down (see -/// [`crate::ai::presence`]). -/// -/// ponytail: no shutdown handle — the loop runs for the life of the process, -/// which is the life of the bridge, and it is idle (one registry read per -/// tick, no query) whenever this replica holds no chat worker. Give it a -/// `CancellationToken` the day the bridge itself becomes restartable. -pub fn spawn_claim_loop(bridge: AiBridge, db: Database) { - // Any unique string. It is only ever compared for equality and read in a - // log line: a claim identifies the *process*, and a claim nobody renews - // expires by age rather than by anyone recognising the claimant. - let me = ulid::Ulid::new().to_string(); - tokio::spawn(async move { - let mut ticker = tokio::time::interval(Duration::from_millis(CHATBOT_CLAIM_POLL_MS)); - ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); - loop { - ticker.tick().await; - // The DISPATCHER's answer, and the gate that matters here. - if !bridge.has_capability(AI_CHAT_CAPABILITY) { - continue; - } - let claimed = match ChatbotMessage::claim_pending(&me, &db).await { - Ok(claimed) => claimed, - Err(err) => { - tracing::warn!("could not claim chat turns: {err}"); - continue; - } - }; - if claimed.is_empty() { - continue; - } - // Read once per batch, not per turn. Unlike the old in-process - // spawn this is the policy live when the turn is *answered* rather - // than when it was accepted — unavoidable once the answering - // process may not be the accepting one, and the window is one poll - // tick wide in the normal case. - let settings = match Settings::load(&db).await { - Ok(settings) => settings, - Err(err) => { - tracing::warn!("could not load settings for a claimed chat turn: {err}"); - continue; - } - }; - let reply_cap = content_cap(&settings); - let history_turns = settings.get_chatbot_history_turns().max(0) as usize; - for answer in claimed { - // One task per turn: the bridge round trip can take tens of - // seconds and must not hold up the next poll. - tokio::spawn(answer_turn( - bridge.clone(), - db.clone(), - answer, - history_turns, - reply_cap, - )); - } - } - }); -} - -/// Fetch one claimed turn's answer and settle its row. +/// Fetch one turn's answer and settle its row. Runs detached from the request. /// /// Every path settles: a row left `pending` would show as a spinner forever. async fn answer_turn( @@ -549,9 +468,9 @@ async fn answer_turn( ) { let answer_id = answer.get_id().clone(); let thread = answer.get_thread_id().clone(); - // The question this reserved row was written next to. Recovered from the - // thread rather than carried in memory, because the process that accepted - // the turn may no longer exist. + // The question this reserved row was written next to, read back from the + // thread — the prompt is already stored, so passing it along would only be + // a second copy of the same string. let prompt = match answer.prompt_for(&db).await { Ok(Some(prompt)) => prompt, Ok(None) => { @@ -563,7 +482,11 @@ async fn answer_turn( return; } Err(err) => { + // Nothing to ask, and nothing will ask again: the claim queue that + // used to reclaim an unsettled row is gone, so leaving it `pending` + // means a spinner until the 300s stale horizon. Settle it here. tracing::warn!("could not read the prompt for {}: {err}", answer_id.key()); + let _ = ChatbotMessage::fail(&answer_id, "internal", &db).await; return; } }; diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 20887f4..472abc7 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -90,7 +90,7 @@ use crate::web::exams::{ /// `allow_rejoin` off (cleared at the door, stamped after, present forever /// refused). The count this pairs with lives in *this* process's memory /// ([`crate::state::ExamPresence`]), so process-wide is exactly the right -/// scope: a peer replica counts its own sockets in its own map. +/// scope: there is no room state anywhere else to serialize against. // ponytail: global lock, per-attempt locks if room churn ever shows up in a // profile. static PRESENCE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); @@ -397,12 +397,13 @@ async fn handle_message( // like `save_answer_checked` — and dropped before the socket // sends, so a slow client never stalls a writer. // - // ponytail (accepted race, reviewed): the lease is process-local, - // so across replicas a save already in flight can land on the - // room's sitting just after a retake made it terminal. It writes a - // history row for the old seq; the grade of record (latest seq) is - // untouched. The fix is a `current_seq` claim on every save — the - // hottest path here — so the cost beats the damage and it stays. + // ponytail (accepted race, reviewed): the room's sitting was + // chosen at join, before any lease, so no lock scope can help — a + // save can land on it just after a retake made it terminal. It + // writes a history row for the old seq; the grade of record (latest + // seq) is untouched. The fix is a `current_seq` claim on every save + // — the hottest path here — so the cost beats the damage and it + // stays. let guard = EXAM_LOCK.read().await; // Tracks how far the gates got: only once the sitting resolved can // a failure possibly be about this one question rather than about diff --git a/src/web/exams/attempts.rs b/src/web/exams/attempts.rs index a640a1e..f07b78d 100644 --- a/src/web/exams/attempts.rs +++ b/src/web/exams/attempts.rs @@ -666,13 +666,11 @@ pub(crate) async fn save_answer_checked( // one unit, or a retake's wipe-and-create (a writer) slips in between // and this stale save lands on the fresh blank sheet. // - // ponytail (accepted race, reviewed): the lease is process-local, so with - // more than one replica a save that started just before a retake can still - // stamp its answer onto the *old* seq, milliseconds after that sitting went - // terminal. Damage is confined to a history row — the grade of record is - // the latest seq, which the late write never touches. Closing it needs a - // `current_seq` claim on every answer save, the hottest path in the app; - // cost beats the damage, so it stays open on purpose. + // The lease covers the gate *and* the upsert here, so a retake cannot + // interleave with this path at all. The accepted late-save race lives in + // the exam-room socket instead, which writes into the sitting it joined + // with — a value chosen before any lease is taken. See + // [`crate::web::exam_ws`]. let _guard = EXAM_LOCK.read().await; let attempt = writable_attempt(exam, user, db).await?; save_answer_in(exam, &attempt, question_id, selected, text, db).await diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index a7d8c08..0806ac6 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -71,10 +71,11 @@ impl Scheduled for Exam { /// Serializes the exam subsystem's cross-record check-then-writes, which /// `BEGIN…COMMIT` cannot (write skew) — the reasoning in [`crate::domain::cap`]. -/// **Replica-local**: it orders requests inside one process only, and the -/// backend runs as two, so every invariant that could be moved into the -/// database has been. What is left needs a cross-record read and a write held -/// together, which no single statement expresses: +/// It orders requests, but only around what it wraps — every invariant that +/// could be moved into the database itself has been, so a gap between a read +/// and its write is decided by the store. What is left here needs a +/// cross-record read and a write held together, which no single statement +/// expresses: /// /// Read side — the answer saves (REST and the exam room), from the /// writable-attempt gate through the upsert; the grade write (draft gate @@ -402,11 +403,11 @@ async fn update_exam( // *Reader* lease of [`EXAM_LOCK`] for exactly one pairing: the mode gate // below reads `exam_attempt`, and an attempt start takes the *writer* // lease, so a first sitting still cannot land between that gate and the - // write — replica-locally, as it always did. + // write, as it always did. // // It buys nothing against grading, which is a reader too: the re-draft gate // is therefore enforced inside the update's own transaction - // (`Exam::update_if_unchanged`), where it holds across replicas. The gate + // (`Exam::update_if_unchanged`), where the store decides it. The gate // below stays as the pre-flight — same error, one round trip earlier. // Concurrent PATCHes of this exam no longer queue behind each other either: // the lost update they used to cause is refused by the compare-and-set. diff --git a/src/web/homework.rs b/src/web/homework.rs index 4331e15..bed6218 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -44,11 +44,11 @@ use super::{ /// Serializes the homework subsystem's cross-record check-then-writes, which /// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as -/// [`crate::web::exams::EXAM_LOCK`]. It is a *within-replica* guard only, so -/// the rule it can no longer be trusted with is the freeze: a graded submission -/// used to stay unedited because the "no grade yet" read and the write it -/// licensed sat under one lease, which two processes never shared. That rule -/// moved into the database — grading stamps +/// [`crate::web::exams::EXAM_LOCK`]. It orders requests but cannot cover a +/// round trip, so the rule it can no longer be trusted with is the freeze: a +/// graded submission used to stay unedited because the "no grade yet" read and +/// the write it licensed sat under one lease, with the database consulted in +/// between. That rule moved into the database — grading stamps /// [`crate::constant::SUBMISSION_GRADED_FIELD`] on the submission row and every /// student-side write carries `graded_by_result = NONE` as its own condition. /// @@ -633,8 +633,7 @@ async fn submit( // The graded gate, twice over. This read answers the common case — graded // minutes ago, and the student who never submitted has no row to carry the // freeze; the upsert's own `WHERE` (the grade stamp on the row) is what - // holds when the grade lands *while* this request runs, in this replica or - // the other one. + // holds when the grade lands *while* this request runs. if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db) .await? .is_some() diff --git a/src/web/meals.rs b/src/web/meals.rs index 8152e10..626d3bf 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -372,7 +372,7 @@ async fn delete_menu( .await? .ok_or(AppError::NotFound)?; // The seat check rides in the delete's own `WHERE` (see `Menu::delete`), so - // a booking landing in another replica cannot slip between the two. + // a concurrent booking cannot slip between the read and the delete. menu.delete(&st.db).await?; Ok(StatusCode::NO_CONTENT) } diff --git a/src/web/settings.rs b/src/web/settings.rs index 72839ee..446d6e5 100644 --- a/src/web/settings.rs +++ b/src/web/settings.rs @@ -331,7 +331,7 @@ async fn update_settings( // only while nothing references the name and refuses every claim from // that instant on. That is the whole guard: the check and the removal // used to be a cross-table count and a save held together by a - // process-wide lock, which the second replica walked straight through. + // process-wide lock that was released around the round trip between them. // // Retired before the save, never after: the other order leaves a window // in which a mark lands under a kind the settings no longer list. A save diff --git a/src/web/subjects.rs b/src/web/subjects.rs index 3786a0d..77d1744 100644 --- a/src/web/subjects.rs +++ b/src/web/subjects.rs @@ -192,8 +192,8 @@ async fn delete_subject( // No locks: the two checks *are* the delete's `WHERE`, decided against the // subject's own reference counters inside one statement. This used to be // three process-wide locks (the only site that held more than one) around - // two cross-table counts, which served one replica and let the other create - // a question on a subject being deleted. + // two cross-table counts, which were stale by the time the delete landed and + // let a concurrent request create a question on a subject being deleted. subject.delete(&st.db).await?; Ok(StatusCode::NO_CONTENT) } diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index 49d0c69..4512c03 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -1162,227 +1162,6 @@ async fn a_blank_chat_answer_fails_as_empty_reply() { assert_eq!(turn["error_code"], "empty_reply"); } -// ----------------------------------------------------------- claim queue -- -// -// A pending assistant row is a durable job, not an in-process task. These -// prove the three things that buys: a turn nobody could answer yet is answered -// when a worker appears, a claim whose owner died is taken back, and a turn is -// dispatched exactly once no matter how many replicas are watching the queue. - -use hezarfen_backend::constant::{CHATBOT_CLAIM_POLL_MS, CHATBOT_CLAIM_RECLAIM_SECS}; -use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage}; -use hezarfen_backend::domain::chatbot_thread::ChatbotThreadId; -use hezarfen_backend::domain::user::UserId; - -/// Write one turn's two rows straight to the queue, bypassing the POST — what -/// a replica that has since died would have left behind. Returns the reserved -/// assistant row's key. -async fn queue_turn(app: &Router, db: &Database, cookie: &str, thread: &str, text: &str) -> String { - let me = common::send(app, "GET", "/auth/me", Some(cookie), None).await; - let user = UserId::from_key(me.body["id"].as_str().expect("own id")); - let thread = ChatbotThreadId::from_key(thread); - ChatbotMessage::append_user(&thread, &user, ChatContent::try_new(text).unwrap(), db) - .await - .expect("the user's turn"); - ChatbotMessage::append_pending_assistant(&thread, &user, db) - .await - .expect("the reserved answer") - .get_id() - .key() - .to_string() -} - -/// A turn nobody has claimed, held by `claimant` since `age_secs` ago. -async fn stamp_claim(db: &Database, mid: &str, claimant: &str, age_secs: i64) { - db.query( - "UPDATE $id SET claimed_by = $who, claimed_at = time::unix(time::now()) * 1000 - $age", - ) - .bind(("id", RecordId::new("chatbot_message", mid.to_string()))) - .bind(("who", claimant.to_string())) - .bind(("age", age_secs * 1_000)) - .await - .expect("stamp a claim") - .check() - .expect("stamp a claim"); -} - -async fn status_of(app: &Router, cookie: &str, thread: &str, mid: &str) -> String { - let res = common::send( - app, - "GET", - &format!("/chatbot/threads/{thread}/messages/{mid}"), - Some(cookie), - None, - ) - .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); - res.body["status"].as_str().expect("status").to_string() -} - -#[tokio::test] -async fn a_turn_written_with_no_worker_is_answered_once_one_appears() { - // The failure this queue removes: the row used to be answered by a task - // spawned inside the POST, so a turn that outlived its process — or was - // written while nothing could serve it — settled `failed` at the staleness - // horizon and never got an answer at all. - let bridge = bridge().await; - let (app, db) = chat_app(&bridge).await; - let (cookie, thread) = chat_user(&app, "ali").await; - - // Nothing is connected, so the gate refuses the POST outright… - let res = common::send( - &app, - "POST", - &format!("/chatbot/threads/{thread}/messages"), - Some(&cookie), - Some(json!({ "content": "kimse yokken" })), - ) - .await; - assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body); - - // …but a row already on the queue (written by a replica that has since - // gone) must still be picked up. - let mid = queue_turn(&app, &db, &cookie, &thread, "kimse yokken").await; - let _service = connect_service( - &bridge, - hello("tutor", &[AI_CHAT_CAPABILITY]), - Behaviour::Reply("geç gelen cevap".into()), - ) - .await; - await_workers(&bridge, 1).await; - - let turn = settled(&app, &cookie, &thread, &mid).await; - assert_eq!(turn["status"], "complete", "{turn}"); - assert_eq!(turn["content"], "geç gelen cevap"); -} - -#[tokio::test] -async fn a_claim_left_by_a_dead_replica_is_taken_back() { - let bridge = bridge().await; - let service = connect_service( - &bridge, - hello("tutor", &[AI_CHAT_CAPABILITY]), - Behaviour::Reply("devraldım".into()), - ) - .await; - await_workers(&bridge, 1).await; - let (app, db) = chat_app(&bridge).await; - let (cookie, thread) = chat_user(&app, "ali").await; - - // A claim a peer took moments ago is respected: that peer is presumably - // still waiting on its inference, and answering alongside it would run the - // model twice for one reply. - let live = queue_turn(&app, &db, &cookie, &thread, "başkası bakıyor").await; - stamp_claim(&db, &live, "a-live-peer", 1).await; - for _ in 0..10 { - tokio::time::sleep(Duration::from_millis(CHATBOT_CLAIM_POLL_MS)).await; - } - assert_eq!( - status_of(&app, &cookie, &thread, &live).await, - "pending", - "a live peer's claim was stolen" - ); - assert!(service.seen().is_empty(), "{:?}", service.seen()); - - // The same claim, past the reclaim horizon, is a claimant that died. The - // turn goes back on the queue rather than waiting out its staleness - // window with nobody answering it. - stamp_claim(&db, &live, "a-dead-peer", CHATBOT_CLAIM_RECLAIM_SECS + 1).await; - let turn = settled(&app, &cookie, &thread, &live).await; - assert_eq!(turn["status"], "complete", "{turn}"); - assert_eq!(turn["content"], "devraldım"); - assert_eq!(service.seen().len(), 1, "{:?}", service.seen()); -} - -#[tokio::test] -async fn a_claimed_turn_is_dispatched_exactly_once() { - // The claim is what stops the poll loop from re-sending a turn every tick - // while the first inference is still running. A silent service holds the - // stream open, so every extra dispatch would show up in `seen()`. - let bridge = bridge_with_timeout(Duration::from_secs(30)).await; - let service = connect_service( - &bridge, - hello("tutor", &[AI_CHAT_CAPABILITY]), - Behaviour::Silent, - ) - .await; - await_workers(&bridge, 1).await; - let (app, _db) = chat_app(&bridge).await; - let (cookie, thread) = chat_user(&app, "ali").await; - - let mid = ask(&app, &cookie, &thread, "uzun sürecek bir soru").await; - await_inflight(&bridge, 1).await; - // Ten poll ticks with the answer still outstanding. - tokio::time::sleep(Duration::from_millis(CHATBOT_CLAIM_POLL_MS * 10)).await; - assert_eq!( - service.seen().len(), - 1, - "one turn, one dispatch: {:?}", - service.seen() - ); - assert_eq!(status_of(&app, &cookie, &thread, &mid).await, "pending"); -} - -#[tokio::test] -async fn a_replica_with_no_worker_accepts_a_turn_its_peer_answers() { - // Two replicas, one database, and the worker dialled into exactly one of - // them. The other has nothing to dispatch with — its own registry says so - // — yet it must still accept the turn, because the `ai_worker` gate can - // see its peer. And exactly one of the two answers it. - let db = hezarfen_backend::database::init_mem() - .await - .expect("mem db"); - let quiet = bridge().await; - let serving = bridge().await; - let app_quiet = replica(&quiet, &db); - let app_serving = replica(&serving, &db); - - let service = connect_service( - &serving, - hello("tutor", &[AI_CHAT_CAPABILITY]), - Behaviour::Reply("komşudan cevap".into()), - ) - .await; - await_workers(&serving, 1).await; - assert!(!quiet.has_capability(AI_CHAT_CAPABILITY), "no local worker"); - // The gate is heartbeated, so give the serving replica's first beat time - // to publish its worker before asking the replica that holds none. - for _ in 0..300 { - if hezarfen_backend::ai::presence::serves(&db, AI_CHAT_CAPABILITY).await { - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - - let (cookie, thread) = chat_user(&app_quiet, "ali").await; - let mid = ask(&app_quiet, &cookie, &thread, "komşuya soru").await; - let turn = settled(&app_quiet, &cookie, &thread, &mid).await; - assert_eq!(turn["status"], "complete", "{turn}"); - assert_eq!(turn["content"], "komşudan cevap"); - assert_eq!(service.seen().len(), 1, "{:?}", service.seen()); - // The answer is one row, so the peer that accepted the turn reads exactly - // what the peer that answered it wrote. - assert_eq!( - status_of(&app_serving, &cookie, &thread, &mid).await, - "complete" - ); -} - -/// A second process against the same database: its own bridge, its own claim -/// loop, one shared queue. -fn replica(bridge: &AiBridge, db: &Database) -> Router { - hezarfen_backend::build_router(hezarfen_backend::state::AppState { - db: db.clone(), - files_path: common::files_dir(), - cookie_secure: false, - rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), - chatbot_limit: Default::default(), - exam_presence: Default::default(), - db_up: Default::default(), - ai: Some(bridge.clone()), - }) -} - // ------------------------------------------------------------- boot wiring -- // // `ai::start_bridge` is the seam between deployment config and the listener. diff --git a/tests/integration.rs b/tests/integration.rs index 9e02eed..c65c0e0 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -4140,7 +4140,7 @@ async fn concurrent_placements_never_exceed_capacity() { /// The course capacity cap is a counter column on the course row now, not a /// process mutex: `UPDATE ... SET n += 1 WHERE n < capacity` is atomic per -/// record, so it holds whichever replica the racing enrolls land on. Removing +/// record, so it holds however the racing enrolls interleave. Removing /// that `WHERE` (or the claim entirely) puts a third student on a capacity-2 /// course and fails this. The unenroll each round proves the seat comes back — /// without the decrement the course is permanently full by round two. @@ -21374,7 +21374,7 @@ async fn concurrent_meal_bookings_never_exceed_the_capacity() { assert_eq!(common::total(&res.body), 3, "and only three rows exist"); // The rows are downstream of the counter, so assert the counter itself: - // it is what every replica's `WHERE` compares, and a drift here would open + // it is what every booking's `WHERE` compares, and a drift here would open // the cap on the next booking however tidy the listing looks. let mut counted = db .query("SELECT VALUE seats_booked FROM type::record('menu', $m)") @@ -21393,8 +21393,7 @@ async fn concurrent_meal_bookings_never_exceed_the_capacity() { /// Publishing the same day+slot twice at once must be one menu and one 409 — /// never two rows and never a 500. The day and slot *are* the record id, so the /// racers collide on a single record inside the database rather than on a -/// check-then-write pair, which is the only form that also holds when the two -/// `POST`s land on different replicas. +/// check-then-write pair, which is the only form no interleaving can defeat. #[tokio::test] async fn concurrent_duplicate_menu_publishes_conflict_not_500() { let (app, db) = app_and_db().await; diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs index c9278f3..abaa3b6 100644 --- a/tests/limits_completeness.rs +++ b/tests/limits_completeness.rs @@ -86,30 +86,6 @@ const EXCLUDED: &[(&str, &str)] = &[ "CHATBOT_PENDING_STALE_SECS", "when a stuck answer is declared failed", ), - // The AI worker gate (`ai_worker`) and the chat claim queue. Both are - // between-replica plumbing: a browser cannot observe which process holds a - // worker or who claimed its turn, and it already learns everything it can - // act on from the 202/503 and the turn's own `status`. - ("AI_WORKER_TABLE", "AI worker presence table"), - ("AI_WORKER_ANNOUNCE", "AI worker presence upsert"), - ("AI_WORKER_WITHDRAW", "AI worker presence delete"), - ("AI_WORKER_SWEEP", "AI worker presence expiry"), - ("AI_WORKER_SERVES", "AI worker presence read"), - ( - "AI_WORKER_HEARTBEAT_SECS", - "how often a replica restamps its AI workers", - ), - ( - "AI_WORKER_LEASE_SECS", - "how long an unrestamped AI worker row is believed", - ), - ("CHATBOT_CLAIM", "chat claim-queue statement"), - ("CHATBOT_CLAIM_POLL_MS", "chat claim-loop cadence"), - ("CHATBOT_CLAIM_BATCH", "turns claimed per sweep"), - ( - "CHATBOT_CLAIM_RECLAIM_SECS", - "when a dead claimer's turn goes back on the queue", - ), // Seed data for the settings singleton, not a bound. The live list is on // `GET /settings`, which is where a client must read it — publishing the // default too would invite rendering it instead of the school's actual one. @@ -125,25 +101,6 @@ const EXCLUDED: &[(&str, &str)] = &[ "DEFAULT_DIETARY_TAGS", "settings seed; the live list is on GET /settings", ), - // The boot leader election. A client never sees the lock, and the timings - // are startup mechanics between processes — publishing them would invite a - // frontend to reason about a boot it cannot observe. - ("MIGRATION_LOCK_DDL", "boot lock table definition"), - ("MIGRATION_LOCK_CLAIM", "boot lock claim statement"), - ("MIGRATION_LOCK_STATE", "boot lock read statement"), - ("MIGRATION_LOCK_TAKEOVER", "boot lock takeover statement"), - ("MIGRATION_LOCK_HEARTBEAT", "boot lock lease renewal"), - ("MIGRATION_LOCK_STAMP", "boot lock completion stamp"), - ( - "MIGRATION_LOCK_LEASE_SECS", - "how long an unrenewed boot lock may be taken over after", - ), - ("MIGRATION_LOCK_HEARTBEAT_SECS", "boot lock renewal cadence"), - ( - "MIGRATION_LOCK_WAIT_SECS", - "how long a non-leader waits for the boot migration", - ), - ("MIGRATION_LOCK_POLL_MS", "boot lock poll cadence"), // The three migration batches and their list moved to // `src/migration_sql.rs` — they are SurrealQL text, not bounds, and the // numeric sweep below still catches any bound that tries to follow them. @@ -192,9 +149,9 @@ const EXCLUDED: &[(&str, &str)] = &[ "ETag middleware's own buffering ceiling", ), ("PURGE_AT", "rate-limiter bucket eviction threshold"), - // How the tiers are kept fleet-wide. A client is held to the tier itself - // (published live in /limits `rate`), never to the cadence the replicas - // reconcile it at — publishing that would invite pacing against it. + // How a tier's window is carried through a restart. A client is held to + // the tier itself (published live in /limits `rate`), never to the cadence + // it is reconciled at — publishing that would invite pacing against it. ( "RATE_SYNC_INTERVAL_SECS", "how often a replica reconciles its counters", diff --git a/tests/name_refs.rs b/tests/name_refs.rs index f630750..1d9d73a 100644 --- a/tests/name_refs.rs +++ b/tests/name_refs.rs @@ -165,7 +165,7 @@ async fn marks_release_their_kind_when_they_are_deleted() { /// The claim's `WHERE`, the other half of the same race: once the kind is out /// of the list, a mark can no longer land under it. Whichever of the two /// writes reaches the counter first, the other is refused — which is what makes -/// the pair safe with two replicas and no shared lock. +/// the pair safe without a lock spanning both writes. #[tokio::test] async fn a_removed_kind_refuses_a_grade() { let school = school_with_kinds(&["lab", "quiz"]).await; diff --git a/tests/rate_limit.rs b/tests/rate_limit.rs index 6e2c3ee..bf6a13d 100644 --- a/tests/rate_limit.rs +++ b/tests/rate_limit.rs @@ -310,16 +310,20 @@ async fn concurrent_bursts_never_over_admit() { assert_eq!((ok, limited), (5, 15)); } -// --- shared across replicas -------------------------------------------- +// --- the window outlives the process ------------------------------------ // -// Two `UserRateLimiter`s over one database stand in for two replicas: they are -// separate processes' worth of in-memory buckets, sharing only the `rate_limit` -// table. Time is paused, so a round of the sync task is driven by advancing -// past `RATE_SYNC_INTERVAL_SECS` — and because the task blocks on the database -// (not on time) mid-round, the short sleep afterwards cannot resolve until the -// round has finished. Assertions are on admissions, never on which replica won -// a race: the embedded engine can drop one of two concurrent writes and still -// answer `Ok`. +// Two `UserRateLimiter`s over one database stand in for the process before and +// after a restart: two separate sets of in-memory buckets sharing only the +// `rate_limit` table, which is what stops a restart mid-window from handing +// every client a fresh budget. Time is paused, so a round of the sync task is +// driven by advancing past `RATE_SYNC_INTERVAL_SECS` — and because the task +// blocks on the database (not on time) mid-round, the short sleep afterwards +// cannot resolve until the round has finished. Assertions are on admissions, +// never on which limiter won a race: the embedded engine can drop one of two +// concurrent writes and still answer `Ok`. +// +// (The `replica` spelling below is historical — renaming test items is a code +// change, not a doc one.) use hezarfen_backend::constant::RATE_SYNC_INTERVAL_SECS; use hezarfen_backend::database::Database; @@ -351,7 +355,7 @@ async fn sync_round() { tokio::time::pause(); } -/// Two "replicas" of one tier, sharing `db`. +/// Two limiters of one tier, sharing `db`. fn two_replicas(max: u32, db: &Database) -> (UserRateLimiter, UserRateLimiter, DbHealth) { let health = DbHealth::default(); let (a, b) = ( @@ -375,13 +379,12 @@ async fn two_replicas_share_one_budget() { let db = shared_db().await; let (a, b, _health) = two_replicas(6, &db); - // Both replicas spend freely until their first sync — the accepted - // one-interval overshoot, and the whole reason the fleet needs the shared - // row at all. + // Each spends freely until its first sync — the accepted one-interval + // overshoot, and the whole reason the shared row exists at all. let spent = admits(&a, "user:a", 6) + admits(&b, "user:a", 6); assert_eq!(spent, 12, "each replica starts on its own local budget"); - // From the first sync on, the fleet total is what binds: neither replica + // From the first sync on, the shared total is what binds: neither limiter // admits anything more in this window, whatever the interleaving was. sync_round().await; assert_eq!( @@ -424,7 +427,7 @@ async fn a_down_database_leaves_each_replica_on_its_local_budget() { health.set(false); // Nothing is shared while the database is down — and nothing stalls: both - // replicas keep serving their own budgets at full speed. + // limiters keep serving their own budgets at full speed. for _ in 0..3 { sync_round().await; assert_eq!(admits(&a, "user:a", 1), 1);