forge
Explore
Log in

Don't you dare go Hollow

🔌 register the insight.* handlers and gate the Hello frame on them

Browse files at this commit

618a44d0d847759fd482447b2df7a481399f0baeAhmet Kaan GümüşParent: 3c46936
  • feat
    • 🔌 register the insight.* handlers and gate the Hello frame on them
Show full message
feat(capabilities): 🔌 register the insight.* handlers and gate the Hello frame on them

The dispatch table was empty while the Hello frame announced three names, so
every dispatched insight.student / insight.refresh was answered
`unknown_capability` -- live, against the deployed backend. handlers.wire()
registers all three on the runtime path (bridge.run_once), and
capabilities.verify_dispatchable() refuses to boot when an advertised name has
no handler, so advertising and dispatch cannot drift apart again.

- insight.student: one student, computed and written now; `since` moves the
  attention window's term start, `sections` narrows the four summary modules
  (an unrequested module is written `null` = "not computed", which the
  backend's SummaryRow keeps apart from `{}`).
- insight.class: the course roster derived from that course's addressed
  homework (the only id source the bridge read allowlist exposes), computed as
  a cohort; `topic_gaps` stays empty and `coverage.unavailable` says why.
- insight.refresh: the school sweep through run_school(nightly=True), so the
  zeka_run ledger row that GET /insights/runs serves is written (running +
  verdict). A discovered roster also purges departed students and sweeps
  retention; `user_ids` is a subset, not a roster, and never purges.
- run_school gains nightly/sections/outcomes; a scoped compute writes no
  ledger, no purge and no sweep. Purge is now gated on a discovered roster,
  which also closes the silent data-loss path in `cli --students`.

Tests: tests/test_handlers.py (fail-pre-fix dispatch, contract fields per
capability, boot self-check, scoped-refresh no-purge); the truth pins in
tests/test_capabilities.py and the purge expectations in test_pipeline.py are
updated to the merged backend dispatch (insight.student + insight.refresh
sent, insight.class still not).

11 changed files +1122 -152

service/README.mdmodified+7 -6
@@ -150,13 +150,14 @@ Tohum verisinde 217.498 sınav cevabı ve kasıtlı olarak bozuk maddeler var. Y
150 150
151 `docs/BACKEND-GEREKSINIMLERI.md` üç maddelik listeyi gerekçeleriyle içerir:151 `docs/BACKEND-GEREKSINIMLERI.md` üç maddelik listeyi gerekçeleriyle içerir:
152 152
153-1. **`insight.*` depo yolu açıldı; sunucu-baslatımlı yön açık.** ZEKA'nın153+1. **`insight.*` depo yolu açıldı; sunucu-baslatımlı yön `insight.student` +
154+ `insight.refresh` için açık.** ZEKA'nın
154 çağırdığı dokuz operasyon backend'de 2026-09-17'de açıldı (`f84c29d`) ve155 çağırdığı dokuz operasyon backend'de 2026-09-17'de açıldı (`f84c29d`) ve
155- çalışır. Backend'in **çağırabildiği** adlar hâlâ yalnız `chat.reply` ve156+ çalışır. Backend'in **çağırabildiği** adlar 2026-09-18 itibarıyla
156- `rag.index`'tir: servis ettiği üç yetenek (`insight.student`,157+ `chat.reply`, `rag.index`, `insight.student` ve `insight.refresh`'tir;
157- `insight.class`, `insight.refresh`) dağıtım kapısı bekliyor; backend'de bu iş158+ `insight.class` ilan edilir ama gönderilmez (kadro listeleme yolu yok --
158- **`InsightDoors`** hattının sahibindedir ve o yön kapılar gelene kadar istek159+ Madde 3). Servis tarafında ilan ile dağıtım açılışta denetlenir
159- üzerine tetikleme kapalıdır.160+ (`src/handlers.py`, `capabilities.verify_dispatchable()`).
160 2. **Sınav yolları izin listesinde yok.** Madde analizi için gereken 9 yol listelenmiştir.161 2. **Sınav yolları izin listesinde yok.** Madde analizi için gereken 9 yol listelenmiştir.
161 3. **Öğrenci listeleme yolu yok.** Okul listesi artık köprüden (`insight.schools.list`),162 3. **Öğrenci listeleme yolu yok.** Okul listesi artık köprüden (`insight.schools.list`),
162 ama kimlerin işleneceği hâlâ yapılandırmadan çözülüyor. Dönem ortası kayıt olan163 ama kimlerin işleneceği hâlâ yapılandırmadan çözülüyor. Dönem ortası kayıt olan
service/docs/BACKEND-GEREKSINIMLERI.mdmodified+20 -8
@@ -19,22 +19,28 @@ istemci-baslatimli bir yetenek cercevesi tanimli degildir (Madde 1).
19 19
20 Yani asagidaki uc madde ZEKA'nin nelerin **disinda** kaldigini tarif eder.20 Yani asagidaki uc madde ZEKA'nin nelerin **disinda** kaldigini tarif eder.
21 21
22-> **DURUM (2026-09-17).** Madde 1'in **(a) servisin cagirdigi `insight.*`22+> **DURUM (2026-09-18).** Madde 1'in **(a) servisin cagirdigi `insight.*`
23 > operasyonlari** yonu backend'de **acildi** (`f84c29d`): kapi listesi23 > operasyonlari** yonu backend'de **acildi** (`f84c29d`): kapi listesi
24 > `/api-docs/openapi.json` icinde gorunur ve `insight.schools.list`,24 > `/api-docs/openapi.json` icinde gorunur ve `insight.schools.list`,
25 > `insight.pending.list`, `insight.retention.sweep` canli backend'e karsi25 > `insight.pending.list`, `insight.retention.sweep` canli backend'e karsi
26 > kosturuldu (uclu de basarili dondu). **(b) backend'in ZEKA'yi cagirmasi**26 > kosturuldu (uclu de basarili dondu). **(b) backend'in ZEKA'yi cagirmasi**
27-> yonu -- dagitim tablosundaki `insight.student` / `insight.class` /27+> yonu 2026-09-18'de `insight.student` ve `insight.refresh` icin **acildi**
28-> `insight.refresh` -- **HALA ACIKTIR**. Asagidaki "yoktur / tanimli degil"28+> (`ai/insight.rs::compute_student/refresh` + `web/insights.rs` kapilari) ve
29-> ifadeleri bu iki yonu ayirmadan okunmamalidir; `src/capabilities.py` modul29+> servis tarafi ayni gun baglandi (`src/handlers.py`; ilan ile dagitim
30-> dokumani ayni ayrimi yapar.30+> acilista `capabilities.verify_dispatchable()` ile denetlenir).
31+> `insight.class` ilan edilir ama hala GONDERILMEZ -- kadro listeleme yolu
32+> yok (Madde 3). Asagidaki "yoktur / tanimli degil" ifadeleri bu iki yonu
33+> ayirmadan okunmamalidir; `src/capabilities.py` modul dokumani ayni ayrimi
34+> yapar.
31 35
32 ---36 ---
33 37
34-## Madde 1 -- `insight.*`: depo yolu ACILDI, sunucu-baslatimli yon acik38+## Madde 1 -- `insight.*`: depo yolu ACILDI, sunucu-baslatimli yon student+refresh icin ACILDI
35 39
36 **Sahibi: backend'deki `InsightDoors` hatti.** Asagidaki zarf DONMUS'TUR; servis40 **Sahibi: backend'deki `InsightDoors` hatti.** Asagidaki zarf DONMUS'TUR; servis
37-ona karsi yazildi. (a) yonu 2026-09-17'de acildi (`f84c29d`); (b) yonu aciktir.41+ona karsi yazildi. (a) yonu 2026-09-17'de acildi (`f84c29d`); (b) yonu
42+2026-09-18'de `insight.student` + `insight.refresh` icin acildi; `insight.class`
43+icin hala aciktir (kadro listeleme yolu -- Madde 3).
38 44
39 ### Ne isteniyor45 ### Ne isteniyor
40 46
@@ -81,6 +87,12 @@ kolonu yoktur.
81 **b) Servisin servis ettigi yetenekler (sunucu-baslatimli akis).**87 **b) Servisin servis ettigi yetenekler (sunucu-baslatimli akis).**
82 `src/constant.rs` icine yeni yetenek sabitleri ve onlari cagiran dagitim kodu:88 `src/constant.rs` icine yeni yetenek sabitleri ve onlari cagiran dagitim kodu:
83 89
90+> **DURUM (2026-09-18).** Sabitler ve dagitim kodu merged: `insight.student`
91+> ve `insight.refresh` gonderilir (`ai/insight.rs`, `web/insights.rs`);
92+> `insight.class` sabiti durur ama onu gonderen bir yol yoktur. Servis tarafi
93+> ayni gun baglandi: `handlers.wire()` uc adi da kaydeder ve acilista
94+> `capabilities.verify_dispatchable()` ilan ile dagitimi karsilastirir.
95+
84 ```rust96 ```rust
85 /// ZEKA -- tek ogrenci icin analiz/tavsiye.97 /// ZEKA -- tek ogrenci icin analiz/tavsiye.
86 pub const AI_INSIGHT_STUDENT_CAPABILITY: &str = "insight.student";98 pub const AI_INSIGHT_STUDENT_CAPABILITY: &str = "insight.student";
@@ -283,7 +295,7 @@ Yani kapsam **elle** tutulur.
283 295
284 | # | Istenen | Kaynak dosya | Olmazsa kaybedilen |296 | # | Istenen | Kaynak dosya | Olmazsa kaybedilen |
285 |---|---|---|---|297 |---|---|---|---|
286-| 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` |298+| 1 | Dokuz `insight.*` operasyonu (yazma + liste + supurme) **ve** `insight.student` / `insight.class` / `insight.refresh` sabitleri + dagitim kodu | `src/constant.rs`, `src/ai/` | ZEKA satirlarini **yazamaz** (gece kosusu `partial`); backend ZEKA'yi **hic cagiramaz**, istege bagli her senaryo duser. Sahibi: `InsightDoors`. **Durum 2026-09-18: student + refresh ACILDI; sinif hala acik (Madde 3).** |
287 | 2 | 9 sinav yolu (+3 sinif/ders yolu) izin listesine | `src/constant.rs:656-676` | **Madde analizi, konu karnesi, sinif isi haritasi** hic uretilemez |299 | 2 | 9 sinav yolu (+3 sinif/ders yolu) izin listesine | `src/constant.rs:656-676` | **Madde analizi, konu karnesi, sinif isi haritasi** hic uretilemez |
288 | 3 | `GET /users/search` izin listesine (okul listesi Madde 1a'da) | `src/constant.rs:656-676` | Ogrenci kadrosu elle tutulur; yeni ogrenci **sessizce** gorunmez |300 | 3 | `GET /users/search` izin listesine (okul listesi Madde 1a'da) | `src/constant.rs:656-676` | Ogrenci kadrosu elle tutulur; yeni ogrenci **sessizce** gorunmez |
289 301
service/docs/CIKTI-SOZLESMESI.mdmodified+5 -3
@@ -416,6 +416,8 @@ bu tuzak yapısal olarak imkânsızdır.
416 5. **`T3.segment_class_gap` gerçek bir sınıfta hiç ateşlemedi** — yalnız yapay416 5. **`T3.segment_class_gap` gerçek bir sınıfta hiç ateşlemedi** — yalnız yapay
417 pozitif kontrolde. Ekranı kurulabilir, ama boş kalabileceği varsayılmalıdır.417 pozitif kontrolde. Ekranı kurulabilir, ama boş kalabileceği varsayılmalıdır.
418 6. **`insight.*` depo kapıları açıldı (`f84c29d`); backend'in ZEKA'yı çağırması418 6. **`insight.*` depo kapıları açıldı (`f84c29d`); backend'in ZEKA'yı çağırması
419- hâlâ kapalı.** Servis satırlarını bu depo kapılarından yazar; sunucu-baslatımlı419+ 2026-09-18'de `insight.student` + `insight.refresh` için açıldı** ve servis
420- üç yetenek için dağıtım kapısı gelene kadar gece koşusu `partial` yazılır.420+ tarafı aynı gün bağlandı (`service/src/handlers.py`; ilan ile dağıtım
421- Sahibi backend'deki `InsightDoors` hattı — `docs/BACKEND-GEREKSINIMLERI.md` Madde 1.421+ açılışta `verify_dispatchable()` ile denetlenir). `insight.class` ilan
422+ edilir ama gönderilmez: kadro listeleme yolu yok. Sahibi backend'deki
423+ `InsightDoors` hattı — `docs/BACKEND-GEREKSINIMLERI.md` Madde 1.
service/src/bridge.pymodified+24 -8
@@ -40,7 +40,7 @@ from aioquic.asyncio.protocol import QuicConnectionProtocol
40 from aioquic.quic.configuration import QuicConfiguration40 from aioquic.quic.configuration import QuicConfiguration
41 from aioquic.quic.events import ConnectionTerminated, QuicEvent, StreamDataReceived41 from aioquic.quic.events import ConnectionTerminated, QuicEvent, StreamDataReceived
42 42
43-from . import capabilities, config, protocol43+from . import capabilities, config, handlers, protocol
44 from .protocol import (44 from .protocol import (
45 ApiRefused,45 ApiRefused,
46 ApiResponse,46 ApiResponse,
@@ -553,7 +553,17 @@ async def run_once(
553 handler: RequestHandler | None = None,553 handler: RequestHandler | None = None,
554 on_ready: Callable[[BridgeProtocol], Any] | None = None,554 on_ready: Callable[[BridgeProtocol], Any] | None = None,
555 ) -> None:555 ) -> None:
556- """Sertifikayi cek, bagla, kaydol, baglanti kapanana kadar bekle."""556+ """Sertifikayi cek, bagla, kaydol, baglanti kapanana kadar bekle.
557+
558+ Kaydolmadan HEMEN once iki sey yapilir: isleyici defteri kurulur
559+ (`handlers.wire()`) ve ilan edilecek her adin karsiligi oldugu denetlenir
560+ (`capabilities.verify_dispatchable()`). `Hello` cercevesinin ciktigi tek
561+ yer burasidir; denetim buraya konunca ilan edip servis edememe durumu
562+ yapisal olarak imkansiz olur -- defter haftalarca bosken uc ad ilan
563+ ediliyordu ve backend'in her istegi `unknown_capability` ile donuyordu.
564+ """
565+ handlers.wire()
566+ capabilities.verify_dispatchable()
557 cert_pem = fetch_certificate(settings)567 cert_pem = fetch_certificate(settings)
558 quic_config = build_quic_configuration(settings, cert_pem)568 quic_config = build_quic_configuration(settings, cert_pem)
559 config.log(569 config.log(
@@ -771,19 +781,25 @@ async def _serve(settings: config.Config) -> int:
771 capabilities.bind_store(store)781 capabilities.bind_store(store)
772 config.log("info", "depo: kopru (insight.*) -- yerel veritabani yok")782 config.log("info", "depo: kopru (insight.*) -- yerel veritabani yok")
773 config.log("info", capabilities.summary())783 config.log("info", capabilities.summary())
774- if settings.refresh_interval_secs <= 0:
775- config.log("info", "gece zamanlayicisi KAPALI (ZEKA_REFRESH_INTERVAL_SECS=0)")
776- return await run_forever(settings)
777 784
778- # Zamanlayici her okul icin bir `Source` ister. Baglanti kopmussa785+ # Zamanlayici da yetenek isleyicileri de her okul icin bir `Source` ister.
779- # `BridgeSource` cagrisi hata verir ve zamanlayici o okulu duser --786+ # Baglanti kopmussa `BridgeSource` cagrisi hata verir: zamanlayici o okulu
780- # dogru davranis: veri cekilemeden hesap yapilmaz.787+ # duser, isleyici `unavailable` doner -- dogru davranis, cunku veri
788+ # cekilemeden hesap yapilmaz ve sessiz bos cevap uretilmez. Baglama
789+ # ZAMANLAYICI KAPALIYKEN DE yapilir: istekleri karsilayan sey zamanlayici
790+ # degil koprudur.
781 def source_for(_school: str) -> Any:791 def source_for(_school: str) -> Any:
782 proto = kopru["protocol"]792 proto = kopru["protocol"]
783 if proto is None:793 if proto is None:
784 raise RuntimeError("kopru henuz bagli degil")794 raise RuntimeError("kopru henuz bagli degil")
785 return BridgeSource(proto)795 return BridgeSource(proto)
786 796
797+ handlers.bind_source(source_for)
798+
799+ if settings.refresh_interval_secs <= 0:
800+ config.log("info", "gece zamanlayicisi KAPALI (ZEKA_REFRESH_INTERVAL_SECS=0)")
801+ return await run_forever(settings)
802+
787 scheduler = Scheduler(803 scheduler = Scheduler(
788 source_for,804 source_for,
789 store,805 store,
service/src/capabilities.pymodified+96 -34
@@ -2,15 +2,18 @@
2 2
3 IKI YON VARDIR; karistirilmamalidir:3 IKI YON VARDIR; karistirilmamalidir:
4 4
5-1. **Sunucu-baslatimli (backend -> ZEKA).** Backend'in ZEKA'ya `Request`5+1. **Sunucu-baslatimli (backend -> ZEKA).** The backend dispatches `Request`
6- gondermesi icin asagidaki adlari DAGITIM tablosunda tanimasi gerekir.6+ frames only for names its own dispatch table carries, and today
7- Bugun backend'in cagirabildigi tek iki ad `chat.reply` ve `rag.index`'tir7+ `insight.student` and `insight.refresh` are there: `ai/insight.rs`
8- (`constant.rs:568` ve `constant.rs:574`); asagidaki `insight.*` adlarinin8+ `compute_student()` / `refresh()` send both, and the doors are in
9- hicbiri orada YOKTUR. Yonlendirme TAM ESLESME iledir (`ai/protocol.rs:91-94`,9+ `web/insights.rs` (merged 2026-09-18). `insight.class` is advertised but
10- `ai/registry.rs`): ZEKA baglanip bu adlari ilan etse bile backend onlara10+ never dispatched: its request names a course, and the bridge's read
11- hicbir `Request` gondermez. Bu yon HALA ACIKTIR. Kopru tarafi (`bridge.py`)11+ allowlist hands a service no roster to enumerate it with
12- gelen cerceveleri karsilamaya hazirdir ki backend bu adlari tanidigi gun12+ (`ai/insight.rs` module docs; `docs/BACKEND-GEREKSINIMLERI.md` item 3).
13- tek satir degisiklik gereksin.13+ Routing is an EXACT match (`ai/protocol.rs:91-94`): every advertised name
14+ gets its handler from `handlers.wire()`, and `verify_dispatchable()` checks
15+ the pair at startup -- if advertising and dispatch ever drift apart, the
16+ service REFUSES TO BOOT.
14 17
15 2. **Istemci-baslatimli (ZEKA -> backend, depo yolu).** ZEKA'nin kendi `zeka_*`18 2. **Istemci-baslatimli (ZEKA -> backend, depo yolu).** ZEKA'nin kendi `zeka_*`
16 satirlarini yazip okudugu yol budur: `store.BridgeStore`,19 satirlarini yazip okudugu yol budur: `store.BridgeStore`,
@@ -34,10 +37,13 @@ kosar; backend'in yetenegi tanimasi yalnizca "istege bagli tetikleme"yi acar.
34 37
35 from __future__ import annotations38 from __future__ import annotations
36 39
40+import logging
37 from typing import Any, Callable, TypedDict41 from typing import Any, Callable, TypedDict
38 42
39 from .protocol import CapabilityError43 from .protocol import CapabilityError
40 44
45+log = logging.getLogger(__name__)
46+
41 # --- yetenek adlari --------------------------------------------------------47 # --- yetenek adlari --------------------------------------------------------
42 # Ad alani `<servis>.<eylem>` desenini izler; backend'in `chat.reply` ve48 # Ad alani `<servis>.<eylem>` desenini izler; backend'in `chat.reply` ve
43 # `rag.index` adlari da boyledir.49 # `rag.index` adlari da boyledir.
@@ -54,12 +60,26 @@ INSIGHT_REFRESH = "insight.refresh"
54 NAMES: tuple[str, ...] = (INSIGHT_STUDENT, INSIGHT_CLASS, INSIGHT_REFRESH)60 NAMES: tuple[str, ...] = (INSIGHT_STUDENT, INSIGHT_CLASS, INSIGHT_REFRESH)
55 61
56 62
57-#: Backend'in ZEKA'ya `Request` GONDEREBILDIGI yetenek adlari63+#: The capability names the backend can send a `Request` FOR -- the half of
58-#: (`constant.rs:568,574`) -- dagitim tablosunun tamami. Servisin cagirdigi64+#: its dispatch table that concerns ZEKA. It does NOT cover the `insight.*`
59-#: `insight.*` depo operasyonlarini KAPSAMAZ (bkz. modul dokumani, 2. yon).65+#: storage operations the service calls (see the module docstring, direction
60-#: ZEKA'nin hicbiri bu kumede degildir; kesisim bos oldugu surece backend66+#: 2). Sources: `constant.rs:568,574` (chat.reply, rag.index) and
61-#: ZEKA'yi cagiramaz. `tests/test_capabilities.py` bu gercegi pinler.67+#: `ai/insight.rs::compute_student/refresh` + the `web/insights.rs` doors
62-BACKEND_CALLABLE_CAPABILITIES: tuple[str, ...] = ("chat.reply", "rag.index")68+#: (insight.student, insight.refresh; merged 2026-09-18). `insight.class` is
69+#: NOT in the set: the constant exists, the code that would send it does not.
70+#: `tests/test_capabilities.py` pins this.
71+BACKEND_CALLABLE_CAPABILITIES: tuple[str, ...] = (
72+ "chat.reply",
73+ "rag.index",
74+ "insight.student",
75+ "insight.refresh",
76+)
77+
78+#: The `sections` vocabulary: the summary's four compute modules. A request
79+#: may name a subset; an unrequested module is NOT computed and reaches the
80+#: row as `null` -- the backend's `SummaryRow` keeps `null` ("not computed")
81+#: and `{}` ("read, and there was nothing") apart on purpose.
82+SECTIONS: tuple[str, ...] = ("marks", "attendance", "submission", "study")
63 83
64 84
65 # --- payload sozlesmeleri --------------------------------------------------85 # --- payload sozlesmeleri --------------------------------------------------
@@ -81,14 +101,14 @@ class StudentRequest(TypedDict, total=False):
81 101
82 102
83 class StudentResponse(TypedDict, total=False):103 class StudentResponse(TypedDict, total=False):
84- """`insight.student` cevap payload'i."""104+ """`insight.student` cevap payload'i (`handlers.student` doldurur)."""
85 105
86 user_id: str106 user_id: str
87 generated_at: str # ISO-8601107 generated_at: str # ISO-8601
88- archetype: str # tespit edilen calisma profili108+ archetype: str # BUGUN URETILMIYOR; alan gonderilmez (coverage.unavailable yazar)
89- signals: list[dict[str, Any]] # {kind, severity, evidence, ...}109+ signals: list[dict[str, Any]] # dikkat maddeleri: {trigger, course, fact, window_from, window_to, evidence}
90- recommendations: list[dict[str, Any]] # {action, rationale, weight}110+ recommendations: list[dict[str, Any]] # zeka_recommendation satirinin govdesi; `retain_until` gonderilmez
91- coverage: dict[str, Any] # hangi veri kaynagindan kac kayit okundu111+ coverage: dict[str, Any] # okunan kaynak -> kayit sayisi + yazma muhasebesi + uretilemeyenler
92 112
93 113
94 class ClassRequest(TypedDict, total=False):114 class ClassRequest(TypedDict, total=False):
@@ -100,13 +120,13 @@ class ClassRequest(TypedDict, total=False):
100 120
101 121
102 class ClassResponse(TypedDict, total=False):122 class ClassResponse(TypedDict, total=False):
103- """`insight.class` cevap payload'i."""123+ """`insight.class` cevap payload'i (`handlers.klass` doldurur)."""
104 124
105 course_id: str125 course_id: str
106 generated_at: str126 generated_at: str
107 cohort_size: int127 cohort_size: int
108- topic_gaps: list[dict[str, Any]] # {topic, mastery, cohort_share}128+ topic_gaps: list[dict[str, Any]] # BUGUN URETILMIYOR: bos liste + coverage.unavailable nedeni
109- attention_list: list[dict[str, Any]] # {user_id, reason, score}129+ attention_list: list[dict[str, Any]] # {user_id, trigger, fact, window_from, window_to, evidence} -- SKOR YOK
110 coverage: dict[str, Any]130 coverage: dict[str, Any]
111 131
112 132
@@ -120,13 +140,17 @@ class RefreshRequest(TypedDict, total=False):
120 140
121 141
122 class RefreshResponse(TypedDict, total=False):142 class RefreshResponse(TypedDict, total=False):
123- """`insight.refresh` cevap payload'i."""143+ """`insight.refresh` cevap payload'i (`handlers.refresh` doldurur)."""
124 144
125 started_at: str145 started_at: str
126 requested: int146 requested: int
127 computed: int147 computed: int
128 skipped: int148 skipped: int
129- failed: list[dict[str, Any]] # {user_id, code, message}149+ failed: list[dict[str, Any]] # {user_id, code, message} -- code: unavailable|internal
150+ #: Sozlesme disi ek alan: kosunun hukmu (`running|ok|partial|failed`).
151+ #: Backend'in struct'i bunu tasimaz ve serde bilinmeyen alani yok sayar;
152+ #: onsuz "0 istendi, 0 hesaplandi" temiz bir sifir gibi okunurdu.
153+ status: str
130 154
131 155
132 #: Yetenek adi -> (istek tipi, cevap tipi). Belge ve dogrulama icin.156 #: Yetenek adi -> (istek tipi, cevap tipi). Belge ve dogrulama icin.
@@ -176,12 +200,48 @@ def names() -> list[str]:
176 200
177 def register(name: str, handler: Handler) -> None:201 def register(name: str, handler: Handler) -> None:
178 """Bir yetenegi kaydet. Ilan edilmeyen ada kayit kabul edilmez -- ilan ile202 """Bir yetenegi kaydet. Ilan edilmeyen ada kayit kabul edilmez -- ilan ile
179- dagitimin ayrisabilecegi tek yer burasi, o yuzden kapatiliyor."""203+ dagitimin ayrisabilecegi tek yer burasi, o yuzden kapatiliyor.
204+
205+ Isleyici es zamanli (async) olabilir: `bridge._handle` boyle bir kancayi
206+ olay dongusunde bekler, senkron olani is parcacigina verir
207+ (`bridge.py:495-515`). ZEKA'nin isleyicileri async'tir cunku her okuma
208+ kendi kopru cagrisidir (`handlers.py`)."""
180 if name not in NAMES:209 if name not in NAMES:
181 raise KeyError(f"ilan edilmeyen yetenek kaydedilemez: {name!r}")210 raise KeyError(f"ilan edilmeyen yetenek kaydedilemez: {name!r}")
182 _handlers[name] = handler211 _handlers[name] = handler
183 212
184 213
214+class RegistrationError(RuntimeError):
215+ """Ilan edilen bir adin isleyicisi yok. Acilista, bilerek patlar."""
216+
217+
218+def dispatchable_names() -> list[str]:
219+ """Isleyicisi KAYITLI adlar. `names()` ne ilan edilecegini soyler."""
220+ return [name for name in NAMES if name in _handlers]
221+
222+
223+def verify_dispatchable() -> None:
224+ """Ilani hak etmeyen tek bir ad varsa ACILISI durdur.
225+
226+ `bridge.run_once()` `Hello` cercevesini yazmadan hemen once cagirir, yani
227+ ilan eden her yol bu denetimden gecmistir. Defter haftalarca BOSTU ve
228+ `Hello` uc ad ilan ediyordu: backend'in gonderdigi her istek, ilan edilen
229+ adi ayni cumlede sayan bir `unknown_capability` ile donuyordu. Bu sinifin
230+ tekrar uretilmesini imkansiz kilan sey, ilan ile defterin ayni anda
231+ dogrulanmasidir -- sonradan ozur dilemek degil.
232+ """
233+ missing = [name for name in NAMES if name not in _handlers]
234+ if not missing:
235+ return
236+ message = (
237+ f"ilan edilen yeteneklerin isleyicisi yok: {', '.join(missing)} "
238+ f"(kayitli: {', '.join(dispatchable_names()) or 'yok'}) -- "
239+ "servis bunlari ILAN EDEMEZ; handlers.wire() cagrildi mi?"
240+ )
241+ log.error(message)
242+ raise RegistrationError(message)
243+
244+
185 def dispatch(name: str, school: str, payload: Any) -> dict[str, Any]:245 def dispatch(name: str, school: str, payload: Any) -> dict[str, Any]:
186 """Gelen `Request`'i isleyicisine ver.246 """Gelen `Request`'i isleyicisine ver.
187 247
@@ -211,17 +271,19 @@ def require_text(payload: dict[str, Any], key: str) -> str:
211 def summary() -> str:271 def summary() -> str:
212 """Acilis logu icin tek satir: iki yonu AYRI soyler.272 """Acilis logu icin tek satir: iki yonu AYRI soyler.
213 273
214- Onceki hali "(backend'in tanidigi: chat.reply, rag.index; N yetenek274+ Onceki hali "backend'in tanidigi: chat.reply, rag.index; N yetenek
215- TANIMSIZ, istek gelmeyecek)" idi ve depo yolu (2. yon) calismaya275+ TANIMSIZ" idi; depo yolu (2. yon) acildiktan ve backend `insight.student`
216- basladiktan sonra backend'in `insight` hakkinda hicbir sey bilmedigi276+ / `insight.refresh`i gonderdikten sonra bu cumle bayatladi. Uc gercek
217- okunuyordu. Liste backend'in **cagirabildikleridir**; servisin277+ ayri ayri yazilir: backend'in gonderebildigi adlar, servisin kayitli
218- **cagirdigi** operasyonlari kapsamaz.278+ isleyicileri, ve backend'in dagitim tablosunda hala olmayan adlar.
219 """279 """
220- not_callable = [n for n in NAMES if n not in BACKEND_CALLABLE_CAPABILITIES]280+ served = dispatchable_names()
281+ unsent = [name for name in NAMES if name not in BACKEND_CALLABLE_CAPABILITIES]
221 return (282 return (
222 f"backend'in cagirabildigi yetenekler: "283 f"backend'in cagirabildigi yetenekler: "
223 f"{', '.join(BACKEND_CALLABLE_CAPABILITIES)} "284 f"{', '.join(BACKEND_CALLABLE_CAPABILITIES)} "
224 f"(servis->backend depo yolu: kopru/insight.* -- bu liste onu kapsamaz); "285 f"(servis->backend depo yolu: kopru/insight.* -- bu liste onu kapsamaz); "
225- f"servis tarafi isler ({', '.join(NAMES)}) backend tarafindan HENUZ "286+ f"servis tarafi isleyiciler: {len(served)}/{len(NAMES)} kayitli "
226- f"cagrilmiyor ({len(not_callable)} ad dagitim tablosunda yok)"287+ f"({', '.join(served) or 'yok'}); "
288+ f"backend'in dagitim tablosunda olmayan: {', '.join(unsent) or 'yok'}"
227 )289 )
service/src/compute/model.pymodified+7 -4
@@ -178,10 +178,13 @@ class StudentSummary:
178 school: str178 school: str
179 student: str179 student: str
180 computed_at: int180 computed_at: int
181- marks: dict[str, Any] = field(default_factory=dict)181+ #: Dört modül `None` OLABİLİR: `sections` ile istenmeyen modül hesaplanmaz
182- attendance: dict[str, Any] = field(default_factory=dict)182+ #: ve satıra `null` gider ("hesaplanmadı"), boş sözlük ise "okundu, kaynak
183- submission: dict[str, Any] = field(default_factory=dict)183+ #: satır yok" demektir (backend `db/insight.rs` `SummaryRow` sözleşmesi).
184- study: dict[str, Any] = field(default_factory=dict)184+ marks: dict[str, Any] | None = field(default_factory=dict)
185+ attendance: dict[str, Any] | None = field(default_factory=dict)
186+ submission: dict[str, Any] | None = field(default_factory=dict)
187+ study: dict[str, Any] | None = field(default_factory=dict)
185 attention: list[dict[str, Any]] = field(default_factory=list)188 attention: list[dict[str, Any]] = field(default_factory=list)
186 confidence: Confidence = Confidence.NONE189 confidence: Confidence = Confidence.NONE
187 190
service/src/handlers.pyadded+430 -0
@@ -0,0 +1,430 @@
1+"""The three `insight.*` capabilities the service serves to the backend.
2+
3+`capabilities.py` owns the wire names and the dispatch table but registers no
4+handler: the table is the contract, this module is the product. `wire()` fills
5+it, and `bridge.run_once()` calls `wire()` together with
6+`capabilities.verify_dispatchable()` right before the `Hello` frame goes out --
7+a name that cannot be dispatched must never be advertised, and that is the
8+defect class this file exists to close (three names were announced for weeks
9+with an empty table behind them, so every `insight.student` /
10+`insight.refresh` dispatch was answered `unknown_capability`).
11+
12+Why the handlers live outside `capabilities.py`: the table must stay
13+importable without the compute stack. A handler, on the other hand, is the
14+whole stack -- a `Source` read, `pipeline.run_school`, and the store writes.
15+
16+Handlers are coroutines on purpose. `bridge.BridgeProtocol._handle()` awaits a
17+coroutine handler in the event loop and pushes only *sync* handlers into the
18+executor (`bridge.py:495-515`); the compute path is async end to end because
19+every school read is a bridge call of its own.
20+
21+What each handler answers is the backend's contract, verbatim:
22+`hezarfen_backend/src/ai/insight.rs` (the payload structs) and
23+`src/web/insights.rs` (the doors). Where a contract field cannot be produced
24+from the data the bridge exposes, the answer says so in `coverage` instead of
25+filling it with a plausible value.
26+"""
27+
28+from __future__ import annotations
29+
30+import asyncio
31+import time
32+from datetime import datetime, timezone
33+from typing import Any, Callable
34+
35+from . import capabilities
36+from .compute import attention as attention_mod
37+from .compute import marks as marks_mod
38+from .pipeline import StudentOutcome, run_school
39+from .protocol import CapabilityError
40+from .store import attention_items, recommendation_rows
41+
42+#: `StudentOutcome.error_kind` -> the refusal code the caller branches on.
43+#: A read that could not be made is `unavailable` (the source may come back);
44+#: a compute that fell over is `internal` (it will not).
45+_ERROR_CODES = {"fetch": "unavailable", "compute": "internal"}
46+
47+#: What this version cannot answer, said once. These notes travel in every
48+#: answer's `coverage.unavailable`: the contract's response members are all
49+#: optional (`total=False`), so an omitted field is legal -- but an omission a
50+#: reader cannot see is indistinguishable from a field nobody asked about.
51+_UNAVAILABLE = {
52+ "archetype": (
53+ "no study-pattern classifier exists in this version; the field is "
54+ "omitted rather than guessed"
55+ ),
56+ "topic_gaps": (
57+ "item-level data (question, choice, answer) is not in the bridge read "
58+ "allowlist; see docs/BACKEND-GEREKSINIMLERI.md item 2"
59+ ),
60+ "roster": (
61+ "no member listing; a class roster is derived from the ids addressed "
62+ "by that course's homework (the same workaround as "
63+ "pipeline.discover_students)"
64+ ),
65+ "term": "no term directory; `term` must be an ISO-8601 date",
66+}
67+
68+#: School slug -> lock. One compute per school at a time: a dispatched refresh
69+#: and the night scheduler can overlap, and two `run_school` sweeps on one
70+#: school would interleave the day's run-ledger row (the row is keyed by
71+#: `run_day`) and race the per-student upserts. In-process only, which is
72+#: enough because the service is one process (`scheduler.py:44-45`).
73+_locks: dict[str, asyncio.Lock] = {}
74+
75+#: Set once by `bridge._serve`: `school -> Source`. Writes and reads travel the
76+#: same bridge, so the factory closes over the live connection.
77+_source_factory: Callable[[str], Any] | None = None
78+
79+
80+def bind_source(factory: Callable[[str], Any]) -> None:
81+ """Bind the school -> `Source` factory. Called once, at startup."""
82+ global _source_factory
83+ _source_factory = factory
84+
85+
86+def _source(school: str) -> Any:
87+ """The live source for one school. Never a fabricated or default one:
88+ a handler that cannot read is `unavailable`, not silently empty."""
89+ if _source_factory is None:
90+ raise CapabilityError(
91+ "unavailable",
92+ "no data source is bound; bridge._serve() binds it at startup",
93+ )
94+ return _source_factory(school)
95+
96+
97+def wire() -> None:
98+ """Register every advertised name. Idempotent; called from `run_once`."""
99+ capabilities.register(capabilities.INSIGHT_STUDENT, student)
100+ capabilities.register(capabilities.INSIGHT_CLASS, klass)
101+ capabilities.register(capabilities.INSIGHT_REFRESH, refresh)
102+
103+
104+def _lock_for(school: str) -> asyncio.Lock:
105+ lock = _locks.get(school)
106+ if lock is None:
107+ lock = asyncio.Lock()
108+ _locks[school] = lock
109+ return lock
110+
111+
112+def _now_ms() -> int:
113+ return int(time.time() * 1000)
114+
115+
116+def _iso(ms: int) -> str:
117+ """Unix ms -> ISO-8601 UTC. The contract's `generated_at`/`started_at`."""
118+ return datetime.fromtimestamp(ms / 1000, tz=timezone.utc).isoformat()
119+
120+
121+def _iso_ms(value: Any, field: str) -> int:
122+ """The only date shape this service can honor: ISO-8601 -> unix ms.
123+
124+ It reaches the pipeline as `term_start_ms`, which is the one way a caller
125+ can move the `attention` window's start (`attention._cold_start`): a
126+ recent `since` means "the term just began", which is what an ISO date can
127+ honestly mean to a service that has no term directory.
128+ """
129+ if not isinstance(value, str) or not value.strip():
130+ raise CapabilityError("bad_request", f"'{field}' must be an ISO-8601 date")
131+ try:
132+ parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
133+ except ValueError:
134+ raise CapabilityError(
135+ "bad_request", f"'{field}' is not a readable ISO-8601 date: {value!r}"
136+ ) from None
137+ if parsed.tzinfo is None:
138+ parsed = parsed.replace(tzinfo=timezone.utc)
139+ return int(parsed.timestamp() * 1000)
140+
141+
142+def _sections(value: Any) -> tuple[str, ...] | None:
143+ """`sections` as the pipeline's filter set; `None` is "all of them"."""
144+ if value is None:
145+ return None
146+ allowed = ", ".join(capabilities.SECTIONS)
147+ if not isinstance(value, list) or not all(
148+ isinstance(name, str) and name.strip() for name in value
149+ ):
150+ raise CapabilityError("bad_request", f"'sections' must name some of: {allowed}")
151+ names = tuple(name.strip() for name in value)
152+ unknown = [name for name in names if name not in capabilities.SECTIONS]
153+ if unknown:
154+ raise CapabilityError(
155+ "bad_request",
156+ f"'sections' names something this service does not compute: "
157+ f"{', '.join(unknown)} (allowed: {allowed})",
158+ )
159+ return names
160+
161+
162+def _top_n(value: Any) -> int | None:
163+ if value is None:
164+ return None
165+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
166+ raise CapabilityError("bad_request", "'top_n' must be a positive integer")
167+ return value
168+
169+
170+def _cards(recs: list[Any]) -> list[dict[str, Any]]:
171+ """The answer's card shape = the stored row minus storage bookkeeping.
172+
173+ Built through the same `store.recommendation_rows` the write uses, so the
174+ cards in the answer are exactly the cards that can land: a card the store
175+ would refuse (no evidence beyond `limitation`) is not claimed here either.
176+ `retain_until` stays out: it is the sweep's business, not the wire's.
177+ """
178+ rows, _rejected = recommendation_rows(recs)
179+ for row in rows:
180+ row.pop("retain_until", None)
181+ return rows
182+
183+
184+async def _sweep(
185+ school: str,
186+ student_ids: list[str] | None,
187+ *,
188+ now: int,
189+ term_start_ms: int | None = None,
190+ sections: tuple[str, ...] | None = None,
191+ nightly: bool = False,
192+) -> tuple[Any, list[StudentOutcome]]:
193+ """One scoped compute: the pipeline, the store, and the outcomes.
194+
195+ `nightly=False` for the per-student and per-class handlers: the run
196+ ledger, the departed purge and the retention sweep belong to the
197+ school-wide job. A dispatched compute must not overwrite the day's
198+ `zeka_run` row (keyed by `run_day`) nor claim a subset of students is the
199+ active roster. `handlers.refresh` is the one caller that passes `True`:
200+ it *is* the school sweep, on demand, and its run record belongs in the
201+ same ledger row the backend's `GET /insights/runs` reads.
202+ """
203+ outcomes: list[StudentOutcome] = []
204+ store = capabilities.store().store_for(school)
205+ result = await run_school(
206+ _source(school),
207+ store,
208+ school,
209+ now_ms=now,
210+ student_ids=None if student_ids is None else list(student_ids),
211+ term_start_ms=term_start_ms,
212+ nightly=nightly,
213+ sections=sections,
214+ outcomes=outcomes,
215+ )
216+ return result, outcomes
217+
218+
219+async def student(school: str, payload: dict[str, Any]) -> dict[str, Any]:
220+ """`insight.student` -- one student, computed and written now.
221+
222+ The two request knobs are honored at the only place they can be:
223+ `since` moves the term start the attention window is measured from, and
224+ `sections` narrows which of the four summary modules is computed. A
225+ module that was not requested is written `null` -- the backend's
226+ `SummaryRow` calls that "not computed", distinct from `{}` ("read, and
227+ there was nothing").
228+ """
229+ user_id = capabilities.require_text(payload, "user_id")
230+ since = payload.get("since")
231+ term_start_ms = _iso_ms(since, "since") if since is not None else None
232+ sections = _sections(payload.get("sections"))
233+ now = _now_ms()
234+ async with _lock_for(school):
235+ result, outcomes = await _sweep(
236+ school, [user_id], now=now, term_start_ms=term_start_ms, sections=sections
237+ )
238+ outcome = outcomes[0]
239+ if outcome.error is not None or outcome.summary is None:
240+ raise CapabilityError(
241+ _ERROR_CODES.get(outcome.error_kind or "compute", "internal"),
242+ f"'{user_id}' could not be computed: {outcome.error}",
243+ )
244+ summary = outcome.summary
245+ return {
246+ "user_id": summary.student,
247+ "generated_at": _iso(summary.computed_at),
248+ # The attention list is the signal list. It is teacher-facing and the
249+ # backend decides who reads it (`web/insights.rs` keeps it out of the
250+ # student's own view); the handler does not pre-filter it away.
251+ "signals": attention_items(summary),
252+ # Cards addressed to this student, and only those: the same table
253+ # carries the teacher's T3/T4 cards about the student, and the role
254+ # gate (`audience_role`) is applied here as well as on the read side.
255+ "recommendations": _cards(
256+ [
257+ rec
258+ for rec in outcome.recommendations
259+ if rec.audience == user_id and str(rec.audience_role) == "student"
260+ ]
261+ ),
262+ "coverage": {
263+ "reads": dict(outcome.coverage),
264+ "sections": sorted(sections) if sections else "all",
265+ "write": {
266+ "rows_written": result.rows_written,
267+ "write_failed": result.write_failed,
268+ },
269+ "unavailable": {
270+ **_UNAVAILABLE,
271+ "attention_triggers": attention_mod.unavailable_triggers(),
272+ },
273+ },
274+ }
275+
276+
277+async def _roster_for_course(
278+ source: Any, school: str, course_id: str
279+) -> tuple[list[str], dict[str, int]]:
280+ """The students this course's homework was addressed to, in order.
281+
282+ The same workaround `pipeline.discover_students` documents at school
283+ level, narrowed to one course: there is no member listing in the bridge's
284+ read allowlist (`docs/BACKEND-GEREKSINIMLERI.md` item 3). A student who
285+ never received addressed homework for this course is invisible here, and
286+ the answer says so in `coverage.unavailable.roster`.
287+ """
288+ rows = await source.homework_list(school)
289+ if isinstance(rows, dict):
290+ rows = rows.get("items") or []
291+ found: list[str] = []
292+ seen: set[str] = set()
293+ course_rows = 0
294+ for row in rows or []:
295+ if not isinstance(row, dict) or marks_mod.course_id_of(row) != course_id:
296+ continue
297+ course_rows += 1
298+ for uid in row.get("assigned") or []:
299+ key = str(uid)
300+ if key not in seen:
301+ seen.add(key)
302+ found.append(key)
303+ return found, {"homework_rows": len(rows or []), "course_rows": course_rows}
304+
305+
306+async def klass(school: str, payload: dict[str, Any]) -> dict[str, Any]:
307+ """`insight.class` -- one course's roster, computed as a cohort.
308+
309+ The backend declares the name but dispatches nothing to it yet
310+ (`hezarfen_backend/src/ai/insight.rs`, module docs); the handler exists so
311+ that the advertised name is true the moment a caller appears.
312+
313+ The cohort is real but partial: the roster comes from homework addresses
314+ (see `_roster_for_course`), so `cohort_size` counts the students whose
315+ data could be read, and the answer never presents a truncated list as the
316+ whole one -- `coverage.attention` carries `total` next to `returned`.
317+ """
318+ course_id = capabilities.require_text(payload, "course_id")
319+ term = payload.get("term")
320+ term_start_ms = _iso_ms(term, "term") if term is not None else None
321+ top_n = _top_n(payload.get("top_n"))
322+ now = _now_ms()
323+ async with _lock_for(school):
324+ source = _source(school)
325+ roster, roster_reads = await _roster_for_course(source, school, course_id)
326+ store = capabilities.store().store_for(school)
327+ outcomes: list[StudentOutcome] = []
328+ result = await run_school(
329+ source,
330+ store,
331+ school,
332+ now_ms=now,
333+ student_ids=roster,
334+ term_start_ms=term_start_ms,
335+ nightly=False,
336+ outcomes=outcomes,
337+ )
338+ attention_list: list[dict[str, Any]] = []
339+ for outcome in outcomes:
340+ if outcome.summary is None:
341+ continue
342+ for item in attention_items(outcome.summary):
343+ attention_list.append({"user_id": outcome.student, **item})
344+ # Deterministic order, never a ranking: the doc's own rule (no score, no
345+ # severity) survives truncation only if the order it truncates is the
346+ # writer's, not a computed one.
347+ attention_list.sort(key=lambda item: (item["user_id"], item["trigger"]))
348+ total = len(attention_list)
349+ if top_n is not None:
350+ attention_list = attention_list[:top_n]
351+ fetched = sum(1 for outcome in outcomes if outcome.coverage)
352+ return {
353+ "course_id": course_id,
354+ "generated_at": _iso(now),
355+ "cohort_size": fetched,
356+ "topic_gaps": [],
357+ "attention_list": attention_list,
358+ "coverage": {
359+ "roster": {
360+ "students": len(roster),
361+ "fetched": fetched,
362+ "failed": sum(1 for outcome in outcomes if outcome.error is not None),
363+ "budget_exceeded": result.budget_exceeded,
364+ "pending": len(result.pending_students),
365+ **roster_reads,
366+ },
367+ "attention": {"total": total, "returned": len(attention_list)},
368+ "write": {
369+ "rows_written": result.rows_written,
370+ "write_failed": result.write_failed,
371+ },
372+ "unavailable": _UNAVAILABLE,
373+ },
374+ }
375+
376+
377+async def refresh(school: str, payload: dict[str, Any]) -> dict[str, Any]:
378+ """`insight.refresh` -- the school sweep, on demand.
379+
380+ This is the night job's own pipeline (`run_school`, `nightly=True`), so
381+ the answer is written the same place the scheduler's is: the `zeka_run`
382+ row the backend's `GET /insights/runs` serves. A refresh of the whole
383+ school also purges departed students and sweeps retention, exactly like
384+ the night run; a refresh naming `user_ids` does not -- that list is a
385+ subset, and `insight.departed.purge` treats its list as the active roster.
386+
387+ `force` is accepted and has no effect, stated rather than silently
388+ ignored: the service keeps no result cache, so every refresh recomputes.
389+ """
390+ user_ids = payload.get("user_ids")
391+ if user_ids is not None:
392+ if not isinstance(user_ids, list) or not all(
393+ isinstance(uid, str) and uid.strip() for uid in user_ids
394+ ):
395+ raise CapabilityError(
396+ "bad_request", "'user_ids' must be a list of non-empty strings"
397+ )
398+ user_ids = [uid.strip() for uid in user_ids]
399+ now = _now_ms()
400+ async with _lock_for(school):
401+ result, outcomes = await _sweep(school, user_ids, now=now, nightly=True)
402+ return {
403+ "started_at": _iso(result.started_at),
404+ "requested": result.students_total,
405+ "computed": result.students_ok,
406+ "skipped": result.students_skipped,
407+ "failed": [
408+ {
409+ "user_id": outcome.student,
410+ "code": _ERROR_CODES.get(outcome.error_kind or "compute", "internal"),
411+ "message": outcome.error or "",
412+ }
413+ for outcome in outcomes
414+ if outcome.error is not None
415+ ],
416+ # Beyond the backend's struct, which ignores what it does not read.
417+ # Without it a reader would have to infer "ok" from counts, and a run
418+ # whose roster could not even be listed (status `failed`, nothing
419+ # counted) would read as a clean zero.
420+ "status": result.status,
421+ }
422+
423+
424+__all__ = [
425+ "bind_source",
426+ "klass",
427+ "refresh",
428+ "student",
429+ "wire",
430+]
service/src/pipeline.pymodified+210 -58
@@ -32,7 +32,7 @@ from __future__ import annotations
32 import dataclasses32 import dataclasses
33 import logging33 import logging
34 import time34 import time
35-from collections.abc import Callable35+from collections.abc import Callable, Sequence
36 from typing import Any36 from typing import Any
37 37
38 from .compute import attendance as attendance_mod38 from .compute import attendance as attendance_mod
@@ -95,6 +95,45 @@ class RunResult:
95 return {"school": self.school, **row}95 return {"school": self.school, **row}
96 96
97 97
98+#: The `sections` vocabulary (`capabilities.SECTIONS`), as a set the pipeline
99+#: can test against. Validation lives at the edge (`handlers._sections`); the
100+#: pipeline only applies the filter a caller hands it.
101+SECTION_NAMES: tuple[str, ...] = ("marks", "attendance", "submission", "study")
102+
103+
104+@dataclasses.dataclass(slots=True)
105+class StudentOutcome:
106+ """One student's result, for the capability handlers.
107+
108+ `RunResult` is bookkeeping only: it says how many students were counted,
109+ not what any of them produced. A dispatched compute answers with a
110+ payload per student, and this is where the per-student truth travels --
111+ which modules were read (`coverage`, empty when the fetch failed), what
112+ was computed, and how it failed if it did.
113+
114+ Only filled when the caller passes an `outcomes` list; the night run
115+ collects none.
116+ """
117+
118+ student: str
119+ #: Source name -> records read. An EMPTY dict means the fetch failed, which
120+ #: is a different claim from "read, and it was empty".
121+ coverage: dict[str, int] = dataclasses.field(default_factory=dict)
122+ summary: StudentSummary | None = None
123+ recommendations: list[Recommendation] = dataclasses.field(default_factory=list)
124+ error: str | None = None
125+ #: `fetch` (the data could not be read) or `compute` (the arithmetic fell
126+ #: over). `handlers._ERROR_CODES` maps it to the refusal code.
127+ error_kind: str | None = None
128+
129+
130+def _section_filter(sections: Sequence[str] | None) -> frozenset[str] | None:
131+ """`None` = every module (the night run). Otherwise the requested subset."""
132+ if sections is None:
133+ return None
134+ return frozenset(str(name) for name in sections)
135+
136+
98 async def discover_students(source: Any, school: str) -> list[str]:137 async def discover_students(source: Any, school: str) -> list[str]:
99 """Okulun öğrenci kimliklerini türetir.138 """Okulun öğrenci kimliklerini türetir.
100 139
@@ -138,16 +177,51 @@ class _Fetched:
138 class_ids: list[str]177 class_ids: list[str]
139 course_stats: dict[str, dict[str, Any]]178 course_stats: dict[str, dict[str, Any]]
140 attendance_stats: dict[str, dict[str, Any]]179 attendance_stats: dict[str, dict[str, Any]]
180+ #: Source name -> records read (see `StudentOutcome.coverage`).
181+ coverage: dict[str, int]
182+
183+
184+async def _fetch_student(
185+ source: Any, school: str, student: str, *, sections: frozenset[str] | None = None
186+) -> _Fetched:
187+ """Tek öğrencinin verisini çeker. Yasaklı alan çağrısı **yoktur**.
141 188
189+ `sections` verilirse YALNIZ istenen modüllerin kaynakları okunur: bir
190+ isteğe iki uç fazladan çağrı yapmak, okunmayan veri için de bir maliyet
191+ ve bir hata yüzeyi yaratırdı. `profile` her hâlükârda okunur (şube
192+ kimlikleri oradan gelir), ödev raporu da `submission` ya da `study`
193+ istenmişse (çalışma profilinin teslim tarihleri ondan çıkar).
194+ """
195+ everything = sections is None
196+
197+ def want(name: str) -> bool:
198+ return everything or name in sections
142 199
143-async def _fetch_student(source: Any, school: str, student: str) -> _Fetched:
144- """Tek öğrencinin verisini çeker. Yasaklı alan çağrısı **yoktur**."""
145 profile = await source.profile(school, student)200 profile = await source.profile(school, student)
146- marks_raw = await source.marks(school, student)201+ marks_raw = await source.marks(school, student) if want("marks") else None
147- attendance_raw = await source.attendance(school, student)202+ attendance_raw = (
148- pomodoro_raw = await source.pomodoro(school, student)203+ await source.attendance(school, student) if want("attendance") else None
149- report_raw = await source.homework_report(school, student)204+ )
150- homework_raw = await source.homework_list(school, student)205+ pomodoro_raw = await source.pomodoro(school, student) if want("study") else None
206+ need_report = want("submission") or want("study")
207+ report_raw = (
208+ await source.homework_report(school, student) if need_report else None
209+ )
210+ homework_raw = (
211+ await source.homework_list(school, student) if need_report else None
212+ )
213+ coverage: dict[str, int] = {"profile": 1 if profile else 0}
214+ if want("marks"):
215+ coverage["marks"] = len(marks_mod.normalize_rows(marks_raw))
216+ if want("attendance"):
217+ coverage["attendance"] = len(attendance_mod.normalize_rows(attendance_raw))
218+ if want("study"):
219+ coverage["pomodoro"] = len(study_mod.normalize_rows(pomodoro_raw))
220+ if need_report:
221+ coverage["homework_report"] = len(
222+ submission_mod.normalize_items(report_raw)
223+ )
224+ coverage["homework_list"] = len(homework_raw or [])
151 return _Fetched(225 return _Fetched(
152 profile=profile,226 profile=profile,
153 marks_raw=marks_raw,227 marks_raw=marks_raw,
@@ -158,6 +232,7 @@ async def _fetch_student(source: Any, school: str, student: str) -> _Fetched:
158 class_ids=marks_mod.class_ids_of(profile),232 class_ids=marks_mod.class_ids_of(profile),
159 course_stats=marks_mod.student_course_stats(marks_raw),233 course_stats=marks_mod.student_course_stats(marks_raw),
160 attendance_stats=attendance_mod.course_stats(attendance_raw),234 attendance_stats=attendance_mod.course_stats(attendance_raw),
235+ coverage=coverage,
161 )236 )
162 237
163 238
@@ -192,12 +267,34 @@ async def run_school(
192 budget_ms: int = DEFAULT_BUDGET_MS,267 budget_ms: int = DEFAULT_BUDGET_MS,
193 resume_students: list[str] | None = None,268 resume_students: list[str] | None = None,
194 monotonic_fn: Callable[[], float] = time.monotonic,269 monotonic_fn: Callable[[], float] = time.monotonic,
270+ nightly: bool = True,
271+ sections: Sequence[str] | None = None,
272+ outcomes: list[StudentOutcome] | None = None,
195 ) -> RunResult:273 ) -> RunResult:
196 """Bir okul için hattı uçtan uca koşturur.274 """Bir okul için hattı uçtan uca koşturur.
197 275
198 `source` yalnız `Source` protokolündeki sekiz metodu uygular; bu fonksiyon276 `source` yalnız `Source` protokolündeki sekiz metodu uygular; bu fonksiyon
199 başka hiçbir şey çağırmaz.277 başka hiçbir şey çağırmaz.
200 278
279+ `nightly=False` (yetenek isleyicileri): koşu defteri, mezuniyet temizliği
280+ ve saklama süpürmesi YAPILMAZ. Bunlar okul geneli gece işinin parçasıdır;
281+ tek öğrencilik bir hesap günün `zeka_run` satırını (anahtar `run_day`)
282+ ezmemeli ve bir ALT KÜMEYİ "aktif kadro" diye temizliğe vermemelidir.
283+ Mezuniyet temizliği zaten yalnız kadro DİZİNDEN çıkarıldığında koşar:
284+ çağıranın verdiği liste (`refresh user_ids`, `cli --students`) bir alt
285+ kümedir ve backend'in `insight.departed.purge` kapısı tam bu yüzden
286+ boş/kısmi listeyi reddeder.
287+
288+ `sections`: hangi modüllerin hesaplanacağı (`SECTION_NAMES`). İstenmeyen
289+ modül hesaplanmaz ve `StudentSummary` alanı `None` kalır -- satıra `null`
290+ gider, backend'in `SummaryRow` sözleşmesindeki "hesaplanmadı". Ad
291+ doğrulaması kenarda (`handlers._sections`) yapılır; burada bilinmeyen ad
292+ sessizce "istenmemiş" sayılır.
293+
294+ `outcomes`: verilirse her öğrenci için bir `StudentOutcome` eklenir
295+ (başarılı, düşen ve bütçeye takılanlar için birer kayıt). Gece koşusu
296+ toplamaz; yetenek isleyicileri cevabı oradan kurar.
297+
201 `resume_students`: geçen koşuda bütçe yüzünden işlenemeyenler. Bunlar298 `resume_students`: geçen koşuda bütçe yüzünden işlenemeyenler. Bunlar
202 listenin **başına** alınır — "bir sonraki koşu oradan devam eder"299 listenin **başına** alınır — "bir sonraki koşu oradan devam eder"
203 (`MODULLER.md` §3.4) cümlesinin uygulaması budur. Sıra dışında hiçbir şey300 (`MODULLER.md` §3.4) cümlesinin uygulaması budur. Sıra dışında hiçbir şey
@@ -207,6 +304,14 @@ async def run_school(
207 testlerde sahte saat verilerek bütçe aşımı **deterministik** kurulur —304 testlerde sahte saat verilerek bütçe aşımı **deterministik** kurulur —
208 aksi halde "60 sn'yi aş" testi makinenin hızına bağlı olurdu.305 aksi halde "60 sn'yi aş" testi makinenin hızına bağlı olurdu.
209 """306 """
307+ # Was the roster handed in (a subset) or read from the directory (the
308+ # roster)? The departed purge is only honest for the latter.
309+ roster_from_directory = student_ids is None
310+ wanted = _section_filter(sections)
311+
312+ def want(name: str) -> bool:
313+ return wanted is None or name in wanted
314+
210 started_wall = now_ms315 started_wall = now_ms
211 started_mono = monotonic_fn()316 started_mono = monotonic_fn()
212 result = RunResult(317 result = RunResult(
@@ -218,7 +323,8 @@ async def run_school(
218 323
219 # Koşu defterine "running" satırı — süreç yeniden başlarsa bayat koşu324 # Koşu defterine "running" satırı — süreç yeniden başlarsa bayat koşu
220 # buradan görülür (`MODULLER.md` §3.4).325 # buradan görülür (`MODULLER.md` §3.4).
221- await store.write_run(result.as_row(), result.run_key())326+ if nightly:
327+ await store.write_run(result.as_row(), result.run_key())
222 328
223 if student_ids is None:329 if student_ids is None:
224 try:330 try:
@@ -229,7 +335,8 @@ async def run_school(
229 result.failed_modules.append("discover_students")335 result.failed_modules.append("discover_students")
230 result.finished_at = now_ms336 result.finished_at = now_ms
231 result.duration_ms = elapsed_ms()337 result.duration_ms = elapsed_ms()
232- await store.write_run(result.as_row(), result.run_key())338+ if nightly:
339+ await store.write_run(result.as_row(), result.run_key())
233 return result340 return result
234 341
235 if resume_students:342 if resume_students:
@@ -256,12 +363,18 @@ async def run_school(
256 pending = list(student_ids[index:])363 pending = list(student_ids[index:])
257 break364 break
258 try:365 try:
259- fetched[student] = await _fetch_student(source, school, student)366+ fetched[student] = await _fetch_student(
367+ source, school, student, sections=wanted
368+ )
260 except Exception as exc: # noqa: BLE001 — kısmi başarısızlıkta devam369 except Exception as exc: # noqa: BLE001 — kısmi başarısızlıkta devam
261 log.warning("öğrenci atlandı (okul=%s, id=%s): %s", school, student, exc)370 log.warning("öğrenci atlandı (okul=%s, id=%s): %s", school, student, exc)
262 result.students_failed += 1371 result.students_failed += 1
263 if "fetch" not in result.failed_modules:372 if "fetch" not in result.failed_modules:
264 result.failed_modules.append("fetch")373 result.failed_modules.append("fetch")
374+ if outcomes is not None:
375+ outcomes.append(
376+ StudentOutcome(student=student, error=str(exc), error_kind="fetch")
377+ )
265 378
266 # ---------------- kohort kurulumu --------------------------------------379 # ---------------- kohort kurulumu --------------------------------------
267 #380 #
@@ -280,6 +393,10 @@ async def run_school(
280 )393 )
281 394
282 # ---------------- 2. geçiş: hesap + tavsiye ----------------------------395 # ---------------- 2. geçiş: hesap + tavsiye ----------------------------
396+ #
397+ # İstenmeyen modül (`sections`) hesaba hiç girmez ve özette `None` kalır.
398+ # Dikkat ve tavsiye kuralları yine çağrılır: modül profillerinin kapıları
399+ # kendi içindedir, eksik profil zaten "ateşlemez" demektir.
283 summaries: list[StudentSummary] = []400 summaries: list[StudentSummary] = []
284 recommendations: list[Recommendation] = []401 recommendations: list[Recommendation] = []
285 for student, data in fetched.items():402 for student, data in fetched.items():
@@ -288,69 +405,99 @@ async def run_school(
288 pending.append(student)405 pending.append(student)
289 continue406 continue
290 try:407 try:
291- marks_profile = marks_mod.student_profile(408+ marks_profile = (
292- data.marks_raw, data.profile, distributions409+ marks_mod.student_profile(data.marks_raw, data.profile, distributions)
410+ if want("marks")
411+ else None
293 )412 )
294- attendance_profile = attendance_mod.student_profile(413+ attendance_profile = (
295- data.attendance_raw, data.class_ids, medians414+ attendance_mod.student_profile(
415+ data.attendance_raw, data.class_ids, medians
416+ )
417+ if want("attendance")
418+ else None
296 )419 )
297- submission_profile = submission_mod.student_profile(420+ submission_profile = (
298- data.report_raw, data.homework_raw, now_ms421+ submission_mod.student_profile(
422+ data.report_raw, data.homework_raw, now_ms
423+ )
424+ if want("submission")
425+ else None
299 )426 )
300- study_profile = study_mod.student_profile(427+ study_profile = (
301- data.pomodoro_raw, now_ms, _due_dates(data.report_raw)428+ study_mod.student_profile(
429+ data.pomodoro_raw, now_ms, _due_dates(data.report_raw)
430+ )
431+ if want("study")
432+ else None
302 )433 )
303 items = attention_mod.order_items(434 items = attention_mod.order_items(
304 attention_mod.evaluate(435 attention_mod.evaluate(
305 student,436 student,
306- attendance_profile=attendance_profile,437+ attendance_profile=attendance_profile or {},
307- submission_profile=submission_profile,438+ submission_profile=submission_profile or {},
308- marks_profile=marks_profile,439+ marks_profile=marks_profile or {},
309 now_ms=now_ms,440 now_ms=now_ms,
310 term_start_ms=term_start_ms,441 term_start_ms=term_start_ms,
311 )442 )
312 )443 )
313- recommendations.extend(444+ recs = recommend_mod.for_student(
314- recommend_mod.for_student(445+ school,
315- school,446+ student,
316- student,447+ marks_profile=marks_profile or {},
317- marks_profile=marks_profile,448+ attendance_profile=attendance_profile or {},
318- attendance_profile=attendance_profile,449+ submission_profile=submission_profile or {},
319- submission_profile=submission_profile,450+ study_profile=study_profile or {},
320- study_profile=study_profile,451+ attention_items=items,
321- attention_items=items,452+ course_teachers=marks_mod.course_teachers(data.marks_raw),
322- course_teachers=marks_mod.course_teachers(data.marks_raw),453+ now_ms=now_ms,
323- now_ms=now_ms,
324- )
325 )454 )
326- summaries.append(455+ recommendations.extend(recs)
327- StudentSummary(456+ summary = StudentSummary(
328- school=school,457+ school=school,
329- student=student,458+ student=student,
330- computed_at=now_ms,459+ computed_at=now_ms,
331- marks=marks_profile,460+ marks=marks_profile,
332- attendance=attendance_profile,461+ attendance=attendance_profile,
333- submission=submission_profile,462+ submission=submission_profile,
334- study=study_profile,463+ study=study_profile,
335- attention=[464+ attention=[
336- {465+ {
337- "trigger": i.trigger.value,466+ "trigger": i.trigger.value,
338- "fact": i.fact,467+ "fact": i.fact,
339- "evidence": i.evidence,468+ "evidence": i.evidence,
340- "window_from": i.window_from,469+ "window_from": i.window_from,
341- "window_to": i.window_to,470+ "window_to": i.window_to,
342- }471+ }
343- for i in items472+ for i in items
344- ],473+ ],
345- confidence=_summary_confidence(marks_profile),474+ confidence=_summary_confidence(marks_profile or {}),
346- )
347 )475 )
476+ summaries.append(summary)
348 result.students_ok += 1477 result.students_ok += 1
478+ if outcomes is not None:
479+ outcomes.append(
480+ StudentOutcome(
481+ student=student,
482+ coverage=dict(data.coverage),
483+ summary=summary,
484+ recommendations=recs,
485+ )
486+ )
349 except Exception as exc: # noqa: BLE001487 except Exception as exc: # noqa: BLE001
350 log.warning("hesap düştü (okul=%s, id=%s): %s", school, student, exc)488 log.warning("hesap düştü (okul=%s, id=%s): %s", school, student, exc)
351 result.students_failed += 1489 result.students_failed += 1
352 if "compute" not in result.failed_modules:490 if "compute" not in result.failed_modules:
353 result.failed_modules.append("compute")491 result.failed_modules.append("compute")
492+ if outcomes is not None:
493+ outcomes.append(
494+ StudentOutcome(
495+ student=student,
496+ coverage=dict(data.coverage),
497+ error=str(exc),
498+ error_kind="compute",
499+ )
500+ )
354 501
355 # ---------------- yazma ------------------------------------------------502 # ---------------- yazma ------------------------------------------------
356 summary_report = await store.write_summaries(summaries)503 summary_report = await store.write_summaries(summaries)
@@ -360,10 +507,14 @@ async def run_school(
360 result.failed_modules.append("store")507 result.failed_modules.append("store")
361 508
362 # Mezuniyet/ayrılma temizliği: listede olmayanın **profili kalmamalıdır**.509 # Mezuniyet/ayrılma temizliği: listede olmayanın **profili kalmamalıdır**.
363- if not result.budget_exceeded and student_ids:510+ # Yalnız dizinden çıkarılan TAM kadro ve yalnız gece koşusu için: çağıranın
511+ # verdiği liste bir ALT KÜMEDİR (refresh `user_ids`, `cli --students`) ve
512+ # onu kadro saymak, adı geçmeyen herkesin türetilmiş verisini sildirirdi.
513+ if nightly and roster_from_directory and not result.budget_exceeded and student_ids:
364 await store.purge_departed(school, list(student_ids))514 await store.purge_departed(school, list(student_ids))
365 515
366- await store.sweep(now_ms)516+ if nightly:
517+ await store.sweep(now_ms)
367 518
368 result.students_skipped = len(pending)519 result.students_skipped = len(pending)
369 result.pending_students = pending520 result.pending_students = pending
@@ -382,5 +533,6 @@ async def run_school(
382 if result.write_failed and result.status == "ok":533 if result.write_failed and result.status == "ok":
383 result.status = "partial"534 result.status = "partial"
384 535
385- await store.write_run(result.as_row(), result.run_key())536+ if nightly:
537+ await store.write_run(result.as_row(), result.run_key())
386 return result538 return result
service/tests/test_capabilities.pymodified+39 -20
@@ -1,17 +1,18 @@
1 """Yetenek defterinin testleri.1 """Yetenek defterinin testleri.
2 2
3-Buradaki en onemli test bir EKSIKLIGI pinler: backend ZEKA'nin yeteneklerinin3+Buradaki en onemli test bir GERCEGI pinler: backend'in ZEKA'ya gonderebildigi
4-hicbirini **cagiramaz** (dagitim tablosunda bu adlar yok), dolayisiyla ZEKA'ya4+adlar `chat.reply`, `rag.index`, `insight.student`, `insight.refresh`tir;
5-hic `Request` gondermez. Bu, servisin backend'i cagirdigi depo yolundan (2. yon,5+`insight.class` ilan edilir ama backend'de onu gonderen bir yol yoktur. Bu,
6-`insight.*` -- calisir) AYRI bir yondur. Backend tarafi duzeldiginde bu test6+servisin backend'i cagirdigi depo yolundan (2. yon, `insight.*` -- calisir)
7-guncellenecek ve degisiklik goze carpacak.7+AYRI bir yondur. Iki taraf da degistiginde bu testler ve
8+`docs/BACKEND-GEREKSINIMLERI.md` madde 1 birlikte guncellenir.
8 """9 """
9 10
10 from __future__ import annotations11 from __future__ import annotations
11 12
12 import unittest13 import unittest
13 14
14-from src import capabilities15+from src import capabilities, handlers
15 from src.protocol import CapabilityError16 from src.protocol import CapabilityError
16 17
17 18
@@ -22,16 +23,24 @@ class CapabilityNameTests(unittest.TestCase):
22 ("insight.student", "insight.class", "insight.refresh"),23 ("insight.student", "insight.class", "insight.refresh"),
23 )24 )
24 25
25- def test_backend_can_call_none_of_them(self):26+ def test_backend_callable_set_is_the_dispatch_table(self):
26- # constant.rs:568 ve :574 -- backend'in cagirabildigi tek iki ad.27+ # constant.rs:568,574 (chat.reply, rag.index) + ai/insight.rs
28+ # (compute_student/refresh) ve web/insights.rs kapilari -- 2026-09-18.
27 self.assertEqual(29 self.assertEqual(
28- capabilities.BACKEND_CALLABLE_CAPABILITIES, ("chat.reply", "rag.index")30+ capabilities.BACKEND_CALLABLE_CAPABILITIES,
31+ ("chat.reply", "rag.index", "insight.student", "insight.refresh"),
29 )32 )
33+ # `insight.class` ilan edilir ama backend GONDERMEZ (kadro listeleme
34+ # yolu yok). Backend tarafi acildiginda bu satiri ve
35+ # docs/BACKEND-GEREKSINIMLERI.md madde 1'i birlikte guncelleyin.
30 self.assertEqual(36 self.assertEqual(
31- set(capabilities.NAMES) & set(capabilities.BACKEND_CALLABLE_CAPABILITIES),37+ set(capabilities.NAMES) - set(capabilities.BACKEND_CALLABLE_CAPABILITIES),
32- set(),38+ {"insight.class"},
33- "backend artik bir ZEKA yetenegini cagirabiliyorsa bu testi ve "39+ )
34- "docs/BACKEND-GEREKSINIMLERI.md madde 1'i guncelleyin",40+
41+ def test_sections_vocabulary_is_the_summary_modules(self):
42+ self.assertEqual(
43+ capabilities.SECTIONS, ("marks", "attendance", "submission", "study")
35 )44 )
36 45
37 def test_every_name_has_a_schema(self):46 def test_every_name_has_a_schema(self):
@@ -53,6 +62,9 @@ class DispatchTests(unittest.TestCase):
53 capabilities._handlers.clear()62 capabilities._handlers.clear()
54 63
55 def test_unknown_capability_is_refused(self):64 def test_unknown_capability_is_refused(self):
65+ # Kayit defteri modul genelidir ve baska testler `handlers.wire()`
66+ # cagirir; bu test BOS bir defteri sart kosar.
67+ capabilities._handlers.clear()
56 with self.assertRaises(CapabilityError) as caught:68 with self.assertRaises(CapabilityError) as caught:
57 capabilities.dispatch("insight.student", "demo", {})69 capabilities.dispatch("insight.student", "demo", {})
58 self.assertEqual(caught.exception.code, "unknown_capability")70 self.assertEqual(caught.exception.code, "unknown_capability")
@@ -80,15 +92,22 @@ class DispatchTests(unittest.TestCase):
80 capabilities.dispatch("insight.class", "demo", ["liste"])92 capabilities.dispatch("insight.class", "demo", ["liste"])
81 self.assertEqual(caught.exception.code, "bad_request")93 self.assertEqual(caught.exception.code, "bad_request")
82 94
83- def test_summary_names_the_callable_direction_only(self):95+ def test_summary_separates_the_three_facts(self):
96+ handlers.wire()
84 text = capabilities.summary()97 text = capabilities.summary()
85- # Liste backend'in CAGIRABILDIGIDIR ...98+ # 1) backend'in GONDEREBILDIGI adlar ...
86- self.assertIn("backend'in cagirabildigi yetenekler: chat.reply, rag.index", text)99+ self.assertIn(
87- self.assertIn("HENUZ cagrilmiyor", text)100+ "backend'in cagirabildigi yetenekler: "
88- # ... ve depo yolunu (2. yon) kapsamadigi acikca yazilidir.101+ "chat.reply, rag.index, insight.student, insight.refresh",
102+ text,
103+ )
104+ # 2) ... depo yolunu (2. yon) kapsamadigi ...
89 self.assertIn("servis->backend depo yolu: kopru/insight.*", text)105 self.assertIn("servis->backend depo yolu: kopru/insight.*", text)
90- # Eski hali depo yolu calismaya basladiktan sonra "backend insight'i106+ # 3) ... ve ilan edilen her adin bir isleyicisi oldugu.
91- # hic bilmiyor" diye okunuyordu.107+ self.assertIn("servis tarafi isleyiciler: 3/3 kayitli", text)
108+ self.assertIn("backend'in dagitim tablosunda olmayan: insight.class", text)
109+ # Eski hali "TANIMSIZ" diyordu ve isleyici kayitliyken bile servisin
110+ # bir sey yapmadigini ima ediyordu.
92 self.assertNotIn("TANIMSIZ", text)111 self.assertNotIn("TANIMSIZ", text)
93 112
94 113
service/tests/test_handlers.pyadded+258 -0
@@ -0,0 +1,258 @@
1+"""The three served capabilities, end to end over a fake bridge.
2+
3+What is proven here, in the order it matters:
4+
5+1. The fail-pre-fix fact. With an empty handler table `dispatch` answers
6+ `unknown_capability` -- that was the live production answer even though the
7+ `Hello` frame announced the name in the same breath. After
8+ `handlers.wire()` the same call reaches a real handler.
9+2. Each capability answers the fields the backend's contract reads
10+ (`hezarfen_backend/src/ai/insight.rs`), through the real store layer
11+ (`BridgeStore` + `RecordingCaller`) and a `FakeSource`.
12+3. The boot self-check refuses to advertise a name with no handler.
13+
14+The fixture data is built relative to the *real* now: `fakes.NOW` is 2023, and
15+with it the 28-day study window would be empty and `O3.pattern` would never
16+fire.
17+"""
18+
19+from __future__ import annotations
20+
21+import time
22+import unittest
23+from datetime import datetime
24+
25+from src import capabilities, handlers
26+from src.compute import clock
27+from src.protocol import CapabilityError
28+from src.store import (
29+ CAP_PURGE,
30+ CAP_RECOMMENDATION,
31+ CAP_RUN,
32+ CAP_SUMMARY,
33+ CAP_SWEEP,
34+ BridgeStore,
35+ RecordingCaller,
36+)
37+
38+from .fakes import FakeSource, dataset
39+
40+SCHOOL = "okul-a"
41+#: Real "now" -- see the module docstring.
42+NOW = int(time.time() * 1000)
43+
44+
45+def _rows(caller: RecordingCaller, capability: str) -> list[dict]:
46+ rows: list[dict] = []
47+ for kind, _, payload in caller.calls:
48+ if kind == capability:
49+ rows.extend(payload.get("rows") or [])
50+ return rows
51+
52+
53+class HandlerTestCase(unittest.IsolatedAsyncioTestCase):
54+ async def asyncSetUp(self) -> None:
55+ self.data = dataset(12, now_ms=NOW)
56+ self.caller = RecordingCaller()
57+ capabilities.bind_store(BridgeStore(self.caller))
58+ handlers.bind_source(lambda school: FakeSource(self.data))
59+ handlers.wire()
60+
61+ async def asyncTearDown(self) -> None:
62+ capabilities._handlers.clear()
63+
64+ async def dispatch(self, capability: str, payload: dict) -> dict:
65+ return await capabilities.dispatch(capability, SCHOOL, payload)
66+
67+ def kinds(self) -> list[str]:
68+ return [kind for kind, _, _ in self.caller.calls]
69+
70+
71+class FailPreFixTests(HandlerTestCase):
72+ async def test_student_is_unknown_until_wire_registers_it(self) -> None:
73+ capabilities._handlers.clear()
74+ with self.assertRaises(CapabilityError) as caught:
75+ await self.dispatch("insight.student", {"user_id": "student-00"})
76+ self.assertEqual(caught.exception.code, "unknown_capability")
77+
78+ handlers.wire()
79+ answer = await self.dispatch("insight.student", {"user_id": "student-00"})
80+ self.assertEqual(answer["user_id"], "student-00")
81+
82+ async def test_a_wired_name_refuses_a_bad_payload_typed(self) -> None:
83+ """After wiring, a malformed call is a `bad_request`, not a miss:
84+ the handler ran and judged the payload."""
85+ with self.assertRaises(CapabilityError) as caught:
86+ await self.dispatch("insight.student", {})
87+ self.assertEqual(caught.exception.code, "bad_request")
88+
89+ async def test_boot_self_check_refuses_a_name_without_a_handler(self) -> None:
90+ capabilities._handlers.pop("insight.class")
91+ with self.assertRaises(capabilities.RegistrationError) as caught:
92+ capabilities.verify_dispatchable()
93+ self.assertIn("insight.class", str(caught.exception))
94+ self.assertEqual(
95+ capabilities.dispatchable_names(), ["insight.student", "insight.refresh"]
96+ )
97+
98+ handlers.wire()
99+ capabilities.verify_dispatchable() # and back to a clean bill
100+
101+
102+class StudentCapabilityTests(HandlerTestCase):
103+ async def test_answer_carries_the_contract_and_writes_only_rows(self) -> None:
104+ answer = await self.dispatch(
105+ "insight.student", {"user_id": "student-00", "since": "2023-06-01"}
106+ )
107+ self.assertEqual(
108+ set(answer),
109+ {"user_id", "generated_at", "signals", "recommendations", "coverage"},
110+ )
111+ self.assertEqual(answer["user_id"], "student-00")
112+ self.assertGreater(datetime.fromisoformat(answer["generated_at"]).year, 2024)
113+ self.assertIsInstance(answer["signals"], list)
114+
115+ # `O3.pattern` fires on the fixture's study sessions; the card is the
116+ # student's own, carries evidence, and is not storage bookkeeping.
117+ self.assertTrue(answer["recommendations"])
118+ card = answer["recommendations"][0]
119+ self.assertEqual(card["audience"], "student-00")
120+ self.assertEqual(card["audience_role"], "student")
121+ self.assertTrue(card["evidence"])
122+ self.assertNotIn("retain_until", card)
123+ # The answer's cards are exactly the ones the store accepted.
124+ self.assertEqual(
125+ [item["rule_id"] for item in answer["recommendations"]],
126+ [
127+ row["rule_id"]
128+ for row in _rows(self.caller, CAP_RECOMMENDATION)
129+ if row["audience"] == "student-00"
130+ ],
131+ )
132+
133+ written = _rows(self.caller, CAP_SUMMARY)
134+ self.assertEqual(len(written), 1)
135+ self.assertEqual(written[0]["student"], "student-00")
136+
137+ # The night run owns the ledger, the purge and the sweep. A
138+ # single-student compute that wrote any of them would clobber the
139+ # day's record with a one-student one.
140+ self.assertEqual(
141+ [kind for kind in self.kinds() if kind in (CAP_RUN, CAP_PURGE, CAP_SWEEP)],
142+ [],
143+ )
144+ self.assertEqual(answer["coverage"]["sections"], "all")
145+ self.assertEqual(answer["coverage"]["reads"]["marks"], 1)
146+ self.assertEqual(answer["coverage"]["reads"]["homework_report"], 6)
147+
148+ async def test_sections_narrow_the_reads_and_null_the_row(self) -> None:
149+ answer = await self.dispatch(
150+ "insight.student", {"user_id": "student-00", "sections": ["marks"]}
151+ )
152+ self.assertEqual(answer["coverage"]["sections"], ["marks"])
153+ self.assertEqual(set(answer["coverage"]["reads"]), {"profile", "marks"})
154+ row = _rows(self.caller, CAP_SUMMARY)[0]
155+ self.assertIsInstance(row["marks"], dict)
156+ # Unrequested modules are "not computed" (`null`), which the backend's
157+ # `SummaryRow` keeps apart from the empty-object "read, nothing there".
158+ self.assertIsNone(row["attendance"])
159+ self.assertIsNone(row["submission"])
160+ self.assertIsNone(row["study"])
161+
162+ async def test_bad_inputs_are_refused_by_name(self) -> None:
163+ with self.assertRaises(CapabilityError) as caught:
164+ await self.dispatch(
165+ "insight.student", {"user_id": "student-00", "sections": ["speech"]}
166+ )
167+ self.assertEqual(caught.exception.code, "bad_request")
168+ with self.assertRaises(CapabilityError) as caught:
169+ await self.dispatch(
170+ "insight.student", {"user_id": "student-00", "since": "dun"}
171+ )
172+ self.assertEqual(caught.exception.code, "bad_request")
173+
174+ async def test_a_failed_fetch_is_a_refusal_not_an_empty_answer(self) -> None:
175+ handlers.bind_source(
176+ lambda school: FakeSource(self.data, fail={"student-05"})
177+ )
178+ with self.assertRaises(CapabilityError) as caught:
179+ await self.dispatch("insight.student", {"user_id": "student-05"})
180+ self.assertEqual(caught.exception.code, "unavailable")
181+
182+
183+class ClassCapabilityTests(HandlerTestCase):
184+ async def test_answer_carries_cohort_and_attention_list(self) -> None:
185+ answer = await self.dispatch(
186+ "insight.class",
187+ {"course_id": "course-1", "term": "2023-06-01", "top_n": 2},
188+ )
189+ self.assertEqual(set(answer), set(capabilities.SCHEMAS["insight.class"][1].__annotations__))
190+ self.assertEqual(answer["course_id"], "course-1")
191+ self.assertEqual(answer["cohort_size"], 12)
192+ self.assertEqual(answer["topic_gaps"], []) # not producible; says so below
193+ self.assertTrue(answer["coverage"]["unavailable"]["topic_gaps"])
194+
195+ self.assertTrue(answer["attention_list"])
196+ item = answer["attention_list"][0]
197+ self.assertEqual(
198+ set(item),
199+ {"user_id", "trigger", "course", "fact", "window_from", "window_to", "evidence"},
200+ )
201+ # The output contract has no ranking field anywhere, the wire included.
202+ self.assertNotIn("score", item)
203+ self.assertEqual(answer["coverage"]["attention"]["total"], 1)
204+ self.assertEqual(answer["coverage"]["attention"]["returned"], 1)
205+ self.assertEqual(answer["coverage"]["roster"]["course_rows"], 1)
206+
207+
208+class RefreshCapabilityTests(HandlerTestCase):
209+ async def test_school_refresh_writes_the_run_ledger_and_counts(self) -> None:
210+ answer = await self.dispatch("insight.refresh", {})
211+ self.assertEqual(answer["requested"], 12)
212+ self.assertEqual(answer["computed"], 12)
213+ self.assertEqual(answer["skipped"], 0)
214+ self.assertEqual(answer["failed"], [])
215+ self.assertEqual(answer["status"], "ok")
216+
217+ runs = [
218+ payload["run"] for kind, _, payload in self.caller.calls if kind == CAP_RUN
219+ ]
220+ self.assertEqual(len(runs), 2) # "running" first, the verdict last
221+ started = int(
222+ datetime.fromisoformat(answer["started_at"]).timestamp() * 1000
223+ )
224+ self.assertEqual(runs[-1]["run_day"], clock.tr_date_key(started))
225+ self.assertEqual(runs[-1]["status"], "ok")
226+ self.assertEqual(runs[-1]["students_total"], 12)
227+ # The whole-school sweep keeps the night run's cleanup steps.
228+ self.assertEqual(self.kinds().count(CAP_PURGE), 1)
229+ self.assertEqual(self.kinds().count(CAP_SWEEP), 1)
230+
231+ async def test_scoped_refresh_never_purges(self) -> None:
232+ """`user_ids` is a subset, not the roster: obeying it through
233+ `insight.departed.purge` would delete everyone it does not name."""
234+ answer = await self.dispatch(
235+ "insight.refresh", {"user_ids": ["student-00", "student-01"]}
236+ )
237+ self.assertEqual(answer["requested"], 2)
238+ self.assertEqual(answer["computed"], 2)
239+ self.assertNotIn(CAP_PURGE, self.kinds())
240+ # Its ledger row is still written: that is the trace a reader polls.
241+ self.assertIn(CAP_RUN, self.kinds())
242+
243+ async def test_failed_students_are_named_in_the_answer(self) -> None:
244+ handlers.bind_source(
245+ lambda school: FakeSource(self.data, fail={"student-05"})
246+ )
247+ answer = await self.dispatch(
248+ "insight.refresh", {"user_ids": ["student-05", "student-00"]}
249+ )
250+ self.assertEqual(answer["requested"], 2)
251+ self.assertEqual(answer["computed"], 1)
252+ self.assertEqual([entry["user_id"] for entry in answer["failed"]], ["student-05"])
253+ self.assertEqual(answer["failed"][0]["code"], "unavailable")
254+ self.assertTrue(answer["failed"][0]["message"])
255+
256+
257+if __name__ == "__main__":
258+ unittest.main()
service/tests/test_pipeline.pymodified+26 -11
@@ -115,8 +115,13 @@ class TestEndToEnd(PipelineTestCase):
115 )115 )
116 116
117 async def test_cleanup_calls_go_out_once(self) -> None:117 async def test_cleanup_calls_go_out_once(self) -> None:
118- """Koşu sonunda süpürme ve mezuniyet temizliği çağrılır."""118+ """Koşu sonunda süpürme ve mezuniyet temizliği çağrılır.
119- _, caller = await self._run(dataset())119+
120+ Kadro DİZİNDEN okunur (`student_ids=None`): temizlik yalnız tam kadro
121+ için koşar, çağıranın verdiği alt küme için koşmaz (bkz.
122+ `run_school` docstring'i).
123+ """
124+ _, caller = await self._run(dataset(), student_ids=None)
120 kinds = [capability for capability, _, _ in caller.calls]125 kinds = [capability for capability, _, _ in caller.calls]
121 self.assertEqual(kinds.count(CAP_SWEEP), 1)126 self.assertEqual(kinds.count(CAP_SWEEP), 1)
122 purge = [127 purge = [
@@ -375,18 +380,18 @@ class TestPipelineWritesThroughTheBridge(unittest.IsolatedAsyncioTestCase):
375 """Ayrilan ogrenci temizlik listesinde YOKTUR: profili kalmamalidir.380 """Ayrilan ogrenci temizlik listesinde YOKTUR: profili kalmamalidir.
376 381
377 Silme backend'in isidir; burada dogrulanan sey gonderilen listenin382 Silme backend'in isidir; burada dogrulanan sey gonderilen listenin
378- gercekten daralmis olmasidir.383+ gercekten daralmis olmasidir. Kadro her iki kosuda da DIZINDEN okunur:
384+ `student-11` okulun odev listesinden cikar ve temizlik onu istemez.
379 """385 """
380 await self._run()386 await self._run()
381 self.assertEqual(len(self.tables["student_summary"]), 12)387 self.assertEqual(len(self.tables["student_summary"]), 12)
382- await run_school(388+ roster = [f"student-{i:02d}" for i in range(10)]
383- FileSource(self.root),389+ data = {key: value for key, value in self.data.items() if key in roster}
384- self.store.store_for("okul-a"),390+ data["_school"] = {
385- "okul-a",391+ "homework_list": [homework("hw-school", "course-1", NOW + DAY, roster)]
386- now_ms=NOW,392+ }
387- term_start_ms=TERM_START,393+ write_fixtures(self.root, "okul-a", data)
388- student_ids=[f"student-{i:02d}" for i in range(10)],394+ await self._run()
389- )
390 purge_calls = [395 purge_calls = [
391 payload396 payload
392 for capability, _, payload in self.caller.calls397 for capability, _, payload in self.caller.calls
@@ -396,6 +401,16 @@ class TestPipelineWritesThroughTheBridge(unittest.IsolatedAsyncioTestCase):
396 self.assertEqual(len(purge_calls[-1]["students"]), 10)401 self.assertEqual(len(purge_calls[-1]["students"]), 10)
397 self.assertNotIn("student-11", purge_calls[-1]["students"])402 self.assertNotIn("student-11", purge_calls[-1]["students"])
398 403
404+ async def test_a_scoped_list_never_purges(self) -> None:
405+ """Cagiranin verdigi liste bir ALT KUME: temizlige verilemez.
406+
407+ `refresh user_ids` ve `cli --students` boyle kosar; o listeyi "aktif
408+ kadro" saymak, adi gecmeyen herkesin turetilmis verisini sildirirdi.
409+ """
410+ await self._run(student_ids=[f"student-{i:02d}" for i in range(10)])
411+ self.assertEqual(self.tables["student_summary"][0]["student"], "student-00")
412+ self.assertNotIn(CAP_PURGE, [capability for capability, _, _ in self.caller.calls])
413+
399 414
400 if __name__ == "__main__":415 if __name__ == "__main__":
401 unittest.main()416 unittest.main()