Relay rag.summarize and rag.questions over the bridge
Browse files at this commit69d4295dd558b3b2b267ec4b040ae0effce52e37Parent: 49f9665- feat
- relay rag.summarize and rag.questions over the bridge
10 changed files +1384 -3
- README.md +76 -0
- src/ai/mod.rs +2 -0
- src/ai/rag_study.rs +401 -0
- src/constant.rs +40 -0
- src/lib.rs +1 -1
- src/web/limits.rs +5 -0
- src/web/rag.rs +446 -1
- tests/ai_bridge.rs +392 -0
- tests/integration.rs +1 -1
- tests/limits_completeness.rs +20 -0
README.mdmodified+76 -0
| @@ -1436,6 +1436,8 @@ window filtering, before paging; negative values are a `400` naming the field. | ||
| 1436 | 1436 | | GET | `/questions/{id}/solutions/{sid}/image` | student | The solution photo's bytes. Access follows the question the solution hangs on — in practice school-wide, since solutions exist only on approved questions. | |
| 1437 | 1437 | | POST | `/questions/{id}/solutions/{sid}/image` | student | Attach (or replace) the solution's photo. Author only — and at any time, since solutions are never frozen. `multipart/form-data` with the image under a `file` field; the declared content type must be `image/png`, `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the bytes at most the school's `max_file_bytes` (settings). | |
| 1438 | 1438 | | DELETE | `/questions/{id}/solutions/{sid}/image` | student | Remove the solution's photo. Author only, anytime — solutions are never frozen. | |
| 1439 | +| POST | `/rag/questions` | student | Generate practice questions over one range of one corpus the caller may study, with the answers bounded to that range. | | |
| 1440 | +| POST | `/rag/summarize` | student | Summarize one range of one corpus the caller may study. | | |
| 1439 | 1441 | | GET | `/rag/threads` | student | The caller's own threads, most recently active first. Paged via `?limit=&offset=`. Nobody — no teacher, no admin — reads anyone else's. | |
| 1440 | 1442 | | POST | `/rag/threads` | student | Start a new RAG thread, optionally named. Every authenticated role may ask — parents included. A user may keep up to the school's `max_chatbot_threads` threads *across both AI nests*; at the cap the request is refused (409) until an old thread is deleted — the cap is storage protection, not a usage quota (that is the per-minute message limit). | |
| 1441 | 1443 | | PATCH | `/rag/threads/{id}` | student | Rename a thread, or clear its name (`title: null`). Owner only; someone else's thread is a `404`, never a `403`. The edit counts as activity, so the thread moves to the top of the list. | |
| @@ -4129,6 +4131,80 @@ file's ids: the service answers `{"files": [{"id": "<course_note_file id>", | ||
| 4129 | 4131 | it indexed. The backend pairs the echoed `doc_id` back to the file it sent, so |
| 4130 | 4132 | a later citation's `doc_id` resolves to a downloadable file. |
| 4131 | 4133 | |
| 4134 | +### The `rag.summarize` and `rag.questions` capabilities | |
| 4135 | + | |
| 4136 | +Two more capabilities of the same RAG service, over the same `Request`/`Response` | |
| 4137 | +frames. Both are **one-shot**: the caller names exactly one `(sinif, ders)` | |
| 4138 | +corpus and a range inside it and waits for the artifact — a summary, or a set of | |
| 4139 | +practice questions. No thread, no stored row, no poll: where `rag.chat` runs the | |
| 4140 | +round trip behind a `202` with a 90 s budget, each of these rides a **25 s** | |
| 4141 | +dispatch deadline so it finishes inside the HTTP middleware's own 30 s envelope. | |
| 4142 | + | |
| 4143 | +`rag.summarize` asks for: | |
| 4144 | + | |
| 4145 | +```json | |
| 4146 | +{ "scope": { "sinif": "10", "ders": "biyoloji", "pages": [16, 17], | |
| 4147 | + "span_ids": [], "scope_label": "DNA" }, | |
| 4148 | + "asker": "01ASKER", "asker_role": "teacher" } | |
| 4149 | +``` | |
| 4150 | + | |
| 4151 | +`rag.questions` sends the same three keys plus the shape of the set: | |
| 4152 | +`n` (the number of questions), `difficulty` (`kolay`/`orta`/`zor`, whatever the | |
| 4153 | +service knows) and `seed_question` (`null` means "any question in the range"). | |
| 4154 | + | |
| 4155 | +`sinif` is `null` for a school-wide corpus (club/etüt). `pages`/`span_ids` are | |
| 4156 | +the range — normally exactly one of them is used, and naming neither is answered | |
| 4157 | +by the service as an abstention (`empty_scope`) rather than refused here. | |
| 4158 | +`asker`/`asker_role` are the calling user and their live school role, exactly as | |
| 4159 | +on `rag.chat`. | |
| 4160 | + | |
| 4161 | +The summarize reply: | |
| 4162 | + | |
| 4163 | +```json | |
| 4164 | +{ "text": "…", "abstained": false, "reason": "", | |
| 4165 | + "citations": [ { "n": 1, "pages": [16], "span_ids": ["s-3"] } ], | |
| 4166 | + "scope_pages": [16, 17], "hierarchical": true } | |
| 4167 | +``` | |
| 4168 | + | |
| 4169 | +The questions reply, whose row keys are the **service's** own: | |
| 4170 | + | |
| 4171 | +```json | |
| 4172 | +{ "items": [ { "soru": "…", "cevap": "…", "zorluk": "orta" } ], | |
| 4173 | + "abstained": false, "reason": "", "span_ids": ["s-3"], "pages": [16] } | |
| 4174 | +``` | |
| 4175 | + | |
| 4176 | +A refusal that is part of the answer stays here, as it does for `rag.chat`: | |
| 4177 | +`abstained: true` with a `reason` is a complete request, never an `err` frame. | |
| 4178 | +Every optional key defaults, but `text` (summarize) and `items` (questions) are | |
| 4179 | +required — a reply without the artifact is unreadable, not empty. | |
| 4180 | + | |
| 4181 | +The HTTP doors are `POST /rag/summarize` and `POST /rag/questions`, with a flat | |
| 4182 | +body: `ders` (required, non-empty), `sinif`, `pages`, `span_ids`, `scope_label`, | |
| 4183 | +and for questions `n` (default 5, at most 20), `difficulty` (default `orta`) and | |
| 4184 | +`seed_question`. Authorization is the nest's own scope derivation, applied | |
| 4185 | +twice: the caller's `(sınıf, ders)` pairs come from their live memberships and | |
| 4186 | +the body only **names a target inside them** — a pair the caller does not hold is | |
| 4187 | +a `403`, and omitting `sinif` for a ders taught at more than one grade is a | |
| 4188 | +`400`, because choosing a corpus for the caller would answer from material they | |
| 4189 | +never named. The door maps the service's `soru`/`cevap`/`zorluk` onto this API's | |
| 4190 | +`question`/`answer`/`difficulty`. `503` when no service offers the capability, | |
| 4191 | +`504` when the service does not answer in time, and `502` when it answers | |
| 4192 | +something unreadable — including the two verdicts that blame the request the | |
| 4193 | +**backend** built (`role_required`, `scope_mismatch`), which are logged as the | |
| 4194 | +bugs they are instead of being relayed as the caller's own fault. | |
| 4195 | + | |
| 4196 | +Two honest limits, on the RAG side, that the backend cannot paper over: | |
| 4197 | + | |
| 4198 | +* **A grade-less corpus is unroutable.** A `sinif: null` pair is legal on the | |
| 4199 | + wire — a club or etüt membership produces one — but the RAG routes its corpora | |
| 4200 | + by grade, so such a request is answered with an abstention rather than with | |
| 4201 | + material from every grade. Grade-scoped pairs are the ones that retrieve. | |
| 4202 | +* **A summary citation cannot be opened.** A `rag.chat` citation carries the | |
| 4203 | + corpus `doc_id` the backend resolves to the `course_note_file` behind it; a | |
| 4204 | + summary is addressed to a range the caller selected rather than to one | |
| 4205 | + document, so its citations carry no `doc_id` and there is no file to resolve — | |
| 4206 | + the `[N]` markers point at pages and retrieval spans, not at downloads. | |
| 4207 | + | |
| 4132 | 4208 | ### API reads (the other direction) |
| 4133 | 4209 | |
| 4134 | 4210 | A service usually needs school data to do its work — who asked, their notes, |
src/ai/mod.rsmodified+2 -0
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | //! * [`chat`] — the JSON payloads carried for the `chat.reply` capability |
| 18 | 18 | //! * [`rag`] — the `rag.index` payloads, and the course-note dispatch behind them |
| 19 | 19 | //! * [`rag_chat`] — the `rag.chat` payloads: a scoped question and the citations behind its answer |
| 20 | +//! * [`rag_study`] — the `rag.summarize`/`rag.questions` payloads: one range of one corpus, answered in one shot | |
| 20 | 21 | //! * [`podcast`] — the `podcast.*` job payloads, the relay behind submit/cancel, |
| 21 | 22 | //! and the job-state report the service calls back |
| 22 | 23 | //! * [`server`] — the listener, handshake, and [`server::AiBridge::dispatch`] |
| @@ -38,6 +39,7 @@ pub mod podcast; | ||
| 38 | 39 | pub mod protocol; |
| 39 | 40 | pub mod rag; |
| 40 | 41 | pub mod rag_chat; |
| 42 | +pub mod rag_study; | |
| 41 | 43 | pub mod registry; |
| 42 | 44 | pub mod server; |
| 43 | 45 | pub mod tls; |
src/ai/rag_study.rsadded+401 -0
| @@ -0,0 +1,401 @@ | ||
| 1 | +//! Payload contract for the `rag.summarize` and `rag.questions` capabilities. | |
| 2 | +//! | |
| 3 | +//! Same transport as every other capability: JSON inside a | |
| 4 | +//! [`Request::payload`](crate::ai::protocol::Request::payload) and coming back | |
| 5 | +//! inside [`Response::Ok`](crate::ai::protocol::Response::Ok)`::payload`. What | |
| 6 | +//! differs from [`super::rag_chat`] is the shape of a turn: those are | |
| 7 | +//! thread-bound and asynchronous (a `202`, a stored row, a poll), while these | |
| 8 | +//! two are **one-shot** — the caller names exactly one corpus and a range | |
| 9 | +//! inside it and waits for the artifact itself (a summary, or a set of | |
| 10 | +//! practice questions). Nothing is stored on either side of the bridge, so the | |
| 11 | +//! reply *is* the answer. | |
| 12 | +//! | |
| 13 | +//! The scope is one `(sinif, ders)` pair plus the page/span range inside it. | |
| 14 | +//! Which pairs the asker may name is the backend's own derivation | |
| 15 | +//! ([`crate::service::rag_scope`]) and the caller's body only picks a target | |
| 16 | +//! within them, so the pair that travels here is already the authorized one. | |
| 17 | +//! The asker rides along for the same reason it does on `rag.chat`: the service | |
| 18 | +//! may read that person's own data back through the bridge's api reads | |
| 19 | +//! (`on_behalf_of`). | |
| 20 | + | |
| 21 | +use std::time::Duration; | |
| 22 | + | |
| 23 | +use serde::{Deserialize, Serialize}; | |
| 24 | + | |
| 25 | +use crate::ai::AiBridge; | |
| 26 | +use crate::constant::{ | |
| 27 | + AI_RAG_QUESTIONS_CAPABILITY, AI_RAG_QUESTIONS_TIMEOUT_SECS, AI_RAG_SUMMARIZE_CAPABILITY, | |
| 28 | + AI_RAG_SUMMARIZE_TIMEOUT_SECS, | |
| 29 | +}; | |
| 30 | +use crate::tenant::Slug; | |
| 31 | + | |
| 32 | +/// The one corpus a study request is addressed to, and where inside it. | |
| 33 | +/// | |
| 34 | +/// One scope, never a list: a summary or a question set is *about* the | |
| 35 | +/// material the caller selected, and a range spanning several corpora has no | |
| 36 | +/// single thing to be about. | |
| 37 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | |
| 38 | +pub struct RagScope { | |
| 39 | + /// The class/grade the corpus belongs to (`"10"`), or `null` for a | |
| 40 | + /// school-wide corpus (club/etüt), which belongs to no section and so | |
| 41 | + /// names no grade. | |
| 42 | + pub sinif: Option<String>, | |
| 43 | + /// The subject/course name the corpus is routed by — the one field a scope | |
| 44 | + /// cannot go without, since a subject-less scope retrieves nothing. | |
| 45 | + pub ders: String, | |
| 46 | + /// The pages of the corpus to work over, when its source is paginated. | |
| 47 | + /// Empty is legal: a scope with neither pages nor spans is answered with an | |
| 48 | + /// `abstained` reply (`empty_scope`), not refused here. | |
| 49 | + #[serde(default)] | |
| 50 | + pub pages: Vec<i64>, | |
| 51 | + /// Opaque retrieval span ids to work over, for a range the caller already | |
| 52 | + /// holds from an earlier retrieval. Normally exactly one of | |
| 53 | + /// `pages`/`span_ids` is set. | |
| 54 | + #[serde(default)] | |
| 55 | + pub span_ids: Vec<String>, | |
| 56 | + /// A human label for the range (the heading the caller selected), used by | |
| 57 | + /// the service in its own prose. May be empty. | |
| 58 | + #[serde(default)] | |
| 59 | + pub scope_label: String, | |
| 60 | +} | |
| 61 | + | |
| 62 | +/// What the backend asks a RAG service to summarize (`rag.summarize`). | |
| 63 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | |
| 64 | +pub struct RagSummarizePayload { | |
| 65 | + /// The corpus and range to summarize. | |
| 66 | + pub scope: RagScope, | |
| 67 | + /// The id of the person who asked. The service reads that person's own | |
| 68 | + /// data back through the bridge's api reads (`on_behalf_of`). Read live | |
| 69 | + /// from the authenticated session, never taken from a request body. | |
| 70 | + pub asker: String, | |
| 71 | + /// The asker's **school role** — the same lowercase strings the rest of the | |
| 72 | + /// API uses, read live from the session, so a service may refuse a scope a | |
| 73 | + /// student's role may not have. | |
| 74 | + pub asker_role: String, | |
| 75 | +} | |
| 76 | + | |
| 77 | +/// What the backend asks a RAG service for (`rag.questions`). | |
| 78 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | |
| 79 | +pub struct RagQuestionsPayload { | |
| 80 | + /// The corpus and range the questions are generated from — also the bound | |
| 81 | + /// on their answers: a question whose answer is not in this range must not | |
| 82 | + /// be generated. | |
| 83 | + pub scope: RagScope, | |
| 84 | + /// The id of the person who asked, exactly as [`RagSummarizePayload`]'s. | |
| 85 | + pub asker: String, | |
| 86 | + /// The asker's live school role. | |
| 87 | + pub asker_role: String, | |
| 88 | + /// How many questions to generate. The door holds it to a small bounded | |
| 89 | + /// set (1..=20) before dispatching. | |
| 90 | + pub n: u32, | |
| 91 | + /// The difficulty the caller asked for (`kolay`/`orta`/`zor` and whatever | |
| 92 | + /// else the service knows). The backend only forwards it — the vocabulary | |
| 93 | + /// is the service's. | |
| 94 | + pub difficulty: String, | |
| 95 | + /// A question to base the set on, when the caller wants variations of one | |
| 96 | + /// specific exercise. `null` means "any question within the scope". | |
| 97 | + #[serde(default)] | |
| 98 | + pub seed_question: Option<String>, | |
| 99 | +} | |
| 100 | + | |
| 101 | +/// One passage a summary drew on, inside the reply's `citations`. | |
| 102 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | |
| 103 | +pub struct RagSummaryCitation { | |
| 104 | + /// The marker the summary text uses to point at this passage: `[N]` in | |
| 105 | + /// `text` resolves to the citation whose `n` is `N`. | |
| 106 | + pub n: u32, | |
| 107 | + /// The page numbers within the document the passage spans. | |
| 108 | + #[serde(default)] | |
| 109 | + pub pages: Vec<i64>, | |
| 110 | + /// Opaque retrieval span ids within the document. | |
| 111 | + #[serde(default)] | |
| 112 | + pub span_ids: Vec<String>, | |
| 113 | +} | |
| 114 | + | |
| 115 | +/// The service's summary, inside `Response::Ok { payload }`. | |
| 116 | +/// | |
| 117 | +/// Handled failures do *not* come back here — they use the existing | |
| 118 | +/// [`Response::Err`](crate::ai::protocol::Response::Err) `{ code, message }`, | |
| 119 | +/// so there is exactly one failure shape on the bridge for every capability. | |
| 120 | +/// A refusal that is part of the answer (nothing in the named range to | |
| 121 | +/// summarize, a guard) rides here with `abstained: true` and a `reason`: the | |
| 122 | +/// request completes, and nothing is reported as an error. | |
| 123 | +/// | |
| 124 | +/// Unlike `rag.chat`'s citations, these carry **no corpus `doc_id`** — a | |
| 125 | +/// summary is addressed to a range the caller selected, not scoped to one | |
| 126 | +/// document — so nothing here resolves to a course-note file. | |
| 127 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | |
| 128 | +pub struct RagSummarizeReply { | |
| 129 | + /// The summary text. Required: a reply without it is unreadable, not an | |
| 130 | + /// empty summary. | |
| 131 | + pub text: String, | |
| 132 | + /// Whether the service declined to summarize rather than summarizing. | |
| 133 | + #[serde(default)] | |
| 134 | + pub abstained: bool, | |
| 135 | + /// Why it abstained, as a short machine code (`empty_scope`, | |
| 136 | + /// `insufficient_data`, `guard_*`, `model_abstained`, …); empty on an | |
| 137 | + /// ordinary answer. | |
| 138 | + #[serde(default)] | |
| 139 | + pub reason: String, | |
| 140 | + /// The passages the summary drew on, oldest first. | |
| 141 | + #[serde(default)] | |
| 142 | + pub citations: Vec<RagSummaryCitation>, | |
| 143 | + /// The pages the summary actually covered, when the service resolved the | |
| 144 | + /// requested range against the corpus. | |
| 145 | + #[serde(default)] | |
| 146 | + pub scope_pages: Vec<i64>, | |
| 147 | + /// Whether the service summarized the range hierarchically (per section, | |
| 148 | + /// then rolled up) rather than flat. | |
| 149 | + #[serde(default)] | |
| 150 | + pub hierarchical: bool, | |
| 151 | +} | |
| 152 | + | |
| 153 | +/// One generated practice question, inside the reply's `items`. | |
| 154 | +/// | |
| 155 | +/// The keys are the **service's** own (`soru`/`cevap`/`zorluk`) — the wire | |
| 156 | +/// mirrors the service's vocabulary exactly as `rag.chat` mirrors its own, and | |
| 157 | +/// the HTTP door is where they become this API's English field names. | |
| 158 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | |
| 159 | +pub struct RagQuestion { | |
| 160 | + /// The question itself. | |
| 161 | + pub soru: String, | |
| 162 | + /// The answer, generated from the named range and never from outside it — | |
| 163 | + /// the range is the bound that keeps a practice question answerable from | |
| 164 | + /// the material the student holds. | |
| 165 | + pub cevap: String, | |
| 166 | + /// The question's difficulty, in the service's own vocabulary. | |
| 167 | + pub zorluk: String, | |
| 168 | +} | |
| 169 | + | |
| 170 | +/// The service's generated question set, inside `Response::Ok { payload }`. | |
| 171 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | |
| 172 | +pub struct RagQuestionsReply { | |
| 173 | + /// The generated questions, in the order they should be shown. Required: a | |
| 174 | + /// reply without `items` is unreadable; a set that could not be generated | |
| 175 | + /// is `abstained: true` with a `reason` instead. | |
| 176 | + pub items: Vec<RagQuestion>, | |
| 177 | + /// Whether the service declined to generate rather than generating. | |
| 178 | + #[serde(default)] | |
| 179 | + pub abstained: bool, | |
| 180 | + /// Why it abstained, as a short machine code; empty on an ordinary answer. | |
| 181 | + #[serde(default)] | |
| 182 | + pub reason: String, | |
| 183 | + /// The retrieval spans the whole set is bounded to. | |
| 184 | + #[serde(default)] | |
| 185 | + pub span_ids: Vec<String>, | |
| 186 | + /// The pages those spans sit on. | |
| 187 | + #[serde(default)] | |
| 188 | + pub pages: Vec<i64>, | |
| 189 | +} | |
| 190 | + | |
| 191 | +/// Ask a RAG service to summarize one range of one corpus. | |
| 192 | +/// | |
| 193 | +/// `Err` is a short, stable code for the door's refusal table — a transport | |
| 194 | +/// failure, the service's own `Response::Err` verdict, or `bad_reply` when the | |
| 195 | +/// reply was unreadable. Two codes are special: `role_required` and | |
| 196 | +/// `scope_mismatch` mean the **backend** composed a request the service may not | |
| 197 | +/// answer (the pair or the role it sent), so they are logged as bugs here and | |
| 198 | +/// reach the caller as a `502` — the same posture `rag.chat` takes. | |
| 199 | +pub async fn summarize( | |
| 200 | + bridge: &AiBridge, | |
| 201 | + slug: &Slug, | |
| 202 | + payload: RagSummarizePayload, | |
| 203 | +) -> Result<RagSummarizeReply, String> { | |
| 204 | + let asker = payload.asker.clone(); | |
| 205 | + let encoded = encode(&payload, AI_RAG_SUMMARIZE_CAPABILITY)?; | |
| 206 | + let raw = bridge | |
| 207 | + .dispatch_with_timeout( | |
| 208 | + slug, | |
| 209 | + AI_RAG_SUMMARIZE_CAPABILITY, | |
| 210 | + encoded, | |
| 211 | + Duration::from_secs(AI_RAG_SUMMARIZE_TIMEOUT_SECS), | |
| 212 | + ) | |
| 213 | + .await | |
| 214 | + .map_err(failure_code)?; | |
| 215 | + let reply: RagSummarizeReply = decode(raw, AI_RAG_SUMMARIZE_CAPABILITY)?; | |
| 216 | + reject_backend_bug(&reply.reason, &asker, AI_RAG_SUMMARIZE_CAPABILITY)?; | |
| 217 | + Ok(reply) | |
| 218 | +} | |
| 219 | + | |
| 220 | +/// Ask a RAG service to generate practice questions over one range of one | |
| 221 | +/// corpus. The refusal vocabulary is [`summarize`]'s, code for code. | |
| 222 | +pub async fn questions( | |
| 223 | + bridge: &AiBridge, | |
| 224 | + slug: &Slug, | |
| 225 | + payload: RagQuestionsPayload, | |
| 226 | +) -> Result<RagQuestionsReply, String> { | |
| 227 | + let asker = payload.asker.clone(); | |
| 228 | + let encoded = encode(&payload, AI_RAG_QUESTIONS_CAPABILITY)?; | |
| 229 | + let raw = bridge | |
| 230 | + .dispatch_with_timeout( | |
| 231 | + slug, | |
| 232 | + AI_RAG_QUESTIONS_CAPABILITY, | |
| 233 | + encoded, | |
| 234 | + Duration::from_secs(AI_RAG_QUESTIONS_TIMEOUT_SECS), | |
| 235 | + ) | |
| 236 | + .await | |
| 237 | + .map_err(failure_code)?; | |
| 238 | + let reply: RagQuestionsReply = decode(raw, AI_RAG_QUESTIONS_CAPABILITY)?; | |
| 239 | + reject_backend_bug(&reply.reason, &asker, AI_RAG_QUESTIONS_CAPABILITY)?; | |
| 240 | + Ok(reply) | |
| 241 | +} | |
| 242 | + | |
| 243 | +/// Encode one payload; a payload that cannot be encoded is this side's bug, so | |
| 244 | +/// it is logged and reported as `internal` rather than as a service verdict. | |
| 245 | +fn encode<P: Serialize>(payload: &P, capability: &str) -> Result<serde_json::Value, String> { | |
| 246 | + serde_json::to_value(payload).map_err(|err| { | |
| 247 | + tracing::error!("could not encode a {capability} request: {err}"); | |
| 248 | + "internal".to_string() | |
| 249 | + }) | |
| 250 | +} | |
| 251 | + | |
| 252 | +/// Decode one service reply, wrapped in the capability's name. An unreadable | |
| 253 | +/// payload is `bad_reply`: the answer is not safe to guess at, and a service | |
| 254 | +/// that changed its shape must be seen failing rather than half-read. | |
| 255 | +fn decode<R: serde::de::DeserializeOwned>( | |
| 256 | + raw: serde_json::Value, | |
| 257 | + capability: &str, | |
| 258 | +) -> Result<R, String> { | |
| 259 | + serde_json::from_value(raw).map_err(|err| { | |
| 260 | + tracing::warn!("AI service answered with an unreadable {capability} payload: {err}"); | |
| 261 | + "bad_reply".to_string() | |
| 262 | + }) | |
| 263 | +} | |
| 264 | + | |
| 265 | +/// The two verdicts that mean the **backend** built a bad request: the scope or | |
| 266 | +/// the role it sent is not something the service may answer. The request still | |
| 267 | +/// fails — an artifact is not safe to invent — but this side of the bridge is | |
| 268 | +/// the bug, so it is logged as one rather than as an ordinary service refusal. | |
| 269 | +fn reject_backend_bug(reason: &str, asker: &str, capability: &str) -> Result<(), String> { | |
| 270 | + if matches!(reason, "role_required" | "scope_mismatch") { | |
| 271 | + tracing::error!( | |
| 272 | + "{capability} refused a request the backend built: {reason} (asker {asker})" | |
| 273 | + ); | |
| 274 | + return Err(reason.to_string()); | |
| 275 | + } | |
| 276 | + Ok(()) | |
| 277 | +} | |
| 278 | + | |
| 279 | +/// A dispatch failure as a short, stable code the frontend can branch on. The | |
| 280 | +/// same mapping the chatbot nest applies to its own round trip. | |
| 281 | +fn failure_code(err: crate::ai::AiError) -> String { | |
| 282 | + use crate::ai::AiError; | |
| 283 | + match err { | |
| 284 | + AiError::NoWorker(_) | AiError::Setup(_) => "unavailable".to_string(), | |
| 285 | + AiError::Busy(_) => "busy".to_string(), | |
| 286 | + AiError::Timeout(_) => "timed_out".to_string(), | |
| 287 | + AiError::Transport(_) => "transport".to_string(), | |
| 288 | + AiError::Protocol(_) | AiError::IdMismatch { .. } => "protocol".to_string(), | |
| 289 | + // The service's own verdict. Kept verbatim so a service can define | |
| 290 | + // codes the backend has never heard of. | |
| 291 | + AiError::Remote { code, message } => { | |
| 292 | + tracing::warn!("AI RAG service refused the request: {code}: {message}"); | |
| 293 | + if code.trim().is_empty() { | |
| 294 | + "service_error".to_string() | |
| 295 | + } else { | |
| 296 | + code | |
| 297 | + } | |
| 298 | + } | |
| 299 | + } | |
| 300 | +} | |
| 301 | + | |
| 302 | +#[cfg(test)] | |
| 303 | +mod tests { | |
| 304 | + use super::*; | |
| 305 | + use serde_json::json; | |
| 306 | + | |
| 307 | + #[test] | |
| 308 | + fn study_payload_keys_are_the_documented_wire_names() { | |
| 309 | + // Services in other languages match on these literals — a rename here | |
| 310 | + // silently breaks every one of them, so pin the encoding, key names | |
| 311 | + // included (the exact wire key sets are the contract). | |
| 312 | + let summarize = serde_json::to_value(RagSummarizePayload { | |
| 313 | + scope: RagScope { | |
| 314 | + sinif: Some("10".into()), | |
| 315 | + ders: "biyoloji".into(), | |
| 316 | + pages: vec![16, 17], | |
| 317 | + span_ids: vec![], | |
| 318 | + scope_label: "DNA".into(), | |
| 319 | + }, | |
| 320 | + asker: "01ASKER".into(), | |
| 321 | + asker_role: "teacher".into(), | |
| 322 | + }) | |
| 323 | + .unwrap(); | |
| 324 | + assert_eq!( | |
| 325 | + summarize, | |
| 326 | + json!({ | |
| 327 | + "scope": { | |
| 328 | + "sinif": "10", | |
| 329 | + "ders": "biyoloji", | |
| 330 | + "pages": [16, 17], | |
| 331 | + "span_ids": [], | |
| 332 | + "scope_label": "DNA", | |
| 333 | + }, | |
| 334 | + "asker": "01ASKER", | |
| 335 | + "asker_role": "teacher", | |
| 336 | + }) | |
| 337 | + ); | |
| 338 | + | |
| 339 | + // A grade-less (school-wide) corpus sends `sinif: null`, exactly as | |
| 340 | + // `rag.chat`'s pairs do, and a span-addressed range sends no pages. | |
| 341 | + let questions = serde_json::to_value(RagQuestionsPayload { | |
| 342 | + scope: RagScope { | |
| 343 | + sinif: None, | |
| 344 | + ders: "Satranç Kulübü".into(), | |
| 345 | + pages: vec![], | |
| 346 | + span_ids: vec!["s-7".into()], | |
| 347 | + scope_label: String::new(), | |
| 348 | + }, | |
| 349 | + asker: "01ASKER".into(), | |
| 350 | + asker_role: "student".into(), | |
| 351 | + n: 5, | |
| 352 | + difficulty: "orta".into(), | |
| 353 | + seed_question: None, | |
| 354 | + }) | |
| 355 | + .unwrap(); | |
| 356 | + assert_eq!( | |
| 357 | + questions, | |
| 358 | + json!({ | |
| 359 | + "scope": { | |
| 360 | + "sinif": null, | |
| 361 | + "ders": "Satranç Kulübü", | |
| 362 | + "pages": [], | |
| 363 | + "span_ids": ["s-7"], | |
| 364 | + "scope_label": "", | |
| 365 | + }, | |
| 366 | + "asker": "01ASKER", | |
| 367 | + "asker_role": "student", | |
| 368 | + "n": 5, | |
| 369 | + "difficulty": "orta", | |
| 370 | + "seed_question": null, | |
| 371 | + }) | |
| 372 | + ); | |
| 373 | + | |
| 374 | + // Every optional reply field defaults on a minimal service answer, and | |
| 375 | + // the one required field of each stays required: a reply without text | |
| 376 | + // (or without items) is unreadable, never an empty artifact. | |
| 377 | + let bare: RagSummarizeReply = | |
| 378 | + serde_json::from_value(json!({ "text": "özet" })).unwrap(); | |
| 379 | + assert!(!bare.abstained); | |
| 380 | + assert_eq!(bare.reason, ""); | |
| 381 | + assert!(bare.citations.is_empty()); | |
| 382 | + assert!(bare.scope_pages.is_empty()); | |
| 383 | + assert!(!bare.hierarchical); | |
| 384 | + assert!(serde_json::from_value::<RagSummarizeReply>(json!({ "abstained": true })).is_err()); | |
| 385 | + | |
| 386 | + let bare: RagQuestionsReply = serde_json::from_value(json!({ "items": [] })).unwrap(); | |
| 387 | + assert!(!bare.abstained); | |
| 388 | + assert_eq!(bare.reason, ""); | |
| 389 | + assert!(bare.span_ids.is_empty()); | |
| 390 | + assert!(bare.pages.is_empty()); | |
| 391 | + assert!(serde_json::from_value::<RagQuestionsReply>(json!({ "abstained": true })).is_err()); | |
| 392 | + | |
| 393 | + // The question row keeps the service's own keys. | |
| 394 | + let row: RagQuestion = | |
| 395 | + serde_json::from_value(json!({ "soru": "DNA nedir?", "cevap": "…", "zorluk": "orta" })) | |
| 396 | + .unwrap(); | |
| 397 | + assert_eq!(row.soru, "DNA nedir?"); | |
| 398 | + assert_eq!(row.cevap, "…"); | |
| 399 | + assert_eq!(row.zorluk, "orta"); | |
| 400 | + } | |
| 401 | +} |
src/constant.rsmodified+40 -0
| @@ -594,6 +594,39 @@ pub const AI_RAG_CHAT_CAPABILITY: &str = "rag.chat"; | ||
| 594 | 594 | /// alone. |
| 595 | 595 | pub const AI_RAG_CHAT_TIMEOUT_SECS: u64 = 90; |
| 596 | 596 | |
| 597 | +/// The capability an AI service declares to summarize one page/span range of | |
| 598 | +/// one school's course-note corpus. One-shot and synchronous, unlike | |
| 599 | +/// [`AI_RAG_CHAT_CAPABILITY`]: the caller names exactly one `(sinif, ders)` | |
| 600 | +/// corpus plus the range inside it and waits for the summary itself — no | |
| 601 | +/// thread, no stored row. With no worker carrying it the door reports the | |
| 602 | +/// service as unavailable. | |
| 603 | +pub const AI_RAG_SUMMARIZE_CAPABILITY: &str = "rag.summarize"; | |
| 604 | + | |
| 605 | +/// Deadline on one `rag.summarize` round trip, and deliberately the short | |
| 606 | +/// waiting-door budget of this family: the door **waits** for the summary and | |
| 607 | +/// every HTTP request shares one envelope, [`REQUEST_TIMEOUT_SECS`] (30 s). | |
| 608 | +/// That middleware drops the handler future wherever it stands and answers its | |
| 609 | +/// own `503`, whose prose is written for a request that may have written | |
| 610 | +/// something — wrong for a door that stores nothing. So the dispatch deadline | |
| 611 | +/// stays **under** the ceiling: the service gets 25 s and this side's own error | |
| 612 | +/// path fires first with the honest verdict (the service did not answer). | |
| 613 | +/// Raising this value needs the middleware ceiling raised with it. | |
| 614 | +pub const AI_RAG_SUMMARIZE_TIMEOUT_SECS: u64 = 25; | |
| 615 | + | |
| 616 | +/// The capability an AI service declares to generate practice questions over | |
| 617 | +/// one page/span range of one school's course-note corpus, with the answers | |
| 618 | +/// bounded to that range. Like [`AI_RAG_SUMMARIZE_CAPABILITY`] it is one-shot | |
| 619 | +/// and synchronous — nothing is stored — and it is its own capability because a | |
| 620 | +/// deployment may serve summaries without serving question generation. | |
| 621 | +pub const AI_RAG_QUESTIONS_CAPABILITY: &str = "rag.questions"; | |
| 622 | + | |
| 623 | +/// Deadline on one `rag.questions` round trip. The same waiting-door budget as | |
| 624 | +/// [`AI_RAG_SUMMARIZE_TIMEOUT_SECS`] for the same reason: generating N | |
| 625 | +/// questions is one model round trip the caller waits on, and it must finish | |
| 626 | +/// inside the middleware's [`REQUEST_TIMEOUT_SECS`] envelope rather than be cut | |
| 627 | +/// by it mid-flight. | |
| 628 | +pub const AI_RAG_QUESTIONS_TIMEOUT_SECS: u64 = 25; | |
| 629 | + | |
| 597 | 630 | /// The capability an AI service declares to analyse one student (ZEKA, |
| 598 | 631 | /// `hezarfen_zeka`). It is the on-demand half of ZEKA — the service also |
| 599 | 632 | /// recomputes on its own schedule — and it is what a teacher's "calculate" is |
| @@ -827,6 +860,13 @@ pub const PODCAST_INTERRUPTED_CODE: &str = "interrupted"; | ||
| 827 | 860 | /// question the asker did not ask, scoped to corpora they did not name. |
| 828 | 861 | pub const MAX_RAG_SCOPE_PAIRS: usize = 200; |
| 829 | 862 | |
| 863 | +/// The most practice questions one `rag.questions` request may ask for. The | |
| 864 | +/// caller waits on the generation, so this is the ceiling on one model round | |
| 865 | +/// trip — not a corpus sweep — and the door refuses a larger set before it | |
| 866 | +/// dispatches anything. Published at `GET /limits` (`rag.max_questions`) so a | |
| 867 | +/// client bounds its own input instead of hard-coding the number. | |
| 868 | +pub const MAX_RAG_QUESTIONS: u32 = 20; | |
| 869 | + | |
| 830 | 870 | /// Default per-minute message limit for the RAG nest, when the school sets |
| 831 | 871 | /// none — a lower ceiling than the chatbot's, since every message here spends |
| 832 | 872 | /// a retrieval over the whole course-note corpus before it generates anything. |
src/lib.rsmodified+1 -1
| @@ -56,7 +56,7 @@ use crate::web::module_gate::gate; | ||
| 56 | 56 | (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."), |
| 57 | 57 | (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 `<slug>.<token>` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.<token>` 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"), |
| 58 | 58 | (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"), |
| 59 | - (name = "rag", description = "The course-note RAG: its own nest, threads and tables, relayed through the same QUIC bridge as the chatbot — RAG is not folded into the chatbot's storage. Every authenticated role may ask (parents included) and every thread is private to its owner. Every question is scoped server-side to the asker's own `(sınıf, ders)` pairs, derived on each request from their live memberships — their şubeler' instances, a linked parent's children, and the school-wide club/etüt memberships they hold (which scope the subject across grades, `sinif: null`) — never from the body, so a caller cannot widen their own retrieval; a scope past `MAX_RAG_SCOPE_PAIRS` pairs is refused (400) rather than narrowed. A RAG thread draws on the school's existing AI thread seats (`max_chatbot_threads`, the same seat count the chatbot nest uses, one pool per user), its prompts and answers are bounded by `max_chatbot_message_len`, and its per-minute tier is its own: `RATE_LIMIT_RAG_PER_MINUTE` (default 6, `0` disables the tier; 429 with `Retry-After`). Sending is asynchronous exactly as the chatbot's is: `POST /rag/threads/{id}/messages` writes the turn plus a `pending` assistant row and answers `202`, then poll `GET /rag/threads/{id}/messages/{mid}` or open its `/stream` (SSE `delta`s then `done`/`error`). `503` when no AI service offers `rag.chat`, with nothing written. An answer may abstain — `abstained: true` with a `reason` (`guard_*`, `insufficient_data`, `model_abstained`) is a complete, successful turn, not an error — and carries its `citations`, up to `MAX_RAG_CITATIONS` per answer and at most `MAX_RAG_CITATION_PAGES` pages each (a service reply past either cap fails the turn whole). Each citation's corpus `doc_id` is resolved to the course-note file that owns it (`file`, `null` when no file the asker may view claims that document) beside the pages and retrieval span ids behind it."), | |
| 59 | + (name = "rag", description = "The course-note RAG: its own nest, threads and tables, relayed through the same QUIC bridge as the chatbot — RAG is not folded into the chatbot's storage. Every authenticated role may ask (parents included) and every thread is private to its owner. Every question is scoped server-side to the asker's own `(sınıf, ders)` pairs, derived on each request from their live memberships — their şubeler' instances, a linked parent's children, and the school-wide club/etüt memberships they hold (which scope the subject across grades, `sinif: null`) — never from the body, so a caller cannot widen their own retrieval; a scope past `MAX_RAG_SCOPE_PAIRS` pairs is refused (400) rather than narrowed. A RAG thread draws on the school's existing AI thread seats (`max_chatbot_threads`, the same seat count the chatbot nest uses, one pool per user), its prompts and answers are bounded by `max_chatbot_message_len`, and its per-minute tier is its own: `RATE_LIMIT_RAG_PER_MINUTE` (default 6, `0` disables the tier; 429 with `Retry-After`). Sending is asynchronous exactly as the chatbot's is: `POST /rag/threads/{id}/messages` writes the turn plus a `pending` assistant row and answers `202`, then poll `GET /rag/threads/{id}/messages/{mid}` or open its `/stream` (SSE `delta`s then `done`/`error`). `503` when no AI service offers `rag.chat`, with nothing written. An answer may abstain — `abstained: true` with a `reason` (`guard_*`, `insufficient_data`, `model_abstained`) is a complete, successful turn, not an error — and carries its `citations`, up to `MAX_RAG_CITATIONS` per answer and at most `MAX_RAG_CITATION_PAGES` pages each (a service reply past either cap fails the turn whole). Each citation's corpus `doc_id` is resolved to the course-note file that owns it (`file`, `null` when no file the asker may view claims that document) beside the pages and retrieval span ids behind it. Two **study** doors are one-shot and synchronous rather than threaded: `POST /rag/summarize` returns a summary of one page/span range and `POST /rag/questions` returns a set of practice questions (plus their range-bounded answers) over one — the artifact is the answer, so nothing is stored and there is no thread or poll. Their body names only a *target within* the asker's own derived pairs (the body's `sinif` plus `ders`): a pair the caller does not hold is `403`, and omitting `sinif` for a ders taught at more than one grade is `400` — the backend never picks a corpus for the caller. Both answer `503` when no AI service offers `rag.summarize`/`rag.questions`, and an `abstained: true` reply with a `reason` is a complete `200`, exactly as on a chat turn. Each waits on its dispatch under a 25 s deadline, deliberately inside the middleware's own 30 s envelope — a dropped handler would answer with prose written for a request that may have written something."), | |
| 60 | 60 | (name = "insights", description = "ZEKA's computed student insights. The `hezarfen_zeka` AI service dials in over the same QUIC bridge as the chatbot, but it does **not** touch a school database: the backend owns every statement against the `zeka_*` tables, and the service calls the backend by name (`insight.*` capabilities on a client-initiated stream — see `src/ai/insight.rs`) to have its computed rows written and read back. So this nest reads what the service computed and asks it to compute on demand, and its write doors are the same operations the bridge serves: `POST /insights/summaries`, `/recommendations`, `/segments`, `/profiles` and `/runs` store one batch each (manager+, one call one transaction, rows about students school-wide), `GET /insights/pending` is the students the freshest run left pending, and `POST /insights/sweep` / `POST /insights/purge` are retention and graduation housekeeping — all scoped to the caller's own school by the nest's extractors, and none of them takes a school, a database or a query in its body. `GET /insights/schools` is the exception and is not this nest's usual principal: the active-school directory names every customer, so it is mounted on the **builder** principal outside the school gate (a school session answers `401`), exactly like the vendor surface's `GET /schools`. `GET /insights/me` is the caller's own view: a student's summary, their own recommendation cards and their segment profile — and **never** the attention list about themselves, which is a teacher's tool and is not returned to a student or to a linked parent. `GET /insights/students/{id}` is the observer's view of one student — teacher+ narrowed to the students they actually reach through a shared class×course instance, or a parent holding a live link — adding the attention list and the caller's own cards about that student; anyone else reads `404`, never `403`. `POST /insights/students/{id}` and `POST /insights/refresh` (manager+) queue a recompute through the bridge and answer `202` — the compute lands in the service's own rows, so a client polls the read routes; `GET /insights/runs` (manager+) is the run ledger, newest first. Both dispatch doors answer `503` when no service offers the capability, and nothing is queued. Expired and dismissed cards are filtered out of every card read, segment rows below 30 answers (`confidence: none`) are filtered out of every profile read, and a card's `about` is never returned to a student caller."), |
| 61 | 61 | (name = "podcast", description = "Podcast generation, relayed through the same QUIC bridge as the chatbot and the RAG nest — and the **backend owns the job**, not just the HTTP surface. `POST /podcast/jobs` (`{source_id, format?}`) resolves the note's newest `application/pdf` attachment — the blob key the dispatch hands the service as `source_key`, so the service opens `<media root>/<school>/<source_key>` — refusing `409 source_missing` when the note has no PDF or its bytes are missing from this host, then mints the job id, writes the row, dispatches `podcast.submit` to the service and answers `202` with `{job_id, state, eta_secs}`; `GET /podcast/jobs/{id}` polls the backend's own row `{state, stage, progress, error_code}` with no service round trip, `GET /podcast/jobs/{id}/result` collects a finished job's `{audio_id, duration_secs, format}` (`409` while it is still running), `GET /podcast/jobs/{id}/audio` streams the episode the service uploaded into this school's own blob directory, and `POST /podcast/jobs/{id}/cancel` asks the service to stop it (`cancelled` is \"this call stopped work\", so a finished job answers `false`; a terminal job answers without the service); `GET /podcast/jobs` is the caller's own history, newest first (`?limit=&offset=`), each row carrying the title of the note it narrated. The service reports every transition back through the `podcast.report` capability and uploads the finished mp3 — so status, result and audio keep answering while the service is down or restarted, and a job nobody is updating reads as failed/interrupted after an ETA-scaled window. Submit and cancel refuse `503` when no worker is connected; none of the four read doors needs one (404 for an unknown or foreign job, 410 past the retention window, 409 before the job is done or when its blob is missing from this host)."), |
| 62 | 62 | (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins…, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"), |
src/web/limits.rsmodified+5 -0
| @@ -367,6 +367,10 @@ struct RagLimits { | ||
| 367 | 367 | /// corpus is routed by the pair, so this bounds what one question can ask |
| 368 | 368 | /// a retrieval to sweep. |
| 369 | 369 | max_scope_pairs: usize, |
| 370 | + /// Hard ceiling on the practice questions one `POST /rag/questions` call | |
| 371 | + /// may ask for. The caller waits on the generation, so this bounds one | |
| 372 | + /// model round trip rather than a corpus sweep. | |
| 373 | + max_questions: u32, | |
| 370 | 374 | /// Hard ceiling on the citations one answer may store in its message row. |
| 371 | 375 | max_citations: usize, |
| 372 | 376 | /// Pages one citation may span. A citation names a page range, and an |
| @@ -686,6 +690,7 @@ impl LimitsResponse { | ||
| 686 | 690 | }, |
| 687 | 691 | rag: RagLimits { |
| 688 | 692 | max_scope_pairs: MAX_RAG_SCOPE_PAIRS, |
| 693 | + max_questions: MAX_RAG_QUESTIONS, | |
| 689 | 694 | max_citations: MAX_RAG_CITATIONS, |
| 690 | 695 | max_citation_pages: MAX_RAG_CITATION_PAGES, |
| 691 | 696 | max_message_len: MAX_CHATBOT_MESSAGE_LEN, |
src/web/rag.rsmodified+446 -1
| @@ -31,6 +31,13 @@ | ||
| 31 | 31 | //! restart therefore orphans a turn in flight: its row stays `pending` until a |
| 32 | 32 | //! reader projects it failed, and the boot sweep stamps that verdict durably |
| 33 | 33 | //! ([`crate::constant::RAG_PENDING_STALE_SECS`]). |
| 34 | +//! | |
| 35 | +//! The two **study** doors (`POST /rag/summarize`, `POST /rag/questions`) are | |
| 36 | +//! the exception to that shape, and deliberately: a summary or a question set | |
| 37 | +//! is one artifact about one range of one corpus, so there is no thread to | |
| 38 | +//! open, no row to poll and nothing stored — the request waits for the | |
| 39 | +//! artifact, under a dispatch deadline kept inside the middleware's own | |
| 40 | +//! envelope. | |
| 34 | 41 | |
| 35 | 42 | use std::time::Duration; |
| 36 | 43 | |
| @@ -53,9 +60,14 @@ use utoipa_axum::routes; | ||
| 53 | 60 | |
| 54 | 61 | use crate::ai::chat::ChatRole; |
| 55 | 62 | use crate::ai::rag_chat::RagScopePair; |
| 63 | +use crate::ai::rag_study::{ | |
| 64 | + self, RagQuestion, RagQuestionsPayload, RagQuestionsReply, RagScope, RagSummarizePayload, | |
| 65 | + RagSummarizeReply, RagSummaryCitation, | |
| 66 | +}; | |
| 56 | 67 | use crate::ai::AiBridge; |
| 57 | 68 | use crate::constant::{ |
| 58 | - AI_RAG_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN, REPLY_CHUNKS, | |
| 69 | + AI_RAG_CHAT_CAPABILITY, AI_RAG_QUESTIONS_CAPABILITY, AI_RAG_SUMMARIZE_CAPABILITY, | |
| 70 | + CHAT_STREAM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN, MAX_RAG_QUESTIONS, REPLY_CHUNKS, | |
| 59 | 71 | }; |
| 60 | 72 | use crate::database::Database; |
| 61 | 73 | use crate::domain::rag_message::{ |
| @@ -78,6 +90,10 @@ pub fn routes() -> OpenApiRouter<AppState> { | ||
| 78 | 90 | .routes(routes!(list_messages, send_message)) |
| 79 | 91 | .routes(routes!(read_message)) |
| 80 | 92 | .routes(routes!(stream_message)) |
| 93 | + // One `routes!(…)` call is one *path*: two handlers in it must share | |
| 94 | + // it (different methods). These two doors share neither. | |
| 95 | + .routes(routes!(summarize)) | |
| 96 | + .routes(routes!(questions)) | |
| 81 | 97 | } |
| 82 | 98 | |
| 83 | 99 | // ---- threads ---------------------------------------------------------- |
| @@ -828,6 +844,386 @@ async fn stream_message( | ||
| 828 | 844 | Ok(Sse::new(ReceiverStream::new(rx)).keep_alive(KeepAlive::default())) |
| 829 | 845 | } |
| 830 | 846 | |
| 847 | +// ---- the one-shot study doors ---------------------------------------------- | |
| 848 | +// | |
| 849 | +// Two capabilities of the same RAG service, each exactly one dispatch: a | |
| 850 | +// summary of one page/span range, and a set of practice questions over one. | |
| 851 | +// They are this nest's only doors that neither thread nor store — the artifact | |
| 852 | +// *is* the answer — so they wait for it, and no per-user rate limiter charges | |
| 853 | +// them: one-shot requests cannot be retried into a loop the way a thread can, | |
| 854 | +// and the RAG counts its own per-call rate and budget caps. | |
| 855 | +// | |
| 856 | +// Authorization is the nest's own scope derivation, applied twice: the asker's | |
| 857 | +// `(sinif, ders)` pairs come from [`service::rag_scope::for_user`] — never from | |
| 858 | +// the body — and the body only *names* a target inside them | |
| 859 | +// ([`resolve_study_pair`]). The pair that travels to the service is the derived | |
| 860 | +// one, so the corpus it retrieves from is a corpus the backend already decided | |
| 861 | +// the asker may study. The service's own scope guard is defence in depth: when | |
| 862 | +// it answers `role_required`/`scope_mismatch` the **backend** built a bad | |
| 863 | +// request, and that is reported as one (a `502`, logged by | |
| 864 | +// [`crate::ai::rag_study`]). | |
| 865 | + | |
| 866 | +/// The scope half of a study request: which corpus, and which range inside it. | |
| 867 | +#[derive(Deserialize, ToSchema)] | |
| 868 | +struct StudyScopeRequest { | |
| 869 | + /// The subject/course to study. Required, non-empty. | |
| 870 | + ders: String, | |
| 871 | + /// The şube/grade the corpus belongs to. Optional — a school-wide corpus | |
| 872 | + /// (club/etüt) has none — and required in practice when the subject is | |
| 873 | + /// taught at more than one grade: the door then answers `400` instead of | |
| 874 | + /// guessing which section the caller meant. | |
| 875 | + #[serde(default)] | |
| 876 | + sinif: Option<String>, | |
| 877 | + /// Pages of the corpus to work over. Normally exactly one of | |
| 878 | + /// `pages`/`span_ids` is named; naming neither is answered by the service | |
| 879 | + /// as an abstention (`empty_scope`), not refused here. | |
| 880 | + #[serde(default)] | |
| 881 | + pages: Vec<i64>, | |
| 882 | + /// Retrieval span ids to work over, for a range the caller already holds | |
| 883 | + /// from an earlier retrieval. | |
| 884 | + #[serde(default)] | |
| 885 | + span_ids: Vec<String>, | |
| 886 | + /// A human label for the range (the heading the caller selected). | |
| 887 | + #[serde(default)] | |
| 888 | + scope_label: Option<String>, | |
| 889 | +} | |
| 890 | + | |
| 891 | +impl StudyScopeRequest { | |
| 892 | + /// The wire scope this request names, with the **resolved** pair as its | |
| 893 | + /// `(sinif, ders)` half: the corpus the service is addressed to is the one | |
| 894 | + /// the asker's own memberships authorized, never the body's spelling of | |
| 895 | + /// it. | |
| 896 | + fn into_scope(self, pair: RagScopePair) -> RagScope { | |
| 897 | + RagScope { | |
| 898 | + sinif: pair.sinif, | |
| 899 | + ders: pair.ders, | |
| 900 | + pages: self.pages, | |
| 901 | + span_ids: self.span_ids, | |
| 902 | + scope_label: self.scope_label.unwrap_or_default(), | |
| 903 | + } | |
| 904 | + } | |
| 905 | +} | |
| 906 | + | |
| 907 | +/// A `/rag/questions` body: the same scope, plus the shape of the set to | |
| 908 | +/// generate. | |
| 909 | +#[derive(Deserialize, ToSchema)] | |
| 910 | +struct QuestionsRequest { | |
| 911 | + #[serde(flatten)] | |
| 912 | + scope: StudyScopeRequest, | |
| 913 | + /// How many questions to generate. Defaults to 5; the door holds it to | |
| 914 | + /// `1..=20`. | |
| 915 | + #[serde(default = "default_question_count")] | |
| 916 | + n: u32, | |
| 917 | + /// The difficulty asked for, in the service's own vocabulary | |
| 918 | + /// (`kolay`/`orta`/`zor`), defaulting to `orta`. Forwarded, never judged | |
| 919 | + /// here: the vocabulary belongs to the service. | |
| 920 | + #[serde(default = "default_difficulty")] | |
| 921 | + difficulty: String, | |
| 922 | + /// A question to base the set on, when the caller wants variations of one | |
| 923 | + /// particular exercise. Omitted means "any question within the range". | |
| 924 | + #[serde(default)] | |
| 925 | + seed_question: Option<String>, | |
| 926 | +} | |
| 927 | + | |
| 928 | +fn default_question_count() -> u32 { | |
| 929 | + 5 | |
| 930 | +} | |
| 931 | + | |
| 932 | +fn default_difficulty() -> String { | |
| 933 | + "orta".to_string() | |
| 934 | +} | |
| 935 | + | |
| 936 | +/// One citation behind a summary, as the bridge carries it. Unlike `rag.chat`'s | |
| 937 | +/// citations it names no corpus document, so nothing here resolves to a | |
| 938 | +/// course-note file: a summary is addressed to a range the caller selected. | |
| 939 | +#[derive(Serialize, ToSchema)] | |
| 940 | +struct RagSummaryCitationResponse { | |
| 941 | + n: u32, | |
| 942 | + pages: Vec<i64>, | |
| 943 | + span_ids: Vec<String>, | |
| 944 | +} | |
| 945 | + | |
| 946 | +impl From<RagSummaryCitation> for RagSummaryCitationResponse { | |
| 947 | + fn from(citation: RagSummaryCitation) -> Self { | |
| 948 | + Self { | |
| 949 | + n: citation.n, | |
| 950 | + pages: citation.pages, | |
| 951 | + span_ids: citation.span_ids, | |
| 952 | + } | |
| 953 | + } | |
| 954 | +} | |
| 955 | + | |
| 956 | +/// A summary of one range of one corpus. `abstained` with a `reason` is a | |
| 957 | +/// complete answer, exactly as it is on a chat turn. | |
| 958 | +#[derive(Serialize, ToSchema)] | |
| 959 | +struct RagSummarizeResponse { | |
| 960 | + text: String, | |
| 961 | + abstained: bool, | |
| 962 | + reason: String, | |
| 963 | + citations: Vec<RagSummaryCitationResponse>, | |
| 964 | + /// The pages the summary actually covered. | |
| 965 | + scope_pages: Vec<i64>, | |
| 966 | + /// Whether the service summarized hierarchically (per section, then rolled | |
| 967 | + /// up) rather than flat. | |
| 968 | + hierarchical: bool, | |
| 969 | +} | |
| 970 | + | |
| 971 | +impl From<RagSummarizeReply> for RagSummarizeResponse { | |
| 972 | + fn from(reply: RagSummarizeReply) -> Self { | |
| 973 | + Self { | |
| 974 | + text: reply.text, | |
| 975 | + abstained: reply.abstained, | |
| 976 | + reason: reply.reason, | |
| 977 | + citations: reply.citations.into_iter().map(Into::into).collect(), | |
| 978 | + scope_pages: reply.scope_pages, | |
| 979 | + hierarchical: reply.hierarchical, | |
| 980 | + } | |
| 981 | + } | |
| 982 | +} | |
| 983 | + | |
| 984 | +/// One generated practice question. The bridge's `soru`/`cevap`/`zorluk` become | |
| 985 | +/// this API's `question`/`answer`/`difficulty` here: the wire keeps the | |
| 986 | +/// service's vocabulary, the HTTP surface keeps the backend's. | |
| 987 | +#[derive(Serialize, ToSchema)] | |
| 988 | +struct RagQuestionResponse { | |
| 989 | + question: String, | |
| 990 | + answer: String, | |
| 991 | + difficulty: String, | |
| 992 | +} | |
| 993 | + | |
| 994 | +impl From<RagQuestion> for RagQuestionResponse { | |
| 995 | + fn from(question: RagQuestion) -> Self { | |
| 996 | + Self { | |
| 997 | + question: question.soru, | |
| 998 | + answer: question.cevap, | |
| 999 | + difficulty: question.zorluk, | |
| 1000 | + } | |
| 1001 | + } | |
| 1002 | +} | |
| 1003 | + | |
| 1004 | +/// A generated set of practice questions over one range of one corpus. | |
| 1005 | +#[derive(Serialize, ToSchema)] | |
| 1006 | +struct RagQuestionsResponse { | |
| 1007 | + items: Vec<RagQuestionResponse>, | |
| 1008 | + abstained: bool, | |
| 1009 | + reason: String, | |
| 1010 | + /// The retrieval spans the whole set is bounded to. | |
| 1011 | + span_ids: Vec<String>, | |
| 1012 | + /// The pages those spans sit on. | |
| 1013 | + pages: Vec<i64>, | |
| 1014 | +} | |
| 1015 | + | |
| 1016 | +impl From<RagQuestionsReply> for RagQuestionsResponse { | |
| 1017 | + fn from(reply: RagQuestionsReply) -> Self { | |
| 1018 | + Self { | |
| 1019 | + items: reply.items.into_iter().map(Into::into).collect(), | |
| 1020 | + abstained: reply.abstained, | |
| 1021 | + reason: reply.reason, | |
| 1022 | + span_ids: reply.span_ids, | |
| 1023 | + pages: reply.pages, | |
| 1024 | + } | |
| 1025 | + } | |
| 1026 | +} | |
| 1027 | + | |
| 1028 | +/// The one `(sınıf, ders)` pair a study request may address, resolved against | |
| 1029 | +/// the asker's own derived pairs — the body only *names* a target inside them. | |
| 1030 | +/// | |
| 1031 | +/// A named grade must be a pair the asker holds **exactly**; anything else is a | |
| 1032 | +/// `403`, because a corpus the asker cannot study must not be summarized on | |
| 1033 | +/// their behalf. An absent or empty grade resolves the subject alone: exactly | |
| 1034 | +/// one pair for that `ders` is the target, none is a `403`, and more than one | |
| 1035 | +/// is a `400` — the caller must name the şube, since picking one for them would | |
| 1036 | +/// answer from a corpus they did not name. | |
| 1037 | +fn resolve_study_pair( | |
| 1038 | + pairs: &[RagScopePair], | |
| 1039 | + ders: &str, | |
| 1040 | + sinif: Option<&str>, | |
| 1041 | +) -> Result<RagScopePair, AppError> { | |
| 1042 | + if ders.trim().is_empty() { | |
| 1043 | + return Err(AppError::Validation(ValidationError::Empty("ders"))); | |
| 1044 | + } | |
| 1045 | + match sinif.filter(|grade| !grade.trim().is_empty()) { | |
| 1046 | + Some(grade) => pairs | |
| 1047 | + .iter() | |
| 1048 | + .find(|pair| pair.ders == ders && pair.sinif.as_deref() == Some(grade)) | |
| 1049 | + .cloned() | |
| 1050 | + .ok_or(AppError::Forbidden( | |
| 1051 | + "the requested ders/sinif pair is not in your scope", | |
| 1052 | + )), | |
| 1053 | + None => { | |
| 1054 | + let mut candidates = pairs.iter().filter(|pair| pair.ders == ders); | |
| 1055 | + let Some(first) = candidates.next() else { | |
| 1056 | + return Err(AppError::Forbidden( | |
| 1057 | + "the requested ders is not in your scope", | |
| 1058 | + )); | |
| 1059 | + }; | |
| 1060 | + if candidates.next().is_some() { | |
| 1061 | + return Err(AppError::Validation(ValidationError::Invalid { | |
| 1062 | + field: "sinif", | |
| 1063 | + reason: "name the grade: this ders is taught in more than one", | |
| 1064 | + })); | |
| 1065 | + } | |
| 1066 | + Ok(first.clone()) | |
| 1067 | + } | |
| 1068 | + } | |
| 1069 | +} | |
| 1070 | + | |
| 1071 | +/// Summarize one range of one corpus the caller may study. | |
| 1072 | +/// | |
| 1073 | +/// Synchronous by design: the summary is what the caller asked for, so there is | |
| 1074 | +/// no thread to open, no row to poll and nothing stored. The scope is derived | |
| 1075 | +/// from the asker's own memberships — never from the body, which only names a | |
| 1076 | +/// target inside them — and the `(sinif, ders)` pair that reaches the service | |
| 1077 | +/// is the derived one. `503` when no AI service offers `rag.summarize`. | |
| 1078 | +/// `abstained: true` with a `reason` is a complete answer riding a `200`. | |
| 1079 | +/// | |
| 1080 | +/// The dispatch deadline (25 s) is deliberately under the middleware's own | |
| 1081 | +/// 30 s envelope ([`crate::constant::REQUEST_TIMEOUT_SECS`]): this door waits, | |
| 1082 | +/// and being dropped mid-flight would answer with prose written for a request | |
| 1083 | +/// that may have written something. | |
| 1084 | +#[utoipa::path( | |
| 1085 | + post, | |
| 1086 | + path = "/summarize", | |
| 1087 | + tag = "rag", | |
| 1088 | + security(("session_cookie" = [])), | |
| 1089 | + request_body = StudyScopeRequest, | |
| 1090 | + responses( | |
| 1091 | + (status = 200, description = "The summary — possibly an abstention: `abstained: true` with a `reason` is a complete answer", body = RagSummarizeResponse), | |
| 1092 | + (status = 400, description = "`ders` is empty, or `sinif` was omitted for a ders taught in more than one grade", body = ErrorResponse), | |
| 1093 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 1094 | + (status = 403, description = "The requested `(sinif, ders)` is not one of the caller's own scopes", body = ErrorResponse), | |
| 1095 | + (status = 409, description = "The AI service refused to run the request — its model is unavailable, or the request was over its rate or budget cap", body = ErrorResponse), | |
| 1096 | + (status = 502, description = "The AI service answered something this backend could not use, or built a request it refused", body = ErrorResponse), | |
| 1097 | + (status = 503, description = "No AI service offers `rag.summarize` right now", body = ErrorResponse), | |
| 1098 | + (status = 504, description = "The AI service did not answer within the dispatch deadline", body = ErrorResponse), | |
| 1099 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | |
| 1100 | + ), | |
| 1101 | +)] | |
| 1102 | +async fn summarize( | |
| 1103 | + State(st): State<AppState>, | |
| 1104 | + SchoolSlug(slug): SchoolSlug, | |
| 1105 | + CurrentUser(user): CurrentUser, | |
| 1106 | + Json(req): Json<StudyScopeRequest>, | |
| 1107 | +) -> Result<Response, AppError> { | |
| 1108 | + let Some(bridge) = st.ai.clone() else { | |
| 1109 | + return Ok(ai_unavailable( | |
| 1110 | + "the AI service is not enabled on this deployment", | |
| 1111 | + )); | |
| 1112 | + }; | |
| 1113 | + if !bridge.has_capability(AI_RAG_SUMMARIZE_CAPABILITY) { | |
| 1114 | + return Ok(ai_unavailable("no AI service is connected right now")); | |
| 1115 | + } | |
| 1116 | + | |
| 1117 | + // The scope the corpus is routed by, derived from the asker's own | |
| 1118 | + // memberships on every request — never from the body, so a caller cannot | |
| 1119 | + // summarize a corpus they cannot study. The body's `ders`/`sinif` only pick | |
| 1120 | + // a pair out of that set. | |
| 1121 | + let pairs = service::rag_scope::for_user(&st.db, &user, user.get_role()).await?; | |
| 1122 | + let pair = resolve_study_pair(&pairs, &req.ders, req.sinif.as_deref())?; | |
| 1123 | + let payload = RagSummarizePayload { | |
| 1124 | + scope: req.into_scope(pair), | |
| 1125 | + // What the session already proves, never what the body claims. | |
| 1126 | + asker: user.get_id().key(), | |
| 1127 | + asker_role: user.get_role().as_str().to_string(), | |
| 1128 | + }; | |
| 1129 | + | |
| 1130 | + match rag_study::summarize(&bridge, &slug, payload).await { | |
| 1131 | + Ok(reply) => Ok(Json(RagSummarizeResponse::from(reply)).into_response()), | |
| 1132 | + Err(code) => Ok(failure(&code)), | |
| 1133 | + } | |
| 1134 | +} | |
| 1135 | + | |
| 1136 | +/// Generate practice questions over one range of one corpus the caller may | |
| 1137 | +/// study, with the answers bounded to that range. | |
| 1138 | +/// | |
| 1139 | +/// One-shot and synchronous like [`summarize`], and gated the same way: the | |
| 1140 | +/// same derived scope, the same `403`/`400` resolution, the same `503` when no | |
| 1141 | +/// service offers the capability, and the same rule that an abstention is a | |
| 1142 | +/// complete answer on a `200`. What it adds is the shape of the set: `n` | |
| 1143 | +/// (default 5, at most [`MAX_RAG_QUESTIONS`]), `difficulty` (default `orta`) | |
| 1144 | +/// and an optional `seed_question` to generate variations of one exercise. | |
| 1145 | +#[utoipa::path( | |
| 1146 | + post, | |
| 1147 | + path = "/questions", | |
| 1148 | + tag = "rag", | |
| 1149 | + security(("session_cookie" = [])), | |
| 1150 | + request_body = QuestionsRequest, | |
| 1151 | + responses( | |
| 1152 | + (status = 200, description = "The generated questions — possibly an abstention: `abstained: true` with a `reason` is a complete answer", body = RagQuestionsResponse), | |
| 1153 | + (status = 400, description = "`ders` is empty, `sinif` was omitted for a ders taught in more than one grade, or `n` is outside `1..=20`", body = ErrorResponse), | |
| 1154 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 1155 | + (status = 403, description = "The requested `(sinif, ders)` is not one of the caller's own scopes", body = ErrorResponse), | |
| 1156 | + (status = 409, description = "The AI service refused to run the request — its model is unavailable, or the request was over its rate or budget cap", body = ErrorResponse), | |
| 1157 | + (status = 502, description = "The AI service answered something this backend could not use, or built a request it refused", body = ErrorResponse), | |
| 1158 | + (status = 503, description = "No AI service offers `rag.questions` right now", body = ErrorResponse), | |
| 1159 | + (status = 504, description = "The AI service did not answer within the dispatch deadline", body = ErrorResponse), | |
| 1160 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | |
| 1161 | + ), | |
| 1162 | +)] | |
| 1163 | +async fn questions( | |
| 1164 | + State(st): State<AppState>, | |
| 1165 | + SchoolSlug(slug): SchoolSlug, | |
| 1166 | + CurrentUser(user): CurrentUser, | |
| 1167 | + Json(req): Json<QuestionsRequest>, | |
| 1168 | +) -> Result<Response, AppError> { | |
| 1169 | + let Some(bridge) = st.ai.clone() else { | |
| 1170 | + return Ok(ai_unavailable( | |
| 1171 | + "the AI service is not enabled on this deployment", | |
| 1172 | + )); | |
| 1173 | + }; | |
| 1174 | + if !bridge.has_capability(AI_RAG_QUESTIONS_CAPABILITY) { | |
| 1175 | + return Ok(ai_unavailable("no AI service is connected right now")); | |
| 1176 | + } | |
| 1177 | + | |
| 1178 | + let pairs = service::rag_scope::for_user(&st.db, &user, user.get_role()).await?; | |
| 1179 | + let pair = resolve_study_pair(&pairs, &req.scope.ders, req.scope.sinif.as_deref())?; | |
| 1180 | + if !(1..=MAX_RAG_QUESTIONS).contains(&req.n) { | |
| 1181 | + return Err(AppError::Validation(ValidationError::Invalid { | |
| 1182 | + field: "n", | |
| 1183 | + reason: "must be between 1 and 20", | |
| 1184 | + })); | |
| 1185 | + } | |
| 1186 | + let payload = RagQuestionsPayload { | |
| 1187 | + scope: req.scope.into_scope(pair), | |
| 1188 | + asker: user.get_id().key(), | |
| 1189 | + asker_role: user.get_role().as_str().to_string(), | |
| 1190 | + n: req.n, | |
| 1191 | + difficulty: req.difficulty, | |
| 1192 | + seed_question: req.seed_question, | |
| 1193 | + }; | |
| 1194 | + | |
| 1195 | + match rag_study::questions(&bridge, &slug, payload).await { | |
| 1196 | + Ok(reply) => Ok(Json(RagQuestionsResponse::from(reply)).into_response()), | |
| 1197 | + Err(code) => Ok(failure(&code)), | |
| 1198 | + } | |
| 1199 | +} | |
| 1200 | + | |
| 1201 | +/// A relayed failure as the response a client branches on: the service's own | |
| 1202 | +/// code decides the status where it is one this backend knows, and anything | |
| 1203 | +/// else is a `502` — the backend cannot vouch for an answer it did not | |
| 1204 | +/// understand, and a gateway error is exactly that claim. | |
| 1205 | +/// | |
| 1206 | +/// `role_required` and `scope_mismatch` land in that fallback deliberately: | |
| 1207 | +/// both mean the **backend** composed a request the service may not answer, so | |
| 1208 | +/// [`crate::ai::rag_study`] logs them as bugs where they are detected and the | |
| 1209 | +/// caller is told the gateway failed rather than being handed the service's own | |
| 1210 | +/// wording for this side's defect. | |
| 1211 | +fn failure(code: &str) -> Response { | |
| 1212 | + let status = match code { | |
| 1213 | + "bad_request" => StatusCode::BAD_REQUEST, | |
| 1214 | + "not_found" => StatusCode::NOT_FOUND, | |
| 1215 | + "not_ready" | "llm_unavailable" => StatusCode::CONFLICT, | |
| 1216 | + "busy" | "unavailable" => StatusCode::SERVICE_UNAVAILABLE, | |
| 1217 | + "timed_out" => StatusCode::GATEWAY_TIMEOUT, | |
| 1218 | + "internal" => StatusCode::INTERNAL_SERVER_ERROR, | |
| 1219 | + // `transport`, `protocol`, `bad_reply`, `role_required`, | |
| 1220 | + // `scope_mismatch`, `service_error`, and any code the service | |
| 1221 | + // invented: a bad gateway. | |
| 1222 | + _ => StatusCode::BAD_GATEWAY, | |
| 1223 | + }; | |
| 1224 | + (status, Json(json!({ "error": code }))).into_response() | |
| 1225 | +} | |
| 1226 | + | |
| 831 | 1227 | #[cfg(test)] |
| 832 | 1228 | mod tests { |
| 833 | 1229 | use super::*; |
| @@ -857,4 +1253,53 @@ mod tests { | ||
| 857 | 1253 | assert_eq!(unresolved.file, None); |
| 858 | 1254 | assert_eq!(unresolved.pages, vec![3, 4]); |
| 859 | 1255 | } |
| 1256 | + | |
| 1257 | + fn pair(sinif: Option<&str>, ders: &str) -> RagScopePair { | |
| 1258 | + RagScopePair { | |
| 1259 | + sinif: sinif.map(str::to_string), | |
| 1260 | + ders: ders.to_string(), | |
| 1261 | + } | |
| 1262 | + } | |
| 1263 | + | |
| 1264 | + #[test] | |
| 1265 | + fn a_study_pair_resolves_only_inside_the_askers_own_scope() { | |
| 1266 | + let pairs = vec![ | |
| 1267 | + pair(Some("10"), "Biyoloji"), | |
| 1268 | + pair(None, "Satranç Kulübü"), | |
| 1269 | + pair(Some("9"), "Matematik"), | |
| 1270 | + ]; | |
| 1271 | + | |
| 1272 | + // A named grade must be the exact pair, and the resolved pair is what | |
| 1273 | + // travels — never the body's own spelling. | |
| 1274 | + let resolved = resolve_study_pair(&pairs, "Biyoloji", Some("10")).unwrap(); | |
| 1275 | + assert_eq!(resolved.sinif.as_deref(), Some("10")); | |
| 1276 | + let grade_less = resolve_study_pair(&pairs, "Satranç Kulübü", None).unwrap(); | |
| 1277 | + assert_eq!(grade_less.sinif, None); | |
| 1278 | + | |
| 1279 | + // A grade the asker is not scoped to, and a ders they hold no pair | |
| 1280 | + // for, are both `403` — a corpus they cannot study must not be | |
| 1281 | + // summarized on their behalf. | |
| 1282 | + assert!(matches!( | |
| 1283 | + resolve_study_pair(&pairs, "Biyoloji", Some("11")), | |
| 1284 | + Err(AppError::Forbidden(_)) | |
| 1285 | + )); | |
| 1286 | + assert!(matches!( | |
| 1287 | + resolve_study_pair(&pairs, "Fizik", None), | |
| 1288 | + Err(AppError::Forbidden(_)) | |
| 1289 | + )); | |
| 1290 | + // An empty ders is a malformed body, not a scope refusal. | |
| 1291 | + assert!(matches!( | |
| 1292 | + resolve_study_pair(&pairs, " ", None), | |
| 1293 | + Err(AppError::Validation(ValidationError::Empty("ders"))) | |
| 1294 | + )); | |
| 1295 | + | |
| 1296 | + // Two şubeler teaching one course: the caller must name the grade, | |
| 1297 | + // because picking one for them answers from a corpus they did not name. | |
| 1298 | + let two = vec![pair(Some("9"), "Fizik"), pair(Some("10"), "Fizik")]; | |
| 1299 | + assert!(matches!( | |
| 1300 | + resolve_study_pair(&two, "Fizik", None), | |
| 1301 | + Err(AppError::Validation(ValidationError::Invalid { field: "sinif", .. })) | |
| 1302 | + )); | |
| 1303 | + assert!(resolve_study_pair(&two, "Fizik", Some("10")).is_ok()); | |
| 1304 | + } | |
| 860 | 1305 | } |
tests/ai_bridge.rsmodified+392 -0
| @@ -3392,6 +3392,398 @@ async fn a_rag_stream_replays_a_settled_turn_with_its_citations() { | ||
| 3392 | 3392 | assert_eq!(citation["ders"], "Fizik", "{message}"); |
| 3393 | 3393 | } |
| 3394 | 3394 | |
| 3395 | +// ---- rag study: the one-shot summarize/questions doors ----------------- | |
| 3396 | +// | |
| 3397 | +// No thread, no stored row: these doors wait on exactly one dispatch and answer | |
| 3398 | +// with the artifact. These pin the wire payloads (the scope derived | |
| 3399 | +// server-side, the asker, the question-set knobs), the authorization the body | |
| 3400 | +// is held to, and the rule that an abstention is a complete `200`. | |
| 3401 | + | |
| 3402 | +use hezarfen_backend::constant::{AI_RAG_QUESTIONS_CAPABILITY, AI_RAG_SUMMARIZE_CAPABILITY}; | |
| 3403 | + | |
| 3404 | +/// A signed-in student whose derived scope is exactly one school-wide club | |
| 3405 | +/// corpus — the cheapest scope a real school can produce, and the same fixture | |
| 3406 | +/// the chat tests above use. Returns (app, their cookie, their user id). | |
| 3407 | +async fn study_user(bridge: &AiBridge) -> (Router, String, String) { | |
| 3408 | + let (app, db) = chat_app(bridge).await; | |
| 3409 | + let staff = common::login_as(&app, &db, "mudur", "manager").await; | |
| 3410 | + let res = common::send( | |
| 3411 | + &app, | |
| 3412 | + "POST", | |
| 3413 | + "/courses", | |
| 3414 | + Some(&staff), | |
| 3415 | + Some(json!({ "title": "Satranç Kulübü", "kind": "club" })), | |
| 3416 | + ) | |
| 3417 | + .await; | |
| 3418 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 3419 | + let club = common::id_of(&res.body); | |
| 3420 | + | |
| 3421 | + let cookie = common::login(&app, "ali").await; | |
| 3422 | + let student = common::me_id(&app, &cookie).await; | |
| 3423 | + let res = common::send( | |
| 3424 | + &app, | |
| 3425 | + "POST", | |
| 3426 | + &format!("/courses/{club}/members"), | |
| 3427 | + Some(&staff), | |
| 3428 | + Some(json!({ "user_id": student })), | |
| 3429 | + ) | |
| 3430 | + .await; | |
| 3431 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 3432 | + (app, cookie, student) | |
| 3433 | +} | |
| 3434 | + | |
| 3435 | +/// The summarize wire contract end to end: one `rag.summarize` dispatch, the | |
| 3436 | +/// frame naming the school and the asker, the scope derived from the asker's | |
| 3437 | +/// own memberships (a club is school-wide, so `sinif: null`) with the body's | |
| 3438 | +/// range carried inside it, and the reply mapped back field for field. | |
| 3439 | +#[tokio::test] | |
| 3440 | +async fn the_summarize_request_carries_the_askers_scope_and_role() { | |
| 3441 | + let bridge = bridge().await; | |
| 3442 | + let service = connect_service( | |
| 3443 | + &bridge, | |
| 3444 | + hello("rag", &[AI_RAG_SUMMARIZE_CAPABILITY]), | |
| 3445 | + Behaviour::Answer(json!({ | |
| 3446 | + "text": "DNA, kalıtımı taşıyan moleküldür.", | |
| 3447 | + "abstained": false, | |
| 3448 | + "reason": "", | |
| 3449 | + "citations": [{ "n": 1, "pages": [16], "span_ids": ["s-3"] }], | |
| 3450 | + "scope_pages": [16, 17], | |
| 3451 | + "hierarchical": true, | |
| 3452 | + })), | |
| 3453 | + ) | |
| 3454 | + .await; | |
| 3455 | + await_workers(&bridge, 1).await; | |
| 3456 | + let (app, cookie, student) = study_user(&bridge).await; | |
| 3457 | + | |
| 3458 | + let res = common::send( | |
| 3459 | + &app, | |
| 3460 | + "POST", | |
| 3461 | + "/rag/summarize", | |
| 3462 | + Some(&cookie), | |
| 3463 | + Some(json!({ "ders": "Satranç Kulübü", "pages": [16, 17], "scope_label": "DNA" })), | |
| 3464 | + ) | |
| 3465 | + .await; | |
| 3466 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 3467 | + assert_eq!(res.body["text"], "DNA, kalıtımı taşıyan moleküldür."); | |
| 3468 | + assert_eq!(res.body["abstained"], false); | |
| 3469 | + assert_eq!(res.body["reason"], ""); | |
| 3470 | + assert_eq!(res.body["citations"][0]["n"], 1); | |
| 3471 | + assert_eq!(res.body["citations"][0]["pages"], json!([16])); | |
| 3472 | + assert_eq!(res.body["citations"][0]["span_ids"], json!(["s-3"])); | |
| 3473 | + assert_eq!(res.body["scope_pages"], json!([16, 17])); | |
| 3474 | + assert_eq!(res.body["hierarchical"], true); | |
| 3475 | + // A summary is addressed to a range the caller selected, not to one | |
| 3476 | + // document, so its citations carry no corpus id to resolve into a file. | |
| 3477 | + assert!( | |
| 3478 | + res.body["citations"][0]["doc_id"].is_null(), | |
| 3479 | + "no file may be implied for a study citation: {}", | |
| 3480 | + res.body | |
| 3481 | + ); | |
| 3482 | + | |
| 3483 | + let seen = service.seen(); | |
| 3484 | + assert_eq!(seen.len(), 1, "one dispatch per call, never a re-send"); | |
| 3485 | + assert_eq!(seen[0].capability, AI_RAG_SUMMARIZE_CAPABILITY); | |
| 3486 | + assert_eq!(seen[0].school, DEMO_SLUG, "the frame names the caller's school"); | |
| 3487 | + let payload = &seen[0].payload; | |
| 3488 | + assert_eq!(payload["asker"], student); | |
| 3489 | + assert_eq!(payload["asker_role"], "student"); | |
| 3490 | + assert_eq!( | |
| 3491 | + payload["scope"], | |
| 3492 | + json!({ | |
| 3493 | + "sinif": null, | |
| 3494 | + "ders": "Satranç Kulübü", | |
| 3495 | + "pages": [16, 17], | |
| 3496 | + "span_ids": [], | |
| 3497 | + "scope_label": "DNA", | |
| 3498 | + }), | |
| 3499 | + "a club is school-wide, so its scope names no grade" | |
| 3500 | + ); | |
| 3501 | +} | |
| 3502 | + | |
| 3503 | +/// The questions wire contract: the same scope, plus the shape of the set, and | |
| 3504 | +/// the service's own `soru`/`cevap`/`zorluk` rows mapped onto this API's | |
| 3505 | +/// `question`/`answer`/`difficulty` (the wire keeps the service's vocabulary). | |
| 3506 | +#[tokio::test] | |
| 3507 | +async fn the_questions_request_carries_its_knobs_and_maps_its_rows() { | |
| 3508 | + let bridge = bridge().await; | |
| 3509 | + let service = connect_service( | |
| 3510 | + &bridge, | |
| 3511 | + hello("rag", &[AI_RAG_QUESTIONS_CAPABILITY]), | |
| 3512 | + Behaviour::Answer(json!({ | |
| 3513 | + "items": [ | |
| 3514 | + { "soru": "DNA nedir?", "cevap": "Kalıtım molekülü.", "zorluk": "kolay" }, | |
| 3515 | + { "soru": "Baz eşleşmesi nedir?", "cevap": "A-T ve G-C.", "zorluk": "orta" }, | |
| 3516 | + ], | |
| 3517 | + "abstained": false, | |
| 3518 | + "reason": "", | |
| 3519 | + "span_ids": ["s-3"], | |
| 3520 | + "pages": [16], | |
| 3521 | + })), | |
| 3522 | + ) | |
| 3523 | + .await; | |
| 3524 | + await_workers(&bridge, 1).await; | |
| 3525 | + let (app, cookie, student) = study_user(&bridge).await; | |
| 3526 | + | |
| 3527 | + let res = common::send( | |
| 3528 | + &app, | |
| 3529 | + "POST", | |
| 3530 | + "/rag/questions", | |
| 3531 | + Some(&cookie), | |
| 3532 | + Some(json!({ | |
| 3533 | + "ders": "Satranç Kulübü", | |
| 3534 | + "span_ids": ["s-3"], | |
| 3535 | + "n": 2, | |
| 3536 | + "difficulty": "kolay", | |
| 3537 | + "seed_question": "DNA nedir?", | |
| 3538 | + })), | |
| 3539 | + ) | |
| 3540 | + .await; | |
| 3541 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 3542 | + assert_eq!( | |
| 3543 | + res.body["items"], | |
| 3544 | + json!([ | |
| 3545 | + { "question": "DNA nedir?", "answer": "Kalıtım molekülü.", "difficulty": "kolay" }, | |
| 3546 | + { "question": "Baz eşleşmesi nedir?", "answer": "A-T ve G-C.", "difficulty": "orta" }, | |
| 3547 | + ]) | |
| 3548 | + ); | |
| 3549 | + assert_eq!(res.body["abstained"], false); | |
| 3550 | + assert_eq!(res.body["span_ids"], json!(["s-3"])); | |
| 3551 | + assert_eq!(res.body["pages"], json!([16])); | |
| 3552 | + | |
| 3553 | + let seen = service.seen(); | |
| 3554 | + assert_eq!(seen.len(), 1, "one dispatch per call, never a re-send"); | |
| 3555 | + assert_eq!(seen[0].capability, AI_RAG_QUESTIONS_CAPABILITY); | |
| 3556 | + let payload = &seen[0].payload; | |
| 3557 | + assert_eq!(payload["asker"], student); | |
| 3558 | + assert_eq!(payload["asker_role"], "student"); | |
| 3559 | + assert_eq!(payload["n"], 2); | |
| 3560 | + assert_eq!(payload["difficulty"], "kolay"); | |
| 3561 | + assert_eq!(payload["seed_question"], "DNA nedir?"); | |
| 3562 | + assert_eq!( | |
| 3563 | + payload["scope"], | |
| 3564 | + json!({ | |
| 3565 | + "sinif": null, | |
| 3566 | + "ders": "Satranç Kulübü", | |
| 3567 | + "pages": [], | |
| 3568 | + "span_ids": ["s-3"], | |
| 3569 | + "scope_label": "", | |
| 3570 | + }) | |
| 3571 | + ); | |
| 3572 | + | |
| 3573 | + // The knobs' defaults are the documented ones, and a body that names none | |
| 3574 | + // of them still dispatches a well-formed request. | |
| 3575 | + let res = common::send( | |
| 3576 | + &app, | |
| 3577 | + "POST", | |
| 3578 | + "/rag/questions", | |
| 3579 | + Some(&cookie), | |
| 3580 | + Some(json!({ "ders": "Satranç Kulübü" })), | |
| 3581 | + ) | |
| 3582 | + .await; | |
| 3583 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 3584 | + let seen = service.seen(); | |
| 3585 | + assert_eq!(seen.len(), 2); | |
| 3586 | + assert_eq!(seen[1].payload["n"], 5, "`n` defaults to 5"); | |
| 3587 | + assert_eq!(seen[1].payload["difficulty"], "orta"); | |
| 3588 | + assert_eq!(seen[1].payload["seed_question"], Value::Null); | |
| 3589 | +} | |
| 3590 | + | |
| 3591 | +/// A connected worker that does not carry the capability is not a worker for | |
| 3592 | +/// these doors: both answer the shared `503`, and nothing is dispatched. | |
| 3593 | +#[tokio::test] | |
| 3594 | +async fn no_study_worker_means_503_and_nothing_is_dispatched() { | |
| 3595 | + let bridge = bridge().await; | |
| 3596 | + let service = connect_service( | |
| 3597 | + &bridge, | |
| 3598 | + hello("rag", &[AI_RAG_CHAT_CAPABILITY]), | |
| 3599 | + Behaviour::Echo, | |
| 3600 | + ) | |
| 3601 | + .await; | |
| 3602 | + await_workers(&bridge, 1).await; | |
| 3603 | + let (app, cookie, _student) = study_user(&bridge).await; | |
| 3604 | + | |
| 3605 | + for path in ["/rag/summarize", "/rag/questions"] { | |
| 3606 | + let res = common::send( | |
| 3607 | + &app, | |
| 3608 | + "POST", | |
| 3609 | + path, | |
| 3610 | + Some(&cookie), | |
| 3611 | + Some(json!({ "ders": "Satranç Kulübü" })), | |
| 3612 | + ) | |
| 3613 | + .await; | |
| 3614 | + assert_eq!( | |
| 3615 | + res.status, | |
| 3616 | + StatusCode::SERVICE_UNAVAILABLE, | |
| 3617 | + "{path}: {}", | |
| 3618 | + res.body | |
| 3619 | + ); | |
| 3620 | + assert_eq!( | |
| 3621 | + res.body["error"], "no AI service is connected right now", | |
| 3622 | + "{path}: {}", | |
| 3623 | + res.body | |
| 3624 | + ); | |
| 3625 | + } | |
| 3626 | + assert!( | |
| 3627 | + service.seen().is_empty(), | |
| 3628 | + "a door refused for want of a capability dispatches nothing" | |
| 3629 | + ); | |
| 3630 | +} | |
| 3631 | + | |
| 3632 | +/// The body only *names* a target inside the asker's own derived pairs. A ders | |
| 3633 | +/// they hold no pair for, and a grade that is not the exact pair they hold, are | |
| 3634 | +/// both `403` — and neither reaches the service. | |
| 3635 | +#[tokio::test] | |
| 3636 | +async fn a_corpus_outside_the_askers_scope_is_refused() { | |
| 3637 | + let bridge = bridge().await; | |
| 3638 | + let service = connect_service( | |
| 3639 | + &bridge, | |
| 3640 | + hello("rag", &[AI_RAG_SUMMARIZE_CAPABILITY, AI_RAG_QUESTIONS_CAPABILITY]), | |
| 3641 | + Behaviour::Answer(json!({ "text": "özet", "items": [] })), | |
| 3642 | + ) | |
| 3643 | + .await; | |
| 3644 | + await_workers(&bridge, 1).await; | |
| 3645 | + let (app, cookie, _student) = study_user(&bridge).await; | |
| 3646 | + | |
| 3647 | + for path in ["/rag/summarize", "/rag/questions"] { | |
| 3648 | + // A subject this student is not enrolled in anywhere. | |
| 3649 | + let res = common::send( | |
| 3650 | + &app, | |
| 3651 | + "POST", | |
| 3652 | + path, | |
| 3653 | + Some(&cookie), | |
| 3654 | + Some(json!({ "ders": "Fizik" })), | |
| 3655 | + ) | |
| 3656 | + .await; | |
| 3657 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{path}: {}", res.body); | |
| 3658 | + | |
| 3659 | + // The club's own pair has no grade, so naming one is not that pair. | |
| 3660 | + let res = common::send( | |
| 3661 | + &app, | |
| 3662 | + "POST", | |
| 3663 | + path, | |
| 3664 | + Some(&cookie), | |
| 3665 | + Some(json!({ "ders": "Satranç Kulübü", "sinif": "10" })), | |
| 3666 | + ) | |
| 3667 | + .await; | |
| 3668 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{path}: {}", res.body); | |
| 3669 | + } | |
| 3670 | + assert!( | |
| 3671 | + service.seen().is_empty(), | |
| 3672 | + "an out-of-scope request never reaches the service" | |
| 3673 | + ); | |
| 3674 | + | |
| 3675 | + // A set size outside the door's own bound is a malformed body, refused | |
| 3676 | + // before any dispatch. | |
| 3677 | + let res = common::send( | |
| 3678 | + &app, | |
| 3679 | + "POST", | |
| 3680 | + "/rag/questions", | |
| 3681 | + Some(&cookie), | |
| 3682 | + Some(json!({ "ders": "Satranç Kulübü", "n": 21 })), | |
| 3683 | + ) | |
| 3684 | + .await; | |
| 3685 | + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); | |
| 3686 | + assert!(service.seen().is_empty(), "`n` is judged before the dispatch"); | |
| 3687 | +} | |
| 3688 | + | |
| 3689 | +/// An abstention is a complete answer on both doors: `200` with the service's | |
| 3690 | +/// own `reason`, never an error status. | |
| 3691 | +#[tokio::test] | |
| 3692 | +async fn an_abstained_study_answer_is_a_complete_200() { | |
| 3693 | + let summary_bridge = bridge().await; | |
| 3694 | + let _service = connect_service( | |
| 3695 | + &summary_bridge, | |
| 3696 | + hello("rag", &[AI_RAG_SUMMARIZE_CAPABILITY]), | |
| 3697 | + Behaviour::Answer(json!({ | |
| 3698 | + "text": "Bu aralıkta özetlenecek içerik yok.", | |
| 3699 | + "abstained": true, | |
| 3700 | + "reason": "empty_scope", | |
| 3701 | + "citations": [], | |
| 3702 | + "scope_pages": [], | |
| 3703 | + "hierarchical": false, | |
| 3704 | + })), | |
| 3705 | + ) | |
| 3706 | + .await; | |
| 3707 | + await_workers(&summary_bridge, 1).await; | |
| 3708 | + let (app, cookie, _student) = study_user(&summary_bridge).await; | |
| 3709 | + | |
| 3710 | + let res = common::send( | |
| 3711 | + &app, | |
| 3712 | + "POST", | |
| 3713 | + "/rag/summarize", | |
| 3714 | + Some(&cookie), | |
| 3715 | + Some(json!({ "ders": "Satranç Kulübü" })), | |
| 3716 | + ) | |
| 3717 | + .await; | |
| 3718 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 3719 | + assert_eq!(res.body["abstained"], true); | |
| 3720 | + assert_eq!(res.body["reason"], "empty_scope"); | |
| 3721 | + assert_eq!(res.body["text"], "Bu aralıkta özetlenecek içerik yok."); | |
| 3722 | + | |
| 3723 | + let questions_bridge = bridge().await; | |
| 3724 | + let _service = connect_service( | |
| 3725 | + &questions_bridge, | |
| 3726 | + hello("rag", &[AI_RAG_QUESTIONS_CAPABILITY]), | |
| 3727 | + Behaviour::Answer(json!({ | |
| 3728 | + "items": [], | |
| 3729 | + "abstained": true, | |
| 3730 | + "reason": "insufficient_data", | |
| 3731 | + "span_ids": [], | |
| 3732 | + "pages": [], | |
| 3733 | + })), | |
| 3734 | + ) | |
| 3735 | + .await; | |
| 3736 | + await_workers(&questions_bridge, 1).await; | |
| 3737 | + let (app, cookie, _student) = study_user(&questions_bridge).await; | |
| 3738 | + | |
| 3739 | + let res = common::send( | |
| 3740 | + &app, | |
| 3741 | + "POST", | |
| 3742 | + "/rag/questions", | |
| 3743 | + Some(&cookie), | |
| 3744 | + Some(json!({ "ders": "Satranç Kulübü" })), | |
| 3745 | + ) | |
| 3746 | + .await; | |
| 3747 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 3748 | + assert_eq!(res.body["items"], json!([])); | |
| 3749 | + assert_eq!(res.body["abstained"], true); | |
| 3750 | + assert_eq!(res.body["reason"], "insufficient_data"); | |
| 3751 | +} | |
| 3752 | + | |
| 3753 | +/// Two verdicts mean the **backend** built a request the service may not | |
| 3754 | +/// answer. The caller gets a `502` — not a refusal that reads as their own | |
| 3755 | +/// fault — and this side logs it as the bug it is. | |
| 3756 | +#[tokio::test] | |
| 3757 | +async fn a_verdict_that_blames_the_backends_own_request_is_a_502() { | |
| 3758 | + let bridge = bridge().await; | |
| 3759 | + let _service = connect_service( | |
| 3760 | + &bridge, | |
| 3761 | + hello("rag", &[AI_RAG_SUMMARIZE_CAPABILITY]), | |
| 3762 | + Behaviour::Answer(json!({ | |
| 3763 | + "text": "", | |
| 3764 | + "abstained": true, | |
| 3765 | + "reason": "role_required", | |
| 3766 | + "citations": [], | |
| 3767 | + "scope_pages": [], | |
| 3768 | + "hierarchical": false, | |
| 3769 | + })), | |
| 3770 | + ) | |
| 3771 | + .await; | |
| 3772 | + await_workers(&bridge, 1).await; | |
| 3773 | + let (app, cookie, _student) = study_user(&bridge).await; | |
| 3774 | + | |
| 3775 | + let res = common::send( | |
| 3776 | + &app, | |
| 3777 | + "POST", | |
| 3778 | + "/rag/summarize", | |
| 3779 | + Some(&cookie), | |
| 3780 | + Some(json!({ "ders": "Satranç Kulübü" })), | |
| 3781 | + ) | |
| 3782 | + .await; | |
| 3783 | + assert_eq!(res.status, StatusCode::BAD_GATEWAY, "{}", res.body); | |
| 3784 | + assert_eq!(res.body["error"], "role_required", "{}", res.body); | |
| 3785 | +} | |
| 3786 | + | |
| 3395 | 3787 | // ---- insights ---------------------------------------------------------- |
| 3396 | 3788 | |
| 3397 | 3789 | use hezarfen_backend::ai::insight; |
tests/integration.rsmodified+1 -1
| @@ -434,7 +434,7 @@ async fn protected_routes_require_session() { | ||
| 434 | 434 | /// Floor on the number of protected operations swept. It only ever goes |
| 435 | 435 | /// up: raise it when routes are added. Without it, deleting a route family |
| 436 | 436 | /// would delete its own coverage and still pass. |
| 437 | - const MIN_PROTECTED: usize = 340; | |
| 437 | + const MIN_PROTECTED: usize = 342; | |
| 438 | 438 | |
| 439 | 439 | let app = mem_app().await; |
| 440 | 440 | let spec = send(&app, "GET", "/api-docs/openapi.json", None, None) |
tests/limits_completeness.rsmodified+20 -0
| @@ -122,6 +122,26 @@ const EXCLUDED: &[(&str, &str)] = &[ | ||
| 122 | 122 | "deadline on one RAG ask round trip; the browser waits on its message \ |
| 123 | 123 | stream, never on this number", |
| 124 | 124 | ), |
| 125 | + ( | |
| 126 | + "AI_RAG_SUMMARIZE_CAPABILITY", | |
| 127 | + "capability string an AI service declares", | |
| 128 | + ), | |
| 129 | + ( | |
| 130 | + "AI_RAG_SUMMARIZE_TIMEOUT_SECS", | |
| 131 | + "deadline on one one-shot summary of a range; the caller waits on the \ | |
| 132 | + artifact itself and acts on the door's 200/400/403/503, never on this \ | |
| 133 | + number", | |
| 134 | + ), | |
| 135 | + ( | |
| 136 | + "AI_RAG_QUESTIONS_CAPABILITY", | |
| 137 | + "capability string an AI service declares", | |
| 138 | + ), | |
| 139 | + ( | |
| 140 | + "AI_RAG_QUESTIONS_TIMEOUT_SECS", | |
| 141 | + "deadline on one one-shot question set over a range; the caller waits \ | |
| 142 | + on the artifact itself and acts on the door's 200/400/403/503, never \ | |
| 143 | + on this number", | |
| 144 | + ), | |
| 125 | 145 | ( |
| 126 | 146 | "AI_INSIGHT_STUDENT_CAPABILITY", |
| 127 | 147 | "capability string an AI service declares", |