From 541d9b7f2ac9409cf343aba8f7f641a581f4a0d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 18 Sep 2026 12:43:01 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=84=20feat(insight):=20render=20and=20?= =?UTF-8?q?serve=20a=20school-level=20report=20document?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `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/.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. --- ...9a2b3ef792d0acfdcecff7c8fd50362454a69.json | 170 +++++ ...6a93569a3e21c0d6a8393871139f95f9612ba.json | 98 +++ ...143b69def99f1e2113817ff6b9b2bbfc8a2b9.json | 40 ++ ...27b28063ef3b41fad9188fbc10bc9cdfbb536.json | 173 +++++ ...825fdd47bf32d4d28af91d0ac79003d3e95eb.json | 40 ++ ...80375fb37576899499a0689cb57eb05d6c4d1.json | 40 ++ ...96ebc5f80922c01d4187052e03f05c5ce00e6.json | 110 +++ ...1e6e2a26abef3c078190d88f6732e45b39be6.json | 158 +++++ README.md | 2 + src/ai/insight.rs | 116 +++- src/constant.rs | 18 + src/db/insight.rs | 238 ++++++- src/web/insights.rs | 303 +++++++- src/web/mod.rs | 43 ++ src/web/podcast.rs | 40 +- tests/insight_report.rs | 645 ++++++++++++++++++ tests/integration.rs | 2 +- tests/limits_completeness.rs | 10 + 18 files changed, 2192 insertions(+), 54 deletions(-) create mode 100644 .sqlx/query-14e1fd9d16713ee60c209e545fb9a2b3ef792d0acfdcecff7c8fd50362454a69.json create mode 100644 .sqlx/query-34ecb6b00feed60a86453a9ef7b6a93569a3e21c0d6a8393871139f95f9612ba.json create mode 100644 .sqlx/query-4a50c4e5b4c369736b0a5b55dfd143b69def99f1e2113817ff6b9b2bbfc8a2b9.json create mode 100644 .sqlx/query-b72c252f9cf975c3b72208812b427b28063ef3b41fad9188fbc10bc9cdfbb536.json create mode 100644 .sqlx/query-d49ecd80b59524287c3d6df8c7f825fdd47bf32d4d28af91d0ac79003d3e95eb.json create mode 100644 .sqlx/query-df0a13a99b74b5a298ff8a7dbe680375fb37576899499a0689cb57eb05d6c4d1.json create mode 100644 .sqlx/query-fd5086c4a2049ebe1f41adfb7e996ebc5f80922c01d4187052e03f05c5ce00e6.json create mode 100644 .sqlx/query-fd55f76226b8fdc1426564e54a31e6e2a26abef3c078190d88f6732e45b39be6.json create mode 100644 tests/insight_report.rs diff --git a/.sqlx/query-14e1fd9d16713ee60c209e545fb9a2b3ef792d0acfdcecff7c8fd50362454a69.json b/.sqlx/query-14e1fd9d16713ee60c209e545fb9a2b3ef792d0acfdcecff7c8fd50362454a69.json new file mode 100644 index 0000000..e0e2825 --- /dev/null +++ b/.sqlx/query-14e1fd9d16713ee60c209e545fb9a2b3ef792d0acfdcecff7c8fd50362454a69.json @@ -0,0 +1,170 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT audience, product, rule_id, rule_version, scope, about, audience_role,\n course, evidence AS \"evidence: SqlJson\",\n confidence, created_at, expires_at, retain_until\n FROM zeka_recommendation ORDER BY audience, created_at, rule_id", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "audience", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "audience" + } + } + }, + { + "ordinal": 1, + "name": "product", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "product" + } + } + }, + { + "ordinal": 2, + "name": "rule_id", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "rule_id" + } + } + }, + { + "ordinal": 3, + "name": "rule_version", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "rule_version" + } + } + }, + { + "ordinal": 4, + "name": "scope", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "scope" + } + } + }, + { + "ordinal": 5, + "name": "about", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "about" + } + } + }, + { + "ordinal": 6, + "name": "audience_role", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "audience_role" + } + } + }, + { + "ordinal": 7, + "name": "course", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "course" + } + } + }, + { + "ordinal": 8, + "name": "evidence: SqlJson", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "evidence" + } + } + }, + { + "ordinal": 9, + "name": "confidence", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "confidence" + } + } + }, + { + "ordinal": 10, + "name": "created_at", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "created_at" + } + } + }, + { + "ordinal": 11, + "name": "expires_at", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "expires_at" + } + } + }, + { + "ordinal": 12, + "name": "retain_until", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_recommendation", + "name": "retain_until" + } + } + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false, + false, + false, + false, + true, + true, + false, + true, + false, + false, + false, + false, + false + ] + }, + "hash": "14e1fd9d16713ee60c209e545fb9a2b3ef792d0acfdcecff7c8fd50362454a69" +} diff --git a/.sqlx/query-34ecb6b00feed60a86453a9ef7b6a93569a3e21c0d6a8393871139f95f9612ba.json b/.sqlx/query-34ecb6b00feed60a86453a9ef7b6a93569a3e21c0d6a8393871139f95f9612ba.json new file mode 100644 index 0000000..b2d7ab8 --- /dev/null +++ b/.sqlx/query-34ecb6b00feed60a86453a9ef7b6a93569a3e21c0d6a8393871139f95f9612ba.json @@ -0,0 +1,98 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT student, trigger, course, fact, window_from, window_to,\n evidence AS \"evidence: SqlJson\"\n FROM zeka_attention_item ORDER BY student, ord", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "student", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "zeka_attention_item", + "name": "student" + } + } + }, + { + "ordinal": 1, + "name": "trigger", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_attention_item", + "name": "trigger" + } + } + }, + { + "ordinal": 2, + "name": "course", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "zeka_attention_item", + "name": "course" + } + } + }, + { + "ordinal": 3, + "name": "fact", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_attention_item", + "name": "fact" + } + } + }, + { + "ordinal": 4, + "name": "window_from", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_attention_item", + "name": "window_from" + } + } + }, + { + "ordinal": 5, + "name": "window_to", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_attention_item", + "name": "window_to" + } + } + }, + { + "ordinal": 6, + "name": "evidence: SqlJson", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "zeka_attention_item", + "name": "evidence" + } + } + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false, + false, + true, + false, + false, + false, + false + ] + }, + "hash": "34ecb6b00feed60a86453a9ef7b6a93569a3e21c0d6a8393871139f95f9612ba" +} diff --git a/.sqlx/query-4a50c4e5b4c369736b0a5b55dfd143b69def99f1e2113817ff6b9b2bbfc8a2b9.json b/.sqlx/query-4a50c4e5b4c369736b0a5b55dfd143b69def99f1e2113817ff6b9b2bbfc8a2b9.json new file mode 100644 index 0000000..e195971 --- /dev/null +++ b/.sqlx/query-4a50c4e5b4c369736b0a5b55dfd143b69def99f1e2113817ff6b9b2bbfc8a2b9.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id, name FROM school WHERE slug = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "school", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "name", + "type_info": "Text", + "origin": { + "Table": { + "table": "school", + "name": "name" + } + } + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "4a50c4e5b4c369736b0a5b55dfd143b69def99f1e2113817ff6b9b2bbfc8a2b9" +} diff --git a/.sqlx/query-b72c252f9cf975c3b72208812b427b28063ef3b41fad9188fbc10bc9cdfbb536.json b/.sqlx/query-b72c252f9cf975c3b72208812b427b28063ef3b41fad9188fbc10bc9cdfbb536.json new file mode 100644 index 0000000..87184ff --- /dev/null +++ b/.sqlx/query-b72c252f9cf975c3b72208812b427b28063ef3b41fad9188fbc10bc9cdfbb536.json @@ -0,0 +1,173 @@ +{ + "db_name": "PostgreSQL", + "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", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "run_day", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_run", + "name": "run_day" + } + } + }, + { + "ordinal": 1, + "name": "started_at", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "started_at" + } + } + }, + { + "ordinal": 2, + "name": "finished_at", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "finished_at" + } + } + }, + { + "ordinal": 3, + "name": "status", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_run", + "name": "status" + } + } + }, + { + "ordinal": 4, + "name": "duration_ms", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "duration_ms" + } + } + }, + { + "ordinal": 5, + "name": "students_total", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "students_total" + } + } + }, + { + "ordinal": 6, + "name": "students_ok", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "students_ok" + } + } + }, + { + "ordinal": 7, + "name": "students_failed", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "students_failed" + } + } + }, + { + "ordinal": 8, + "name": "students_skipped", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "students_skipped" + } + } + }, + { + "ordinal": 9, + "name": "rows_written", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "rows_written" + } + } + }, + { + "ordinal": 10, + "name": "budget_exceeded", + "type_info": "Bool", + "origin": { + "Table": { + "table": "zeka_run", + "name": "budget_exceeded" + } + } + }, + { + "ordinal": 11, + "name": "budget_ms", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "budget_ms" + } + } + }, + { + "ordinal": 12, + "name": "retain_until", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_run", + "name": "retain_until" + } + } + } + ], + "parameters": { + "Left": [ + "Text", + "Int8" + ] + }, + "nullable": [ + false, + false, + true, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false + ] + }, + "hash": "b72c252f9cf975c3b72208812b427b28063ef3b41fad9188fbc10bc9cdfbb536" +} diff --git a/.sqlx/query-d49ecd80b59524287c3d6df8c7f825fdd47bf32d4d28af91d0ac79003d3e95eb.json b/.sqlx/query-d49ecd80b59524287c3d6df8c7f825fdd47bf32d4d28af91d0ac79003d3e95eb.json new file mode 100644 index 0000000..c760357 --- /dev/null +++ b/.sqlx/query-d49ecd80b59524287c3d6df8c7f825fdd47bf32d4d28af91d0ac79003d3e95eb.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT run, module FROM zeka_run_failed_module\n WHERE run = ANY($1) ORDER BY run, ord", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "run", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_run_failed_module", + "name": "run" + } + } + }, + { + "ordinal": 1, + "name": "module", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_run_failed_module", + "name": "module" + } + } + } + ], + "parameters": { + "Left": [ + "TextArray" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "d49ecd80b59524287c3d6df8c7f825fdd47bf32d4d28af91d0ac79003d3e95eb" +} diff --git a/.sqlx/query-df0a13a99b74b5a298ff8a7dbe680375fb37576899499a0689cb57eb05d6c4d1.json b/.sqlx/query-df0a13a99b74b5a298ff8a7dbe680375fb37576899499a0689cb57eb05d6c4d1.json new file mode 100644 index 0000000..6069f5d --- /dev/null +++ b/.sqlx/query-df0a13a99b74b5a298ff8a7dbe680375fb37576899499a0689cb57eb05d6c4d1.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT run, student FROM zeka_run_pending\n WHERE run = ANY($1) ORDER BY run, ord", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "run", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_run_pending", + "name": "run" + } + } + }, + { + "ordinal": 1, + "name": "student", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "zeka_run_pending", + "name": "student" + } + } + } + ], + "parameters": { + "Left": [ + "TextArray" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "df0a13a99b74b5a298ff8a7dbe680375fb37576899499a0689cb57eb05d6c4d1" +} diff --git a/.sqlx/query-fd5086c4a2049ebe1f41adfb7e996ebc5f80922c01d4187052e03f05c5ce00e6.json b/.sqlx/query-fd5086c4a2049ebe1f41adfb7e996ebc5f80922c01d4187052e03f05c5ce00e6.json new file mode 100644 index 0000000..7c16e7f --- /dev/null +++ b/.sqlx/query-fd5086c4a2049ebe1f41adfb7e996ebc5f80922c01d4187052e03f05c5ce00e6.json @@ -0,0 +1,110 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT student,\n marks AS \"marks?: SqlJson\",\n attendance AS \"attendance?: SqlJson\",\n submission AS \"submission?: SqlJson\",\n study AS \"study?: SqlJson\",\n confidence, computed_at, retain_until\n FROM zeka_student_summary ORDER BY student", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "student", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "zeka_student_summary", + "name": "student" + } + } + }, + { + "ordinal": 1, + "name": "marks?: SqlJson", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "zeka_student_summary", + "name": "marks" + } + } + }, + { + "ordinal": 2, + "name": "attendance?: SqlJson", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "zeka_student_summary", + "name": "attendance" + } + } + }, + { + "ordinal": 3, + "name": "submission?: SqlJson", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "zeka_student_summary", + "name": "submission" + } + } + }, + { + "ordinal": 4, + "name": "study?: SqlJson", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "zeka_student_summary", + "name": "study" + } + } + }, + { + "ordinal": 5, + "name": "confidence", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_student_summary", + "name": "confidence" + } + } + }, + { + "ordinal": 6, + "name": "computed_at", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_student_summary", + "name": "computed_at" + } + } + }, + { + "ordinal": 7, + "name": "retain_until", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_student_summary", + "name": "retain_until" + } + } + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false, + true, + true, + true, + true, + false, + false, + false + ] + }, + "hash": "fd5086c4a2049ebe1f41adfb7e996ebc5f80922c01d4187052e03f05c5ce00e6" +} diff --git a/.sqlx/query-fd55f76226b8fdc1426564e54a31e6e2a26abef3c078190d88f6732e45b39be6.json b/.sqlx/query-fd55f76226b8fdc1426564e54a31e6e2a26abef3c078190d88f6732e45b39be6.json new file mode 100644 index 0000000..33b0255 --- /dev/null +++ b/.sqlx/query-fd55f76226b8fdc1426564e54a31e6e2a26abef3c078190d88f6732e45b39be6.json @@ -0,0 +1,158 @@ +{ + "db_name": "PostgreSQL", + "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", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "student", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "student" + } + } + }, + { + "ordinal": 1, + "name": "dimension", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "dimension" + } + } + }, + { + "ordinal": 2, + "name": "label", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "label" + } + } + }, + { + "ordinal": 3, + "name": "n_answers", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "n_answers" + } + } + }, + { + "ordinal": 4, + "name": "n_correct", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "n_correct" + } + } + }, + { + "ordinal": 5, + "name": "accuracy", + "type_info": "Float8", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "accuracy" + } + } + }, + { + "ordinal": 6, + "name": "overall_n_answers", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "overall_n_answers" + } + } + }, + { + "ordinal": 7, + "name": "overall_accuracy", + "type_info": "Float8", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "overall_accuracy" + } + } + }, + { + "ordinal": 8, + "name": "contrast", + "type_info": "Float8", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "contrast" + } + } + }, + { + "ordinal": 9, + "name": "confidence", + "type_info": "Text", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "confidence" + } + } + }, + { + "ordinal": 10, + "name": "computed_at", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "computed_at" + } + } + }, + { + "ordinal": 11, + "name": "retain_until", + "type_info": "Int8", + "origin": { + "Table": { + "table": "zeka_student_segment_profile", + "name": "retain_until" + } + } + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false + ] + }, + "hash": "fd55f76226b8fdc1426564e54a31e6e2a26abef3c078190d88f6732e45b39be6" +} diff --git a/README.md b/README.md index 1c7a81d..e2c57fd 100644 --- a/README.md +++ b/README.md @@ -1332,6 +1332,8 @@ window filtering, before paging; negative values are a `400` naming the field. | 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. | | 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=`. | | POST | `/insights/runs` | manager | Store one compute run's ledger row (with its pending students and failed modules, both replaced). | +| GET | `/insights/runs/{run_day}/report` | manager | The stored report document, streamed. | +| 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. | | GET | `/insights/schools` | builder | The deployment's active schools, by slug — the directory a shared AI fleet schedules over. | | POST | `/insights/segments` | manager | Store a batch of ZEKA's question-segment labels (and each question's dimension split). | | 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. | diff --git a/src/ai/insight.rs b/src/ai/insight.rs index b02c728..08c840a 100644 --- a/src/ai/insight.rs +++ b/src/ai/insight.rs @@ -5,8 +5,11 @@ //! //! * **Outbound** (the backend dispatches to the service): //! [`AI_INSIGHT_STUDENT_CAPABILITY`] — one student, on demand; -//! [`AI_INSIGHT_REFRESH_CAPABILITY`] — a school-wide sweep, on demand. The -//! dispatches below carry them ([`compute_student`], [`refresh`]). +//! [`AI_INSIGHT_REFRESH_CAPABILITY`] — a school-wide sweep, on demand; +//! [`AI_INSIGHT_REPORT_CAPABILITY`] — a school-level report document, on +//! demand (its request carries the rows the backend already holds). The +//! dispatches below carry them ([`compute_student`], [`refresh`], +//! [`report`]). //! * **Inbound** (the service calls the backend): the nine operations of //! [`AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY`]'s family — the storage surface //! ZEKA's `zeka_*` rows are written and read through, because **no AI @@ -39,11 +42,15 @@ use serde_json::Value; use crate::ai::AiBridge; use crate::ai::error::AiError; use crate::ai::protocol::FrameError; -use crate::constant::{AI_INSIGHT_REFRESH_TIMEOUT_SECS, AI_INSIGHT_STUDENT_TIMEOUT_SECS}; +use crate::constant::{ + AI_INSIGHT_REFRESH_TIMEOUT_SECS, AI_INSIGHT_REPORT_TIMEOUT_SECS, + AI_INSIGHT_STUDENT_TIMEOUT_SECS, +}; use crate::tenant::Slug; pub use crate::constant::{ - AI_INSIGHT_CLASS_CAPABILITY, AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY, + AI_INSIGHT_CLASS_CAPABILITY, AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_REPORT_CAPABILITY, + AI_INSIGHT_STUDENT_CAPABILITY, }; /// What the backend asks a service to compute for one student. @@ -167,7 +174,7 @@ pub struct RefreshRequest { /// The receipt for a refresh: what the sweep did, once it did it. The run's /// own ledger is `zeka_run` in the school database, which is what a reader /// polls while this answer is still on its way. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct RefreshResponse { #[serde(default)] pub started_at: Option, @@ -182,6 +189,76 @@ pub struct RefreshResponse { pub failed: Vec, } +/// `kind` on a school-level report request — the one document kind this +/// dispatch asks for today. Spelled as the service's own vocabulary spells it +/// (`okul`), because it selects a builder there. +pub const REPORT_KIND_SCHOOL: &str = "okul"; + +/// What the backend asks a service to render for a whole school, for one run +/// day. +/// +/// Unlike the other two outbound requests, this one **carries the data**: the +/// service computes nothing here, and it may not read a school's database, so +/// the backend sends the rows it already holds from its own `zeka_*` tables — +/// the same serde rows the storage surface writes ([`SummaryRow`], +/// [`RecommendationRow`], [`ProfileRow`], [`RunRow`]) — and the service +/// renders them into one self-contained document. +/// +/// A run day with no `zeka_run` row, or one whose tables are empty, is a +/// legal request: the lists are then empty (or missing the absent day) and +/// the document's own `notes` say so. Nothing here refuses a day the ledger +/// does not know. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ReportRequest { + /// [`REPORT_KIND_SCHOOL`] — which builder the service runs. + pub kind: String, + /// The run day the document is about, `YYYY-MM-DD`. + pub run_day: String, + /// Who asked for the document — see [`StudentRequest::requested_by`]. The + /// rendering reads nothing, but the service's logs name the requester. + pub requested_by: String, + /// The school's own identity, so the document prints a display name + /// rather than a slug. + pub school: ReportSchool, + /// Every stored summary (with its attention items) in the school. + pub summaries: Vec, + pub recommendations: Vec, + pub profiles: Vec, + /// The ledger rows the document may show: the named day first when it + /// exists, then the newest days, at most a handful. + pub runs: Vec, +} + +/// What the service rendered. `html` is the one required member: a response +/// without a document is not a partial answer, it is a dispatch that produced +/// nothing to store, and [`crate::ai::insight::report`]'s caller would rather +/// refuse it than persist an empty file. The rest is the service's own +/// bookkeeping, optional for the same reason every response member here is. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ReportResponse { + #[serde(default)] + pub kind: Option, + #[serde(default)] + pub run_day: Option, + /// `html` today — the format the stored artifact is served as. Recorded + /// rather than assumed, so a future format is visible on the wire. + #[serde(default)] + pub format: Option, + /// The self-contained document, `` first. + pub html: String, + #[serde(default)] + pub byte_size: Option, + /// Whether the service clipped the document (a row set past its own + /// ceiling). Stored and reported verbatim: a clipped document must not + /// read as a complete one. + #[serde(default)] + pub truncated: bool, + /// The service's own remarks about the document — e.g. that the run day + /// has no ledger row. Shown to the manager beside the artifact. + #[serde(default)] + pub notes: Vec, +} + /// Compute one student's insight, awaited. No capability check here: the /// caller decides what "no service" means, and every caller today is an HTTP /// door that has already answered `503` for it ([`crate::web::insights`]). @@ -217,8 +294,27 @@ pub async fn refresh( .await } -/// One request, one typed answer — the two dispatches differ only in -/// capability, deadline and payload type. +/// Ask for one school-level report document, awaited. The request carries +/// every row the document needs, and the answer carries the rendered HTML +/// back; the deadline is [`AI_INSIGHT_REPORT_TIMEOUT_SECS`]. The caller +/// stores the document — this function only moves it. +pub async fn report( + bridge: &AiBridge, + school: &Slug, + request: &ReportRequest, +) -> Result { + dispatch( + bridge, + school, + AI_INSIGHT_REPORT_CAPABILITY, + AI_INSIGHT_REPORT_TIMEOUT_SECS, + request, + ) + .await +} + +/// One request, one typed answer — the dispatches differ only in capability, +/// deadline and payload type. /// /// A reply that does not parse as the expected type is a /// [`FrameError::Malformed`]: the bytes were JSON, but not this contract's @@ -261,9 +357,9 @@ fn malformed(err: serde_json::Error) -> AiError { pub use crate::db::insight::{ AttentionRow, PendingList, ProfileRow, ProfileWriteRequest, PurgeRequest, RecommendationRow, - RecommendationWriteRequest, RunRow, RunWriteRequest, SchoolDirectory, SegmentConfidences, - SegmentLabels, SegmentRow, SegmentWriteRequest, SummaryRow, SummaryWriteRequest, - TableVerdicts, WriteReceipt, + RecommendationWriteRequest, ReportSchool, RunRow, RunWriteRequest, SchoolDirectory, + SegmentConfidences, SegmentLabels, SegmentRow, SegmentWriteRequest, SummaryRow, + SummaryWriteRequest, TableVerdicts, WriteReceipt, }; use crate::constant::{ diff --git a/src/constant.rs b/src/constant.rs index 71a26db..a141c76 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -635,6 +635,24 @@ pub const AI_INSIGHT_REFRESH_CAPABILITY: &str = "insight.refresh"; /// summary. pub const AI_INSIGHT_REFRESH_TIMEOUT_SECS: u64 = 300; +/// The capability an AI service declares to render a school-level report +/// document. The service computes nothing here: the backend already holds +/// every row the document is built from (the `zeka_*` tables), sends them in +/// the request, and stores the self-contained HTML the service answers with. +/// The rendering lives in the service because the reader/report-package +/// contract does — the backend never composes an insight document, the same +/// way it never composes an insight row. +pub const AI_INSIGHT_REPORT_CAPABILITY: &str = "insight.report"; + +/// Deadline on one `insight.report` round trip. Sized like the refresh sweep's +/// ceiling, because it renders the same school-wide row set: the service does +/// no reads and no model calls, but a large school's rows are already on its +/// side of the wire when this starts ticking. Unlike the other two insight +/// dispatches, a caller *waits on this one* — the door stores the document +/// before it answers, so the deadline is also the ceiling on what a manager +/// can be made to wait for. +pub const AI_INSIGHT_REPORT_TIMEOUT_SECS: u64 = 300; + // ---- zeka's storage surface (capabilities the *backend* serves) ------------ // // The three constants above are capabilities an AI service *declares*: the diff --git a/src/db/insight.rs b/src/db/insight.rs index 6d3feed..f453a59 100644 --- a/src/db/insight.rs +++ b/src/db/insight.rs @@ -43,6 +43,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use serde_json::Value as JsonValue; use sqlx::AssertSqlSafe; +use sqlx::types::Json as SqlJson; use utoipa::ToSchema; use uuid::Uuid; @@ -313,6 +314,18 @@ pub struct SchoolDirectory { pub schools: Vec, } +/// One school's own identity, as a rendered report prints it. The bridge +/// frame already names the school by slug, but a document that reaches a +/// manager's screen carries the display name, and the control row is the only +/// authority on it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct ReportSchool { + /// `school.id` — the surrogate key, not the slug: a slug may be renamed. + pub id: String, + pub slug: String, + pub name: String, +} + // ---- shared validation ----------------------------------------------------- /// 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 { /// `YYYY-MM-DD`, the ledger's key. Checked here so a malformed day is the /// caller's `invalid_payload` and not a CHECK violation dressed as a `500`. -fn run_day_ok(day: &str) -> bool { +/// The report doors share it: a run day shapes a blob key there, and a +/// caller-supplied path segment that shapes a path is validated before it is +/// joined. +pub fn run_day_ok(day: &str) -> bool { let bytes = day.as_bytes(); bytes.len() == 10 && bytes @@ -841,6 +857,226 @@ pub async fn active_schools(control: &Database) -> Result Result, AppError> { + let row = sqlx::query!("SELECT id, name FROM school WHERE slug = $1", slug) + .fetch_optional(control) + .await?; + Ok(row.map(|row| ReportSchool { + id: row.id.to_string(), + slug: slug.to_string(), + name: row.name, + })) +} + +// ---- the school-wide reads the report payload carries ----------------------- +// +// Every read above is per-student or per-audience, because that is every +// reader this nest had. A *document* about the school is the first caller that +// needs the whole row set at once, so these four project each table straight +// into the wire rows the bridge payload carries ([`SummaryRow`], +// [`RecommendationRow`], [`ProfileRow`], [`RunRow`]) — one mapping, in one +// place, shared by SQL and the wire. No filters: the document's own reader +// (the service's report package) decides what it shows, and a backend that +// pre-filtered would be a second, silent author of the report. + +/// Every stored summary with its attention items, in student order. The +/// attention list is one query for the whole set, grouped by student — not +/// one query per summary. +pub async fn all_summaries(db: &Database) -> Result, AppError> { + let rows = sqlx::query!( + r#"SELECT student, + marks AS "marks?: SqlJson", + attendance AS "attendance?: SqlJson", + submission AS "submission?: SqlJson", + study AS "study?: SqlJson", + confidence, computed_at, retain_until + FROM zeka_student_summary ORDER BY student"# + ) + .fetch_all(db) + .await?; + let mut attention: BTreeMap> = BTreeMap::new(); + for row in sqlx::query!( + r#"SELECT student, trigger, course, fact, window_from, window_to, + evidence AS "evidence: SqlJson" + FROM zeka_attention_item ORDER BY student, ord"# + ) + .fetch_all(db) + .await? + { + attention.entry(row.student).or_default().push(AttentionRow { + trigger: row.trigger, + course: row.course.map(|course| course.to_string()), + fact: row.fact, + window_from: row.window_from, + window_to: row.window_to, + evidence: row.evidence.0, + }); + } + Ok(rows + .into_iter() + .map(|row| SummaryRow { + attention: attention.remove(&row.student).unwrap_or_default(), + student: row.student.to_string(), + marks: row.marks.map(|json| json.0), + attendance: row.attendance.map(|json| json.0), + submission: row.submission.map(|json| json.0), + study: row.study.map(|json| json.0), + confidence: row.confidence, + computed_at: row.computed_at, + retain_until: row.retain_until, + }) + .collect()) +} + +/// Every stored card, whatever its audience, in a stable order. The write +/// merged each row's `limitation` into its stored evidence object, so the +/// read leaves the [write-side](RecommendationRow::limitation) field empty — +/// a second copy here could only disagree with the one inside `evidence`. +/// +/// The wire row carries no `dismissed_at`, so the stored dismissal trail +/// (`dismissed_at`/`dismiss_by`/`dismiss_reason` on the table) does not +/// travel: a consumer that gates on dismissal cannot fire on this read. That +/// is a known gap of the report payload's contract — the reader that filters +/// dismissals is the per-audience read ([`crate::web::insights`]), and +/// widening the row here is a contract change this lane does not make. +pub async fn all_recommendations(db: &Database) -> Result, AppError> { + let rows = sqlx::query!( + r#"SELECT audience, product, rule_id, rule_version, scope, about, audience_role, + course, evidence AS "evidence: SqlJson", + confidence, created_at, expires_at, retain_until + FROM zeka_recommendation ORDER BY audience, created_at, rule_id"# + ) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|row| RecommendationRow { + audience: row.audience.to_string(), + product: row.product, + rule_id: row.rule_id, + rule_version: row.rule_version, + scope: row.scope, + about: row.about.map(|about| about.to_string()), + audience_role: row.audience_role, + course: row.course.map(|course| course.to_string()), + evidence: row.evidence.0, + limitation: None, + confidence: row.confidence, + // The column is `created_at`; the wire row spells it `computed_at`, + // and the write maps the same pair the same way. + computed_at: row.created_at, + expires_at: row.expires_at, + retain_until: row.retain_until, + }) + .collect()) +} + +/// Every stored segment profile, in student order. Noise rows (`confidence = +/// 'none'`) are included: this read feeds a document, and the display floor is +/// the reader's rule, applied where the reader applies it. +pub async fn all_profiles(db: &Database) -> Result, AppError> { + let rows = sqlx::query!( + r#"SELECT student, dimension, label, n_answers, n_correct, accuracy, + overall_n_answers, overall_accuracy, contrast, confidence, + computed_at, retain_until + FROM zeka_student_segment_profile ORDER BY student, dimension, label"# + ) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|row| ProfileRow { + student: row.student.to_string(), + dimension: row.dimension, + label: row.label, + n_answers: row.n_answers, + n_correct: row.n_correct, + accuracy: row.accuracy, + overall_n_answers: row.overall_n_answers, + overall_accuracy: row.overall_accuracy, + contrast: row.contrast, + confidence: row.confidence, + computed_at: row.computed_at, + retain_until: row.retain_until, + }) + .collect()) +} + +/// How many ledger rows a report carries: the named day plus recent context. +/// Deliberately small — the ledger is context for the document, which is +/// about one day, not a ledger dump. +const REPORT_RUNS: i64 = 5; + +/// The run ledger a report carries, with each run's children. The named day +/// leads when it exists (a report about it must be able to show it even if it +/// has scrolled out of the newest rows), then the newest days follow. +pub async fn runs_for_report(db: &Database, run_day: &str) -> Result, AppError> { + let rows = sqlx::query!( + r#"SELECT run_day, started_at, finished_at, status, duration_ms, + students_total, students_ok, students_failed, students_skipped, + rows_written, budget_exceeded, budget_ms, retain_until + FROM zeka_run + ORDER BY (run_day = $1) DESC, started_at DESC, run_day DESC + LIMIT $2"#, + run_day, + REPORT_RUNS, + ) + .fetch_all(db) + .await?; + let days: Vec = rows.iter().map(|row| row.run_day.clone()).collect(); + let mut pending: BTreeMap> = BTreeMap::new(); + for row in sqlx::query!( + r#"SELECT run, student FROM zeka_run_pending + WHERE run = ANY($1) ORDER BY run, ord"#, + &days + ) + .fetch_all(db) + .await? + { + pending + .entry(row.run) + .or_default() + .push(row.student.to_string()); + } + let mut failed: BTreeMap> = BTreeMap::new(); + for row in sqlx::query!( + r#"SELECT run, module FROM zeka_run_failed_module + WHERE run = ANY($1) ORDER BY run, ord"#, + &days + ) + .fetch_all(db) + .await? + { + failed.entry(row.run).or_default().push(row.module); + } + Ok(rows + .into_iter() + .map(|row| RunRow { + pending_students: pending.remove(&row.run_day).unwrap_or_default(), + failed_modules: failed.remove(&row.run_day).unwrap_or_default(), + run_day: row.run_day, + started_at: row.started_at, + finished_at: row.finished_at, + status: row.status, + duration_ms: row.duration_ms, + students_total: row.students_total, + students_ok: row.students_ok, + students_failed: row.students_failed, + students_skipped: row.students_skipped, + rows_written: row.rows_written, + budget_exceeded: row.budget_exceeded, + budget_ms: row.budget_ms, + retain_until: row.retain_until, + }) + .collect()) +} + // ---- retention ------------------------------------------------------------- /// The nine tables a sweep walks, children before their parents: the foreign diff --git a/src/web/insights.rs b/src/web/insights.rs index e3b03ac..cb60c2c 100644 --- a/src/web/insights.rs +++ b/src/web/insights.rs @@ -41,10 +41,20 @@ //! student's compute can outlast the request-timeout layer //! ([`crate::constant::REQUEST_TIMEOUT_SECS`]). The client polls the stored //! rows — the compute doors change nothing a reader cannot already see. +//! +//! The **report** doors are the one exception, and deliberately: building the +//! school's document is not a compute the service does on its own schedule — +//! it is one artifact the manager asked for, rendered from rows the backend +//! already holds, so `POST /runs/{run_day}/report` waits, stores the returned +//! HTML under the school's own blob directory, and answers `200` with what +//! was stored. `GET /runs/{run_day}/report` streams that document back. use axum::Json; +use axum::body::Body; use axum::extract::{Path, Query}; +use axum::http::HeaderValue; use axum::http::StatusCode; +use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS}; use axum::response::{IntoResponse, Response}; use serde::{Deserialize, Serialize}; use serde_json::Value as JsonValue; @@ -53,14 +63,16 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; +use crate::ai::error::AiError; use crate::ai::insight::{ - self, PendingList, ProfileWriteRequest, PurgeRequest, ROSTER_SOURCE_EXPLICIT, - ROSTER_SOURCE_SCHOOL, RecommendationWriteRequest, RefreshRequest, RunWriteRequest, + self, PendingList, ProfileWriteRequest, PurgeRequest, REPORT_KIND_SCHOOL, ROSTER_SOURCE_EXPLICIT, + ROSTER_SOURCE_SCHOOL, RecommendationWriteRequest, RefreshRequest, ReportRequest, RunWriteRequest, SchoolDirectory, SegmentWriteRequest, StudentRequest, SummaryWriteRequest, TableVerdicts, WriteReceipt, }; use crate::constant::{ - AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY, MAX_INSIGHT_REFRESH_STUDENTS, + AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_REPORT_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY, + MAX_INSIGHT_REFRESH_STUDENTS, }; use crate::database::Database; use crate::db; @@ -75,7 +87,9 @@ use crate::state::AppState; use crate::tenant::ResolvedTenant; use crate::web::tenant_state::State; -use super::{CurrentUser, Page, PageParams, RequireBuilder, RequireManager, ai_unavailable, paginate}; +use super::{ + CurrentUser, Page, PageParams, RequireBuilder, RequireManager, ai_unavailable, paginate, pump, +}; /// The single `now` every card read is filtered against. ZEKA stores unix /// milliseconds, so "expired" is a comparison, not a projection. @@ -89,6 +103,7 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(my_insight)) .routes(routes!(student_insight, compute_student)) .routes(routes!(list_runs, write_run)) + .routes(routes!(generate_report, serve_report)) .routes(routes!(write_summaries)) .routes(routes!(write_recommendations)) .routes(routes!(write_segments)) @@ -299,6 +314,286 @@ fn accepted() -> Response { .into_response() } +// ---- the report doors ------------------------------------------------------ + +/// The receipt for a stored report. `generated_at` is this backend's clock the +/// moment the document was stored — the artifact's age is what a manager +/// re-clicking the button wants to see. +#[derive(Serialize, ToSchema)] +struct ReportReceipt { + /// The run day the document is about, `YYYY-MM-DD`. + #[schema(example = "2026-09-17")] + run_day: String, + /// The stored document's size in bytes. + byte_size: u64, + /// Whether the service clipped the document. A clipped report must not + /// read as a complete one. + truncated: bool, + /// The service's own remarks about the document — e.g. that the run day + /// has no ledger row. Shown to the manager beside the artifact. + notes: Vec, + /// When this backend stored the document, unix milliseconds. + generated_at: i64, +} + +/// Where a school's generated report documents live under its blob directory: +/// one file per run day. The day is validated before it is joined (see +/// [`db::insight::run_day_ok`]), so the key can carry no separator and no +/// `..`. +const REPORT_DIR: &str = "zeka_report"; + +fn report_key(run_day: &str) -> String { + format!("{REPORT_DIR}/{run_day}.html") +} + +/// 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. +/// +/// Manager+ only: the document is whole-school, like the refresh sweep and the +/// run ledger. The payload is read from this school's own `zeka_*` tables and +/// dispatched to the service that declares `insight.report`; the service may +/// not read a database, so every row the document needs travels in the +/// request — the same serde rows the storage surface writes. +/// +/// A run day with no ledger row, or one whose tables are empty, is still a +/// legal request: the service renders what it was given and says so in +/// `notes`. Refusals: `503` when no service offers the capability, or it did +/// not answer — nothing was stored; `429` when every worker is at capacity; +/// and the service's own typed refusals, mapped per class by +/// [`report_refusal`]. +#[utoipa::path( + post, + path = "/runs/{run_day}/report", + tag = "insights", + security(("session_cookie" = [])), + params(("run_day" = String, Path, description = "The run day, `YYYY-MM-DD`")), + responses( + (status = 200, description = "The document was rendered and stored; the receipt says what was stored", body = ReportReceipt), + (status = 400, description = "`run_day` is not a `YYYY-MM-DD` day, or the AI service refused the composed request", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (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), + (status = 413, description = "The rendered document is over the AI service's size ceiling; nothing was stored", body = ErrorResponse), + (status = 429, description = "Every AI service offering `insight.report` is at capacity", body = ErrorResponse), + (status = 503, description = "No AI service offers `insight.report`, or it did not answer; nothing was stored", body = ErrorResponse), + ), +)] +async fn generate_report( + State(st): State, + tenant: ResolvedTenant, + RequireManager(user): RequireManager, + Path(run_day): Path, +) -> Result { + if !db::insight::run_day_ok(&run_day) { + return Err(AppError::Validation(ValidationError::Invalid { + field: "run_day", + reason: "must be a `YYYY-MM-DD` day", + })); + } + let Some(bridge) = st.ai.clone() else { + return Ok(ai_unavailable( + "the AI service is not enabled on this deployment", + )); + }; + if !bridge.has_capability(AI_INSIGHT_REPORT_CAPABILITY) { + return Ok(ai_unavailable("no AI service is connected right now")); + } + let Some(school) = + db::insight::school_identity(st.tenants.control(), tenant.slug.as_str()).await? + else { + return Err(AppError::Internal(format!( + "the resolved school `{}` has no control row", + tenant.slug.as_str() + ))); + }; + let request = ReportRequest { + kind: REPORT_KIND_SCHOOL.to_string(), + run_day: run_day.clone(), + requested_by: user.get_id().key(), + school, + summaries: db::insight::all_summaries(&st.db).await?, + recommendations: db::insight::all_recommendations(&st.db).await?, + profiles: db::insight::all_profiles(&st.db).await?, + runs: db::insight::runs_for_report(&st.db, &run_day).await?, + }; + let answer = match insight::report(&bridge, &tenant.slug, &request).await { + Ok(answer) => answer, + Err(AiError::Remote { code, message }) => { + tracing::warn!("insight.report refused: {code}: {message}"); + return Err(report_refusal(code, message)); + } + Err(AiError::Busy(_)) => { + return Err(AppError::TooManyRequests { retry_after_secs: 5 }); + } + // No worker (the capability was withdrawn between the check and the + // dispatch), a timeout, a transport or protocol failure: the document + // cannot be produced now, and claiming otherwise would store nothing. + Err(err) => { + tracing::warn!("insight.report failed: {err}"); + return Ok(ai_unavailable( + "the AI service did not answer; nothing was stored", + )); + } + }; + // An empty document is not a document: storing it would serve a blank + // page as if it were the report, and a manager would read that as "the + // school has nothing to say". Refused, never persisted. + if answer.html.trim().is_empty() { + tracing::error!("insight.report answered with an empty document for {run_day}"); + return Err(AppError::Internal( + "the AI service answered with an empty document".to_string(), + )); + } + store_report(&st.files_path, &run_day, &answer.html).await?; + Ok(Json(ReportReceipt { + run_day, + byte_size: answer.html.len() as u64, + truncated: answer.truncated, + notes: answer.notes, + generated_at: now_millis(), + }) + .into_response()) +} + +/// The service's refusal vocabulary as this door's HTTP answer. +/// +/// The report service closes four codes (`hezarfen_zeka`'s handler) and a +/// client branches on the class each becomes: +/// +/// * `bad_request` — the service judged the composed request bad (an unserved +/// kind, a malformed day, a row field that is not a list, a school +/// disagreement). The payload is composed here, so this is a backend defect +/// and the caller can only be told the request was refused; the service's +/// own words go to the log. +/// * `insufficient_rows` — all four row lists were empty, so there is no +/// document to build. `409 report_empty`: no retry conjures data, a sweep +/// does. +/// * `document_too_large` — over the service's own HTML ceiling, which it +/// never truncates past. `413`. +/// * `internal` — the render failed on the service's side. `500`. +/// +/// Anything else is `409 report_refused` with the service's code and message +/// kept verbatim: a service may define codes this backend has never heard of, +/// and swallowing them would hide the one explanation a caller needs. +fn report_refusal(code: String, message: String) -> AppError { + match code.as_str() { + "bad_request" => AppError::Validation(ValidationError::Invalid { + field: "report", + reason: "the AI service refused the composed request; the reason is in the backend log", + }), + "insufficient_rows" => AppError::ConflictCoded { + code: "report_empty", + message: format!( + "the AI service has no rows to render a report from: {message}" + ), + }, + "document_too_large" => AppError::PayloadTooLarge(format!( + "the rendered report is over the AI service's size ceiling, and it does not truncate: {message}" + )), + "internal" => AppError::Internal(format!( + "the AI service failed to render the report: {message}" + )), + _ => AppError::ConflictCoded { + code: "report_refused", + message: format!("the AI service refused the report: {code}: {message}"), + }, + } +} + +/// The stored report document, streamed. +/// +/// `409 report_missing` when nothing has been generated for the day — a +/// refusal that covers a day the ledger has never heard of too: generation +/// accepts such a day on purpose (the document's `notes` say it), so a `404` +/// here could refuse a day the POST door had just answered `200` for. +#[utoipa::path( + get, + path = "/runs/{run_day}/report", + tag = "insights", + security(("session_cookie" = [])), + params(("run_day" = String, Path, description = "The run day, `YYYY-MM-DD`")), + responses( + (status = 200, description = "The stored document", content_type = "text/html"), + (status = 400, description = "`run_day` is not a `YYYY-MM-DD` day", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 409, description = "No report has been generated for this day (`report_missing`)", body = ErrorResponse), + ), +)] +async fn serve_report( + State(st): State, + RequireManager(_user): RequireManager, + Path(run_day): Path, +) -> Result { + if !db::insight::run_day_ok(&run_day) { + return Err(AppError::Validation(ValidationError::Invalid { + field: "run_day", + reason: "must be a `YYYY-MM-DD` day", + })); + } + let key = report_key(&run_day); + let path = crate::web::blob_path(&st.files_path, &key); + let file = tokio::fs::File::open(&path).await.map_err(|err| { + if err.kind() != std::io::ErrorKind::NotFound { + tracing::error!("could not open the stored report {key}: {err}"); + } + AppError::ConflictCoded { + code: "report_missing", + message: format!("no report has been generated for `{run_day}` yet"), + } + })?; + Ok(( + [ + ( + CONTENT_TYPE, + HeaderValue::from_static("text/html; charset=utf-8"), + ), + (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")), + (CACHE_CONTROL, HeaderValue::from_static("private, no-store")), + ], + Body::from_stream(pump(file)), + ) + .into_response()) +} + +/// Store the rendered document under the school's own blob directory. +/// +/// Written to a temp name and renamed into place: the artifact appears +/// atomically or not at all, so a reader — or a second POST racing this one — +/// can never open a half-written document. The temp file is removed if +/// anything fails before the rename. +async fn store_report( + files_path: &std::path::Path, + run_day: &str, + html: &str, +) -> Result<(), AppError> { + crate::web::ensure_files_dir(files_path).await?; + let dir = crate::web::blob_path(files_path, REPORT_DIR); + tokio::fs::create_dir_all(&dir).await.map_err(|err| { + AppError::Internal(format!("failed to create the report directory: {err}")) + })?; + let temp = dir.join(format!( + ".report-{}.tmp", + crate::domain::monotonic_id::next_uuid() + )); + if let Err(err) = tokio::fs::write(&temp, html.as_bytes()).await { + let _ = tokio::fs::remove_file(&temp).await; + return Err(AppError::Internal(format!( + "failed to write the report document: {err}" + ))); + } + let path = crate::web::blob_path(files_path, &report_key(run_day)); + if let Err(err) = tokio::fs::rename(&temp, &path).await { + let _ = tokio::fs::remove_file(&temp).await; + return Err(AppError::Internal(format!( + "failed to store the report document: {err}" + ))); + } + Ok(()) +} + // ---- the storage doors ----------------------------------------------------- // // ZEKA's own tables are written and read by the backend, never by the service diff --git a/src/web/mod.rs b/src/web/mod.rs index 8e57e98..5e71a90 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -255,6 +255,49 @@ pub(crate) async fn remove_blob(files_path: &FsPath, key: &str) { } } +/// How much of a stored blob is read per chunk, and how many chunks its body +/// may have in flight. 4 × 64 KiB is the whole memory ceiling one stream +/// costs, however large the file behind it. Shared by every streaming blob +/// door (podcast audio, the insight report document). +const BLOB_CHUNK_BYTES: usize = 64 * 1024; +const BLOB_CHUNKS_IN_FLIGHT: usize = 4; + +/// A stored file as a byte stream: a reader task hands chunks to the body over +/// a bounded channel, so a client that stops reading parks the pump at the +/// next send instead of pinning the whole file in memory, and a closed body +/// ends the task by itself. +pub(crate) fn pump( + file: tokio::fs::File, +) -> impl tokio_stream::Stream> + Send + 'static +{ + let (tx, rx) = tokio::sync::mpsc::channel::>( + BLOB_CHUNKS_IN_FLIGHT, + ); + tokio::spawn(async move { + let mut file = file; + let mut buf = vec![0u8; BLOB_CHUNK_BYTES]; + loop { + match tokio::io::AsyncReadExt::read(&mut file, &mut buf).await { + Ok(0) => break, + Ok(n) => { + if tx + .send(Ok(axum::body::Bytes::copy_from_slice(&buf[..n]))) + .await + .is_err() + { + break; + } + } + Err(err) => { + let _ = tx.send(Err(err)).await; + break; + } + } + } + }); + tokio_stream::wrappers::ReceiverStream::new(rx) +} + /// The declared content type of an inline-displayed image upload, held to the /// raster allowlist — SVG stays out (it can script) since these bytes are /// rendered inline to whole classes. Shared by exam question images and pool diff --git a/src/web/podcast.rs b/src/web/podcast.rs index 060cb40..dcfa192 100644 --- a/src/web/podcast.rs +++ b/src/web/podcast.rs @@ -45,7 +45,7 @@ //! fail is never queued. use axum::Json; -use axum::body::{Body, Bytes}; +use axum::body::Body; use axum::extract::{Path, Query}; use axum::http::HeaderValue; use axum::http::StatusCode; @@ -53,9 +53,6 @@ use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS}; use axum::response::{IntoResponse, Response}; use serde::{Deserialize, Serialize}; use serde_json::json; -use tokio::sync::mpsc; -use tokio_stream::Stream; -use tokio_stream::wrappers::ReceiverStream; use utoipa::{IntoParams, ToSchema}; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; @@ -74,13 +71,7 @@ use crate::service::podcast_job as jobs; use crate::state::AppState; use crate::web::tenant_state::{SchoolSlug, State}; -use super::{CurrentUser, Page, PageParams, ai_unavailable}; - -/// How much of the audio is read per chunk, and how many chunks the body may -/// have in flight. 4 × 64 KiB is the whole memory ceiling one audio stream -/// costs, however large the file behind it. -const AUDIO_CHUNK_BYTES: usize = 64 * 1024; -const AUDIO_CHUNKS_IN_FLIGHT: usize = 4; +use super::{CurrentUser, Page, PageParams, ai_unavailable, pump}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -630,33 +621,6 @@ async fn owned(st: &AppState, user: &User, id: &str) -> Result impl Stream> + Send + 'static { - let (tx, rx) = mpsc::channel::>(AUDIO_CHUNKS_IN_FLIGHT); - tokio::spawn(async move { - let mut file = file; - let mut buf = vec![0u8; AUDIO_CHUNK_BYTES]; - loop { - match tokio::io::AsyncReadExt::read(&mut file, &mut buf).await { - Ok(0) => break, - Ok(n) => { - if tx.send(Ok(Bytes::copy_from_slice(&buf[..n]))).await.is_err() { - break; - } - } - Err(err) => { - let _ = tx.send(Err(err)).await; - break; - } - } - } - }); - ReceiverStream::new(rx) -} - /// Why a dispatching door has no worker to talk to. Deliberately small: the /// refusal is not a response — the caller builds the `503` at its own call /// site, so a large, rarely-taken `Response` never rides the `Result` type of diff --git a/tests/insight_report.rs b/tests/insight_report.rs new file mode 100644 index 0000000..0189b53 --- /dev/null +++ b/tests/insight_report.rs @@ -0,0 +1,645 @@ +//! End-to-end tests for the school-report doors, against a fake ZEKA service. +//! +//! `POST /insights/runs/{run_day}/report` reads this school's own `zeka_*` +//! rows, dispatches them to the service that declares `insight.report`, stores +//! the returned HTML under the school's blob directory, and answers `200` with +//! what was stored; `GET` streams that document back. Everything runs over a +//! real QUIC socket on loopback — a real handshake, real TLS, real streams — +//! with [`Behaviour::Report`] standing in for what ZEKA does with the request. +//! +//! The assertions split the same way `tests/podcast.rs` splits them: what a +//! browser gets from the real router, and what the *service* received +//! ([`FakeService::seen`]) — a door that quietly sent nothing, or asked the +//! wrong principal, fails the `seen` assertions rather than looking green. + +mod common; + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use axum::Router; +use axum::http::StatusCode; +use hezarfen_backend::ai::protocol::{Greeting, Hello, Request, Response, read_frame, write_frame}; +use hezarfen_backend::ai::{AiBridge, BridgeConfig}; +use hezarfen_backend::constant::{ + AI_ALPN, AI_INSIGHT_REPORT_CAPABILITY, AI_PROTOCOL, +}; +use hezarfen_backend::database::Database; +use hezarfen_backend::domain::timestamp::Timestamp; +use hezarfen_backend::tenant::DEMO_SLUG; +use serde_json::{Value, json}; +use uuid::Uuid; + +const TOKEN: &str = "shared-ai-token"; + +/// One answer frame, **bounded**: a bridge that never answers must fail this +/// test by name in seconds rather than hang the run — a hung Test step holds +/// the serialized deploy lock behind it. +async fn frame_or_fail( + recv: &mut quinn::RecvStream, + what: &str, +) -> T { + match tokio::time::timeout(Duration::from_secs(10), read_frame(recv)).await { + Ok(Ok(frame)) => frame, + Ok(Err(err)) => panic!("{what}: the frame could not be read: {err}"), + Err(_) => panic!("{what}: no frame arrived within 10s — the bridge did not answer"), + } +} + +// ---------------------------------------------------------------- harness -- + +/// Start a bridge on an ephemeral port. +async fn bridge() -> AiBridge { + AiBridge::bind(BridgeConfig { + addr: "127.0.0.1:0".parse().unwrap(), + token: TOKEN.to_string(), + cert_path: None, + key_path: None, + request_timeout: Duration::from_secs(5), + }) + .await + .expect("bridge binds on an ephemeral port") +} + +/// A QUIC client endpoint that trusts exactly the bridge's own certificate — +/// the same pinning a real service does, rather than a verification bypass. +fn client_endpoint(bridge: &AiBridge) -> quinn::Endpoint { + hezarfen_backend::ai::tls::install_crypto_provider(); + let mut roots = rustls::RootCertStore::empty(); + roots.add(bridge.certificate()).expect("pin the leaf"); + let mut tls = rustls::ClientConfig::builder() + .with_root_certificates(roots) + .with_no_client_auth(); + tls.alpn_protocols = vec![AI_ALPN.to_vec()]; + + let quic_tls = + quinn::crypto::rustls::QuicClientConfig::try_from(tls).expect("client TLS is QUIC-usable"); + let mut config = quinn::ClientConfig::new(Arc::new(quic_tls)); + let mut transport = quinn::TransportConfig::default(); + transport.max_concurrent_bidi_streams(64u32.into()); + config.transport_config(Arc::new(transport)); + + let mut endpoint = + quinn::Endpoint::client("127.0.0.1:0".parse().unwrap()).expect("client bind"); + endpoint.set_default_client_config(config); + endpoint +} + +fn hello(service: &str, capabilities: &[&str]) -> Hello { + Hello { + protocol: AI_PROTOCOL.to_string(), + service: service.to_string(), + capabilities: capabilities.iter().map(|c| c.to_string()).collect(), + token: TOKEN.to_string(), + max_concurrent: None, + } +} + +/// A connected fake service. Holding it keeps the connection (and so the +/// registration) alive; dropping it is how a test simulates a crash. +struct FakeService { + _endpoint: quinn::Endpoint, + _control: (quinn::SendStream, quinn::RecvStream), + /// Every request this service received, in arrival order. + seen: Arc>>, +} + +impl FakeService { + fn seen(&self) -> Vec { + self.seen.lock().unwrap().clone() + } + + /// The one report request this service was handed. + fn report_request(&self) -> Request { + self.seen() + .into_iter() + .find(|request| request.capability == AI_INSIGHT_REPORT_CAPABILITY) + .expect("the door dispatched the report capability") + } +} + +/// What the fake service does with each request it receives. +#[derive(Clone)] +enum Behaviour { + /// Answer like ZEKA's report package: a self-contained HTML document that + /// echoes the run day and how many summaries it was handed. + Report, + /// Refuse like ZEKA's report handler does: the code is chosen by the run + /// day, so one connection can drive every refusal class. + Refuse, + /// Answer `200` with an html member that is the empty string — a service + /// defect the door must not persist. + Empty, +} + +/// The refusal code the fake service answers for a run day — all four codes +/// the real handler closes, one day each. +fn refusal_code(run_day: &str) -> String { + match run_day { + "2026-09-11" => "bad_request", + "2026-09-12" => "insufficient_rows", + "2026-09-13" => "document_too_large", + "2026-09-14" => "internal", + other => panic!("the fake service was asked for an unmapped day `{other}`"), + } + .to_string() +} + +/// Dial, register, and start serving requests with `behaviour`. +async fn connect_service(bridge: &AiBridge, hello: Hello, behaviour: Behaviour) -> FakeService { + let endpoint = client_endpoint(bridge); + let conn = endpoint + .connect(bridge.local_addr().unwrap(), "localhost") + .expect("dial") + .await + .expect("QUIC handshake"); + let (mut send, mut recv) = conn.open_bi().await.expect("control stream"); + write_frame(&mut send, &hello).await.expect("send Hello"); + let greeting: Greeting = frame_or_fail(&mut recv, "read Greeting").await; + match greeting { + Greeting::Welcome { protocol, .. } => assert_eq!(protocol, AI_PROTOCOL), + other => panic!("expected a welcome, got {other:?}"), + } + + let seen = Arc::new(Mutex::new(Vec::new())); + serve(conn.clone(), behaviour, Arc::clone(&seen)); + FakeService { + _endpoint: endpoint, + _control: (send, recv), + seen, + } +} + +/// The service's request loop: one task per incoming server-initiated stream. +fn serve(conn: quinn::Connection, behaviour: Behaviour, seen: Arc>>) { + tokio::spawn(async move { + while let Ok((mut send, mut recv)) = conn.accept_bi().await { + let behaviour = behaviour.clone(); + let seen = Arc::clone(&seen); + tokio::spawn(async move { + let Ok(request) = read_frame::<_, Request>(&mut recv).await else { + return; + }; + seen.lock().unwrap().push(request.clone()); + let response = match behaviour { + Behaviour::Report => Response::Ok { + id: request.id.clone(), + school: request.school.clone(), + payload: report_answer(&request), + }, + Behaviour::Refuse => { + let code = refusal_code( + request.payload["run_day"].as_str().unwrap_or_default(), + ); + Response::Err { + id: request.id.clone(), + school: request.school.clone(), + message: format!("`{code}` reddedildi"), + code, + } + } + Behaviour::Empty => Response::Ok { + id: request.id.clone(), + school: request.school.clone(), + payload: json!({ + "kind": "okul", + "run_day": request.payload["run_day"], + "format": "html", + "html": "", + "byte_size": 0, + "truncated": false, + "notes": [], + }), + }, + }; + let _ = write_frame(&mut send, &response).await; + let _ = send.finish(); + let _ = send.stopped().await; + }); + } + }); +} + +/// The HTML a fake report render produces for the request it was handed. +fn report_html(request: &Request) -> String { + let run_day = request.payload["run_day"].as_str().unwrap_or(""); + let students = request.payload["summaries"] + .as_array() + .map(|rows| rows.len()) + .unwrap_or(0); + format!( + "\n\ + Okul analiz raporu\ +

Okul analiz raporu — {run_day}

\ +

{students} öğrenci özeti

" + ) +} + +/// What the fake ZEKA report package answers: the document plus its own +/// bookkeeping. +fn report_answer(request: &Request) -> Value { + let html = report_html(request); + json!({ + "kind": "okul", + "run_day": request.payload["run_day"], + "format": "html", + "byte_size": html.len(), + "html": html, + "truncated": false, + "notes": ["koşu defteri okundu"], + }) +} + +/// Registration completes asynchronously after the welcome is on the wire, so +/// tests that assert on the registry wait for it rather than racing it. +async fn await_workers(bridge: &AiBridge, expected: usize) { + for _ in 0..300 { + if bridge.workers().len() == expected { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + panic!( + "expected {expected} workers, registry holds {:?}", + bridge.workers() + ); +} + +/// A registered ZEKA service, the router wired to its bridge, a logged-in +/// manager, and the school's database handle — the fixture the round-trip +/// tests start from. +async fn report_app() -> (FakeService, Router, String, Database) { + let bridge = bridge().await; + let service = connect_service( + &bridge, + hello("zeka", &[AI_INSIGHT_REPORT_CAPABILITY]), + Behaviour::Report, + ) + .await; + await_workers(&bridge, 1).await; + let (app, db) = common::app_with_ai(Some(bridge)).await; + let manager = common::login_as(&app, &db, "mudur", "manager").await; + (service, app, manager, db) +} + +// --------------------------------------------------------------- fixtures -- + +/// Seed one student's ZEKA rows the way the service writes them: a summary +/// with one attention item, one live card, one segment profile, and the +/// ledger row for `run_day` with its pending student and failed module. All of +/// it is what the report dispatch must carry. +async fn seed_report_rows(db: &Database, run_day: &str, student: &str, audience: &str) { + let student_uuid = Uuid::parse_str(student).expect("student id"); + let audience_uuid = Uuid::parse_str(audience).expect("audience id"); + let now = Timestamp::now().as_millis(); + + sqlx::query( + "INSERT INTO zeka_student_summary + (student, marks, attendance, submission, study, confidence, computed_at, retain_until) + VALUES ($1, '{\"courses\":{\"matematik\":{\"average\":72}}}'::jsonb, NULL, NULL, NULL, + 'stable', $2, $3)", + ) + .bind(student_uuid) + .bind(now) + .bind(now + 400 * 86_400_000) + .execute(db) + .await + .unwrap(); + + sqlx::query( + "INSERT INTO zeka_attention_item + (student, trigger, course, fact, window_from, window_to, evidence, ord) + VALUES ($1, 'attendance', NULL, 'son 30 gunun 4 dersi kacirildi', $2, $3, + '{\"absent_days\":4}'::jsonb, 1)", + ) + .bind(student_uuid) + .bind(now - 30 * 86_400_000) + .bind(now) + .execute(db) + .await + .unwrap(); + + sqlx::query( + "INSERT INTO zeka_recommendation + (id, audience, product, rule_id, rule_version, scope, about, audience_role, + course, evidence, confidence, created_at, expires_at, retain_until, + dismissed_at, dismissed_by, dismiss_reason) + VALUES ($1, $2, 'T4', 'T4.attendance', 1, NULL, $3, 'teacher', NULL, + '{\"absent_days\":4,\"limitation\":\"yalniz ders yoklamasi\"}'::jsonb, + 'stable', $4, $5, $6, NULL, NULL, NULL)", + ) + .bind(Uuid::now_v7()) + .bind(audience_uuid) + .bind(student_uuid) + .bind(now) + .bind(now + 86_400_000) + .bind(now + 90 * 86_400_000) + .execute(db) + .await + .unwrap(); + + sqlx::query( + "INSERT INTO zeka_student_segment_profile + (student, dimension, label, n_answers, n_correct, accuracy, + overall_n_answers, overall_accuracy, contrast, confidence, + computed_at, retain_until) + VALUES ($1, 'bilissel_talep', 'analiz', 120, 48, 0.40, 240, 0.55, -0.15, + 'stable', $2, $3)", + ) + .bind(student_uuid) + .bind(now) + .bind(now + 400 * 86_400_000) + .execute(db) + .await + .unwrap(); + + sqlx::query( + "INSERT INTO zeka_run + (run_day, started_at, finished_at, status, duration_ms, + students_total, students_ok, students_failed, students_skipped, + rows_written, budget_exceeded, budget_ms, retain_until) + VALUES ($1, $2, $3, 'ok', 61000, 1, 1, 0, 0, 44, false, 60000, $4)", + ) + .bind(run_day) + .bind(now - 61_000) + .bind(now) + .bind(now + 90 * 86_400_000) + .execute(db) + .await + .unwrap(); + sqlx::query("INSERT INTO zeka_run_pending (run, student, ord) VALUES ($1, $2, 1)") + .bind(run_day) + .bind(student_uuid) + .execute(db) + .await + .unwrap(); + sqlx::query("INSERT INTO zeka_run_failed_module (run, module, ord) VALUES ($1, 'study', 1)") + .bind(run_day) + .execute(db) + .await + .unwrap(); +} + +// ------------------------------------------------------------- http doors -- + +/// One `POST /insights/runs/{run_day}/report`. +async fn generate(app: &Router, cookie: &str, run_day: &str) -> common::Res { + common::send( + app, + "POST", + &format!("/insights/runs/{run_day}/report"), + Some(cookie), + None, + ) + .await +} + +/// One `GET /insights/runs/{run_day}/report`, raw — the body is an HTML +/// document or a JSON refusal, never a parsed envelope. +async fn fetch_report( + app: &Router, + cookie: &str, + run_day: &str, +) -> (StatusCode, axum::http::HeaderMap, Vec) { + common::send_raw( + app, + "GET", + &format!("/insights/runs/{run_day}/report"), + Some(cookie), + None, + Vec::new(), + ) + .await +} + +/// A refusal body parsed out of raw bytes. +fn refusal_body(bytes: &[u8]) -> Value { + serde_json::from_slice(bytes).expect("a refusal body is JSON") +} + +// ------------------------------------------------------------------ tests -- + +/// The whole round trip: the manager generates the document, the service is +/// handed the school's own rows and the caller's identity, and the stored +/// artifact is served back with the document's content type — byte for byte +/// what the service rendered. +#[tokio::test] +async fn a_generated_report_is_stored_and_served_to_its_manager() { + let (service, app, manager, db) = report_app().await; + let manager_id = common::me_id(&app, &manager).await; + let student = common::login(&app, "ali").await; + let student_id = common::me_id(&app, &student).await; + seed_report_rows(&db, "2026-09-16", &student_id, &manager_id).await; + + let res = generate(&app, &manager, "2026-09-16").await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["run_day"], "2026-09-16"); + assert_eq!(res.body["truncated"], false); + assert_eq!(res.body["notes"], json!(["koşu defteri okundu"])); + assert!(res.body["generated_at"].as_i64().unwrap() > 0); + assert_eq!( + res.body["byte_size"].as_u64().unwrap(), + report_html(&service.report_request()).len() as u64, + "the receipt sizes the stored document, not the service's claim" + ); + + // What the service was handed. This is the payload contract: the rows the + // backend holds, the caller's identity, and the school's own fields. + let request = service.report_request(); + assert_eq!(request.payload["kind"], "okul"); + assert_eq!(request.payload["run_day"], "2026-09-16"); + assert_eq!( + request.payload["requested_by"], manager_id, + "the dispatch names the authenticated caller, not the school" + ); + assert_eq!(request.payload["school"]["slug"], DEMO_SLUG); + assert!( + request.payload["school"]["id"].as_str().is_some_and(|id| !id.is_empty()), + "the school's own id travels" + ); + assert!( + request.payload["school"]["name"] + .as_str() + .is_some_and(|name| !name.is_empty()), + "the school's display name travels" + ); + let summaries = request.payload["summaries"] + .as_array() + .expect("summaries is a list"); + let mine = summaries + .iter() + .find(|row| row["student"] == student_id) + .expect("the seeded student's summary is in the payload"); + assert_eq!(mine["confidence"], "stable"); + assert_eq!(mine["attention"][0]["trigger"], "attendance"); + assert_eq!(mine["attention"][0]["evidence"]["absent_days"], 4); + let cards = request.payload["recommendations"].as_array().unwrap(); + assert_eq!(cards.len(), 1); + assert_eq!(cards[0]["rule_id"], "T4.attendance"); + assert_eq!(cards[0]["about"], student_id); + assert_eq!(request.payload["profiles"][0]["dimension"], "bilissel_talep"); + assert_eq!(request.payload["profiles"][0]["contrast"], -0.15); + let runs = request.payload["runs"].as_array().unwrap(); + assert_eq!(runs[0]["run_day"], "2026-09-16"); + assert_eq!(runs[0]["pending_students"], json!([student_id])); + assert_eq!(runs[0]["failed_modules"], json!(["study"])); + + // The artifact a browser gets back. + let (status, headers, bytes) = fetch_report(&app, &manager, "2026-09-16").await; + assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&bytes)); + assert_eq!(headers["content-type"], "text/html; charset=utf-8"); + assert_eq!(headers["x-content-type-options"], "nosniff"); + assert_eq!(headers["cache-control"], "private, no-store"); + let html = String::from_utf8(bytes).expect("the stored document is UTF-8"); + assert_eq!(html, report_html(&service.report_request())); + assert!(html.starts_with("")); +} + +/// Generation is deliberately synchronous and does not require a ledger row: +/// a run day with no `zeka_run` row still dispatches (the service says in +/// `notes` what it found), and the artifact it returns is served. A `404` +/// here would refuse a day the POST door had just answered `200` for. +#[tokio::test] +async fn a_run_day_with_no_ledger_row_still_generates_and_serves() { + let (service, app, manager, _db) = report_app().await; + + let res = generate(&app, &manager, "2099-01-01").await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["run_day"], "2099-01-01"); + + let request = service.report_request(); + assert_eq!(request.payload["run_day"], "2099-01-01"); + assert_eq!( + request.payload["runs"].as_array().map(Vec::len), + Some(0), + "no ledger row means no ledger rows, not a refusal" + ); + + let (status, headers, _bytes) = fetch_report(&app, &manager, "2099-01-01").await; + assert_eq!(status, StatusCode::OK); + assert_eq!(headers["content-type"], "text/html; charset=utf-8"); +} + +/// Reading before anything was generated is the coded `409` — the refusal a +/// client branches on, never a `404` it could confuse with a missing route. +#[tokio::test] +async fn a_report_that_was_never_generated_is_a_coded_conflict() { + let (app, db) = common::app_and_db().await; + let manager = common::login_as(&app, &db, "mudur", "manager").await; + + let (status, _headers, bytes) = fetch_report(&app, &manager, "2099-12-31").await; + assert_eq!(status, StatusCode::CONFLICT); + let body = refusal_body(&bytes); + assert_eq!(body["code"], "report_missing"); + assert!( + body["error"].as_str().unwrap().contains("2099-12-31"), + "the message names the day: {body}" + ); +} + +/// A service that answers, refusing, maps each of its four codes to the right +/// HTTP class — and stores nothing on any of them. +#[tokio::test] +async fn service_refusals_map_each_code_to_its_http_class() { + let bridge = bridge().await; + let _service = connect_service( + &bridge, + hello("zeka", &[AI_INSIGHT_REPORT_CAPABILITY]), + Behaviour::Refuse, + ) + .await; + await_workers(&bridge, 1).await; + let (app, db) = common::app_with_ai(Some(bridge)).await; + let manager = common::login_as(&app, &db, "mudur", "manager").await; + + // `bad_request`: the service judged the composed request bad. + let res = generate(&app, &manager, "2026-09-11").await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + + // `insufficient_rows`: nothing to render — a coded conflict, not a 500. + let res = generate(&app, &manager, "2026-09-12").await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + assert_eq!(res.body["code"], "report_empty"); + assert!( + res.body["error"] + .as_str() + .is_some_and(|message| message.contains("insufficient_rows")), + "the service's own words survive: {}", + res.body + ); + + // `document_too_large`: the render happened but is over the ceiling. + let res = generate(&app, &manager, "2026-09-13").await; + assert_eq!(res.status, StatusCode::PAYLOAD_TOO_LARGE, "{}", res.body); + + // `internal`: the render failed on the service's side. + let res = generate(&app, &manager, "2026-09-14").await; + assert_eq!(res.status, StatusCode::INTERNAL_SERVER_ERROR, "{}", res.body); + + // None of the four stored a document. + for day in ["2026-09-11", "2026-09-12", "2026-09-13", "2026-09-14"] { + let (status, _headers, bytes) = fetch_report(&app, &manager, day).await; + assert_eq!(status, StatusCode::CONFLICT, "{day}"); + assert_eq!(refusal_body(&bytes)["code"], "report_missing", "{day}"); + } +} + +/// No service at all: `503` before any read, and nothing was stored. +#[tokio::test] +async fn generating_without_a_service_is_unavailable() { + let (app, db) = common::app_and_db().await; + let manager = common::login_as(&app, &db, "mudur", "manager").await; + + let res = generate(&app, &manager, "2026-09-14").await; + assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body); + assert!(res.body["error"].is_string()); +} + +/// A service that answers `200` with an empty document is refused: a blank +/// page must never be stored and served as if it were the report. +#[tokio::test] +async fn an_empty_document_is_never_stored() { + let bridge = bridge().await; + let _service = connect_service( + &bridge, + hello("zeka", &[AI_INSIGHT_REPORT_CAPABILITY]), + Behaviour::Empty, + ) + .await; + await_workers(&bridge, 1).await; + let (app, db) = common::app_with_ai(Some(bridge)).await; + let manager = common::login_as(&app, &db, "mudur", "manager").await; + + let res = generate(&app, &manager, "2026-09-10").await; + assert_eq!(res.status, StatusCode::INTERNAL_SERVER_ERROR, "{}", res.body); + + let (status, _headers, bytes) = fetch_report(&app, &manager, "2026-09-10").await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(refusal_body(&bytes)["code"], "report_missing"); +} + +/// Both doors are manager+; a teacher is refused before anything is read or +/// dispatched, and a malformed day never shapes a path. +#[tokio::test] +async fn report_doors_are_manager_only_and_validate_the_day() { + let (app, db) = common::app_and_db().await; + let teacher = common::login_as(&app, &db, "ayse", "teacher").await; + + let res = generate(&app, &teacher, "2026-09-16").await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + let (status, _headers, _bytes) = fetch_report(&app, &teacher, "2026-09-16").await; + assert_eq!(status, StatusCode::FORBIDDEN); + + let manager = common::login_as(&app, &db, "mudur", "manager").await; + let res = generate(&app, &manager, "2026-9-16").await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + // A percent-encoded traversal in the day segment decodes to something no + // `YYYY-MM-DD` day is, so it is refused before it could shape a path. + let (status, _headers, bytes) = fetch_report(&app, &manager, "%2e%2e%2f%2e%2e%2fetc%2fpasswd").await; + assert_eq!( + status, + StatusCode::BAD_REQUEST, + "a path-shaped day is refused before it is joined: {}", + String::from_utf8_lossy(&bytes) + ); +} diff --git a/tests/integration.rs b/tests/integration.rs index 89392fa..45fcd4f 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -434,7 +434,7 @@ async fn protected_routes_require_session() { /// Floor on the number of protected operations swept. It only ever goes /// up: raise it when routes are added. Without it, deleting a route family /// would delete its own coverage and still pass. - const MIN_PROTECTED: usize = 338; + const MIN_PROTECTED: usize = 340; let app = mem_app().await; let spec = send(&app, "GET", "/api-docs/openapi.json", None, None) diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs index 50bd3ef..66677e1 100644 --- a/tests/limits_completeness.rs +++ b/tests/limits_completeness.rs @@ -145,6 +145,16 @@ const EXCLUDED: &[(&str, &str)] = &[ "deadline on one school-wide recompute; the run's own ledger is \ `zeka_run`, which the client polls", ), + ( + "AI_INSIGHT_REPORT_CAPABILITY", + "capability string an AI service declares", + ), + ( + "AI_INSIGHT_REPORT_TIMEOUT_SECS", + "deadline on one school-level report render; the manager waits on the \ + artifact itself and a client acts on the door's 200/409/503, never on \ + this number", + ), // The storage surface ZEKA's rows are written through (the service calls // these; the backend runs them). A browser never speaks the bridge, and // the HTTP doors that mirror them publish what a client can act on.