From 0f55f34e76c3c3b49a541b55237afb7dbca1719a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 18 Sep 2026 07:03:01 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(insight):=20name=20the=20reque?= =?UTF-8?q?ster=20and=20fill=20a=20school-wide=20refresh=20roster?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every `insight.*` dispatch now carries `requested_by` — the caller the door authenticated, which the service passes as `on_behalf_of` so its per-student reads (`/marks/{user}` and the rest) answer as that teacher or manager instead of the synthetic `ai` principal those reads refuse with a 403. `insight.refresh` also always fills `user_ids`: a caller-named list passes through exactly as given, while an empty body is filled from the school's own student roster (every user holding the `student` role), because the service's own roster discovery reads homework `assigned` lists, which a live school rarely fills — so an empty body used to sweep nobody. The payload's new `roster_source` records which roster the list was, and the refresh log names it so the run ledger's counts are explainable. A school with no students dispatches an empty list and answers 0 honestly; a roster past `MAX_INSIGHT_REFRESH_STUDENTS` is refused rather than clipped. Local-Gate: 644eaaee78ddae2e35af223da2719c3a55697a86 (1488 passed, 466s) --- src/ai/insight.rs | 54 +++++++++++++-- src/constant.rs | 9 +++ src/web/insights.rs | 71 +++++++++++++++++--- tests/ai_bridge.rs | 127 +++++++++++++++++++++++++++++++++++ tests/limits_completeness.rs | 6 ++ 5 files changed, 250 insertions(+), 17 deletions(-) diff --git a/src/ai/insight.rs b/src/ai/insight.rs index 35a90e5..b02c728 100644 --- a/src/ai/insight.rs +++ b/src/ai/insight.rs @@ -55,6 +55,13 @@ pub use crate::constant::{ pub struct StudentRequest { /// The student's user id. pub user_id: String, + /// Who asked for this compute: the caller the door authenticated, and the + /// principal every bridge read for this dispatch runs as. The service + /// passes it as `on_behalf_of`, because the synthetic `ai` principal a + /// read with nobody named would run as is refused `403` on a per-student + /// report (`/marks/{user}` and the rest) — the report answers a teacher or + /// a manager, never the service itself. + pub requested_by: String, /// ISO-8601 date to compute from; omitted, the service starts at the /// term's beginning. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -95,6 +102,8 @@ pub struct StudentResponse { pub struct ClassRequest { /// The course or class the analysis is about. pub course_id: String, + /// Who asked for this compute — see [`StudentRequest::requested_by`]. + pub requested_by: String, /// The term to read; omitted, the service uses the current one. #[serde(default, skip_serializing_if = "Option::is_none")] pub term: Option, @@ -121,16 +130,35 @@ pub struct ClassResponse { pub coverage: Option, } +/// `roster_source` when the caller named the students themselves: the list is +/// passed through exactly as given. +pub const ROSTER_SOURCE_EXPLICIT: &str = "explicit"; + +/// `roster_source` when the door filled `user_ids` from the school's own +/// student roster (an empty request body). +pub const ROSTER_SOURCE_SCHOOL: &str = "school"; + /// What the backend asks a service to recompute for a whole school. /// -/// A batch job: with `user_ids` omitted the service works through its own -/// configured student list — the backend does not enumerate one, because a -/// school-wide roster is not something the bridge's read scope hands a -/// service (same doc, item 3). +/// A batch job, and the door always fills `user_ids`: a caller-named list +/// passes through exactly as given ([`ROSTER_SOURCE_EXPLICIT`]), while an +/// empty one is filled from the school's own student roster +/// ([`ROSTER_SOURCE_SCHOOL`]) — the backend enumerates one now because the +/// service's own roster discovery reads homework `assigned` lists, which a +/// live school rarely fills, so an empty body used to sweep nobody. +/// `roster_source` records which of the two the list was, so the run's counts +/// read honestly: a `school` sweep that computed few students is a bounded +/// run, not a caller who named few. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RefreshRequest { + /// Who asked for this sweep — see [`StudentRequest::requested_by`]. + pub requested_by: String, + /// The students to recompute, in the order the door resolved them. #[serde(default, skip_serializing_if = "Option::is_none")] pub user_ids: Option>, + /// Which roster [`Self::user_ids`] came from: [`ROSTER_SOURCE_EXPLICIT`] + /// or [`ROSTER_SOURCE_SCHOOL`]. + pub roster_source: String, /// Recompute even where a cached result is still valid. #[serde(default, skip_serializing_if = "Option::is_none")] pub force: Option, @@ -425,22 +453,34 @@ mod tests { fn the_request_names_are_the_contracts() { let request = StudentRequest { user_id: "user-1".into(), + requested_by: "user-9".into(), since: Some("2026-09-01".into()), sections: None, }; assert_eq!( serde_json::to_value(&request).unwrap(), - serde_json::json!({ "user_id": "user-1", "since": "2026-09-01" }), - "an omitted section list stays off the wire, not null" + serde_json::json!({ + "user_id": "user-1", + "requested_by": "user-9", + "since": "2026-09-01", + }), + "a requested_by always rides the wire; an omitted section list stays off it, not null" ); let refresh = RefreshRequest { + requested_by: "user-9".into(), user_ids: Some(vec!["user-1".into()]), + roster_source: ROSTER_SOURCE_EXPLICIT.into(), force: Some(true), }; assert_eq!( serde_json::to_value(&refresh).unwrap(), - serde_json::json!({ "user_ids": ["user-1"], "force": true }) + serde_json::json!({ + "requested_by": "user-9", + "user_ids": ["user-1"], + "roster_source": "explicit", + "force": true, + }) ); } diff --git a/src/constant.rs b/src/constant.rs index 3c46447..71a26db 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -710,6 +710,15 @@ pub const MAX_INSIGHT_PENDING_STUDENTS: usize = 20_000; /// mistake. pub const MAX_INSIGHT_PURGE_STUDENTS: usize = 20_000; +/// The most students one `insight.refresh` may carry when its door fills an +/// empty request body from the school's own roster. The service works through +/// the list in its own batches (`ZEKA_REFRESH_BATCH`, 25 at a time) and +/// records the rest as pending for its next run, so the ceiling is the frame's, +/// not one run's — [`MAX_INSIGHT_PENDING_STUDENTS`]'s size class. Over it the +/// door **refuses** rather than clipping: a clipped roster would leave students +/// unanalysed while the run's ledger read as complete. +pub const MAX_INSIGHT_REFRESH_STUDENTS: usize = 20_000; + /// How long a `rag.chat` turn may sit `pending` before a reader projects it as /// failed. The RAG nest mirrors the chatbot's asynchronous send /// ([`CHATBOT_PENDING_STALE_SECS`]): the round trip outlives the request that diff --git a/src/web/insights.rs b/src/web/insights.rs index c025834..e3b03ac 100644 --- a/src/web/insights.rs +++ b/src/web/insights.rs @@ -54,11 +54,14 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::ai::insight::{ - self, PendingList, ProfileWriteRequest, PurgeRequest, RecommendationWriteRequest, - RefreshRequest, RunWriteRequest, SchoolDirectory, SegmentWriteRequest, StudentRequest, - SummaryWriteRequest, TableVerdicts, WriteReceipt, + self, PendingList, ProfileWriteRequest, PurgeRequest, ROSTER_SOURCE_EXPLICIT, + ROSTER_SOURCE_SCHOOL, RecommendationWriteRequest, RefreshRequest, RunWriteRequest, + SchoolDirectory, SegmentWriteRequest, StudentRequest, SummaryWriteRequest, TableVerdicts, + WriteReceipt, +}; +use crate::constant::{ + AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY, MAX_INSIGHT_REFRESH_STUDENTS, }; -use crate::constant::{AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY}; use crate::database::Database; use crate::db; use crate::domain::class_group::ClassGroupId; @@ -133,8 +136,9 @@ struct ComputeStudentRequest { #[derive(Deserialize, ToSchema, Default)] struct RefreshInsightsRequest { - /// Student user ids to recompute; omit for the service's own configured - /// list — the backend does not enumerate a school roster for it. + /// Student user ids to recompute; omit (or send an empty list) to sweep + /// the school's own student roster — every user holding the `student` + /// role. A named list is used exactly as given. user_ids: Option>, /// Recompute even where the service considers its cached result valid. force: Option, @@ -149,6 +153,10 @@ struct RefreshInsightsRequest { /// Authorization is [`student_insight`]'s, gate for gate: the caller must be /// able to read the student before they may ask for a recompute, and the /// refusal is a `404` (a foreign id and a missing one look the same). +/// +/// The dispatch names the **caller** as `requested_by`, not the student: the +/// service reads the student's marks and the rest as that caller, so a +/// teacher's or manager's own reach is what the reads answer against. #[utoipa::path( post, path = "/students/{user}", @@ -178,6 +186,7 @@ async fn compute_student( let body = body.map(|Json(body)| body).unwrap_or_default(); let request = StudentRequest { user_id: target.key(), + requested_by: user.get_id().key(), since: body.since, sections: body.sections, }; @@ -212,6 +221,15 @@ async fn compute_student( /// Manager+ only: this is a school-wide batch, and the run it starts spends /// the service's whole time budget. `503` when no service offers /// `insight.refresh` — nothing is queued. +/// +/// The dispatch names the **caller** as `requested_by` — the principal the +/// service's own reads for the sweep run as — and always fills `user_ids`: a +/// named list passes through exactly as given, while an empty body is filled +/// from the school's own student roster (every user holding the `student` +/// role). The service's own roster discovery reads homework `assigned` lists, +/// so an empty body used to sweep nobody; the payload's `roster_source` records +/// which roster the list was. A school with no students dispatches an empty +/// list and answers `0` honestly. #[utoipa::path( post, path = "/refresh", @@ -220,7 +238,7 @@ async fn compute_student( request_body = RefreshInsightsRequest, responses( (status = 202, description = "Queued; the service writes its run ledger on its own", body = AcceptedResponse), - (status = 400, description = "`user_ids` names something that is not a user id", body = ErrorResponse), + (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), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 503, description = "No AI service offers `insight.refresh` right now; nothing was queued", body = ErrorResponse), @@ -230,12 +248,18 @@ async fn compute_student( async fn refresh( State(st): State, tenant: ResolvedTenant, - RequireManager(_user): RequireManager, + RequireManager(user): RequireManager, body: Option>, ) -> Result { let body = body.map(|Json(body)| body).unwrap_or_default(); + let (roster, roster_source) = match normalized_ids(body.user_ids)? { + Some(ids) if !ids.is_empty() => (ids, ROSTER_SOURCE_EXPLICIT), + _ => (school_roster(&st.db).await?, ROSTER_SOURCE_SCHOOL), + }; let request = RefreshRequest { - user_ids: normalized_ids(body.user_ids)?, + requested_by: user.get_id().key(), + user_ids: Some(roster), + roster_source: roster_source.to_string(), force: body.force, }; let Some(bridge) = st.ai.clone() else { @@ -249,9 +273,10 @@ async fn refresh( let slug = tenant.slug.clone(); tokio::spawn(async move { + let source = request.roster_source.clone(); match insight::refresh(&bridge, &slug, &request).await { Ok(answer) => tracing::info!( - "insight.refresh answered: {} requested, {} computed, {} skipped, {} failed", + "insight.refresh ({source} roster) answered: {} requested, {} computed, {} skipped, {} failed", answer.requested.unwrap_or(0), answer.computed.unwrap_or(0), answer.skipped.unwrap_or(0), @@ -573,6 +598,32 @@ fn normalized_ids(ids: Option>) -> Result>, AppEr .transpose() } +/// The school's own student roster, as the refresh door fills an empty request +/// body with. +/// +/// The same set the office's student table lists: every `app_user` holding the +/// `student` role exactly, newest first ([`db::user::list_by_role`]). It is +/// what the service cannot assemble itself — its own roster discovery reads +/// homework `assigned` lists, which a live school rarely fills — so an empty +/// body must name the school here or the sweep computes nobody. +/// +/// Refused, never clipped, past +/// [`MAX_INSIGHT_REFRESH_STUDENTS`](crate::constant::MAX_INSIGHT_REFRESH_STUDENTS): +/// a clipped roster would leave students unanalysed while the run read as +/// complete. A school with no students answers an empty list — a sweep that +/// computed nobody is a true answer, not a failure. +async fn school_roster(db: &Database) -> Result, AppError> { + let students = db::user::list_by_role(db, Role::Student).await?; + if students.len() > MAX_INSIGHT_REFRESH_STUDENTS { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_ids", + reason: "the school's roster is larger than one refresh may carry; \ + name the students to recompute explicitly", + })); + } + Ok(students.iter().map(|user| user.get_id().key()).collect()) +} + // ---- the reads ------------------------------------------------------------- /// One student's nightly summary. The four module objects are ZEKA's own diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index b5900a5..c905e4f 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -3463,6 +3463,7 @@ async fn an_insight_student_dispatch_names_the_school_and_round_trips() { &demo(), &hezarfen_backend::ai::StudentRequest { user_id: ali.clone(), + requested_by: ali.clone(), since: None, sections: None, }, @@ -3539,6 +3540,132 @@ async fn no_insight_refresh_worker_means_503_and_nothing_is_dispatched() { assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); } +// ---- the requester and the roster a refresh reads ------------------------- + +use hezarfen_backend::ai::insight::{ROSTER_SOURCE_EXPLICIT, ROSTER_SOURCE_SCHOOL}; + +/// The ids of a JSON array of strings, sorted — the roster's own order is the +/// database's (newest first), which is not what these tests are about. +fn sorted_ids(value: &Value) -> Vec { + let mut ids: Vec = value + .as_array() + .expect("a json array") + .iter() + .map(|id| id.as_str().expect("an id string").to_string()) + .collect(); + ids.sort(); + ids +} + +/// Every `insight.*` dispatch names the caller it runs as. The compute doors +/// are authorized for the caller, so the service must read the student's data +/// as that caller too — the synthetic `ai` principal those reads would +/// otherwise run as is refused `403` on `/marks/{user}`. The refresh door also +/// fills an empty body from the school's own student roster: its own discovery +/// (homework `assigned` lists) does not name enough of a live school to sweep. +#[tokio::test] +async fn the_insight_doors_name_the_caller_and_the_refresh_roster_they_read() { + let bridge = bridge().await; + let service = connect_service( + &bridge, + hello( + "zeka", + &[AI_INSIGHT_STUDENT_CAPABILITY, AI_INSIGHT_REFRESH_CAPABILITY], + ), + Behaviour::Echo, + ) + .await; + await_workers(&bridge, 1).await; + let (app, db) = chat_app(&bridge).await; + + let staff = common::login_as(&app, &db, "mudur", "manager").await; + let staff_id = common::me_id(&app, &staff).await; + let ayse = common::login_as(&app, &db, "ayse", "student").await; + let ayse_id = common::me_id(&app, &ayse).await; + let veli = common::login_as(&app, &db, "veli", "student").await; + let veli_id = common::me_id(&app, &veli).await; + + // The student door names the caller beside the student it computes. + let res = common::send( + &app, + "POST", + &format!("/insights/students/{ayse_id}"), + Some(&staff), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); + + let seen = await_seen(&service, 1).await; + assert_eq!(seen[0].payload["user_id"], ayse_id); + assert_eq!(seen[0].payload["requested_by"], staff_id); + + // An empty refresh body carries the school's own roster — both students. + let res = common::send( + &app, + "POST", + "/insights/refresh", + Some(&staff), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); + let seen = await_seen(&service, 2).await; + assert_eq!(seen[1].payload["requested_by"], staff_id); + assert_eq!(seen[1].payload["roster_source"], ROSTER_SOURCE_SCHOOL); + let mut expected = vec![ayse_id.clone(), veli_id.clone()]; + expected.sort(); + assert_eq!(sorted_ids(&seen[1].payload["user_ids"]), expected); + + // A named list is used exactly as given, never widened to the roster. + let res = common::send( + &app, + "POST", + "/insights/refresh", + Some(&staff), + Some(json!({ "user_ids": [veli_id] })), + ) + .await; + assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); + let seen = await_seen(&service, 3).await; + assert_eq!(seen[2].payload["roster_source"], ROSTER_SOURCE_EXPLICIT); + assert_eq!(seen[2].payload["requested_by"], staff_id); + assert_eq!(seen[2].payload["user_ids"], json!([veli_id])); +} + +/// A school with no students still dispatches an honest empty sweep: the +/// roster fill answers an empty list rather than refusing, so a refresh on a +/// brand-new school completes with `0 requested` instead of vanishing. +#[tokio::test] +async fn an_empty_school_roster_still_dispatches_with_an_empty_list() { + let bridge = bridge().await; + let service = connect_service( + &bridge, + hello("zeka", &[AI_INSIGHT_REFRESH_CAPABILITY]), + Behaviour::Echo, + ) + .await; + await_workers(&bridge, 1).await; + let (app, db) = chat_app(&bridge).await; + let staff = common::login_as(&app, &db, "mudur", "manager").await; + let staff_id = common::me_id(&app, &staff).await; + + let res = common::send( + &app, + "POST", + "/insights/refresh", + Some(&staff), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); + + let seen = await_seen(&service, 1).await; + assert_eq!(seen[0].payload["requested_by"], staff_id); + assert_eq!(seen[0].payload["roster_source"], ROSTER_SOURCE_SCHOOL); + assert_eq!(seen[0].payload["user_ids"], json!([])); +} + // ---- a capability a service contradicts -------------------------------- // // The class this closes: a service announces `insight.refresh` in its `Hello`, diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs index 66063a1..50bd3ef 100644 --- a/tests/limits_completeness.rs +++ b/tests/limits_completeness.rs @@ -201,6 +201,12 @@ const EXCLUDED: &[(&str, &str)] = &[ "students one bridge purge call may name; the roster is the AI \ service's own list, not something a browser assembles", ), + ( + "MAX_INSIGHT_REFRESH_STUDENTS", + "students one school-wide refresh may carry when its door fills the \ + roster itself; the refresh batch is the AI service's own work unit, \ + not a client-facing bound", + ), ( "AI_PODCAST_SUBMIT_CAPABILITY", "capability string an AI service declares",