forge
Explore
Log in

Don't you dare go Hollow

Render and serve a school-level report document

Browse files at this commit

541d9b7f2ac9409cf343aba8f7f641a581f4a0d7Ahmet Kaan GümüşParent: 0f55f34
  • feat
    • render and serve a school-level report document
Show full message
📄 feat(insight): render and serve a school-level report document

`insight.report` is the third outbound ZEKA dispatch, and the first that
carries its data: the service may not read a school database, so the backend
reads its own `zeka_*` rows (four new school-wide bulk reads, projected
straight into the serde rows the storage surface already writes) and sends
them in the request. The service renders, the backend stores.

* `POST /insights/runs/{run_day}/report` — manager+, synchronous: build the
  payload, dispatch with `AI_INSIGHT_REPORT_TIMEOUT_SECS`, store the returned
  HTML under the school's own blob directory (`zeka_report/<day>.html`, temp
  name + rename, never a partial file), answer `200` with what was stored.
  A run day with no ledger row is a legal request; the service's `notes` say
  what it found. Its typed refusals map per class: `bad_request` 400,
  `insufficient_rows` 409 `report_empty`, `document_too_large` 413,
  `internal` 500, anything else 409 `report_refused`. An empty document is
  refused, never persisted — a blank page must not read as a report.
* `GET /insights/runs/{run_day}/report` — manager+, streams the stored
  document (`text/html; charset=utf-8`, nosniff, private no-store);
  `409 report_missing` when nothing was generated, a day the ledger has never
  heard of included.

Both doors share one path (one `routes!(generate_report, serve_report)`), so
no nest or `MODULE_PREFIXES` change; `MIN_PROTECTED` 338 → 340 (derived).
`pump` moves from the podcast nest to `web` as a shared blob-stream helper.

Known gap, reported rather than widened here: the wire `RecommendationRow`
carries no `dismissed_at`, so the service's dismissal gate cannot fire on
this payload.
.sqlx/query-14e1fd9d16713ee60c209e545fb9a2b3ef792d0acfdcecff7c8fd50362454a69.jsonadded+170 -0
@@ -0,0 +1,170 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT audience, product, rule_id, rule_version, scope, about, audience_role,\n course, evidence AS \"evidence: SqlJson<JsonValue>\",\n confidence, created_at, expires_at, retain_until\n FROM zeka_recommendation ORDER BY audience, created_at, rule_id",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "audience",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "zeka_recommendation",
13+ "name": "audience"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "product",
20+ "type_info": "Text",
21+ "origin": {
22+ "Table": {
23+ "table": "zeka_recommendation",
24+ "name": "product"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "rule_id",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "zeka_recommendation",
35+ "name": "rule_id"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "rule_version",
42+ "type_info": "Int8",
43+ "origin": {
44+ "Table": {
45+ "table": "zeka_recommendation",
46+ "name": "rule_version"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "scope",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "zeka_recommendation",
57+ "name": "scope"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "about",
64+ "type_info": "Uuid",
65+ "origin": {
66+ "Table": {
67+ "table": "zeka_recommendation",
68+ "name": "about"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "audience_role",
75+ "type_info": "Text",
76+ "origin": {
77+ "Table": {
78+ "table": "zeka_recommendation",
79+ "name": "audience_role"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "course",
86+ "type_info": "Uuid",
87+ "origin": {
88+ "Table": {
89+ "table": "zeka_recommendation",
90+ "name": "course"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "evidence: SqlJson<JsonValue>",
97+ "type_info": "Jsonb",
98+ "origin": {
99+ "Table": {
100+ "table": "zeka_recommendation",
101+ "name": "evidence"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "confidence",
108+ "type_info": "Text",
109+ "origin": {
110+ "Table": {
111+ "table": "zeka_recommendation",
112+ "name": "confidence"
113+ }
114+ }
115+ },
116+ {
117+ "ordinal": 10,
118+ "name": "created_at",
119+ "type_info": "Int8",
120+ "origin": {
121+ "Table": {
122+ "table": "zeka_recommendation",
123+ "name": "created_at"
124+ }
125+ }
126+ },
127+ {
128+ "ordinal": 11,
129+ "name": "expires_at",
130+ "type_info": "Int8",
131+ "origin": {
132+ "Table": {
133+ "table": "zeka_recommendation",
134+ "name": "expires_at"
135+ }
136+ }
137+ },
138+ {
139+ "ordinal": 12,
140+ "name": "retain_until",
141+ "type_info": "Int8",
142+ "origin": {
143+ "Table": {
144+ "table": "zeka_recommendation",
145+ "name": "retain_until"
146+ }
147+ }
148+ }
149+ ],
150+ "parameters": {
151+ "Left": []
152+ },
153+ "nullable": [
154+ false,
155+ false,
156+ false,
157+ false,
158+ true,
159+ true,
160+ false,
161+ true,
162+ false,
163+ false,
164+ false,
165+ false,
166+ false
167+ ]
168+ },
169+ "hash": "14e1fd9d16713ee60c209e545fb9a2b3ef792d0acfdcecff7c8fd50362454a69"
170+}
.sqlx/query-34ecb6b00feed60a86453a9ef7b6a93569a3e21c0d6a8393871139f95f9612ba.jsonadded+98 -0
@@ -0,0 +1,98 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT student, trigger, course, fact, window_from, window_to,\n evidence AS \"evidence: SqlJson<JsonValue>\"\n FROM zeka_attention_item ORDER BY student, ord",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "student",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "zeka_attention_item",
13+ "name": "student"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "trigger",
20+ "type_info": "Text",
21+ "origin": {
22+ "Table": {
23+ "table": "zeka_attention_item",
24+ "name": "trigger"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "course",
31+ "type_info": "Uuid",
32+ "origin": {
33+ "Table": {
34+ "table": "zeka_attention_item",
35+ "name": "course"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "fact",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "zeka_attention_item",
46+ "name": "fact"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "window_from",
53+ "type_info": "Int8",
54+ "origin": {
55+ "Table": {
56+ "table": "zeka_attention_item",
57+ "name": "window_from"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "window_to",
64+ "type_info": "Int8",
65+ "origin": {
66+ "Table": {
67+ "table": "zeka_attention_item",
68+ "name": "window_to"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "evidence: SqlJson<JsonValue>",
75+ "type_info": "Jsonb",
76+ "origin": {
77+ "Table": {
78+ "table": "zeka_attention_item",
79+ "name": "evidence"
80+ }
81+ }
82+ }
83+ ],
84+ "parameters": {
85+ "Left": []
86+ },
87+ "nullable": [
88+ false,
89+ false,
90+ true,
91+ false,
92+ false,
93+ false,
94+ false
95+ ]
96+ },
97+ "hash": "34ecb6b00feed60a86453a9ef7b6a93569a3e21c0d6a8393871139f95f9612ba"
98+}
.sqlx/query-4a50c4e5b4c369736b0a5b55dfd143b69def99f1e2113817ff6b9b2bbfc8a2b9.jsonadded+40 -0
@@ -0,0 +1,40 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id, name FROM school WHERE slug = $1",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "school",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "name",
20+ "type_info": "Text",
21+ "origin": {
22+ "Table": {
23+ "table": "school",
24+ "name": "name"
25+ }
26+ }
27+ }
28+ ],
29+ "parameters": {
30+ "Left": [
31+ "Text"
32+ ]
33+ },
34+ "nullable": [
35+ false,
36+ false
37+ ]
38+ },
39+ "hash": "4a50c4e5b4c369736b0a5b55dfd143b69def99f1e2113817ff6b9b2bbfc8a2b9"
40+}
.sqlx/query-b72c252f9cf975c3b72208812b427b28063ef3b41fad9188fbc10bc9cdfbb536.jsonadded+173 -0
@@ -0,0 +1,173 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT run_day, started_at, finished_at, status, duration_ms,\n students_total, students_ok, students_failed, students_skipped,\n rows_written, budget_exceeded, budget_ms, retain_until\n FROM zeka_run\n ORDER BY (run_day = $1) DESC, started_at DESC, run_day DESC\n LIMIT $2",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "run_day",
9+ "type_info": "Text",
10+ "origin": {
11+ "Table": {
12+ "table": "zeka_run",
13+ "name": "run_day"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "started_at",
20+ "type_info": "Int8",
21+ "origin": {
22+ "Table": {
23+ "table": "zeka_run",
24+ "name": "started_at"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "finished_at",
31+ "type_info": "Int8",
32+ "origin": {
33+ "Table": {
34+ "table": "zeka_run",
35+ "name": "finished_at"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "status",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "zeka_run",
46+ "name": "status"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "duration_ms",
53+ "type_info": "Int8",
54+ "origin": {
55+ "Table": {
56+ "table": "zeka_run",
57+ "name": "duration_ms"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "students_total",
64+ "type_info": "Int8",
65+ "origin": {
66+ "Table": {
67+ "table": "zeka_run",
68+ "name": "students_total"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "students_ok",
75+ "type_info": "Int8",
76+ "origin": {
77+ "Table": {
78+ "table": "zeka_run",
79+ "name": "students_ok"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "students_failed",
86+ "type_info": "Int8",
87+ "origin": {
88+ "Table": {
89+ "table": "zeka_run",
90+ "name": "students_failed"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "students_skipped",
97+ "type_info": "Int8",
98+ "origin": {
99+ "Table": {
100+ "table": "zeka_run",
101+ "name": "students_skipped"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "rows_written",
108+ "type_info": "Int8",
109+ "origin": {
110+ "Table": {
111+ "table": "zeka_run",
112+ "name": "rows_written"
113+ }
114+ }
115+ },
116+ {
117+ "ordinal": 10,
118+ "name": "budget_exceeded",
119+ "type_info": "Bool",
120+ "origin": {
121+ "Table": {
122+ "table": "zeka_run",
123+ "name": "budget_exceeded"
124+ }
125+ }
126+ },
127+ {
128+ "ordinal": 11,
129+ "name": "budget_ms",
130+ "type_info": "Int8",
131+ "origin": {
132+ "Table": {
133+ "table": "zeka_run",
134+ "name": "budget_ms"
135+ }
136+ }
137+ },
138+ {
139+ "ordinal": 12,
140+ "name": "retain_until",
141+ "type_info": "Int8",
142+ "origin": {
143+ "Table": {
144+ "table": "zeka_run",
145+ "name": "retain_until"
146+ }
147+ }
148+ }
149+ ],
150+ "parameters": {
151+ "Left": [
152+ "Text",
153+ "Int8"
154+ ]
155+ },
156+ "nullable": [
157+ false,
158+ false,
159+ true,
160+ false,
161+ true,
162+ false,
163+ false,
164+ false,
165+ false,
166+ false,
167+ false,
168+ false,
169+ false
170+ ]
171+ },
172+ "hash": "b72c252f9cf975c3b72208812b427b28063ef3b41fad9188fbc10bc9cdfbb536"
173+}
.sqlx/query-d49ecd80b59524287c3d6df8c7f825fdd47bf32d4d28af91d0ac79003d3e95eb.jsonadded+40 -0
@@ -0,0 +1,40 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT run, module FROM zeka_run_failed_module\n WHERE run = ANY($1) ORDER BY run, ord",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "run",
9+ "type_info": "Text",
10+ "origin": {
11+ "Table": {
12+ "table": "zeka_run_failed_module",
13+ "name": "run"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "module",
20+ "type_info": "Text",
21+ "origin": {
22+ "Table": {
23+ "table": "zeka_run_failed_module",
24+ "name": "module"
25+ }
26+ }
27+ }
28+ ],
29+ "parameters": {
30+ "Left": [
31+ "TextArray"
32+ ]
33+ },
34+ "nullable": [
35+ false,
36+ false
37+ ]
38+ },
39+ "hash": "d49ecd80b59524287c3d6df8c7f825fdd47bf32d4d28af91d0ac79003d3e95eb"
40+}
.sqlx/query-df0a13a99b74b5a298ff8a7dbe680375fb37576899499a0689cb57eb05d6c4d1.jsonadded+40 -0
@@ -0,0 +1,40 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT run, student FROM zeka_run_pending\n WHERE run = ANY($1) ORDER BY run, ord",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "run",
9+ "type_info": "Text",
10+ "origin": {
11+ "Table": {
12+ "table": "zeka_run_pending",
13+ "name": "run"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "student",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "zeka_run_pending",
24+ "name": "student"
25+ }
26+ }
27+ }
28+ ],
29+ "parameters": {
30+ "Left": [
31+ "TextArray"
32+ ]
33+ },
34+ "nullable": [
35+ false,
36+ false
37+ ]
38+ },
39+ "hash": "df0a13a99b74b5a298ff8a7dbe680375fb37576899499a0689cb57eb05d6c4d1"
40+}
.sqlx/query-fd5086c4a2049ebe1f41adfb7e996ebc5f80922c01d4187052e03f05c5ce00e6.jsonadded+110 -0
@@ -0,0 +1,110 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT student,\n marks AS \"marks?: SqlJson<JsonValue>\",\n attendance AS \"attendance?: SqlJson<JsonValue>\",\n submission AS \"submission?: SqlJson<JsonValue>\",\n study AS \"study?: SqlJson<JsonValue>\",\n confidence, computed_at, retain_until\n FROM zeka_student_summary ORDER BY student",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "student",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "zeka_student_summary",
13+ "name": "student"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "marks?: SqlJson<JsonValue>",
20+ "type_info": "Jsonb",
21+ "origin": {
22+ "Table": {
23+ "table": "zeka_student_summary",
24+ "name": "marks"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "attendance?: SqlJson<JsonValue>",
31+ "type_info": "Jsonb",
32+ "origin": {
33+ "Table": {
34+ "table": "zeka_student_summary",
35+ "name": "attendance"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "submission?: SqlJson<JsonValue>",
42+ "type_info": "Jsonb",
43+ "origin": {
44+ "Table": {
45+ "table": "zeka_student_summary",
46+ "name": "submission"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "study?: SqlJson<JsonValue>",
53+ "type_info": "Jsonb",
54+ "origin": {
55+ "Table": {
56+ "table": "zeka_student_summary",
57+ "name": "study"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "confidence",
64+ "type_info": "Text",
65+ "origin": {
66+ "Table": {
67+ "table": "zeka_student_summary",
68+ "name": "confidence"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "computed_at",
75+ "type_info": "Int8",
76+ "origin": {
77+ "Table": {
78+ "table": "zeka_student_summary",
79+ "name": "computed_at"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "retain_until",
86+ "type_info": "Int8",
87+ "origin": {
88+ "Table": {
89+ "table": "zeka_student_summary",
90+ "name": "retain_until"
91+ }
92+ }
93+ }
94+ ],
95+ "parameters": {
96+ "Left": []
97+ },
98+ "nullable": [
99+ false,
100+ true,
101+ true,
102+ true,
103+ true,
104+ false,
105+ false,
106+ false
107+ ]
108+ },
109+ "hash": "fd5086c4a2049ebe1f41adfb7e996ebc5f80922c01d4187052e03f05c5ce00e6"
110+}
.sqlx/query-fd55f76226b8fdc1426564e54a31e6e2a26abef3c078190d88f6732e45b39be6.jsonadded+158 -0
@@ -0,0 +1,158 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT student, dimension, label, n_answers, n_correct, accuracy,\n overall_n_answers, overall_accuracy, contrast, confidence,\n computed_at, retain_until\n FROM zeka_student_segment_profile ORDER BY student, dimension, label",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "student",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "zeka_student_segment_profile",
13+ "name": "student"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "dimension",
20+ "type_info": "Text",
21+ "origin": {
22+ "Table": {
23+ "table": "zeka_student_segment_profile",
24+ "name": "dimension"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "label",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "zeka_student_segment_profile",
35+ "name": "label"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "n_answers",
42+ "type_info": "Int8",
43+ "origin": {
44+ "Table": {
45+ "table": "zeka_student_segment_profile",
46+ "name": "n_answers"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "n_correct",
53+ "type_info": "Int8",
54+ "origin": {
55+ "Table": {
56+ "table": "zeka_student_segment_profile",
57+ "name": "n_correct"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "accuracy",
64+ "type_info": "Float8",
65+ "origin": {
66+ "Table": {
67+ "table": "zeka_student_segment_profile",
68+ "name": "accuracy"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "overall_n_answers",
75+ "type_info": "Int8",
76+ "origin": {
77+ "Table": {
78+ "table": "zeka_student_segment_profile",
79+ "name": "overall_n_answers"
80+ }
81+ }
82+ },
83+ {
84+ "ordinal": 7,
85+ "name": "overall_accuracy",
86+ "type_info": "Float8",
87+ "origin": {
88+ "Table": {
89+ "table": "zeka_student_segment_profile",
90+ "name": "overall_accuracy"
91+ }
92+ }
93+ },
94+ {
95+ "ordinal": 8,
96+ "name": "contrast",
97+ "type_info": "Float8",
98+ "origin": {
99+ "Table": {
100+ "table": "zeka_student_segment_profile",
101+ "name": "contrast"
102+ }
103+ }
104+ },
105+ {
106+ "ordinal": 9,
107+ "name": "confidence",
108+ "type_info": "Text",
109+ "origin": {
110+ "Table": {
111+ "table": "zeka_student_segment_profile",
112+ "name": "confidence"
113+ }
114+ }
115+ },
116+ {
117+ "ordinal": 10,
118+ "name": "computed_at",
119+ "type_info": "Int8",
120+ "origin": {
121+ "Table": {
122+ "table": "zeka_student_segment_profile",
123+ "name": "computed_at"
124+ }
125+ }
126+ },
127+ {
128+ "ordinal": 11,
129+ "name": "retain_until",
130+ "type_info": "Int8",
131+ "origin": {
132+ "Table": {
133+ "table": "zeka_student_segment_profile",
134+ "name": "retain_until"
135+ }
136+ }
137+ }
138+ ],
139+ "parameters": {
140+ "Left": []
141+ },
142+ "nullable": [
143+ false,
144+ false,
145+ false,
146+ false,
147+ false,
148+ false,
149+ false,
150+ false,
151+ false,
152+ false,
153+ false,
154+ false
155+ ]
156+ },
157+ "hash": "fd55f76226b8fdc1426564e54a31e6e2a26abef3c078190d88f6732e45b39be6"
158+}
README.mdmodified+2 -0
@@ -1332,6 +1332,8 @@ window filtering, before paging; negative values are a `400` naming the field.
1332 | POST | `/insights/refresh` | manager | Ask ZEKA to recompute the whole school's insights, detached. `202` means queued; the sweep's own record is `zeka_run`, which `GET /insights/runs` reads — poll that to watch a run move from `running` to its verdict. |1332 | POST | `/insights/refresh` | manager | Ask ZEKA to recompute the whole school's insights, detached. `202` means queued; the sweep's own record is `zeka_run`, which `GET /insights/runs` reads — poll that to watch a run move from `running` to its verdict. |
1333 | GET | `/insights/runs` | manager | The run ledger, newest first. Manager+ only: `pending_students` is a list of people, and ZEKA's output contract confines it to the management view. Paged via `?limit=&offset=`. |1333 | GET | `/insights/runs` | manager | The run ledger, newest first. Manager+ only: `pending_students` is a list of people, and ZEKA's output contract confines it to the management view. Paged via `?limit=&offset=`. |
1334 | POST | `/insights/runs` | manager | Store one compute run's ledger row (with its pending students and failed modules, both replaced). |1334 | POST | `/insights/runs` | manager | Store one compute run's ledger row (with its pending students and failed modules, both replaced). |
1335+| GET | `/insights/runs/{run_day}/report` | manager | The stored report document, streamed. |
1336+| POST | `/insights/runs/{run_day}/report` | manager | Render the school's report for one run day, and store it. Synchronous, and deliberately so: the manager clicked one button, and the document is what they asked for — there is no queue to poll and no partial state, and the receipt says what was stored. |
1335 | GET | `/insights/schools` | builder | The deployment's active schools, by slug — the directory a shared AI fleet schedules over. |1337 | GET | `/insights/schools` | builder | The deployment's active schools, by slug — the directory a shared AI fleet schedules over. |
1336 | POST | `/insights/segments` | manager | Store a batch of ZEKA's question-segment labels (and each question's dimension split). |1338 | POST | `/insights/segments` | manager | Store a batch of ZEKA's question-segment labels (and each question's dimension split). |
1337 | GET | `/insights/students/{user}` | teacher | One student's insight, as an observer reads it. Teacher+ (narrowed to the students they reach) or a parent holding a live link to that student; everyone else — other students included — gets the same `404` a missing id gets. |1339 | GET | `/insights/students/{user}` | teacher | One student's insight, as an observer reads it. Teacher+ (narrowed to the students they reach) or a parent holding a live link to that student; everyone else — other students included — gets the same `404` a missing id gets. |
src/ai/insight.rsmodified+106 -10
@@ -5,8 +5,11 @@
5 //!5 //!
6 //! * **Outbound** (the backend dispatches to the service):6 //! * **Outbound** (the backend dispatches to the service):
7 //! [`AI_INSIGHT_STUDENT_CAPABILITY`] — one student, on demand;7 //! [`AI_INSIGHT_STUDENT_CAPABILITY`] — one student, on demand;
8-//! [`AI_INSIGHT_REFRESH_CAPABILITY`] — a school-wide sweep, on demand. The8+//! [`AI_INSIGHT_REFRESH_CAPABILITY`] — a school-wide sweep, on demand;
9-//! dispatches below carry them ([`compute_student`], [`refresh`]).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`]).
10 //! * **Inbound** (the service calls the backend): the nine operations of13 //! * **Inbound** (the service calls the backend): the nine operations of
11 //! [`AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY`]'s family — the storage surface14 //! [`AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY`]'s family — the storage surface
12 //! ZEKA's `zeka_*` rows are written and read through, because **no AI15 //! ZEKA's `zeka_*` rows are written and read through, because **no AI
@@ -39,11 +42,15 @@ use serde_json::Value;
39 use crate::ai::AiBridge;42 use crate::ai::AiBridge;
40 use crate::ai::error::AiError;43 use crate::ai::error::AiError;
41 use crate::ai::protocol::FrameError;44 use crate::ai::protocol::FrameError;
42-use crate::constant::{AI_INSIGHT_REFRESH_TIMEOUT_SECS, AI_INSIGHT_STUDENT_TIMEOUT_SECS};45+use crate::constant::{
46+ AI_INSIGHT_REFRESH_TIMEOUT_SECS, AI_INSIGHT_REPORT_TIMEOUT_SECS,
47+ AI_INSIGHT_STUDENT_TIMEOUT_SECS,
48+};
43 use crate::tenant::Slug;49 use crate::tenant::Slug;
44 50
45 pub use crate::constant::{51 pub use crate::constant::{
46- AI_INSIGHT_CLASS_CAPABILITY, AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY,52+ AI_INSIGHT_CLASS_CAPABILITY, AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_REPORT_CAPABILITY,
53+ AI_INSIGHT_STUDENT_CAPABILITY,
47 };54 };
48 55
49 /// What the backend asks a service to compute for one student.56 /// What the backend asks a service to compute for one student.
@@ -167,7 +174,7 @@ pub struct RefreshRequest {
167 /// The receipt for a refresh: what the sweep did, once it did it. The run's174 /// The receipt for a refresh: what the sweep did, once it did it. The run's
168 /// own ledger is `zeka_run` in the school database, which is what a reader175 /// own ledger is `zeka_run` in the school database, which is what a reader
169 /// polls while this answer is still on its way.176 /// polls while this answer is still on its way.
170-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]177+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
171 pub struct RefreshResponse {178 pub struct RefreshResponse {
172 #[serde(default)]179 #[serde(default)]
173 pub started_at: Option<String>,180 pub started_at: Option<String>,
@@ -182,6 +189,76 @@ pub struct RefreshResponse {
182 pub failed: Vec<Value>,189 pub failed: Vec<Value>,
183 }190 }
184 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.
195+pub 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)]
212+pub 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 slug.
222+ pub school: ReportSchool,
223+ /// Every stored summary (with its attention items) in the school.
224+ pub summaries: Vec<SummaryRow>,
225+ pub recommendations: Vec<RecommendationRow>,
226+ pub profiles: Vec<ProfileRow>,
227+ /// The ledger rows the document may show: the named day first when it
228+ /// exists, then the newest days, at most a handful.
229+ pub runs: Vec<RunRow>,
230+}
231+
232+/// What the service rendered. `html` is the one required member: a response
233+/// without a document is not a partial answer, it is a dispatch that produced
234+/// nothing to store, and [`crate::ai::insight::report`]'s caller would rather
235+/// refuse it than persist an empty file. The rest is the service's own
236+/// bookkeeping, optional for the same reason every response member here is.
237+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
238+pub struct ReportResponse {
239+ #[serde(default)]
240+ pub kind: Option<String>,
241+ #[serde(default)]
242+ pub run_day: Option<String>,
243+ /// `html` today — the format the stored artifact is served as. Recorded
244+ /// rather than assumed, so a future format is visible on the wire.
245+ #[serde(default)]
246+ pub format: Option<String>,
247+ /// The self-contained document, `<!doctype html>` first.
248+ pub html: String,
249+ #[serde(default)]
250+ pub byte_size: Option<u64>,
251+ /// Whether the service clipped the document (a row set past its own
252+ /// ceiling). Stored and reported verbatim: a clipped document must not
253+ /// read as a complete one.
254+ #[serde(default)]
255+ pub truncated: bool,
256+ /// The service's own remarks about the document — e.g. that the run day
257+ /// has no ledger row. Shown to the manager beside the artifact.
258+ #[serde(default)]
259+ pub notes: Vec<String>,
260+}
261+
185 /// Compute one student's insight, awaited. No capability check here: the262 /// Compute one student's insight, awaited. No capability check here: the
186 /// caller decides what "no service" means, and every caller today is an HTTP263 /// caller decides what "no service" means, and every caller today is an HTTP
187 /// door that has already answered `503` for it ([`crate::web::insights`]).264 /// door that has already answered `503` for it ([`crate::web::insights`]).
@@ -217,8 +294,27 @@ pub async fn refresh(
217 .await294 .await
218 }295 }
219 296
220-/// One request, one typed answer — the two dispatches differ only in297+/// Ask for one school-level report document, awaited. The request carries
221-/// capability, deadline and payload type.298+/// every row the document needs, and the answer carries the rendered HTML
299+/// back; the deadline is [`AI_INSIGHT_REPORT_TIMEOUT_SECS`]. The caller
300+/// stores the document — this function only moves it.
301+pub async fn report(
302+ bridge: &AiBridge,
303+ school: &Slug,
304+ request: &ReportRequest,
305+) -> Result<ReportResponse, AiError> {
306+ dispatch(
307+ bridge,
308+ school,
309+ AI_INSIGHT_REPORT_CAPABILITY,
310+ AI_INSIGHT_REPORT_TIMEOUT_SECS,
311+ request,
312+ )
313+ .await
314+}
315+
316+/// One request, one typed answer — the dispatches differ only in capability,
317+/// deadline and payload type.
222 ///318 ///
223 /// A reply that does not parse as the expected type is a319 /// A reply that does not parse as the expected type is a
224 /// [`FrameError::Malformed`]: the bytes were JSON, but not this contract's320 /// [`FrameError::Malformed`]: the bytes were JSON, but not this contract's
@@ -261,9 +357,9 @@ fn malformed(err: serde_json::Error) -> AiError {
261 357
262 pub use crate::db::insight::{358 pub use crate::db::insight::{
263 AttentionRow, PendingList, ProfileRow, ProfileWriteRequest, PurgeRequest, RecommendationRow,359 AttentionRow, PendingList, ProfileRow, ProfileWriteRequest, PurgeRequest, RecommendationRow,
264- RecommendationWriteRequest, RunRow, RunWriteRequest, SchoolDirectory, SegmentConfidences,360+ RecommendationWriteRequest, ReportSchool, RunRow, RunWriteRequest, SchoolDirectory,
265- SegmentLabels, SegmentRow, SegmentWriteRequest, SummaryRow, SummaryWriteRequest,361+ SegmentConfidences, SegmentLabels, SegmentRow, SegmentWriteRequest, SummaryRow,
266- TableVerdicts, WriteReceipt,362+ SummaryWriteRequest, TableVerdicts, WriteReceipt,
267 };363 };
268 364
269 use crate::constant::{365 use crate::constant::{
src/constant.rsmodified+18 -0
@@ -635,6 +635,24 @@ pub const AI_INSIGHT_REFRESH_CAPABILITY: &str = "insight.refresh";
635 /// summary.635 /// summary.
636 pub const AI_INSIGHT_REFRESH_TIMEOUT_SECS: u64 = 300;636 pub const AI_INSIGHT_REFRESH_TIMEOUT_SECS: u64 = 300;
637 637
638+/// The capability an AI service declares to render a school-level report
639+/// document. The service computes nothing here: the backend already holds
640+/// every row the document is built from (the `zeka_*` tables), sends them in
641+/// the request, and stores the self-contained HTML the service answers with.
642+/// The rendering lives in the service because the reader/report-package
643+/// contract does — the backend never composes an insight document, the same
644+/// way it never composes an insight row.
645+pub const AI_INSIGHT_REPORT_CAPABILITY: &str = "insight.report";
646+
647+/// Deadline on one `insight.report` round trip. Sized like the refresh sweep's
648+/// ceiling, because it renders the same school-wide row set: the service does
649+/// no reads and no model calls, but a large school's rows are already on its
650+/// side of the wire when this starts ticking. Unlike the other two insight
651+/// dispatches, a caller *waits on this one* — the door stores the document
652+/// before it answers, so the deadline is also the ceiling on what a manager
653+/// can be made to wait for.
654+pub const AI_INSIGHT_REPORT_TIMEOUT_SECS: u64 = 300;
655+
638 // ---- zeka's storage surface (capabilities the *backend* serves) ------------656 // ---- zeka's storage surface (capabilities the *backend* serves) ------------
639 //657 //
640 // The three constants above are capabilities an AI service *declares*: the658 // The three constants above are capabilities an AI service *declares*: the
src/db/insight.rsmodified+237 -1
@@ -43,6 +43,7 @@ use std::collections::BTreeMap;
43 use serde::{Deserialize, Serialize};43 use serde::{Deserialize, Serialize};
44 use serde_json::Value as JsonValue;44 use serde_json::Value as JsonValue;
45 use sqlx::AssertSqlSafe;45 use sqlx::AssertSqlSafe;
46+use sqlx::types::Json as SqlJson;
46 use utoipa::ToSchema;47 use utoipa::ToSchema;
47 use uuid::Uuid;48 use uuid::Uuid;
48 49
@@ -313,6 +314,18 @@ pub struct SchoolDirectory {
313 pub schools: Vec<String>,314 pub schools: Vec<String>,
314 }315 }
315 316
317+/// One school's own identity, as a rendered report prints it. The bridge
318+/// frame already names the school by slug, but a document that reaches a
319+/// manager's screen carries the display name, and the control row is the only
320+/// authority on it.
321+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
322+pub struct ReportSchool {
323+ /// `school.id` — the surrogate key, not the slug: a slug may be renamed.
324+ pub id: String,
325+ pub slug: String,
326+ pub name: String,
327+}
328+
316 // ---- shared validation -----------------------------------------------------329 // ---- shared validation -----------------------------------------------------
317 330
318 /// Refuse a batch past [`MAX_INSIGHT_BATCH_ROWS`] rather than taking it331 /// Refuse a batch past [`MAX_INSIGHT_BATCH_ROWS`] rather than taking it
@@ -357,7 +370,10 @@ fn parse_uuid(field: &'static str, value: &str) -> Result<Uuid, AppError> {
357 370
358 /// `YYYY-MM-DD`, the ledger's key. Checked here so a malformed day is the371 /// `YYYY-MM-DD`, the ledger's key. Checked here so a malformed day is the
359 /// caller's `invalid_payload` and not a CHECK violation dressed as a `500`.372 /// caller's `invalid_payload` and not a CHECK violation dressed as a `500`.
360-fn run_day_ok(day: &str) -> bool {373+/// The report doors share it: a run day shapes a blob key there, and a
374+/// caller-supplied path segment that shapes a path is validated before it is
375+/// joined.
376+pub fn run_day_ok(day: &str) -> bool {
361 let bytes = day.as_bytes();377 let bytes = day.as_bytes();
362 bytes.len() == 10378 bytes.len() == 10
363 && bytes379 && bytes
@@ -841,6 +857,226 @@ pub async fn active_schools(control: &Database) -> Result<SchoolDirectory, AppEr
841 Ok(SchoolDirectory { schools })857 Ok(SchoolDirectory { schools })
842 }858 }
843 859
860+/// One school's identity row, by slug. `None` only for a slug the control
861+/// database does not hold — a resolved tenant always has one, so a caller
862+/// reads that as an internal fault, not as a refusal.
863+pub async fn school_identity(
864+ control: &Database,
865+ slug: &str,
866+) -> Result<Option<ReportSchool>, AppError> {
867+ let row = sqlx::query!("SELECT id, name FROM school WHERE slug = $1", slug)
868+ .fetch_optional(control)
869+ .await?;
870+ Ok(row.map(|row| ReportSchool {
871+ id: row.id.to_string(),
872+ slug: slug.to_string(),
873+ name: row.name,
874+ }))
875+}
876+
877+// ---- the school-wide reads the report payload carries -----------------------
878+//
879+// Every read above is per-student or per-audience, because that is every
880+// reader this nest had. A *document* about the school is the first caller that
881+// needs the whole row set at once, so these four project each table straight
882+// into the wire rows the bridge payload carries ([`SummaryRow`],
883+// [`RecommendationRow`], [`ProfileRow`], [`RunRow`]) — one mapping, in one
884+// place, shared by SQL and the wire. No filters: the document's own reader
885+// (the service's report package) decides what it shows, and a backend that
886+// pre-filtered would be a second, silent author of the report.
887+
888+/// Every stored summary with its attention items, in student order. The
889+/// attention list is one query for the whole set, grouped by student — not
890+/// one query per summary.
891+pub async fn all_summaries(db: &Database) -> Result<Vec<SummaryRow>, AppError> {
892+ let rows = sqlx::query!(
893+ r#"SELECT student,
894+ marks AS "marks?: SqlJson<JsonValue>",
895+ attendance AS "attendance?: SqlJson<JsonValue>",
896+ submission AS "submission?: SqlJson<JsonValue>",
897+ study AS "study?: SqlJson<JsonValue>",
898+ confidence, computed_at, retain_until
899+ FROM zeka_student_summary ORDER BY student"#
900+ )
901+ .fetch_all(db)
902+ .await?;
903+ let mut attention: BTreeMap<Uuid, Vec<AttentionRow>> = BTreeMap::new();
904+ for row in sqlx::query!(
905+ r#"SELECT student, trigger, course, fact, window_from, window_to,
906+ evidence AS "evidence: SqlJson<JsonValue>"
907+ FROM zeka_attention_item ORDER BY student, ord"#
908+ )
909+ .fetch_all(db)
910+ .await?
911+ {
912+ attention.entry(row.student).or_default().push(AttentionRow {
913+ trigger: row.trigger,
914+ course: row.course.map(|course| course.to_string()),
915+ fact: row.fact,
916+ window_from: row.window_from,
917+ window_to: row.window_to,
918+ evidence: row.evidence.0,
919+ });
920+ }
921+ Ok(rows
922+ .into_iter()
923+ .map(|row| SummaryRow {
924+ attention: attention.remove(&row.student).unwrap_or_default(),
925+ student: row.student.to_string(),
926+ marks: row.marks.map(|json| json.0),
927+ attendance: row.attendance.map(|json| json.0),
928+ submission: row.submission.map(|json| json.0),
929+ study: row.study.map(|json| json.0),
930+ confidence: row.confidence,
931+ computed_at: row.computed_at,
932+ retain_until: row.retain_until,
933+ })
934+ .collect())
935+}
936+
937+/// Every stored card, whatever its audience, in a stable order. The write
938+/// merged each row's `limitation` into its stored evidence object, so the
939+/// read leaves the [write-side](RecommendationRow::limitation) field empty —
940+/// a second copy here could only disagree with the one inside `evidence`.
941+///
942+/// The wire row carries no `dismissed_at`, so the stored dismissal trail
943+/// (`dismissed_at`/`dismiss_by`/`dismiss_reason` on the table) does not
944+/// travel: a consumer that gates on dismissal cannot fire on this read. That
945+/// is a known gap of the report payload's contract — the reader that filters
946+/// dismissals is the per-audience read ([`crate::web::insights`]), and
947+/// widening the row here is a contract change this lane does not make.
948+pub async fn all_recommendations(db: &Database) -> Result<Vec<RecommendationRow>, AppError> {
949+ let rows = sqlx::query!(
950+ r#"SELECT audience, product, rule_id, rule_version, scope, about, audience_role,
951+ course, evidence AS "evidence: SqlJson<JsonValue>",
952+ confidence, created_at, expires_at, retain_until
953+ FROM zeka_recommendation ORDER BY audience, created_at, rule_id"#
954+ )
955+ .fetch_all(db)
956+ .await?;
957+ Ok(rows
958+ .into_iter()
959+ .map(|row| RecommendationRow {
960+ audience: row.audience.to_string(),
961+ product: row.product,
962+ rule_id: row.rule_id,
963+ rule_version: row.rule_version,
964+ scope: row.scope,
965+ about: row.about.map(|about| about.to_string()),
966+ audience_role: row.audience_role,
967+ course: row.course.map(|course| course.to_string()),
968+ evidence: row.evidence.0,
969+ limitation: None,
970+ confidence: row.confidence,
971+ // The column is `created_at`; the wire row spells it `computed_at`,
972+ // and the write maps the same pair the same way.
973+ computed_at: row.created_at,
974+ expires_at: row.expires_at,
975+ retain_until: row.retain_until,
976+ })
977+ .collect())
978+}
979+
980+/// Every stored segment profile, in student order. Noise rows (`confidence =
981+/// 'none'`) are included: this read feeds a document, and the display floor is
982+/// the reader's rule, applied where the reader applies it.
983+pub async fn all_profiles(db: &Database) -> Result<Vec<ProfileRow>, AppError> {
984+ let rows = sqlx::query!(
985+ r#"SELECT student, dimension, label, n_answers, n_correct, accuracy,
986+ overall_n_answers, overall_accuracy, contrast, confidence,
987+ computed_at, retain_until
988+ FROM zeka_student_segment_profile ORDER BY student, dimension, label"#
989+ )
990+ .fetch_all(db)
991+ .await?;
992+ Ok(rows
993+ .into_iter()
994+ .map(|row| ProfileRow {
995+ student: row.student.to_string(),
996+ dimension: row.dimension,
997+ label: row.label,
998+ n_answers: row.n_answers,
999+ n_correct: row.n_correct,
1000+ accuracy: row.accuracy,
1001+ overall_n_answers: row.overall_n_answers,
1002+ overall_accuracy: row.overall_accuracy,
1003+ contrast: row.contrast,
1004+ confidence: row.confidence,
1005+ computed_at: row.computed_at,
1006+ retain_until: row.retain_until,
1007+ })
1008+ .collect())
1009+}
1010+
1011+/// How many ledger rows a report carries: the named day plus recent context.
1012+/// Deliberately small — the ledger is context for the document, which is
1013+/// about one day, not a ledger dump.
1014+const REPORT_RUNS: i64 = 5;
1015+
1016+/// The run ledger a report carries, with each run's children. The named day
1017+/// leads when it exists (a report about it must be able to show it even if it
1018+/// has scrolled out of the newest rows), then the newest days follow.
1019+pub async fn runs_for_report(db: &Database, run_day: &str) -> Result<Vec<RunRow>, AppError> {
1020+ let rows = sqlx::query!(
1021+ r#"SELECT run_day, started_at, finished_at, status, duration_ms,
1022+ students_total, students_ok, students_failed, students_skipped,
1023+ rows_written, budget_exceeded, budget_ms, retain_until
1024+ FROM zeka_run
1025+ ORDER BY (run_day = $1) DESC, started_at DESC, run_day DESC
1026+ LIMIT $2"#,
1027+ run_day,
1028+ REPORT_RUNS,
1029+ )
1030+ .fetch_all(db)
1031+ .await?;
1032+ let days: Vec<String> = rows.iter().map(|row| row.run_day.clone()).collect();
1033+ let mut pending: BTreeMap<String, Vec<String>> = BTreeMap::new();
1034+ for row in sqlx::query!(
1035+ r#"SELECT run, student FROM zeka_run_pending
1036+ WHERE run = ANY($1) ORDER BY run, ord"#,
1037+ &days
1038+ )
1039+ .fetch_all(db)
1040+ .await?
1041+ {
1042+ pending
1043+ .entry(row.run)
1044+ .or_default()
1045+ .push(row.student.to_string());
1046+ }
1047+ let mut failed: BTreeMap<String, Vec<String>> = BTreeMap::new();
1048+ for row in sqlx::query!(
1049+ r#"SELECT run, module FROM zeka_run_failed_module
1050+ WHERE run = ANY($1) ORDER BY run, ord"#,
1051+ &days
1052+ )
1053+ .fetch_all(db)
1054+ .await?
1055+ {
1056+ failed.entry(row.run).or_default().push(row.module);
1057+ }
1058+ Ok(rows
1059+ .into_iter()
1060+ .map(|row| RunRow {
1061+ pending_students: pending.remove(&row.run_day).unwrap_or_default(),
1062+ failed_modules: failed.remove(&row.run_day).unwrap_or_default(),
1063+ run_day: row.run_day,
1064+ started_at: row.started_at,
1065+ finished_at: row.finished_at,
1066+ status: row.status,
1067+ duration_ms: row.duration_ms,
1068+ students_total: row.students_total,
1069+ students_ok: row.students_ok,
1070+ students_failed: row.students_failed,
1071+ students_skipped: row.students_skipped,
1072+ rows_written: row.rows_written,
1073+ budget_exceeded: row.budget_exceeded,
1074+ budget_ms: row.budget_ms,
1075+ retain_until: row.retain_until,
1076+ })
1077+ .collect())
1078+}
1079+
844 // ---- retention -------------------------------------------------------------1080 // ---- retention -------------------------------------------------------------
845 1081
846 /// The nine tables a sweep walks, children before their parents: the foreign1082 /// The nine tables a sweep walks, children before their parents: the foreign
src/web/insights.rsmodified+299 -4
@@ -41,10 +41,20 @@
41 //! student's compute can outlast the request-timeout layer41 //! student's compute can outlast the request-timeout layer
42 //! ([`crate::constant::REQUEST_TIMEOUT_SECS`]). The client polls the stored42 //! ([`crate::constant::REQUEST_TIMEOUT_SECS`]). The client polls the stored
43 //! rows — the compute doors change nothing a reader cannot already see.43 //! rows — the compute doors change nothing a reader cannot already see.
44+//!
45+//! The **report** doors are the one exception, and deliberately: building the
46+//! school's document is not a compute the service does on its own schedule —
47+//! it is one artifact the manager asked for, rendered from rows the backend
48+//! already holds, so `POST /runs/{run_day}/report` waits, stores the returned
49+//! HTML under the school's own blob directory, and answers `200` with what
50+//! was stored. `GET /runs/{run_day}/report` streams that document back.
44 51
45 use axum::Json;52 use axum::Json;
53+use axum::body::Body;
46 use axum::extract::{Path, Query};54 use axum::extract::{Path, Query};
55+use axum::http::HeaderValue;
47 use axum::http::StatusCode;56 use axum::http::StatusCode;
57+use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS};
48 use axum::response::{IntoResponse, Response};58 use axum::response::{IntoResponse, Response};
49 use serde::{Deserialize, Serialize};59 use serde::{Deserialize, Serialize};
50 use serde_json::Value as JsonValue;60 use serde_json::Value as JsonValue;
@@ -53,14 +63,16 @@ use utoipa::ToSchema;
53 use utoipa_axum::router::OpenApiRouter;63 use utoipa_axum::router::OpenApiRouter;
54 use utoipa_axum::routes;64 use utoipa_axum::routes;
55 65
66+use crate::ai::error::AiError;
56 use crate::ai::insight::{67 use crate::ai::insight::{
57- self, PendingList, ProfileWriteRequest, PurgeRequest, ROSTER_SOURCE_EXPLICIT,68+ self, PendingList, ProfileWriteRequest, PurgeRequest, REPORT_KIND_SCHOOL, ROSTER_SOURCE_EXPLICIT,
58- ROSTER_SOURCE_SCHOOL, RecommendationWriteRequest, RefreshRequest, RunWriteRequest,69+ ROSTER_SOURCE_SCHOOL, RecommendationWriteRequest, RefreshRequest, ReportRequest, RunWriteRequest,
59 SchoolDirectory, SegmentWriteRequest, StudentRequest, SummaryWriteRequest, TableVerdicts,70 SchoolDirectory, SegmentWriteRequest, StudentRequest, SummaryWriteRequest, TableVerdicts,
60 WriteReceipt,71 WriteReceipt,
61 };72 };
62 use crate::constant::{73 use crate::constant::{
63- AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY, MAX_INSIGHT_REFRESH_STUDENTS,74+ AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_REPORT_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY,
75+ MAX_INSIGHT_REFRESH_STUDENTS,
64 };76 };
65 use crate::database::Database;77 use crate::database::Database;
66 use crate::db;78 use crate::db;
@@ -75,7 +87,9 @@ use crate::state::AppState;
75 use crate::tenant::ResolvedTenant;87 use crate::tenant::ResolvedTenant;
76 use crate::web::tenant_state::State;88 use crate::web::tenant_state::State;
77 89
78-use super::{CurrentUser, Page, PageParams, RequireBuilder, RequireManager, ai_unavailable, paginate};90+use super::{
91+ CurrentUser, Page, PageParams, RequireBuilder, RequireManager, ai_unavailable, paginate, pump,
92+};
79 93
80 /// The single `now` every card read is filtered against. ZEKA stores unix94 /// The single `now` every card read is filtered against. ZEKA stores unix
81 /// milliseconds, so "expired" is a comparison, not a projection.95 /// milliseconds, so "expired" is a comparison, not a projection.
@@ -89,6 +103,7 @@ pub fn routes() -> OpenApiRouter<AppState> {
89 .routes(routes!(my_insight))103 .routes(routes!(my_insight))
90 .routes(routes!(student_insight, compute_student))104 .routes(routes!(student_insight, compute_student))
91 .routes(routes!(list_runs, write_run))105 .routes(routes!(list_runs, write_run))
106+ .routes(routes!(generate_report, serve_report))
92 .routes(routes!(write_summaries))107 .routes(routes!(write_summaries))
93 .routes(routes!(write_recommendations))108 .routes(routes!(write_recommendations))
94 .routes(routes!(write_segments))109 .routes(routes!(write_segments))
@@ -299,6 +314,286 @@ fn accepted() -> Response {
299 .into_response()314 .into_response()
300 }315 }
301 316
317+// ---- the report doors ------------------------------------------------------
318+
319+/// The receipt for a stored report. `generated_at` is this backend's clock the
320+/// moment the document was stored — the artifact's age is what a manager
321+/// re-clicking the button wants to see.
322+#[derive(Serialize, ToSchema)]
323+struct ReportReceipt {
324+ /// The run day the document is about, `YYYY-MM-DD`.
325+ #[schema(example = "2026-09-17")]
326+ run_day: String,
327+ /// The stored document's size in bytes.
328+ byte_size: u64,
329+ /// Whether the service clipped the document. A clipped report must not
330+ /// read as a complete one.
331+ truncated: bool,
332+ /// The service's own remarks about the document — e.g. that the run day
333+ /// has no ledger row. Shown to the manager beside the artifact.
334+ notes: Vec<String>,
335+ /// When this backend stored the document, unix milliseconds.
336+ generated_at: i64,
337+}
338+
339+/// Where a school's generated report documents live under its blob directory:
340+/// one file per run day. The day is validated before it is joined (see
341+/// [`db::insight::run_day_ok`]), so the key can carry no separator and no
342+/// `..`.
343+const REPORT_DIR: &str = "zeka_report";
344+
345+fn report_key(run_day: &str) -> String {
346+ format!("{REPORT_DIR}/{run_day}.html")
347+}
348+
349+/// Render the school's report for one run day, and store it. Synchronous, and
350+/// deliberately so: the manager clicked one button, and the document is what
351+/// they asked for — there is no queue to poll and no partial state, and the
352+/// receipt says what was stored.
353+///
354+/// Manager+ only: the document is whole-school, like the refresh sweep and the
355+/// run ledger. The payload is read from this school's own `zeka_*` tables and
356+/// dispatched to the service that declares `insight.report`; the service may
357+/// not read a database, so every row the document needs travels in the
358+/// request — the same serde rows the storage surface writes.
359+///
360+/// A run day with no ledger row, or one whose tables are empty, is still a
361+/// legal request: the service renders what it was given and says so in
362+/// `notes`. Refusals: `503` when no service offers the capability, or it did
363+/// not answer — nothing was stored; `429` when every worker is at capacity;
364+/// and the service's own typed refusals, mapped per class by
365+/// [`report_refusal`].
366+#[utoipa::path(
367+ post,
368+ path = "/runs/{run_day}/report",
369+ tag = "insights",
370+ security(("session_cookie" = [])),
371+ params(("run_day" = String, Path, description = "The run day, `YYYY-MM-DD`")),
372+ responses(
373+ (status = 200, description = "The document was rendered and stored; the receipt says what was stored", body = ReportReceipt),
374+ (status = 400, description = "`run_day` is not a `YYYY-MM-DD` day, or the AI service refused the composed request", body = ErrorResponse),
375+ (status = 401, description = "Not authenticated", body = ErrorResponse),
376+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
377+ (status = 409, description = "The AI service answered, refusing — `report_refused`, or `report_empty` when it has no rows to render; nothing was stored", body = ErrorResponse),
378+ (status = 413, description = "The rendered document is over the AI service's size ceiling; nothing was stored", body = ErrorResponse),
379+ (status = 429, description = "Every AI service offering `insight.report` is at capacity", body = ErrorResponse),
380+ (status = 503, description = "No AI service offers `insight.report`, or it did not answer; nothing was stored", body = ErrorResponse),
381+ ),
382+)]
383+async fn generate_report(
384+ State(st): State<AppState>,
385+ tenant: ResolvedTenant,
386+ RequireManager(user): RequireManager,
387+ Path(run_day): Path<String>,
388+) -> Result<Response, AppError> {
389+ if !db::insight::run_day_ok(&run_day) {
390+ return Err(AppError::Validation(ValidationError::Invalid {
391+ field: "run_day",
392+ reason: "must be a `YYYY-MM-DD` day",
393+ }));
394+ }
395+ let Some(bridge) = st.ai.clone() else {
396+ return Ok(ai_unavailable(
397+ "the AI service is not enabled on this deployment",
398+ ));
399+ };
400+ if !bridge.has_capability(AI_INSIGHT_REPORT_CAPABILITY) {
401+ return Ok(ai_unavailable("no AI service is connected right now"));
402+ }
403+ let Some(school) =
404+ db::insight::school_identity(st.tenants.control(), tenant.slug.as_str()).await?
405+ else {
406+ return Err(AppError::Internal(format!(
407+ "the resolved school `{}` has no control row",
408+ tenant.slug.as_str()
409+ )));
410+ };
411+ let request = ReportRequest {
412+ kind: REPORT_KIND_SCHOOL.to_string(),
413+ run_day: run_day.clone(),
414+ requested_by: user.get_id().key(),
415+ school,
416+ summaries: db::insight::all_summaries(&st.db).await?,
417+ recommendations: db::insight::all_recommendations(&st.db).await?,
418+ profiles: db::insight::all_profiles(&st.db).await?,
419+ runs: db::insight::runs_for_report(&st.db, &run_day).await?,
420+ };
421+ let answer = match insight::report(&bridge, &tenant.slug, &request).await {
422+ Ok(answer) => answer,
423+ Err(AiError::Remote { code, message }) => {
424+ tracing::warn!("insight.report refused: {code}: {message}");
425+ return Err(report_refusal(code, message));
426+ }
427+ Err(AiError::Busy(_)) => {
428+ return Err(AppError::TooManyRequests { retry_after_secs: 5 });
429+ }
430+ // No worker (the capability was withdrawn between the check and the
431+ // dispatch), a timeout, a transport or protocol failure: the document
432+ // cannot be produced now, and claiming otherwise would store nothing.
433+ Err(err) => {
434+ tracing::warn!("insight.report failed: {err}");
435+ return Ok(ai_unavailable(
436+ "the AI service did not answer; nothing was stored",
437+ ));
438+ }
439+ };
440+ // An empty document is not a document: storing it would serve a blank
441+ // page as if it were the report, and a manager would read that as "the
442+ // school has nothing to say". Refused, never persisted.
443+ if answer.html.trim().is_empty() {
444+ tracing::error!("insight.report answered with an empty document for {run_day}");
445+ return Err(AppError::Internal(
446+ "the AI service answered with an empty document".to_string(),
447+ ));
448+ }
449+ store_report(&st.files_path, &run_day, &answer.html).await?;
450+ Ok(Json(ReportReceipt {
451+ run_day,
452+ byte_size: answer.html.len() as u64,
453+ truncated: answer.truncated,
454+ notes: answer.notes,
455+ generated_at: now_millis(),
456+ })
457+ .into_response())
458+}
459+
460+/// The service's refusal vocabulary as this door's HTTP answer.
461+///
462+/// The report service closes four codes (`hezarfen_zeka`'s handler) and a
463+/// client branches on the class each becomes:
464+///
465+/// * `bad_request` — the service judged the composed request bad (an unserved
466+/// kind, a malformed day, a row field that is not a list, a school
467+/// disagreement). The payload is composed here, so this is a backend defect
468+/// and the caller can only be told the request was refused; the service's
469+/// own words go to the log.
470+/// * `insufficient_rows` — all four row lists were empty, so there is no
471+/// document to build. `409 report_empty`: no retry conjures data, a sweep
472+/// does.
473+/// * `document_too_large` — over the service's own HTML ceiling, which it
474+/// never truncates past. `413`.
475+/// * `internal` — the render failed on the service's side. `500`.
476+///
477+/// Anything else is `409 report_refused` with the service's code and message
478+/// kept verbatim: a service may define codes this backend has never heard of,
479+/// and swallowing them would hide the one explanation a caller needs.
480+fn report_refusal(code: String, message: String) -> AppError {
481+ match code.as_str() {
482+ "bad_request" => AppError::Validation(ValidationError::Invalid {
483+ field: "report",
484+ reason: "the AI service refused the composed request; the reason is in the backend log",
485+ }),
486+ "insufficient_rows" => AppError::ConflictCoded {
487+ code: "report_empty",
488+ message: format!(
489+ "the AI service has no rows to render a report from: {message}"
490+ ),
491+ },
492+ "document_too_large" => AppError::PayloadTooLarge(format!(
493+ "the rendered report is over the AI service's size ceiling, and it does not truncate: {message}"
494+ )),
495+ "internal" => AppError::Internal(format!(
496+ "the AI service failed to render the report: {message}"
497+ )),
498+ _ => AppError::ConflictCoded {
499+ code: "report_refused",
500+ message: format!("the AI service refused the report: {code}: {message}"),
501+ },
502+ }
503+}
504+
505+/// The stored report document, streamed.
506+///
507+/// `409 report_missing` when nothing has been generated for the day — a
508+/// refusal that covers a day the ledger has never heard of too: generation
509+/// accepts such a day on purpose (the document's `notes` say it), so a `404`
510+/// here could refuse a day the POST door had just answered `200` for.
511+#[utoipa::path(
512+ get,
513+ path = "/runs/{run_day}/report",
514+ tag = "insights",
515+ security(("session_cookie" = [])),
516+ params(("run_day" = String, Path, description = "The run day, `YYYY-MM-DD`")),
517+ responses(
518+ (status = 200, description = "The stored document", content_type = "text/html"),
519+ (status = 400, description = "`run_day` is not a `YYYY-MM-DD` day", body = ErrorResponse),
520+ (status = 401, description = "Not authenticated", body = ErrorResponse),
521+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
522+ (status = 409, description = "No report has been generated for this day (`report_missing`)", body = ErrorResponse),
523+ ),
524+)]
525+async fn serve_report(
526+ State(st): State<AppState>,
527+ RequireManager(_user): RequireManager,
528+ Path(run_day): Path<String>,
529+) -> Result<Response, AppError> {
530+ if !db::insight::run_day_ok(&run_day) {
531+ return Err(AppError::Validation(ValidationError::Invalid {
532+ field: "run_day",
533+ reason: "must be a `YYYY-MM-DD` day",
534+ }));
535+ }
536+ let key = report_key(&run_day);
537+ let path = crate::web::blob_path(&st.files_path, &key);
538+ let file = tokio::fs::File::open(&path).await.map_err(|err| {
539+ if err.kind() != std::io::ErrorKind::NotFound {
540+ tracing::error!("could not open the stored report {key}: {err}");
541+ }
542+ AppError::ConflictCoded {
543+ code: "report_missing",
544+ message: format!("no report has been generated for `{run_day}` yet"),
545+ }
546+ })?;
547+ Ok((
548+ [
549+ (
550+ CONTENT_TYPE,
551+ HeaderValue::from_static("text/html; charset=utf-8"),
552+ ),
553+ (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")),
554+ (CACHE_CONTROL, HeaderValue::from_static("private, no-store")),
555+ ],
556+ Body::from_stream(pump(file)),
557+ )
558+ .into_response())
559+}
560+
561+/// Store the rendered document under the school's own blob directory.
562+///
563+/// Written to a temp name and renamed into place: the artifact appears
564+/// atomically or not at all, so a reader — or a second POST racing this one —
565+/// can never open a half-written document. The temp file is removed if
566+/// anything fails before the rename.
567+async fn store_report(
568+ files_path: &std::path::Path,
569+ run_day: &str,
570+ html: &str,
571+) -> Result<(), AppError> {
572+ crate::web::ensure_files_dir(files_path).await?;
573+ let dir = crate::web::blob_path(files_path, REPORT_DIR);
574+ tokio::fs::create_dir_all(&dir).await.map_err(|err| {
575+ AppError::Internal(format!("failed to create the report directory: {err}"))
576+ })?;
577+ let temp = dir.join(format!(
578+ ".report-{}.tmp",
579+ crate::domain::monotonic_id::next_uuid()
580+ ));
581+ if let Err(err) = tokio::fs::write(&temp, html.as_bytes()).await {
582+ let _ = tokio::fs::remove_file(&temp).await;
583+ return Err(AppError::Internal(format!(
584+ "failed to write the report document: {err}"
585+ )));
586+ }
587+ let path = crate::web::blob_path(files_path, &report_key(run_day));
588+ if let Err(err) = tokio::fs::rename(&temp, &path).await {
589+ let _ = tokio::fs::remove_file(&temp).await;
590+ return Err(AppError::Internal(format!(
591+ "failed to store the report document: {err}"
592+ )));
593+ }
594+ Ok(())
595+}
596+
302 // ---- the storage doors -----------------------------------------------------597 // ---- the storage doors -----------------------------------------------------
303 //598 //
304 // ZEKA's own tables are written and read by the backend, never by the service599 // ZEKA's own tables are written and read by the backend, never by the service
src/web/mod.rsmodified+43 -0
@@ -255,6 +255,49 @@ pub(crate) async fn remove_blob(files_path: &FsPath, key: &str) {
255 }255 }
256 }256 }
257 257
258+/// How much of a stored blob is read per chunk, and how many chunks its body
259+/// may have in flight. 4 × 64 KiB is the whole memory ceiling one stream
260+/// costs, however large the file behind it. Shared by every streaming blob
261+/// door (podcast audio, the insight report document).
262+const BLOB_CHUNK_BYTES: usize = 64 * 1024;
263+const BLOB_CHUNKS_IN_FLIGHT: usize = 4;
264+
265+/// A stored file as a byte stream: a reader task hands chunks to the body over
266+/// a bounded channel, so a client that stops reading parks the pump at the
267+/// next send instead of pinning the whole file in memory, and a closed body
268+/// ends the task by itself.
269+pub(crate) fn pump(
270+ file: tokio::fs::File,
271+) -> impl tokio_stream::Stream<Item = Result<axum::body::Bytes, std::io::Error>> + Send + 'static
272+{
273+ let (tx, rx) = tokio::sync::mpsc::channel::<Result<axum::body::Bytes, std::io::Error>>(
274+ BLOB_CHUNKS_IN_FLIGHT,
275+ );
276+ tokio::spawn(async move {
277+ let mut file = file;
278+ let mut buf = vec![0u8; BLOB_CHUNK_BYTES];
279+ loop {
280+ match tokio::io::AsyncReadExt::read(&mut file, &mut buf).await {
281+ Ok(0) => break,
282+ Ok(n) => {
283+ if tx
284+ .send(Ok(axum::body::Bytes::copy_from_slice(&buf[..n])))
285+ .await
286+ .is_err()
287+ {
288+ break;
289+ }
290+ }
291+ Err(err) => {
292+ let _ = tx.send(Err(err)).await;
293+ break;
294+ }
295+ }
296+ }
297+ });
298+ tokio_stream::wrappers::ReceiverStream::new(rx)
299+}
300+
258 /// The declared content type of an inline-displayed image upload, held to the301 /// The declared content type of an inline-displayed image upload, held to the
259 /// raster allowlist — SVG stays out (it can script) since these bytes are302 /// raster allowlist — SVG stays out (it can script) since these bytes are
260 /// rendered inline to whole classes. Shared by exam question images and pool303 /// rendered inline to whole classes. Shared by exam question images and pool
src/web/podcast.rsmodified+2 -38
@@ -45,7 +45,7 @@
45 //! fail is never queued.45 //! fail is never queued.
46 46
47 use axum::Json;47 use axum::Json;
48-use axum::body::{Body, Bytes};48+use axum::body::Body;
49 use axum::extract::{Path, Query};49 use axum::extract::{Path, Query};
50 use axum::http::HeaderValue;50 use axum::http::HeaderValue;
51 use axum::http::StatusCode;51 use axum::http::StatusCode;
@@ -53,9 +53,6 @@ use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS};
53 use axum::response::{IntoResponse, Response};53 use axum::response::{IntoResponse, Response};
54 use serde::{Deserialize, Serialize};54 use serde::{Deserialize, Serialize};
55 use serde_json::json;55 use serde_json::json;
56-use tokio::sync::mpsc;
57-use tokio_stream::Stream;
58-use tokio_stream::wrappers::ReceiverStream;
59 use utoipa::{IntoParams, ToSchema};56 use utoipa::{IntoParams, ToSchema};
60 use utoipa_axum::router::OpenApiRouter;57 use utoipa_axum::router::OpenApiRouter;
61 use utoipa_axum::routes;58 use utoipa_axum::routes;
@@ -74,13 +71,7 @@ use crate::service::podcast_job as jobs;
74 use crate::state::AppState;71 use crate::state::AppState;
75 use crate::web::tenant_state::{SchoolSlug, State};72 use crate::web::tenant_state::{SchoolSlug, State};
76 73
77-use super::{CurrentUser, Page, PageParams, ai_unavailable};74+use super::{CurrentUser, Page, PageParams, ai_unavailable, pump};
78-
79-/// How much of the audio is read per chunk, and how many chunks the body may
80-/// have in flight. 4 × 64 KiB is the whole memory ceiling one audio stream
81-/// costs, however large the file behind it.
82-const AUDIO_CHUNK_BYTES: usize = 64 * 1024;
83-const AUDIO_CHUNKS_IN_FLIGHT: usize = 4;
84 75
85 pub fn routes() -> OpenApiRouter<AppState> {76 pub fn routes() -> OpenApiRouter<AppState> {
86 OpenApiRouter::new()77 OpenApiRouter::new()
@@ -630,33 +621,6 @@ async fn owned(st: &AppState, user: &User, id: &str) -> Result<PodcastJob, AppEr
630 Ok(job)621 Ok(job)
631 }622 }
632 623
633-/// A file as a byte stream: a reader task hands chunks to the body over a
634-/// bounded channel, so a client that stops reading parks the pump at the next
635-/// send instead of pinning the whole file in memory, and a closed body ends the
636-/// task by itself.
637-fn pump(file: tokio::fs::File) -> impl Stream<Item = Result<Bytes, std::io::Error>> + Send + 'static {
638- let (tx, rx) = mpsc::channel::<Result<Bytes, std::io::Error>>(AUDIO_CHUNKS_IN_FLIGHT);
639- tokio::spawn(async move {
640- let mut file = file;
641- let mut buf = vec![0u8; AUDIO_CHUNK_BYTES];
642- loop {
643- match tokio::io::AsyncReadExt::read(&mut file, &mut buf).await {
644- Ok(0) => break,
645- Ok(n) => {
646- if tx.send(Ok(Bytes::copy_from_slice(&buf[..n]))).await.is_err() {
647- break;
648- }
649- }
650- Err(err) => {
651- let _ = tx.send(Err(err)).await;
652- break;
653- }
654- }
655- }
656- });
657- ReceiverStream::new(rx)
658-}
659-
660 /// Why a dispatching door has no worker to talk to. Deliberately small: the624 /// Why a dispatching door has no worker to talk to. Deliberately small: the
661 /// refusal is not a response — the caller builds the `503` at its own call625 /// refusal is not a response — the caller builds the `503` at its own call
662 /// site, so a large, rarely-taken `Response` never rides the `Result` type of626 /// site, so a large, rarely-taken `Response` never rides the `Result` type of
tests/insight_report.rsadded+645 -0
@@ -0,0 +1,645 @@
1+//! End-to-end tests for the school-report doors, against a fake ZEKA service.
2+//!
3+//! `POST /insights/runs/{run_day}/report` reads this school's own `zeka_*`
4+//! rows, dispatches them to the service that declares `insight.report`, stores
5+//! the returned HTML under the school's blob directory, and answers `200` with
6+//! what was stored; `GET` streams that document back. Everything runs over a
7+//! real QUIC socket on loopback — a real handshake, real TLS, real streams —
8+//! with [`Behaviour::Report`] standing in for what ZEKA does with the request.
9+//!
10+//! The assertions split the same way `tests/podcast.rs` splits them: what a
11+//! browser gets from the real router, and what the *service* received
12+//! ([`FakeService::seen`]) — a door that quietly sent nothing, or asked the
13+//! wrong principal, fails the `seen` assertions rather than looking green.
14+
15+mod common;
16+
17+use std::sync::{Arc, Mutex};
18+use std::time::Duration;
19+
20+use axum::Router;
21+use axum::http::StatusCode;
22+use hezarfen_backend::ai::protocol::{Greeting, Hello, Request, Response, read_frame, write_frame};
23+use hezarfen_backend::ai::{AiBridge, BridgeConfig};
24+use hezarfen_backend::constant::{
25+ AI_ALPN, AI_INSIGHT_REPORT_CAPABILITY, AI_PROTOCOL,
26+};
27+use hezarfen_backend::database::Database;
28+use hezarfen_backend::domain::timestamp::Timestamp;
29+use hezarfen_backend::tenant::DEMO_SLUG;
30+use serde_json::{Value, json};
31+use uuid::Uuid;
32+
33+const TOKEN: &str = "shared-ai-token";
34+
35+/// One answer frame, **bounded**: a bridge that never answers must fail this
36+/// test by name in seconds rather than hang the run — a hung Test step holds
37+/// the serialized deploy lock behind it.
38+async fn frame_or_fail<T: serde::de::DeserializeOwned>(
39+ recv: &mut quinn::RecvStream,
40+ what: &str,
41+) -> T {
42+ match tokio::time::timeout(Duration::from_secs(10), read_frame(recv)).await {
43+ Ok(Ok(frame)) => frame,
44+ Ok(Err(err)) => panic!("{what}: the frame could not be read: {err}"),
45+ Err(_) => panic!("{what}: no frame arrived within 10s — the bridge did not answer"),
46+ }
47+}
48+
49+// ---------------------------------------------------------------- harness --
50+
51+/// Start a bridge on an ephemeral port.
52+async fn bridge() -> AiBridge {
53+ AiBridge::bind(BridgeConfig {
54+ addr: "127.0.0.1:0".parse().unwrap(),
55+ token: TOKEN.to_string(),
56+ cert_path: None,
57+ key_path: None,
58+ request_timeout: Duration::from_secs(5),
59+ })
60+ .await
61+ .expect("bridge binds on an ephemeral port")
62+}
63+
64+/// A QUIC client endpoint that trusts exactly the bridge's own certificate —
65+/// the same pinning a real service does, rather than a verification bypass.
66+fn client_endpoint(bridge: &AiBridge) -> quinn::Endpoint {
67+ hezarfen_backend::ai::tls::install_crypto_provider();
68+ let mut roots = rustls::RootCertStore::empty();
69+ roots.add(bridge.certificate()).expect("pin the leaf");
70+ let mut tls = rustls::ClientConfig::builder()
71+ .with_root_certificates(roots)
72+ .with_no_client_auth();
73+ tls.alpn_protocols = vec![AI_ALPN.to_vec()];
74+
75+ let quic_tls =
76+ quinn::crypto::rustls::QuicClientConfig::try_from(tls).expect("client TLS is QUIC-usable");
77+ let mut config = quinn::ClientConfig::new(Arc::new(quic_tls));
78+ let mut transport = quinn::TransportConfig::default();
79+ transport.max_concurrent_bidi_streams(64u32.into());
80+ config.transport_config(Arc::new(transport));
81+
82+ let mut endpoint =
83+ quinn::Endpoint::client("127.0.0.1:0".parse().unwrap()).expect("client bind");
84+ endpoint.set_default_client_config(config);
85+ endpoint
86+}
87+
88+fn hello(service: &str, capabilities: &[&str]) -> Hello {
89+ Hello {
90+ protocol: AI_PROTOCOL.to_string(),
91+ service: service.to_string(),
92+ capabilities: capabilities.iter().map(|c| c.to_string()).collect(),
93+ token: TOKEN.to_string(),
94+ max_concurrent: None,
95+ }
96+}
97+
98+/// A connected fake service. Holding it keeps the connection (and so the
99+/// registration) alive; dropping it is how a test simulates a crash.
100+struct FakeService {
101+ _endpoint: quinn::Endpoint,
102+ _control: (quinn::SendStream, quinn::RecvStream),
103+ /// Every request this service received, in arrival order.
104+ seen: Arc<Mutex<Vec<Request>>>,
105+}
106+
107+impl FakeService {
108+ fn seen(&self) -> Vec<Request> {
109+ self.seen.lock().unwrap().clone()
110+ }
111+
112+ /// The one report request this service was handed.
113+ fn report_request(&self) -> Request {
114+ self.seen()
115+ .into_iter()
116+ .find(|request| request.capability == AI_INSIGHT_REPORT_CAPABILITY)
117+ .expect("the door dispatched the report capability")
118+ }
119+}
120+
121+/// What the fake service does with each request it receives.
122+#[derive(Clone)]
123+enum Behaviour {
124+ /// Answer like ZEKA's report package: a self-contained HTML document that
125+ /// echoes the run day and how many summaries it was handed.
126+ Report,
127+ /// Refuse like ZEKA's report handler does: the code is chosen by the run
128+ /// day, so one connection can drive every refusal class.
129+ Refuse,
130+ /// Answer `200` with an html member that is the empty string — a service
131+ /// defect the door must not persist.
132+ Empty,
133+}
134+
135+/// The refusal code the fake service answers for a run day — all four codes
136+/// the real handler closes, one day each.
137+fn refusal_code(run_day: &str) -> String {
138+ match run_day {
139+ "2026-09-11" => "bad_request",
140+ "2026-09-12" => "insufficient_rows",
141+ "2026-09-13" => "document_too_large",
142+ "2026-09-14" => "internal",
143+ other => panic!("the fake service was asked for an unmapped day `{other}`"),
144+ }
145+ .to_string()
146+}
147+
148+/// Dial, register, and start serving requests with `behaviour`.
149+async fn connect_service(bridge: &AiBridge, hello: Hello, behaviour: Behaviour) -> FakeService {
150+ let endpoint = client_endpoint(bridge);
151+ let conn = endpoint
152+ .connect(bridge.local_addr().unwrap(), "localhost")
153+ .expect("dial")
154+ .await
155+ .expect("QUIC handshake");
156+ let (mut send, mut recv) = conn.open_bi().await.expect("control stream");
157+ write_frame(&mut send, &hello).await.expect("send Hello");
158+ let greeting: Greeting = frame_or_fail(&mut recv, "read Greeting").await;
159+ match greeting {
160+ Greeting::Welcome { protocol, .. } => assert_eq!(protocol, AI_PROTOCOL),
161+ other => panic!("expected a welcome, got {other:?}"),
162+ }
163+
164+ let seen = Arc::new(Mutex::new(Vec::new()));
165+ serve(conn.clone(), behaviour, Arc::clone(&seen));
166+ FakeService {
167+ _endpoint: endpoint,
168+ _control: (send, recv),
169+ seen,
170+ }
171+}
172+
173+/// The service's request loop: one task per incoming server-initiated stream.
174+fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc<Mutex<Vec<Request>>>) {
175+ tokio::spawn(async move {
176+ while let Ok((mut send, mut recv)) = conn.accept_bi().await {
177+ let behaviour = behaviour.clone();
178+ let seen = Arc::clone(&seen);
179+ tokio::spawn(async move {
180+ let Ok(request) = read_frame::<_, Request>(&mut recv).await else {
181+ return;
182+ };
183+ seen.lock().unwrap().push(request.clone());
184+ let response = match behaviour {
185+ Behaviour::Report => Response::Ok {
186+ id: request.id.clone(),
187+ school: request.school.clone(),
188+ payload: report_answer(&request),
189+ },
190+ Behaviour::Refuse => {
191+ let code = refusal_code(
192+ request.payload["run_day"].as_str().unwrap_or_default(),
193+ );
194+ Response::Err {
195+ id: request.id.clone(),
196+ school: request.school.clone(),
197+ message: format!("`{code}` reddedildi"),
198+ code,
199+ }
200+ }
201+ Behaviour::Empty => Response::Ok {
202+ id: request.id.clone(),
203+ school: request.school.clone(),
204+ payload: json!({
205+ "kind": "okul",
206+ "run_day": request.payload["run_day"],
207+ "format": "html",
208+ "html": "",
209+ "byte_size": 0,
210+ "truncated": false,
211+ "notes": [],
212+ }),
213+ },
214+ };
215+ let _ = write_frame(&mut send, &response).await;
216+ let _ = send.finish();
217+ let _ = send.stopped().await;
218+ });
219+ }
220+ });
221+}
222+
223+/// The HTML a fake report render produces for the request it was handed.
224+fn report_html(request: &Request) -> String {
225+ let run_day = request.payload["run_day"].as_str().unwrap_or("<gun yok>");
226+ let students = request.payload["summaries"]
227+ .as_array()
228+ .map(|rows| rows.len())
229+ .unwrap_or(0);
230+ format!(
231+ "<!doctype html>\n<html lang=\"tr\"><head><meta charset=\"utf-8\">\
232+ <title>Okul analiz raporu</title></head>\
233+ <body><h1>Okul analiz raporu — {run_day}</h1>\
234+ <p>{students} öğrenci özeti</p></body></html>"
235+ )
236+}
237+
238+/// What the fake ZEKA report package answers: the document plus its own
239+/// bookkeeping.
240+fn report_answer(request: &Request) -> Value {
241+ let html = report_html(request);
242+ json!({
243+ "kind": "okul",
244+ "run_day": request.payload["run_day"],
245+ "format": "html",
246+ "byte_size": html.len(),
247+ "html": html,
248+ "truncated": false,
249+ "notes": ["koşu defteri okundu"],
250+ })
251+}
252+
253+/// Registration completes asynchronously after the welcome is on the wire, so
254+/// tests that assert on the registry wait for it rather than racing it.
255+async fn await_workers(bridge: &AiBridge, expected: usize) {
256+ for _ in 0..300 {
257+ if bridge.workers().len() == expected {
258+ return;
259+ }
260+ tokio::time::sleep(Duration::from_millis(10)).await;
261+ }
262+ panic!(
263+ "expected {expected} workers, registry holds {:?}",
264+ bridge.workers()
265+ );
266+}
267+
268+/// A registered ZEKA service, the router wired to its bridge, a logged-in
269+/// manager, and the school's database handle — the fixture the round-trip
270+/// tests start from.
271+async fn report_app() -> (FakeService, Router, String, Database) {
272+ let bridge = bridge().await;
273+ let service = connect_service(
274+ &bridge,
275+ hello("zeka", &[AI_INSIGHT_REPORT_CAPABILITY]),
276+ Behaviour::Report,
277+ )
278+ .await;
279+ await_workers(&bridge, 1).await;
280+ let (app, db) = common::app_with_ai(Some(bridge)).await;
281+ let manager = common::login_as(&app, &db, "mudur", "manager").await;
282+ (service, app, manager, db)
283+}
284+
285+// --------------------------------------------------------------- fixtures --
286+
287+/// Seed one student's ZEKA rows the way the service writes them: a summary
288+/// with one attention item, one live card, one segment profile, and the
289+/// ledger row for `run_day` with its pending student and failed module. All of
290+/// it is what the report dispatch must carry.
291+async fn seed_report_rows(db: &Database, run_day: &str, student: &str, audience: &str) {
292+ let student_uuid = Uuid::parse_str(student).expect("student id");
293+ let audience_uuid = Uuid::parse_str(audience).expect("audience id");
294+ let now = Timestamp::now().as_millis();
295+
296+ sqlx::query(
297+ "INSERT INTO zeka_student_summary
298+ (student, marks, attendance, submission, study, confidence, computed_at, retain_until)
299+ VALUES ($1, '{\"courses\":{\"matematik\":{\"average\":72}}}'::jsonb, NULL, NULL, NULL,
300+ 'stable', $2, $3)",
301+ )
302+ .bind(student_uuid)
303+ .bind(now)
304+ .bind(now + 400 * 86_400_000)
305+ .execute(db)
306+ .await
307+ .unwrap();
308+
309+ sqlx::query(
310+ "INSERT INTO zeka_attention_item
311+ (student, trigger, course, fact, window_from, window_to, evidence, ord)
312+ VALUES ($1, 'attendance', NULL, 'son 30 gunun 4 dersi kacirildi', $2, $3,
313+ '{\"absent_days\":4}'::jsonb, 1)",
314+ )
315+ .bind(student_uuid)
316+ .bind(now - 30 * 86_400_000)
317+ .bind(now)
318+ .execute(db)
319+ .await
320+ .unwrap();
321+
322+ sqlx::query(
323+ "INSERT INTO zeka_recommendation
324+ (id, audience, product, rule_id, rule_version, scope, about, audience_role,
325+ course, evidence, confidence, created_at, expires_at, retain_until,
326+ dismissed_at, dismissed_by, dismiss_reason)
327+ VALUES ($1, $2, 'T4', 'T4.attendance', 1, NULL, $3, 'teacher', NULL,
328+ '{\"absent_days\":4,\"limitation\":\"yalniz ders yoklamasi\"}'::jsonb,
329+ 'stable', $4, $5, $6, NULL, NULL, NULL)",
330+ )
331+ .bind(Uuid::now_v7())
332+ .bind(audience_uuid)
333+ .bind(student_uuid)
334+ .bind(now)
335+ .bind(now + 86_400_000)
336+ .bind(now + 90 * 86_400_000)
337+ .execute(db)
338+ .await
339+ .unwrap();
340+
341+ sqlx::query(
342+ "INSERT INTO zeka_student_segment_profile
343+ (student, dimension, label, n_answers, n_correct, accuracy,
344+ overall_n_answers, overall_accuracy, contrast, confidence,
345+ computed_at, retain_until)
346+ VALUES ($1, 'bilissel_talep', 'analiz', 120, 48, 0.40, 240, 0.55, -0.15,
347+ 'stable', $2, $3)",
348+ )
349+ .bind(student_uuid)
350+ .bind(now)
351+ .bind(now + 400 * 86_400_000)
352+ .execute(db)
353+ .await
354+ .unwrap();
355+
356+ sqlx::query(
357+ "INSERT INTO zeka_run
358+ (run_day, started_at, finished_at, status, duration_ms,
359+ students_total, students_ok, students_failed, students_skipped,
360+ rows_written, budget_exceeded, budget_ms, retain_until)
361+ VALUES ($1, $2, $3, 'ok', 61000, 1, 1, 0, 0, 44, false, 60000, $4)",
362+ )
363+ .bind(run_day)
364+ .bind(now - 61_000)
365+ .bind(now)
366+ .bind(now + 90 * 86_400_000)
367+ .execute(db)
368+ .await
369+ .unwrap();
370+ sqlx::query("INSERT INTO zeka_run_pending (run, student, ord) VALUES ($1, $2, 1)")
371+ .bind(run_day)
372+ .bind(student_uuid)
373+ .execute(db)
374+ .await
375+ .unwrap();
376+ sqlx::query("INSERT INTO zeka_run_failed_module (run, module, ord) VALUES ($1, 'study', 1)")
377+ .bind(run_day)
378+ .execute(db)
379+ .await
380+ .unwrap();
381+}
382+
383+// ------------------------------------------------------------- http doors --
384+
385+/// One `POST /insights/runs/{run_day}/report`.
386+async fn generate(app: &Router, cookie: &str, run_day: &str) -> common::Res {
387+ common::send(
388+ app,
389+ "POST",
390+ &format!("/insights/runs/{run_day}/report"),
391+ Some(cookie),
392+ None,
393+ )
394+ .await
395+}
396+
397+/// One `GET /insights/runs/{run_day}/report`, raw — the body is an HTML
398+/// document or a JSON refusal, never a parsed envelope.
399+async fn fetch_report(
400+ app: &Router,
401+ cookie: &str,
402+ run_day: &str,
403+) -> (StatusCode, axum::http::HeaderMap, Vec<u8>) {
404+ common::send_raw(
405+ app,
406+ "GET",
407+ &format!("/insights/runs/{run_day}/report"),
408+ Some(cookie),
409+ None,
410+ Vec::new(),
411+ )
412+ .await
413+}
414+
415+/// A refusal body parsed out of raw bytes.
416+fn refusal_body(bytes: &[u8]) -> Value {
417+ serde_json::from_slice(bytes).expect("a refusal body is JSON")
418+}
419+
420+// ------------------------------------------------------------------ tests --
421+
422+/// The whole round trip: the manager generates the document, the service is
423+/// handed the school's own rows and the caller's identity, and the stored
424+/// artifact is served back with the document's content type — byte for byte
425+/// what the service rendered.
426+#[tokio::test]
427+async fn a_generated_report_is_stored_and_served_to_its_manager() {
428+ let (service, app, manager, db) = report_app().await;
429+ let manager_id = common::me_id(&app, &manager).await;
430+ let student = common::login(&app, "ali").await;
431+ let student_id = common::me_id(&app, &student).await;
432+ seed_report_rows(&db, "2026-09-16", &student_id, &manager_id).await;
433+
434+ let res = generate(&app, &manager, "2026-09-16").await;
435+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
436+ assert_eq!(res.body["run_day"], "2026-09-16");
437+ assert_eq!(res.body["truncated"], false);
438+ assert_eq!(res.body["notes"], json!(["koşu defteri okundu"]));
439+ assert!(res.body["generated_at"].as_i64().unwrap() > 0);
440+ assert_eq!(
441+ res.body["byte_size"].as_u64().unwrap(),
442+ report_html(&service.report_request()).len() as u64,
443+ "the receipt sizes the stored document, not the service's claim"
444+ );
445+
446+ // What the service was handed. This is the payload contract: the rows the
447+ // backend holds, the caller's identity, and the school's own fields.
448+ let request = service.report_request();
449+ assert_eq!(request.payload["kind"], "okul");
450+ assert_eq!(request.payload["run_day"], "2026-09-16");
451+ assert_eq!(
452+ request.payload["requested_by"], manager_id,
453+ "the dispatch names the authenticated caller, not the school"
454+ );
455+ assert_eq!(request.payload["school"]["slug"], DEMO_SLUG);
456+ assert!(
457+ request.payload["school"]["id"].as_str().is_some_and(|id| !id.is_empty()),
458+ "the school's own id travels"
459+ );
460+ assert!(
461+ request.payload["school"]["name"]
462+ .as_str()
463+ .is_some_and(|name| !name.is_empty()),
464+ "the school's display name travels"
465+ );
466+ let summaries = request.payload["summaries"]
467+ .as_array()
468+ .expect("summaries is a list");
469+ let mine = summaries
470+ .iter()
471+ .find(|row| row["student"] == student_id)
472+ .expect("the seeded student's summary is in the payload");
473+ assert_eq!(mine["confidence"], "stable");
474+ assert_eq!(mine["attention"][0]["trigger"], "attendance");
475+ assert_eq!(mine["attention"][0]["evidence"]["absent_days"], 4);
476+ let cards = request.payload["recommendations"].as_array().unwrap();
477+ assert_eq!(cards.len(), 1);
478+ assert_eq!(cards[0]["rule_id"], "T4.attendance");
479+ assert_eq!(cards[0]["about"], student_id);
480+ assert_eq!(request.payload["profiles"][0]["dimension"], "bilissel_talep");
481+ assert_eq!(request.payload["profiles"][0]["contrast"], -0.15);
482+ let runs = request.payload["runs"].as_array().unwrap();
483+ assert_eq!(runs[0]["run_day"], "2026-09-16");
484+ assert_eq!(runs[0]["pending_students"], json!([student_id]));
485+ assert_eq!(runs[0]["failed_modules"], json!(["study"]));
486+
487+ // The artifact a browser gets back.
488+ let (status, headers, bytes) = fetch_report(&app, &manager, "2026-09-16").await;
489+ assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&bytes));
490+ assert_eq!(headers["content-type"], "text/html; charset=utf-8");
491+ assert_eq!(headers["x-content-type-options"], "nosniff");
492+ assert_eq!(headers["cache-control"], "private, no-store");
493+ let html = String::from_utf8(bytes).expect("the stored document is UTF-8");
494+ assert_eq!(html, report_html(&service.report_request()));
495+ assert!(html.starts_with("<!doctype html>"));
496+}
497+
498+/// Generation is deliberately synchronous and does not require a ledger row:
499+/// a run day with no `zeka_run` row still dispatches (the service says in
500+/// `notes` what it found), and the artifact it returns is served. A `404`
501+/// here would refuse a day the POST door had just answered `200` for.
502+#[tokio::test]
503+async fn a_run_day_with_no_ledger_row_still_generates_and_serves() {
504+ let (service, app, manager, _db) = report_app().await;
505+
506+ let res = generate(&app, &manager, "2099-01-01").await;
507+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
508+ assert_eq!(res.body["run_day"], "2099-01-01");
509+
510+ let request = service.report_request();
511+ assert_eq!(request.payload["run_day"], "2099-01-01");
512+ assert_eq!(
513+ request.payload["runs"].as_array().map(Vec::len),
514+ Some(0),
515+ "no ledger row means no ledger rows, not a refusal"
516+ );
517+
518+ let (status, headers, _bytes) = fetch_report(&app, &manager, "2099-01-01").await;
519+ assert_eq!(status, StatusCode::OK);
520+ assert_eq!(headers["content-type"], "text/html; charset=utf-8");
521+}
522+
523+/// Reading before anything was generated is the coded `409` — the refusal a
524+/// client branches on, never a `404` it could confuse with a missing route.
525+#[tokio::test]
526+async fn a_report_that_was_never_generated_is_a_coded_conflict() {
527+ let (app, db) = common::app_and_db().await;
528+ let manager = common::login_as(&app, &db, "mudur", "manager").await;
529+
530+ let (status, _headers, bytes) = fetch_report(&app, &manager, "2099-12-31").await;
531+ assert_eq!(status, StatusCode::CONFLICT);
532+ let body = refusal_body(&bytes);
533+ assert_eq!(body["code"], "report_missing");
534+ assert!(
535+ body["error"].as_str().unwrap().contains("2099-12-31"),
536+ "the message names the day: {body}"
537+ );
538+}
539+
540+/// A service that answers, refusing, maps each of its four codes to the right
541+/// HTTP class — and stores nothing on any of them.
542+#[tokio::test]
543+async fn service_refusals_map_each_code_to_its_http_class() {
544+ let bridge = bridge().await;
545+ let _service = connect_service(
546+ &bridge,
547+ hello("zeka", &[AI_INSIGHT_REPORT_CAPABILITY]),
548+ Behaviour::Refuse,
549+ )
550+ .await;
551+ await_workers(&bridge, 1).await;
552+ let (app, db) = common::app_with_ai(Some(bridge)).await;
553+ let manager = common::login_as(&app, &db, "mudur", "manager").await;
554+
555+ // `bad_request`: the service judged the composed request bad.
556+ let res = generate(&app, &manager, "2026-09-11").await;
557+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
558+
559+ // `insufficient_rows`: nothing to render — a coded conflict, not a 500.
560+ let res = generate(&app, &manager, "2026-09-12").await;
561+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
562+ assert_eq!(res.body["code"], "report_empty");
563+ assert!(
564+ res.body["error"]
565+ .as_str()
566+ .is_some_and(|message| message.contains("insufficient_rows")),
567+ "the service's own words survive: {}",
568+ res.body
569+ );
570+
571+ // `document_too_large`: the render happened but is over the ceiling.
572+ let res = generate(&app, &manager, "2026-09-13").await;
573+ assert_eq!(res.status, StatusCode::PAYLOAD_TOO_LARGE, "{}", res.body);
574+
575+ // `internal`: the render failed on the service's side.
576+ let res = generate(&app, &manager, "2026-09-14").await;
577+ assert_eq!(res.status, StatusCode::INTERNAL_SERVER_ERROR, "{}", res.body);
578+
579+ // None of the four stored a document.
580+ for day in ["2026-09-11", "2026-09-12", "2026-09-13", "2026-09-14"] {
581+ let (status, _headers, bytes) = fetch_report(&app, &manager, day).await;
582+ assert_eq!(status, StatusCode::CONFLICT, "{day}");
583+ assert_eq!(refusal_body(&bytes)["code"], "report_missing", "{day}");
584+ }
585+}
586+
587+/// No service at all: `503` before any read, and nothing was stored.
588+#[tokio::test]
589+async fn generating_without_a_service_is_unavailable() {
590+ let (app, db) = common::app_and_db().await;
591+ let manager = common::login_as(&app, &db, "mudur", "manager").await;
592+
593+ let res = generate(&app, &manager, "2026-09-14").await;
594+ assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);
595+ assert!(res.body["error"].is_string());
596+}
597+
598+/// A service that answers `200` with an empty document is refused: a blank
599+/// page must never be stored and served as if it were the report.
600+#[tokio::test]
601+async fn an_empty_document_is_never_stored() {
602+ let bridge = bridge().await;
603+ let _service = connect_service(
604+ &bridge,
605+ hello("zeka", &[AI_INSIGHT_REPORT_CAPABILITY]),
606+ Behaviour::Empty,
607+ )
608+ .await;
609+ await_workers(&bridge, 1).await;
610+ let (app, db) = common::app_with_ai(Some(bridge)).await;
611+ let manager = common::login_as(&app, &db, "mudur", "manager").await;
612+
613+ let res = generate(&app, &manager, "2026-09-10").await;
614+ assert_eq!(res.status, StatusCode::INTERNAL_SERVER_ERROR, "{}", res.body);
615+
616+ let (status, _headers, bytes) = fetch_report(&app, &manager, "2026-09-10").await;
617+ assert_eq!(status, StatusCode::CONFLICT);
618+ assert_eq!(refusal_body(&bytes)["code"], "report_missing");
619+}
620+
621+/// Both doors are manager+; a teacher is refused before anything is read or
622+/// dispatched, and a malformed day never shapes a path.
623+#[tokio::test]
624+async fn report_doors_are_manager_only_and_validate_the_day() {
625+ let (app, db) = common::app_and_db().await;
626+ let teacher = common::login_as(&app, &db, "ayse", "teacher").await;
627+
628+ let res = generate(&app, &teacher, "2026-09-16").await;
629+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
630+ let (status, _headers, _bytes) = fetch_report(&app, &teacher, "2026-09-16").await;
631+ assert_eq!(status, StatusCode::FORBIDDEN);
632+
633+ let manager = common::login_as(&app, &db, "mudur", "manager").await;
634+ let res = generate(&app, &manager, "2026-9-16").await;
635+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
636+ // A percent-encoded traversal in the day segment decodes to something no
637+ // `YYYY-MM-DD` day is, so it is refused before it could shape a path.
638+ let (status, _headers, bytes) = fetch_report(&app, &manager, "%2e%2e%2f%2e%2e%2fetc%2fpasswd").await;
639+ assert_eq!(
640+ status,
641+ StatusCode::BAD_REQUEST,
642+ "a path-shaped day is refused before it is joined: {}",
643+ String::from_utf8_lossy(&bytes)
644+ );
645+}
tests/integration.rsmodified+1 -1
@@ -434,7 +434,7 @@ async fn protected_routes_require_session() {
434 /// Floor on the number of protected operations swept. It only ever goes434 /// Floor on the number of protected operations swept. It only ever goes
435 /// up: raise it when routes are added. Without it, deleting a route family435 /// up: raise it when routes are added. Without it, deleting a route family
436 /// would delete its own coverage and still pass.436 /// would delete its own coverage and still pass.
437- const MIN_PROTECTED: usize = 338;437+ const MIN_PROTECTED: usize = 340;
438 438
439 let app = mem_app().await;439 let app = mem_app().await;
440 let spec = send(&app, "GET", "/api-docs/openapi.json", None, None)440 let spec = send(&app, "GET", "/api-docs/openapi.json", None, None)
tests/limits_completeness.rsmodified+10 -0
@@ -145,6 +145,16 @@ const EXCLUDED: &[(&str, &str)] = &[
145 "deadline on one school-wide recompute; the run's own ledger is \145 "deadline on one school-wide recompute; the run's own ledger is \
146 `zeka_run`, which the client polls",146 `zeka_run`, which the client polls",
147 ),147 ),
148+ (
149+ "AI_INSIGHT_REPORT_CAPABILITY",
150+ "capability string an AI service declares",
151+ ),
152+ (
153+ "AI_INSIGHT_REPORT_TIMEOUT_SECS",
154+ "deadline on one school-level report render; the manager waits on the \
155+ artifact itself and a client acts on the door's 200/409/503, never on \
156+ this number",
157+ ),
148 // The storage surface ZEKA's rows are written through (the service calls158 // The storage surface ZEKA's rows are written through (the service calls
149 // these; the backend runs them). A browser never speaks the bridge, and159 // these; the backend runs them). A browser never speaks the bridge, and
150 // the HTTP doors that mirror them publish what a client can act on.160 // the HTTP doors that mirror them publish what a client can act on.