From 7c96e47e91c6a53a4949074bdf5f53dd1a1e4570 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 17 Sep 2026 19:28:16 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20ZEKA=20no=20longer=20touche?= =?UTF-8?q?s=20the=20database=20directly=20-=20the=20insight.*=20storage?= =?UTF-8?q?=20surface?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit No AI service may hold a school database credential, so the nine reads and writes ZEKA performed against its own zeka_* tables become named operations the backend serves: insight.summary|recommendation|segment|profile|run.upsert, insight.pending.list, insight.retention.sweep, insight.departed.purge and the deployment-scoped insight.schools.list. They ride a new client-initiated capability call (CapabilityRequest -> CapabilityResponse, mirroring Request/Response field for field) and are mounted as HTTP doors on the same functions (manager+; the school directory is the builder's, outside the school gate). Every statement runs inside the school the frame named, in one transaction per batch. --- ...f749302b7824859737c780efb433e972af5e4.json | 210 ++++ ...ff0448a94963efd2d4b669f4b5b63ce009c84.json | 14 + ...18cdd618f48caa4f3c49dc5ecbdffcfafccc6.json | 16 + ...2227d102dfdcc8c42e3958427d8bc1bf91225.json | 27 + ...3ff6ce87354aaa1a808eeeb6b2e72f56a3d48.json | 14 + ...5d4474062400acdf4d6b10f4ec9fb2408808a.json | 14 + ...bdd59d39b5f90fb69e27cf6acb616cd3c8101.json | 222 ++++ ...5dc575c23ef9aaf415321bfedae115dfbc8ac.json | 21 + ...857924536cb9eae45bb42ac5ddf8b37ef5702.json | 14 + ...87498d97beaa1c834ecfe46948b92d4c64a17.json | 14 + ...769f2f96ef594e3b147de6a86dd3c4fdd25e4.json | 14 + ...971e4e862032a071474516a149286eb61e9c8.json | 33 + ...1d6d80b9a0cad9fbba7a655104c7d1a16ea18.json | 208 ++++ ...89d93fbb51942736383921d200584eb202d32.json | 28 + ...901a1939d16cb7aff9023c8b7331ece7265c0.json | 209 ++++ ...78150a1e8c7f19991e21b45272785cd2e4055.json | 209 ++++ ...f1c0437b5db4609942d07a95a1262a723bb99.json | 21 + ...44918826d27c938b536063b8c526f1133d620.json | 26 + ...6041a67a486a5560fa151ad8fe8210bfd9d53.json | 209 ++++ ...b672f5b07587db6047f00cfda9c2effe7af56.json | 17 + ...de315709a64b53ff6fd8f6837f61283f1001b.json | 26 + ...eb9e549150c86a1c752343b841147f359de28.json | 14 + ...12da661992cdc26d5ec3e2c30f6a6dcda2487.json | 25 + ...3c2109bc86448a3dc6895c5bf2a9c0c99cc98.json | 215 ++++ ...448cebbfaa47e3e7e1d907a8c902d582b3fbc.json | 14 + ...0c66f070d71e3435dc8f359d09675c5fcccdc.json | 214 ++++ ...f782b9fee47fde37708ee071f9002bd163888.json | 16 + ...e5c4b7ca3c48dd8e9cebf91c745130de0ad4e.json | 14 + README.md | 19 +- src/ai/capability.rs | 101 ++ src/ai/insight.rs | 228 +++- src/ai/protocol.rs | 245 ++++- src/ai/server.rs | 259 ++++- src/constant.rs | 149 ++- src/db/insight.rs | 986 ++++++++++++++++++ src/db/mod.rs | 2 + src/lib.rs | 8 +- src/web/insights.rs | 324 +++++- tests/ai_bridge.rs | 451 ++++++++ tests/ai_protocol.rs | 107 ++ tests/limits_completeness.rs | 96 +- 41 files changed, 4993 insertions(+), 60 deletions(-) create mode 100644 .sqlx/query-00e4b6eca87d0ab5012f3d0562bf749302b7824859737c780efb433e972af5e4.json create mode 100644 .sqlx/query-1419d2d6a1288438261cfccd2ceff0448a94963efd2d4b669f4b5b63ce009c84.json create mode 100644 .sqlx/query-16da7d91af8ef555b98bdf14cc418cdd618f48caa4f3c49dc5ecbdffcfafccc6.json create mode 100644 .sqlx/query-3773b2b5864210017fbfa74b89d2227d102dfdcc8c42e3958427d8bc1bf91225.json create mode 100644 .sqlx/query-5b00aa8c5c7814c7a5c82f5b0be3ff6ce87354aaa1a808eeeb6b2e72f56a3d48.json create mode 100644 .sqlx/query-5c4295befb79370b86726cfc5ce5d4474062400acdf4d6b10f4ec9fb2408808a.json create mode 100644 .sqlx/query-636b29289a1fc139ca239ddae85bdd59d39b5f90fb69e27cf6acb616cd3c8101.json create mode 100644 .sqlx/query-63ab56b7c9cec73b82d7143c9595dc575c23ef9aaf415321bfedae115dfbc8ac.json create mode 100644 .sqlx/query-64a0ae377768cc932bb3751b6d8857924536cb9eae45bb42ac5ddf8b37ef5702.json create mode 100644 .sqlx/query-670b56558479909cc3f10badcfa87498d97beaa1c834ecfe46948b92d4c64a17.json create mode 100644 .sqlx/query-744065e06ac54db230fdfe81656769f2f96ef594e3b147de6a86dd3c4fdd25e4.json create mode 100644 .sqlx/query-7a93565369caf1d8f68b8214735971e4e862032a071474516a149286eb61e9c8.json create mode 100644 .sqlx/query-826c34848d470eb17f7a677d1ce1d6d80b9a0cad9fbba7a655104c7d1a16ea18.json create mode 100644 .sqlx/query-8378e48dd68785c1caccc7e7be489d93fbb51942736383921d200584eb202d32.json create mode 100644 .sqlx/query-913496d365010822c99818a92fc901a1939d16cb7aff9023c8b7331ece7265c0.json create mode 100644 .sqlx/query-91c968305e53e61df2c67fdaeea78150a1e8c7f19991e21b45272785cd2e4055.json create mode 100644 .sqlx/query-9c0a2825d86358bb6088de901bff1c0437b5db4609942d07a95a1262a723bb99.json create mode 100644 .sqlx/query-a090ce70a604c900d6a516bf14844918826d27c938b536063b8c526f1133d620.json create mode 100644 .sqlx/query-ad5b90d0407d3abf9a3bdf119146041a67a486a5560fa151ad8fe8210bfd9d53.json create mode 100644 .sqlx/query-b0f040f8c3044894f49702f9918b672f5b07587db6047f00cfda9c2effe7af56.json create mode 100644 .sqlx/query-c0f04896f37ecdb45eefd6ff79ede315709a64b53ff6fd8f6837f61283f1001b.json create mode 100644 .sqlx/query-d47b73487d9975d8c5fb3fc6236eb9e549150c86a1c752343b841147f359de28.json create mode 100644 .sqlx/query-da1423194dea4b1b011f5d3634b12da661992cdc26d5ec3e2c30f6a6dcda2487.json create mode 100644 .sqlx/query-e3c904f558317d2d0c709f4b6bb3c2109bc86448a3dc6895c5bf2a9c0c99cc98.json create mode 100644 .sqlx/query-eef4d307eacc7efa9eff673b382448cebbfaa47e3e7e1d907a8c902d582b3fbc.json create mode 100644 .sqlx/query-f1a079e6c5978b7d9458172705e0c66f070d71e3435dc8f359d09675c5fcccdc.json create mode 100644 .sqlx/query-f844815300b8be204b2cf5f2b1ef782b9fee47fde37708ee071f9002bd163888.json create mode 100644 .sqlx/query-f93aab2536f71779fa9d1b973a9e5c4b7ca3c48dd8e9cebf91c745130de0ad4e.json create mode 100644 src/ai/capability.rs create mode 100644 src/db/insight.rs diff --git a/.sqlx/query-00e4b6eca87d0ab5012f3d0562bf749302b7824859737c780efb433e972af5e4.json b/.sqlx/query-00e4b6eca87d0ab5012f3d0562bf749302b7824859737c780efb433e972af5e4.json new file mode 100644 index 0000000..66bff97 --- /dev/null +++ b/.sqlx/query-00e4b6eca87d0ab5012f3d0562bf749302b7824859737c780efb433e972af5e4.json @@ -0,0 +1,210 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE podcast_job SET state = 'failed', error_code = $2, stage = '', updated_at = $3 WHERE id = $1 AND state IN ('queued', 'running') RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: PodcastJobId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "podcast_job", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "user_id: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "podcast_job", + "name": "user_id" + } + } + }, + { + "ordinal": 2, + "name": "source_id", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "source_id" + } + } + }, + { + "ordinal": 3, + "name": "format", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "format" + } + } + }, + { + "ordinal": 4, + "name": "state: PodcastJobState", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "state" + } + } + }, + { + "ordinal": 5, + "name": "stage", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "stage" + } + } + }, + { + "ordinal": 6, + "name": "progress", + "type_info": "Float8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "progress" + } + } + }, + { + "ordinal": 7, + "name": "error_code", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "error_code" + } + } + }, + { + "ordinal": 8, + "name": "audio_key", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_key" + } + } + }, + { + "ordinal": 9, + "name": "audio_name", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_name" + } + } + }, + { + "ordinal": 10, + "name": "audio_type", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_type" + } + } + }, + { + "ordinal": 11, + "name": "audio_bytes", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_bytes" + } + } + }, + { + "ordinal": 12, + "name": "duration_secs", + "type_info": "Float8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "duration_secs" + } + } + }, + { + "ordinal": 13, + "name": "eta_secs", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "eta_secs" + } + } + }, + { + "ordinal": 14, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "created_at" + } + } + }, + { + "ordinal": 15, + "name": "updated_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "updated_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + true, + false, + false, + false, + true, + true, + true, + true, + true, + true, + true, + false, + false + ] + }, + "hash": "00e4b6eca87d0ab5012f3d0562bf749302b7824859737c780efb433e972af5e4" +} diff --git a/.sqlx/query-1419d2d6a1288438261cfccd2ceff0448a94963efd2d4b669f4b5b63ce009c84.json b/.sqlx/query-1419d2d6a1288438261cfccd2ceff0448a94963efd2d4b669f4b5b63ce009c84.json new file mode 100644 index 0000000..3f35860 --- /dev/null +++ b/.sqlx/query-1419d2d6a1288438261cfccd2ceff0448a94963efd2d4b669f4b5b63ce009c84.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM zeka_run_pending WHERE run = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "1419d2d6a1288438261cfccd2ceff0448a94963efd2d4b669f4b5b63ce009c84" +} diff --git a/.sqlx/query-16da7d91af8ef555b98bdf14cc418cdd618f48caa4f3c49dc5ecbdffcfafccc6.json b/.sqlx/query-16da7d91af8ef555b98bdf14cc418cdd618f48caa4f3c49dc5ecbdffcfafccc6.json new file mode 100644 index 0000000..b0c17f3 --- /dev/null +++ b/.sqlx/query-16da7d91af8ef555b98bdf14cc418cdd618f48caa4f3c49dc5ecbdffcfafccc6.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO zeka_run_failed_module (run, module, ord) VALUES ($1, $2, $3)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text", + "Int2" + ] + }, + "nullable": [] + }, + "hash": "16da7d91af8ef555b98bdf14cc418cdd618f48caa4f3c49dc5ecbdffcfafccc6" +} diff --git a/.sqlx/query-3773b2b5864210017fbfa74b89d2227d102dfdcc8c42e3958427d8bc1bf91225.json b/.sqlx/query-3773b2b5864210017fbfa74b89d2227d102dfdcc8c42e3958427d8bc1bf91225.json new file mode 100644 index 0000000..6d7e0ad --- /dev/null +++ b/.sqlx/query-3773b2b5864210017fbfa74b89d2227d102dfdcc8c42e3958427d8bc1bf91225.json @@ -0,0 +1,27 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO zeka_recommendation\n (id, audience, product, rule_id, rule_version, scope, about, audience_role,\n course, evidence, confidence, created_at, expires_at, retain_until)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)\n ON CONFLICT (audience, product, rule_id, about, scope) DO UPDATE SET\n rule_version = EXCLUDED.rule_version,\n audience_role = EXCLUDED.audience_role,\n course = EXCLUDED.course,\n evidence = EXCLUDED.evidence,\n confidence = EXCLUDED.confidence,\n created_at = EXCLUDED.created_at,\n expires_at = EXCLUDED.expires_at,\n retain_until = EXCLUDED.retain_until", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Text", + "Text", + "Int8", + "Text", + "Uuid", + "Text", + "Uuid", + "Jsonb", + "Text", + "Int8", + "Int8", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "3773b2b5864210017fbfa74b89d2227d102dfdcc8c42e3958427d8bc1bf91225" +} diff --git a/.sqlx/query-5b00aa8c5c7814c7a5c82f5b0be3ff6ce87354aaa1a808eeeb6b2e72f56a3d48.json b/.sqlx/query-5b00aa8c5c7814c7a5c82f5b0be3ff6ce87354aaa1a808eeeb6b2e72f56a3d48.json new file mode 100644 index 0000000..c6cfb2c --- /dev/null +++ b/.sqlx/query-5b00aa8c5c7814c7a5c82f5b0be3ff6ce87354aaa1a808eeeb6b2e72f56a3d48.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM zeka_question_segment_dimension WHERE question = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "5b00aa8c5c7814c7a5c82f5b0be3ff6ce87354aaa1a808eeeb6b2e72f56a3d48" +} diff --git a/.sqlx/query-5c4295befb79370b86726cfc5ce5d4474062400acdf4d6b10f4ec9fb2408808a.json b/.sqlx/query-5c4295befb79370b86726cfc5ce5d4474062400acdf4d6b10f4ec9fb2408808a.json new file mode 100644 index 0000000..d8c5d81 --- /dev/null +++ b/.sqlx/query-5c4295befb79370b86726cfc5ce5d4474062400acdf4d6b10f4ec9fb2408808a.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM zeka_run_failed_module WHERE run = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "5c4295befb79370b86726cfc5ce5d4474062400acdf4d6b10f4ec9fb2408808a" +} diff --git a/.sqlx/query-636b29289a1fc139ca239ddae85bdd59d39b5f90fb69e27cf6acb616cd3c8101.json b/.sqlx/query-636b29289a1fc139ca239ddae85bdd59d39b5f90fb69e27cf6acb616cd3c8101.json new file mode 100644 index 0000000..f7420d1 --- /dev/null +++ b/.sqlx/query-636b29289a1fc139ca239ddae85bdd59d39b5f90fb69e27cf6acb616cd3c8101.json @@ -0,0 +1,222 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO podcast_job (id, user_id, source_id, format, state, stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $15) RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: PodcastJobId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "podcast_job", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "user_id: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "podcast_job", + "name": "user_id" + } + } + }, + { + "ordinal": 2, + "name": "source_id", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "source_id" + } + } + }, + { + "ordinal": 3, + "name": "format", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "format" + } + } + }, + { + "ordinal": 4, + "name": "state: PodcastJobState", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "state" + } + } + }, + { + "ordinal": 5, + "name": "stage", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "stage" + } + } + }, + { + "ordinal": 6, + "name": "progress", + "type_info": "Float8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "progress" + } + } + }, + { + "ordinal": 7, + "name": "error_code", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "error_code" + } + } + }, + { + "ordinal": 8, + "name": "audio_key", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_key" + } + } + }, + { + "ordinal": 9, + "name": "audio_name", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_name" + } + } + }, + { + "ordinal": 10, + "name": "audio_type", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_type" + } + } + }, + { + "ordinal": 11, + "name": "audio_bytes", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_bytes" + } + } + }, + { + "ordinal": 12, + "name": "duration_secs", + "type_info": "Float8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "duration_secs" + } + } + }, + { + "ordinal": 13, + "name": "eta_secs", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "eta_secs" + } + } + }, + { + "ordinal": 14, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "created_at" + } + } + }, + { + "ordinal": 15, + "name": "updated_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "updated_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Text", + "Text", + "Text", + "Text", + "Float8", + "Text", + "Text", + "Text", + "Text", + "Int8", + "Float8", + "Int8", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + true, + false, + false, + false, + true, + true, + true, + true, + true, + true, + true, + false, + false + ] + }, + "hash": "636b29289a1fc139ca239ddae85bdd59d39b5f90fb69e27cf6acb616cd3c8101" +} diff --git a/.sqlx/query-63ab56b7c9cec73b82d7143c9595dc575c23ef9aaf415321bfedae115dfbc8ac.json b/.sqlx/query-63ab56b7c9cec73b82d7143c9595dc575c23ef9aaf415321bfedae115dfbc8ac.json new file mode 100644 index 0000000..8c48eed --- /dev/null +++ b/.sqlx/query-63ab56b7c9cec73b82d7143c9595dc575c23ef9aaf415321bfedae115dfbc8ac.json @@ -0,0 +1,21 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO zeka_student_summary\n (student, marks, attendance, submission, study, confidence,\n computed_at, retain_until)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n ON CONFLICT (student) DO UPDATE SET\n marks = EXCLUDED.marks, attendance = EXCLUDED.attendance,\n submission = EXCLUDED.submission, study = EXCLUDED.study,\n confidence = EXCLUDED.confidence, computed_at = EXCLUDED.computed_at,\n retain_until = EXCLUDED.retain_until", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Jsonb", + "Jsonb", + "Jsonb", + "Jsonb", + "Text", + "Int8", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "63ab56b7c9cec73b82d7143c9595dc575c23ef9aaf415321bfedae115dfbc8ac" +} diff --git a/.sqlx/query-64a0ae377768cc932bb3751b6d8857924536cb9eae45bb42ac5ddf8b37ef5702.json b/.sqlx/query-64a0ae377768cc932bb3751b6d8857924536cb9eae45bb42ac5ddf8b37ef5702.json new file mode 100644 index 0000000..b5d4961 --- /dev/null +++ b/.sqlx/query-64a0ae377768cc932bb3751b6d8857924536cb9eae45bb42ac5ddf8b37ef5702.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM zeka_recommendation\n WHERE about IS NOT NULL AND about <> ALL($1)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [] + }, + "hash": "64a0ae377768cc932bb3751b6d8857924536cb9eae45bb42ac5ddf8b37ef5702" +} diff --git a/.sqlx/query-670b56558479909cc3f10badcfa87498d97beaa1c834ecfe46948b92d4c64a17.json b/.sqlx/query-670b56558479909cc3f10badcfa87498d97beaa1c834ecfe46948b92d4c64a17.json new file mode 100644 index 0000000..3c1029a --- /dev/null +++ b/.sqlx/query-670b56558479909cc3f10badcfa87498d97beaa1c834ecfe46948b92d4c64a17.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM zeka_student_summary WHERE student <> ALL($1)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [] + }, + "hash": "670b56558479909cc3f10badcfa87498d97beaa1c834ecfe46948b92d4c64a17" +} diff --git a/.sqlx/query-744065e06ac54db230fdfe81656769f2f96ef594e3b147de6a86dd3c4fdd25e4.json b/.sqlx/query-744065e06ac54db230fdfe81656769f2f96ef594e3b147de6a86dd3c4fdd25e4.json new file mode 100644 index 0000000..1d48931 --- /dev/null +++ b/.sqlx/query-744065e06ac54db230fdfe81656769f2f96ef594e3b147de6a86dd3c4fdd25e4.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM zeka_student_segment_profile WHERE student <> ALL($1)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [] + }, + "hash": "744065e06ac54db230fdfe81656769f2f96ef594e3b147de6a86dd3c4fdd25e4" +} diff --git a/.sqlx/query-7a93565369caf1d8f68b8214735971e4e862032a071474516a149286eb61e9c8.json b/.sqlx/query-7a93565369caf1d8f68b8214735971e4e862032a071474516a149286eb61e9c8.json new file mode 100644 index 0000000..3cc4fba --- /dev/null +++ b/.sqlx/query-7a93565369caf1d8f68b8214735971e4e862032a071474516a149286eb61e9c8.json @@ -0,0 +1,33 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO zeka_question_segment\n (question, exam, course, subject, bilissel_talep, dikkat_tuzagi, okuma_yuku,\n adim_sayisi, confidence_bilissel_talep, confidence_dikkat_tuzagi,\n confidence_okuma_yuku, confidence_adim_sayisi, confidence, trap_choice,\n rationale, model, prompt_version, variant, computed_at, retain_until)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10,\n $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)\n ON CONFLICT (question) DO UPDATE SET\n exam = EXCLUDED.exam, course = EXCLUDED.course, subject = EXCLUDED.subject,\n bilissel_talep = EXCLUDED.bilissel_talep,\n dikkat_tuzagi = EXCLUDED.dikkat_tuzagi,\n okuma_yuku = EXCLUDED.okuma_yuku,\n adim_sayisi = EXCLUDED.adim_sayisi,\n confidence_bilissel_talep = EXCLUDED.confidence_bilissel_talep,\n confidence_dikkat_tuzagi = EXCLUDED.confidence_dikkat_tuzagi,\n confidence_okuma_yuku = EXCLUDED.confidence_okuma_yuku,\n confidence_adim_sayisi = EXCLUDED.confidence_adim_sayisi,\n confidence = EXCLUDED.confidence, trap_choice = EXCLUDED.trap_choice,\n rationale = EXCLUDED.rationale, model = EXCLUDED.model,\n prompt_version = EXCLUDED.prompt_version, variant = EXCLUDED.variant,\n computed_at = EXCLUDED.computed_at, retain_until = EXCLUDED.retain_until", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Uuid", + "Uuid", + "Text", + "Text", + "Text", + "Text", + "Float8", + "Float8", + "Float8", + "Float8", + "Text", + "Text", + "Text", + "Text", + "Text", + "Text", + "Int8", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "7a93565369caf1d8f68b8214735971e4e862032a071474516a149286eb61e9c8" +} diff --git a/.sqlx/query-826c34848d470eb17f7a677d1ce1d6d80b9a0cad9fbba7a655104c7d1a16ea18.json b/.sqlx/query-826c34848d470eb17f7a677d1ce1d6d80b9a0cad9fbba7a655104c7d1a16ea18.json new file mode 100644 index 0000000..4419a53 --- /dev/null +++ b/.sqlx/query-826c34848d470eb17f7a677d1ce1d6d80b9a0cad9fbba7a655104c7d1a16ea18.json @@ -0,0 +1,208 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" FROM podcast_job WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: PodcastJobId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "podcast_job", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "user_id: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "podcast_job", + "name": "user_id" + } + } + }, + { + "ordinal": 2, + "name": "source_id", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "source_id" + } + } + }, + { + "ordinal": 3, + "name": "format", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "format" + } + } + }, + { + "ordinal": 4, + "name": "state: PodcastJobState", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "state" + } + } + }, + { + "ordinal": 5, + "name": "stage", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "stage" + } + } + }, + { + "ordinal": 6, + "name": "progress", + "type_info": "Float8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "progress" + } + } + }, + { + "ordinal": 7, + "name": "error_code", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "error_code" + } + } + }, + { + "ordinal": 8, + "name": "audio_key", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_key" + } + } + }, + { + "ordinal": 9, + "name": "audio_name", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_name" + } + } + }, + { + "ordinal": 10, + "name": "audio_type", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_type" + } + } + }, + { + "ordinal": 11, + "name": "audio_bytes", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_bytes" + } + } + }, + { + "ordinal": 12, + "name": "duration_secs", + "type_info": "Float8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "duration_secs" + } + } + }, + { + "ordinal": 13, + "name": "eta_secs", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "eta_secs" + } + } + }, + { + "ordinal": 14, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "created_at" + } + } + }, + { + "ordinal": 15, + "name": "updated_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "updated_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + true, + false, + false, + false, + true, + true, + true, + true, + true, + true, + true, + false, + false + ] + }, + "hash": "826c34848d470eb17f7a677d1ce1d6d80b9a0cad9fbba7a655104c7d1a16ea18" +} diff --git a/.sqlx/query-8378e48dd68785c1caccc7e7be489d93fbb51942736383921d200584eb202d32.json b/.sqlx/query-8378e48dd68785c1caccc7e7be489d93fbb51942736383921d200584eb202d32.json new file mode 100644 index 0000000..133cbd5 --- /dev/null +++ b/.sqlx/query-8378e48dd68785c1caccc7e7be489d93fbb51942736383921d200584eb202d32.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT p.student FROM zeka_run_pending p\n JOIN zeka_run r ON r.run_day = p.run\n WHERE r.run_day = (SELECT run_day FROM zeka_run\n ORDER BY started_at DESC, run_day DESC LIMIT 1)\n ORDER BY p.ord\n LIMIT $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "student", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "zeka_run_pending", + "name": "student" + } + } + } + ], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [ + false + ] + }, + "hash": "8378e48dd68785c1caccc7e7be489d93fbb51942736383921d200584eb202d32" +} diff --git a/.sqlx/query-913496d365010822c99818a92fc901a1939d16cb7aff9023c8b7331ece7265c0.json b/.sqlx/query-913496d365010822c99818a92fc901a1939d16cb7aff9023c8b7331ece7265c0.json new file mode 100644 index 0000000..31ab398 --- /dev/null +++ b/.sqlx/query-913496d365010822c99818a92fc901a1939d16cb7aff9023c8b7331ece7265c0.json @@ -0,0 +1,209 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE podcast_job SET eta_secs = $2 WHERE id = $1 RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: PodcastJobId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "podcast_job", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "user_id: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "podcast_job", + "name": "user_id" + } + } + }, + { + "ordinal": 2, + "name": "source_id", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "source_id" + } + } + }, + { + "ordinal": 3, + "name": "format", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "format" + } + } + }, + { + "ordinal": 4, + "name": "state: PodcastJobState", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "state" + } + } + }, + { + "ordinal": 5, + "name": "stage", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "stage" + } + } + }, + { + "ordinal": 6, + "name": "progress", + "type_info": "Float8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "progress" + } + } + }, + { + "ordinal": 7, + "name": "error_code", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "error_code" + } + } + }, + { + "ordinal": 8, + "name": "audio_key", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_key" + } + } + }, + { + "ordinal": 9, + "name": "audio_name", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_name" + } + } + }, + { + "ordinal": 10, + "name": "audio_type", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_type" + } + } + }, + { + "ordinal": 11, + "name": "audio_bytes", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_bytes" + } + } + }, + { + "ordinal": 12, + "name": "duration_secs", + "type_info": "Float8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "duration_secs" + } + } + }, + { + "ordinal": 13, + "name": "eta_secs", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "eta_secs" + } + } + }, + { + "ordinal": 14, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "created_at" + } + } + }, + { + "ordinal": 15, + "name": "updated_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "updated_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + true, + false, + false, + false, + true, + true, + true, + true, + true, + true, + true, + false, + false + ] + }, + "hash": "913496d365010822c99818a92fc901a1939d16cb7aff9023c8b7331ece7265c0" +} diff --git a/.sqlx/query-91c968305e53e61df2c67fdaeea78150a1e8c7f19991e21b45272785cd2e4055.json b/.sqlx/query-91c968305e53e61df2c67fdaeea78150a1e8c7f19991e21b45272785cd2e4055.json new file mode 100644 index 0000000..2e0ee6c --- /dev/null +++ b/.sqlx/query-91c968305e53e61df2c67fdaeea78150a1e8c7f19991e21b45272785cd2e4055.json @@ -0,0 +1,209 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" FROM podcast_job WHERE id = $1 AND user_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: PodcastJobId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "podcast_job", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "user_id: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "podcast_job", + "name": "user_id" + } + } + }, + { + "ordinal": 2, + "name": "source_id", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "source_id" + } + } + }, + { + "ordinal": 3, + "name": "format", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "format" + } + } + }, + { + "ordinal": 4, + "name": "state: PodcastJobState", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "state" + } + } + }, + { + "ordinal": 5, + "name": "stage", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "stage" + } + } + }, + { + "ordinal": 6, + "name": "progress", + "type_info": "Float8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "progress" + } + } + }, + { + "ordinal": 7, + "name": "error_code", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "error_code" + } + } + }, + { + "ordinal": 8, + "name": "audio_key", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_key" + } + } + }, + { + "ordinal": 9, + "name": "audio_name", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_name" + } + } + }, + { + "ordinal": 10, + "name": "audio_type", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_type" + } + } + }, + { + "ordinal": 11, + "name": "audio_bytes", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_bytes" + } + } + }, + { + "ordinal": 12, + "name": "duration_secs", + "type_info": "Float8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "duration_secs" + } + } + }, + { + "ordinal": 13, + "name": "eta_secs", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "eta_secs" + } + } + }, + { + "ordinal": 14, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "created_at" + } + } + }, + { + "ordinal": 15, + "name": "updated_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "updated_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + true, + false, + false, + false, + true, + true, + true, + true, + true, + true, + true, + false, + false + ] + }, + "hash": "91c968305e53e61df2c67fdaeea78150a1e8c7f19991e21b45272785cd2e4055" +} diff --git a/.sqlx/query-9c0a2825d86358bb6088de901bff1c0437b5db4609942d07a95a1262a723bb99.json b/.sqlx/query-9c0a2825d86358bb6088de901bff1c0437b5db4609942d07a95a1262a723bb99.json new file mode 100644 index 0000000..a6758a4 --- /dev/null +++ b/.sqlx/query-9c0a2825d86358bb6088de901bff1c0437b5db4609942d07a95a1262a723bb99.json @@ -0,0 +1,21 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO zeka_attention_item\n (student, trigger, course, fact, window_from, window_to, evidence, ord)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Uuid", + "Text", + "Int8", + "Int8", + "Jsonb", + "Int2" + ] + }, + "nullable": [] + }, + "hash": "9c0a2825d86358bb6088de901bff1c0437b5db4609942d07a95a1262a723bb99" +} diff --git a/.sqlx/query-a090ce70a604c900d6a516bf14844918826d27c938b536063b8c526f1133d620.json b/.sqlx/query-a090ce70a604c900d6a516bf14844918826d27c938b536063b8c526f1133d620.json new file mode 100644 index 0000000..eb9783f --- /dev/null +++ b/.sqlx/query-a090ce70a604c900d6a516bf14844918826d27c938b536063b8c526f1133d620.json @@ -0,0 +1,26 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO zeka_run\n (run_day, started_at, finished_at, status, duration_ms, students_total,\n students_ok, students_failed, students_skipped, rows_written,\n budget_exceeded, budget_ms, retain_until)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)\n ON CONFLICT (run_day) DO UPDATE SET\n started_at = EXCLUDED.started_at, finished_at = EXCLUDED.finished_at,\n status = EXCLUDED.status, duration_ms = EXCLUDED.duration_ms,\n students_total = EXCLUDED.students_total, students_ok = EXCLUDED.students_ok,\n students_failed = EXCLUDED.students_failed,\n students_skipped = EXCLUDED.students_skipped,\n rows_written = EXCLUDED.rows_written,\n budget_exceeded = EXCLUDED.budget_exceeded, budget_ms = EXCLUDED.budget_ms,\n retain_until = EXCLUDED.retain_until", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Int8", + "Int8", + "Text", + "Int8", + "Int8", + "Int8", + "Int8", + "Int8", + "Int8", + "Bool", + "Int8", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "a090ce70a604c900d6a516bf14844918826d27c938b536063b8c526f1133d620" +} diff --git a/.sqlx/query-ad5b90d0407d3abf9a3bdf119146041a67a486a5560fa151ad8fe8210bfd9d53.json b/.sqlx/query-ad5b90d0407d3abf9a3bdf119146041a67a486a5560fa151ad8fe8210bfd9d53.json new file mode 100644 index 0000000..ce5bb21 --- /dev/null +++ b/.sqlx/query-ad5b90d0407d3abf9a3bdf119146041a67a486a5560fa151ad8fe8210bfd9d53.json @@ -0,0 +1,209 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE podcast_job SET state = 'cancelled', stage = '', updated_at = $2 WHERE id = $1 AND state IN ('queued', 'running') RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: PodcastJobId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "podcast_job", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "user_id: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "podcast_job", + "name": "user_id" + } + } + }, + { + "ordinal": 2, + "name": "source_id", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "source_id" + } + } + }, + { + "ordinal": 3, + "name": "format", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "format" + } + } + }, + { + "ordinal": 4, + "name": "state: PodcastJobState", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "state" + } + } + }, + { + "ordinal": 5, + "name": "stage", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "stage" + } + } + }, + { + "ordinal": 6, + "name": "progress", + "type_info": "Float8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "progress" + } + } + }, + { + "ordinal": 7, + "name": "error_code", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "error_code" + } + } + }, + { + "ordinal": 8, + "name": "audio_key", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_key" + } + } + }, + { + "ordinal": 9, + "name": "audio_name", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_name" + } + } + }, + { + "ordinal": 10, + "name": "audio_type", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_type" + } + } + }, + { + "ordinal": 11, + "name": "audio_bytes", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_bytes" + } + } + }, + { + "ordinal": 12, + "name": "duration_secs", + "type_info": "Float8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "duration_secs" + } + } + }, + { + "ordinal": 13, + "name": "eta_secs", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "eta_secs" + } + } + }, + { + "ordinal": 14, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "created_at" + } + } + }, + { + "ordinal": 15, + "name": "updated_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "updated_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + true, + false, + false, + false, + true, + true, + true, + true, + true, + true, + true, + false, + false + ] + }, + "hash": "ad5b90d0407d3abf9a3bdf119146041a67a486a5560fa151ad8fe8210bfd9d53" +} diff --git a/.sqlx/query-b0f040f8c3044894f49702f9918b672f5b07587db6047f00cfda9c2effe7af56.json b/.sqlx/query-b0f040f8c3044894f49702f9918b672f5b07587db6047f00cfda9c2effe7af56.json new file mode 100644 index 0000000..d851981 --- /dev/null +++ b/.sqlx/query-b0f040f8c3044894f49702f9918b672f5b07587db6047f00cfda9c2effe7af56.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO zeka_question_segment_dimension\n (question, dimension, role, ord)\n VALUES ($1, $2, $3, $4)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Text", + "Int2" + ] + }, + "nullable": [] + }, + "hash": "b0f040f8c3044894f49702f9918b672f5b07587db6047f00cfda9c2effe7af56" +} diff --git a/.sqlx/query-c0f04896f37ecdb45eefd6ff79ede315709a64b53ff6fd8f6837f61283f1001b.json b/.sqlx/query-c0f04896f37ecdb45eefd6ff79ede315709a64b53ff6fd8f6837f61283f1001b.json new file mode 100644 index 0000000..e9894d9 --- /dev/null +++ b/.sqlx/query-c0f04896f37ecdb45eefd6ff79ede315709a64b53ff6fd8f6837f61283f1001b.json @@ -0,0 +1,26 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT slug FROM school WHERE status = 'active' ORDER BY slug", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "slug", + "type_info": "Text", + "origin": { + "Table": { + "table": "school", + "name": "slug" + } + } + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false + ] + }, + "hash": "c0f04896f37ecdb45eefd6ff79ede315709a64b53ff6fd8f6837f61283f1001b" +} diff --git a/.sqlx/query-d47b73487d9975d8c5fb3fc6236eb9e549150c86a1c752343b841147f359de28.json b/.sqlx/query-d47b73487d9975d8c5fb3fc6236eb9e549150c86a1c752343b841147f359de28.json new file mode 100644 index 0000000..7a3b6aa --- /dev/null +++ b/.sqlx/query-d47b73487d9975d8c5fb3fc6236eb9e549150c86a1c752343b841147f359de28.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM zeka_attention_item WHERE student = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "d47b73487d9975d8c5fb3fc6236eb9e549150c86a1c752343b841147f359de28" +} diff --git a/.sqlx/query-da1423194dea4b1b011f5d3634b12da661992cdc26d5ec3e2c30f6a6dcda2487.json b/.sqlx/query-da1423194dea4b1b011f5d3634b12da661992cdc26d5ec3e2c30f6a6dcda2487.json new file mode 100644 index 0000000..8d17141 --- /dev/null +++ b/.sqlx/query-da1423194dea4b1b011f5d3634b12da661992cdc26d5ec3e2c30f6a6dcda2487.json @@ -0,0 +1,25 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO zeka_student_segment_profile\n (student, dimension, label, n_answers, n_correct, accuracy,\n overall_n_answers, overall_accuracy, contrast, confidence,\n computed_at, retain_until)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)\n ON CONFLICT (student, dimension, label) DO UPDATE SET\n n_answers = EXCLUDED.n_answers, n_correct = EXCLUDED.n_correct,\n accuracy = EXCLUDED.accuracy,\n overall_n_answers = EXCLUDED.overall_n_answers,\n overall_accuracy = EXCLUDED.overall_accuracy,\n contrast = EXCLUDED.contrast, confidence = EXCLUDED.confidence,\n computed_at = EXCLUDED.computed_at, retain_until = EXCLUDED.retain_until", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Text", + "Int8", + "Int8", + "Float8", + "Int8", + "Float8", + "Float8", + "Text", + "Int8", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "da1423194dea4b1b011f5d3634b12da661992cdc26d5ec3e2c30f6a6dcda2487" +} diff --git a/.sqlx/query-e3c904f558317d2d0c709f4b6bb3c2109bc86448a3dc6895c5bf2a9c0c99cc98.json b/.sqlx/query-e3c904f558317d2d0c709f4b6bb3c2109bc86448a3dc6895c5bf2a9c0c99cc98.json new file mode 100644 index 0000000..013c0f4 --- /dev/null +++ b/.sqlx/query-e3c904f558317d2d0c709f4b6bb3c2109bc86448a3dc6895c5bf2a9c0c99cc98.json @@ -0,0 +1,215 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE podcast_job SET state = $3, stage = $4, progress = $5, error_code = $6, format = COALESCE(format, $7::text), updated_at = $8 WHERE id = $1 AND state = $2 RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: PodcastJobId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "podcast_job", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "user_id: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "podcast_job", + "name": "user_id" + } + } + }, + { + "ordinal": 2, + "name": "source_id", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "source_id" + } + } + }, + { + "ordinal": 3, + "name": "format", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "format" + } + } + }, + { + "ordinal": 4, + "name": "state: PodcastJobState", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "state" + } + } + }, + { + "ordinal": 5, + "name": "stage", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "stage" + } + } + }, + { + "ordinal": 6, + "name": "progress", + "type_info": "Float8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "progress" + } + } + }, + { + "ordinal": 7, + "name": "error_code", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "error_code" + } + } + }, + { + "ordinal": 8, + "name": "audio_key", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_key" + } + } + }, + { + "ordinal": 9, + "name": "audio_name", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_name" + } + } + }, + { + "ordinal": 10, + "name": "audio_type", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_type" + } + } + }, + { + "ordinal": 11, + "name": "audio_bytes", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_bytes" + } + } + }, + { + "ordinal": 12, + "name": "duration_secs", + "type_info": "Float8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "duration_secs" + } + } + }, + { + "ordinal": 13, + "name": "eta_secs", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "eta_secs" + } + } + }, + { + "ordinal": 14, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "created_at" + } + } + }, + { + "ordinal": 15, + "name": "updated_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "updated_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Text", + "Text", + "Float8", + "Text", + "Text", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + true, + false, + false, + false, + true, + true, + true, + true, + true, + true, + true, + false, + false + ] + }, + "hash": "e3c904f558317d2d0c709f4b6bb3c2109bc86448a3dc6895c5bf2a9c0c99cc98" +} diff --git a/.sqlx/query-eef4d307eacc7efa9eff673b382448cebbfaa47e3e7e1d907a8c902d582b3fbc.json b/.sqlx/query-eef4d307eacc7efa9eff673b382448cebbfaa47e3e7e1d907a8c902d582b3fbc.json new file mode 100644 index 0000000..195d332 --- /dev/null +++ b/.sqlx/query-eef4d307eacc7efa9eff673b382448cebbfaa47e3e7e1d907a8c902d582b3fbc.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM zeka_run_pending WHERE student <> ALL($1)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [] + }, + "hash": "eef4d307eacc7efa9eff673b382448cebbfaa47e3e7e1d907a8c902d582b3fbc" +} diff --git a/.sqlx/query-f1a079e6c5978b7d9458172705e0c66f070d71e3435dc8f359d09675c5fcccdc.json b/.sqlx/query-f1a079e6c5978b7d9458172705e0c66f070d71e3435dc8f359d09675c5fcccdc.json new file mode 100644 index 0000000..5521750 --- /dev/null +++ b/.sqlx/query-f1a079e6c5978b7d9458172705e0c66f070d71e3435dc8f359d09675c5fcccdc.json @@ -0,0 +1,214 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE podcast_job SET audio_key = $2, audio_name = $3, audio_type = $4, audio_bytes = $5, duration_secs = $6, updated_at = $7 WHERE id = $1 RETURNING id AS \"id: PodcastJobId\", user_id AS \"user_id: UserId\", source_id, format, state AS \"state: PodcastJobState\", stage, progress, error_code, audio_key, audio_name, audio_type, audio_bytes, duration_secs, eta_secs, created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: PodcastJobId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "podcast_job", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "user_id: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "podcast_job", + "name": "user_id" + } + } + }, + { + "ordinal": 2, + "name": "source_id", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "source_id" + } + } + }, + { + "ordinal": 3, + "name": "format", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "format" + } + } + }, + { + "ordinal": 4, + "name": "state: PodcastJobState", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "state" + } + } + }, + { + "ordinal": 5, + "name": "stage", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "stage" + } + } + }, + { + "ordinal": 6, + "name": "progress", + "type_info": "Float8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "progress" + } + } + }, + { + "ordinal": 7, + "name": "error_code", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "error_code" + } + } + }, + { + "ordinal": 8, + "name": "audio_key", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_key" + } + } + }, + { + "ordinal": 9, + "name": "audio_name", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_name" + } + } + }, + { + "ordinal": 10, + "name": "audio_type", + "type_info": "Text", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_type" + } + } + }, + { + "ordinal": 11, + "name": "audio_bytes", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "audio_bytes" + } + } + }, + { + "ordinal": 12, + "name": "duration_secs", + "type_info": "Float8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "duration_secs" + } + } + }, + { + "ordinal": 13, + "name": "eta_secs", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "eta_secs" + } + } + }, + { + "ordinal": 14, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "created_at" + } + } + }, + { + "ordinal": 15, + "name": "updated_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "podcast_job", + "name": "updated_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Text", + "Text", + "Int8", + "Float8", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + true, + false, + false, + false, + true, + true, + true, + true, + true, + true, + true, + false, + false + ] + }, + "hash": "f1a079e6c5978b7d9458172705e0c66f070d71e3435dc8f359d09675c5fcccdc" +} diff --git a/.sqlx/query-f844815300b8be204b2cf5f2b1ef782b9fee47fde37708ee071f9002bd163888.json b/.sqlx/query-f844815300b8be204b2cf5f2b1ef782b9fee47fde37708ee071f9002bd163888.json new file mode 100644 index 0000000..1c75553 --- /dev/null +++ b/.sqlx/query-f844815300b8be204b2cf5f2b1ef782b9fee47fde37708ee071f9002bd163888.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO zeka_run_pending (run, student, ord) VALUES ($1, $2, $3)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Uuid", + "Int4" + ] + }, + "nullable": [] + }, + "hash": "f844815300b8be204b2cf5f2b1ef782b9fee47fde37708ee071f9002bd163888" +} diff --git a/.sqlx/query-f93aab2536f71779fa9d1b973a9e5c4b7ca3c48dd8e9cebf91c745130de0ad4e.json b/.sqlx/query-f93aab2536f71779fa9d1b973a9e5c4b7ca3c48dd8e9cebf91c745130de0ad4e.json new file mode 100644 index 0000000..371d33d --- /dev/null +++ b/.sqlx/query-f93aab2536f71779fa9d1b973a9e5c4b7ca3c48dd8e9cebf91c745130de0ad4e.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM zeka_attention_item WHERE student <> ALL($1)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [] + }, + "hash": "f93aab2536f71779fa9d1b973a9e5c4b7ca3c48dd8e9cebf91c745130de0ad4e" +} diff --git a/README.md b/README.md index 69ed7b2..d99a099 100644 --- a/README.md +++ b/README.md @@ -1325,10 +1325,19 @@ window filtering, before paging; negative values are a `400` naming the field. | DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove a file from the caller's own submission — row first, then its blob. Same visibility gates as submitting. Refused (409) once graded. Removing a file re-stamps the submission's `updated_at`. | | GET | `/homework/{id}/submissions` | teacher | The teacher's roster for a homework, paged via `?limit=&offset=` (omit `limit` for all of it): one row per student in the audience — the assigned subset, or every student currently enrolled in the instance when the homework carries none — plus any student outside it who still owns a submission or grade (an unenrollment or an audience change leaves work behind; it stays visible here, flagged). Each row carries the submission with its files and computed late flag, the grade, a computed `missing`, and a computed `unenrolled`. Requires teacher+ and management rights over the homework's instance. Returns a `{items, total, limit, offset}` envelope. | | GET | `/insights/me` | student | The caller's own insight. Students get their summary, their own cards and their segment profile — **never** the attention list about themselves. Any other role gets the cards addressed to them (a teacher's `T4` cards about their students), with `summary`/`segments` empty. | +| GET | `/insights/pending` | manager | The students the freshest compute run left pending — where the next run starts. | +| POST | `/insights/profiles` | manager | Store a batch of ZEKA's student segment profiles. | +| POST | `/insights/purge` | manager | Delete the derived rows of every student who is no longer on the roster. | +| POST | `/insights/recommendations` | manager | Store a batch of ZEKA's recommendation cards. | | 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/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. | | POST | `/insights/students/{user}` | teacher | Ask ZEKA to recompute one student's insight, detached. `202` means queued, not computed: the service works through the student's data and writes its `zeka_*` rows on its own, and `GET /insights/students/{id}` shows them as soon as they land. `503` when no service offers `insight.student` — and nothing is queued. | +| POST | `/insights/summaries` | manager | Store a batch of ZEKA's student summaries (and their attention items). | +| POST | `/insights/sweep` | manager | Delete every `zeka_*` row whose retention window has closed. | | GET | `/instances/me` | student | The instances the caller may act in or see, paged via `?limit=&offset=` (omit `limit` for all of them), newest first; returns a `{items, total, limit, offset}` envelope. The route a student reads to find the courses their section is being taught, and a teacher the ones they run. | | GET | `/instances/{id}` | student | Fetch one instance by id. Visible to its enrolled students, its assigned teachers, its şube's homeroom teacher, and managers/admins. | | PATCH | `/instances/{id}` | teacher | Update one instance's own policy. Requires teacher+ and a right over this instance: manager+, one of its assigned teachers, or its şube's homeroom teacher. Omitted fields keep their value; both are non-clearable. | @@ -1400,11 +1409,11 @@ window filtering, before paging; negative values are a `400` naming the field. | POST | `/payments/reversals` | manager | Undo a line entered by mistake, for its exact amount — the line itself stays, with an opposing one appended beside it. Only a `charge` or a `refund` may be reversed (`400` otherwise): a mistaken payment is corrected with a refund, so money leaving the school is always spelled the one way. **Idempotent** — a line has at most one reversal, however often the call is retried. | | GET | `/payments/statement/me` | student | The caller's own statement. The per-charge rows are paged via `?limit=&offset=` (omit `limit` for all of them); `balance_minor` is the same on every page, because the fold behind it reads every line. | | GET | `/payments/statement/{user}` | manager | One student's statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is overdue. Own record always; otherwise manager+ or a parent link (a teacher gets a `403`). The rows are paged via `?limit=&offset=`; `balance_minor` is the same on every page. | -| GET | `/podcast/audio` | student | Stream one produced audio file. `path` is the `audio_id` `podcast.result` answered, resolved under **this caller's school** output directory — the same directory the service's `PODCAST_OUTPUT_ROOT` points at — and streamed in 64 KiB chunks, so a long episode costs the backend a bounded buffer rather than its whole length in memory. | -| POST | `/podcast/jobs` | student | Start one podcast job. Answers `202` with the service's receipt the moment the service accepts it; the pipeline then runs in the service's own worker pool, so poll `GET /jobs/{id}` for progress. | -| GET | `/podcast/jobs/{id}` | student | One job's current state. Poll this; the answer is the service's own snapshot. | -| POST | `/podcast/jobs/{id}/cancel` | student | Cancel one job. `cancelled` says whether *this call* stopped work — a job that had already finished, or was already cancelled, answers `false` and is not an error. | -| GET | `/podcast/jobs/{id}/result` | student | A finished job's artifacts — above all the `audio_id` the audio door streams. A job that has not finished yet is refused by the service with `not_ready` (409); one it has never heard of with `not_found` (404). | +| POST | `/podcast/jobs` | student | Start one podcast job. Answers `202` with the backend's own receipt the moment the service accepts it. | +| GET | `/podcast/jobs/{id}` | student | One job's current state — the backend's own row, so this door answers with the service down, restarted, or never connected at all. A job nobody has updated inside its ETA-scaled window reads as `failed`/`interrupted`; that projection is read-side only and never written. | +| GET | `/podcast/jobs/{id}/audio` | student | Stream one produced episode. The bytes are this school's own — ingested under this school's blob directory — and the content type is the one the upload declared, replayed from the row. | +| POST | `/podcast/jobs/{id}/cancel` | student | Cancel one job. `cancelled` says whether *this call* stopped work — a job that had already finished, or was already cancelled, answers `false` and is not an error. Only a live job needs the service; a terminal one is answered from the row without a worker. A service that has never heard of a live job (its store was wiped) leaves the row `failed`/`interrupted`: the job cannot finish, and the row says so. | +| GET | `/podcast/jobs/{id}/result` | student | A finished job's artifact references. A job that has not finished is a `409 not_ready`; one the caller does not own, a `404`. | | POST | `/pomodoro/finish` | student | Finish the running pomodoro session, closing it with a server-stamped instant (`409` when nothing is running); answers `counted` — whether it moved the badge counters (ran at least `pomodoro.min_counted_ms`, within that UTC day's `pomodoro.max_counted_per_day`). | | GET | `/pomodoro/me` | student | The caller's own pomodoro log, newest first — the running session (if any) included (`finished_at: null`) — plus `total_focus_ms`, the unpaged sum of finished-session durations. Paged via `?limit=&offset=` (omit `limit` for the whole log). | | POST | `/pomodoro/start` | student | Start a pomodoro focus session. Students only. The instant is stamped by the server clock — clients never supply it. Always succeeds for a student: a dangling unfinished session (the browser died mid-timer) is discarded and replaced, so there is no way to lock yourself out of starting. The frontend runs the visible countdown and the break rhythm; the backend records only the focus stint. The body is optional and names the stint: a `label` rides the response and every log it lists in — a blank or absent body starts an unnamed stint, an over-long label is `400`. | diff --git a/src/ai/capability.rs b/src/ai/capability.rs new file mode 100644 index 0000000..3abbe0a --- /dev/null +++ b/src/ai/capability.rs @@ -0,0 +1,101 @@ +//! The table of capabilities the **backend** serves — the operations a +//! service calls over the bridge's client-initiated `CapabilityRequest` shape +//! (`hab/2`'s third request kind), and each one's scope. +//! +//! There is one table per capability family, and this module is the walk over +//! them: [`crate::ai::insight`] serves ZEKA's storage surface, +//! [`crate::ai::podcast`] serves the podcast job's state reports. Both answer +//! the same frame, both are dispatched from the same place — the bridge's +//! capability dispatcher in `ai::server` — and neither owns the other's +//! names: a name neither table holds is `unknown_capability`, with no prefix +//! match and no fallback, exactly as the two tables' own doc comments say. +//! +//! The scope decides one thing only: whether the bridge resolves the frame's +//! school before the operation runs. A [`Scope::School`] operation runs against +//! the named school's own database — the frame's school is the *only* tenancy +//! input, and a slug that matches nothing is `unknown_school`, never a +//! fallback to another school or to the control database. + +use serde_json::Value; + +use crate::ai::podcast; +use crate::constant::AI_PODCAST_REPORT_CAPABILITY; +use crate::database::Database; +use crate::tenant::ResolvedTenant; + +pub use crate::ai::insight::Scope; + +/// The refusal shape every backend-served capability answers with: a flat, +/// stable code and a message that names the field or reason. Same alias as +/// [`crate::ai::insight::Refusal`] — one vocabulary across families. +pub type Refusal = (&'static str, String); + +/// Every capability the podcast family serves, and its scope. One entry today; +/// a table rather than a match arm so the walk in [`scope_of`] and the +/// dispatch in [`serve`] are structurally the same decision, and a second +/// podcast operation is one added row. +pub const PODCAST_SERVED: &[(&str, Scope)] = &[(AI_PODCAST_REPORT_CAPABILITY, Scope::School)]; + +/// The scope of one backend-served capability, or `None` if no family serves +/// it. Matched exactly, family by family, in a fixed order. +pub fn scope_of(capability: &str) -> Option { + crate::ai::insight::scope_of(capability).or_else(|| { + PODCAST_SERVED + .iter() + .find(|(name, _)| *name == capability) + .map(|(_, scope)| *scope) + }) +} + +/// Run one backend-served capability. The caller (the bridge) resolves the +/// school *before* this is called, from [`scope_of`]'s answer — a +/// [`Scope::Deployment`] operation gets `None`, and a [`Scope::School`] one +/// always gets the tenant. +pub async fn serve( + capability: &str, + school: Option<&ResolvedTenant>, + control: &Database, + payload: &Value, +) -> Result { + if crate::ai::insight::scope_of(capability).is_some() { + return crate::ai::insight::serve(capability, school, control, payload).await; + } + match capability { + AI_PODCAST_REPORT_CAPABILITY => { + let Some(tenant) = school else { + return Err(( + "internal", + format!("`{AI_PODCAST_REPORT_CAPABILITY}` is school-scoped but no school was resolved"), + )); + }; + // The frame's payload is cloned once per report call, and a report + // is a handful of short fields — this is the price of one dispatch + // table across two families that decode differently. + podcast::report(&tenant.db, payload.clone()).await + } + _ => Err(( + "unknown_capability", + format!("the backend serves no `{capability}` operation"), + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_family_name_resolves_and_a_stranger_does_not() { + assert_eq!(scope_of(AI_PODCAST_REPORT_CAPABILITY), Some(Scope::School)); + assert_eq!(scope_of("podcast.submit"), None, "worker-only, not served"); + assert_eq!(scope_of("podcast.status"), None, "deleted: the row answers"); + assert_eq!(scope_of("podcast.nothing"), None); + assert_eq!(scope_of(""), None); + } + + #[test] + fn the_podcast_table_is_exactly_its_documented_vocabulary() { + assert_eq!(PODCAST_SERVED.len(), 1); + assert!(PODCAST_SERVED.iter().all(|(_, scope)| *scope == Scope::School)); + } +} diff --git a/src/ai/insight.rs b/src/ai/insight.rs index 6ae65d3..2bc0409 100644 --- a/src/ai/insight.rs +++ b/src/ai/insight.rs @@ -1,21 +1,20 @@ -//! Payload contract for the `insight.*` capabilities, and the dispatch behind -//! the two the backend can route today. +//! Payload contract for the `insight.*` capabilities, in both directions. //! //! ZEKA (`hezarfen_zeka`) computes student and class insights from a school's -//! own data. Unlike the chatbot and the RAG nests, whose answers the backend -//! stores, ZEKA **writes its own rows**: the `zeka_*` tables in each school -//! database, created by the school migrator -//! (`migrations/school/20260917000002_zeka.sql`). This module only carries the -//! frames; [`crate::web::insights`] is the reader of what lands. +//! own data. The family has two halves and they travel opposite ways: //! -//! That split is why the dispatches here return the service's answer rather -//! than store it — the answer is a receipt, and the rows are the product. A -//! dispatch that times out, or a service that refuses, leaves the previously -//! computed rows exactly as they are: a stale insight beats a hole. The two -//! capabilities this module dispatches: -//! -//! * [`AI_INSIGHT_STUDENT_CAPABILITY`] — one student, on demand; -//! * [`AI_INSIGHT_REFRESH_CAPABILITY`] — a school-wide sweep, on demand. +//! * **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`]). +//! * **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 +//! service may touch a school database**. [`serve`] runs them; the SQL +//! lives in [`crate::db::insight`], and [`crate::web::insights`] mounts the +//! same functions as HTTP doors. This is the shape the whole family exists +//! for: an operation named on the wire, scoped to the frame's school, with +//! no path, no table and no query any caller can name. //! //! [`AI_INSIGHT_CLASS_CAPABILITY`] is declared (the service announces it) but //! deliberately not dispatched: its request names a course the service would @@ -27,7 +26,9 @@ //! Every payload member is optional on the response side on purpose: the //! service's TypedDicts are `total=False`, so a partial answer is a legal //! answer, and a strict struct here would turn a service update into a -//! backend error. +//! backend error. The inbound rows are the opposite: they are a *write* +//! contract, so a missing field is refused rather than defaulted — except +//! where this module says an omission is meaningful. use std::time::Duration; @@ -221,6 +222,201 @@ fn malformed(err: serde_json::Error) -> AiError { AiError::Protocol(FrameError::Malformed(err)) } +// ---- the operations the backend serves ------------------------------------- +// +// The half of this module that runs *towards* the backend. ZEKA computes, but +// it may not write: no AI service holds a school database credential on this +// deployment, so its `zeka_*` rows are written and read here, by name, over +// the same bridge — one operation per call, each scoped to the school the +// frame named. [`crate::db::insight`] is the SQL; this is the contract: which +// names exist, what each payload is, and how a refusal reads. + +pub use crate::db::insight::{ + AttentionRow, PendingList, ProfileRow, ProfileWriteRequest, PurgeRequest, RecommendationRow, + RecommendationWriteRequest, RunRow, RunWriteRequest, SchoolDirectory, SegmentConfidences, + SegmentLabels, SegmentRow, SegmentWriteRequest, SummaryRow, SummaryWriteRequest, + TableVerdicts, WriteReceipt, +}; + +use crate::constant::{ + AI_INSIGHT_DEPARTED_PURGE_CAPABILITY, AI_INSIGHT_PENDING_LIST_CAPABILITY, + AI_INSIGHT_PROFILE_UPSERT_CAPABILITY, AI_INSIGHT_RECOMMENDATION_UPSERT_CAPABILITY, + AI_INSIGHT_RETENTION_SWEEP_CAPABILITY, AI_INSIGHT_RUN_UPSERT_CAPABILITY, + AI_INSIGHT_SCHOOLS_LIST_CAPABILITY, AI_INSIGHT_SEGMENT_UPSERT_CAPABILITY, + AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY, +}; +use crate::database::Database; +use crate::db; +use crate::domain::timestamp::Timestamp; +use crate::error::AppError; +use crate::module::Module; +use crate::tenant::ResolvedTenant; + +/// A refusal headed for a [`CapabilityResponse::Err`](crate::ai::protocol::CapabilityResponse::Err): +/// the documented code, and a message that names the field a caller can fix. +pub type Refusal = (&'static str, String); + +/// What a served capability is scoped to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Scope { + /// It runs against the school the frame named, and nothing else. + School, + /// Its answer does not come from a school's database at all — the + /// directory the fleet schedules over. The frame sends no school. + Deployment, +} + +/// Every capability the backend serves, and its scope. Matched exactly: a +/// name that is not here is `unknown_capability`, with no prefix match and no +/// fallback — an operation a caller cannot name is one it cannot run. +pub const SERVED: &[(&str, Scope)] = &[ + (AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY, Scope::School), + ( + AI_INSIGHT_RECOMMENDATION_UPSERT_CAPABILITY, + Scope::School, + ), + (AI_INSIGHT_SEGMENT_UPSERT_CAPABILITY, Scope::School), + (AI_INSIGHT_PROFILE_UPSERT_CAPABILITY, Scope::School), + (AI_INSIGHT_RUN_UPSERT_CAPABILITY, Scope::School), + (AI_INSIGHT_PENDING_LIST_CAPABILITY, Scope::School), + (AI_INSIGHT_RETENTION_SWEEP_CAPABILITY, Scope::School), + (AI_INSIGHT_DEPARTED_PURGE_CAPABILITY, Scope::School), + (AI_INSIGHT_SCHOOLS_LIST_CAPABILITY, Scope::Deployment), +]; + +/// The scope of one served capability, or `None` if the backend serves no +/// operation by that name. +pub fn scope_of(capability: &str) -> Option { + SERVED + .iter() + .find(|(name, _)| *name == capability) + .map(|(_, scope)| *scope) +} + +/// Run one capability call and hand back its payload. +/// +/// `school` is the tenant the bridge resolved for the frame — `None` only for +/// a [`Scope::Deployment`] capability, whose frame names no school. The +/// school's own feature set is checked here as well as at the HTTP nest: a +/// school that is not being served insights should not be accumulating rows +/// for them either. +pub async fn serve( + capability: &str, + school: Option<&ResolvedTenant>, + control: &Database, + payload: &Value, +) -> Result { + if scope_of(capability).is_none() { + return Err(( + "unknown_capability", + format!("the backend serves no `{capability}` operation"), + )); + } + if capability == AI_INSIGHT_SCHOOLS_LIST_CAPABILITY { + let directory = db::insight::active_schools(control).await.map_err(refusal)?; + return encode(&directory); + } + let Some(tenant) = school else { + return Err(( + "unknown_school", + "this operation runs against a school and the frame named none".to_string(), + )); + }; + if !tenant.modules.contains(Module::Chatbot) { + return Err(( + "not_permitted", + "this school does not have the insights module enabled".to_string(), + )); + } + let db = &tenant.db; + let answer = match capability { + AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY => { + let request: SummaryWriteRequest = decode(payload)?; + encode(&db::insight::write_summaries(db, request.rows).await.map_err(refusal)?) + } + AI_INSIGHT_RECOMMENDATION_UPSERT_CAPABILITY => { + let request: RecommendationWriteRequest = decode(payload)?; + encode( + &db::insight::write_recommendations(db, request.rows) + .await + .map_err(refusal)?, + ) + } + AI_INSIGHT_SEGMENT_UPSERT_CAPABILITY => { + let request: SegmentWriteRequest = decode(payload)?; + encode(&db::insight::write_segments(db, request.rows).await.map_err(refusal)?) + } + AI_INSIGHT_PROFILE_UPSERT_CAPABILITY => { + let request: ProfileWriteRequest = decode(payload)?; + encode(&db::insight::write_profiles(db, request.rows).await.map_err(refusal)?) + } + AI_INSIGHT_RUN_UPSERT_CAPABILITY => { + let request: RunWriteRequest = decode(payload)?; + encode(&db::insight::write_run(db, request.run).await.map_err(refusal)?) + } + AI_INSIGHT_PENDING_LIST_CAPABILITY => { + encode(&db::insight::last_pending(db).await.map_err(refusal)?) + } + AI_INSIGHT_RETENTION_SWEEP_CAPABILITY => { + // The backend's own clock decides expiry — a service's clock is + // not a second authority on when a row's retention has closed. + let now_ms = Timestamp::now().as_millis(); + encode(&db::insight::sweep(db, now_ms).await.map_err(refusal)?) + } + AI_INSIGHT_DEPARTED_PURGE_CAPABILITY => { + let request: PurgeRequest = decode(payload)?; + encode( + &db::insight::purge_departed(db, request.students) + .await + .map_err(refusal)?, + ) + } + // `scope_of` matched above, so the table and this match agree; the + // arm exists so a table entry without an operation is a compile-time + // miss instead of a runtime surprise. + other => { + return Err(( + "unknown_capability", + format!("the backend serves no `{other}` operation"), + )); + } + }; + answer +} + +/// Decode one payload into the operation's own type. A payload that does not +/// fit is `invalid_payload`, never `malformed`: the frame was a capability +/// call, the body was not this operation's body, and the caller can fix it. +fn decode(payload: &Value) -> Result { + serde_json::from_value(payload.clone()) + .map_err(|err| ("invalid_payload", format!("payload: {err}"))) +} + +fn encode(value: &T) -> Result { + serde_json::to_value(value).map_err(|err| ("internal", format!("could not encode the answer: {err}"))) +} + +/// [`AppError`] as the protocol's refusal vocabulary. The mapping is the +/// whole reason the db layer returns `AppError` rather than its own type: +/// HTTP answers these through [`crate::error`], and a capability call answers +/// the same verdict with the code a service branches on. +fn refusal(err: AppError) -> Refusal { + match err { + AppError::Validation(err) => ("invalid_payload", err.to_string()), + AppError::PayloadTooLarge(message) => ("too_many_rows", message), + AppError::ModuleDisabled(module) => ( + "not_permitted", + format!("this school does not have the `{module}` module enabled"), + ), + AppError::NotFound => ("not_found", "the named row does not exist".to_string()), + AppError::DbUnavailable | AppError::DbTimeout => ( + "unavailable", + "this school's database could not be reached".to_string(), + ), + other => ("internal", other.to_string()), + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/ai/protocol.rs b/src/ai/protocol.rs index 0952d2f..2a7727f 100644 --- a/src/ai/protocol.rs +++ b/src/ai/protocol.rs @@ -30,8 +30,48 @@ //! and then the stream is finished. That is how a service gets a course //! note's file bytes, which no JSON frame could carry. //! -//! The two client-initiated request shapes are told apart by their required -//! field: an [`ApiRequest`] has `path`, a [`BlobRequest`] has `file`. +//! * Each **capability call** also goes the service's way, on its own +//! client-initiated bidirectional stream: the service writes one +//! [`CapabilityRequest`], finishes its send side, and reads one +//! [`CapabilityResponse`]. This is the reverse of the [`Request`]/ +//! [`Response`] pair above, and it exists for the same reason the api read +//! does: capabilities live on both sides. The backend *dispatches* +//! `chat.reply` and `insight.student` to a service; a service *calls* +//! `insight.summary.upsert` and the rest of the backend's storage surface +//! to have the backend write rows an AI service may not write itself. +//! +//! The three client-initiated request shapes are told apart by their +//! required field: an [`ApiRequest`] has `path`, a [`BlobRequest`] has +//! `file`, a [`CapabilityRequest`] has `capability`. +//! +//! * Each **blob upload** is the blob read's mirror image: the service writes +//! one [`BlobUploadRequest`], then exactly `size` **raw** bytes — again not a +//! frame — and finishes its send side; the backend stores them and answers +//! one [`BlobUploadResponse`] header frame. That is how a service hands back +//! an artifact it produced (today the podcast service's finished mp3), which +//! no JSON frame could carry. Distinguished from a [`BlobRequest`] by its +//! required `upload` marker and `job_id`. +//! +//! # Refusal codes +//! +//! [`ApiResponse::Err`], [`BlobResponse::Err`] and [`CapabilityResponse::Err`] +//! all carry a `code`: a stable, machine-readable string a service branches +//! on, never a message. The vocabulary, in one place: +//! +//! * `malformed` — the frame is not this shape (a missing or mistyped field). +//! * `unknown_capability` — no operation this backend serves has that name. +//! * `unknown_school` — the named slug is not a school on this deployment. +//! * `school_suspended` — it exists and is switched off; worth retrying later. +//! * `not_permitted` — the school's own feature set refuses the operation. +//! * `invalid_payload` — the payload does not fit the operation's contract +//! (`message` names the field). +//! * `too_many_rows` — a count bound was exceeded (`message` names it); the +//! operation was refused whole, never applied in part. +//! * `unavailable` — the school's database could not be reached. +//! * `timed_out` — the operation outlived the bridge's deadline; whether it +//! landed is unknown, so retrying is the caller's decision. +//! * `internal` — the backend failed while doing the work. +//! * `path_not_allowed`, `unknown_user`, `method_not_allowed` — api-read only. //! //! # School scoping //! @@ -264,6 +304,124 @@ pub enum BlobResponse { }, } +/// A call of one capability the *backend* serves, written by the service on a +/// fresh client-initiated stream. The mirror image of [`Request`], which the +/// backend writes when it calls a capability the *service* serves. +/// +/// Distinguished from an [`ApiRequest`] by its required `capability` field and +/// from a [`BlobRequest`] by its required `school` and `payload`. There is no +/// path and no method: an operation is named, never addressed — the backend's +/// storage surface is a list of operations, and a frame that could name a +/// table, a schema or a query would be the door this shape exists to not have. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct CapabilityRequest { + /// Trace id (ULID). Not used for correlation — the stream does that. + pub id: String, + /// Slug of the school the call is scoped to. Required, exactly as on + /// every other frame — one capability is deployment-scoped + /// (`insight.schools.list`, whose answer *is* the school directory) and + /// sends the empty string there. + pub school: String, + /// The operation to run. Matched exactly against the backend's served + /// capabilities; anything else is `unknown_capability`. + pub capability: String, + /// Operation-specific body, opaque to the transport. + pub payload: Value, +} + +/// The backend's single answer frame, mirroring [`Response`] field for field: +/// `status` is the discriminator, and both variants echo the school the call +/// named so a service can tell which of its in-flight calls was answered. +/// +/// `Err` is a *handled* refusal (unknown capability, a payload that does not +/// fit, the school's database unreachable). A service that dies mid-call just +/// drops the stream, which surfaces as a transport error instead. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "status", rename_all = "snake_case")] +pub enum CapabilityResponse { + Ok { + /// Echo of [`CapabilityRequest::id`]. + id: String, + /// Echo of [`CapabilityRequest::school`]. + school: String, + payload: Value, + }, + Err { + /// Echo of [`CapabilityRequest::id`]. + id: String, + /// Echo of [`CapabilityRequest::school`], as sent. + school: String, + /// One of this module's documented refusal codes. + code: String, + message: String, + }, +} + +/// A write of one produced artifact's *bytes*, written by the *service* on a +/// fresh client-initiated stream. The mirror image of [`BlobRequest`]: the +/// service names what it is handing over, exactly `size` raw bytes follow this +/// frame, and the backend stores them somewhere that belongs to the school — +/// never to the service's own volume. +/// +/// Distinguished from a [`BlobRequest`] (the read) by the required `upload` +/// marker and its `job_id`: an upload is always *about* one backend-minted +/// job, and the backend links the stored blob to that job's row. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct BlobUploadRequest { + /// Trace id (ULID). Not used for correlation — the stream does that. + pub id: String, + /// The shape marker. Must be `true`; any other value is `malformed`. + pub upload: bool, + /// Slug of the school the artifact belongs to. Required — the bytes land + /// in that school's own blob directory, never anywhere else. + pub school: String, + /// The backend-minted podcast job the artifact belongs to. + pub job_id: String, + /// The artifact's display name (an episode's file name). Stored as + /// metadata; never used to build a path. + pub name: String, + /// The artifact's MIME type. Must be an `audio/*` type today. + pub content_type: String, + /// Exactly how many raw bytes follow this frame. + pub size: u64, + /// The episode's length, when the producer knows it. Metadata for the + /// read doors; `None` is allowed. + #[serde(default)] + pub duration_secs: Option, +} + +/// The single answer frame an upload gets. There are no bytes after it: the +/// artifact travels service → backend only, and `Ok.key` is the handle the +/// read doors publish (`GET /podcast/jobs/{id}/audio` resolves it). A refusal +/// carries nothing after the frame, and the backend resets the stream rather +/// than reading a body it will not store. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "status", rename_all = "snake_case")] +pub enum BlobUploadResponse { + Ok { + /// Echo of [`BlobUploadRequest::id`]. + id: String, + /// Echo of [`BlobUploadRequest::school`]. + school: String, + /// The key the bytes were stored under, relative to the school's blob + /// root (`podcast/.`). + key: String, + /// How many bytes were written — always the request's `size`. + size: u64, + }, + Err { + /// Echo of [`BlobUploadRequest::id`]. + id: String, + /// Echo of [`BlobUploadRequest::school`], as sent. + school: String, + /// This module's documented refusal codes, plus the operation's own + /// (`unknown_job`, `expired`, `audio_missing`, …) — flat and stable, + /// never nested. + code: String, + message: String, + }, +} + /// Write one length-prefixed JSON frame. pub async fn write_frame(w: &mut W, message: &T) -> Result<(), FrameError> where @@ -468,6 +626,89 @@ mod tests { assert_eq!(err["code"], "path_not_allowed"); } + #[tokio::test] + async fn capability_frame_tags_are_the_documented_wire_names() { + // The answer mirrors `Response` exactly — same `status` discriminator, + // same field names — so a service decodes both with one function. + // Pinned because other-language services match these literals. + let ok = serde_json::to_value(CapabilityResponse::Ok { + id: "1".into(), + school: "demo".into(), + payload: json!({ "written": 2 }), + }) + .unwrap(); + assert_eq!(ok["status"], "ok"); + assert_eq!(ok["id"], "1"); + assert_eq!(ok["school"], "demo"); + assert_eq!(ok["payload"]["written"], 2); + let err = serde_json::to_value(CapabilityResponse::Err { + id: "1".into(), + school: "demo".into(), + code: "unknown_capability".into(), + message: "nope".into(), + }) + .unwrap(); + assert_eq!(err["status"], "err"); + assert_eq!(err["code"], "unknown_capability"); + assert_eq!(err["school"], "demo"); + // A refusal carries no payload: there is no half-answer to read. + assert!(err.get("payload").is_none()); + } + + #[tokio::test] + async fn a_capability_request_needs_an_id_a_school_a_capability_and_a_payload() { + let call: CapabilityRequest = serde_json::from_value(json!({ + "id": "01J", + "school": "demo", + "capability": "insight.summary.upsert", + "payload": { "rows": [] }, + })) + .unwrap(); + assert_eq!(call.capability, "insight.summary.upsert"); + // Each of the three fields is required: a frame missing its + // capability names no operation to run, and a frame missing its + // school could only be answered out of a database nobody named. + for missing in ["id", "school", "capability", "payload"] { + let mut frame = json!({ + "id": "01J", + "school": "demo", + "capability": "insight.pending.list", + "payload": {}, + }); + frame.as_object_mut().unwrap().remove(missing); + assert!( + serde_json::from_value::(frame).is_err(), + "a frame without `{missing}` must not parse" + ); + } + } + + #[tokio::test] + async fn the_client_initiated_shapes_do_not_parse_as_each_other() { + // Routing is by required field (`path` / `file` / `capability`), so + // this is the property that keeps a capability call from being + // mistaken for an api read — or for a blob read, which is what the + // frame would look like if `capability` were ever optional. + let call = json!({ + "id": "01J", + "school": "demo", + "capability": "insight.pending.list", + "payload": {}, + }); + assert!( + serde_json::from_value::(call.clone()).is_ok(), + "the capability frame must parse as a capability call" + ); + assert!( + serde_json::from_value::(call.clone()).is_err(), + "a capability call must not parse as an api read" + ); + assert!( + serde_json::from_value::(call).is_err(), + "a capability call must not parse as a blob read" + ); + } + #[tokio::test] async fn an_api_request_needs_only_an_id_a_school_and_a_path() { let bare: ApiRequest = serde_json::from_value(json!({ diff --git a/src/ai/server.rs b/src/ai/server.rs index 94583a8..5e343d8 100644 --- a/src/ai/server.rs +++ b/src/ai/server.rs @@ -15,8 +15,9 @@ use tracing::Instrument; use crate::ai::error::AiError; use crate::ai::protocol::{ - ApiRequest, ApiResponse, BlobRequest, BlobResponse, FrameError, Greeting, Hello, RejectCode, - Request, Response, protocol_matches, read_frame, write_frame, + ApiRequest, ApiResponse, BlobRequest, BlobResponse, BlobUploadRequest, BlobUploadResponse, + CapabilityRequest, CapabilityResponse, FrameError, Greeting, Hello, RejectCode, Request, + Response, protocol_matches, read_frame, write_frame, }; use crate::ai::registry::{AiRegistry, WorkerSnapshot, clamp_concurrency}; use crate::ai::tls; @@ -495,6 +496,42 @@ async fn serve_client_stream( } return; } + // The third client-initiated shape: a call of a capability the *backend* + // serves (ZEKA's storage surface). Routed on `capability`, which neither + // of the shapes above carries. + if raw.get("capability").is_some() { + match serde_json::from_value::(raw) { + Ok(request) => { + let response = serve_capability(&inner, request).await; + answer_capability(&mut send, response).await; + } + Err(e) => { + answer_capability( + &mut send, + capability_refusal(&id, &school, "malformed", e.to_string()), + ) + .await; + } + } + return; + } + // The fourth client-initiated shape: an artifact's bytes coming *in* (the + // podcast service's finished mp3). Routed on `upload`, the marker neither + // of the shapes above carries; the `size` raw bytes follow the frame on + // this same stream. + if raw.get("upload").is_some() { + match serde_json::from_value::(raw) { + Ok(request) => serve_upload(&inner, &mut send, recv, request).await, + Err(e) => { + let refused = upload_refusal(id, school, "malformed", e.to_string()); + if let Err(e) = write_frame(&mut send, &refused).await { + tracing::warn!("could not refuse an AI service's malformed upload: {e}"); + } + let _ = send.finish(); + } + } + return; + } // Neither shape. Reported as the api-read refusal it has always been — // `path` is the field a frame this far off most likely meant to carry. let api_err = serde_json::from_value::(raw) @@ -580,6 +617,107 @@ async fn write_blob_body( } } +/// Serve one artifact upload: validate the frame, store exactly `size` bytes +/// under the school's blob root, stamp the job's row, and answer one +/// [`BlobUploadResponse`] frame. Nothing follows the answer — the artifact +/// travels one way only. +/// +/// A refusal answers the frame and resets the read side: the service may still +/// be writing its bytes, and none of them will be stored, so letting the +/// stream drain would only spend the sender's bandwidth on a file that is +/// already refused. +async fn serve_upload( + inner: &Inner, + send: &mut quinn::SendStream, + mut recv: quinn::RecvStream, + request: BlobUploadRequest, +) { + let id = request.id.clone(); + let school = request.school.clone(); + let response = match ingest_upload(inner, &request, &mut recv).await { + Ok((key, size)) => BlobUploadResponse::Ok { + id, + school, + key, + size, + }, + Err((code, message)) => { + // The bytes that would have followed are not wanted; tell the + // sender so its write stops rather than filling a stream nobody + // reads. + let _ = recv.stop(1u32.into()); + upload_refusal( + request.id.clone(), + request.school.clone(), + &code, + message, + ) + } + }; + if let Err(e) = write_frame(send, &response).await { + tracing::warn!("could not answer an AI service's blob upload {}: {e}", request.id); + } + let _ = send.finish(); +} + +/// The body of an upload: resolve the school, check the job, stream exactly +/// `size` bytes into a temp file under the school's own blob root, rename it +/// into place, and stamp the row. `Err` is the refusal `(code, message)`. +/// +/// The order is the point: metadata and the job's existence are checked before +/// a byte is read (a refusal must not cost the sender the whole file), and the +/// bytes are complete on disk — renamed, not half-written — before the row +/// names them. A row write that finds the job gone deletes the file it just +/// stored rather than leaving an orphan. +async fn ingest_upload( + inner: &Inner, + request: &BlobUploadRequest, + body: &mut quinn::RecvStream, +) -> Result<(String, u64), (&'static str, String)> { + if !request.upload { + return Err(( + "malformed", + "`upload` must be true on a blob upload".to_string(), + )); + } + let api = inner.api.get().ok_or(( + "unavailable", + "the api is not serving yet — retry".to_string(), + ))?; + let tenant = api.school(&request.school).await?; + let (slug, db) = (tenant.slug, tenant.db); + // This stream bypasses the router, so it also bypasses the route_layer the + // module gate is — the entitlement is checked here by hand instead. The + // podcast nest is the `chatbot` module's, exactly as it is over HTTP. + if !tenant.modules.contains(Module::Chatbot) { + return Err(( + "not_permitted", + format!("the `{slug}` school has no `chatbot` module"), + )); + } + let refusal = crate::ai::podcast::refusal; + let root = api.files_dir(&slug); + let (key, size) = crate::ai::podcast::ingest(&db, &root, request, body) + .await + .map_err(|r| refusal(&r))?; + Ok((key, size)) +} + +/// One upload refusal frame. The school is echoed as the caller spelled it. +fn upload_refusal( + id: String, + school: String, + code: &str, + message: String, +) -> BlobUploadResponse { + BlobUploadResponse::Err { + id, + school, + code: code.to_string(), + message, + } +} + /// Resolve, authorize and open one blob. `Err` is the refusal that becomes a /// [`BlobResponse::Err`] code. /// @@ -909,6 +1047,123 @@ async fn write_answer( written } +/// Run one capability the backend serves, and frame its answer. +/// +/// The school is resolved the same way an api read's is — through the same +/// registry, with the same three refusals — because it decides *which +/// database* the operation runs against; a deployment-scoped capability +/// (the school directory) resolves none, and is the only one that may. +/// The work is bounded by the bridge's own request deadline: past it the +/// service gets `timed_out` and decides for itself whether to retry, which is +/// the honest answer, since the statement may well have landed. +async fn serve_capability(inner: &Inner, request: CapabilityRequest) -> CapabilityResponse { + // The backend-served families walk one composed table + // ([`crate::ai::capability`]): ZEKA's storage surface and the podcast + // job's state reports. The scope decides whether the frame's school is + // resolved below — it is, for every family today. + use crate::ai::capability::{self, Scope}; + + let Some(api) = inner.api.get() else { + return capability_refusal( + &request.id, + &request.school, + "unavailable", + "this process has no api surface to run capabilities against".to_string(), + ); + }; + let tenant = match capability::scope_of(&request.capability) { + Some(Scope::Deployment) => None, + Some(Scope::School) => match api.school(&request.school).await { + Ok(tenant) => Some(tenant), + Err((code, message)) => { + return capability_refusal(&request.id, &request.school, code, message); + } + }, + None => { + return capability_refusal( + &request.id, + &request.school, + "unknown_capability", + format!("the backend serves no `{}` operation", request.capability), + ); + } + }; + let control = api.tenants.control(); + let call = capability::serve( + &request.capability, + tenant.as_ref(), + &control, + &request.payload, + ); + match tokio::time::timeout(inner.request_timeout, call).await { + Ok(Ok(payload)) => CapabilityResponse::Ok { + id: request.id, + school: request.school, + payload, + }, + Ok(Err((code, message))) => { + capability_refusal(&request.id, &request.school, code, message) + } + Err(_) => capability_refusal( + &request.id, + &request.school, + "timed_out", + format!( + "the operation did not finish within {}s", + inner.request_timeout.as_secs() + ), + ), + } +} + +/// One refusal frame, with the school echoed as the caller spelled it. +fn capability_refusal( + id: &str, + school: &str, + code: &str, + message: String, +) -> CapabilityResponse { + CapabilityResponse::Err { + id: id.to_string(), + school: school.to_string(), + code: code.to_string(), + message, + } +} + +async fn answer_capability(send: &mut quinn::SendStream, response: CapabilityResponse) { + if let Err(e) = write_capability_answer(send, &response).await { + tracing::warn!("could not answer an AI service's capability call: {e}"); + } + let _ = send.finish(); +} + +/// Frame one capability answer, downgrading an oversize `Ok` exactly as +/// [`write_answer`] does for an api read: an answer too big to frame becomes a +/// `too_large` refusal rather than silence, since a caller that got no frame +/// at all would wait out its own deadline to learn nothing. +async fn write_capability_answer( + w: &mut W, + response: &CapabilityResponse, +) -> Result<(), FrameError> { + let written = write_frame(w, response).await; + if let (Err(FrameError::TooLarge(_)), CapabilityResponse::Ok { id, school, .. }) = + (&written, response) + { + return write_frame( + w, + &capability_refusal( + id, + school, + "too_large", + format!("the answer exceeds the {AI_MAX_FRAME_BYTES}-byte frame limit"), + ), + ) + .await; + } + written +} + /// Read the `Hello`, decide, answer, and register on success. /// /// `Err(())` means the connection was refused and already closed — the caller diff --git a/src/constant.rs b/src/constant.rs index 1ce02fd..f9ca32f 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -598,7 +598,9 @@ pub const AI_RAG_CHAT_TIMEOUT_SECS: u64 = 90; /// `hezarfen_zeka`). It is the on-demand half of ZEKA — the service also /// recomputes on its own schedule — and it is what a teacher's "hesapla" is /// routed to. The service reads the student's own data back through the -/// bridge's api reads and writes nothing but its `zeka_*` rows. +/// bridge's api reads and has the backend write its `zeka_*` rows — no AI +/// service holds a school database credential here (see the storage-surface +/// constants below). pub const AI_INSIGHT_STUDENT_CAPABILITY: &str = "insight.student"; /// Deadline on one `insight.student` round trip. Computing one student reads @@ -619,7 +621,7 @@ pub const AI_INSIGHT_CLASS_CAPABILITY: &str = "insight.class"; /// The capability an AI service declares to recompute a whole school's /// insights. A batch job: the service works through its configured student -/// list under its own time budget and writes a run ledger. Like ZEKA's own +/// list under its own time budget and has the backend write its run ledger. Like ZEKA's own /// schedule, this is optional on top of the service's own cadence — it is /// what lets the office trigger a sweep from the UI. pub const AI_INSIGHT_REFRESH_CAPABILITY: &str = "insight.refresh"; @@ -633,6 +635,81 @@ pub const AI_INSIGHT_REFRESH_CAPABILITY: &str = "insight.refresh"; /// summary. pub const AI_INSIGHT_REFRESH_TIMEOUT_SECS: u64 = 300; +// ---- zeka's storage surface (capabilities the *backend* serves) ------------ +// +// The three constants above are capabilities an AI service *declares*: the +// backend dispatches `insight.student`/`insight.refresh` to ZEKA and ZEKA +// answers. The nine below run the other way and are the reason this section +// exists: no AI service may touch a school database directly, so every read +// and write ZEKA needs against its own `zeka_*` tables is a named operation +// the backend performs on its behalf, on the same bridge, on a +// client-initiated stream (`src/ai/server.rs::serve_client_stream`). +// +// They are deliberately *not* declared here as worker capabilities: a worker +// never announces them, and `AiBridge::dispatch` never routes them. They are +// the backend's own surface, dispatched by capability name against +// `crate::ai::insight`'s table — an operation, never a query: no capability +// takes a database, a schema, a table or a SQL fragment, and the school is +// the frame's own field, resolved to that school's database before any +// statement runs. + +/// ZEKA stores one student's computed summary (and that student's attention +/// items, replaced wholesale) for one school. +pub const AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY: &str = "insight.summary.upsert"; + +/// ZEKA stores the recommendation cards a run produced. The backend mints the +/// rows' ids — an id is the writer's, and the writer is now the backend. +pub const AI_INSIGHT_RECOMMENDATION_UPSERT_CAPABILITY: &str = "insight.recommendation.upsert"; + +/// ZEKA stores its question-segment labels (and each question's dimension +/// split, replaced wholesale). +pub const AI_INSIGHT_SEGMENT_UPSERT_CAPABILITY: &str = "insight.segment.upsert"; + +/// ZEKA stores a student's per-dimension segment profile. +pub const AI_INSIGHT_PROFILE_UPSERT_CAPABILITY: &str = "insight.profile.upsert"; + +/// ZEKA stores one compute run's ledger row (and the run's pending students +/// and failed modules, both replaced wholesale). +pub const AI_INSIGHT_RUN_UPSERT_CAPABILITY: &str = "insight.run.upsert"; + +/// ZEKA reads back the students the freshest run left pending — where the +/// next run starts. +pub const AI_INSIGHT_PENDING_LIST_CAPABILITY: &str = "insight.pending.list"; + +/// ZEKA asks the backend to sweep every `zeka_*` table of rows whose +/// retention window has closed. +pub const AI_INSIGHT_RETENTION_SWEEP_CAPABILITY: &str = "insight.retention.sweep"; + +/// ZEKA asks the backend to delete the derived rows of students who are no +/// longer enrolled. +pub const AI_INSIGHT_DEPARTED_PURGE_CAPABILITY: &str = "insight.departed.purge"; + +/// The one deployment-scoped operation: the active schools a shared AI fleet +/// schedules over. The frame carries no school because its answer is the +/// directory itself — the same reason [`crate::ai::protocol::Hello`] carries +/// none. +pub const AI_INSIGHT_SCHOOLS_LIST_CAPABILITY: &str = "insight.schools.list"; + +/// The most rows one of the four bulk writes may carry in a single call. The +/// service's own batch size (`store.BATCH_SIZE` in `hezarfen_zeka`) — it +/// chunks its nightly output at exactly this, and a call one row past it is +/// refused (`too_many_rows`) rather than truncated, because a silently +/// shortened batch would read as a written student. +pub const MAX_INSIGHT_BATCH_ROWS: usize = 500; + +/// The most students `insight.pending.list` will answer with. The list is +/// handed over whole — the service resumes its next run from it, so a +/// clipped list would silently drop students — and a school past this bound +/// is refused (`too_many_rows`) instead. +pub const MAX_INSIGHT_PENDING_STUDENTS: usize = 20_000; + +/// The most students one `insight.departed.purge` call may name. Same shape +/// as [`MAX_INSIGHT_PENDING_STUDENTS`]: over it the call is refused, and the +/// empty list is refused too — an empty roster is a fetch that failed, and +/// deleting every derived row on that reading would be the worst available +/// mistake. +pub const MAX_INSIGHT_PURGE_STUDENTS: usize = 20_000; + /// How long a `rag.chat` turn may sit `pending` before a reader projects it as /// failed. The RAG nest mirrors the chatbot's asynchronous send /// ([`CHATBOT_PENDING_STALE_SECS`]): the round trip outlives the request that @@ -643,25 +720,30 @@ pub const RAG_PENDING_STALE_SECS: i64 = CHATBOT_PENDING_STALE_SECS; // ---- podcast --------------------------------------------------------------- // // The podcast service turns one stored source into an audio episode, which is -// a *job*: submitted, polled, collected, and maybe cancelled — the service -// owns the record, and the backend relays each HTTP call to the worker that -// declares the matching capability. All four capabilities answer immediately -// (the pipeline runs in the service's own pool), so unlike `rag.index` and -// `rag.chat` none of them needs a per-capability deadline: the bridge's -// ordinary request timeout already covers a job-store read. +// a *job*. The backend owns the job's record: `POST /podcast/jobs` mints the +// id, writes the `podcast_job` row, and dispatches `podcast.submit`; the +// service reports every transition back through the client-initiated +// `podcast.report` capability and uploads the finished mp3 as raw bytes. The +// read doors (`GET /podcast/jobs/{id}`, `.../result`, `.../audio`) answer from +// the row, so a service restart or a wiped service volume costs liveness at +// most. Only submit and cancel are dispatched to a worker, and both answer +// immediately — the pipeline runs in the service's own pool — so neither needs +// a per-capability deadline: the bridge's ordinary request timeout covers a +// job-store write. /// The capability an AI service declares to accept a podcast job. The backend -/// dispatches on it from `POST /podcast/jobs`, and the service mints the job -/// id every other `podcast.*` call then names. +/// dispatches on it from `POST /podcast/jobs`, and the payload carries the +/// **backend-minted** job id — the id the row, the service's own record, and +/// the audio blob are all keyed by. pub const AI_PODCAST_SUBMIT_CAPABILITY: &str = "podcast.submit"; -/// The capability an AI service declares to report one podcast job's state, -/// read back by `GET /podcast/jobs/{id}`. -pub const AI_PODCAST_STATUS_CAPABILITY: &str = "podcast.status"; - -/// The capability an AI service declares to hand back a finished job's -/// artifacts — above all the `audio_id` the `/podcast/audio` door streams. -pub const AI_PODCAST_RESULT_CAPABILITY: &str = "podcast.result"; +/// The capability the **backend** serves for one podcast job's state reports. +/// The service calls it — on a client-initiated stream, the same shape as +/// ZEKA's storage surface — once per transition, echoing the job's identity +/// (`job_id`, `source_id`, `user_id`) and the state it moved to. The backend +/// validates the echo, the transition and the retention window, and writes its +/// own row; there is no state the service holds that the backend does not. +pub const AI_PODCAST_REPORT_CAPABILITY: &str = "podcast.report"; /// The capability an AI service declares to cancel one podcast job. Its own /// capability rather than a flag on submit: the cancel is a write on the @@ -669,6 +751,39 @@ pub const AI_PODCAST_RESULT_CAPABILITY: &str = "podcast.result"; /// can offer the door at all. pub const AI_PODCAST_CANCEL_CAPABILITY: &str = "podcast.cancel"; +/// The largest episode the backend will ingest from a service +/// (`BlobUploadRequest`). A ceiling, not a quota: a two-hour episode at a +/// generous bitrate is well under it, and anything above is refused before a +/// byte reaches disk — a service bug must not be able to fill the host. +pub const PODCAST_AUDIO_MAX_BYTES: usize = 256 * 1024 * 1024; + +/// How long a finished podcast job's record and audio stay readable. Past it +/// the doors answer `410` — the record is history, and the blob is no longer +/// served. Sized like the RAG outputs' retention window: long enough for a +/// listener to come back for yesterday's episode, short enough that a shared +/// host does not accumulate every episode ever made. +pub const PODCAST_JOB_RETENTION_SECS: i64 = 7 * 24 * 60 * 60; + +/// The floor of the read-side staleness window: a `queued`/`running` job +/// nobody has updated for at least this long is presented as +/// `failed`/`interrupted`. The window is +/// `max(PODCAST_JOB_STALE_FLOOR_SECS, eta_secs × PODCAST_JOB_STALE_ETA_FACTOR)` +/// so a queue wait the service itself estimated as long is never declared +/// dead mid-flight. +pub const PODCAST_JOB_STALE_FLOOR_SECS: i64 = 600; + +/// How many times a job's own ETA the service may exceed before the read side +/// stops believing it is still running. Three: past three times its own +/// estimate, the honest reading is that the process that owned it is gone. +pub const PODCAST_JOB_STALE_ETA_FACTOR: i64 = 3; + +/// The `error_code` a job carries when *this backend* concluded it died: a +/// dispatch that never reached a worker, a cancel of a job the service no +/// longer has, or a read-side projection of a stale row. Deliberately the +/// service's own word for the same fact (its restart sweep writes it too), so +/// a client sees one vocabulary however the job died. +pub const PODCAST_INTERRUPTED_CODE: &str = "interrupted"; + /// The most `(sınıf, ders)` scope pairs one `rag.chat` request may carry. The /// corpus is routed by the **pair** — a grade and a subject list sent /// separately would cross-product into combinations the asker never named — so diff --git a/src/db/insight.rs b/src/db/insight.rs new file mode 100644 index 0000000..6d3feed --- /dev/null +++ b/src/db/insight.rs @@ -0,0 +1,986 @@ +//! ZEKA's own tables, and the operations that write and read them. +//! +//! ZEKA (`hezarfen_zeka`) computes student and class insights, but it does +//! **not** touch a school database: every statement against the `zeka_*` +//! tables runs here, on the backend, under the school the caller named. That +//! is a standing rule of this deployment, not a preference — an AI service +//! process holding a database credential of its own would be a second, silent +//! door into every school's rows, one no request-scoped check can close. So +//! the service's storage surface is nine named operations ([`crate::ai::insight`] +//! carries the wire contract and the dispatch), and this module is what they +//! execute. +//! +//! The row types here are therefore **both** the SQL's input and the bridge's +//! payload: a nightly batch arrives as JSON, is parsed into these structs +//! (`invalid_payload` on anything that does not fit), and is written verbatim — +//! the backend is a trust boundary for the *shape*, never an author of the +//! content. Fields are spelled exactly as the tables' columns are, because a +//! consumer that has to guess a mapping between two spellings will eventually +//! guess wrong. +//! +//! Three invariants are worth stating up front, since they are what the SQL +//! below is arranged around: +//! +//! * **A batch is one transaction.** Every bulk write is all-or-nothing: a +//! refusal means nothing landed, so a service that retries a batch cannot +//! half-apply it. Row-at-a-time statements inside one transaction keep that +//! honesty without a multi-row statement whose bind count would be a second +//! bound to police; the batch ceiling [`MAX_INSIGHT_BATCH_ROWS`] keeps the +//! statement count bounded. +//! * **Child rows are replaced, never merged.** `attention`, the segment +//! `dimension` rows, and a run's `pending`/`failed_module` rows are deleted +//! for their owners and re-inserted from the payload. Merging would leave a +//! fact the service stopped producing on the screen forever. +//! * **The school is the database.** Every function here takes the school's +//! own pool and nothing else: there is no `school` column to filter on +//! because there is no row from another school in reach. Foreign keys carry +//! the rest — an id from another school's database is not a row this +//! database will accept, and that refusal is mapped to a validation error +//! rather than a `500` so the caller learns which id was wrong. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; +use serde_json::Value as JsonValue; +use sqlx::AssertSqlSafe; +use utoipa::ToSchema; +use uuid::Uuid; + +use crate::constant::{ + MAX_INSIGHT_BATCH_ROWS, MAX_INSIGHT_PENDING_STUDENTS, MAX_INSIGHT_PURGE_STUDENTS, +}; +use crate::database::{Database, foreign_key_violation, tx_with_retry}; +use crate::domain::monotonic_id::next_uuid; +use crate::error::{AppError, ValidationError}; + +// ---- the wire rows --------------------------------------------------------- + +/// One student's computed summary, and the attention items that travel with +/// it. The two tables are replaced together — see the module docs. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct SummaryRow { + /// `app_user.id` of the student this summary is about. + pub student: String, + /// The four evidence blocks, stored verbatim as JSONB. `null` is a legal + /// value: it means the section had no source rows, which is not the same + /// fact as a section that was not computed. + #[serde(default)] + pub marks: Option, + #[serde(default)] + pub attendance: Option, + #[serde(default)] + pub submission: Option, + #[serde(default)] + pub study: Option, + /// `none` | `exploratory` | `stable` — the service's own confidence in + /// the summary; the table's CHECK is the authority on the vocabulary. + pub confidence: String, + /// When the service computed this row, unix milliseconds. + pub computed_at: i64, + /// Unix milliseconds after which the sweep deletes the row. The service + /// owns its retention policy; the backend writes what it is told. + pub retain_until: i64, + /// The student's attention items, in the service's own order. Omitted + /// means "this student has none", which clears the previous ones. + #[serde(default)] + pub attention: Vec, +} + +/// One attention item: a fact about a student that a teacher should see. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct AttentionRow { + /// The rule's trigger name, e.g. `not_egilimi_dusuyor`. + pub trigger: String, + /// The course the trigger fired in, when it fired in one. + #[serde(default)] + pub course: Option, + /// The one-line fact a reader sees. + pub fact: String, + /// The window the fact was measured over, unix milliseconds. + pub window_from: i64, + pub window_to: i64, + /// The evidence object: the numbers behind the fact. Required — an item + /// whose evidence is missing is dropped by the service before it is sent, + /// and one that arrives without it is a payload error, not a silent write. + pub evidence: JsonValue, +} + +/// One recommendation card. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct RecommendationRow { + /// The user the card is addressed to (`audience_role` says as what). + pub audience: String, + /// The product surface it belongs to, e.g. `student_home`. + pub product: String, + /// The rule that produced it, and the rule set's version. + pub rule_id: String, + pub rule_version: i64, + /// The rule's own scope marker (a segment label, a course) — part of the + /// natural key, so two scopes of one rule are two cards. + #[serde(default)] + pub scope: Option, + /// The student the card is *about*, when it is about one. + #[serde(default)] + pub about: Option, + /// `student` | `teacher` | `parent` | `manager`. + pub audience_role: String, + #[serde(default)] + pub course: Option, + /// The evidence object. A row whose evidence carries nothing but + /// `limitation` is **not written** and is counted `rejected` in the + /// receipt — the service's own rule, kept where it can be audited. + pub evidence: JsonValue, + /// The stated limitation of the measurement, merged into the stored + /// evidence object under `limitation`. + #[serde(default)] + pub limitation: Option, + /// `none` | `exploratory` | `stable`. + pub confidence: String, + pub computed_at: i64, + pub expires_at: i64, + pub retain_until: i64, +} + +/// The four rubric labels of one question, in the service's nested shape. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct SegmentLabels { + pub bilissel_talep: String, + pub dikkat_tuzagi: String, + pub okuma_yuku: String, + pub adim_sayisi: String, +} + +/// The model's confidence in each of the four labels, `0..=1`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct SegmentConfidences { + pub bilissel_talep: f64, + pub dikkat_tuzagi: f64, + pub okuma_yuku: f64, + pub adim_sayisi: f64, +} + +/// One question's segment labels, and the dimension split that travels with +/// them (replaced together). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct SegmentRow { + /// The exam question this row labels. + pub question: String, + pub exam: String, + pub course: String, + pub subject: String, + pub labels: SegmentLabels, + pub confidences: SegmentConfidences, + /// The row's overall confidence, `none` | `exploratory` | `stable`. + pub confidence: String, + /// The distractors the question's wrong answers point at, when known. + #[serde(default)] + pub trap_choice: Option, + /// Why the labels are what they are — the reader's audit trail. + pub rationale: String, + /// The model (and prompt) that produced the labels. + pub model: String, + pub prompt_version: String, + /// The prompt variant, when the service is A/B-ing one. + #[serde(default)] + pub variant: Option, + pub computed_at: i64, + pub retain_until: i64, + /// Dimensions the downstream rules may use. + #[serde(default)] + pub downstream_dimensions: Vec, + /// Dimensions still being measured. + #[serde(default)] + pub experimental_dimensions: Vec, +} + +/// One student's accuracy inside one rubric segment, against the same +/// student's overall rate. `contrast` is the only field rules may fire on. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct ProfileRow { + pub student: String, + /// `bilissel_talep` | `dikkat_tuzagi` | `okuma_yuku` (production only). + pub dimension: String, + pub label: String, + pub n_answers: i64, + pub n_correct: i64, + pub accuracy: f64, + pub overall_n_answers: i64, + pub overall_accuracy: f64, + pub contrast: f64, + /// `none` | `exploratory` | `stable`. + pub confidence: String, + pub computed_at: i64, + pub retain_until: i64, +} + +/// One compute run's ledger row, with the run's own children. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct RunRow { + /// `YYYY-MM-DD` (TR day). The primary key: a re-run of the same night + /// overwrites rather than duplicating. + pub run_day: String, + pub started_at: i64, + #[serde(default)] + pub finished_at: Option, + /// `running` | `ok` | `partial` | `failed` | `skipped`. + pub status: String, + #[serde(default)] + pub duration_ms: Option, + pub students_total: i64, + pub students_ok: i64, + pub students_failed: i64, + pub students_skipped: i64, + pub rows_written: i64, + pub budget_exceeded: bool, + pub budget_ms: i64, + pub retain_until: i64, + /// Students the budget ran out on — the next run's starting point. + #[serde(default)] + pub pending_students: Vec, + /// Modules that failed in this run. + #[serde(default)] + pub failed_modules: Vec, +} + +// ---- the request/receipt envelopes ---------------------------------------- + +/// `insight.summary.upsert` / `POST /insights/summaries`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct SummaryWriteRequest { + pub rows: Vec, +} + +/// `insight.recommendation.upsert` / `POST /insights/recommendations`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct RecommendationWriteRequest { + pub rows: Vec, +} + +/// `insight.segment.upsert` / `POST /insights/segments`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct SegmentWriteRequest { + pub rows: Vec, +} + +/// `insight.profile.upsert` / `POST /insights/profiles`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct ProfileWriteRequest { + pub rows: Vec, +} + +/// `insight.run.upsert` / `POST /insights/runs`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct RunWriteRequest { + pub run: RunRow, +} + +/// `insight.departed.purge` / `POST /insights/purge`. The **active** roster: +/// every student not named loses their derived rows. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct PurgeRequest { + pub students: Vec, +} + +/// What a bulk write did: rows written, and (for recommendations only) rows +/// the service's own evidence rule kept out. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct WriteReceipt { + pub written: u64, + #[serde(default, skip_serializing_if = "is_zero")] + pub rejected: u64, +} + +fn is_zero(value: &u64) -> bool { + *value == 0 +} + +/// The freshest run's pending students, in the service's order. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct PendingList { + pub students: Vec, +} + +/// The per-table verdict of a sweep or a purge, keyed by table name — the +/// shape the service's CLI prints and exits non-zero on. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct TableVerdicts { + pub tables: BTreeMap, +} + +/// The deployment's active schools, by slug. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] +pub struct SchoolDirectory { + pub schools: Vec, +} + +// ---- shared validation ----------------------------------------------------- + +/// Refuse a batch past [`MAX_INSIGHT_BATCH_ROWS`] rather than taking it +/// piecemeal: a batch is the unit the service retries, so accepting part of +/// one would turn its retry into a duplicate. +fn check_batch(field: &'static str, rows: &[impl Sized]) -> Result<(), AppError> { + if rows.len() > MAX_INSIGHT_BATCH_ROWS { + return Err(AppError::PayloadTooLarge(format!( + "{field}: {} rows is over the ceiling of {MAX_INSIGHT_BATCH_ROWS} rows per call", + rows.len() + ))); + } + Ok(()) +} + +/// A foreign-key violation is a payload error here, not a server fault: the +/// statement named a row this school's database does not have (most often an +/// id belonging to another school), and the caller can fix it. +fn as_validation(err: AppError) -> AppError { + match &err { + AppError::Db(source) if foreign_key_violation(source) => { + AppError::Validation(ValidationError::Invalid { + field: "rows", + reason: "a referenced row does not exist in this school", + }) + } + _ => err, + } +} + +/// One hyphenated uuid from the wire. Ids cross the bridge as strings — the +/// `uuid` crate's serde support is not enabled here, and a string that is not +/// a uuid should read as a field error, not as a decode failure with no field. +fn parse_uuid(field: &'static str, value: &str) -> Result { + Uuid::parse_str(value).map_err(|_| { + AppError::Validation(ValidationError::Invalid { + field, + reason: "must be a hyphenated uuid", + }) + }) +} + +/// `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 { + let bytes = day.as_bytes(); + bytes.len() == 10 + && bytes + .iter() + .enumerate() + .all(|(i, b)| if matches!(i, 4 | 7) { *b == b'-' } else { b.is_ascii_digit() }) +} + +// ---- writes ---------------------------------------------------------------- + +/// Store a batch of student summaries, replacing each student's attention +/// items. One transaction: a batch lands whole or not at all. +pub async fn write_summaries(db: &Database, rows: Vec) -> Result { + check_batch("rows", &rows)?; + let written = rows.len() as u64; + tx_with_retry(db, false, async move |tx| write_summaries_in(tx, &rows).await) + .await + .map_err(as_validation)?; + Ok(WriteReceipt { + written, + rejected: 0, + }) +} + +/// The transaction body of [`write_summaries`], a named fn rather than an async +/// closure: an `AsyncFnMut` closure whose future does the work trips rustc's +/// "implementation of `Send` is not general enough" (see `tx_with_retry`). +async fn write_summaries_in(tx: &mut sqlx::PgConnection, rows: &[SummaryRow]) -> Result<(), AppError> { + + for row in rows { + let student = parse_uuid("student", &row.student)?; + sqlx::query!( + "INSERT INTO zeka_student_summary + (student, marks, attendance, submission, study, confidence, + computed_at, retain_until) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT (student) DO UPDATE SET + marks = EXCLUDED.marks, attendance = EXCLUDED.attendance, + submission = EXCLUDED.submission, study = EXCLUDED.study, + confidence = EXCLUDED.confidence, computed_at = EXCLUDED.computed_at, + retain_until = EXCLUDED.retain_until", + student, + row.marks.clone(), + row.attendance.clone(), + row.submission.clone(), + row.study.clone(), + row.confidence, + row.computed_at, + row.retain_until, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "DELETE FROM zeka_attention_item WHERE student = $1", + student, + ) + .execute(&mut *tx) + .await?; + for (ord, item) in row.attention.iter().enumerate() { + let course = item + .course + .as_deref() + .map(|id| parse_uuid("course", id)) + .transpose()?; + sqlx::query!( + "INSERT INTO zeka_attention_item + (student, trigger, course, fact, window_from, window_to, evidence, ord) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", + student, + item.trigger, + course, + item.fact, + item.window_from, + item.window_to, + item.evidence.clone(), + ord as i16, + ) + .execute(&mut *tx) + .await?; + } + } + Ok(()) +} + +/// The service's own evidence rule, applied where the write happens: a card +/// whose evidence carries nothing but its limitation is not a finding. Such a +/// row is counted `rejected` in the receipt and left unwritten — silently +/// dropping it would be the one thing this rule exists to prevent. +fn carries_evidence(evidence: &JsonValue) -> bool { + evidence.as_object().is_some_and(|object| { + object + .iter() + .any(|(key, value)| key != "limitation" && !value.is_null()) + }) +} + +/// Store a batch of recommendation cards. The backend mints each row's id: +/// an id belongs to whoever writes the row, and that is now this process. +pub async fn write_recommendations( + db: &Database, + rows: Vec, +) -> Result { + check_batch("rows", &rows)?; + let (written, rejected) = + tx_with_retry(db, false, async move |tx| write_recommendations_in(tx, &rows).await) + .await + .map_err(as_validation)?; + Ok(WriteReceipt { written, rejected }) +} + +/// The service's own evidence rule, applied where the write happens: a card +/// whose evidence carries nothing but its limitation is not a finding. Such a +/// row is counted `rejected` and left unwritten — silently dropping it would +/// be the one thing this rule exists to prevent. Returns `(written, rejected)`. +async fn write_recommendations_in( + tx: &mut sqlx::PgConnection, + rows: &[RecommendationRow], +) -> Result<(u64, u64), AppError> { + let mut written = 0u64; + let mut rejected = 0u64; + for row in rows { + if !carries_evidence(&row.evidence) { + rejected += 1; + continue; + } + let evidence = merge_limitation(&row.evidence, row.limitation.as_deref())?; + let audience = parse_uuid("audience", &row.audience)?; + let about = row + .about + .as_deref() + .map(|id| parse_uuid("about", id)) + .transpose()?; + let course = row + .course + .as_deref() + .map(|id| parse_uuid("course", id)) + .transpose()?; + 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) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) + ON CONFLICT (audience, product, rule_id, about, scope) DO UPDATE SET + rule_version = EXCLUDED.rule_version, + audience_role = EXCLUDED.audience_role, + course = EXCLUDED.course, + evidence = EXCLUDED.evidence, + confidence = EXCLUDED.confidence, + created_at = EXCLUDED.created_at, + expires_at = EXCLUDED.expires_at, + retain_until = EXCLUDED.retain_until", + next_uuid(), + audience, + row.product, + row.rule_id, + row.rule_version, + row.scope, + about, + row.audience_role, + course, + evidence, + row.confidence, + row.computed_at, + row.expires_at, + row.retain_until, + ) + .execute(&mut *tx) + .await?; + written += 1; + } + Ok((written, rejected)) +} + +/// The stored evidence object: the payload's own object with `limitation` +/// written into it, exactly as the service kept it. A payload whose `evidence` +/// is not an object cannot be merged and is refused. +fn merge_limitation( + evidence: &JsonValue, + limitation: Option<&str>, +) -> Result { + let mut object = evidence + .as_object() + .cloned() + .ok_or(AppError::Validation(ValidationError::Invalid { + field: "evidence", + reason: "must be a JSON object", + }))?; + if let Some(limitation) = limitation { + object.insert( + "limitation".to_string(), + JsonValue::String(limitation.to_string()), + ); + } + Ok(JsonValue::Object(object)) +} + +/// Store a batch of question segments, replacing each question's dimension +/// split. +pub async fn write_segments(db: &Database, rows: Vec) -> Result { + check_batch("rows", &rows)?; + let written = rows.len() as u64; + tx_with_retry(db, false, async move |tx| write_segments_in(tx, &rows).await) + .await + .map_err(as_validation)?; + Ok(WriteReceipt { + written, + rejected: 0, + }) +} + +/// The transaction body of [`write_segments`], a named fn rather than an async +/// closure: an `AsyncFnMut` closure whose future does the work trips rustc's +/// "implementation of `Send` is not general enough" (see `tx_with_retry`). +async fn write_segments_in(tx: &mut sqlx::PgConnection, rows: &[SegmentRow]) -> Result<(), AppError> { + + for row in rows { + let question = parse_uuid("question", &row.question)?; + let exam = parse_uuid("exam", &row.exam)?; + let course = parse_uuid("course", &row.course)?; + let subject = parse_uuid("subject", &row.subject)?; + sqlx::query!( + "INSERT INTO zeka_question_segment + (question, exam, course, subject, bilissel_talep, dikkat_tuzagi, okuma_yuku, + adim_sayisi, confidence_bilissel_talep, confidence_dikkat_tuzagi, + confidence_okuma_yuku, confidence_adim_sayisi, confidence, trap_choice, + rationale, model, prompt_version, variant, computed_at, retain_until) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, + $11, $12, $13, $14, $15, $16, $17, $18, $19, $20) + ON CONFLICT (question) DO UPDATE SET + exam = EXCLUDED.exam, course = EXCLUDED.course, subject = EXCLUDED.subject, + bilissel_talep = EXCLUDED.bilissel_talep, + dikkat_tuzagi = EXCLUDED.dikkat_tuzagi, + okuma_yuku = EXCLUDED.okuma_yuku, + adim_sayisi = EXCLUDED.adim_sayisi, + confidence_bilissel_talep = EXCLUDED.confidence_bilissel_talep, + confidence_dikkat_tuzagi = EXCLUDED.confidence_dikkat_tuzagi, + confidence_okuma_yuku = EXCLUDED.confidence_okuma_yuku, + confidence_adim_sayisi = EXCLUDED.confidence_adim_sayisi, + confidence = EXCLUDED.confidence, trap_choice = EXCLUDED.trap_choice, + rationale = EXCLUDED.rationale, model = EXCLUDED.model, + prompt_version = EXCLUDED.prompt_version, variant = EXCLUDED.variant, + computed_at = EXCLUDED.computed_at, retain_until = EXCLUDED.retain_until", + question, + exam, + course, + subject, + row.labels.bilissel_talep, + row.labels.dikkat_tuzagi, + row.labels.okuma_yuku, + row.labels.adim_sayisi, + row.confidences.bilissel_talep, + row.confidences.dikkat_tuzagi, + row.confidences.okuma_yuku, + row.confidences.adim_sayisi, + row.confidence, + row.trap_choice, + row.rationale, + row.model, + row.prompt_version, + row.variant, + row.computed_at, + row.retain_until, + ) + .execute(&mut *tx) + .await?; + // A dimension that moved between downstream and experimental (or + // a rubric version that dropped one) must not leave its old row + // behind. + sqlx::query!( + "DELETE FROM zeka_question_segment_dimension WHERE question = $1", + question, + ) + .execute(&mut *tx) + .await?; + let mut ord: i16 = 0; + for (role, names) in [ + ("downstream", &row.downstream_dimensions), + ("experimental", &row.experimental_dimensions), + ] { + for name in names { + sqlx::query!( + "INSERT INTO zeka_question_segment_dimension + (question, dimension, role, ord) + VALUES ($1, $2, $3, $4)", + question, + name, + role, + ord, + ) + .execute(&mut *tx) + .await?; + ord += 1; + } + } + } + Ok(()) +} + +/// Store a batch of student segment profiles. +pub async fn write_profiles(db: &Database, rows: Vec) -> Result { + check_batch("rows", &rows)?; + let written = rows.len() as u64; + tx_with_retry(db, false, async move |tx| write_profiles_in(tx, &rows).await) + .await + .map_err(as_validation)?; + Ok(WriteReceipt { + written, + rejected: 0, + }) +} + +/// The transaction body of [`write_profiles`], a named fn rather than an async +/// closure: an `AsyncFnMut` closure whose future does the work trips rustc's +/// "implementation of `Send` is not general enough" (see `tx_with_retry`). +async fn write_profiles_in(tx: &mut sqlx::PgConnection, rows: &[ProfileRow]) -> Result<(), AppError> { + + for row in rows { + let student = parse_uuid("student", &row.student)?; + 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, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) + ON CONFLICT (student, dimension, label) DO UPDATE SET + n_answers = EXCLUDED.n_answers, n_correct = EXCLUDED.n_correct, + accuracy = EXCLUDED.accuracy, + overall_n_answers = EXCLUDED.overall_n_answers, + overall_accuracy = EXCLUDED.overall_accuracy, + contrast = EXCLUDED.contrast, confidence = EXCLUDED.confidence, + computed_at = EXCLUDED.computed_at, retain_until = EXCLUDED.retain_until", + student, + row.dimension, + row.label, + row.n_answers, + row.n_correct, + row.accuracy, + row.overall_n_answers, + row.overall_accuracy, + row.contrast, + row.confidence, + row.computed_at, + row.retain_until, + ) + .execute(&mut *tx) + .await?; + } + Ok(()) +} + +/// Store one run's ledger row, replacing the run's pending/failed children. +pub async fn write_run(db: &Database, run: RunRow) -> Result { + if !run_day_ok(&run.run_day) { + return Err(AppError::Validation(ValidationError::Invalid { + field: "run_day", + reason: "must be YYYY-MM-DD", + })); + } + let pending: Vec = run + .pending_students + .iter() + .map(|id| parse_uuid("pending_students", id)) + .collect::>()?; + tx_with_retry(db, false, async move |tx| write_run_in(tx, &run, &pending).await) + .await + .map_err(as_validation)?; + Ok(WriteReceipt { + written: 1, + rejected: 0, + }) +} + +/// The transaction body of [`write_run`], a named fn rather than an async +/// closure: an `AsyncFnMut` closure whose future does the work trips rustc's +/// "implementation of `Send` is not general enough" (see `tx_with_retry`). +async fn write_run_in(tx: &mut sqlx::PgConnection, run: &RunRow, pending: &[Uuid]) -> Result<(), AppError> { + + 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, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) + ON CONFLICT (run_day) DO UPDATE SET + started_at = EXCLUDED.started_at, finished_at = EXCLUDED.finished_at, + status = EXCLUDED.status, duration_ms = EXCLUDED.duration_ms, + students_total = EXCLUDED.students_total, students_ok = EXCLUDED.students_ok, + students_failed = EXCLUDED.students_failed, + students_skipped = EXCLUDED.students_skipped, + rows_written = EXCLUDED.rows_written, + budget_exceeded = EXCLUDED.budget_exceeded, budget_ms = EXCLUDED.budget_ms, + retain_until = EXCLUDED.retain_until", + run.run_day, + run.started_at, + run.finished_at, + run.status, + run.duration_ms, + run.students_total, + run.students_ok, + run.students_failed, + run.students_skipped, + run.rows_written, + run.budget_exceeded, + run.budget_ms, + run.retain_until, + ) + .execute(&mut *tx) + .await?; + sqlx::query!("DELETE FROM zeka_run_pending WHERE run = $1", run.run_day) + .execute(&mut *tx) + .await?; + sqlx::query!( + "DELETE FROM zeka_run_failed_module WHERE run = $1", + run.run_day + ) + .execute(&mut *tx) + .await?; + for (ord, student) in pending.iter().enumerate() { + sqlx::query!( + "INSERT INTO zeka_run_pending (run, student, ord) VALUES ($1, $2, $3)", + run.run_day, + student, + ord as i32, + ) + .execute(&mut *tx) + .await?; + } + for (ord, module) in run.failed_modules.iter().enumerate() { + sqlx::query!( + "INSERT INTO zeka_run_failed_module (run, module, ord) VALUES ($1, $2, $3)", + run.run_day, + module, + ord as i16, + ) + .execute(&mut *tx) + .await?; + } + Ok(()) +} + +// ---- reads ----------------------------------------------------------------- + +/// The freshest run's pending students, in the order the run recorded them. +/// +/// Refused rather than clipped past [`MAX_INSIGHT_PENDING_STUDENTS`]: the +/// service resumes its next run from this list, so a shortened one would drop +/// students silently. The read asks for one row past the ceiling so the +/// refusal never has to materialize the whole list. +pub async fn last_pending(db: &Database) -> Result { + let ceiling = MAX_INSIGHT_PENDING_STUDENTS as i64; + let rows = sqlx::query_scalar!( + "SELECT p.student FROM zeka_run_pending p + JOIN zeka_run r ON r.run_day = p.run + WHERE r.run_day = (SELECT run_day FROM zeka_run + ORDER BY started_at DESC, run_day DESC LIMIT 1) + ORDER BY p.ord + LIMIT $1", + ceiling + 1, + ) + .fetch_all(db) + .await?; + if rows.len() > MAX_INSIGHT_PENDING_STUDENTS { + return Err(AppError::PayloadTooLarge(format!( + "students: the freshest run left more than {MAX_INSIGHT_PENDING_STUDENTS} students pending" + ))); + } + Ok(PendingList { + students: rows.iter().map(|id| id.to_string()).collect(), + }) +} + +/// The deployment's active schools, by slug — the one read that is not +/// scoped to a school, because it is how a shared AI fleet learns which +/// schools exist. +pub async fn active_schools(control: &Database) -> Result { + let schools = sqlx::query_scalar!( + "SELECT slug FROM school WHERE status = 'active' ORDER BY slug" + ) + .fetch_all(control) + .await?; + Ok(SchoolDirectory { schools }) +} + +// ---- retention ------------------------------------------------------------- + +/// The nine tables a sweep walks, children before their parents: the foreign +/// keys are `ON DELETE NO ACTION`, so a parent cannot go while a child row +/// still names it. +const SWEEP_CHILDREN: &[(&str, &str, &str)] = &[ + ("zeka_attention_item", "zeka_student_summary", "student"), + ("zeka_question_segment_dimension", "zeka_question_segment", "question"), + ("zeka_run_pending", "zeka_run", "run"), + ("zeka_run_failed_module", "zeka_run", "run"), +]; + +/// The tables that carry their own `retain_until`. +const SWEEP_PARENTS: &[&str] = &[ + "zeka_student_summary", + "zeka_recommendation", + "zeka_run", + "zeka_question_segment", + "zeka_student_segment_profile", +]; + +/// Delete every row whose retention window has closed. `now_ms` is the +/// backend's own clock — one clock decides expiry, never the caller's. +/// +/// One table at a time, each in its own statement, and a table whose delete +/// fails is reported `false` rather than aborting the rest: a sweep is +/// housekeeping, and losing the whole night's cleanup because one table is +/// locked would leave every other table's expired rows in place. The caller +/// reads the verdict per table, exactly as the service's own sweep did. +pub async fn sweep(db: &Database, now_ms: i64) -> Result { + let mut tables = BTreeMap::new(); + for (child, parent, key) in SWEEP_CHILDREN { + let parent_key = if *parent == "zeka_run" { "run_day" } else { *key }; + let sql = format!( + "DELETE FROM {child} WHERE {key} IN \ + (SELECT {parent_key} FROM {parent} WHERE retain_until < $1)" + ); + tables.insert( + (*child).to_string(), + run_sweep_statement(db, &sql, now_ms).await, + ); + } + for table in SWEEP_PARENTS { + let sql = format!("DELETE FROM {table} WHERE retain_until < $1"); + tables.insert((*table).to_string(), run_sweep_statement(db, &sql, now_ms).await); + } + Ok(TableVerdicts { tables }) +} + +/// The table names come from [`SWEEP_CHILDREN`]/[`SWEEP_PARENTS`], never from +/// a caller — the only dynamic SQL in this module, and the reason +/// [`AssertSqlSafe`] is licensed here. +async fn run_sweep_statement(db: &Database, sql: &str, now_ms: i64) -> bool { + sqlx::query(AssertSqlSafe(sql.to_string())) + .bind(now_ms) + .execute(db) + .await + .is_ok() +} + +/// Delete the derived rows of everyone who is no longer on the roster. One +/// transaction: a purge is a decision about a cohort, not a per-row repair. +/// +/// The empty list is **refused**, never obeyed: an empty roster is almost +/// always a fetch that failed, and reading it as "nobody is enrolled any +/// more" would delete every student's derived data in one call. +pub async fn purge_departed( + db: &Database, + students: Vec, +) -> Result { + if students.is_empty() { + return Err(AppError::Validation(ValidationError::Empty("students"))); + } + if students.len() > MAX_INSIGHT_PURGE_STUDENTS { + return Err(AppError::PayloadTooLarge(format!( + "students: {} ids is over the ceiling of {MAX_INSIGHT_PURGE_STUDENTS} per call", + students.len() + ))); + } + let active: Vec = students + .iter() + .map(|id| parse_uuid("students", id)) + .collect::>()?; + tx_with_retry(db, false, async move |tx| purge_departed_in(tx, &active).await) + .await + .map_err(as_validation)?; + + // One transaction, so the verdicts move together: every table succeeded + // or the call was refused above. + let tables = [ + "zeka_attention_item", + "zeka_student_summary", + "zeka_student_segment_profile", + "zeka_recommendation", + "zeka_run_pending", + ] + .into_iter() + .map(|table| (table.to_string(), true)) + .collect(); + Ok(TableVerdicts { tables }) +} + +/// The transaction body of [`purge_departed`], a named fn rather than an async +/// closure: an `AsyncFnMut` closure whose future does the work trips rustc's +/// "implementation of `Send` is not general enough" (see `tx_with_retry`). +async fn purge_departed_in(tx: &mut sqlx::PgConnection, active: &[Uuid]) -> Result<(), AppError> { + + // Children first (they reference the summary), then the parents. + sqlx::query!( + "DELETE FROM zeka_attention_item WHERE student <> ALL($1)", + active, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "DELETE FROM zeka_student_summary WHERE student <> ALL($1)", + active, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "DELETE FROM zeka_student_segment_profile WHERE student <> ALL($1)", + active, + ) + .execute(&mut *tx) + .await?; + // Cards about a departed student go; school-wide cards (`about` is + // NULL) are addressed to someone still enrolled and stay. + sqlx::query!( + "DELETE FROM zeka_recommendation + WHERE about IS NOT NULL AND about <> ALL($1)", + active, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "DELETE FROM zeka_run_pending WHERE student <> ALL($1)", + active, + ) + .execute(&mut *tx) + .await?; + Ok(()) +} diff --git a/src/db/mod.rs b/src/db/mod.rs index efad7c2..41c4390 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -40,6 +40,7 @@ pub mod homework; pub mod homework_file; pub mod homework_result; pub mod homework_submission; +pub mod insight; pub mod karne; pub mod meal_attendance; pub mod meal_booking; @@ -53,6 +54,7 @@ pub mod page; pub mod parent_link; pub mod payment_ledger; pub mod person; +pub mod podcast_job; pub mod pomodoro; pub mod pool_question; pub mod pool_question_image; diff --git a/src/lib.rs b/src/lib.rs index f91223e..fa0daae 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -57,8 +57,8 @@ use crate::web::module_gate::gate; (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `POST /auth/register` is still aimed at a school (`{school, username, password}`): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `.` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"), (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), (name = "rag", description = "The course-note RAG: its own nest, threads and tables, relayed through the same QUIC bridge as the chatbot — RAG is not folded into the chatbot's storage. Every authenticated role may ask (parents included) and every thread is private to its owner. Every question is scoped server-side to the asker's own `(sınıf, ders)` pairs, derived on each request from their live memberships — their şubeler' instances, a linked parent's children, and the school-wide club/etüt memberships they hold (which scope the subject across grades, `sinif: null`) — never from the body, so a caller cannot widen their own retrieval; a scope past `MAX_RAG_SCOPE_PAIRS` pairs is refused (400) rather than narrowed. A RAG thread draws on the school's existing AI thread seats (`max_chatbot_threads`, the same seat count the chatbot nest uses, one pool per user), its prompts and answers are bounded by `max_chatbot_message_len`, and its per-minute tier is its own: `RATE_LIMIT_RAG_PER_MINUTE` (default 6, `0` disables the tier; 429 with `Retry-After`). Sending is asynchronous exactly as the chatbot's is: `POST /rag/threads/{id}/messages` writes the turn plus a `pending` assistant row and answers `202`, then poll `GET /rag/threads/{id}/messages/{mid}` or open its `/stream` (SSE `delta`s then `done`/`error`). `503` when no AI service offers `rag.chat`, with nothing written. An answer may abstain — `abstained: true` with a `reason` (`guard_*`, `insufficient_data`, `model_abstained`) is a complete, successful turn, not an error — and carries its `citations`, up to `MAX_RAG_CITATIONS` per answer and at most `MAX_RAG_CITATION_PAGES` pages each (a service reply past either cap fails the turn whole). Each citation's corpus `doc_id` is resolved to the course-note file that owns it (`file`, `null` when no file the asker may view claims that document) beside the pages and retrieval span ids behind it."), - (name = "insights", description = "ZEKA's computed student insights — the `hezarfen_zeka` AI service dials in over the same QUIC bridge as the chatbot and writes its own `zeka_*` rows into each school's database, so this nest reads what it wrote and asks it to compute on demand; the backend never composes an insight row itself. `GET /insights/me` is the caller's own view: a student's summary, their own recommendation cards and their segment profile — and **never** the attention list about themselves, which is a teacher's tool and is not returned to a student or to a linked parent. `GET /insights/students/{id}` is the observer's view of one student — teacher+ narrowed to the students they actually reach through a shared class×course instance, or a parent holding a live link — adding the attention list and the caller's own cards about that student; anyone else reads `404`, never `403`. `POST /insights/students/{id}` and `POST /insights/refresh` (manager+) queue a recompute through the bridge and answer `202` — the compute lands in the service's own rows, so a client polls the read routes; `GET /insights/runs` (manager+) is the run ledger, newest first. Both dispatch doors answer `503` when no service offers the capability, and nothing is queued. Expired and dismissed cards are filtered out of every card read, segment rows below 30 answers (`confidence: none`) are filtered out of every profile read, and a card's `about` is never returned to a student caller."), - (name = "podcast", description = "Podcast generation, relayed through the same QUIC bridge as the chatbot and the RAG nest — the backend owns authentication and the HTTP surface, the podcast service owns the job. `POST /podcast/jobs` (`{source_id, format?}`) starts one and answers `202` with the service's `{job_id, state, eta_secs}` receipt; `GET /podcast/jobs/{id}` polls its `{state, stage, progress, error_code}`, `GET /podcast/jobs/{id}/result` collects a finished job's `{audio_id, duration_secs, script_id, audio_ids, script_ids, format}` (`409` while it is still running), and `POST /podcast/jobs/{id}/cancel` asks the service to stop it (`cancelled` is \"this call stopped work\", so a finished job answers `false`). Each door refuses `503` when no connected service declares its capability, and each relays the service's own refusal code (`not_found`, `not_ready`, `busy`, `llm_unavailable`, …) with a matching status. The produced audio never crosses the bridge: `audio_id` is a path relative to the school's own output directory under `FILES_PATH` (the service's `PODCAST_OUTPUT_ROOT` points there), and `GET /podcast/audio?path=…` streams those bytes — refusing absolute paths, `.`/`..` segments, backslashes and symlinks that resolve outside the school's directory with `400`, so one school can never read another's episode even knowing its path. **None of these doors writes a row**: the job record and its files live in the service. Gated by the school's `chatbot` module (the AI package's only module), like `/chatbot` and `/rag`; any authenticated member of the school may call them, and the school wall is the bridge's (`hab/2` stamps the caller's school onto every request; the bridge does **not** verify the echo on replies — answers are correlated by frame id alone). What the backend cannot judge is *which* sources a caller may narrate — `source_id` is the service's own record id, and no backend query can say what it names."), + (name = "insights", description = "ZEKA's computed student insights. The `hezarfen_zeka` AI service dials in over the same QUIC bridge as the chatbot, but it does **not** touch a school database: the backend owns every statement against the `zeka_*` tables, and the service calls the backend by name (`insight.*` capabilities on a client-initiated stream — see `src/ai/insight.rs`) to have its computed rows written and read back. So this nest reads what the service computed and asks it to compute on demand, and its write doors are the same operations the bridge serves: `POST /insights/summaries`, `/recommendations`, `/segments`, `/profiles` and `/runs` store one batch each (manager+, one call one transaction, rows about students school-wide), `GET /insights/pending` is the students the freshest run left pending, and `POST /insights/sweep` / `POST /insights/purge` are retention and graduation housekeeping — all scoped to the caller's own school by the nest's extractors, and none of them takes a school, a database or a query in its body. `GET /insights/schools` is the exception and is not this nest's usual principal: the active-school directory names every customer, so it is mounted on the **builder** principal outside the school gate (a school session answers `401`), exactly like the vendor surface's `GET /schools`. `GET /insights/me` is the caller's own view: a student's summary, their own recommendation cards and their segment profile — and **never** the attention list about themselves, which is a teacher's tool and is not returned to a student or to a linked parent. `GET /insights/students/{id}` is the observer's view of one student — teacher+ narrowed to the students they actually reach through a shared class×course instance, or a parent holding a live link — adding the attention list and the caller's own cards about that student; anyone else reads `404`, never `403`. `POST /insights/students/{id}` and `POST /insights/refresh` (manager+) queue a recompute through the bridge and answer `202` — the compute lands in the service's own rows, so a client polls the read routes; `GET /insights/runs` (manager+) is the run ledger, newest first. Both dispatch doors answer `503` when no service offers the capability, and nothing is queued. Expired and dismissed cards are filtered out of every card read, segment rows below 30 answers (`confidence: none`) are filtered out of every profile read, and a card's `about` is never returned to a student caller."), + (name = "podcast", description = "Podcast generation, relayed through the same QUIC bridge as the chatbot and the RAG nest — and the **backend owns the job**, not just the HTTP surface. `POST /podcast/jobs` (`{source_id, format?}`) mints the job id, writes the row, then dispatches `podcast.submit` to the service and answers `202` with `{job_id, state, eta_secs}`; `GET /podcast/jobs/{id}` polls the backend's own row `{state, stage, progress, error_code}` with no service round trip, `GET /podcast/jobs/{id}/result` collects a finished job's `{audio_id, duration_secs, format}` (`409` while it is still running), `GET /podcast/jobs/{id}/audio` streams the episode the service uploaded into this school's own blob directory, and `POST /podcast/jobs/{id}/cancel` asks the service to stop it (`cancelled` is \"this call stopped work\", so a finished job answers `false`; a terminal job answers without the service). The service reports every transition back through the `podcast.report` capability and uploads the finished mp3 — so status, result and audio keep answering while the service is down or restarted, and a job nobody is updating reads as failed/interrupted after an ETA-scaled window. Submit and cancel refuse `503` when no worker is connected; none of the three read doors needs one (404 for an unknown or foreign job, 410 past the retention window, 409 before the job is done or when its blob is missing from this host)."), (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins…, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"), (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`). Every authenticated role keeps notes, `parent` included: a note is private own-scoped data with no other reader, and the routes carry **no role bar at all** — ownership is the whole authorization, so nobody but the owner ever reaches a note or its files (a stranger's id is a `404`, never a `403`). That is deliberate and it is the fix for a real defect: while these routes required `student`, a demotion to `parent` locked the owner out of their own notes for good, and since nothing else in the crate reads a note and no route cascades one, the rows and their on-disk blobs became unreachable and undeletable by everybody. Own-scoped personal data is not confiscated by a role change"), (name = "messages", description = "One-to-one mail-style messages, upward only below staff: a student or parent writes to a teacher, manager or admin (parents included — messaging is the one place a parent writes) and never to another student or parent (`403`), while staff write to anyone, each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), @@ -158,6 +158,10 @@ pub fn build_router(state: AppState) -> Router { .nest("/ai", web::ai::routes()) .nest("/auth", web::auth::routes(&state)) .merge(web::builder::routes(&state)) + // The insights directory is the one route of that nest a school + // session may not reach (it names every customer), so it is mounted + // here on the builder principal instead of inside the gate below. + .merge(web::insights::school_directory_routes()) .nest( "/chatbot", gate(web::chatbot::routes(), &state, Module::Chatbot), diff --git a/src/web/insights.rs b/src/web/insights.rs index e2f9c73..17d7c5c 100644 --- a/src/web/insights.rs +++ b/src/web/insights.rs @@ -1,11 +1,15 @@ -//! The insight nest: the read surface over ZEKA's own tables, plus the two -//! doors that ask ZEKA to compute. +//! The insight nest: the read surface over ZEKA's tables, the doors that ask +//! ZEKA to compute, and the storage doors its rows are written through. //! -//! ZEKA (`hezarfen_zeka`) is an AI service that dials in over the QUIC bridge -//! and **writes its own rows** into each school database — the `zeka_*` -//! tables created by the school migrator. The backend never composes those -//! rows; it reads them here and, on request, asks the service to compute -//! (the dispatch contract lives in [`crate::ai::insight`]). +//! ZEKA (`hezarfen_zeka`) is an AI service that dials in over the QUIC bridge. +//! It **does not touch a school database** — no AI service on this deployment +//! does — so the `zeka_*` tables, created by the school migrator, are written +//! and read only by this process. Two surfaces, one implementation each: the +//! service calls the backend over the bridge (`insight.summary.upsert` and +//! the rest of the family — the wire contract is [`crate::ai::insight`], the +//! statements are [`crate::db::insight`]), and the same operations are +//! mounted here as HTTP doors for tooling. The backend never composes an +//! insight row; it stores what the service computed and hands it back. //! //! Reading is authorized the way every per-student report in this API is: //! [`service::parent_link::ensure_can_observe`] decides whether the caller @@ -49,9 +53,14 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; -use crate::ai::insight::{self, RefreshRequest, StudentRequest}; +use crate::ai::insight::{ + self, PendingList, ProfileWriteRequest, PurgeRequest, RecommendationWriteRequest, + RefreshRequest, RunWriteRequest, SchoolDirectory, SegmentWriteRequest, StudentRequest, + SummaryWriteRequest, TableVerdicts, WriteReceipt, +}; use crate::constant::{AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY}; use crate::database::Database; +use crate::db; use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; use crate::domain::role::Role; @@ -63,7 +72,7 @@ use crate::state::AppState; use crate::tenant::ResolvedTenant; use crate::web::tenant_state::State; -use super::{CurrentUser, Page, PageParams, RequireManager, ai_unavailable, paginate}; +use super::{CurrentUser, Page, PageParams, RequireBuilder, RequireManager, ai_unavailable, paginate}; /// The single `now` every card read is filtered against. ZEKA stores unix /// milliseconds, so "expired" is a comparison, not a projection. @@ -76,7 +85,28 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(refresh)) .routes(routes!(my_insight)) .routes(routes!(student_insight, compute_student)) - .routes(routes!(list_runs)) + .routes(routes!(list_runs, write_run)) + .routes(routes!(write_summaries)) + .routes(routes!(write_recommendations)) + .routes(routes!(write_segments)) + .routes(routes!(write_profiles)) + .routes(routes!(pending_students)) + .routes(routes!(sweep_retention)) + .routes(routes!(purge_departed)) +} + +/// The one door of this nest that is **not** school-scoped: the deployment's +/// active-school directory. +/// +/// ZEKA's storage operations are all scoped to the school a session belongs +/// to, and so are these doors — but the directory is not: it names every +/// customer. A school session must therefore never reach it, which is why +/// this route is mounted *outside* the school-scoped gate, on the builder +/// principal (the deployment operator), exactly like the vendor surface's own +/// `GET /schools`. A school cookie answers `401` here, as it does everywhere +/// the builder principal is required. +pub fn school_directory_routes() -> OpenApiRouter { + OpenApiRouter::new().routes(routes!(active_schools)) } // ---- the compute doors ----------------------------------------------------- @@ -244,6 +274,280 @@ fn accepted() -> Response { .into_response() } +// ---- the storage doors ----------------------------------------------------- +// +// ZEKA's own tables are written and read by the backend, never by the service +// (`crate::db::insight` holds the statements, `src/ai/insight.rs` the bridge +// contract). These are the same nine operations over HTTP — one service +// function, two surfaces — so a deployment's tooling can seed, inspect and +// maintain what the service computed without holding a bridge connection. +// +// Manager+ on all of them: every one reads or writes rows about students +// school-wide, which is the same floor `GET /insights/runs` and the refresh +// door carry. The school is the caller's own, resolved by the nest's own +// extractors; no door here takes a school, a database or a query in its body. + +/// Store a batch of ZEKA's student summaries (and their attention items). +/// +/// This is what the AI service calls over the bridge as +/// `insight.summary.upsert`. One call is one batch and one transaction: the +/// batch lands whole or not at all, so a caller that retries cannot +/// half-apply it. Each student's attention items are **replaced**, never +/// merged — a fact the service stopped producing must not stay on screen. +/// At most [`MAX_INSIGHT_BATCH_ROWS`](crate::constant::MAX_INSIGHT_BATCH_ROWS) +/// rows per call. +#[utoipa::path( + post, + path = "/summaries", + tag = "insights", + security(("session_cookie" = [])), + request_body = SummaryWriteRequest, + responses( + (status = 200, description = "The rows were written", body = WriteReceipt), + (status = 400, description = "The payload does not fit the operation: a field is malformed, or a referenced row is not in this school", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 413, description = "More rows than one call may carry", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn write_summaries( + State(st): State, + RequireManager(_user): RequireManager, + Json(body): Json, +) -> Result, AppError> { + Ok(Json(db::insight::write_summaries(&st.db, body.rows).await?)) +} + +/// Store a batch of ZEKA's recommendation cards. +/// +/// The bridge capability is `insight.recommendation.upsert`. The backend +/// mints each row's id. A row whose evidence carries nothing but a +/// `limitation` is **not written** and is counted `rejected` in the receipt — +/// the service's own rule, applied where the write happens instead of being +/// trusted to the writer. +#[utoipa::path( + post, + path = "/recommendations", + tag = "insights", + security(("session_cookie" = [])), + request_body = RecommendationWriteRequest, + responses( + (status = 200, description = "The rows were written; `rejected` counts the cards the evidence rule kept out", body = WriteReceipt), + (status = 400, description = "The payload does not fit the operation: a field is malformed, or a referenced row is not in this school", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 413, description = "More rows than one call may carry", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn write_recommendations( + State(st): State, + RequireManager(_user): RequireManager, + Json(body): Json, +) -> Result, AppError> { + Ok(Json( + db::insight::write_recommendations(&st.db, body.rows).await?, + )) +} + +/// Store a batch of ZEKA's question-segment labels (and each question's +/// dimension split). +/// +/// The bridge capability is `insight.segment.upsert`; the dimension rows are +/// replaced with the payload, like the attention items above. +#[utoipa::path( + post, + path = "/segments", + tag = "insights", + security(("session_cookie" = [])), + request_body = SegmentWriteRequest, + responses( + (status = 200, description = "The rows were written", body = WriteReceipt), + (status = 400, description = "The payload does not fit the operation: a field is malformed, or a referenced row is not in this school", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 413, description = "More rows than one call may carry", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn write_segments( + State(st): State, + RequireManager(_user): RequireManager, + Json(body): Json, +) -> Result, AppError> { + Ok(Json(db::insight::write_segments(&st.db, body.rows).await?)) +} + +/// Store a batch of ZEKA's student segment profiles. +/// +/// The bridge capability is `insight.profile.upsert`. `contrast` is the field +/// the service's rules fire on — the raw `accuracy` mostly measures a +/// student's general level and is stored for the evidence panel only. +#[utoipa::path( + post, + path = "/profiles", + tag = "insights", + security(("session_cookie" = [])), + request_body = ProfileWriteRequest, + responses( + (status = 200, description = "The rows were written", body = WriteReceipt), + (status = 400, description = "The payload does not fit the operation: a field is malformed, or a referenced row is not in this school", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 413, description = "More rows than one call may carry", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn write_profiles( + State(st): State, + RequireManager(_user): RequireManager, + Json(body): Json, +) -> Result, AppError> { + Ok(Json(db::insight::write_profiles(&st.db, body.rows).await?)) +} + +/// Store one compute run's ledger row (with its pending students and failed +/// modules, both replaced). +/// +/// The bridge capability is `insight.run.upsert`; the run is keyed by +/// `run_day` (`YYYY-MM-DD`), so a re-run of the same night overwrites rather +/// than duplicating. `GET /insights/runs` reads the ledger back. +#[utoipa::path( + post, + path = "/runs", + tag = "insights", + security(("session_cookie" = [])), + request_body = RunWriteRequest, + responses( + (status = 200, description = "The run's ledger row was written", body = WriteReceipt), + (status = 400, description = "The payload does not fit the operation: `run_day` is not `YYYY-MM-DD`, or a referenced row is not in this school", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn write_run( + State(st): State, + RequireManager(_user): RequireManager, + Json(body): Json, +) -> Result, AppError> { + Ok(Json(db::insight::write_run(&st.db, body.run).await?)) +} + +/// The students the freshest compute run left pending — where the next run +/// starts. +/// +/// Manager+ only, like `GET /insights/runs`: `pending_students` is a list of +/// people, and this is the same list unpaged. The bridge capability is +/// `insight.pending.list`; the list is answered whole or refused past +/// [`MAX_INSIGHT_PENDING_STUDENTS`](crate::constant::MAX_INSIGHT_PENDING_STUDENTS), +/// never clipped, because the service resumes its next run from it. +#[utoipa::path( + get, + path = "/pending", + tag = "insights", + security(("session_cookie" = [])), + responses( + (status = 200, description = "The freshest run's pending students, in the run's own order", body = PendingList), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 413, description = "More pending students than one answer may carry", body = ErrorResponse), + ), +)] +async fn pending_students( + State(st): State, + RequireManager(_user): RequireManager, +) -> Result, AppError> { + Ok(Json(db::insight::last_pending(&st.db).await?)) +} + +/// Delete every `zeka_*` row whose retention window has closed. +/// +/// The bridge capability is `insight.retention.sweep`. Children go before +/// their parents (the foreign keys are `ON DELETE NO ACTION`), the backend's +/// own clock decides expiry, and each table answers its own verdict — a table +/// that could not be swept is reported `false` while the rest proceed, since +/// housekeeping must not lose a whole run over one locked table. +#[utoipa::path( + post, + path = "/sweep", + tag = "insights", + security(("session_cookie" = [])), + responses( + (status = 200, description = "One verdict per table: whether its expired rows were deleted", body = TableVerdicts), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + ), +)] +async fn sweep_retention( + State(st): State, + RequireManager(_user): RequireManager, +) -> Result, AppError> { + let now_ms = crate::domain::timestamp::Timestamp::now().as_millis(); + Ok(Json(db::insight::sweep(&st.db, now_ms).await?)) +} + +/// Delete the derived rows of every student who is no longer on the roster. +/// +/// The bridge capability is `insight.departed.purge`; `students` is the +/// **active** roster, and every student not named loses their summaries, +/// profiles, attention items, cards about them, and pending-run entries. One +/// transaction, so the verdicts move together. An empty list is refused: an +/// empty roster is a fetch that failed, and obeying it would delete the whole +/// school's derived data. +#[utoipa::path( + post, + path = "/purge", + tag = "insights", + security(("session_cookie" = [])), + request_body = PurgeRequest, + responses( + (status = 200, description = "One verdict per table: whether the departed students' rows were deleted", body = TableVerdicts), + (status = 400, description = "The payload does not fit the operation: the roster is empty", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 413, description = "More students than one call may name", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + ), +)] +async fn purge_departed( + State(st): State, + RequireManager(_user): RequireManager, + Json(body): Json, +) -> Result, AppError> { + Ok(Json( + db::insight::purge_departed(&st.db, body.students).await?, + )) +} + +/// The deployment's active schools, by slug — the directory a shared AI fleet +/// schedules over. +/// +/// This is the one operation of the family that is not school-scoped, and the +/// one door of this nest that is not a school's: it names every customer, so +/// it runs on the **builder** principal (the deployment operator), mounted +/// outside the school gate exactly like the vendor surface's `GET /schools`. +/// A school session gets `401` here. The bridge capability is +/// `insight.schools.list`, which is the service's own deployment-scoped call: +/// the same function, two surfaces, and a school-scoped caller on neither. +#[utoipa::path( + get, + path = "/insights/schools", + tag = "insights", + security(("session_cookie" = [])), + responses( + (status = 200, description = "Every active school on this deployment, by slug", body = SchoolDirectory), + (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), + ), +)] +async fn active_schools( + axum::extract::State(st): axum::extract::State, + RequireBuilder(_builder): RequireBuilder, +) -> Result, AppError> { + Ok(Json(db::insight::active_schools(st.tenants.control()).await?)) +} + /// Canonicalize the ids a refresh body names — through the same parser every /// route uses for a wire id, so a client cannot hand the service a spelling /// this backend itself would never produce. Anything that parses as no uuid diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index ccb86ae..58159d9 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -3501,3 +3501,454 @@ async fn no_insight_refresh_worker_means_503_and_nothing_is_dispatched() { .await; assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); } + +// ------------------------------------------- the backend-served capabilities -- +// +// The other direction: a service calling the *backend*. ZEKA's storage +// surface is nine `insight.*` operations the backend executes against the +// school the frame names — no AI service holds a school database credential +// on this deployment, so these calls are the only way its rows are written. +// Everything below rides a real client-initiated QUIC stream, like the api +// read it is shaped after. + +use hezarfen_backend::ai::protocol::{CapabilityRequest, CapabilityResponse}; +use hezarfen_backend::constant::{ + AI_INSIGHT_PENDING_LIST_CAPABILITY, AI_INSIGHT_RETENTION_SWEEP_CAPABILITY, + AI_INSIGHT_RUN_UPSERT_CAPABILITY, AI_INSIGHT_SCHOOLS_LIST_CAPABILITY, + AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY, +}; +use hezarfen_backend::domain::user::{Password, Username}; +use hezarfen_backend::service::builder; +use hezarfen_backend::tenant::SchoolId; + +/// One capability call: a fresh client-initiated stream, one frame out, one +/// back, stream dropped — the same lifecycle as `api_read` above. +async fn capability_call( + conn: &quinn::Connection, + request: CapabilityRequest, +) -> CapabilityResponse { + let (mut send, mut recv) = conn.open_bi().await.expect("capability stream"); + write_frame(&mut send, &request).await.expect("write CapabilityRequest"); + let _ = send.finish(); + read_frame(&mut recv).await.expect("read CapabilityResponse") +} + +fn insight_call(capability: &str, school: &str, payload: Value) -> CapabilityRequest { + CapabilityRequest { + id: format!("trace-{capability}"), + school: school.to_string(), + capability: capability.to_string(), + payload, + } +} + +fn ok_capability(answer: CapabilityResponse) -> Value { + match answer { + CapabilityResponse::Ok { payload, .. } => payload, + CapabilityResponse::Err { code, message, .. } => { + panic!("expected the backend to run the operation, got {code}: {message}") + } + } +} + +fn refused_capability(answer: CapabilityResponse) -> (String, String) { + match answer { + CapabilityResponse::Err { code, message, .. } => (code, message), + CapabilityResponse::Ok { payload, .. } => { + panic!("expected a refusal, got {payload}") + } + } +} + +/// A summary row as the service sends it, for one student. +fn summary_payload(student: &str, retain_until: i64) -> Value { + json!({ "rows": [{ + "student": student, + "marks": { "ortalama": 72 }, + "confidence": "stable", + "computed_at": 1_700_000_000_000i64, + "retain_until": retain_until, + "attention": [{ + "trigger": "not_egilimi_dusuyor", + "fact": "Son üç sınavda ortalama 12 puan düştü.", + "window_from": 1_690_000_000_000i64, + "window_to": 1_700_000_000_000i64, + "evidence": { "delta": -12 }, + }], + }] }) +} + +/// The demo school, an app with the bridge armed, a manager cookie and one +/// student's id — the fixture every test below needs. +async fn insight_fixture( + bridge: &AiBridge, +) -> (FakeService, Router, hezarfen_backend::database::Database, String, String) { + let service = + connect_service(bridge, hello("zeka", &["insight.refresh"]), Behaviour::Echo).await; + await_workers(bridge, 1).await; + let (app, db) = common::app_with_ai(Some(bridge.clone())).await; + let mudur = common::login_as(&app, &db, "mudur", "manager").await; + let ayse = common::login_as(&app, &db, "ayse", "student").await; + let student = common::me_id(&app, &ayse).await; + (service, app, db, mudur, student) +} + +#[tokio::test] +async fn a_capability_call_writes_the_row_the_schools_own_read_door_serves() { + let bridge = bridge().await; + let (service, app, _db, mudur, student) = insight_fixture(&bridge).await; + + let answer = capability_call( + &service.conn, + insight_call( + AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY, + DEMO_SLUG, + summary_payload(&student, 1_800_000_000_000i64), + ), + ) + .await; + let CapabilityResponse::Ok { payload, school, id } = answer else { + panic!("expected the write to land: {answer:?}"); + }; + assert_eq!(id, format!("trace-{AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY}")); + assert_eq!(school, DEMO_SLUG, "the answer echoes the school the frame named"); + assert_eq!(payload["written"], 1); + + // The same row is what the nest's own read door serves the school's staff + // — one function behind the write, one behind the read, neither school + // able to see the other's row. + let res = common::send( + &app, + "GET", + &format!("/insights/students/{student}"), + Some(&mudur), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["summary"]["marks"]["ortalama"], 72); + assert_eq!(res.body["summary"]["confidence"], "stable"); + assert_eq!(res.body["attention"].as_array().map(Vec::len), Some(1)); + assert_eq!(res.body["attention"][0]["trigger"], "not_egilimi_dusuyor"); +} + +#[tokio::test] +async fn the_insight_ledger_and_pending_list_round_trip_over_the_bridge() { + let bridge = bridge().await; + let (service, _app, _db, _mudur, student) = insight_fixture(&bridge).await; + + let run = insight_call( + AI_INSIGHT_RUN_UPSERT_CAPABILITY, + DEMO_SLUG, + json!({ "run": { + "run_day": "2026-09-17", + "started_at": 1_700_000_000_000i64, + "status": "partial", + "students_total": 3, + "students_ok": 2, + "students_failed": 0, + "students_skipped": 1, + "rows_written": 2, + "budget_exceeded": true, + "budget_ms": 60_000, + "retain_until": 1_800_000_000_000i64, + "pending_students": [student], + "failed_modules": ["segment"], + } }), + ); + assert_eq!(ok_capability(capability_call(&service.conn, run).await)["written"], 1); + + let pending = ok_capability( + capability_call( + &service.conn, + insight_call(AI_INSIGHT_PENDING_LIST_CAPABILITY, DEMO_SLUG, json!({})), + ) + .await, + ); + assert_eq!(pending["students"], json!([student])); + + // A run day that is not `YYYY-MM-DD` is the caller's payload error, not a + // CHECK violation dressed as a server fault. + let bad_day = insight_call( + AI_INSIGHT_RUN_UPSERT_CAPABILITY, + DEMO_SLUG, + json!({ "run": { + "run_day": "17.09.2026", + "started_at": 1, + "status": "running", + "students_total": 0, "students_ok": 0, "students_failed": 0, + "students_skipped": 0, "rows_written": 0, + "budget_exceeded": false, "budget_ms": 1, + "retain_until": 1, + } }), + ); + let (code, message) = refused_capability(capability_call(&service.conn, bad_day).await); + assert_eq!(code, "invalid_payload"); + assert!(message.contains("run_day"), "names the field: {message}"); +} + +#[tokio::test] +async fn the_sweep_and_purge_capabilities_answer_per_table_verdicts() { + let bridge = bridge().await; + let (service, _app, _db, _mudur, student) = insight_fixture(&bridge).await; + + // An expired row: the sweep's own clock decides, so it must go. + let answer = capability_call( + &service.conn, + insight_call( + AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY, + DEMO_SLUG, + summary_payload(&student, 1), // long past + ), + ) + .await; + assert_eq!(ok_capability(answer)["written"], 1); + + let verdicts = ok_capability( + capability_call( + &service.conn, + insight_call(AI_INSIGHT_RETENTION_SWEEP_CAPABILITY, DEMO_SLUG, json!({})), + ) + .await, + ); + assert_eq!(verdicts["tables"]["zeka_student_summary"], true); + assert_eq!(verdicts["tables"].as_object().map(|t| t.len()), Some(9)); + + // An empty roster is a fetch that failed, never "nobody is enrolled": + // obeyed, it would delete every student's derived rows in one call. + let empty = insight_call( + "insight.departed.purge", + DEMO_SLUG, + json!({ "students": [] }), + ); + let (code, _) = refused_capability(capability_call(&service.conn, empty).await); + assert_eq!(code, "invalid_payload"); +} + +#[tokio::test] +async fn a_capability_call_cannot_touch_another_schools_rows() { + let bridge = bridge().await; + let service = + connect_service(&bridge, hello("zeka", &["insight.refresh"]), Behaviour::Echo).await; + await_workers(&bridge, 1).await; + let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await; + let _mudur = common::login_as(&app, &demo_db, "mudur", "manager").await; + let ayse = common::login_as(&app, &demo_db, "ayse", "student").await; + let student = common::me_id(&app, &ayse).await; + let beta = Slug::try_new("beta").unwrap(); + let beta_db = tenants + .create(SchoolId::generate(), &beta, "Beta College", ModuleSet::all()) + .await + .expect("beta"); + + // Same payload the demo school accepts, sent for beta: beta's database + // has no such student, so the foreign key refuses it. That refusal is the + // proof the statement ran inside *beta's* database — run against the + // demo school it would have landed, which is exactly what must not + // happen when a frame names another school. + let cross = insight_call( + AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY, + beta.as_str(), + summary_payload(&student, 1_800_000_000_000i64), + ); + let (code, message) = refused_capability(capability_call(&service.conn, cross).await); + assert_eq!(code, "invalid_payload"); + assert!(message.contains("referenced row"), "{message}"); + + // Nothing landed in beta, and nothing leaked into the demo school either. + let beta_rows: i64 = sqlx::query_scalar("SELECT count(*) FROM zeka_student_summary") + .fetch_one(&beta_db) + .await + .expect("beta count"); + assert_eq!(beta_rows, 0); + let demo_rows: i64 = sqlx::query_scalar("SELECT count(*) FROM zeka_student_summary") + .fetch_one(&demo_db) + .await + .expect("demo count"); + assert_eq!(demo_rows, 0, "the refused call wrote nothing anywhere"); +} + +#[tokio::test] +async fn a_capability_call_refuses_unknown_names_and_payloads_that_do_not_fit() { + let bridge = bridge().await; + let (service, _app, _db, _mudur, student) = insight_fixture(&bridge).await; + + // A name nobody serves — no prefix match, no fallback: the shape that + // would make this a generic door is the shape that is missing. + let unknown = insight_call("insight.database.query", DEMO_SLUG, json!({ "sql": "SELECT 1" })); + let (code, message) = refused_capability(capability_call(&service.conn, unknown).await); + assert_eq!(code, "unknown_capability"); + assert!(message.contains("insight.database.query"), "{message}"); + + // A payload that does not fit the operation's contract. + let bad = insight_call( + AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY, + DEMO_SLUG, + json!({ "rows": [{ "student": "not-a-uuid", "confidence": "stable", + "computed_at": 1, "retain_until": 2 }] }), + ); + let (code, message) = refused_capability(capability_call(&service.conn, bad).await); + assert_eq!(code, "invalid_payload"); + assert!(message.contains("student"), "names the field: {message}"); + + // A frame that names a school nobody deploys. + let stranger = insight_call( + AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY, + "nowhere", + summary_payload(&student, 1), + ); + let (code, _) = refused_capability(capability_call(&service.conn, stranger).await); + assert_eq!(code, "unknown_school"); +} + +#[tokio::test] +async fn the_school_directory_is_the_one_deployment_scoped_operation() { + let bridge = bridge().await; + let service = + connect_service(&bridge, hello("zeka", &["insight.refresh"]), Behaviour::Echo).await; + await_workers(&bridge, 1).await; + let (app, _db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await; + let beta = Slug::try_new("beta").unwrap(); + tenants + .create(SchoolId::generate(), &beta, "Beta College", ModuleSet::all()) + .await + .expect("beta"); + + // The frame names no school (there is none to name: this is how a shared + // fleet learns which schools exist). + let answer = capability_call( + &service.conn, + insight_call(AI_INSIGHT_SCHOOLS_LIST_CAPABILITY, "", json!({})), + ) + .await; + let payload = ok_capability(answer); + let schools: Vec<&str> = payload["schools"] + .as_array() + .expect("schools") + .iter() + .map(|s| s.as_str().expect("slug")) + .collect(); + assert_eq!(schools, vec!["beta", DEMO_SLUG], "active schools, sorted"); + + // Over HTTP the same operation is the builder's: a school session must + // not be able to enumerate the deployment's other customers. + let ayse = common::login(&app, "ayse").await; + let refused = common::send(&app, "GET", "/insights/schools", Some(&ayse), None).await; + assert_eq!(refused.status, StatusCode::UNAUTHORIZED, "{}", refused.body); + let anonymous = common::send(&app, "GET", "/insights/schools", None, None).await; + assert_eq!(anonymous.status, StatusCode::UNAUTHORIZED); + + // And the builder — the deployment operator — reads the same directory. + builder::ensure( + tenants.control(), + Username::try_new("operator").unwrap(), + Password::try_new("secret1").unwrap(), + ) + .await + .expect("seed the builder"); + let login = common::send( + &app, + "POST", + "/builder/login", + None, + Some(json!({ "username": "operator", "password": "secret1" })), + ) + .await; + assert_eq!(login.status, StatusCode::OK, "{}", login.body); + let cookie = login.cookie.expect("builder cookie"); + let listed = common::send(&app, "GET", "/insights/schools", Some(&cookie), None).await; + assert_eq!(listed.status, StatusCode::OK, "{}", listed.body); + assert_eq!(listed.body, payload); +} + +#[tokio::test] +async fn the_storage_doors_are_manager_only_and_write_the_callers_own_school() { + let bridge = bridge().await; + let (service, app, db, mudur, student) = insight_fixture(&bridge).await; + let _ = service; + + // A teacher may read insights, but these doors write rows about students + // school-wide: manager+ is the floor, as it is on the ledger read. + let ogretmen = common::login_as(&app, &db, "ogretmen", "teacher").await; + let body = summary_payload(&student, 1_800_000_000_000i64); + let refused = common::send( + &app, + "POST", + "/insights/summaries", + Some(&ogretmen), + Some(body.clone()), + ) + .await; + assert_eq!(refused.status, StatusCode::FORBIDDEN, "{}", refused.body); + let anonymous = common::send(&app, "POST", "/insights/summaries", None, Some(body.clone())).await; + assert_eq!(anonymous.status, StatusCode::UNAUTHORIZED); + + // The same operation the bridge serves, on the caller's own school. + let written = common::send( + &app, + "POST", + "/insights/summaries", + Some(&mudur), + Some(body), + ) + .await; + assert_eq!(written.status, StatusCode::OK, "{}", written.body); + assert_eq!(written.body["written"], 1); + + // 413 for a batch past the ceiling, refused whole — never narrowed. + let over: Vec = (0..501) + .map(|_| { + json!({ "student": student, "confidence": "stable", + "computed_at": 1_700_000_000_000i64, + "retain_until": 1_800_000_000_000i64 }) + }) + .collect(); + let too_many = common::send( + &app, + "POST", + "/insights/summaries", + Some(&mudur), + Some(json!({ "rows": over })), + ) + .await; + assert_eq!(too_many.status, StatusCode::PAYLOAD_TOO_LARGE, "{}", too_many.body); + + // The run ledger's POST and the existing GET share one path. + let run = common::send( + &app, + "POST", + "/insights/runs", + Some(&mudur), + Some(json!({ "run": { + "run_day": "2026-09-18", + "started_at": 1_700_000_000_000i64, + "status": "ok", + "students_total": 1, "students_ok": 1, "students_failed": 0, + "students_skipped": 0, "rows_written": 1, + "budget_exceeded": false, "budget_ms": 60_000, + "retain_until": 1_800_000_000_000i64, + } })), + ) + .await; + assert_eq!(run.status, StatusCode::OK, "{}", run.body); + let ledger = common::send(&app, "GET", "/insights/runs", Some(&mudur), None).await; + assert_eq!(ledger.status, StatusCode::OK, "{}", ledger.body); + assert_eq!(ledger.body["items"][0]["run_day"], "2026-09-18"); + assert_eq!(ledger.body["items"][0]["status"], "ok"); + + // The sweep is a bodyless action route and answers one verdict per table. + let swept = common::send(&app, "POST", "/insights/sweep", Some(&mudur), None).await; + assert_eq!(swept.status, StatusCode::OK, "{}", swept.body); + assert_eq!(swept.body["tables"].as_object().map(|t| t.len()), Some(9)); + // The retention the payload named is honoured: this row lives on. + let kept = common::send( + &app, + "GET", + &format!("/insights/students/{student}"), + Some(&mudur), + None, + ) + .await; + assert_eq!(kept.status, StatusCode::OK); + assert_eq!(kept.body["summary"]["marks"]["ortalama"], 72); +} diff --git a/tests/ai_protocol.rs b/tests/ai_protocol.rs index dec2bb4..76108b9 100644 --- a/tests/ai_protocol.rs +++ b/tests/ai_protocol.rs @@ -1631,3 +1631,110 @@ async fn an_api_read_still_answers_on_the_shared_client_stream_path() { assert_eq!(answer["code"], "malformed"); assert_eq!(answer["id"], "t-neither"); } + +// ---------------------------------------------------- capability calls -- +// +// The third client-initiated shape: a service calling an operation the +// *backend* serves (ZEKA's storage surface — no AI service holds a school +// database credential here). Nothing about the two shapes that existed before +// may move: an api read is still routed on `path`, a blob read on `file`, and +// a service that never calls a capability never receives one — the new frame +// only ever appears on a stream the service itself opened, so a client that +// does not speak it cannot be surprised by it. These tests pin the shape the +// way a foreign service reads it: bytes in, untyped JSON out. + +#[tokio::test] +async fn a_capability_call_carries_exactly_the_published_keys() { + let bridge = bridge().await; + let service = raw::handshake(&bridge, &raw::hello("zeka", "insight.refresh")).await; + await_workers(&bridge, 1).await; + // The storage surface runs against a real school database, so the bridge + // needs the api handle armed (`app_with_ai`) and a student that exists. + let (app, db) = common::app_with_ai(Some(bridge.clone())).await; + let _ = db; + let ayse = common::login(&app, "ayse").await; + let student = common::me_id(&app, &ayse).await; + + let body = format!( + r#"{{"id":"t-cap","school":"{SCHOOL}","capability":"insight.summary.upsert","payload":{{"rows":[{{"student":"{student}","marks":{{"ortalama":72}},"confidence":"stable","computed_at":1700000000000,"retain_until":1800000000000}}]}}}}"# + ); + let (answer, _) = raw::api_read(&service.conn, body.as_bytes()).await; + + assert_eq!( + raw::keys(&answer), + ["id", "payload", "school", "status"], + "capability answer shape changed: {answer}" + ); + assert_eq!(answer["status"], "ok", "{answer}"); + assert_eq!(answer["id"], "t-cap"); + assert_eq!( + answer["school"], SCHOOL, + "the answer echoes the school the call named" + ); + assert_eq!(answer["payload"]["written"], 1, "{answer}"); +} + +#[tokio::test] +async fn a_capability_refusal_is_flat_and_never_reports_ok() { + // A service branches on `status` first and on `code` second; both are + // pinned literals, and a refusal carries no payload — there is no + // half-answer to read. + let bridge = bridge().await; + let service = raw::handshake(&bridge, &raw::hello("zeka", "insight.refresh")).await; + await_workers(&bridge, 1).await; + let (_app, _db) = common::app_with_ai(Some(bridge.clone())).await; + + let body = format!( + r#"{{"id":"t-nope","school":"{SCHOOL}","capability":"insight.database.query","payload":{{"sql":"select 1"}}}}"# + ); + let (answer, _) = raw::api_read(&service.conn, body.as_bytes()).await; + assert_eq!( + raw::keys(&answer), + ["code", "id", "message", "school", "status"], + "capability refusal shape changed: {answer}" + ); + assert_eq!(answer["status"], "err", "{answer}"); + assert_eq!(answer["code"], "unknown_capability", "{answer}"); + assert_eq!(answer["id"], "t-nope"); + assert_eq!(answer["school"], SCHOOL); + assert!( + answer["message"].as_str().is_some_and(|m| !m.is_empty()), + "message must be a string a service can log" + ); +} + +#[tokio::test] +async fn the_capability_shape_does_not_steal_the_shapes_that_existed_before() { + // Precedence, pinned: `path` wins over `file` wins over `capability`, so + // every frame that parsed as one of the older shapes still parses as it + // did — the capability branch is only reached when neither is present. + let bridge = bridge().await; + let service = raw::handshake(&bridge, &raw::hello("indexer", "rag.index")).await; + await_workers(&bridge, 1).await; + let (app, _db) = common::app_with_ai(Some(bridge.clone())).await; + let ayse = common::login(&app, "ayse").await; + let student = common::me_id(&app, &ayse).await; + + // A frame carrying both: still the api read it has always been. + let body = format!( + r#"{{"id":"t-both","school":"{SCHOOL}","path":"/auth/me","capability":"insight.pending.list","payload":{{}},"on_behalf_of":"{student}"}}"# + ); + let (answer, _) = raw::api_read(&service.conn, body.as_bytes()).await; + assert_eq!(answer["outcome"], "ok", "{answer}"); + assert_eq!(answer["status"], 200, "{answer}"); + + // A capability-only frame: the capability call, and a read the service + // asked for comes back in its own envelope. + let body = format!( + r#"{{"id":"t-pending","school":"{SCHOOL}","capability":"insight.pending.list","payload":{{}}}}"# + ); + let (answer, _) = raw::api_read(&service.conn, body.as_bytes()).await; + assert_eq!(answer["status"], "ok", "{answer}"); + assert_eq!(answer["payload"]["students"], json!([]), "{answer}"); + + // Neither: the same api-read refusal as before this shape existed. + let (answer, _) = + raw::api_read(&service.conn, br#"{"id":"t-neither","school":"demo"}"#).await; + assert_eq!(answer["outcome"], "err", "{answer}"); + assert_eq!(answer["code"], "malformed"); +} diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs index aa46ba2..66063a1 100644 --- a/tests/limits_completeness.rs +++ b/tests/limits_completeness.rs @@ -145,22 +145,101 @@ const EXCLUDED: &[(&str, &str)] = &[ "deadline on one school-wide recompute; the run's own ledger is \ `zeka_run`, which the client polls", ), + // 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. ( - "AI_PODCAST_SUBMIT_CAPABILITY", - "capability string an AI service declares", + "AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY", + "capability string the backend serves to an AI service", ), ( - "AI_PODCAST_STATUS_CAPABILITY", - "capability string an AI service declares", + "AI_INSIGHT_RECOMMENDATION_UPSERT_CAPABILITY", + "capability string the backend serves to an AI service", + ), + ( + "AI_INSIGHT_SEGMENT_UPSERT_CAPABILITY", + "capability string the backend serves to an AI service", + ), + ( + "AI_INSIGHT_PROFILE_UPSERT_CAPABILITY", + "capability string the backend serves to an AI service", + ), + ( + "AI_INSIGHT_RUN_UPSERT_CAPABILITY", + "capability string the backend serves to an AI service", + ), + ( + "AI_INSIGHT_PENDING_LIST_CAPABILITY", + "capability string the backend serves to an AI service", + ), + ( + "AI_INSIGHT_RETENTION_SWEEP_CAPABILITY", + "capability string the backend serves to an AI service", + ), + ( + "AI_INSIGHT_DEPARTED_PURGE_CAPABILITY", + "capability string the backend serves to an AI service", + ), + ( + "AI_INSIGHT_SCHOOLS_LIST_CAPABILITY", + "capability string the backend serves to an AI service", + ), + ( + "MAX_INSIGHT_BATCH_ROWS", + "rows per bridge call: the AI service's own batch size, enforced by the \ + doors as a 413 and by the bridge as `too_many_rows`; a client of \ + neither cannot act on it", + ), + ( + "MAX_INSIGHT_PENDING_STUDENTS", + "students one bridge answer may carry; over it the call is refused \ + (`too_many_rows`) rather than clipped, so there is no client-side \ + value to size against", + ), + ( + "MAX_INSIGHT_PURGE_STUDENTS", + "students one bridge purge call may name; the roster is the AI \ + service's own list, not something a browser assembles", ), ( - "AI_PODCAST_RESULT_CAPABILITY", + "AI_PODCAST_SUBMIT_CAPABILITY", "capability string an AI service declares", ), + ( + "AI_PODCAST_REPORT_CAPABILITY", + "capability string the backend serves; the AI service calls it", + ), ( "AI_PODCAST_CANCEL_CAPABILITY", "capability string an AI service declares", ), + ( + "PODCAST_AUDIO_MAX_BYTES", + "the largest episode the backend ingests from a service; a service-side \ + ingest bound a browser never assembles a body for", + ), + ( + "PODCAST_JOB_RETENTION_SECS", + "how long a finished podcast job stays readable; the doors answer 410 \ + past it, which is the whole client-visible behavior — the number is \ + the operator's policy, not a value a client sizes against", + ), + ( + "PODCAST_JOB_STALE_FLOOR_SECS", + "floor of the read-side staleness window a dead job is projected \ + failed in; a client reads the projected state, never sets this", + ), + ( + "PODCAST_JOB_STALE_ETA_FACTOR", + "how many times its own ETA a podcast job may exceed before the read \ + side stops believing it runs; same as the floor — the projection is \ + the visible behavior", + ), + ( + "PODCAST_INTERRUPTED_CODE", + "error_code value the backend writes for a job it concluded died; a \ + client reads it off the job, it is not a tunable", + ), ( "CHAT_STREAM_POLL_MS", "server-side poll cadence behind the SSE stream", @@ -436,7 +515,12 @@ fn moved_value_tables_are_still_published_or_deliberately_excluded() { /// constant: every former entry now lives there and is excused (or published) /// through `EXCLUDED` above instead. A new name here is a claim that a bound /// belongs somewhere else, which needs an argument. -const NOT_A_CLIENT_BOUND: &[(&str, &str)] = &[]; +const NOT_A_CLIENT_BOUND: &[(&str, &str)] = &[( + "MAX_CODE_LEN", + "bound on the length of a podcast report's `stage`/`error_code` — values \ + the AI *service* writes onto the job row; a browser reads the stored \ + string back, it never sizes one against this", +)]; #[test] fn validation_bounds_live_in_constant_rs() {