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.rs1254 lines, 48.2 KiBHistoryRawDownload
1//! ZEKA's own tables, and the operations that write and read them.
2//!
3//! ZEKA (`hezarfen_zeka`) computes student and class insights, but it does
4//! **not** touch a school database: every statement against the `zeka_*`
5//! tables runs here, on the backend, under the school the caller named. That
6//! is a standing rule of this deployment, not a preference — an AI service
7//! process holding a database credential of its own would be a second, silent
8//! door into every school's rows, one no request-scoped check can close. So
9//! the service's storage surface is nine named operations ([`crate::ai::insight`]
10//! carries the wire contract and the dispatch), and this module is what they
11//! execute.
12//!
13//! The row types here are therefore **both** the SQL's input and the bridge's
14//! payload: a nightly batch arrives as JSON, is parsed into these structs
15//! (`invalid_payload` on anything that does not fit), and is written verbatim —
16//! the backend is a trust boundary for the *shape*, never an author of the
17//! content. Fields are spelled exactly as the tables' columns are, because a
18//! consumer that has to guess a mapping between two spellings will eventually
19//! guess wrong.
20//!
21//! Three invariants are worth stating up front, since they are what the SQL
22//! below is arranged around:
23//!
24//! * **A batch is one transaction.** Every bulk write is all-or-nothing: a
25//! refusal means nothing landed, so a service that retries a batch cannot
26//! half-apply it. Row-at-a-time statements inside one transaction keep that
27//! honesty without a multi-row statement whose bind count would be a second
28//! bound to police; the batch ceiling [`MAX_INSIGHT_BATCH_ROWS`] keeps the
29//! statement count bounded.
30//! * **Child rows are replaced, never merged.** `attention`, the segment
31//! `dimension` rows, and a run's `pending`/`failed_module` rows are deleted
32//! for their owners and re-inserted from the payload. Merging would leave a
33//! fact the service stopped producing on the screen forever.
34//! * **The school is the database.** Every function here takes the school's
35//! own pool and nothing else: there is no `school` column to filter on
36//! because there is no row from another school in reach. Foreign keys carry
37//! the rest — an id from another school's database is not a row this
38//! database will accept, and that refusal is mapped to a validation error
39//! rather than a `500` so the caller learns which id was wrong.
40
41use std::collections::BTreeMap;
42
43use serde::{Deserialize, Serialize};
44use serde_json::Value as JsonValue;
45use sqlx::AssertSqlSafe;
46use sqlx::types::Json as SqlJson;
47use utoipa::ToSchema;
48use uuid::Uuid;
49
50use crate::constant::{
51 MAX_INSIGHT_BATCH_ROWS, MAX_INSIGHT_PENDING_STUDENTS, MAX_INSIGHT_PURGE_STUDENTS,
52};
53use crate::database::{Database, foreign_key_violation, tx_with_retry};
54use crate::domain::monotonic_id::next_uuid;
55use crate::error::{AppError, ValidationError};
56use crate::tenant::SchoolId;
57
58// ---- the wire rows ---------------------------------------------------------
59
60/// One student's computed summary, and the attention items that travel with
61/// it. The two tables are replaced together — see the module docs.
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
63pub struct SummaryRow {
64 /// `app_user.id` of the student this summary is about.
65 pub student: String,
66 /// The four evidence blocks, stored verbatim as JSONB. `null` is a legal
67 /// value: it means the section had no source rows, which is not the same
68 /// fact as a section that was not computed.
69 #[serde(default)]
70 pub marks: Option<JsonValue>,
71 #[serde(default)]
72 pub attendance: Option<JsonValue>,
73 #[serde(default)]
74 pub submission: Option<JsonValue>,
75 #[serde(default)]
76 pub study: Option<JsonValue>,
77 /// `none` | `exploratory` | `stable` — the service's own confidence in
78 /// the summary; the table's CHECK is the authority on the vocabulary.
79 pub confidence: String,
80 /// When the service computed this row, unix milliseconds.
81 pub computed_at: i64,
82 /// Unix milliseconds after which the sweep deletes the row. The service
83 /// owns its retention policy; the backend writes what it is told.
84 pub retain_until: i64,
85 /// The student's attention items, in the service's own order. Omitted
86 /// means "this student has none", which clears the previous ones.
87 #[serde(default)]
88 pub attention: Vec<AttentionRow>,
89}
90
91/// One attention item: a fact about a student that a teacher should see.
92#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
93pub struct AttentionRow {
94 /// The rule's trigger name, e.g. `not_egilimi_dusuyor`.
95 pub trigger: String,
96 /// The course the trigger fired in, when it fired in one.
97 #[serde(default)]
98 pub course: Option<String>,
99 /// The one-line fact a reader sees.
100 pub fact: String,
101 /// The window the fact was measured over, unix milliseconds.
102 pub window_from: i64,
103 pub window_to: i64,
104 /// The evidence object: the numbers behind the fact. Required — an item
105 /// whose evidence is missing is dropped by the service before it is sent,
106 /// and one that arrives without it is a payload error, not a silent write.
107 pub evidence: JsonValue,
108}
109
110/// One recommendation card.
111#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
112pub struct RecommendationRow {
113 /// The user the card is addressed to (`audience_role` says as what).
114 pub audience: String,
115 /// The product surface it belongs to, e.g. `student_home`.
116 pub product: String,
117 /// The rule that produced it, and the rule set's version.
118 pub rule_id: String,
119 pub rule_version: i64,
120 /// The rule's own scope marker (a segment label, a course) — part of the
121 /// natural key, so two scopes of one rule are two cards.
122 #[serde(default)]
123 pub scope: Option<String>,
124 /// The student the card is *about*, when it is about one.
125 #[serde(default)]
126 pub about: Option<String>,
127 /// `student` | `teacher` | `parent` | `manager`.
128 pub audience_role: String,
129 #[serde(default)]
130 pub course: Option<String>,
131 /// The evidence object. A row whose evidence carries nothing but
132 /// `limitation` is **not written** and is counted `rejected` in the
133 /// receipt — the service's own rule, kept where it can be audited.
134 pub evidence: JsonValue,
135 /// The stated limitation of the measurement, merged into the stored
136 /// evidence object under `limitation`.
137 #[serde(default)]
138 pub limitation: Option<String>,
139 /// `none` | `exploratory` | `stable`.
140 pub confidence: String,
141 pub computed_at: i64,
142 pub expires_at: i64,
143 pub retain_until: i64,
144}
145
146/// The four rubric labels of one question, in the service's nested shape.
147#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
148pub struct SegmentLabels {
149 pub bilissel_talep: String,
150 pub dikkat_tuzagi: String,
151 pub okuma_yuku: String,
152 pub adim_sayisi: String,
153}
154
155/// The model's confidence in each of the four labels, `0..=1`.
156#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
157pub struct SegmentConfidences {
158 pub bilissel_talep: f64,
159 pub dikkat_tuzagi: f64,
160 pub okuma_yuku: f64,
161 pub adim_sayisi: f64,
162}
163
164/// One question's segment labels, and the dimension split that travels with
165/// them (replaced together).
166#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
167pub struct SegmentRow {
168 /// The exam question this row labels.
169 pub question: String,
170 pub exam: String,
171 pub course: String,
172 pub subject: String,
173 pub labels: SegmentLabels,
174 pub confidences: SegmentConfidences,
175 /// The row's overall confidence, `none` | `exploratory` | `stable`.
176 pub confidence: String,
177 /// The distractors the question's wrong answers point at, when known.
178 #[serde(default)]
179 pub trap_choice: Option<String>,
180 /// Why the labels are what they are — the reader's audit trail.
181 pub rationale: String,
182 /// The model (and prompt) that produced the labels.
183 pub model: String,
184 pub prompt_version: String,
185 /// The prompt variant, when the service is A/B-ing one.
186 #[serde(default)]
187 pub variant: Option<String>,
188 pub computed_at: i64,
189 pub retain_until: i64,
190 /// Dimensions the downstream rules may use.
191 #[serde(default)]
192 pub downstream_dimensions: Vec<String>,
193 /// Dimensions still being measured.
194 #[serde(default)]
195 pub experimental_dimensions: Vec<String>,
196}
197
198/// One student's accuracy inside one rubric segment, against the same
199/// student's overall rate. `contrast` is the only field rules may fire on.
200#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
201pub struct ProfileRow {
202 pub student: String,
203 /// `bilissel_talep` | `dikkat_tuzagi` | `okuma_yuku` (production only).
204 pub dimension: String,
205 pub label: String,
206 pub n_answers: i64,
207 pub n_correct: i64,
208 pub accuracy: f64,
209 pub overall_n_answers: i64,
210 pub overall_accuracy: f64,
211 pub contrast: f64,
212 /// `none` | `exploratory` | `stable`.
213 pub confidence: String,
214 pub computed_at: i64,
215 pub retain_until: i64,
216}
217
218/// One compute run's ledger row, with the run's own children.
219#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
220pub struct RunRow {
221 /// `YYYY-MM-DD` (TR day). The primary key: a re-run of the same night
222 /// overwrites rather than duplicating.
223 pub run_day: String,
224 pub started_at: i64,
225 #[serde(default)]
226 pub finished_at: Option<i64>,
227 /// `running` | `ok` | `partial` | `failed` | `skipped`.
228 pub status: String,
229 #[serde(default)]
230 pub duration_ms: Option<i64>,
231 pub students_total: i64,
232 pub students_ok: i64,
233 pub students_failed: i64,
234 pub students_skipped: i64,
235 pub rows_written: i64,
236 pub budget_exceeded: bool,
237 pub budget_ms: i64,
238 pub retain_until: i64,
239 /// Students the budget ran out on — the next run's starting point.
240 #[serde(default)]
241 pub pending_students: Vec<String>,
242 /// Modules that failed in this run.
243 #[serde(default)]
244 pub failed_modules: Vec<String>,
245}
246
247// ---- the request/receipt envelopes ----------------------------------------
248
249/// `insight.summary.upsert` / `POST /insights/summaries`.
250#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
251pub struct SummaryWriteRequest {
252 pub rows: Vec<SummaryRow>,
253}
254
255/// `insight.recommendation.upsert` / `POST /insights/recommendations`.
256#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
257pub struct RecommendationWriteRequest {
258 pub rows: Vec<RecommendationRow>,
259}
260
261/// `insight.segment.upsert` / `POST /insights/segments`.
262#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
263pub struct SegmentWriteRequest {
264 pub rows: Vec<SegmentRow>,
265}
266
267/// `insight.profile.upsert` / `POST /insights/profiles`.
268#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
269pub struct ProfileWriteRequest {
270 pub rows: Vec<ProfileRow>,
271}
272
273/// `insight.run.upsert` / `POST /insights/runs`.
274#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
275pub struct RunWriteRequest {
276 pub run: RunRow,
277}
278
279/// `insight.departed.purge` / `POST /insights/purge`. The **active** roster:
280/// every student not named loses their derived rows.
281#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
282pub struct PurgeRequest {
283 pub students: Vec<String>,
284}
285
286/// What a bulk write did: rows written, and (for recommendations only) rows
287/// the service's own evidence rule kept out.
288#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
289pub struct WriteReceipt {
290 pub written: u64,
291 #[serde(default, skip_serializing_if = "is_zero")]
292 pub rejected: u64,
293}
294
295fn is_zero(value: &u64) -> bool {
296 *value == 0
297}
298
299/// The freshest run's pending students, in the service's order.
300#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
301pub struct PendingList {
302 pub students: Vec<String>,
303}
304
305/// The per-table verdict of a sweep or a purge, keyed by table name — the
306/// shape the service's CLI prints and exits non-zero on.
307#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
308pub struct TableVerdicts {
309 pub tables: BTreeMap<String, bool>,
310}
311
312/// The deployment's active schools, as hyphenated uuids.
313#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
314pub struct SchoolDirectory {
315 pub schools: Vec<String>,
316}
317
318/// One school's own identity, as a rendered report prints it. The bridge
319/// frame already names the school by uuid, and a document that reaches a
320/// manager's screen also carries the display name. The control row is the
321/// only authority on it.
322#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
323pub struct ReportSchool {
324 /// `school.id`, hyphenated.
325 pub id: String,
326 pub name: String,
327}
328
329/// One class (şube) as a rendered document labels it: the id the summaries'
330/// own evidence carries, and the display name a reader should see in its
331/// place. A document that prints the id instead is a machine identifier on
332/// the most human-facing artifact the product ships.
333#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
334pub struct ClassLabel {
335 pub id: String,
336 pub name: String,
337}
338
339// ---- shared validation -----------------------------------------------------
340
341/// Refuse a batch past [`MAX_INSIGHT_BATCH_ROWS`] rather than taking it
342/// piecemeal: a batch is the unit the service retries, so accepting part of
343/// one would turn its retry into a duplicate.
344fn check_batch(field: &'static str, rows: &[impl Sized]) -> Result<(), AppError> {
345 if rows.len() > MAX_INSIGHT_BATCH_ROWS {
346 return Err(AppError::PayloadTooLarge(format!(
347 "{field}: {} rows is over the ceiling of {MAX_INSIGHT_BATCH_ROWS} rows per call",
348 rows.len()
349 )));
350 }
351 Ok(())
352}
353
354/// A foreign-key violation is a payload error here, not a server fault: the
355/// statement named a row this school's database does not have (most often an
356/// id belonging to another school), and the caller can fix it.
357fn as_validation(err: AppError) -> AppError {
358 match &err {
359 AppError::Db(source) if foreign_key_violation(source) => {
360 AppError::Validation(ValidationError::Invalid {
361 field: "rows",
362 reason: "a referenced row does not exist in this school",
363 })
364 }
365 _ => err,
366 }
367}
368
369/// One hyphenated uuid from the wire. Ids cross the bridge as strings — the
370/// `uuid` crate's serde support is not enabled here, and a string that is not
371/// a uuid should read as a field error, not as a decode failure with no field.
372fn parse_uuid(field: &'static str, value: &str) -> Result<Uuid, AppError> {
373 Uuid::parse_str(value).map_err(|_| {
374 AppError::Validation(ValidationError::Invalid {
375 field,
376 reason: "must be a hyphenated uuid",
377 })
378 })
379}
380
381/// `YYYY-MM-DD`, the ledger's key. Checked here so a malformed day is the
382/// caller's `invalid_payload` and not a CHECK violation dressed as a `500`.
383/// The report doors share it: a run day shapes a blob key there, and a
384/// caller-supplied path segment that shapes a path is validated before it is
385/// joined.
386pub fn run_day_ok(day: &str) -> bool {
387 let bytes = day.as_bytes();
388 bytes.len() == 10
389 && bytes
390 .iter()
391 .enumerate()
392 .all(|(i, b)| if matches!(i, 4 | 7) { *b == b'-' } else { b.is_ascii_digit() })
393}
394
395// ---- writes ----------------------------------------------------------------
396
397/// Store a batch of student summaries, replacing each student's attention
398/// items. One transaction: a batch lands whole or not at all.
399pub async fn write_summaries(db: &Database, rows: Vec<SummaryRow>) -> Result<WriteReceipt, AppError> {
400 check_batch("rows", &rows)?;
401 let written = rows.len() as u64;
402 tx_with_retry(db, false, async move |tx| write_summaries_in(tx, &rows).await)
403 .await
404 .map_err(as_validation)?;
405 Ok(WriteReceipt {
406 written,
407 rejected: 0,
408 })
409}
410
411/// The transaction body of [`write_summaries`], a named fn rather than an async
412/// closure: an `AsyncFnMut` closure whose future does the work trips rustc's
413/// "implementation of `Send` is not general enough" (see `tx_with_retry`).
414async fn write_summaries_in(tx: &mut sqlx::PgConnection, rows: &[SummaryRow]) -> Result<(), AppError> {
415
416 for row in rows {
417 let student = parse_uuid("student", &row.student)?;
418 sqlx::query!(
419 "INSERT INTO zeka_student_summary
420 (student, marks, attendance, submission, study, confidence,
421 computed_at, retain_until)
422 VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
423 ON CONFLICT (student) DO UPDATE SET
424 marks = EXCLUDED.marks, attendance = EXCLUDED.attendance,
425 submission = EXCLUDED.submission, study = EXCLUDED.study,
426 confidence = EXCLUDED.confidence, computed_at = EXCLUDED.computed_at,
427 retain_until = EXCLUDED.retain_until",
428 student,
429 row.marks.clone(),
430 row.attendance.clone(),
431 row.submission.clone(),
432 row.study.clone(),
433 row.confidence,
434 row.computed_at,
435 row.retain_until,
436 )
437 .execute(&mut *tx)
438 .await?;
439 sqlx::query!(
440 "DELETE FROM zeka_attention_item WHERE student = $1",
441 student,
442 )
443 .execute(&mut *tx)
444 .await?;
445 for (ord, item) in row.attention.iter().enumerate() {
446 let course = item
447 .course
448 .as_deref()
449 .map(|id| parse_uuid("course", id))
450 .transpose()?;
451 sqlx::query!(
452 "INSERT INTO zeka_attention_item
453 (student, trigger, course, fact, window_from, window_to, evidence, ord)
454 VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
455 student,
456 item.trigger,
457 course,
458 item.fact,
459 item.window_from,
460 item.window_to,
461 item.evidence.clone(),
462 ord as i16,
463 )
464 .execute(&mut *tx)
465 .await?;
466 }
467 }
468 Ok(())
469}
470
471/// The service's own evidence rule, applied where the write happens: a card
472/// whose evidence carries nothing but its limitation is not a finding. Such a
473/// row is counted `rejected` in the receipt and left unwritten — silently
474/// dropping it would be the one thing this rule exists to prevent.
475fn carries_evidence(evidence: &JsonValue) -> bool {
476 evidence.as_object().is_some_and(|object| {
477 object
478 .iter()
479 .any(|(key, value)| key != "limitation" && !value.is_null())
480 })
481}
482
483/// Store a batch of recommendation cards. The backend mints each row's id:
484/// an id belongs to whoever writes the row, and that is now this process.
485pub async fn write_recommendations(
486 db: &Database,
487 rows: Vec<RecommendationRow>,
488) -> Result<WriteReceipt, AppError> {
489 check_batch("rows", &rows)?;
490 let (written, rejected) =
491 tx_with_retry(db, false, async move |tx| write_recommendations_in(tx, &rows).await)
492 .await
493 .map_err(as_validation)?;
494 Ok(WriteReceipt { written, rejected })
495}
496
497/// The service's own evidence rule, applied where the write happens: a card
498/// whose evidence carries nothing but its limitation is not a finding. Such a
499/// row is counted `rejected` and left unwritten — silently dropping it would
500/// be the one thing this rule exists to prevent. Returns `(written, rejected)`.
501async fn write_recommendations_in(
502 tx: &mut sqlx::PgConnection,
503 rows: &[RecommendationRow],
504) -> Result<(u64, u64), AppError> {
505 let mut written = 0u64;
506 let mut rejected = 0u64;
507 for row in rows {
508 if !carries_evidence(&row.evidence) {
509 rejected += 1;
510 continue;
511 }
512 let evidence = merge_limitation(&row.evidence, row.limitation.as_deref())?;
513 let audience = parse_uuid("audience", &row.audience)?;
514 let about = row
515 .about
516 .as_deref()
517 .map(|id| parse_uuid("about", id))
518 .transpose()?;
519 let course = row
520 .course
521 .as_deref()
522 .map(|id| parse_uuid("course", id))
523 .transpose()?;
524 sqlx::query!(
525 "INSERT INTO zeka_recommendation
526 (id, audience, product, rule_id, rule_version, scope, about, audience_role,
527 course, evidence, confidence, created_at, expires_at, retain_until)
528 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
529 ON CONFLICT (audience, product, rule_id, about, scope) DO UPDATE SET
530 rule_version = EXCLUDED.rule_version,
531 audience_role = EXCLUDED.audience_role,
532 course = EXCLUDED.course,
533 evidence = EXCLUDED.evidence,
534 confidence = EXCLUDED.confidence,
535 created_at = EXCLUDED.created_at,
536 expires_at = EXCLUDED.expires_at,
537 retain_until = EXCLUDED.retain_until",
538 next_uuid(),
539 audience,
540 row.product,
541 row.rule_id,
542 row.rule_version,
543 row.scope,
544 about,
545 row.audience_role,
546 course,
547 evidence,
548 row.confidence,
549 row.computed_at,
550 row.expires_at,
551 row.retain_until,
552 )
553 .execute(&mut *tx)
554 .await?;
555 written += 1;
556 }
557 Ok((written, rejected))
558}
559
560/// The stored evidence object: the payload's own object with `limitation`
561/// written into it, exactly as the service kept it. A payload whose `evidence`
562/// is not an object cannot be merged and is refused.
563fn merge_limitation(
564 evidence: &JsonValue,
565 limitation: Option<&str>,
566) -> Result<JsonValue, AppError> {
567 let mut object = evidence
568 .as_object()
569 .cloned()
570 .ok_or(AppError::Validation(ValidationError::Invalid {
571 field: "evidence",
572 reason: "must be a JSON object",
573 }))?;
574 if let Some(limitation) = limitation {
575 object.insert(
576 "limitation".to_string(),
577 JsonValue::String(limitation.to_string()),
578 );
579 }
580 Ok(JsonValue::Object(object))
581}
582
583/// Store a batch of question segments, replacing each question's dimension
584/// split.
585pub async fn write_segments(db: &Database, rows: Vec<SegmentRow>) -> Result<WriteReceipt, AppError> {
586 check_batch("rows", &rows)?;
587 let written = rows.len() as u64;
588 tx_with_retry(db, false, async move |tx| write_segments_in(tx, &rows).await)
589 .await
590 .map_err(as_validation)?;
591 Ok(WriteReceipt {
592 written,
593 rejected: 0,
594 })
595}
596
597/// The transaction body of [`write_segments`], a named fn rather than an async
598/// closure: an `AsyncFnMut` closure whose future does the work trips rustc's
599/// "implementation of `Send` is not general enough" (see `tx_with_retry`).
600async fn write_segments_in(tx: &mut sqlx::PgConnection, rows: &[SegmentRow]) -> Result<(), AppError> {
601
602 for row in rows {
603 let question = parse_uuid("question", &row.question)?;
604 let exam = parse_uuid("exam", &row.exam)?;
605 let course = parse_uuid("course", &row.course)?;
606 let subject = parse_uuid("subject", &row.subject)?;
607 sqlx::query!(
608 "INSERT INTO zeka_question_segment
609 (question, exam, course, subject, bilissel_talep, dikkat_tuzagi, okuma_yuku,
610 adim_sayisi, confidence_bilissel_talep, confidence_dikkat_tuzagi,
611 confidence_okuma_yuku, confidence_adim_sayisi, confidence, trap_choice,
612 rationale, model, prompt_version, variant, computed_at, retain_until)
613 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10,
614 $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)
615 ON CONFLICT (question) DO UPDATE SET
616 exam = EXCLUDED.exam, course = EXCLUDED.course, subject = EXCLUDED.subject,
617 bilissel_talep = EXCLUDED.bilissel_talep,
618 dikkat_tuzagi = EXCLUDED.dikkat_tuzagi,
619 okuma_yuku = EXCLUDED.okuma_yuku,
620 adim_sayisi = EXCLUDED.adim_sayisi,
621 confidence_bilissel_talep = EXCLUDED.confidence_bilissel_talep,
622 confidence_dikkat_tuzagi = EXCLUDED.confidence_dikkat_tuzagi,
623 confidence_okuma_yuku = EXCLUDED.confidence_okuma_yuku,
624 confidence_adim_sayisi = EXCLUDED.confidence_adim_sayisi,
625 confidence = EXCLUDED.confidence, trap_choice = EXCLUDED.trap_choice,
626 rationale = EXCLUDED.rationale, model = EXCLUDED.model,
627 prompt_version = EXCLUDED.prompt_version, variant = EXCLUDED.variant,
628 computed_at = EXCLUDED.computed_at, retain_until = EXCLUDED.retain_until",
629 question,
630 exam,
631 course,
632 subject,
633 row.labels.bilissel_talep,
634 row.labels.dikkat_tuzagi,
635 row.labels.okuma_yuku,
636 row.labels.adim_sayisi,
637 row.confidences.bilissel_talep,
638 row.confidences.dikkat_tuzagi,
639 row.confidences.okuma_yuku,
640 row.confidences.adim_sayisi,
641 row.confidence,
642 row.trap_choice,
643 row.rationale,
644 row.model,
645 row.prompt_version,
646 row.variant,
647 row.computed_at,
648 row.retain_until,
649 )
650 .execute(&mut *tx)
651 .await?;
652 // A dimension that moved between downstream and experimental (or
653 // a rubric version that dropped one) must not leave its old row
654 // behind.
655 sqlx::query!(
656 "DELETE FROM zeka_question_segment_dimension WHERE question = $1",
657 question,
658 )
659 .execute(&mut *tx)
660 .await?;
661 let mut ord: i16 = 0;
662 for (role, names) in [
663 ("downstream", &row.downstream_dimensions),
664 ("experimental", &row.experimental_dimensions),
665 ] {
666 for name in names {
667 sqlx::query!(
668 "INSERT INTO zeka_question_segment_dimension
669 (question, dimension, role, ord)
670 VALUES ($1, $2, $3, $4)",
671 question,
672 name,
673 role,
674 ord,
675 )
676 .execute(&mut *tx)
677 .await?;
678 ord += 1;
679 }
680 }
681 }
682 Ok(())
683}
684
685/// Store a batch of student segment profiles.
686pub async fn write_profiles(db: &Database, rows: Vec<ProfileRow>) -> Result<WriteReceipt, AppError> {
687 check_batch("rows", &rows)?;
688 let written = rows.len() as u64;
689 tx_with_retry(db, false, async move |tx| write_profiles_in(tx, &rows).await)
690 .await
691 .map_err(as_validation)?;
692 Ok(WriteReceipt {
693 written,
694 rejected: 0,
695 })
696}
697
698/// The transaction body of [`write_profiles`], a named fn rather than an async
699/// closure: an `AsyncFnMut` closure whose future does the work trips rustc's
700/// "implementation of `Send` is not general enough" (see `tx_with_retry`).
701async fn write_profiles_in(tx: &mut sqlx::PgConnection, rows: &[ProfileRow]) -> Result<(), AppError> {
702
703 for row in rows {
704 let student = parse_uuid("student", &row.student)?;
705 sqlx::query!(
706 "INSERT INTO zeka_student_segment_profile
707 (student, dimension, label, n_answers, n_correct, accuracy,
708 overall_n_answers, overall_accuracy, contrast, confidence,
709 computed_at, retain_until)
710 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
711 ON CONFLICT (student, dimension, label) DO UPDATE SET
712 n_answers = EXCLUDED.n_answers, n_correct = EXCLUDED.n_correct,
713 accuracy = EXCLUDED.accuracy,
714 overall_n_answers = EXCLUDED.overall_n_answers,
715 overall_accuracy = EXCLUDED.overall_accuracy,
716 contrast = EXCLUDED.contrast, confidence = EXCLUDED.confidence,
717 computed_at = EXCLUDED.computed_at, retain_until = EXCLUDED.retain_until",
718 student,
719 row.dimension,
720 row.label,
721 row.n_answers,
722 row.n_correct,
723 row.accuracy,
724 row.overall_n_answers,
725 row.overall_accuracy,
726 row.contrast,
727 row.confidence,
728 row.computed_at,
729 row.retain_until,
730 )
731 .execute(&mut *tx)
732 .await?;
733 }
734 Ok(())
735}
736
737/// Store one run's ledger row, replacing the run's pending/failed children.
738pub async fn write_run(db: &Database, run: RunRow) -> Result<WriteReceipt, AppError> {
739 if !run_day_ok(&run.run_day) {
740 return Err(AppError::Validation(ValidationError::Invalid {
741 field: "run_day",
742 reason: "must be YYYY-MM-DD",
743 }));
744 }
745 let pending: Vec<Uuid> = run
746 .pending_students
747 .iter()
748 .map(|id| parse_uuid("pending_students", id))
749 .collect::<Result<_, _>>()?;
750 tx_with_retry(db, false, async move |tx| write_run_in(tx, &run, &pending).await)
751 .await
752 .map_err(as_validation)?;
753 Ok(WriteReceipt {
754 written: 1,
755 rejected: 0,
756 })
757}
758
759/// The transaction body of [`write_run`], a named fn rather than an async
760/// closure: an `AsyncFnMut` closure whose future does the work trips rustc's
761/// "implementation of `Send` is not general enough" (see `tx_with_retry`).
762async fn write_run_in(tx: &mut sqlx::PgConnection, run: &RunRow, pending: &[Uuid]) -> Result<(), AppError> {
763
764 sqlx::query!(
765 "INSERT INTO zeka_run
766 (run_day, started_at, finished_at, status, duration_ms, students_total,
767 students_ok, students_failed, students_skipped, rows_written,
768 budget_exceeded, budget_ms, retain_until)
769 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
770 ON CONFLICT (run_day) DO UPDATE SET
771 started_at = EXCLUDED.started_at, finished_at = EXCLUDED.finished_at,
772 status = EXCLUDED.status, duration_ms = EXCLUDED.duration_ms,
773 students_total = EXCLUDED.students_total, students_ok = EXCLUDED.students_ok,
774 students_failed = EXCLUDED.students_failed,
775 students_skipped = EXCLUDED.students_skipped,
776 rows_written = EXCLUDED.rows_written,
777 budget_exceeded = EXCLUDED.budget_exceeded, budget_ms = EXCLUDED.budget_ms,
778 retain_until = EXCLUDED.retain_until",
779 run.run_day,
780 run.started_at,
781 run.finished_at,
782 run.status,
783 run.duration_ms,
784 run.students_total,
785 run.students_ok,
786 run.students_failed,
787 run.students_skipped,
788 run.rows_written,
789 run.budget_exceeded,
790 run.budget_ms,
791 run.retain_until,
792 )
793 .execute(&mut *tx)
794 .await?;
795 sqlx::query!("DELETE FROM zeka_run_pending WHERE run = $1", run.run_day)
796 .execute(&mut *tx)
797 .await?;
798 sqlx::query!(
799 "DELETE FROM zeka_run_failed_module WHERE run = $1",
800 run.run_day
801 )
802 .execute(&mut *tx)
803 .await?;
804 for (ord, student) in pending.iter().enumerate() {
805 sqlx::query!(
806 "INSERT INTO zeka_run_pending (run, student, ord) VALUES ($1, $2, $3)",
807 run.run_day,
808 student,
809 ord as i32,
810 )
811 .execute(&mut *tx)
812 .await?;
813 }
814 for (ord, module) in run.failed_modules.iter().enumerate() {
815 sqlx::query!(
816 "INSERT INTO zeka_run_failed_module (run, module, ord) VALUES ($1, $2, $3)",
817 run.run_day,
818 module,
819 ord as i16,
820 )
821 .execute(&mut *tx)
822 .await?;
823 }
824 Ok(())
825}
826
827// ---- reads -----------------------------------------------------------------
828
829/// The freshest run's pending students, in the order the run recorded them.
830///
831/// Refused rather than clipped past [`MAX_INSIGHT_PENDING_STUDENTS`]: the
832/// service resumes its next run from this list, so a shortened one would drop
833/// students silently. The read asks for one row past the ceiling so the
834/// refusal never has to materialize the whole list.
835pub async fn last_pending(db: &Database) -> Result<PendingList, AppError> {
836 let ceiling = MAX_INSIGHT_PENDING_STUDENTS as i64;
837 let rows = sqlx::query_scalar!(
838 "SELECT p.student FROM zeka_run_pending p
839 JOIN zeka_run r ON r.run_day = p.run
840 WHERE r.run_day = (SELECT run_day FROM zeka_run
841 ORDER BY started_at DESC, run_day DESC LIMIT 1)
842 ORDER BY p.ord
843 LIMIT $1",
844 ceiling + 1,
845 )
846 .fetch_all(db)
847 .await?;
848 if rows.len() > MAX_INSIGHT_PENDING_STUDENTS {
849 return Err(AppError::PayloadTooLarge(format!(
850 "students: the freshest run left more than {MAX_INSIGHT_PENDING_STUDENTS} students pending"
851 )));
852 }
853 Ok(PendingList {
854 students: rows.iter().map(|id| id.to_string()).collect(),
855 })
856}
857
858/// The deployment's active schools, as hyphenated uuids — the one read that
859/// is not scoped to a school, because it is how a shared AI fleet learns
860/// which schools exist.
861pub async fn active_schools(control: &Database) -> Result<SchoolDirectory, AppError> {
862 let schools = sqlx::query_scalar!(
863 "SELECT id FROM school WHERE status = 'active' ORDER BY name"
864 )
865 .fetch_all(control)
866 .await?;
867 Ok(SchoolDirectory {
868 schools: schools.into_iter().map(|id| id.to_string()).collect(),
869 })
870}
871
872/// One school's identity row, by id. `None` only for an id the control
873/// database does not hold — a resolved tenant always has one, so a caller
874/// reads that as an internal fault, not as a refusal.
875pub async fn school_identity(
876 control: &Database,
877 id: &SchoolId,
878) -> Result<Option<ReportSchool>, AppError> {
879 let row = sqlx::query!("SELECT id, name FROM school WHERE id = $1", id.uuid())
880 .fetch_optional(control)
881 .await?;
882 Ok(row.map(|row| ReportSchool {
883 id: row.id.to_string(),
884 name: row.name,
885 }))
886}
887
888/// Every class (şube) of the school, id and display name, in name order.
889///
890/// The service's summaries carry class ids inside their own evidence objects,
891/// so a document that groups by class has only those ids to print — and an id
892/// is not a label. This is the lookup that turns them into names. It is sent
893/// whole rather than narrowed to the ids the current rows mention: a school's
894/// class list is tens of rows, and a partial list would make the renderer's
895/// fallback depend on how complete this read's filters were.
896pub async fn all_classes(db: &Database) -> Result<Vec<ClassLabel>, AppError> {
897 let rows = sqlx::query!("SELECT id, name FROM class_group ORDER BY name, id")
898 .fetch_all(db)
899 .await?;
900 Ok(rows
901 .into_iter()
902 .map(|row| ClassLabel {
903 id: row.id.to_string(),
904 name: row.name,
905 })
906 .collect())
907}
908
909// ---- the school-wide reads the report payload carries -----------------------
910//
911// Every read above is per-student or per-audience, because that is every
912// reader this nest had. A *document* about the school is the first caller that
913// needs the whole row set at once, so these four project each table straight
914// into the wire rows the bridge payload carries ([`SummaryRow`],
915// [`RecommendationRow`], [`ProfileRow`], [`RunRow`]) — one mapping, in one
916// place, shared by SQL and the wire. No filters: the document's own reader
917// (the service's report package) decides what it shows, and a backend that
918// pre-filtered would be a second, silent author of the report.
919
920/// Every stored summary with its attention items, in student order. The
921/// attention list is one query for the whole set, grouped by student — not
922/// one query per summary.
923pub async fn all_summaries(db: &Database) -> Result<Vec<SummaryRow>, AppError> {
924 let rows = sqlx::query!(
925 r#"SELECT student,
926 marks AS "marks?: SqlJson<JsonValue>",
927 attendance AS "attendance?: SqlJson<JsonValue>",
928 submission AS "submission?: SqlJson<JsonValue>",
929 study AS "study?: SqlJson<JsonValue>",
930 confidence, computed_at, retain_until
931 FROM zeka_student_summary ORDER BY student"#
932 )
933 .fetch_all(db)
934 .await?;
935 let mut attention: BTreeMap<Uuid, Vec<AttentionRow>> = BTreeMap::new();
936 for row in sqlx::query!(
937 r#"SELECT student, trigger, course, fact, window_from, window_to,
938 evidence AS "evidence: SqlJson<JsonValue>"
939 FROM zeka_attention_item ORDER BY student, ord"#
940 )
941 .fetch_all(db)
942 .await?
943 {
944 attention.entry(row.student).or_default().push(AttentionRow {
945 trigger: row.trigger,
946 course: row.course.map(|course| course.to_string()),
947 fact: row.fact,
948 window_from: row.window_from,
949 window_to: row.window_to,
950 evidence: row.evidence.0,
951 });
952 }
953 Ok(rows
954 .into_iter()
955 .map(|row| SummaryRow {
956 attention: attention.remove(&row.student).unwrap_or_default(),
957 student: row.student.to_string(),
958 marks: row.marks.map(|json| json.0),
959 attendance: row.attendance.map(|json| json.0),
960 submission: row.submission.map(|json| json.0),
961 study: row.study.map(|json| json.0),
962 confidence: row.confidence,
963 computed_at: row.computed_at,
964 retain_until: row.retain_until,
965 })
966 .collect())
967}
968
969/// Every stored card, whatever its audience, in a stable order. The write
970/// merged each row's `limitation` into its stored evidence object, so the
971/// read leaves the [write-side](RecommendationRow::limitation) field empty —
972/// a second copy here could only disagree with the one inside `evidence`.
973///
974/// The wire row carries no `dismissed_at`, so the stored dismissal trail
975/// (`dismissed_at`/`dismiss_by`/`dismiss_reason` on the table) does not
976/// travel: a consumer that gates on dismissal cannot fire on this read. That
977/// is a known gap of the report payload's contract — the reader that filters
978/// dismissals is the per-audience read ([`crate::web::insights`]), and
979/// widening the row here is a contract change this lane does not make.
980pub async fn all_recommendations(db: &Database) -> Result<Vec<RecommendationRow>, AppError> {
981 let rows = sqlx::query!(
982 r#"SELECT audience, product, rule_id, rule_version, scope, about, audience_role,
983 course, evidence AS "evidence: SqlJson<JsonValue>",
984 confidence, created_at, expires_at, retain_until
985 FROM zeka_recommendation ORDER BY audience, created_at, rule_id"#
986 )
987 .fetch_all(db)
988 .await?;
989 Ok(rows
990 .into_iter()
991 .map(|row| RecommendationRow {
992 audience: row.audience.to_string(),
993 product: row.product,
994 rule_id: row.rule_id,
995 rule_version: row.rule_version,
996 scope: row.scope,
997 about: row.about.map(|about| about.to_string()),
998 audience_role: row.audience_role,
999 course: row.course.map(|course| course.to_string()),
1000 evidence: row.evidence.0,
1001 limitation: None,
1002 confidence: row.confidence,
1003 // The column is `created_at`; the wire row spells it `computed_at`,
1004 // and the write maps the same pair the same way.
1005 computed_at: row.created_at,
1006 expires_at: row.expires_at,
1007 retain_until: row.retain_until,
1008 })
1009 .collect())
1010}
1011
1012/// Every stored segment profile, in student order. Noise rows (`confidence =
1013/// 'none'`) are included: this read feeds a document, and the display floor is
1014/// the reader's rule, applied where the reader applies it.
1015pub async fn all_profiles(db: &Database) -> Result<Vec<ProfileRow>, AppError> {
1016 let rows = sqlx::query!(
1017 r#"SELECT student, dimension, label, n_answers, n_correct, accuracy,
1018 overall_n_answers, overall_accuracy, contrast, confidence,
1019 computed_at, retain_until
1020 FROM zeka_student_segment_profile ORDER BY student, dimension, label"#
1021 )
1022 .fetch_all(db)
1023 .await?;
1024 Ok(rows
1025 .into_iter()
1026 .map(|row| ProfileRow {
1027 student: row.student.to_string(),
1028 dimension: row.dimension,
1029 label: row.label,
1030 n_answers: row.n_answers,
1031 n_correct: row.n_correct,
1032 accuracy: row.accuracy,
1033 overall_n_answers: row.overall_n_answers,
1034 overall_accuracy: row.overall_accuracy,
1035 contrast: row.contrast,
1036 confidence: row.confidence,
1037 computed_at: row.computed_at,
1038 retain_until: row.retain_until,
1039 })
1040 .collect())
1041}
1042
1043/// How many ledger rows a report carries: the named day plus recent context.
1044/// Deliberately small — the ledger is context for the document, which is
1045/// about one day, not a ledger dump.
1046const REPORT_RUNS: i64 = 5;
1047
1048/// The run ledger a report carries, with each run's children. The named day
1049/// leads when it exists (a report about it must be able to show it even if it
1050/// has scrolled out of the newest rows), then the newest days follow.
1051pub async fn runs_for_report(db: &Database, run_day: &str) -> Result<Vec<RunRow>, AppError> {
1052 let rows = sqlx::query!(
1053 r#"SELECT run_day, started_at, finished_at, status, duration_ms,
1054 students_total, students_ok, students_failed, students_skipped,
1055 rows_written, budget_exceeded, budget_ms, retain_until
1056 FROM zeka_run
1057 ORDER BY (run_day = $1) DESC, started_at DESC, run_day DESC
1058 LIMIT $2"#,
1059 run_day,
1060 REPORT_RUNS,
1061 )
1062 .fetch_all(db)
1063 .await?;
1064 let days: Vec<String> = rows.iter().map(|row| row.run_day.clone()).collect();
1065 let mut pending: BTreeMap<String, Vec<String>> = BTreeMap::new();
1066 for row in sqlx::query!(
1067 r#"SELECT run, student FROM zeka_run_pending
1068 WHERE run = ANY($1) ORDER BY run, ord"#,
1069 &days
1070 )
1071 .fetch_all(db)
1072 .await?
1073 {
1074 pending
1075 .entry(row.run)
1076 .or_default()
1077 .push(row.student.to_string());
1078 }
1079 let mut failed: BTreeMap<String, Vec<String>> = BTreeMap::new();
1080 for row in sqlx::query!(
1081 r#"SELECT run, module FROM zeka_run_failed_module
1082 WHERE run = ANY($1) ORDER BY run, ord"#,
1083 &days
1084 )
1085 .fetch_all(db)
1086 .await?
1087 {
1088 failed.entry(row.run).or_default().push(row.module);
1089 }
1090 Ok(rows
1091 .into_iter()
1092 .map(|row| RunRow {
1093 pending_students: pending.remove(&row.run_day).unwrap_or_default(),
1094 failed_modules: failed.remove(&row.run_day).unwrap_or_default(),
1095 run_day: row.run_day,
1096 started_at: row.started_at,
1097 finished_at: row.finished_at,
1098 status: row.status,
1099 duration_ms: row.duration_ms,
1100 students_total: row.students_total,
1101 students_ok: row.students_ok,
1102 students_failed: row.students_failed,
1103 students_skipped: row.students_skipped,
1104 rows_written: row.rows_written,
1105 budget_exceeded: row.budget_exceeded,
1106 budget_ms: row.budget_ms,
1107 retain_until: row.retain_until,
1108 })
1109 .collect())
1110}
1111
1112// ---- retention -------------------------------------------------------------
1113
1114/// The nine tables a sweep walks, children before their parents: the foreign
1115/// keys are `ON DELETE NO ACTION`, so a parent cannot go while a child row
1116/// still names it.
1117const SWEEP_CHILDREN: &[(&str, &str, &str)] = &[
1118 ("zeka_attention_item", "zeka_student_summary", "student"),
1119 ("zeka_question_segment_dimension", "zeka_question_segment", "question"),
1120 ("zeka_run_pending", "zeka_run", "run"),
1121 ("zeka_run_failed_module", "zeka_run", "run"),
1122];
1123
1124/// The tables that carry their own `retain_until`.
1125const SWEEP_PARENTS: &[&str] = &[
1126 "zeka_student_summary",
1127 "zeka_recommendation",
1128 "zeka_run",
1129 "zeka_question_segment",
1130 "zeka_student_segment_profile",
1131];
1132
1133/// Delete every row whose retention window has closed. `now_ms` is the
1134/// backend's own clock — one clock decides expiry, never the caller's.
1135///
1136/// One table at a time, each in its own statement, and a table whose delete
1137/// fails is reported `false` rather than aborting the rest: a sweep is
1138/// housekeeping, and losing the whole night's cleanup because one table is
1139/// locked would leave every other table's expired rows in place. The caller
1140/// reads the verdict per table, exactly as the service's own sweep did.
1141pub async fn sweep(db: &Database, now_ms: i64) -> Result<TableVerdicts, AppError> {
1142 let mut tables = BTreeMap::new();
1143 for (child, parent, key) in SWEEP_CHILDREN {
1144 let parent_key = if *parent == "zeka_run" { "run_day" } else { *key };
1145 let sql = format!(
1146 "DELETE FROM {child} WHERE {key} IN \
1147 (SELECT {parent_key} FROM {parent} WHERE retain_until < $1)"
1148 );
1149 tables.insert(
1150 (*child).to_string(),
1151 run_sweep_statement(db, &sql, now_ms).await,
1152 );
1153 }
1154 for table in SWEEP_PARENTS {
1155 let sql = format!("DELETE FROM {table} WHERE retain_until < $1");
1156 tables.insert((*table).to_string(), run_sweep_statement(db, &sql, now_ms).await);
1157 }
1158 Ok(TableVerdicts { tables })
1159}
1160
1161/// The table names come from [`SWEEP_CHILDREN`]/[`SWEEP_PARENTS`], never from
1162/// a caller — the only dynamic SQL in this module, and the reason
1163/// [`AssertSqlSafe`] is licensed here.
1164async fn run_sweep_statement(db: &Database, sql: &str, now_ms: i64) -> bool {
1165 sqlx::query(AssertSqlSafe(sql.to_string()))
1166 .bind(now_ms)
1167 .execute(db)
1168 .await
1169 .is_ok()
1170}
1171
1172/// Delete the derived rows of everyone who is no longer on the roster. One
1173/// transaction: a purge is a decision about a cohort, not a per-row repair.
1174///
1175/// The empty list is **refused**, never obeyed: an empty roster is almost
1176/// always a fetch that failed, and reading it as "nobody is enrolled any
1177/// more" would delete every student's derived data in one call.
1178pub async fn purge_departed(
1179 db: &Database,
1180 students: Vec<String>,
1181) -> Result<TableVerdicts, AppError> {
1182 if students.is_empty() {
1183 return Err(AppError::Validation(ValidationError::Empty("students")));
1184 }
1185 if students.len() > MAX_INSIGHT_PURGE_STUDENTS {
1186 return Err(AppError::PayloadTooLarge(format!(
1187 "students: {} ids is over the ceiling of {MAX_INSIGHT_PURGE_STUDENTS} per call",
1188 students.len()
1189 )));
1190 }
1191 let active: Vec<Uuid> = students
1192 .iter()
1193 .map(|id| parse_uuid("students", id))
1194 .collect::<Result<_, _>>()?;
1195 tx_with_retry(db, false, async move |tx| purge_departed_in(tx, &active).await)
1196 .await
1197 .map_err(as_validation)?;
1198
1199 // One transaction, so the verdicts move together: every table succeeded
1200 // or the call was refused above.
1201 let tables = [
1202 "zeka_attention_item",
1203 "zeka_student_summary",
1204 "zeka_student_segment_profile",
1205 "zeka_recommendation",
1206 "zeka_run_pending",
1207 ]
1208 .into_iter()
1209 .map(|table| (table.to_string(), true))
1210 .collect();
1211 Ok(TableVerdicts { tables })
1212}
1213
1214/// The transaction body of [`purge_departed`], a named fn rather than an async
1215/// closure: an `AsyncFnMut` closure whose future does the work trips rustc's
1216/// "implementation of `Send` is not general enough" (see `tx_with_retry`).
1217async fn purge_departed_in(tx: &mut sqlx::PgConnection, active: &[Uuid]) -> Result<(), AppError> {
1218
1219 // Children first (they reference the summary), then the parents.
1220 sqlx::query!(
1221 "DELETE FROM zeka_attention_item WHERE student <> ALL($1)",
1222 active,
1223 )
1224 .execute(&mut *tx)
1225 .await?;
1226 sqlx::query!(
1227 "DELETE FROM zeka_student_summary WHERE student <> ALL($1)",
1228 active,
1229 )
1230 .execute(&mut *tx)
1231 .await?;
1232 sqlx::query!(
1233 "DELETE FROM zeka_student_segment_profile WHERE student <> ALL($1)",
1234 active,
1235 )
1236 .execute(&mut *tx)
1237 .await?;
1238 // Cards about a departed student go; school-wide cards (`about` is
1239 // NULL) are addressed to someone still enrolled and stay.
1240 sqlx::query!(
1241 "DELETE FROM zeka_recommendation
1242 WHERE about IS NOT NULL AND about <> ALL($1)",
1243 active,
1244 )
1245 .execute(&mut *tx)
1246 .await?;
1247 sqlx::query!(
1248 "DELETE FROM zeka_run_pending WHERE student <> ALL($1)",
1249 active,
1250 )
1251 .execute(&mut *tx)
1252 .await?;
1253 Ok(())
1254}