diff --git a/service/README.md b/service/README.md index 7deb56f..5e9d394 100644 --- a/service/README.md +++ b/service/README.md @@ -54,7 +54,9 @@ Servisin çağırdığı operasyonlar: `insight.schools.list`, `insight.summary. `insight.recommendation.upsert`, `insight.segment.upsert`, `insight.profile.upsert`, `insight.run.upsert`, `insight.pending.list`, `insight.retention.sweep`, `insight.departed.purge`. Servisin **servis ettiği** yetenekler `insight.student`, -`insight.class`, `insight.refresh`'tir (`src/capabilities.py`). +`insight.class`, `insight.refresh` ve `insight.report`'tur (`src/capabilities.py`; +`insight.report` okul raporu **belgesini** üretir — satırlar payload'da gelir, +servis köprüden hiçbir şey okumaz). --- diff --git a/service/docs/BACKEND-GEREKSINIMLERI.md b/service/docs/BACKEND-GEREKSINIMLERI.md index c563537..3a1127b 100644 --- a/service/docs/BACKEND-GEREKSINIMLERI.md +++ b/service/docs/BACKEND-GEREKSINIMLERI.md @@ -29,7 +29,9 @@ Yani asagidaki uc madde ZEKA'nin nelerin **disinda** kaldigini tarif eder. > servis tarafi ayni gun baglandi (`src/handlers.py`; ilan ile dagitim > acilista `capabilities.verify_dispatchable()` ile denetlenir). > `insight.class` ilan edilir ama hala GONDERILMEZ -- kadro listeleme yolu -> yok (Madde 3). Asagidaki "yoktur / tanimli degil" ifadeleri bu iki yonu +> yok (Madde 3). `insight.report` icin servis tarafi da hazir (2026-09-18): +> backend'in dagitim tablosuna girmesi bekleniyor, bkz. `## insight.report`. +> Asagidaki "yoktur / tanimli degil" ifadeleri bu iki yonu > ayirmadan okunmamalidir; `src/capabilities.py` modul dokumani ayni ayrimi > yapar. @@ -147,6 +149,87 @@ inmesidir. --- +## insight.report -- okul raporu BELGESI (sunucu-baslatimli; servis tarafi HAZIR 2026-09-18) + +**Sahibi: backend'deki `InsightDoors` hatti.** Servis tarafi bugun hazir: +`insight.report` ilan edilir, isleyicisi kayitlidir (`handlers.report`) ve +acilistaki `capabilities.verify_dispatchable()` onu dagitilabilir sayar. +Eksik olan tek sey backend'in dagitim tablosudur (`hezarfen_backend/src` +icinde bu ad 2026-09-18 itibariyla hic gecmez), yani bugun kimse bu yetenegi +cagiramaz. Kapi acildiginda uc sey BIRLIKTE guncellenir: `src/capabilities.py` +`BACKEND_CALLABLE_CAPABILITIES`, `tests/test_capabilities.py` pini ve +yukaridaki durum cumlesi. + +### Ne isteniyor + +Backend, okulun `zeka_*` satirlarini **kendi okur** ve tek bir +`insight.report` istegiyle gonderir; servis belgeyi uretir ve cevap +cercevesinde **HTML metni olarak** dondurur. Blob yuklemesi yok, depo yok: +belge, servisin hicbir okuma yapmadigi tek `insight.*` isleyicisidir. + +**Istek payload'i.** Cercevedeki `school` = okul slug'i. Satirlar ZEKA'nin +depo yoluyla yazdigi bicimdir -- backend'in kendi yapilari (`db/insight.rs` +`SummaryRow` / `RecommendationRow` / `ProfileRow` / `RunRow`), yani ikinci bir +esleme yok: + +| Alan | Tip | Ne | +|---|---|---| +| `kind` | str | Zorunlu; sunulan tek deger `okul` | +| `run_day` | str | `YYYY-MM-DD` (TR gunu); yoksa en yeni kosu satirindan turetilir | +| `requested_by` | str | Belgeyi isteyen mudur; okuma yapilmadigi icin yalniz log'a yazilir | +| `school` | nesne | `{id, slug, name}`; `name` belge BASLIGIDIR, `slug` cerceveyle ayni olmali | +| `summaries` | liste | `zeka_student_summary` satirlari (`attention` listesi dahil) | +| `recommendations` | liste | `zeka_recommendation` satirlari | +| `profiles` | liste | `zeka_student_segment_profile` satirlari | +| `runs` | liste | `zeka_run` satirlari (`run_day` alani belgenin gununu verir) | + +Satirlarda `school` GONDERILMEZ: ZEKA onu hic yazmaz, cercevede gelir ve +servis her satira kendisi damgalar (tek kimlik kaynagi). Yine de bir satir +baska bir okul tasirsa istek reddedilir -- damgalamak degil, reddetmek. + +**Cevap payload'i** (belge cercevenin ICINDE gider): + +```json +{ "kind": "okul", "run_day": "2026-09-18", "format": "html", + "html": "...", "byte_size": 12345, "truncated": false, + "notes": ["Siralama yoktur. ...", "Kaniti olmayan satir rapora girmez. ..."], + "coverage": { "rows": {"summaries": 42, "recommendations": 7, + "profiles": 11, "runs": 1}, "empty": false } } +``` + +- `byte_size` = `html`in UTF-8 bayt uzunlugu; `truncated` bugun her zaman + `false` (sinir asilirsa belge KESILMEZ, asagidaki kodla reddedilir). +- `notes` paketin kendi kapsam/sinir cumleleridir: backend onlari oldugu gibi + gosterir, kendi cumlesini uydurmaz. +- `coverage` sozlesme disi ek alandir (refresh'in `status`u gibi: serde + bilinmeyen alani yok sayar): ham satir sayilari + paketin `empty` hukmu, + "belge neden bos" sorusu log'dan da cevaplanabilsin diye. + +### Redler (backend'in HTTP durumuna eslemesi icin) + +| Kod | Ne zaman | Onerilen esleme | +|---|---|---| +| `bad_request` | Sozlesmeye uymayan payload: sunulmayan/bilinmeyen `kind`, bozuk `run_day`, liste olmayan satir alani, cerceveyle celisen okul | 400 | +| `insufficient_rows` | Dort liste de bos: uretilecek belge yok; bos belge cevap degildir | 404/409 -- ekran kendi "yetersiz veri" durumunu gostersin | +| `document_too_large` | HTML 4 MiB'i asiyor (cerceve kapagi 8 MiB) | 413 | +| `internal` | Paket belgeyi kuramadi ya da cizemedi | 500/502 | + +### Bugunun sinirlari + +- **Dort rapor tipinden yalniz `okul` sunulur.** `ogrenci` / `ogretmen` / + `ham` icin istek sozlesmesi yok (payload `student`, `teacher` ve + `question_segment` tasimaz); istek gelirse `bad_request` doner ve yarim + belge uretilmez. +- **Kapatilmis tavsiyeler.** Paketin kapatma kapisi satirda `dismissed_at` + arar; backend'in `RecommendationRow`'u alani tasimaz (kapatma yazimi bugun + hic yok). Kapatma ozelligi gelirse ya okunan satir `dismissed_at` tasimali + ya backend kapatilmis satirlari gondermemeli -- yoksa kapatilmis kart + rapora geri duser. +- **HTML siniri 4 MiB** (`AI_MAX_FRAME_BYTES // 2`): belge cevap cercevesinin + icinde gider ve JSON kacislarina da yer kalmali. + +--- + ## Madde 2 -- Izin listesine sinav yollarinin eklenmesi ### Ne isteniyor @@ -298,6 +381,7 @@ Yani kapsam **elle** tutulur. | 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).** | | 2 | 9 sinav yolu (+3 sinif/ders yolu) izin listesine | `src/constant.rs:656-676` | **Madde analizi, konu karnesi, sinif isi haritasi** hic uretilemez | | 3 | `GET /users/search` izin listesine (okul listesi Madde 1a'da) | `src/constant.rs:656-676` | Ogrenci kadrosu elle tutulur; yeni ogrenci **sessizce** gorunmez | +| 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) | --- diff --git a/service/docs/CIKTI-SOZLESMESI.md b/service/docs/CIKTI-SOZLESMESI.md index d607d02..954c0a4 100644 --- a/service/docs/CIKTI-SOZLESMESI.md +++ b/service/docs/CIKTI-SOZLESMESI.md @@ -419,5 +419,9 @@ bu tuzak yapısal olarak imkânsızdır. 2026-09-18'de `insight.student` + `insight.refresh` için açıldı** ve servis tarafı aynı gün bağlandı (`service/src/handlers.py`; ilan ile dağıtım açılışta `verify_dispatchable()` ile denetlenir). `insight.class` ilan - edilir ama gönderilmez: kadro listeleme yolu yok. Sahibi backend'deki - `InsightDoors` hattı — `docs/BACKEND-GEREKSINIMLERI.md` Madde 1. + edilir ama gönderilmez: kadro listeleme yolu yok. **`insight.report` + (okul raporu BELGESİ) servis tarafında aynı gün hazır** — belgeyi + backend'in gönderdiği satırlardan üretir; backend'in dağıtım tablosuna + girmesi bekleniyor (`docs/BACKEND-GEREKSINIMLERI.md` `## insight.report`). + Sahibi backend'deki `InsightDoors` hattı — `docs/BACKEND-GEREKSINIMLERI.md` + Madde 1. diff --git a/service/src/capabilities.py b/service/src/capabilities.py index 2543c7f..ddf4453 100644 --- a/service/src/capabilities.py +++ b/service/src/capabilities.py @@ -10,6 +10,10 @@ IKI YON VARDIR; karistirilmamalidir: never dispatched: its request names a course, and the bridge's read allowlist hands a service no roster to enumerate it with (`ai/insight.rs` module docs; `docs/BACKEND-GEREKSINIMLERI.md` item 3). + `insight.report` is the fourth name and the one whose answer is a DOCUMENT: + the backend reads its own `zeka_*` rows and dispatches them, and the service + renders the school report from them without reading anything itself + (`docs/BACKEND-GEREKSINIMLERI.md`, `## insight.report`). Routing is an EXACT match (`ai/protocol.rs:91-94`): every advertised name gets its handler from `handlers.wire()`, and `verify_dispatchable()` checks the pair at startup -- if advertising and dispatch ever drift apart, the @@ -57,7 +61,21 @@ INSIGHT_CLASS = "insight.class" INSIGHT_REFRESH = "insight.refresh" """Bir okul icin hesaplari yeniden kosturur; parti isidir.""" -NAMES: tuple[str, ...] = (INSIGHT_STUDENT, INSIGHT_CLASS, INSIGHT_REFRESH) +INSIGHT_REPORT = "insight.report" +"""Verilen satirlardan okul raporu BELGESI uretir. + +Tek `insight.*` isleyicisi ki koprudan HICBIR SEY okumaz: satirlar payload'da +gelir (backend kendi `zeka_*` tablolarindan okur), servis yalniz render eder. +Istek/cevap sozlesmesi: `ReportRequest` / `ReportResponse` ve +`docs/BACKEND-GEREKSINIMLERI.md` `## insight.report`. +""" + +NAMES: tuple[str, ...] = ( + INSIGHT_STUDENT, + INSIGHT_CLASS, + INSIGHT_REFRESH, + INSIGHT_REPORT, +) #: 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) #: `ai/insight.rs::compute_student/refresh` + the `web/insights.rs` doors #: (insight.student, insight.refresh; merged 2026-09-18). `insight.class` is #: NOT in the set: the constant exists, the code that would send it does not. +#: `insight.report` is NOT in it either, for the same reason and one more: the +#: service side is READY (advertised + `handlers.report`), but the backend's +#: dispatch table carries no `insight.report` yet (`hezarfen_backend/src` has +#: no such name as of 2026-09-18). When that door lands, three edits move +#: together: this tuple, the pin in `tests/test_capabilities.py`, and the +#: status line of `docs/BACKEND-GEREKSINIMLERI.md` `## insight.report`. #: `tests/test_capabilities.py` pins this. BACKEND_CALLABLE_CAPABILITIES: tuple[str, ...] = ( "chat.reply", @@ -159,11 +183,67 @@ class RefreshResponse(TypedDict, total=False): status: str +class ReportRequest(TypedDict, total=False): + """`insight.report` istek payload'i -- backend'in okudugu satirlar. + + Satirlar backend'in KENDI yapilaridir (`db/insight.rs` `SummaryRow`, + `RecommendationRow`, `ProfileRow`, `RunRow`): ZEKA'nin depo yoluyla + yazdigi bicimin aynisi, yani ikinci bir esleme yok. Satirlarda `school` + YOKTUR -- ZEKA onu hic yazmaz; cercevede gelir ve isleyici her satira + damgalar (tek kimlik kaynagi). Payload'daki `school` yalniz GORUNUM icin + (`name` baslikta); `slug` cerceveyle celisirse istek reddedilir. + """ + + kind: str + """Sunulan tek tip: `okul` (bkz. `handlers._SERVED_REPORT_KINDS`).""" + run_day: str + """`YYYY-MM-DD` (TR gunu); yoksa en yeni kosu satirindan turetilir.""" + requested_by: str + """Belgeyi isteyen mudur. Okuma yapilmadigi icin yalniz log'a yazilir.""" + school: dict[str, Any] + """`{"id": ..., "slug": ..., "name": ...}` -- `name` belge basligidir.""" + summaries: list[dict[str, Any]] + """`zeka_student_summary` satirlari; `attention` listesi DAHIL (personel + raporunun dikkat tablosunu besleyen tek alan odur).""" + recommendations: list[dict[str, Any]] + """`zeka_recommendation` satirlari (kapatilan/suresi gecen satirlar + backend tarafindan suzulmezse paket onlari yine gostermez -- ama + `dismissed_at` satirda yoksa kapi bunu goremez; bkz. docs).""" + profiles: list[dict[str, Any]] + """`zeka_student_segment_profile` satirlari.""" + runs: list[dict[str, Any]] + """`zeka_run` satirlari; `run_day` alani belgenin gununu verir.""" + + +class ReportResponse(TypedDict, total=False): + """`insight.report` cevap payload'i (`handlers.report` doldurur). + + Tek `insight.*` cevabi ki BELGENIN KENDISINI tasir: blob yuklemesi yok, + depo yok. Degerler: `bad_request` (sozlesmeye uymayan payload), + `insufficient_rows` (dort liste de bos -- belge uretilecek satir yok), + `document_too_large` (HTML `_MAX_HTML_BYTES` ustunde; KESILMEZ, reddedilir), + `internal` (paket kurulamadi/cizilemedi). + """ + + kind: str + run_day: str # belgenin gunu: istekten aynen, yoksa turetildi + format: str # bugun her zaman "html" + html: str # tek dosyalik, kendi kendine yeten belge + byte_size: int # `html`in UTF-8 bayt uzunlugu + truncated: bool # her zaman False: sinir asilirsa reddedilir, kesilmez + notes: list[str] # paketin kendi kapsam/sinir cumleleri (report.notes) + #: Sozlesme disi ek alan (refresh'in `status`u gibi: serde yok sayar): + #: satir sayilari + paketin `empty` hukmu. "Belge neden bos" sorusunu + #: log'dan cevaplamak icin. + coverage: dict[str, Any] + + #: Yetenek adi -> (istek tipi, cevap tipi). Belge ve dogrulama icin. SCHEMAS: dict[str, tuple[type, type]] = { INSIGHT_STUDENT: (StudentRequest, StudentResponse), INSIGHT_CLASS: (ClassRequest, ClassResponse), INSIGHT_REFRESH: (RefreshRequest, RefreshResponse), + INSIGHT_REPORT: (ReportRequest, ReportResponse), } diff --git a/service/src/handlers.py b/service/src/handlers.py index f3fdb72..c85e478 100644 --- a/service/src/handlers.py +++ b/service/src/handlers.py @@ -1,4 +1,4 @@ -"""The three `insight.*` capabilities the service serves to the backend. +"""The four `insight.*` capabilities the service serves to the backend. `capabilities.py` owns the wire names and the dispatch table but registers no 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` / Why the handlers live outside `capabilities.py`: the table must stay importable without the compute stack. A handler, on the other hand, is the whole stack -- a `Source` read, `pipeline.run_school`, and the store writes. +`report` is that rule's one exception: it reads nothing at all (its rows arrive +in the payload), but it belongs to the same table and answers from the same +package, so it lives here with its siblings. Handlers are coroutines on purpose. `bridge.BridgeProtocol._handle()` awaits a coroutine handler in the event loop and pushes only *sync* handlers into the @@ -35,9 +38,12 @@ from typing import Any, Callable from . import capabilities from . import config from .compute import attention as attention_mod +from .compute import clock from .compute import marks as marks_mod from .pipeline import StudentOutcome, run_school -from .protocol import CapabilityError +from .protocol import AI_MAX_FRAME_BYTES, CapabilityError +from .report import MemoryReader, build_report, load_bundle +from .report import render as report_render from .source import NOT_PERMITTED from .store import attention_items, recommendation_rows @@ -154,6 +160,7 @@ def wire() -> None: capabilities.register(capabilities.INSIGHT_STUDENT, student) capabilities.register(capabilities.INSIGHT_CLASS, klass) capabilities.register(capabilities.INSIGHT_REFRESH, refresh) + capabilities.register(capabilities.INSIGHT_REPORT, report) def _lock_for(school: str) -> asyncio.Lock: @@ -528,10 +535,207 @@ async def refresh(school: str, payload: dict[str, Any]) -> dict[str, Any]: } +# --------------------------------------------------------------------------- +# insight.report -- the school report DOCUMENT +# --------------------------------------------------------------------------- + +#: The report kinds this capability serves. The package has four +#: (`report.gate.REPORT_TYPES`), but only `okul` has a request contract: the +#: payload carries four row lists and neither a `student`, a `teacher` nor the +#: `question_segment` rows (`ogrenci`/`ogretmen`/`ham` would need them), so the +#: other three are refused BY NAME rather than answered half-built. +_SERVED_REPORT_KINDS: tuple[str, ...] = ("okul",) + +#: The payload's four row lists and the `MemoryReader` table each maps to. The +#: keys are the backend's (`db/insight.rs` row structs, one list each); the +#: tables are the report package's own read surface (`report/reader.py`). The +#: mapping is total and one-way: no payload row is ever reshaped. +_REPORT_ROWS: tuple[tuple[str, str], ...] = ( + ("summaries", "student_summary"), + ("recommendations", "recommendation"), + ("profiles", "student_segment_profile"), + ("runs", "insight_run"), +) + +#: The HTML byte cap: half of the frame cap, because the document rides INSIDE +#: the JSON response frame (`AI_MAX_FRAME_BYTES` counts all of it). A document +#: over the cap is REFUSED, never truncated: a half-written HTML file is not a +#: readable document, and the download behind it would be silently broken. +_MAX_HTML_BYTES = AI_MAX_FRAME_BYTES // 2 + + +def _report_school(frame_school: str, payload: dict[str, Any]) -> str: + """The value every row is stamped with -- and the document's own school. + + The frame's `school` is the tenant identity; `payload.school.name` is the + DISPLAY name the report title carries. A payload whose `school.slug` + disagrees with the frame is refused: two identity sources is how another + school's rows reach a document. + """ + info = payload.get("school") + if info is None: + return frame_school + if not isinstance(info, dict): + raise CapabilityError("bad_request", "'school' bir nesne olmali") + slug = info.get("slug") + if isinstance(slug, str) and slug.strip() and slug.strip() != frame_school: + raise CapabilityError( + "bad_request", + f"payload'daki school.slug ({slug!r}) cercevedeki okulla " + f"({frame_school!r}) ayni degil", + ) + name = info.get("name") + if isinstance(name, str) and name.strip(): + return name.strip() + return frame_school + + +def _report_tables( + payload: dict[str, Any], school: str, frame_school: str +) -> dict[str, list[dict[str, Any]]]: + """The payload's four lists as `MemoryReader` tables, `school` stamped. + + Rows do NOT carry `school` (ZEKA never wrote one; the frame carries it), so + the stamp is added here -- and a row that claims a DIFFERENT school is a + refusal, not an overwrite: that is the cross-tenant shape this seam exists + to make impossible. + """ + tables: dict[str, list[dict[str, Any]]] = {} + for key, table in _REPORT_ROWS: + rows = payload.get(key) + if rows is None: + tables[table] = [] + continue + if not isinstance(rows, list) or any( + not isinstance(row, dict) for row in rows + ): + raise CapabilityError("bad_request", f"'{key}' bir nesne listesi olmali") + stamped: list[dict[str, Any]] = [] + for row in rows: + claimed = row.get("school") + if ( + isinstance(claimed, str) + and claimed.strip() + and claimed.strip() not in (school, frame_school) + ): + raise CapabilityError( + "bad_request", + f"'{key}' satiri baska bir okul tasiyor ({claimed!r}); " + f"cerceve {frame_school!r}", + ) + stamped.append({**row, "school": school}) + tables[table] = stamped + return tables + + +def _report_run_day(value: Any, runs: list[dict[str, Any]], now_ms: int) -> str: + """The document's day: the request's `run_day`, else the newest run's. + + `insight_run.run_day` is the TR day ZEKA wrote (`store.run_row`); no run + row at all (a report asked for before the first sweep) falls back to + `generated_at`'s TR day -- the day the document was made, not an invented + one. + """ + if value is not None: + day = value.strip() if isinstance(value, str) else "" + try: + datetime.strptime(day, "%Y-%m-%d") + except ValueError as exc: + raise CapabilityError( + "bad_request", f"'run_day' 'YYYY-MM-DD' biciminde olmali: {value!r}" + ) from exc + return day + newest, at = "", -1 + for row in runs: + day = row.get("run_day") + started = int(row.get("started_at") or 0) + if isinstance(day, str) and day.strip() and started >= at: + newest, at = day.strip(), started + return newest or clock.tr_date_key(now_ms) + + +async def report(school: str, payload: dict[str, Any]) -> dict[str, Any]: + """`insight.report` -- the school report DOCUMENT, from rows sent to it. + + The one `insight.*` handler that reads NOTHING over the bridge: the backend + reads its own `zeka_*` tables and dispatches those rows, and the service + only renders them -- no store, no database (standing rule). `requested_by` + is the backend's authenticated manager; with no read to run as anybody it + is logged, not resolved into `on_behalf_of`. + + Refusals, all typed for the backend to map: `bad_request` (a payload this + contract cannot read, or a kind this capability does not serve), + `insufficient_rows` (all four lists empty: there is nothing to render, and + an empty document is not an answer -- the caller states that in its own + words), `document_too_large` (over `_MAX_HTML_BYTES`; never truncated), + `internal` (the report package could not build or render the document). + """ + kind = capabilities.require_text(payload, "kind") + if kind not in _SERVED_REPORT_KINDS: + raise CapabilityError( + "bad_request", + f"'{kind}' bu yetenekte sunulmuyor (sunulan: " + f"{', '.join(_SERVED_REPORT_KINDS)}); paketin diger tipleri icin " + "istek sozlesmesi yok", + ) + now_ms = _now_ms() + display = _report_school(school, payload) + tables = _report_tables(payload, display, school) + total = sum(len(rows) for rows in tables.values()) + if total == 0: + raise CapabilityError( + "insufficient_rows", + "'summaries', 'recommendations', 'profiles', 'runs' listelerinin " + "hepsi bos: belge uretilecek satir yok", + ) + run_day = _report_run_day(payload.get("run_day"), tables["insight_run"], now_ms) + reader = MemoryReader(tables) + try: + bundle = await load_bundle(reader, display, kind, now_ms=now_ms) + document = build_report(kind, bundle) + html = report_render.to_html(document) + except Exception as exc: # the refusal IS the contract: no half document + raise CapabilityError("internal", f"rapor uretilemedi: {exc}") from exc + encoded = html.encode("utf-8") + if len(encoded) > _MAX_HTML_BYTES: + raise CapabilityError( + "document_too_large", + f"belge {len(encoded)} bayt, sinir {_MAX_HTML_BYTES} " + f"(cerceve kapagi {AI_MAX_FRAME_BYTES}); kesmek yerine reddedilir", + ) + who = payload.get("requested_by") + config.log( + "info", + f"insight.report: belge uretildi (okul={school}, tip={kind}, " + f"satir={total}, bayt={len(encoded)}, isteyen=" + f"{who.strip() if isinstance(who, str) and who.strip() else '-'})", + ) + return { + "kind": kind, + "run_day": run_day, + "format": "html", + "html": html, + "byte_size": len(encoded), + # Always False today: an over-cap document is refused above, never cut. + # The field exists because the backend's struct carries it. + "truncated": False, + "notes": list(document.notes), + # Beyond the backend's struct, which ignores what it does not read + # (the same shape as `refresh`'s `status`): raw row counts per payload + # list and the package's own `empty` verdict, so "why is the document + # empty" is answerable from the log line and from the answer. + "coverage": { + "rows": {key: len(tables[table]) for key, table in _REPORT_ROWS}, + "empty": document.empty, + }, + } + + __all__ = [ "bind_source", "klass", "refresh", + "report", "student", "wire", ] diff --git a/service/tests/test_capabilities.py b/service/tests/test_capabilities.py index 8e3077e..9e62d86 100644 --- a/service/tests/test_capabilities.py +++ b/service/tests/test_capabilities.py @@ -20,7 +20,7 @@ class CapabilityNameTests(unittest.TestCase): def test_declared_names(self): self.assertEqual( capabilities.NAMES, - ("insight.student", "insight.class", "insight.refresh"), + ("insight.student", "insight.class", "insight.refresh", "insight.report"), ) def test_backend_callable_set_is_the_dispatch_table(self): @@ -31,11 +31,14 @@ class CapabilityNameTests(unittest.TestCase): ("chat.reply", "rag.index", "insight.student", "insight.refresh"), ) # `insight.class` ilan edilir ama backend GONDERMEZ (kadro listeleme - # yolu yok). Backend tarafi acildiginda bu satiri ve - # docs/BACKEND-GEREKSINIMLERI.md madde 1'i birlikte guncelleyin. + # yolu yok). `insight.report` da ayni: servis tarafi HAZIR (ilan + + # handlers.report) ama backend'in dagitim tablosunda adi yok + # (hezarfen_backend/src, 2026-09-18). Backend tarafi acildiginda bu + # satiri ve docs/BACKEND-GEREKSINIMLERI.md `## insight.report`i + # birlikte guncelleyin. self.assertEqual( set(capabilities.NAMES) - set(capabilities.BACKEND_CALLABLE_CAPABILITIES), - {"insight.class"}, + {"insight.class", "insight.report"}, ) def test_sections_vocabulary_is_the_summary_modules(self): @@ -104,8 +107,11 @@ class DispatchTests(unittest.TestCase): # 2) ... depo yolunu (2. yon) kapsamadigi ... self.assertIn("servis->backend depo yolu: kopru/insight.*", text) # 3) ... ve ilan edilen her adin bir isleyicisi oldugu. - self.assertIn("servis tarafi isleyiciler: 3/3 kayitli", text) - self.assertIn("backend'in dagitim tablosunda olmayan: insight.class", text) + self.assertIn("servis tarafi isleyiciler: 4/4 kayitli", text) + self.assertIn( + "backend'in dagitim tablosunda olmayan: insight.class, insight.report", + text, + ) # Eski hali "TANIMSIZ" diyordu ve isleyici kayitliyken bile servisin # bir sey yapmadigini ima ediyordu. self.assertNotIn("TANIMSIZ", text) diff --git a/service/tests/test_handlers.py b/service/tests/test_handlers.py index dd5aca2..bb26e8a 100644 --- a/service/tests/test_handlers.py +++ b/service/tests/test_handlers.py @@ -92,7 +92,8 @@ class FailPreFixTests(HandlerTestCase): capabilities.verify_dispatchable() self.assertIn("insight.class", str(caught.exception)) self.assertEqual( - capabilities.dispatchable_names(), ["insight.student", "insight.refresh"] + capabilities.dispatchable_names(), + ["insight.student", "insight.refresh", "insight.report"], ) handlers.wire() diff --git a/service/tests/test_report_capability.py b/service/tests/test_report_capability.py new file mode 100644 index 0000000..46ca004 --- /dev/null +++ b/service/tests/test_report_capability.py @@ -0,0 +1,395 @@ +"""`insight.report` -- the school report document, end to end over the table. + +What is proven here, in the order it matters: + +1. The fail-pre-fix fact, for the fourth served name: with an empty handler + table the dispatch answers `unknown_capability`; `handlers.wire()` makes the + same call reach a real handler, and the boot self-check counts the name + dispatchable -- and refuses to boot when it is not. +2. The whole point of the seam: row lists shaped EXACTLY like what the backend + sends -- built here by the very writers that wrote them in production + (`store.summary_rows` / `recommendation_rows` / `profile_rows` / `run_row`), + with NO `school` key anywhere (ZEKA never wrote one; the frame carries it) -- + render the school report HTML: the display name, the student count, the + per-student attention lines, and only the roles the `okul` report may show. +3. Refusals are typed and leave no half-built document behind: an empty row set + (`insufficient_rows`), an unserved kind or a payload that breaks the contract + (`bad_request`), a package failure (`internal`), an over-cap document + (`document_too_large`) -- never a truncated HTML file. +""" + +from __future__ import annotations + +import time +import unittest +from typing import Any +from unittest.mock import patch + +from src import capabilities, handlers, protocol +from src.compute import clock +from src.compute.model import ( + Audience, + Confidence, + Recommendation, + StudentSegmentProfile, + StudentSummary, +) +from src.protocol import CapabilityError +from src.store import profile_rows, recommendation_rows, run_row, summary_rows + +SCHOOL = "demo-okul" +DISPLAY = "Demo Anadolu Lisesi" +NOW = int(time.time() * 1000) +DAY = clock.DAY_MS +RUN_DAY = clock.tr_date_key(NOW) + +FACT_A = "Son 30 günde 4 ödev teslim edilmedi" +FACT_B = "Not eğilimi son üç sınavda düştü" + + +def _marks(course: str, title: str, band: str) -> dict[str, Any]: + """One course's evidence block, in the shape `marks.py` writes.""" + return { + "classes": ["9-A"], + "courses": { + course: { + "course": course, + "course_title": title, + "n_marks": 6, + "average": 42.5, + "trend": {"available": True, "dropped": True, "rising": False}, + "placement": { + "band": band, + "confidence": "stable", + "z": -1.8, + "class_average": 68.0, + "class_sd": 9.0, + "cohort_n": 12, + }, + } + }, + } + + +def _attention(trigger: str, fact: str) -> dict[str, Any]: + """One attention item, in the shape `attention.py` writes.""" + return { + "trigger": trigger, + "course": "course-1", + "fact": fact, + "window_from": NOW - 30 * DAY, + "window_to": NOW, + "evidence": {"missing": 4, "cohort_median": 1}, + } + + +def summaries() -> list[dict[str, Any]]: + """`zeka_student_summary` rows, exactly as ZEKA writes them (no `school`).""" + return summary_rows( + [ + StudentSummary( + school=SCHOOL, + student="ogrenci-a", + computed_at=NOW, + marks=_marks("course-1", "Matematik", "review"), + attendance={"overall": {"rate": 0.82}, "courses": {}}, + submission={"overall": {"n": 12, "n_submitted": 9, "n_missing": 3}}, + study={"recent_28d": {"n_stints": 11, "active_days": 7}}, + attention=[_attention("homework", FACT_A)], + confidence=Confidence.STABLE, + ), + StudentSummary( + school=SCHOOL, + student="ogrenci-b", + computed_at=NOW, + marks=_marks("course-2", "Fen Bilimleri", "on_track"), + attendance={"overall": {"rate": 0.95}, "courses": {}}, + submission={"overall": {"n": 11, "n_submitted": 11, "n_missing": 0}}, + study={"recent_28d": {"n_stints": 15, "active_days": 9}}, + attention=[_attention("mark_trend", FACT_B)], + confidence=Confidence.STABLE, + ), + StudentSummary( + school=SCHOOL, + student="ogrenci-c", + computed_at=NOW, + marks=_marks("course-1", "Matematik", "insufficient_data"), + attendance={"overall": {"rate": 1.0}, "courses": {}}, + submission={"overall": {"n": 10, "n_submitted": 10, "n_missing": 0}}, + study={"recent_28d": {"n_stints": 8, "active_days": 6}}, + confidence=Confidence.EXPLORATORY, + ), + ] + ) + + +def recommendations() -> list[dict[str, Any]]: + """`zeka_recommendation` rows: teacher, student and parent cards. + + The parent card is the gate witness: `allowed_roles("okul")` is + `STAFF_ROLES | STUDENT_FACING_ROLES` (`report/gate.py`), so teacher and + student cards show in the school report and the parent card must not. + """ + rows, rejected = recommendation_rows( + [ + Recommendation( + school=SCHOOL, + audience="ogretmen-1", + audience_role=Audience.TEACHER, + product="T4", + rule_id="T4.homework", + about="ogrenci-a", + course="course-1", + evidence={"missing": 4, "cohort_median": 1}, + limitation="Teslim anı bilinmiyor.", + confidence=Confidence.STABLE, + computed_at=NOW, + expires_at=NOW + 7 * DAY, + ), + Recommendation( + school=SCHOOL, + audience="ogrenci-a", + audience_role=Audience.STUDENT, + product="O1", + rule_id="O1.review_band", + course="course-1", + evidence={"student_average": 42.5, "class_average": 68.0}, + limitation="Konu kırılımı yok.", + confidence=Confidence.STABLE, + computed_at=NOW, + expires_at=NOW + 7 * DAY, + ), + Recommendation( + school=SCHOOL, + audience="veli-1", + audience_role=Audience.PARENT, + product="V1", + rule_id="V1.parent_only", + about="ogrenci-a", + evidence={"n": 3}, + limitation="Veli kartı okul raporunda gösterilmez.", + confidence=Confidence.STABLE, + computed_at=NOW, + expires_at=NOW + 7 * DAY, + ), + ] + ) + assert rejected == 0, "fixture rows must carry evidence" + return rows + + +def profiles() -> list[dict[str, Any]]: + """`zeka_student_segment_profile` rows.""" + return profile_rows( + [ + StudentSegmentProfile( + school=SCHOOL, + student="ogrenci-a", + dimension="bilissel_talep", + label="analiz", + n_answers=120, + n_correct=60, + overall_n_answers=400, + overall_accuracy=0.61, + computed_at=NOW, + confidence=Confidence.STABLE, + ), + StudentSegmentProfile( + school=SCHOOL, + student="ogrenci-b", + dimension="dikkat_tuzagi", + label="var", + n_answers=150, + n_correct=90, + overall_n_answers=400, + overall_accuracy=0.61, + computed_at=NOW, + confidence=Confidence.EXPLORATORY, + ), + ] + ) + + +def runs() -> list[dict[str, Any]]: + """`zeka_run` rows, keyed the way the store writes them.""" + return [ + run_row( + { + "started_at": NOW - 3600_000, + "finished_at": NOW, + "status": "ok", + "students_total": 3, + "students_ok": 3, + "students_failed": 0, + "students_skipped": 0, + "rows_written": 9, + "budget_exceeded": False, + "budget_ms": 60_000, + "pending_students": [], + "failed_modules": [], + }, + f"{SCHOOL}_{RUN_DAY}", + ) + ] + + +def payload(**over: Any) -> dict[str, Any]: + """The request exactly as the backend builds it (`## insight.report`).""" + sent: dict[str, Any] = { + "kind": "okul", + "run_day": RUN_DAY, + "requested_by": "mudur-1", + "school": {"id": "01990000-0000-7000-8000-000000000001", "slug": SCHOOL, "name": DISPLAY}, + "summaries": summaries(), + "recommendations": recommendations(), + "profiles": profiles(), + "runs": runs(), + } + sent.update(over) + return sent + + +class ReportCase(unittest.IsolatedAsyncioTestCase): + """Wired table, one school, and the payload the backend will send.""" + + def setUp(self) -> None: + handlers.wire() + + def tearDown(self) -> None: + capabilities._handlers.clear() + + async def dispatch(self, sent: dict[str, Any]) -> dict[str, Any]: + return await capabilities.dispatch("insight.report", SCHOOL, sent) + + +class DispatchTests(ReportCase): + async def test_report_is_unknown_until_wire_registers_it(self) -> None: + capabilities._handlers.clear() + with self.assertRaises(CapabilityError) as caught: + await self.dispatch(payload()) + self.assertEqual(caught.exception.code, "unknown_capability") + + handlers.wire() + answer = await self.dispatch(payload()) + self.assertEqual(answer["format"], "html") + + def test_the_boot_self_check_counts_it_dispatchable(self) -> None: + self.assertIn("insight.report", capabilities.dispatchable_names()) + capabilities.verify_dispatchable() # a clean bill: no raise + + capabilities._handlers.pop("insight.report") + with self.assertRaises(capabilities.RegistrationError) as caught: + capabilities.verify_dispatchable() + self.assertIn("insight.report", str(caught.exception)) + + +class DocumentTests(ReportCase): + async def test_the_html_carries_name_count_and_per_student_lines(self) -> None: + answer = await self.dispatch(payload()) + html = answer["html"] + + # 1) a self-contained HTML document, not an error page + self.assertTrue(html.startswith("")) + # 2) the DISPLAY name the payload carried is the title + self.assertIn(DISPLAY, html) + # 3) the student count is the number of summaries the backend sent -- + # rows carry no `school`, so this also proves the frame's stamp + self.assertIn('