diff --git a/README.md b/README.md index 63b5b5f..cd01e40 100644 --- a/README.md +++ b/README.md @@ -4051,6 +4051,52 @@ is opaque to the transport; its shape belongs to the capability. rather than answer late. A handled failure is an `err` frame; a crash is just a dropped stream. +### The `rag.chat` capability + +`rag.chat` answers a question **about a school's course-note corpus**, with +citations. Same `Request`/`Response` frames as any capability; only the payload +differs. The service retrieves the relevant passages first and then generates, +so its deadline (90s) is longer than a plain chat turn's. + +The request payload: + +```json +{ "message": "ikinci yasa nedir?", "asker": "01ASKER", "asker_role": "student", + "scope": [ { "sinif": "11", "ders": "Fizik" } ], + "history": [ { "role": "user", "content": "merhaba" } ] } +``` + +`asker` is the id of the person who asked, so the service can read *their* own +data back through the api reads above (`on_behalf_of`) — a question about "my +marks" is answered from their marks. `asker_role` is their school role, the +same lowercase strings the chatbot request carries. `scope` is a list of +`(sinif, ders)` **pairs**: the corpus is routed by the pair, so a grade and a +subject list sent separately would cross-product into combinations the asker +never named. At most `MAX_RAG_SCOPE_PAIRS` (200) pairs ride one request. +`history` is the same oldest-first tail as `chat.reply`, optional. + +The reply payload: + +```json +{ "text": "F = m·a [1]", "abstained": false, "reason": "", + "citations": [ { "n": 1, "doc_id": "01DOC", "pages": [3], + "span_ids": ["s-7"], "ders": "Fizik" } ] } +``` + +A refusal that is part of the answer stays here rather than becoming an `err` +frame: `abstained: true` with a short `reason` (`guard_*`, `insufficient_data`, +`model_abstained`, `scope_mismatch`, `role_required`, …) is a completed turn. +Each citation's `n` is the marker `[N]` the answer text uses, so a client +resolves `[N]` by finding the citation whose `n` is `N` and opening the +document `citations[].doc_id` names. `doc_id` is the **corpus** document id — +the backend maps it to the `course_note_file` that owns that PDF. + +For that mapping to exist, the `rag.index` **reply** should echo each indexed +file's ids: the service answers `{"files": [{"id": "", +"doc_id": ""}]}`, naming the corpus id it assigned to each file +it indexed. The backend pairs the echoed `doc_id` back to the file it sent, so +a later citation's `doc_id` resolves to a downloadable file. + ### API reads (the other direction) A service usually needs school data to do its work — who asked, their notes, diff --git a/src/ai/mod.rs b/src/ai/mod.rs index 31463c3..428934a 100644 --- a/src/ai/mod.rs +++ b/src/ai/mod.rs @@ -15,6 +15,7 @@ //! * [`protocol`] — frames on the wire //! * [`chat`] — the JSON payloads carried for the `chat.reply` capability //! * [`rag`] — the `rag.index` payloads, and the course-note dispatch behind them +//! * [`rag_chat`] — the `rag.chat` payloads: a scoped question and the citations behind its answer //! * [`server`] — the listener, handshake, and [`server::AiBridge::dispatch`] //! * [`registry`] — who is connected here, and who gets the next request //! * [`tls`] — the listener's certificate @@ -28,6 +29,7 @@ pub mod chat; pub mod error; pub mod protocol; pub mod rag; +pub mod rag_chat; pub mod registry; pub mod server; pub mod tls; @@ -35,6 +37,9 @@ pub mod tls; pub use chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn}; pub use error::AiError; pub use rag::{RagFile, RagIndexPayload}; +pub use rag_chat::{ + RagChatReplyPayload, RagChatRequestPayload, RagCitation, RagScopePair, RagTurn, +}; pub use registry::{AiRegistry, WorkerSnapshot}; pub use server::{AiBridge, BridgeConfig}; diff --git a/src/ai/rag_chat.rs b/src/ai/rag_chat.rs new file mode 100644 index 0000000..4019e99 --- /dev/null +++ b/src/ai/rag_chat.rs @@ -0,0 +1,203 @@ +//! Payload contract for the `rag.chat` capability. +//! +//! Same transport as every other capability: this is JSON riding inside a +//! [`Request::payload`](crate::ai::protocol::Request::payload) and coming back +//! inside [`Response::Ok`](crate::ai::protocol::Response::Ok)`::payload`. One +//! request, one answer — retrieval-then-answer is unary here even though it is +//! two steps inside the service. +//! +//! The service answers *about* a school's course-note corpus, so the request +//! carries both who is asking (so the service can read that person's own data +//! back through the bridge's api reads, as `on_behalf_of`) and the +//! `(sınıf, ders)` scope the corpus is routed by. The reply returns the answer +//! text plus the citations behind it, so the backend can resolve each cited +//! passage to the course-note file it came from. + +use serde::{Deserialize, Serialize}; + +use crate::ai::chat::ChatRole; + +/// One `(sınıf, ders)` pair the question is scoped to. +/// +/// The corpus is routed by the **pair**: a grade and a subject list sent +/// separately would cross-product into combinations the asker never named, so +/// each pair is one scope the service may retrieve from. `sinif` is optional — +/// a question about a subject across every grade names `ders` alone — and +/// `ders` is required, since a subject-less scope retrieves nothing. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RagScopePair { + /// The class/grade the subject is taught in (`"9"`, `"10"`), or omitted to + /// scope the subject across grades. + #[serde(default)] + pub sinif: Option, + /// The subject/course name the pair is scoped to (Matematik, Fizik). The + /// one field a pair cannot go without. + pub ders: String, +} + +/// One previous message in the RAG conversation. +/// +/// The same `{role, content}` shape the chatbot's history uses — a model's +/// `messages` array takes it with no remapping — so the two histories are +/// interchangeable. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RagTurn { + pub role: ChatRole, + pub content: String, +} + +/// What the backend asks a RAG service to answer. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RagChatRequestPayload { + /// The user's new question. `history` does *not* contain it. + pub message: String, + /// The id of the user who asked. The service reads that person's own data + /// back through the bridge's api reads (`on_behalf_of`), so a question + /// about "my marks" is answered from *their* marks and never from another + /// student's. Read live from the authenticated session, never taken from a + /// request body. + pub asker: String, + /// The asker's **school role** — `"parent"`, `"student"`, `"teacher"`, + /// `"manager"` or `"admin"`, the same lowercase strings the rest of the + /// API uses. Read live from the session on every request, like the chatbot + /// request's copy, so a service may answer on it: a student must not be + /// handed an answer scoped for a manager. + pub asker_role: String, + /// The `(sınıf, ders)` pairs the question is scoped to — one entry per pair, + /// because the RAG routes corpora by the pair. At most + /// [`MAX_RAG_SCOPE_PAIRS`](crate::constant::MAX_RAG_SCOPE_PAIRS); a request + /// carrying more is refused rather than narrowed. + pub scope: Vec, + /// The last N turns of the conversation, **oldest first** — index 0 the + /// furthest back, the final element the turn immediately before `message`. + /// Absent or `[]` means a fresh conversation. + #[serde(default)] + pub history: Vec, +} + +/// One passage the answer drew on, inside the reply's `citations`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RagCitation { + /// The marker the answer text uses to point at this passage: `[N]` in + /// `text` resolves to the citation whose `n` is `N`. + pub n: u32, + /// The corpus document id the passage came from. The backend maps it to + /// the course-note file that owns that PDF (the `rag.index` reply echoes + /// this id back per file), so a citation resolves to something a reader can + /// open. + pub doc_id: String, + /// The page numbers within the document the passage spans, when the source + /// is paginated. + #[serde(default)] + pub pages: Vec, + /// Opaque retrieval span ids within the document, for a client that wants + /// to highlight the exact passage rather than the whole page. + #[serde(default)] + pub span_ids: Vec, + /// The subject the passage belongs to, when the corpus records one. + #[serde(default)] + pub ders: Option, +} + +/// The service's answer, inside `Response::Ok { payload }`. +/// +/// Handled failures do *not* come back here — they use the existing +/// [`Response::Err`](crate::ai::protocol::Response::Err) `{ code, message }`, +/// so there is exactly one failure shape on the bridge for every capability. +/// A refusal that is part of the answer (the service chose not to answer, or +/// could not) rides here instead, because it is still an answer: the turn +/// completes, no error surfaces. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RagChatReplyPayload { + /// The complete answer text, with `[N]` markers resolving to `citations`. + pub text: String, + /// Whether the service declined to answer rather than answering. A true + /// value is a complete, successful turn — not a failure — and `reason` + /// says why. + #[serde(default)] + pub abstained: bool, + /// Why the service abstained, as a short machine code (`""` when it did + /// not): `guard_*`, `insufficient_data`, `model_abstained`, + /// `scope_mismatch`, `role_required`, or a service-specific code. Empty on + /// an ordinary answer. + #[serde(default)] + pub reason: String, + /// The passages the answer drew on, oldest first. + #[serde(default)] + pub citations: Vec, +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn rag_chat_payload_keys_are_the_documented_wire_names() { + // Services in other languages match on these literals — a rename here + // silently breaks every one of them, so pin the encoding, key names + // included (the exact wire key sets are the contract). + let request = serde_json::to_value(RagChatRequestPayload { + message: "ikinci yasa nedir?".into(), + asker: "01ASKER".into(), + asker_role: "student".into(), + scope: vec![RagScopePair { + sinif: Some("11".into()), + ders: "Fizik".into(), + }], + history: vec![RagTurn { + role: ChatRole::User, + content: "merhaba".into(), + }], + }) + .unwrap(); + assert_eq!( + request, + json!({ + "message": "ikinci yasa nedir?", + "asker": "01ASKER", + "asker_role": "student", + "scope": [{ "sinif": "11", "ders": "Fizik" }], + "history": [{ "role": "user", "content": "merhaba" }], + }) + ); + + let reply = serde_json::to_value(RagChatReplyPayload { + text: "F = m·a [1]".into(), + abstained: false, + reason: String::new(), + citations: vec![RagCitation { + n: 1, + doc_id: "01DOC".into(), + pages: vec![3], + span_ids: vec!["s-7".into()], + ders: Some("Fizik".into()), + }], + }) + .unwrap(); + assert_eq!( + reply, + json!({ + "text": "F = m·a [1]", + "abstained": false, + "reason": "", + "citations": [{ + "n": 1, + "doc_id": "01DOC", + "pages": [3], + "span_ids": ["s-7"], + "ders": "Fizik", + }], + }) + ); + + // The three optional fields default to empty on a minimal service + // reply, and a scope pair may omit `sinif`. + let bare: RagChatReplyPayload = + serde_json::from_value(json!({ "text": "bilmiyorum", "abstained": true })).unwrap(); + assert_eq!(bare.reason, ""); + assert!(bare.citations.is_empty()); + let pair: RagScopePair = serde_json::from_value(json!({ "ders": "Matematik" })).unwrap(); + assert_eq!(pair.sinif, None); + } +} diff --git a/src/constant.rs b/src/constant.rs index d069c14..f458bff 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -580,6 +580,41 @@ pub const AI_RAG_INDEX_CAPABILITY: &str = "rag.index"; /// is fire-and-forget, off the HTTP request path. pub const AI_RAG_INDEX_TIMEOUT_SECS: u64 = 120; +/// The capability an AI service declares to answer a RAG question over a +/// school's course-note corpus. Separate from [`AI_CHAT_CAPABILITY`] on +/// purpose: retrieval-then-answer is its own service with its own corpus, and +/// a deployment may run one without the other. With no worker carrying it the +/// RAG endpoints report the service as unavailable. +pub const AI_RAG_CHAT_CAPABILITY: &str = "rag.chat"; + +/// Deadline on one `rag.chat` round trip. Much longer than a plain chat turn +/// ([`AI_DEFAULT_REQUEST_TIMEOUT_SECS`]): the service first retrieves the +/// relevant passages and only then generates an answer, so a question that +/// touches several course notes is retrieval plus inference, not inference +/// alone. +pub const AI_RAG_CHAT_TIMEOUT_SECS: u64 = 90; + +/// How long a `rag.chat` turn may sit `pending` before a reader projects it as +/// failed. The RAG nest mirrors the chatbot's asynchronous send +/// ([`CHATBOT_PENDING_STALE_SECS`]): the round trip outlives the request that +/// started it, and a restart mid-inference strands the row rather than letting +/// anyone answer it, so the same staleness window applies. +pub const RAG_PENDING_STALE_SECS: i64 = CHATBOT_PENDING_STALE_SECS; + +/// The most `(sınıf, ders)` scope pairs one `rag.chat` request may carry. The +/// corpus is routed by the **pair** — a grade and a subject list sent +/// separately would cross-product into combinations the asker never named — so +/// this is the number of pairs handed to the service in one call, bounding +/// both the frame size and the service's routing work. A request carrying more +/// is refused rather than silently narrowed: dropping pairs would answer a +/// question the asker did not ask, scoped to corpora they did not name. +pub const MAX_RAG_SCOPE_PAIRS: usize = 200; + +/// Default per-minute message limit for the RAG nest, when the school sets +/// none — a lower ceiling than the chatbot's, since every message here spends +/// a retrieval over the whole course-note corpus before it generates anything. +pub const DEFAULT_RAG_RATE_LIMIT: u32 = 6; + /// Hard ceiling on one chat message's characters — the newtype bound, above /// which no school setting can reach. Sized for a pasted question with its /// working, well under [`AI_MAX_FRAME_BYTES`] once history rides along. diff --git a/src/lib.rs b/src/lib.rs index 1875947..8453c9c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -52,7 +52,7 @@ use crate::web::module_gate::gate; modifiers(&SecurityAddon), tags( (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /health` (and its `/` mirror) reports what the process can currently do — `{status, db, ai}` — answering `503` with a body that names the failing dependency rather than a bare refusal, and it keeps answering while the database is down. `GET /limits` publishes every fixed bound the API enforces — field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) — so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. Two refusals split that contract: every JSON-bodied operation answers `422` when the request never became the type the handler asked for (a wrong-typed field, a missing required one), and that one is a plain-text deserializer diagnostic rather than the `{error}` envelope, so it is read by a human and not parsed by a client; `400` carries the usual `{error}` and means either non-JSON bytes or a well-typed value that broke a rule published here. Multipart upload routes have no JSON body and so answer `400`, never `422`. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off). `GET /modules/catalog` is the same kind of contract for the product's shape: every sellable module, the package it is sold in, and the modules it structurally requires — unauthenticated and deploy-constant, since it is identical for every school. What one school actually bought is `GET /modules` (any logged-in user), the cheap way to hide a nest the school does not have instead of discovering it as a `403`. Those tiers are per client; a server whose client table is saturated by a flood meters otherwise-unknown callers against one shared budget instead, so an unfamiliar client can briefly see a `429` it did not itself earn — always with a `Retry-After`, never longer than the window"), - (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/2`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Every frame in either direction names the school it belongs to (`school`, the slug), so one fleet of services serves every school on the deployment and a read is answered out of that school's own database — an unknown slug is `unknown_school`, a suspended one `school_suspended`. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), + (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/2`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Every frame in either direction names the school it belongs to (`school`, the slug), so one fleet of services serves every school on the deployment and a read is answered out of that school's own database — an unknown slug is `unknown_school`, a suspended one `school_suspended`. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). `GET /ai/capabilities` (authenticated) lists what connected services are serving right now — one entry per capability with its worker count and in-flight requests — and answers `200 {enabled: false, capabilities: []}` when the bridge is off: a discovery read showing *that* there is no AI fleet, not a dependency probe. See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school slug; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; the registry row reads `provisioning` until that schema is in place, so a boot cut short mid-create is finished by the next one instead of leaving a school that answers `500`; `PATCH /schools/{slug}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{slug}` destroys its data and its uploaded files for good. `POST /schools/{slug}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{slug}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it. It is also where a school's **entitlements** are sold: `GET /schools/{slug}/modules` lists what it has and what is left, `POST`/`DELETE /schools/{slug}/modules/{module}` flips one (idempotently), and `PATCH /schools/{slug}/modules` re-sells the whole shelf in one atomic write — modules and packages, both directions, expanded into a single resulting set that is checked once, so a `409` names every broken dependency at once and nothing is written unless the request is accepted whole. A change lands on the school's very next request, live cookies included: a disabled module answers `403 {error, module}` on every route in its nest. The catalog itself (`GET /modules/catalog`) and a school user's own set (`GET /modules`) are on the `meta` tag."), (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `POST /auth/register` is still aimed at a school (`{school, username, password}`): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `.` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"), (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), diff --git a/src/web/ai.rs b/src/web/ai.rs index 5284cab..bde0c5c 100644 --- a/src/web/ai.rs +++ b/src/web/ai.rs @@ -26,9 +26,11 @@ use crate::ai::tls; use crate::constant::AI_PROTOCOL; use crate::error::{AppError, ErrorResponse}; use crate::state::AppState; +use crate::web::CurrentUser; +use std::collections::BTreeMap; pub fn routes() -> OpenApiRouter { - OpenApiRouter::new().routes(routes!(bridge_certificate)) + OpenApiRouter::new().routes(routes!(bridge_certificate, capabilities)) } /// Everything a service needs to reach the bridge, except the shared token @@ -82,6 +84,82 @@ async fn bridge_certificate( })) } +/// What the bridge can currently do, grouped by capability. +#[derive(Serialize, ToSchema)] +pub struct CapabilitiesResponse { + /// Whether a bridge is listening at all (`AI_QUIC_ADDR` set). `false` here + /// is a discovery answer, not an error: the deployment simply runs no AI. + enabled: bool, + /// The wire protocol the bridge speaks, currently `hab/2`. + #[schema(example = "hab/2")] + protocol: String, + /// One entry per capability any connected worker serves, sorted by name. + capabilities: Vec, +} + +/// One capability's live fleet: how many workers serve it, and the work in +/// flight across them. +#[derive(Serialize, ToSchema)] +pub struct CapabilityWorkers { + /// The capability string a service declared, e.g. `chat.reply` or + /// `rag.chat`. + #[schema(example = "chat.reply")] + capability: String, + /// How many connected workers have declared this capability. + workers: usize, + /// Requests currently being answered across those workers. + inflight: u64, +} + +/// The capabilities connected AI services are serving right now, per +/// capability, with the work in flight — a discovery read for an operator or a +/// service deciding what it may ask this bridge to do. +/// +/// **`200`, even with the bridge off.** This lists what is available rather +/// than probing a dependency, so a disabled bridge answers `enabled: false` +/// and an empty list, not a `503` — a caller learns *that* there is no AI +/// fleet rather than that the request itself failed. +#[utoipa::path( + get, + path = "/capabilities", + tag = "ai", + responses( + (status = 200, description = "Every capability a connected worker serves, grouped and sorted", body = CapabilitiesResponse), + (status = 401, description = "No authenticated session", body = ErrorResponse), + ), +)] +async fn capabilities( + State(state): State, + _user: CurrentUser, +) -> Json { + let (enabled, workers) = match &state.ai { + Some(bridge) => (true, bridge.workers()), + None => (false, Vec::new()), + }; + // A worker serving N capabilities counts once toward each of them, so the + // group totals are per-capability fleets, not a partition of the workers. + let mut by_capability: BTreeMap = BTreeMap::new(); + for worker in workers { + for capability in &worker.capabilities { + let entry = by_capability.entry(capability.clone()).or_insert((0, 0)); + entry.0 += 1; + entry.1 += worker.inflight as u64; + } + } + Json(CapabilitiesResponse { + enabled, + protocol: AI_PROTOCOL.to_string(), + capabilities: by_capability + .into_iter() + .map(|(capability, (workers, inflight))| CapabilityWorkers { + capability, + workers, + inflight, + }) + .collect(), + }) +} + /// Wrap DER bytes as a PEM certificate: base64 in 64-character lines between /// the standard armour, which is what every TLS library's loader expects. fn to_pem(der: &[u8]) -> String { diff --git a/tests/ai_protocol.rs b/tests/ai_protocol.rs index 0ede163..9f15fc0 100644 --- a/tests/ai_protocol.rs +++ b/tests/ai_protocol.rs @@ -1016,6 +1016,89 @@ async fn a_chat_request_names_the_askers_school_role() { .await; } +// ------------------------------------------------- rag.chat payload keys -- +// +// `rag.chat` is the other capability whose payload is a published contract. +// In this wave nothing in the HTTP surface builds one yet, so its payload is +// pinned by putting the crate's own payload through the real bridge and reading +// the bytes exactly as a foreign service would: raw frames, and the documented +// key sets — never parsed back through the crate's payload structs. + +#[tokio::test] +async fn rag_chat_payloads_carry_the_documented_wire_keys() { + use hezarfen_backend::ai::{ + RagChatReplyPayload, RagChatRequestPayload, RagCitation, RagScopePair, + }; + + let bridge = bridge().await; + let service = raw::handshake(&bridge, &raw::hello("rag", "rag.chat")).await; + await_workers(&bridge, 1).await; + + let request = serde_json::to_value(RagChatRequestPayload { + message: "ikinci yasa nedir?".into(), + asker: "01ASKER".into(), + asker_role: "student".into(), + scope: vec![RagScopePair { + sinif: Some("11".into()), + ders: "Fizik".into(), + }], + history: Vec::new(), + }) + .unwrap(); + let call = dispatch(&bridge, "rag.chat", request); + + let (frame, bytes, send, _recv) = raw::take_request(&service.conn).await; + assert_eq!(frame["capability"], "rag.chat"); + assert_eq!( + raw::keys(&frame["payload"]), + ["asker", "asker_role", "history", "message", "scope"], + "the documented rag.chat request payload keys" + ); + assert_eq!( + raw::keys(&frame["payload"]["scope"][0]), + ["ders", "sinif"], + "a scope pair is routed by (sinif, ders)" + ); + // Byte-level: the `(sinif, ders)` pair set, not a re-wrapped shape. + let text = String::from_utf8(bytes).expect("the frame body is UTF-8 JSON"); + assert!( + text.contains(r#""scope":[{"sinif":"11","ders":"Fizik"}]"#), + "{text}" + ); + + let reply = serde_json::to_value(RagChatReplyPayload { + text: "F = m·a [1]".into(), + abstained: false, + reason: String::new(), + citations: vec![RagCitation { + n: 1, + doc_id: "01DOC".into(), + pages: vec![3], + span_ids: vec!["s-7".into()], + ders: Some("Fizik".into()), + }], + }) + .unwrap(); + let id = frame["id"].as_str().expect("trace id").to_string(); + raw::answer( + send, + format!(r#"{{"status":"ok","id":"{id}","school":"{SCHOOL}","payload":{reply}}}"#).as_bytes(), + ) + .await; + + let answer = call.await.unwrap().unwrap(); + assert_eq!( + raw::keys(&answer), + ["abstained", "citations", "reason", "text"], + "the documented rag.chat reply payload keys" + ); + assert_eq!( + raw::keys(&answer["citations"][0]), + ["ders", "doc_id", "n", "pages", "span_ids"], + "the documented citation keys" + ); +} + // ------------------------------------------------------------- api reads -- // // The other direction: a service opens its own stream and asks the school API diff --git a/tests/e2e.rs b/tests/e2e.rs index 3d3f192..71f2be9 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -2048,6 +2048,36 @@ async fn chat_stream_and_poll_agree_that_an_answer_was_truncated() { assert_eq!(&polled, streamed, "the two reads must not disagree"); } +#[tokio::test] +async fn capabilities_reports_a_registered_chat_service() { + // A discovery read: once the fake `chat.reply` service has dialled in, + // `GET /ai/capabilities` lists that capability with its worker fleet. + let service = chat_service("F = ma").await; + let (base, _db) = spawn_server_with_ai(Some(service.bridge.clone())).await; + let ali = client(); + register(&ali, &base, "ali").await; + login(&ali, &base, "ali").await; + + let caps: Value = ali + .get(format!("{base}/ai/capabilities")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(caps["enabled"], json!(true)); + assert_eq!(caps["protocol"], json!("hab/2")); + let row = caps["capabilities"] + .as_array() + .expect("a capabilities array") + .iter() + .find(|c| c["capability"] == json!("chat.reply")) + .expect("the fake service serves chat.reply"); + assert_eq!(row["workers"], json!(1)); + assert!(row["inflight"].is_u64(), "{row}"); +} + #[tokio::test] async fn chat_stream_delivers_deltas_then_done_over_http() { let answer = long_answer();