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

insight.rs679 lines, 27.9 KiBHistoryRawDownload
1//! Payload contract for the `insight.*` capabilities, in both directions.
2//!
3//! ZEKA (`hezarfen_zeka`) computes student and class insights from a school's
4//! own data. The family has two halves and they travel opposite ways:
5//!
6//! * **Outbound** (the backend dispatches to the service):
7//! [`AI_INSIGHT_STUDENT_CAPABILITY`] — one student, on demand;
8//! [`AI_INSIGHT_REFRESH_CAPABILITY`] — a school-wide sweep, on demand;
9//! [`AI_INSIGHT_REPORT_CAPABILITY`] — a school-level report document, on
10//! demand (its request carries the rows the backend already holds). The
11//! dispatches below carry them ([`compute_student`], [`refresh`],
12//! [`report`]).
13//! * **Inbound** (the service calls the backend): the nine operations of
14//! [`AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY`]'s family — the storage surface
15//! ZEKA's `zeka_*` rows are written and read through, because **no AI
16//! service may touch a school database**. [`serve`] runs them; the SQL
17//! lives in [`crate::db::insight`], and [`crate::web::insights`] mounts the
18//! same functions as HTTP doors. This is the shape the whole family exists
19//! for: an operation named on the wire, scoped to the frame's school, with
20//! no path, no table and no query any caller can name.
21//!
22//! [`AI_INSIGHT_CLASS_CAPABILITY`] is declared (the service announces it) but
23//! deliberately not dispatched: its request names a course the service would
24//! have to enumerate a roster for, and the bridge's read allowlist carries no
25//! member listing yet — the backend half of that contract is still open
26//! (`hezarfen_zeka/service/docs/BACKEND-GEREKSINIMLERI.md`, item 3). Routing
27//! it early would only hand the service a request it cannot answer.
28//!
29//! Every payload member is optional on the response side on purpose: the
30//! service's TypedDicts are `total=False`, so a partial answer is a legal
31//! answer, and a strict struct here would turn a service update into a
32//! backend error. The inbound rows are the opposite: they are a *write*
33//! contract, so a missing field is refused rather than defaulted — except
34//! where this module says an omission is meaningful.
35
36use std::time::Duration;
37
38use serde::de::DeserializeOwned;
39use serde::{Deserialize, Serialize};
40use serde_json::Value;
41
42use crate::ai::AiBridge;
43use crate::ai::error::AiError;
44use crate::ai::protocol::FrameError;
45use crate::constant::{
46 AI_INSIGHT_REFRESH_TIMEOUT_SECS, AI_INSIGHT_REPORT_TIMEOUT_SECS,
47 AI_INSIGHT_STUDENT_TIMEOUT_SECS,
48};
49use crate::tenant::SchoolId;
50
51pub use crate::constant::{
52 AI_INSIGHT_CLASS_CAPABILITY, AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_REPORT_CAPABILITY,
53 AI_INSIGHT_STUDENT_CAPABILITY,
54};
55
56/// What the backend asks a service to compute for one student.
57///
58/// `school` is **not** a payload member: it rides the frame's own
59/// [`Request.school`](crate::ai::protocol::Request::school), and a second
60/// copy here would be one more place the two could disagree.
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62pub struct StudentRequest {
63 /// The student's user id.
64 pub user_id: String,
65 /// Who asked for this compute: the caller the door authenticated, and the
66 /// principal every bridge read for this dispatch runs as. The service
67 /// passes it as `on_behalf_of`, because the synthetic `ai` principal a
68 /// read with nobody named would run as is refused `403` on a per-student
69 /// report (`/marks/{user}` and the rest) — the report answers a teacher or
70 /// a manager, never the service itself.
71 pub requested_by: String,
72 /// ISO-8601 date to compute from; omitted, the service starts at the
73 /// term's beginning.
74 #[serde(default, skip_serializing_if = "Option::is_none")]
75 pub since: Option<String>,
76 /// Sections to compute; omitted, the service computes all of them.
77 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub sections: Option<Vec<String>>,
79}
80
81/// What the service computed for one student.
82///
83/// `signals` and `recommendations` stay JSON values: their shape belongs to
84/// the service's rule catalogue, which is versioned far faster than this
85/// crate, and the stored form of the same data is JSONB for exactly that
86/// reason. A reader that needs a card's fields reads them by name.
87#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88pub struct StudentResponse {
89 #[serde(default)]
90 pub user_id: Option<String>,
91 #[serde(default)]
92 pub generated_at: Option<String>,
93 /// The study profile the service detected.
94 #[serde(default)]
95 pub archetype: Option<String>,
96 #[serde(default)]
97 pub signals: Vec<Value>,
98 #[serde(default)]
99 pub recommendations: Vec<Value>,
100 /// Which data source contributed how many records.
101 #[serde(default)]
102 pub coverage: Option<Value>,
103}
104
105/// What the backend would ask a service to compute for one class (a course
106/// as one section teaches it). Defined for the contract; nothing dispatches it
107/// yet — see the module docs.
108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109pub struct ClassRequest {
110 /// The course or class the analysis is about.
111 pub course_id: String,
112 /// Who asked for this compute — see [`StudentRequest::requested_by`].
113 pub requested_by: String,
114 /// The term to read; omitted, the service uses the current one.
115 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub term: Option<String>,
117 /// Length of the attention list.
118 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub top_n: Option<u32>,
120}
121
122/// What the service computed for one class. Same leniency as
123/// [`StudentResponse`]: the loose members are the service's own shapes.
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125pub struct ClassResponse {
126 #[serde(default)]
127 pub course_id: Option<String>,
128 #[serde(default)]
129 pub generated_at: Option<String>,
130 #[serde(default)]
131 pub cohort_size: Option<u64>,
132 #[serde(default)]
133 pub topic_gaps: Vec<Value>,
134 #[serde(default)]
135 pub attention_list: Vec<Value>,
136 #[serde(default)]
137 pub coverage: Option<Value>,
138}
139
140/// `roster_source` when the caller named the students themselves: the list is
141/// passed through exactly as given.
142pub const ROSTER_SOURCE_EXPLICIT: &str = "explicit";
143
144/// `roster_source` when the door filled `user_ids` from the school's own
145/// student roster (an empty request body).
146pub const ROSTER_SOURCE_SCHOOL: &str = "school";
147
148/// What the backend asks a service to recompute for a whole school.
149///
150/// A batch job, and the door always fills `user_ids`: a caller-named list
151/// passes through exactly as given ([`ROSTER_SOURCE_EXPLICIT`]), while an
152/// empty one is filled from the school's own student roster
153/// ([`ROSTER_SOURCE_SCHOOL`]) — the backend enumerates one now because the
154/// service's own roster discovery reads homework `assigned` lists, which a
155/// live school rarely fills, so an empty body used to sweep nobody.
156/// `roster_source` records which of the two the list was, so the run's counts
157/// read honestly: a `school` sweep that computed few students is a bounded
158/// run, not a caller who named few.
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160pub struct RefreshRequest {
161 /// Who asked for this sweep — see [`StudentRequest::requested_by`].
162 pub requested_by: String,
163 /// The students to recompute, in the order the door resolved them.
164 #[serde(default, skip_serializing_if = "Option::is_none")]
165 pub user_ids: Option<Vec<String>>,
166 /// Which roster [`Self::user_ids`] came from: [`ROSTER_SOURCE_EXPLICIT`]
167 /// or [`ROSTER_SOURCE_SCHOOL`].
168 pub roster_source: String,
169 /// Recompute even where a cached result is still valid.
170 #[serde(default, skip_serializing_if = "Option::is_none")]
171 pub force: Option<bool>,
172}
173
174/// The receipt for a refresh: what the sweep did, once it did it. The run's
175/// own ledger is `zeka_run` in the school database, which is what a reader
176/// polls while this answer is still on its way.
177#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
178pub struct RefreshResponse {
179 #[serde(default)]
180 pub started_at: Option<String>,
181 #[serde(default)]
182 pub requested: Option<u64>,
183 #[serde(default)]
184 pub computed: Option<u64>,
185 #[serde(default)]
186 pub skipped: Option<u64>,
187 /// `{user_id, code, message}` per student the sweep could not compute.
188 #[serde(default)]
189 pub failed: Vec<Value>,
190}
191
192/// `kind` on a school-level report request — the one document kind this
193/// dispatch asks for today. Spelled as the service's own vocabulary spells it
194/// (`okul`), because it selects a builder there.
195pub const REPORT_KIND_SCHOOL: &str = "okul";
196
197/// What the backend asks a service to render for a whole school, for one run
198/// day.
199///
200/// Unlike the other two outbound requests, this one **carries the data**: the
201/// service computes nothing here, and it may not read a school's database, so
202/// the backend sends the rows it already holds from its own `zeka_*` tables —
203/// the same serde rows the storage surface writes ([`SummaryRow`],
204/// [`RecommendationRow`], [`ProfileRow`], [`RunRow`]) — and the service
205/// renders them into one self-contained document.
206///
207/// A run day with no `zeka_run` row, or one whose tables are empty, is a
208/// legal request: the lists are then empty (or missing the absent day) and
209/// the document's own `notes` say so. Nothing here refuses a day the ledger
210/// does not know.
211#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
212pub struct ReportRequest {
213 /// [`REPORT_KIND_SCHOOL`] — which builder the service runs.
214 pub kind: String,
215 /// The run day the document is about, `YYYY-MM-DD`.
216 pub run_day: String,
217 /// Who asked for the document — see [`StudentRequest::requested_by`]. The
218 /// rendering reads nothing, but the service's logs name the requester.
219 pub requested_by: String,
220 /// The school's own identity, so the document prints a display name
221 /// rather than a raw id.
222 pub school: ReportSchool,
223 /// Every class (şube) of the school, id and display name: the summaries'
224 /// evidence carries class **ids**, and a document that groups by class
225 /// must print the name a reader recognizes. A sibling key rather than a
226 /// member of [`Self::school`]: it is a lookup for the rows, not part of
227 /// the school's identity. A class a row names but this list does not
228 /// carry (a deleted one) is absent on purpose — the renderer falls back
229 /// to an honest label, never a name invented here.
230 pub classes: Vec<ClassLabel>,
231 /// Every stored summary (with its attention items) in the school.
232 pub summaries: Vec<SummaryRow>,
233 pub recommendations: Vec<RecommendationRow>,
234 pub profiles: Vec<ProfileRow>,
235 /// The ledger rows the document may show: the named day first when it
236 /// exists, then the newest days, at most a handful.
237 pub runs: Vec<RunRow>,
238}
239
240/// What the service rendered. `html` is the one required member: a response
241/// without a document is not a partial answer, it is a dispatch that produced
242/// nothing to store, and [`crate::ai::insight::report`]'s caller would rather
243/// refuse it than persist an empty file. The rest is the service's own
244/// bookkeeping, optional for the same reason every response member here is.
245#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
246pub struct ReportResponse {
247 #[serde(default)]
248 pub kind: Option<String>,
249 #[serde(default)]
250 pub run_day: Option<String>,
251 /// `html` today — the format the stored artifact is served as. Recorded
252 /// rather than assumed, so a future format is visible on the wire.
253 #[serde(default)]
254 pub format: Option<String>,
255 /// The self-contained document, `<!doctype html>` first.
256 pub html: String,
257 #[serde(default)]
258 pub byte_size: Option<u64>,
259 /// Whether the service clipped the document (a row set past its own
260 /// ceiling). Stored and reported verbatim: a clipped document must not
261 /// read as a complete one.
262 #[serde(default)]
263 pub truncated: bool,
264 /// The service's own remarks about the document — e.g. that the run day
265 /// has no ledger row. Shown to the manager beside the artifact.
266 #[serde(default)]
267 pub notes: Vec<String>,
268}
269
270/// Compute one student's insight, awaited. No capability check here: the
271/// caller decides what "no service" means, and every caller today is an HTTP
272/// door that has already answered `503` for it ([`crate::web::insights`]).
273pub async fn compute_student(
274 bridge: &AiBridge,
275 school: &SchoolId,
276 request: &StudentRequest,
277) -> Result<StudentResponse, AiError> {
278 dispatch(
279 bridge,
280 school,
281 AI_INSIGHT_STUDENT_CAPABILITY,
282 AI_INSIGHT_STUDENT_TIMEOUT_SECS,
283 request,
284 )
285 .await
286}
287
288/// Ask for a school-wide recompute, awaited. The service answers when its
289/// batch is over; the deadline is [`AI_INSIGHT_REFRESH_TIMEOUT_SECS`].
290pub async fn refresh(
291 bridge: &AiBridge,
292 school: &SchoolId,
293 request: &RefreshRequest,
294) -> Result<RefreshResponse, AiError> {
295 dispatch(
296 bridge,
297 school,
298 AI_INSIGHT_REFRESH_CAPABILITY,
299 AI_INSIGHT_REFRESH_TIMEOUT_SECS,
300 request,
301 )
302 .await
303}
304
305/// Ask for one school-level report document, awaited. The request carries
306/// every row the document needs, and the answer carries the rendered HTML
307/// back; the deadline is [`AI_INSIGHT_REPORT_TIMEOUT_SECS`] — short on
308/// purpose, so the caller's own error path wins the race against the request
309/// envelope ([`crate::constant::REQUEST_TIMEOUT_SECS`]). The caller stores the
310/// document — this function only moves it.
311pub async fn report(
312 bridge: &AiBridge,
313 school: &SchoolId,
314 request: &ReportRequest,
315) -> Result<ReportResponse, AiError> {
316 dispatch(
317 bridge,
318 school,
319 AI_INSIGHT_REPORT_CAPABILITY,
320 AI_INSIGHT_REPORT_TIMEOUT_SECS,
321 request,
322 )
323 .await
324}
325
326/// One request, one typed answer — the dispatches differ only in capability,
327/// deadline and payload type.
328///
329/// A reply that does not parse as the expected type is a
330/// [`FrameError::Malformed`]: the bytes were JSON, but not this contract's
331/// JSON, and handing back a half-understood answer would be worse than
332/// reporting the service out of step.
333async fn dispatch<T>(
334 bridge: &AiBridge,
335 school: &SchoolId,
336 capability: &str,
337 timeout_secs: u64,
338 request: &impl Serialize,
339) -> Result<T, AiError>
340where
341 T: DeserializeOwned,
342{
343 let payload = serde_json::to_value(request).map_err(malformed)?;
344 let answer = bridge
345 .dispatch_with_timeout(
346 school,
347 capability,
348 payload,
349 Duration::from_secs(timeout_secs),
350 )
351 .await?;
352 serde_json::from_value(answer).map_err(malformed)
353}
354
355fn malformed(err: serde_json::Error) -> AiError {
356 AiError::Protocol(FrameError::Malformed(err))
357}
358
359// ---- the operations the backend serves -------------------------------------
360//
361// The half of this module that runs *towards* the backend. ZEKA computes, but
362// it may not write: no AI service holds a school database credential on this
363// deployment, so its `zeka_*` rows are written and read here, by name, over
364// the same bridge — one operation per call, each scoped to the school the
365// frame named. [`crate::db::insight`] is the SQL; this is the contract: which
366// names exist, what each payload is, and how a refusal reads.
367
368pub use crate::db::insight::{
369 AttentionRow, ClassLabel, PendingList, ProfileRow, ProfileWriteRequest, PurgeRequest,
370 RecommendationRow, RecommendationWriteRequest, ReportSchool, RunRow, RunWriteRequest,
371 SchoolDirectory, SegmentConfidences, SegmentLabels, SegmentRow, SegmentWriteRequest, SummaryRow,
372 SummaryWriteRequest, TableVerdicts, WriteReceipt,
373};
374
375use crate::constant::{
376 AI_INSIGHT_DEPARTED_PURGE_CAPABILITY, AI_INSIGHT_PENDING_LIST_CAPABILITY,
377 AI_INSIGHT_PROFILE_UPSERT_CAPABILITY, AI_INSIGHT_RECOMMENDATION_UPSERT_CAPABILITY,
378 AI_INSIGHT_RETENTION_SWEEP_CAPABILITY, AI_INSIGHT_RUN_UPSERT_CAPABILITY,
379 AI_INSIGHT_SCHOOLS_LIST_CAPABILITY, AI_INSIGHT_SEGMENT_UPSERT_CAPABILITY,
380 AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY,
381};
382use crate::database::Database;
383use crate::db;
384use crate::domain::timestamp::Timestamp;
385use crate::error::AppError;
386use crate::module::Module;
387use crate::tenant::ResolvedTenant;
388
389/// A refusal headed for a [`CapabilityResponse::Err`](crate::ai::protocol::CapabilityResponse::Err):
390/// the documented code, and a message that names the field a caller can fix.
391pub type Refusal = (&'static str, String);
392
393/// What a served capability is scoped to.
394#[derive(Debug, Clone, Copy, PartialEq, Eq)]
395pub enum Scope {
396 /// It runs against the school the frame named, and nothing else.
397 School,
398 /// Its answer does not come from a school's database at all — the
399 /// directory the fleet schedules over. The frame sends no school.
400 Deployment,
401}
402
403/// Every capability the backend serves, and its scope. Matched exactly: a
404/// name that is not here is `unknown_capability`, with no prefix match and no
405/// fallback — an operation a caller cannot name is one it cannot run.
406pub const SERVED: &[(&str, Scope)] = &[
407 (AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY, Scope::School),
408 (
409 AI_INSIGHT_RECOMMENDATION_UPSERT_CAPABILITY,
410 Scope::School,
411 ),
412 (AI_INSIGHT_SEGMENT_UPSERT_CAPABILITY, Scope::School),
413 (AI_INSIGHT_PROFILE_UPSERT_CAPABILITY, Scope::School),
414 (AI_INSIGHT_RUN_UPSERT_CAPABILITY, Scope::School),
415 (AI_INSIGHT_PENDING_LIST_CAPABILITY, Scope::School),
416 (AI_INSIGHT_RETENTION_SWEEP_CAPABILITY, Scope::School),
417 (AI_INSIGHT_DEPARTED_PURGE_CAPABILITY, Scope::School),
418 (AI_INSIGHT_SCHOOLS_LIST_CAPABILITY, Scope::Deployment),
419];
420
421/// The scope of one served capability, or `None` if the backend serves no
422/// operation by that name.
423pub fn scope_of(capability: &str) -> Option<Scope> {
424 SERVED
425 .iter()
426 .find(|(name, _)| *name == capability)
427 .map(|(_, scope)| *scope)
428}
429
430/// Run one capability call and hand back its payload.
431///
432/// `school` is the tenant the bridge resolved for the frame — `None` only for
433/// a [`Scope::Deployment`] capability, whose frame names no school. The
434/// school's own feature set is checked here as well as at the HTTP nest: a
435/// school that is not being served insights should not be accumulating rows
436/// for them either.
437pub async fn serve(
438 capability: &str,
439 school: Option<&ResolvedTenant>,
440 control: &Database,
441 payload: &Value,
442) -> Result<Value, Refusal> {
443 if scope_of(capability).is_none() {
444 return Err((
445 "unknown_capability",
446 format!("the backend serves no `{capability}` operation"),
447 ));
448 }
449 if capability == AI_INSIGHT_SCHOOLS_LIST_CAPABILITY {
450 let directory = db::insight::active_schools(control).await.map_err(refusal)?;
451 return encode(&directory);
452 }
453 let Some(tenant) = school else {
454 return Err((
455 "unknown_school",
456 "this operation runs against a school and the frame named none".to_string(),
457 ));
458 };
459 if !tenant.modules.contains(Module::Chatbot) {
460 return Err((
461 "not_permitted",
462 "this school does not have the insights module enabled".to_string(),
463 ));
464 }
465 let db = &tenant.db;
466 match capability {
467 AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY => {
468 let request: SummaryWriteRequest = decode(payload)?;
469 encode(&db::insight::write_summaries(db, request.rows).await.map_err(refusal)?)
470 }
471 AI_INSIGHT_RECOMMENDATION_UPSERT_CAPABILITY => {
472 let request: RecommendationWriteRequest = decode(payload)?;
473 encode(
474 &db::insight::write_recommendations(db, request.rows)
475 .await
476 .map_err(refusal)?,
477 )
478 }
479 AI_INSIGHT_SEGMENT_UPSERT_CAPABILITY => {
480 let request: SegmentWriteRequest = decode(payload)?;
481 encode(&db::insight::write_segments(db, request.rows).await.map_err(refusal)?)
482 }
483 AI_INSIGHT_PROFILE_UPSERT_CAPABILITY => {
484 let request: ProfileWriteRequest = decode(payload)?;
485 encode(&db::insight::write_profiles(db, request.rows).await.map_err(refusal)?)
486 }
487 AI_INSIGHT_RUN_UPSERT_CAPABILITY => {
488 let request: RunWriteRequest = decode(payload)?;
489 encode(&db::insight::write_run(db, request.run).await.map_err(refusal)?)
490 }
491 AI_INSIGHT_PENDING_LIST_CAPABILITY => {
492 encode(&db::insight::last_pending(db).await.map_err(refusal)?)
493 }
494 AI_INSIGHT_RETENTION_SWEEP_CAPABILITY => {
495 // The backend's own clock decides expiry — a service's clock is
496 // not a second authority on when a row's retention has closed.
497 let now_ms = Timestamp::now().as_millis();
498 encode(&db::insight::sweep(db, now_ms).await.map_err(refusal)?)
499 }
500 AI_INSIGHT_DEPARTED_PURGE_CAPABILITY => {
501 let request: PurgeRequest = decode(payload)?;
502 encode(
503 &db::insight::purge_departed(db, request.students)
504 .await
505 .map_err(refusal)?,
506 )
507 }
508 // `scope_of` matched above, so the table and this match agree; the
509 // arm exists so a table entry without an operation is a compile-time
510 // miss instead of a runtime surprise.
511 other => Err((
512 "unknown_capability",
513 format!("the backend serves no `{other}` operation"),
514 )),
515 }
516}
517
518/// Decode one payload into the operation's own type. A payload that does not
519/// fit is `invalid_payload`, never `malformed`: the frame was a capability
520/// call, the body was not this operation's body, and the caller can fix it.
521fn decode<T: DeserializeOwned>(payload: &Value) -> Result<T, Refusal> {
522 serde_json::from_value(payload.clone())
523 .map_err(|err| ("invalid_payload", format!("payload: {err}")))
524}
525
526fn encode<T: Serialize>(value: &T) -> Result<Value, Refusal> {
527 serde_json::to_value(value).map_err(|err| ("internal", format!("could not encode the answer: {err}")))
528}
529
530/// [`AppError`] as the protocol's refusal vocabulary. The mapping is the
531/// whole reason the db layer returns `AppError` rather than its own type:
532/// HTTP answers these through [`crate::error`], and a capability call answers
533/// the same verdict with the code a service branches on.
534fn refusal(err: AppError) -> Refusal {
535 match err {
536 AppError::Validation(err) => ("invalid_payload", err.to_string()),
537 AppError::PayloadTooLarge(message) => ("too_many_rows", message),
538 AppError::ModuleDisabled(module) => (
539 "not_permitted",
540 format!("this school does not have the `{module}` module enabled"),
541 ),
542 AppError::NotFound => ("not_found", "the named row does not exist".to_string()),
543 AppError::DbUnavailable | AppError::DbTimeout => (
544 "unavailable",
545 "this school's database could not be reached".to_string(),
546 ),
547 other => ("internal", other.to_string()),
548 }
549}
550
551#[cfg(test)]
552mod tests {
553 use super::*;
554
555 /// The wire names ARE this contract — a Python service reads them by
556 /// name, and a Rust-side rename that slipped past a struct literal would
557 /// break the service silently. Pinned on the encoded JSON.
558 #[test]
559 fn the_request_names_are_the_contracts() {
560 let request = StudentRequest {
561 user_id: "user-1".into(),
562 requested_by: "user-9".into(),
563 since: Some("2026-09-01".into()),
564 sections: None,
565 };
566 assert_eq!(
567 serde_json::to_value(&request).unwrap(),
568 serde_json::json!({
569 "user_id": "user-1",
570 "requested_by": "user-9",
571 "since": "2026-09-01",
572 }),
573 "a requested_by always rides the wire; an omitted section list stays off it, not null"
574 );
575
576 let refresh = RefreshRequest {
577 requested_by: "user-9".into(),
578 user_ids: Some(vec!["user-1".into()]),
579 roster_source: ROSTER_SOURCE_EXPLICIT.into(),
580 force: Some(true),
581 };
582 assert_eq!(
583 serde_json::to_value(&refresh).unwrap(),
584 serde_json::json!({
585 "requested_by": "user-9",
586 "user_ids": ["user-1"],
587 "roster_source": "explicit",
588 "force": true,
589 })
590 );
591 }
592
593 /// A partial answer is a legal answer: the service's TypedDicts are
594 /// `total=False`, so parsing must not demand every member — a strict
595 /// struct here would turn a service update into a backend error.
596 #[test]
597 fn a_partial_answer_parses() {
598 let answer: StudentResponse =
599 serde_json::from_value(serde_json::json!({ "user_id": "user-1" }))
600 .expect("a partial answer is still an answer");
601 assert_eq!(answer.user_id.as_deref(), Some("user-1"));
602 assert!(answer.signals.is_empty());
603 assert!(answer.coverage.is_none());
604 }
605
606 /// The report payload's own names, pinned on the encoded JSON for the same
607 /// reason as the request test above: `hezarfen_zeka` reads `kind`,
608 /// `run_day`, `school` and the four row lists by name.
609 #[test]
610 fn the_report_request_names_are_the_contracts() {
611 let request = ReportRequest {
612 kind: REPORT_KIND_SCHOOL.into(),
613 run_day: "2026-09-17".into(),
614 requested_by: "user-9".into(),
615 school: ReportSchool {
616 id: "019732e3-7b00-7000-8000-00000000dead".into(),
617 name: "Demo Okulu".into(),
618 },
619 classes: vec![ClassLabel {
620 id: "class-1".into(),
621 name: "8-A".into(),
622 }],
623 summaries: Vec::new(),
624 recommendations: Vec::new(),
625 profiles: Vec::new(),
626 runs: Vec::new(),
627 };
628 assert_eq!(
629 serde_json::to_value(&request).unwrap(),
630 serde_json::json!({
631 "kind": "okul",
632 "run_day": "2026-09-17",
633 "requested_by": "user-9",
634 "school": { "id": "019732e3-7b00-7000-8000-00000000dead", "name": "Demo Okulu" },
635 "classes": [{ "id": "class-1", "name": "8-A" }],
636 "summaries": [],
637 "recommendations": [],
638 "profiles": [],
639 "runs": [],
640 })
641 );
642 }
643
644 /// A report answer without a document is not a partial answer: `html` is
645 /// the one member the door cannot do without, and a service that omits it
646 /// is out of step, not empty-handed — the door would rather refuse the
647 /// dispatch than store a blank artifact. Every other member stays optional.
648 #[test]
649 fn a_report_answer_without_html_does_not_parse() {
650 let missing = serde_json::from_value::<ReportResponse>(serde_json::json!({
651 "kind": "okul",
652 "run_day": "2026-09-17"
653 }));
654 assert!(
655 missing.is_err(),
656 "a documentless answer is Malformed, never an empty file"
657 );
658
659 let answer: ReportResponse =
660 serde_json::from_value(serde_json::json!({ "html": "<!doctype html><html></html>" }))
661 .expect("the rest is optional");
662 assert!(answer.notes.is_empty());
663 assert!(!answer.truncated);
664 assert!(answer.byte_size.is_none());
665 }
666
667 /// The report door waits on its dispatch inside ONE HTTP request, so its
668 /// deadline must stay under the request envelope
669 /// ([`crate::constant::REQUEST_TIMEOUT_SECS`]): the middleware drops the
670 /// handler future at that ceiling — mid-write included — and answers its
671 /// own `503` whose "the write may or may not have applied" prose is wrong
672 /// for a door that knows nothing was stored. Raising the dispatch deadline
673 /// without the ceiling silently re-breaks exactly that, so the invariant
674 /// is checked when this module compiles, not when a test runs.
675 const _: () = assert!(
676 AI_INSIGHT_REPORT_TIMEOUT_SECS < crate::constant::REQUEST_TIMEOUT_SECS,
677 "the report dispatch must lose the race to the middleware on purpose"
678 );
679}