forge
Explore
Log in

Don't you dare go Hollow

🧹 drop the coordination for replicas we never run

Browse files at this commit

a9cfe7ba613ef9ba0f12ffa01da30d9ef18a2effAhmet Kaan GümüşParent: 9490623
  • chore
    • 🧹 drop the coordination for replicas we never run
Show full message
chore: 🧹 drop the coordination for replicas we never run

The backend runs as one process against one database, deployed
stop-the-world. The machinery that let several of them agree was built
ahead of a multi-replica rollout that stayed parked, so none of it was
ever load-bearing: the boot lease elected a leader out of a field of
one, the ai_worker table announced a worker to nobody, and the chat
claim queue only ever claimed its own writes.

Boot now migrates and seeds straight-line; a chat turn is dispatched by
the handler that accepted it; the 503 gate reads the in-process
registry. The retired columns and tables are unset and removed in
separate batches, repair before REMOVE.

What stays, with its reason corrected rather than removed: cap.rs,
field_update.rs, the refcounts, the CAS retry loops and the in-process
locks. Those close write skew between concurrent requests inside one
process, which two replicas made worse but never caused.

A turn orphaned by a restart or a panic is no longer reclaimed. It
settles as timed_out within CHATBOT_PENDING_STALE_SECS.

The design survives in the ledger if a second process is ever wanted.

49 changed files +500 -2094

README.mdmodified+71 -62
@@ -408,14 +408,14 @@ student's budget on another's. `0` disables it like the other two. It is
408 charged before anything is written, so a `429` leaves no trace (see408 charged before anything is written, so a `429` leaves no trace (see
409 "Chatbot").409 "Chatbot").
410 410
411-All three tiers are **fleet-wide, not per replica**. Admission stays in memory411+All three tiers admit from memory β€” no request ever waits on the database to be
412-(no request ever waits on the database to be let in), and a background task in412+let in β€” but the window **outlives the process**. A background task folds each
413-each replica folds its new admits into one shared `rate_limit` row per tier +413+tier's new admits into one shared `rate_limit` row per tier + client + minute
414-client + minute every 2 seconds, then caps itself by the total that comes back.414+every 2 seconds, then caps the in-memory bucket by the total that comes back,
415-Two replicas therefore enforce one budget, with one caveat: within a single415+so a restart mid-minute does not hand every client a fresh budget. One caveat:
416-2-second interval a client that reaches both can spend up to the tier's budget416+a just-started process can spend up to the tier's budget in the 2 seconds
417-on each before the shared total tightens them. If the database is down the417+before its first fold tightens it. If the database is down the tiers simply
418-tiers simply fall back to their own local budgets β€” nobody is refused for it.418+fall back to their own local budgets β€” nobody is refused for it.
419 419
420 Behind a reverse proxy every connection carries the proxy's address, so also420 Behind a reverse proxy every connection carries the proxy's address, so also
421 set `TRUST_PROXY=true` to key clients by the rightmost `X-Forwarded-For` entry421 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
1006 are **live** and hold the slot; rejecting or cancelling frees it for someone1006 are **live** and hold the slot; rejecting or cancelling frees it for someone
1007 else immediately (the slot carries an `occupied` counter, taken by a booking1007 else immediately (the slot carries an `occupied` counter, taken by a booking
1008 and handed back in the same transaction as the reject or cancel that settles1008 and handed back in the same transaction as the reject or cancel that settles
1009-it, so the guard holds across replicas). The1009+it, so the seat is decided by the database rather than by a count two
1010-decisions:1010+concurrent bookings can both read as free). The decisions:
1011 1011
1012 - `PATCH /{id}/approve` β€” the slot's teacher (or manager+) confirms. Refused1012 - `PATCH /{id}/approve` β€” the slot's teacher (or manager+) confirms. Refused
1013 (`409`) when the effective window has already started.1013 (`409`) when the effective window has already started.
@@ -1547,14 +1547,14 @@ account.
1547 room back and the charge **can be paid again** β€” and reversing that refund1547 room back and the charge **can be paid again** β€” and reversing that refund
1548 takes the room back with it. Money that came back out is not money the school1548 takes the room back with it. Money that came back out is not money the school
1549 still holds.1549 still holds.
1550-- **The over-payment cap is advisory.** The `409` past a charge's or a credit's1550+- **The over-payment cap is not the database's.** The `409` past a charge's or
1551- worth is a cross-record fold taken under a process-local lock, and with two1551+ a credit's worth is a cross-record fold, which SurrealDB cannot enforce on
1552- replicas serving, two payments recorded in the same instant can together1552+ its own; it holds because the backend is one process and the fold, and the
1553- overshoot. That is accepted deliberately: this is human data entry at an1553+ append it authorizes, are taken under one lock. Should an over-payment ever
1554- office desk, not a concurrent machine load, the outcome is an over-paid1554+ be recorded anyway it is not a crisis: this is human data entry at an office
1555- charge that is plainly visible in the statement, and it is undone by1555+ desk, the outcome is an over-paid charge that is plainly visible in the
1556- appending a refund. Both lines are true records of money that really1556+ statement, and it is undone by appending a refund. Both lines are true
1557- arrived β€” refusing them would be the worse lie.1557+ records of money that really arrived β€” refusing them would be the worse lie.
1558 - **There is no payment gateway and no card data, ever**, and none is planned:1558 - **There is no payment gateway and no card data, ever**, and none is planned:
1559 nothing here talks to a bank, a PSP, or a card network. `method` is free text1559 nothing here talks to a bank, a PSP, or a card network. `method` is free text
1560 ("cash", "havale", …) describing how money that already arrived was handed1560 ("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.
2376 | `404` | no such thread or message β€” or not the caller's |2376 | `404` | no such thread or message β€” or not the caller's |
2377 | `409` | already at `max_chatbot_threads`; delete a thread first |2377 | `409` | already at `max_chatbot_threads`; delete a thread first |
2378 | `429` | over `RATE_LIMIT_CHATBOT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` |2378 | `429` | over `RATE_LIMIT_CHATBOT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` |
2379-| `503` | no service anywhere in the deployment offers `chat.reply` β€” **nothing was written**, retry later |2379+| `503` | no connected service offers `chat.reply` β€” **nothing was written**, retry later |
2380 2380
2381 The `503` ordering matters: availability is checked before the rows exist, so2381 The `503` ordering matters: availability is checked before the rows exist, so
2382 an unavailable service leaves no dead `pending` row behind, and the rate limit2382 an unavailable service leaves no dead `pending` row behind, and the rate limit
2383-is charged before that, so a refused turn leaves no trace at all. The check2383+is charged before that, so a refused turn leaves no trace at all. The check is
2384-asks two questions β€” is a `chat.reply` worker connected to *this* backend2384+the backend's own worker registry, which owns the QUIC sockets and is therefore
2385-process, and failing that, is one connected to any other β€” so a deployment2385+the whole truth about what can be answered.
2386-running several backends accepts a turn as long as one of them can answer it.
2387-
2388-### A turn is a claimed job
2389-
2390-The `pending` assistant row *is* the work item. Backend processes poll it: a
2391-process holding a `chat.reply` worker claims an unanswered turn, dispatches it
2392-over its own connection, and stamps the result. That is why a `202` is a real
2393-promise β€” a backend restart no longer strands the turn it had just accepted,
2394-and a turn accepted by a process with no worker of its own is answered by one
2395-that has. The cost is up to ~200 ms before the request leaves for the service.
2396-A claim whose owner disappears is taken back after 90 seconds.
2397 2386
2398 ### A turn always settles2387 ### A turn always settles
2399 2388
2400 Once the two rows exist the answer never stays `pending` forever, through2389 Once the two rows exist the answer never stays `pending` forever, through
2401 three independent mechanisms:2390 three independent mechanisms:
2402 2391
2403-- the process that claimed the turn stamps `complete` or `failed` β€” the normal2392+- the task that owns the bridge round trip stamps `complete` or `failed` β€”
2404- path, and a claim its owner never finishes is retried by another;2393+ the normal path;
2405 - a reader **projects** a `pending` row older than 300 seconds as2394 - a reader **projects** a `pending` row older than 300 seconds as
2406 `failed`/`timed_out` (a read-time projection, not a write β€” the row is left2395 `failed`/`timed_out` (a read-time projection, not a write β€” the row is left
2407 for the task that may still own it);2396 for the task that may still own it);
2408 - a **boot sweep** flips every leftover `pending` past the 300-second horizon2397 - a **boot sweep** flips every leftover `pending` past the 300-second horizon
2409 to `failed`/`interrupted`, which is what a process death mid-inference looks2398 to `failed`/`interrupted`, which is what a process death mid-inference looks
2410- like. It leaves rows another process has claimed recently alone, so a2399+ like. Younger rows are left alone, since one may still be in flight.
2411- restarting backend cannot shoot down a turn its peer is answering.2400+
2401+A restart therefore loses a turn that was in flight: it settles
2402+`failed`/`interrupted` rather than being answered. Accepted β€” the backend is a
2403+single process with stop-the-world deploys, so there is no peer that could have
2404+taken it over.
2412 2405
2413 Two more verdicts come from inspecting the answer: an **empty** reply is2406 Two more verdicts come from inspecting the answer: an **empty** reply is
2414 reported as `failed`/`empty_reply` (a blank bubble is indistinguishable from a2407 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.
2460 2453
2461 ## Concurrency model2454 ## Concurrency model
2462 2455
2463-The backend runs as more than one replica against one database, so every2456+The backend runs as **one process against one database**, and that buys less
2464-invariant is guarded where all replicas can see it. Three tiers:2457+than it sounds like: every request is an async task, dozens are in flight at
2458+once, and each of them awaits the database in the middle of its work. So
2459+"read, decide, write" is never safe on its own β€” SurrealDB does not
2460+conflict-check a cross-record `count()` against a concurrent insert
2461+(write-skew), and that fires between two tasks in one process exactly as it
2462+would between two machines. The mutex-only design this replaced was already
2463+losing races at one process. Every invariant is therefore guarded where the
2464+database itself decides the winner. Three tiers:
2465 2465
2466 1. **Single-row conditional writes** β€” compare-and-set (`save_if_unchanged`),2466 1. **Single-row conditional writes** β€” compare-and-set (`save_if_unchanged`),
2467- `UPDATE … WHERE`, stored counters (`domain::cap`), leases. These hold2467+ `UPDATE … WHERE`, stored counters (`domain::cap`). A single-record write is
2468- *across replicas*: the database decides the winner, the loser retries or2468+ atomic, so of N concurrent tasks exactly the allowed number get a non-empty
2469- gets a 409.2469+ result: the database decides the winner, the loser retries
2470+ (`CAS_UPDATE_RETRIES`) or gets a 409.
2470 2. **In-transaction `IF … THROW` gates** β€” the check runs inside the same2471 2. **In-transaction `IF … THROW` gates** β€” the check runs inside the same
2471 statement as the write it authorizes, so it is atomic with it. Used where2472 statement as the write it authorizes, so it is atomic with it. Used where
2472 the rule reads the row being written (state machines, delete guards).2473 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:
2480 are claimed in one transaction (`cap::claim_and_create`), so a duplicate2481 are claimed in one transaction (`cap::claim_and_create`), so a duplicate
2481 `CREATE` rolls its own seat back instead of costing a stranger their place.2482 `CREATE` rolls its own seat back instead of costing a stranger their place.
2482 3. **Two accepted races**, reviewed and deliberately left open:2483 3. **Two accepted races**, reviewed and deliberately left open:
2483- - *Attempt-seq late save* β€” a save racing a retake can stamp an answer onto2484+ - *Attempt-seq late save* β€” an exam-room socket writes into the sitting it
2484- the just-terminal previous sitting. Damage: one history row; the grade of2485+ joined with, a choice made before any lock is taken, so a save racing a
2485- record (latest `seq`) is never touched.2486+ retake can stamp an answer onto the just-terminal previous sitting.
2486- - *Approved-overlap* β€” two replicas approving in the same instant can2487+ Damage: one history row; the grade of record (latest `seq`) is never
2488+ touched.
2489+ - *Approved-overlap* β€” two approvals landing in the same instant can
2487 double-book a teacher. Damage: one overlapping half-hour, visible to both2490 double-book a teacher. Damage: one overlapping half-hour, visible to both
2488 parties, fixable by cancelling either side.2491 parties, fixable by cancelling either side.
2489 2492
2490-In-process locks that remain do so for reasons a database write cannot serve:2493+In-process locks remain, and they are a *second* line, never the guarantee:
2491-`PRESENCE_LOCK` guards in-process socket state, `CLAIM_LOCK` keeps one2494+`PRESENCE_LOCK` guards in-process socket state (there is no row to conditional
2492-counter writer per process (the `WHERE` clause is the cap β€” the lock only2495+-write), `CLAIM_LOCK` keeps one counter writer at a time (the `WHERE` clause is
2493-tames the retry loop, and keeps the tests' in-memory engine deterministic),2496+the cap β€” the lock only tames the retry loop, and keeps the tests' in-memory
2494-`APPOINTMENT_LOCK` still collapses the common within-replica overlap case.2497+engine deterministic), `APPOINTMENT_LOCK` collapses the common overlap case in
2495-2498+front of a rule no single-record write can express. Removing one of them costs
2496-Deployment contract: a release that adds or renames a stored counter must2499+throughput or an accepted race; removing the conditional write behind it costs
2497-restart *all* replicas together (`podman compose down` + `up`), never rolling.2500+the invariant.
2498-An old binary writes rows without touching the new counters, the `= NONE`2501+
2499-backfill guard (correctly) refuses to re-seed, and the resulting permanent2502+Boot is unconditional: the schema batches, the backfills and the admin seed all
2500-under-count lets a guard approve exactly what it exists to refuse.2503+run on every start, because exactly one process ever starts. Deployment is
2504+stop-the-world β€” `podman compose down` then `up`, never overlapping β€” and a
2505+release that adds or renames a stored counter *requires* it. An old binary
2506+writes rows without touching the new counter, the `= NONE` backfill guard
2507+(correctly) refuses to re-seed, and the resulting permanent under-count lets a
2508+guard approve exactly what it exists to refuse. In-flight work does not survive
2509+a restart either: a chatbot turn mid-inference settles `failed`/`interrupted`.
2501 2510
2502 ## Layout2511 ## Layout
2503 2512
@@ -2532,10 +2541,10 @@ src/
2532 Generator, so same-millisecond rows never scramble2541 Generator, so same-millisecond rows never scramble
2533 key.rs sitting(): the deterministic per-sitting record key shared by2542 key.rs sitting(): the deterministic per-sitting record key shared by
2534 attempts, answers, answer images and results (seq 1 stays bare)2543 attempts, answers, answer images and results (seq 1 stays bare)
2535- cap.rs claim()/release(): the cross-replica count caps β€” an atomic2544+ cap.rs claim()/release(): the count caps the database enforces β€” an
2536- `UPDATE parent SET n += 1 WHERE n < cap` on a counter column2545+ atomic `UPDATE parent SET n += 1 WHERE n < cap` on a counter
2537- of the parent row, replacing the per-process mutexes that2546+ column of the parent row, replacing count-then-write mutexes
2538- only held while one instance owned the database;2547+ that could not see a concurrent insert;
2539 claim_and_create() commits that seat and the child row in2548 claim_and_create() commits that seat and the child row in
2540 one transaction, for children with a deterministic id2549 one transaction, for children with a deterministic id
2541 text_fold.rs case- and diacritic-insensitive folding for search, shared by2550 text_fold.rs case- and diacritic-insensitive folding for search, shared by
@@ -2647,7 +2656,7 @@ src/
2647 2656
2648 Tests: `cargo test` β€” unit (in-source), integration (`tower::oneshot` + in-memory2657 Tests: `cargo test` β€” unit (in-source), integration (`tower::oneshot` + in-memory
2649 db), rate-limit (both tiers, proxy-header and peer-address keying, shipped2658 db), rate-limit (both tiers, proxy-header and peer-address keying, shipped
2650-limits over every route, two "replicas" sharing one budget over one db), e2e2659+limits over every route, two limiters sharing one budget over one db), e2e
2651 (real TCP + reqwest cookie jar), persistence2660 (real TCP + reqwest cookie jar), persistence
2652 (tempfile file engine, including close + reopen), ai-bridge (real QUIC on2661 (tempfile file engine, including close + reopen), ai-bridge (real QUIC on
2653 loopback against a fake AI service), ai-protocol (the `hab/1` wire contract,2662 loopback against a fake AI service), ai-protocol (the `hab/1` wire contract,
src/ai/mod.rsmodified+0 -2
@@ -15,7 +15,6 @@
15 //! * [`chat`] β€” the JSON payloads carried for the `chat.reply` capability15 //! * [`chat`] β€” the JSON payloads carried for the `chat.reply` capability
16 //! * [`server`] β€” the listener, handshake, and [`server::AiBridge::dispatch`]16 //! * [`server`] β€” the listener, handshake, and [`server::AiBridge::dispatch`]
17 //! * [`registry`] β€” who is connected here, and who gets the next request17 //! * [`registry`] β€” who is connected here, and who gets the next request
18-//! * [`presence`] β€” who is connected *anywhere*, for a cross-replica gate
19 //! * [`tls`] β€” the listener's certificate18 //! * [`tls`] β€” the listener's certificate
20 //!19 //!
21 //! The transport is generic; the features land on top of it. So far that is20 //! The transport is generic; the features land on top of it. So far that is
@@ -23,7 +22,6 @@
23 22
24 pub mod chat;23 pub mod chat;
25 pub mod error;24 pub mod error;
26-pub mod presence;
27 pub mod protocol;25 pub mod protocol;
28 pub mod registry;26 pub mod registry;
29 pub mod server;27 pub mod server;
src/ai/presence.rsdeleted+0 -188
@@ -1,188 +0,0 @@
1-//! Who can serve which AI capability *anywhere in the deployment* β€” the GATE.
2-//!
3-//! There are two answers to "is an AI service available", and confusing them
4-//! is the one way this module can do damage, so they are named:
5-//!
6-//! * **The gate β€” this module, the `ai_worker` table.** It answers "could
7-//! anything, anywhere, serve `chat.reply`?". Every replica writes a row for
8-//! each worker whose QUIC connection *it* holds and restamps it every
9-//! [`AI_WORKER_HEARTBEAT_SECS`]; a row unstamped for
10-//! [`AI_WORKER_LEASE_SECS`] is ignored and swept, so a replica that dies
11-//! leaves no permanent phantom. It is a cache of other processes' sockets:
12-//! it lags a registration by up to one heartbeat and a crash by up to one
13-//! lease, in *both* directions. Its only job is to spare a user a 503 on a
14-//! replica that holds no worker itself, because a peer's claim loop will
15-//! answer the turn. It must never guard a write and must never decide a
16-//! dispatch.
17-//! * **The dispatcher β€” [`crate::ai::registry::Registry`], in process.** It
18-//! owns the sockets. Only it knows whether *this* replica can answer, and it
19-//! is the only thing the chat claim loop consults before taking a turn. A
20-//! claim made on the gate's word would park a turn on a replica with nothing
21-//! to send it to.
22-//!
23-//! The split is why the table is safe to be wrong: nothing downstream of a
24-//! wrong answer is irreversible. A false yes costs one accepted turn that
25-//! settles `failed` (or waits out its staleness window); a false no costs one
26-//! 503 the user can retry.
27-
28-use surrealdb::types::RecordId;
29-
30-use crate::ai::registry::WorkerSnapshot;
31-use crate::constant::{
32- AI_WORKER_ANNOUNCE, AI_WORKER_LEASE_SECS, AI_WORKER_SERVES, AI_WORKER_SWEEP, AI_WORKER_TABLE,
33- AI_WORKER_WITHDRAW,
34-};
35-use crate::database::Database;
36-use crate::error::AppError;
37-
38-fn row(id: &str) -> RecordId {
39- RecordId::new(AI_WORKER_TABLE, id)
40-}
41-
42-/// Publish (or restamp) the workers this replica holds right now.
43-///
44-/// `UPSERT` per worker, and the caller passes the whole live set every
45-/// heartbeat: a row lost to a database blip, or a worker that registered
46-/// before the presence table was attached, heals on the next beat instead of
47-/// staying invisible to every peer forever.
48-pub async fn announce(db: &Database, workers: &[WorkerSnapshot]) -> Result<(), AppError> {
49- for worker in workers {
50- db.query(AI_WORKER_ANNOUNCE)
51- .bind(("id", row(&worker.id)))
52- .bind(("service", worker.service.clone()))
53- .bind(("capabilities", worker.capabilities.clone()))
54- .await?
55- .check()?;
56- }
57- Ok(())
58-}
59-
60-/// Drop a worker that said goodbye. Immediate, so a clean disconnect closes
61-/// the gate now rather than a lease later.
62-pub async fn withdraw(db: &Database, id: &str) -> Result<(), AppError> {
63- db.query(AI_WORKER_WITHDRAW)
64- .bind(("id", row(id)))
65- .await?
66- .check()?;
67- Ok(())
68-}
69-
70-/// Forget workers nobody restamped within the lease β€” their replica died
71-/// without deregistering them. Any replica may run it: the rows are keyed by
72-/// worker, not by owner, and a live worker's row is never stale.
73-pub async fn sweep(db: &Database) -> Result<(), AppError> {
74- db.query(AI_WORKER_SWEEP)
75- .bind(("lease_ms", AI_WORKER_LEASE_SECS * 1_000))
76- .await?
77- .check()?;
78- Ok(())
79-}
80-
81-/// The gate read: does *any* replica hold a worker for `capability`?
82-///
83-/// Errors answer "no" rather than propagating. This is consulted on the 503
84-/// path of a request that has not written anything yet, so the worst a
85-/// database hiccup can do is tell one user to retry β€” turning it into a 500
86-/// would be strictly worse for the same fault.
87-pub async fn serves(db: &Database, capability: &str) -> bool {
88- let found: Result<Vec<RecordId>, AppError> = async {
89- Ok(db
90- .query(AI_WORKER_SERVES)
91- .bind(("capability", capability.to_string()))
92- .bind(("lease_ms", AI_WORKER_LEASE_SECS * 1_000))
93- .await?
94- .check()?
95- .take(0)?)
96- }
97- .await;
98- match found {
99- Ok(rows) => !rows.is_empty(),
100- Err(err) => {
101- tracing::warn!("could not read the AI worker gate: {err}");
102- false
103- }
104- }
105-}
106-
107-#[cfg(test)]
108-mod tests {
109- use super::*;
110- use crate::constant::AI_CHAT_CAPABILITY;
111-
112- fn worker(id: &str, capabilities: &[&str]) -> WorkerSnapshot {
113- WorkerSnapshot {
114- id: id.to_string(),
115- service: "tutor".to_string(),
116- capabilities: capabilities.iter().map(|c| c.to_string()).collect(),
117- inflight: 0,
118- max_concurrent: 4,
119- }
120- }
121-
122- #[tokio::test]
123- async fn a_stale_row_stops_answering_the_gate() {
124- // The phantom this exists to prevent: a replica that dies leaves its
125- // row behind, and without the age filter that row would keep every
126- // peer's chat endpoint reporting a service that is gone.
127- let db = crate::database::init_mem().await.unwrap();
128- announce(&db, &[worker("w1", &[AI_CHAT_CAPABILITY])])
129- .await
130- .unwrap();
131- assert!(serves(&db, AI_CHAT_CAPABILITY).await);
132- assert!(!serves(&db, "ocr.extract").await, "a capability nobody has");
133-
134- // Age it past the lease, as a dead replica's row ages on its own.
135- db.query("UPDATE ai_worker SET seen_at = seen_at - $ms")
136- .bind(("ms", (AI_WORKER_LEASE_SECS + 1) * 1_000))
137- .await
138- .unwrap()
139- .check()
140- .unwrap();
141- assert!(
142- !serves(&db, AI_CHAT_CAPABILITY).await,
143- "a stale row must not hold the gate open"
144- );
145- sweep(&db).await.unwrap();
146- let rows: Vec<RecordId> = db
147- .query("SELECT VALUE id FROM ai_worker")
148- .await
149- .unwrap()
150- .check()
151- .unwrap()
152- .take(0)
153- .unwrap();
154- assert!(rows.is_empty(), "the sweep deletes what the read ignores");
155- }
156-
157- #[tokio::test]
158- async fn announcing_twice_restamps_rather_than_duplicating() {
159- let db = crate::database::init_mem().await.unwrap();
160- let live = [worker("w1", &[AI_CHAT_CAPABILITY])];
161- announce(&db, &live).await.unwrap();
162- db.query("UPDATE ai_worker SET seen_at = seen_at - $ms")
163- .bind(("ms", (AI_WORKER_LEASE_SECS + 1) * 1_000))
164- .await
165- .unwrap()
166- .check()
167- .unwrap();
168- assert!(!serves(&db, AI_CHAT_CAPABILITY).await);
169-
170- announce(&db, &live).await.unwrap();
171- assert!(serves(&db, AI_CHAT_CAPABILITY).await, "the beat healed it");
172- let rows: Vec<RecordId> = db
173- .query("SELECT VALUE id FROM ai_worker")
174- .await
175- .unwrap()
176- .check()
177- .unwrap()
178- .take(0)
179- .unwrap();
180- assert_eq!(rows.len(), 1, "one worker is one row");
181-
182- withdraw(&db, "w1").await.unwrap();
183- assert!(
184- !serves(&db, AI_CHAT_CAPABILITY).await,
185- "goodbye is immediate"
186- );
187- }
188-}
src/ai/server.rsmodified+4 -97
@@ -12,14 +12,12 @@ use serde_json::Value;
12 use ulid::Ulid;12 use ulid::Ulid;
13 13
14 use crate::ai::error::AiError;14 use crate::ai::error::AiError;
15-use crate::ai::presence;
16 use crate::ai::protocol::{15 use crate::ai::protocol::{
17 Greeting, Hello, RejectCode, Request, Response, protocol_matches, read_frame, write_frame,16 Greeting, Hello, RejectCode, Request, Response, protocol_matches, read_frame, write_frame,
18 };17 };
19 use crate::ai::registry::{AiRegistry, WorkerSnapshot, clamp_concurrency};18 use crate::ai::registry::{AiRegistry, WorkerSnapshot, clamp_concurrency};
20 use crate::ai::tls;19 use crate::ai::tls;
21 use crate::constant::{AI_HANDSHAKE_TIMEOUT_SECS, AI_PROTOCOL};20 use crate::constant::{AI_HANDSHAKE_TIMEOUT_SECS, AI_PROTOCOL};
22-use crate::database::Database;
23 21
24 /// What the bridge needs to come up.22 /// What the bridge needs to come up.
25 #[derive(Clone, Debug)]23 #[derive(Clone, Debug)]
@@ -37,13 +35,6 @@ pub struct BridgeConfig {
37 35
38 struct Inner {36 struct Inner {
39 registry: AiRegistry,37 registry: AiRegistry,
40- /// The database, once [`AiBridge::attach_presence`] has handed it over β€”
41- /// used for the `ai_worker` gate and nothing else (see
42- /// [`crate::ai::presence`]). `OnceLock` because the bridge binds before the
43- /// router is built, so presence is wired *after* the listener is already
44- /// accepting: a worker may register before this is set, and the heartbeat
45- /// republishes the whole live set precisely so that one is not lost.
46- presence: std::sync::OnceLock<Database>,
47 /// The leaf certificate this listener presents, kept so it can be shown to38 /// The leaf certificate this listener presents, kept so it can be shown to
48 /// an operator (or pinned by an in-process client) without re-reading the39 /// an operator (or pinned by an in-process client) without re-reading the
49 /// PEM off disk.40 /// PEM off disk.
@@ -86,7 +77,6 @@ impl AiBridge {
86 77
87 let inner = Arc::new(Inner {78 let inner = Arc::new(Inner {
88 registry: AiRegistry::default(),79 registry: AiRegistry::default(),
89- presence: std::sync::OnceLock::new(),
90 certificate: bridge_tls.leaf.clone(),80 certificate: bridge_tls.leaf.clone(),
91 token: config.token,81 token: config.token,
92 request_timeout: config.request_timeout,82 request_timeout: config.request_timeout,
@@ -124,35 +114,15 @@ impl AiBridge {
124 self.inner.registry.snapshot()114 self.inner.registry.snapshot()
125 }115 }
126 116
127- /// Is anything connected *to this process* that can serve `capability`?117+ /// Is anything connected that can serve `capability`?
128 ///118 ///
129- /// The DISPATCHER's answer, and the authoritative one: this registry owns119+ /// This registry owns the sockets, so it is the whole truth about what the
130- /// the sockets, so only it may decide that this replica can answer a job.120+ /// backend can answer. Racy in the harmless direction β€” a worker can vanish
131- /// Racy in the harmless direction β€” a worker can vanish between the check121+ /// between the check and the dispatch β€” so it never guards a write.
132- /// and the dispatch β€” so it still never guards a write. For "can *anyone*
133- /// serve it", which is a different and weaker question, see
134- /// [`crate::ai::presence::serves`].
135 pub fn has_capability(&self, capability: &str) -> bool {122 pub fn has_capability(&self, capability: &str) -> bool {
136 self.inner.registry.has_capability(capability)123 self.inner.registry.has_capability(capability)
137 }124 }
138 125
139- /// Hand the bridge the database, so the workers it holds become visible to
140- /// other replicas through the `ai_worker` gate. Returns whether this call
141- /// was the one that wired it β€” the caller uses that to start exactly one
142- /// claim loop per process.
143- ///
144- /// Idempotent by construction: a second call is a no-op and returns
145- /// `false`. Nothing here is required for the bridge to work; a deployment
146- /// that never attaches presence simply keeps the single-process behaviour,
147- /// where the in-process registry is the whole truth.
148- pub fn attach_presence(&self, db: Database) -> bool {
149- if self.inner.presence.set(db.clone()).is_err() {
150- return false;
151- }
152- heartbeat_presence(Arc::downgrade(&self.inner), db);
153- true
154- }
155-
156 /// Send one request to a service and await its answer.126 /// Send one request to a service and await its answer.
157 ///127 ///
158 /// Each call takes a fresh QUIC bidirectional stream, so concurrent calls128 /// Each call takes a fresh QUIC bidirectional stream, so concurrent calls
@@ -235,45 +205,6 @@ impl AiBridge {
235 }205 }
236 }206 }
237 207
238-/// Republish this replica's live worker set to the `ai_worker` gate, forever.
239-///
240-/// The whole set every beat rather than deltas: it is the self-healing half of
241-/// the gate (a row lost to a database blip, or a worker registered before
242-/// presence was attached, comes back on the next tick), and the set is a
243-/// handful of rows. The sweep rides along so a replica that died without
244-/// deregistering stops holding anyone's gate open.
245-///
246-/// Holds a `Weak` on the bridge so that *this* task is not itself a reason to
247-/// keep a listener alive. It is not a shutdown mechanism, and in the wired-up
248-/// process it never fires: `chatbot::spawn_claim_loop` owns an `AiBridge` by
249-/// value for the life of the process, so the strong count never reaches zero
250-/// and both tasks run until exit. That is intended for a server β€” the bridge
251-/// is not restartable β€” and is only visible in tests, which build many
252-/// bridges. Correct that (a `CancellationToken` on both loops) the day a
253-/// bridge needs to be torn down while the process lives.
254-fn heartbeat_presence(inner: std::sync::Weak<Inner>, db: Database) {
255- tokio::spawn(async move {
256- let mut ticker = tokio::time::interval(Duration::from_secs(
257- crate::constant::AI_WORKER_HEARTBEAT_SECS,
258- ));
259- ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
260- loop {
261- // The first tick is immediate, so workers registered before the
262- // database arrived are published now and not one beat late.
263- ticker.tick().await;
264- let Some(inner) = inner.upgrade() else { return };
265- let workers = inner.registry.snapshot();
266- drop(inner);
267- if let Err(err) = presence::announce(&db, &workers).await {
268- tracing::warn!("could not publish the AI worker gate: {err}");
269- }
270- if let Err(err) = presence::sweep(&db).await {
271- tracing::warn!("could not sweep the AI worker gate: {err}");
272- }
273- }
274- });
275-}
276-
277 /// Accept connections until the endpoint closes. One task per service.208 /// Accept connections until the endpoint closes. One task per service.
278 async fn accept_loop(inner: Arc<Inner>) {209 async fn accept_loop(inner: Arc<Inner>) {
279 while let Some(incoming) = inner.endpoint.accept().await {210 while let Some(incoming) = inner.endpoint.accept().await {
@@ -314,13 +245,6 @@ async fn serve_connection(inner: Arc<Inner>, conn: quinn::Connection, remote: So
314 // dies without saying anything.245 // dies without saying anything.
315 let reason = conn.closed().await;246 let reason = conn.closed().await;
316 inner.registry.remove(&worker_id);247 inner.registry.remove(&worker_id);
317- // The gate closes with the registry, not a lease later β€” but only after
318- // the registry, which is the authoritative one (see `presence`).
319- if let Some(db) = inner.presence.get()
320- && let Err(err) = presence::withdraw(db, &worker_id).await
321- {
322- tracing::warn!("could not withdraw AI worker {worker_id} from the gate: {err}");
323- }
324 tracing::info!("AI service `{service}` ({worker_id}) at {remote} disconnected: {reason}");248 tracing::info!("AI service `{service}` ({worker_id}) at {remote} disconnected: {reason}");
325 }249 }
326 250
@@ -409,23 +333,6 @@ async fn register(
409 max_concurrent,333 max_concurrent,
410 conn.clone(),334 conn.clone(),
411 );335 );
412- // …and only then published to the gate, so `ai_worker` can never advertise
413- // a worker the local dispatcher would refuse to pick.
414- if let Some(db) = inner.presence.get() {
415- let announced = WorkerSnapshot {
416- id: worker_id.clone(),
417- service: hello.service.clone(),
418- capabilities: hello.capabilities.clone(),
419- inflight: 0,
420- max_concurrent,
421- };
422- if let Err(err) = presence::announce(db, &[announced]).await {
423- // Not fatal, and not a reason to refuse the service: the worker is
424- // already usable by this replica, and the next heartbeat
425- // republishes the whole live set.
426- tracing::warn!("could not publish AI worker {worker_id} to the gate: {err}");
427- }
428- }
429 tracing::info!(336 tracing::info!(
430 "AI service `{}` ({worker_id}) at {remote} registered: {:?}, max_concurrent {max_concurrent}",337 "AI service `{}` ({worker_id}) at {remote} registered: {:?}, max_concurrent {max_concurrent}",
431 hello.service,338 hello.service,
src/config.rsmodified+17 -20
@@ -110,13 +110,11 @@ fn parse_limit(value: Option<String>, default: u32) -> u32 {
110 /// never what an operator means β€” so it falls back with the rest of the110 /// never what an operator means β€” so it falls back with the rest of the
111 /// garbage.111 /// garbage.
112 ///112 ///
113-/// The ceiling is the load-bearing part, and it is enforced here because here113+/// The ceiling is enforced here because here is the only place the number
114-/// is the only place the number enters the process. A deadline above114+/// enters the process. A deadline above [`AI_MAX_REQUEST_TIMEOUT_SECS`] keeps
115-/// [`AI_MAX_REQUEST_TIMEOUT_SECS`] lets one dispatch outlive115+/// a task and a worker slot busy past the point where the answer could still
116-/// `CHATBOT_CLAIM_RECLAIM_SECS`, and the chat claim queue then hands the same116+/// be shown to anyone (see that constant), so it is clamped rather than
117-/// turn to a second worker while the first is still answering it β€” two117+/// honoured.
118-/// inferences for one reply. Clamping at the boundary is what makes that
119-/// unreachable *by configuration*, instead of true only for the default.
120 fn parse_timeout(value: Option<String>, default: u64) -> u64 {118 fn parse_timeout(value: Option<String>, default: u64) -> u64 {
121 let asked = value119 let asked = value
122 .and_then(|v| v.trim().parse().ok())120 .and_then(|v| v.trim().parse().ok())
@@ -127,8 +125,8 @@ fn parse_timeout(value: Option<String>, default: u64) -> u64 {
127 // reason (a queue horizon) is not one they could guess from the name.125 // reason (a queue horizon) is not one they could guess from the name.
128 tracing::warn!(126 tracing::warn!(
129 "AI_REQUEST_TIMEOUT_SECS={asked} is above the {AI_MAX_REQUEST_TIMEOUT_SECS}s ceiling \127 "AI_REQUEST_TIMEOUT_SECS={asked} is above the {AI_MAX_REQUEST_TIMEOUT_SECS}s ceiling \
130- the chat claim queue allows (a longer inference would be reclaimed and re-dispatched \128+ (a reply that late is discarded as stale before anyone sees it) β€” using \
131- mid-flight) β€” using {AI_MAX_REQUEST_TIMEOUT_SECS}s"129+ {AI_MAX_REQUEST_TIMEOUT_SECS}s"
132 );130 );
133 return AI_MAX_REQUEST_TIMEOUT_SECS;131 return AI_MAX_REQUEST_TIMEOUT_SECS;
134 }132 }
@@ -155,7 +153,7 @@ fn parse_flag(value: Option<String>) -> bool {
155 mod tests {153 mod tests {
156 use super::{parse_flag, parse_limit, parse_port, parse_timeout};154 use super::{parse_flag, parse_limit, parse_port, parse_timeout};
157 use crate::constant::{155 use crate::constant::{
158- AI_DEFAULT_REQUEST_TIMEOUT_SECS, AI_MAX_REQUEST_TIMEOUT_SECS, CHATBOT_CLAIM_RECLAIM_SECS,156+ AI_DEFAULT_REQUEST_TIMEOUT_SECS, AI_MAX_REQUEST_TIMEOUT_SECS, CHATBOT_PENDING_STALE_SECS,
159 };157 };
160 158
161 #[tokio::test]159 #[tokio::test]
@@ -169,19 +167,18 @@ mod tests {
169 }167 }
170 168
171 #[tokio::test]169 #[tokio::test]
172- async fn a_configured_timeout_can_never_outlive_the_chat_claim_horizon() {170+ async fn a_configured_timeout_is_clamped_below_the_stale_horizon() {
173- // The one double-dispatch an operator could still reach: nothing used171+ // Nothing used to stop `AI_REQUEST_TIMEOUT_SECS=600`, and a dispatch
174- // to stop `AI_REQUEST_TIMEOUT_SECS=120`, and a dispatch outliving172+ // that outlives `CHATBOT_PENDING_STALE_SECS` holds a worker slot for an
175- // `CHATBOT_CLAIM_RECLAIM_SECS` has its turn reclaimed and re-sent while173+ // answer every reader has already been shown as failed. The
176- // the first inference is still running β€” the model answers one turn174+ // relationship, not a literal, is what is asserted: raising the ceiling
177- // twice. The relationship, not a literal, is what is asserted: raising175+ // past the staleness window cannot pass this.
178- // one of the two numbers without the other cannot pass this.176+ for asked in ["61", "120", "600", "18446744073709551615"] {
179- for asked in ["91", "120", "600", "18446744073709551615"] {
180 let got = parse_timeout(Some(asked.into()), AI_DEFAULT_REQUEST_TIMEOUT_SECS);177 let got = parse_timeout(Some(asked.into()), AI_DEFAULT_REQUEST_TIMEOUT_SECS);
181 assert!(178 assert!(
182- (got as i64) < CHATBOT_CLAIM_RECLAIM_SECS,179+ (got as i64) < CHATBOT_PENDING_STALE_SECS,
183 "AI_REQUEST_TIMEOUT_SECS={asked} was honoured as {got}s, at or past the \180 "AI_REQUEST_TIMEOUT_SECS={asked} was honoured as {got}s, at or past the \
184- {CHATBOT_CLAIM_RECLAIM_SECS}s reclaim horizon"181+ {CHATBOT_PENDING_STALE_SECS}s staleness horizon"
185 );182 );
186 assert_eq!(got, AI_MAX_REQUEST_TIMEOUT_SECS, "clamped to the ceiling");183 assert_eq!(got, AI_MAX_REQUEST_TIMEOUT_SECS, "clamped to the ceiling");
187 }184 }
src/constant.rsmodified+19 -224
@@ -402,56 +402,6 @@ pub const AI_KEEPALIVE_SECS: u64 = 10;
402 /// chat endpoints report the service as unavailable.402 /// chat endpoints report the service as unavailable.
403 pub const AI_CHAT_CAPABILITY: &str = "chat.reply";403 pub const AI_CHAT_CAPABILITY: &str = "chat.reply";
404 404
405-// --- AI worker presence: the GATE, never the dispatcher -----------------
406-//
407-// Read `crate::ai::presence` before touching anything below. In one line: the
408-// `ai_worker` table answers "could *anything, anywhere* serve this
409-// capability?" so a POST on a replica holding no worker can still be accepted
410-// (a peer's claim loop will answer it). It is a heartbeated cache of other
411-// processes' sockets and it is allowed to be wrong in both directions. The
412-// in-process `ai::registry::Registry` is the dispatcher and the only thing
413-// that may decide who actually answers.
414-
415-/// The heartbeated presence table. One row per connected worker, written by
416-/// whichever replica owns that worker's QUIC connection.
417-pub const AI_WORKER_TABLE: &str = "ai_worker";
418-
419-/// How often a replica restamps `seen_at` for the workers it holds, and how
420-/// long a row is believed without a restamp. The lease is a comfortable
421-/// multiple of the beat (three), so a single missed heartbeat never hides a
422-/// live worker, and it matches [`AI_IDLE_TIMEOUT_SECS`] β€” the window in which
423-/// the transport itself notices a dead service β€” so a replica that dies
424-/// outright leaves a phantom for no longer than a service that dies outright.
425-pub const AI_WORKER_HEARTBEAT_SECS: u64 = 10;
426-pub const AI_WORKER_LEASE_SECS: i64 = 30;
427-
428-/// Write (or restamp) one worker's row. `UPSERT` rather than `CREATE`: the
429-/// heartbeat replays the whole live set every beat, which is what heals a row
430-/// lost to a database blip or written before the presence table was attached.
431-pub const AI_WORKER_ANNOUNCE: &str = "
432- UPSERT $id CONTENT { service: $service, capabilities: $capabilities,
433- seen_at: time::unix(time::now()) * 1000 };
434-";
435-
436-/// Drop a worker whose connection closed. Immediate β€” the gate should not
437-/// hold a door open for a service that has already said goodbye.
438-pub const AI_WORKER_WITHDRAW: &str = "DELETE $id;";
439-
440-/// Forget workers nobody has restamped within the lease: the replica holding
441-/// them died without deregistering. Any replica's heartbeat may run it β€” the
442-/// rows are keyed by worker, not by owner.
443-pub const AI_WORKER_SWEEP: &str = "
444- DELETE ai_worker WHERE seen_at < time::unix(time::now()) * 1000 - $lease_ms;
445-";
446-
447-/// The gate read. Age-filtered in the query, not by the sweep, so a phantom
448-/// row is inert the moment it is stale rather than when someone gets round to
449-/// deleting it.
450-pub const AI_WORKER_SERVES: &str = "
451- SELECT VALUE id FROM ai_worker WHERE $capability IN capabilities
452- AND seen_at >= time::unix(time::now()) * 1000 - $lease_ms LIMIT 1;
453-";
454-
455 /// Hard ceiling on one chat message's characters β€” the newtype bound, above405 /// Hard ceiling on one chat message's characters β€” the newtype bound, above
456 /// which no school setting can reach. Sized for a pasted question with its406 /// which no school setting can reach. Sized for a pasted question with its
457 /// working, well under [`AI_MAX_FRAME_BYTES`] once history rides along.407 /// working, well under [`AI_MAX_FRAME_BYTES`] once history rides along.
@@ -497,92 +447,17 @@ pub const CHAT_STREAM_POLL_MS: u64 = 200;
497 /// this only catches the row whose task died with the process.447 /// this only catches the row whose task died with the process.
498 pub const CHATBOT_PENDING_STALE_SECS: i64 = 300;448 pub const CHATBOT_PENDING_STALE_SECS: i64 = 300;
499 449
500-// --- the chat claim queue ----------------------------------------------
501-
502-/// How often a replica looks for an unanswered turn, and how many it takes in
503-/// one sweep. The poll is what replaces the in-process `tokio::spawn` a POST
504-/// used to do, so it is the answer's added latency floor β€” matched to
505-/// [`CHAT_STREAM_POLL_MS`], the cadence the client already waits at, so a turn
506-/// is never claimed slower than its own reader refreshes. The batch is small
507-/// on purpose: a claim is a promise to dispatch now, and dispatching more at
508-/// once than a worker's `max_concurrent` would only turn the surplus into
509-/// `busy` failures.
510-pub const CHATBOT_CLAIM_POLL_MS: u64 = 200;
511-pub const CHATBOT_CLAIM_BATCH: i64 = 4;
512-
513-/// How long a claim is believed before another replica may take the turn back.
514-///
515-/// Sized between the two horizons it sits between, and both bounds bite (see
516-/// `the_claim_horizon_sits_between_the_inference_and_the_stale_window`):
517-///
518-/// * **Above the AI request timeout** ([`AI_DEFAULT_REQUEST_TIMEOUT_SECS`],
519-/// 30s), with room to spare, because a reclaim that fires while the first
520-/// claimer is still waiting on a legitimate inference makes two services
521-/// answer the same turn β€” twice the cost for one reply (the second is then
522-/// discarded by the `status = 'pending'` gate on the settle, so it is waste,
523-/// not corruption). Three times the default leaves margin for the settle
524-/// write and for a moderately raised `AI_REQUEST_TIMEOUT_SECS`.
525-/// * **Below [`CHATBOT_PENDING_STALE_SECS`]** (300s), because a turn is only
526-/// claimable inside that window; a reclaim horizon at or above it would
527-/// never fire before the turn stopped being worth answering, making the
528-/// dead-claimer retry dead code. At 90s a turn survives two lost claimers
529-/// and still gets answered.
530-pub const CHATBOT_CLAIM_RECLAIM_SECS: i64 = 90;
531-
532 /// The largest per-request AI deadline a deployment may configure450 /// The largest per-request AI deadline a deployment may configure
533 /// (`AI_REQUEST_TIMEOUT_SECS`). Anything above it is clamped down to it at451 /// (`AI_REQUEST_TIMEOUT_SECS`). Anything above it is clamped down to it at
534 /// startup, loudly β€” see [`crate::config`].452 /// startup, loudly β€” see [`crate::config`].
535 ///453 ///
536-/// Not a taste limit; it is the claim queue's arithmetic, and the bound the454+/// A sanity ceiling, well under [`CHATBOT_PENDING_STALE_SECS`]: a reply that
537-/// doc above only *asserted* before. A dispatch allowed to outlive455+/// arrives after the staleness window is discarded by the read-time
538-/// [`CHATBOT_CLAIM_RECLAIM_SECS`] has its turn reclaimed and re-sent while the456+/// projection, so a deadline anywhere near it could never produce an answer a
539-/// first inference is still legitimately running, so the model runs twice for457+/// user sees β€” it would only hold a task and a worker slot open for nothing.
540-/// one reply. (The settle's `status = 'pending'` gate still admits only one458+/// A school that genuinely needs longer raises this and the staleness window
541-/// answer, so it is waste rather than corruption β€” but a worker with side459+/// together.
542-/// effects makes it worse than waste.) Nothing but the parser stood between an460+pub const AI_MAX_REQUEST_TIMEOUT_SECS: u64 = 60;
543-/// operator and that: `AI_REQUEST_TIMEOUT_SECS=120` used to be honoured
544-/// verbatim.
545-///
546-/// Clamped rather than refused, because a slow model is a legitimate thing to
547-/// own and a boot that dies over it helps nobody β€” and because the ceiling is
548-/// real either way: a reply that arrives after
549-/// [`CHATBOT_PENDING_STALE_SECS`] is discarded by the read-time projection, so
550-/// no deadline near it was ever going to produce an answer a user sees. A
551-/// school that genuinely needs longer raises the horizon and the staleness
552-/// window together, and the ordering tests police the result.
553-///
554-/// Two thirds of the horizon, derived and never hand-kept: raising the horizon
555-/// raises this with it, so the two numbers cannot drift apart. The remaining
556-/// third is the room the reply needs to arrive, be capped and be stamped
557-/// before anyone may reclaim the turn.
558-pub const AI_MAX_REQUEST_TIMEOUT_SECS: u64 = CHATBOT_CLAIM_RECLAIM_SECS as u64 * 2 / 3;
559-
560-/// Take up to [`CHATBOT_CLAIM_BATCH`] unanswered turns for this replica.
561-///
562-/// Two statements because SurrealDB has no `LIMIT` on `UPDATE`: the first
563-/// picks candidates, the second claims them. The pick is advisory β€” a peer may
564-/// take a row in between β€” so the `UPDATE` repeats the *whole* guard, and
565-/// per-record `UPDATE ... WHERE` is atomic, so a row claimed by a rival simply
566-/// does not come back in `RETURN AFTER`. Nothing here consults `ai_worker`:
567-/// the caller has already asked its own registry whether it can answer.
568-///
569-/// The guard, term by term: only a reserved assistant row (`pending`), only
570-/// one young enough that somebody is still waiting for it (`$stale_ms` β€” past
571-/// that a reader already shows it failed, so answering it would resurrect a
572-/// turn the user was told was lost), and only one that is unclaimed *or* whose
573-/// claimer has gone quiet past `$reclaim_ms`. Both disjuncts are required: a
574-/// row whose claimer died must be retried, not left forever.
575-pub const CHATBOT_CLAIM: &str = "
576- LET $ids = (SELECT VALUE id FROM chatbot_message
577- WHERE status = 'pending' AND role = 'assistant'
578- AND created_at >= time::unix(time::now()) * 1000 - $stale_ms
579- AND (claimed_by = NONE OR claimed_at < time::unix(time::now()) * 1000 - $reclaim_ms)
580- ORDER BY created_at ASC, id ASC LIMIT $batch);
581- UPDATE $ids SET claimed_by = $me, claimed_at = time::unix(time::now()) * 1000
582- WHERE status = 'pending'
583- AND (claimed_by = NONE OR claimed_at < time::unix(time::now()) * 1000 - $reclaim_ms)
584- RETURN AFTER;
585-";
586 461
587 /// How long a dialling AI service has to complete its `Hello`/`Welcome`462 /// How long a dialling AI service has to complete its `Hello`/`Welcome`
588 /// exchange before the connection is dropped. Short: the handshake is one463 /// exchange before the connection is dropped. Short: the handshake is one
@@ -605,13 +480,13 @@ pub const DEFAULT_CHATBOT_RATE_LIMIT: u32 = 20;
605 /// swept out on the next check. Keeps memory bounded without a reaper task.480 /// swept out on the next check. Keeps memory bounded without a reaper task.
606 pub const PURGE_AT: usize = 10_000;481 pub const PURGE_AT: usize = 10_000;
607 482
608-/// The shared counter every replica folds its local admits into, so N replicas483+/// The shared counter the limiter folds its local admits into, so a window's
609-/// enforce one budget instead of N (see [`crate::rate_limit`]).484+/// budget survives a restart (see [`crate::rate_limit`]).
610 pub const RATE_LIMIT_TABLE: &str = "rate_limit";485 pub const RATE_LIMIT_TABLE: &str = "rate_limit";
611 486
612-/// How often a limiter pushes its admits and reads the fleet's total back.487+/// How often a limiter pushes its admits and reads the window's total back.
613-/// The knob that decides the worst case: within one interval a replica can488+/// The knob that decides the worst case: within one interval a just-started
614-/// admit up to its full local budget before the shared total tightens it, so489+/// process can admit up to its full local budget before the total tightens it, so
615 /// short enough to matter and long enough to stay one query per tier per tick.490 /// short enough to matter and long enough to stay one query per tier per tick.
616 pub const RATE_SYNC_INTERVAL_SECS: u64 = 2;491 pub const RATE_SYNC_INTERVAL_SECS: u64 = 2;
617 492
@@ -794,12 +669,13 @@ pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger";
794 pub const KIND_REF_TABLE: &str = "kind_ref";669 pub const KIND_REF_TABLE: &str = "kind_ref";
795 pub const SLOT_REF_TABLE: &str = "slot_ref";670 pub const SLOT_REF_TABLE: &str = "slot_ref";
796 671
797-// --- cross-replica cap counters ----------------------------------------672+// --- stored cap counters -------------------------------------------------
798 673
799 /// The counter columns behind the count caps (see [`crate::domain::cap`]).674 /// The counter columns behind the count caps (see [`crate::domain::cap`]).
800 /// Each one lives on the *parent* row, because a single-record conditional675 /// Each one lives on the *parent* row, because a single-record conditional
801-/// `UPDATE` is the only guard that holds when the writers are in different676+/// `UPDATE` is the only guard a concurrent writer cannot outrun (a lock is
802-/// processes. Spelled here rather than at the call site so the field a claim677+/// released around the round trip). Spelled here rather than at the call site
678+/// so the field a claim
803 /// increments and the field a delete decrements cannot drift apart; the679 /// increments and the field a delete decrements cannot drift apart; the
804 /// definitions themselves are in `MIGRATION`, and a typo there is caught by680 /// definitions themselves are in `MIGRATION`, and a typo there is caught by
805 /// SCHEMAFULL refusing the write.681 /// SCHEMAFULL refusing the write.
@@ -821,8 +697,8 @@ pub const SLOT_OCCUPIED_FIELD: &str = "occupied";
821 /// Not caps either, and uncapped by design: how many exam questions and how697 /// Not caps either, and uncapped by design: how many exam questions and how
822 /// many homework still point at a subject. A subject may be deleted exactly698 /// many homework still point at a subject. A subject may be deleted exactly
823 /// while both read zero, so the delete's own `WHERE` decides it β€” the699 /// while both read zero, so the delete's own `WHERE` decides it β€” the
824-/// cross-table "does anything reference this?" count it replaces served one700+/// cross-table "does anything reference this?" count it replaces was already
825-/// replica only.701+/// stale when the delete landed.
826 pub const SUBJECT_QUESTION_COUNT_FIELD: &str = "exam_question_count";702 pub const SUBJECT_QUESTION_COUNT_FIELD: &str = "exam_question_count";
827 pub const SUBJECT_HOMEWORK_COUNT_FIELD: &str = "homework_count";703 pub const SUBJECT_HOMEWORK_COUNT_FIELD: &str = "homework_count";
828 /// How many marks an exam carries. Uncapped too, and the only counter its704 /// How many marks an exam carries. Uncapped too, and the only counter its
@@ -848,7 +724,7 @@ pub const MENU_VERSION_FIELD: &str = "version";
848 /// the submission is still open. Every student-side write to a submission (its724 /// the submission is still open. Every student-side write to a submission (its
849 /// text, its files) carries `graded_by_result = NONE` as a condition, so the725 /// text, its files) carries `graded_by_result = NONE` as a condition, so the
850 /// "not graded yet" decision and the write it licenses are one conditional726 /// "not graded yet" decision and the write it licenses are one conditional
851-/// single-record write rather than a cross-table read a peer replica can727+/// single-record write rather than a cross-table read a concurrent grade can
852 /// outrun. Set by grading, cleared by un-grading, never by the student.728 /// outrun. Set by grading, cleared by un-grading, never by the student.
853 pub const SUBMISSION_GRADED_FIELD: &str = "graded_by_result";729 pub const SUBMISSION_GRADED_FIELD: &str = "graded_by_result";
854 /// The condition itself, spelled once: a submission is writable exactly while730 /// 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";
863 /// parent: seven doublings from 2ms is a quarter of a second of patience.739 /// parent: seven doublings from 2ms is a quarter of a second of patience.
864 pub const CAP_WRITE_TRIES: usize = 8;740 pub const CAP_WRITE_TRIES: usize = 8;
865 pub const CAP_WRITE_BACKOFF_MS: u64 = 2;741 pub const CAP_WRITE_BACKOFF_MS: u64 = 2;
866-
867-// --- boot leader election ----------------------------------------------
868-
869-/// The lock row every booting process races for (see
870-/// [`crate::database::boot_once`]). Its own table, and the only SCHEMALESS one
871-/// in the database: the lock has to be claimable *before* the SCHEMAFULL batch
872-/// that defines every other table has run, so a lock whose own schema needed
873-/// migrating could not guard the migration. `IF NOT EXISTS` makes the
874-/// definition safe for all N processes to issue.
875-pub const MIGRATION_LOCK_TABLE: &str = "migration_lock";
876-pub const MIGRATION_LOCK_DDL: &str = "DEFINE TABLE IF NOT EXISTS migration_lock SCHEMALESS;";
877-
878-/// Claim the lock. A deterministic id is the whole mechanism: SurrealDB v3
879-/// answers a `CREATE` on an existing id with "already exists" rather than
880-/// overwriting it, so of N concurrent processes exactly one gets an `Ok`.
881-/// Returns the holder like the takeover does, so one caller reads both.
882-pub const MIGRATION_LOCK_CLAIM: &str = "
883- CREATE migration_lock:boot SET holder = $me, claimed_at = time::unix(time::now()) * 1000,
884- applied_at = NONE, applies = 0 RETURN VALUE holder;
885-";
886-
887-/// What a loser needs to know, decided by the *database's* clock β€” never the
888-/// process's, since two replicas' clocks disagree and the lease horizon is the
889-/// one thing a wrong clock could turn into a concurrent migration.
890-///
891-/// `applied` means "applied *this* binary's schema": a stamp carries the
892-/// fingerprint of the DDL that produced it, and a peer's stamp with any other
893-/// fingerprint is no evidence about the schema this process is about to write
894-/// (see [`crate::database::migration_fingerprint`]).
895-pub const MIGRATION_LOCK_STATE: &str = "
896- SELECT holder, applied_at != NONE AND (fingerprint ?? '') = $fingerprint AS applied,
897- claimed_at >= time::unix(time::now()) * 1000 - $lease_ms AS live
898- FROM ONLY migration_lock:boot;
899-";
900-
901-/// Take the lock off a holder that cannot be relied on: one that has gone
902-/// silent past the lease horizon (killed mid-migration), or one that finished
903-/// with a *different* schema than ours β€” a stamp is the last thing a leader
904-/// writes, so a foreign fingerprint means nobody is in the DDL right now and
905-/// this binary's own migration still has to run.
906-///
907-/// Per-record `UPDATE ... WHERE` is atomic, so a second taker re-reads the
908-/// freshly bumped `claimed_at` and is refused (empty result). Clears
909-/// `applied_at` and `fingerprint`: the previous generation's stamp says nothing
910-/// about this one's schema.
911-pub const MIGRATION_LOCK_TAKEOVER: &str = "
912- UPDATE migration_lock:boot SET holder = $me, claimed_at = time::unix(time::now()) * 1000,
913- applied_at = NONE, fingerprint = NONE
914- WHERE claimed_at < time::unix(time::now()) * 1000 - $lease_ms
915- OR (applied_at != NONE AND (fingerprint ?? '') != $fingerprint)
916- RETURN VALUE holder;
917-";
918-
919-/// Renew the lease while the migration runs, and stamp it done afterwards.
920-/// Both are `holder`-guarded and both report the holder back, so a leader that
921-/// was declared dead and replaced not only stops being able to write the lock β€”
922-/// it finds out (an empty result), which is the only way it can learn that a
923-/// peer is now applying the same DDL underneath it.
924-pub const MIGRATION_LOCK_HEARTBEAT: &str = "
925- UPDATE migration_lock:boot SET claimed_at = time::unix(time::now()) * 1000
926- WHERE holder = $me RETURN VALUE holder;
927-";
928-pub const MIGRATION_LOCK_STAMP: &str = "
929- UPDATE migration_lock:boot SET applied_at = time::unix(time::now()) * 1000, applies += 1,
930- fingerprint = $fingerprint
931- WHERE holder = $me RETURN VALUE holder;
932-";
933-
934-/// How long a lock may go unrenewed before a peer may take it over. Must stay
935-/// a comfortable multiple of `MIGRATION_LOCK_HEARTBEAT_SECS`: it is the number
936-/// of missed beats that separates "the leader was killed" from "the leader is
937-/// slow", and mistaking the second for the first runs two migrations at once.
938-pub const MIGRATION_LOCK_LEASE_SECS: i64 = 30;
939-pub const MIGRATION_LOCK_HEARTBEAT_SECS: u64 = 5;
940-
941-/// How long a non-leader waits for the leader's `applied_at` before failing the
942-/// boot, and how often it looks. Bounded because a boot that hangs forever is
943-/// indistinguishable from a hung database; loud because the alternative β€”
944-/// serving on a schema nobody confirmed β€” is worse.
945-pub const MIGRATION_LOCK_WAIT_SECS: u64 = 180;
946-pub const MIGRATION_LOCK_POLL_MS: u64 = 200;
src/database.rsmodified+84 -761
@@ -3,15 +3,9 @@
3 use surrealdb::Surreal;3 use surrealdb::Surreal;
4 use surrealdb::engine::any::Any;4 use surrealdb::engine::any::Any;
5 use surrealdb::opt::auth::Root;5 use surrealdb::opt::auth::Root;
6-use surrealdb::types::SurrealValue;
7 6
8 use crate::config::Config;7 use crate::config::Config;
9-use crate::constant::{8+use crate::constant::CHATBOT_PENDING_STALE_SECS;
10- CAS_UPDATE_RETRIES, CHATBOT_PENDING_STALE_SECS, MIGRATION_LOCK_CLAIM, MIGRATION_LOCK_DDL,
11- MIGRATION_LOCK_HEARTBEAT, MIGRATION_LOCK_HEARTBEAT_SECS, MIGRATION_LOCK_LEASE_SECS,
12- MIGRATION_LOCK_POLL_MS, MIGRATION_LOCK_STAMP, MIGRATION_LOCK_STATE, MIGRATION_LOCK_TAKEOVER,
13- MIGRATION_LOCK_WAIT_SECS,
14-};
15 use crate::domain::user::{Password, User, Username};9 use crate::domain::user::{Password, User, Username};
16 use crate::error::AppError;10 use crate::error::AppError;
17 use crate::migration_sql::MIGRATION_BATCHES;11 use crate::migration_sql::MIGRATION_BATCHES;
@@ -32,13 +26,13 @@ use crate::migration_sql::MIGRATION_BATCHES;
32 /// Cloning the `Arc` shares the single session established at boot instead.26 /// Cloning the `Arc` shares the single session established at boot instead.
33 pub type Database = std::sync::Arc<Surreal<Any>>;27 pub type Database = std::sync::Arc<Surreal<Any>>;
34 28
35-/// Connect to the SurrealDB server, sign in as root, and apply the schema β€”29+/// Connect to the SurrealDB server, sign in as root, apply the schema and seed
36-/// the latter through the boot election, so that N overlapping processes apply30+/// the admin. One process, one database, stop-the-world deploys β€” so all of it
37-/// it once between them (see [`boot_once`]).31+/// runs unconditionally on every boot.
38 pub async fn init(cfg: &Config) -> Result<Database, AppError> {32 pub async fn init(cfg: &Config) -> Result<Database, AppError> {
39- // Validated before the connection, not after the election: half a33+ // Validated before the connection, not after: half a credential pair is a
40- // credential pair is a deployment mistake, and finding that out only in the34+ // deployment mistake, and reporting it only after a successful dial buries
41- // process that happened to win the lock would make it a coin flip.35+ // it under an outage that isn't one.
42 let admin = admin_credentials(cfg)?;36 let admin = admin_credentials(cfg)?;
43 let db = connect_with_retry(cfg).await;37 let db = connect_with_retry(cfg).await;
44 db.signin(Root {38 db.signin(Root {
@@ -50,12 +44,10 @@ pub async fn init(cfg: &Config) -> Result<Database, AppError> {
50 .use_db(cfg.db_name.clone())44 .use_db(cfg.db_name.clone())
51 .await?;45 .await?;
52 let db = std::sync::Arc::new(db);46 let db = std::sync::Arc::new(db);
53- boot_once(47+ migrate(&db).await?;
54- &db,48+ if let Some((username, password)) = admin {
55- admin,49+ User::ensure_admin(username, password, &db).await?;
56- std::time::Duration::from_secs(MIGRATION_LOCK_WAIT_SECS),50+ }
57- )
58- .await?;
59 Ok(db)51 Ok(db)
60 }52 }
61 53
@@ -77,181 +69,6 @@ fn admin_credentials(cfg: &Config) -> Result<Option<(Username, Password)>, AppEr
77 }69 }
78 }70 }
79 71
80-/// Run the boot work that must happen exactly once β€” the schema batches and the
81-/// admin seed β€” under a leader election, and hold every other process at the
82-/// door until it *has* happened. Returns whether we were the leader.
83-///
84-/// Two processes overlap on every rolling restart, long before any replica
85-/// work: they used to race the same SCHEMAFULL DDL, the same data backfills
86-/// (including the chatbot pending sweep, which writes live rows) and the same
87-/// `ensure_admin` read-then-create. The election is a deterministic-id
88-/// `CREATE`: SurrealDB v3 answers a create on an existing id with "already
89-/// exists" instead of overwriting, so of N racing processes exactly one gets an
90-/// `Ok`, and that one is the leader.
91-///
92-/// The lock is a *heartbeated lease*, not a once-only flag, and both halves of
93-/// that are deliberate:
94-///
95-/// * Heartbeated, because a leader killed mid-migration must not wedge every
96-/// future boot, yet a leader that is merely slow must never be overtaken β€”
97-/// two processes in the DDL at once is the exact race being prevented. The
98-/// leader renews `claimed_at` every `MIGRATION_LOCK_HEARTBEAT_SECS` for as
99-/// long as it works, and a peer takes over only after
100-/// `MIGRATION_LOCK_LEASE_SECS` of silence. The price is that recovery from a
101-/// killed leader waits out the lease; the alternative, a plain age horizon,
102-/// would have to exceed the slowest imaginable migration to be safe.
103-/// * A lease, not a flag, because a boot an hour later may be a new binary with
104-/// new DDL and must re-apply, and because the data backfills (the chatbot
105-/// pending sweep above all) are meant to run on every restart. Only a boot
106-/// *inside* the lease trusts a peer's `applied_at` β€” i.e. exactly the
107-/// rolling-restart window β€” and only when that stamp carries this binary's own
108-/// [`migration_fingerprint`], so a mixed-version window cannot make the newer
109-/// process skip its own DDL.
110-///
111-/// `wait` is how long a non-leader keeps polling before it fails the boot; a
112-/// parameter rather than a constant read inline so a test can prove that
113-/// deadline actually bites without sitting out `MIGRATION_LOCK_WAIT_SECS`.
114-async fn boot_once(
115- db: &Database,
116- admin: Option<(Username, Password)>,
117- wait: std::time::Duration,
118-) -> Result<bool, AppError> {
119- let lease_ms = MIGRATION_LOCK_LEASE_SECS * 1_000;
120- // Any unique string; the lock only ever compares it for equality.
121- let me = ulid::Ulid::new().to_string();
122- // No query deadline anywhere in here on purpose: the SDK parks queries
123- // while the socket is down instead of failing them, so a timeout would
124- // report an outage as a dead leader and hand the migration to a second
125- // process (see `crate::error::AppError::DbTimeout`).
126- //
127- // The bootstrap step: the lock's own table has to exist before anyone can
128- // claim a row in it, so every process defines it (`IF NOT EXISTS`) rather
129- // than the leader β€” the leader is not known yet. N processes issuing that
130- // at once makes the key-value layer abort the losers with a retryable write
131- // conflict, and a conflict here means a rival committed the very definition
132- // we wanted, so it counts as success.
133- if let Err(err) = db
134- .query(MIGRATION_LOCK_DDL)
135- .await
136- .and_then(|response| response.check())
137- && !lost_the_race(&err)
138- {
139- return Err(err.into());
140- }
141-
142- let deadline = tokio::time::Instant::now() + wait;
143- loop {
144- if claim(db, MIGRATION_LOCK_CLAIM, &me, lease_ms).await? {
145- return leader_applies(db, &me, admin).await.map(|()| true);
146- }
147- let read = db
148- .query(MIGRATION_LOCK_STATE)
149- .bind(("lease_ms", lease_ms))
150- .bind(("fingerprint", migration_fingerprint()))
151- .await
152- .and_then(|response| response.check())
153- .and_then(|mut response| response.take::<Option<LockState>>(0));
154- let state = match read {
155- Ok(state) => state,
156- // The leader heartbeats this very row every few seconds and rivals
157- // take it over, so a read of it can be aborted as retryable β€” which
158- // is not an error about the lock, just "no answer this round". This
159- // poll loop, with its deadline, *is* the bounded retry the conflict
160- // asks for, so treat it like a missing row and look again. Retrying
161- // a `SELECT` is free of side effects by construction.
162- Err(err) if lost_the_race(&err) => None,
163- Err(err) => return Err(err.into()),
164- };
165- match state {
166- // A live lease, stamped with our own fingerprint: the exact schema
167- // this process needs is in place, so stop waiting.
168- Some(state) if state.live && state.applied => {
169- tracing::info!(leader = %state.holder, "schema applied by another process");
170- return Ok(false);
171- }
172- // Anything else may be takeable β€” the holder went silent past the
173- // lease, or it finished but with a different schema than ours. The
174- // statement's `WHERE` is the arbiter, so a live holder still inside
175- // the DDL refuses us and we fall through to waiting.
176- Some(state) if claim(db, MIGRATION_LOCK_TAKEOVER, &me, lease_ms).await? => {
177- tracing::warn!(
178- previous = %state.holder,
179- live = state.live,
180- "taking over the boot migration lock: the holder went silent or applied \
181- a different schema"
182- );
183- return leader_applies(db, &me, admin).await.map(|()| true);
184- }
185- Some(state) => {
186- tracing::debug!(leader = %state.holder, "waiting for the boot migration");
187- }
188- // The row vanished; the next iteration's `CREATE` picks it up.
189- None => {}
190- }
191- if tokio::time::Instant::now() >= deadline {
192- // Loudly, not optimistically: SCHEMAFULL means an unmigrated
193- // database fails every write anyway, and it would do so as
194- // scattered 500s instead of one startup error. Exiting hands the
195- // retry to the container runtime, which is where boot retries live.
196- //
197- // One production sequence reaches this branch: a leader that keeps
198- // renewing its lease for longer than `wait` without ever stamping β€”
199- // a migration slower than `MIGRATION_LOCK_WAIT_SECS`. A leader that
200- // *stops* renewing never gets here, because the takeover above fires
201- // a lease (30s) rather than a wait (180s) after the last renewal. So
202- // the relative size of those two constants is not what selects this
203- // branch; "the lock stayed live-and-unstamped for the whole wait"
204- // is β€” which is precisely the state
205- // `a_live_lock_is_waited_for_and_the_wait_is_bounded` constructs,
206- // renewer and all, at a scaled-down wait.
207- return Err(AppError::Internal(format!(
208- "the boot migration lock stayed held for {wait:?}; \
209- refusing to serve on a schema no process has confirmed"
210- )));
211- }
212- tokio::time::sleep(std::time::Duration::from_millis(MIGRATION_LOCK_POLL_MS)).await;
213- }
214-}
215-
216-/// The lock row as a loser reads it. `live`/`applied` are computed by the
217-/// database so the verdict never depends on this process's clock.
218-#[derive(SurrealValue)]
219-struct LockState {
220- holder: String,
221- applied: bool,
222- live: bool,
223-}
224-
225-/// Run one of the two acquiring statements and report whether we now hold the
226-/// lock β€” both return our own holder id when we do, and nothing when a rival
227-/// got there first.
228-///
229-/// Two failures mean "not ours", not "broken". "Already exists" is the
230-/// deterministic-id create losing the race, and a key-value *write conflict* is
231-/// the same race decided one layer down: when two processes create the same id
232-/// at genuinely the same instant, the loser's transaction is aborted as
233-/// retryable rather than answered with the duplicate-key message (observed on
234-/// every run of `two_concurrent_boots_apply_the_schema_once`). Either way the
235-/// caller loops, re-reads the lock and finds out who holds it β€” which is also
236-/// the retry the conflict asks for.
237-async fn claim(db: &Database, sql: &str, me: &str, lease_ms: i64) -> Result<bool, AppError> {
238- let result = db
239- .query(sql)
240- .bind(("me", me.to_string()))
241- .bind(("lease_ms", lease_ms))
242- .bind(("fingerprint", migration_fingerprint()))
243- .await
244- .and_then(|response| response.check());
245- match result {
246- Ok(mut response) => {
247- let holders: Vec<String> = response.take(0)?;
248- Ok(holders.iter().any(|holder| holder == me))
249- }
250- Err(err) if lost_the_race(&err) => Ok(false),
251- Err(err) => Err(err.into()),
252- }
253-}
254-
255 /// The two ways a rival's claim shows up as an error on ours: our `CREATE` hit72 /// The two ways a rival's claim shows up as an error on ours: our `CREATE` hit
256 /// their row, or the key-value layer aborted our transaction because theirs73 /// their row, or the key-value layer aborted our transaction because theirs
257 /// touched the same key first.74 /// touched the same key first.
@@ -285,146 +102,6 @@ pub(crate) fn lost_the_race(err: &surrealdb::Error) -> bool {
285 message.contains("already exists") || message.contains("can be retried")102 message.contains("already exists") || message.contains("can be retried")
286 }103 }
287 104
288-/// A hash of the exact DDL and backfills this binary intends to apply.
289-///
290-/// It is what makes a peer's "applied" stamp trustworthy. Without it, a process
291-/// booting inside the lease window trusts *any* finished predecessor β€” so a new
292-/// binary starting seconds after an old one stamped would skip its own newer
293-/// DDL and then serve on a schema missing the very fields its handlers write.
294-/// With it, "somebody applied a schema" narrows to "somebody applied *this*
295-/// schema", and anything else is treated as unapplied.
296-///
297-/// Derived from the three SQL constants, never a hand-bumped version number: a
298-/// number nobody remembers to raise is worse than no check at all, while this
299-/// one changes on its own the moment the schema does.
300-fn migration_fingerprint() -> &'static str {
301- use sha2::{Digest, Sha256};
302- static FINGERPRINT: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
303- let mut hasher = Sha256::new();
304- // Length-prefixed, not concatenated: without a separator, moving a
305- // statement from one batch into the next leaves the byte stream β€” and so
306- // the fingerprint β€” unchanged, while changing what the boot actually
307- // does (batch boundaries are what keep the DDL out of the backfills).
308- for sql in MIGRATION_BATCHES {
309- hasher.update((sql.len() as u64).to_le_bytes());
310- hasher.update(sql.as_bytes());
311- }
312- for (name, value) in migration_binds() {
313- hasher.update(name.as_bytes());
314- hasher.update(value.to_le_bytes());
315- }
316- hex::encode(hasher.finalize())
317- });
318- &FINGERPRINT
319-}
320-
321-/// Leader path: keep the lease alive, apply everything, then stamp it done.
322-///
323-/// The renewal runs *concurrently with* the work rather than after it, in the
324-/// same task: `select!` polls both, so a lease that cannot be renewed is
325-/// noticed while the DDL is still going instead of at the end.
326-async fn leader_applies(
327- db: &Database,
328- me: &str,
329- admin: Option<(Username, Password)>,
330-) -> Result<(), AppError> {
331- let apply = async {
332- migrate(db).await?;
333- if let Some((username, password)) = admin {
334- User::ensure_admin(username, password, db).await?;
335- }
336- Ok::<(), AppError>(())
337- };
338- tokio::select! {
339- applied = apply => applied?,
340- lost = renew_lease(db, me) => return Err(lost),
341- }
342-
343- // The stamp is the one write in this path with nothing above it to retry
344- // it: waiters are polling the same row and taking it over, so the
345- // key-value layer can abort ours as retryable, and an escaping conflict
346- // fails a boot that had already migrated everything. Repeating it is safe
347- // despite `applies += 1` β€” a conflicted transaction commits nothing, and
348- // the statement's `holder` guard turns a *genuine* takeover into an empty
349- // result rather than a second count. Bounded, because a conflict that
350- // never clears is a real failure and must stay one.
351- let mut stamped: Vec<String> = Vec::new();
352- for attempt in 0..CAS_UPDATE_RETRIES {
353- let attempted = db
354- .query(MIGRATION_LOCK_STAMP)
355- .bind(("me", me.to_string()))
356- .bind(("fingerprint", migration_fingerprint()))
357- .await
358- .and_then(|response| response.check());
359- match attempted {
360- Ok(mut response) => {
361- stamped = response.take(0)?;
362- break;
363- }
364- Err(err) if lost_the_race(&err) && attempt + 1 < CAS_UPDATE_RETRIES => {
365- tracing::warn!("stamping the boot migration lock conflicted ({err}) β€” retrying");
366- tokio::time::sleep(std::time::Duration::from_millis(MIGRATION_LOCK_POLL_MS)).await;
367- }
368- Err(err) => return Err(err.into()),
369- }
370- }
371- if stamped.is_empty() {
372- // The same verdict as a lost renewal, for the same reason β€” this is the
373- // backstop for losing the lock in the window between the last renewal
374- // and the stamp.
375- return Err(lost_lease());
376- }
377- Ok(())
378-}
379-
380-/// Renew the lease until it can no longer be renewed. Resolves *only* on that
381-/// loss, so it can sit opposite the real work in a `select!`.
382-///
383-/// A refused renewal (empty result) means a peer declared us dead and took the
384-/// lock, so it is now applying the same DDL underneath us. We treat that as
385-/// fatal to this boot and stop: our statements are all idempotent, so there is
386-/// nothing to undo, but continuing would keep two processes writing schema at
387-/// once β€” the exact race this module exists to prevent β€” and would leave us
388-/// serving as if we had migrated. Failing hands the retry to the container
389-/// runtime, which re-elects cleanly.
390-///
391-/// A renewal that *errors* is different: the socket may simply be down, and the
392-/// SDK parks queries rather than failing them, so a real error here is rare and
393-/// says nothing definite. Log it and keep trying β€” if it persists, the lease
394-/// expires, a peer takes over, and the next renewal is refused, which is the
395-/// verdict above. `.check()` is load-bearing: a statement-level failure comes
396-/// back inside an `Ok` response, so without it a renewal could fail forever
397-/// while logging nothing and renewing nothing.
398-async fn renew_lease(db: &Database, me: &str) -> AppError {
399- let mut interval = tokio::time::interval(std::time::Duration::from_secs(
400- MIGRATION_LOCK_HEARTBEAT_SECS,
401- ));
402- loop {
403- interval.tick().await;
404- match db
405- .query(MIGRATION_LOCK_HEARTBEAT)
406- .bind(("me", me.to_string()))
407- .await
408- .and_then(|response| response.check())
409- {
410- Ok(mut response) => match response.take::<Vec<String>>(0) {
411- Ok(holders) if holders.is_empty() => return lost_lease(),
412- Ok(_) => tracing::debug!("boot migration lease renewed"),
413- Err(err) => tracing::warn!("boot lock renewal returned unusable rows: {err}"),
414- },
415- Err(err) => tracing::warn!("boot lock renewal failed: {err}"),
416- }
417- }
418-}
419-
420-fn lost_lease() -> AppError {
421- AppError::Internal(
422- "lost the boot migration lock while applying it β€” another process took it over and is \
423- applying the schema, so this boot stops rather than race it"
424- .into(),
425- )
426-}
427-
428 /// Dial the database, retrying until it answers.105 /// Dial the database, retrying until it answers.
429 ///106 ///
430 /// Never gives up, because giving up is worse than waiting: the database is107 /// Never gives up, because giving up is worse than waiting: the database is
@@ -475,419 +152,13 @@ pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> {
475 152
476 /// Parameters the batches are executed with. Bound, not baked into the SQL153 /// Parameters the batches are executed with. Bound, not baked into the SQL
477 /// string: a `const` cannot be interpolated into another `const`, and a154 /// string: a `const` cannot be interpolated into another `const`, and a
478-/// hand-copied 300000 would drift silently. They are part of what the migration155+/// hand-copied 300000 would drift silently.
479-/// *does*, so [`migration_fingerprint`] hashes them alongside the SQL β€” a
480-/// changed horizon is a changed migration.
481 fn migration_binds() -> [(&'static str, i64); 1] {156 fn migration_binds() -> [(&'static str, i64); 1] {
482 [("stale_ms", CHATBOT_PENDING_STALE_SECS * 1_000)]157 [("stale_ms", CHATBOT_PENDING_STALE_SECS * 1_000)]
483 }158 }
484 159
485 #[cfg(test)]160 #[cfg(test)]
486 mod tests {161 mod tests {
487- use super::{Database, boot_once};
488- use crate::constant::{MIGRATION_LOCK_LEASE_SECS, MIGRATION_LOCK_TABLE};
489- use crate::domain::user::{Password, Username};
490- use std::time::Duration;
491-
492- /// An empty in-memory database with *no* schema β€” what a booting process
493- /// actually finds. [`super::init_mem`] cannot be used here: it migrates.
494- async fn unmigrated() -> Database {
495- let db = surrealdb::engine::any::connect("memory").await.unwrap();
496- db.use_ns("hezarfen").use_db("hezarfen").await.unwrap();
497- std::sync::Arc::new(db)
498- }
499-
500- fn admin() -> Option<(Username, Password)> {
501- Some((
502- Username::try_new("root").unwrap(),
503- Password::try_new("secret1").unwrap(),
504- ))
505- }
506-
507- /// How many times the lock has been stamped applied β€” the observable side
508- /// effect that makes "exactly one process applied" checkable.
509- async fn applies(db: &Database) -> i64 {
510- let mut res = db
511- .query("SELECT VALUE applies FROM ONLY migration_lock:boot")
512- .await
513- .unwrap();
514- res.take::<Option<i64>>(0).unwrap().unwrap()
515- }
516-
517- /// How many `root` rows the seed left. Guarded on the table existing: a
518- /// waiter that failed its boot never ran the DDL, so `user` may be absent,
519- /// which is an error rather than an empty result.
520- async fn admin_count(db: &Database) -> i64 {
521- let mut res = db
522- .query(
523- "RETURN IF 'user' IN object::keys((INFO FOR DB).tables) {
524- array::len((SELECT id FROM user WHERE username = 'root'))
525- } ELSE { 0 };",
526- )
527- .await
528- .unwrap();
529- res.take::<Option<i64>>(0).unwrap().unwrap()
530- }
531-
532- /// Two processes booting at once β€” the rolling-restart case, which happens
533- /// today without any replica work. Exactly one may run the DDL, the
534- /// backfills and the admin seed; the other has to wait for it and then
535- /// serve, not repeat it.
536- #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
537- async fn two_concurrent_boots_apply_the_schema_once() {
538- let db = unmigrated().await;
539- let (a, b) = (db.clone(), db.clone());
540- let one =
541- tokio::spawn(async move { boot_once(&a, admin(), Duration::from_secs(30)).await });
542- let two =
543- tokio::spawn(async move { boot_once(&b, admin(), Duration::from_secs(30)).await });
544- let (one, two) = (one.await.unwrap().unwrap(), two.await.unwrap().unwrap());
545-
546- assert!(one ^ two, "exactly one process leads the boot: {one}/{two}");
547- assert_eq!(applies(&db).await, 1, "the migration was applied once");
548- assert_eq!(admin_count(&db).await, 1, "the admin was seeded once");
549- // The loser still needs the schema it skipped applying.
550- assert!(
551- db.query("CREATE user:x SET username = 'x', password_hash = 'h'")
552- .await
553- .unwrap()
554- .check()
555- .is_ok(),
556- "the schema is in place once both boots return"
557- );
558- }
559-
560- /// The same race with enough processes in it to actually hit the
561- /// key-value layer's retryable aborts: eight boots contending for one lock
562- /// row collide on the losers' state read and the leader's stamp, which with
563- /// two boots surfaces only once in a few full-suite runs.
564- ///
565- /// What it asserts is deliberately narrow: no boot may fail with a
566- /// *retryable* conflict. A conflict is the layer asking to be asked again,
567- /// so one reaching the caller is always a missing retry β€” while the other
568- /// outcomes of a crowded election (a leader that loses its lease to a
569- /// taker) are documented behaviour, not bugs, and asserting against them
570- /// here would only make this flaky. Exactly-once stays the two-boot test's
571- /// job.
572- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
573- async fn a_crowd_of_boots_never_surfaces_a_retryable_conflict() {
574- let db = unmigrated().await;
575- let boots: Vec<_> = (0..8)
576- .map(|_| {
577- let db = db.clone();
578- tokio::spawn(async move { boot_once(&db, admin(), Duration::from_secs(30)).await })
579- })
580- .collect();
581- for boot in boots {
582- if let Err(err) = boot.await.unwrap() {
583- let message = err.to_string();
584- assert!(
585- !message.contains("can be retried") && !message.contains("conflict"),
586- "a retryable conflict escaped boot_once instead of being retried: {message}"
587- );
588- }
589- }
590- }
591-
592- /// A leader killed mid-migration leaves its claim behind. Nothing may
593- /// require a human with a SurrealQL prompt to clear it: the next boot takes
594- /// the lease over once it has gone unrenewed past the horizon.
595- #[tokio::test]
596- async fn an_abandoned_lock_is_taken_over_by_the_next_boot() {
597- let db = unmigrated().await;
598- // Exactly what a SIGKILL at the worst moment leaves: claimed, never
599- // stamped, and no heartbeat since.
600- db.query(
601- "DEFINE TABLE migration_lock SCHEMALESS;
602- CREATE migration_lock:boot SET holder = 'dead', applies = 0,
603- claimed_at = time::unix(time::now()) * 1000 - ($lease + 1) * 1000;",
604- )
605- .bind(("lease", MIGRATION_LOCK_LEASE_SECS))
606- .await
607- .unwrap()
608- .check()
609- .unwrap();
610-
611- assert!(
612- boot_once(&db, admin(), Duration::from_secs(5))
613- .await
614- .unwrap(),
615- "the abandoned lock is taken over, not waited on"
616- );
617- assert_eq!(applies(&db).await, 1);
618- assert_eq!(admin_count(&db).await, 1);
619- }
620-
621- /// The other side of that horizon: a lock claimed a moment ago belongs to a
622- /// process that is probably still working, so it is waited for β€” and if the
623- /// wait runs out the boot fails loudly instead of serving on a schema
624- /// nobody has confirmed.
625- #[tokio::test]
626- async fn a_live_lock_is_waited_for_and_the_wait_is_bounded() {
627- let db = unmigrated().await;
628- db.query(
629- "DEFINE TABLE migration_lock SCHEMALESS;
630- CREATE migration_lock:boot SET holder = 'busy', applies = 0,
631- claimed_at = time::unix(time::now()) * 1000;",
632- )
633- .await
634- .unwrap()
635- .check()
636- .unwrap();
637-
638- // A real leader renews; without a renewer this would test "the lease
639- // happened to still be inside its horizon", which is a different branch
640- // from the one production reaches (a leader slower than the wait).
641- let renewer = tokio::spawn({
642- let db = db.clone();
643- async move {
644- loop {
645- db.query(super::MIGRATION_LOCK_HEARTBEAT)
646- .bind(("me", "busy".to_string()))
647- .await
648- .unwrap()
649- .check()
650- .unwrap();
651- tokio::time::sleep(Duration::from_millis(50)).await;
652- }
653- }
654- });
655- let err = boot_once(&db, admin(), Duration::from_millis(600))
656- .await
657- .expect_err("a held, unstamped lock must not let a boot through");
658- renewer.abort();
659- assert!(
660- err.to_string().contains("refusing to serve"),
661- "the boot fails loudly: {err}"
662- );
663- assert_eq!(applies(&db).await, 0, "the waiter applied nothing");
664- assert_eq!(admin_count(&db).await, 0, "and seeded nothing");
665- }
666-
667- /// The rolling-deploy hole the fingerprint exists for: a peer stamped the
668- /// lock moments ago, inside the lease, so its lease is live and its work is
669- /// done β€” but it applied a *different* schema. Trusting that stamp means
670- /// serving on a database missing the fields this binary's own handlers
671- /// write. It must be treated as unapplied and taken over.
672- #[tokio::test]
673- async fn a_peers_stamp_for_a_different_schema_is_not_trusted() {
674- let db = unmigrated().await;
675- db.query(
676- "DEFINE TABLE migration_lock SCHEMALESS;
677- CREATE migration_lock:boot SET holder = 'old-binary', applies = 1,
678- claimed_at = time::unix(time::now()) * 1000,
679- applied_at = time::unix(time::now()) * 1000,
680- fingerprint = 'the DDL of some other build';",
681- )
682- .await
683- .unwrap()
684- .check()
685- .unwrap();
686-
687- assert!(
688- boot_once(&db, admin(), Duration::from_secs(5))
689- .await
690- .unwrap(),
691- "a stamp from a different schema is no evidence about ours"
692- );
693- assert_eq!(applies(&db).await, 2, "we applied ours on top");
694- assert_eq!(admin_count(&db).await, 1);
695- let mut res = db
696- .query("SELECT VALUE fingerprint FROM ONLY migration_lock:boot")
697- .await
698- .unwrap();
699- assert_eq!(
700- res.take::<Option<String>>(0).unwrap().as_deref(),
701- Some(super::migration_fingerprint()),
702- "and left our own fingerprint behind"
703- );
704- }
705-
706- /// The same lock, stamped with *our* fingerprint, is the case the skip
707- /// exists for β€” otherwise every rolling restart re-runs the whole migration
708- /// and the peer's boot is pointless.
709- #[tokio::test]
710- async fn a_peers_stamp_for_our_own_schema_is_trusted() {
711- let db = unmigrated().await;
712- db.query(
713- "DEFINE TABLE migration_lock SCHEMALESS;
714- CREATE migration_lock:boot SET holder = 'peer', applies = 1,
715- claimed_at = time::unix(time::now()) * 1000,
716- applied_at = time::unix(time::now()) * 1000,
717- fingerprint = $fingerprint;",
718- )
719- .bind(("fingerprint", super::migration_fingerprint()))
720- .await
721- .unwrap()
722- .check()
723- .unwrap();
724-
725- assert!(
726- !boot_once(&db, admin(), Duration::from_secs(5))
727- .await
728- .unwrap(),
729- "the peer applied this very schema, so this process just proceeds"
730- );
731- assert_eq!(applies(&db).await, 1, "and applies nothing itself");
732- }
733-
734- /// A hash of the same bytes, computed independently: the fingerprint has to
735- /// cover every batch, every bound value, and the boundaries between them.
736- /// Any of those left out is a schema change two binaries could disagree on
737- /// while claiming the same fingerprint.
738- #[test]
739- fn the_fingerprint_covers_every_batch_its_binds_and_the_boundaries() {
740- use sha2::{Digest, Sha256};
741- let hash = |batches: &[String], binds: &[(&str, i64)]| {
742- let mut hasher = Sha256::new();
743- for sql in batches {
744- hasher.update((sql.len() as u64).to_le_bytes());
745- hasher.update(sql.as_bytes());
746- }
747- for (name, value) in binds {
748- hasher.update(name.as_bytes());
749- hasher.update(value.to_le_bytes());
750- }
751- hex::encode(hasher.finalize())
752- };
753- let batches: Vec<String> = crate::migration_sql::MIGRATION_BATCHES
754- .iter()
755- .map(|sql| (*sql).to_string())
756- .collect();
757- let binds = super::migration_binds();
758- assert_eq!(super::migration_fingerprint(), hash(&batches, &binds));
759-
760- let mut edited = batches.clone();
761- edited[2].push_str("-- one more backfill\n");
762- assert_ne!(
763- super::migration_fingerprint(),
764- hash(&edited, &binds),
765- "an edited batch must change the fingerprint"
766- );
767- // The boundary itself: the same bytes, one statement moved from the DDL
768- // batch into the backfill batch. Concatenation without a separator would
769- // hash these two arrangements identically.
770- let mut moved = batches.clone();
771- let at = moved[1].len() - 20;
772- let tail = moved[1].split_off(at);
773- moved[2].insert_str(0, &tail);
774- assert_ne!(
775- super::migration_fingerprint(),
776- hash(&moved, &binds),
777- "moving text across a batch boundary must change the fingerprint"
778- );
779- assert_ne!(
780- super::migration_fingerprint(),
781- hash(&batches, &[("stale_ms", 1)]),
782- "a changed bound value is a changed migration"
783- );
784- }
785-
786- /// The forcing function behind all of that: `migrate` and
787- /// `migration_fingerprint` must read the *same* list. A fourth batch
788- /// executed by one and not hashed by the other would let two binaries with
789- /// different schemas claim the same fingerprint β€” and then skip each other's
790- /// migration, which is the whole hole the fingerprint was added to close.
791- #[test]
792- fn what_the_boot_executes_is_what_the_fingerprint_hashes() {
793- let source =
794- std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/database.rs"))
795- .expect("read database.rs");
796- let body = |name: &str| {
797- let start = source.find(name).expect("function is declared");
798- let rest = &source[start..];
799- let end = rest.find("\n}\n").expect("function ends");
800- rest[..end].to_string()
801- };
802- for (name, body) in [
803- ("pub async fn migrate", body("pub async fn migrate")),
804- ("fn migration_fingerprint", body("fn migration_fingerprint")),
805- ] {
806- assert!(
807- body.contains("MIGRATION_BATCHES") && body.contains("migration_binds()"),
808- "{name} must derive from MIGRATION_BATCHES + migration_binds(), \
809- or the executed and the hashed migration can drift apart"
810- );
811- }
812- let executed = body("pub async fn migrate");
813- assert_eq!(
814- executed.matches("db.query(").count(),
815- 1,
816- "migrate() runs exactly one statement source β€” the batch list. A second \
817- `db.query(...)` here is a batch the fingerprint does not hash:\n{executed}"
818- );
819- }
820-
821- /// Path one of two: the renewal itself is refused. Driven straight at
822- /// `renew_lease` rather than through `leader_applies`, because inside the
823- /// `select!` a stamp failure would produce the same error and the test would
824- /// pass without this path working at all.
825- #[tokio::test]
826- async fn a_refused_renewal_ends_the_lease_fatally() {
827- let db = unmigrated().await;
828- db.query(
829- "DEFINE TABLE migration_lock SCHEMALESS;
830- CREATE migration_lock:boot SET holder = 'somebody-else', applies = 0,
831- claimed_at = time::unix(time::now()) * 1000;",
832- )
833- .await
834- .unwrap()
835- .check()
836- .unwrap();
837-
838- // Only ever resolves on a loss, so reaching this line is the assertion;
839- // the timeout is there to fail the test instead of hanging it.
840- let err = tokio::time::timeout(Duration::from_secs(5), super::renew_lease(&db, "me"))
841- .await
842- .expect("a renewal refused by the lock must resolve, not keep renewing");
843- assert!(
844- err.to_string().contains("lost the boot migration lock"),
845- "{err}"
846- );
847- }
848-
849- /// Path two: the lock is stolen *after* the last renewal, so nothing refuses
850- /// us until the stamp. The thief strikes while the DDL is running, far
851- /// inside the renewal interval, which is exactly the window the stamp
852- /// backstop exists for.
853- #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
854- async fn a_lock_stolen_after_the_last_renewal_is_caught_by_the_stamp() {
855- let db = unmigrated().await;
856- db.query(
857- "DEFINE TABLE migration_lock SCHEMALESS;
858- CREATE migration_lock:boot SET holder = 'me', applies = 0,
859- claimed_at = time::unix(time::now()) * 1000;",
860- )
861- .await
862- .unwrap()
863- .check()
864- .unwrap();
865- let thief = tokio::spawn({
866- let db = db.clone();
867- async move {
868- tokio::time::sleep(Duration::from_millis(5)).await;
869- db.query("UPDATE migration_lock:boot SET holder = 'thief'")
870- .await
871- .unwrap()
872- .check()
873- .unwrap();
874- }
875- });
876-
877- let err = super::leader_applies(&db, "me", admin())
878- .await
879- .expect_err("a leader that cannot stamp its own lock must not report success");
880- thief.await.unwrap();
881- assert!(
882- err.to_string().contains("lost the boot migration lock"),
883- "{err}"
884- );
885- assert_eq!(
886- applies(&db).await,
887- 0,
888- "and the lock is not stamped as applied by us"
889- );
890- }
891 162
892 /// The admin seed must not be interruptible into a state no later boot can163 /// The admin seed must not be interruptible into a state no later boot can
893 /// repair. `create` + `set_role` was: killed between the two writes it164 /// repair. `create` + `set_role` was: killed between the two writes it
@@ -915,26 +186,6 @@ mod tests {
915 );186 );
916 }187 }
917 188
918- /// The lock's table name is spelled in six places (the DDL and every
919- /// statement), and a rename that misses one would split the election in two
920- /// silently β€” every process would then "win" its own lock.
921- #[test]
922- fn every_lock_statement_names_the_lock_table() {
923- for sql in [
924- crate::constant::MIGRATION_LOCK_DDL,
925- crate::constant::MIGRATION_LOCK_CLAIM,
926- crate::constant::MIGRATION_LOCK_STATE,
927- crate::constant::MIGRATION_LOCK_TAKEOVER,
928- crate::constant::MIGRATION_LOCK_HEARTBEAT,
929- crate::constant::MIGRATION_LOCK_STAMP,
930- ] {
931- assert!(
932- sql.contains(MIGRATION_LOCK_TABLE),
933- "{sql} does not name {MIGRATION_LOCK_TABLE}"
934- );
935- }
936- }
937-
938 #[tokio::test]189 #[tokio::test]
939 async fn boot_fails_chatbot_messages_left_pending() {190 async fn boot_fails_chatbot_messages_left_pending() {
940 let db = super::init_mem().await.unwrap();191 let db = super::init_mem().await.unwrap();
@@ -970,6 +221,78 @@ mod tests {
970 assert!(interrupted["completed_at"].as_i64().unwrap() > 0);221 assert!(interrupted["completed_at"].as_i64().unwrap() > 0);
971 }222 }
972 223
224+ #[tokio::test]
225+ async fn the_retired_claim_columns_are_dropped_off_a_live_row() {
226+ // Stale-data path for the 2026-07-30 removal of the chat claim queue.
227+ // A dev volume carries `chatbot_message` rows *with* claim values and an
228+ // `ai_worker` table, so the boot has to clear the values while their
229+ // definitions still stand (PRE_REPAIR) and only then retire the columns
230+ // β€” SCHEMAFULL rejects every write to a row storing a column that no
231+ // longer exists, which would make the row unanswerable forever.
232+ let db = super::init_mem().await.unwrap();
233+ db.query(
234+ "DEFINE FIELD claimed_by ON chatbot_message TYPE option<string>;
235+ DEFINE FIELD claimed_at ON chatbot_message TYPE option<int>;
236+ DEFINE TABLE ai_worker SCHEMAFULL;
237+ DEFINE FIELD seen_at ON ai_worker TYPE int;
238+ DEFINE TABLE migration_lock SCHEMALESS;",
239+ )
240+ .await
241+ .unwrap()
242+ .check()
243+ .unwrap();
244+ db.query(
245+ "CREATE user:u SET username = 'u', password_hash = 'x';
246+ CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1;
247+ CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u,
248+ role = 'assistant', content = '', status = 'pending',
249+ created_at = time::unix(time::now()) * 1000,
250+ claimed_by = 'a-dead-replica', claimed_at = 1;
251+ CREATE ai_worker:w SET seen_at = 1;
252+ CREATE migration_lock:the_lock SET holder = 'a-dead-replica', expires_at = 1;",
253+ )
254+ .await
255+ .unwrap()
256+ .check()
257+ .unwrap();
258+
259+ // Twice: the repair and both removals have to be idempotent, since
260+ // every boot runs them.
261+ super::migrate(&db).await.unwrap();
262+ super::migrate(&db).await.unwrap();
263+
264+ let mut info = db.query("INFO FOR TABLE chatbot_message").await.unwrap();
265+ let table: serde_json::Value = info.take::<Option<serde_json::Value>>(0).unwrap().unwrap();
266+ let fields = table["fields"].as_object().expect("fields");
267+ assert!(!fields.contains_key("claimed_by"), "{table}");
268+ assert!(!fields.contains_key("claimed_at"), "{table}");
269+ let mut tables = db.query("INFO FOR DB").await.unwrap();
270+ let dbinfo: serde_json::Value = tables
271+ .take::<Option<serde_json::Value>>(0)
272+ .unwrap()
273+ .unwrap();
274+ let tables = dbinfo["tables"].as_object().expect("tables");
275+ assert!(!tables.contains_key("ai_worker"), "{dbinfo}");
276+ // Same story one table over: the elected-boot lease, stale leader row
277+ // and all.
278+ assert!(!tables.contains_key("migration_lock"), "{dbinfo}");
279+
280+ // The load-bearing half: the row that carried a claim is still
281+ // writable. A leftover value under no definition fails here.
282+ db.query("UPDATE chatbot_message:m SET status = 'complete', content = 'ok'")
283+ .await
284+ .unwrap()
285+ .check()
286+ .unwrap();
287+ let mut row = db
288+ .query("SELECT * FROM ONLY chatbot_message:m")
289+ .await
290+ .unwrap();
291+ let row: serde_json::Value = row.take::<Option<serde_json::Value>>(0).unwrap().unwrap();
292+ assert_eq!(row["status"], "complete", "{row}");
293+ assert!(row.get("claimed_by").is_none(), "{row}");
294+ }
295+
973 /// The other half of the sweep: a restart seconds after a dispatch must not296 /// The other half of the sweep: a restart seconds after a dispatch must not
974 /// kill the turn β€” the answering task may still be alive on the other side297 /// kill the turn β€” the answering task may still be alive on the other side
975 /// of the bridge, and the row is not yet past the stale horizon.298 /// of the bridge, and the row is not yet past the stale horizon.
src/domain/appointment.rsmodified+30 -31
@@ -8,26 +8,26 @@
8 //! [`cap`](crate::domain::cap) of one. Booking [`claim`](cap::claim)s it;8 //! [`cap`](crate::domain::cap) of one. Booking [`claim`](cap::claim)s it;
9 //! rejecting or cancelling gives it back in the *same transaction* as the9 //! rejecting or cancelling gives it back in the *same transaction* as the
10 //! status flip, so the slot frees itself with nothing to sweep. Both are10 //! status flip, so the slot frees itself with nothing to sweep. Both are
11-//! single-record conditional writes, so this invariant holds across replicas.11+//! single-record conditional writes, so the store decides it, not a lock.
12 //! - **No double-booked person.** An approved meeting may not overlap another12 //! - **No double-booked person.** An approved meeting may not overlap another
13 //! approved meeting of the same teacher *or* of the same requester. That is a13 //! approved meeting of the same teacher *or* of the same requester. That is a
14 //! count-then-write over *many* rows, which a `BEGIN…COMMIT` does not14 //! count-then-write over *many* rows, which a `BEGIN…COMMIT` does not
15 //! serialize in SurrealDB (write-skew), so it stays under15 //! serialize in SurrealDB (write-skew), so it stays under
16-//! [`APPOINTMENT_LOCK`] β€” and stays replica-local.16+//! [`APPOINTMENT_LOCK`], which is the whole guarantee behind it.
17 //!17 //!
18 //! The *single-row* invariant β€” a decision must be written onto the state it18 //! The *single-row* invariant β€” a decision must be written onto the state it
19-//! was validated against β€” is **not** the lock's job, and never was: the lock19+//! was validated against β€” is **not** the lock's job, and never was: a
20-//! is process-local, so two replicas each take their own copy of it and a20+//! whole-row save built on a snapshot read before the lock was taken would
21-//! whole-row save would silently drop the other's decision. That one is a21+//! silently drop whatever landed in between. That one is a compare-and-set
22-//! compare-and-set ([`Appointment::save_if_unchanged`]), which holds across22+//! ([`Appointment::save_if_unchanged`]), decided by the store.
23-//! replicas.
24 //!23 //!
25-//! Overlap is a **documented accepted race** (reviewed, not an oversight):24+//! Overlap therefore rests on the lock alone β€” it is a predicate over *other*
26-//! it is a predicate over *other* rows with no single row to key a counter or25+//! rows, with no single row to key a counter or a CAS on. That holds while
27-//! a CAS on, so across replicas two approvals decided in the same instant can26+//! every approving write takes [`APPOINTMENT_LOCK`]; one that skips it puts two
28-//! both land. Damage is one double-booked half-hour, visible to both parties27+//! meetings in one half-hour, so the rule is stated here rather than left to be
29-//! and fixable by cancelling either side β€” no money, no grade, no data loss.28+//! noticed. The damage if it ever happens is one double-booked half-hour,
30-//! Closing it would need a lease row per teacher taken on every approval.29+//! visible to both parties and fixable by cancelling either side β€” no money, no
30+//! grade, no data loss.
31 31
32 use std::sync::LazyLock;32 use std::sync::LazyLock;
33 33
@@ -51,13 +51,12 @@ use crate::validate::validate_required;
51 /// "Is this teacher (or this requester) already committed at that time" is a51 /// "Is this teacher (or this requester) already committed at that time" is a
52 /// predicate over other appointment rows, and SurrealDB does not conflict-check52 /// predicate over other appointment rows, and SurrealDB does not conflict-check
53 /// a cross-record read against a concurrent insert, so the check and its write53 /// a cross-record read against a concurrent insert, so the check and its write
54-/// have to be one atomic step *within this process*. Occupancy is no longer its54+/// have to be one atomic step, and this lock is the only thing that makes them
55-/// business: that is the slot's `occupied` counter, a conditional single-record55+/// one. Occupancy is no longer its business: that is the slot's `occupied`
56-/// write that holds between replicas too.56+/// counter, a conditional single-record write the store decides.
57 ///57 ///
58-/// Which leaves the accepted race the module doc records: this lock is58+/// So this is load-bearing, not a convenience: an approval path that does not
59-/// process-local, so two replicas can each approve an overlapping meeting in59+/// take it can double-book a teacher, as the module doc records.
60-/// the same instant. Visible to both parties, undone by cancelling either side.
61 ///60 ///
62 /// Lock order: taken *before* `cap`'s `CLAIM_LOCK` (booking claims a slot while61 /// Lock order: taken *before* `cap`'s `CLAIM_LOCK` (booking claims a slot while
63 /// holding this) and never the other way round. No path ever holds this62 /// holding this) and never the other way round. No path ever holds this
@@ -323,8 +322,8 @@ impl Appointment {
323 /// already taken, or when the requester is already committed elsewhere at322 /// already taken, or when the requester is already committed elsewhere at
324 /// that time. The slot is taken by [`cap::claim`] on the slot row β€” a323 /// that time. The slot is taken by [`cap::claim`] on the slot row β€” a
325 /// conditional single-record write, so two racing requests cannot both find324 /// conditional single-record write, so two racing requests cannot both find
326- /// it free however many replicas they arrive at; the requester's own overlap325+ /// it free however they interleave; the requester's own overlap is the
327- /// is the lock's part.326+ /// lock's part.
328 pub async fn book(327 pub async fn book(
329 slot: &AppointmentSlotId,328 slot: &AppointmentSlotId,
330 requester: &UserId,329 requester: &UserId,
@@ -876,15 +875,15 @@ mod tests {
876 assert_eq!(accepted.get_status(), AppointmentStatus::Approved);875 assert_eq!(accepted.get_status(), AppointmentStatus::Approved);
877 }876 }
878 877
879- /// The compare-and-set every decision writes through. `APPOINTMENT_LOCK` is878+ /// The compare-and-set every decision writes through β€” the guard against a
880- /// process-local, so with two replicas serving, nothing else stands between879+ /// decision built on a snapshot that has since moved, which no lock taken
881- /// an approval and a counter-proposal landing on the same booking β€” and the880+ /// after the read can catch. The interleaving that matters is the one a
882- /// interleaving that matters is the one a status-only guard would miss,881+ /// status-only guard would miss, since `propose` leaves a pending booking
883- /// since `propose` leaves a pending booking pending.882+ /// pending.
884 ///883 ///
885 /// Deliberately sequential: the mem engine answers `Ok` to a write it then884 /// Deliberately sequential: the mem engine answers `Ok` to a write it then
886 /// drops, so a `join!` of two decisions proves nothing. This drives the885 /// drops, so a `join!` of two decisions proves nothing. This drives the
887- /// primitive itself with the exact snapshot a second replica would hold.886+ /// primitive itself with the exact stale snapshot the race produces.
888 #[tokio::test]887 #[tokio::test]
889 async fn a_decision_built_on_a_stale_snapshot_never_lands() {888 async fn a_decision_built_on_a_stale_snapshot_never_lands() {
890 let db = crate::database::init_mem().await.unwrap();889 let db = crate::database::init_mem().await.unwrap();
@@ -947,7 +946,7 @@ mod tests {
947 }946 }
948 947
949 /// What the slot row itself says about being taken β€” the authority every948 /// What the slot row itself says about being taken β€” the authority every
950- /// gate now reads, in any replica.949+ /// gate now reads.
951 async fn occupied(slot: &AppointmentSlotId, db: &Database) -> i64 {950 async fn occupied(slot: &AppointmentSlotId, db: &Database) -> i64 {
952 let mut result = db951 let mut result = db
953 .query("SELECT VALUE (occupied ?? 0) FROM $slot")952 .query("SELECT VALUE (occupied ?? 0) FROM $slot")
@@ -959,9 +958,9 @@ mod tests {
959 result.take::<Vec<i64>>(0).unwrap()[0]958 result.take::<Vec<i64>>(0).unwrap()[0]
960 }959 }
961 960
962- /// The double-book race, as the *other replica* runs it: `APPOINTMENT_LOCK`961+ /// The double-book race with the lock taken out of the picture: a second
963- /// is process-local, so a second process's booking arrives at the database962+ /// booking arrives at the database with nothing between it and the slot but
964- /// with nothing between it and the slot but the claim's own `WHERE`. Driven963+ /// the claim's own `WHERE`, which is what must refuse it. Driven
965 /// through [`cap::claim`] directly rather than through a `join!`, since the964 /// through [`cap::claim`] directly rather than through a `join!`, since the
966 /// in-memory engine can drop one of two concurrent writes to a record and965 /// in-memory engine can drop one of two concurrent writes to a record and
967 /// still answer `Ok` β€” this asks the primitive the exact question the race966 /// still answer `Ok` β€” this asks the primitive the exact question the race
src/domain/appointment_slot.rsmodified+8 -8
@@ -5,7 +5,7 @@
5 //! cancel that settles it β€” so the slot frees itself again, and unlike a UNIQUE5 //! cancel that settles it β€” so the slot frees itself again, and unlike a UNIQUE
6 //! index it does not keep a dead booking's seat. Stored rather than counted6 //! index it does not keep a dead booking's seat. Stored rather than counted
7 //! from the [`Appointment`] rows because a conditional write on one row is the7 //! from the [`Appointment`] rows because a conditional write on one row is the
8-//! only guard that survives a second replica.8+//! only guard a concurrent booking cannot outrun.
9 //!9 //!
10 //! A recurring publish is expanded into concrete rows here, at write time,10 //! A recurring publish is expanded into concrete rows here, at write time,
11 //! sharing one `series` id β€” no recurrence rule is ever evaluated at read11 //! sharing one `series` id β€” no recurrence rule is ever evaluated at read
@@ -434,7 +434,7 @@ impl AppointmentSlot {
434 /// going away, so they cascade out with it, like [`Event::delete`]'s rows.434 /// going away, so they cascade out with it, like [`Event::delete`]'s rows.
435 ///435 ///
436 /// The guard is the delete's own `WHERE`, so no booking can land between a436 /// The guard is the delete's own `WHERE`, so no booking can land between a
437- /// check and the row going away β€” in this replica or another.437+ /// check and the row going away.
438 pub async fn delete(self, db: &Database) -> Result<AppointmentSlot, AppError> {438 pub async fn delete(self, db: &Database) -> Result<AppointmentSlot, AppError> {
439 Self::delete_free(std::slice::from_ref(&self.id), db).await?;439 Self::delete_free(std::slice::from_ref(&self.id), db).await?;
440 Ok(self)440 Ok(self)
@@ -459,7 +459,7 @@ impl AppointmentSlot {
459 /// Shared body of both deletes: drop every named slot, but only while its459 /// Shared body of both deletes: drop every named slot, but only while its
460 /// `occupied` counter says nobody is waiting on it β€” the delete's own460 /// `occupied` counter says nobody is waiting on it β€” the delete's own
461 /// `WHERE` is the guard, which is what makes it hold against a booking461 /// `WHERE` is the guard, which is what makes it hold against a booking
462- /// landing in another replica (a separate read-then-delete could not).462+ /// landing in the middle of it (a separate read-then-delete could not).
463 ///463 ///
464 /// All-or-nothing across the whole list: if fewer rows go than were named,464 /// All-or-nothing across the whole list: if fewer rows go than were named,
465 /// the transaction is thrown away, so a series never loses its free weeks465 /// the transaction is thrown away, so a series never loses its free weeks
@@ -753,10 +753,10 @@ mod tests {
753 );753 );
754 }754 }
755 755
756- /// The delete-vs-book race: a booking that lands in another replica between756+ /// The delete-vs-book race: a booking that lands between this delete's read
757- /// this delete's read and its write must still keep the slot alive, so the757+ /// and its write must still keep the slot alive, so the guard has to be the
758- /// guard has to be the delete's own `WHERE` β€” here driven by taking the seat758+ /// delete's own `WHERE` β€” here driven by taking the seat the way that
759- /// the way that replica would, with no booking row to read.759+ /// booking would, with no booking row to read.
760 ///760 ///
761 /// A series is all-or-nothing: one taken week refuses the whole publish,761 /// A series is all-or-nothing: one taken week refuses the whole publish,
762 /// and the free weeks must survive the refusal.762 /// and the free weeks must survive the refusal.
@@ -779,7 +779,7 @@ mod tests {
779 // A free slot goes, and its series is deletable while every week is free.779 // A free slot goes, and its series is deletable while every week is free.
780 assert!(slots[0].clone().delete(&db).await.is_ok());780 assert!(slots[0].clone().delete(&db).await.is_ok());
781 // The seat on the middle week is taken β€” no booking row, exactly as a781 // The seat on the middle week is taken β€” no booking row, exactly as a
782- // racing replica would leave it mid-flight.782+ // racing booking would leave it mid-flight.
783 assert!(783 assert!(
784 cap::claim(&slots[1].get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db)784 cap::claim(&slots[1].get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db)
785 .await785 .await
src/domain/bank_question.rsmodified+3 -2
@@ -387,8 +387,9 @@ impl BankQuestion {
387 /// field is re-stated from the snapshot, and the kind/choices/correct trio387 /// field is re-stated from the snapshot, and the kind/choices/correct trio
388 /// has to be (a text-only edit re-submits the stored options *with their388 /// has to be (a text-only edit re-submits the stored options *with their
389 /// ids* so each keeps its picture) β€” so without the compare-and-set the389 /// ids* so each keeps its picture) β€” so without the compare-and-set the
390- /// later writer silently reverts the earlier one. An in-process `RwLock`390+ /// later writer silently reverts the earlier one β€” and the window is a
391- /// only stopped that between requests of *one* replica.391+ /// database round trip wide, which is exactly how far apart two concurrent
392+ /// requests to this one process can sit.
392 ///393 ///
393 /// Every field the merge re-states is in the guard, which is the same list394 /// Every field the merge re-states is in the guard, which is the same list
394 /// the `SET` writes. `choices` is compared whole: its objects carry two395 /// the `SET` writes. `choices` is compared whole: its objects carry two
src/domain/cap.rsmodified+17 -17
@@ -1,17 +1,17 @@
1-//! Count caps that hold across replicas.1+//! Count caps the database enforces, not the process.
2 //!2 //!
3 //! Every "at most N children per parent" rule used to be a count-then-write3 //! Every "at most N children per parent" rule used to be a count-then-write
4 //! under a process-wide `Mutex`, because a `BEGIN…COMMIT` cannot enforce it:4 //! under a process-wide `Mutex`, because a `BEGIN…COMMIT` cannot enforce it:
5 //! SurrealDB does not conflict-check a cross-record `count()` against a5 //! SurrealDB does not conflict-check a cross-record `count()` against a
6 //! concurrent insert (write-skew), so two racing writers both saw a free slot.6 //! concurrent insert (write-skew), so two racing writers both saw a free slot.
7-//! A mutex only serializes the writers *inside one process*, and the backend7+//! A mutex serializes the writers, but only around whatever it wraps: every
8-//! now runs as two replicas against one database β€” so every one of those caps8+//! one of those caps held a lock across a database round trip, and the count it
9-//! was open again.9+//! was protecting was already a guess by the time the insert landed.
10 //!10 //!
11 //! The guard that does survive is a single-record conditional write: an11 //! The guard that does survive is a single-record conditional write: an
12 //! `UPDATE … SET n += 1 WHERE n < cap` on the *parent* row is atomic, so of N12 //! `UPDATE … SET n += 1 WHERE n < cap` on the *parent* row is atomic, so of N
13 //! concurrent claimers exactly `cap` get a non-empty result and the rest are13 //! concurrent claimers exactly `cap` get a non-empty result and the rest are
14-//! refused, whatever process they run in. The counter is therefore the14+//! refused, with no lock and no window. The counter is therefore the
15 //! authority on how many slots are taken, and the child rows follow it:15 //! authority on how many slots are taken, and the child rows follow it:
16 //! [`claim`] before the insert, [`release`] if the insert then fails, and a16 //! [`claim`] before the insert, [`release`] if the insert then fails, and a
17 //! decrement in the *same transaction* as every delete of a child row.17 //! decrement in the *same transaction* as every delete of a child row.
@@ -34,14 +34,13 @@ use crate::database::{Database, lost_the_race};
34 use crate::domain::timestamp::Timestamp;34 use crate::domain::timestamp::Timestamp;
35 use crate::error::AppError;35 use crate::error::AppError;
36 36
37-/// One writer per process at a time, over every counter.37+/// One counter writer at a time, over every counter.
38 ///38 ///
39 /// Not the cap β€” the `WHERE` clause is the cap, and it holds with or without39 /// Not the cap β€” the `WHERE` clause is the cap, and it holds with or without
40-/// this. What the lock buys is that a replica sends its counter writes one at a40+/// this. What the lock buys is that the process sends its counter writes one at
41-/// time, so the only contention the database ever sees on a parent row is41+/// a time, so the database never sees a parent row contended by every in-flight
42-/// between replicas: at most as many concurrent writers as there are processes,42+/// request at once. That keeps the optimistic retry loop below to a beat or two
43-/// instead of as many as there are in-flight requests. That keeps the optimistic43+/// rather than a storm.
44-/// retry loop below to a beat or two rather than a storm.
45 ///44 ///
46 /// It is also what keeps the test suite deterministic. The embedded in-memory45 /// It is also what keeps the test suite deterministic. The embedded in-memory
47 /// engine the tests run on does *not* have the real server's conflict46 /// engine the tests run on does *not* have the real server's conflict
@@ -75,7 +74,8 @@ pub(crate) async fn claim(
75 /// [`claim`], but only while `guard` β€” an extra predicate on that same parent74 /// [`claim`], but only while `guard` β€” an extra predicate on that same parent
76 /// row β€” also holds. A caller whose insert has a second precondition (a homework75 /// row β€” also holds. A caller whose insert has a second precondition (a homework
77 /// submission's file add is refused once the work is graded) gets both decided76 /// submission's file add is refused once the work is graded) gets both decided
78-/// by the one conditional write, instead of by a read a peer replica can outrun.77+/// by the one conditional write, instead of by a read a concurrent write can
78+/// outrun.
79 /// A miss is either "full" *or* "the guard failed"; the caller re-reads to tell79 /// A miss is either "full" *or* "the guard failed"; the caller re-reads to tell
80 /// them apart, and only to pick the message. `guard` is always an in-crate SQL80 /// them apart, and only to pick the message. `guard` is always an in-crate SQL
81 /// literal, never user input.81 /// literal, never user input.
@@ -131,11 +131,11 @@ pub(crate) enum Claimed<T> {
131 /// carries a deterministic id (one row per pair), two writers placing the *same*131 /// carries a deterministic id (one row per pair), two writers placing the *same*
132 /// pair both pass the claim β€” neither row exists yet β€” so on a tight cap the132 /// pair both pass the claim β€” neither row exists yet β€” so on a tight cap the
133 /// second is told "full" for a seat it was never going to need, and a release133 /// second is told "full" for a seat it was never going to need, and a release
134-/// afterwards is too late to unsay it. A process-wide mutex hid that inside one134+/// afterwards is too late to unsay it. A process-wide mutex could not hide that
135-/// process and hid nothing between two. Here the duplicate `CREATE` aborts the135+/// either: it is released around the very round trip the two writes race in.
136-/// transaction, which takes its own increment with it, and the caller reads the136+/// Here the duplicate `CREATE` aborts the transaction, which takes its own
137-/// winner's row back β€” so the counter never counts a row that does not exist,137+/// increment with it, and the caller reads the winner's row back β€” so the
138-/// in any replica.138+/// counter never counts a row that does not exist.
139 ///139 ///
140 /// The row is looked for *before* the seat is claimed, in that same140 /// The row is looked for *before* the seat is claimed, in that same
141 /// transaction, because on a tight cap the claim is the first thing to fail: a141 /// transaction, because on a tight cap the claim is the first thing to fail: a
src/domain/chatbot_message.rsmodified+6 -93
@@ -1,11 +1,9 @@
1 //! One turn of a chatbot thread. Both sides are persisted: the user's prompt1 //! One turn of a chatbot thread. Both sides are persisted: the user's prompt
2 //! lands `complete`, and the assistant's row is written `pending` *before* the2 //! lands `complete`, and the assistant's row is written `pending` *before* the
3-//! AI call so a reload never loses an answer in flight. A pending row is then3+//! AI call so a reload never loses an answer in flight. The task that owns the
4-//! a durable *job*: whichever replica holds a `chat.reply` worker claims it4+//! bridge round trip then flips it to `complete` (with the text) or `failed`
5-//! (`claim_pending`), dispatches it, and flips it to `complete` (with the text)5+//! (with a code), and the boot sweep in `database.rs` fails whatever a process
6-//! or `failed` (with a code). A claimer that dies loses its claim to the next6+//! death left behind past the staleness window.
7-//! sweep, and the boot sweep in `database.rs` fails whatever nobody could
8-//! answer inside the staleness window.
9 //!7 //!
10 //! `user_id` is duplicated from the thread onto every message so an8 //! `user_id` is duplicated from the thread onto every message so an
11 //! ownership check is one read, with no join.9 //! ownership check is one read, with no join.
@@ -16,8 +14,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
16 use ulid::{Generator, Ulid};14 use ulid::{Generator, Ulid};
17 15
18 use crate::constant::{16 use crate::constant::{
19- CHAT_MESSAGE_TABLE, CHATBOT_CLAIM, CHATBOT_CLAIM_BATCH, CHATBOT_CLAIM_RECLAIM_SECS,17+ CHAT_MESSAGE_TABLE, CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, MAX_ERROR_CODE_LEN,
20- CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, MAX_ERROR_CODE_LEN, STALE_ERROR_CODE,18+ STALE_ERROR_CODE,
21 };19 };
22 use crate::database::Database;20 use crate::database::Database;
23 use crate::domain::chatbot_thread::ChatbotThreadId;21 use crate::domain::chatbot_thread::ChatbotThreadId;
@@ -148,15 +146,6 @@ pub struct ChatbotMessage {
148 error_code: Option<String>,146 error_code: Option<String>,
149 created_at: Timestamp,147 created_at: Timestamp,
150 completed_at: Option<Timestamp>,148 completed_at: Option<Timestamp>,
151- /// Which replica's claim loop owes this turn an answer, and when it said
152- /// so. `None` means nobody has taken it; a claim older than
153- /// [`CHATBOT_CLAIM_RECLAIM_SECS`] is a claimer that died, and the turn goes
154- /// back on the queue (see [`ChatbotMessage::claim_pending`]).
155- ///
156- /// Never read by an HTTP handler and never in the DTO: whose process is
157- /// answering is deployment plumbing, not something a client can act on.
158- claimed_by: Option<String>,
159- claimed_at: Option<Timestamp>,
160 }149 }
161 150
162 impl ChatbotMessage {151 impl ChatbotMessage {
@@ -245,8 +234,6 @@ impl ChatbotMessage {
245 error_code: None,234 error_code: None,
246 created_at: now,235 created_at: now,
247 completed_at: Some(now),236 completed_at: Some(now),
248- claimed_by: None,
249- claimed_at: None,
250 },237 },
251 db,238 db,
252 )239 )
@@ -272,8 +259,6 @@ impl ChatbotMessage {
272 error_code: None,259 error_code: None,
273 created_at: Timestamp::now(),260 created_at: Timestamp::now(),
274 completed_at: None,261 completed_at: None,
275- claimed_by: None,
276- claimed_at: None,
277 },262 },
278 db,263 db,
279 )264 )
@@ -353,37 +338,6 @@ impl ChatbotMessage {
353 Ok(messages)338 Ok(messages)
354 }339 }
355 340
356- /// Take up to [`CHATBOT_CLAIM_BATCH`] unanswered turns for the claimant
357- /// `me`, and hand back the rows now owed an answer by *this* process.
358- ///
359- /// The queue read. It is deliberately blind to which capabilities exist
360- /// anywhere: the caller has already asked its own in-process registry
361- /// whether it can answer, and that registry β€” never the `ai_worker` gate β€”
362- /// is what makes a claim honest. Claiming a turn this process cannot
363- /// dispatch would park it for a whole reclaim horizon.
364- ///
365- /// A lost race is not an error: the guard is re-evaluated per record inside
366- /// the `UPDATE`, so a row a peer took simply does not come back. A
367- /// transaction conflict is the same verdict one layer down and yields an
368- /// empty batch rather than a failure β€” the next poll re-reads the queue,
369- /// which is also the retry the conflict asks for.
370- pub async fn claim_pending(me: &str, db: &Database) -> Result<Vec<ChatbotMessage>, AppError> {
371- let result = db
372- .query(CHATBOT_CLAIM)
373- .bind(("me", me.to_string()))
374- .bind(("batch", CHATBOT_CLAIM_BATCH))
375- .bind(("stale_ms", CHATBOT_PENDING_STALE_SECS * 1_000))
376- .bind(("reclaim_ms", CHATBOT_CLAIM_RECLAIM_SECS * 1_000))
377- .await
378- .and_then(|response| response.check());
379- match result {
380- // Statement 0 is the `LET`; the claimed rows are statement 1.
381- Ok(mut response) => Ok(response.take::<Vec<ChatbotMessage>>(1)?),
382- Err(err) if lost_the_claim(&err) => Ok(Vec::new()),
383- Err(err) => Err(err.into()),
384- }
385- }
386-
387 /// The user turn this reserved answer belongs to: the newest `user` row341 /// The user turn this reserved answer belongs to: the newest `user` row
388 /// written before it in the same thread.342 /// written before it in the same thread.
389 ///343 ///
@@ -478,23 +432,6 @@ impl ChatbotMessage {
478 }432 }
479 }433 }
480 434
481-/// A concurrent claim that the key-value layer decided against us, rather than
482-/// a broken query. Read from the *typed* surface: every engine's conflict
483-/// wording funnels into `QueryError::TransactionConflict` (surrealdb-core
484-/// 3.2.3 `err/to_types.rs:295`), where a substring match covers only whichever
485-/// wording the engine of the day happens to use.
486-///
487-/// Deliberately a second copy of `database::lost_the_race` rather than a shared
488-/// helper: that one is private to the boot election, which is owned elsewhere
489-/// and must not gain a caller. Five lines is the cheaper coupling.
490-fn lost_the_claim(err: &surrealdb::Error) -> bool {
491- use surrealdb::types::{ErrorDetails, QueryError};
492- matches!(
493- err.details(),
494- ErrorDetails::Query(Some(QueryError::TransactionConflict))
495- )
496-}
497-
498 #[cfg(test)]435 #[cfg(test)]
499 mod tests {436 mod tests {
500 use super::*;437 use super::*;
@@ -566,28 +503,6 @@ mod tests {
566 }503 }
567 }504 }
568 505
569- #[test]
570- fn the_claim_horizon_sits_between_the_inference_and_the_stale_window() {
571- // Both bounds are load-bearing and neither is decoration:
572- // below the AI request timeout, a reclaim fires while the first
573- // claimer is still legitimately waiting and two services answer the
574- // same turn; at or above the staleness horizon a turn stops being
575- // claimable before the reclaim could ever fire, so a dead claimer's
576- // turn is never retried at all.
577- use crate::constant::AI_DEFAULT_REQUEST_TIMEOUT_SECS;
578- assert!(
579- CHATBOT_CLAIM_RECLAIM_SECS > AI_DEFAULT_REQUEST_TIMEOUT_SECS as i64,
580- "a reclaim inside a legitimate inference double-answers the turn"
581- );
582- #[allow(clippy::assertions_on_constants)]
583- {
584- assert!(
585- CHATBOT_CLAIM_RECLAIM_SECS < CHATBOT_PENDING_STALE_SECS,
586- "a reclaim horizon past the staleness window can never fire"
587- );
588- }
589- }
590-
591 #[tokio::test]506 #[tokio::test]
592 async fn stale_pending_projects_as_failed() {507 async fn stale_pending_projects_as_failed() {
593 let aged = |secs: i64| {508 let aged = |secs: i64| {
@@ -602,8 +517,6 @@ mod tests {
602 error_code: None,517 error_code: None,
603 created_at: Timestamp::from_millis(Timestamp::now().as_millis() - secs * 1_000),518 created_at: Timestamp::from_millis(Timestamp::now().as_millis() - secs * 1_000),
604 completed_at: None,519 completed_at: None,
605- claimed_by: None,
606- claimed_at: None,
607 }520 }
608 .projected()521 .projected()
609 };522 };
src/domain/chatbot_thread.rsmodified+1 -1
@@ -107,7 +107,7 @@ impl ChatbotThread {
107 107
108 /// Start a thread unless `user` is already at the school's108 /// Start a thread unless `user` is already at the school's
109 /// `max_chatbot_threads`. The slot is taken by [`cap::claim`] on the user109 /// `max_chatbot_threads`. The slot is taken by [`cap::claim`] on the user
110- /// row β€” an atomic single-record write, so two replicas racing the same110+ /// row β€” an atomic single-record write, so two requests racing the same
111 /// user's last slot cannot both win, and the cap is read fresh so a111 /// user's last slot cannot both win, and the cap is read fresh so a
112 /// concurrent settings PATCH is respected.112 /// concurrent settings PATCH is respected.
113 pub async fn create_capped(113 pub async fn create_capped(
src/domain/course.rsmodified+3 -3
@@ -164,8 +164,8 @@ impl Course {
164 /// Create the course, claiming a reference on the term it links (if any)164 /// Create the course, claiming a reference on the term it links (if any)
165 /// *before* the row is written: the claim is a conditional write on the165 /// *before* the row is written: the claim is a conditional write on the
166 /// term row, so it fails when the term is already gone and it makes the166 /// term row, so it fails when the term is already gone and it makes the
167- /// term undeletable the instant this link exists β€” across replicas, which167+ /// term undeletable the instant this link exists, which the count-then-write
168- /// the mutex it replaced could not do inside one process.168+ /// mutex it replaced could not do.
169 pub async fn create(169 pub async fn create(
170 creator: &UserId,170 creator: &UserId,
171 title: CourseTitle,171 title: CourseTitle,
@@ -401,7 +401,7 @@ impl Course {
401 /// roster is read off the course's own `enrollment_count`, so the check and401 /// roster is read off the course's own `enrollment_count`, so the check and
402 /// the delete are one conditional write on one record β€” an enroll racing402 /// the delete are one conditional write on one record β€” an enroll racing
403 /// this either takes its seat first (and the delete is refused) or finds403 /// this either takes its seat first (and the delete is refused) or finds
404- /// the row gone (and is refused itself), in any replica. `Err(NotFound)`404+ /// the row gone (and is refused itself). `Err(NotFound)`
405 /// keeps the answer a concurrent *delete* used to get.405 /// keeps the answer a concurrent *delete* used to get.
406 pub async fn delete(self, db: &Database) -> Result<bool, AppError> {406 pub async fn delete(self, db: &Database) -> Result<bool, AppError> {
407 let mut result = db407 let mut result = db
src/domain/enrollment.rsmodified+2 -2
@@ -68,8 +68,8 @@ impl Enrollment {
68 /// the loser of the `CREATE` reads the winner's row back and returns it.68 /// the loser of the `CREATE` reads the winner's row back and returns it.
69 /// When the course carries a capacity, a full roster refuses new members69 /// When the course carries a capacity, a full roster refuses new members
70 /// (409) β€” the seat is taken by [`cap::claim`] on the course row, an atomic70 /// (409) β€” the seat is taken by [`cap::claim`] on the course row, an atomic
71- /// single-record conditional write, so the cap holds across replicas and71+ /// single-record conditional write, so the cap holds against concurrent
72- /// against a concurrent capacity PATCH alike. An already enrolled user is72+ /// enrolls and a concurrent capacity PATCH alike. An already enrolled user is
73 /// returned as-is even when the roster is full, and never charged a seat.73 /// returned as-is even when the roster is full, and never charged a seat.
74 /// The same claim is the delete guard's other half: it is refused outright74 /// The same claim is the delete guard's other half: it is refused outright
75 /// once the course row is gone, and while it holds a seat the course cannot75 /// once the course row is gone, and while it holds a seat the course cannot
src/domain/exam_attempt.rsmodified+4 -3
@@ -321,9 +321,10 @@ impl ExamAttempt {
321 /// [`Self::FROZEN_SLOT`] onwards (`BEGIN` and the `IF` take a slot each).321 /// [`Self::FROZEN_SLOT`] onwards (`BEGIN` and the `IF` take a slot each).
322 ///322 ///
323 /// This replaces a process-wide `EXAM_LOCK.write()` held across the check323 /// This replaces a process-wide `EXAM_LOCK.write()` held across the check
324- /// and the write. That lock served one process; the gate serves the324+ /// and the write. That lock ordered the two requests but still read the
325- /// database, so a question edit on replica A can no longer sail past an325+ /// attempt table a round trip before it wrote; the gate checks inside the
326- /// attempt started on replica B.326+ /// writing statement, so a question edit can no longer sail past an attempt
327+ /// that started in that gap.
327 //328 //
328 // ponytail: the count and a concurrent `CREATE exam_attempt` are still not329 // ponytail: the count and a concurrent `CREATE exam_attempt` are still not
329 // serialized against each other β€” SurrealDB does not conflict-check a330 // serialized against each other β€” SurrealDB does not conflict-check a
src/domain/exam_question.rsmodified+2 -2
@@ -398,7 +398,7 @@ impl ExamQuestion {
398 // is claimed before the child it caps ([`cap::claim`], here uncapped):398 // is claimed before the child it caps ([`cap::claim`], here uncapped):
399 // the subject delete is conditioned on that counter reading zero, so399 // the subject delete is conditioned on that counter reading zero, so
400 // the two contend on the subject record and a question can no longer400 // the two contend on the subject record and a question can no longer
401- // land on a subject another replica is deleting. A miss means the401+ // land on a subject a concurrent request is deleting. A miss means the
402 // subject is already gone β€” the same 400 the web layer's pre-flight402 // subject is already gone β€” the same 400 the web layer's pre-flight
403 // check answers with.403 // check answers with.
404 let counted = subject.record();404 let counted = subject.record();
@@ -423,7 +423,7 @@ impl ExamQuestion {
423 };423 };
424 // The freeze gate rides in the same transaction as the insert: a424 // The freeze gate rides in the same transaction as the insert: a
425 // question cannot appear under an exam somebody has already started,425 // question cannot appear under an exam somebody has already started,
426- // whichever replica the two requests hit.426+ // however the two requests interleave.
427 let inserted = async {427 let inserted = async {
428 let mut result = db428 let mut result = db
429 .query(ExamAttempt::unfrozen("CREATE $id CONTENT $question;"))429 .query(ExamAttempt::unfrozen("CREATE $id CONTENT $question;"))
src/domain/exam_result.rsmodified+2 -1
@@ -24,7 +24,8 @@ pub(crate) fn draft_error() -> AppError {
24 /// that name, and whether the school has retired it (see24 /// that name, and whether the school has retired it (see
25 /// [`crate::domain::cap`]). Keyed by the name itself: the kind is snapshotted25 /// [`crate::domain::cap`]). Keyed by the name itself: the kind is snapshotted
26 /// text on the exam, and this row is what makes "a kind nothing is graded under26 /// text on the exam, and this row is what makes "a kind nothing is graded under
27-/// may be removed" a decision two replicas can share.27+/// may be removed" a decision the database takes, not a count a concurrent mark
28+/// can invalidate.
28 pub(crate) fn kind_ref(kind: &str) -> RecordId {29 pub(crate) fn kind_ref(kind: &str) -> RecordId {
29 RecordId::new(KIND_REF_TABLE, kind)30 RecordId::new(KIND_REF_TABLE, kind)
30 }31 }
src/domain/fee_plan.rsmodified+3 -3
@@ -199,9 +199,9 @@ impl FeePlan {
199 199
200 /// Has this plan ever been assigned? The 409 guard on edit and delete.200 /// Has this plan ever been assigned? The 409 guard on edit and delete.
201 ///201 ///
202- /// A scan, and deliberately so: it races an assign landing in the same202+ /// A scan, and deliberately so: it races an assign landing in the gap
203- /// instant on the other replica, which can leave a plan edited *and*203+ /// between this read and the edit it licenses, which can leave a plan edited
204- /// assigned. Accepted β€” both versions of the plan were manager-approved,204+ /// *and* assigned. Accepted β€” both versions of the plan were manager-approved,
205 /// and the charges the assign raised are frozen copies either way, so no205 /// and the charges the assign raised are frozen copies either way, so no
206 /// money moves behind anyone's back.206 /// money moves behind anyone's back.
207 pub async fn has_assignments(id: &FeePlanId, db: &Database) -> Result<bool, AppError> {207 pub async fn has_assignments(id: &FeePlanId, db: &Database) -> Result<bool, AppError> {
src/domain/fee_plan_assignment.rsmodified+2 -2
@@ -4,8 +4,8 @@
4 //!4 //!
5 //! The row is keyed `<plan>_<student>`, and every charge it raises is keyed5 //! The row is keyed `<plan>_<student>`, and every charge it raises is keyed
6 //! from that same key plus the installment number, so the whole operation is6 //! from that same key plus the installment number, so the whole operation is
7-//! idempotent **by identity**: assigning twice writes nothing the second time7+//! idempotent **by identity**: assigning twice writes nothing the second time,
8-//! (on this replica or the other one), and an assign cut short after three of8+//! however the two requests interleave, and an assign cut short after three of
9 //! twelve charges landed completes itself when it is repeated. No scan decides9 //! twelve charges landed completes itself when it is repeated. No scan decides
10 //! "has this been billed yet?" β€” a scan can be slipped past by a concurrent10 //! "has this been billed yet?" β€” a scan can be slipped past by a concurrent
11 //! writer, and the cost of that mistake here is a double-billed family.11 //! writer, and the cost of that mistake here is a double-billed family.
src/domain/field_update.rsmodified+2 -1
@@ -63,7 +63,8 @@ impl FieldUpdate {
63 /// handler made against its snapshot is re-made by the database at write63 /// handler made against its snapshot is re-made by the database at write
64 /// time, against the row as it is *then*: two PATCHes each moving one end,64 /// time, against the row as it is *then*: two PATCHes each moving one end,
65 /// each fine on its own, cannot commit an inverted range between them. That65 /// each fine on its own, cannot commit an inverted range between them. That
66- /// is what an in-process `Mutex` used to buy, and this holds across replicas.66+ /// is what an in-process `Mutex` used to buy, without a window between the
67+ /// snapshot and the write for a concurrent request to slip into.
67 ///68 ///
68 /// Call it after the `.set()`s of both fields. A PATCH that moves neither69 /// Call it after the `.set()`s of both fields. A PATCH that moves neither
69 /// end emits no guard at all (nothing to race), matching the lock window it70 /// end emits no guard at all (nothing to race), matching the lock window it
src/domain/homework.rsmodified+1 -1
@@ -164,7 +164,7 @@ impl Homework {
164 // question's twin ([`crate::domain::exam_question::ExamQuestion`]): the164 // question's twin ([`crate::domain::exam_question::ExamQuestion`]): the
165 // subject delete is refused while this counter is non-zero, so the165 // subject delete is refused while this counter is non-zero, so the
166 // create and the delete contend on the subject record rather than on a166 // create and the delete contend on the subject record rather than on a
167- // cross-table count only one replica could see. A miss means the167+ // cross-table count neither of them sees the other move. A miss means the
168 // subject is already gone, which is the 400 the web layer's pre-flight168 // subject is already gone, which is the 400 the web layer's pre-flight
169 // check answers with.169 // check answers with.
170 let counted = subject.record();170 let counted = subject.record();
src/domain/homework_file.rsmodified+1 -1
@@ -126,7 +126,7 @@ impl HomeworkFile {
126 /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own126 /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own
127 /// wording). Both are decided by one [`cap::claim_when`] on the submission127 /// wording). Both are decided by one [`cap::claim_when`] on the submission
128 /// row β€” a conditional single-record write, the only guard that holds when128 /// row β€” a conditional single-record write, the only guard that holds when
129- /// the racing writers are in two replicas, the same story as129+ /// two uploads race, the same story as
130 /// `NoteFile::insert`. Which of the two conditions failed is read back130 /// `NoteFile::insert`. Which of the two conditions failed is read back
131 /// afterwards, off the losing path only, and only to pick the message.131 /// afterwards, off the losing path only, and only to pick the message.
132 pub async fn insert(self, db: &Database) -> Result<Option<HomeworkFile>, AppError> {132 pub async fn insert(self, db: &Database) -> Result<Option<HomeworkFile>, AppError> {
src/domain/homework_result.rsmodified+3 -3
@@ -124,9 +124,9 @@ impl HomeworkResult {
124 /// In the same transaction the grade *stamps* the student's submission124 /// In the same transaction the grade *stamps* the student's submission
125 /// ([`crate::constant::SUBMISSION_GRADED_FIELD`]), which is what freezes it:125 /// ([`crate::constant::SUBMISSION_GRADED_FIELD`]), which is what freezes it:
126 /// every student-side write to that row then fails its own126 /// every student-side write to that row then fails its own
127- /// `graded_by_result = NONE` condition, with no cross-table read for a peer127+ /// `graded_by_result = NONE` condition, with no cross-table read for a
128- /// replica to slip past. A submission that does not exist yet is left alone128+ /// concurrent write to slip past. A submission that does not exist yet is
129- /// β€” grading absent work must not conjure a hand-in (the report reads129+ /// left alone β€” grading absent work must not conjure a hand-in (the report reads
130 /// `submitted`/`missing`/`late` straight off that row).130 /// `submitted`/`missing`/`late` straight off that row).
131 //131 //
132 // ponytail: that one case keeps a residual race β€” a student's *first* hand-in132 // ponytail: that one case keeps a residual race β€” a student's *first* hand-in
src/domain/homework_submission.rsmodified+2 -2
@@ -116,7 +116,7 @@ impl HomeworkSubmission {
116 /// could let two concurrent first-submits pick different stamps and 500.116 /// could let two concurrent first-submits pick different stamps and 500.
117 ///117 ///
118 /// The `WHERE` is the freeze: [`SUBMISSION_OPEN_GUARD`] makes "not graded118 /// The `WHERE` is the freeze: [`SUBMISSION_OPEN_GUARD`] makes "not graded
119- /// yet" a condition of this very write instead of a read the grading replica119+ /// yet" a condition of this very write instead of a read a concurrent grade
120 /// can land behind. An absent row satisfies it (the stamp is `NONE` there120 /// can land behind. An absent row satisfies it (the stamp is `NONE` there
121 /// too), so a first submit still creates.121 /// too), so a first submit still creates.
122 pub async fn upsert(122 pub async fn upsert(
@@ -285,7 +285,7 @@ mod tests {
285 /// The freeze, as stored state rather than as a race: the grade stamps the285 /// The freeze, as stored state rather than as a race: the grade stamps the
286 /// submission row, and from then on the submission's own writes fail their286 /// submission row, and from then on the submission's own writes fail their
287 /// condition β€” no read of `homework_result` involved, which is what makes it287 /// condition β€” no read of `homework_result` involved, which is what makes it
288- /// hold when the grader is in the other replica. Un-grading clears the stamp288+ /// hold when the grade lands mid-request. Un-grading clears the stamp
289 /// and the row is writable again.289 /// and the row is writable again.
290 ///290 ///
291 /// Bite check: drop `WHERE graded_by_result = NONE` from291 /// Bite check: drop `WHERE graded_by_result = NONE` from
src/domain/meal_booking.rsmodified+3 -3
@@ -14,7 +14,7 @@
14 //! conditional single-record write ([`cap`]). Counting the rows instead is14 //! conditional single-record write ([`cap`]). Counting the rows instead is
15 //! write-skew β€” SurrealDB does not conflict-check a cross-record count15 //! write-skew β€” SurrealDB does not conflict-check a cross-record count
16 //! against a concurrent insert β€” and a process-wide lock around that count16 //! against a concurrent insert β€” and a process-wide lock around that count
17-//! only holds inside one replica, which the school no longer runs one of.17+//! is released around the very round trip the racing insert lands in.
18 //! Cancelling gives the seat back in the *same transaction* as the flip.18 //! Cancelling gives the seat back in the *same transaction* as the flip.
19 //! - **The price is claimed, not just read.** The seat is taken at the menu19 //! - **The price is claimed, not just read.** The seat is taken at the menu
20 //! revision the price was read at, in the same transaction as the row20 //! revision the price was read at, in the same transaction as the row
@@ -159,8 +159,8 @@ impl MealBooking {
159 /// at, so a dish added, re-priced or removed in that gap loses the claim and159 /// at, so a dish added, re-priced or removed in that gap loses the claim and
160 /// the whole decision is made again on fresh figures. What is frozen onto160 /// the whole decision is made again on fresh figures. What is frozen onto
161 /// the row is therefore always a price the menu genuinely carried at the161 /// the row is therefore always a price the menu genuinely carried at the
162- /// instant the seat was taken β€” the guarantee a lock could only give inside162+ /// instant the seat was taken β€” a guarantee a lock around the read could
163- /// one replica.163+ /// not give, since the price is read a round trip before the claim.
164 ///164 ///
165 /// The charge is appended after, keyed by (seat, attempt): eight concurrent165 /// The charge is appended after, keyed by (seat, attempt): eight concurrent
166 /// `POST`s of one seat hold one seat and write one charge line. The price is166 /// `POST`s of one seat hold one seat and write one charge line. The price is
src/domain/menu.rsmodified+11 -10
@@ -31,12 +31,13 @@ use crate::error::{AppError, ValidationError};
31 /// conflict-check). Publishing no longer needs it β€” the day+slot *is* the31 /// conflict-check). Publishing no longer needs it β€” the day+slot *is* the
32 /// record id β€” and neither does a booking, a menu delete, or the settings32 /// record id β€” and neither does a booking, a menu delete, or the settings
33 /// slot-removal guard: those went to conditional single-record writes33 /// slot-removal guard: those went to conditional single-record writes
34-/// ([`crate::domain::cap`]), which hold across replicas as this lock cannot.34+/// ([`crate::domain::cap`]), which the store decides as this lock cannot.
35 //35 //
36-// ponytail: the dish cap is therefore still replica-local β€” two replicas can36+// ponytail: the dish cap therefore rests on this lock alone β€” a dish write
37-// each add the 50th dish. Closing it is another `cap` counter (`dish_count` on37+// added without taking it reopens the count-then-write hole silently. Closing
38-// the menu row) plus its backfill; the ceiling is 51 dishes on a menu, not38+// it properly is another `cap` counter (`dish_count` on the menu row) plus its
39-// money or a seat, so it was not worth the column here.39+// backfill; the ceiling is 51 dishes on a menu, not money or a seat, so it was
40+// not worth the column here.
40 ///41 ///
41 /// A leaf: nothing held under it takes another lock.42 /// A leaf: nothing held under it takes another lock.
42 pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(());43 pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(());
@@ -46,7 +47,7 @@ pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(());
46 /// [`crate::domain::cap`]). The mirror of47 /// [`crate::domain::cap`]). The mirror of
47 /// [`kind_ref`](crate::domain::exam_result::kind_ref) for exam kinds: the slot48 /// [`kind_ref`](crate::domain::exam_result::kind_ref) for exam kinds: the slot
48 /// is snapshotted text on the menu, so this row is the only place the two49 /// is snapshotted text on the menu, so this row is the only place the two
49-/// tables' relationship is a single record two replicas can contend on.50+/// tables' relationship is a single record concurrent writes can contend on.
50 pub(crate) fn slot_ref(slot: &str) -> RecordId {51 pub(crate) fn slot_ref(slot: &str) -> RecordId {
51 RecordId::new(SLOT_REF_TABLE, slot)52 RecordId::new(SLOT_REF_TABLE, slot)
52 }53 }
@@ -56,7 +57,7 @@ pub struct MenuId(RecordId);
56 57
57 impl MenuId {58 impl MenuId {
58 /// The one id a menu for this day and slot can have. Deterministic on59 /// The one id a menu for this day and slot can have. Deterministic on
59- /// purpose (the `EnrollmentId` trick): two replicas publishing the same60+ /// purpose (the `EnrollmentId` trick): two requests publishing the same
60 /// meal race on a single record instead of writing two rows, so the loser61 /// meal race on a single record instead of writing two rows, so the loser
61 /// is told "already exists" by the store and answered the same 409 the62 /// is told "already exists" by the store and answered the same 409 the
62 /// pre-check gives. `date` is fixed-width `YYYY-MM-DD`, so the `_` joiner63 /// pre-check gives. `date` is fixed-width `YYYY-MM-DD`, so the `_` joiner
@@ -209,8 +210,8 @@ impl Menu {
209 /// Publish a menu. Refused (409) when the day+slot already carries one.210 /// Publish a menu. Refused (409) when the day+slot already carries one.
210 ///211 ///
211 /// The day and slot *are* the record id ([`MenuId::for_slot`]), so the212 /// The day and slot *are* the record id ([`MenuId::for_slot`]), so the
212- /// refusal is decided by the store rather than by a check a peer replica can213+ /// refusal is decided by the store rather than by a check a concurrent
213- /// outrun: two publishes of the same meal write one id, and the loser's214+ /// publish can outrun: two publishes of the same meal write one id, and the loser's
214 /// "already exists" becomes the same 409. The pre-check stays for the215 /// "already exists" becomes the same 409. The pre-check stays for the
215 /// ordinary case β€” and for menus published before ids were derived, whose216 /// ordinary case β€” and for menus published before ids were derived, whose
216 /// ULID key no new publish can collide with.217 /// ULID key no new publish can collide with.
@@ -326,7 +327,7 @@ impl Menu {
326 ///327 ///
327 /// Refused (409) while a seat is still held, and the *row itself* decides328 /// Refused (409) while a seat is still held, and the *row itself* decides
328 /// that: the delete carries the seat counter in its `WHERE`, so a booking329 /// that: the delete carries the seat counter in its `WHERE`, so a booking
329- /// landing in another replica at that instant either takes its seat before330+ /// landing at that instant either takes its seat before
330 /// the delete (which then finds a non-zero counter and refuses) or after it331 /// the delete (which then finds a non-zero counter and refuses) or after it
331 /// (and finds no menu). A read-then-delete pair had a window where both332 /// (and finds no menu). A read-then-delete pair had a window where both
332 /// happened β€” a paid seat on a menu that no longer exists.333 /// happened β€” a paid seat on a menu that no longer exists.
src/domain/note_file.rsmodified+3 -2
@@ -157,8 +157,9 @@ impl NoteFile {
157 /// already holds [`MAX_NOTE_FILES`]. The slot is taken by [`cap::claim`] on157 /// already holds [`MAX_NOTE_FILES`]. The slot is taken by [`cap::claim`] on
158 /// the note row: a `BEGIN…COMMIT` around a count can't enforce the cap158 /// the note row: a `BEGIN…COMMIT` around a count can't enforce the cap
159 /// (SurrealDB doesn't conflict-check a cross-record count against a159 /// (SurrealDB doesn't conflict-check a cross-record count against a
160- /// concurrent insert) and a process-wide mutex can't either once the160+ /// concurrent insert) and a process-wide mutex can't either, since it is
161- /// backend runs as two replicas β€” a conditional single-record write can.161+ /// released around the very round trip the insert races β€” a conditional
162+ /// single-record write can.
162 pub async fn insert(self, db: &Database) -> Result<NoteFile, AppError> {163 pub async fn insert(self, db: &Database) -> Result<NoteFile, AppError> {
163 let note = self.note.record();164 let note = self.note.record();
164 if !cap::claim(&note, NOTE_FILE_COUNT_FIELD, MAX_NOTE_FILES as i64, db).await? {165 if !cap::claim(&note, NOTE_FILE_COUNT_FIELD, MAX_NOTE_FILES as i64, db).await? {
src/domain/payment_ledger.rsmodified+28 -23
@@ -53,7 +53,7 @@
53 //! amount or against a *different* line is a `409`, never the stored line β€”53 //! amount or against a *different* line is a `409`, never the stored line β€”
54 //! returning it would hide a client bug behind a `201`.54 //! returning it would hide a client bug behind a `201`.
55 //!55 //!
56-//! **The over-payment cap is ADVISORY (accepted race).** [`PaymentLedger::credit`]56+//! **The over-payment cap is the lock's, not the database's.** [`PaymentLedger::credit`]
57 //! and [`PaymentLedger::refund`] refuse to take more than the line they target57 //! and [`PaymentLedger::refund`] refuse to take more than the line they target
58 //! is worth, by folding that line's whole subtree under [`PAYMENT_LOCK`]. The58 //! is worth, by folding that line's whole subtree under [`PAYMENT_LOCK`]. The
59 //! fold, rather than a sum of the direct children, because money handed back59 //! fold, rather than a sum of the direct children, because money handed back
@@ -63,22 +63,26 @@
63 //! landing between a payment's fold and its append would admit the payment63 //! landing between a payment's fold and its append would admit the payment
64 //! against room it no longer has.64 //! against room it no longer has.
65 //!65 //!
66-//! That check is a count-then-write across rows, and SurrealDB does not conflict-check66+//! The lock is what makes that check mean anything, and it is load-bearing:
67-//! a cross-record read against a concurrent insert (the write-skew this repo has67+//! the fold is a count-then-write across rows, and SurrealDB does not
68-//! hit before), while the lock is *process-local* and **two replicas serve in68+//! conflict-check a cross-record read against a concurrent insert (the
69-//! production** β€” so two payments recorded in the same instant on different69+//! write-skew this repo has hit before), so a fold left unserialized would let
70-//! replicas can together overshoot a charge. Accepted deliberately: the outcome70+//! two payments both see room and both take it. Running as one process buys
71-//! is an over-paid charge, visible in the statement and undone by a refund,71+//! nothing on its own β€” two request tasks interleave across the fold's `await`
72-//! and both entries are true records of money that really arrived. A CAS72+//! exactly as two machines would. The cap therefore holds only for as long as
73-//! counter row was rejected β€” refunding would have to decrement it, which is a73+//! *every* write that moves this arithmetic is taken under [`PAYMENT_LOCK`];
74-//! stored derived balance by another name.74+//! a future append that skips it re-opens the hole silently, which is why the
75+//! rule is stated here rather than left to be noticed. If an over-payment ever
76+//! does land it is not a crisis β€” an over-paid charge is plainly visible in the
77+//! statement and undone by appending a refund, and both entries are true
78+//! records of money that really arrived. A CAS counter row was rejected β€”
79+//! refunding would have to decrement it, which is a stored derived balance by
80+//! another name.
75 //!81 //!
76-//! The same replica boundary bounds the `request_key` mismatch `409`: it is a82+//! The `request_key` mismatch `409` rides on the same lock: it is a
77-//! read-then-compare, so if two *first-time* posts of one key with different83+//! read-then-compare, and it is read *inside* the lock, so two first-time posts
78-//! amounts land on two replicas at once, the loser is handed the winner's line84+//! of one key with different amounts cannot both walk past it. One line, one
79-//! as a `201` instead of the conflict. One line, one amount, no double charge β€”85+//! amount, no double charge, and the "you reused a key" diagnostic is exact.
80-//! the guarantee that matters holds; only the "you reused a key" diagnostic is
81-//! best-effort, and every retry after either has landed reports it correctly.
82 86
83 use surrealdb::types::{AlreadyExistsError, RecordId, RecordIdKey, SurrealValue};87 use surrealdb::types::{AlreadyExistsError, RecordId, RecordIdKey, SurrealValue};
84 use tokio::sync::Mutex;88 use tokio::sync::Mutex;
@@ -97,11 +101,12 @@ use crate::domain::timestamp::Timestamp;
97 use crate::domain::user::UserId;101 use crate::domain::user::UserId;
98 use crate::error::{AppError, ValidationError};102 use crate::error::{AppError, ValidationError};
99 103
100-/// Serializes the advisory over-payment check, the append it authorizes, and104+/// Serializes the over-payment check, the append it authorizes, and every
101-/// every other append that changes the arithmetic that check does β€” nothing105+/// other append that changes the arithmetic that check does β€” nothing else.
102-/// else. Process-local, hence the accepted cross-replica race the module doc106+/// It is the whole guarantee behind that cap, not a convenience: the fold it
103-/// records. Held across no other lock, and no other lock is taken while it is107+/// protects is a cross-record read the database will not conflict-check
104-/// held.108+/// against a concurrent insert. Held across no other lock, and no other lock is
109+/// taken while it is held.
105 pub(crate) static PAYMENT_LOCK: Mutex<()> = Mutex::const_new(());110 pub(crate) static PAYMENT_LOCK: Mutex<()> = Mutex::const_new(());
106 111
107 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]112 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
@@ -132,7 +137,7 @@ impl PaymentLedgerId {
132 }137 }
133 138
134 /// The one reversal a line may ever have β€” a retried undo appends nothing139 /// The one reversal a line may ever have β€” a retried undo appends nothing
135- /// the second time, on this replica or any other.140+ /// the second time β€” the id decides that, not a scan.
136 pub fn for_reversal(line: &PaymentLedgerId) -> Self {141 pub fn for_reversal(line: &PaymentLedgerId) -> Self {
137 Self(RecordId::new(142 Self(RecordId::new(
138 PAYMENT_LEDGER_TABLE,143 PAYMENT_LEDGER_TABLE,
@@ -569,7 +574,7 @@ impl PaymentLedger {
569 /// subtree [`PaymentLedger::applied_to`] folds, so one landing between a574 /// subtree [`PaymentLedger::applied_to`] folds, so one landing between a
570 /// concurrent payment's fold and its append would let that payment be575 /// concurrent payment's fold and its append would let that payment be
571 /// admitted against room it no longer has. The lock is what makes the cap576 /// admitted against room it no longer has. The lock is what makes the cap
572- /// exact within a replica, which is the promise this module's doc makes.577+ /// exact, which is the promise this module's doc makes.
573 pub async fn reversal(578 pub async fn reversal(
574 line: &PaymentLedger,579 line: &PaymentLedger,
575 note: Option<LedgerNote>,580 note: Option<LedgerNote>,
src/domain/registration.rsmodified+2 -2
@@ -68,8 +68,8 @@ impl Registration {
68 /// existing row back untouched β€” a true no-op that never counts against68 /// existing row back untouched β€” a true no-op that never counts against
69 /// the cap and never rewrites who placed them. The seat is taken by69 /// the cap and never rewrites who placed them. The seat is taken by
70 /// [`cap::claim`] on the event row β€” an atomic single-record conditional70 /// [`cap::claim`] on the event row β€” an atomic single-record conditional
71- /// write, so neither a racing registration in another replica nor a71+ /// write, so neither a racing registration nor a concurrent
72- /// concurrent capacity/audience/schedule PATCH can over-admit.72+ /// capacity/audience/schedule PATCH can over-admit.
73 pub async fn register(73 pub async fn register(
74 event: &EventId,74 event: &EventId,
75 user: &UserId,75 user: &UserId,
src/domain/subject.rsmodified+4 -4
@@ -170,10 +170,10 @@ impl Subject {
170 /// delete with a 409. That refusal is the delete's own `WHERE`, read off the170 /// delete with a 409. That refusal is the delete's own `WHERE`, read off the
171 /// two reference counters this row carries171 /// two reference counters this row carries
172 /// ([`crate::constant::SUBJECT_QUESTION_COUNT_FIELD`] and its homework172 /// ([`crate::constant::SUBJECT_QUESTION_COUNT_FIELD`] and its homework
173- /// twin), which is what makes it hold when the question is created on173+ /// twin), which is what makes it hold against a question created by a
174- /// another replica β€” the cross-table `SELECT … LIMIT 1` it replaces was a174+ /// request racing this one β€” the cross-table `SELECT … LIMIT 1` it replaces
175- /// count-then-delete no transaction serializes, pinned by three175+ /// was a count-then-delete no transaction serializes, pinned by three
176- /// process-wide locks that only ever served one process.176+ /// process-wide locks that could not cover the round trip between them.
177 ///177 ///
178 /// Which of the two blocked is read off the counters *before* the delete,178 /// Which of the two blocked is read off the counters *before* the delete,
179 /// purely to pick the message; the decision itself was already made by the179 /// purely to pick the message; the decision itself was already made by the
src/lib.rsmodified+3 -14
@@ -58,7 +58,7 @@ use crate::state::AppState;
58 (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"),58 (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"),
59 (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"),59 (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"),
60 (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"),60 (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"),
61- (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 `<target>_k_<key>` (`_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 `<line>_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"),61+ (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 `<target>_k_<key>` (`_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 `<line>_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"),
62 (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"),62 (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"),
63 (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+"),63 (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+"),
64 (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"),64 (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 {
88 /// Also serves interactive docs: Swagger UI at `/swagger`, raw spec at88 /// Also serves interactive docs: Swagger UI at `/swagger`, raw spec at
89 /// `/api-docs/openapi.json`. Root `/` mirrors the health probe.89 /// `/api-docs/openapi.json`. Root `/` mirrors the health probe.
90 pub fn build_router(state: AppState) -> Router {90 pub fn build_router(state: AppState) -> Router {
91- // The AI bridge's two database-backed halves, wired here because this is
92- // the only place holding the bridge and the database at once: the
93- // `ai_worker` gate (so peers can see the workers this process holds) and
94- // this replica's chat claim loop. `attach_presence` returning `true` means
95- // this call was the first, which is what keeps it to one loop per process.
96- if let Some(bridge) = state.ai.clone()
97- && bridge.attach_presence(state.db.clone())
98- {
99- web::chatbot::spawn_claim_loop(bridge, state.db.clone());
100- }
101-
102 let (router, api) = OpenApiRouter::with_openapi(ApiDoc::openapi())91 let (router, api) = OpenApiRouter::with_openapi(ApiDoc::openapi())
103 .route("/", get(health))92 .route("/", get(health))
104 .routes(routes!(health))93 .routes(routes!(health))
@@ -136,9 +125,9 @@ pub fn build_router(state: AppState) -> Router {
136 state.rate_limit.api_per_minute,125 state.rate_limit.api_per_minute,
137 state.rate_limit.trust_proxy,126 state.rate_limit.trust_proxy,
138 );127 );
139- // Every tier's budget is fleet-wide, not per process (see128+ // Every tier's budget outlives the process it was spent in (see
140 // [`rate_limit::RateLimiter::share`]). The chatbot tier is shared here too129 // [`rate_limit::RateLimiter::share`]). The chatbot tier is shared here too
141- // rather than in `main`, so it holds in every process that serves it.130+ // rather than in `main`, so a router built anywhere gets the same behaviour.
142 api_limiter.share("api", state.db.clone(), state.db_up.clone());131 api_limiter.share("api", state.db.clone(), state.db_up.clone());
143 state132 state
144 .chatbot_limit133 .chatbot_limit
src/main.rsmodified+2 -2
@@ -19,8 +19,8 @@ async fn main() -> anyhow::Result<()> {
19 // Hash the login decoy now, so the first unknown-username login is not the19 // Hash the login decoy now, so the first unknown-username login is not the
20 // one request that pays for it (see `PasswordHash::prewarm_decoy`).20 // one request that pays for it (see `PasswordHash::prewarm_decoy`).
21 hezarfen_backend::domain::user::PasswordHash::prewarm_decoy();21 hezarfen_backend::domain::user::PasswordHash::prewarm_decoy();
22- // Schema *and* the admin seed: both are boot work that must happen once22+ // Connects, migrates the schema and seeds the admin β€” all of it idempotent
23- // across overlapping processes, so both live behind the boot election.23+ // and unconditional on every boot.
24 let db = database::init(&cfg).await?;24 let db = database::init(&cfg).await?;
25 let db_up = DbHealth::default();25 let db_up = DbHealth::default();
26 keepalive(db.clone(), db_up.clone());26 keepalive(db.clone(), db_up.clone());
src/migration_sql.rsmodified+42 -48
@@ -4,8 +4,8 @@
4 //! ~700 lines of schema, and left in the constants file they buried the4 //! ~700 lines of schema, and left in the constants file they buried the
5 //! validation bounds that file exists to hold. Nothing else changed β€” they are5 //! validation bounds that file exists to hold. Nothing else changed β€” they are
6 //! still `pub const`, still the only migration text, and6 //! still `pub const`, still the only migration text, and
7-//! [`crate::database::migrate`] and [`crate::database::migration_fingerprint`]7+//! [`crate::database::migrate`] still reads [`MIGRATION_BATCHES`] and nothing
8-//! still both read [`MIGRATION_BATCHES`] and nothing else.8+//! else.
9 //!9 //!
10 //! Numbers stay in `constant.rs`: `tests/limits_completeness.rs` sweeps `src/`10 //! Numbers stay in `constant.rs`: `tests/limits_completeness.rs` sweeps `src/`
11 //! for stray bounds, and a bound hidden here would reach neither `GET /limits`11 //! for stray bounds, and a bound hidden here would reach neither `GET /limits`
@@ -20,6 +20,9 @@
20 /// UNSET included. So the value has to go while its definition is still20 /// UNSET included. So the value has to go while its definition is still
21 /// standing. Runs as its own query for the usual reason (see `MIGRATION`).21 /// standing. Runs as its own query for the usual reason (see `MIGRATION`).
22 ///22 ///
23+/// `chatbot_message.claimed_by` / `claimed_at` (retired 2026-07-30 with the
24+/// chat claim queue) are the same story, one table over.
25+///
23 /// The table-exists guard is load-bearing: on a fresh database `MIGRATION` has26 /// The table-exists guard is load-bearing: on a fresh database `MIGRATION` has
24 /// not run yet, and an UPDATE against an undefined table is an error, not an27 /// not run yet, and an UPDATE against an undefined table is an error, not an
25 /// empty result. On a database that has the table but never had the column the28 /// empty result. On a database that has the table but never had the column the
@@ -28,6 +31,10 @@ pub const PRE_REPAIR: &str = "
28 IF 'exam_question' IN object::keys((INFO FOR DB).tables) {31 IF 'exam_question' IN object::keys((INFO FOR DB).tables) {
29 UPDATE exam_question UNSET source_bank WHERE source_bank != NONE32 UPDATE exam_question UNSET source_bank WHERE source_bank != NONE
30 };33 };
34+ IF 'chatbot_message' IN object::keys((INFO FOR DB).tables) {
35+ UPDATE chatbot_message UNSET claimed_by, claimed_at
36+ WHERE claimed_by != NONE OR claimed_at != NONE
37+ };
31 ";38 ";
32 39
33 /// SCHEMAFULL schema: every column is typed, references use `record<..>`.40 /// SCHEMAFULL schema: every column is typed, references use `record<..>`.
@@ -116,26 +123,26 @@ pub const MIGRATION: &str = "
116 DEFINE FIELD IF NOT EXISTS error_code ON chatbot_message TYPE option<string>;123 DEFINE FIELD IF NOT EXISTS error_code ON chatbot_message TYPE option<string>;
117 DEFINE FIELD IF NOT EXISTS created_at ON chatbot_message TYPE int READONLY;124 DEFINE FIELD IF NOT EXISTS created_at ON chatbot_message TYPE int READONLY;
118 DEFINE FIELD IF NOT EXISTS completed_at ON chatbot_message TYPE option<int>;125 DEFINE FIELD IF NOT EXISTS completed_at ON chatbot_message TYPE option<int>;
119- -- The claim (2026-07-27): which replica's claim loop owes this turn an126+ -- The chat claim queue is gone (2026-07-30): one process answers its own
120- -- answer, and when it said so. Absent = nobody has taken it yet; a claim127+ -- turns, so nothing claims them. PRE_REPAIR clears the values first β€”
121- -- older than CHATBOT_CLAIM_RECLAIM_SECS is a dead claimer and the turn is128+ -- SCHEMAFULL rejects every write to a row still storing a column that no
122- -- taken back (see `CHATBOT_CLAIM`).129+ -- longer exists.
123- DEFINE FIELD IF NOT EXISTS claimed_by ON chatbot_message TYPE option<string>;130+ REMOVE FIELD IF EXISTS claimed_by ON TABLE chatbot_message;
124- DEFINE FIELD IF NOT EXISTS claimed_at ON chatbot_message TYPE option<int>;131+ REMOVE FIELD IF EXISTS claimed_at ON TABLE chatbot_message;
125 DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at;132 DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at;
126 DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id;133 DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id;
127- -- The claim loop's sweep: every poll asks for pending rows by age.134+ -- The boot sweep asks for pending rows by age.
128 DEFINE INDEX IF NOT EXISTS chatbot_message_status_created ON chatbot_message FIELDS status, created_at;135 DEFINE INDEX IF NOT EXISTS chatbot_message_status_created ON chatbot_message FIELDS status, created_at;
129 136
130- -- Which AI workers are connected to *any* replica (2026-07-27). The GATE137+ -- The AI worker presence table is gone (2026-07-30): one process holds
131- -- and nothing else: a row only says a socket existed somewhere at138+ -- every worker socket, so its in-process registry is the whole truth and
132- -- `seen_at`, so it may spare a user a 503 but must never pick who answers139+ -- nothing needed publishing.
133- -- β€” that is the in-process registry's call. Heartbeated by the replica140+ REMOVE TABLE IF EXISTS ai_worker;
134- -- owning the connection; a stale row is ignored by the read and swept.141+
135- DEFINE TABLE IF NOT EXISTS ai_worker SCHEMAFULL;142+ -- The elected-boot lease is gone with it (2026-07-30): one process migrates,
136- DEFINE FIELD IF NOT EXISTS service ON ai_worker TYPE string;143+ -- so nothing takes the lock. SCHEMALESS and read by nobody, so unlike the
137- DEFINE FIELD IF NOT EXISTS capabilities ON ai_worker TYPE array<string>;144+ -- claim columns it needs no PRE_REPAIR β€” the table just goes.
138- DEFINE FIELD IF NOT EXISTS seen_at ON ai_worker TYPE int;145+ REMOVE TABLE IF EXISTS migration_lock;
139 146
140 -- How much of a rate-limit budget the whole fleet has spent in one wall147 -- How much of a rate-limit budget the whole fleet has spent in one wall
141 -- window (2026-07-27). One row per tier+client+window, id-keyed so every148 -- window (2026-07-27). One row per tier+client+window, id-keyed so every
@@ -740,33 +747,23 @@ pub const BACKFILL: &str = "
740 -- which is what they were presented as all along.747 -- which is what they were presented as all along.
741 UPDATE chatbot_message SET truncated = false WHERE truncated = NONE;748 UPDATE chatbot_message SET truncated = false WHERE truncated = NONE;
742 749
743- -- An assistant turn is answered by a claim loop in some replica's process,750+ -- An assistant turn is answered by a task in this process, so a restart can
744- -- so a restart can leave its row `pending` with nobody left to complete it.751+ -- leave its row `pending` with nobody left to complete it. Only rows past
745- -- Only rows past the stale horizon ($stale_ms, from752+ -- the stale horizon ($stale_ms, from `CHATBOT_PENDING_STALE_SECS`) are
746- -- `CHATBOT_PENDING_STALE_SECS`) are certainly abandoned though: a young one753+ -- certainly abandoned though: a young one may still be being answered on
747- -- may still be being answered on the other side of the AI bridge, and a754+ -- the other side of the AI bridge, and a deploy must not shoot down a turn
748- -- deploy must not shoot down a turn dispatched seconds ago. Nothing is lost755+ -- dispatched seconds ago. Nothing is lost by waiting β€” a reader already
749- -- by waiting β€” a reader already presents an over-age `pending` row as756+ -- presents an over-age `pending` row as failed, and the next boot sweeps
750- -- failed, and the next boot sweeps for real whatever crossed the horizon in757+ -- for real whatever crossed the horizon in the meantime.
751- -- the meantime.
752- --
753- -- Claim-aware since 2026-07-27, because the sweep is no longer school-wide
754- -- truth: under N replicas the row may belong to a *live peer's* claim loop,
755- -- and failing it here would shoot down another process's in-flight turn.
756- -- So a claim restamped within the window is left alone. Both disjuncts
757- -- matter β€” `claimed_by = NONE` alone would strand every row whose claimer
758- -- died, which is the one case the sweep exists for.
759 --758 --
760- -- The claim age is measured against $stale_ms rather than759+ -- The claim half of this guard went with the claim queue (2026-07-30): it
761- -- CHATBOT_CLAIM_RECLAIM_SECS only because the boot binds one horizon (see760+ -- only ever spared a row a *live peer* was answering, and there is no peer.
762- -- `database::migration_binds`); erring long is the safe direction β€” the761+ -- The rows selected are otherwise the same ones β€” an unclaimed row past the
763- -- cost is that a row claimed just before it aged out waits one more boot762+ -- horizon was always swept, and a claim of this process's own could not
764- -- for its durable stamp, while readers have shown it failed all along.763+ -- outlive the process whose boot is running this.
765 UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted',764 UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted',
766 completed_at = time::unix(time::now()) * 1000765 completed_at = time::unix(time::now()) * 1000
767- WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms766+ WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms;
768- AND (claimed_by = NONE
769- OR claimed_at < time::unix(time::now()) * 1000 - $stale_ms);
770 767
771 -- Promotion out of student now deletes the user's enrollments (2026-07-18);768 -- Promotion out of student now deletes the user's enrollments (2026-07-18);
772 -- this sweeps rows promoted before that fix. A deleted user reads as769 -- this sweeps rows promoted before that fix. A deleted user reads as
@@ -953,10 +950,7 @@ pub const BACKFILL: &str = "
953 ";950 ";
954 951
955 /// The migration batches, in the order a boot applies them β€” and the *only*952 /// The migration batches, in the order a boot applies them β€” and the *only*
956-/// list of them. [`crate::database::migrate`] runs exactly these and953+/// list of them. [`crate::database::migrate`] runs exactly these. They stay
957-/// [`crate::database::migration_fingerprint`] hashes exactly these, so a fourth954+/// three separate queries: statements in one batch see the schema as it stood
958-/// batch cannot be executed without changing the fingerprint that decides955+/// when the batch started (see `MIGRATION`).
959-/// whether a peer's schema is ours. They stay three separate queries: statements
960-/// in one batch see the schema as it stood when the batch started (see
961-/// `MIGRATION`).
962 pub const MIGRATION_BATCHES: [&str; 3] = [PRE_REPAIR, MIGRATION, BACKFILL];956 pub const MIGRATION_BATCHES: [&str; 3] = [PRE_REPAIR, MIGRATION, BACKFILL];
src/rate_limit.rsmodified+21 -22
@@ -25,23 +25,22 @@
25 //! an accepted trade-off for an implementation simple enough to read in one25 //! an accepted trade-off for an implementation simple enough to read in one
26 //! sitting; argon2 keeps each allowed login attempt expensive anyway.26 //! sitting; argon2 keeps each allowed login attempt expensive anyway.
27 //!27 //!
28-//! # Across replicas28+//! # The shared window
29 //!29 //!
30-//! The counters above are per process, and the backend runs as two replicas β€”30+//! The counters above are per process. [`RateLimiter::share`] also carries them
31-//! so a client hitting both got twice its budget. [`RateLimiter::share`] closes31+//! through the process: a background task folds each bucket's new admits into
32-//! that: a background task folds each bucket's new admits into one shared row32+//! one shared row per tier + client + wall window (`rate_limit`, see
33-//! per tier + client + wall window (`rate_limit`, see
34 //! [`crate::constant::RATE_LIMIT_TABLE`]) every33 //! [`crate::constant::RATE_LIMIT_TABLE`]) every
35-//! [`crate::constant::RATE_SYNC_INTERVAL_SECS`], and the fleet-wide total that34+//! [`crate::constant::RATE_SYNC_INTERVAL_SECS`], and the stored total that
36-//! comes back caps what the local bucket admits for the rest of that window.35+//! comes back caps what the local bucket admits for the rest of that window β€”
36+//! so a restart mid-window does not hand every client a fresh budget.
37 //!37 //!
38 //! Admission itself stays in memory and stays synchronous β€” no request ever38 //! Admission itself stays in memory and stays synchronous β€” no request ever
39 //! waits on the database to be let in, and a database that is down or slow39 //! waits on the database to be let in, and a database that is down or slow
40 //! costs nothing but the sharing (the tiers fall back to their local budgets40 //! costs nothing but the sharing (the tiers fall back to their local budgets
41-//! rather than failing anyone). The cost is a lag: within one interval a41+//! rather than failing anyone). The cost is a lag: a process that has just
42-//! replica can spend up to its own full budget before the shared total tells42+//! started can spend up to its own full budget for one interval before the
43-//! it to stop, so the fleet's worst case is `replicas Γ— max` for one interval43+//! shared total tells it to stop.
44-//! and `max` from then on.
45 44
46 use std::collections::HashMap;45 use std::collections::HashMap;
47 use std::hash::Hash;46 use std::hash::Hash;
@@ -111,7 +110,7 @@ struct Bucket {
111 /// row. Never above `count`, so `count - pushed` is what is still ours to110 /// row. Never above `count`, so `count - pushed` is what is still ours to
112 /// report.111 /// report.
113 pushed: u32,112 pushed: u32,
114- /// The fleet-wide total the last sync read back β€” everyone's admits,113+ /// The stored total the last sync read back β€” every admit in this window,
115 /// `pushed` included. Zero until a sync lands, which is what makes an114 /// `pushed` included. Zero until a sync lands, which is what makes an
116 /// unshared limiter behave exactly like the local-only one it replaced.115 /// unshared limiter behave exactly like the local-only one it replaced.
117 remote: u32,116 remote: u32,
@@ -133,9 +132,9 @@ impl Bucket {
133 }132 }
134 }133 }
135 134
136- /// Requests the whole fleet has spent in this window as far as this process135+ /// Requests spent in this window as far as this process can tell: what the
137- /// can tell: what every replica had reported at the last sync, plus our own136+ /// shared row held at the last sync β€” this process's earlier life included β€”
138- /// admits since. Equals `count` until a sync lands.137+ /// plus our own admits since. Equals `count` until a sync lands.
139 fn spent(&self) -> u32 {138 fn spent(&self) -> u32 {
140 self.remote.saturating_add(self.count - self.pushed)139 self.remote.saturating_add(self.count - self.pushed)
141 }140 }
@@ -259,9 +258,9 @@ impl<K> RateLimiter<K>
259 where258 where
260 K: Eq + Hash + Clone + std::fmt::Display + Send + Sync + 'static,259 K: Eq + Hash + Clone + std::fmt::Display + Send + Sync + 'static,
261 {260 {
262- /// Make this tier's budget fleet-wide: every261+ /// Make this tier's budget outlive the process: every
263- /// [`RATE_SYNC_INTERVAL_SECS`] a background task reports what this replica262+ /// [`RATE_SYNC_INTERVAL_SECS`] a background task reports what this limiter
264- /// has admitted and reads back what everyone has, which caps further local263+ /// has admitted and reads back the window's total, which caps further local
265 /// admits in the same window (see the module docs).264 /// admits in the same window (see the module docs).
266 ///265 ///
267 /// `tier` names the counter's namespace in the shared table β€” two limiters266 /// `tier` names the counter's namespace in the shared table β€” two limiters
@@ -309,7 +308,7 @@ where
309 }308 }
310 309
311 /// Fold every live bucket's new admits into its shared row and take the310 /// Fold every live bucket's new admits into its shared row and take the
312-/// fleet-wide total back.311+/// window's total back.
313 ///312 ///
314 /// One statement per bucket in one query, and each statement is its own313 /// One statement per bucket in one query, and each statement is its own
315 /// transaction β€” so a statement that loses a write race fails alone. Its bucket314 /// transaction β€” so a statement that loses a write race fails alone. Its bucket
@@ -392,9 +391,9 @@ async fn sync_once<K: Eq + Hash + Clone + std::fmt::Display>(
392 }391 }
393 }392 }
394 393
395-/// The wall-clock window a shared row is keyed by, aligned so every replica394+/// The wall-clock window a shared row is keyed by, aligned so a restarted
396-/// agrees on it β€” the local windows cannot be used for this, since each one395+/// process lands on the same one β€” the local windows cannot be used for this,
397-/// starts whenever that client's first request happened to land.396+/// since each starts whenever that client's first request happened to land.
398 fn current_epoch(window: Duration) -> i64 {397 fn current_epoch(window: Duration) -> i64 {
399 let ms = i64::try_from(window.as_millis()).unwrap_or(i64::MAX).max(1);398 let ms = i64::try_from(window.as_millis()).unwrap_or(i64::MAX).max(1);
400 Timestamp::now().as_millis().div_euclid(ms) * ms399 Timestamp::now().as_millis().div_euclid(ms) * ms
src/web/auth.rsmodified+2 -2
@@ -27,8 +27,8 @@ pub fn routes(state: &AppState) -> OpenApiRouter<AppState> {
27 // over the auth limit must never block an intentional logout.27 // over the auth limit must never block an intentional logout.
28 let rate_limit: &RateLimitConfig = &state.rate_limit;28 let rate_limit: &RateLimitConfig = &state.rate_limit;
29 let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy);29 let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy);
30- // One budget across replicas, not one per process β€” the tier only means30+ // The budget survives a restart β€” the tier only means something if a
31- // something if a brute-forcer cannot get it twice by hitting both.31+ // brute-forcer cannot reset it by waiting out a deploy.
32 limiter.share("auth", state.db.clone(), state.db_up.clone());32 limiter.share("auth", state.db.clone(), state.db_up.clone());
33 OpenApiRouter::new()33 OpenApiRouter::new()
34 .routes(routes!(register))34 .routes(routes!(register))
src/web/chatbot.rsmodified+37 -114
@@ -12,11 +12,11 @@
12 //! polls `GET .../messages/{mid}` or opens its SSE stream β€” both read the same12 //! polls `GET .../messages/{mid}` or opens its SSE stream β€” both read the same
13 //! row, so they can never disagree.13 //! row, so they can never disagree.
14 //!14 //!
15-//! The pending row *is* the job. It used to be answered by a `tokio::spawn`15+//! The bridge round trip runs in a `tokio::spawn` the POST leaves behind. A
16-//! from the POST, which meant a restart orphaned every turn in flight; since16+//! restart therefore orphans a turn in flight: its row stays `pending` until a
17-//! 2026-07-27 it is claimed off the database by [`spawn_claim_loop`], so the17+//! reader projects it failed, and the boot sweep stamps that verdict durably.
18-//! turn is answered by whichever process holds a `chat.reply` worker β€” the one18+//! Acceptable because the backend is one process with stop-the-world deploys β€”
19-//! that accepted it, a peer replica, or the one that comes up after a restart.19+//! there is no peer that could have picked the turn up anyway.
20 20
21 use std::time::Duration;21 use std::time::Duration;
22 22
@@ -35,10 +35,9 @@ use utoipa_axum::router::OpenApiRouter;
35 use utoipa_axum::routes;35 use utoipa_axum::routes;
36 36
37 use crate::ai::chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn};37 use crate::ai::chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn};
38-use crate::ai::{AiBridge, AiError, presence};38+use crate::ai::{AiBridge, AiError};
39 use crate::constant::{39 use crate::constant::{
40- AI_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, CHATBOT_CLAIM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN,40+ AI_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN, MIN_CHUNK_CHARS, REPLY_CHUNKS,
41- MIN_CHUNK_CHARS, REPLY_CHUNKS,
42 };41 };
43 use crate::database::Database;42 use crate::database::Database;
44 use crate::domain::chatbot_message::{43 use crate::domain::chatbot_message::{
@@ -348,15 +347,10 @@ async fn list_messages(
348 /// Order matters and is deliberate: the per-user rate limit is charged347 /// Order matters and is deliberate: the per-user rate limit is charged
349 /// *before* anything is written, so a refused turn leaves no trace;348 /// *before* anything is written, so a refused turn leaves no trace;
350 /// availability is checked *before* the rows exist, so an unavailable service349 /// availability is checked *before* the rows exist, so an unavailable service
351-/// produces a `503` and no dead pending row.350+/// produces a `503` and no dead pending row. Once the rows are written the turn
352-///351+/// always settles β€” the answering task stamps `complete`/`failed`, a reader
353-/// The pending row is a claimed job, not an in-process task: whichever backend352+/// projects a long-stale `pending` as failed, and the boot sweep repairs
354-/// process holds a `chat.reply` worker picks it up (within ~200ms) and answers353+/// whatever a process death left behind.
355-/// it, so a restart no longer strands the turn β€” and a process with no worker
356-/// of its own still accepts turns its peers can answer. The turn always
357-/// settles: the claiming process stamps `complete`/`failed`, a claim its owner
358-/// never finishes is retried, a reader projects a long-stale `pending` as
359-/// failed, and the boot sweep repairs the rest.
360 #[utoipa::path(354 #[utoipa::path(
361 post,355 post,
362 path = "/threads/{id}/messages",356 path = "/threads/{id}/messages",
@@ -395,28 +389,15 @@ async fn send_message(
395 }389 }
396 let content = ChatContent::try_new(&req.content)?;390 let content = ChatContent::try_new(&req.content)?;
397 391
398- // The 503 gate, and the only place it is evaluated. Two questions, asked392+ // The 503 gate, and the only place it is evaluated. `has_capability` is
399- // cheapest first, and neither of them guards a write β€” the gate only393+ // documented racy β€” that is fine here: it never guards a write, it only
400- // spares the user a thread full of rows nothing could ever answer:394+ // spares the user a thread full of rows nothing could ever answer.
401- //395+ let Some(bridge) = st.ai.clone() else {
402- // 1. can *this* replica answer? β€” the in-process registry, which owns
403- // the sockets. Authoritative and free, so it is asked first, which is
404- // also why a single-replica deployment pays no round trip here.
405- // 2. can any *other* replica? β€” the heartbeated `ai_worker` table, which
406- // may lag reality by a heartbeat in either direction. A yes here is
407- // not a promise that this process can do anything: the turn is
408- // written and a peer's claim loop picks it up.
409- //
410- // Neither answer decides who dispatches. That is the claim loop's own
411- // registry, every time (see `crate::ai::presence`).
412- let Some(bridge) = st.ai.as_ref() else {
413 return Ok(unavailable(396 return Ok(unavailable(
414 "the AI service is not enabled on this deployment",397 "the AI service is not enabled on this deployment",
415 ));398 ));
416 };399 };
417- if !bridge.has_capability(AI_CHAT_CAPABILITY)400+ if !bridge.has_capability(AI_CHAT_CAPABILITY) {
418- && !presence::serves(&st.db, AI_CHAT_CAPABILITY).await
419- {
420 return Ok(unavailable("no AI service is connected right now"));401 return Ok(unavailable("no AI service is connected right now"));
421 }402 }
422 403
@@ -434,16 +415,23 @@ async fn send_message(
434 );415 );
435 }416 }
436 417
437- // Nothing is dispatched here, deliberately. The pending row *is* the job:418+ let message_id = answer.get_id().key().to_string();
438- // a claim loop β€” this replica's or a peer's β€” takes it within one419+ // Never awaited inline: the bridge round trip can outlast the request
439- // `CHATBOT_CLAIM_POLL_MS` tick and answers it. An in-process420+ // timeout that guards every handler, and the POST must return now. The
440- // `tokio::spawn` could not survive the restart that orphans the turn,421+ // settings snapshot goes with it, so the whole turn is judged by the policy
441- // which is the whole failure this queue removes.422+ // that was live when it was accepted.
423+ tokio::spawn(answer_turn(
424+ bridge,
425+ st.db.clone(),
426+ answer,
427+ settings.get_chatbot_history_turns().max(0) as usize,
428+ reply_cap,
429+ ));
442 430
443 Ok((431 Ok((
444 StatusCode::ACCEPTED,432 StatusCode::ACCEPTED,
445 Json(AcceptedResponse {433 Json(AcceptedResponse {
446- message_id: answer.get_id().key().to_string(),434+ message_id,
447 status: MessageStatus::Pending.as_str().to_string(),435 status: MessageStatus::Pending.as_str().to_string(),
448 }),436 }),
449 )437 )
@@ -468,76 +456,7 @@ fn unavailable(message: &str) -> Response {
468 .into_response()456 .into_response()
469 }457 }
470 458
471-/// This replica's share of the chat work queue.459+/// Fetch one turn's answer and settle its row. Runs detached from the request.
472-///
473-/// One task per process, started by [`crate::build_router`] when a bridge is
474-/// configured. Every [`CHATBOT_CLAIM_POLL_MS`] it asks *its own* registry
475-/// whether it can serve `chat.reply` and, if so, claims a small batch of
476-/// unanswered turns and dispatches them.
477-///
478-/// The registry is the only thing consulted, never the `ai_worker` gate: the
479-/// gate can say a peer has a worker, and claiming on that word would park the
480-/// turn here for a whole reclaim horizon with no socket to send it down (see
481-/// [`crate::ai::presence`]).
482-///
483-/// ponytail: no shutdown handle β€” the loop runs for the life of the process,
484-/// which is the life of the bridge, and it is idle (one registry read per
485-/// tick, no query) whenever this replica holds no chat worker. Give it a
486-/// `CancellationToken` the day the bridge itself becomes restartable.
487-pub fn spawn_claim_loop(bridge: AiBridge, db: Database) {
488- // Any unique string. It is only ever compared for equality and read in a
489- // log line: a claim identifies the *process*, and a claim nobody renews
490- // expires by age rather than by anyone recognising the claimant.
491- let me = ulid::Ulid::new().to_string();
492- tokio::spawn(async move {
493- let mut ticker = tokio::time::interval(Duration::from_millis(CHATBOT_CLAIM_POLL_MS));
494- ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
495- loop {
496- ticker.tick().await;
497- // The DISPATCHER's answer, and the gate that matters here.
498- if !bridge.has_capability(AI_CHAT_CAPABILITY) {
499- continue;
500- }
501- let claimed = match ChatbotMessage::claim_pending(&me, &db).await {
502- Ok(claimed) => claimed,
503- Err(err) => {
504- tracing::warn!("could not claim chat turns: {err}");
505- continue;
506- }
507- };
508- if claimed.is_empty() {
509- continue;
510- }
511- // Read once per batch, not per turn. Unlike the old in-process
512- // spawn this is the policy live when the turn is *answered* rather
513- // than when it was accepted β€” unavoidable once the answering
514- // process may not be the accepting one, and the window is one poll
515- // tick wide in the normal case.
516- let settings = match Settings::load(&db).await {
517- Ok(settings) => settings,
518- Err(err) => {
519- tracing::warn!("could not load settings for a claimed chat turn: {err}");
520- continue;
521- }
522- };
523- let reply_cap = content_cap(&settings);
524- let history_turns = settings.get_chatbot_history_turns().max(0) as usize;
525- for answer in claimed {
526- // One task per turn: the bridge round trip can take tens of
527- // seconds and must not hold up the next poll.
528- tokio::spawn(answer_turn(
529- bridge.clone(),
530- db.clone(),
531- answer,
532- history_turns,
533- reply_cap,
534- ));
535- }
536- }
537- });
538-}
539-
540-/// Fetch one claimed turn's answer and settle its row.
541 ///460 ///
542 /// Every path settles: a row left `pending` would show as a spinner forever.461 /// Every path settles: a row left `pending` would show as a spinner forever.
543 async fn answer_turn(462 async fn answer_turn(
@@ -549,9 +468,9 @@ async fn answer_turn(
549 ) {468 ) {
550 let answer_id = answer.get_id().clone();469 let answer_id = answer.get_id().clone();
551 let thread = answer.get_thread_id().clone();470 let thread = answer.get_thread_id().clone();
552- // The question this reserved row was written next to. Recovered from the471+ // The question this reserved row was written next to, read back from the
553- // thread rather than carried in memory, because the process that accepted472+ // thread β€” the prompt is already stored, so passing it along would only be
554- // the turn may no longer exist.473+ // a second copy of the same string.
555 let prompt = match answer.prompt_for(&db).await {474 let prompt = match answer.prompt_for(&db).await {
556 Ok(Some(prompt)) => prompt,475 Ok(Some(prompt)) => prompt,
557 Ok(None) => {476 Ok(None) => {
@@ -563,7 +482,11 @@ async fn answer_turn(
563 return;482 return;
564 }483 }
565 Err(err) => {484 Err(err) => {
485+ // Nothing to ask, and nothing will ask again: the claim queue that
486+ // used to reclaim an unsettled row is gone, so leaving it `pending`
487+ // means a spinner until the 300s stale horizon. Settle it here.
566 tracing::warn!("could not read the prompt for {}: {err}", answer_id.key());488 tracing::warn!("could not read the prompt for {}: {err}", answer_id.key());
489+ let _ = ChatbotMessage::fail(&answer_id, "internal", &db).await;
567 return;490 return;
568 }491 }
569 };492 };
src/web/exam_ws.rsmodified+8 -7
@@ -90,7 +90,7 @@ use crate::web::exams::{
90 /// `allow_rejoin` off (cleared at the door, stamped after, present forever90 /// `allow_rejoin` off (cleared at the door, stamped after, present forever
91 /// refused). The count this pairs with lives in *this* process's memory91 /// refused). The count this pairs with lives in *this* process's memory
92 /// ([`crate::state::ExamPresence`]), so process-wide is exactly the right92 /// ([`crate::state::ExamPresence`]), so process-wide is exactly the right
93-/// scope: a peer replica counts its own sockets in its own map.93+/// scope: there is no room state anywhere else to serialize against.
94 // ponytail: global lock, per-attempt locks if room churn ever shows up in a94 // ponytail: global lock, per-attempt locks if room churn ever shows up in a
95 // profile.95 // profile.
96 static PRESENCE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());96 static PRESENCE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
@@ -397,12 +397,13 @@ async fn handle_message(
397 // like `save_answer_checked` β€” and dropped before the socket397 // like `save_answer_checked` β€” and dropped before the socket
398 // sends, so a slow client never stalls a writer.398 // sends, so a slow client never stalls a writer.
399 //399 //
400- // ponytail (accepted race, reviewed): the lease is process-local,400+ // ponytail (accepted race, reviewed): the room's sitting was
401- // so across replicas a save already in flight can land on the401+ // chosen at join, before any lease, so no lock scope can help β€” a
402- // room's sitting just after a retake made it terminal. It writes a402+ // save can land on it just after a retake made it terminal. It
403- // history row for the old seq; the grade of record (latest seq) is403+ // writes a history row for the old seq; the grade of record (latest
404- // untouched. The fix is a `current_seq` claim on every save β€” the404+ // seq) is untouched. The fix is a `current_seq` claim on every save
405- // hottest path here β€” so the cost beats the damage and it stays.405+ // β€” the hottest path here β€” so the cost beats the damage and it
406+ // stays.
406 let guard = EXAM_LOCK.read().await;407 let guard = EXAM_LOCK.read().await;
407 // Tracks how far the gates got: only once the sitting resolved can408 // Tracks how far the gates got: only once the sitting resolved can
408 // a failure possibly be about this one question rather than about409 // a failure possibly be about this one question rather than about
src/web/exams/attempts.rsmodified+5 -7
@@ -666,13 +666,11 @@ pub(crate) async fn save_answer_checked(
666 // one unit, or a retake's wipe-and-create (a writer) slips in between666 // one unit, or a retake's wipe-and-create (a writer) slips in between
667 // and this stale save lands on the fresh blank sheet.667 // and this stale save lands on the fresh blank sheet.
668 //668 //
669- // ponytail (accepted race, reviewed): the lease is process-local, so with669+ // The lease covers the gate *and* the upsert here, so a retake cannot
670- // more than one replica a save that started just before a retake can still670+ // interleave with this path at all. The accepted late-save race lives in
671- // stamp its answer onto the *old* seq, milliseconds after that sitting went671+ // the exam-room socket instead, which writes into the sitting it joined
672- // terminal. Damage is confined to a history row β€” the grade of record is672+ // with β€” a value chosen before any lease is taken. See
673- // the latest seq, which the late write never touches. Closing it needs a673+ // [`crate::web::exam_ws`].
674- // `current_seq` claim on every answer save, the hottest path in the app;
675- // cost beats the damage, so it stays open on purpose.
676 let _guard = EXAM_LOCK.read().await;674 let _guard = EXAM_LOCK.read().await;
677 let attempt = writable_attempt(exam, user, db).await?;675 let attempt = writable_attempt(exam, user, db).await?;
678 save_answer_in(exam, &attempt, question_id, selected, text, db).await676 save_answer_in(exam, &attempt, question_id, selected, text, db).await
src/web/exams/mod.rsmodified+7 -6
@@ -71,10 +71,11 @@ impl Scheduled for Exam {
71 71
72 /// Serializes the exam subsystem's cross-record check-then-writes, which72 /// Serializes the exam subsystem's cross-record check-then-writes, which
73 /// `BEGIN…COMMIT` cannot (write skew) β€” the reasoning in [`crate::domain::cap`].73 /// `BEGIN…COMMIT` cannot (write skew) β€” the reasoning in [`crate::domain::cap`].
74-/// **Replica-local**: it orders requests inside one process only, and the74+/// It orders requests, but only around what it wraps β€” every invariant that
75-/// backend runs as two, so every invariant that could be moved into the75+/// could be moved into the database itself has been, so a gap between a read
76-/// database has been. What is left needs a cross-record read and a write held76+/// and its write is decided by the store. What is left here needs a
77-/// together, which no single statement expresses:77+/// cross-record read and a write held together, which no single statement
78+/// expresses:
78 ///79 ///
79 /// Read side β€” the answer saves (REST and the exam room), from the80 /// Read side β€” the answer saves (REST and the exam room), from the
80 /// writable-attempt gate through the upsert; the grade write (draft gate81 /// writable-attempt gate through the upsert; the grade write (draft gate
@@ -402,11 +403,11 @@ async fn update_exam(
402 // *Reader* lease of [`EXAM_LOCK`] for exactly one pairing: the mode gate403 // *Reader* lease of [`EXAM_LOCK`] for exactly one pairing: the mode gate
403 // below reads `exam_attempt`, and an attempt start takes the *writer*404 // below reads `exam_attempt`, and an attempt start takes the *writer*
404 // lease, so a first sitting still cannot land between that gate and the405 // lease, so a first sitting still cannot land between that gate and the
405- // write β€” replica-locally, as it always did.406+ // write, as it always did.
406 //407 //
407 // It buys nothing against grading, which is a reader too: the re-draft gate408 // It buys nothing against grading, which is a reader too: the re-draft gate
408 // is therefore enforced inside the update's own transaction409 // is therefore enforced inside the update's own transaction
409- // (`Exam::update_if_unchanged`), where it holds across replicas. The gate410+ // (`Exam::update_if_unchanged`), where the store decides it. The gate
410 // below stays as the pre-flight β€” same error, one round trip earlier.411 // below stays as the pre-flight β€” same error, one round trip earlier.
411 // Concurrent PATCHes of this exam no longer queue behind each other either:412 // Concurrent PATCHes of this exam no longer queue behind each other either:
412 // the lost update they used to cause is refused by the compare-and-set.413 // the lost update they used to cause is refused by the compare-and-set.
src/web/homework.rsmodified+6 -7
@@ -44,11 +44,11 @@ use super::{
44 44
45 /// Serializes the homework subsystem's cross-record check-then-writes, which45 /// Serializes the homework subsystem's cross-record check-then-writes, which
46 /// `BEGIN…COMMIT` cannot (write skew) β€” the same reasoning as46 /// `BEGIN…COMMIT` cannot (write skew) β€” the same reasoning as
47-/// [`crate::web::exams::EXAM_LOCK`]. It is a *within-replica* guard only, so47+/// [`crate::web::exams::EXAM_LOCK`]. It orders requests but cannot cover a
48-/// the rule it can no longer be trusted with is the freeze: a graded submission48+/// round trip, so the rule it can no longer be trusted with is the freeze: a
49-/// used to stay unedited because the "no grade yet" read and the write it49+/// graded submission used to stay unedited because the "no grade yet" read and
50-/// licensed sat under one lease, which two processes never shared. That rule50+/// the write it licensed sat under one lease, with the database consulted in
51-/// moved into the database β€” grading stamps51+/// between. That rule moved into the database β€” grading stamps
52 /// [`crate::constant::SUBMISSION_GRADED_FIELD`] on the submission row and every52 /// [`crate::constant::SUBMISSION_GRADED_FIELD`] on the submission row and every
53 /// student-side write carries `graded_by_result = NONE` as its own condition.53 /// student-side write carries `graded_by_result = NONE` as its own condition.
54 ///54 ///
@@ -633,8 +633,7 @@ async fn submit(
633 // The graded gate, twice over. This read answers the common case β€” graded633 // The graded gate, twice over. This read answers the common case β€” graded
634 // minutes ago, and the student who never submitted has no row to carry the634 // minutes ago, and the student who never submitted has no row to carry the
635 // freeze; the upsert's own `WHERE` (the grade stamp on the row) is what635 // freeze; the upsert's own `WHERE` (the grade stamp on the row) is what
636- // holds when the grade lands *while* this request runs, in this replica or636+ // holds when the grade lands *while* this request runs.
637- // the other one.
638 if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db)637 if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db)
639 .await?638 .await?
640 .is_some()639 .is_some()
src/web/meals.rsmodified+1 -1
@@ -372,7 +372,7 @@ async fn delete_menu(
372 .await?372 .await?
373 .ok_or(AppError::NotFound)?;373 .ok_or(AppError::NotFound)?;
374 // The seat check rides in the delete's own `WHERE` (see `Menu::delete`), so374 // The seat check rides in the delete's own `WHERE` (see `Menu::delete`), so
375- // a booking landing in another replica cannot slip between the two.375+ // a concurrent booking cannot slip between the read and the delete.
376 menu.delete(&st.db).await?;376 menu.delete(&st.db).await?;
377 Ok(StatusCode::NO_CONTENT)377 Ok(StatusCode::NO_CONTENT)
378 }378 }
src/web/settings.rsmodified+1 -1
@@ -331,7 +331,7 @@ async fn update_settings(
331 // only while nothing references the name and refuses every claim from331 // only while nothing references the name and refuses every claim from
332 // that instant on. That is the whole guard: the check and the removal332 // that instant on. That is the whole guard: the check and the removal
333 // used to be a cross-table count and a save held together by a333 // used to be a cross-table count and a save held together by a
334- // process-wide lock, which the second replica walked straight through.334+ // process-wide lock that was released around the round trip between them.
335 //335 //
336 // Retired before the save, never after: the other order leaves a window336 // Retired before the save, never after: the other order leaves a window
337 // in which a mark lands under a kind the settings no longer list. A save337 // in which a mark lands under a kind the settings no longer list. A save
src/web/subjects.rsmodified+2 -2
@@ -192,8 +192,8 @@ async fn delete_subject(
192 // No locks: the two checks *are* the delete's `WHERE`, decided against the192 // No locks: the two checks *are* the delete's `WHERE`, decided against the
193 // subject's own reference counters inside one statement. This used to be193 // subject's own reference counters inside one statement. This used to be
194 // three process-wide locks (the only site that held more than one) around194 // three process-wide locks (the only site that held more than one) around
195- // two cross-table counts, which served one replica and let the other create195+ // two cross-table counts, which were stale by the time the delete landed and
196- // a question on a subject being deleted.196+ // let a concurrent request create a question on a subject being deleted.
197 subject.delete(&st.db).await?;197 subject.delete(&st.db).await?;
198 Ok(StatusCode::NO_CONTENT)198 Ok(StatusCode::NO_CONTENT)
199 }199 }
tests/ai_bridge.rsmodified+0 -221
@@ -1162,227 +1162,6 @@ async fn a_blank_chat_answer_fails_as_empty_reply() {
1162 assert_eq!(turn["error_code"], "empty_reply");1162 assert_eq!(turn["error_code"], "empty_reply");
1163 }1163 }
1164 1164
1165-// ----------------------------------------------------------- claim queue --
1166-//
1167-// A pending assistant row is a durable job, not an in-process task. These
1168-// prove the three things that buys: a turn nobody could answer yet is answered
1169-// when a worker appears, a claim whose owner died is taken back, and a turn is
1170-// dispatched exactly once no matter how many replicas are watching the queue.
1171-
1172-use hezarfen_backend::constant::{CHATBOT_CLAIM_POLL_MS, CHATBOT_CLAIM_RECLAIM_SECS};
1173-use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage};
1174-use hezarfen_backend::domain::chatbot_thread::ChatbotThreadId;
1175-use hezarfen_backend::domain::user::UserId;
1176-
1177-/// Write one turn's two rows straight to the queue, bypassing the POST β€” what
1178-/// a replica that has since died would have left behind. Returns the reserved
1179-/// assistant row's key.
1180-async fn queue_turn(app: &Router, db: &Database, cookie: &str, thread: &str, text: &str) -> String {
1181- let me = common::send(app, "GET", "/auth/me", Some(cookie), None).await;
1182- let user = UserId::from_key(me.body["id"].as_str().expect("own id"));
1183- let thread = ChatbotThreadId::from_key(thread);
1184- ChatbotMessage::append_user(&thread, &user, ChatContent::try_new(text).unwrap(), db)
1185- .await
1186- .expect("the user's turn");
1187- ChatbotMessage::append_pending_assistant(&thread, &user, db)
1188- .await
1189- .expect("the reserved answer")
1190- .get_id()
1191- .key()
1192- .to_string()
1193-}
1194-
1195-/// A turn nobody has claimed, held by `claimant` since `age_secs` ago.
1196-async fn stamp_claim(db: &Database, mid: &str, claimant: &str, age_secs: i64) {
1197- db.query(
1198- "UPDATE $id SET claimed_by = $who, claimed_at = time::unix(time::now()) * 1000 - $age",
1199- )
1200- .bind(("id", RecordId::new("chatbot_message", mid.to_string())))
1201- .bind(("who", claimant.to_string()))
1202- .bind(("age", age_secs * 1_000))
1203- .await
1204- .expect("stamp a claim")
1205- .check()
1206- .expect("stamp a claim");
1207-}
1208-
1209-async fn status_of(app: &Router, cookie: &str, thread: &str, mid: &str) -> String {
1210- let res = common::send(
1211- app,
1212- "GET",
1213- &format!("/chatbot/threads/{thread}/messages/{mid}"),
1214- Some(cookie),
1215- None,
1216- )
1217- .await;
1218- assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1219- res.body["status"].as_str().expect("status").to_string()
1220-}
1221-
1222-#[tokio::test]
1223-async fn a_turn_written_with_no_worker_is_answered_once_one_appears() {
1224- // The failure this queue removes: the row used to be answered by a task
1225- // spawned inside the POST, so a turn that outlived its process β€” or was
1226- // written while nothing could serve it β€” settled `failed` at the staleness
1227- // horizon and never got an answer at all.
1228- let bridge = bridge().await;
1229- let (app, db) = chat_app(&bridge).await;
1230- let (cookie, thread) = chat_user(&app, "ali").await;
1231-
1232- // Nothing is connected, so the gate refuses the POST outright…
1233- let res = common::send(
1234- &app,
1235- "POST",
1236- &format!("/chatbot/threads/{thread}/messages"),
1237- Some(&cookie),
1238- Some(json!({ "content": "kimse yokken" })),
1239- )
1240- .await;
1241- assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);
1242-
1243- // …but a row already on the queue (written by a replica that has since
1244- // gone) must still be picked up.
1245- let mid = queue_turn(&app, &db, &cookie, &thread, "kimse yokken").await;
1246- let _service = connect_service(
1247- &bridge,
1248- hello("tutor", &[AI_CHAT_CAPABILITY]),
1249- Behaviour::Reply("geΓ§ gelen cevap".into()),
1250- )
1251- .await;
1252- await_workers(&bridge, 1).await;
1253-
1254- let turn = settled(&app, &cookie, &thread, &mid).await;
1255- assert_eq!(turn["status"], "complete", "{turn}");
1256- assert_eq!(turn["content"], "geΓ§ gelen cevap");
1257-}
1258-
1259-#[tokio::test]
1260-async fn a_claim_left_by_a_dead_replica_is_taken_back() {
1261- let bridge = bridge().await;
1262- let service = connect_service(
1263- &bridge,
1264- hello("tutor", &[AI_CHAT_CAPABILITY]),
1265- Behaviour::Reply("devraldΔ±m".into()),
1266- )
1267- .await;
1268- await_workers(&bridge, 1).await;
1269- let (app, db) = chat_app(&bridge).await;
1270- let (cookie, thread) = chat_user(&app, "ali").await;
1271-
1272- // A claim a peer took moments ago is respected: that peer is presumably
1273- // still waiting on its inference, and answering alongside it would run the
1274- // model twice for one reply.
1275- let live = queue_turn(&app, &db, &cookie, &thread, "başkası bakıyor").await;
1276- stamp_claim(&db, &live, "a-live-peer", 1).await;
1277- for _ in 0..10 {
1278- tokio::time::sleep(Duration::from_millis(CHATBOT_CLAIM_POLL_MS)).await;
1279- }
1280- assert_eq!(
1281- status_of(&app, &cookie, &thread, &live).await,
1282- "pending",
1283- "a live peer's claim was stolen"
1284- );
1285- assert!(service.seen().is_empty(), "{:?}", service.seen());
1286-
1287- // The same claim, past the reclaim horizon, is a claimant that died. The
1288- // turn goes back on the queue rather than waiting out its staleness
1289- // window with nobody answering it.
1290- stamp_claim(&db, &live, "a-dead-peer", CHATBOT_CLAIM_RECLAIM_SECS + 1).await;
1291- let turn = settled(&app, &cookie, &thread, &live).await;
1292- assert_eq!(turn["status"], "complete", "{turn}");
1293- assert_eq!(turn["content"], "devraldΔ±m");
1294- assert_eq!(service.seen().len(), 1, "{:?}", service.seen());
1295-}
1296-
1297-#[tokio::test]
1298-async fn a_claimed_turn_is_dispatched_exactly_once() {
1299- // The claim is what stops the poll loop from re-sending a turn every tick
1300- // while the first inference is still running. A silent service holds the
1301- // stream open, so every extra dispatch would show up in `seen()`.
1302- let bridge = bridge_with_timeout(Duration::from_secs(30)).await;
1303- let service = connect_service(
1304- &bridge,
1305- hello("tutor", &[AI_CHAT_CAPABILITY]),
1306- Behaviour::Silent,
1307- )
1308- .await;
1309- await_workers(&bridge, 1).await;
1310- let (app, _db) = chat_app(&bridge).await;
1311- let (cookie, thread) = chat_user(&app, "ali").await;
1312-
1313- let mid = ask(&app, &cookie, &thread, "uzun sΓΌrecek bir soru").await;
1314- await_inflight(&bridge, 1).await;
1315- // Ten poll ticks with the answer still outstanding.
1316- tokio::time::sleep(Duration::from_millis(CHATBOT_CLAIM_POLL_MS * 10)).await;
1317- assert_eq!(
1318- service.seen().len(),
1319- 1,
1320- "one turn, one dispatch: {:?}",
1321- service.seen()
1322- );
1323- assert_eq!(status_of(&app, &cookie, &thread, &mid).await, "pending");
1324-}
1325-
1326-#[tokio::test]
1327-async fn a_replica_with_no_worker_accepts_a_turn_its_peer_answers() {
1328- // Two replicas, one database, and the worker dialled into exactly one of
1329- // them. The other has nothing to dispatch with β€” its own registry says so
1330- // β€” yet it must still accept the turn, because the `ai_worker` gate can
1331- // see its peer. And exactly one of the two answers it.
1332- let db = hezarfen_backend::database::init_mem()
1333- .await
1334- .expect("mem db");
1335- let quiet = bridge().await;
1336- let serving = bridge().await;
1337- let app_quiet = replica(&quiet, &db);
1338- let app_serving = replica(&serving, &db);
1339-
1340- let service = connect_service(
1341- &serving,
1342- hello("tutor", &[AI_CHAT_CAPABILITY]),
1343- Behaviour::Reply("komşudan cevap".into()),
1344- )
1345- .await;
1346- await_workers(&serving, 1).await;
1347- assert!(!quiet.has_capability(AI_CHAT_CAPABILITY), "no local worker");
1348- // The gate is heartbeated, so give the serving replica's first beat time
1349- // to publish its worker before asking the replica that holds none.
1350- for _ in 0..300 {
1351- if hezarfen_backend::ai::presence::serves(&db, AI_CHAT_CAPABILITY).await {
1352- break;
1353- }
1354- tokio::time::sleep(Duration::from_millis(10)).await;
1355- }
1356-
1357- let (cookie, thread) = chat_user(&app_quiet, "ali").await;
1358- let mid = ask(&app_quiet, &cookie, &thread, "komşuya soru").await;
1359- let turn = settled(&app_quiet, &cookie, &thread, &mid).await;
1360- assert_eq!(turn["status"], "complete", "{turn}");
1361- assert_eq!(turn["content"], "komşudan cevap");
1362- assert_eq!(service.seen().len(), 1, "{:?}", service.seen());
1363- // The answer is one row, so the peer that accepted the turn reads exactly
1364- // what the peer that answered it wrote.
1365- assert_eq!(
1366- status_of(&app_serving, &cookie, &thread, &mid).await,
1367- "complete"
1368- );
1369-}
1370-
1371-/// A second process against the same database: its own bridge, its own claim
1372-/// loop, one shared queue.
1373-fn replica(bridge: &AiBridge, db: &Database) -> Router {
1374- hezarfen_backend::build_router(hezarfen_backend::state::AppState {
1375- db: db.clone(),
1376- files_path: common::files_dir(),
1377- cookie_secure: false,
1378- rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
1379- chatbot_limit: Default::default(),
1380- exam_presence: Default::default(),
1381- db_up: Default::default(),
1382- ai: Some(bridge.clone()),
1383- })
1384-}
1385-
1386 // ------------------------------------------------------------- boot wiring --1165 // ------------------------------------------------------------- boot wiring --
1387 //1166 //
1388 // `ai::start_bridge` is the seam between deployment config and the listener.1167 // `ai::start_bridge` is the seam between deployment config and the listener.
tests/integration.rsmodified+3 -4
@@ -4140,7 +4140,7 @@ async fn concurrent_placements_never_exceed_capacity() {
4140 4140
4141 /// The course capacity cap is a counter column on the course row now, not a4141 /// The course capacity cap is a counter column on the course row now, not a
4142 /// process mutex: `UPDATE ... SET n += 1 WHERE n < capacity` is atomic per4142 /// process mutex: `UPDATE ... SET n += 1 WHERE n < capacity` is atomic per
4143-/// record, so it holds whichever replica the racing enrolls land on. Removing4143+/// record, so it holds however the racing enrolls interleave. Removing
4144 /// that `WHERE` (or the claim entirely) puts a third student on a capacity-24144 /// that `WHERE` (or the claim entirely) puts a third student on a capacity-2
4145 /// course and fails this. The unenroll each round proves the seat comes back β€”4145 /// course and fails this. The unenroll each round proves the seat comes back β€”
4146 /// without the decrement the course is permanently full by round two.4146 /// without the decrement the course is permanently full by round two.
@@ -21374,7 +21374,7 @@ async fn concurrent_meal_bookings_never_exceed_the_capacity() {
21374 assert_eq!(common::total(&res.body), 3, "and only three rows exist");21374 assert_eq!(common::total(&res.body), 3, "and only three rows exist");
21375 21375
21376 // The rows are downstream of the counter, so assert the counter itself:21376 // The rows are downstream of the counter, so assert the counter itself:
21377- // it is what every replica's `WHERE` compares, and a drift here would open21377+ // it is what every booking's `WHERE` compares, and a drift here would open
21378 // the cap on the next booking however tidy the listing looks.21378 // the cap on the next booking however tidy the listing looks.
21379 let mut counted = db21379 let mut counted = db
21380 .query("SELECT VALUE seats_booked FROM type::record('menu', $m)")21380 .query("SELECT VALUE seats_booked FROM type::record('menu', $m)")
@@ -21393,8 +21393,7 @@ async fn concurrent_meal_bookings_never_exceed_the_capacity() {
21393 /// Publishing the same day+slot twice at once must be one menu and one 409 β€”21393 /// Publishing the same day+slot twice at once must be one menu and one 409 β€”
21394 /// never two rows and never a 500. The day and slot *are* the record id, so the21394 /// never two rows and never a 500. The day and slot *are* the record id, so the
21395 /// racers collide on a single record inside the database rather than on a21395 /// racers collide on a single record inside the database rather than on a
21396-/// check-then-write pair, which is the only form that also holds when the two21396+/// check-then-write pair, which is the only form no interleaving can defeat.
21397-/// `POST`s land on different replicas.
21398 #[tokio::test]21397 #[tokio::test]
21399 async fn concurrent_duplicate_menu_publishes_conflict_not_500() {21398 async fn concurrent_duplicate_menu_publishes_conflict_not_500() {
21400 let (app, db) = app_and_db().await;21399 let (app, db) = app_and_db().await;
tests/limits_completeness.rsmodified+3 -46
@@ -86,30 +86,6 @@ const EXCLUDED: &[(&str, &str)] = &[
86 "CHATBOT_PENDING_STALE_SECS",86 "CHATBOT_PENDING_STALE_SECS",
87 "when a stuck answer is declared failed",87 "when a stuck answer is declared failed",
88 ),88 ),
89- // The AI worker gate (`ai_worker`) and the chat claim queue. Both are
90- // between-replica plumbing: a browser cannot observe which process holds a
91- // worker or who claimed its turn, and it already learns everything it can
92- // act on from the 202/503 and the turn's own `status`.
93- ("AI_WORKER_TABLE", "AI worker presence table"),
94- ("AI_WORKER_ANNOUNCE", "AI worker presence upsert"),
95- ("AI_WORKER_WITHDRAW", "AI worker presence delete"),
96- ("AI_WORKER_SWEEP", "AI worker presence expiry"),
97- ("AI_WORKER_SERVES", "AI worker presence read"),
98- (
99- "AI_WORKER_HEARTBEAT_SECS",
100- "how often a replica restamps its AI workers",
101- ),
102- (
103- "AI_WORKER_LEASE_SECS",
104- "how long an unrestamped AI worker row is believed",
105- ),
106- ("CHATBOT_CLAIM", "chat claim-queue statement"),
107- ("CHATBOT_CLAIM_POLL_MS", "chat claim-loop cadence"),
108- ("CHATBOT_CLAIM_BATCH", "turns claimed per sweep"),
109- (
110- "CHATBOT_CLAIM_RECLAIM_SECS",
111- "when a dead claimer's turn goes back on the queue",
112- ),
113 // Seed data for the settings singleton, not a bound. The live list is on89 // Seed data for the settings singleton, not a bound. The live list is on
114 // `GET /settings`, which is where a client must read it β€” publishing the90 // `GET /settings`, which is where a client must read it β€” publishing the
115 // default too would invite rendering it instead of the school's actual one.91 // default too would invite rendering it instead of the school's actual one.
@@ -125,25 +101,6 @@ const EXCLUDED: &[(&str, &str)] = &[
125 "DEFAULT_DIETARY_TAGS",101 "DEFAULT_DIETARY_TAGS",
126 "settings seed; the live list is on GET /settings",102 "settings seed; the live list is on GET /settings",
127 ),103 ),
128- // The boot leader election. A client never sees the lock, and the timings
129- // are startup mechanics between processes β€” publishing them would invite a
130- // frontend to reason about a boot it cannot observe.
131- ("MIGRATION_LOCK_DDL", "boot lock table definition"),
132- ("MIGRATION_LOCK_CLAIM", "boot lock claim statement"),
133- ("MIGRATION_LOCK_STATE", "boot lock read statement"),
134- ("MIGRATION_LOCK_TAKEOVER", "boot lock takeover statement"),
135- ("MIGRATION_LOCK_HEARTBEAT", "boot lock lease renewal"),
136- ("MIGRATION_LOCK_STAMP", "boot lock completion stamp"),
137- (
138- "MIGRATION_LOCK_LEASE_SECS",
139- "how long an unrenewed boot lock may be taken over after",
140- ),
141- ("MIGRATION_LOCK_HEARTBEAT_SECS", "boot lock renewal cadence"),
142- (
143- "MIGRATION_LOCK_WAIT_SECS",
144- "how long a non-leader waits for the boot migration",
145- ),
146- ("MIGRATION_LOCK_POLL_MS", "boot lock poll cadence"),
147 // The three migration batches and their list moved to104 // The three migration batches and their list moved to
148 // `src/migration_sql.rs` β€” they are SurrealQL text, not bounds, and the105 // `src/migration_sql.rs` β€” they are SurrealQL text, not bounds, and the
149 // numeric sweep below still catches any bound that tries to follow them.106 // numeric sweep below still catches any bound that tries to follow them.
@@ -192,9 +149,9 @@ const EXCLUDED: &[(&str, &str)] = &[
192 "ETag middleware's own buffering ceiling",149 "ETag middleware's own buffering ceiling",
193 ),150 ),
194 ("PURGE_AT", "rate-limiter bucket eviction threshold"),151 ("PURGE_AT", "rate-limiter bucket eviction threshold"),
195- // How the tiers are kept fleet-wide. A client is held to the tier itself152+ // How a tier's window is carried through a restart. A client is held to
196- // (published live in /limits `rate`), never to the cadence the replicas153+ // the tier itself (published live in /limits `rate`), never to the cadence
197- // reconcile it at β€” publishing that would invite pacing against it.154+ // it is reconciled at β€” publishing that would invite pacing against it.
198 (155 (
199 "RATE_SYNC_INTERVAL_SECS",156 "RATE_SYNC_INTERVAL_SECS",
200 "how often a replica reconciles its counters",157 "how often a replica reconciles its counters",
tests/name_refs.rsmodified+1 -1
@@ -165,7 +165,7 @@ async fn marks_release_their_kind_when_they_are_deleted() {
165 /// The claim's `WHERE`, the other half of the same race: once the kind is out165 /// The claim's `WHERE`, the other half of the same race: once the kind is out
166 /// of the list, a mark can no longer land under it. Whichever of the two166 /// of the list, a mark can no longer land under it. Whichever of the two
167 /// writes reaches the counter first, the other is refused β€” which is what makes167 /// writes reaches the counter first, the other is refused β€” which is what makes
168-/// the pair safe with two replicas and no shared lock.168+/// the pair safe without a lock spanning both writes.
169 #[tokio::test]169 #[tokio::test]
170 async fn a_removed_kind_refuses_a_grade() {170 async fn a_removed_kind_refuses_a_grade() {
171 let school = school_with_kinds(&["lab", "quiz"]).await;171 let school = school_with_kinds(&["lab", "quiz"]).await;
tests/rate_limit.rsmodified+18 -15
@@ -310,16 +310,20 @@ async fn concurrent_bursts_never_over_admit() {
310 assert_eq!((ok, limited), (5, 15));310 assert_eq!((ok, limited), (5, 15));
311 }311 }
312 312
313-// --- shared across replicas --------------------------------------------313+// --- the window outlives the process ------------------------------------
314 //314 //
315-// Two `UserRateLimiter`s over one database stand in for two replicas: they are315+// Two `UserRateLimiter`s over one database stand in for the process before and
316-// separate processes' worth of in-memory buckets, sharing only the `rate_limit`316+// after a restart: two separate sets of in-memory buckets sharing only the
317-// table. Time is paused, so a round of the sync task is driven by advancing317+// `rate_limit` table, which is what stops a restart mid-window from handing
318-// past `RATE_SYNC_INTERVAL_SECS` β€” and because the task blocks on the database318+// every client a fresh budget. Time is paused, so a round of the sync task is
319-// (not on time) mid-round, the short sleep afterwards cannot resolve until the319+// driven by advancing past `RATE_SYNC_INTERVAL_SECS` β€” and because the task
320-// round has finished. Assertions are on admissions, never on which replica won320+// blocks on the database (not on time) mid-round, the short sleep afterwards
321-// a race: the embedded engine can drop one of two concurrent writes and still321+// cannot resolve until the round has finished. Assertions are on admissions,
322-// answer `Ok`.322+// never on which limiter won a race: the embedded engine can drop one of two
323+// concurrent writes and still answer `Ok`.
324+//
325+// (The `replica` spelling below is historical β€” renaming test items is a code
326+// change, not a doc one.)
323 327
324 use hezarfen_backend::constant::RATE_SYNC_INTERVAL_SECS;328 use hezarfen_backend::constant::RATE_SYNC_INTERVAL_SECS;
325 use hezarfen_backend::database::Database;329 use hezarfen_backend::database::Database;
@@ -351,7 +355,7 @@ async fn sync_round() {
351 tokio::time::pause();355 tokio::time::pause();
352 }356 }
353 357
354-/// Two "replicas" of one tier, sharing `db`.358+/// Two limiters of one tier, sharing `db`.
355 fn two_replicas(max: u32, db: &Database) -> (UserRateLimiter, UserRateLimiter, DbHealth) {359 fn two_replicas(max: u32, db: &Database) -> (UserRateLimiter, UserRateLimiter, DbHealth) {
356 let health = DbHealth::default();360 let health = DbHealth::default();
357 let (a, b) = (361 let (a, b) = (
@@ -375,13 +379,12 @@ async fn two_replicas_share_one_budget() {
375 let db = shared_db().await;379 let db = shared_db().await;
376 let (a, b, _health) = two_replicas(6, &db);380 let (a, b, _health) = two_replicas(6, &db);
377 381
378- // Both replicas spend freely until their first sync β€” the accepted382+ // Each spends freely until its first sync β€” the accepted one-interval
379- // one-interval overshoot, and the whole reason the fleet needs the shared383+ // overshoot, and the whole reason the shared row exists at all.
380- // row at all.
381 let spent = admits(&a, "user:a", 6) + admits(&b, "user:a", 6);384 let spent = admits(&a, "user:a", 6) + admits(&b, "user:a", 6);
382 assert_eq!(spent, 12, "each replica starts on its own local budget");385 assert_eq!(spent, 12, "each replica starts on its own local budget");
383 386
384- // From the first sync on, the fleet total is what binds: neither replica387+ // From the first sync on, the shared total is what binds: neither limiter
385 // admits anything more in this window, whatever the interleaving was.388 // admits anything more in this window, whatever the interleaving was.
386 sync_round().await;389 sync_round().await;
387 assert_eq!(390 assert_eq!(
@@ -424,7 +427,7 @@ async fn a_down_database_leaves_each_replica_on_its_local_budget() {
424 health.set(false);427 health.set(false);
425 428
426 // Nothing is shared while the database is down β€” and nothing stalls: both429 // Nothing is shared while the database is down β€” and nothing stalls: both
427- // replicas keep serving their own budgets at full speed.430+ // limiters keep serving their own budgets at full speed.
428 for _ in 0..3 {431 for _ in 0..3 {
429 sync_round().await;432 sync_round().await;
430 assert_eq!(admits(&a, "user:a", 1), 1);433 assert_eq!(admits(&a, "user:a", 1), 1);