Serve the school report document as insight.report
Browse files at this commit1d00d9d34201240d739de4ae786eeb970ac8d37fParent: 8eb06bc- feat
- serve the school report document as insight.report
8 changed files +790 -14
- service/README.md +3 -1
- service/docs/BACKEND-GEREKSINIMLERI.md +85 -1
- service/docs/CIKTI-SOZLESMESI.md +6 -2
- service/src/capabilities.py +81 -1
- service/src/handlers.py +206 -2
- service/tests/test_capabilities.py +12 -6
- service/tests/test_handlers.py +2 -1
- service/tests/test_report_capability.py +395 -0
service/README.mdmodified+3 -1
| @@ -54,7 +54,9 @@ Servisin çağırdığı operasyonlar: `insight.schools.list`, `insight.summary. | |||
| 54 | `insight.recommendation.upsert`, `insight.segment.upsert`, `insight.profile.upsert`, | 54 | `insight.recommendation.upsert`, `insight.segment.upsert`, `insight.profile.upsert`, |
| 55 | `insight.run.upsert`, `insight.pending.list`, `insight.retention.sweep`, | 55 | `insight.run.upsert`, `insight.pending.list`, `insight.retention.sweep`, |
| 56 | `insight.departed.purge`. Servisin **servis ettiği** yetenekler `insight.student`, | 56 | `insight.departed.purge`. Servisin **servis ettiği** yetenekler `insight.student`, |
| 57 | -`insight.class`, `insight.refresh`'tir (`src/capabilities.py`). | 57 | +`insight.class`, `insight.refresh` ve `insight.report`'tur (`src/capabilities.py`; |
| 58 | +`insight.report` okul raporu **belgesini** üretir — satırlar payload'da gelir, | ||
| 59 | +servis köprüden hiçbir şey okumaz). | ||
| 58 | 60 | ||
| 59 | --- | 61 | --- |
| 60 | 62 | ||
service/docs/BACKEND-GEREKSINIMLERI.mdmodified+85 -1
| @@ -29,7 +29,9 @@ Yani asagidaki uc madde ZEKA'nin nelerin **disinda** kaldigini tarif eder. | |||
| 29 | > servis tarafi ayni gun baglandi (`src/handlers.py`; ilan ile dagitim | 29 | > servis tarafi ayni gun baglandi (`src/handlers.py`; ilan ile dagitim |
| 30 | > acilista `capabilities.verify_dispatchable()` ile denetlenir). | 30 | > acilista `capabilities.verify_dispatchable()` ile denetlenir). |
| 31 | > `insight.class` ilan edilir ama hala GONDERILMEZ -- kadro listeleme yolu | 31 | > `insight.class` ilan edilir ama hala GONDERILMEZ -- kadro listeleme yolu |
| 32 | -> yok (Madde 3). Asagidaki "yoktur / tanimli degil" ifadeleri bu iki yonu | 32 | +> yok (Madde 3). `insight.report` icin servis tarafi da hazir (2026-09-18): |
| 33 | +> backend'in dagitim tablosuna girmesi bekleniyor, bkz. `## insight.report`. | ||
| 34 | +> Asagidaki "yoktur / tanimli degil" ifadeleri bu iki yonu | ||
| 33 | > ayirmadan okunmamalidir; `src/capabilities.py` modul dokumani ayni ayrimi | 35 | > ayirmadan okunmamalidir; `src/capabilities.py` modul dokumani ayni ayrimi |
| 34 | > yapar. | 36 | > yapar. |
| 35 | 37 | ||
| @@ -147,6 +149,87 @@ inmesidir. | |||
| 147 | 149 | ||
| 148 | --- | 150 | --- |
| 149 | 151 | ||
| 152 | +## insight.report -- okul raporu BELGESI (sunucu-baslatimli; servis tarafi HAZIR 2026-09-18) | ||
| 153 | + | ||
| 154 | +**Sahibi: backend'deki `InsightDoors` hatti.** Servis tarafi bugun hazir: | ||
| 155 | +`insight.report` ilan edilir, isleyicisi kayitlidir (`handlers.report`) ve | ||
| 156 | +acilistaki `capabilities.verify_dispatchable()` onu dagitilabilir sayar. | ||
| 157 | +Eksik olan tek sey backend'in dagitim tablosudur (`hezarfen_backend/src` | ||
| 158 | +icinde bu ad 2026-09-18 itibariyla hic gecmez), yani bugun kimse bu yetenegi | ||
| 159 | +cagiramaz. Kapi acildiginda uc sey BIRLIKTE guncellenir: `src/capabilities.py` | ||
| 160 | +`BACKEND_CALLABLE_CAPABILITIES`, `tests/test_capabilities.py` pini ve | ||
| 161 | +yukaridaki durum cumlesi. | ||
| 162 | + | ||
| 163 | +### Ne isteniyor | ||
| 164 | + | ||
| 165 | +Backend, okulun `zeka_*` satirlarini **kendi okur** ve tek bir | ||
| 166 | +`insight.report` istegiyle gonderir; servis belgeyi uretir ve cevap | ||
| 167 | +cercevesinde **HTML metni olarak** dondurur. Blob yuklemesi yok, depo yok: | ||
| 168 | +belge, servisin hicbir okuma yapmadigi tek `insight.*` isleyicisidir. | ||
| 169 | + | ||
| 170 | +**Istek payload'i.** Cercevedeki `school` = okul slug'i. Satirlar ZEKA'nin | ||
| 171 | +depo yoluyla yazdigi bicimdir -- backend'in kendi yapilari (`db/insight.rs` | ||
| 172 | +`SummaryRow` / `RecommendationRow` / `ProfileRow` / `RunRow`), yani ikinci bir | ||
| 173 | +esleme yok: | ||
| 174 | + | ||
| 175 | +| Alan | Tip | Ne | | ||
| 176 | +|---|---|---| | ||
| 177 | +| `kind` | str | Zorunlu; sunulan tek deger `okul` | | ||
| 178 | +| `run_day` | str | `YYYY-MM-DD` (TR gunu); yoksa en yeni kosu satirindan turetilir | | ||
| 179 | +| `requested_by` | str | Belgeyi isteyen mudur; okuma yapilmadigi icin yalniz log'a yazilir | | ||
| 180 | +| `school` | nesne | `{id, slug, name}`; `name` belge BASLIGIDIR, `slug` cerceveyle ayni olmali | | ||
| 181 | +| `summaries` | liste | `zeka_student_summary` satirlari (`attention` listesi dahil) | | ||
| 182 | +| `recommendations` | liste | `zeka_recommendation` satirlari | | ||
| 183 | +| `profiles` | liste | `zeka_student_segment_profile` satirlari | | ||
| 184 | +| `runs` | liste | `zeka_run` satirlari (`run_day` alani belgenin gununu verir) | | ||
| 185 | + | ||
| 186 | +Satirlarda `school` GONDERILMEZ: ZEKA onu hic yazmaz, cercevede gelir ve | ||
| 187 | +servis her satira kendisi damgalar (tek kimlik kaynagi). Yine de bir satir | ||
| 188 | +baska bir okul tasirsa istek reddedilir -- damgalamak degil, reddetmek. | ||
| 189 | + | ||
| 190 | +**Cevap payload'i** (belge cercevenin ICINDE gider): | ||
| 191 | + | ||
| 192 | +```json | ||
| 193 | +{ "kind": "okul", "run_day": "2026-09-18", "format": "html", | ||
| 194 | + "html": "<!DOCTYPE html>...", "byte_size": 12345, "truncated": false, | ||
| 195 | + "notes": ["Siralama yoktur. ...", "Kaniti olmayan satir rapora girmez. ..."], | ||
| 196 | + "coverage": { "rows": {"summaries": 42, "recommendations": 7, | ||
| 197 | + "profiles": 11, "runs": 1}, "empty": false } } | ||
| 198 | +``` | ||
| 199 | + | ||
| 200 | +- `byte_size` = `html`in UTF-8 bayt uzunlugu; `truncated` bugun her zaman | ||
| 201 | + `false` (sinir asilirsa belge KESILMEZ, asagidaki kodla reddedilir). | ||
| 202 | +- `notes` paketin kendi kapsam/sinir cumleleridir: backend onlari oldugu gibi | ||
| 203 | + gosterir, kendi cumlesini uydurmaz. | ||
| 204 | +- `coverage` sozlesme disi ek alandir (refresh'in `status`u gibi: serde | ||
| 205 | + bilinmeyen alani yok sayar): ham satir sayilari + paketin `empty` hukmu, | ||
| 206 | + "belge neden bos" sorusu log'dan da cevaplanabilsin diye. | ||
| 207 | + | ||
| 208 | +### Redler (backend'in HTTP durumuna eslemesi icin) | ||
| 209 | + | ||
| 210 | +| Kod | Ne zaman | Onerilen esleme | | ||
| 211 | +|---|---|---| | ||
| 212 | +| `bad_request` | Sozlesmeye uymayan payload: sunulmayan/bilinmeyen `kind`, bozuk `run_day`, liste olmayan satir alani, cerceveyle celisen okul | 400 | | ||
| 213 | +| `insufficient_rows` | Dort liste de bos: uretilecek belge yok; bos belge cevap degildir | 404/409 -- ekran kendi "yetersiz veri" durumunu gostersin | | ||
| 214 | +| `document_too_large` | HTML 4 MiB'i asiyor (cerceve kapagi 8 MiB) | 413 | | ||
| 215 | +| `internal` | Paket belgeyi kuramadi ya da cizemedi | 500/502 | | ||
| 216 | + | ||
| 217 | +### Bugunun sinirlari | ||
| 218 | + | ||
| 219 | +- **Dort rapor tipinden yalniz `okul` sunulur.** `ogrenci` / `ogretmen` / | ||
| 220 | + `ham` icin istek sozlesmesi yok (payload `student`, `teacher` ve | ||
| 221 | + `question_segment` tasimaz); istek gelirse `bad_request` doner ve yarim | ||
| 222 | + belge uretilmez. | ||
| 223 | +- **Kapatilmis tavsiyeler.** Paketin kapatma kapisi satirda `dismissed_at` | ||
| 224 | + arar; backend'in `RecommendationRow`'u alani tasimaz (kapatma yazimi bugun | ||
| 225 | + hic yok). Kapatma ozelligi gelirse ya okunan satir `dismissed_at` tasimali | ||
| 226 | + ya backend kapatilmis satirlari gondermemeli -- yoksa kapatilmis kart | ||
| 227 | + rapora geri duser. | ||
| 228 | +- **HTML siniri 4 MiB** (`AI_MAX_FRAME_BYTES // 2`): belge cevap cercevesinin | ||
| 229 | + icinde gider ve JSON kacislarina da yer kalmali. | ||
| 230 | + | ||
| 231 | +--- | ||
| 232 | + | ||
| 150 | ## Madde 2 -- Izin listesine sinav yollarinin eklenmesi | 233 | ## Madde 2 -- Izin listesine sinav yollarinin eklenmesi |
| 151 | 234 | ||
| 152 | ### Ne isteniyor | 235 | ### Ne isteniyor |
| @@ -298,6 +381,7 @@ Yani kapsam **elle** tutulur. | |||
| 298 | | 1 | Dokuz `insight.*` operasyonu (yazma + liste + supurme) **ve** `insight.student` / `insight.class` / `insight.refresh` sabitleri + dagitim kodu | `src/constant.rs`, `src/ai/` | ZEKA satirlarini **yazamaz** (gece kosusu `partial`); backend ZEKA'yi **hic cagiramaz**, istege bagli her senaryo duser. Sahibi: `InsightDoors`. **Durum 2026-09-18: student + refresh ACILDI; sinif hala acik (Madde 3).** | | 381 | | 1 | Dokuz `insight.*` operasyonu (yazma + liste + supurme) **ve** `insight.student` / `insight.class` / `insight.refresh` sabitleri + dagitim kodu | `src/constant.rs`, `src/ai/` | ZEKA satirlarini **yazamaz** (gece kosusu `partial`); backend ZEKA'yi **hic cagiramaz**, istege bagli her senaryo duser. Sahibi: `InsightDoors`. **Durum 2026-09-18: student + refresh ACILDI; sinif hala acik (Madde 3).** | |
| 299 | | 2 | 9 sinav yolu (+3 sinif/ders yolu) izin listesine | `src/constant.rs:656-676` | **Madde analizi, konu karnesi, sinif isi haritasi** hic uretilemez | | 382 | | 2 | 9 sinav yolu (+3 sinif/ders yolu) izin listesine | `src/constant.rs:656-676` | **Madde analizi, konu karnesi, sinif isi haritasi** hic uretilemez | |
| 300 | | 3 | `GET /users/search` izin listesine (okul listesi Madde 1a'da) | `src/constant.rs:656-676` | Ogrenci kadrosu elle tutulur; yeni ogrenci **sessizce** gorunmez | | 383 | | 3 | `GET /users/search` izin listesine (okul listesi Madde 1a'da) | `src/constant.rs:656-676` | Ogrenci kadrosu elle tutulur; yeni ogrenci **sessizce** gorunmez | |
| 384 | +| 4 | `insight.report` dagitim kapisi: backend kendi `zeka_*` satirlarini okuyup gondersin (bkz. `## insight.report`) | `src/ai/`, `src/constant.rs`, `src/web/` | Okul raporu **belgesi** uretilemez; servis tarafi hazir (2026-09-18) | | ||
| 301 | 385 | ||
| 302 | --- | 386 | --- |
| 303 | 387 | ||
service/docs/CIKTI-SOZLESMESI.mdmodified+6 -2
| @@ -419,5 +419,9 @@ bu tuzak yapısal olarak imkânsızdır. | |||
| 419 | 2026-09-18'de `insight.student` + `insight.refresh` için açıldı** ve servis | 419 | 2026-09-18'de `insight.student` + `insight.refresh` için açıldı** ve servis |
| 420 | tarafı aynı gün bağlandı (`service/src/handlers.py`; ilan ile dağıtım | 420 | tarafı aynı gün bağlandı (`service/src/handlers.py`; ilan ile dağıtım |
| 421 | açılışta `verify_dispatchable()` ile denetlenir). `insight.class` ilan | 421 | açılışta `verify_dispatchable()` ile denetlenir). `insight.class` ilan |
| 422 | - edilir ama gönderilmez: kadro listeleme yolu yok. Sahibi backend'deki | 422 | + edilir ama gönderilmez: kadro listeleme yolu yok. **`insight.report` |
| 423 | - `InsightDoors` hattı — `docs/BACKEND-GEREKSINIMLERI.md` Madde 1. | 423 | + (okul raporu BELGESİ) servis tarafında aynı gün hazır** — belgeyi |
| 424 | + backend'in gönderdiği satırlardan üretir; backend'in dağıtım tablosuna | ||
| 425 | + girmesi bekleniyor (`docs/BACKEND-GEREKSINIMLERI.md` `## insight.report`). | ||
| 426 | + Sahibi backend'deki `InsightDoors` hattı — `docs/BACKEND-GEREKSINIMLERI.md` | ||
| 427 | + Madde 1. | ||
service/src/capabilities.pymodified+81 -1
| @@ -10,6 +10,10 @@ IKI YON VARDIR; karistirilmamalidir: | |||
| 10 | never dispatched: its request names a course, and the bridge's read | 10 | never dispatched: its request names a course, and the bridge's read |
| 11 | allowlist hands a service no roster to enumerate it with | 11 | allowlist hands a service no roster to enumerate it with |
| 12 | (`ai/insight.rs` module docs; `docs/BACKEND-GEREKSINIMLERI.md` item 3). | 12 | (`ai/insight.rs` module docs; `docs/BACKEND-GEREKSINIMLERI.md` item 3). |
| 13 | + `insight.report` is the fourth name and the one whose answer is a DOCUMENT: | ||
| 14 | + the backend reads its own `zeka_*` rows and dispatches them, and the service | ||
| 15 | + renders the school report from them without reading anything itself | ||
| 16 | + (`docs/BACKEND-GEREKSINIMLERI.md`, `## insight.report`). | ||
| 13 | Routing is an EXACT match (`ai/protocol.rs:91-94`): every advertised name | 17 | Routing is an EXACT match (`ai/protocol.rs:91-94`): every advertised name |
| 14 | gets its handler from `handlers.wire()`, and `verify_dispatchable()` checks | 18 | gets its handler from `handlers.wire()`, and `verify_dispatchable()` checks |
| 15 | the pair at startup -- if advertising and dispatch ever drift apart, the | 19 | the pair at startup -- if advertising and dispatch ever drift apart, the |
| @@ -57,7 +61,21 @@ INSIGHT_CLASS = "insight.class" | |||
| 57 | INSIGHT_REFRESH = "insight.refresh" | 61 | INSIGHT_REFRESH = "insight.refresh" |
| 58 | """Bir okul icin hesaplari yeniden kosturur; parti isidir.""" | 62 | """Bir okul icin hesaplari yeniden kosturur; parti isidir.""" |
| 59 | 63 | ||
| 60 | -NAMES: tuple[str, ...] = (INSIGHT_STUDENT, INSIGHT_CLASS, INSIGHT_REFRESH) | 64 | +INSIGHT_REPORT = "insight.report" |
| 65 | +"""Verilen satirlardan okul raporu BELGESI uretir. | ||
| 66 | + | ||
| 67 | +Tek `insight.*` isleyicisi ki koprudan HICBIR SEY okumaz: satirlar payload'da | ||
| 68 | +gelir (backend kendi `zeka_*` tablolarindan okur), servis yalniz render eder. | ||
| 69 | +Istek/cevap sozlesmesi: `ReportRequest` / `ReportResponse` ve | ||
| 70 | +`docs/BACKEND-GEREKSINIMLERI.md` `## insight.report`. | ||
| 71 | +""" | ||
| 72 | + | ||
| 73 | +NAMES: tuple[str, ...] = ( | ||
| 74 | + INSIGHT_STUDENT, | ||
| 75 | + INSIGHT_CLASS, | ||
| 76 | + INSIGHT_REFRESH, | ||
| 77 | + INSIGHT_REPORT, | ||
| 78 | +) | ||
| 61 | 79 | ||
| 62 | 80 | ||
| 63 | #: The capability names the backend can send a `Request` FOR -- the half of | 81 | #: The capability names the backend can send a `Request` FOR -- the half of |
| @@ -67,6 +85,12 @@ NAMES: tuple[str, ...] = (INSIGHT_STUDENT, INSIGHT_CLASS, INSIGHT_REFRESH) | |||
| 67 | #: `ai/insight.rs::compute_student/refresh` + the `web/insights.rs` doors | 85 | #: `ai/insight.rs::compute_student/refresh` + the `web/insights.rs` doors |
| 68 | #: (insight.student, insight.refresh; merged 2026-09-18). `insight.class` is | 86 | #: (insight.student, insight.refresh; merged 2026-09-18). `insight.class` is |
| 69 | #: NOT in the set: the constant exists, the code that would send it does not. | 87 | #: NOT in the set: the constant exists, the code that would send it does not. |
| 88 | +#: `insight.report` is NOT in it either, for the same reason and one more: the | ||
| 89 | +#: service side is READY (advertised + `handlers.report`), but the backend's | ||
| 90 | +#: dispatch table carries no `insight.report` yet (`hezarfen_backend/src` has | ||
| 91 | +#: no such name as of 2026-09-18). When that door lands, three edits move | ||
| 92 | +#: together: this tuple, the pin in `tests/test_capabilities.py`, and the | ||
| 93 | +#: status line of `docs/BACKEND-GEREKSINIMLERI.md` `## insight.report`. | ||
| 70 | #: `tests/test_capabilities.py` pins this. | 94 | #: `tests/test_capabilities.py` pins this. |
| 71 | BACKEND_CALLABLE_CAPABILITIES: tuple[str, ...] = ( | 95 | BACKEND_CALLABLE_CAPABILITIES: tuple[str, ...] = ( |
| 72 | "chat.reply", | 96 | "chat.reply", |
| @@ -159,11 +183,67 @@ class RefreshResponse(TypedDict, total=False): | |||
| 159 | status: str | 183 | status: str |
| 160 | 184 | ||
| 161 | 185 | ||
| 186 | +class ReportRequest(TypedDict, total=False): | ||
| 187 | + """`insight.report` istek payload'i -- backend'in okudugu satirlar. | ||
| 188 | + | ||
| 189 | + Satirlar backend'in KENDI yapilaridir (`db/insight.rs` `SummaryRow`, | ||
| 190 | + `RecommendationRow`, `ProfileRow`, `RunRow`): ZEKA'nin depo yoluyla | ||
| 191 | + yazdigi bicimin aynisi, yani ikinci bir esleme yok. Satirlarda `school` | ||
| 192 | + YOKTUR -- ZEKA onu hic yazmaz; cercevede gelir ve isleyici her satira | ||
| 193 | + damgalar (tek kimlik kaynagi). Payload'daki `school` yalniz GORUNUM icin | ||
| 194 | + (`name` baslikta); `slug` cerceveyle celisirse istek reddedilir. | ||
| 195 | + """ | ||
| 196 | + | ||
| 197 | + kind: str | ||
| 198 | + """Sunulan tek tip: `okul` (bkz. `handlers._SERVED_REPORT_KINDS`).""" | ||
| 199 | + run_day: str | ||
| 200 | + """`YYYY-MM-DD` (TR gunu); yoksa en yeni kosu satirindan turetilir.""" | ||
| 201 | + requested_by: str | ||
| 202 | + """Belgeyi isteyen mudur. Okuma yapilmadigi icin yalniz log'a yazilir.""" | ||
| 203 | + school: dict[str, Any] | ||
| 204 | + """`{"id": ..., "slug": ..., "name": ...}` -- `name` belge basligidir.""" | ||
| 205 | + summaries: list[dict[str, Any]] | ||
| 206 | + """`zeka_student_summary` satirlari; `attention` listesi DAHIL (personel | ||
| 207 | + raporunun dikkat tablosunu besleyen tek alan odur).""" | ||
| 208 | + recommendations: list[dict[str, Any]] | ||
| 209 | + """`zeka_recommendation` satirlari (kapatilan/suresi gecen satirlar | ||
| 210 | + backend tarafindan suzulmezse paket onlari yine gostermez -- ama | ||
| 211 | + `dismissed_at` satirda yoksa kapi bunu goremez; bkz. docs).""" | ||
| 212 | + profiles: list[dict[str, Any]] | ||
| 213 | + """`zeka_student_segment_profile` satirlari.""" | ||
| 214 | + runs: list[dict[str, Any]] | ||
| 215 | + """`zeka_run` satirlari; `run_day` alani belgenin gununu verir.""" | ||
| 216 | + | ||
| 217 | + | ||
| 218 | +class ReportResponse(TypedDict, total=False): | ||
| 219 | + """`insight.report` cevap payload'i (`handlers.report` doldurur). | ||
| 220 | + | ||
| 221 | + Tek `insight.*` cevabi ki BELGENIN KENDISINI tasir: blob yuklemesi yok, | ||
| 222 | + depo yok. Degerler: `bad_request` (sozlesmeye uymayan payload), | ||
| 223 | + `insufficient_rows` (dort liste de bos -- belge uretilecek satir yok), | ||
| 224 | + `document_too_large` (HTML `_MAX_HTML_BYTES` ustunde; KESILMEZ, reddedilir), | ||
| 225 | + `internal` (paket kurulamadi/cizilemedi). | ||
| 226 | + """ | ||
| 227 | + | ||
| 228 | + kind: str | ||
| 229 | + run_day: str # belgenin gunu: istekten aynen, yoksa turetildi | ||
| 230 | + format: str # bugun her zaman "html" | ||
| 231 | + html: str # tek dosyalik, kendi kendine yeten belge | ||
| 232 | + byte_size: int # `html`in UTF-8 bayt uzunlugu | ||
| 233 | + truncated: bool # her zaman False: sinir asilirsa reddedilir, kesilmez | ||
| 234 | + notes: list[str] # paketin kendi kapsam/sinir cumleleri (report.notes) | ||
| 235 | + #: Sozlesme disi ek alan (refresh'in `status`u gibi: serde yok sayar): | ||
| 236 | + #: satir sayilari + paketin `empty` hukmu. "Belge neden bos" sorusunu | ||
| 237 | + #: log'dan cevaplamak icin. | ||
| 238 | + coverage: dict[str, Any] | ||
| 239 | + | ||
| 240 | + | ||
| 162 | #: Yetenek adi -> (istek tipi, cevap tipi). Belge ve dogrulama icin. | 241 | #: Yetenek adi -> (istek tipi, cevap tipi). Belge ve dogrulama icin. |
| 163 | SCHEMAS: dict[str, tuple[type, type]] = { | 242 | SCHEMAS: dict[str, tuple[type, type]] = { |
| 164 | INSIGHT_STUDENT: (StudentRequest, StudentResponse), | 243 | INSIGHT_STUDENT: (StudentRequest, StudentResponse), |
| 165 | INSIGHT_CLASS: (ClassRequest, ClassResponse), | 244 | INSIGHT_CLASS: (ClassRequest, ClassResponse), |
| 166 | INSIGHT_REFRESH: (RefreshRequest, RefreshResponse), | 245 | INSIGHT_REFRESH: (RefreshRequest, RefreshResponse), |
| 246 | + INSIGHT_REPORT: (ReportRequest, ReportResponse), | ||
| 167 | } | 247 | } |
| 168 | 248 | ||
| 169 | 249 | ||
service/src/handlers.pymodified+206 -2
| @@ -1,4 +1,4 @@ | |||
| 1 | -"""The three `insight.*` capabilities the service serves to the backend. | 1 | +"""The four `insight.*` capabilities the service serves to the backend. |
| 2 | 2 | ||
| 3 | `capabilities.py` owns the wire names and the dispatch table but registers no | 3 | `capabilities.py` owns the wire names and the dispatch table but registers no |
| 4 | handler: the table is the contract, this module is the product. `wire()` fills | 4 | handler: the table is the contract, this module is the product. `wire()` fills |
| @@ -12,6 +12,9 @@ with an empty table behind them, so every `insight.student` / | |||
| 12 | Why the handlers live outside `capabilities.py`: the table must stay | 12 | Why the handlers live outside `capabilities.py`: the table must stay |
| 13 | importable without the compute stack. A handler, on the other hand, is the | 13 | importable without the compute stack. A handler, on the other hand, is the |
| 14 | whole stack -- a `Source` read, `pipeline.run_school`, and the store writes. | 14 | whole stack -- a `Source` read, `pipeline.run_school`, and the store writes. |
| 15 | +`report` is that rule's one exception: it reads nothing at all (its rows arrive | ||
| 16 | +in the payload), but it belongs to the same table and answers from the same | ||
| 17 | +package, so it lives here with its siblings. | ||
| 15 | 18 | ||
| 16 | Handlers are coroutines on purpose. `bridge.BridgeProtocol._handle()` awaits a | 19 | Handlers are coroutines on purpose. `bridge.BridgeProtocol._handle()` awaits a |
| 17 | coroutine handler in the event loop and pushes only *sync* handlers into the | 20 | coroutine handler in the event loop and pushes only *sync* handlers into the |
| @@ -35,9 +38,12 @@ from typing import Any, Callable | |||
| 35 | from . import capabilities | 38 | from . import capabilities |
| 36 | from . import config | 39 | from . import config |
| 37 | from .compute import attention as attention_mod | 40 | from .compute import attention as attention_mod |
| 41 | +from .compute import clock | ||
| 38 | from .compute import marks as marks_mod | 42 | from .compute import marks as marks_mod |
| 39 | from .pipeline import StudentOutcome, run_school | 43 | from .pipeline import StudentOutcome, run_school |
| 40 | -from .protocol import CapabilityError | 44 | +from .protocol import AI_MAX_FRAME_BYTES, CapabilityError |
| 45 | +from .report import MemoryReader, build_report, load_bundle | ||
| 46 | +from .report import render as report_render | ||
| 41 | from .source import NOT_PERMITTED | 47 | from .source import NOT_PERMITTED |
| 42 | from .store import attention_items, recommendation_rows | 48 | from .store import attention_items, recommendation_rows |
| 43 | 49 | ||
| @@ -154,6 +160,7 @@ def wire() -> None: | |||
| 154 | capabilities.register(capabilities.INSIGHT_STUDENT, student) | 160 | capabilities.register(capabilities.INSIGHT_STUDENT, student) |
| 155 | capabilities.register(capabilities.INSIGHT_CLASS, klass) | 161 | capabilities.register(capabilities.INSIGHT_CLASS, klass) |
| 156 | capabilities.register(capabilities.INSIGHT_REFRESH, refresh) | 162 | capabilities.register(capabilities.INSIGHT_REFRESH, refresh) |
| 163 | + capabilities.register(capabilities.INSIGHT_REPORT, report) | ||
| 157 | 164 | ||
| 158 | 165 | ||
| 159 | def _lock_for(school: str) -> asyncio.Lock: | 166 | def _lock_for(school: str) -> asyncio.Lock: |
| @@ -528,10 +535,207 @@ async def refresh(school: str, payload: dict[str, Any]) -> dict[str, Any]: | |||
| 528 | } | 535 | } |
| 529 | 536 | ||
| 530 | 537 | ||
| 538 | +# --------------------------------------------------------------------------- | ||
| 539 | +# insight.report -- the school report DOCUMENT | ||
| 540 | +# --------------------------------------------------------------------------- | ||
| 541 | + | ||
| 542 | +#: The report kinds this capability serves. The package has four | ||
| 543 | +#: (`report.gate.REPORT_TYPES`), but only `okul` has a request contract: the | ||
| 544 | +#: payload carries four row lists and neither a `student`, a `teacher` nor the | ||
| 545 | +#: `question_segment` rows (`ogrenci`/`ogretmen`/`ham` would need them), so the | ||
| 546 | +#: other three are refused BY NAME rather than answered half-built. | ||
| 547 | +_SERVED_REPORT_KINDS: tuple[str, ...] = ("okul",) | ||
| 548 | + | ||
| 549 | +#: The payload's four row lists and the `MemoryReader` table each maps to. The | ||
| 550 | +#: keys are the backend's (`db/insight.rs` row structs, one list each); the | ||
| 551 | +#: tables are the report package's own read surface (`report/reader.py`). The | ||
| 552 | +#: mapping is total and one-way: no payload row is ever reshaped. | ||
| 553 | +_REPORT_ROWS: tuple[tuple[str, str], ...] = ( | ||
| 554 | + ("summaries", "student_summary"), | ||
| 555 | + ("recommendations", "recommendation"), | ||
| 556 | + ("profiles", "student_segment_profile"), | ||
| 557 | + ("runs", "insight_run"), | ||
| 558 | +) | ||
| 559 | + | ||
| 560 | +#: The HTML byte cap: half of the frame cap, because the document rides INSIDE | ||
| 561 | +#: the JSON response frame (`AI_MAX_FRAME_BYTES` counts all of it). A document | ||
| 562 | +#: over the cap is REFUSED, never truncated: a half-written HTML file is not a | ||
| 563 | +#: readable document, and the download behind it would be silently broken. | ||
| 564 | +_MAX_HTML_BYTES = AI_MAX_FRAME_BYTES // 2 | ||
| 565 | + | ||
| 566 | + | ||
| 567 | +def _report_school(frame_school: str, payload: dict[str, Any]) -> str: | ||
| 568 | + """The value every row is stamped with -- and the document's own school. | ||
| 569 | + | ||
| 570 | + The frame's `school` is the tenant identity; `payload.school.name` is the | ||
| 571 | + DISPLAY name the report title carries. A payload whose `school.slug` | ||
| 572 | + disagrees with the frame is refused: two identity sources is how another | ||
| 573 | + school's rows reach a document. | ||
| 574 | + """ | ||
| 575 | + info = payload.get("school") | ||
| 576 | + if info is None: | ||
| 577 | + return frame_school | ||
| 578 | + if not isinstance(info, dict): | ||
| 579 | + raise CapabilityError("bad_request", "'school' bir nesne olmali") | ||
| 580 | + slug = info.get("slug") | ||
| 581 | + if isinstance(slug, str) and slug.strip() and slug.strip() != frame_school: | ||
| 582 | + raise CapabilityError( | ||
| 583 | + "bad_request", | ||
| 584 | + f"payload'daki school.slug ({slug!r}) cercevedeki okulla " | ||
| 585 | + f"({frame_school!r}) ayni degil", | ||
| 586 | + ) | ||
| 587 | + name = info.get("name") | ||
| 588 | + if isinstance(name, str) and name.strip(): | ||
| 589 | + return name.strip() | ||
| 590 | + return frame_school | ||
| 591 | + | ||
| 592 | + | ||
| 593 | +def _report_tables( | ||
| 594 | + payload: dict[str, Any], school: str, frame_school: str | ||
| 595 | +) -> dict[str, list[dict[str, Any]]]: | ||
| 596 | + """The payload's four lists as `MemoryReader` tables, `school` stamped. | ||
| 597 | + | ||
| 598 | + Rows do NOT carry `school` (ZEKA never wrote one; the frame carries it), so | ||
| 599 | + the stamp is added here -- and a row that claims a DIFFERENT school is a | ||
| 600 | + refusal, not an overwrite: that is the cross-tenant shape this seam exists | ||
| 601 | + to make impossible. | ||
| 602 | + """ | ||
| 603 | + tables: dict[str, list[dict[str, Any]]] = {} | ||
| 604 | + for key, table in _REPORT_ROWS: | ||
| 605 | + rows = payload.get(key) | ||
| 606 | + if rows is None: | ||
| 607 | + tables[table] = [] | ||
| 608 | + continue | ||
| 609 | + if not isinstance(rows, list) or any( | ||
| 610 | + not isinstance(row, dict) for row in rows | ||
| 611 | + ): | ||
| 612 | + raise CapabilityError("bad_request", f"'{key}' bir nesne listesi olmali") | ||
| 613 | + stamped: list[dict[str, Any]] = [] | ||
| 614 | + for row in rows: | ||
| 615 | + claimed = row.get("school") | ||
| 616 | + if ( | ||
| 617 | + isinstance(claimed, str) | ||
| 618 | + and claimed.strip() | ||
| 619 | + and claimed.strip() not in (school, frame_school) | ||
| 620 | + ): | ||
| 621 | + raise CapabilityError( | ||
| 622 | + "bad_request", | ||
| 623 | + f"'{key}' satiri baska bir okul tasiyor ({claimed!r}); " | ||
| 624 | + f"cerceve {frame_school!r}", | ||
| 625 | + ) | ||
| 626 | + stamped.append({**row, "school": school}) | ||
| 627 | + tables[table] = stamped | ||
| 628 | + return tables | ||
| 629 | + | ||
| 630 | + | ||
| 631 | +def _report_run_day(value: Any, runs: list[dict[str, Any]], now_ms: int) -> str: | ||
| 632 | + """The document's day: the request's `run_day`, else the newest run's. | ||
| 633 | + | ||
| 634 | + `insight_run.run_day` is the TR day ZEKA wrote (`store.run_row`); no run | ||
| 635 | + row at all (a report asked for before the first sweep) falls back to | ||
| 636 | + `generated_at`'s TR day -- the day the document was made, not an invented | ||
| 637 | + one. | ||
| 638 | + """ | ||
| 639 | + if value is not None: | ||
| 640 | + day = value.strip() if isinstance(value, str) else "" | ||
| 641 | + try: | ||
| 642 | + datetime.strptime(day, "%Y-%m-%d") | ||
| 643 | + except ValueError as exc: | ||
| 644 | + raise CapabilityError( | ||
| 645 | + "bad_request", f"'run_day' 'YYYY-MM-DD' biciminde olmali: {value!r}" | ||
| 646 | + ) from exc | ||
| 647 | + return day | ||
| 648 | + newest, at = "", -1 | ||
| 649 | + for row in runs: | ||
| 650 | + day = row.get("run_day") | ||
| 651 | + started = int(row.get("started_at") or 0) | ||
| 652 | + if isinstance(day, str) and day.strip() and started >= at: | ||
| 653 | + newest, at = day.strip(), started | ||
| 654 | + return newest or clock.tr_date_key(now_ms) | ||
| 655 | + | ||
| 656 | + | ||
| 657 | +async def report(school: str, payload: dict[str, Any]) -> dict[str, Any]: | ||
| 658 | + """`insight.report` -- the school report DOCUMENT, from rows sent to it. | ||
| 659 | + | ||
| 660 | + The one `insight.*` handler that reads NOTHING over the bridge: the backend | ||
| 661 | + reads its own `zeka_*` tables and dispatches those rows, and the service | ||
| 662 | + only renders them -- no store, no database (standing rule). `requested_by` | ||
| 663 | + is the backend's authenticated manager; with no read to run as anybody it | ||
| 664 | + is logged, not resolved into `on_behalf_of`. | ||
| 665 | + | ||
| 666 | + Refusals, all typed for the backend to map: `bad_request` (a payload this | ||
| 667 | + contract cannot read, or a kind this capability does not serve), | ||
| 668 | + `insufficient_rows` (all four lists empty: there is nothing to render, and | ||
| 669 | + an empty document is not an answer -- the caller states that in its own | ||
| 670 | + words), `document_too_large` (over `_MAX_HTML_BYTES`; never truncated), | ||
| 671 | + `internal` (the report package could not build or render the document). | ||
| 672 | + """ | ||
| 673 | + kind = capabilities.require_text(payload, "kind") | ||
| 674 | + if kind not in _SERVED_REPORT_KINDS: | ||
| 675 | + raise CapabilityError( | ||
| 676 | + "bad_request", | ||
| 677 | + f"'{kind}' bu yetenekte sunulmuyor (sunulan: " | ||
| 678 | + f"{', '.join(_SERVED_REPORT_KINDS)}); paketin diger tipleri icin " | ||
| 679 | + "istek sozlesmesi yok", | ||
| 680 | + ) | ||
| 681 | + now_ms = _now_ms() | ||
| 682 | + display = _report_school(school, payload) | ||
| 683 | + tables = _report_tables(payload, display, school) | ||
| 684 | + total = sum(len(rows) for rows in tables.values()) | ||
| 685 | + if total == 0: | ||
| 686 | + raise CapabilityError( | ||
| 687 | + "insufficient_rows", | ||
| 688 | + "'summaries', 'recommendations', 'profiles', 'runs' listelerinin " | ||
| 689 | + "hepsi bos: belge uretilecek satir yok", | ||
| 690 | + ) | ||
| 691 | + run_day = _report_run_day(payload.get("run_day"), tables["insight_run"], now_ms) | ||
| 692 | + reader = MemoryReader(tables) | ||
| 693 | + try: | ||
| 694 | + bundle = await load_bundle(reader, display, kind, now_ms=now_ms) | ||
| 695 | + document = build_report(kind, bundle) | ||
| 696 | + html = report_render.to_html(document) | ||
| 697 | + except Exception as exc: # the refusal IS the contract: no half document | ||
| 698 | + raise CapabilityError("internal", f"rapor uretilemedi: {exc}") from exc | ||
| 699 | + encoded = html.encode("utf-8") | ||
| 700 | + if len(encoded) > _MAX_HTML_BYTES: | ||
| 701 | + raise CapabilityError( | ||
| 702 | + "document_too_large", | ||
| 703 | + f"belge {len(encoded)} bayt, sinir {_MAX_HTML_BYTES} " | ||
| 704 | + f"(cerceve kapagi {AI_MAX_FRAME_BYTES}); kesmek yerine reddedilir", | ||
| 705 | + ) | ||
| 706 | + who = payload.get("requested_by") | ||
| 707 | + config.log( | ||
| 708 | + "info", | ||
| 709 | + f"insight.report: belge uretildi (okul={school}, tip={kind}, " | ||
| 710 | + f"satir={total}, bayt={len(encoded)}, isteyen=" | ||
| 711 | + f"{who.strip() if isinstance(who, str) and who.strip() else '-'})", | ||
| 712 | + ) | ||
| 713 | + return { | ||
| 714 | + "kind": kind, | ||
| 715 | + "run_day": run_day, | ||
| 716 | + "format": "html", | ||
| 717 | + "html": html, | ||
| 718 | + "byte_size": len(encoded), | ||
| 719 | + # Always False today: an over-cap document is refused above, never cut. | ||
| 720 | + # The field exists because the backend's struct carries it. | ||
| 721 | + "truncated": False, | ||
| 722 | + "notes": list(document.notes), | ||
| 723 | + # Beyond the backend's struct, which ignores what it does not read | ||
| 724 | + # (the same shape as `refresh`'s `status`): raw row counts per payload | ||
| 725 | + # list and the package's own `empty` verdict, so "why is the document | ||
| 726 | + # empty" is answerable from the log line and from the answer. | ||
| 727 | + "coverage": { | ||
| 728 | + "rows": {key: len(tables[table]) for key, table in _REPORT_ROWS}, | ||
| 729 | + "empty": document.empty, | ||
| 730 | + }, | ||
| 731 | + } | ||
| 732 | + | ||
| 733 | + | ||
| 531 | __all__ = [ | 734 | __all__ = [ |
| 532 | "bind_source", | 735 | "bind_source", |
| 533 | "klass", | 736 | "klass", |
| 534 | "refresh", | 737 | "refresh", |
| 738 | + "report", | ||
| 535 | "student", | 739 | "student", |
| 536 | "wire", | 740 | "wire", |
| 537 | ] | 741 | ] |
service/tests/test_capabilities.pymodified+12 -6
| @@ -20,7 +20,7 @@ class CapabilityNameTests(unittest.TestCase): | |||
| 20 | def test_declared_names(self): | 20 | def test_declared_names(self): |
| 21 | self.assertEqual( | 21 | self.assertEqual( |
| 22 | capabilities.NAMES, | 22 | capabilities.NAMES, |
| 23 | - ("insight.student", "insight.class", "insight.refresh"), | 23 | + ("insight.student", "insight.class", "insight.refresh", "insight.report"), |
| 24 | ) | 24 | ) |
| 25 | 25 | ||
| 26 | def test_backend_callable_set_is_the_dispatch_table(self): | 26 | def test_backend_callable_set_is_the_dispatch_table(self): |
| @@ -31,11 +31,14 @@ class CapabilityNameTests(unittest.TestCase): | |||
| 31 | ("chat.reply", "rag.index", "insight.student", "insight.refresh"), | 31 | ("chat.reply", "rag.index", "insight.student", "insight.refresh"), |
| 32 | ) | 32 | ) |
| 33 | # `insight.class` ilan edilir ama backend GONDERMEZ (kadro listeleme | 33 | # `insight.class` ilan edilir ama backend GONDERMEZ (kadro listeleme |
| 34 | - # yolu yok). Backend tarafi acildiginda bu satiri ve | 34 | + # yolu yok). `insight.report` da ayni: servis tarafi HAZIR (ilan + |
| 35 | - # docs/BACKEND-GEREKSINIMLERI.md madde 1'i birlikte guncelleyin. | 35 | + # handlers.report) ama backend'in dagitim tablosunda adi yok |
| 36 | + # (hezarfen_backend/src, 2026-09-18). Backend tarafi acildiginda bu | ||
| 37 | + # satiri ve docs/BACKEND-GEREKSINIMLERI.md `## insight.report`i | ||
| 38 | + # birlikte guncelleyin. | ||
| 36 | self.assertEqual( | 39 | self.assertEqual( |
| 37 | set(capabilities.NAMES) - set(capabilities.BACKEND_CALLABLE_CAPABILITIES), | 40 | set(capabilities.NAMES) - set(capabilities.BACKEND_CALLABLE_CAPABILITIES), |
| 38 | - {"insight.class"}, | 41 | + {"insight.class", "insight.report"}, |
| 39 | ) | 42 | ) |
| 40 | 43 | ||
| 41 | def test_sections_vocabulary_is_the_summary_modules(self): | 44 | def test_sections_vocabulary_is_the_summary_modules(self): |
| @@ -104,8 +107,11 @@ class DispatchTests(unittest.TestCase): | |||
| 104 | # 2) ... depo yolunu (2. yon) kapsamadigi ... | 107 | # 2) ... depo yolunu (2. yon) kapsamadigi ... |
| 105 | self.assertIn("servis->backend depo yolu: kopru/insight.*", text) | 108 | self.assertIn("servis->backend depo yolu: kopru/insight.*", text) |
| 106 | # 3) ... ve ilan edilen her adin bir isleyicisi oldugu. | 109 | # 3) ... ve ilan edilen her adin bir isleyicisi oldugu. |
| 107 | - self.assertIn("servis tarafi isleyiciler: 3/3 kayitli", text) | 110 | + self.assertIn("servis tarafi isleyiciler: 4/4 kayitli", text) |
| 108 | - self.assertIn("backend'in dagitim tablosunda olmayan: insight.class", text) | 111 | + self.assertIn( |
| 112 | + "backend'in dagitim tablosunda olmayan: insight.class, insight.report", | ||
| 113 | + text, | ||
| 114 | + ) | ||
| 109 | # Eski hali "TANIMSIZ" diyordu ve isleyici kayitliyken bile servisin | 115 | # Eski hali "TANIMSIZ" diyordu ve isleyici kayitliyken bile servisin |
| 110 | # bir sey yapmadigini ima ediyordu. | 116 | # bir sey yapmadigini ima ediyordu. |
| 111 | self.assertNotIn("TANIMSIZ", text) | 117 | self.assertNotIn("TANIMSIZ", text) |
service/tests/test_handlers.pymodified+2 -1
| @@ -92,7 +92,8 @@ class FailPreFixTests(HandlerTestCase): | |||
| 92 | capabilities.verify_dispatchable() | 92 | capabilities.verify_dispatchable() |
| 93 | self.assertIn("insight.class", str(caught.exception)) | 93 | self.assertIn("insight.class", str(caught.exception)) |
| 94 | self.assertEqual( | 94 | self.assertEqual( |
| 95 | - capabilities.dispatchable_names(), ["insight.student", "insight.refresh"] | 95 | + capabilities.dispatchable_names(), |
| 96 | + ["insight.student", "insight.refresh", "insight.report"], | ||
| 96 | ) | 97 | ) |
| 97 | 98 | ||
| 98 | handlers.wire() | 99 | handlers.wire() |
service/tests/test_report_capability.pyadded+395 -0
| @@ -0,0 +1,395 @@ | |||
| 1 | +"""`insight.report` -- the school report document, end to end over the table. | ||
| 2 | + | ||
| 3 | +What is proven here, in the order it matters: | ||
| 4 | + | ||
| 5 | +1. The fail-pre-fix fact, for the fourth served name: with an empty handler | ||
| 6 | + table the dispatch answers `unknown_capability`; `handlers.wire()` makes the | ||
| 7 | + same call reach a real handler, and the boot self-check counts the name | ||
| 8 | + dispatchable -- and refuses to boot when it is not. | ||
| 9 | +2. The whole point of the seam: row lists shaped EXACTLY like what the backend | ||
| 10 | + sends -- built here by the very writers that wrote them in production | ||
| 11 | + (`store.summary_rows` / `recommendation_rows` / `profile_rows` / `run_row`), | ||
| 12 | + with NO `school` key anywhere (ZEKA never wrote one; the frame carries it) -- | ||
| 13 | + render the school report HTML: the display name, the student count, the | ||
| 14 | + per-student attention lines, and only the roles the `okul` report may show. | ||
| 15 | +3. Refusals are typed and leave no half-built document behind: an empty row set | ||
| 16 | + (`insufficient_rows`), an unserved kind or a payload that breaks the contract | ||
| 17 | + (`bad_request`), a package failure (`internal`), an over-cap document | ||
| 18 | + (`document_too_large`) -- never a truncated HTML file. | ||
| 19 | +""" | ||
| 20 | + | ||
| 21 | +from __future__ import annotations | ||
| 22 | + | ||
| 23 | +import time | ||
| 24 | +import unittest | ||
| 25 | +from typing import Any | ||
| 26 | +from unittest.mock import patch | ||
| 27 | + | ||
| 28 | +from src import capabilities, handlers, protocol | ||
| 29 | +from src.compute import clock | ||
| 30 | +from src.compute.model import ( | ||
| 31 | + Audience, | ||
| 32 | + Confidence, | ||
| 33 | + Recommendation, | ||
| 34 | + StudentSegmentProfile, | ||
| 35 | + StudentSummary, | ||
| 36 | +) | ||
| 37 | +from src.protocol import CapabilityError | ||
| 38 | +from src.store import profile_rows, recommendation_rows, run_row, summary_rows | ||
| 39 | + | ||
| 40 | +SCHOOL = "demo-okul" | ||
| 41 | +DISPLAY = "Demo Anadolu Lisesi" | ||
| 42 | +NOW = int(time.time() * 1000) | ||
| 43 | +DAY = clock.DAY_MS | ||
| 44 | +RUN_DAY = clock.tr_date_key(NOW) | ||
| 45 | + | ||
| 46 | +FACT_A = "Son 30 günde 4 ödev teslim edilmedi" | ||
| 47 | +FACT_B = "Not eğilimi son üç sınavda düştü" | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +def _marks(course: str, title: str, band: str) -> dict[str, Any]: | ||
| 51 | + """One course's evidence block, in the shape `marks.py` writes.""" | ||
| 52 | + return { | ||
| 53 | + "classes": ["9-A"], | ||
| 54 | + "courses": { | ||
| 55 | + course: { | ||
| 56 | + "course": course, | ||
| 57 | + "course_title": title, | ||
| 58 | + "n_marks": 6, | ||
| 59 | + "average": 42.5, | ||
| 60 | + "trend": {"available": True, "dropped": True, "rising": False}, | ||
| 61 | + "placement": { | ||
| 62 | + "band": band, | ||
| 63 | + "confidence": "stable", | ||
| 64 | + "z": -1.8, | ||
| 65 | + "class_average": 68.0, | ||
| 66 | + "class_sd": 9.0, | ||
| 67 | + "cohort_n": 12, | ||
| 68 | + }, | ||
| 69 | + } | ||
| 70 | + }, | ||
| 71 | + } | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +def _attention(trigger: str, fact: str) -> dict[str, Any]: | ||
| 75 | + """One attention item, in the shape `attention.py` writes.""" | ||
| 76 | + return { | ||
| 77 | + "trigger": trigger, | ||
| 78 | + "course": "course-1", | ||
| 79 | + "fact": fact, | ||
| 80 | + "window_from": NOW - 30 * DAY, | ||
| 81 | + "window_to": NOW, | ||
| 82 | + "evidence": {"missing": 4, "cohort_median": 1}, | ||
| 83 | + } | ||
| 84 | + | ||
| 85 | + | ||
| 86 | +def summaries() -> list[dict[str, Any]]: | ||
| 87 | + """`zeka_student_summary` rows, exactly as ZEKA writes them (no `school`).""" | ||
| 88 | + return summary_rows( | ||
| 89 | + [ | ||
| 90 | + StudentSummary( | ||
| 91 | + school=SCHOOL, | ||
| 92 | + student="ogrenci-a", | ||
| 93 | + computed_at=NOW, | ||
| 94 | + marks=_marks("course-1", "Matematik", "review"), | ||
| 95 | + attendance={"overall": {"rate": 0.82}, "courses": {}}, | ||
| 96 | + submission={"overall": {"n": 12, "n_submitted": 9, "n_missing": 3}}, | ||
| 97 | + study={"recent_28d": {"n_stints": 11, "active_days": 7}}, | ||
| 98 | + attention=[_attention("homework", FACT_A)], | ||
| 99 | + confidence=Confidence.STABLE, | ||
| 100 | + ), | ||
| 101 | + StudentSummary( | ||
| 102 | + school=SCHOOL, | ||
| 103 | + student="ogrenci-b", | ||
| 104 | + computed_at=NOW, | ||
| 105 | + marks=_marks("course-2", "Fen Bilimleri", "on_track"), | ||
| 106 | + attendance={"overall": {"rate": 0.95}, "courses": {}}, | ||
| 107 | + submission={"overall": {"n": 11, "n_submitted": 11, "n_missing": 0}}, | ||
| 108 | + study={"recent_28d": {"n_stints": 15, "active_days": 9}}, | ||
| 109 | + attention=[_attention("mark_trend", FACT_B)], | ||
| 110 | + confidence=Confidence.STABLE, | ||
| 111 | + ), | ||
| 112 | + StudentSummary( | ||
| 113 | + school=SCHOOL, | ||
| 114 | + student="ogrenci-c", | ||
| 115 | + computed_at=NOW, | ||
| 116 | + marks=_marks("course-1", "Matematik", "insufficient_data"), | ||
| 117 | + attendance={"overall": {"rate": 1.0}, "courses": {}}, | ||
| 118 | + submission={"overall": {"n": 10, "n_submitted": 10, "n_missing": 0}}, | ||
| 119 | + study={"recent_28d": {"n_stints": 8, "active_days": 6}}, | ||
| 120 | + confidence=Confidence.EXPLORATORY, | ||
| 121 | + ), | ||
| 122 | + ] | ||
| 123 | + ) | ||
| 124 | + | ||
| 125 | + | ||
| 126 | +def recommendations() -> list[dict[str, Any]]: | ||
| 127 | + """`zeka_recommendation` rows: teacher, student and parent cards. | ||
| 128 | + | ||
| 129 | + The parent card is the gate witness: `allowed_roles("okul")` is | ||
| 130 | + `STAFF_ROLES | STUDENT_FACING_ROLES` (`report/gate.py`), so teacher and | ||
| 131 | + student cards show in the school report and the parent card must not. | ||
| 132 | + """ | ||
| 133 | + rows, rejected = recommendation_rows( | ||
| 134 | + [ | ||
| 135 | + Recommendation( | ||
| 136 | + school=SCHOOL, | ||
| 137 | + audience="ogretmen-1", | ||
| 138 | + audience_role=Audience.TEACHER, | ||
| 139 | + product="T4", | ||
| 140 | + rule_id="T4.homework", | ||
| 141 | + about="ogrenci-a", | ||
| 142 | + course="course-1", | ||
| 143 | + evidence={"missing": 4, "cohort_median": 1}, | ||
| 144 | + limitation="Teslim anı bilinmiyor.", | ||
| 145 | + confidence=Confidence.STABLE, | ||
| 146 | + computed_at=NOW, | ||
| 147 | + expires_at=NOW + 7 * DAY, | ||
| 148 | + ), | ||
| 149 | + Recommendation( | ||
| 150 | + school=SCHOOL, | ||
| 151 | + audience="ogrenci-a", | ||
| 152 | + audience_role=Audience.STUDENT, | ||
| 153 | + product="O1", | ||
| 154 | + rule_id="O1.review_band", | ||
| 155 | + course="course-1", | ||
| 156 | + evidence={"student_average": 42.5, "class_average": 68.0}, | ||
| 157 | + limitation="Konu kırılımı yok.", | ||
| 158 | + confidence=Confidence.STABLE, | ||
| 159 | + computed_at=NOW, | ||
| 160 | + expires_at=NOW + 7 * DAY, | ||
| 161 | + ), | ||
| 162 | + Recommendation( | ||
| 163 | + school=SCHOOL, | ||
| 164 | + audience="veli-1", | ||
| 165 | + audience_role=Audience.PARENT, | ||
| 166 | + product="V1", | ||
| 167 | + rule_id="V1.parent_only", | ||
| 168 | + about="ogrenci-a", | ||
| 169 | + evidence={"n": 3}, | ||
| 170 | + limitation="Veli kartı okul raporunda gösterilmez.", | ||
| 171 | + confidence=Confidence.STABLE, | ||
| 172 | + computed_at=NOW, | ||
| 173 | + expires_at=NOW + 7 * DAY, | ||
| 174 | + ), | ||
| 175 | + ] | ||
| 176 | + ) | ||
| 177 | + assert rejected == 0, "fixture rows must carry evidence" | ||
| 178 | + return rows | ||
| 179 | + | ||
| 180 | + | ||
| 181 | +def profiles() -> list[dict[str, Any]]: | ||
| 182 | + """`zeka_student_segment_profile` rows.""" | ||
| 183 | + return profile_rows( | ||
| 184 | + [ | ||
| 185 | + StudentSegmentProfile( | ||
| 186 | + school=SCHOOL, | ||
| 187 | + student="ogrenci-a", | ||
| 188 | + dimension="bilissel_talep", | ||
| 189 | + label="analiz", | ||
| 190 | + n_answers=120, | ||
| 191 | + n_correct=60, | ||
| 192 | + overall_n_answers=400, | ||
| 193 | + overall_accuracy=0.61, | ||
| 194 | + computed_at=NOW, | ||
| 195 | + confidence=Confidence.STABLE, | ||
| 196 | + ), | ||
| 197 | + StudentSegmentProfile( | ||
| 198 | + school=SCHOOL, | ||
| 199 | + student="ogrenci-b", | ||
| 200 | + dimension="dikkat_tuzagi", | ||
| 201 | + label="var", | ||
| 202 | + n_answers=150, | ||
| 203 | + n_correct=90, | ||
| 204 | + overall_n_answers=400, | ||
| 205 | + overall_accuracy=0.61, | ||
| 206 | + computed_at=NOW, | ||
| 207 | + confidence=Confidence.EXPLORATORY, | ||
| 208 | + ), | ||
| 209 | + ] | ||
| 210 | + ) | ||
| 211 | + | ||
| 212 | + | ||
| 213 | +def runs() -> list[dict[str, Any]]: | ||
| 214 | + """`zeka_run` rows, keyed the way the store writes them.""" | ||
| 215 | + return [ | ||
| 216 | + run_row( | ||
| 217 | + { | ||
| 218 | + "started_at": NOW - 3600_000, | ||
| 219 | + "finished_at": NOW, | ||
| 220 | + "status": "ok", | ||
| 221 | + "students_total": 3, | ||
| 222 | + "students_ok": 3, | ||
| 223 | + "students_failed": 0, | ||
| 224 | + "students_skipped": 0, | ||
| 225 | + "rows_written": 9, | ||
| 226 | + "budget_exceeded": False, | ||
| 227 | + "budget_ms": 60_000, | ||
| 228 | + "pending_students": [], | ||
| 229 | + "failed_modules": [], | ||
| 230 | + }, | ||
| 231 | + f"{SCHOOL}_{RUN_DAY}", | ||
| 232 | + ) | ||
| 233 | + ] | ||
| 234 | + | ||
| 235 | + | ||
| 236 | +def payload(**over: Any) -> dict[str, Any]: | ||
| 237 | + """The request exactly as the backend builds it (`## insight.report`).""" | ||
| 238 | + sent: dict[str, Any] = { | ||
| 239 | + "kind": "okul", | ||
| 240 | + "run_day": RUN_DAY, | ||
| 241 | + "requested_by": "mudur-1", | ||
| 242 | + "school": {"id": "01990000-0000-7000-8000-000000000001", "slug": SCHOOL, "name": DISPLAY}, | ||
| 243 | + "summaries": summaries(), | ||
| 244 | + "recommendations": recommendations(), | ||
| 245 | + "profiles": profiles(), | ||
| 246 | + "runs": runs(), | ||
| 247 | + } | ||
| 248 | + sent.update(over) | ||
| 249 | + return sent | ||
| 250 | + | ||
| 251 | + | ||
| 252 | +class ReportCase(unittest.IsolatedAsyncioTestCase): | ||
| 253 | + """Wired table, one school, and the payload the backend will send.""" | ||
| 254 | + | ||
| 255 | + def setUp(self) -> None: | ||
| 256 | + handlers.wire() | ||
| 257 | + | ||
| 258 | + def tearDown(self) -> None: | ||
| 259 | + capabilities._handlers.clear() | ||
| 260 | + | ||
| 261 | + async def dispatch(self, sent: dict[str, Any]) -> dict[str, Any]: | ||
| 262 | + return await capabilities.dispatch("insight.report", SCHOOL, sent) | ||
| 263 | + | ||
| 264 | + | ||
| 265 | +class DispatchTests(ReportCase): | ||
| 266 | + async def test_report_is_unknown_until_wire_registers_it(self) -> None: | ||
| 267 | + capabilities._handlers.clear() | ||
| 268 | + with self.assertRaises(CapabilityError) as caught: | ||
| 269 | + await self.dispatch(payload()) | ||
| 270 | + self.assertEqual(caught.exception.code, "unknown_capability") | ||
| 271 | + | ||
| 272 | + handlers.wire() | ||
| 273 | + answer = await self.dispatch(payload()) | ||
| 274 | + self.assertEqual(answer["format"], "html") | ||
| 275 | + | ||
| 276 | + def test_the_boot_self_check_counts_it_dispatchable(self) -> None: | ||
| 277 | + self.assertIn("insight.report", capabilities.dispatchable_names()) | ||
| 278 | + capabilities.verify_dispatchable() # a clean bill: no raise | ||
| 279 | + | ||
| 280 | + capabilities._handlers.pop("insight.report") | ||
| 281 | + with self.assertRaises(capabilities.RegistrationError) as caught: | ||
| 282 | + capabilities.verify_dispatchable() | ||
| 283 | + self.assertIn("insight.report", str(caught.exception)) | ||
| 284 | + | ||
| 285 | + | ||
| 286 | +class DocumentTests(ReportCase): | ||
| 287 | + async def test_the_html_carries_name_count_and_per_student_lines(self) -> None: | ||
| 288 | + answer = await self.dispatch(payload()) | ||
| 289 | + html = answer["html"] | ||
| 290 | + | ||
| 291 | + # 1) a self-contained HTML document, not an error page | ||
| 292 | + self.assertTrue(html.startswith("<!DOCTYPE html>")) | ||
| 293 | + # 2) the DISPLAY name the payload carried is the title | ||
| 294 | + self.assertIn(DISPLAY, html) | ||
| 295 | + # 3) the student count is the number of summaries the backend sent -- | ||
| 296 | + # rows carry no `school`, so this also proves the frame's stamp | ||
| 297 | + self.assertIn('<td>Öğrenci</td><td class="num">3</td>', html) | ||
| 298 | + # 4) one line per student's attention item, with the student's id | ||
| 299 | + self.assertIn("<td>ogrenci-a</td>", html) | ||
| 300 | + self.assertIn(FACT_A, html) | ||
| 301 | + self.assertIn("<td>ogrenci-b</td>", html) | ||
| 302 | + self.assertIn(FACT_B, html) | ||
| 303 | + # 5) the role gate ran: teacher and student cards show (the `okul` | ||
| 304 | + # report allows both), the parent card does not | ||
| 305 | + self.assertIn("T4.homework", html) | ||
| 306 | + self.assertIn("O1.review_band", html) | ||
| 307 | + self.assertNotIn("V1.parent_only", html) | ||
| 308 | + | ||
| 309 | + # The answer's own contract | ||
| 310 | + self.assertEqual(answer["kind"], "okul") | ||
| 311 | + self.assertEqual(answer["format"], "html") | ||
| 312 | + self.assertEqual(answer["run_day"], RUN_DAY) | ||
| 313 | + self.assertIs(answer["truncated"], False) | ||
| 314 | + self.assertEqual(answer["byte_size"], len(html.encode("utf-8"))) | ||
| 315 | + self.assertEqual( | ||
| 316 | + answer["coverage"]["rows"], | ||
| 317 | + {"summaries": 3, "recommendations": 3, "profiles": 2, "runs": 1}, | ||
| 318 | + ) | ||
| 319 | + self.assertIs(answer["coverage"]["empty"], False) | ||
| 320 | + # The limitation notes are the package's own sentences, not invented ones | ||
| 321 | + self.assertTrue(answer["notes"]) | ||
| 322 | + self.assertTrue( | ||
| 323 | + all(isinstance(note, str) and note for note in answer["notes"]) | ||
| 324 | + ) | ||
| 325 | + self.assertTrue(any("sıralama yoktur" in note for note in answer["notes"])) | ||
| 326 | + | ||
| 327 | + async def test_run_day_falls_back_to_the_newest_run_row(self) -> None: | ||
| 328 | + sent = payload() | ||
| 329 | + del sent["run_day"] | ||
| 330 | + answer = await self.dispatch(sent) | ||
| 331 | + self.assertEqual(answer["run_day"], RUN_DAY) | ||
| 332 | + | ||
| 333 | + | ||
| 334 | +class RefusalTests(ReportCase): | ||
| 335 | + async def test_an_empty_row_set_is_refused_not_rendered(self) -> None: | ||
| 336 | + for sent in ( | ||
| 337 | + payload(summaries=[], recommendations=[], profiles=[], runs=[]), | ||
| 338 | + {"kind": "okul"}, # no row lists at all | ||
| 339 | + ): | ||
| 340 | + with self.assertRaises(CapabilityError) as caught: | ||
| 341 | + await self.dispatch(sent) | ||
| 342 | + self.assertEqual(caught.exception.code, "insufficient_rows") | ||
| 343 | + | ||
| 344 | + async def test_a_kind_this_capability_does_not_serve_is_refused(self) -> None: | ||
| 345 | + for kind in ("ogrenci", "ogretmen", "ham", "rapor", ""): | ||
| 346 | + with self.assertRaises(CapabilityError) as caught: | ||
| 347 | + await self.dispatch(payload(kind=kind)) | ||
| 348 | + self.assertEqual(caught.exception.code, "bad_request") | ||
| 349 | + | ||
| 350 | + async def test_a_row_claiming_another_school_is_refused(self) -> None: | ||
| 351 | + sent = payload() | ||
| 352 | + sent["summaries"] = [{**sent["summaries"][0], "school": "baska-okul"}] | ||
| 353 | + with self.assertRaises(CapabilityError) as caught: | ||
| 354 | + await self.dispatch(sent) | ||
| 355 | + self.assertEqual(caught.exception.code, "bad_request") | ||
| 356 | + self.assertIn("baska-okul", str(caught.exception)) | ||
| 357 | + | ||
| 358 | + async def test_a_school_slug_disagreeing_with_the_frame_is_refused(self) -> None: | ||
| 359 | + with self.assertRaises(CapabilityError) as caught: | ||
| 360 | + await self.dispatch( | ||
| 361 | + payload(school={"id": "x", "slug": "baska-okul", "name": "Başka"}) | ||
| 362 | + ) | ||
| 363 | + self.assertEqual(caught.exception.code, "bad_request") | ||
| 364 | + | ||
| 365 | + async def test_a_malformed_row_list_is_refused(self) -> None: | ||
| 366 | + with self.assertRaises(CapabilityError) as caught: | ||
| 367 | + await self.dispatch(payload(profiles={"student": "ogrenci-a"})) | ||
| 368 | + self.assertEqual(caught.exception.code, "bad_request") | ||
| 369 | + | ||
| 370 | + async def test_a_render_failure_is_a_typed_refusal(self) -> None: | ||
| 371 | + with patch.object( | ||
| 372 | + handlers.report_render, "to_html", side_effect=RuntimeError("çizim düştü") | ||
| 373 | + ): | ||
| 374 | + with self.assertRaises(CapabilityError) as caught: | ||
| 375 | + await self.dispatch(payload()) | ||
| 376 | + self.assertEqual(caught.exception.code, "internal") | ||
| 377 | + self.assertIn("çizim düştü", str(caught.exception)) | ||
| 378 | + | ||
| 379 | + async def test_an_oversize_document_is_refused_not_truncated(self) -> None: | ||
| 380 | + cap = protocol.AI_MAX_FRAME_BYTES // 2 | ||
| 381 | + with patch.object( | ||
| 382 | + handlers.report_render, "to_html", return_value="x" * (cap + 1) | ||
| 383 | + ): | ||
| 384 | + with self.assertRaises(CapabilityError) as caught: | ||
| 385 | + await self.dispatch(payload()) | ||
| 386 | + self.assertEqual(caught.exception.code, "document_too_large") | ||
| 387 | + | ||
| 388 | + def test_the_html_cap_is_half_the_frame_cap(self) -> None: | ||
| 389 | + # The document rides INSIDE the JSON frame: half the cap is the room | ||
| 390 | + # the rest of the frame (and JSON escaping) needs. | ||
| 391 | + self.assertEqual(handlers._MAX_HTML_BYTES * 2, protocol.AI_MAX_FRAME_BYTES) | ||
| 392 | + | ||
| 393 | + | ||
| 394 | +if __name__ == "__main__": | ||
| 395 | + unittest.main() | ||