diff --git a/service/README.md b/service/README.md index 3fef8b2..7deb56f 100644 --- a/service/README.md +++ b/service/README.md @@ -150,13 +150,14 @@ Tohum verisinde 217.498 sınav cevabı ve kasıtlı olarak bozuk maddeler var. Y `docs/BACKEND-GEREKSINIMLERI.md` üç maddelik listeyi gerekçeleriyle içerir: -1. **`insight.*` depo yolu açıldı; sunucu-baslatımlı yön açık.** ZEKA'nın +1. **`insight.*` depo yolu açıldı; sunucu-baslatımlı yön `insight.student` + + `insight.refresh` için açık.** ZEKA'nın çağırdığı dokuz operasyon backend'de 2026-09-17'de açıldı (`f84c29d`) ve - çalışır. Backend'in **çağırabildiği** adlar hâlâ yalnız `chat.reply` ve - `rag.index`'tir: servis ettiği üç yetenek (`insight.student`, - `insight.class`, `insight.refresh`) dağıtım kapısı bekliyor; backend'de bu iş - **`InsightDoors`** hattının sahibindedir ve o yön kapılar gelene kadar istek - üzerine tetikleme kapalıdır. + çalışır. Backend'in **çağırabildiği** adlar 2026-09-18 itibarıyla + `chat.reply`, `rag.index`, `insight.student` ve `insight.refresh`'tir; + `insight.class` ilan edilir ama gönderilmez (kadro listeleme yolu yok -- + Madde 3). Servis tarafında ilan ile dağıtım açılışta denetlenir + (`src/handlers.py`, `capabilities.verify_dispatchable()`). 2. **Sınav yolları izin listesinde yok.** Madde analizi için gereken 9 yol listelenmiştir. 3. **Öğrenci listeleme yolu yok.** Okul listesi artık köprüden (`insight.schools.list`), ama kimlerin işleneceği hâlâ yapılandırmadan çözülüyor. Dönem ortası kayıt olan diff --git a/service/docs/BACKEND-GEREKSINIMLERI.md b/service/docs/BACKEND-GEREKSINIMLERI.md index fed90b6..c563537 100644 --- a/service/docs/BACKEND-GEREKSINIMLERI.md +++ b/service/docs/BACKEND-GEREKSINIMLERI.md @@ -19,22 +19,28 @@ istemci-baslatimli bir yetenek cercevesi tanimli degildir (Madde 1). Yani asagidaki uc madde ZEKA'nin nelerin **disinda** kaldigini tarif eder. -> **DURUM (2026-09-17).** Madde 1'in **(a) servisin cagirdigi `insight.*` +> **DURUM (2026-09-18).** Madde 1'in **(a) servisin cagirdigi `insight.*` > operasyonlari** yonu backend'de **acildi** (`f84c29d`): kapi listesi > `/api-docs/openapi.json` icinde gorunur ve `insight.schools.list`, > `insight.pending.list`, `insight.retention.sweep` canli backend'e karsi > kosturuldu (uclu de basarili dondu). **(b) backend'in ZEKA'yi cagirmasi** -> yonu -- dagitim tablosundaki `insight.student` / `insight.class` / -> `insight.refresh` -- **HALA ACIKTIR**. Asagidaki "yoktur / tanimli degil" -> ifadeleri bu iki yonu ayirmadan okunmamalidir; `src/capabilities.py` modul -> dokumani ayni ayrimi yapar. +> yonu 2026-09-18'de `insight.student` ve `insight.refresh` icin **acildi** +> (`ai/insight.rs::compute_student/refresh` + `web/insights.rs` kapilari) ve +> 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 +> ayirmadan okunmamalidir; `src/capabilities.py` modul dokumani ayni ayrimi +> yapar. --- -## Madde 1 -- `insight.*`: depo yolu ACILDI, sunucu-baslatimli yon acik +## Madde 1 -- `insight.*`: depo yolu ACILDI, sunucu-baslatimli yon student+refresh icin ACILDI **Sahibi: backend'deki `InsightDoors` hatti.** Asagidaki zarf DONMUS'TUR; servis -ona karsi yazildi. (a) yonu 2026-09-17'de acildi (`f84c29d`); (b) yonu aciktir. +ona karsi yazildi. (a) yonu 2026-09-17'de acildi (`f84c29d`); (b) yonu +2026-09-18'de `insight.student` + `insight.refresh` icin acildi; `insight.class` +icin hala aciktir (kadro listeleme yolu -- Madde 3). ### Ne isteniyor @@ -81,6 +87,12 @@ kolonu yoktur. **b) Servisin servis ettigi yetenekler (sunucu-baslatimli akis).** `src/constant.rs` icine yeni yetenek sabitleri ve onlari cagiran dagitim kodu: +> **DURUM (2026-09-18).** Sabitler ve dagitim kodu merged: `insight.student` +> ve `insight.refresh` gonderilir (`ai/insight.rs`, `web/insights.rs`); +> `insight.class` sabiti durur ama onu gonderen bir yol yoktur. Servis tarafi +> ayni gun baglandi: `handlers.wire()` uc adi da kaydeder ve acilista +> `capabilities.verify_dispatchable()` ilan ile dagitimi karsilastirir. + ```rust /// ZEKA -- tek ogrenci icin analiz/tavsiye. pub const AI_INSIGHT_STUDENT_CAPABILITY: &str = "insight.student"; @@ -283,7 +295,7 @@ Yani kapsam **elle** tutulur. | # | Istenen | Kaynak dosya | Olmazsa kaybedilen | |---|---|---|---| -| 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` | +| 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 | diff --git a/service/docs/CIKTI-SOZLESMESI.md b/service/docs/CIKTI-SOZLESMESI.md index 169541f..d607d02 100644 --- a/service/docs/CIKTI-SOZLESMESI.md +++ b/service/docs/CIKTI-SOZLESMESI.md @@ -416,6 +416,8 @@ bu tuzak yapısal olarak imkânsızdır. 5. **`T3.segment_class_gap` gerçek bir sınıfta hiç ateşlemedi** — yalnız yapay pozitif kontrolde. Ekranı kurulabilir, ama boş kalabileceği varsayılmalıdır. 6. **`insight.*` depo kapıları açıldı (`f84c29d`); backend'in ZEKA'yı çağırması - hâlâ kapalı.** Servis satırlarını bu depo kapılarından yazar; sunucu-baslatımlı - üç yetenek için dağıtım kapısı gelene kadar gece koşusu `partial` yazılır. - Sahibi backend'deki `InsightDoors` hattı — `docs/BACKEND-GEREKSINIMLERI.md` Madde 1. + 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. diff --git a/service/src/bridge.py b/service/src/bridge.py index 06ee6f6..ca10a64 100644 --- a/service/src/bridge.py +++ b/service/src/bridge.py @@ -40,7 +40,7 @@ from aioquic.asyncio.protocol import QuicConnectionProtocol from aioquic.quic.configuration import QuicConfiguration from aioquic.quic.events import ConnectionTerminated, QuicEvent, StreamDataReceived -from . import capabilities, config, protocol +from . import capabilities, config, handlers, protocol from .protocol import ( ApiRefused, ApiResponse, @@ -553,7 +553,17 @@ async def run_once( handler: RequestHandler | None = None, on_ready: Callable[[BridgeProtocol], Any] | None = None, ) -> None: - """Sertifikayi cek, bagla, kaydol, baglanti kapanana kadar bekle.""" + """Sertifikayi cek, bagla, kaydol, baglanti kapanana kadar bekle. + + Kaydolmadan HEMEN once iki sey yapilir: isleyici defteri kurulur + (`handlers.wire()`) ve ilan edilecek her adin karsiligi oldugu denetlenir + (`capabilities.verify_dispatchable()`). `Hello` cercevesinin ciktigi tek + yer burasidir; denetim buraya konunca ilan edip servis edememe durumu + yapisal olarak imkansiz olur -- defter haftalarca bosken uc ad ilan + ediliyordu ve backend'in her istegi `unknown_capability` ile donuyordu. + """ + handlers.wire() + capabilities.verify_dispatchable() cert_pem = fetch_certificate(settings) quic_config = build_quic_configuration(settings, cert_pem) config.log( @@ -771,19 +781,25 @@ async def _serve(settings: config.Config) -> int: capabilities.bind_store(store) config.log("info", "depo: kopru (insight.*) -- yerel veritabani yok") config.log("info", capabilities.summary()) - if settings.refresh_interval_secs <= 0: - config.log("info", "gece zamanlayicisi KAPALI (ZEKA_REFRESH_INTERVAL_SECS=0)") - return await run_forever(settings) - # Zamanlayici her okul icin bir `Source` ister. Baglanti kopmussa - # `BridgeSource` cagrisi hata verir ve zamanlayici o okulu duser -- - # dogru davranis: veri cekilemeden hesap yapilmaz. + # Zamanlayici da yetenek isleyicileri de her okul icin bir `Source` ister. + # Baglanti kopmussa `BridgeSource` cagrisi hata verir: zamanlayici o okulu + # duser, isleyici `unavailable` doner -- dogru davranis, cunku veri + # cekilemeden hesap yapilmaz ve sessiz bos cevap uretilmez. Baglama + # ZAMANLAYICI KAPALIYKEN DE yapilir: istekleri karsilayan sey zamanlayici + # degil koprudur. def source_for(_school: str) -> Any: proto = kopru["protocol"] if proto is None: raise RuntimeError("kopru henuz bagli degil") return BridgeSource(proto) + handlers.bind_source(source_for) + + if settings.refresh_interval_secs <= 0: + config.log("info", "gece zamanlayicisi KAPALI (ZEKA_REFRESH_INTERVAL_SECS=0)") + return await run_forever(settings) + scheduler = Scheduler( source_for, store, diff --git a/service/src/capabilities.py b/service/src/capabilities.py index 0743232..314ec1f 100644 --- a/service/src/capabilities.py +++ b/service/src/capabilities.py @@ -2,15 +2,18 @@ IKI YON VARDIR; karistirilmamalidir: -1. **Sunucu-baslatimli (backend -> ZEKA).** Backend'in ZEKA'ya `Request` - gondermesi icin asagidaki adlari DAGITIM tablosunda tanimasi gerekir. - Bugun backend'in cagirabildigi tek iki ad `chat.reply` ve `rag.index`'tir - (`constant.rs:568` ve `constant.rs:574`); asagidaki `insight.*` adlarinin - hicbiri orada YOKTUR. Yonlendirme TAM ESLESME iledir (`ai/protocol.rs:91-94`, - `ai/registry.rs`): ZEKA baglanip bu adlari ilan etse bile backend onlara - hicbir `Request` gondermez. Bu yon HALA ACIKTIR. Kopru tarafi (`bridge.py`) - gelen cerceveleri karsilamaya hazirdir ki backend bu adlari tanidigi gun - tek satir degisiklik gereksin. +1. **Sunucu-baslatimli (backend -> ZEKA).** The backend dispatches `Request` + frames only for names its own dispatch table carries, and today + `insight.student` and `insight.refresh` are there: `ai/insight.rs` + `compute_student()` / `refresh()` send both, and the doors are in + `web/insights.rs` (merged 2026-09-18). `insight.class` is advertised but + 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). + 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 + service REFUSES TO BOOT. 2. **Istemci-baslatimli (ZEKA -> backend, depo yolu).** ZEKA'nin kendi `zeka_*` satirlarini yazip okudugu yol budur: `store.BridgeStore`, @@ -34,10 +37,13 @@ kosar; backend'in yetenegi tanimasi yalnizca "istege bagli tetikleme"yi acar. from __future__ import annotations +import logging from typing import Any, Callable, TypedDict from .protocol import CapabilityError +log = logging.getLogger(__name__) + # --- yetenek adlari -------------------------------------------------------- # Ad alani `.` desenini izler; backend'in `chat.reply` ve # `rag.index` adlari da boyledir. @@ -54,12 +60,26 @@ INSIGHT_REFRESH = "insight.refresh" NAMES: tuple[str, ...] = (INSIGHT_STUDENT, INSIGHT_CLASS, INSIGHT_REFRESH) -#: Backend'in ZEKA'ya `Request` GONDEREBILDIGI yetenek adlari -#: (`constant.rs:568,574`) -- dagitim tablosunun tamami. Servisin cagirdigi -#: `insight.*` depo operasyonlarini KAPSAMAZ (bkz. modul dokumani, 2. yon). -#: ZEKA'nin hicbiri bu kumede degildir; kesisim bos oldugu surece backend -#: ZEKA'yi cagiramaz. `tests/test_capabilities.py` bu gercegi pinler. -BACKEND_CALLABLE_CAPABILITIES: tuple[str, ...] = ("chat.reply", "rag.index") +#: The capability names the backend can send a `Request` FOR -- the half of +#: its dispatch table that concerns ZEKA. It does NOT cover the `insight.*` +#: storage operations the service calls (see the module docstring, direction +#: 2). Sources: `constant.rs:568,574` (chat.reply, rag.index) and +#: `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. +#: `tests/test_capabilities.py` pins this. +BACKEND_CALLABLE_CAPABILITIES: tuple[str, ...] = ( + "chat.reply", + "rag.index", + "insight.student", + "insight.refresh", +) + +#: The `sections` vocabulary: the summary's four compute modules. A request +#: may name a subset; an unrequested module is NOT computed and reaches the +#: row as `null` -- the backend's `SummaryRow` keeps `null` ("not computed") +#: and `{}` ("read, and there was nothing") apart on purpose. +SECTIONS: tuple[str, ...] = ("marks", "attendance", "submission", "study") # --- payload sozlesmeleri -------------------------------------------------- @@ -81,14 +101,14 @@ class StudentRequest(TypedDict, total=False): class StudentResponse(TypedDict, total=False): - """`insight.student` cevap payload'i.""" + """`insight.student` cevap payload'i (`handlers.student` doldurur).""" user_id: str generated_at: str # ISO-8601 - archetype: str # tespit edilen calisma profili - signals: list[dict[str, Any]] # {kind, severity, evidence, ...} - recommendations: list[dict[str, Any]] # {action, rationale, weight} - coverage: dict[str, Any] # hangi veri kaynagindan kac kayit okundu + archetype: str # BUGUN URETILMIYOR; alan gonderilmez (coverage.unavailable yazar) + signals: list[dict[str, Any]] # dikkat maddeleri: {trigger, course, fact, window_from, window_to, evidence} + recommendations: list[dict[str, Any]] # zeka_recommendation satirinin govdesi; `retain_until` gonderilmez + coverage: dict[str, Any] # okunan kaynak -> kayit sayisi + yazma muhasebesi + uretilemeyenler class ClassRequest(TypedDict, total=False): @@ -100,13 +120,13 @@ class ClassRequest(TypedDict, total=False): class ClassResponse(TypedDict, total=False): - """`insight.class` cevap payload'i.""" + """`insight.class` cevap payload'i (`handlers.klass` doldurur).""" course_id: str generated_at: str cohort_size: int - topic_gaps: list[dict[str, Any]] # {topic, mastery, cohort_share} - attention_list: list[dict[str, Any]] # {user_id, reason, score} + topic_gaps: list[dict[str, Any]] # BUGUN URETILMIYOR: bos liste + coverage.unavailable nedeni + attention_list: list[dict[str, Any]] # {user_id, trigger, fact, window_from, window_to, evidence} -- SKOR YOK coverage: dict[str, Any] @@ -120,13 +140,17 @@ class RefreshRequest(TypedDict, total=False): class RefreshResponse(TypedDict, total=False): - """`insight.refresh` cevap payload'i.""" + """`insight.refresh` cevap payload'i (`handlers.refresh` doldurur).""" started_at: str requested: int computed: int skipped: int - failed: list[dict[str, Any]] # {user_id, code, message} + failed: list[dict[str, Any]] # {user_id, code, message} -- code: unavailable|internal + #: Sozlesme disi ek alan: kosunun hukmu (`running|ok|partial|failed`). + #: Backend'in struct'i bunu tasimaz ve serde bilinmeyen alani yok sayar; + #: onsuz "0 istendi, 0 hesaplandi" temiz bir sifir gibi okunurdu. + status: str #: Yetenek adi -> (istek tipi, cevap tipi). Belge ve dogrulama icin. @@ -176,12 +200,48 @@ def names() -> list[str]: def register(name: str, handler: Handler) -> None: """Bir yetenegi kaydet. Ilan edilmeyen ada kayit kabul edilmez -- ilan ile - dagitimin ayrisabilecegi tek yer burasi, o yuzden kapatiliyor.""" + dagitimin ayrisabilecegi tek yer burasi, o yuzden kapatiliyor. + + Isleyici es zamanli (async) olabilir: `bridge._handle` boyle bir kancayi + olay dongusunde bekler, senkron olani is parcacigina verir + (`bridge.py:495-515`). ZEKA'nin isleyicileri async'tir cunku her okuma + kendi kopru cagrisidir (`handlers.py`).""" if name not in NAMES: raise KeyError(f"ilan edilmeyen yetenek kaydedilemez: {name!r}") _handlers[name] = handler +class RegistrationError(RuntimeError): + """Ilan edilen bir adin isleyicisi yok. Acilista, bilerek patlar.""" + + +def dispatchable_names() -> list[str]: + """Isleyicisi KAYITLI adlar. `names()` ne ilan edilecegini soyler.""" + return [name for name in NAMES if name in _handlers] + + +def verify_dispatchable() -> None: + """Ilani hak etmeyen tek bir ad varsa ACILISI durdur. + + `bridge.run_once()` `Hello` cercevesini yazmadan hemen once cagirir, yani + ilan eden her yol bu denetimden gecmistir. Defter haftalarca BOSTU ve + `Hello` uc ad ilan ediyordu: backend'in gonderdigi her istek, ilan edilen + adi ayni cumlede sayan bir `unknown_capability` ile donuyordu. Bu sinifin + tekrar uretilmesini imkansiz kilan sey, ilan ile defterin ayni anda + dogrulanmasidir -- sonradan ozur dilemek degil. + """ + missing = [name for name in NAMES if name not in _handlers] + if not missing: + return + message = ( + f"ilan edilen yeteneklerin isleyicisi yok: {', '.join(missing)} " + f"(kayitli: {', '.join(dispatchable_names()) or 'yok'}) -- " + "servis bunlari ILAN EDEMEZ; handlers.wire() cagrildi mi?" + ) + log.error(message) + raise RegistrationError(message) + + def dispatch(name: str, school: str, payload: Any) -> dict[str, Any]: """Gelen `Request`'i isleyicisine ver. @@ -211,17 +271,19 @@ def require_text(payload: dict[str, Any], key: str) -> str: def summary() -> str: """Acilis logu icin tek satir: iki yonu AYRI soyler. - Onceki hali "(backend'in tanidigi: chat.reply, rag.index; N yetenek - TANIMSIZ, istek gelmeyecek)" idi ve depo yolu (2. yon) calismaya - basladiktan sonra backend'in `insight` hakkinda hicbir sey bilmedigi - okunuyordu. Liste backend'in **cagirabildikleridir**; servisin - **cagirdigi** operasyonlari kapsamaz. + Onceki hali "backend'in tanidigi: chat.reply, rag.index; N yetenek + TANIMSIZ" idi; depo yolu (2. yon) acildiktan ve backend `insight.student` + / `insight.refresh`i gonderdikten sonra bu cumle bayatladi. Uc gercek + ayri ayri yazilir: backend'in gonderebildigi adlar, servisin kayitli + isleyicileri, ve backend'in dagitim tablosunda hala olmayan adlar. """ - not_callable = [n for n in NAMES if n not in BACKEND_CALLABLE_CAPABILITIES] + served = dispatchable_names() + unsent = [name for name in NAMES if name not in BACKEND_CALLABLE_CAPABILITIES] return ( f"backend'in cagirabildigi yetenekler: " f"{', '.join(BACKEND_CALLABLE_CAPABILITIES)} " f"(servis->backend depo yolu: kopru/insight.* -- bu liste onu kapsamaz); " - f"servis tarafi isler ({', '.join(NAMES)}) backend tarafindan HENUZ " - f"cagrilmiyor ({len(not_callable)} ad dagitim tablosunda yok)" + f"servis tarafi isleyiciler: {len(served)}/{len(NAMES)} kayitli " + f"({', '.join(served) or 'yok'}); " + f"backend'in dagitim tablosunda olmayan: {', '.join(unsent) or 'yok'}" ) diff --git a/service/src/compute/model.py b/service/src/compute/model.py index 204081f..9bc5264 100644 --- a/service/src/compute/model.py +++ b/service/src/compute/model.py @@ -178,10 +178,13 @@ class StudentSummary: school: str student: str computed_at: int - marks: dict[str, Any] = field(default_factory=dict) - attendance: dict[str, Any] = field(default_factory=dict) - submission: dict[str, Any] = field(default_factory=dict) - study: dict[str, Any] = field(default_factory=dict) + #: Dört modül `None` OLABİLİR: `sections` ile istenmeyen modül hesaplanmaz + #: ve satıra `null` gider ("hesaplanmadı"), boş sözlük ise "okundu, kaynak + #: satır yok" demektir (backend `db/insight.rs` `SummaryRow` sözleşmesi). + marks: dict[str, Any] | None = field(default_factory=dict) + attendance: dict[str, Any] | None = field(default_factory=dict) + submission: dict[str, Any] | None = field(default_factory=dict) + study: dict[str, Any] | None = field(default_factory=dict) attention: list[dict[str, Any]] = field(default_factory=list) confidence: Confidence = Confidence.NONE diff --git a/service/src/handlers.py b/service/src/handlers.py new file mode 100644 index 0000000..96cc350 --- /dev/null +++ b/service/src/handlers.py @@ -0,0 +1,430 @@ +"""The three `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 +it, and `bridge.run_once()` calls `wire()` together with +`capabilities.verify_dispatchable()` right before the `Hello` frame goes out -- +a name that cannot be dispatched must never be advertised, and that is the +defect class this file exists to close (three names were announced for weeks +with an empty table behind them, so every `insight.student` / +`insight.refresh` dispatch was answered `unknown_capability`). + +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. + +Handlers are coroutines on purpose. `bridge.BridgeProtocol._handle()` awaits a +coroutine handler in the event loop and pushes only *sync* handlers into the +executor (`bridge.py:495-515`); the compute path is async end to end because +every school read is a bridge call of its own. + +What each handler answers is the backend's contract, verbatim: +`hezarfen_backend/src/ai/insight.rs` (the payload structs) and +`src/web/insights.rs` (the doors). Where a contract field cannot be produced +from the data the bridge exposes, the answer says so in `coverage` instead of +filling it with a plausible value. +""" + +from __future__ import annotations + +import asyncio +import time +from datetime import datetime, timezone +from typing import Any, Callable + +from . import capabilities +from .compute import attention as attention_mod +from .compute import marks as marks_mod +from .pipeline import StudentOutcome, run_school +from .protocol import CapabilityError +from .store import attention_items, recommendation_rows + +#: `StudentOutcome.error_kind` -> the refusal code the caller branches on. +#: A read that could not be made is `unavailable` (the source may come back); +#: a compute that fell over is `internal` (it will not). +_ERROR_CODES = {"fetch": "unavailable", "compute": "internal"} + +#: What this version cannot answer, said once. These notes travel in every +#: answer's `coverage.unavailable`: the contract's response members are all +#: optional (`total=False`), so an omitted field is legal -- but an omission a +#: reader cannot see is indistinguishable from a field nobody asked about. +_UNAVAILABLE = { + "archetype": ( + "no study-pattern classifier exists in this version; the field is " + "omitted rather than guessed" + ), + "topic_gaps": ( + "item-level data (question, choice, answer) is not in the bridge read " + "allowlist; see docs/BACKEND-GEREKSINIMLERI.md item 2" + ), + "roster": ( + "no member listing; a class roster is derived from the ids addressed " + "by that course's homework (the same workaround as " + "pipeline.discover_students)" + ), + "term": "no term directory; `term` must be an ISO-8601 date", +} + +#: School slug -> lock. One compute per school at a time: a dispatched refresh +#: and the night scheduler can overlap, and two `run_school` sweeps on one +#: school would interleave the day's run-ledger row (the row is keyed by +#: `run_day`) and race the per-student upserts. In-process only, which is +#: enough because the service is one process (`scheduler.py:44-45`). +_locks: dict[str, asyncio.Lock] = {} + +#: Set once by `bridge._serve`: `school -> Source`. Writes and reads travel the +#: same bridge, so the factory closes over the live connection. +_source_factory: Callable[[str], Any] | None = None + + +def bind_source(factory: Callable[[str], Any]) -> None: + """Bind the school -> `Source` factory. Called once, at startup.""" + global _source_factory + _source_factory = factory + + +def _source(school: str) -> Any: + """The live source for one school. Never a fabricated or default one: + a handler that cannot read is `unavailable`, not silently empty.""" + if _source_factory is None: + raise CapabilityError( + "unavailable", + "no data source is bound; bridge._serve() binds it at startup", + ) + return _source_factory(school) + + +def wire() -> None: + """Register every advertised name. Idempotent; called from `run_once`.""" + capabilities.register(capabilities.INSIGHT_STUDENT, student) + capabilities.register(capabilities.INSIGHT_CLASS, klass) + capabilities.register(capabilities.INSIGHT_REFRESH, refresh) + + +def _lock_for(school: str) -> asyncio.Lock: + lock = _locks.get(school) + if lock is None: + lock = asyncio.Lock() + _locks[school] = lock + return lock + + +def _now_ms() -> int: + return int(time.time() * 1000) + + +def _iso(ms: int) -> str: + """Unix ms -> ISO-8601 UTC. The contract's `generated_at`/`started_at`.""" + return datetime.fromtimestamp(ms / 1000, tz=timezone.utc).isoformat() + + +def _iso_ms(value: Any, field: str) -> int: + """The only date shape this service can honor: ISO-8601 -> unix ms. + + It reaches the pipeline as `term_start_ms`, which is the one way a caller + can move the `attention` window's start (`attention._cold_start`): a + recent `since` means "the term just began", which is what an ISO date can + honestly mean to a service that has no term directory. + """ + if not isinstance(value, str) or not value.strip(): + raise CapabilityError("bad_request", f"'{field}' must be an ISO-8601 date") + try: + parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00")) + except ValueError: + raise CapabilityError( + "bad_request", f"'{field}' is not a readable ISO-8601 date: {value!r}" + ) from None + if parsed.tzinfo is None: + parsed = parsed.replace(tzinfo=timezone.utc) + return int(parsed.timestamp() * 1000) + + +def _sections(value: Any) -> tuple[str, ...] | None: + """`sections` as the pipeline's filter set; `None` is "all of them".""" + if value is None: + return None + allowed = ", ".join(capabilities.SECTIONS) + if not isinstance(value, list) or not all( + isinstance(name, str) and name.strip() for name in value + ): + raise CapabilityError("bad_request", f"'sections' must name some of: {allowed}") + names = tuple(name.strip() for name in value) + unknown = [name for name in names if name not in capabilities.SECTIONS] + if unknown: + raise CapabilityError( + "bad_request", + f"'sections' names something this service does not compute: " + f"{', '.join(unknown)} (allowed: {allowed})", + ) + return names + + +def _top_n(value: Any) -> int | None: + if value is None: + return None + if isinstance(value, bool) or not isinstance(value, int) or value <= 0: + raise CapabilityError("bad_request", "'top_n' must be a positive integer") + return value + + +def _cards(recs: list[Any]) -> list[dict[str, Any]]: + """The answer's card shape = the stored row minus storage bookkeeping. + + Built through the same `store.recommendation_rows` the write uses, so the + cards in the answer are exactly the cards that can land: a card the store + would refuse (no evidence beyond `limitation`) is not claimed here either. + `retain_until` stays out: it is the sweep's business, not the wire's. + """ + rows, _rejected = recommendation_rows(recs) + for row in rows: + row.pop("retain_until", None) + return rows + + +async def _sweep( + school: str, + student_ids: list[str] | None, + *, + now: int, + term_start_ms: int | None = None, + sections: tuple[str, ...] | None = None, + nightly: bool = False, +) -> tuple[Any, list[StudentOutcome]]: + """One scoped compute: the pipeline, the store, and the outcomes. + + `nightly=False` for the per-student and per-class handlers: the run + ledger, the departed purge and the retention sweep belong to the + school-wide job. A dispatched compute must not overwrite the day's + `zeka_run` row (keyed by `run_day`) nor claim a subset of students is the + active roster. `handlers.refresh` is the one caller that passes `True`: + it *is* the school sweep, on demand, and its run record belongs in the + same ledger row the backend's `GET /insights/runs` reads. + """ + outcomes: list[StudentOutcome] = [] + store = capabilities.store().store_for(school) + result = await run_school( + _source(school), + store, + school, + now_ms=now, + student_ids=None if student_ids is None else list(student_ids), + term_start_ms=term_start_ms, + nightly=nightly, + sections=sections, + outcomes=outcomes, + ) + return result, outcomes + + +async def student(school: str, payload: dict[str, Any]) -> dict[str, Any]: + """`insight.student` -- one student, computed and written now. + + The two request knobs are honored at the only place they can be: + `since` moves the term start the attention window is measured from, and + `sections` narrows which of the four summary modules is computed. A + module that was not requested is written `null` -- the backend's + `SummaryRow` calls that "not computed", distinct from `{}` ("read, and + there was nothing"). + """ + user_id = capabilities.require_text(payload, "user_id") + since = payload.get("since") + term_start_ms = _iso_ms(since, "since") if since is not None else None + sections = _sections(payload.get("sections")) + now = _now_ms() + async with _lock_for(school): + result, outcomes = await _sweep( + school, [user_id], now=now, term_start_ms=term_start_ms, sections=sections + ) + outcome = outcomes[0] + if outcome.error is not None or outcome.summary is None: + raise CapabilityError( + _ERROR_CODES.get(outcome.error_kind or "compute", "internal"), + f"'{user_id}' could not be computed: {outcome.error}", + ) + summary = outcome.summary + return { + "user_id": summary.student, + "generated_at": _iso(summary.computed_at), + # The attention list is the signal list. It is teacher-facing and the + # backend decides who reads it (`web/insights.rs` keeps it out of the + # student's own view); the handler does not pre-filter it away. + "signals": attention_items(summary), + # Cards addressed to this student, and only those: the same table + # carries the teacher's T3/T4 cards about the student, and the role + # gate (`audience_role`) is applied here as well as on the read side. + "recommendations": _cards( + [ + rec + for rec in outcome.recommendations + if rec.audience == user_id and str(rec.audience_role) == "student" + ] + ), + "coverage": { + "reads": dict(outcome.coverage), + "sections": sorted(sections) if sections else "all", + "write": { + "rows_written": result.rows_written, + "write_failed": result.write_failed, + }, + "unavailable": { + **_UNAVAILABLE, + "attention_triggers": attention_mod.unavailable_triggers(), + }, + }, + } + + +async def _roster_for_course( + source: Any, school: str, course_id: str +) -> tuple[list[str], dict[str, int]]: + """The students this course's homework was addressed to, in order. + + The same workaround `pipeline.discover_students` documents at school + level, narrowed to one course: there is no member listing in the bridge's + read allowlist (`docs/BACKEND-GEREKSINIMLERI.md` item 3). A student who + never received addressed homework for this course is invisible here, and + the answer says so in `coverage.unavailable.roster`. + """ + rows = await source.homework_list(school) + if isinstance(rows, dict): + rows = rows.get("items") or [] + found: list[str] = [] + seen: set[str] = set() + course_rows = 0 + for row in rows or []: + if not isinstance(row, dict) or marks_mod.course_id_of(row) != course_id: + continue + course_rows += 1 + for uid in row.get("assigned") or []: + key = str(uid) + if key not in seen: + seen.add(key) + found.append(key) + return found, {"homework_rows": len(rows or []), "course_rows": course_rows} + + +async def klass(school: str, payload: dict[str, Any]) -> dict[str, Any]: + """`insight.class` -- one course's roster, computed as a cohort. + + The backend declares the name but dispatches nothing to it yet + (`hezarfen_backend/src/ai/insight.rs`, module docs); the handler exists so + that the advertised name is true the moment a caller appears. + + The cohort is real but partial: the roster comes from homework addresses + (see `_roster_for_course`), so `cohort_size` counts the students whose + data could be read, and the answer never presents a truncated list as the + whole one -- `coverage.attention` carries `total` next to `returned`. + """ + course_id = capabilities.require_text(payload, "course_id") + term = payload.get("term") + term_start_ms = _iso_ms(term, "term") if term is not None else None + top_n = _top_n(payload.get("top_n")) + now = _now_ms() + async with _lock_for(school): + source = _source(school) + roster, roster_reads = await _roster_for_course(source, school, course_id) + store = capabilities.store().store_for(school) + outcomes: list[StudentOutcome] = [] + result = await run_school( + source, + store, + school, + now_ms=now, + student_ids=roster, + term_start_ms=term_start_ms, + nightly=False, + outcomes=outcomes, + ) + attention_list: list[dict[str, Any]] = [] + for outcome in outcomes: + if outcome.summary is None: + continue + for item in attention_items(outcome.summary): + attention_list.append({"user_id": outcome.student, **item}) + # Deterministic order, never a ranking: the doc's own rule (no score, no + # severity) survives truncation only if the order it truncates is the + # writer's, not a computed one. + attention_list.sort(key=lambda item: (item["user_id"], item["trigger"])) + total = len(attention_list) + if top_n is not None: + attention_list = attention_list[:top_n] + fetched = sum(1 for outcome in outcomes if outcome.coverage) + return { + "course_id": course_id, + "generated_at": _iso(now), + "cohort_size": fetched, + "topic_gaps": [], + "attention_list": attention_list, + "coverage": { + "roster": { + "students": len(roster), + "fetched": fetched, + "failed": sum(1 for outcome in outcomes if outcome.error is not None), + "budget_exceeded": result.budget_exceeded, + "pending": len(result.pending_students), + **roster_reads, + }, + "attention": {"total": total, "returned": len(attention_list)}, + "write": { + "rows_written": result.rows_written, + "write_failed": result.write_failed, + }, + "unavailable": _UNAVAILABLE, + }, + } + + +async def refresh(school: str, payload: dict[str, Any]) -> dict[str, Any]: + """`insight.refresh` -- the school sweep, on demand. + + This is the night job's own pipeline (`run_school`, `nightly=True`), so + the answer is written the same place the scheduler's is: the `zeka_run` + row the backend's `GET /insights/runs` serves. A refresh of the whole + school also purges departed students and sweeps retention, exactly like + the night run; a refresh naming `user_ids` does not -- that list is a + subset, and `insight.departed.purge` treats its list as the active roster. + + `force` is accepted and has no effect, stated rather than silently + ignored: the service keeps no result cache, so every refresh recomputes. + """ + user_ids = payload.get("user_ids") + if user_ids is not None: + if not isinstance(user_ids, list) or not all( + isinstance(uid, str) and uid.strip() for uid in user_ids + ): + raise CapabilityError( + "bad_request", "'user_ids' must be a list of non-empty strings" + ) + user_ids = [uid.strip() for uid in user_ids] + now = _now_ms() + async with _lock_for(school): + result, outcomes = await _sweep(school, user_ids, now=now, nightly=True) + return { + "started_at": _iso(result.started_at), + "requested": result.students_total, + "computed": result.students_ok, + "skipped": result.students_skipped, + "failed": [ + { + "user_id": outcome.student, + "code": _ERROR_CODES.get(outcome.error_kind or "compute", "internal"), + "message": outcome.error or "", + } + for outcome in outcomes + if outcome.error is not None + ], + # Beyond the backend's struct, which ignores what it does not read. + # Without it a reader would have to infer "ok" from counts, and a run + # whose roster could not even be listed (status `failed`, nothing + # counted) would read as a clean zero. + "status": result.status, + } + + +__all__ = [ + "bind_source", + "klass", + "refresh", + "student", + "wire", +] diff --git a/service/src/pipeline.py b/service/src/pipeline.py index 522c4ed..8c73a86 100644 --- a/service/src/pipeline.py +++ b/service/src/pipeline.py @@ -32,7 +32,7 @@ from __future__ import annotations import dataclasses import logging import time -from collections.abc import Callable +from collections.abc import Callable, Sequence from typing import Any from .compute import attendance as attendance_mod @@ -95,6 +95,45 @@ class RunResult: return {"school": self.school, **row} +#: The `sections` vocabulary (`capabilities.SECTIONS`), as a set the pipeline +#: can test against. Validation lives at the edge (`handlers._sections`); the +#: pipeline only applies the filter a caller hands it. +SECTION_NAMES: tuple[str, ...] = ("marks", "attendance", "submission", "study") + + +@dataclasses.dataclass(slots=True) +class StudentOutcome: + """One student's result, for the capability handlers. + + `RunResult` is bookkeeping only: it says how many students were counted, + not what any of them produced. A dispatched compute answers with a + payload per student, and this is where the per-student truth travels -- + which modules were read (`coverage`, empty when the fetch failed), what + was computed, and how it failed if it did. + + Only filled when the caller passes an `outcomes` list; the night run + collects none. + """ + + student: str + #: Source name -> records read. An EMPTY dict means the fetch failed, which + #: is a different claim from "read, and it was empty". + coverage: dict[str, int] = dataclasses.field(default_factory=dict) + summary: StudentSummary | None = None + recommendations: list[Recommendation] = dataclasses.field(default_factory=list) + error: str | None = None + #: `fetch` (the data could not be read) or `compute` (the arithmetic fell + #: over). `handlers._ERROR_CODES` maps it to the refusal code. + error_kind: str | None = None + + +def _section_filter(sections: Sequence[str] | None) -> frozenset[str] | None: + """`None` = every module (the night run). Otherwise the requested subset.""" + if sections is None: + return None + return frozenset(str(name) for name in sections) + + async def discover_students(source: Any, school: str) -> list[str]: """Okulun öğrenci kimliklerini türetir. @@ -138,16 +177,51 @@ class _Fetched: class_ids: list[str] course_stats: dict[str, dict[str, Any]] attendance_stats: dict[str, dict[str, Any]] + #: Source name -> records read (see `StudentOutcome.coverage`). + coverage: dict[str, int] + + +async def _fetch_student( + source: Any, school: str, student: str, *, sections: frozenset[str] | None = None +) -> _Fetched: + """Tek öğrencinin verisini çeker. Yasaklı alan çağrısı **yoktur**. + `sections` verilirse YALNIZ istenen modüllerin kaynakları okunur: bir + isteğe iki uç fazladan çağrı yapmak, okunmayan veri için de bir maliyet + ve bir hata yüzeyi yaratırdı. `profile` her hâlükârda okunur (şube + kimlikleri oradan gelir), ödev raporu da `submission` ya da `study` + istenmişse (çalışma profilinin teslim tarihleri ondan çıkar). + """ + everything = sections is None + + def want(name: str) -> bool: + return everything or name in sections -async def _fetch_student(source: Any, school: str, student: str) -> _Fetched: - """Tek öğrencinin verisini çeker. Yasaklı alan çağrısı **yoktur**.""" profile = await source.profile(school, student) - marks_raw = await source.marks(school, student) - attendance_raw = await source.attendance(school, student) - pomodoro_raw = await source.pomodoro(school, student) - report_raw = await source.homework_report(school, student) - homework_raw = await source.homework_list(school, student) + marks_raw = await source.marks(school, student) if want("marks") else None + attendance_raw = ( + await source.attendance(school, student) if want("attendance") else None + ) + pomodoro_raw = await source.pomodoro(school, student) if want("study") else None + need_report = want("submission") or want("study") + report_raw = ( + await source.homework_report(school, student) if need_report else None + ) + homework_raw = ( + await source.homework_list(school, student) if need_report else None + ) + coverage: dict[str, int] = {"profile": 1 if profile else 0} + if want("marks"): + coverage["marks"] = len(marks_mod.normalize_rows(marks_raw)) + if want("attendance"): + coverage["attendance"] = len(attendance_mod.normalize_rows(attendance_raw)) + if want("study"): + coverage["pomodoro"] = len(study_mod.normalize_rows(pomodoro_raw)) + if need_report: + coverage["homework_report"] = len( + submission_mod.normalize_items(report_raw) + ) + coverage["homework_list"] = len(homework_raw or []) return _Fetched( profile=profile, marks_raw=marks_raw, @@ -158,6 +232,7 @@ async def _fetch_student(source: Any, school: str, student: str) -> _Fetched: class_ids=marks_mod.class_ids_of(profile), course_stats=marks_mod.student_course_stats(marks_raw), attendance_stats=attendance_mod.course_stats(attendance_raw), + coverage=coverage, ) @@ -192,12 +267,34 @@ async def run_school( budget_ms: int = DEFAULT_BUDGET_MS, resume_students: list[str] | None = None, monotonic_fn: Callable[[], float] = time.monotonic, + nightly: bool = True, + sections: Sequence[str] | None = None, + outcomes: list[StudentOutcome] | None = None, ) -> RunResult: """Bir okul için hattı uçtan uca koşturur. `source` yalnız `Source` protokolündeki sekiz metodu uygular; bu fonksiyon başka hiçbir şey çağırmaz. + `nightly=False` (yetenek isleyicileri): koşu defteri, mezuniyet temizliği + ve saklama süpürmesi YAPILMAZ. Bunlar okul geneli gece işinin parçasıdır; + tek öğrencilik bir hesap günün `zeka_run` satırını (anahtar `run_day`) + ezmemeli ve bir ALT KÜMEYİ "aktif kadro" diye temizliğe vermemelidir. + Mezuniyet temizliği zaten yalnız kadro DİZİNDEN çıkarıldığında koşar: + çağıranın verdiği liste (`refresh user_ids`, `cli --students`) bir alt + kümedir ve backend'in `insight.departed.purge` kapısı tam bu yüzden + boş/kısmi listeyi reddeder. + + `sections`: hangi modüllerin hesaplanacağı (`SECTION_NAMES`). İstenmeyen + modül hesaplanmaz ve `StudentSummary` alanı `None` kalır -- satıra `null` + gider, backend'in `SummaryRow` sözleşmesindeki "hesaplanmadı". Ad + doğrulaması kenarda (`handlers._sections`) yapılır; burada bilinmeyen ad + sessizce "istenmemiş" sayılır. + + `outcomes`: verilirse her öğrenci için bir `StudentOutcome` eklenir + (başarılı, düşen ve bütçeye takılanlar için birer kayıt). Gece koşusu + toplamaz; yetenek isleyicileri cevabı oradan kurar. + `resume_students`: geçen koşuda bütçe yüzünden işlenemeyenler. Bunlar listenin **başına** alınır — "bir sonraki koşu oradan devam eder" (`MODULLER.md` §3.4) cümlesinin uygulaması budur. Sıra dışında hiçbir şey @@ -207,6 +304,14 @@ async def run_school( testlerde sahte saat verilerek bütçe aşımı **deterministik** kurulur — aksi halde "60 sn'yi aş" testi makinenin hızına bağlı olurdu. """ + # Was the roster handed in (a subset) or read from the directory (the + # roster)? The departed purge is only honest for the latter. + roster_from_directory = student_ids is None + wanted = _section_filter(sections) + + def want(name: str) -> bool: + return wanted is None or name in wanted + started_wall = now_ms started_mono = monotonic_fn() result = RunResult( @@ -218,7 +323,8 @@ async def run_school( # Koşu defterine "running" satırı — süreç yeniden başlarsa bayat koşu # buradan görülür (`MODULLER.md` §3.4). - await store.write_run(result.as_row(), result.run_key()) + if nightly: + await store.write_run(result.as_row(), result.run_key()) if student_ids is None: try: @@ -229,7 +335,8 @@ async def run_school( result.failed_modules.append("discover_students") result.finished_at = now_ms result.duration_ms = elapsed_ms() - await store.write_run(result.as_row(), result.run_key()) + if nightly: + await store.write_run(result.as_row(), result.run_key()) return result if resume_students: @@ -256,12 +363,18 @@ async def run_school( pending = list(student_ids[index:]) break try: - fetched[student] = await _fetch_student(source, school, student) + fetched[student] = await _fetch_student( + source, school, student, sections=wanted + ) except Exception as exc: # noqa: BLE001 — kısmi başarısızlıkta devam log.warning("öğrenci atlandı (okul=%s, id=%s): %s", school, student, exc) result.students_failed += 1 if "fetch" not in result.failed_modules: result.failed_modules.append("fetch") + if outcomes is not None: + outcomes.append( + StudentOutcome(student=student, error=str(exc), error_kind="fetch") + ) # ---------------- kohort kurulumu -------------------------------------- # @@ -280,6 +393,10 @@ async def run_school( ) # ---------------- 2. geçiş: hesap + tavsiye ---------------------------- + # + # İstenmeyen modül (`sections`) hesaba hiç girmez ve özette `None` kalır. + # Dikkat ve tavsiye kuralları yine çağrılır: modül profillerinin kapıları + # kendi içindedir, eksik profil zaten "ateşlemez" demektir. summaries: list[StudentSummary] = [] recommendations: list[Recommendation] = [] for student, data in fetched.items(): @@ -288,69 +405,99 @@ async def run_school( pending.append(student) continue try: - marks_profile = marks_mod.student_profile( - data.marks_raw, data.profile, distributions + marks_profile = ( + marks_mod.student_profile(data.marks_raw, data.profile, distributions) + if want("marks") + else None ) - attendance_profile = attendance_mod.student_profile( - data.attendance_raw, data.class_ids, medians + attendance_profile = ( + attendance_mod.student_profile( + data.attendance_raw, data.class_ids, medians + ) + if want("attendance") + else None ) - submission_profile = submission_mod.student_profile( - data.report_raw, data.homework_raw, now_ms + submission_profile = ( + submission_mod.student_profile( + data.report_raw, data.homework_raw, now_ms + ) + if want("submission") + else None ) - study_profile = study_mod.student_profile( - data.pomodoro_raw, now_ms, _due_dates(data.report_raw) + study_profile = ( + study_mod.student_profile( + data.pomodoro_raw, now_ms, _due_dates(data.report_raw) + ) + if want("study") + else None ) items = attention_mod.order_items( attention_mod.evaluate( student, - attendance_profile=attendance_profile, - submission_profile=submission_profile, - marks_profile=marks_profile, + attendance_profile=attendance_profile or {}, + submission_profile=submission_profile or {}, + marks_profile=marks_profile or {}, now_ms=now_ms, term_start_ms=term_start_ms, ) ) - recommendations.extend( - recommend_mod.for_student( - school, - student, - marks_profile=marks_profile, - attendance_profile=attendance_profile, - submission_profile=submission_profile, - study_profile=study_profile, - attention_items=items, - course_teachers=marks_mod.course_teachers(data.marks_raw), - now_ms=now_ms, - ) + recs = recommend_mod.for_student( + school, + student, + marks_profile=marks_profile or {}, + attendance_profile=attendance_profile or {}, + submission_profile=submission_profile or {}, + study_profile=study_profile or {}, + attention_items=items, + course_teachers=marks_mod.course_teachers(data.marks_raw), + now_ms=now_ms, ) - summaries.append( - StudentSummary( - school=school, - student=student, - computed_at=now_ms, - marks=marks_profile, - attendance=attendance_profile, - submission=submission_profile, - study=study_profile, - attention=[ - { - "trigger": i.trigger.value, - "fact": i.fact, - "evidence": i.evidence, - "window_from": i.window_from, - "window_to": i.window_to, - } - for i in items - ], - confidence=_summary_confidence(marks_profile), - ) + recommendations.extend(recs) + summary = StudentSummary( + school=school, + student=student, + computed_at=now_ms, + marks=marks_profile, + attendance=attendance_profile, + submission=submission_profile, + study=study_profile, + attention=[ + { + "trigger": i.trigger.value, + "fact": i.fact, + "evidence": i.evidence, + "window_from": i.window_from, + "window_to": i.window_to, + } + for i in items + ], + confidence=_summary_confidence(marks_profile or {}), ) + summaries.append(summary) result.students_ok += 1 + if outcomes is not None: + outcomes.append( + StudentOutcome( + student=student, + coverage=dict(data.coverage), + summary=summary, + recommendations=recs, + ) + ) except Exception as exc: # noqa: BLE001 log.warning("hesap düştü (okul=%s, id=%s): %s", school, student, exc) result.students_failed += 1 if "compute" not in result.failed_modules: result.failed_modules.append("compute") + if outcomes is not None: + outcomes.append( + StudentOutcome( + student=student, + coverage=dict(data.coverage), + error=str(exc), + error_kind="compute", + ) + ) # ---------------- yazma ------------------------------------------------ summary_report = await store.write_summaries(summaries) @@ -360,10 +507,14 @@ async def run_school( result.failed_modules.append("store") # Mezuniyet/ayrılma temizliği: listede olmayanın **profili kalmamalıdır**. - if not result.budget_exceeded and student_ids: + # Yalnız dizinden çıkarılan TAM kadro ve yalnız gece koşusu için: çağıranın + # verdiği liste bir ALT KÜMEDİR (refresh `user_ids`, `cli --students`) ve + # onu kadro saymak, adı geçmeyen herkesin türetilmiş verisini sildirirdi. + if nightly and roster_from_directory and not result.budget_exceeded and student_ids: await store.purge_departed(school, list(student_ids)) - await store.sweep(now_ms) + if nightly: + await store.sweep(now_ms) result.students_skipped = len(pending) result.pending_students = pending @@ -382,5 +533,6 @@ async def run_school( if result.write_failed and result.status == "ok": result.status = "partial" - await store.write_run(result.as_row(), result.run_key()) + if nightly: + await store.write_run(result.as_row(), result.run_key()) return result diff --git a/service/tests/test_capabilities.py b/service/tests/test_capabilities.py index 7118724..8e3077e 100644 --- a/service/tests/test_capabilities.py +++ b/service/tests/test_capabilities.py @@ -1,17 +1,18 @@ """Yetenek defterinin testleri. -Buradaki en onemli test bir EKSIKLIGI pinler: backend ZEKA'nin yeteneklerinin -hicbirini **cagiramaz** (dagitim tablosunda bu adlar yok), dolayisiyla ZEKA'ya -hic `Request` gondermez. Bu, servisin backend'i cagirdigi depo yolundan (2. yon, -`insight.*` -- calisir) AYRI bir yondur. Backend tarafi duzeldiginde bu test -guncellenecek ve degisiklik goze carpacak. +Buradaki en onemli test bir GERCEGI pinler: backend'in ZEKA'ya gonderebildigi +adlar `chat.reply`, `rag.index`, `insight.student`, `insight.refresh`tir; +`insight.class` ilan edilir ama backend'de onu gonderen bir yol yoktur. Bu, +servisin backend'i cagirdigi depo yolundan (2. yon, `insight.*` -- calisir) +AYRI bir yondur. Iki taraf da degistiginde bu testler ve +`docs/BACKEND-GEREKSINIMLERI.md` madde 1 birlikte guncellenir. """ from __future__ import annotations import unittest -from src import capabilities +from src import capabilities, handlers from src.protocol import CapabilityError @@ -22,16 +23,24 @@ class CapabilityNameTests(unittest.TestCase): ("insight.student", "insight.class", "insight.refresh"), ) - def test_backend_can_call_none_of_them(self): - # constant.rs:568 ve :574 -- backend'in cagirabildigi tek iki ad. + def test_backend_callable_set_is_the_dispatch_table(self): + # constant.rs:568,574 (chat.reply, rag.index) + ai/insight.rs + # (compute_student/refresh) ve web/insights.rs kapilari -- 2026-09-18. self.assertEqual( - capabilities.BACKEND_CALLABLE_CAPABILITIES, ("chat.reply", "rag.index") + capabilities.BACKEND_CALLABLE_CAPABILITIES, + ("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. self.assertEqual( - set(capabilities.NAMES) & set(capabilities.BACKEND_CALLABLE_CAPABILITIES), - set(), - "backend artik bir ZEKA yetenegini cagirabiliyorsa bu testi ve " - "docs/BACKEND-GEREKSINIMLERI.md madde 1'i guncelleyin", + set(capabilities.NAMES) - set(capabilities.BACKEND_CALLABLE_CAPABILITIES), + {"insight.class"}, + ) + + def test_sections_vocabulary_is_the_summary_modules(self): + self.assertEqual( + capabilities.SECTIONS, ("marks", "attendance", "submission", "study") ) def test_every_name_has_a_schema(self): @@ -53,6 +62,9 @@ class DispatchTests(unittest.TestCase): capabilities._handlers.clear() def test_unknown_capability_is_refused(self): + # Kayit defteri modul genelidir ve baska testler `handlers.wire()` + # cagirir; bu test BOS bir defteri sart kosar. + capabilities._handlers.clear() with self.assertRaises(CapabilityError) as caught: capabilities.dispatch("insight.student", "demo", {}) self.assertEqual(caught.exception.code, "unknown_capability") @@ -80,15 +92,22 @@ class DispatchTests(unittest.TestCase): capabilities.dispatch("insight.class", "demo", ["liste"]) self.assertEqual(caught.exception.code, "bad_request") - def test_summary_names_the_callable_direction_only(self): + def test_summary_separates_the_three_facts(self): + handlers.wire() text = capabilities.summary() - # Liste backend'in CAGIRABILDIGIDIR ... - self.assertIn("backend'in cagirabildigi yetenekler: chat.reply, rag.index", text) - self.assertIn("HENUZ cagrilmiyor", text) - # ... ve depo yolunu (2. yon) kapsamadigi acikca yazilidir. + # 1) backend'in GONDEREBILDIGI adlar ... + self.assertIn( + "backend'in cagirabildigi yetenekler: " + "chat.reply, rag.index, insight.student, insight.refresh", + text, + ) + # 2) ... depo yolunu (2. yon) kapsamadigi ... self.assertIn("servis->backend depo yolu: kopru/insight.*", text) - # Eski hali depo yolu calismaya basladiktan sonra "backend insight'i - # hic bilmiyor" diye okunuyordu. + # 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) + # 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 new file mode 100644 index 0000000..2f02165 --- /dev/null +++ b/service/tests/test_handlers.py @@ -0,0 +1,258 @@ +"""The three served capabilities, end to end over a fake bridge. + +What is proven here, in the order it matters: + +1. The fail-pre-fix fact. With an empty handler table `dispatch` answers + `unknown_capability` -- that was the live production answer even though the + `Hello` frame announced the name in the same breath. After + `handlers.wire()` the same call reaches a real handler. +2. Each capability answers the fields the backend's contract reads + (`hezarfen_backend/src/ai/insight.rs`), through the real store layer + (`BridgeStore` + `RecordingCaller`) and a `FakeSource`. +3. The boot self-check refuses to advertise a name with no handler. + +The fixture data is built relative to the *real* now: `fakes.NOW` is 2023, and +with it the 28-day study window would be empty and `O3.pattern` would never +fire. +""" + +from __future__ import annotations + +import time +import unittest +from datetime import datetime + +from src import capabilities, handlers +from src.compute import clock +from src.protocol import CapabilityError +from src.store import ( + CAP_PURGE, + CAP_RECOMMENDATION, + CAP_RUN, + CAP_SUMMARY, + CAP_SWEEP, + BridgeStore, + RecordingCaller, +) + +from .fakes import FakeSource, dataset + +SCHOOL = "okul-a" +#: Real "now" -- see the module docstring. +NOW = int(time.time() * 1000) + + +def _rows(caller: RecordingCaller, capability: str) -> list[dict]: + rows: list[dict] = [] + for kind, _, payload in caller.calls: + if kind == capability: + rows.extend(payload.get("rows") or []) + return rows + + +class HandlerTestCase(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + self.data = dataset(12, now_ms=NOW) + self.caller = RecordingCaller() + capabilities.bind_store(BridgeStore(self.caller)) + handlers.bind_source(lambda school: FakeSource(self.data)) + handlers.wire() + + async def asyncTearDown(self) -> None: + capabilities._handlers.clear() + + async def dispatch(self, capability: str, payload: dict) -> dict: + return await capabilities.dispatch(capability, SCHOOL, payload) + + def kinds(self) -> list[str]: + return [kind for kind, _, _ in self.caller.calls] + + +class FailPreFixTests(HandlerTestCase): + async def test_student_is_unknown_until_wire_registers_it(self) -> None: + capabilities._handlers.clear() + with self.assertRaises(CapabilityError) as caught: + await self.dispatch("insight.student", {"user_id": "student-00"}) + self.assertEqual(caught.exception.code, "unknown_capability") + + handlers.wire() + answer = await self.dispatch("insight.student", {"user_id": "student-00"}) + self.assertEqual(answer["user_id"], "student-00") + + async def test_a_wired_name_refuses_a_bad_payload_typed(self) -> None: + """After wiring, a malformed call is a `bad_request`, not a miss: + the handler ran and judged the payload.""" + with self.assertRaises(CapabilityError) as caught: + await self.dispatch("insight.student", {}) + self.assertEqual(caught.exception.code, "bad_request") + + async def test_boot_self_check_refuses_a_name_without_a_handler(self) -> None: + capabilities._handlers.pop("insight.class") + with self.assertRaises(capabilities.RegistrationError) as caught: + capabilities.verify_dispatchable() + self.assertIn("insight.class", str(caught.exception)) + self.assertEqual( + capabilities.dispatchable_names(), ["insight.student", "insight.refresh"] + ) + + handlers.wire() + capabilities.verify_dispatchable() # and back to a clean bill + + +class StudentCapabilityTests(HandlerTestCase): + async def test_answer_carries_the_contract_and_writes_only_rows(self) -> None: + answer = await self.dispatch( + "insight.student", {"user_id": "student-00", "since": "2023-06-01"} + ) + self.assertEqual( + set(answer), + {"user_id", "generated_at", "signals", "recommendations", "coverage"}, + ) + self.assertEqual(answer["user_id"], "student-00") + self.assertGreater(datetime.fromisoformat(answer["generated_at"]).year, 2024) + self.assertIsInstance(answer["signals"], list) + + # `O3.pattern` fires on the fixture's study sessions; the card is the + # student's own, carries evidence, and is not storage bookkeeping. + self.assertTrue(answer["recommendations"]) + card = answer["recommendations"][0] + self.assertEqual(card["audience"], "student-00") + self.assertEqual(card["audience_role"], "student") + self.assertTrue(card["evidence"]) + self.assertNotIn("retain_until", card) + # The answer's cards are exactly the ones the store accepted. + self.assertEqual( + [item["rule_id"] for item in answer["recommendations"]], + [ + row["rule_id"] + for row in _rows(self.caller, CAP_RECOMMENDATION) + if row["audience"] == "student-00" + ], + ) + + written = _rows(self.caller, CAP_SUMMARY) + self.assertEqual(len(written), 1) + self.assertEqual(written[0]["student"], "student-00") + + # The night run owns the ledger, the purge and the sweep. A + # single-student compute that wrote any of them would clobber the + # day's record with a one-student one. + self.assertEqual( + [kind for kind in self.kinds() if kind in (CAP_RUN, CAP_PURGE, CAP_SWEEP)], + [], + ) + self.assertEqual(answer["coverage"]["sections"], "all") + self.assertEqual(answer["coverage"]["reads"]["marks"], 1) + self.assertEqual(answer["coverage"]["reads"]["homework_report"], 6) + + async def test_sections_narrow_the_reads_and_null_the_row(self) -> None: + answer = await self.dispatch( + "insight.student", {"user_id": "student-00", "sections": ["marks"]} + ) + self.assertEqual(answer["coverage"]["sections"], ["marks"]) + self.assertEqual(set(answer["coverage"]["reads"]), {"profile", "marks"}) + row = _rows(self.caller, CAP_SUMMARY)[0] + self.assertIsInstance(row["marks"], dict) + # Unrequested modules are "not computed" (`null`), which the backend's + # `SummaryRow` keeps apart from the empty-object "read, nothing there". + self.assertIsNone(row["attendance"]) + self.assertIsNone(row["submission"]) + self.assertIsNone(row["study"]) + + async def test_bad_inputs_are_refused_by_name(self) -> None: + with self.assertRaises(CapabilityError) as caught: + await self.dispatch( + "insight.student", {"user_id": "student-00", "sections": ["speech"]} + ) + self.assertEqual(caught.exception.code, "bad_request") + with self.assertRaises(CapabilityError) as caught: + await self.dispatch( + "insight.student", {"user_id": "student-00", "since": "dun"} + ) + self.assertEqual(caught.exception.code, "bad_request") + + async def test_a_failed_fetch_is_a_refusal_not_an_empty_answer(self) -> None: + handlers.bind_source( + lambda school: FakeSource(self.data, fail={"student-05"}) + ) + with self.assertRaises(CapabilityError) as caught: + await self.dispatch("insight.student", {"user_id": "student-05"}) + self.assertEqual(caught.exception.code, "unavailable") + + +class ClassCapabilityTests(HandlerTestCase): + async def test_answer_carries_cohort_and_attention_list(self) -> None: + answer = await self.dispatch( + "insight.class", + {"course_id": "course-1", "term": "2023-06-01", "top_n": 2}, + ) + self.assertEqual(set(answer), set(capabilities.SCHEMAS["insight.class"][1].__annotations__)) + self.assertEqual(answer["course_id"], "course-1") + self.assertEqual(answer["cohort_size"], 12) + self.assertEqual(answer["topic_gaps"], []) # not producible; says so below + self.assertTrue(answer["coverage"]["unavailable"]["topic_gaps"]) + + self.assertTrue(answer["attention_list"]) + item = answer["attention_list"][0] + self.assertEqual( + set(item), + {"user_id", "trigger", "course", "fact", "window_from", "window_to", "evidence"}, + ) + # The output contract has no ranking field anywhere, the wire included. + self.assertNotIn("score", item) + self.assertEqual(answer["coverage"]["attention"]["total"], 1) + self.assertEqual(answer["coverage"]["attention"]["returned"], 1) + self.assertEqual(answer["coverage"]["roster"]["course_rows"], 1) + + +class RefreshCapabilityTests(HandlerTestCase): + async def test_school_refresh_writes_the_run_ledger_and_counts(self) -> None: + answer = await self.dispatch("insight.refresh", {}) + self.assertEqual(answer["requested"], 12) + self.assertEqual(answer["computed"], 12) + self.assertEqual(answer["skipped"], 0) + self.assertEqual(answer["failed"], []) + self.assertEqual(answer["status"], "ok") + + runs = [ + payload["run"] for kind, _, payload in self.caller.calls if kind == CAP_RUN + ] + self.assertEqual(len(runs), 2) # "running" first, the verdict last + started = int( + datetime.fromisoformat(answer["started_at"]).timestamp() * 1000 + ) + self.assertEqual(runs[-1]["run_day"], clock.tr_date_key(started)) + self.assertEqual(runs[-1]["status"], "ok") + self.assertEqual(runs[-1]["students_total"], 12) + # The whole-school sweep keeps the night run's cleanup steps. + self.assertEqual(self.kinds().count(CAP_PURGE), 1) + self.assertEqual(self.kinds().count(CAP_SWEEP), 1) + + async def test_scoped_refresh_never_purges(self) -> None: + """`user_ids` is a subset, not the roster: obeying it through + `insight.departed.purge` would delete everyone it does not name.""" + answer = await self.dispatch( + "insight.refresh", {"user_ids": ["student-00", "student-01"]} + ) + self.assertEqual(answer["requested"], 2) + self.assertEqual(answer["computed"], 2) + self.assertNotIn(CAP_PURGE, self.kinds()) + # Its ledger row is still written: that is the trace a reader polls. + self.assertIn(CAP_RUN, self.kinds()) + + async def test_failed_students_are_named_in_the_answer(self) -> None: + handlers.bind_source( + lambda school: FakeSource(self.data, fail={"student-05"}) + ) + answer = await self.dispatch( + "insight.refresh", {"user_ids": ["student-05", "student-00"]} + ) + self.assertEqual(answer["requested"], 2) + self.assertEqual(answer["computed"], 1) + self.assertEqual([entry["user_id"] for entry in answer["failed"]], ["student-05"]) + self.assertEqual(answer["failed"][0]["code"], "unavailable") + self.assertTrue(answer["failed"][0]["message"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/service/tests/test_pipeline.py b/service/tests/test_pipeline.py index 5bc4cac..2d26efc 100644 --- a/service/tests/test_pipeline.py +++ b/service/tests/test_pipeline.py @@ -115,8 +115,13 @@ class TestEndToEnd(PipelineTestCase): ) async def test_cleanup_calls_go_out_once(self) -> None: - """Koşu sonunda süpürme ve mezuniyet temizliği çağrılır.""" - _, caller = await self._run(dataset()) + """Koşu sonunda süpürme ve mezuniyet temizliği çağrılır. + + Kadro DİZİNDEN okunur (`student_ids=None`): temizlik yalnız tam kadro + için koşar, çağıranın verdiği alt küme için koşmaz (bkz. + `run_school` docstring'i). + """ + _, caller = await self._run(dataset(), student_ids=None) kinds = [capability for capability, _, _ in caller.calls] self.assertEqual(kinds.count(CAP_SWEEP), 1) purge = [ @@ -375,18 +380,18 @@ class TestPipelineWritesThroughTheBridge(unittest.IsolatedAsyncioTestCase): """Ayrilan ogrenci temizlik listesinde YOKTUR: profili kalmamalidir. Silme backend'in isidir; burada dogrulanan sey gonderilen listenin - gercekten daralmis olmasidir. + gercekten daralmis olmasidir. Kadro her iki kosuda da DIZINDEN okunur: + `student-11` okulun odev listesinden cikar ve temizlik onu istemez. """ await self._run() self.assertEqual(len(self.tables["student_summary"]), 12) - await run_school( - FileSource(self.root), - self.store.store_for("okul-a"), - "okul-a", - now_ms=NOW, - term_start_ms=TERM_START, - student_ids=[f"student-{i:02d}" for i in range(10)], - ) + roster = [f"student-{i:02d}" for i in range(10)] + data = {key: value for key, value in self.data.items() if key in roster} + data["_school"] = { + "homework_list": [homework("hw-school", "course-1", NOW + DAY, roster)] + } + write_fixtures(self.root, "okul-a", data) + await self._run() purge_calls = [ payload for capability, _, payload in self.caller.calls @@ -396,6 +401,16 @@ class TestPipelineWritesThroughTheBridge(unittest.IsolatedAsyncioTestCase): self.assertEqual(len(purge_calls[-1]["students"]), 10) self.assertNotIn("student-11", purge_calls[-1]["students"]) + async def test_a_scoped_list_never_purges(self) -> None: + """Cagiranin verdigi liste bir ALT KUME: temizlige verilemez. + + `refresh user_ids` ve `cli --students` boyle kosar; o listeyi "aktif + kadro" saymak, adi gecmeyen herkesin turetilmis verisini sildirirdi. + """ + await self._run(student_ids=[f"student-{i:02d}" for i in range(10)]) + self.assertEqual(self.tables["student_summary"][0]["student"], "student-00") + self.assertNotIn(CAP_PURGE, [capability for capability, _, _ in self.caller.calls]) + if __name__ == "__main__": unittest.main()