forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

rag.rs1409 lines, 60.3 KiBHistoryRawDownload
1//! The RAG nest: browser ⇄ backend ⇄ AI service (over the QUIC bridge),
2//! scoped to a school's course-note corpus.
3//!
4//! The relay contract is [`super::chatbot`]'s, shape for shape: the backend
5//! owns everything except the answer — auth, the per-user rate limit, the
6//! thread, the payload format, and the last look at the reply before it is
7//! stored. There are no intent or rule tables, and every thread is private to
8//! its owner. What differs is the **scope**: every question carries the
9//! `(class, course)` pairs the corpus is routed by, derived server-side
10//! ([`crate::service::rag_scope`]: a manager or an admin gets every class-course
11//! pair in the school, everyone else their own memberships) and never from the
12//! request body, and every citation the service returns is resolved here to
13//! the course-note file that owns the cited document — the `doc_id` only the
14//! backend can turn into something a reader can open.
15//!
16//! The school's existing AI caps govern both nests: a RAG thread is reserved
17//! against the same `max_chatbot_threads` seat count, a prompt and its answer
18//! are bounded by the same `max_chatbot_message_len`, and the history replayed
19//! to the service is the same `chatbot_history_turns` window. Only the
20//! per-minute tier is RAG's own (`DEFAULT_RAG_RATE_LIMIT`), because every
21//! message here spends a retrieval over the whole corpus before it generates
22//! anything.
23//!
24//! Sending is asynchronous by design. `POST .../messages` writes the user's
25//! turn plus an empty `pending` assistant row and answers `202` immediately;
26//! a retrieval-then-answer round trip can outlast the request-timeout layer
27//! that guards every HTTP handler, so nothing is awaited on the request path.
28//! The client then either polls `GET .../messages/{mid}` or opens its SSE
29//! stream — both read the same row, so they can never disagree.
30//!
31//! The bridge round trip runs in a `tokio::spawn` the POST leaves behind. A
32//! restart therefore orphans a turn in flight: its row stays `pending` until a
33//! reader projects it failed, and the boot sweep stamps that verdict durably
34//! ([`crate::constant::RAG_PENDING_STALE_SECS`]).
35//!
36//! The two **study** doors (`POST /rag/summarize`, `POST /rag/questions`) are
37//! the exception to that shape, and deliberately: a summary or a question set
38//! is one artifact about one range of one corpus, so there is no thread to
39//! open, no row to poll and nothing stored — the request waits for the
40//! artifact, under a dispatch deadline kept inside the middleware's own
41//! envelope.
42
43use std::time::Duration;
44
45use crate::tenant::ResolvedTenant;
46use crate::web::tenant_state::{SchoolIdCookie, State, TenantExt};
47use axum::Json;
48use axum::extract::{Path, Query};
49use axum::http::StatusCode;
50use axum::response::sse::{Event, KeepAlive, Sse};
51use axum::response::{IntoResponse, Response};
52use serde::{Deserialize, Serialize};
53use serde_json::json;
54use sqlx::types::Json as SqlJson;
55use tokio::sync::mpsc;
56use tokio_stream::Stream;
57use tokio_stream::wrappers::ReceiverStream;
58use utoipa::ToSchema;
59use utoipa_axum::router::OpenApiRouter;
60use utoipa_axum::routes;
61
62use crate::ai::chat::ChatRole;
63use crate::ai::rag_chat::RagScopePair;
64use crate::ai::rag_study::{
65 self, RagQuestion, RagQuestionsPayload, RagQuestionsReply, RagScope, RagSummarizePayload,
66 RagSummarizeReply, RagSummaryCitation,
67};
68use crate::ai::AiBridge;
69use crate::constant::{
70 AI_RAG_CHAT_CAPABILITY, AI_RAG_QUESTIONS_CAPABILITY, AI_RAG_SUMMARIZE_CAPABILITY,
71 CHAT_STREAM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN, MAX_RAG_QUESTIONS, REPLY_CHUNKS,
72};
73use crate::database::Database;
74use crate::domain::rag_message::{
75 RagCitedFile, RagContent, RagMessage, RagMessageId, RagMessageRole, RagMessageStatus,
76};
77use crate::domain::rag_thread::{RagThread, RagThreadId, RagThreadTitle};
78use crate::domain::role::Role;
79use crate::domain::settings::Settings;
80use crate::domain::user::UserId;
81use crate::error::{AppError, ErrorResponse, ValidationError};
82use crate::service;
83use crate::state::{AppState, scoped_key};
84
85use super::{CurrentUser, Page, PageParams, ai_unavailable, slice_reply, sse_error, sse_send};
86
87pub fn routes() -> OpenApiRouter<AppState> {
88 OpenApiRouter::new()
89 .routes(routes!(create_thread, list_threads))
90 .routes(routes!(rename_thread, delete_thread))
91 .routes(routes!(list_messages, send_message))
92 .routes(routes!(read_message))
93 .routes(routes!(stream_message))
94 // One `routes!(…)` call is one *path*: two handlers in it must share
95 // it (different methods). These two doors share neither.
96 .routes(routes!(summarize))
97 .routes(routes!(questions))
98}
99
100// ---- threads ----------------------------------------------------------
101
102#[derive(Deserialize, ToSchema)]
103struct CreateRagThread {
104 /// Optional thread name, up to 200 characters. Blank counts as absent —
105 /// an untitled thread is normal (the UI labels it from its first turn).
106 #[schema(max_length = 200, example = "Fizik ödevi")]
107 title: Option<String>,
108}
109
110/// One RAG thread. `updated_at` moves on every turn, and the list is sorted by
111/// it, so the thread just written to is always first.
112#[derive(Serialize, ToSchema)]
113struct RagThreadResponse {
114 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
115 id: String,
116 #[schema(example = "Fizik ödevi")]
117 title: Option<String>,
118 /// UTC unix-milliseconds, server-stamped.
119 created_at: i64,
120 /// UTC unix-milliseconds of the last turn, server-stamped.
121 updated_at: i64,
122}
123
124impl RagThreadResponse {
125 fn new(thread: &RagThread) -> Self {
126 Self {
127 id: thread.get_id().key().to_string(),
128 title: thread.get_title().map(|title| title.as_str().to_string()),
129 created_at: thread.get_created_at().as_millis(),
130 updated_at: thread.get_updated_at().as_millis(),
131 }
132 }
133}
134
135/// Start a new RAG thread, optionally named. Every authenticated role may ask
136/// — parents included. A user may keep up to the school's
137/// `max_chatbot_threads` threads *across both AI nests*; at the cap the
138/// request is refused (409) until an old thread is deleted — the cap is
139/// storage protection, not a usage quota (that is the per-minute message
140/// limit).
141#[utoipa::path(
142 post,
143 path = "/threads",
144 tag = "rag",
145 security(("session_cookie" = [])),
146 request_body = CreateRagThread,
147 responses(
148 (status = 201, description = "The new thread", body = RagThreadResponse),
149 (status = 400, description = "Invalid title", body = ErrorResponse),
150 (status = 401, description = "Not authenticated", body = ErrorResponse),
151 (status = 409, description = "At the school's thread cap", body = ErrorResponse),
152 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
153 ),
154)]
155async fn create_thread(
156 State(st): State<AppState>,
157 CurrentUser(user): CurrentUser,
158 Json(req): Json<CreateRagThread>,
159) -> Result<(StatusCode, Json<RagThreadResponse>), AppError> {
160 // Blank is "untitled", not an error — the same rule the chatbot nest
161 // applies to a thread name.
162 let title = match req.title.as_deref().map(str::trim).unwrap_or_default() {
163 "" => None,
164 value => Some(RagThreadTitle::try_new(value)?),
165 };
166
167 // The cap is checked and the row written as one critical section in the
168 // domain: counting here and creating after would over-admit under
169 // concurrency (the database does not serialize a count against inserts).
170 let thread = service::rag_thread::create_capped(&st.db, user.get_id(), title).await?;
171 Ok((
172 StatusCode::CREATED,
173 Json(RagThreadResponse::new(&thread)),
174 ))
175}
176
177/// The caller's own threads, most recently active first. Paged via
178/// `?limit=&offset=`. Nobody — no teacher, no admin — reads anyone else's.
179#[utoipa::path(
180 get,
181 path = "/threads",
182 tag = "rag",
183 security(("session_cookie" = [])),
184 params(PageParams),
185 responses(
186 (status = 200, description = "A page of the caller's threads", body = Page<RagThreadResponse>),
187 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
188 (status = 401, description = "Not authenticated", body = ErrorResponse),
189 ),
190)]
191async fn list_threads(
192 State(st): State<AppState>,
193 CurrentUser(user): CurrentUser,
194 Query(page): Query<PageParams>,
195) -> Result<Json<Page<RagThreadResponse>>, AppError> {
196 let (limit, offset) = page.resolve()?;
197 let (threads, total) =
198 service::rag_thread::list_for_user(&st.db, user.get_id(), limit, offset).await?;
199 let items = threads.iter().map(RagThreadResponse::new).collect();
200 Ok(Json(Page::new(items, total, limit, offset)))
201}
202
203#[derive(Deserialize, ToSchema)]
204struct RenameRagThread {
205 /// The new name, up to 200 characters. `null` — or blank — clears it back
206 /// to untitled, the same rule the create route applies.
207 #[schema(max_length = 200, example = "Fizik ödevi")]
208 title: Option<String>,
209}
210
211/// Rename a thread, or clear its name (`title: null`). Owner only; someone
212/// else's thread is a `404`, never a `403`. The edit counts as activity, so the
213/// thread moves to the top of the list.
214///
215/// Nothing names a thread automatically: the first message is not turned into
216/// a title, and the AI service is never asked for one.
217#[utoipa::path(
218 patch,
219 path = "/threads/{id}",
220 tag = "rag",
221 security(("session_cookie" = [])),
222 params(("id" = String, Path, description = "RagThread id")),
223 request_body = RenameRagThread,
224 responses(
225 (status = 200, description = "The renamed thread", body = RagThreadResponse),
226 (status = 400, description = "Invalid title", body = ErrorResponse),
227 (status = 401, description = "Not authenticated", body = ErrorResponse),
228 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
229 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
230 ),
231)]
232async fn rename_thread(
233 State(st): State<AppState>,
234 CurrentUser(user): CurrentUser,
235 Path(id): Path<String>,
236 Json(req): Json<RenameRagThread>,
237) -> Result<Json<RagThreadResponse>, AppError> {
238 let title = match req.title.as_deref().map(str::trim).unwrap_or_default() {
239 "" => None,
240 value => Some(RagThreadTitle::try_new(value)?),
241 };
242 let thread = own_thread(&id, user.get_id(), &st.db).await?;
243 let renamed = service::rag_thread::rename(&st.db, &thread, title).await?;
244 Ok(Json(RagThreadResponse::new(&renamed)))
245}
246
247/// Delete a thread and every turn in it, permanently. Owner only; someone
248/// else's thread is a `404`, never a `403` (its existence is not leaked).
249#[utoipa::path(
250 delete,
251 path = "/threads/{id}",
252 tag = "rag",
253 security(("session_cookie" = [])),
254 params(("id" = String, Path, description = "RagThread id")),
255 responses(
256 (status = 204, description = "Deleted, with its messages"),
257 (status = 401, description = "Not authenticated", body = ErrorResponse),
258 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
259 ),
260)]
261async fn delete_thread(
262 State(st): State<AppState>,
263 CurrentUser(user): CurrentUser,
264 Path(id): Path<String>,
265) -> Result<StatusCode, AppError> {
266 let thread = own_thread(&id, user.get_id(), &st.db).await?;
267 service::rag_thread::delete(&st.db, thread).await?;
268 Ok(StatusCode::NO_CONTENT)
269}
270
271/// Read a thread the caller owns, or `404`. A foreign id is indistinguishable
272/// from a missing one.
273async fn own_thread(id: &str, user: &UserId, db: &Database) -> Result<RagThread, AppError> {
274 service::rag_thread::read_for(db, &RagThreadId::from_key(id), user)
275 .await?
276 .ok_or(AppError::NotFound)
277}
278
279// ---- turns ------------------------------------------------------------------
280
281#[derive(Deserialize, ToSchema)]
282struct SendRagMessage {
283 /// What to ask. Required. `maxLength` here is the server's hard ceiling;
284 /// the live cap is the school's `max_chatbot_message_len` (`GET /settings`),
285 /// which is always at or below it — the same knob the chatbot nest uses.
286 #[schema(
287 example = "Newton'un ikinci yasasını açıklar mısın?",
288 max_length = 8_000
289 )]
290 content: String,
291}
292
293/// The receipt for an accepted turn. The answer is *not* here: it is being
294/// retrieved and generated. Poll `GET /rag/threads/{id}/messages/{mid}` or
295/// open its `/stream`.
296#[derive(Serialize, ToSchema)]
297struct AcceptedResponse {
298 /// The assistant row reserved for the answer.
299 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
300 message_id: String,
301 /// Always `pending` — that is what "accepted" means here.
302 #[schema(example = "pending")]
303 status: String,
304}
305
306/// One citation behind an answer, already resolved to something openable.
307#[derive(Serialize, ToSchema)]
308struct RagCitationResponse {
309 /// The marker the answer text points at: `[N]` in `content` resolves to
310 /// the citation whose `n` is `N`.
311 #[schema(example = 1)]
312 n: u32,
313 /// The `course_note_file` record key the service's corpus `doc_id` was
314 /// resolved through — fetch the file from
315 /// `/course-note-files/{id}/content`. `null` while no file the asker may
316 /// view claims that document (identical PDF bytes resolve to the same
317 /// `doc_id`, so a citation may point at a file in a course this asker
318 /// cannot read); the passage is still citable, just not openable.
319 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
320 file: Option<String>,
321 /// The page numbers within the document the passage spans.
322 #[schema(example = json!([3, 4]))]
323 pages: Vec<i64>,
324 /// Opaque retrieval span ids within the document, for a client that
325 /// highlights the exact passage.
326 span_ids: Vec<String>,
327 /// The subject the passage belongs to, when the corpus records one.
328 #[schema(example = "Fizik")]
329 ders: Option<String>,
330}
331
332impl From<&RagCitedFile> for RagCitationResponse {
333 fn from(citation: &RagCitedFile) -> Self {
334 Self {
335 n: citation.n,
336 file: citation.file.clone(),
337 pages: citation.pages.clone(),
338 span_ids: citation.span_ids.clone(),
339 ders: citation.ders.clone(),
340 }
341 }
342}
343
344/// One turn. `content` is empty while `status` is `pending`; `error_code` is
345/// set only when `status` is `failed`.
346#[derive(Serialize, ToSchema)]
347struct RagMessageResponse {
348 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
349 id: String,
350 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
351 thread_id: String,
352 /// `user` or `assistant`.
353 #[schema(example = "assistant")]
354 role: String,
355 /// `pending`, `complete`, or `failed`. A user turn is always `complete`.
356 #[schema(example = "complete")]
357 status: String,
358 content: String,
359 /// `true` when the service declined to answer — a complete, successful
360 /// turn, not a failure. `reason` says why (`guard_*`, `insufficient_data`,
361 /// `model_abstained`, …).
362 #[schema(example = false)]
363 abstained: bool,
364 /// The abstention's short machine code; `""` on an ordinary answer and on
365 /// every user turn.
366 #[schema(example = "insufficient_data")]
367 reason: String,
368 /// The passages the answer drew on, oldest first. Empty on a user turn,
369 /// on a pending one and on a failed one.
370 citations: Vec<RagCitationResponse>,
371 /// Short machine-readable reason when `status` is `failed`:
372 /// `unavailable`, `busy`, `timed_out`, `transport`, `protocol`,
373 /// `bad_reply`, `empty_reply`, `interrupted`, or a code the AI service
374 /// itself returned.
375 #[schema(example = "timed_out")]
376 error_code: Option<String>,
377 /// UTC unix-milliseconds, server-stamped.
378 created_at: i64,
379 /// When the turn settled (complete or failed); `null` while pending.
380 completed_at: Option<i64>,
381}
382
383impl RagMessageResponse {
384 fn new(message: &RagMessage) -> Self {
385 let reply = message.get_reply();
386 Self {
387 id: message.get_id().key().to_string(),
388 thread_id: message.get_thread_id().key().to_string(),
389 role: message.get_role().as_str().to_string(),
390 status: message.get_status().as_str().to_string(),
391 content: message.get_content().as_str().to_string(),
392 abstained: reply.is_some_and(|reply| reply.abstained),
393 reason: reply.map(|reply| reply.reason.clone()).unwrap_or_default(),
394 citations: reply
395 .map(|reply| reply.citations.iter().map(Into::into).collect())
396 .unwrap_or_default(),
397 error_code: message.get_error_code().map(str::to_string),
398 created_at: message.get_created_at().as_millis(),
399 completed_at: message.get_completed_at().map(|at| at.as_millis()),
400 }
401 }
402}
403
404/// The whole thread, oldest first. Paged via `?limit=&offset=`. Owner only.
405#[utoipa::path(
406 get,
407 path = "/threads/{id}/messages",
408 tag = "rag",
409 security(("session_cookie" = [])),
410 params(("id" = String, Path, description = "RagThread id"), PageParams),
411 responses(
412 (status = 200, description = "A page of the thread's turns", body = Page<RagMessageResponse>),
413 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
414 (status = 401, description = "Not authenticated", body = ErrorResponse),
415 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
416 ),
417)]
418async fn list_messages(
419 State(st): State<AppState>,
420 CurrentUser(user): CurrentUser,
421 Path(id): Path<String>,
422 Query(page): Query<PageParams>,
423) -> Result<Json<Page<RagMessageResponse>>, AppError> {
424 let (limit, offset) = page.resolve()?;
425 let thread = own_thread(&id, user.get_id(), &st.db).await?;
426 let (messages, total) =
427 service::rag_message::list_for_thread(&st.db, thread.get_id(), limit, offset).await?;
428 let items = messages.iter().map(RagMessageResponse::new).collect();
429 Ok(Json(Page::new(items, total, limit, offset)))
430}
431
432/// Ask the corpus a question: `{content}`, at most the school's
433/// `max_chatbot_message_len`. Answers `202 {message_id, status: "pending"}` the
434/// moment both rows are written — the answer itself lands later, in the
435/// reserved assistant row. `503` when no AI service offers `rag.chat`, and
436/// nothing is written; `429` + `Retry-After` over the per-user send limit.
437///
438/// Order matters and is deliberate: ownership is settled first (a foreign
439/// thread is a `404` and is never charged), then the per-user rate limit (a
440/// refused turn leaves no trace), then availability (so an unavailable service
441/// produces a `503` and no dead pending row), then the scope the question is
442/// asked under — derived by [`crate::service::rag_scope`], never from the
443/// body. Once the rows are written the turn always settles: the answering task
444/// stamps `complete`/`failed`, a reader projects a long-stale `pending` as
445/// failed, and the boot sweep repairs whatever a process death left behind.
446#[utoipa::path(
447 post,
448 path = "/threads/{id}/messages",
449 tag = "rag",
450 security(("session_cookie" = [])),
451 params(("id" = String, Path, description = "RagThread id")),
452 request_body = SendRagMessage,
453 responses(
454 (status = 202, description = "Accepted; the answer is on its way", body = AcceptedResponse),
455 (status = 400, description = "Empty message, or longer than the school's `max_chatbot_message_len`, or a scope past `MAX_RAG_SCOPE_PAIRS`", body = ErrorResponse),
456 (status = 401, description = "Not authenticated", body = ErrorResponse),
457 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
458 (status = 429, description = "Over the per-user send limit; retry after the advertised delay", body = ErrorResponse),
459 (status = 503, description = "No AI service offers `rag.chat` right now; nothing was written", body = ErrorResponse),
460 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
461 ),
462)]
463async fn send_message(
464 State(st): State<AppState>,
465 SchoolIdCookie(school): SchoolIdCookie,
466 tenant: ResolvedTenant,
467 CurrentUser(user): CurrentUser,
468 Path(id): Path<String>,
469 Json(req): Json<SendRagMessage>,
470) -> Result<Response, AppError> {
471 // Ownership first: a foreign thread is a 404, never a 403 — and a 404 must
472 // not spend the asker's minute.
473 let thread = own_thread(&id, user.get_id(), &st.db).await?;
474
475 // Then the tier. Charged before anything is written, so a refused turn
476 // leaves no row behind.
477 st.rag_limit
478 .enforce_user(&scoped_key(&school, user.get_id().key().as_str()))?;
479
480 let settings = service::settings::load(&st.db).await?;
481 let reply_cap = content_cap(&settings);
482 let length = req.content.chars().count();
483 if length > reply_cap {
484 return Err(AppError::Validation(ValidationError::TooLong {
485 field: "content",
486 max: reply_cap,
487 got: length,
488 }));
489 }
490 let content = RagContent::try_new(&req.content)?;
491
492 // The 503 gate, and the only place it is evaluated. `has_capability` is
493 // documented racy — that is fine here: it never guards a write, it only
494 // spares the user a thread full of rows nothing could ever answer.
495 let Some(bridge) = st.ai.clone() else {
496 return Ok(ai_unavailable(
497 "the AI service is not enabled on this deployment",
498 ));
499 };
500 if !bridge.has_capability(AI_RAG_CHAT_CAPABILITY) {
501 return Ok(ai_unavailable("no AI service is connected right now"));
502 }
503
504 // The scope the corpus is routed by, derived on every question — a
505 // manager or an admin gets every class-course pair in the school, everyone
506 // else their own memberships — never from the body, so a student cannot
507 // widen their own retrieval, and never from a stored copy, so a
508 // membership change takes effect on the next question. An empty scope is
509 // legal when the asker really has nothing to retrieve from, and is sent
510 // as-is: the service abstains rather than the backend refusing a question
511 // it cannot know is answerable. An admin's empty personal membership is
512 // not that case.
513 let scope = service::rag_scope::for_user(&st.db, &user, user.get_role()).await?;
514
515 // Each create rides the thread's own row — it moves `updated_at` (the
516 // list's sort key, so this is also the activity stamp) inside its own
517 // transaction. That is what serializes a turn against `DELETE
518 // /rag/threads/{id}`: the read above cannot, since reads do not conflict,
519 // and a row written into the delete's window survived it as a turn under a
520 // thread that is gone.
521 let prompt =
522 service::rag_message::append_user(&st.db, thread.get_id(), user.get_id(), content).await?;
523 let answer =
524 service::rag_message::append_pending_assistant(&st.db, thread.get_id(), user.get_id())
525 .await?;
526
527 let message_id = answer.get_id().key().to_string();
528 // Never awaited inline: the retrieval-then-answer round trip can outlast
529 // the request timeout that guards every handler, and the POST must return
530 // now. The settings snapshot goes with it, so the whole turn is judged by
531 // the policy that was live when it was accepted.
532 // The prompt travels by id, not by write order: two POSTs on one thread
533 // interleave across the two creates above, and picking "the newest user
534 // row before this answer" out of the thread then answers the *other*
535 // request's question twice.
536 tokio::spawn(answer_turn(
537 // The school and its database travel together — the same pair the
538 // request was already resolved into, and one without the other is how
539 // an answer lands in the wrong school.
540 TenantExt {
541 id: school,
542 db: st.db.clone(),
543 modules: tenant.modules,
544 },
545 bridge,
546 prompt.get_id().clone(),
547 answer,
548 *user.get_id(),
549 user.get_role(),
550 scope,
551 settings.get_chatbot_history_turns().max(0) as usize,
552 reply_cap,
553 ));
554
555 Ok((
556 StatusCode::ACCEPTED,
557 Json(AcceptedResponse {
558 message_id,
559 status: RagMessageStatus::Pending.as_str().to_string(),
560 }),
561 )
562 .into_response())
563}
564
565/// The school's per-message character cap, never above the domain's hard
566/// ceiling. Applied to what the user sends *and* to what the service answers —
567/// the same knob the chatbot nest reads.
568fn content_cap(settings: &Settings) -> usize {
569 (settings.get_max_chatbot_message_len().max(0) as usize).min(MAX_CHATBOT_MESSAGE_LEN)
570}
571
572/// Fetch one turn's answer and settle its row. Runs detached from the request.
573///
574/// Every path settles: a row left `pending` would show as a spinner forever.
575#[allow(clippy::too_many_arguments)] // the whole turn, handed to the detached task as one
576async fn answer_turn(
577 tenant: TenantExt,
578 bridge: AiBridge,
579 prompt_id: RagMessageId,
580 answer: RagMessage,
581 asker: UserId,
582 asker_role: Role,
583 scope: Vec<RagScopePair>,
584 history_turns: usize,
585 reply_cap: usize,
586) {
587 let db = tenant.db.clone();
588 let answer_id = answer.get_id().clone();
589 let thread = answer.get_thread_id().clone();
590 // This request's own question, read back by id — the text is already
591 // stored, so carrying the id rather than the string keeps the prompt and
592 // its answer paired however two POSTs on one thread interleave.
593 let prompt = match service::rag_message::prompt_of(&db, &prompt_id).await {
594 Ok(Some(prompt)) => prompt,
595 Ok(None) => {
596 // The prompt row is gone — only reachable if the thread was deleted
597 // out from under this task. There is nothing to ask, so settle.
598 tracing::warn!("rag answer {} has no prompt to send", answer_id.key());
599 let _ = service::rag_message::fail(&db, &answer_id, "internal").await;
600 return;
601 }
602 Err(err) => {
603 // Nothing to ask, and nothing will ask again: an unsettled row
604 // would be a spinner until the staleness horizon. Settle it here.
605 tracing::warn!("could not read the prompt for {}: {err}", answer_id.key());
606 let _ = service::rag_message::fail(&db, &answer_id, "internal").await;
607 return;
608 }
609 };
610 let fresh = [prompt.get_id().clone(), answer_id.clone()];
611 let history = match history_for(&db, &thread, &fresh, history_turns).await {
612 Ok(history) => history,
613 Err(err) => {
614 tracing::warn!("could not load rag history: {err}");
615 let _ = service::rag_message::fail(&db, &answer_id, "internal").await;
616 return;
617 }
618 };
619 let settled = match crate::ai::rag_chat::answer(
620 &db,
621 &bridge,
622 &tenant.id,
623 &thread,
624 &fresh,
625 prompt.get_content().as_str().to_string(),
626 &asker,
627 asker_role,
628 scope,
629 history,
630 )
631 .await
632 {
633 Ok((text, reply)) => {
634 // The service is a trust boundary: cap what it wrote before it
635 // reaches a row (or a browser). Truncation over rejection — a
636 // clipped answer still helps, a discarded one does not.
637 let clipped: String = text.chars().take(reply_cap).collect();
638 if clipped.chars().count() < text.chars().count() {
639 tracing::warn!(
640 "clipped an AI RAG reply to the school's {reply_cap}-character limit"
641 );
642 }
643 match RagContent::try_new(&clipped) {
644 Ok(content) => {
645 service::rag_message::complete(&db, &answer_id, content, SqlJson(reply)).await
646 }
647 Err(err) => {
648 // Nothing to show, and `RagContent` would refuse it anyway.
649 // A blank bubble is indistinguishable from a bug, so it is
650 // reported as one.
651 tracing::error!("a clipped AI RAG reply was still not storable: {err}");
652 service::rag_message::fail(&db, &answer_id, "bad_reply").await
653 }
654 }
655 }
656 Err(code) => {
657 tracing::warn!("rag answer {} failed: {code}", answer_id.key());
658 service::rag_message::fail(&db, &answer_id, &code).await
659 }
660 };
661 match settled {
662 Ok(_) => {}
663 // The row was no longer `pending`: the boot sweep or a stale-timeout
664 // already spoke for it, or the thread was deleted mid-flight. Benign —
665 // the user is not waiting on this row any more.
666 Err(AppError::NotFound) => {
667 tracing::info!("rag answer {} was already settled", answer_id.key());
668 }
669 Err(err) => tracing::error!("could not settle rag answer {}: {err}", answer_id.key()),
670 }
671}
672
673/// The tail of the thread replayed to the service: oldest first, only settled
674/// turns with text, and never the two rows this turn just wrote (the new
675/// prompt rides in `message`, the answer does not exist yet).
676async fn history_for(
677 db: &Database,
678 thread: &RagThreadId,
679 fresh: &[RagMessageId; 2],
680 turns: usize,
681) -> Result<Vec<crate::ai::rag_chat::RagTurn>, AppError> {
682 // The query counts only settled rows with text, so a run of failed answers
683 // makes the window reach *further back* instead of shrinking it — that is
684 // what "the last `chatbot_history_turns` settled turns" means. +2 so
685 // dropping this turn's own two rows cannot shorten it either (only the
686 // user one can match: the assistant row is still `pending`).
687 let tail =
688 service::rag_message::list_settled_tail(db, thread, turns.saturating_add(2)).await?;
689 let mut history: Vec<crate::ai::rag_chat::RagTurn> = tail
690 .iter()
691 .filter(|message| !fresh.contains(message.get_id()))
692 .map(|message| crate::ai::rag_chat::RagTurn {
693 role: match message.get_role() {
694 RagMessageRole::User => ChatRole::User,
695 RagMessageRole::Assistant => ChatRole::Assistant,
696 },
697 content: message.get_content().as_str().to_string(),
698 })
699 .collect();
700 if history.len() > turns {
701 history.drain(..history.len() - turns);
702 }
703 Ok(history)
704}
705
706/// Poll one turn. The non-SSE fallback for `/stream`, reading the same row —
707/// including the projection that presents a long-stale `pending` as `failed`,
708/// so the two can never disagree about a turn's state.
709#[utoipa::path(
710 get,
711 path = "/threads/{id}/messages/{mid}",
712 tag = "rag",
713 security(("session_cookie" = [])),
714 params(
715 ("id" = String, Path, description = "RagThread id"),
716 ("mid" = String, Path, description = "Message id"),
717 ),
718 responses(
719 (status = 200, description = "The turn, in whatever state it is", body = RagMessageResponse),
720 (status = 401, description = "Not authenticated", body = ErrorResponse),
721 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
722 ),
723)]
724async fn read_message(
725 State(st): State<AppState>,
726 CurrentUser(user): CurrentUser,
727 Path((id, mid)): Path<(String, String)>,
728) -> Result<Json<RagMessageResponse>, AppError> {
729 let message = own_message(&id, &mid, user.get_id(), &st.db).await?;
730 Ok(Json(RagMessageResponse::new(&message)))
731}
732
733/// Read one turn only if the caller owns it *and* it belongs to the named
734/// thread — a mismatched pair is a `404`, like a foreign one.
735///
736/// The thread is re-read rather than inferred from the message's `thread_id`,
737/// so a turn whose thread was deleted reads as gone through these two routes
738/// too — the same defence in depth [`super::chatbot`]'s twin carries.
739async fn own_message(
740 thread: &str,
741 message: &str,
742 user: &UserId,
743 db: &Database,
744) -> Result<RagMessage, AppError> {
745 own_thread(thread, user, db).await?;
746 service::rag_message::read_for(db, &RagMessageId::from_key(message), user)
747 .await?
748 .filter(|message| message.get_thread_id().key() == thread)
749 .ok_or(AppError::NotFound)
750}
751
752/// Watch one turn as Server-Sent Events: `delta` chunks of the answer, then a
753/// single `done` carrying the finished message, or one `error`. The stream
754/// closes after `done`/`error` — one stream per turn, not per thread.
755///
756/// Works whatever state the turn is in when the stream opens: an answer that
757/// already landed replays as `delta`s and a `done` straight away, so a client
758/// that reconnects late is never left hanging. Consume with `EventSource`
759/// (cookies ride along on same-site / credentialed requests). The `done`
760/// payload carries the whole settled turn — text, abstention, citations — so a
761/// late reader gets the citations too, not only the deltas.
762#[utoipa::path(
763 get,
764 path = "/threads/{id}/messages/{mid}/stream",
765 tag = "rag",
766 security(("session_cookie" = [])),
767 params(
768 ("id" = String, Path, description = "RagThread id"),
769 ("mid" = String, Path, description = "Message id"),
770 ),
771 responses(
772 (status = 200, description = "SSE: `delta` (`{text}`) chunks, then `done` (`{message}`) or `error` (`{code, message}`)", content_type = "text/event-stream"),
773 (status = 401, description = "Not authenticated", body = ErrorResponse),
774 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
775 ),
776)]
777async fn stream_message(
778 State(st): State<AppState>,
779 CurrentUser(user): CurrentUser,
780 Path((id, mid)): Path<(String, String)>,
781) -> Result<Sse<impl Stream<Item = Result<Event, axum::Error>>>, AppError> {
782 // Ownership is settled before the response becomes a stream — after this
783 // point the only way to say "no" is an `error` event.
784 own_message(&id, &mid, user.get_id(), &st.db).await?;
785
786 let (tx, rx) = mpsc::channel(REPLY_CHUNKS + 2);
787 let (message_id, user_id, db) = (
788 RagMessageId::from_key(&mid),
789 *user.get_id(),
790 st.db.clone(),
791 );
792 tokio::spawn(async move {
793 let mut ticker = tokio::time::interval(Duration::from_millis(CHAT_STREAM_POLL_MS));
794 loop {
795 // The first tick fires immediately: an already-finished turn is
796 // delivered on connect rather than one poll interval later.
797 //
798 // The wait also watches the receiver, because a `pending` turn
799 // sends nothing and would otherwise never learn that the client
800 // hung up: axum drops the response body — and with it this
801 // channel's receiver — the moment the connection dies, so this is
802 // where an abandoned stream stops polling the database.
803 tokio::select! {
804 _ = ticker.tick() => {}
805 _ = tx.closed() => return,
806 }
807 let message = match service::rag_message::read_for(&db, &message_id, &user_id).await {
808 Ok(Some(message)) => message,
809 // Deleted mid-stream (the thread went away) — say so and stop.
810 Ok(None) => {
811 sse_error(&tx, "not_found", "this message no longer exists").await;
812 return;
813 }
814 Err(err) => {
815 tracing::warn!("rag stream read failed: {err}");
816 sse_error(&tx, "internal", "could not read the message").await;
817 return;
818 }
819 };
820
821 match message.get_status() {
822 // Includes the read-time projection: a `pending` row past its
823 // staleness window arrives here as `failed`, so this loop
824 // always terminates.
825 RagMessageStatus::Pending => continue,
826 RagMessageStatus::Complete => {
827 for chunk in slice_reply(message.get_content().as_str()) {
828 if sse_send(&tx, "delta", json!({ "text": chunk }))
829 .await
830 .is_err()
831 {
832 return;
833 }
834 }
835 let done = json!({ "message": RagMessageResponse::new(&message) });
836 let _ = sse_send(&tx, "done", done).await;
837 return;
838 }
839 RagMessageStatus::Failed => {
840 let code = message.get_error_code().unwrap_or("failed");
841 sse_error(&tx, code, "the assistant could not answer this message").await;
842 return;
843 }
844 }
845 }
846 });
847
848 Ok(Sse::new(ReceiverStream::new(rx)).keep_alive(KeepAlive::default()))
849}
850
851// ---- the one-shot study doors ----------------------------------------------
852//
853// Two capabilities of the same RAG service, each exactly one dispatch: a
854// summary of one page/span range, and a set of practice questions over one.
855// They are this nest's only doors that neither thread nor store — the artifact
856// *is* the answer — so they wait for it, and no per-user rate limiter charges
857// them: one-shot requests cannot be retried into a loop the way a thread can,
858// and the RAG counts its own per-call rate and budget caps.
859//
860// Authorization is the nest's own scope derivation, applied twice: the asker's
861// `(sinif, ders)` pairs come from [`service::rag_scope::for_user`] — never from
862// the body — and the body only *names* a target inside them
863// ([`resolve_study_pair`]). The pair that travels to the service is the derived
864// one, so the corpus it retrieves from is a corpus the backend already decided
865// the asker may study. The service's own scope guard is defence in depth: when
866// it answers `role_required`/`scope_mismatch` the **backend** built a bad
867// request, and that is reported as one (a `502`, logged by
868// [`crate::ai::rag_study`]).
869
870/// The scope half of a study request: which corpus, and which range inside it.
871#[derive(Deserialize, ToSchema)]
872struct StudyScopeRequest {
873 /// The subject/course to study. Required, non-empty.
874 ders: String,
875 /// The şube/grade the corpus belongs to. Optional — a school-wide corpus
876 /// (club/etüt) has none — and required in practice when the subject is
877 /// taught at more than one grade: the door then answers `400` instead of
878 /// guessing which section the caller meant.
879 #[serde(default)]
880 sinif: Option<String>,
881 /// Pages of the corpus to work over. Normally exactly one of
882 /// `pages`/`span_ids` is named; naming neither is answered by the service
883 /// as an abstention (`empty_scope`), not refused here.
884 #[serde(default)]
885 pages: Vec<i64>,
886 /// Retrieval span ids to work over, for a range the caller already holds
887 /// from an earlier retrieval.
888 #[serde(default)]
889 span_ids: Vec<String>,
890 /// A human label for the range (the heading the caller selected).
891 #[serde(default)]
892 scope_label: Option<String>,
893}
894
895impl StudyScopeRequest {
896 /// The wire scope this request names, with the **resolved** pair as its
897 /// `(sinif, ders)` half: the corpus the service is addressed to is the one
898 /// [`crate::service::rag_scope`] authorized, never the body's spelling of
899 /// it.
900 fn into_scope(self, pair: RagScopePair) -> RagScope {
901 RagScope {
902 sinif: pair.sinif,
903 ders: pair.ders,
904 pages: self.pages,
905 span_ids: self.span_ids,
906 scope_label: self.scope_label.unwrap_or_default(),
907 }
908 }
909}
910
911/// A `/rag/questions` body: the same scope, plus the shape of the set to
912/// generate.
913#[derive(Deserialize, ToSchema)]
914struct QuestionsRequest {
915 #[serde(flatten)]
916 scope: StudyScopeRequest,
917 /// How many questions to generate. Defaults to 5; the door holds it to
918 /// `1..=20`.
919 #[serde(default = "default_question_count")]
920 n: u32,
921 /// The difficulty asked for, in the service's own vocabulary
922 /// (`kolay`/`orta`/`zor`), defaulting to `orta`. Forwarded, never judged
923 /// here: the vocabulary belongs to the service.
924 #[serde(default = "default_difficulty")]
925 difficulty: String,
926 /// A question to base the set on, when the caller wants variations of one
927 /// particular exercise. Omitted means "any question within the range".
928 #[serde(default)]
929 seed_question: Option<String>,
930}
931
932fn default_question_count() -> u32 {
933 5
934}
935
936fn default_difficulty() -> String {
937 "orta".to_string()
938}
939
940/// One citation behind a summary, as the bridge carries it. Unlike `rag.chat`'s
941/// citations it names no corpus document, so nothing here resolves to a
942/// course-note file: a summary is addressed to a range the caller selected.
943#[derive(Serialize, ToSchema)]
944struct RagSummaryCitationResponse {
945 n: u32,
946 pages: Vec<i64>,
947 span_ids: Vec<String>,
948}
949
950impl From<RagSummaryCitation> for RagSummaryCitationResponse {
951 fn from(citation: RagSummaryCitation) -> Self {
952 Self {
953 n: citation.n,
954 pages: citation.pages,
955 span_ids: citation.span_ids,
956 }
957 }
958}
959
960/// A summary of one range of one corpus. `abstained` with a `reason` is a
961/// complete answer, exactly as it is on a chat turn.
962#[derive(Serialize, ToSchema)]
963struct RagSummarizeResponse {
964 text: String,
965 abstained: bool,
966 reason: String,
967 citations: Vec<RagSummaryCitationResponse>,
968 /// The pages the summary actually covered.
969 scope_pages: Vec<i64>,
970 /// Whether the service summarized hierarchically (per section, then rolled
971 /// up) rather than flat.
972 hierarchical: bool,
973}
974
975impl From<RagSummarizeReply> for RagSummarizeResponse {
976 fn from(reply: RagSummarizeReply) -> Self {
977 Self {
978 text: reply.text,
979 abstained: reply.abstained,
980 reason: reply.reason,
981 citations: reply.citations.into_iter().map(Into::into).collect(),
982 scope_pages: reply.scope_pages,
983 hierarchical: reply.hierarchical,
984 }
985 }
986}
987
988/// One generated practice question. The bridge's `soru`/`cevap`/`zorluk` become
989/// this API's `question`/`answer`/`difficulty` here: the wire keeps the
990/// service's vocabulary, the HTTP surface keeps the backend's.
991#[derive(Serialize, ToSchema)]
992struct RagQuestionResponse {
993 question: String,
994 answer: String,
995 difficulty: String,
996}
997
998impl From<RagQuestion> for RagQuestionResponse {
999 fn from(question: RagQuestion) -> Self {
1000 Self {
1001 question: question.soru,
1002 answer: question.cevap,
1003 difficulty: question.zorluk,
1004 }
1005 }
1006}
1007
1008/// A generated set of practice questions over one range of one corpus.
1009#[derive(Serialize, ToSchema)]
1010struct RagQuestionsResponse {
1011 items: Vec<RagQuestionResponse>,
1012 abstained: bool,
1013 reason: String,
1014 /// The retrieval spans the whole set is bounded to.
1015 span_ids: Vec<String>,
1016 /// The pages those spans sit on.
1017 pages: Vec<i64>,
1018}
1019
1020impl From<RagQuestionsReply> for RagQuestionsResponse {
1021 fn from(reply: RagQuestionsReply) -> Self {
1022 Self {
1023 items: reply.items.into_iter().map(Into::into).collect(),
1024 abstained: reply.abstained,
1025 reason: reply.reason,
1026 span_ids: reply.span_ids,
1027 pages: reply.pages,
1028 }
1029 }
1030}
1031
1032/// The one `(sınıf, ders)` pair a study request may address, resolved against
1033/// the asker's own derived pairs — the body only *names* a target inside them.
1034///
1035/// A named ders matches a pair **exactly** first — a picker's own spelling is
1036/// never re-rolled — and only then through [`crate::domain::text_fold::search_fold`],
1037/// the fold the RAG slug vocabulary rides: a citation names its course by slug
1038/// (`biyoloji`), the pair carries the course title (`Biyoloji`), and the two
1039/// spellings must resolve to one pair. A named grade must still be a pair the
1040/// asker holds; anything else is a `403`, because a corpus the asker cannot
1041/// study must not be summarized on their behalf. An absent or empty grade
1042/// resolves the subject alone: exactly one pair for that `ders` is the target,
1043/// none is a `403`, and more than one is a `400` — the caller must name the
1044/// şube, since picking one for them would answer from a corpus they did not
1045/// name. Two *distinct* courses folding to one key refuse the same way rather
1046/// than routing on a guess.
1047fn resolve_study_pair(
1048 pairs: &[RagScopePair],
1049 ders: &str,
1050 sinif: Option<&str>,
1051) -> Result<RagScopePair, AppError> {
1052 if ders.trim().is_empty() {
1053 return Err(AppError::Validation(ValidationError::Empty("ders")));
1054 }
1055 let grade = sinif.filter(|grade| !grade.trim().is_empty());
1056 let in_grade =
1057 |pair: &&RagScopePair| grade.is_none() || pair.sinif.as_deref() == grade;
1058 let mut matches: Vec<&RagScopePair> =
1059 pairs.iter().filter(|pair| in_grade(pair) && pair.ders == ders).collect();
1060 if matches.is_empty() {
1061 let folded = crate::domain::text_fold::search_fold(ders);
1062 matches = pairs
1063 .iter()
1064 .filter(|pair| {
1065 in_grade(pair) && crate::domain::text_fold::search_fold(&pair.ders) == folded
1066 })
1067 .collect();
1068 }
1069 let Some(first) = matches.first() else {
1070 return Err(AppError::Forbidden(match grade {
1071 Some(_) => "the requested ders/sinif pair is not in your scope",
1072 None => "the requested ders is not in your scope",
1073 }));
1074 };
1075 if matches.len() > 1 {
1076 // One title across several grades is the name-the-grade refusal;
1077 // distinct titles folding equal cannot be settled by naming anything,
1078 // so the ders itself is judged ambiguous — never a first-wins guess.
1079 let one_title = matches.iter().all(|pair| pair.ders == first.ders);
1080 return Err(AppError::Validation(ValidationError::Invalid {
1081 field: if one_title { "sinif" } else { "ders" },
1082 reason: if one_title {
1083 "name the grade: this ders is taught in more than one"
1084 } else {
1085 "more than one course matches this name; name the course exactly"
1086 },
1087 }));
1088 }
1089 Ok((*first).clone())
1090}
1091
1092/// Summarize one range of one corpus the caller may study.
1093///
1094/// Synchronous by design: the summary is what the caller asked for, so there is
1095/// no thread to open, no row to poll and nothing stored. The scope is derived
1096/// by [`crate::service::rag_scope`] — a manager or an admin gets every
1097/// class-course pair in the school, everyone else their own memberships —
1098/// never from the body, which only names a target inside them — and the
1099/// `(sinif, ders)` pair that reaches the service is the derived one. `503`
1100/// when no AI service offers `rag.summarize`.
1101/// `abstained: true` with a `reason` is a complete answer riding a `200`.
1102///
1103/// The dispatch deadline (25 s) is deliberately under the middleware's own
1104/// 30 s envelope ([`crate::constant::REQUEST_TIMEOUT_SECS`]): this door waits,
1105/// and being dropped mid-flight would answer with prose written for a request
1106/// that may have written something.
1107#[utoipa::path(
1108 post,
1109 path = "/summarize",
1110 tag = "rag",
1111 security(("session_cookie" = [])),
1112 request_body = StudyScopeRequest,
1113 responses(
1114 (status = 200, description = "The summary — possibly an abstention: `abstained: true` with a `reason` is a complete answer", body = RagSummarizeResponse),
1115 (status = 400, description = "`ders` is empty, or `sinif` was omitted for a ders taught in more than one grade", body = ErrorResponse),
1116 (status = 401, description = "Not authenticated", body = ErrorResponse),
1117 (status = 403, description = "The requested `(sinif, ders)` is not one of the caller's own scopes", body = ErrorResponse),
1118 (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),
1119 (status = 502, description = "The AI service answered something this backend could not use, or built a request it refused", body = ErrorResponse),
1120 (status = 503, description = "No AI service offers `rag.summarize` right now", body = ErrorResponse),
1121 (status = 504, description = "The AI service did not answer within the dispatch deadline", body = ErrorResponse),
1122 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
1123 ),
1124)]
1125async fn summarize(
1126 State(st): State<AppState>,
1127 SchoolIdCookie(school): SchoolIdCookie,
1128 CurrentUser(user): CurrentUser,
1129 Json(req): Json<StudyScopeRequest>,
1130) -> Result<Response, AppError> {
1131 let Some(bridge) = st.ai.clone() else {
1132 return Ok(ai_unavailable(
1133 "the AI service is not enabled on this deployment",
1134 ));
1135 };
1136 if !bridge.has_capability(AI_RAG_SUMMARIZE_CAPABILITY) {
1137 return Ok(ai_unavailable("no AI service is connected right now"));
1138 }
1139
1140 // The scope the corpus is routed by, derived on every request — a manager
1141 // or an admin gets every class-course pair in the school, everyone else
1142 // their own memberships — never from the body, so a caller cannot
1143 // summarize a corpus they cannot study. The body's `ders`/`sinif` only
1144 // pick a pair out of that set.
1145 let pairs = service::rag_scope::for_user(&st.db, &user, user.get_role()).await?;
1146 let pair = resolve_study_pair(&pairs, &req.ders, req.sinif.as_deref())?;
1147 let payload = RagSummarizePayload {
1148 scope: req.into_scope(pair),
1149 scope_pairs: pairs
1150 .iter()
1151 .map(|pair| (pair.sinif.clone(), pair.ders.clone()))
1152 .collect(),
1153 // What the session already proves, never what the body claims.
1154 asker: user.get_id().key(),
1155 asker_role: user.get_role().as_str().to_string(),
1156 };
1157 match rag_study::summarize(&bridge, &school, payload).await {
1158 Ok(reply) => Ok(Json(RagSummarizeResponse::from(reply)).into_response()),
1159 Err(code) => Ok(failure(&code)),
1160 }
1161}
1162
1163/// Generate practice questions over one range of one corpus the caller may
1164/// study, with the answers bounded to that range.
1165///
1166/// One-shot and synchronous like [`summarize`], and gated the same way: the
1167/// same derived scope, the same `403`/`400` resolution, the same `503` when no
1168/// service offers the capability, and the same rule that an abstention is a
1169/// complete answer on a `200`. What it adds is the shape of the set: `n`
1170/// (default 5, at most [`MAX_RAG_QUESTIONS`]), `difficulty` (default `orta`)
1171/// and an optional `seed_question` to generate variations of one exercise.
1172#[utoipa::path(
1173 post,
1174 path = "/questions",
1175 tag = "rag",
1176 security(("session_cookie" = [])),
1177 request_body = QuestionsRequest,
1178 responses(
1179 (status = 200, description = "The generated questions — possibly an abstention: `abstained: true` with a `reason` is a complete answer", body = RagQuestionsResponse),
1180 (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),
1181 (status = 401, description = "Not authenticated", body = ErrorResponse),
1182 (status = 403, description = "The requested `(sinif, ders)` is not one of the caller's own scopes", body = ErrorResponse),
1183 (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),
1184 (status = 502, description = "The AI service answered something this backend could not use, or built a request it refused", body = ErrorResponse),
1185 (status = 503, description = "No AI service offers `rag.questions` right now", body = ErrorResponse),
1186 (status = 504, description = "The AI service did not answer within the dispatch deadline", body = ErrorResponse),
1187 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
1188 ),
1189)]
1190async fn questions(
1191 State(st): State<AppState>,
1192 SchoolIdCookie(school): SchoolIdCookie,
1193 CurrentUser(user): CurrentUser,
1194 Json(req): Json<QuestionsRequest>,
1195) -> Result<Response, AppError> {
1196 let Some(bridge) = st.ai.clone() else {
1197 return Ok(ai_unavailable(
1198 "the AI service is not enabled on this deployment",
1199 ));
1200 };
1201 if !bridge.has_capability(AI_RAG_QUESTIONS_CAPABILITY) {
1202 return Ok(ai_unavailable("no AI service is connected right now"));
1203 }
1204
1205 let pairs = service::rag_scope::for_user(&st.db, &user, user.get_role()).await?;
1206 let pair = resolve_study_pair(&pairs, &req.scope.ders, req.scope.sinif.as_deref())?;
1207 if !(1..=MAX_RAG_QUESTIONS).contains(&req.n) {
1208 return Err(AppError::Validation(ValidationError::Invalid {
1209 field: "n",
1210 reason: "must be between 1 and 20",
1211 }));
1212 }
1213 let payload = RagQuestionsPayload {
1214 scope: req.scope.into_scope(pair),
1215 scope_pairs: pairs
1216 .iter()
1217 .map(|pair| (pair.sinif.clone(), pair.ders.clone()))
1218 .collect(),
1219 asker: user.get_id().key(),
1220 asker_role: user.get_role().as_str().to_string(),
1221 n: req.n,
1222 difficulty: req.difficulty,
1223 seed_question: req.seed_question,
1224 };
1225
1226 match rag_study::questions(&bridge, &school, payload).await {
1227 Ok(reply) => Ok(Json(RagQuestionsResponse::from(reply)).into_response()),
1228 Err(code) => Ok(failure(&code)),
1229 }
1230}
1231
1232/// A relayed failure as the response a client branches on: the service's own
1233/// code decides the status where it is one this backend knows, and anything
1234/// else is a `502` — the backend cannot vouch for an answer it did not
1235/// understand, and a gateway error is exactly that claim.
1236///
1237/// `role_required` and `scope_mismatch` land in that fallback deliberately:
1238/// both mean the **backend** composed a request the service may not answer, so
1239/// [`crate::ai::rag_study`] logs them as bugs where they are detected and the
1240/// caller is told the gateway failed rather than being handed the service's own
1241/// wording for this side's defect.
1242fn failure(code: &str) -> Response {
1243 let status = match code {
1244 "bad_request" => StatusCode::BAD_REQUEST,
1245 "not_found" => StatusCode::NOT_FOUND,
1246 "not_ready" | "llm_unavailable" => StatusCode::CONFLICT,
1247 "busy" | "unavailable" => StatusCode::SERVICE_UNAVAILABLE,
1248 "timed_out" => StatusCode::GATEWAY_TIMEOUT,
1249 "internal" => StatusCode::INTERNAL_SERVER_ERROR,
1250 // `transport`, `protocol`, `bad_reply`, `role_required`,
1251 // `scope_mismatch`, `service_error`, and any code the service
1252 // invented: a bad gateway.
1253 _ => StatusCode::BAD_GATEWAY,
1254 };
1255 (status, Json(json!({ "error": code }))).into_response()
1256}
1257
1258#[cfg(test)]
1259mod tests {
1260 use super::*;
1261
1262 #[test]
1263 fn a_citation_reply_maps_every_field_into_the_wire_shape() {
1264 let stored = RagCitedFile {
1265 n: 2,
1266 file: Some("0197-file".into()),
1267 pages: vec![3, 4],
1268 span_ids: vec!["s-1".into()],
1269 ders: Some("Fizik".into()),
1270 };
1271 let wire = RagCitationResponse::from(&stored);
1272 assert_eq!(wire.n, 2);
1273 assert_eq!(wire.file.as_deref(), Some("0197-file"));
1274 assert_eq!(wire.pages, vec![3, 4]);
1275 assert_eq!(wire.span_ids, vec!["s-1"]);
1276 assert_eq!(wire.ders.as_deref(), Some("Fizik"));
1277
1278 // An unresolved citation keeps every other field — the passage is
1279 // still citable, only not openable.
1280 let unresolved = RagCitationResponse::from(&RagCitedFile {
1281 file: None,
1282 ..stored
1283 });
1284 assert_eq!(unresolved.file, None);
1285 assert_eq!(unresolved.pages, vec![3, 4]);
1286 }
1287
1288 fn pair(sinif: Option<&str>, ders: &str) -> RagScopePair {
1289 RagScopePair {
1290 sinif: sinif.map(str::to_string),
1291 ders: ders.to_string(),
1292 }
1293 }
1294
1295 #[test]
1296 fn a_study_pair_resolves_only_inside_the_askers_own_scope() {
1297 let pairs = vec![
1298 pair(Some("10"), "Biyoloji"),
1299 pair(None, "Satranç Kulübü"),
1300 pair(Some("9"), "Matematik"),
1301 ];
1302
1303 // A named grade must be the exact pair, and the resolved pair is what
1304 // travels — never the body's own spelling.
1305 let resolved = resolve_study_pair(&pairs, "Biyoloji", Some("10")).unwrap();
1306 assert_eq!(resolved.sinif.as_deref(), Some("10"));
1307 let grade_less = resolve_study_pair(&pairs, "Satranç Kulübü", None).unwrap();
1308 assert_eq!(grade_less.sinif, None);
1309
1310 // A grade the asker is not scoped to, and a ders they hold no pair
1311 // for, are both `403` — a corpus they cannot study must not be
1312 // summarized on their behalf.
1313 assert!(matches!(
1314 resolve_study_pair(&pairs, "Biyoloji", Some("11")),
1315 Err(AppError::Forbidden(_))
1316 ));
1317 assert!(matches!(
1318 resolve_study_pair(&pairs, "Fizik", None),
1319 Err(AppError::Forbidden(_))
1320 ));
1321 // An empty ders is a malformed body, not a scope refusal.
1322 assert!(matches!(
1323 resolve_study_pair(&pairs, " ", None),
1324 Err(AppError::Validation(ValidationError::Empty("ders")))
1325 ));
1326
1327 // Two şubeler teaching one course: the caller must name the grade,
1328 // because picking one for them answers from a corpus they did not name.
1329 let two = vec![pair(Some("9"), "Fizik"), pair(Some("10"), "Fizik")];
1330 assert!(matches!(
1331 resolve_study_pair(&two, "Fizik", None),
1332 Err(AppError::Validation(ValidationError::Invalid { field: "sinif", .. }))
1333 ));
1334 assert!(resolve_study_pair(&two, "Fizik", Some("10")).is_ok());
1335 }
1336 /// A citation names its course by the RAG slug vocabulary (lowercase,
1337 /// diacritic-stripped) while the pair carries the course title: the body's
1338 /// `biyoloji` must resolve the pair whose title is `Biyoloji`, with the
1339 /// derived title — never the body's slug — being what travels.
1340 #[test]
1341 fn a_study_pair_matches_the_slug_spelling_through_the_search_fold() {
1342 let pairs = vec![
1343 pair(Some("10"), "Biyoloji"),
1344 pair(Some("9"), "İngilizce"),
1345 pair(Some("11"), "Coğrafya"),
1346 ];
1347
1348 // The slug spelling resolves, with and without a named grade.
1349 let resolved = resolve_study_pair(&pairs, "biyoloji", None).unwrap();
1350 assert_eq!(resolved.ders, "Biyoloji");
1351 assert_eq!(resolved.sinif.as_deref(), Some("10"));
1352 assert_eq!(
1353 resolve_study_pair(&pairs, "biyoloji", Some("10")).unwrap().ders,
1354 "Biyoloji"
1355 );
1356
1357 // The fold is Turkish-correct both ways: dotted İ folds, and the
1358 // slug's stripped diacritics still reach the accented title.
1359 assert_eq!(
1360 resolve_study_pair(&pairs, "ingilizce", None).unwrap().ders,
1361 "İngilizce"
1362 );
1363 assert_eq!(
1364 resolve_study_pair(&pairs, "cografya", Some("11")).unwrap().ders,
1365 "Coğrafya"
1366 );
1367
1368 // A grade the asker holds no folded pair for, and a ders no course
1369 // folds to, are still the same scope refusal — never widened access.
1370 assert!(matches!(
1371 resolve_study_pair(&pairs, "biyoloji", Some("11")),
1372 Err(AppError::Forbidden(_))
1373 ));
1374 assert!(matches!(
1375 resolve_study_pair(&pairs, "fizik", None),
1376 Err(AppError::Forbidden(_))
1377 ));
1378 }
1379
1380 /// Two *distinct* courses folding to one key refuse rather than route on
1381 /// a guess — the same multi-match verdict family as the multi-grade
1382 /// refusal, judged on `ders` since naming a grade cannot settle it.
1383 #[test]
1384 fn folded_ambiguity_refuses_instead_of_guessing() {
1385 // `Kâğıt` and `Kagit` fold to one key, and no exact spelling of the
1386 // slug settles which one the caller meant.
1387 let folded_twins = vec![pair(Some("9"), "Kâğıt"), pair(Some("9"), "Kagit")];
1388 assert!(matches!(
1389 resolve_study_pair(&folded_twins, "kagit", None),
1390 Err(AppError::Validation(ValidationError::Invalid { field: "ders", .. }))
1391 ));
1392 assert!(matches!(
1393 resolve_study_pair(&folded_twins, "kagit", Some("9")),
1394 Err(AppError::Validation(ValidationError::Invalid { field: "ders", .. }))
1395 ));
1396
1397 // One course taught in two grades, named by slug: the caller must
1398 // still name the grade.
1399 let two_grades = vec![pair(Some("9"), "Biyoloji"), pair(Some("10"), "Biyoloji")];
1400 assert!(matches!(
1401 resolve_study_pair(&two_grades, "biyoloji", None),
1402 Err(AppError::Validation(ValidationError::Invalid { field: "sinif", .. }))
1403 ));
1404 assert_eq!(
1405 resolve_study_pair(&two_grades, "biyoloji", Some("10")).unwrap().ders,
1406 "Biyoloji"
1407 );
1408 }
1409}