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

insights.rs1469 lines, 62.7 KiBHistoryRawDownload
1//! The insight nest: the read surface over ZEKA's tables, the doors that ask
2//! ZEKA to compute, and the storage doors its rows are written through.
3//!
4//! ZEKA (`hezarfen_zeka`) is an AI service that dials in over the QUIC bridge.
5//! It **does not touch a school database** — no AI service on this deployment
6//! does — so the `zeka_*` tables, created by the school migrator, are written
7//! and read only by this process. Two surfaces, one implementation each: the
8//! service calls the backend over the bridge (`insight.summary.upsert` and
9//! the rest of the family — the wire contract is [`crate::ai::insight`], the
10//! statements are [`crate::db::insight`]), and the same operations are
11//! mounted here as HTTP doors for tooling. The backend never composes an
12//! insight row; it stores what the service computed and hands it back.
13//!
14//! Reading is authorized the way every per-student report in this API is:
15//! [`service::parent_link::ensure_can_observe`] decides whether the caller
16//! may read *that student* at all (teacher+ clears it, a parent needs a live
17//! link), and a teacher is then narrowed to the students they actually reach
18//! — a shared class×course instance, asked through
19//! [`service::instance::visible_instances`]. A student who is not the subject
20//! reads `404`, never `403`: a foreign id is indistinguishable from a missing
21//! one, the same posture `/marks/{user}` and `/rag/threads/{id}` take.
22//!
23//! What each door deliberately does **not** return is as much of the contract
24//! as what it does (ZEKA's output contract,
25//! `hezarfen_zeka/service/docs/CIKTI-SOZLESMESI.md` §5):
26//!
27//! * The attention list is a teacher's tool. It never appears in
28//! [`my_insight`], and a linked parent reading their child does not get it
29//! either — only staff at `teacher` or above do.
30//! * A card's `about` (another student's id) never reaches a student caller.
31//! * Segment rows with `confidence = 'none'` (fewer than 30 answers) are
32//! filtered out: noise stays in the database, not on a screen.
33//! * Dismissed and expired cards are filtered out of both card reads — the
34//! application closes a card by stamping `dismissed_at`, and a closed card
35//! must not come back. (The dismiss **write** is not built here: nothing in
36//! this batch asked for it, and it needs its own decision on who may stamp
37//! the audit trail. `deferred`, not half-done.)
38//!
39//! Sending is detached, like every other AI round trip in this API: the
40//! compute doors answer `202` the moment the work is queued, because a
41//! student's compute can outlast the request-timeout layer
42//! ([`crate::constant::REQUEST_TIMEOUT_SECS`]). The client polls the stored
43//! rows — the compute doors change nothing a reader cannot already see.
44//!
45//! The **report** doors are the one exception, and deliberately: building the
46//! school's document is not a compute the service does on its own schedule —
47//! it is one artifact the manager asked for, rendered from rows the backend
48//! already holds, so `POST /runs/{run_day}/report` waits, stores the returned
49//! HTML under the school's own blob directory, and answers `200` with what
50//! was stored. `GET /runs/{run_day}/report` streams that document back.
51
52use axum::Json;
53use axum::body::Body;
54use axum::extract::{Path, Query};
55use axum::http::HeaderValue;
56use axum::http::StatusCode;
57use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS};
58use axum::response::{IntoResponse, Response};
59use serde::{Deserialize, Serialize};
60use serde_json::Value as JsonValue;
61use sqlx::types::Json as SqlJson;
62use utoipa::ToSchema;
63use utoipa_axum::router::OpenApiRouter;
64use utoipa_axum::routes;
65
66use crate::ai::error::AiError;
67use crate::ai::insight::{
68 self, PendingList, ProfileWriteRequest, PurgeRequest, REPORT_KIND_SCHOOL, ROSTER_SOURCE_EXPLICIT,
69 ROSTER_SOURCE_SCHOOL, RecommendationWriteRequest, RefreshRequest, ReportRequest, RunWriteRequest,
70 SchoolDirectory, SegmentWriteRequest, StudentRequest, SummaryWriteRequest, TableVerdicts,
71 WriteReceipt,
72};
73use crate::constant::{
74 AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_REPORT_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY,
75 MAX_INSIGHT_REFRESH_STUDENTS,
76};
77use crate::database::Database;
78use crate::db;
79use crate::domain::class_group::ClassGroupId;
80use crate::domain::course::CourseId;
81use crate::domain::role::Role;
82use crate::domain::user::{User, UserId};
83use crate::error::{AppError, ErrorResponse, ValidationError};
84use crate::service;
85use crate::service::parent_link::ensure_can_observe;
86use crate::state::AppState;
87use crate::tenant::ResolvedTenant;
88use crate::web::tenant_state::State;
89
90use super::{
91 CurrentUser, Page, PageParams, RequireBuilder, RequireManager, ai_unavailable, paginate, pump,
92};
93
94/// The single `now` every card read is filtered against. ZEKA stores unix
95/// milliseconds, so "expired" is a comparison, not a projection.
96fn now_millis() -> i64 {
97 crate::domain::timestamp::Timestamp::now().as_millis()
98}
99
100pub fn routes() -> OpenApiRouter<AppState> {
101 OpenApiRouter::new()
102 .routes(routes!(refresh))
103 .routes(routes!(my_insight))
104 .routes(routes!(student_insight, compute_student))
105 .routes(routes!(list_runs, write_run))
106 .routes(routes!(generate_report, serve_report))
107 .routes(routes!(write_summaries))
108 .routes(routes!(write_recommendations))
109 .routes(routes!(write_segments))
110 .routes(routes!(write_profiles))
111 .routes(routes!(pending_students))
112 .routes(routes!(sweep_retention))
113 .routes(routes!(purge_departed))
114}
115
116/// The one door of this nest that is **not** school-scoped: the deployment's
117/// active-school directory.
118///
119/// ZEKA's storage operations are all scoped to the school a session belongs
120/// to, and so are these doors — but the directory is not: it names every
121/// customer. A school session must therefore never reach it, which is why
122/// this route is mounted *outside* the school-scoped gate, on the builder
123/// principal (the deployment operator), exactly like the vendor surface's own
124/// `GET /schools`. A school cookie answers `401` here, as it does everywhere
125/// the builder principal is required.
126pub fn school_directory_routes() -> OpenApiRouter<AppState> {
127 OpenApiRouter::new().routes(routes!(active_schools))
128}
129
130// ---- the compute doors -----------------------------------------------------
131
132/// The receipt for a queued dispatch. It carries no id: what was started is
133/// not a row of ours, and the work's own record is ZEKA's (`zeka_run` for a
134/// refresh, a student's `computed_at` for a compute).
135#[derive(Serialize, ToSchema)]
136struct AcceptedResponse {
137 /// Always `accepted` — the field exists so a client can branch on the
138 /// body rather than on the status code alone.
139 #[schema(example = "accepted")]
140 status: String,
141}
142
143#[derive(Deserialize, ToSchema, Default)]
144struct ComputeStudentRequest {
145 /// ISO-8601 date to compute from; omit for the term's beginning.
146 #[schema(example = "2026-09-01")]
147 since: Option<String>,
148 /// Compute only these sections; omit for all of them.
149 sections: Option<Vec<String>>,
150}
151
152#[derive(Deserialize, ToSchema, Default)]
153struct RefreshInsightsRequest {
154 /// Student user ids to recompute; omit (or send an empty list) to sweep
155 /// the school's own student roster — every user holding the `student`
156 /// role. A named list is used exactly as given.
157 user_ids: Option<Vec<String>>,
158 /// Recompute even where the service considers its cached result valid.
159 force: Option<bool>,
160}
161
162/// Ask ZEKA to recompute one student's insight, detached. `202` means queued,
163/// not computed: the service works through the student's data and writes its
164/// `zeka_*` rows on its own, and `GET /insights/students/{id}` shows them as
165/// soon as they land. `503` when no service offers `insight.student` — and
166/// nothing is queued.
167///
168/// Authorization is [`student_insight`]'s, gate for gate: the caller must be
169/// able to read the student before they may ask for a recompute, and the
170/// refusal is a `404` (a foreign id and a missing one look the same).
171///
172/// The dispatch names the **caller** as `requested_by`, not the student: the
173/// service reads the student's marks and the rest as that caller, so a
174/// teacher's or manager's own reach is what the reads answer against.
175#[utoipa::path(
176 post,
177 path = "/students/{user}",
178 tag = "insights",
179 security(("session_cookie" = [])),
180 params(("user" = String, Path, description = "User id")),
181 request_body = ComputeStudentRequest,
182 responses(
183 (status = 202, description = "Queued; the service writes the rows on its own", body = AcceptedResponse),
184 (status = 401, description = "Not authenticated", body = ErrorResponse),
185 (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse),
186 (status = 404, description = "Not found — no such student, or not one the caller may read", body = ErrorResponse),
187 (status = 503, description = "No AI service offers `insight.student` right now; nothing was queued", body = ErrorResponse),
188 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
189 ),
190)]
191async fn compute_student(
192 State(st): State<AppState>,
193 tenant: ResolvedTenant,
194 CurrentUser(user): CurrentUser,
195 Path(id): Path<String>,
196 body: Option<Json<ComputeStudentRequest>>,
197) -> Result<Response, AppError> {
198 let target = UserId::from_key(&id);
199 ensure_can_read(&user, &target, &st.db).await?;
200
201 let body = body.map(|Json(body)| body).unwrap_or_default();
202 let request = StudentRequest {
203 user_id: target.key(),
204 requested_by: user.get_id().key(),
205 since: body.since,
206 sections: body.sections,
207 };
208 let Some(bridge) = st.ai.clone() else {
209 return Ok(ai_unavailable(
210 "the AI service is not enabled on this deployment",
211 ));
212 };
213 if !bridge.has_capability(AI_INSIGHT_STUDENT_CAPABILITY) {
214 return Ok(ai_unavailable("no AI service is connected right now"));
215 }
216 let school = tenant.id;
217 tokio::spawn(async move {
218 match insight::compute_student(&bridge, &school, &request).await {
219 Ok(answer) => tracing::info!(
220 "insight.student answered for {}: {} signal(s), {} recommendation(s)",
221 request.user_id,
222 answer.signals.len(),
223 answer.recommendations.len()
224 ),
225 Err(err) => tracing::warn!("insight.student failed for {}: {err}", request.user_id),
226 }
227 });
228
229 Ok(accepted())
230}
231
232/// Ask ZEKA to recompute the whole school's insights, detached. `202` means
233/// queued; the sweep's own record is `zeka_run`, which `GET /insights/runs`
234/// reads — poll that to watch a run move from `running` to its verdict.
235///
236/// Manager+ only: this is a school-wide batch, and the run it starts spends
237/// the service's whole time budget. `503` when no service offers
238/// `insight.refresh` — nothing is queued.
239///
240/// The dispatch names the **caller** as `requested_by` — the principal the
241/// service's own reads for the sweep run as — and always fills `user_ids`: a
242/// named list passes through exactly as given, while an empty body is filled
243/// from the school's own student roster (every user holding the `student`
244/// role). The service's own roster discovery reads homework `assigned` lists,
245/// so an empty body used to sweep nobody; the payload's `roster_source` records
246/// which roster the list was. A school with no students dispatches an empty
247/// list and answers `0` honestly.
248#[utoipa::path(
249 post,
250 path = "/refresh",
251 tag = "insights",
252 security(("session_cookie" = [])),
253 request_body = RefreshInsightsRequest,
254 responses(
255 (status = 202, description = "Queued; the service writes its run ledger on its own", body = AcceptedResponse),
256 (status = 400, description = "`user_ids` names something that is not a user id, or the school's roster is larger than one refresh may carry", body = ErrorResponse),
257 (status = 401, description = "Not authenticated", body = ErrorResponse),
258 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
259 (status = 503, description = "No AI service offers `insight.refresh` right now; nothing was queued", body = ErrorResponse),
260 (status = 422, description = "The body does not fit this request: a field has the wrong type"),
261 ),
262)]
263async fn refresh(
264 State(st): State<AppState>,
265 tenant: ResolvedTenant,
266 RequireManager(user): RequireManager,
267 body: Option<Json<RefreshInsightsRequest>>,
268) -> Result<Response, AppError> {
269 let body = body.map(|Json(body)| body).unwrap_or_default();
270 let (roster, roster_source) = match normalized_ids(body.user_ids)? {
271 Some(ids) if !ids.is_empty() => (ids, ROSTER_SOURCE_EXPLICIT),
272 _ => (school_roster(&st.db).await?, ROSTER_SOURCE_SCHOOL),
273 };
274 let request = RefreshRequest {
275 requested_by: user.get_id().key(),
276 user_ids: Some(roster),
277 roster_source: roster_source.to_string(),
278 force: body.force,
279 };
280 let Some(bridge) = st.ai.clone() else {
281 return Ok(ai_unavailable(
282 "the AI service is not enabled on this deployment",
283 ));
284 };
285 if !bridge.has_capability(AI_INSIGHT_REFRESH_CAPABILITY) {
286 return Ok(ai_unavailable("no AI service is connected right now"));
287 }
288
289 let school = tenant.id;
290 tokio::spawn(async move {
291 let source = request.roster_source.clone();
292 match insight::refresh(&bridge, &school, &request).await {
293 Ok(answer) => tracing::info!(
294 "insight.refresh ({source} roster) answered: {} requested, {} computed, {} skipped, {} failed",
295 answer.requested.unwrap_or(0),
296 answer.computed.unwrap_or(0),
297 answer.skipped.unwrap_or(0),
298 answer.failed.len()
299 ),
300 Err(err) => tracing::warn!("insight.refresh failed: {err}"),
301 }
302 });
303
304 Ok(accepted())
305}
306
307fn accepted() -> Response {
308 (
309 StatusCode::ACCEPTED,
310 Json(AcceptedResponse {
311 status: "accepted".to_string(),
312 }),
313 )
314 .into_response()
315}
316
317// ---- the report doors ------------------------------------------------------
318
319/// The receipt for a stored report. `generated_at` is this backend's clock the
320/// moment the document was stored — the artifact's age is what a manager
321/// re-clicking the button wants to see.
322#[derive(Serialize, ToSchema)]
323struct ReportReceipt {
324 /// The run day the document is about, `YYYY-MM-DD`.
325 #[schema(example = "2026-09-17")]
326 run_day: String,
327 /// The stored document's size in bytes.
328 byte_size: u64,
329 /// Whether the service clipped the document. A clipped report must not
330 /// read as a complete one.
331 truncated: bool,
332 /// The service's own remarks about the document — e.g. that the run day
333 /// has no ledger row. Shown to the manager beside the artifact.
334 notes: Vec<String>,
335 /// When this backend stored the document, unix milliseconds.
336 generated_at: i64,
337}
338
339/// Where a school's generated report documents live under its blob directory:
340/// one file per run day. The day is validated before it is joined (see
341/// [`db::insight::run_day_ok`]), so the key can carry no separator and no
342/// `..`.
343const REPORT_DIR: &str = "zeka_report";
344
345fn report_key(run_day: &str) -> String {
346 format!("{REPORT_DIR}/{run_day}.html")
347}
348
349/// Render the school's report for one run day, and store it. Synchronous, and
350/// deliberately so: the manager clicked one button, and the document is what
351/// they asked for — there is no queue to poll and no partial state, and the
352/// receipt says what was stored.
353///
354/// Manager+ only: the document is whole-school, like the refresh sweep and the
355/// run ledger. The payload is read from this school's own `zeka_*` tables and
356/// dispatched to the service that declares `insight.report`; the service may
357/// not read a database, so every row the document needs travels in the
358/// request — the same serde rows the storage surface writes.
359///
360/// A run day with no ledger row, or one whose tables are empty, is still a
361/// legal request: the service renders what it was given and says so in
362/// `notes`. Refusals: `503` when no service offers the capability, or it did
363/// not answer — nothing was stored; `429` when every worker is at capacity;
364/// and the service's own typed refusals, mapped per class by
365/// [`report_refusal`].
366#[utoipa::path(
367 post,
368 path = "/runs/{run_day}/report",
369 tag = "insights",
370 security(("session_cookie" = [])),
371 params(("run_day" = String, Path, description = "The run day, `YYYY-MM-DD`")),
372 responses(
373 (status = 200, description = "The document was rendered and stored; the receipt says what was stored", body = ReportReceipt),
374 (status = 400, description = "`run_day` is not a `YYYY-MM-DD` day, or the AI service refused the composed request", body = ErrorResponse),
375 (status = 401, description = "Not authenticated", body = ErrorResponse),
376 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
377 (status = 409, description = "The AI service answered, refusing — `report_refused`, or `report_empty` when it has no rows to render; nothing was stored", body = ErrorResponse),
378 (status = 413, description = "The rendered document is over the AI service's size ceiling; nothing was stored", body = ErrorResponse),
379 (status = 429, description = "Every AI service offering `insight.report` is at capacity", body = ErrorResponse),
380 (status = 503, description = "No AI service offers `insight.report`, or it did not answer; nothing was stored", body = ErrorResponse),
381 ),
382)]
383async fn generate_report(
384 State(st): State<AppState>,
385 tenant: ResolvedTenant,
386 RequireManager(user): RequireManager,
387 Path(run_day): Path<String>,
388) -> Result<Response, AppError> {
389 if !db::insight::run_day_ok(&run_day) {
390 return Err(AppError::Validation(ValidationError::Invalid {
391 field: "run_day",
392 reason: "must be a `YYYY-MM-DD` day",
393 }));
394 }
395 let Some(bridge) = st.ai.clone() else {
396 return Ok(ai_unavailable(
397 "the AI service is not enabled on this deployment",
398 ));
399 };
400 if !bridge.has_capability(AI_INSIGHT_REPORT_CAPABILITY) {
401 return Ok(ai_unavailable("no AI service is connected right now"));
402 }
403 let Some(school) =
404 db::insight::school_identity(st.tenants.control(), &tenant.id).await?
405 else {
406 return Err(AppError::Internal(format!(
407 "the resolved school `{}` has no control row",
408 tenant.id.as_str()
409 )));
410 };
411 let request = ReportRequest {
412 kind: REPORT_KIND_SCHOOL.to_string(),
413 run_day: run_day.clone(),
414 requested_by: user.get_id().key(),
415 school,
416 classes: db::insight::all_classes(&st.db).await?,
417 summaries: db::insight::all_summaries(&st.db).await?,
418 recommendations: db::insight::all_recommendations(&st.db).await?,
419 profiles: db::insight::all_profiles(&st.db).await?,
420 runs: db::insight::runs_for_report(&st.db, &run_day).await?,
421 };
422 let answer = match insight::report(&bridge, &tenant.id, &request).await {
423 Ok(answer) => answer,
424 Err(AiError::Remote { code, message }) => {
425 tracing::warn!("insight.report refused: {code}: {message}");
426 return Err(report_refusal(code, message));
427 }
428 Err(AiError::Busy(_)) => {
429 return Err(AppError::TooManyRequests { retry_after_secs: 5 });
430 }
431 // No worker (the capability was withdrawn between the check and the
432 // dispatch), a timeout, a transport or protocol failure: the document
433 // cannot be produced now, and claiming otherwise would store nothing.
434 Err(err) => {
435 tracing::warn!("insight.report failed: {err}");
436 return Ok(ai_unavailable(
437 "the AI service did not answer; nothing was stored",
438 ));
439 }
440 };
441 // An empty document is not a document: storing it would serve a blank
442 // page as if it were the report, and a manager would read that as "the
443 // school has nothing to say". Refused, never persisted.
444 if answer.html.trim().is_empty() {
445 tracing::error!("insight.report answered with an empty document for {run_day}");
446 return Err(AppError::Internal(
447 "the AI service answered with an empty document".to_string(),
448 ));
449 }
450 store_report(&st.files_path, &run_day, &answer.html).await?;
451 Ok(Json(ReportReceipt {
452 run_day,
453 byte_size: answer.html.len() as u64,
454 truncated: answer.truncated,
455 notes: answer.notes,
456 generated_at: now_millis(),
457 })
458 .into_response())
459}
460
461/// The service's refusal vocabulary as this door's HTTP answer.
462///
463/// The report service closes four codes (`hezarfen_zeka`'s handler) and a
464/// client branches on the class each becomes:
465///
466/// * `bad_request` — the service judged the composed request bad (an unserved
467/// kind, a malformed day, a row field that is not a list, a school
468/// disagreement). The payload is composed here, so this is a backend defect
469/// and the caller can only be told the request was refused; the service's
470/// own words go to the log.
471/// * `insufficient_rows` — all four row lists were empty, so there is no
472/// document to build. `409 report_empty`: no retry conjures data, a sweep
473/// does.
474/// * `document_too_large` — over the service's own HTML ceiling, which it
475/// never truncates past. `413`.
476/// * `internal` — the render failed on the service's side. `500`.
477///
478/// Anything else is `409 report_refused` with the service's code and message
479/// kept verbatim: a service may define codes this backend has never heard of,
480/// and swallowing them would hide the one explanation a caller needs.
481fn report_refusal(code: String, message: String) -> AppError {
482 match code.as_str() {
483 "bad_request" => AppError::Validation(ValidationError::Invalid {
484 field: "report",
485 reason: "the AI service refused the composed request; the reason is in the backend log",
486 }),
487 "insufficient_rows" => AppError::ConflictCoded {
488 code: "report_empty",
489 message: format!(
490 "the AI service has no rows to render a report from: {message}"
491 ),
492 },
493 "document_too_large" => AppError::PayloadTooLarge(format!(
494 "the rendered report is over the AI service's size ceiling, and it does not truncate: {message}"
495 )),
496 "internal" => AppError::Internal(format!(
497 "the AI service failed to render the report: {message}"
498 )),
499 _ => AppError::ConflictCoded {
500 code: "report_refused",
501 message: format!("the AI service refused the report: {code}: {message}"),
502 },
503 }
504}
505
506/// The stored report document, streamed.
507///
508/// `409 report_missing` when nothing has been generated for the day — a
509/// refusal that covers a day the ledger has never heard of too: generation
510/// accepts such a day on purpose (the document's `notes` say it), so a `404`
511/// here could refuse a day the POST door had just answered `200` for.
512#[utoipa::path(
513 get,
514 path = "/runs/{run_day}/report",
515 tag = "insights",
516 security(("session_cookie" = [])),
517 params(("run_day" = String, Path, description = "The run day, `YYYY-MM-DD`")),
518 responses(
519 (status = 200, description = "The stored document", content_type = "text/html"),
520 (status = 400, description = "`run_day` is not a `YYYY-MM-DD` day", body = ErrorResponse),
521 (status = 401, description = "Not authenticated", body = ErrorResponse),
522 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
523 (status = 409, description = "No report has been generated for this day (`report_missing`)", body = ErrorResponse),
524 ),
525)]
526async fn serve_report(
527 State(st): State<AppState>,
528 RequireManager(_user): RequireManager,
529 Path(run_day): Path<String>,
530) -> Result<Response, AppError> {
531 if !db::insight::run_day_ok(&run_day) {
532 return Err(AppError::Validation(ValidationError::Invalid {
533 field: "run_day",
534 reason: "must be a `YYYY-MM-DD` day",
535 }));
536 }
537 let key = report_key(&run_day);
538 let path = crate::web::blob_path(&st.files_path, &key);
539 let file = tokio::fs::File::open(&path).await.map_err(|err| {
540 if err.kind() != std::io::ErrorKind::NotFound {
541 tracing::error!("could not open the stored report {key}: {err}");
542 }
543 AppError::ConflictCoded {
544 code: "report_missing",
545 message: format!("no report has been generated for `{run_day}` yet"),
546 }
547 })?;
548 Ok((
549 [
550 (
551 CONTENT_TYPE,
552 HeaderValue::from_static("text/html; charset=utf-8"),
553 ),
554 (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")),
555 (CACHE_CONTROL, HeaderValue::from_static("private, no-store")),
556 ],
557 Body::from_stream(pump(file)),
558 )
559 .into_response())
560}
561
562/// Store the rendered document under the school's own blob directory.
563///
564/// Written to a temp name and renamed into place: the artifact appears
565/// atomically or not at all, so a reader — or a second POST racing this one —
566/// can never open a half-written document. The temp file is removed if
567/// anything fails before the rename.
568async fn store_report(
569 files_path: &std::path::Path,
570 run_day: &str,
571 html: &str,
572) -> Result<(), AppError> {
573 crate::web::ensure_files_dir(files_path).await?;
574 let dir = crate::web::blob_path(files_path, REPORT_DIR);
575 tokio::fs::create_dir_all(&dir).await.map_err(|err| {
576 AppError::Internal(format!("failed to create the report directory: {err}"))
577 })?;
578 let temp = dir.join(format!(
579 ".report-{}.tmp",
580 crate::domain::monotonic_id::next_uuid()
581 ));
582 if let Err(err) = tokio::fs::write(&temp, html.as_bytes()).await {
583 let _ = tokio::fs::remove_file(&temp).await;
584 return Err(AppError::Internal(format!(
585 "failed to write the report document: {err}"
586 )));
587 }
588 let path = crate::web::blob_path(files_path, &report_key(run_day));
589 if let Err(err) = tokio::fs::rename(&temp, &path).await {
590 let _ = tokio::fs::remove_file(&temp).await;
591 return Err(AppError::Internal(format!(
592 "failed to store the report document: {err}"
593 )));
594 }
595 Ok(())
596}
597
598// ---- the storage doors -----------------------------------------------------
599//
600// ZEKA's own tables are written and read by the backend, never by the service
601// (`crate::db::insight` holds the statements, `src/ai/insight.rs` the bridge
602// contract). These are the same nine operations over HTTP — one service
603// function, two surfaces — so a deployment's tooling can seed, inspect and
604// maintain what the service computed without holding a bridge connection.
605//
606// Manager+ on all of them: every one reads or writes rows about students
607// school-wide, which is the same floor `GET /insights/runs` and the refresh
608// door carry. The school is the caller's own, resolved by the nest's own
609// extractors; no door here takes a school, a database or a query in its body.
610
611/// Store a batch of ZEKA's student summaries (and their attention items).
612///
613/// This is what the AI service calls over the bridge as
614/// `insight.summary.upsert`. One call is one batch and one transaction: the
615/// batch lands whole or not at all, so a caller that retries cannot
616/// half-apply it. Each student's attention items are **replaced**, never
617/// merged — a fact the service stopped producing must not stay on screen.
618/// At most [`MAX_INSIGHT_BATCH_ROWS`](crate::constant::MAX_INSIGHT_BATCH_ROWS)
619/// rows per call.
620#[utoipa::path(
621 post,
622 path = "/summaries",
623 tag = "insights",
624 security(("session_cookie" = [])),
625 request_body = SummaryWriteRequest,
626 responses(
627 (status = 200, description = "The rows were written", body = WriteReceipt),
628 (status = 400, description = "The payload does not fit the operation: a field is malformed, or a referenced row is not in this school", body = ErrorResponse),
629 (status = 401, description = "Not authenticated", body = ErrorResponse),
630 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
631 (status = 413, description = "More rows than one call may carry", body = ErrorResponse),
632 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
633 ),
634)]
635async fn write_summaries(
636 State(st): State<AppState>,
637 RequireManager(_user): RequireManager,
638 Json(body): Json<SummaryWriteRequest>,
639) -> Result<Json<WriteReceipt>, AppError> {
640 Ok(Json(db::insight::write_summaries(&st.db, body.rows).await?))
641}
642
643/// Store a batch of ZEKA's recommendation cards.
644///
645/// The bridge capability is `insight.recommendation.upsert`. The backend
646/// mints each row's id. A row whose evidence carries nothing but a
647/// `limitation` is **not written** and is counted `rejected` in the receipt —
648/// the service's own rule, applied where the write happens instead of being
649/// trusted to the writer.
650#[utoipa::path(
651 post,
652 path = "/recommendations",
653 tag = "insights",
654 security(("session_cookie" = [])),
655 request_body = RecommendationWriteRequest,
656 responses(
657 (status = 200, description = "The rows were written; `rejected` counts the cards the evidence rule kept out", body = WriteReceipt),
658 (status = 400, description = "The payload does not fit the operation: a field is malformed, or a referenced row is not in this school", body = ErrorResponse),
659 (status = 401, description = "Not authenticated", body = ErrorResponse),
660 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
661 (status = 413, description = "More rows than one call may carry", body = ErrorResponse),
662 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
663 ),
664)]
665async fn write_recommendations(
666 State(st): State<AppState>,
667 RequireManager(_user): RequireManager,
668 Json(body): Json<RecommendationWriteRequest>,
669) -> Result<Json<WriteReceipt>, AppError> {
670 Ok(Json(
671 db::insight::write_recommendations(&st.db, body.rows).await?,
672 ))
673}
674
675/// Store a batch of ZEKA's question-segment labels (and each question's
676/// dimension split).
677///
678/// The bridge capability is `insight.segment.upsert`; the dimension rows are
679/// replaced with the payload, like the attention items above.
680#[utoipa::path(
681 post,
682 path = "/segments",
683 tag = "insights",
684 security(("session_cookie" = [])),
685 request_body = SegmentWriteRequest,
686 responses(
687 (status = 200, description = "The rows were written", body = WriteReceipt),
688 (status = 400, description = "The payload does not fit the operation: a field is malformed, or a referenced row is not in this school", body = ErrorResponse),
689 (status = 401, description = "Not authenticated", body = ErrorResponse),
690 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
691 (status = 413, description = "More rows than one call may carry", body = ErrorResponse),
692 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
693 ),
694)]
695async fn write_segments(
696 State(st): State<AppState>,
697 RequireManager(_user): RequireManager,
698 Json(body): Json<SegmentWriteRequest>,
699) -> Result<Json<WriteReceipt>, AppError> {
700 Ok(Json(db::insight::write_segments(&st.db, body.rows).await?))
701}
702
703/// Store a batch of ZEKA's student segment profiles.
704///
705/// The bridge capability is `insight.profile.upsert`. `contrast` is the field
706/// the service's rules fire on — the raw `accuracy` mostly measures a
707/// student's general level and is stored for the evidence panel only.
708#[utoipa::path(
709 post,
710 path = "/profiles",
711 tag = "insights",
712 security(("session_cookie" = [])),
713 request_body = ProfileWriteRequest,
714 responses(
715 (status = 200, description = "The rows were written", body = WriteReceipt),
716 (status = 400, description = "The payload does not fit the operation: a field is malformed, or a referenced row is not in this school", body = ErrorResponse),
717 (status = 401, description = "Not authenticated", body = ErrorResponse),
718 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
719 (status = 413, description = "More rows than one call may carry", body = ErrorResponse),
720 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
721 ),
722)]
723async fn write_profiles(
724 State(st): State<AppState>,
725 RequireManager(_user): RequireManager,
726 Json(body): Json<ProfileWriteRequest>,
727) -> Result<Json<WriteReceipt>, AppError> {
728 Ok(Json(db::insight::write_profiles(&st.db, body.rows).await?))
729}
730
731/// Store one compute run's ledger row (with its pending students and failed
732/// modules, both replaced).
733///
734/// The bridge capability is `insight.run.upsert`; the run is keyed by
735/// `run_day` (`YYYY-MM-DD`), so a re-run of the same night overwrites rather
736/// than duplicating. `GET /insights/runs` reads the ledger back.
737#[utoipa::path(
738 post,
739 path = "/runs",
740 tag = "insights",
741 security(("session_cookie" = [])),
742 request_body = RunWriteRequest,
743 responses(
744 (status = 200, description = "The run's ledger row was written", body = WriteReceipt),
745 (status = 400, description = "The payload does not fit the operation: `run_day` is not `YYYY-MM-DD`, or a referenced row is not in this school", body = ErrorResponse),
746 (status = 401, description = "Not authenticated", body = ErrorResponse),
747 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
748 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
749 ),
750)]
751async fn write_run(
752 State(st): State<AppState>,
753 RequireManager(_user): RequireManager,
754 Json(body): Json<RunWriteRequest>,
755) -> Result<Json<WriteReceipt>, AppError> {
756 Ok(Json(db::insight::write_run(&st.db, body.run).await?))
757}
758
759/// The students the freshest compute run left pending — where the next run
760/// starts.
761///
762/// Manager+ only, like `GET /insights/runs`: `pending_students` is a list of
763/// people, and this is the same list unpaged. The bridge capability is
764/// `insight.pending.list`; the list is answered whole or refused past
765/// [`MAX_INSIGHT_PENDING_STUDENTS`](crate::constant::MAX_INSIGHT_PENDING_STUDENTS),
766/// never clipped, because the service resumes its next run from it.
767#[utoipa::path(
768 get,
769 path = "/pending",
770 tag = "insights",
771 security(("session_cookie" = [])),
772 responses(
773 (status = 200, description = "The freshest run's pending students, in the run's own order", body = PendingList),
774 (status = 401, description = "Not authenticated", body = ErrorResponse),
775 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
776 (status = 413, description = "More pending students than one answer may carry", body = ErrorResponse),
777 ),
778)]
779async fn pending_students(
780 State(st): State<AppState>,
781 RequireManager(_user): RequireManager,
782) -> Result<Json<PendingList>, AppError> {
783 Ok(Json(db::insight::last_pending(&st.db).await?))
784}
785
786/// Delete every `zeka_*` row whose retention window has closed.
787///
788/// The bridge capability is `insight.retention.sweep`. Children go before
789/// their parents (the foreign keys are `ON DELETE NO ACTION`), the backend's
790/// own clock decides expiry, and each table answers its own verdict — a table
791/// that could not be swept is reported `false` while the rest proceed, since
792/// housekeeping must not lose a whole run over one locked table.
793#[utoipa::path(
794 post,
795 path = "/sweep",
796 tag = "insights",
797 security(("session_cookie" = [])),
798 responses(
799 (status = 200, description = "One verdict per table: whether its expired rows were deleted", body = TableVerdicts),
800 (status = 401, description = "Not authenticated", body = ErrorResponse),
801 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
802 ),
803)]
804async fn sweep_retention(
805 State(st): State<AppState>,
806 RequireManager(_user): RequireManager,
807) -> Result<Json<TableVerdicts>, AppError> {
808 let now_ms = crate::domain::timestamp::Timestamp::now().as_millis();
809 Ok(Json(db::insight::sweep(&st.db, now_ms).await?))
810}
811
812/// Delete the derived rows of every student who is no longer on the roster.
813///
814/// The bridge capability is `insight.departed.purge`; `students` is the
815/// **active** roster, and every student not named loses their summaries,
816/// profiles, attention items, cards about them, and pending-run entries. One
817/// transaction, so the verdicts move together. An empty list is refused: an
818/// empty roster is a fetch that failed, and obeying it would delete the whole
819/// school's derived data.
820#[utoipa::path(
821 post,
822 path = "/purge",
823 tag = "insights",
824 security(("session_cookie" = [])),
825 request_body = PurgeRequest,
826 responses(
827 (status = 200, description = "One verdict per table: whether the departed students' rows were deleted", body = TableVerdicts),
828 (status = 400, description = "The payload does not fit the operation: the roster is empty", body = ErrorResponse),
829 (status = 401, description = "Not authenticated", body = ErrorResponse),
830 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
831 (status = 413, description = "More students than one call may name", body = ErrorResponse),
832 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
833 ),
834)]
835async fn purge_departed(
836 State(st): State<AppState>,
837 RequireManager(_user): RequireManager,
838 Json(body): Json<PurgeRequest>,
839) -> Result<Json<TableVerdicts>, AppError> {
840 Ok(Json(
841 db::insight::purge_departed(&st.db, body.students).await?,
842 ))
843}
844
845/// The deployment's active schools, by school — the directory a shared AI fleet
846/// schedules over.
847///
848/// This is the one operation of the family that is not school-scoped, and the
849/// one door of this nest that is not a school's: it names every customer, so
850/// it runs on the **builder** principal (the deployment operator), mounted
851/// outside the school gate exactly like the vendor surface's `GET /schools`.
852/// A school session gets `401` here. The bridge capability is
853/// `insight.schools.list`, which is the service's own deployment-scoped call:
854/// the same function, two surfaces, and a school-scoped caller on neither.
855#[utoipa::path(
856 get,
857 path = "/insights/schools",
858 tag = "insights",
859 security(("session_cookie" = [])),
860 responses(
861 (status = 200, description = "Every active school on this deployment, by school", body = SchoolDirectory),
862 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
863 ),
864)]
865async fn active_schools(
866 axum::extract::State(st): axum::extract::State<AppState>,
867 RequireBuilder(_builder): RequireBuilder,
868) -> Result<Json<SchoolDirectory>, AppError> {
869 Ok(Json(db::insight::active_schools(st.tenants.control()).await?))
870}
871
872/// Canonicalize the ids a refresh body names — through the same parser every
873/// route uses for a wire id, so a client cannot hand the service a spelling
874/// this backend itself would never produce. Anything that parses as no uuid
875/// is a `400`: unlike a path segment (where garbage reads as the nil id and
876/// matches no row), a batch naming students is a list this backend must not
877/// forward half-understood.
878fn normalized_ids(ids: Option<Vec<String>>) -> Result<Option<Vec<String>>, AppError> {
879 ids.map(|ids| {
880 ids.into_iter()
881 .map(|id| {
882 let parsed = UserId::from_key(&id);
883 if parsed.uuid().is_nil() {
884 Err(AppError::Validation(ValidationError::Invalid {
885 field: "user_ids",
886 reason: "must be user ids",
887 }))
888 } else {
889 Ok(parsed.key())
890 }
891 })
892 .collect::<Result<Vec<String>, AppError>>()
893 })
894 .transpose()
895}
896
897/// The school's own student roster, as the refresh door fills an empty request
898/// body with.
899///
900/// The same set the office's student table lists: every `app_user` holding the
901/// `student` role exactly, newest first ([`db::user::list_by_role`]). It is
902/// what the service cannot assemble itself — its own roster discovery reads
903/// homework `assigned` lists, which a live school rarely fills — so an empty
904/// body must name the school here or the sweep computes nobody.
905///
906/// Refused, never clipped, past
907/// [`MAX_INSIGHT_REFRESH_STUDENTS`](crate::constant::MAX_INSIGHT_REFRESH_STUDENTS):
908/// a clipped roster would leave students unanalysed while the run read as
909/// complete. A school with no students answers an empty list — a sweep that
910/// computed nobody is a true answer, not a failure.
911async fn school_roster(db: &Database) -> Result<Vec<String>, AppError> {
912 let students = db::user::list_by_role(db, Role::Student).await?;
913 if students.len() > MAX_INSIGHT_REFRESH_STUDENTS {
914 return Err(AppError::Validation(ValidationError::Invalid {
915 field: "user_ids",
916 reason: "the school's roster is larger than one refresh may carry; \
917 name the students to recompute explicitly",
918 }));
919 }
920 Ok(students.iter().map(|user| user.get_id().key()).collect())
921}
922
923// ---- the reads -------------------------------------------------------------
924
925/// One student's nightly summary. The four module objects are ZEKA's own
926/// shapes (JSONB, by design): read a member by name, never by position. `null`
927/// for a module the run could not compute — an empty object and a missing
928/// module are different claims, and only one of them is true.
929#[derive(Serialize, ToSchema)]
930struct SummaryResponse {
931 marks: Option<JsonValue>,
932 attendance: Option<JsonValue>,
933 submission: Option<JsonValue>,
934 study: Option<JsonValue>,
935 /// The weakest input's tier: `none` | `exploratory` | `stable`.
936 #[schema(example = "stable")]
937 confidence: String,
938 /// UTC unix milliseconds the summary was computed at — the stamp a
939 /// client polls for after asking for a recompute.
940 computed_at: i64,
941 /// UTC unix milliseconds after which the sweep deletes the row.
942 retain_until: i64,
943}
944
945/// One entry of the attention list — a statement of fact about a window, not
946/// a judgement. **Teacher-facing**: it is never returned to the student it is
947/// about (see the module docs).
948#[derive(Serialize, ToSchema)]
949struct AttentionItemResponse {
950 /// Which trigger fired: `attendance` | `homework` | `mark_trend` today —
951 /// a fourth trigger is a rule change, so treat this as an open set.
952 #[schema(example = "attendance")]
953 trigger: String,
954 /// The course the trigger is about, when it has one; `null` = school-wide.
955 course: Option<String>,
956 /// The sentence the teacher reads, written once at compute time.
957 fact: String,
958 /// UTC unix milliseconds — the window the fact is about.
959 window_from: i64,
960 window_to: i64,
961 /// The numbers behind the fact, for the "neden?" panel. Never empty.
962 evidence: JsonValue,
963}
964
965/// One recommendation card addressed to the caller. It carries no
966/// `dismissed_at`/`dismiss_by`: a dismissed card is filtered out of both card
967/// reads, so the field could only ever be null — and a face that never
968/// arrives is worse than no face.
969#[derive(Serialize, ToSchema)]
970struct RecommendationResponse {
971 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
972 id: String,
973 /// The product family: `O1` … `O4` for students, `T3`/`T4` for teachers.
974 #[schema(example = "T4")]
975 product: String,
976 /// Which rule produced it, and which version of that rule.
977 #[schema(example = "T4.attendance")]
978 rule_id: String,
979 rule_version: i64,
980 /// The rule's optional scope segment; `null` when the rule has none.
981 scope: Option<String>,
982 /// Who the card is about; `null` on a card addressed to its subject
983 /// (a student's own card), and never returned to a student caller.
984 about: Option<String>,
985 /// The role gate the card was written for: `student` | `teacher` |
986 /// `parent` | `manager`.
987 audience_role: String,
988 course: Option<String>,
989 /// The numbers behind the card, including the mandatory `limitation`
990 /// line. Never empty.
991 evidence: JsonValue,
992 confidence: String,
993 created_at: i64,
994 /// After this instant the card is past; expired rows are filtered out of
995 /// both reads.
996 expires_at: i64,
997}
998
999/// One student × dimension × label row. `accuracy` is returned alongside
1000/// `contrast` and never alone: raw accuracy carries general ability, and
1001/// `contrast = accuracy − overall_accuracy` is the part specific to the
1002/// segment.
1003#[derive(Serialize, ToSchema)]
1004struct SegmentProfileResponse {
1005 /// A production dimension: `bilissel_talep` | `dikkat_tuzagi` |
1006 /// `okuma_yuku` (the experimental `adim_sayisi` never reaches a student).
1007 #[schema(example = "bilissel_talep")]
1008 dimension: String,
1009 #[schema(example = "analiz")]
1010 label: String,
1011 n_answers: i64,
1012 n_correct: i64,
1013 /// The segment's hit rate, `n_correct / n_answers`.
1014 accuracy: f64,
1015 /// The student's hit rate across all labelled items — the subtrahend, on
1016 /// the row so the evidence panel can show the comparison.
1017 overall_n_answers: i64,
1018 overall_accuracy: f64,
1019 /// The honest measure: `accuracy − overall_accuracy`. Negative = behind
1020 /// the student's own general level in this segment.
1021 contrast: f64,
1022 confidence: String,
1023 computed_at: i64,
1024}
1025
1026/// One student's whole readable insight: the stored summary, the caller's own
1027/// cards about them, and the segment profile.
1028#[derive(Serialize, ToSchema)]
1029struct StudentInsightResponse {
1030 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
1031 user_id: String,
1032 /// `null` until ZEKA has computed this student at least once.
1033 summary: Option<SummaryResponse>,
1034 /// Teacher-facing; always empty for the subject's own view and for a
1035 /// linked parent.
1036 attention: Vec<AttentionItemResponse>,
1037 /// Cards addressed to the caller about this student — nobody else's cards
1038 /// appear here, so two teachers reading one student each see their own.
1039 cards: Vec<RecommendationResponse>,
1040 segments: Vec<SegmentProfileResponse>,
1041}
1042
1043/// The caller's own insight. Students get their summary, their own cards and
1044/// their segment profile — **never** the attention list about themselves.
1045/// Any other role gets the cards addressed to them (a teacher's `T4` cards
1046/// about their students), with `summary`/`segments` empty.
1047#[utoipa::path(
1048 get,
1049 path = "/me",
1050 tag = "insights",
1051 security(("session_cookie" = [])),
1052 responses(
1053 (status = 200, description = "The caller's own insight", body = StudentInsightResponse),
1054 (status = 401, description = "Not authenticated", body = ErrorResponse),
1055 ),
1056)]
1057async fn my_insight(
1058 State(st): State<AppState>,
1059 CurrentUser(user): CurrentUser,
1060) -> Result<Json<StudentInsightResponse>, AppError> {
1061 let id = user.get_id();
1062 let student = user.get_role() == Role::Student;
1063 Ok(Json(StudentInsightResponse {
1064 user_id: id.key(),
1065 summary: if student {
1066 summary_of(&st.db, id).await?
1067 } else {
1068 None
1069 },
1070 attention: Vec::new(),
1071 cards: cards_of(&st.db, id, user.get_role(), None).await?,
1072 segments: if student {
1073 segments_of(&st.db, id).await?
1074 } else {
1075 Vec::new()
1076 },
1077 }))
1078}
1079
1080/// One student's insight, as an observer reads it. Teacher+ (narrowed to the
1081/// students they reach) or a parent holding a live link to that student;
1082/// everyone else — other students included — gets the same `404` a missing id
1083/// gets.
1084#[utoipa::path(
1085 get,
1086 path = "/students/{user}",
1087 tag = "insights",
1088 security(("session_cookie" = [])),
1089 params(("user" = String, Path, description = "User id")),
1090 responses(
1091 (status = 200, description = "The student's insight, plus the caller's own cards about them", body = StudentInsightResponse),
1092 (status = 401, description = "Not authenticated", body = ErrorResponse),
1093 (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse),
1094 (status = 404, description = "Not found — no such student, or not one the caller may read", body = ErrorResponse),
1095 ),
1096)]
1097async fn student_insight(
1098 State(st): State<AppState>,
1099 CurrentUser(user): CurrentUser,
1100 Path(id): Path<String>,
1101) -> Result<Json<StudentInsightResponse>, AppError> {
1102 let target = UserId::from_key(&id);
1103 ensure_can_read(&user, &target, &st.db).await?;
1104 let staff = user.get_role().at_least(Role::Teacher);
1105 Ok(Json(StudentInsightResponse {
1106 user_id: target.key(),
1107 summary: summary_of(&st.db, &target).await?,
1108 attention: if staff {
1109 attention_of(&st.db, &target).await?
1110 } else {
1111 Vec::new()
1112 },
1113 cards: cards_of(&st.db, user.get_id(), user.get_role(), Some(&target)).await?,
1114 segments: segments_of(&st.db, &target).await?,
1115 }))
1116}
1117
1118/// One compute run, as the ledger keeps it.
1119#[derive(Serialize, ToSchema)]
1120struct InsightRunResponse {
1121 /// The run's key: `YYYY-MM-DD`, so a re-run of the same night overwrites
1122 /// rather than duplicating.
1123 #[schema(example = "2026-09-17")]
1124 run_day: String,
1125 started_at: i64,
1126 finished_at: Option<i64>,
1127 /// `running` | `ok` | `partial` | `failed` | `skipped`. A `partial` run
1128 /// must be shown as such: some students were not processed.
1129 #[schema(example = "partial")]
1130 status: String,
1131 duration_ms: Option<i64>,
1132 students_total: i64,
1133 students_ok: i64,
1134 students_failed: i64,
1135 students_skipped: i64,
1136 rows_written: i64,
1137 /// Whether the run hit its time budget before finishing.
1138 budget_exceeded: bool,
1139 budget_ms: i64,
1140 /// The students the budget ran out on; the next run starts here. Kept for
1141 /// the management view, which is the only caller of this route.
1142 pending_students: Vec<String>,
1143 /// Modules that failed, one per row — so a section can be marked missing
1144 /// instead of shown as a hole.
1145 failed_modules: Vec<String>,
1146}
1147
1148/// The run ledger, newest first. Manager+ only: `pending_students` is a list
1149/// of people, and ZEKA's output contract confines it to the management view.
1150/// Paged via `?limit=&offset=`.
1151#[utoipa::path(
1152 get,
1153 path = "/runs",
1154 tag = "insights",
1155 security(("session_cookie" = [])),
1156 params(PageParams),
1157 responses(
1158 (status = 200, description = "The school's compute runs, newest first", body = Page<InsightRunResponse>),
1159 (status = 400, description = "`limit` or `offset` out of range", body = ErrorResponse),
1160 (status = 401, description = "Not authenticated", body = ErrorResponse),
1161 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
1162 ),
1163)]
1164async fn list_runs(
1165 State(st): State<AppState>,
1166 RequireManager(_user): RequireManager,
1167 Query(page): Query<PageParams>,
1168) -> Result<Json<Page<InsightRunResponse>>, AppError> {
1169 let (limit, offset) = page.resolve()?;
1170 let rows = sqlx::query!(
1171 r#"SELECT run_day, started_at, finished_at, status, duration_ms,
1172 students_total, students_ok, students_failed, students_skipped,
1173 rows_written, budget_exceeded, budget_ms
1174 FROM zeka_run
1175 ORDER BY started_at DESC, run_day DESC"#
1176 )
1177 .fetch_all(&st.db)
1178 .await?;
1179 let total = rows.len() as i64;
1180 let window = paginate(&rows, limit, offset);
1181 let days: Vec<String> = window.iter().map(|row| row.run_day.clone()).collect();
1182 let mut pending = children_of(&st.db, "pending", &days).await?;
1183 let mut failed = children_of(&st.db, "failed", &days).await?;
1184 let items = window
1185 .iter()
1186 .map(|row| InsightRunResponse {
1187 run_day: row.run_day.clone(),
1188 started_at: row.started_at,
1189 finished_at: row.finished_at,
1190 status: row.status.clone(),
1191 duration_ms: row.duration_ms,
1192 students_total: row.students_total,
1193 students_ok: row.students_ok,
1194 students_failed: row.students_failed,
1195 students_skipped: row.students_skipped,
1196 rows_written: row.rows_written,
1197 budget_exceeded: row.budget_exceeded,
1198 budget_ms: row.budget_ms,
1199 pending_students: pending.remove(&row.run_day).unwrap_or_default(),
1200 failed_modules: failed.remove(&row.run_day).unwrap_or_default(),
1201 })
1202 .collect();
1203 Ok(Json(Page::new(items, total, limit, offset)))
1204}
1205
1206/// The children of the runs on this page — one query for the whole page, not
1207/// one per run, grouped by run day in `ord` order.
1208async fn children_of(
1209 db: &Database,
1210 kind: &str,
1211 days: &[String],
1212) -> Result<std::collections::HashMap<String, Vec<String>>, AppError> {
1213 if days.is_empty() {
1214 return Ok(std::collections::HashMap::new());
1215 }
1216 let mut grouped: std::collections::HashMap<String, Vec<String>> =
1217 std::collections::HashMap::new();
1218 match kind {
1219 "pending" => {
1220 for row in sqlx::query!(
1221 r#"SELECT run, student FROM zeka_run_pending
1222 WHERE run = ANY($1) ORDER BY run, ord"#,
1223 days
1224 )
1225 .fetch_all(db)
1226 .await?
1227 {
1228 grouped
1229 .entry(row.run)
1230 .or_default()
1231 .push(row.student.to_string());
1232 }
1233 }
1234 "failed" => {
1235 for row in sqlx::query!(
1236 r#"SELECT run, module FROM zeka_run_failed_module
1237 WHERE run = ANY($1) ORDER BY run, ord"#,
1238 days
1239 )
1240 .fetch_all(db)
1241 .await?
1242 {
1243 grouped.entry(row.run).or_default().push(row.module);
1244 }
1245 }
1246 other => unreachable!("unknown run child table: {other}"),
1247 }
1248 Ok(grouped)
1249}
1250
1251// ---- the queries -----------------------------------------------------------
1252
1253/// The nightly summary, or `None` until ZEKA has computed this student once.
1254async fn summary_of(db: &Database, student: &UserId) -> Result<Option<SummaryResponse>, AppError> {
1255 let row = sqlx::query!(
1256 r#"SELECT marks AS "marks?: SqlJson<JsonValue>",
1257 attendance AS "attendance?: SqlJson<JsonValue>",
1258 submission AS "submission?: SqlJson<JsonValue>",
1259 study AS "study?: SqlJson<JsonValue>",
1260 confidence, computed_at, retain_until
1261 FROM zeka_student_summary WHERE student = $1"#,
1262 student.uuid(),
1263 )
1264 .fetch_optional(db)
1265 .await?;
1266 Ok(row.map(|row| SummaryResponse {
1267 marks: row.marks.map(|json| json.0),
1268 attendance: row.attendance.map(|json| json.0),
1269 submission: row.submission.map(|json| json.0),
1270 study: row.study.map(|json| json.0),
1271 confidence: row.confidence,
1272 computed_at: row.computed_at,
1273 retain_until: row.retain_until,
1274 }))
1275}
1276
1277/// The attention list, in the writer's own order. Only staff at `teacher` or
1278/// above ever call this — see the module docs.
1279async fn attention_of(
1280 db: &Database,
1281 student: &UserId,
1282) -> Result<Vec<AttentionItemResponse>, AppError> {
1283 let rows = sqlx::query!(
1284 r#"SELECT trigger, course AS "course?: CourseId",
1285 fact, window_from, window_to,
1286 evidence AS "evidence: SqlJson<JsonValue>"
1287 FROM zeka_attention_item WHERE student = $1 ORDER BY ord"#,
1288 student.uuid(),
1289 )
1290 .fetch_all(db)
1291 .await?;
1292 Ok(rows
1293 .into_iter()
1294 .map(|row| AttentionItemResponse {
1295 trigger: row.trigger,
1296 course: row.course.map(|course| course.key().to_string()),
1297 fact: row.fact,
1298 window_from: row.window_from,
1299 window_to: row.window_to,
1300 evidence: row.evidence.0,
1301 })
1302 .collect())
1303}
1304
1305/// Cards addressed to `audience`, filtered to the label the caller's own role
1306/// reads (`audience_role`) and to cards that are still live: not expired, not
1307/// dismissed. `about` narrows to one student — `None` is the caller's own
1308/// card list, which for a teacher is the `T4` cards about their students.
1309async fn cards_of(
1310 db: &Database,
1311 audience: &UserId,
1312 role: Role,
1313 about: Option<&UserId>,
1314) -> Result<Vec<RecommendationResponse>, AppError> {
1315 let rows = sqlx::query!(
1316 r#"SELECT id, product, rule_id, rule_version, scope,
1317 about AS "about?: UserId",
1318 audience_role, course AS "course?: CourseId",
1319 evidence AS "evidence: SqlJson<JsonValue>",
1320 confidence, created_at, expires_at
1321 FROM zeka_recommendation
1322 WHERE audience = $1 AND audience_role = $2
1323 AND ($3::uuid IS NULL OR about = $3)
1324 AND expires_at > $4 AND dismissed_at IS NULL
1325 ORDER BY created_at DESC, id"#,
1326 audience.uuid(),
1327 audience_role(role),
1328 about.map(UserId::uuid),
1329 now_millis(),
1330 )
1331 .fetch_all(db)
1332 .await?;
1333 Ok(rows
1334 .into_iter()
1335 .map(|row| RecommendationResponse {
1336 id: row.id.to_string(),
1337 product: row.product,
1338 rule_id: row.rule_id,
1339 rule_version: row.rule_version,
1340 scope: row.scope,
1341 // A student's own card has no `about` in the database, and the
1342 // contract forbids one reaching a student caller even if a rule
1343 // ever set it — so the value is dropped for a student caller, not
1344 // merely absent.
1345 about: (role != Role::Student)
1346 .then_some(row.about)
1347 .flatten()
1348 .map(|about| about.key().to_string()),
1349 audience_role: row.audience_role,
1350 course: row.course.map(|course| course.key().to_string()),
1351 evidence: row.evidence.0,
1352 confidence: row.confidence,
1353 created_at: row.created_at,
1354 expires_at: row.expires_at,
1355 })
1356 .collect())
1357}
1358
1359/// The segment profile, noise filtered out: a row below 30 answers
1360/// (`confidence = 'none'`) stays in the database and off every screen.
1361async fn segments_of(
1362 db: &Database,
1363 student: &UserId,
1364) -> Result<Vec<SegmentProfileResponse>, AppError> {
1365 let rows = sqlx::query!(
1366 r#"SELECT dimension, label, n_answers, n_correct, accuracy,
1367 overall_n_answers, overall_accuracy, contrast, confidence,
1368 computed_at
1369 FROM zeka_student_segment_profile
1370 WHERE student = $1 AND confidence <> 'none'
1371 ORDER BY dimension, label"#,
1372 student.uuid(),
1373 )
1374 .fetch_all(db)
1375 .await?;
1376 Ok(rows
1377 .into_iter()
1378 .map(|row| SegmentProfileResponse {
1379 dimension: row.dimension,
1380 label: row.label,
1381 n_answers: row.n_answers,
1382 n_correct: row.n_correct,
1383 accuracy: row.accuracy,
1384 overall_n_answers: row.overall_n_answers,
1385 overall_accuracy: row.overall_accuracy,
1386 contrast: row.contrast,
1387 confidence: row.confidence,
1388 computed_at: row.computed_at,
1389 })
1390 .collect())
1391}
1392
1393// ---- authorization ---------------------------------------------------------
1394
1395/// The one gate every per-student insight route shares, read and compute
1396/// alike.
1397///
1398/// [`ensure_can_observe`] settles the role question — teacher+ clears it, a
1399/// parent needs a live link — and the student a caller may *reach* is then
1400/// narrowed the same way `/marks/{user}` narrows a report: a teacher reads a
1401/// student only when they run an instance that student sits in. The narrowing
1402/// is a `404` rather than an empty body because the insight rows are not
1403/// per-instance: there is nothing honest to narrow *to*, and a foreign
1404/// student's id must be indistinguishable from a missing one.
1405async fn ensure_can_read(caller: &User, target: &UserId, db: &Database) -> Result<(), AppError> {
1406 ensure_can_observe(caller, target, db).await?;
1407 let target = service::user::read(db, target)
1408 .await?
1409 .ok_or(AppError::NotFound)?;
1410 // Only a student has insights: a colleague's id is not a narrower report,
1411 // it is a 404.
1412 if target.get_role() != Role::Student {
1413 return Err(AppError::NotFound);
1414 }
1415 if caller.get_role() == Role::Teacher && !teacher_reaches(db, caller, target.get_id()).await? {
1416 return Err(AppError::NotFound);
1417 }
1418 Ok(())
1419}
1420
1421/// Does this teacher actually reach this student — a shared class×course
1422/// instance the teacher runs and the student sits in? The instances a teacher
1423/// runs are [`service::instance::visible_instances`]'s `manages` half, which
1424/// is the same D10 rule every instance-scoped route applies
1425/// ([`service::class_course::ensure_instance_teacher`]): an assigned teacher
1426/// or the class section's homeroom teacher, and nobody else.
1427async fn teacher_reaches(
1428 db: &Database,
1429 teacher: &User,
1430 student: &UserId,
1431) -> Result<bool, AppError> {
1432 let (members, _) = crate::db::class_member::list_for_user(db, student, None, 0).await?;
1433 let classes: Vec<ClassGroupId> = members
1434 .iter()
1435 .map(|member| member.get_class().clone())
1436 .collect();
1437 if classes.is_empty() {
1438 return Ok(false);
1439 }
1440 let runs: Vec<uuid::Uuid> = service::instance::visible_instances(teacher, db)
1441 .await?
1442 .into_iter()
1443 .filter(|(_, manages)| *manages)
1444 .map(|(instance, _)| instance.get_id().uuid())
1445 .collect();
1446 if runs.is_empty() {
1447 return Ok(false);
1448 }
1449 Ok(crate::db::class_course::list_for_class_ids(db, &classes)
1450 .await?
1451 .iter()
1452 .any(|instance| runs.contains(&instance.get_id().uuid())))
1453}
1454
1455/// The `audience_role` label a caller reads cards under. ZEKA's catalogue
1456/// closes four labels (`student` | `teacher` | `parent` | `manager`); the two
1457/// staff ranks above teacher fold into `manager`, and the bridge's own
1458/// principal reads under a label no row can carry (the column's CHECK lists
1459/// the human four) — so a service reading as itself gets the empty list an
1460/// absent surface should give it.
1461fn audience_role(role: Role) -> &'static str {
1462 match role {
1463 Role::Student => "student",
1464 Role::Parent => "parent",
1465 Role::Teacher => "teacher",
1466 Role::Manager | Role::Admin => "manager",
1467 Role::Ai => "ai",
1468 }
1469}